#!/usr/bin/env python3
"""zgamma-s127-evaluate.py -- gg -> Z gamma with the exact top mass: the SECTOR-127 t-cone legs (the 72-master cone that
closes the six sector-127 masters under d/dt), transported between four points of an independent reference set and gated
there.  The served zgamma-evaluate.py (the sector-125 pair) is unchanged and is not used by this script.

WHAT ONE LEG IS
  The cone: at fixed s = -1/4, M = m_Z^2/m_t^2 = 7/25, m_t^2 = 1 and d = 4 - 2 eps, the six sector-127 masters and the 66 masters
  their t-derivatives reach form a closed 72 x 72 system d/dt M = A_t(eps, t) M with exact rational entries
  (vendor_row20_s127/cone/A_t127_s-1_4.json; the leading 14 x 14 block is the served sector-125 cone).  Four points of the
  independent reference set lie on that line, at t = -25, -6, -3/2, -1/3 (points/points.json names them E04, E03, E02, E01 --
  the data-file names -- with their kinematics); at each the reference set holds every master's eps-Laurent coefficients as
  140-digit strings, certified to 109-112 digits at the sector-127 rows by its own two independent computations.
  A leg seeds the 72-vector with the reference values at one point, transports it along t to a neighbouring point by
  mpmath.odefun on the eps-expanded connection (orders eps^-3 .. eps^4; the eps^3, eps^4 orders are truncation-affected and
  not gated there; the rebuilt window --orders -3,6 below gates them), refined into sub-nodes of length <= max-seg with the full state checkpointed after every sub-node, and at the
  target compares the six sector-127 masters, order by order (eps^-3 .. eps^2, the validated orders), with the reference
  strings there: digits = -log10(|transported - reference| / (|reference| + 10^-(dps-5))), formed at 400 digits from the
  140-digit strings.  The printed count is the WORST sector-127 digit over the gated (row, order) pairs.
  The six legs (legs.json), each independent of every other:
    L1f  E04 -> E03  (t -25 -> -6;   straight; max-seg 2;   10 sub-nodes)      L1r  E03 -> E04  (the reverse)
    L2f  E03 -> E02  (t -6 -> -3/2;  the u = 4 m_t^2 threshold at t = -347/100 lies on the segment: a rectangular contour of
                      depth 1 into the lower half t-plane, the Feynman side; max-seg 1/2; 13 sub-nodes)   L2r  (the reverse)
    L3f  E02 -> E01  (t -3/2 -> -1/3; straight; max-seg 1/4; 5 sub-nodes)      L3r  E01 -> E02  (the reverse)
  The transport worker (vendor_row20_s127/s127_leg_worker.py) is the worker of record, driven here with its command line of
  record; the pair and per-order loss table (vendor_row20_s127/post_leg.py) is the table of record.

THE TIERS AND THEIR BARS (record.json; the bar = floor of the record's worst sector-127 digit at that leg and precision)
  dps 30 (every leg):  L1f 24.87 -> 24   L1r 24.25 -> 24   L2f 23.33 -> 23   L2r 26.23 -> 26   L3f 24.12 -> 24   L3r 23.94 -> 23
  dps 45 (every leg):  L1f 40.66 -> 40   L1r 40.03 -> 40   L2f 37.90 -> 37   L2r 40.35 -> 40   L3f 39.18 -> 39   L3r 39.34 -> 39
  dps 60 (every leg):  L1f 55.85 -> 55   L1r 55.01 -> 55   L2f 53.34 -> 53   L2r 55.71 -> 55   L3f 54.98 -> 54   L3r 54.62 -> 54
  the two-precision pairs (post_leg.py; the bar = floor of the record's worst pair digit):  45/60 on every leg  L1f 40.52 -> 40   L1r 39.95 -> 39
  L2f 38.92 -> 38   L2r 40.27 -> 40   L3f 39.18 -> 39   L3r 39.34 -> 39;  30/45 on every leg (24, 24, 23, 26, 24, 23).
  A leg is a LONG computation -- minutes at dps 30 on the short legs, hours at dps 45/60 and on the L2 legs (see the walls
  below) -- checkpointed after every sub-node: a run interrupted at any point resumes from its last sub-node when the same
  command is run again with the same --workdir.

ORDERS WINDOW -3..6 (the rebuilt record; record.json orders_windows['-3,6'])
  --orders -3,6 transports eps^-3 .. eps^6 instead of the record's own eps^-3 .. eps^4: with two more orders of headroom the
  eps^3 and eps^4 rows enter the gate (validated at the reference points; the gated orders are eps^-3 .. eps^4), while eps^5
  and eps^6 are truncation-affected and excluded.  The record at this window is the rebuilt run of every leg at dps 45 and
  60 (the worker line of record plus --orders=-3,6); its eps^-3 .. eps^2 rows agree with the record's own window to the
  record's floor on all twelve runs (the identity gates of record).  The bars = floors of the rebuilt worst sector-127 digit:
  dps 45:  L1f 39.48 -> 39   L1r 38.72 -> 38   L2f 36.77 -> 36   L2r 39.26 -> 39   L3f 37.44 -> 37   L3r 37.25 -> 37
  dps 60:  L1f 54.33 -> 54   L1r 53.56 -> 53   L2f 52.07 -> 52   L2r 54.33 -> 54   L3f 53.77 -> 53   L3r 52.81 -> 52
  the 45/60 pairs (post_leg.py at the window; the bar = floor of the worst pair digit):  L1f 38.68 -> 38   L1r 38.65 -> 38
  L2f 37.28 -> 37   L2r 38.55 -> 38   L3f 37.44 -> 37   L3r 37.25 -> 37
  the gate of record (bar 30; min(pair, vs the reference at 60) per row): the eps^0..4 count floors  L1f 38.68  L1r 38.65
  L2f 37.28  L2r 38.55  L3f 37.44  L3r 37.25 (worst row 71 at eps^4 on L3r); the eps^3,4 rows alone  L1f 38.68  L1r 38.65
  L2f 37.28  L2r 38.55  L3f 37.44  L3r 37.25.
  USAGE  python3 zgamma-s127-evaluate.py --leg L3r --dps 45 --orders -3,6
         python3 zgamma-s127-evaluate.py --leg L3r --pair 45,60 --orders -3,6
         python3 zgamma-s127-evaluate.py --leg L3r --dps 45 --check --orders -3,6
  The window's checkpoints, heartbeats, worker logs and results live in <workdir>/orders_-3_6/ under the same names as the
  record's own window; a checkpoint of one window is never consumed by another (the worker's checkpoint meta carries the
  orders and refuses a mismatch: its rc 6 -> rc 5 here, by name).  A leg at this window is a LONG computation (the record's
  walls in --help); dps 30 has no record at the window and is refused up front.  The eps^5, eps^6 seed strings are not
  certified by the reference set's own pair: their accuracy is inferred from the recovered eps^3, eps^4 rows.

USAGE
  python3 zgamma-s127-evaluate.py                          # = --leg L3r --dps 30 (the cheapest leg at the lowest documented precision)
  python3 zgamma-s127-evaluate.py --leg L3f --dps 45       # one leg at one precision, gated at its bar and compared with the record
  python3 zgamma-s127-evaluate.py --leg L3f --dps 60
  python3 zgamma-s127-evaluate.py --leg L3f --pair 45,60   # the pair/loss table from two transports already in --workdir
  python3 zgamma-s127-evaluate.py --leg L3f --dps 45 --check   # the two-precision form: the leg at 45 and at 60, then the pair
  python3 zgamma-s127-evaluate.py --leg L3r --dps 30 --mutate  # the planted control: one reference digit changed on a copy -> FAIL by name
  python3 zgamma-s127-evaluate.py --selftest                # the worker's own 2 x 2 exact transport + checkpoint round trip (seconds)
  python3 zgamma-s127-evaluate.py --leg L2f --dps 45 --show-command   # print the worker line of record for that tier and exit
  --workdir DIR (default zgamma-s127-work/ under the current directory): the checkpoint, heartbeat, worker log and result of
  every tier live there, named by leg and precision; --max-seg overrides the record's cadence (a different checkpoint path:
  the record's sub-node count is then not reproduced); --out JSON writes the run receipt (refused up front if it exists);
  --orders LO,HI selects the transport's eps window (only -3,6 has a record: ORDERS WINDOW above; its files live in
  <workdir>/orders_LO_HI/).

EXIT CODES  0 PASS (the worst sector-127 digit meets the bar; every requested tier) | 1 FAIL (below the bar, named; also the
  expected outcome of --mutate) | 2 usage (also: --out exists; an --orders window or a precision with no record) | 3 REFUSED (a shipped file's sha256 pin mismatch, named) |
  4 a pinned file MISSING | 5 the worker did not finish (its exit code and last line printed; rc 6 from the worker = a
  checkpoint from another configuration in --workdir: move it aside) | 6 the --mutate control was NOT caught (a defect of
  the control, never a pass).

MEASURED WALLS (GNU time wall clock, one process, nice 10, a shared 96-core host at loadavg ~130-150 -- a quiet core is
  faster; the record's own walls are in record.json): see the epilog of --help (the same table).
"""
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
VENDOR = os.path.join(HERE, "vendor_row20_s127")
RC_FAIL, RC_USAGE, RC_REFUSED, RC_MISSING, RC_WORKER, RC_NOTCAUGHT = 1, 2, 3, 4, 5, 6
LEGS = ["L1f", "L1r", "L2f", "L2r", "L3f", "L3r"]
PRECISIONS = [30, 45, 60]

