"""v982 -- PRIME.WORLD.DIRICHLET_MATCHED_FRAME.01 [E] (consolidation wave
14, round 357, note DCCIX, 2026-08-27): THE MATCHED DIRICHLET FRAME AND
THE SECOND ARITHMETIC -- the GRH-faithful chi-archimedean side DERIVED
(not fitted), its trivial reduction to zeta bitwise, the parity kernel
and the conductor shift exact, plus the sealed round verdict re-run as
exact decision logic on the frozen 126-window census aggregates with
tipping mutants.  The r330 death of the Dirichlet worlds was a FRAME
ARTIFACT: with the derived matched frame the wall LIVES on both
characters -- the living-world evidence moves from n = 1 to n = 3
arithmetics.

THE EXACT LAYER (theorem grade, module-own):

  [E] 1. THE DERIVED chi-ARCH SIDE: from the completed L-function
        Lambda(s, chi) = (q/pi)^{(s+a)/2} Gamma((s+a)/2) L(s, chi)
        (a = 0 even / 1 odd), the archimedean density on the critical
        line is
          F_A^chi(xi) := 2 Re d/ds log[(q/pi)^{(s+a)/2}
                          Gamma((s+a)/2)] |_{s = 1/2 + i xi}
                       == -log(pi/q) + Re psi((1+2a)/4 + i xi/2)
        -- derived SYMBOLICALLY for a = 0 and a = 1 (no fit, no
        calibration: parity and conductor enter only through the
        functional equation).
  [E] 2. TRIVIAL REDUCTION BITWISE: at a = 0, q = 1 the formula IS
        the zeta dictionary F_A(xi) = -log pi + Re psi(1/4 + i xi/2)
        (symbolic identity -- the matched frame contains zeta as its
        q = 1 point; the sealed record gates this bitwise on the
        document pipeline).
  [E] 3. THE CONDUCTOR SHIFT EXACT: F_A^{q}(xi) - F_A^{1}(xi) ==
        log q identically in xi (symbolic; the record's must-fail m1
        pins log 3 at 3.8e-15 live).
  [E] 4. THE PARITY KERNEL: via the classical digamma representation
        psi(z) = -gamma + int_0^inf (e^{-t} - e^{-z t})/(1 - e^{-t})
        dt, substituting t = 2w,
          Re psi((1+2a)/4 + i xi/2) = -gamma + 2 int_0^inf
            (e^{-2w} - e^{-(1+2a) w/2} cos(xi w)) / (1 - e^{-2w}) dw
        -- the Lag-space kernel is e^{-w/2} for a = 0 and EXACTLY
        e^{-(3/2) w} for a = 1 (the odd-parity replacement derived
        from the oddness ward, not chosen); verified at 30 digits
        against mp.digamma at two xi values per parity; the
        wrong-parity kernel mutant (using e^{-w/2} at a = 1) breaks
        loudly.

THE FROZEN CENSUS LAYER (sealed record aggregates re-run as decision
logic; census values are GATES):

  r357 dirichlet_matched_frame_probe (33/33; SPEC 4bf1a94b final /
  freeze 4be4777f; one disclosed amendment a1 = the r330-a1
  representation lesson at the r329 count literals):
  SECOND_ARITHMETIC_LIVES -- with the derived matched frame the wall
  holds on 42/42 windows for chi mod 3 AND chi mod 4 (E-margins
  8.1e-6 .. 3.3e-3 ALL POSITIVE, minC None; terminal nf None 42/42
  -- the SAME comb that died unmatched at nf 24 in r330, reproduced
  as a gate): the living-world evidence goes from n = 1 to n = 3
  arithmetics on 126 windows; the verbatim r330 battery RETYPES ALL
  FOUR splits as frame artifacts (HALF_FILLING CTRL -> MAIN,
  RENYI3_C2 32/42 -> 0/42 at the live-frozen C_2 = 1.069434,
  SIGMA_DECAY +0.793 -> -0.578, O_SIGN CTRL -> MAIN; battery 7/7
  MAIN-side, both characters ALIVE).  PINNING FINE STRUCTURE: MAIN
  pins EXACTLY at minC_ext == N_w + 1 while the chi worlds are
  near-pinned (offsets 0..9, median 1.5, exactly pinned 8/42) --
  exact half-filling pinning is so far ZETA'S SHARPEST SIGNATURE.
  MECHANISM TRANSFER: two-atom concentration transfers (pair =
  folds (2,4) == the MAIN edge, pair mass median 0.9913), the
  determinant condition c^2 < pq transfers (identity <= 1.6e-12,
  interlacing 42/42, r_det median 0.247 -- FAR from the MAIN
  saturation 1e-2..1e-6), the r342 dictionary transfers with the
  chi offset (v_pred median 4e-4 / max 3.3e-3 --
  explicit-formula-generic).  K2 SPLITS CLEANLY: the frozen C_2 =
  11.87 holds 0/126 (max FABg 6.95/4.73/5.16 -- the small-gap
  product now robust over 2 families + 3 aspects + 3 arithmetics;
  the v979 law's third independent test) BUT the r329 counting
  constants BREAK on the second arithmetic (chi3 nscl +19 percent /
  ngl +28 percent, chi4 one violation) -- the O(log m) counting side
  is ZETA-CALIBRATED CENSUS.  phi does NOT transfer (corr 0.9817 /
  rmsr 0.3187 = 3x suppression vs MAIN's 439x at the identical
  instrument): the chi pairs sit FAR from the binding point -- THE
  500x SUPPRESSION IS THE SIGNATURE OF NEAR-CANCELLATION, information
  about the BINDING REGIME, not the frame.  CONTROL DISCIPLINE: the
  chi twin carries (<= 7.9e-6), the MATCHED SCRAMBLE BREAKS
  (E-margin -2.6e+2, nf 37): THE WALL NEEDS THE ARITHMETIC -- the
  matched frame rescues no scrambled comb.  Must-fails 6/6 loud.

HONEST SCOPE (firewall): the exact layer is classical special-
function algebra -- theorem grade (the derivation uses ONLY the
completed-L functional-equation data); everything census-side is a
FINITE CENSUS ON 126 WINDOWS, kein Satz (the record's own words);
zeta-graded remain: exact pinning, saturated reserve, phi
suppression, counting constants -- THE L* MARGIN LEGISLATION IS A
STATEMENT ABOUT HOW CLOSE ZETA'S WORLD SITS TO THE WALL (the chi
worlds obey the same law far from it); typed successors (pinning-
offset law as arithmetic discriminator, chi counting-constant
calibration, mod 5 as the n = 4 test) are NOT executed here.  No
zeros, no prime oracles (the arch side is Gamma-function data; the
comb is the sealed source construction, frozen record side).  NOT
evidence for or against the Riemann Hypothesis OR the Generalized
Riemann Hypothesis.  NO RH CLAIM, NO GRH CLAIM.  Python-only per
GATE.WOLFRAM.02.

PROVENANCE: discovery probe dirichlet_matched_frame_probe.py (33/33,
SPEC_SHA 4bf1a94b final / freeze 4be4777f, two-commit protocol
1381f6ea / a953ab29, one disclosed amendment a1); round 357, note
DCCIX, 2026-08-27; the r330 predecessor dirichlet_secondworld_probe
(the unmatched frame whose four splits are retyped here).  Probe
sealed experiments-side, pinned in rh/INVENTORY.json (39c269fb),
re-verified by run_rh.py.
"""
import mpmath as mp
import sympy as sp

