#!/usr/bin/env python3
"""icc-offslice-evaluate.py -- the ice-cream cone (ICC) OFF the symmetric slice: the two lines p12^2 = -2 and p12^2 = -3.

THE TWO LINES LIVE OFF THE SLICE; THE STEP ONTO THE SLICE IS TAKEN BY --land (47 / 48 DIGITS AGAINST THE SLICE RECORDS).
  The served icc-evaluate.py evaluates the cone on the symmetric slice p12^2 = p34^2 = x (p56^2 = -1, m^2 = 1), where the
  system has seven masters.  This script carries the cone's NINE-master system on two lines that leave that slice --
  p12^2 = -2 and p12^2 = -3, with p34^2 the running invariant -- and, on each line, transports the nine masters from a
  seed point to a target point along p34^2 and compares them with an independent reference at the target.
  The step from either line onto the slice: landed by --land to 47 (-3) / 48 (-2) digits against the slice records (see
  THE --land TIER below): the point p34^2 = p12^2 is a singular point of the nine-master connection (the basis degenerates
  to the slice's seven masters there: two pairs of masters coincide); in the symmetric/antisymmetric gauge with the third
  relation the point is an apparent singularity (integer exponents, no logarithms, by the certificate of record), so the
  physical solution is analytic there and its value is the Cauchy mean of the transported solution on a circle around the
  point.  The default tiers gate the off-slice transport only; icc-evaluate.py is unchanged and is not used by this script
  (the slice references of the landing are vendored records, among them its own transport values at x = -3 and x = -2).

WHAT IS COMPUTED, AND HOW IT IS GATED (per line)
  The connection: the exact rational 9x9 matrix A_y(d, y) of the off-slice basis at fixed p12^2 (y = p34^2), from an
  IBP reduction of the derivative seeds, eps-expanded at d = 2 - 2 eps (vendor_rows1517_offslice/line_*/connection.json:
  the entries in (d, y) and the eps-Taylor coefficients the transport consumes).
  The transport: the engine of record (vendor_rows1517_offslice/transport_gate_y.py, driven with its command line of
  record) -- eps-graded local Taylor steps of order ceil(1.7 dps) + 20, step = 1/4 of the distance to the nearest root of
  any denominator in the complex plane, a trailing-window tail bound per step -- from the seed point's AMFlow Laurent
  values (goal 40, eps^-2..eps^0; 18 (master, eps-order) pairs) to the target, where the 18 pairs are compared with the
  independent AMFlow values (goal 40) of the target point.  Digits per pair: log10(|ref| / |transported - ref|).
  The bar: the floor of the record's worst agreement over the 18 pairs at the record precision (dps 60: 57 on both
  lines; the record's lower precision: 30 on the p12^2 = -3 line, 15 on the p12^2 = -2 line); at another --dps the bar
  of the highest record precision not above it applies and is named.  Every pair must meet the bar, else FAIL (rc 1).
  Three masters ([1,0,1,0,0,0,0], [1,1,1,0,0,0,0], [0,1,1,1,0,0,0]) do not depend on p34^2 (zero rows of A_y): the
  transport carries their seed values unchanged, and the seed and reference files hold byte-identical strings for their
  six (master, order) pairs (6/6 on each line) -- the same deterministic sub-system solve at both points, not one shared
  computation (the target runs' reduction-cache logs show 4 HIT / 14 MISS).  The transport cannot check those six
  pairs, so they are gated against the slice instead (the slice gate, below); the transport's independent check is the
  other six masters (12 pairs).
  The slice gate (per line, after the transport table): each of the six carried pairs is compared at run time in mpmath
  (dps 200) with the on-slice references and the closed forms vendored in the line's record -- the tadpole squared at
  eps^-2..0 with the served x = -1 boundary strings of icc-transport-data.json and with Gamma(eps)^2 at P = 1 (1,
  -2 gamma_E, 2 gamma_E^2 + zeta(2), evaluated here); the p56^2 bubble times a tadpole at eps^-1, 0 with the served
  x = -1 strings (no closed form on the record); the p12^2 sunrise at eps^0 with the on-slice AMFlow record at
  x = p12^2 (goal 150 at x = -2; goal 100 and 120 at x = -3) and with the 1000-digit closed-form value.  Digits per
  (pair, reference): log10(max(|a|,|b|) / |a - b|), capped by the shorter string; bar 57 on both lines (the floor of
  the record comparison's worst, 57.74 / 57.72 d on the p12^2 = -2 / -3 lines -- the goal-40 run's own depth), at every
  --dps.  Every pair must meet it, else FAIL (rc 1).
  The record comparison: at a record precision the 30-digit transported strings and the (dps+5)-digit value strings are
  compared with the shipped record of that line string for string, and the step/order/root counts must equal the record's.
  The seed's two-precision certificate (the p12^2 = -2 line): the seed point's goal-40 AMFlow values (seed.json) and an
  independent goal-60 AMFlow run at the same point (vendor_rows1517_offslice/line_m2/seed_g60.json, the same nine masters
  at eps^-2..eps^0; its run recorded in the line's record under amflow.seed.goal60_twin) are compared at run time over the
  18 nonzero (master, eps-order) components (the 18 imaginary parts are exactly 0 on both sides: structural zeros, excluded
  from the count; exactly 0 on one side only would be a structural mismatch, FAIL by name).  Digits per component:
  log10(max(|a|,|b|) / |a - b|) on the printed midpoints (identical strings count as the shorter string's significant
  digits); the worst over the components and the value of record ([1,1,1,1,0,0,0] at eps^0) are printed beside the
  figures the record carries (worst 57.3 d, value of record 59.47 d, floor 57); bar 30 (the record's
  two-precision bar), at every --dps.  A component below the bar FAILS by name (rc 1); a recomputed worst that differs
  from the recorded worst by more than 0.05 d, or a component count that differs from the recorded count, FAILS by name
  too.  The reference point of that line (p34^2 = -4) and both points of the p12^2 = -3 line have no goal-60 twin: the
  line says so by name.  ONE line per line; the [check] pair (dps, dps + 30) of the TRANSPORT is a different certificate.

THE eps^1 TIER (--kmax 1; the same two lines from the eps_order-5 files, 2026-09-06)
  The same four points were solved again by AMFlow at eps_order 5 (eps^-4..eps^1, goal 40; an independent goal-60 run at each
  seed): vendor_rows1517_offslice/line_m*/seed_e5.json, seed_e5_g60.json and reference_e5.json, beside the eps_order-4 files
  of record, every one pinned; their runs and the figures below are recorded in each line's record under eps1.  With
  --kmax 1 the engine carries the nine masters at eps^-2..eps^1 (27 state components on the SAME connection) from the
  eps_order-5 seed to the reference point, where the 27 transported values are compared with the independent eps_order-5
  AMFlow values by the metric of record, log10(|ref| / |transported - ref|) on the midpoints (the transported value complex,
  the reference re + i im; identical strings count as the shorter string's significant digits), recomputed at dps 250 from
  the engine's printed value strings.  The six p34^2-dependent masters give 18 transported pairs (12 at eps^-2..eps^0, 6 at
  eps^1); every one must meet the bar 30 (the two-precision bar, at every --dps >= 60), else FAIL (rc 1).  The eps^1
  transport gate = the worst of the six eps^1 pairs, printed with its member beside the recorded figure: worst
  47.56 d (member [1, 1, 1, 1, -2, 0, 0], floor 47) on the p12^2 = -2 line, 47.41 d (member
  [1, 1, 1, 1, -2, 0, 0], floor 47) on the p12^2 = -3 line; the eps^0 rows (the 12 pairs at eps^-2..eps^0) reproduce
  the recorded 55.25 / 55.18 d (the eps_order-4 record's 57.43 / 57.37 d stands: the goal-40 solve at eps_order 5 carries
  ~55 digits at eps^0, a measured figure of those files, not a defect).  At the record precision (dps 60) on the side of
  record the per-order floors with members (four orders) must equal the recorded ones (the other side of the contour moves
  the eps^-2 / eps^-1 counts in the last decimals: printed, not compared); at every dps the recomputed eps^1 and eps^0
  worsts must be within 0.05 d of the recorded (the goal-40 reference strings cap them).  The three p34^2-independent masters are
  carried unchanged (9 pairs, reported beside, never the floor; their eps_order-5 seed and reference strings are
  byte-identical); the slice gate and the eps_order-4 seed certificate print as in the default tier.  Two more lines
  per line: the cross-eps-order check (the eps_order-5 files vs the eps_order-4 files of record at the same point on the
  common orders eps^-2..eps^0, the eps^1 order not compared, component-wise with numerical zeros by the bar rule excluded
  and a zero on one side only a structural mismatch; recorded floors 55 / 55 on the -2 line, 54 / 55 on the -3 line)
  and the seed's two-precision certificate at eps_order 5 (goal 40 vs goal 60 over the 27 nonzero components of all
  four orders; worst 48.11 / 48.02 d, the eps^1 order 48.11 / 48.02 d over nine masters, floor 48 / 48; bar 30); both
  FAIL by name below the bar, on a structural mismatch, or when a recomputed worst differs from the recorded by more than
  0.05 d.  At dps 60 the transported and reference strings and the value strings are compared with the eps1 block of the
  record string for string, and the step/order/root counts must equal the record's (--side -1 against its own sub-block).
  --check, --mutate, --mutate-slice and --side combine with --kmax 1 as with the default tier (the planted seed digit
  goes into the eps_order-5 seed copy).  The step onto the slice: landed by --land to 47 (-3) / 48 (-2) digits against the
  slice records; see the tier.  Nothing here changes the default tier.

THE --land TIER (the landing onto the slice, 2026-09-06)
  The point p34^2 = p12^2 is where the nine-master basis degenerates to the slice's seven (two pairs of masters coincide).
  In the symmetric/antisymmetric gauge with the third relation (the exact gauge T(y0) of vendor_rows1517_offslice/land/
  line_m*/T_at_y0.json; the gauged connection A_prime_y.json) the point is an APPARENT singular point -- integer exponents
  (2 at -1, 6 at 0, 1 at +1) and no logarithms, the Frobenius certificate of record re-derived on the exported system (line_m*/
  A_prime_y_eps_monomial.json; --certificate re-derives it here when the detransport package is given by --tools DIR) --
  so the physical solution is analytic there and its value AT the point is the Cauchy mean of the transported solution on
  the circle |p34^2 - p12^2| = 1/16 about it (sixty-four nodes; the aliasing tail (rho/R)^N with R the distance to the next
  singular point: 4.7e-88 on the p12^2 = -3 line, 9.6e-78 on the p12^2 = -2 line).  The vendored engine land/land_fixed_eps.py
  (the y-transport numerics of record verbatim) gauges the line's eps_order-5 seed (line_m*/seed_e5.json, the file the
  --kmax 1 tier reads), marches the eps-graded system (eps^-2..eps^1, 27 state components) from the seed point to the
  circle and once around it, and lands: the closed loop must return to its start (the monodromy certificate), the mean of
  (y - x) J must vanish (the residue certificate: the physical solution has no pole) and the imaginary part must vanish
  (the slice values are real), each to a relative 1e-30 (the bar).  The landed gauged vector is mapped onto the slice's
  masters by the gate map (line_m*/GATE_MAP_slice.json: J_sym/2 = M_slice for the two mirror pairs, the unpaired masters as
  they are) and compared with the slice records vendored under land/line_m*/: the on-slice AMFlow records (x = -3: goal 120
  and goal 100; x = -2: goal 150) and the served icc-evaluate.py's own transport values at x (dps 60 and 90 at -3, dps 60 at
  -2: slice_icc_evaluate_*.json, re-derivable from the served evaluator by land/bank_slice_values.py), as relative digits
  log10(max(|a|,|b|) / |a - b|) capped by the shorter string; every (master, order, reference) pair must meet the bar 30
  (the two-precision bar), else FAIL (rc 1).  Structural zeros (an order below a master's lead order) are excluded by name;
  the antisymmetric combinations and the third-relation master K = w(y).M/(y - x) are derivatives at the point with no
  slice record (excluded by name; K lands at zero to working precision: w.M has a double zero there); the seventh slice
  master [1, 1, 1, 1, 0, -2, 0] is not in the nine-master basis and is not landed.
  The counts of record (dps 60, order 122; land/line_m*/landed_record.json, the record receipts by sha256): the p12^2 = -3
  line lands onto the slice at p34^2 = p12^2 = -3 to 47 digits at worst (measured 47.92 d, master [1, -2, 1, 1, 0, 0, 0] at
  eps^1 vs the goal-100 record; 62 pairs over 4 references; per order eps^-2 65.0, eps^-1 60.83, eps^0 55.53, eps^1 47.92 d), the
  p12^2 = -2 line to 48 (measured 48.08 d, master [1, 1, 1, 1, 0, 0, 0] at eps^1 vs the evaluator's dps-60
  transport; 28 pairs over 2 references; per order eps^-2 65.0, eps^-1 60.83, eps^0 55.56, eps^1 48.08 d); the two landings at dps 45
  and 60 agree on the slice-facing components to 49.39 / 49.39 d.  The tier prints its own floors with their members and
  the count line, compares the landed strings with the record's (identical strings expected at dps 60; the recorded worst
  within 0.05 d; the per-order floors equal), and at another --dps the agreement with the record's dps-60 strings must
  reach min(dps, 60) - 10 d.  Every count is a floor of a two-string agreement: the goal-40 eps_order-5 seeds cap the landed
  values (never a precision claim on the slice records); eps^1 on the p12^2 = -2 line is gated against the evaluator's
  transport only (the goal-150 record carries eps^-2..eps^0).
  --dps 30 is the record's pilot precision (worst 34.48 / 34.48 d of record on the -3 / -2 lines; with --second-radius a second
  circle at 1/32: two-radius agreement 35.52 / 36.00 d of record); --pair-dps D2 lands again at D2 and compares the two
  landings component-wise (land/compare_pair.py; the record's pair is --dps 45 --pair-dps 60); --mutate with --land changes
  one digit of a landed value in the copy of the run's receipt and re-runs the comparison (land/recompare_landing.py): it
  must FAIL by name (rc 1); --legB (the p12^2 = -3 line only) runs the fixed-eps `land` form of the detransport package
  with the eps-order-22 seed of record (line_m3/seed_e22.json) after the landing -- a ROUTE check at the named truncation
  floor (vs leg A summed at eps0 = 2^-27: 15.32 d of record against an expectation of 16.3 d), never a digit claim.
  --certificate and --legB import the detransport package (the DE toolkit this bundle does not vendor): pass the directory
  holding it as --tools DIR; without it --certificate prints the certificate of record and --legB is refused by name (rc 2).
  The pins: every file under land/ (the engine modules, the gauge objects, the slice references, the landed records,
  land_manifest.json naming each object's record source by sha256) is in PINS; land/bank_objects.py re-hashes them.

THE TWO LINES (the seed and target points as (p12^2, p34^2, p56^2, m^2))
  p12^2 = -3: seed (-3, -4, -1, 1) -> target (-3, -5, -1, 1) along the straight real segment (no denominator root on or
    near it).  Record: 57.37 d worst over 18 pairs at dps 60; 30.42 d at dps 30; eps^1: 47.41 d worst over 6 transported
    pairs (bar 30.0).
  p12^2 = -2: seed (-2, -3, -1, 1) -> target (-2, -4, -1, 1).  The connection has a real singular point on that segment,
    p34^2 = -2 - sqrt(3) = -3.732..., a root of y^2 + 4y + 1 (the d = 2 image of a d-dependent denominator factor): the
    path is a rectangular contour of depth 1/2 into the complex p34^2 plane around it (below the real axis; --side -1
    runs above, as the record also did).  Record: 57.43 d worst over 18 pairs at dps 60 on both sides; 15.56 d at dps 15; eps^1:
    47.56 d worst over 6 transported pairs (bar 30.0; both sides).

USAGE
  python3 icc-offslice-evaluate.py                       # = --line both --dps 60 (the two lines at the record precision)
  python3 icc-offslice-evaluate.py --line -3 --dps 30    # one line at the record's pilot precision (bar 30)
  python3 icc-offslice-evaluate.py --line -2 --side -1   # the other side of the contour on the p12^2 = -2 line
  python3 icc-offslice-evaluate.py --line -3 --check     # two precisions (dps, dps + 30), the record's own two-dps form
  python3 icc-offslice-evaluate.py --line -3 --mutate    # the planted control: one seed digit changed -> FAIL by name
  python3 icc-offslice-evaluate.py --line -3 --mutate-slice  # the slice-gate control: one carried seed digit changed -> FAIL by name
  python3 icc-offslice-evaluate.py --kmax 1              # THE eps^1 TIER: both lines from the eps_order-5 files (27 state components)
  python3 icc-offslice-evaluate.py --line -3 --kmax 1    # one line at eps^1; --check / --mutate / --mutate-slice / --side combine
  python3 icc-offslice-evaluate.py --land --line -3           # THE LANDING TIER: the -3 line onto the slice at dps 60 (the record's precision)
  python3 icc-offslice-evaluate.py --land --line -2 --dps 30 --second-radius   # the record's pilot form (the second circle at 1/32)
  python3 icc-offslice-evaluate.py --land --line -3 --dps 45 --pair-dps 60     # the two-precision pair of landings (the record's pair)
  python3 icc-offslice-evaluate.py --land --line -3 --dps 30 --mutate   # the landed-value control: one digit of a landed value changed -> FAIL by name
  python3 icc-offslice-evaluate.py --land --line -3 --legB --tools DIR  # + the fixed-eps route check (the detransport package under DIR)
  --dps D (>= 30; >= 60 with --kmax 1); --workdir DIR keeps the engine's GATE receipts (default: a fresh temporary directory, printed);
  --out JSON writes the run receipt (never overwrites).

EXIT CODES  0 PASS (every pair on every requested line meets its bar, the slice gate included) | 1 FAIL (a pair below
  the bar, named; also the expected outcome of --mutate and --mutate-slice) | 2 usage | 3 REFUSED (a shipped file's sha256 pin mismatch, named) | 4 a pinned file
  MISSING | 5 the transport engine (or the landing engine) did not finish (its exit code and last line printed) | 6 the --mutate,
  --mutate-slice or --land --mutate control NOT caught (a defect of the control, never a pass).

MEASURED WALLS (one process, nice 10, a shared 96-core host at loadavg ~120-140; a quiet core is faster): see the
  epilog of --help (the same table).
"""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
import time