# --- PINS (script-emitted from the shipped bytes; sha256 of every vendored file) ---
PINS = {
    "vendor_row20_s127/cone/A_t127_s-1_4.json": "5bd43620996992e0b60bd6971c1e562e39bcbde9f56b0e133deb99db5423b806",
    "vendor_row20_s127/cone/STRUCTURE_VERDICT.json": "1990d773e52f73866eb2626fe3efbbc1a8c98296b7b36daae200d4c0deb30cf7",
    "vendor_row20_s127/digit_gate.py": "f0beb35df7e8824acb9d2bd00cedf43b82e7a54f6b63c170eeda152a3bb482ad",
    "vendor_row20_s127/legs.json": "51cff1bc0de687c244bff06eb615bfe7a3c65767cea86732c309312bbd4c7744",
    "vendor_row20_s127/points/E01/accepted.tsv": "eb847576bfeaa9d607524feab7605d1f509156045d04e2bc86ca4036817b6251",
    "vendor_row20_s127/points/E02/accepted.tsv": "7afbcbc2262e10951de23da63e386da5185c4f2e9d13d436d15f93b57eac37f1",
    "vendor_row20_s127/points/E03/accepted.tsv": "f9b75c36c5299b09740807990b82794186f5cec905a332f3e841914afb9eb8e4",
    "vendor_row20_s127/points/E04/accepted.tsv": "46aeefac4f4b03f6282f04893d032f423f3a1276d75f1fa036da139487f80d73",
    "vendor_row20_s127/points/points.json": "6c11788dbe70cdffee5d72fa2880f900a40aa228c5da3bdeec02a505c20bbcc0",
    "vendor_row20_s127/post_leg.py": "f2da4ba8cb38fbc8984b5bd67d475af501b83d8aacb52889490181b48e904bc8",
    "vendor_row20_s127/record.json": "3c09378bbed84d9a12d6c2e90da688fca7fd253280bfa78371f50ed662f4d3fa",
    "vendor_row20_s127/s127_leg_worker.py": "2166e2f9a44153c6cd87244995ad46fc71233562549218430287ded49bd5d7bd",
}
# --- END PINS ---