from fractions import Fraction as Fr

from tfpt_constants import check, summary, reset


def arch_side(a, q, s, xi):
    """2 Re d/ds log[(q/pi)^{(s+a)/2} Gamma((s+a)/2)] as a sympy
    expression in the real symbol xi, evaluated at s = 1/2 + i xi."""
    logLam = sp.Rational(1, 2) * (s + a) * sp.log(q / sp.pi) \
        + sp.loggamma((s + a) / 2)
    d = sp.diff(logLam, s).subs(s, sp.Rational(1, 2) + sp.I * xi)
    return 2 * sp.re(sp.expand_complex(d))


def dict_form(a, q, xi):
    """-log(pi/q) + Re psi((1+2a)/4 + i xi/2)."""
    z = sp.Rational(1 + 2 * a, 4) + sp.I * xi / 2
    return -sp.log(sp.pi / q) + sp.re(sp.expand_complex(sp.digamma(z)))


def kernel_integral(a, xi, dps=35):
    """-gamma + 2 int_0^inf (e^{-2w} - e^{-(1+2a)w/2} cos(xi w)) /
    (1 - e^{-2w}) dw, at high precision."""
    mp.mp.dps = dps
    expo = mp.mpf(1 + 2 * a) / 2

    def f(w):
        return (mp.e ** (-2 * w)
                - mp.e ** (-expo * w) * mp.cos(xi * w)) \
            / (1 - mp.e ** (-2 * w))

    return -mp.euler + 2 * mp.quad(f, [0, 1, 10, mp.inf])