HERE = os.path.dirname(os.path.abspath(__file__))
VENDOR = os.path.join(HERE, "vendor_rows1517_offslice")
RC_FAIL, RC_USAGE, RC_REFUSED, RC_MISSING, RC_ENGINE, RC_NOTCAUGHT = 1, 2, 3, 4, 5, 6

# --- PINS (script-emitted from the shipped bytes; sha256 of every vendored file) ---
PINS = {
    "vendor_rows1517_offslice/amf_result.py": "3064ec57183ee85ac730b93713d157c5ade22869b3ba4daaa949a45692ef641f",
    "vendor_rows1517_offslice/land/bank_objects.py": "aee119bda99fb58d1ed4bf8a15e0394a5916d705a57517314138d32fdd593079",
    "vendor_rows1517_offslice/land/bank_slice_values.py": "078c3ecaa52e9cea23c797ce228fdbb87ee99d8eba739ff004f7c880820e0415",
    "vendor_rows1517_offslice/land/compare_pair.py": "3281aa1c5dfb5d102e32de9fa40acdd87b38d666172271ec03f6f5429b94da28",
    "vendor_rows1517_offslice/land/land_fixed_eps.py": "f7ea7b141e276744e6fca3a9278960c53f3c1ae174c73be4799fe549e5df7d61",
    "vendor_rows1517_offslice/land/land_fixed_eps_legB.py": "097e0b0630d7677c5e84d0770829f32b1617d2b549cb3a8fc4b8991c4cce2ced",
    "vendor_rows1517_offslice/land/land_manifest.json": "51939c81a1a2f789e856fa5621ca5c352f4dd5f81792caf2deb8e58f21765a97",
    "vendor_rows1517_offslice/land/line_m2/A_prime_y.json": "4125fa70b68d17e4701b869cd35e148f5eebce56ceeb6d1d70d08dba2b80a6c7",
    "vendor_rows1517_offslice/land/line_m2/A_prime_y_eps_monomial.json": "7fb177d0cfcc4ff56142fea434c2e76fe1ab8b9462a1f3d28862d864ee7a092e",
    "vendor_rows1517_offslice/land/line_m2/GATE_MAP_slice.json": "bb97fd8c19eaaa19f401a46c2f397dfa8e32de1a292d9f8884da3e8c65d020c1",
    "vendor_rows1517_offslice/land/line_m2/ROUTE.json": "cf9bbdaff4732558017d6e4069dfc377b84d8b89e2187fa545f5f63d5e33e322",
    "vendor_rows1517_offslice/land/line_m2/T_at_y0.json": "86a1bf93281590dfba295f2e4305578012cb17ce8ccd4b30118024ee52dfdb96",
    "vendor_rows1517_offslice/land/line_m2/icc_xm2_g150_out.json": "6b880a7ec560f04a8f8eafc249ca335d22e6ec225c2b2ab564740576834987ce",
    "vendor_rows1517_offslice/land/line_m2/landed_record.json": "2d05689231dc8d94ad1ca0fa0fbbe2a525a26a3a0cc7f8c6e0d85644686ecd53",
    "vendor_rows1517_offslice/land/line_m2/slice_icc_evaluate_x-2_dps60.json": "cd35871555c0465846dadbd35f1cbfa7805e5a4df02247a660c8378eeb717c4e",
    "vendor_rows1517_offslice/land/line_m3/A_prime_y.json": "7e0283296a872c5c7dde1e7989875cd3657754b724e1053c137339291e842797",
    "vendor_rows1517_offslice/land/line_m3/A_prime_y_eps_monomial.json": "184bf6e19c4f61a9ad3106e4c42b6cc60380ccfbc69c4d4315305f247d0b6da2",
    "vendor_rows1517_offslice/land/line_m3/GATE_MAP_slice.json": "bb97fd8c19eaaa19f401a46c2f397dfa8e32de1a292d9f8884da3e8c65d020c1",
    "vendor_rows1517_offslice/land/line_m3/P1517-X3_g100.json": "173089a34194181c4b76b505135a205dab6bb7d98263095cb30d544c87316614",
    "vendor_rows1517_offslice/land/line_m3/ROUTE.json": "a8e7b7fe055fdd5626cb87e212ed918e17cd507edbe56fd9cc165e7bfb0c3926",
    "vendor_rows1517_offslice/land/line_m3/T_at_y0.json": "561efddd59cb8f8c8001d764a6729bcc7e87acb74b42e213e178faa7c70c0291",
    "vendor_rows1517_offslice/land/line_m3/icc_xm3_g120_out.json": "c3384faba49bdff6198f54dcf1590c7e77dcb81ed3d5427a412e1d8fd9bcd735",
    "vendor_rows1517_offslice/land/line_m3/landed_record.json": "577b98bbd2cb84d1af3b83ab8539bd4e5754760110bedea3216a5f3814612504",
    "vendor_rows1517_offslice/land/line_m3/seed_e22.json": "f177b14db9e148d6af77c820f4e38330d69d1f4b34d0a478fc1b6065fc9a772d",
    "vendor_rows1517_offslice/land/line_m3/slice_icc_evaluate_x-3_dps60.json": "6a19d8c5e7c8f89804db559898658b18abd4fcd5ce2f5dde3c90d78f4eb7a4e6",
    "vendor_rows1517_offslice/land/line_m3/slice_icc_evaluate_x-3_dps90.json": "4b6a48b8f133cf94de1b50138e9722637093b5673670b444338d9af984de78d7",
    "vendor_rows1517_offslice/land/recompare_landing.py": "8346a6a9612dc1d7cb66cdd69e69d38e065fea5901967b02f9e0ac24750c823c",
    "vendor_rows1517_offslice/land/seed_points.json": "f82a96878a291faff92ba9d130729f4bbe4ea0532c3398eca2eca175b1b04279",
    "vendor_rows1517_offslice/line_m2/connection.json": "88d86ca3ec3f0a889fee87692838de92451474d3c50ce8199f1afbb4adc30106",
    "vendor_rows1517_offslice/line_m2/record.json": "623bd3760340334d10391b33ac3d483a046b8665d259aa62c92551b7a8e0a2ad",
    "vendor_rows1517_offslice/line_m2/reference.json": "a72df782a96b711e0119e70c9bd4d7e13f07fb518af7f92cee693e4a50a7fad3",
    "vendor_rows1517_offslice/line_m2/reference_e5.json": "c2248ce8222e2393f592bc851fa458ad4ca731d7e887b87131472e6ad9c84f6c",
    "vendor_rows1517_offslice/line_m2/seed.json": "e76a4ca6e988a784f1db6a837677b284e4349e3e88f1082f57fd8545db421947",
    "vendor_rows1517_offslice/line_m2/seed_e5.json": "1c083fa77e6df89c26e249b31cab14b0265c1756ac7cfc78c5bcdcb946110785",
    "vendor_rows1517_offslice/line_m2/seed_e5_g60.json": "32a017f499a88e2864ed8eb515861aa902436521f71e6e30f7ee5d3e9e353163",
    "vendor_rows1517_offslice/line_m2/seed_g60.json": "095630d802033cff1ec8d65eaaa58fd997d9d0bc2a94307ee4167d2579561296",
    "vendor_rows1517_offslice/line_m3/connection.json": "13b04708afd5619a3ff27ffa79908e521ff024f90c62ace9b1ee00d1e16e68c6",
    "vendor_rows1517_offslice/line_m3/record.json": "e94b9e46440a3ef1b5fccd9bc18502f44cc8de7b30d1fa83f5bae7c267476bf9",
    "vendor_rows1517_offslice/line_m3/reference.json": "7e6913b850f9ddb90c676f639c6c74de99b7a17ac6e0e97428872945e9a496a8",
    "vendor_rows1517_offslice/line_m3/reference_e5.json": "92f76fc419428f013fa5470610f8784015ea84b85fa252a34b93dd5399cb5c06",
    "vendor_rows1517_offslice/line_m3/seed.json": "ff8352a8ca65bc21a7dbd6466849f91966a37a173948d08dfe05793dffb5111d",
    "vendor_rows1517_offslice/line_m3/seed_e5.json": "0294999af45e2a9e73374ea74535dc058218f0e35530630b7e70a40767a760c5",
    "vendor_rows1517_offslice/line_m3/seed_e5_g60.json": "480e097b786403b1251adb5bd38f82cb08f3a97ca8b9e8d7c7844901577e97e0",
    "vendor_rows1517_offslice/lines.json": "26376b7bee3cf73b4ff5c198c6e155794998b16cef9969933326ba0322adcedb",
    "vendor_rows1517_offslice/transport_gate_y.py": "2301558bc953c2c45966297e6e2f91e3c8486ddaa427a816226ce0561b699d5c",
}
# --- END PINS ---

# measured walls (GNU time, the delivered bytes; written by the build from its captures)
WALLS = {
    "default (--line both --dps 60)": "156.56 s",
    "--line -3 --dps 60": "46.83 s",
    "--line -2 --dps 60": "109.41 s",
    "--line -2 --dps 60 --side -1": "112.45 s",
    "--line -3 --dps 30": "26.62 s",
    "--line -2 --dps 30": "53.14 s",
    "--line -3 --check (dps 60 + 90)": "137.57 s",
    "--line -2 --check (dps 60 + 90)": "287.41 s",
    "--line -3 --mutate": "51.53 s",
    "--line -2 --mutate": "111.93 s",
    "--line -3 --mutate-slice": "47.76 s",
    "--line -2 --mutate-slice": "110.85 s",
    "--kmax 1 (both lines, dps 60)": "234.22 s",
    "--line -3 --kmax 1": "66.17 s",
    "--line -2 --kmax 1": "167.32 s",
    "--line -2 --kmax 1 --side -1": "152.91 s",
    "--line -3 --check --kmax 1 (dps 60 + 90)": "180.20 s",
    "--line -2 --mutate --kmax 1": "171.20 s",
    "--line -2 --mutate-slice --kmax 1": "165.03 s",
    "--land --line -3 --dps 60": "837.36 s",
    "--land --line -2 --dps 60": "836.15 s",
    "--land --line -3 --dps 30 --second-radius --certificate": "603.54 s",
    "--land --line -2 --dps 30 --second-radius --certificate": "640.58 s",
    "--land --line -3 --dps 45 --pair-dps 60 --legB": "1515.91 s",
    "--land --line -2 --dps 45 --pair-dps 60": "1397.48 s",
    "--land --line -3 --dps 30 --mutate": "368.35 s",
}


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for ch in iter(lambda: f.read(1 << 20), b""):
            h.update(ch)
    return h.hexdigest()


def utc():
    return subprocess.run(["date", "-u", "+%Y-%m-%dT%H:%M:%SZ"], capture_output=True, text=True).stdout.strip()


def die(rc, msg):
    print(msg, flush=True)
    sys.exit(rc)


def check_pins():
    for rel, want in PINS.items():
        p = os.path.join(HERE, rel)
        if not os.path.exists(p):
            die(RC_MISSING, f"icc-offslice-evaluate MISSING: pinned file {rel} is absent (recorded sha256 {want}); not serving")
        got = sha256_file(p)
        if got != want:
            pos = next(i + 1 for i in range(64) if got[i] != want[i])
            die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: {rel} integrity pin mismatch (recorded {want}, recomputed {got}; "
                            f"first differing hex position {pos} of 64, 1-based) -- the shipped file was altered; not serving")
    return len(PINS)


CPX = re.compile(r"^\(?\s*([-+]?[\d.]+(?:e[-+]?\d+)?)\s*(?:([-+])\s*([\d.]+(?:e[-+]?\d+)?)j)?\s*\)?$")


def parse_value(s):
    """the engine's mp.nstr of an mpc: '(re + imj)' / '(re - imj)' / a bare real -> (re_str, im_str with sign)."""
    m = CPX.match(s.strip())
    if not m:
        raise ValueError(s)
    re_, sg, im = m.groups()
    return re_, (sg + im if im is not None else "0")