# measured walls (GNU time, the delivered bytes; written by the build from its captures)
WALLS = {
    "default (--leg L3r --dps 30; the cheapest leg at the lowest documented precision; one process, host loadavg 138)": "1191.40 s",
    "--selftest": "1.49 s",
    "--leg L3r --dps 30 --mutate (the finished checkpoint re-gated; nothing transported)": "2.34 s",
    "--leg L1f --dps 45 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "7684.97 s",
    "--leg L1r --dps 45 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "7456.19 s",
    "--leg L2f --dps 45 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "18727.33 s",
    "--leg L2r --dps 45 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "18160.03 s",
    "--leg L3f --dps 45 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "2926.41 s",
    "--leg L3r --dps 45 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "3095.02 s",
    "--leg L1f --dps 60 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "13053.12 s",
    "--leg L1r --dps 60 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "14771.77 s",
    "--leg L3f --dps 60 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "6382.78 s",
    "--leg L3r --dps 60 (ten legs at once under one 10-core cpu quota, host loadavg 132-164)": "7427.99 s",
    "--leg L1f --pair 45,60 (post_leg.py on two finished transports in --workdir)": "0.32 s",
    "--leg L1r --pair 45,60 (post_leg.py on two finished transports in --workdir)": "0.38 s",
    "--leg L3f --pair 45,60 (post_leg.py on two finished transports in --workdir)": "0.25 s",
    "--leg L3r --pair 45,60 (post_leg.py on two finished transports in --workdir)": "0.25 s",
    "--leg L3r --pair 30,45 (post_leg.py on two finished transports in --workdir)": "0.28 s",
    "--leg L3f --dps 45 --mutate (the finished checkpoint re-gated; nothing transported)": "1.81 s",
    "--leg L3f --dps 45 --check from finished checkpoints of both precisions (re-gated, nothing transported, then the pair)": "3.22 s",
    "--leg L2f --dps 60 (the record's own run of the worker line of record: one process on one core, nice 10, a shared host, contended)": "21847.7 s",
    "--leg L2r --dps 60 (the record's own run of the worker line of record: one process on one core, nice 10, a shared host, contended)": "19056.4 s",
    "--leg L2f --dps 60 from the record's finished checkpoint in --workdir (re-gated at its last sub-node, nothing transported; host loadavg 108.42)": "1.51 s",
    "--leg L2r --dps 60 from the record's finished checkpoint in --workdir (re-gated at its last sub-node, nothing transported; host loadavg 108.42)": "1.45 s",
    "--leg L2f --pair 45,60 (post_leg.py on two finished transports in --workdir)": "0.27 s",
    "--leg L2r --pair 45,60 (post_leg.py on two finished transports in --workdir)": "0.28 s",
    "--leg L2f --dps 60 --mutate (the finished checkpoint re-gated; nothing transported)": "1.60 s",
    "--leg L1f --dps 45 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "3829.7 s",
    "--leg L1r --dps 45 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "4089.0 s",
    "--leg L2f --dps 45 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "11133.0 s",
    "--leg L2r --dps 45 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "10869.4 s",
    "--leg L3f --dps 45 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "2052.7 s",
    "--leg L3r --dps 45 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "2022.8 s",
    "--leg L1f --dps 60 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "7208.2 s",
    "--leg L1r --dps 60 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "7772.0 s",
    "--leg L2f --dps 60 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "25084.0 s",
    "--leg L2r --dps 60 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "24428.0 s",
    "--leg L3f --dps 60 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "3729.8 s",
    "--leg L3r --dps 60 --orders -3,6 (the record's own run of the worker line of record at the window, one process, low priority, a shared host, contended)": "3863.1 s",
    "--leg L1f --dps 45 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.92)": "1.47 s",
    "--leg L1f --dps 60 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.77)": "1.65 s",
    "--leg L1r --dps 45 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.77)": "1.45 s",
    "--leg L1r --dps 60 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.77)": "1.63 s",
    "--leg L2f --dps 45 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.30)": "1.60 s",
    "--leg L2f --dps 60 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.30)": "1.66 s",
    "--leg L2r --dps 45 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.30)": "1.59 s",
    "--leg L2r --dps 60 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.28)": "1.60 s",
    "--leg L3f --dps 45 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.28)": "1.62 s",
    "--leg L3f --dps 60 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.28)": "1.44 s",
    "--leg L3r --dps 45 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.58)": "1.45 s",
    "--leg L3r --dps 60 --orders -3,6 from the record's finished checkpoint in <workdir>/orders_-3_6/ (re-gated at its last sub-node, nothing transported; host loadavg 91.58)": "1.48 s",
    "--leg L1f --pair 45,60 --orders -3,6 (post_leg.py on two finished transports in <workdir>/orders_-3_6/)": "0.29 s",
    "--leg L1r --pair 45,60 --orders -3,6 (post_leg.py on two finished transports in <workdir>/orders_-3_6/)": "0.30 s",
    "--leg L2f --pair 45,60 --orders -3,6 (post_leg.py on two finished transports in <workdir>/orders_-3_6/)": "0.45 s",
    "--leg L2r --pair 45,60 --orders -3,6 (post_leg.py on two finished transports in <workdir>/orders_-3_6/)": "0.31 s",
    "--leg L3f --pair 45,60 --orders -3,6 (post_leg.py on two finished transports in <workdir>/orders_-3_6/)": "0.31 s",
    "--leg L3r --pair 45,60 --orders -3,6 (post_leg.py on two finished transports in <workdir>/orders_-3_6/)": "0.39 s",
    "--leg L3r --dps 45 --check --orders -3,6 from finished checkpoints of both precisions (re-gated, nothing transported, then the pair)": "3.31 s",
    "--leg L3r --dps 45 --orders -3,6 --mutate (the finished checkpoint re-gated; nothing transported)": "1.63 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"zgamma-s127-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"zgamma-s127-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)


def bar_for(rec_leg, dps):
    """the bar at (leg, dps): the floor of the record's worst sector-127 digit there; else at the highest documented precision below."""
    bars = rec_leg["bars"]
    if str(dps) in bars:
        return bars[str(dps)], dps
    below = [int(k) for k in bars if int(k) < dps]
    if not below:
        return None, None
    use = max(below)
    return bars[str(use)], use


def pair_bar_for(rec_leg, lo, hi):
    key = f"{lo}/{hi}"
    if key in rec_leg["pair_bars"]:
        return rec_leg["pair_bars"][key], key
    cands = [k for k in rec_leg["pair_bars"] if int(k.split("/")[1]) <= hi]
    if not cands:
        return None, None
    use = max(cands, key=lambda k: int(k.split("/")[1]))
    return rec_leg["pair_bars"][use], use


def window(rec, workdir, orders):
    """the record legs table, the workdir and the record's window block for the requested eps window: None -> the record's own
    window (rec['legs'], --workdir itself, None: the served behaviour); (LO, HI) -> rec['orders_windows']['LO,HI'] (REFUSED by
    name when the record carries no such window): its legs table and the sub-workdir <workdir>/orders_LO_HI/, so that a
    checkpoint or result of one window is never consumed by another (the worker's own checkpoint meta carries the orders and
    refuses a mismatch in any case)."""
    if orders is None:
        return rec["legs"], workdir, None
    key = f"{orders[0]},{orders[1]}"
    W = rec.get("orders_windows", {})
    if key not in W:
        die(RC_USAGE, f"zgamma-s127-evaluate REFUSED: no record at the orders window {key}; the documented window is {', '.join(W) if W else 'none'} "
                      f"(--orders absent = the record's own window eps^-3 .. eps^4); nothing was computed")
    wdir = os.path.join(workdir, f"orders_{orders[0]}_{orders[1]}")
    os.makedirs(wdir, exist_ok=True)
    return W[key]["legs"], wdir, W[key]


def worker_cmd(leg, L, dps, workdir, max_seg, ckpt, out_dir, label, orders=None):
    cmd = [sys.executable, os.path.join(VENDOR, "s127_leg_worker.py"), "--cone", os.path.join(VENDOR, "cone", "A_t127_s-1_4.json"),
           "--base", L["from"], "--targets", L["to"], "--dps", str(dps), "--detour", L["worker_detour_flag"], "--max-seg", max_seg,
           "--ckpt", ckpt, "--heartbeat", os.path.join(workdir, f"heartbeat_{label}.json"), "--out-dir", out_dir, "--label", label,
           "--gate-dps", "400", "--pass-margin", "10"]
    if orders is not None:
        cmd.append(f"--orders={orders[0]},{orders[1]}")   # the worker's own --orders knob, one token (a leading '-' would read as a flag)
    return cmd


def show_cmd(cmd):
    return " ".join(os.path.relpath(c, HERE) if c.startswith(HERE) else ("python3" if c == sys.executable else c) for c in cmd)


RX_NODE = re.compile(r"sub-node (\d+)/(\d+) .* done in ([\d.]+) s \(F calls so far (\d+)\)")
RX_EL = re.compile(r"^\[\s*([\d.]+)s\]")


def run_worker(cmd, workdir, label, rec_T, env_extra=None, tag=""):
    """drive the vendored worker with the command line of record; stream its log; after every sub-node print the rate and the
    projection of the whole leg from the run's own elapsed time and F-call count (an ESTIMATE, labelled)."""
    env = dict(os.environ)
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    if env_extra:
        env.update(env_extra)
    print(f"  [worker] {show_cmd(cmd)}", flush=True)
    log = open(os.path.join(workdir, f"worker_{label}{tag}.log"), "a")
    log.write(f"=== {utc()} launch: {' '.join(cmd)}\n")
    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
        log.write(ln + "\n")
        log.flush()
        print(f"  [worker] {ln}", flush=True)
        m = RX_NODE.search(ln)
        if m:
            k, n, calls = int(m.group(1)), int(m.group(2)), int(m.group(4))
            el = RX_EL.match(ln)
            elapsed = float(el.group(1)) if el else time.time() - t0
            rate = elapsed / calls if calls else float("nan")
            if rec_T is not None:
                proj = rate * rec_T["n_F_calls"]
                print(f"  [rate] {calls} F calls in {elapsed:.1f} s = {rate:.3f} s per call; the record's leg took {rec_T['n_F_calls']} calls "
                      f"-> whole-leg ESTIMATE {proj:.0f} s ({proj / 60:.1f} min) at this rate; sub-node {k}/{n} done", flush=True)
            else:
                print(f"  [rate] {calls} F calls in {elapsed:.1f} s = {rate:.3f} s per call; sub-node {k}/{n} done (no record F-call count at "
                      f"this precision: the remaining sub-nodes are longer than the first ones on every recorded leg)", flush=True)
    rc = p.wait()
    log.write(f"=== {utc()} exit rc {rc}\n")
    log.close()
    wall = time.time() - t0
    return rc, round(wall, 1), last


def s127_rows(T):
    Lg = T["legs"][0]
    return {str(r["i"]): r for r in Lg["gate_rows"] if r["sec"] == 127}


def gate_transport(T, leg, dps, rec_leg, bar, bar_dps, quiet_rows=False):
    Lg = T["legs"][0]
    worst = Lg["worst_digits_sector127"]
    orders = list(range(int(T["orders"][0]), int(T["orders"][1]) + 1))
    affected = set(int(o) for o in T["truncation_affected_orders"])
    rows = s127_rows(T)
    print(f"  transported {Lg['from']} -> {Lg['to']} (t {Lg['t_from']} -> {str(Lg['t_to'])[:12]}), {Lg['n_subnodes']} sub-nodes, {T['n_F_calls']} F calls, "
          f"worker wall {Lg['wall_s']} s; path {'straight' if not Lg['crossing'] else 'contour around ' + str(Lg['crossing'])}; worker verdict {Lg['gate_verdict']} "
          f"(PASS iff worst >= dps - {T['pass_margin']})")
    if not quiet_rows:
        print(f"  {'sector-127 master':>32}  " + "  ".join(f"{'eps^%d' % o:>8}" for o in orders) + "   (digits vs the reference; x = truncation-affected, not gated)")
        for i in sorted(rows, key=int):
            r = rows[i]
            cells = []
            for o in orders:
                po = r["per_order"].get(str(o))
                if po is None:
                    cells.append(f"{'-':>8}")
                elif o in affected or int(po.get("validated", 0)) != 1:
                    cells.append(f"{str(po['digits']) + 'x':>8}")
                else:
                    cells.append(f"{po['digits']:>8}")
            print(f"  {str(r['nu']):>32}  " + "  ".join(cells))
    ok = worst >= bar
    print(f"  worst sector-127 digit {worst:.2f} over the gated (row, order) pairs vs the bar {bar} (floor of the record's {bar_dps and rec_leg['transports'][str(bar_dps)]['worst_digits_sector127']:.2f} d at dps {bar_dps}"
          f"{'' if bar_dps == dps else ', the highest documented precision below ' + str(dps)}): {'PASS' if ok else 'FAIL'}")
    vs = None
    if str(dps) in rec_leg["transports"]:
        R = rec_leg["transports"][str(dps)]
        same_d = same_s = tot = 0
        for i, r in rows.items():
            for o, po in r["per_order"].items():
                rp = R["sector127_rows"][i]["per_order"][o]
                tot += 1
                same_d += (po["digits"] == rp["digits"])
                same_s += (po["pred_re"] == rp["pred_re"] and po["pred_im"] == rp["pred_im"])
        counts_equal = (Lg["n_subnodes"] == R["n_subnodes"]) and (T["n_F_calls"] == R["n_F_calls"])
        vs = {"record_dps": dps, "record_worst": R["worst_digits_sector127"], "this_worst": worst, "worst_identical": abs(worst - R["worst_digits_sector127"]) < 1e-9,
              "row_order_digits_identical": same_d, "value_strings_identical": same_s, "of": tot, "n_subnodes": [Lg["n_subnodes"], R["n_subnodes"]],
              "n_F_calls": [T["n_F_calls"], R["n_F_calls"]], "counts_equal": counts_equal, "record_wall_s": R["wall_s"], "record_wall_label": R["wall_label"], "this_wall_s": Lg["wall_s"]}
        print(f"  vs the record at dps {dps}: worst {R['worst_digits_sector127']:.2f} d (record) vs {worst:.2f} d (this run){' -- identical' if vs['worst_identical'] else ''}; "
              f"per-(row, order) digits identical {same_d}/{tot}; value strings identical {same_s}/{tot}; sub-node/F-call counts equal: {counts_equal} "
              f"({Lg['n_subnodes']}/{R['n_subnodes']} sub-nodes, {T['n_F_calls']}/{R['n_F_calls']} calls); record wall {R['wall_s']} s ({R['wall_label'].split(' (')[0]}) vs this run {Lg['wall_s']} s")
    return ok, worst, vs


def evaluate_leg(leg, dps, legs, rec, workdir, max_seg=None, quiet_rows=False, orders=None):
    L = legs["legs"][leg]
    rec_legs, wdir, _ = window(rec, workdir, orders)
    rec_leg = rec_legs[leg]
    bar, bar_dps = bar_for(rec_leg, dps)
    if bar is None:
        die(RC_USAGE, f"zgamma-s127-evaluate REFUSED: no record at dps {dps} for leg {leg} in the orders window {orders[0]},{orders[1]} "
                      f"(its documented precisions: {', '.join(sorted(rec_leg['bars'], key=int))}); nothing was computed")
    label = f"{leg}_dps{dps}"
    seg = max_seg or L["max_seg"]
    ckpt = os.path.join(wdir, f"ckpt_{label}.json")
    out = os.path.join(wdir, f"TRANSPORT_{label}.json")
    print(f"\n[leg] {leg}: {L['from']} (t = {L['t_from']}) -> {L['to']} (t = {L['t_to']}), {L['detour']}; max-seg {seg}{'' if seg == L['max_seg'] else ' (the record: ' + L['max_seg'] + ')'}; dps {dps}; "
          f"{'orders ' + str(orders[0]) + '..' + str(orders[1]) + ' (the rebuilt window); ' if orders else ''}bar {bar} (record dps {bar_dps}); seed {L['seed_file']}, gate {L['gate_file']}")
    rec_T = rec_leg["transports"].get(str(dps))
    if rec_T:
        print(f"  the record at this precision: worst {rec_T['worst_digits_sector127']:.2f} d, {rec_T['n_subnodes']} sub-nodes, {rec_T['n_F_calls']} F calls, wall {rec_T['wall_s']} s ({rec_T['wall_label'].split(' (')[0]})")
    if os.path.exists(ckpt):
        try:
            ck = json.load(open(ckpt))
            print(f"  checkpoint present: {os.path.basename(ckpt)} status {ck.get('status')} ({ck.get('nodes_done')}/{ck.get('n_subnodes')} sub-nodes done) -- the worker resumes from it")
        except Exception:
            print(f"  checkpoint present but unreadable: {os.path.basename(ckpt)}")
    cmd = worker_cmd(leg, L, dps, wdir, seg, ckpt, wdir, label, orders)
    rc, wall, last = run_worker(cmd, wdir, label, rec_T if (rec_T and seg == L["max_seg"]) else None)
    if rc != 0 or not os.path.exists(out):
        die(RC_WORKER, f"zgamma-s127-evaluate WORKER DID NOT FINISH on leg {leg} at dps {dps}: rc {rc}; last line: {last!r}"
                       + (" -- rc 6 = a checkpoint from another configuration under --workdir; move it aside" if rc == 6 else ""))
    T = json.load(open(out))
    ok, worst, vs = gate_transport(T, leg, dps, rec_leg, bar, bar_dps, quiet_rows=quiet_rows)
    return {"leg": leg, "dps": dps, "bar": bar, "bar_dps": bar_dps, "worst": worst, "pass": ok, "max_seg": seg, "n_subnodes": T["legs"][0]["n_subnodes"], "n_F_calls": T["n_F_calls"],
            "worker_wall_s": T["legs"][0]["wall_s"], "subprocess_wall_s": wall, "worker_verdict": T["legs"][0]["gate_verdict"], "result": os.path.basename(out), "result_sha256": sha256_file(out),
            "checkpoint": os.path.basename(ckpt), "vs_record": vs, "stamp_utc": T["stamp_utc"]}


def run_pair(leg, lo, hi, rec, workdir, orders=None):
    rec_legs, wdir, _ = window(rec, workdir, orders)
    rec_leg = rec_legs[leg]
    tlo, thi = os.path.join(wdir, f"TRANSPORT_{leg}_dps{lo}.json"), os.path.join(wdir, f"TRANSPORT_{leg}_dps{hi}.json")
    for p in (tlo, thi):
        if not os.path.exists(p):
            die(RC_USAGE, f"zgamma-s127-evaluate --pair: {os.path.basename(p)} is not in --workdir {wdir}; run that tier first")
    bar, bar_key = pair_bar_for(rec_leg, lo, hi)
    if bar is None:
        die(RC_USAGE, f"zgamma-s127-evaluate REFUSED: no record for the pair {lo}/{hi} on leg {leg} in the orders window {orders[0]},{orders[1]} "
                      f"(its documented pairs: {', '.join(rec_leg['pair_bars'])}); nothing was computed")
    out = os.path.join(wdir, f"POST_{leg}_pair{lo}_{hi}.json")
    if os.path.exists(out):
        os.remove(out)
    cmd = [sys.executable, os.path.join(VENDOR, "post_leg.py"), "--leg", leg, "--t30", tlo, "--t45", thi, "--out", out, "--bar", str(bar)]
    print(f"\n[pair] {leg}: the two-precision pair dps {lo} / {hi} and the per-order loss table (post_leg.py, the table of record); {'orders ' + str(orders[0]) + '..' + str(orders[1]) + ' (the rebuilt window); ' if orders else ''}bar {bar} (floor of the record's worst pair digit"
          f"{'' if bar_key == f'{lo}/{hi}' else ' for the pair ' + bar_key + ', the highest documented pair not above'})")
    print(f"  [post_leg] {show_cmd(cmd)}")
    env = dict(os.environ)
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    r = subprocess.run(cmd, capture_output=True, text=True, cwd=wdir, env=env)
    for ln in (r.stdout + r.stderr).strip().split("\n"):
        print(f"  [post_leg] {ln}")
    if r.returncode != 0 or not os.path.exists(out):
        die(RC_WORKER, f"zgamma-s127-evaluate post_leg.py did not finish: rc {r.returncode}")
    Pj = json.load(open(out))
    q = Pj["quoted_sector127"]
    loss = Pj["per_order_loss_table"]
    print(f"  {'order':>6}  {'dps%d worst s127' % lo:>16}  {'dps%d worst s127' % hi:>16}  {'gain':>6}  {'dps%d worst all' % lo:>15}  {'dps%d worst all' % hi:>15}")
    for o in sorted(loss, key=int):
        row = loss[o]
        a, b = row[f"dps{lo}_worst_s127"], row[f"dps{hi}_worst_s127"]
        print(f"  {o:>6}  {a:>16}  {b:>16}  {(b - a) if (a is not None and b is not None) else '-':>6}  {row[f'dps{lo}_worst_all']:>15}  {row[f'dps{hi}_worst_all']:>15}")
    worst_pair = q["worst_pair_d"]
    ok = worst_pair >= bar
    print(f"  sector-127 rows gated {Pj['n_rows_sector127_gated']} (of {Pj['n_rows_gated(validated, not truncation-affected)']} gated rows, {Pj['n_rows_total']} in all); worst pair digit {worst_pair} d; "
          f"worst vs the reference at dps {hi} {q[f'worst_vs_reference_dps{hi}_d']} d, at dps {lo} {q[f'worst_vs_reference_dps{lo}_d']} d; quoted (min of pair and the higher-dps agreement) {q['worst_quoted_d']} d; "
          f"{Pj['alias_vs_boundary_verdict']}")
    print(f"  the strict full-string gate over every gated row (gate_strings): {Pj['gate_strings_overall']} (as in the record: the 140-digit reference strings are never matched in full at these precisions; informational)")
    print(f"  pair bar {bar}: {'PASS' if ok else 'FAIL'}")
    vs = None
    key = f"{lo}/{hi}"
    if key in rec_leg["pairs"]:
        R = rec_leg["pairs"][key]
        same_loss = all(loss[o][k] == R["per_order_loss_table"][o][k] for o in loss for k in loss[o]) and set(loss) == set(R["per_order_loss_table"])
        vs = {"record_worst_pair_d": R["quoted_sector127"]["worst_pair_d"], "this_worst_pair_d": worst_pair, "record_worst_quoted_d": R["quoted_sector127"]["worst_quoted_d"], "this_worst_quoted_d": q["worst_quoted_d"],
              "loss_table_identical": same_loss, "record_n_rows_sector127_gated": R["n_rows_sector127_gated"], "this_n_rows_sector127_gated": Pj["n_rows_sector127_gated"], "record_verdict": R["alias_vs_boundary_verdict"]}
        print(f"  vs the record's pair {key}: worst pair {R['quoted_sector127']['worst_pair_d']} d (record) vs {worst_pair} d (this run); quoted {R['quoted_sector127']['worst_quoted_d']} vs {q['worst_quoted_d']}; "
              f"per-order loss table identical: {same_loss}; sector-127 rows gated {R['n_rows_sector127_gated']} vs {Pj['n_rows_sector127_gated']}")
    return {"leg": leg, "dps_pair": [lo, hi], "bar": bar, "bar_key": bar_key, "worst_pair_d": worst_pair, "worst_quoted_d": q["worst_quoted_d"], "pass": ok, "post": os.path.basename(out), "post_sha256": sha256_file(out),
            "per_order_loss_table": loss, "alias_vs_boundary_verdict": Pj["alias_vs_boundary_verdict"], "vs_record": vs}


def mutate_points(points_src, points_dst, target, master_nu, order, digit_index=20):
    """the planted control: a copy of the reference set with ONE digit of one reference string changed -- the real part of the
    coefficient of eps^order of the first sector-127 master at the target point, its digit_index-th significant digit + 1 mod 10."""
    if os.path.exists(points_dst):
        shutil.rmtree(points_dst)
    shutil.copytree(points_src, points_dst)
    p = os.path.join(points_dst, target, "accepted.tsv")
    key = ",".join(str(x) for x in master_nu)
    lines = open(p).read().split("\n")
    hit = None
    for k, ln in enumerate(lines):
        parts = ln.split("\t")
        if len(parts) >= 6 and parts[0] == key and int(parts[1]) == order:
            s = parts[2]
            digits_pos = [i for i, c in enumerate(s) if c.isdigit()]
            # the digit_index-th significant digit (leading zeros are not significant)
            sig = [i for i in digits_pos if s[:i].lstrip("-0.") != "" or s[i] != "0"]
            i = sig[digit_index - 1]
            new = s[:i] + str((int(s[i]) + 1) % 10) + s[i + 1:]
            hit = (k, s[i], new[i], i, s[:i + 3])
            parts[2] = new
            lines[k] = "\t".join(parts)
            break
    assert hit is not None
    open(p, "w").write("\n".join(lines))
    return hit


def main():
    ap = argparse.ArgumentParser(
        description="gg -> Z gamma with the exact top mass: the sector-127 t-cone (72 masters) transported between the points of an independent reference set "
                    "and gated at the target on the six sector-127 masters, order by order; the two-precision pair and per-order loss table.  A leg is a long "
                    "computation (minutes to hours), checkpointed after every sub-node and resumed from --workdir.",
        epilog="measured walls (GNU time wall clock, one process, nice 10, a shared 96-core host at loadavg ~130-150): "
               + ("; ".join(f"{k}: {v}" for k, v in WALLS.items()) if WALLS else "(none measured yet)")
               + ".  Exit codes: 0 PASS, 1 FAIL, 2 usage, 3 REFUSED by name, 4 pinned file MISSING, 5 the worker did not finish, 6 --mutate not caught.")
    ap.add_argument("--leg", default=None, choices=LEGS, help="which leg (default: the cheapest leg at the lowest documented precision, by the record's walls)")
    ap.add_argument("--dps", type=int, default=30, choices=PRECISIONS, help="working precision of the transport (default 30 = the lowest documented precision)")
    ap.add_argument("--pair", default=None, metavar="LO,HI", help="the pair/loss table from TRANSPORT_<leg>_dps<LO>.json and _dps<HI>.json already in --workdir (no transport is run)")
    ap.add_argument("--check", action="store_true", help="the two-precision form: the leg at --dps and at the next documented precision, then the pair")
    ap.add_argument("--mutate", action="store_true", help="the planted control: one reference digit changed on a copy of the reference set; the gate must FAIL by name (rc 1)")
    ap.add_argument("--selftest", action="store_true", help="the worker's own 2 x 2 exact transport + checkpoint pack/resume round trip (seconds)")
    ap.add_argument("--show-command", action="store_true", help="print the worker line of record for the requested tier and exit")
    ap.add_argument("--max-seg", default=None, metavar="P/Q", help="sub-node length in t (the checkpoint cadence); default = the record's cadence for the leg")
    ap.add_argument("--orders", default=None, metavar="LO,HI", help="the eps window of the transport: absent = the record's own window (eps^-3 .. eps^4); -3,6 = the rebuilt window "
                    "(eps^-3 .. eps^6: eps^3 and eps^4 enter the gate, eps^5 and eps^6 are truncation-affected and excluded) read from the record's orders_windows block; the "
                    "window's checkpoints, worker logs and results live in <workdir>/orders_LO_HI/; a window with no record is refused (rc 2)")
    ap.add_argument("--workdir", default=None, metavar="DIR", help="where checkpoints, heartbeats, worker logs and results live (default: zgamma-s127-work/ under the current directory)")
    ap.add_argument("--out", default=None, metavar="JSON", help="write the run receipt here (refused up front if the file exists)")
    argv = sys.argv[1:]
    if "--orders" in argv and argv.index("--orders") + 1 < len(argv):
        i = argv.index("--orders")
        argv[i:i + 2] = [f"--orders={argv[i + 1]}"]   # '--orders -3,6': the value's leading '-' would read as a flag
    args = ap.parse_args(argv)
    try:
        sys.stdout.reconfigure(line_buffering=True)
    except AttributeError:
        pass
    if args.out and os.path.exists(args.out):
        die(RC_USAGE, f"zgamma-s127-evaluate: --out {args.out} exists; nothing is overwritten and nothing was computed")
    if sum(bool(x) for x in (args.pair, args.check, args.mutate, args.selftest)) > 1:
        ap.error("--pair, --check, --mutate and --selftest are separate tiers")
    orders = None
    if args.orders:
        try:
            lo_o, hi_o = (int(x) for x in args.orders.split(","))
        except ValueError:
            ap.error("--orders LO,HI (two integers, e.g. -3,6)")
        if lo_o >= hi_o:
            ap.error("--orders LO,HI: LO < HI")
        orders = (lo_o, hi_o)
    t_all = time.time()
    stamp0 = utc()
    npins = check_pins()
    legs = json.load(open(os.path.join(VENDOR, "legs.json")))
    rec = json.load(open(os.path.join(VENDOR, "record.json")))
    cheap = rec["cheapest_leg_at_dps30"]
    leg = args.leg or cheap["leg"]
    workdir = os.path.abspath(args.workdir or os.path.join(os.getcwd(), "zgamma-s127-work"))
    os.makedirs(workdir, exist_ok=True)
    mode = "selftest" if args.selftest else "pair" if args.pair else "check" if args.check else "mutate" if args.mutate else "leg"
    print(f"[mode] sector-127 t-cone: {mode}; leg {leg}{' (the default: the smallest recorded wall at dps 30, ' + str(cheap['wall_s']) + ' s of ' + ', '.join(k + ' ' + str(v) for k, v in cheap['walls_s'].items()) + ')' if args.leg is None else ''}; dps {args.dps}"
          + (f"; orders {orders[0]}..{orders[1]}" if orders else ""))
    print(f"[pins] {npins} shipped files verified by sha256")
    print(f"[workdir] {workdir}")
    rec_legs, wdir, Wb = window(rec, workdir, orders)
    if orders:
        print(f"[window] orders {orders[0]}..{orders[1]} (the record's window block: gated orders eps^{Wb['gated_orders'][0]} .. eps^{Wb['gated_orders'][1]}; truncation-affected "
              f"{', '.join('eps^' + str(o) for o in Wb['truncation_affected_orders'])}, excluded): the window's checkpoints, heartbeats, worker logs and results live in {wdir}")
    if args.show_command:
        L = legs["legs"][leg]
        seg = args.max_seg or L["max_seg"]
        cmd = worker_cmd(leg, L, args.dps, wdir, seg, os.path.join(wdir, f"ckpt_{leg}_dps{args.dps}.json"), wdir, f"{leg}_dps{args.dps}", orders)
        print(f"[command] {show_cmd(cmd)}")
        print(f"[record]  {L['worker_line']}" + (f" --orders={orders[0]},{orders[1]}" if orders else ""))
        sys.exit(0)
    results, pairs, verdict, rc, planted = [], [], None, 0, None
    if args.selftest:
        cmd = [sys.executable, os.path.join(VENDOR, "s127_leg_worker.py"), "--selftest"]
        env = dict(os.environ)
        env["PYTHONDONTWRITEBYTECODE"] = "1"
        env["S127_SELFTEST_DIR"] = workdir
        print(f"  [worker] {show_cmd(cmd)}")
        r = subprocess.run(cmd, capture_output=True, text=True, cwd=workdir, env=env)
        for ln in (r.stdout + r.stderr).strip().split("\n"):
            print(f"  [worker] {ln}")
        ok = r.returncode == 0 and "PASS" in r.stdout and "FAIL" not in r.stdout
        verdict = "PASS" if ok else "FAIL"
        rc = 0 if ok else RC_FAIL
        results.append({"selftest_rc": r.returncode, "pass": ok})
    elif args.pair:
        try:
            lo, hi = (int(x) for x in args.pair.split(","))
        except ValueError:
            ap.error("--pair LO,HI (two precisions, e.g. 45,60)")
        if lo >= hi or lo not in PRECISIONS or hi not in PRECISIONS:
            ap.error(f"--pair: the precisions must be two of {PRECISIONS}, increasing")
        pr = run_pair(leg, lo, hi, rec, workdir, orders)
        pairs.append(pr)
        verdict = "PASS" if pr["pass"] else "FAIL"
        rc = 0 if pr["pass"] else RC_FAIL
    elif args.mutate:
        L = legs["legs"][leg]
        rec_leg = rec_legs[leg]
        bar, bar_dps = bar_for(rec_leg, args.dps)
        if bar is None:
            die(RC_USAGE, f"zgamma-s127-evaluate REFUSED: no record at dps {args.dps} for leg {leg} in the orders window {orders[0]},{orders[1]} "
                          f"(its documented precisions: {', '.join(sorted(rec_leg['bars'], key=int))}); nothing was computed")
        label = f"{leg}_dps{args.dps}"
        ckpt = os.path.join(wdir, f"ckpt_{label}.json")
        done = False
        if os.path.exists(ckpt):
            try:
                done = json.load(open(ckpt)).get("status") == "DONE"
            except Exception:
                done = False
        if not done:
            print(f"\n[mutate] no finished checkpoint for {label} in --workdir: the transport runs first (the control then re-gates its state)")
            results.append(evaluate_leg(leg, args.dps, legs, rec, workdir, max_seg=args.max_seg, quiet_rows=True, orders=orders))
        cone = json.load(open(os.path.join(VENDOR, "cone", "A_t127_s-1_4.json")))
        master = cone["cone_nu"][cone["S127"][0]]
        pdst = os.path.join(wdir, f"points_mutated_{label}")
        hit = mutate_points(os.path.join(VENDOR, "points"), pdst, L["to"], master, 0)
        planted = {"target": L["to"], "master": master, "order": 0, "line": hit[0], "digit_from": hit[1], "digit_to": hit[2], "char_index": hit[3], "prefix": hit[4]}
        print(f"\n[mutate] MUTATION CONTROL on leg {leg} at dps {args.dps}: on a COPY of the reference set, the coefficient of eps^0 of the sector-127 master {master} at {L['to']} "
              f"has its 20th significant digit changed '{hit[1]}' -> '{hit[2]}' (a ~1e-20 relative change of one reference string; line {hit[0] + 1} of the copy); expected: the gate FAILS by name")
        mck = os.path.join(wdir, f"ckpt_{label}_mutated.json")
        shutil.copy2(ckpt, mck)
        mout = os.path.join(wdir, f"mutated_{label}")
        os.makedirs(mout, exist_ok=True)
        print(f"  the finished checkpoint {os.path.basename(ckpt)} is copied to {os.path.basename(mck)}; the worker resumes at its last sub-node (nothing to transport) and re-gates the state against the copy")
        cmd = worker_cmd(leg, L, args.dps, wdir, args.max_seg or L["max_seg"], mck, mout, label, orders)
        rc_w, wall, last = run_worker(cmd, wdir, label, None, env_extra={"ZGAMMA_S127_POINTS": pdst}, tag="_mutated")
        out = os.path.join(mout, f"TRANSPORT_{label}.json")
        if rc_w != 0 or not os.path.exists(out):
            die(RC_WORKER, f"zgamma-s127-evaluate WORKER DID NOT FINISH (mutation control): rc {rc_w}; last line: {last!r}")
        T = json.load(open(out))
        ok, worst, _ = gate_transport(T, leg, args.dps, rec_leg, bar, bar_dps)
        rows = s127_rows(T)
        hit_row = rows[str(cone["S127"][0])]["per_order"]["0"]["digits"]
        caught = (not ok) and hit_row < bar
        verdict = (f"MUTATION CAUGHT (the gate FAILS by name: the mutated pair {master} | eps^0 reads {hit_row} d, the worst {worst:.2f} d < bar {bar})" if caught
                   else f"MUTATION NOT CAUGHT (a defect of the control: worst {worst:.2f} d vs bar {bar})")
        rc = RC_FAIL if caught else RC_NOTCAUGHT
        results.append({"leg": leg, "dps": args.dps, "bar": bar, "worst": worst, "mutated_pair_digits": hit_row, "caught": caught, "planted": planted, "subprocess_wall_s": wall})
    else:
        r1 = evaluate_leg(leg, args.dps, legs, rec, workdir, max_seg=args.max_seg, orders=orders)
        results.append(r1)
        if args.check:
            nxt = [d for d in PRECISIONS if d > args.dps]
            if not nxt:
                die(RC_USAGE, "zgamma-s127-evaluate --check: no documented precision above 60")
            r2 = evaluate_leg(leg, nxt[0], legs, rec, workdir, max_seg=args.max_seg, quiet_rows=True, orders=orders)
            results.append(r2)
            pairs.append(run_pair(leg, args.dps, nxt[0], rec, workdir, orders))
        n_fail = sum(0 if r["pass"] else 1 for r in results) + sum(0 if p["pass"] else 1 for p in pairs)
        verdict = "PASS" if n_fail == 0 else "FAIL"
        rc = 0 if n_fail == 0 else RC_FAIL
    wall = round(time.time() - t_all, 1)
    print(f"\nVERDICT {verdict}: " + "; ".join(f"{r['leg']} dps {r['dps']}: worst {r['worst']:.2f} d vs bar {r['bar']}" for r in results if "worst" in r)
          + ("; " + "; ".join(f"pair {p['dps_pair'][0]}/{p['dps_pair'][1]}: worst pair {p['worst_pair_d']} d vs bar {p['bar']}" for p in pairs) if pairs else "")
          + (f"; selftest rc {results[0]['selftest_rc']}" if args.selftest else "") + f"; total wall {wall} s")
    if args.out:
        recp = {"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": {"leg": leg, "dps": args.dps, "pair": args.pair, "check": args.check, "mutate": args.mutate, "selftest": args.selftest, "max_seg": args.max_seg},
                "workdir": os.path.basename(workdir), "results": results, "pairs": pairs, "verdict": verdict, "rc": rc}
        if orders:
            recp["args"]["orders"] = list(orders)
            recp["orders_window"] = {"orders": list(orders), "workdir": os.path.join(os.path.basename(workdir), os.path.basename(wdir))}
        fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
        with os.fdopen(fd, "w") as f:
            json.dump(recp, f, indent=1)
        print(f"[written] {os.path.basename(args.out)}")
    sys.exit(rc)


if __name__ == "__main__":
    main()