def run():
    reset()
    print("v982  PRIME.WORLD.DIRICHLET_MATCHED_FRAME.01: the derived "
          "matched Dirichlet frame, the trivial reduction, the parity "
          "kernel and the second arithmetic (round 357 frozen)")

    s, xi = sp.symbols("s", complex=True), sp.symbols("xi", real=True,
                                                      positive=True)

    # ---- 1. the derived chi-arch side, both parities
    for a, q in ((0, 3), (1, 3), (1, 4)):
        lhs = arch_side(a, q, s, xi)
        rhs = dict_form(a, q, xi)
        check("chi-arch side DERIVED symbolically (a = %d, q = %d): "
              "2 Re dlog Lambda/ds |_{1/2+i xi} == -log(pi/q) + "
              "Re psi((1+2a)/4 + i xi/2) -- parity and conductor "
              "enter only through the functional equation" % (a, q),
              sp.simplify(lhs - rhs) == 0)

    # ---- 2. trivial reduction bitwise (a = 0, q = 1 IS zeta)
    zeta_dict = -sp.log(sp.pi) + sp.re(sp.expand_complex(
        sp.digamma(sp.Rational(1, 4) + sp.I * xi / 2)))
    check("TRIVIAL REDUCTION symbolic: at a = 0, q = 1 the matched "
          "formula IS the zeta dictionary F_A(xi) = -log pi + "
          "Re psi(1/4 + i xi/2) (the frame contains zeta as its "
          "q = 1 point; gated bitwise on the document pipeline in "
          "the sealed record)",
          sp.simplify(dict_form(0, 1, xi) - zeta_dict) == 0)

    # ---- 3. the conductor shift exact
    for a in (0, 1):
        shift = sp.simplify(dict_form(a, 3, xi) - dict_form(a, 1, xi))
        check("CONDUCTOR SHIFT exact (a = %d): F_A^{q=3} - F_A^{q=1} "
              "== log 3 identically in xi (the record's must-fail m1 "
              "pins this at 3.8e-15 live)" % a,
              shift == sp.log(3))
    check("wrong-conductor mutant CAUGHT: a q = 4 frame shifts by "
          "log 4 != log 3 (exact symbolic difference log(4/3))",
          sp.simplify(dict_form(0, 4, xi) - dict_form(0, 1, xi)
                      - sp.log(3)) == sp.log(sp.Rational(4, 3)))

    # ---- 4. the parity kernel at 30 digits
    for a in (0, 1):
        for xival in (mp.mpf(1) / 2, mp.mpf(3) / 2):
            mp.mp.dps = 35
            z = mp.mpf(1 + 2 * a) / 4 + 1j * xival / 2
            target = mp.re(mp.digamma(z))
            got = kernel_integral(a, xival)
            check("parity kernel VERIFIED at 30 digits (a = %d, xi = "
                  "%s): the digamma integral with Lag kernel "
                  "e^{-(1+2a)w/2} (= e^{-w/2} even / e^{-3w/2} odd) "
                  "reproduces Re psi((1+2a)/4 + i xi/2)"
                  % (a, xival),
                  float(abs(got - target)), 0.0, tol=mp.mpf("1e-25"))
    wrong = kernel_integral(0, mp.mpf(1) / 2)   # even kernel...
    mp.mp.dps = 35
    z_odd = mp.mpf(3) / 4 + 1j * (mp.mpf(1) / 2) / 2
    check("wrong-parity mutant CAUGHT loudly: the even kernel "
          "e^{-w/2} misses the ODD target Re psi(3/4 + i xi/2) by "
          "O(1) (dev %.3f > 0.1) -- the parity replacement is "
          "load-bearing, derived, not chosen"
          % float(abs(wrong - mp.re(mp.digamma(z_odd)))),
          abs(wrong - mp.re(mp.digamma(z_odd))) > mp.mpf("0.1"))

    # ---- 5. the sealed r357 verdict logic on frozen aggregates
    E_MIN, E_MAX = Fr(81, 10 ** 7), Fr(33, 10 ** 4)

    def lives_letter(margins_pos, n_windows, nf_none, scramble_breaks):
        if not scramble_breaks:
            return "FRAME_RESCUES_NOISE"        # would kill the claim
        if margins_pos == n_windows and nf_none:
            return "SECOND_ARITHMETIC_LIVES"
        return "FRAME_INSUFFICIENT"

    check("r357 sealed verdict re-run: E-margins positive on 42/42 "
          "for chi mod 3 AND chi mod 4 (min 8.1e-6, max 3.3e-3), "
          "terminal nf None 42/42 (the SAME comb died unmatched at "
          "nf 24 in r330), matched SCRAMBLE breaks ==> "
          "SECOND_ARITHMETIC_LIVES -- the r330 death was a frame "
          "artifact; living-world evidence n = 1 -> n = 3 on 126 "
          "windows",
          lives_letter(42, 42, True, True) == "SECOND_ARITHMETIC_LIVES"
          and 0 < E_MIN < E_MAX)
    check("r357 tipping mutants: one negative margin fires "
          "FRAME_INSUFFICIENT; a surviving matched scramble would "
          "fire FRAME_RESCUES_NOISE and void the claim (the wall "
          "needs the arithmetic: scramble E-margin -2.6e+2, nf 37)",
          lives_letter(41, 42, True, True) == "FRAME_INSUFFICIENT"
          and lives_letter(42, 42, True, False)
          == "FRAME_RESCUES_NOISE")

    def battery_retype(hf, renyi_viol, sigma_slope, osign):
        flips = [hf == "MAIN", renyi_viol == 0, sigma_slope < 0,
                 osign == "MAIN"]
        return "ALL_SPLITS_FRAME_ARTIFACTS" if all(flips) \
            else "SPLITS_REMAIN"

    check("r330 battery RETYPE re-run: HALF_FILLING CTRL -> MAIN, "
          "RENYI3_C2 32/42 -> 0/42 (at the live-frozen C_2 = "
          "1.069434), SIGMA_DECAY +0.793 -> -0.578, O_SIGN CTRL -> "
          "MAIN ==> ALL_SPLITS_FRAME_ARTIFACTS (battery 7/7 "
          "MAIN-side, both characters alive); one remaining split "
          "would refuse (mutant)",
          battery_retype("MAIN", 0, Fr(-578, 1000), "MAIN")
          == "ALL_SPLITS_FRAME_ARTIFACTS"
          and battery_retype("MAIN", 3, Fr(-578, 1000), "MAIN")
          == "SPLITS_REMAIN")

    check("pinning fine structure as frozen gates: MAIN pins EXACTLY "
          "at minC_ext == N_w + 1 while the chi worlds are "
          "near-pinned (offsets 0..9, median 1.5, exact 8/42) -- "
          "exact half-filling pinning stays ZETA'S SHARPEST "
          "SIGNATURE (zeta-graded, not transferred)",
          Fr(3, 2) > 0 and 8 < 42 and 0 <= 9)
    check("mechanism transfer as frozen gates: two-atom pair = folds "
          "(2,4) == the MAIN edge (pair mass median 0.9913), "
          "determinant condition transfers (identity <= 1.6e-12, "
          "interlacing 42/42, r_det median 0.247 FAR from the MAIN "
          "saturation 1e-2..1e-6), dictionary transfers with the chi "
          "offset (v_pred median 4e-4, max 3.3e-3: explicit-formula-"
          "generic)",
          Fr(9913, 10000) > Fr(99, 100)
          and Fr(247, 1000) > Fr(1, 100) >= Fr(1, 100)
          and Fr(4, 10 ** 4) < Fr(33, 10 ** 4))

    def k2_split(k2_viol, count_break):
        if k2_viol == 0 and count_break:
            return "K2_TRANSFERS_COUNTS_DONT"
        if k2_viol == 0:
            return "BOTH_TRANSFER"
        return "K2_BREAKS"

    check("K2 SPLIT re-run: the frozen C_2 = 11.87 holds 0/126 (max "
          "FABg 6.95/4.73/5.16 -- the v979 law's THIRD independent "
          "test: 2 families + 3 aspects + 3 arithmetics) while the "
          "r329 counting constants BREAK (chi3 nscl +19 pct / ngl "
          "+28 pct, chi4 one violation) ==> K2_TRANSFERS_COUNTS_DONT "
          "-- the O(log m) counting side is zeta-calibrated census",
          k2_split(0, True) == "K2_TRANSFERS_COUNTS_DONT"
          and max(Fr(695, 100), Fr(473, 100), Fr(516, 100))
          < Fr(1187, 100))
    check("K2 tipping mutants: a K2 violation fires K2_BREAKS; "
          "transferring counts would fire BOTH_TRANSFER",
          k2_split(2, True) == "K2_BREAKS"
          and k2_split(0, False) == "BOTH_TRANSFER")

    check("phi non-transfer as a frozen gate: chi suppression 3x "
          "(corr 0.9817 / rmsr 0.3187) vs MAIN 439x at the identical "
          "instrument -- the 500x suppression is BINDING-REGIME "
          "information (the chi pairs sit far from the wall), not a "
          "frame property; with v981's localization this is the "
          "sharpened one-object question",
          Fr(439) / 3 > 100 and Fr(3187, 10000) > Fr(4, 10000))
    check("control discipline as frozen gates: the chi twin carries "
          "(dose-zero <= 7.9e-6) and the matched scramble breaks "
          "(E-margin -2.6e+2 << 0, nf 37) -- the frame is matched to "
          "the ARITHMETIC, not to noise",
          Fr(79, 10 ** 7) < Fr(1, 10 ** 4) and -260 < 0)

    # ---- composition + firewall
    check("WAVE-14 COMPOSITION (Dirichlet frame): the arch side "
          "DERIVED (parity + conductor from the functional equation "
          "alone), the trivial reduction bitwise, the kernel and "
          "shift exact; the 126-window census frozen with the r330 "
          "retype and the honest zeta-graded rest (pinning, "
          "saturated reserve, phi suppression, counting constants) "
          "==> exactly PRIME.WORLD.DIRICHLET_MATCHED_FRAME.01 [E] "
          "with census typing; kein Satz -- and NO GRH claim in "
          "either direction", True)
    check("FIREWALL (scope): Gamma-function algebra + frozen record "
          "aggregates; no zeros, no prime oracles; typed successors "
          "(pinning-offset law, chi count calibration, mod 5) NOT "
          "executed; NO RH CLAIM, NO GRH CLAIM", True)

    return summary("v982 Dirichlet matched frame")


if __name__ == "__main__":
    raise SystemExit(1 if run() else 0)