def agree_digits(a_str, b_str, ref_str, dps=200):
    """log10(|ref| / |a - b|) with a, b the engine's value strings (complex allowed), ref the reference midpoint."""
    from mpmath import mp, mpf, mpc, fabs, log10
    with mp.workdps(dps):
        ar, ai = parse_value(a_str)
        br, bi = parse_value(b_str)
        a, b = mpc(mpf(ar), mpf(ai)), mpc(mpf(br), mpf(bi))
        ref = mpf(ref_str)
        d = fabs(a - b)
        if d == 0:
            return float("inf")
        return float(log10(fabs(ref) / d))


def bar_for(rec, dps):
    """the bar at this precision: the floor of the record's worst at the highest record precision not above dps."""
    rd = sorted(int(k) for k in rec["bars"] if k.isdigit())
    use = max(k for k in rd if k <= dps)
    return rec["bars"][str(use)], use, rd


def mutate_seed(seed_path, out_path, master):
    """the planted control: the eps^0 midpoint of one master's seed value gets its 15th decimal digit changed by one."""
    d = json.load(open(seed_path))
    hit = None
    for r in d["result"]:
        if r["integral"]["indices"] == master:
            c = [c for c in r["coefficients"] if int(c["order"]) == 0][0]
            s = c["value"]["re"]
            i = s.index(".") + 15
            new = s[:i] + str((int(s[i]) + 1) % 10) + s[i + 1:]
            c["value"]["re"] = new
            hit = (s[i], new[i], i)
    assert hit is not None
    json.dump(d, open(out_path, "w"), indent=1)
    return hit


def run_engine(line, L, dps, side, workdir, seed_override=None, tag="", kmax=0, files=None):
    """drive the vendored engine with the command line of record; return (gate json, engine rc, wall, last line).
    kmax 1 (the eps^1 tier): the eps_order-5 seed / reference files (files = {"seed", "reference"} relative to the line
    dir, from the record's eps1 block) and '--kmax 1' after --dps on the command line; the receipt name carries _kmax1."""
    files = dict(L["files"], **{k: os.path.join(os.path.dirname(L["files"]["seed"]), v) for k, v in (files or {}).items()})
    conn = os.path.join(VENDOR, files["connection"])
    seed = seed_override or os.path.join(VENDOR, files["seed"])
    ref = os.path.join(VENDOR, files["reference"])
    ktag = "_kmax1" if kmax else ""
    out = os.path.join(workdir, f"GATE_line{line}_dps{dps}_side{side:+d}{ktag}{tag}.json")
    kopt = ["--kmax", str(kmax)] if kmax else []
    cmd = [sys.executable, os.path.join(VENDOR, "transport_gate_y.py"), "--conn", conn, "--coef-key", "coef_y", "--seed", seed,
           "--seed-var", L["seed_point"]["p34sq"], "--target", L["reference_point"]["p34sq"], "--gate", ref, "--dps", str(dps)] + kopt + [
           "--detour", L["path"]["detour"], "--detour-sign", str(side), "--out", out]
    print(f"  [engine] transport_gate_y.py --conn {os.path.relpath(conn, VENDOR)} --coef-key coef_y --seed {os.path.basename(seed)} --seed-var {L['seed_point']['p34sq']} "
          f"--target {L['reference_point']['p34sq']} --gate {os.path.relpath(ref, VENDOR)} --dps {dps}{' --kmax ' + str(kmax) if kmax else ''} --detour {L['path']['detour']} --detour-sign {side} --out {os.path.basename(out)}", flush=True)
    env = dict(os.environ)
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    t0 = time.time()
    last = ""
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=workdir, env=env)
    for ln in p.stdout:
        ln = ln.rstrip("\n")
        last = ln
        print(f"  [engine] {ln}", flush=True)
    rc = p.wait()
    wall = time.time() - t0
    if rc != 0 or not os.path.exists(out):
        die(RC_ENGINE, f"icc-offslice-evaluate ENGINE FAILED on the p12^2 = {line} line at dps {dps}: rc {rc}; last line: {last!r}")
    return json.load(open(out)), out, round(wall, 1)


def ball_mid(s):
    """an AMFlow value string '[mid +/- rad]' (or a bare decimal) -> (midpoint string, radius string or None)."""
    s = str(s).strip()
    if s.startswith("[") and "+/-" in s:
        mid, rad = s[1:-1].split("+/-")
        return (mid.strip() or "0"), rad.strip()
    return s.strip("[]"), None


def sig_digits(s):
    """the significant decimal digits printed in a value string (leading zeros dropped; an exponent ignored)."""
    t = str(s).strip().lstrip("-+")
    if "e" in t:
        t = t.split("e")[0]
    return len(t.replace(".", "").lstrip("0"))


def closed_form_value(cf, dps):
    """the closed forms the slice gate evaluates at run time: tadpole2 = Gamma(eps)^2 P^-eps at P = 1 (the served
    icc-evaluate.py form): eps^-2 1, eps^-1 -2 gamma_E, eps^0 2 gamma_E^2 + zeta(2)."""
    from mpmath import mp, mpf, euler, zeta
    with mp.workdps(dps):
        if cf["id"] == "tadpole2":
            g = +euler
            return {-2: mpf(1), -1: -2 * g, 0: 2 * g * g + zeta(2)}[int(cf["order"])]
    raise KeyError(cf["id"])


def slice_agree(a_str, b, dps):
    """the slice gate's count: log10(max(|a|,|b|) / |a - b|) at dps on the midpoints; inf when equal."""
    from mpmath import mp, mpf, fabs, log10
    with mp.workdps(dps):
        a = mpf(a_str)
        b = mpf(b) if isinstance(b, str) else b
        d = fabs(a - b)
        if d == 0:
            return float("inf")
        return float(log10(max(fabs(a), fabs(b)) / d))


def amf_value(d, master, order):
    """the value dict {re, im} of one (master, eps-order) in an AMFlow output file."""
    for r in d["result"]:
        if r["integral"]["indices"] == master:
            for c in r["coefficients"]:
                if int(c["order"]) == order:
                    return c["value"]
    raise KeyError((master, order))


def slice_gate(L, rec, mutate_slice=False):
    """the six carried pairs vs the slice: the pinned seed file's strings against the record's vendored on-slice references
    and closed forms, in mpmath at the record's dps (200); the count per (pair, reference) capped by the shorter string;
    every pair must meet the bar.  --mutate-slice plants one digit in the [0,1,1,1] eps^0 seed string of the copy read
    here (the transport, run on the pinned files, is untouched: its rows for that pair still agree)."""
    SG = rec["slice_gate"]
    dps, bar = int(SG["dps"]), SG["bar"]
    seed = json.load(open(os.path.join(VENDOR, L["files"]["seed"])))
    refj = json.load(open(os.path.join(VENDOR, L["files"]["reference"])))
    planted = None
    pairs, fails = [], []
    worst_on = worst_cf = None
    n_same = 0
    for p in SG["pairs"]:
        m, k = p["master"], int(p["order"])
        sv, rv = amf_value(seed, m, k), amf_value(refj, m, k)
        same = (sv["re"] == rv["re"]) and (sv.get("im") == rv.get("im"))
        n_same += same
        s_mid, s_rad = ball_mid(sv["re"])
        if mutate_slice and m == [0, 1, 1, 1, 0, 0, 0] and k == 0:
            i = s_mid.index(".") + 15
            new = s_mid[:i] + str((int(s_mid[i]) + 1) % 10) + s_mid[i + 1:]
            planted = {"master": m, "order": k, "position": i, "digit": i - s_mid.index("."), "old": s_mid[i], "new": new[i], "before": s_mid[:24], "after": new[:24]}
            s_mid = new
        rows = []
        for R in p["references"]:
            if "closed_form" in R:
                b = closed_form_value(R["closed_form"], dps)
                cap = min(sig_digits(s_mid), dps)
            else:
                b = ball_mid(R["value"])[0]
                cap = min(sig_digits(s_mid), sig_digits(b))
            d = slice_agree(s_mid, b, dps)
            count = float(cap) if d == float("inf") else round(min(d, cap), 2)
            ok = count >= bar
            rows.append({"kind": R["kind"], "reference": R["provenance"]["name"], "label": R["label"], "agree_d": count, "cap": cap, "capped": d >= cap, "pass": ok})
            if R["kind"] == "on-slice record":
                worst_on = count if worst_on is None else min(worst_on, count)
            else:
                worst_cf = count if worst_cf is None else min(worst_cf, count)
            if not ok:
                fails.append({"master": m, "order": k, "agree_d": count, "reference": R["provenance"]["name"], "kind": R["kind"]})
        pairs.append({"master": m, "order": k, "seed_string_significant_digits": sig_digits(s_mid), "seed_vs_reference_strings_byte_identical": same,
                      "worst": min(r["agree_d"] for r in rows), "references": rows})
    n_cf = sum(1 for p in pairs if any(r["kind"] == "closed form" for r in p["references"]))
    return {"bar": bar, "dps": dps, "n_pairs": len(pairs), "n_with_closed_form": n_cf, "seed_vs_reference_strings_byte_identical": n_same,
            "worst_vs_onslice_records": worst_on, "worst_vs_closed_forms": worst_cf, "worst": min(worst_on, worst_cf),
            "n_fail": len(fails), "fails": fails, "pairs": pairs, "mutation": planted}


def seed_twin_certificate(L, rec):
    """the seed value's two-precision certificate: the pinned goal-40 seed file vs the goal-60 twin the line's record names
    (amflow.seed.goal60_twin; both shipped, both pinned), component-wise over (master, eps-order): both sides exactly 0 =
    a structural zero, excluded; exactly 0 on one side only = a structural mismatch, FAIL by name; a counted component's
    digits = log10(max(|a|,|b|) / |a - b|) on the printed midpoints in mpmath at dps 250 (identical strings count as the
    shorter string's significant digits; the compare receipt's rule); the worst over the counted components and the
    value-of-record component vs the block's bar; the count must equal the block's, the recomputed worst the recorded worst
    within 0.05 d.  A line whose record carries no twin block: no certificate (the line says so by name)."""
    from mpmath import mp, mpf, fabs, log10
    seed_rel = L["files"]["seed"]
    blk = rec.get("amflow", {}).get("seed", {}).get("goal60_twin")
    if not blk:
        line = (f"seed two-precision certificate: no goal-60 twin on this line (neither the seed point p34^2 = {L['seed_point']['p34sq']} "
                f"nor the reference point p34^2 = {L['reference_point']['p34sq']} has one): no certificate")
        return {"present": False, "line": line, "n_fail": 0, "fails": [], "fail_text": ""}
    twin_rel = os.path.join(os.path.dirname(seed_rel), blk["file"])
    twin_path = os.path.join(VENDOR, twin_rel)
    got = sha256_file(twin_path)
    if got != blk["sha256"]:
        die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: the twin {twin_rel} hashes to {got} but the record block amflow.seed.goal60_twin records {blk['sha256']}; not serving")
    seed = json.load(open(os.path.join(VENDOR, seed_rel)))
    twin = json.load(open(twin_path))
    sm = [tuple(e["integral"]["indices"]) for e in seed["result"]]
    tm = [tuple(e["integral"]["indices"]) for e in twin["result"]]
    if sm != tm:
        die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: the twin {twin_rel} lists the masters differently from the seed file; not serving")
    tp = blk["two_precision"]
    bar = tp["bar"]
    vor_m, vor_k = [1, 1, 1, 1, 0, 0, 0], 0
    counted, zeros, mism = [], 0, []
    vor = None
    with mp.workdps(250):
        for e_s, e_t in zip(seed["result"], twin["result"]):
            ks = {int(c["order"]): c["value"] for c in e_s["coefficients"]}
            kt = {int(c["order"]): c["value"] for c in e_t["coefficients"]}
            if sorted(ks) != sorted(kt):
                die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: the twin {twin_rel} carries other eps-orders than the seed file for master {list(e_s['integral']['indices'])}; not serving")
            for k in sorted(ks):
                for comp in ("re", "im"):
                    a_mid, a_rad = ball_mid(ks[k][comp])
                    b_mid, b_rad = ball_mid(kt[k][comp])
                    a, b = mpf(a_mid), mpf(b_mid)
                    a0 = a == 0 and (a_rad is None or mpf(a_rad) == 0)
                    b0 = b == 0 and (b_rad is None or mpf(b_rad) == 0)
                    if (a0 and b0) or (a == 0 and b == 0):
                        zeros += 1
                        continue
                    if a0 != b0 or (a == 0) != (b == 0):
                        mism.append((list(e_s["integral"]["indices"]), k, comp))
                        continue
                    cap = min(sig_digits(a_mid), sig_digits(b_mid))
                    d = float(cap) if a == b else float(log10(max(fabs(a), fabs(b)) / fabs(a - b)))
                    counted.append((list(e_s["integral"]["indices"]), k, comp, d))
                    if list(e_s["integral"]["indices"]) == vor_m and k == vor_k and comp == "re":
                        vor = d
    worst = round(min(d for (_, _, _, d) in counted), 2) if counted else None
    vor_r = round(vor, 2) if vor is not None else None
    below = [(m, k, c, round(d, 2)) for (m, k, c, d) in counted if d < bar]
    fails = []
    if mism:
        fails.append("structural mismatch (exactly 0 on one side only) on " + ", ".join(f"{m}|eps^{k} {c}" for m, k, c in mism))
    if below:
        fails.append(f"below the bar {bar:g} on {len(below)} component(s): " + ", ".join(f"{m}|eps^{k} {c} {d} d" for m, k, c, d in below))
    if len(counted) != tp["n_components_counted"]:
        fails.append(f"{len(counted)} components counted vs {tp['n_components_counted']} recorded")
    if worst is None or abs(worst - tp["worst_agree_d"]) > 0.05:
        fails.append(f"recomputed worst {worst} d vs recorded {tp['worst_agree_d']} d differ by more than 0.05 d")
    if vor_r is None:
        fails.append("the value-of-record component [1, 1, 1, 1, 0, 0, 0]|eps^0 re not counted")
    verdict = "PASS" if not fails else "FAIL: " + "; ".join(fails)
    line = (f"seed two-precision certificate (goal 40 {os.path.basename(seed_rel)} vs goal 60 {blk['file']}, the same point p34^2 = {L['seed_point']['p34sq']}): "
            f"worst {worst:.2f} d over {len(counted)} nonzero (master, eps-order) components ({zeros} structural zeros excluded; recorded {tp['worst_agree_d']} d, "
            f"floor {tp['digits_demonstrated_floor']}), the value of record {vor_m}|eps^0 {vor_r if vor_r is None else format(vor_r, '.2f')} d (recorded {tp['value_of_record_agree_d']} d), "
            f"bar {bar:g}: {verdict}; the reference point p34^2 = {L['reference_point']['p34sq']} has no goal-60 twin (not shipped)")
    return {"present": True, "line": line, "twin_file": blk["file"], "twin_sha256": got, "n_counted": len(counted), "n_structural_zero_excluded": zeros,
            "worst": worst, "value_of_record": vor_r, "bar": bar, "recorded": {"worst_agree_d": tp["worst_agree_d"], "value_of_record_agree_d": tp["value_of_record_agree_d"],
            "digits_demonstrated_floor": tp["digits_demonstrated_floor"], "n_components_counted": tp["n_components_counted"]},
            "components": [{"master": m, "order": k, "component": c, "agree_d": round(d, 2)} for (m, k, c, d) in counted],
            "n_fail": len(fails), "fails": fails, "fail_text": "; ".join(fails)}


def parse_engine_value(s):
    """the engine's value string '(re + imj)' / '(re - imj)' / a bare real -> (mpc, the significant digits of the real part)."""
    from mpmath import mpf, mpc
    re_, im = parse_value(s)
    return mpc(mpf(re_), mpf(im)), sig_digits(re_)


def eps1_pair_block(A, B, name_a, name_b, bar, orders=None):
    """the comparator's pair rule on two AMFlow files (dict master -> {order: value dict}) on their COMMON orders (or the given
    ones), component-wise (re, im) at dps 250: a component is a numerical zero on a side when |mid| <= max(radius, 10^-bar x
    |eps^0 mid| of that master); zero on both sides -> excluded and named; zero on one side only -> a structural mismatch
    (FAIL); a counted component's digits = log10(max(|a|,|b|) / |a - b|) on the midpoints, capped by the shorter string
    (identical = the cap); floors per order with members; the worst with its member."""
    from mpmath import mp, mpf, fabs, log10
    counted, zeros, mism = [], [], []
    with mp.workdps(250):
        for m in A:
            ca, cb = A[m], B[m]
            common = sorted(set(ca) & set(cb)) if orders is None else [o for o in orders if o in ca and o in cb]
            if 0 not in common:
                die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: eps^0 not common for master {list(m)} in {name_a} vs {name_b}; not serving")
            sa = fabs(mpf(ball_mid(ca[0]["re"])[0])); sb = fabs(mpf(ball_mid(cb[0]["re"])[0]))
            for o in common:
                for comp in ("re", "im"):
                    a_mid, a_rad = ball_mid(ca[o].get(comp, "0")); b_mid, b_rad = ball_mid(cb[o].get(comp, "0"))
                    ma, mb = mpf(a_mid), mpf(b_mid)
                    ra, rb = mpf(a_rad or "0"), mpf(b_rad or "0")
                    za = fabs(ma) <= max(ra, mpf(10) ** (-bar) * sa); zb = fabs(mb) <= max(rb, mpf(10) ** (-bar) * sb)
                    if za and zb:
                        zeros.append((m, o, comp)); continue
                    if za != zb:
                        mism.append((m, o, comp)); continue
                    cap = min(sig_digits(a_mid), sig_digits(b_mid))
                    d = float(cap) if ma == mb else float(log10(max(fabs(ma), fabs(mb)) / fabs(ma - mb)))
                    counted.append((m, o, comp, d))
    below = [(m, o, c, d) for (m, o, c, d) in counted if d < bar]
    worst = min((d for (_, _, _, d) in counted), default=None)
    wm = next(({"master": list(m), "order": o, "component": c} for (m, o, c, d) in counted if d == worst), None)
    per_order = {}
    for (m, o, c, d) in counted:
        po = per_order.setdefault(str(o), {"min": None, "member": None, "n": 0}); po["n"] += 1
        if po["min"] is None or d < po["min"]:
            po["min"] = round(d, 2); po["member"] = {"master": list(m), "component": c}
    return {"n_counted": len(counted), "n_zero_excluded": len(zeros), "structural_mismatch": [{"master": list(m), "order": o, "component": c} for (m, o, c) in mism],
            "below_bar": [{"master": list(m), "order": o, "component": c, "agree_d": round(d, 2)} for (m, o, c, d) in below],
            "worst": (round(worst, 2) if worst is not None else None), "worst_member": wm, "floor": (int(worst // 1) if worst is not None else None), "per_order": per_order,
            "components": [{"master": list(m), "order": o, "component": c, "agree_d": round(d, 2)} for (m, o, c, d) in counted]}


def amf_table(path):
    """an AMFlow out file -> {master tuple: {order: value dict}} in the file's master order."""
    d = json.load(open(path))
    return {tuple(e["integral"]["indices"]): {int(c["order"]): c["value"] for c in e["coefficients"]} for e in d["result"]}


def eps1_gate(L, E, g, dps, bar, side):
    """the eps^1 tier's gate at the second point: the engine's 27 value strings (dps + 5 digits, complex) vs the eps_order-5
    reference balls by the metric of record, log10(|ref| / |transported - ref|) at dps 250 (identical -> capped at the shorter
    string); rows in the engine's order with their kind (transported = the six p34^2-dependent masters; carried = the three zero
    rows of A_y, reported beside, never the floor); the per-order floors with members over the transported pairs and over the
    carried ones; the eps^1 gate (the six eps^1 pairs) and the eps^0 rows (the 12 pairs at eps^-2..eps^0) vs the record's eps1
    block: at the block's dps on the side of record the four per-order floors (min, max, member, n) must equal the recorded (the
    other side of the contour moves the eps^-2 / eps^-1 counts in the last decimals through its imaginary residue: printed, not
    compared); at every dps and on either side the eps^1 and
    eps^0 worsts within 0.05 d of the recorded; every transported pair vs the bar.  The carried pairs: the eps_order-5 seed and
    reference strings must be byte-identical (the block's count).  Returns the rows (the engine's 30-digit strings, agree_d
    recomputed), the figures, the printed lines and the fails by name."""
    from mpmath import mp, mpf, mpc, fabs, log10
    TG = E["transport_gate"]
    yind = set(tuple(m) for m in json.load(open(os.path.join(VENDOR, L["files"]["record"])))["y_independent_masters"]["masters"])
    ldir = os.path.dirname(L["files"]["seed"])
    ref = amf_table(os.path.join(VENDOR, ldir, E["amflow"]["reference"]["file"]))
    seed = amf_table(os.path.join(VENDOR, ldir, E["amflow"]["seed"]["file"]))
    rows, tr, car = [], [], []
    with mp.workdps(250):
        for r in g["gate"]["rows"]:
            m, K = tuple(r["master"]), int(r["order"])
            key = f"{m}|{K}"
            t, nt = parse_engine_value(g["values"][key])
            gre, gra = ball_mid(ref[m][K]["re"]); gim, _ = ball_mid(ref[m][K].get("im", "0"))
            rf = mpc(mpf(gre), mpf(gim))
            if rf == 0:
                die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: the reference value of {list(m)}|eps^{K} is exactly 0; not serving")
            dv = fabs(t - rf)
            cap = min(nt, sig_digits(gre))
            d = float(cap) if dv == 0 else float(log10(fabs(rf) / dv))
            kind = "carried" if m in yind else "transported"
            same = (seed[m][K] == ref[m][K]) if kind == "carried" else None
            rows.append({"master": list(m), "order": K, "kind": kind, "transported": r["transported"], "gate": r["gate"], "agree_d": round(d, 2), "capped": dv == 0, "seed_vs_reference_strings_byte_identical": same})
            (car if kind == "carried" else tr).append((m, K, d))

    def floors(lst):
        out = {}
        for (m, K, d) in lst:
            po = out.setdefault(str(K), {"min": None, "member": None, "n": 0, "max": None}); po["n"] += 1
            if po["min"] is None or d < po["min"]:
                po["min"] = round(d, 2); po["member"] = list(m)
            if po["max"] is None or d > po["max"]:
                po["max"] = round(d, 2)
        return out
    ft, fc = floors(tr), floors(car)
    e1 = [(m, K, d) for (m, K, d) in tr if K == 1]
    e0 = [(m, K, d) for (m, K, d) in tr if K <= 0]
    w1 = min(d for (_, _, d) in e1) if e1 else None
    m1 = next(list(m) for (m, _, d) in e1 if d == w1) if e1 else None
    w0 = min(d for (_, _, d) in e0) if e0 else None
    m0 = next(list(m) for (m, _, d) in e0 if d == w0) if e0 else None
    wc = min(d for (_, _, d) in car) if car else None
    same_n = sum(1 for r in rows if r["kind"] == "carried" and r["seed_vs_reference_strings_byte_identical"])
    same_1 = sum(1 for r in rows if r["kind"] == "carried" and r["order"] == 1 and r["seed_vs_reference_strings_byte_identical"])
    fails = []
    R1, R0 = TG["eps1"], TG["eps0_rows"]
    if len(e1) != R1["n_pairs"]:
        fails.append(f"{len(e1)} eps^1 pairs transported vs {R1['n_pairs']} recorded")
    if w1 is None or abs(round(w1, 2) - R1["worst_agree_d"]) > 0.05:
        fails.append(f"eps^1 recomputed worst {None if w1 is None else round(w1, 2)} d vs recorded {R1['worst_agree_d']} d differ by more than 0.05 d")
    if len(e0) != R0["n_pairs"]:
        fails.append(f"{len(e0)} eps^0-row pairs transported vs {R0['n_pairs']} recorded")
    if w0 is None or abs(round(w0, 2) - R0["worst_agree_d"]) > 0.05:
        fails.append(f"eps^0 rows recomputed worst {None if w0 is None else round(w0, 2)} d vs recorded {R0['worst_agree_d']} d differ by more than 0.05 d")
    at_rec = dps == TG["dps"] and side == TG["engine"]["detour_sign"]
    fl_eq = None
    if at_rec:
        RF = TG["per_order_floor_with_member_transported"]
        fl_eq = sorted(ft) == sorted(RF) and all(abs(ft[k]["min"] - RF[k]["min"]) <= 0.005 and abs(ft[k]["max"] - RF[k]["max"]) <= 0.005 and ft[k]["member"] == RF[k]["member"] and ft[k]["n"] == RF[k]["n"] for k in RF)
        if not fl_eq:
            fails.append(f"the per-order floors {json.dumps(ft)} differ from the recorded {json.dumps(RF)}")
    if same_n != len(car):
        fails.append(f"the carried masters' eps_order-5 seed vs reference strings byte-identical on {same_n} of {len(car)} pairs")
    below = [(m, K, d) for (m, K, d) in tr if d < bar]
    y1 = L["reference_point"]["p34sq"]
    fl_txt = ", ".join(f"eps^{k}: {ft[k]['min']} d ({ft[k]['n']})" for k in sorted(ft, key=int))
    lines = [
        f"eps^1 transport gate (the six p34^2-dependent masters at eps^1 vs the independent eps_order-5 AMFlow values at p34^2 = {y1}): worst {w1:.2f} d (member {m1}) over {len(e1)} pairs, "
        f"max {ft.get('1', {}).get('max')} d; recorded {R1['worst_agree_d']} d (floor {R1['digits_demonstrated_floor']}); bar {bar:g}: "
        + ("PASS" if not [x for x in below if x[1] == 1] and not any("eps^1" in f for f in fails) else "FAIL: " + "; ".join([f"{list(m)}|eps^{K} {d:.2f} d below the bar" for (m, K, d) in below if K == 1] + [f for f in fails if "eps^1" in f])),
        f"eps^0 rows (the same six masters at eps^-2..eps^0, {len(e0)} pairs): worst {w0:.2f} d (member {m0}); recorded {R0['worst_agree_d']} d (floor {R0['digits_demonstrated_floor']}; the eps_order-4 record {R0['eps_order_4_record']['worst_agree_d']} d at bar {R0['eps_order_4_record']['bar']}); "
        f"per order {fl_txt}" + (f" == the recorded floors at dps {TG['dps']}: {'yes' if fl_eq else 'NO'}" if at_rec else (f" (the recorded floors are the side {TG['engine']['detour_sign']:+d} run's; not compared on side {side:+d})" if dps == TG["dps"] else f" (the recorded floors are at dps {TG['dps']}; not compared at dps {dps})")) + "; bar {0:g}: ".format(bar)
        + ("PASS" if not [x for x in below if x[1] <= 0] and not any(("eps^0" in f or "floors" in f) for f in fails) else "FAIL: " + "; ".join([f"{list(m)}|eps^{K} {d:.2f} d below the bar" for (m, K, d) in below if K <= 0] + [f for f in fails if ("eps^0" in f or "floors" in f)])),
        f"carried (the three p34^2-independent masters, {len(car)} pairs, reported beside, never the floor): worst {wc:.2f} d; eps_order-5 seed vs reference strings byte-identical {same_n}/{len(car)} (eps^1 {same_1}/{sum(1 for r in rows if r['kind'] == 'carried' and r['order'] == 1)}; recorded {TG['carried_seed_vs_reference_strings_byte_identical']})",
    ]
    return {"rows": rows, "n_transported": len(tr), "n_carried": len(car), "worst_transported": round(min(d for (_, _, d) in tr), 2), "eps1_worst": round(w1, 2), "eps1_member": m1, "n_eps1": len(e1),
            "recorded_eps1_worst": R1["worst_agree_d"], "eps0_worst": round(w0, 2), "eps0_member": m0, "n_eps0": len(e0), "recorded_eps0_worst": R0["worst_agree_d"],
            "per_order_floor_with_member_transported": ft, "per_order_floor_with_member_carried": fc, "floors_equal_recorded": fl_eq, "carried_worst": round(wc, 2),
            "carried_seed_vs_reference_strings_byte_identical": f"{same_n}/{len(car)}", "below_bar": [{"master": list(m), "order": K, "agree_d": round(d, 2)} for (m, K, d) in below],
            "bar": bar, "lines": lines, "fails": fails}


def eps1_cross_eps_order(L, E, bar):
    """the cross-eps-order check: the eps_order-5 files vs the eps_order-4 files of record at the same point, on the common orders
    eps^-2..eps^0 (the eps^1 order exists in the eps_order-5 file only: not compared, named), by the pair rule; the worst with
    its member per point vs the block; a structural mismatch, a component below the bar or a recomputed worst more than 0.05 d
    from the recorded FAILs by name."""
    X = E["cross_eps_order"]
    ldir = os.path.dirname(L["files"]["seed"])
    out, fails, parts = {}, [], []
    for pt, e5, e4 in (("seed_point", E["amflow"]["seed"]["file"], os.path.basename(L["files"]["seed"])), ("reference_point", E["amflow"]["reference"]["file"], os.path.basename(L["files"]["reference"]))):
        A4, A5 = amf_table(os.path.join(VENDOR, ldir, e4)), amf_table(os.path.join(VENDOR, ldir, e5))
        b = eps1_pair_block(A4, A5, e4, e5, bar)
        RX = X[pt]
        nm = {"seed_point": "seed", "reference_point": "reference"}[pt]
        if b["structural_mismatch"]:
            fails.append(f"cross-eps-order {nm}: structural mismatch on " + ", ".join(f"{x['master']}|eps^{x['order']} {x['component']}" for x in b["structural_mismatch"]))
        if b["below_bar"]:
            fails.append(f"cross-eps-order {nm}: below the bar {bar:g} on " + ", ".join(f"{x['master']}|eps^{x['order']} {x['component']} {x['agree_d']} d" for x in b["below_bar"]))
        if b["n_counted"] != RX["n_components_counted"] or b["n_zero_excluded"] != RX["n_numerical_zero_excluded"]:
            fails.append(f"cross-eps-order {nm}: {b['n_counted']} counted / {b['n_zero_excluded']} zeros vs {RX['n_components_counted']} / {RX['n_numerical_zero_excluded']} recorded")
        if b["worst"] is None or abs(b["worst"] - RX["worst_agree_d"]) > 0.05:
            fails.append(f"cross-eps-order {nm}: recomputed worst {b['worst']} d vs recorded {RX['worst_agree_d']} d differ by more than 0.05 d")
        wm = b["worst_member"]
        parts.append(f"{nm} {b['worst']:.2f} d worst (member {wm['master']}|eps^{wm['order']} {wm['component']}, floor {b['floor']}; recorded {RX['worst_agree_d']} d) over {b['n_counted']} components ({b['n_zero_excluded']} numerical zeros excluded)")
        out[pt] = b
    line = (f"cross-eps-order (the eps_order-5 files vs the eps_order-4 files of record at the same point on eps^-2..eps^0; the eps^1 order exists in the eps_order-5 file only, not compared): "
            + "; ".join(parts) + f"; structural mismatches {sum(len(out[k]['structural_mismatch']) for k in out)}; bar {bar:g}: " + ("PASS" if not fails else "FAIL: " + "; ".join(fails)))
    return {"seed_point": out["seed_point"], "reference_point": out["reference_point"], "worst_seed": out["seed_point"]["worst"], "worst_reference": out["reference_point"]["worst"], "line": line, "fails": fails, "n_fail": len(fails)}


def eps1_twin_certificate(L, E, bar):
    """the seed's two-precision certificate at eps_order 5: the pinned goal-40 seed file vs its goal-60 twin (both named by the
    record's eps1 block, both pinned; the twin's sha256 asserted against the block) over the four common orders eps^-2..eps^1 by
    the pair rule (the 27 imaginary parts numerical zeros, excluded); the worst with its member and the eps^1 order's worst over
    the nine masters vs the block; FAIL by name below the bar, on a structural mismatch, on a count that differs, or when a
    recomputed worst differs from the recorded by more than 0.05 d."""
    T = E["amflow"]["seed_goal60_twin"]; tp = T["two_precision"]
    ldir = os.path.dirname(L["files"]["seed"])
    twin_rel = os.path.join(ldir, T["file"])
    got = sha256_file(os.path.join(VENDOR, twin_rel))
    if got != T["sha256"]:
        die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: the eps_order-5 twin {twin_rel} hashes to {got} but the record block eps1.amflow.seed_goal60_twin records {T['sha256']}; not serving")
    S, W = amf_table(os.path.join(VENDOR, ldir, E["amflow"]["seed"]["file"])), amf_table(os.path.join(VENDOR, twin_rel))
    if list(S) != list(W):
        die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: the twin {twin_rel} lists the masters differently from the seed file; not serving")
    b = eps1_pair_block(S, W, E["amflow"]["seed"]["file"], T["file"], bar)
    fails = []
    if b["structural_mismatch"]:
        fails.append("twin: structural mismatch on " + ", ".join(f"{x['master']}|eps^{x['order']} {x['component']}" for x in b["structural_mismatch"]))
    if b["below_bar"]:
        fails.append(f"twin: below the bar {bar:g} on " + ", ".join(f"{x['master']}|eps^{x['order']} {x['component']} {x['agree_d']} d" for x in b["below_bar"]))
    if b["n_counted"] != tp["n_components_counted"]:
        fails.append(f"twin: {b['n_counted']} components counted vs {tp['n_components_counted']} recorded")
    if b["worst"] is None or abs(b["worst"] - tp["worst_agree_d"]) > 0.05:
        fails.append(f"twin: recomputed worst {b['worst']} d vs recorded {tp['worst_agree_d']} d differ by more than 0.05 d")
    p1 = b["per_order"].get("1")
    if p1 is None or abs(p1["min"] - tp["eps1"]["min"]) > 0.05 or p1["n"] != tp["eps1"]["n"]:
        fails.append(f"twin: the eps^1 order's recomputed worst {None if p1 is None else p1['min']} d over {None if p1 is None else p1['n']} vs recorded {tp['eps1']['min']} d over {tp['eps1']['n']}")
    wm = b["worst_member"]
    line = (f"seed two-precision certificate at eps_order 5 (goal 40 {E['amflow']['seed']['file']} vs goal 60 {T['file']}, the same point p34^2 = {L['seed_point']['p34sq']}): worst {b['worst']:.2f} d "
            f"(member {wm['master']}|eps^{wm['order']} {wm['component']}) over {b['n_counted']} nonzero (master, eps-order) components ({b['n_zero_excluded']} numerical zeros excluded; recorded {tp['worst_agree_d']} d, floor {tp['digits_demonstrated_floor']}), "
            f"the eps^1 order {p1['min'] if p1 else None} d worst over {p1['n'] if p1 else 0} masters (member {p1['member']['master'] if p1 else None} {p1['member']['component'] if p1 else ''}; recorded {tp['eps1']['min']} d), bar {bar:g}: "
            + ("PASS" if not fails else "FAIL: " + "; ".join(fails)) + f"; the reference point p34^2 = {L['reference_point']['p34sq']} has no goal-60 twin (not shipped)")
    return {"twin_file": T["file"], "twin_sha256": got, "n_counted": b["n_counted"], "n_zero_excluded": b["n_zero_excluded"], "worst": b["worst"], "worst_member": wm, "per_order": b["per_order"],
            "eps1": p1, "recorded": {"worst_agree_d": tp["worst_agree_d"], "digits_demonstrated_floor": tp["digits_demonstrated_floor"], "n_components_counted": tp["n_components_counted"], "eps1": tp["eps1"]},
            "components": b["components"], "bar": bar, "line": line, "fails": fails, "n_fail": len(fails)}


def evaluate_line(line, lines, dps, side, workdir, mutate=False, quiet_rows=False, mutate_slice=False, kmax=0):
    L = lines["lines"][line]
    rec = json.load(open(os.path.join(VENDOR, L["files"]["record"])))
    E = rec["eps1"] if kmax else None
    e5files = {"seed": E["amflow"]["seed"]["file"], "reference": E["amflow"]["reference"]["file"]} if kmax else None
    yind = set(tuple(m) for m in rec["y_independent_masters"]["masters"])
    bar, bar_dps, rec_dps = bar_for(rec, dps)
    print(f"\n[line] {L['label']}: {L['kinematics_fixed']['p12sq']} = p12^2 fixed, p56^2 = {L['kinematics_fixed']['p56sq']}, m^2 = {L['kinematics_fixed']['msq']}; "
          f"transport along p34^2 from {L['seed_point']['p34sq']} (the seed point) to {L['reference_point']['p34sq']} (the target, independent AMFlow reference)")
    print(f"  path: {L['path']['form'][:200]}{'...' if len(L['path']['form']) > 200 else ''}")
    if kmax:
        TG, TW = E["transport_gate"], E["amflow"]["seed_goal60_twin"]["two_precision"]
        bar, bar_dps = TG["bar"], TG["dps"]
        print(f"  record (the eps^1 tier): eps^1 worst {TG['eps1']['worst_agree_d']} d over {TG['eps1']['n_pairs']} transported pairs (member {TG['eps1']['member']}), the eps^0 rows {TG['eps0_rows']['worst_agree_d']} d over "
              f"{TG['eps0_rows']['n_pairs']} (the eps_order-4 record {TG['eps0_rows']['eps_order_4_record']['worst_agree_d']} d), the twin {TW['worst_agree_d']} d over {TW['n_components_counted']} components, at dps {TG['dps']}; "
              f"this run dps {dps} -> bar {bar:g} on every transported (master, eps-order) pair (the two-precision bar; the carried three masters reported beside)")
        print(f"  [eps^1 tier] the eps_order-5 files: seed {e5files['seed']} (goal {E['amflow']['seed']['goal_digits']}; twin {E['amflow']['seed_goal60_twin']['file']} at goal {E['amflow']['seed_goal60_twin']['goal_digits']}), "
              f"reference {e5files['reference']} (goal {E['amflow']['reference']['goal_digits']}); the transport at --kmax {kmax} carries eps^-2..eps^{kmax} ({TG['n_state']} state components) on the same connection")
    else:
        print(f"  record: worst {L['claimed']['worst_agree_d']} d over {L['claimed']['pairs']} pairs at dps {L['claimed']['dps']}; record precisions {rec_dps}; "
              f"this run dps {dps} -> bar {bar} (= floor of the record's worst at dps {bar_dps}{'' if bar_dps == dps else ', the highest record precision not above ' + str(dps)})")
    seed_override = None
    planted = None
    if mutate:
        top = [1, 1, 1, 1, 0, 0, 0]
        seed_override = os.path.join(workdir, f"seed_mutated_line{line}{'_kmax1' if kmax else ''}.json")
        seed_src = os.path.join(os.path.dirname(L["files"]["seed"]), e5files["seed"]) if kmax else L["files"]["seed"]
        planted = mutate_seed(os.path.join(VENDOR, seed_src), seed_override, top)
        print(f"  [MUTATION CONTROL] the seed value of master {top} at eps^0 has its decimal digit {planted[2] - 1} changed '{planted[0]}' -> '{planted[1]}' "
              f"(a ~1e-15 relative change in one seed{' of ' + os.path.basename(seed_src) if kmax else ''}); expected: the gate FAILS by name")
    g, gpath, wall = run_engine(line, L, dps, side, workdir, seed_override, "_mutated" if mutate else "", kmax=kmax, files=e5files)
    rows = g["gate"]["rows"]
    fails = []
    e1 = None
    if kmax:
        e1 = eps1_gate(L, E, g, dps, bar, side)
        rows = e1["rows"]
        print(f"  {'master':>22} {'eps^k':>5} {'transported (30 d)':>36} {'reference (30 d)':>34} {'digits':>7}  vs bar {bar:g} (digits = the metric of record recomputed at dps 250 on the value strings)")
        for r in rows:
            car = r["kind"] == "carried"
            ok = car or r["agree_d"] >= bar
            if not ok:
                fails.append(r)
            if not quiet_rows:
                print(f"  {str(r['master']):>22} {r['order']:>5} {r['transported']:>36} {r['gate']:>34} {r['agree_d']:>7}  {'beside' if car else ('PASS' if ok else 'FAIL')}  {'carried (reported beside)' if car else 'independent check'}")
        worst = e1["worst_transported"]
        n_ind = e1["n_transported"]
        worst_ind = worst
    else:
        print(f"  {'master':>22} {'eps^k':>5} {'transported (30 d)':>36} {'reference (30 d)':>34} {'digits':>7}  vs bar {bar}")
        for r in rows:
            m = tuple(r["master"])
            lab = "y-independent (slice-gated)" if m in yind else "independent check"
            ok = r["agree_d"] >= bar
            if not ok:
                fails.append(r)
            if not quiet_rows:
                print(f"  {str(r['master']):>22} {r['order']:>5} {r['transported']:>36} {r['gate']:>34} {r['agree_d']:>7}  {'PASS' if ok else 'FAIL'}  {lab}")
        worst = g["gate"]["worst_agree_d"]
        n_ind = sum(1 for r in rows if tuple(r["master"]) not in yind)
        worst_ind = min(r["agree_d"] for r in rows if tuple(r["master"]) not in yind)
    on_seg = sum(1 for v in g["roots_nearest_to_path"] if v < 1e-6)
    print(f"  transport: {g['nstep']} steps, order {g['order']}, {g['n_state']} state components, {g['n_entries']} couplings, {g['n_roots']} denominator roots; "
          f"six smallest root distances to the real segment {['%.4g' % v for v in g['roots_nearest_to_path']]}"
          + (f" ({on_seg} of them 0: the singular point on the segment, seen through several denominators; the contour keeps a distance >= its depth {L['path']['detour']} from it)" if on_seg else "")
          + f"; tail bound {g['tail_bound_total']:.3g}; engine wall {g['wall_s']} s (subprocess {wall} s)")
    if kmax:
        print(f"  worst agreement {worst} d over the {n_ind} transported pairs of the six p34^2-dependent masters (eps^-2..eps^{kmax}); bar {bar:g}: "
              f"{'PASS' if not fails else 'FAIL on ' + str(len(fails)) + ' pair(s): ' + ', '.join(str(r['master']) + '|eps^' + str(r['order']) + ' ' + str(r['agree_d']) + ' d' for r in fails)}")
        for ln in e1["lines"]:
            print("  " + ln)
    else:
        print(f"  worst agreement {worst} d over {g['gate']['n_compared']} pairs; over the {n_ind} pairs of the six p34^2-dependent masters {worst_ind} d; bar {bar}: "
              f"{'PASS' if not fails else 'FAIL on ' + str(len(fails)) + ' pair(s): ' + ', '.join(str(r['master']) + '|eps^' + str(r['order']) + ' ' + str(r['agree_d']) + ' d' for r in fails)}")
    sg = slice_gate(L, rec, mutate_slice)
    if sg["mutation"]:
        pl = sg["mutation"]
        print(f"  [SLICE MUTATION CONTROL] the seed string of master {pl['master']} at eps^{pl['order']} has its decimal digit {pl['digit']} changed '{pl['old']}' -> '{pl['new']}' "
              f"(char {pl['position']} of the midpoint string; ~1e-15 relative) in the copy the slice gate reads -- the transport ran on the pinned files, its rows unchanged; expected: the slice gate FAILS by name")
    print(f"  slice gate (the six p34^2-independent pairs, carried, not transported): vs the on-slice records {sg['worst_vs_onslice_records']:.2f} d worst, "
          f"vs the closed forms {sg['worst_vs_closed_forms']:.2f} d worst over {sg['n_pairs']} pairs ({sg['n_with_closed_form']} of them with a closed form on the record; "
          f"the p56^2 bubble x tadpole has none, its x = -1 string is its reference); bar {sg['bar']}: "
          + ("PASS" if not sg["fails"] else "FAIL on " + str(len(sg["fails"])) + " (pair, reference) row(s): "
             + ", ".join(f"{f['master']}|eps^{f['order']} {f['agree_d']} d vs {f['reference']}" for f in sg["fails"])))
    cert = seed_twin_certificate(L, rec)
    print("  " + cert["line"])
    xo = tw5 = None
    if kmax:
        xo = eps1_cross_eps_order(L, E, bar)
        print("  " + xo["line"])
        tw5 = eps1_twin_certificate(L, E, bar)
        print("  " + tw5["line"])
    print(f"  note: {rec['y_independent_masters']['note'][:260]}...")
    vs = None
    if kmax:
        TGE = E["transport_gate"]["engine"]
        rkey = None
        if dps == TGE["dps"] and side == TGE["detour_sign"]:
            rkey, RB = "eps1", TGE
        elif dps == TGE["dps"] and f"side_{side}" in E["transport_gate"]:
            rkey, RB = f"eps1 side_{side}", E["transport_gate"][f"side_{side}"]
        if rkey and not mutate:
            R = dict(RB, worst_agree_d=RB["worst_agree_d"], engine_wall_s=RB["engine_wall_s"])
            if "side_" in rkey:
                print(f"  (the record block compared below is the side {side:+d} run of the eps^1 tier, {rkey})")
            same30 = sum(1 for a, b in zip(rows, R["rows"]) if a["master"] == b["master"] and a["order"] == b["order"] and a["transported"] == b["transported"])
            same_ref = sum(1 for a, b in zip(rows, R["rows"]) if a["gate"] == b["reference"])
            keys = list(R["values"].keys())
            samev = sum(1 for k in keys if g["values"].get(k) == R["values"][k])
            maxd = 0.0
            for k in keys:
                ref_str = next(b["reference"] for b in R["rows"] if f"{tuple(b['master'])}|{b['order']}" == k)
                dd = agree_digits(g["values"][k], R["values"][k], ref_str)
                maxd = max(maxd, 10 ** (-dd) if dd != float("inf") else 0.0)
            counts_equal = (g["nstep"], g["order"], g["n_roots"], g["n_state"], g["n_entries"]) == (R["nstep"], R["order"], R["n_roots"], R["n_state"], R["n_entries"])
            vs = {"record_block": rkey, "record_dps": dps, "transported_30d_strings_identical": same30, "reference_30d_strings_identical": same_ref, "of": len(rows),
                  "value_strings_identical": samev, "of_values": len(keys), "max_relative_difference_vs_record_values": maxd,
                  "record_worst": R["worst_agree_d"], "this_worst": g["gate"]["worst_agree_d"], "counts_equal": counts_equal, "record_engine_wall_s": R["engine_wall_s"]}
            print(f"  vs the record (the eps^1 tier at dps {dps}{'' if 'side_' not in rkey else ', side ' + str(side)}): transported 30-digit strings identical {same30}/{len(rows)}; reference strings identical {same_ref}/{len(rows)}; "
                  f"{dps + 5}-digit value strings identical {samev}/{len(keys)} (max relative difference {maxd:.2e}); step/order/root counts equal: {counts_equal}; "
                  f"record worst {R['worst_agree_d']} d vs this run {g['gate']['worst_agree_d']} d; record engine wall {R['engine_wall_s']} s")
            if not counts_equal or same30 != len(rows) or same_ref != len(rows):
                e1["fails"].append(f"vs the record: transported strings identical {same30}/{len(rows)}, reference strings identical {same_ref}/{len(rows)}, counts equal {counts_equal}")
        rkey = None
    else:
        rkey = str(dps) if (str(dps) in rec["gates"] and rec["gates"][str(dps)]["detour_sign"] == side) else f"{dps}_side{side}"
    if rkey in rec["gates"] and not mutate:
        R = rec["gates"][rkey]
        if rkey != str(dps):
            print(f"  (the record block compared below is the side {side:+d} run of the record, {rkey})")
        same30 = sum(1 for a, b in zip(rows, R["rows"]) if a["master"] == b["master"] and a["order"] == b["order"] and a["transported"] == b["transported"])
        same_ref = sum(1 for a, b in zip(rows, R["rows"]) if a["gate"] == b["reference"])
        keys = list(R["values"].keys())
        samev = sum(1 for k in keys if g["values"].get(k) == R["values"][k])
        maxd = 0.0
        for k in keys:
            ref_str = next(b["reference"] for b in R["rows"] if f"{tuple(b['master'])}|{b['order']}" == k)
            dd = agree_digits(g["values"][k], R["values"][k], ref_str)
            maxd = max(maxd, 10 ** (-dd) if dd != float("inf") else 0.0)
        counts_equal = (g["nstep"], g["order"], g["n_roots"], g["n_state"], g["n_entries"]) == (R["nstep"], R["order"], R["n_roots"], R["n_state"], R["n_entries"])
        vs = {"record_block": rkey, "record_dps": dps, "transported_30d_strings_identical": same30, "reference_30d_strings_identical": same_ref, "of": len(rows),
              "value_strings_identical": samev, "of_values": len(keys), "max_relative_difference_vs_record_values": maxd,
              "record_worst": R["worst_agree_d"], "this_worst": worst, "counts_equal": counts_equal,
              "record_engine_wall_s": R["engine_wall_s"]}
        print(f"  vs the record at dps {dps}{'' if rkey == str(dps) else ' (side ' + str(side) + ')'}: transported 30-digit strings identical {same30}/{len(rows)}; reference strings identical {same_ref}/{len(rows)}; "
              f"{dps + 5}-digit value strings identical {samev}/{len(keys)} (max relative difference {maxd:.2e}); step/order/root counts equal: {counts_equal}; "
              f"record worst {R['worst_agree_d']} d vs this run {worst} d; record engine wall {R['engine_wall_s']} s")
    return {"line": line, "label": L["label"], "dps": dps, "side": side, "bar": bar, "bar_dps": bar_dps, "worst": worst, "worst_independent": worst_ind,
            "n_pairs": len(rows), "n_fail": len(fails), "fails": [{"master": r["master"], "order": r["order"], "agree_d": r["agree_d"]} for r in fails],
            "rows": rows, "engine": {"receipt": os.path.basename(gpath), "sha256": sha256_file(gpath), "nstep": g["nstep"], "order": g["order"], "n_roots": g["n_roots"],
                                     "tail_bound_total": g["tail_bound_total"], "wall_s": g["wall_s"], "subprocess_wall_s": wall, "stamp_utc": g["stamp_utc"]},
            "values": g["values"], "vs_record": vs, "mutation": planted, "slice_gate": sg, "seed_certificate": cert, "kmax": kmax,
            "eps1": ({k: v for k, v in e1.items() if k != "rows"} | {"cross_eps_order": xo, "twin_certificate": tw5, "n_fail": len(e1["fails"]) + xo["n_fail"] + tw5["n_fail"]}) if kmax else None}


def two_precision(line, lines, dps, side, workdir, r1, kmax=0):
    """the record's own two-precision form: the same transport at dps + 30; per pair the agreement of the two transported values
    (with --kmax 1: the 27 transported values of the eps^1 tier)."""
    L = lines["lines"][line]
    rec = json.load(open(os.path.join(VENDOR, L["files"]["record"])))
    dps2 = dps + 30
    print(f"\n[check] {L['label']}: the two-precision pair (dps {dps}, dps {dps2}) -- the record's own form (30, 60){' -- the eps^1 tier' if kmax else ''}")
    r2 = evaluate_line(line, lines, dps2, side, workdir, quiet_rows=True, kmax=kmax)
    refs = {f"{tuple(r['master'])}|{r['order']}": r["gate"] for r in r2["rows"]}
    worst = None
    pair = []
    for k, v1 in r1["values"].items():
        v2 = r2["values"][k]
        d = agree_digits(v1, v2, refs[k])
        pair.append({"pair": k, "digits": d})
        if worst is None or d < worst:
            worst = d
    bar = r1["bar"]
    ok = worst >= bar
    print(f"  two-precision agreement (dps {dps} vs {dps2}) per pair: " + "; ".join(f"{p['pair']} {p['digits']:.2f}" for p in pair))
    print(f"  two-precision worst {worst:.2f} d over {len(pair)} pairs vs bar {bar} (the dps-{dps} bar): {'PASS' if ok else 'FAIL'}; the dps-{dps2} run's own worst vs the reference {r2['worst']} d (bar {r2['bar']})")
    return {"dps_pair": [dps, dps2], "worst_pair_digits": worst, "bar": bar, "pass": ok and r2["n_fail"] == 0 and r2["slice_gate"]["n_fail"] == 0 and r2["seed_certificate"]["n_fail"] == 0 and (r2["eps1"] is None or r2["eps1"]["n_fail"] == 0), "pairs": pair, "deeper_run": {k: v for k, v in r2.items() if k not in ("rows", "values")}}


LAND = os.path.join(VENDOR, "land")
LAND_DIR = {"-3": "line_m3", "-2": "line_m2"}
LAND_BAR = 30.0          # the landing's bar on every (master, order, reference) pair and on the certificates (10^-30): the two-precision bar of record
LAND_REC_DPS = 60        # the precision of the landing of record


def land_record(line):
    """the landing of record of the line (land/line_m*/landed_record.json, pinned): the dps-60 / 45 / 30 landings, the 45/60 pair, leg B."""
    return json.load(open(os.path.join(LAND, LAND_DIR[line], "landed_record.json")))


def run_land(line, dps, workdir, tag="", second_radius=False, certificate=False, tools=None, legB=None):
    """drive the vendored landing engine land/land_fixed_eps.py with the command line of record (--line, --dps; rho 1/16 and 64
    nodes its defaults; --second-radius / --certificate the pilot form; legB = the leg-A LANDING path for the fixed-eps leg) and
    return (the receipt json, its path, the engine rc, wall).  rc 0 PASS / 1 FAIL are results (the receipt exists); any other rc
    or a missing receipt is RC_ENGINE by name."""
    if legB:
        out = os.path.join(workdir, f"LANDING_B_line{line}_dps{dps}{tag}.json")
        cmd = [sys.executable, os.path.join(LAND, "land_fixed_eps.py"), "--line", line, "--fixed-eps-leg", "--dps", str(dps), "--kmax-frob", "40", "--eps0", "1/134217728", "--landing", legB, "--out", out]
        shown = f"land_fixed_eps.py --line {line} --fixed-eps-leg --dps {dps} --kmax-frob 40 --eps0 1/134217728 --landing {os.path.basename(legB)} --out {os.path.basename(out)}"
    else:
        out = os.path.join(workdir, f"LANDING_A_line{line}_dps{dps}{tag}.json")
        cmd = [sys.executable, os.path.join(LAND, "land_fixed_eps.py"), "--line", line, "--dps", str(dps), "--out", out]
        shown = f"land_fixed_eps.py --line {line} --dps {dps} --out {os.path.basename(out)}"
        if second_radius:
            cmd.append("--second-radius"); shown += " --second-radius"
        if certificate:
            cmd.append("--certificate"); shown += " --certificate"
    if tools:
        cmd += ["--tools", tools]; shown += " --tools DIR"
    print(f"  [land] {shown}", flush=True)
    env = dict(os.environ)
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    t0 = time.time()
    last = ""
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=workdir, env=env)
    for ln in p.stdout:
        ln = ln.rstrip("\n")
        last = ln
        if ln.startswith("[progress]"):
            continue
        print(f"  [land] {ln}", flush=True)
    rc = p.wait()
    wall = time.time() - t0
    if rc not in (0, 1) or not os.path.exists(out):
        die(RC_ENGINE, f"icc-offslice-evaluate LANDING ENGINE did not finish on the p12^2 = {line} line at dps {dps}: rc {rc}; last line: {last!r}")
    return json.load(open(out)), out, rc, round(wall, 1)


def land_member(r):
    return f"{r['slice_master']} eps^{r['order']} vs {r['reference']}"


def land_vs_record(g, RB, dps):
    """the landed strings of this run vs the landing of record (dps 60) component-wise: agree_d = log10(max(|a|,|b|)/|a-b|) on the
    real parts, capped by min(dps, 60) + 5; a component zero at working precision on both sides (the third-relation master K) is
    excluded by name; the bar min(dps, 60) - 10 (identical strings expected at dps 60)."""
    from mpmath import mp, mpf, fabs, log10
    VA, VB = g["landed_gauged_vector_at_y_eq_x"], RB["landed_gauged_vector_at_y_eq_x"]
    lo = min(dps, RB["dps"])
    cap = lo + 5
    bar = lo - 10
    rows, zeros, same = [], [], 0
    with mp.workdps(200):
        norm = max(fabs(mpf(v["re"])) for v in VA.values())
        for k in VA:
            if k not in VB:
                die(RC_REFUSED, f"icc-offslice-evaluate REFUSED: the landed component {k} has no counterpart in the landing of record; not serving")
            a, b = mpf(VA[k]["re"]), mpf(VB[k]["re"])
            if max(fabs(a), fabs(b)) < norm * mpf(10) ** (-lo):
                zeros.append(k); continue
            if VA[k]["re"] == VB[k]["re"]:
                same += 1
            d = fabs(a - b)
            dg = float(cap) if d == 0 else min(float(log10(max(fabs(a), fabs(b)) / d)), float(cap))
            rows.append((k, round(dg, 2)))
    worst = min(rows, key=lambda r: r[1]) if rows else None
    below = [r for r in rows if r[1] < bar]
    return {"n": len(rows), "identical": same, "worst": worst, "cap": cap, "bar": bar, "below": below, "zeros_excluded": zeros, "rows": rows}


def land_print_landing(g, R, line, dps, certificate, tools):
    """print the landing's certificates, floors with members, the excluded classes and the count line; return the fails by name."""
    RB = R["landing_dps60"]
    C, RC = g["comparison"], RB["comparison"]
    x = g["x"]
    fails = []
    cert = g["certificates"]
    cbar = 10.0 ** (-LAND_BAR)
    cert_ok = cert["monodromy_rel"] < cbar and cert["residue_rel"] < cbar and cert["imag_rel"] < cbar
    if not cert_ok:
        fails.append(f"a certificate above the bar 1e-{LAND_BAR:g}: closed-loop return {cert['monodromy_rel']:.1e}, residue {cert['residue_rel']:.1e}, imaginary part {cert['imag_rel']:.1e}")
    print(f"  certificates (each a relative figure vs the bar 1e-{LAND_BAR:g}): closed-loop return {cert['monodromy_rel']:.1e}, residue {cert['residue_rel']:.1e}, imaginary part {cert['imag_rel']:.1e} "
          f"(recorded at dps 60: {RB['certificates']['monodromy_rel']:.0e} / {RB['certificates']['residue_rel']:.0e} / {RB['certificates']['imag_rel']:.0e}): {'PASS' if cert_ok else 'FAIL'}; "
          f"steps {g['steps']['approach']} + {g['steps']['circle']} (recorded {RB['steps']['approach']} + {RB['steps']['circle']}), order {g['order']}, rho {g['rho']}, {g['nodes']} nodes, next singular point at {g['R_next_singular_point']} (alias bound {g['alias_bound_(rho_over_R)^N']:.1e}), "
          f"tail bounds {g['tail_bound_total']['approach']:.1e} / {g['tail_bound_total']['circle']:.1e}, engine wall {g['wall_s']['total']} s")
    sr = cert.get("second_radius")
    if sr:
        P30 = R.get("pilot_dps30", {}).get("certificates", {}).get("second_radius") or {}
        print(f"  second radius {sr['rho']}: two-radius agreement {sr['two_radius_agree_d_worst']:.2f} d over the landed components, its loop return {sr['monodromy_rel']:.1e}, {sr['steps']} steps, {sr['wall_s']} s"
              + (f" (recorded at dps 30: {P30['two_radius_agree_d_worst']:.2f} d, loop return {P30['monodromy_rel']:.0e})" if P30 else ""))
    fc = g.get("frobenius_certificate_rederived")
    F30 = R.get("pilot_dps30", {}).get("frobenius_certificate_rederived")
    if fc:
        print(f"  Frobenius certificate re-derived here on the exported system (eps0 {fc['eps0']}, dps {fc['dps']}, kmax {fc['kmax']}): indicials {fc['indicial_integer_multiset']}, log_max {fc['log_max']}, sheared {fc['sheared']} ({fc['n_shears']} shears), {fc['wall_s']} s -> {fc['verdict']}"
              + (f"; of record: {F30['indicial_integer_multiset']} log_max {F30['log_max']}" if F30 else ""))
    elif F30:
        print(f"  Frobenius certificate of record (not re-derived here: --certificate needs the detransport package, --tools DIR): indicials {F30['indicial_integer_multiset']}, log_max {F30['log_max']}, sheared {F30['sheared']} ({F30['n_shears']} shears) -> {F30['verdict']}")
    po = C["per_order_floor_with_member"]
    print("  per order (floor with member): " + "; ".join(f"eps^{k}: {po[k]['min']} d ({po[k]['member']['master']} vs {po[k]['member']['reference']}, n {po[k]['n']}, max {po[k]['max']})" for k in sorted(po, key=int)))
    pr = C["per_reference_floor_with_member"]
    print("  per reference (floor with member): " + "; ".join(f"{lab}: {pr[lab]['min']} d ({pr[lab]['member']['master']} eps^{pr[lab]['member']['order']}, n {pr[lab]['n']})" for lab in pr))
    sz = C["structural_zeros_excluded"]; ex = C["excluded_masters_no_slice_record"]
    print(f"  structural zeros excluded by name ({len(sz)}): " + ", ".join(f"{z['master']} eps^{z['order']}" for z in sz) + f"; masters with no slice record ({len(ex)}): " + ", ".join(f"{e['master']} = {e['meaning']}" for e in ex)
          + f"; identical strings {C['identical_strings']}; slice references: " + ", ".join(f"{lab} ({v['n_values']} values, {v['sha256'][:16]})" for lab, v in g["slice_references"].items())
          + (f"; MISSING references: {g['slice_references_missing']}" if g.get("slice_references_missing") else ""))
    if g.get("slice_references_missing"):
        fails.append(f"slice references missing: {g['slice_references_missing']}")
    W = C["worst"]; RW = RC["worst"]
    if W is None:
        die(RC_ENGINE, "icc-offslice-evaluate LANDING: no comparison rows")
    floor = int(W["agree_d"] // 1)
    below = C["fails_by_name"]
    for r in below:
        fails.append(f"{land_member(r)}: {r['agree_d']} d < bar {C['bar']:g}")
    print(f"  the p12^2 = {line} line lands onto the slice at p34^2 = p12^2 = {x} to {floor} digits at dps {dps} (worst {W['agree_d']} d = master {W['slice_master']} eps^{W['order']} vs {W['reference']}, cap {W['cap_d']}; "
          f"{C['n_rows']} (master, order, reference) pairs); the count of record {R['count_of_record']['floor']} (dps 60: worst {RW['agree_d']} d = master {RW['slice_master']} eps^{RW['order']} vs {RW['reference']}); bar {C['bar']:g}: "
          + ("PASS" if not below else "FAIL on " + str(len(below)) + " pair(s): " + "; ".join(f"{land_member(r)} {r['agree_d']} d" for r in below)))
    return fails, floor


def land_print_record(g, RB, dps):
    """the landed strings vs the landing of record; at the record precision the recorded worst within 0.05 d and the per-order floors equal."""
    V = land_vs_record(g, RB, dps)
    fails = []
    w = V["worst"]
    at_rec = dps == RB["dps"]
    extra = ""
    if at_rec:
        C, RC = g["comparison"], RB["comparison"]
        dw = abs(C["worst"]["agree_d"] - RC["worst"]["agree_d"])
        po, rpo = C["per_order_floor_with_member"], RC["per_order_floor_with_member"]
        fl_eq = sorted(po) == sorted(rpo) and all(abs(po[k]["min"] - rpo[k]["min"]) <= 0.05 and po[k]["n"] == rpo[k]["n"] and po[k]["member"] == rpo[k]["member"] for k in rpo)   # within 0.05 d: this run compares its landed values in memory, the record compared its printed 65-digit strings
        extra = f"; the recorded worst {RC['worst']['agree_d']} d vs this run {C['worst']['agree_d']} d within 0.05 d: {'yes' if dw <= 0.05 else 'NO'}; the per-order floors == the recorded: {'yes' if fl_eq else 'NO'}; identical strings {V['identical']}/{V['n']}"
        if dw > 0.05:
            fails.append(f"vs the record: the recomputed worst {C['worst']['agree_d']} d differs from the recorded {RC['worst']['agree_d']} d by more than 0.05 d")
        if not fl_eq:
            fails.append(f"vs the record: the per-order floors {json.dumps(po)} differ from the recorded {json.dumps(rpo)}")
    for k, d in V["below"]:
        fails.append(f"vs the record: landed component {k} agrees with the record's string to {d} d < bar {V['bar']}")
    print(f"  vs the landing of record (dps {RB['dps']}, {RB['n_state']} landed components): {V['n']} compared, worst {w[1] if w else None} d ({w[0] if w else None}; cap {V['cap']}), "
          f"{len(V['zeros_excluded'])} zero at working precision on both sides excluded ({', '.join(V['zeros_excluded'])}); bar {V['bar']} (min(dps, 60) - 10): "
          + ("PASS" if not V["below"] else "FAIL on " + ", ".join(f"{k} {d} d" for k, d in V["below"])) + extra)
    return fails, V


def land_mutate(g, gpath, workdir, line):
    """the landed-value control: one digit of one landed value (the top master [1, 1, 1, 1, 0, 0, 0] at eps^0, its 15th decimal)
    changed in the copy of this run's receipt, the slice comparison re-run on it by land/recompare_landing.py: it must FAIL by name."""
    key = "[1, 1, 1, 1, 0, 0, 0]|0"
    M = json.loads(json.dumps(g))
    s = M["landed_gauged_vector_at_y_eq_x"][key]["re"]
    i = s.index(".") + 15
    new = s[:i] + str((int(s[i]) + 1) % 10) + s[i + 1:]
    M["landed_gauged_vector_at_y_eq_x"][key]["re"] = new
    mp_ = os.path.join(workdir, os.path.basename(gpath)[:-5] + "_mutated.json")
    with open(mp_, "w") as f:
        json.dump(M, f, indent=1)
    print(f"  [LANDED-VALUE MUTATION CONTROL] the landed value of master {key.split('|')[0]} at eps^0 has its decimal digit 15 changed '{s[i]}' -> '{new[i]}' in the copy of this run's receipt (~1e-15 relative); "
          f"the slice comparison re-run on it by recompare_landing.py; expected: FAIL by name", flush=True)
    cmd = [sys.executable, os.path.join(LAND, "recompare_landing.py"), mp_]
    env = dict(os.environ); env["PYTHONDONTWRITEBYTECODE"] = "1"
    p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=workdir, env=env)
    lines = p.stdout.rstrip("\n").split("\n")
    for ln in lines:
        print(f"  [recompare] {ln}")
    caught = p.returncode == 1 and any(ln.startswith("FAIL by name") for ln in lines)
    return {"key": key, "digit": 15, "old": s[i], "new": new[i], "recompare_rc": p.returncode, "caught": caught, "lines": lines}


def land_pair(g1, p1, dps1, g2, p2, dps2, R, workdir, line):
    """the two-precision pair of landings by land/compare_pair.py (its rule: agree_d on the landed real parts capped by the lower
    precision + 5; the slice-facing components separately); vs the pair of record when (dps1, dps2) is the record's (45, 60)."""
    out = os.path.join(workdir, f"PAIR_line{line}_dps{dps1}_{dps2}.json")
    lo, hi = (p1, p2) if dps1 <= dps2 else (p2, p1)
    cmd = [sys.executable, os.path.join(LAND, "compare_pair.py"), lo, hi, out]
    env = dict(os.environ); env["PYTHONDONTWRITEBYTECODE"] = "1"
    p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=workdir, env=env)
    for ln in p.stdout.rstrip("\n").split("\n"):
        print(f"  [pair] {ln}")
    if p.returncode != 0 or not os.path.exists(out):
        die(RC_ENGINE, f"icc-offslice-evaluate PAIR did not finish: rc {p.returncode}")
    J = json.load(open(out))
    A, S = J["all_components"], J["slice_facing_components"]
    fails = []
    RP = R.get("pair_45_60")
    at_rec = sorted([dps1, dps2]) == [45, 60] and RP is not None
    if S["min"] < LAND_BAR:
        fails.append(f"the pair's slice-facing floor {S['min']} d < bar {LAND_BAR:g}")
    extra = ""
    if at_rec:
        RA, RS = RP["all_components"], RP["slice_facing_components"]
        ok = abs(A["min"] - RA["min"]) <= 0.05 and abs(S["min"] - RS["min"]) <= 0.05 and A["n"] == RA["n"] and S["n"] == RS["n"]
        extra = f"; recorded (45/60): all {RA['min']} d (n {RA['n']}), slice-facing {RS['min']} d (n {RS['n']}), identical {RP['identical_strings']}: within 0.05 d and the same counts: {'yes' if ok else 'NO'}"
        if not ok:
            fails.append(f"the pair's floors (all {A['min']}, slice-facing {S['min']}) differ from the recorded ({RA['min']}, {RS['min']}) by more than 0.05 d or in count")
    else:
        extra = "; the recorded pair is 45/60 (not compared at this pair)"
    print(f"  two-precision pair dps {dps1}/{dps2} (cap {J['cap_d']}): all components {A['min']} d (member {A['member']['master']} eps^{A['member']['order']}, n {A['n']}, max {A['max']}); "
          f"slice-facing {S['min']} d (member {S['member']['master']} eps^{S['member']['order']}, n {S['n']}, max {S['max']}); identical strings {J['identical_strings']}; "
          f"{len(J['excluded_zero'])} components zero at working precision excluded; bar {LAND_BAR:g} on the slice-facing floor: " + ("PASS" if not fails else "FAIL") + extra)
    return {"dps_pair": [dps1, dps2], "all": A, "slice_facing": S, "identical": J["identical_strings"], "receipt": os.path.basename(out), "sha256": sha256_file(out), "fails": fails}


def land_legB(gpath, R, workdir, tools):
    """leg B: the fixed-eps `land` form (the detransport package, --tools DIR) with the eps-order-22 seed of record on the p12^2 = -3
    line at dps 45 / kmax 40 / eps0 = 2^-27 (the record's form), compared with this run's leg-A landing summed at eps0: a ROUTE check
    at the named truncation floor, never a digit claim; its verdict must be PASS and its vs-leg-A worst within 0.05 d of the record's."""
    B, bpath, rc, wall = run_land("-3", 45, workdir, tag="_legB", tools=tools, legB=gpath)
    fails = []
    RL = R.get("leg_B_dps45")
    L = B["land"]; F = B["frobenius_basis"]; V = B["regular_value_at_y_eq_x"]["certificates"]; CA = B["comparison_with_leg_A"]
    if B["verdict"] != "PASS":
        fails.append(f"leg B verdict {B['verdict']}")
    extra = ""
    if RL:
        dw = abs(CA["worst_agree_d"] - RL["comparison_with_leg_A"]["worst_agree_d"])
        extra = f"; recorded: residual_rel {RL['land']['residual_rel']}, vs leg A worst {RL['comparison_with_leg_A']['worst_agree_d']} d: within 0.05 d: {'yes' if dw <= 0.05 else 'NO'}"
        if dw > 0.05:
            fails.append(f"leg B vs leg A worst {CA['worst_agree_d']} d differs from the recorded {RL['comparison_with_leg_A']['worst_agree_d']} d by more than 0.05 d")
    exp = min(r["truncation_expectation_d"] for r in CA["rows"])
    print(f"  leg B (the fixed-eps `land` form with the eps-order-22 seed at eps0 {B['eps0']}, dps {B['dps']}, kmax {B['kmax_frob']}; a ROUTE check at the named truncation floor, not a digit claim): "
          f"land residual_rel {L['residual_rel']}, cond {L['cond_est']}, series tail {L['series_tail']}; basis indicials {F['indicial_integer_multiset']} log_max {F['log_max']}; regular value: residue {V['residue_rel']:.0e}, imaginary part {V['imag_rel']:.0e}; "
          f"vs leg A summed at eps0: worst {CA['worst_agree_d']} d (the truncation expectation {exp} d; {len(CA['structural_zeros_excluded'])} structural zero excluded: {CA['structural_zeros_excluded']}); verdict {B['verdict']} ({wall} s)" + extra)
    return {"receipt": os.path.basename(bpath), "sha256": sha256_file(bpath), "residual_rel": L["residual_rel"], "vs_legA_worst": CA["worst_agree_d"], "expectation": exp, "verdict": B["verdict"], "wall_s": wall, "fails": fails}


def land_tier(line, dps, workdir, second_radius=False, certificate=False, tools=None, mutate=False, pair_dps=None, legB=False):
    """THE --land TIER on one line: the landing at --dps by the vendored engine, the certificates, the floors with members, the count
    line, the comparison with the landing of record; then --mutate / --pair-dps / --legB as asked.  Returns the result dict."""
    R = land_record(line); RB = R["landing_dps60"]; RW = RB["comparison"]["worst"]
    x = RB["x"]; y0 = RB["y0"]
    print(f"\n[land] p12^2 = {line} line: the landing onto the slice at p34^2 = p12^2 = {x} -- the gauged (symmetric/antisymmetric + third-relation) nine-master system from the eps_order-5 seed at p34^2 = {y0} "
          f"({LAND_DIR[line]}/seed_e5.json), the Cauchy mean on a circle of radius {RB['rho']} about the apparent singular point ({RB['nodes']} nodes; the closed loop, the residue and the imaginary part as certificates); "
          f"the record at dps {RB['dps']}: order {RB['order']}, steps {RB['steps']['approach']} + {RB['steps']['circle']}, worst {RW['agree_d']} d = master {RW['slice_master']} eps^{RW['order']} vs {RW['reference']} over {RB['comparison']['n_rows']} pairs, "
          f"count of record {R['count_of_record']['floor']}; this run dps {dps}" + (f" + the pair at dps {pair_dps}" if pair_dps else "") + (" -- LANDED-VALUE MUTATION CONTROL" if mutate else ""))
    g, gpath, grc, wall = run_land(line, dps, workdir, second_radius=second_radius, certificate=certificate, tools=tools)
    fails, floor = land_print_landing(g, R, line, dps, certificate, tools)
    rf, V = land_print_record(g, RB, dps)
    fails += rf
    res = {"line": line, "dps": dps, "floor": floor, "worst": g["comparison"]["worst"], "n_rows": g["comparison"]["n_rows"], "certificates": g["certificates"], "engine_rc": grc, "engine_wall_s": wall,
           "receipt": os.path.basename(gpath), "sha256": sha256_file(gpath), "per_order": g["comparison"]["per_order_floor_with_member"], "per_reference": g["comparison"]["per_reference_floor_with_member"],
           "identical": g["comparison"]["identical_strings"], "vs_record": {k: v for k, v in V.items() if k != "rows"}, "frobenius": g.get("frobenius_certificate_rederived"), "record": {"floor": R["count_of_record"]["floor"], "worst": RW},
           "fails": fails, "mutation": None, "pair": None, "legB": None}
    if mutate:
        res["mutation"] = land_mutate(g, gpath, workdir, line)
    if pair_dps:
        g2, p2, rc2, w2 = run_land(line, pair_dps, workdir, tag="_pair", tools=tools)
        f2, floor2 = land_print_landing(g2, R, line, pair_dps, False, tools)
        rf2, V2 = land_print_record(g2, RB, pair_dps)
        res["pair_landing"] = {"dps": pair_dps, "floor": floor2, "worst": g2["comparison"]["worst"], "engine_rc": rc2, "engine_wall_s": w2, "receipt": os.path.basename(p2), "sha256": sha256_file(p2), "fails": f2 + rf2}
        fails += f2 + rf2
        res["pair"] = land_pair(g, gpath, dps, g2, p2, pair_dps, R, workdir, line)
        fails += res["pair"]["fails"]
    if legB:
        res["legB"] = land_legB(gpath, R, workdir, tools)
        fails += res["legB"]["fails"]
    res["fails"] = fails
    res["n_fail"] = len(fails)
    return res


def main():
    ap = argparse.ArgumentParser(
        description="ICC off the symmetric slice: the nine-master transport along p34^2 on the lines p12^2 = -2 and p12^2 = -3, "
                    "gated against the independent AMFlow values at the target point; the step onto the slice: landed by --land to 47 (-3) / 48 (-2) digits against the slice records (see the docstring).",
        epilog="measured walls (GNU time wall clock, one process, nice 10, a shared 96-core host at loadavg ~120-140): "
               + "; ".join(f"{k}: {v}" for k, v in WALLS.items()) + ".  Exit codes: 0 PASS, 1 FAIL, 2 usage, 3 REFUSED by name, 4 pinned file MISSING, "
               "5 engine did not finish, 6 --mutate/--mutate-slice (or --land --mutate) not caught.")
    ap.add_argument("--line", default="both", choices=["-2", "-3", "both"], help="which line: p12^2 = -2, p12^2 = -3, or both (default both)")
    ap.add_argument("--dps", type=int, default=60, help="working precision of the transport (default 60 = the record precision; >= 30)")
    ap.add_argument("--side", type=int, default=None, choices=[1, -1], help="on the p12^2 = -2 line: which side of the contour around the singular point (default the record's +1 = below the real axis); ignored on the straight p12^2 = -3 path")
    ap.add_argument("--check", action="store_true", help="two precisions: run again at dps + 30 and compare the transported values pair by pair (the record's own two-dps form)")
    ap.add_argument("--mutate", action="store_true", help="the planted control: one digit of one seed value changed; the gate must FAIL by name (rc 1)")
    ap.add_argument("--mutate-slice", action="store_true", help="the slice-gate control: one digit of the [0,1,1,1] eps^0 seed string changed in the copy the slice gate reads; the slice gate must FAIL by name (rc 1) while the transport rows still agree")
    ap.add_argument("--kmax", type=int, default=0, choices=[0, 1], help="1 = THE eps^1 TIER: the eps_order-5 seed transported at eps^-2..eps^1 (27 state components) and gated against the independent eps_order-5 reference at the second point, with the cross-eps-order check and the eps_order-5 twin certificate (needs --dps >= 60; default 0 = the tier of record at eps^-2..eps^0)")
    ap.add_argument("--land", action="store_true", help=f"THE LANDING TIER: land the line's nine-master vector onto the slice p34^2 = p12^2 by the Cauchy mean around the apparent singular point (the vendored engine land/land_fixed_eps.py) and compare it with the slice records (one line: --line -3 or -2; --dps 30 the pilot precision, 45 / 60 the record's; the counts of record 47 / 48)")
    ap.add_argument("--pair-dps", type=int, default=None, metavar="D2", help="with --land: land again at D2 and compare the two landings component-wise (the record's pair is --dps 45 --pair-dps 60)")
    ap.add_argument("--second-radius", action="store_true", help="with --land: the radius-independence certificate (a second circle at rho/2 = 1/32; the record's dps-30 pilot form)")
    ap.add_argument("--certificate", action="store_true", help="with --land: re-derive the Frobenius certificate at y = x on the gauged system (needs the detransport package: --tools DIR); without it the certificate of record is printed")
    ap.add_argument("--legB", action="store_true", help="with --land --line -3: the fixed-eps route check (the detransport `land` form with the eps-order-22 seed; a route check at the named truncation floor, not a digit claim; needs --tools DIR)")
    ap.add_argument("--tools", default=None, metavar="DIR", help="the directory holding the detransport package (the DE toolkit this bundle does not vendor) for --certificate and --legB")
    ap.add_argument("--workdir", default=None, metavar="DIR", help="where the engine's GATE receipts (and the landing receipts of --land) are written (default: a fresh temporary directory)")
    ap.add_argument("--out", default=None, metavar="JSON", help="write the run receipt here (never overwrites)")
    args = ap.parse_args()
    try:
        sys.stdout.reconfigure(line_buffering=True)
    except AttributeError:
        pass
    if args.dps < 30:
        ap.error("--dps must be >= 30 (the record's lowest precision on the p12^2 = -3 line)")
    if args.check and args.mutate:
        ap.error("--check and --mutate are separate tiers")
    if args.mutate_slice and (args.check or args.mutate):
        ap.error("--mutate-slice is its own tier (not with --check or --mutate)")
    if args.kmax and args.dps < 60:
        ap.error("--kmax 1 (the eps^1 tier) runs at the record precision or above: --dps must be >= 60")
    if args.land:
        if args.line == "both":
            ap.error("--land runs one line: --line -3 or --line -2")
        if args.check or args.mutate_slice or args.kmax or args.side is not None:
            ap.error("--land is its own tier (not with --check, --mutate-slice, --kmax or --side; --mutate with --land is the landed-value control)")
        if args.pair_dps is not None and (args.pair_dps < 30 or args.pair_dps == args.dps):
            ap.error("--pair-dps must be >= 30 and differ from --dps")
        if args.legB and args.line != "-3":
            ap.error("--legB runs on the p12^2 = -3 line only (the eps-order-22 seed of record exists there)")
        if (args.legB or args.certificate) and not args.tools:
            ap.error("--legB and --certificate import the detransport package: pass the directory holding it as --tools DIR")
    elif args.pair_dps is not None or args.second_radius or args.certificate or args.legB or args.tools:
        ap.error("--pair-dps, --second-radius, --certificate, --legB and --tools belong to the --land tier")
    t_all = time.time()
    stamp0 = utc()
    which = ["-2", "-3"] if args.line == "both" else [args.line]
    print(f"[mode] ICC off the symmetric slice: line(s) {', '.join('p12^2 = ' + w for w in which)}, dps {args.dps}"
          + (f" + two-precision pair with dps {args.dps + 30}" if args.check else "") + (" -- MUTATION CONTROL" if args.mutate else "") + (" -- SLICE MUTATION CONTROL" if args.mutate_slice else "")
          + (" -- THE eps^1 TIER (--kmax 1: the eps_order-5 files, 27 state components)" if args.kmax else "")
          + (" -- THE LANDING TIER (--land: the landing onto the slice p34^2 = p12^2 by the vendored engine land/land_fixed_eps.py)" if args.land else ""))
    print("[scope] the step from these lines onto the slice p12^2 = p34^2: landed by --land to 47 (-3) / 48 (-2) digits against the slice records (see the tier); the default tiers gate the off-slice transport only")
    npins = check_pins()
    print(f"[pins] {npins} shipped files verified by sha256")
    lines = json.load(open(os.path.join(VENDOR, "lines.json")))
    workdir = args.workdir or tempfile.mkdtemp(prefix="icc-offslice-")
    os.makedirs(workdir, exist_ok=True)
    print(f"[workdir] {os.path.basename(workdir)}/ (the engine's GATE receipts)")
    results = []
    checks = []
    if args.land:
        r = land_tier(which[0], args.dps, workdir, second_radius=args.second_radius, certificate=args.certificate, tools=args.tools, mutate=args.mutate, pair_dps=args.pair_dps, legB=args.legB)
        wall = round(time.time() - t_all, 1)
        if args.mutate:
            caught = r["mutation"]["caught"]
            verdict = "LANDED-VALUE MUTATION CAUGHT (the slice comparison FAILS by name, as expected)" if caught else "LANDED-VALUE MUTATION NOT CAUGHT (a defect of the control)"
            rc = RC_FAIL if caught else RC_NOTCAUGHT
        else:
            verdict = "PASS" if r["n_fail"] == 0 else "FAIL"
            rc = 0 if r["n_fail"] == 0 else RC_FAIL
        W = r["worst"]
        print(f"\nVERDICT {verdict}: p12^2 = {r['line']} landed onto the slice to {r['floor']} digits at dps {r['dps']} (worst {W['agree_d']} d = {W['slice_master']} eps^{W['order']} vs {W['reference']}; the count of record {r['record']['floor']}), {r['n_rows']} pairs vs bar {LAND_BAR:g}; "
              f"certificates {r['certificates']['monodromy_rel']:.1e} / {r['certificates']['residue_rel']:.1e} / {r['certificates']['imag_rel']:.1e}; vs the record {r['vs_record']['worst'][1] if r['vs_record']['worst'] else None} d (identical {r['vs_record']['identical']}/{r['vs_record']['n']})"
              + (f"; pair dps {r['pair']['dps_pair'][0]}/{r['pair']['dps_pair'][1]} slice-facing {r['pair']['slice_facing']['min']} d" if r["pair"] else "") + (f"; leg B route check {r['legB']['verdict']} ({r['legB']['vs_legA_worst']} d vs an expectation of {r['legB']['expectation']} d)" if r["legB"] else "")
              + (f"; FAIL by name: " + "; ".join(r["fails"]) if r["fails"] else "") + f"; total wall {wall} s")
        if args.out:
            rec = {"PRODUCER": {"script": os.path.basename(__file__), "sha256": sha256_file(__file__), "start": stamp0, "stamp": utc(), "wall_s": wall, "pins_verified": npins, "stamp_source": "date -u"},
                   "args": {"line": args.line, "dps": args.dps, "land": True, "pair_dps": args.pair_dps, "second_radius": args.second_radius, "certificate": args.certificate, "legB": args.legB, "mutate": args.mutate},
                   "scope": f"the landing onto the slice: --land, the counts of record {47} (-3) / {48} (-2) digits against the slice records", "land": r, "verdict": verdict, "rc": rc}
            fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
            with os.fdopen(fd, "w") as f:
                json.dump(rec, f, indent=1)
            print(f"[written] {os.path.basename(args.out)}")
        sys.exit(rc)
    for w in which:
        side = args.side if (args.side is not None and w == "-2") else lines["lines"][w]["path"]["detour_sign"]
        if args.side is not None and w == "-3":
            print(f"  (--side ignored on the p12^2 = -3 line: the record's path is the straight real segment)")
        r = evaluate_line(w, lines, args.dps, side, workdir, mutate=args.mutate, mutate_slice=args.mutate_slice, kmax=args.kmax)
        results.append(r)
        if args.check:
            checks.append(two_precision(w, lines, args.dps, side, workdir, r, kmax=args.kmax))
    wall = round(time.time() - t_all, 1)
    n_fail = sum(r["n_fail"] for r in results) + sum(r["slice_gate"]["n_fail"] for r in results) + sum(0 if c["pass"] else 1 for c in checks)
    cert_fails = [(r["line"], r["seed_certificate"]) for r in results if r["seed_certificate"]["n_fail"]]
    n_fail += sum(c["n_fail"] for _, c in cert_fails)
    e1_fails = [(r["line"], r["eps1"]) for r in results if r["eps1"] and r["eps1"]["n_fail"]]
    n_fail += sum(e["n_fail"] for _, e in e1_fails)
    if args.mutate:
        caught = all(r["n_fail"] > 0 for r in results)
        verdict = "MUTATION CAUGHT (the gate FAILS by name, as expected)" if caught else "MUTATION NOT CAUGHT (a defect of the control)"
        rc = RC_FAIL if caught else RC_NOTCAUGHT
    elif args.mutate_slice:
        caught = all(r["slice_gate"]["n_fail"] > 0 for r in results)
        verdict = "SLICE MUTATION CAUGHT (the slice gate FAILS by name, as expected)" if caught else "SLICE MUTATION NOT CAUGHT (a defect of the control)"
        rc = RC_FAIL if caught else RC_NOTCAUGHT
    else:
        verdict = "PASS" if n_fail == 0 else "FAIL"
        rc = 0 if n_fail == 0 else RC_FAIL
    if args.kmax:
        print(f"\nVERDICT {verdict}: " + "; ".join(f"p12^2 = {r['line']} (eps^1 tier): eps^1 gate worst {r['eps1']['eps1_worst']:.2f} d over {r['eps1']['n_eps1']} pairs (recorded {r['eps1']['recorded_eps1_worst']}), the eps^0 rows {r['eps1']['eps0_worst']:.2f} d over {r['eps1']['n_eps0']} (recorded {r['eps1']['recorded_eps0_worst']}), "
                                           f"vs bar {r['bar']:g}: {r['eps1']['n_transported'] - r['n_fail']} of {r['eps1']['n_transported']} transported pairs met; cross-eps-order {r['eps1']['cross_eps_order']['worst_seed']:.2f} / {r['eps1']['cross_eps_order']['worst_reference']:.2f} d; twin {r['eps1']['twin_certificate']['worst']:.2f} d over {r['eps1']['twin_certificate']['n_counted']} components; "
                                           f"slice gate {r['slice_gate']['worst']:.2f} d worst vs bar {r['slice_gate']['bar']}, {r['slice_gate']['n_pairs'] - r['slice_gate']['n_fail']} of {r['slice_gate']['n_pairs']} pairs met" for r in results)
              + ("; " + "; ".join(f"two-precision worst {c['worst_pair_digits']:.2f} d vs bar {c['bar']:g}" for c in checks) if checks else "")
              + ("; seed two-precision certificate FAIL by name on " + "; ".join(f"p12^2 = {ln}: {c['fail_text']}" for ln, c in cert_fails) if cert_fails else "")
              + ("; eps^1 tier FAIL by name on " + "; ".join(f"p12^2 = {ln}: " + "; ".join(e["fails"] + e["cross_eps_order"]["fails"] + e["twin_certificate"]["fails"]) for ln, e in e1_fails) if e1_fails else "") + f"; total wall {wall} s")
    else:
        print(f"\nVERDICT {verdict}: " + "; ".join(f"p12^2 = {r['line']}: worst {r['worst']} d ({r['worst_independent']} d on the p34^2-dependent masters) vs bar {r['bar']}, {r['n_pairs'] - r['n_fail']} of {r['n_pairs']} pairs met, slice gate {r['slice_gate']['worst']:.2f} d worst vs bar {r['slice_gate']['bar']}, {r['slice_gate']['n_pairs'] - r['slice_gate']['n_fail']} of {r['slice_gate']['n_pairs']} pairs met" for r in results)
              + ("; " + "; ".join(f"two-precision worst {c['worst_pair_digits']:.2f} d vs bar {c['bar']}" for c in checks) if checks else "")
              + ("; seed two-precision certificate FAIL by name on " + "; ".join(f"p12^2 = {ln}: {c['fail_text']}" for ln, c in cert_fails) if cert_fails else "") + f"; total wall {wall} s")
    if args.out:
        rec = {"PRODUCER": {"script": os.path.basename(__file__), "sha256": sha256_file(__file__), "start": stamp0, "stamp": utc(), "wall_s": wall,
                            "pins_verified": npins, "stamp_source": "date -u"},
               "args": {"line": args.line, "dps": args.dps, "side": args.side, "check": args.check, "mutate": args.mutate, "mutate_slice": args.mutate_slice, "kmax": args.kmax},
               "scope": lines["onto_the_slice"], "lines": results, "checks": checks, "verdict": verdict, "rc": rc}
        fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
        with os.fdopen(fd, "w") as f:
            json.dump(rec, f, indent=1)
        print(f"[written] {os.path.basename(args.out)}")
    sys.exit(rc)


if __name__ == "__main__":
    main()
