"""PF-002 stationarity architecture study, version 1.

Virtual lab only. Compares four acquisition architectures under separated
nuisance classes, with conservative bounds, adversarial witnesses through the
committed channels and fresh-seed checks. All parameters come from the protocol
twin. No physical calibration, hardware capability or propulsion result is
claimed, and a failed certificate is not a statement of impossibility.
"""

from dataclasses import dataclass, replace
import hashlib
from itertools import product
import json
import math
from pathlib import Path
import platform
import random
import sys
import time
import unicodedata

from coupled_differential_optical_v2 import (
    DETECTOR, PRIMARY, REFERENCE, SOURCE, map_interval)
from differential_instrument import acquire as acquire_channels
from optical_driver import predict
import pf002_stationarity_bounds_v1 as bounds
import pf002_stationarity_oracle_v1 as oracle
from trial_detector import acquire_trial, analyse_trial
from virtual_instruments import observe

ROOT = Path(__file__).resolve().parent
PROTOCOL_FILE = "pf002-stationarity-v1-protocol.json"
ENVIRONMENT = "Virtual lab - simulated experiment"
STRUCTURE_DIGEST = ("sha256:d913afd39c052fe80ed83f4cb26ddc48"
                    "7bc6d94f060067c5568d9097b957b711")
IMPLEMENTATION = (
    "pf002_stationarity_v1.py", "pf002_stationarity_bounds_v1.py",
    "pf002_stationarity_oracle_v1.py", "pf002_stationarity_deadline_v1.py",
    "PF002_STATIONARITY_V1.md",
    PROTOCOL_FILE, "pf002_robustness_deadline_v1.py",
    "coupled_differential_optical_v2.py", "differential_instrument.py",
    "trial_detector.py", "detector_qualification.py",
    "detector_stability.py", "virtual_instruments.py", "recoil_budget.py",
    "optical_driver.py", "optical_reference.py",
)


class OperationalFailure(Exception):
    """A required reading or decision does not exist."""


def _unique(pairs):
    keys = [key for key, _ in pairs]
    if len(keys) != len(set(keys)):
        raise ValueError("duplicate key in protocol")
    return dict(pairs)


def _reject_constant(token):
    raise ValueError(f"non-finite number in protocol: {token}")


def key_paths(value, prefix=""):
    """Every key path, so an unknown or missing key at any level changes it."""
    paths = set()
    if isinstance(value, dict):
        for key, item in value.items():
            paths.add(f"{prefix}/{key}")
            paths |= key_paths(item, f"{prefix}/{key}")
    elif isinstance(value, list):
        for item in value:
            paths |= key_paths(item, f"{prefix}[]")
    return paths


def _depth(value):
    if isinstance(value, dict):
        return 1+max((_depth(item) for item in value.values()), default=0)
    if isinstance(value, list):
        return 1+max((_depth(item) for item in value), default=0)
    return 0


def _strings(value):
    if isinstance(value, str):
        yield value
    elif isinstance(value, dict):
        for key, item in value.items():
            yield key
            yield from _strings(item)
    elif isinstance(value, list):
        for item in value:
            yield from _strings(item)


def structure_digest(protocol):
    text = "\n".join(sorted(key_paths(protocol))).encode("ascii")
    return "sha256:"+hashlib.sha256(text).hexdigest()


def validate_protocol(data):
    """Strict parse and cross-checks. Any failure refuses execution."""
    limit = 1048576
    if len(data) > limit:
        raise ValueError("protocol exceeds 1 MiB")
    protocol = json.loads(data.decode("utf-8"), object_pairs_hook=_unique,
                          parse_constant=_reject_constant)
    if any(not unicodedata.is_normalized("NFC", s) for s in _strings(protocol)):
        raise ValueError("protocol text is not NFC")
    rules = protocol["validation"]
    if _depth(protocol) > rules["maximum_json_depth"]:
        raise ValueError("protocol nesting too deep")
    if structure_digest(protocol) != STRUCTURE_DIGEST:
        raise ValueError("protocol has unknown or missing keys")
    if protocol["configuration_count"] != (
            len(protocol["architectures"])*len(protocol["scenarios"])
            + protocol["dose_rows"]["count"]):
        raise ValueError("configuration count mismatch")
    for cohort in ("confirmatory", "exploratory"):
        low, high = protocol[cohort]["seeds"]
        if high-low+1 != protocol[cohort]["seed_count"]:
            raise ValueError("seed range mismatch")
    total = protocol["timing"]["samples_total"]
    for name, arch in protocol["architectures"].items():
        size = arch["dwell_samples"]
        if arch["dwells"]*size != total or arch["dwells"] % 2:
            raise ValueError(f"unequal label time: {name}")
        for key in ("late_window_samples", "early_window_samples"):
            if not 1 <= arch[key][0] <= arch[key][1] <= size:
                raise ValueError(f"window outside dwell: {name}")
    sweeps = protocol["exploratory"]["envelope_only_sweeps"]
    count = sum(len(sweeps[key]) for key in (
        "pilot_amplitude_newtons", "pilot_frequency_hertz",
        "pilot_coupling_bound_fraction", "dwell_seconds",
        "blind_level_fraction", "structural_allowance_scale"))
    if count > sweeps["maximum_evaluations"]:
        raise ValueError("sweep cap exceeded")
    declared = protocol["parameter_bounds"]
    pilot = protocol["pilot"]
    for value in [pilot["primary_amplitude_newtons"],
                  *pilot["dose_row_amplitudes_newtons"]]:
        if not declared["pilot_amplitude_newtons"][0] <= value <= (
                declared["pilot_amplitude_newtons"][1]):
            raise ValueError("pilot amplitude out of bounds")
    if not declared["pilot_frequency_hertz"][0] <= pilot["frequency_hertz"] <= (
            declared["pilot_frequency_hertz"][1]):
        raise ValueError("pilot frequency out of bounds")
    if protocol["required_margin_newtons"] != 1e-12:
        raise ValueError("required margin is fixed")
    return protocol


def load_protocol(path=ROOT/PROTOCOL_FILE):
    return validate_protocol(Path(path).read_bytes())


def check_runtime(protocol, identity=None):
    """Retained records exist only for the declared runtime identity."""
    declared = protocol["runtime"]
    actual = identity or {
        "python_implementation": platform.python_implementation(),
        "python_version": platform.python_version(),
        "machine": platform.machine(), "system": platform.system(),
        "byteorder": sys.byteorder,
        "float_mantissa_bits": sys.float_info.mant_dig}
    for key, value in actual.items():
        if declared[key] != value:
            raise ValueError(f"runtime identity mismatch: {key}")
    return actual


PROTOCOL = load_protocol()
BASE = PROTOCOL["retained_baseline"]
PILOT = PROTOCOL["pilot"]
LEVELS = PROTOCOL["nuisance_levels"]
TIMING = PROTOCOL["timing"]
COVER = PROTOCOL["continuous_parameter_coverage"]
GAP = COVER["enclosure_gap"]
SEARCH = PROTOCOL["witness_search"]
FAILS = PROTOCOL["failure_thresholds"]
STEP = TIMING["sample_step_seconds"]
SAMPLES = TIMING["samples_total"]
TOTAL = TIMING["total_elapsed_seconds"]
HOLD_SAMPLES = 10
REQUIRED = PROTOCOL["required_margin_newtons"]
STRUCTURAL = PROTOCOL["structural_allowance_per_phase_newtons"]
FLIP = PROTOCOL["orientation_flip_gain_bound"]
NUMERIC = PROTOCOL["numerical_allowance_newtons"]
BAND = PROTOCOL["vibration_band_hertz"]
COMMON = BASE["common_force_newtons"]
WEIGHT = BASE["weight"]
LEAK = BASE["leakage"]
COUPLING = BASE["reference_common_coupling"]
HEAT_COUPLING = BASE["reference_heat_coupling"]
QUARTER = math.pi/2
PHASE_POINTS = PROTOCOL["optical_envelope"]["phase_lattice_points"]
FEED_POINTS = PROTOCOL["optical_envelope"]["feed_lattice_points"]
WORST_AGE = PROTOCOL["optical_envelope"]["worst_age_seconds"]
WITHIN_POINTS = PROTOCOL["phase_feed"]["within_dwell_lattice_points"]
LAG_KNOWLEDGE = PROTOCOL["lag_decision"]["response_knowledge_fraction"]
if (BASE["reference_response_seconds"] != REFERENCE.response_seconds
        or BASE["reference_thermal_seconds"] != REFERENCE.thermal_seconds):
    raise ValueError("protocol baseline differs from the committed channels")


@dataclass(frozen=True)
class Architecture:
    name: str
    dwells: int
    size: int
    late: tuple
    early: tuple
    pilot: bool
    additive: float
    rule: str


def architecture(name):
    item = PROTOCOL["architectures"][name]
    return Architecture(name, item["dwells"], item["dwell_samples"],
                        tuple(item["late_window_samples"]),
                        tuple(item["early_window_samples"]), item["pilot"],
                        item["detector_additive_error_watts"],
                        item["order_rule"])


ARCHITECTURES = tuple(architecture(name) for name in PROTOCOL["architectures"])


def by_prefix(prefix):
    return next(a for a in ARCHITECTURES if a.name.startswith(prefix))


def thue_morse(count):
    """A is sigma -1 and B is sigma +1, starting ABBA."""
    return [-(-1)**bin(i).count("1") for i in range(count)]


def permitted_orders(arch):
    if arch.rule.startswith("seeded_one_of_16"):
        return [tuple(s for pair in pattern for s in pair)
                for pattern in product(((1, -1), (-1, 1)), repeat=4)]
    base = thue_morse(arch.dwells)
    return [tuple(base), tuple(-s for s in base)]


def validate_order(arch, order):
    if len(order) != arch.dwells or sum(order) != 0:
        raise ValueError("sequence has unequal label time")
    if tuple(order) not in permitted_orders(arch):
        raise ValueError("sequence is not a declared order")
    return tuple(order)


def _level_set(name):
    return LEVELS[name]["primary_fraction"], LEVELS[name]["reference_fraction"]


def scenario_settings(name):
    item = PROTOCOL["scenarios"][name]
    classes = set(item["classes"])
    level = _level_set(item["level"]) if item.get("level") in (
        "retained", "candidate") else (0.0, 0.0)
    if "blind_label_correlated" in classes:
        key = item.get("blind_level", item.get("level"))
        blind = LEVELS["blind_levels_fraction"][key]
    else:
        blind = 0.0
    common = (LEVELS["common_force_label_bound_fraction"]
              if "common_force_label_correlated" in classes else 0.0)
    return {"name": name, "classes": classes, "s_p": level[0], "s_r": level[1],
            "blind": blind, "common": common}


def amplitude_factor(settings):
    table = PROTOCOL["amplitude_bounds"]["class_factors"]
    total = 0.0
    for name in settings["classes"]:
        if name in table:
            total += table[name]["numerator"]/table[name]["denominator"]
    return total


def window_step(settings):
    """Largest change of readout gain between adjacent hold blocks in a dwell.

    Slow: |dx| <= 0.025 and |d(x^2)| <= 0.05 per second, so 0.075*s. Rate:
    s/5. Within-window label: 2*s. Paths add without clipping.
    """
    classes = settings["classes"]
    factor = 0.0
    if "slow_drift" in classes:
        factor += 0.075
    if "bounded_rate" in classes:
        factor += LEVELS["slew_fraction_of_amplitude_per_second"]
    if "label_within_window" in classes:
        factor += 2.0
    return factor*settings["s_p"], factor*settings["s_r"]


_unit_cache = {}


def _unit(phase):
    if phase not in _unit_cache:
        source = predict(SOURCE["wavelength_m"], SOURCE["aperture_radius_m"],
                         SOURCE["separation_m"], phase, 1.0,
                         SOURCE["laser_conversion_efficiency"],
                         SOURCE["control_power_watts"])
        _unit_cache[phase] = (
            source["radiated_fraction_of_optical_feed"],
            source["outgoing_radiation_recoil_component_newtons_xyz"][0])
    return _unit_cache[phase]


def recoil(phase, feed):
    return feed*SOURCE["optical_feed_watts"]*_unit(phase)[1]


def source_heat(phase, feed):
    power = feed*SOURCE["optical_feed_watts"]
    return (power/SOURCE["laser_conversion_efficiency"]
            - power*_unit(phase)[0]+SOURCE["control_power_watts"])


_detector_cache = {}


def detector_interval(phase, power, end, additive):
    """Frozen detector. Only additive error carries the exposure mapping."""
    key = (phase, power, end, additive)
    if key not in _detector_cache:
        public, _ = acquire_trial(
            phase_radians=phase, escaping_power_watts=power, end_seconds=end,
            grid=DETECTOR["grid"], cone_degrees=DETECTOR["cone_degrees"],
            pointing_bound_degrees=DETECTOR["pointing_bound_degrees"],
            gain_bound=DETECTOR["gain_bound"],
            total_power_bound_watts=DETECTOR["total_power_bound_watts"],
            additive_error_watts=additive, gain_drift_per_second=1e-6,
            power_drift_watts_per_second=1e-6,
            wavelength_m=SOURCE["wavelength_m"],
            aperture_radius_m=SOURCE["aperture_radius_m"],
            separation_m=SOURCE["separation_m"])
        _detector_cache[key] = analyse_trial(public)
    return _detector_cache[key]


def lattice(centre, half, points):
    if half == 0:
        return [centre]
    return [centre+half*(2*k/(points-1)-1) for k in range(points)]


def within_lattice(half):
    if half == 0:
        return [0.0]
    span = (WITHIN_POINTS-1)//2
    return [half*m/span for m in range(-span, span+1)]


_window_cache = {}


def optical_window(additive, phase_jitter=None, feed_variation=None):
    """Numerical optical envelope, not a proof: a lattice with a remainder."""
    jitter = (BASE["phase_jitter_radians"] if phase_jitter is None
              else phase_jitter)
    variation = (BASE["feed_variation_fraction"] if feed_variation is None
                 else feed_variation)
    key = (additive, jitter, variation)
    if key in _window_cache:
        return _window_cache[key]
    positive = QUARTER if recoil(QUARTER, 1) > 0 else -QUARTER
    feeds = lattice(1.0, variation, FEED_POINTS)
    walk_phase = within_lattice(jitter)
    walk_feed = within_lattice(variation)

    def side(base):
        lows, highs = [], []
        for feed in feeds:
            row_low, row_high = [], []
            for phase in lattice(base, jitter, PHASE_POINTS):
                power = feed*SOURCE["optical_feed_watts"]*_unit(phase)[0]
                low, high = detector_interval(phase, power, WORST_AGE, additive)
                row_low.append(low)
                row_high.append(high)
            lows.append(row_low)
            highs.append(row_high)
        change = 0.0
        for table in (lows, highs):
            for row in table:
                for x, y in zip(row, row[1:]):
                    change = max(change, abs(x-y))
            for upper, lower in zip(table, table[1:]):
                for x, y in zip(upper, lower):
                    change = max(change, abs(x-y))
        return min(map(min, lows)), max(map(max, highs)), change

    p_low, p_high, p_change = side(positive)
    n_low, n_high, n_change = side(-positive)
    remainder = p_change+n_change
    walk, strengths, powers = 0.0, {}, []
    for base in (positive, -positive):
        values = []
        for phase, feed, psi, xi in product(
                lattice(base, jitter, PHASE_POINTS), feeds, walk_phase,
                walk_feed):
            actual = recoil(phase+psi, feed*(1+xi))
            walk = max(walk, abs(actual-recoil(phase, feed)))
            values.append(actual)
            powers.append(source_heat(phase+psi, feed*(1+xi)))
        strengths[base] = (min(values), max(values))
    result = {
        "optical_minimum_newtons": p_low-n_high-remainder,
        "optical_maximum_newtons": p_high-n_low+remainder,
        "walk_newtons": 2*walk,
        "signal_minimum_newtons": strengths[positive][0]-strengths[-positive][1],
        "signal_maximum_newtons": strengths[positive][1]-strengths[-positive][0],
        "heat_minimum_watts": min(powers),
        "heat_maximum_watts": max(powers),
    }
    _window_cache[key] = result
    return result


def nominal_contrast():
    return 2*abs(recoil(QUARTER, 1))


def phase_lock(phase):
    if abs(phase) < 1:
        return 0
    return 1 if recoil(math.copysign(QUARTER, phase), 1) > 0 else -1


def stream(*parts):
    text = "|".join(str(part) for part in parts).encode("ascii")
    return int.from_bytes(hashlib.sha256(text).digest()[:8], "big")


def run_channel(balance, force, heat):
    """Noiseless mechanical state: the committed cascade, stepped here."""
    a = -math.expm1(-STEP/balance.thermal_seconds)
    b = -math.expm1(-STEP/balance.response_seconds)
    thermal = mechanical = 0.0
    states = []
    for input_force, input_heat in zip(force, heat):
        thermal += a*(input_heat*balance.thermal_newtons_per_watt-thermal)
        mechanical += b*(input_force+thermal-mechanical)
        states.append(mechanical)
    return states


def window_indices(arch, window, dwell):
    return range(dwell*arch.size+window[0]-1, dwell*arch.size+window[1])


def window_times(arch, window, dwell=0):
    return [(k+1)*STEP for k in window_indices(arch, window, dwell)]


def hold_block(sample, offset):
    """Block index of zero-based sample; block m ends at reading offset+10m."""
    return (sample+HOLD_SAMPLES-offset)//HOLD_SAMPLES


def block_centre(block, offset):
    low = max(0.0, (offset+HOLD_SAMPLES*(block-1))*STEP)
    high = min(TOTAL, (offset+HOLD_SAMPLES*block)*STEP)
    return (low+high)/2


def block_values(offset, function):
    values = {}
    series = []
    for sample in range(SAMPLES):
        block = hold_block(sample, offset)
        if block not in values:
            values[block] = function(block)
        series.append(values[block])
    return series


def slow_path(a, b, offset):
    def value(block):
        x = 2*block_centre(block, offset)/TOTAL-1
        return a*x+b*(x*x-1/3)
    return block_values(offset, value)


def rate_path(rng, s, offset):
    slew = s*LEVELS["slew_fraction_of_amplitude_per_second"]
    state = {"value": rng.uniform(-s, s), "block": 0}

    def value(block):
        while state["block"] < block:
            step = rng.choice((-slew, 0.0, slew))
            state["value"] = max(-s, min(s, state["value"]+step))
            state["block"] += 1
        return state["value"]
    return block_values(offset, value)


def label_values(sigmas, bound, seed, rng):
    """Even seeds draw per dwell; odd seeds lock to the label at the bound."""
    if seed % 2 == 0:
        return [rng.uniform(-bound, bound) for _ in sigmas]
    sign = rng.choice((-1, 1))
    return [s*sign*bound for s in sigmas]


def within_window_path(arch, sigmas, s, sign, offset):
    series = []
    for sample in range(SAMPLES):
        block = hold_block(sample, offset)
        series.append(sigmas[sample//arch.size]*sign*s*(-1)**block)
    return series


def adversarial_offset(arch, omega=None):
    """Offset maximising nominal reference rectification, public model only."""
    omega = omega or 2*math.pi*PILOT["frequency_hertz"]
    drive = [math.sin(omega*(k+1)*STEP) for k in range(SAMPLES)]
    state = run_channel(replace(REFERENCE, thermal_newtons_per_watt=0.0), drive,
                        [0.0]*SAMPLES)
    best, chosen = -1.0, 0
    indices = list(window_indices(arch, arch.late, arch.dwells-1))
    for offset in range(HOLD_SAMPLES):
        total = abs(math.fsum((-1)**hold_block(k, offset)*state[k]
                              for k in indices))
        if total > best:
            best, chosen = total, offset
    return chosen


def draw(arch, scenario, dose, seed, control, orientation, cohort):
    """All random draws. Rows differ only by what the control itself injects.

    Controls and architectures share draws, except for the order bit, so a
    mimic and its recoil row meet the same nuisance realisation.
    """
    settings = scenario_settings(scenario)

    def rng(purpose, *extra):
        return random.Random(stream(
            "pf002-stationarity-v1", cohort, scenario, dose, seed, orientation,
            purpose, *extra))

    order_rng = rng("order", arch.name)
    orders = permitted_orders(arch)
    order = orders[order_rng.randrange(len(orders))]
    constants = rng("constants")
    dg, dw = BASE["calibration_knowledge"], BASE["weight_knowledge"]
    dl = BASE["leakage_knowledge"]
    draws = {
        "arch": arch, "settings": settings, "order": order,
        "control": control, "orientation": orientation,
        "gp": PRIMARY.calibration_fraction+constants.uniform(-dg, dg),
        "gr": REFERENCE.calibration_fraction+constants.uniform(-dg, dg),
        "w": WEIGHT+constants.uniform(-dw, dw),
        "leak": max(0.0, LEAK+constants.uniform(-dl, dl)),
        "vibration": constants.uniform(*BAND),
    }
    nuisance = rng("nuisance")
    if "label_within_window" in settings["classes"]:
        offset = adversarial_offset(arch)
    else:
        offset = nuisance.randrange(HOLD_SAMPLES)
    draws["offset"] = offset
    e = {"p": [0.0]*SAMPLES, "r": [0.0]*SAMPLES}
    for channel, s in (("p", settings["s_p"]), ("r", settings["s_r"])):
        if "slow_drift" in settings["classes"]:
            path = slow_path(nuisance.uniform(-s, s), nuisance.uniform(-s, s),
                             offset)
            e[channel] = [x+y for x, y in zip(e[channel], path)]
        if "bounded_rate" in settings["classes"]:
            path = rate_path(nuisance, s, offset)
            e[channel] = [x+y for x, y in zip(e[channel], path)]
        if "label_correlated" in settings["classes"]:
            values = label_values(order, s, seed, nuisance)
            e[channel] = [x+values[k//arch.size]
                          for k, x in enumerate(e[channel])]
        if "label_within_window" in settings["classes"]:
            path = within_window_path(arch, order, s,
                                      nuisance.choice((-1, 1)), offset)
            e[channel] = [x+y for x, y in zip(e[channel], path)]
    draws["e_p"], draws["e_r"] = e["p"], e["r"]
    draws["blind"] = label_values(order, settings["blind"], seed, nuisance)
    draws["common"] = label_values(order, settings["common"], seed, nuisance)
    pilot = rng("pilot")
    low, high = PILOT["coupling_constant_interval"]
    draws["kappa"] = pilot.uniform(low, high)
    draws["a"] = label_values(order, PILOT["actuator_label_fraction_bound"],
                              seed, pilot)
    draws["k"] = label_values(order, PILOT["coupling_label_fraction_bound"],
                              seed, pilot)
    draws["tau"] = label_values(order, PILOT["timing_label_bound_seconds"],
                                seed, pilot)
    estimator = rng("estimator")
    knowledge = PILOT["response_time_estimator_knowledge_fraction"]
    draws["xi_p"] = estimator.uniform(-knowledge, knowledge)
    draws["xi_r"] = estimator.uniform(-knowledge, knowledge)
    optical = rng("optical")
    mapping = optical.choice((-1, 1))
    positive = QUARTER if recoil(QUARTER, 1) > 0 else -QUARTER
    jitter = BASE["phase_jitter_radians"]
    variation = BASE["feed_variation_fraction"]
    draws["mapping"] = mapping
    phases, feeds = [], []
    for sigma in order:
        base = 0.0 if control == "phase-null" else sigma*mapping*positive
        phases.append(optical.choice(lattice(base, jitter, PHASE_POINTS)))
        feeds.append(optical.choice(lattice(1.0, variation, FEED_POINTS)))
    draws["phases"], draws["feeds"] = phases, feeds
    walk = rng("phase_feed")
    span = (WITHIN_POINTS-1)//2
    state = {"m": walk.randint(-span, span), "q": walk.randint(-span, span),
             "block": 0}
    psi_values = within_lattice(jitter)
    xi_values = within_lattice(variation)

    def value(block):
        while state["block"] < block:
            state["m"] = max(-span, min(span, state["m"]+walk.choice((-1, 0, 1))))
            state["q"] = max(-span, min(span, state["q"]+walk.choice((-1, 0, 1))))
            state["block"] += 1
        return psi_values[state["m"]+span], xi_values[state["q"]+span]
    pairs = block_values(offset, value)
    draws["psi"] = [p for p, _ in pairs]
    draws["xi"] = [x for _, x in pairs]
    draws["noise_seed"] = rng("noise").randrange(2**32)
    return draws


def lag_scale(arch, locks, lag):
    """Force scale that matches late contrast to the instant impostor."""
    balance = replace(PRIMARY, thermal_newtons_per_watt=0.0)
    target = [locks[k//arch.size] for k in range(SAMPLES)]
    weight = -math.expm1(-STEP/lag)
    state = 0.0
    lagged = []
    for value in target:
        state += weight*(value-state)
        lagged.append(state)

    def contrast(force):
        states = run_channel(balance, force, [0.0]*SAMPLES)
        return math.fsum(
            locks[i]*math.fsum(states[k] for k in window_indices(
                arch, arch.late, i)) for i in range(arch.dwells))
    return contrast(target)/contrast(lagged)


def forces(draws, amplitude):
    """Generator side: every input and actual quantity, sample by sample."""
    arch, control = draws["arch"], draws["control"]
    orientation = draws["orientation"]
    size, order = arch.size, draws["order"]
    impostor = nominal_contrast()/2
    locks = [phase_lock(p) for p in draws["phases"]]
    lag = None
    if control == "impostor-source-fixed-lag-10s":
        lag = PROTOCOL["impostor_lag_seconds"][0]
    elif control == "impostor-source-fixed-lag-0p1s":
        lag = PROTOCOL["impostor_lag_seconds"][1]
    scale = lag_scale(arch, locks, lag) if lag else 1.0
    lag_weight = -math.expm1(-STEP/lag) if lag else 0.0
    lag_state = 0.0
    omega = 2*math.pi*PILOT["frequency_hertz"]
    signal, common, heat, pilot, kappa = [], [], [], [], []
    for k in range(SAMPLES):
        i = k//size
        phase = draws["phases"][i]+draws["psi"][k]
        feed = draws["feeds"][i]*(1+draws["xi"][k])
        if control in ("opposite-phase", "phase-null"):
            force = orientation*recoil(phase, feed)
        elif control in ("force-decoupled", "reference-path-label-mimic"):
            force = 0.0
        elif control == "impostor-lab-fixed-in-window":
            force = locks[i]*impostor
        elif control == "impostor-source-fixed-instant":
            force = orientation*locks[i]*impostor
        elif lag:
            lag_state += lag_weight*(orientation*locks[i]*impostor-lag_state)
            force = scale*lag_state
        elif control == "impostor-out-of-window":
            force = locks[i]*PROTOCOL["out_of_window_impostor_force_newtons"]
        else:
            raise ValueError("unsupported control")
        signal.append(force)
        common.append(COMMON*(1+draws["common"][i]))
        power = source_heat(phase, feed)
        if arch.pilot and amplitude:
            drive = amplitude*(1+draws["a"][i])*math.sin(
                omega*((k+1)*STEP+draws["tau"][i]))
            pilot.append(drive)
            kappa.append(draws["kappa"]*(1+draws["k"][i]))
            power += PILOT["actuator_heat_watts"]*(
                1+PILOT["actuator_heat_label_fraction_bound"]*order[i])
        else:
            pilot.append(0.0)
            kappa.append(1.0)
        heat.append(power)
    coupling = []
    for i in range(arch.dwells):
        value = COUPLING*(1+draws["blind"][i])
        if control == "reference-path-label-mimic":
            value += -orientation*locks[i]*impostor/(draws["w"]*COMMON)
        coupling.append(value)
    return {"signal": signal, "common": common, "heat": heat, "pilot": pilot,
            "kappa": kappa, "coupling": coupling}


def segments(arch, offset):
    edges = {0, SAMPLES}
    edges |= {i*arch.size for i in range(arch.dwells)}
    edges |= {k for k in range(offset, SAMPLES, HOLD_SAMPLES)}
    ordered = sorted(edges)
    return list(zip(ordered, ordered[1:]))


def injection(pilot, kappa, coupling, leak):
    """Generator-side transform. c and leak never reach the estimator."""
    separation = coupling-leak
    if separation < PROTOCOL["generative_model"]["minimum_c_minus_leak"]:
        raise OperationalFailure("input transform ill conditioned")
    gain = (kappa-leak)/separation
    if abs(gain) > PROTOCOL["generative_model"]["maximum_transform_gain"]:
        raise OperationalFailure("input transform gain out of bounds")
    return gain*pilot, (1-gain)*pilot


def _with_noise(readings, path):
    return [y+n for y, n in zip(readings, path)]


def read_channels(draws, inputs, *, noise_path=None):
    """Primary formulation: the committed acquire, one call per segment."""
    arch = draws["arch"]
    quiet = noise_path is not None
    primary = replace(PRIMARY, vibration_hertz=draws["vibration"])
    reference = replace(REFERENCE, vibration_hertz=draws["vibration"])
    if quiet:
        primary = replace(primary, noise_bound_newtons=0.0)
        reference = replace(reference, noise_bound_newtons=0.0)
    rng = random.Random(draws["noise_seed"])
    state, y_p, y_r = None, [], []
    leak = draws["leak"]
    for start, stop in segments(arch, draws["offset"]):
        i = start//arch.size
        coupling = inputs["coupling"][i]
        signal, common = [], []
        for k in range(start, stop):
            x, y = injection(inputs["pilot"][k], inputs["kappa"][k], coupling,
                             leak)
            signal.append(inputs["signal"][k]+y)
            common.append(inputs["common"][k]+x)
        p = replace(primary, calibration_fraction=draws["gp"]+draws["e_p"][start])
        r = replace(reference,
                    calibration_fraction=draws["gr"]+draws["e_r"][start])
        result = acquire_channels(
            p, r, signal, common, inputs["heat"][start:stop], STEP,
            rng.randrange(2**32), weight=draws["w"], leakage=leak,
            reference_common_coupling=coupling,
            reference_heat_coupling=HEAT_COUPLING, initial=state)
        state = result["continuation"]
        y_p += result["primary_readings_newtons"]
        y_r += result["reference_readings_newtons"]
    if quiet:
        y_p = _with_noise(y_p, noise_path[0])
        y_r = _with_noise(y_r, noise_path[1])
    return y_p, y_r


def read_direct(draws, inputs):
    """Comparison formulation: force lists through observe, no transform."""
    arch = draws["arch"]
    states = [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)]
    output = ([], [])
    for start, stop in segments(arch, draws["offset"]):
        i = start//arch.size
        coupling = inputs["coupling"][i]
        rows = range(start, stop)
        force_p = [inputs["signal"][k]+inputs["common"][k]+inputs["pilot"][k]
                   for k in rows]
        force_r = [draws["leak"]*inputs["signal"][k]
                   + coupling*inputs["common"][k]
                   + inputs["kappa"][k]*inputs["pilot"][k] for k in rows]
        heat_p = inputs["heat"][start:stop]
        heat_r = [HEAT_COUPLING*h for h in heat_p]
        pairs = ((replace(PRIMARY, vibration_hertz=draws["vibration"],
                          noise_bound_newtons=0.0,
                          calibration_fraction=draws["gp"]+draws["e_p"][start]),
                  force_p, heat_p),
                 (replace(REFERENCE, vibration_hertz=draws["vibration"],
                          noise_bound_newtons=0.0,
                          calibration_fraction=draws["gr"]+draws["e_r"][start]),
                  force_r, heat_r))
        for index, (balance, force, heat) in enumerate(pairs):
            mechanical, thermal, elapsed = states[index]
            result = observe(balance, force, heat, STEP, 0,
                             initial_force_newtons=mechanical,
                             initial_thermal_newtons=thermal,
                             start_seconds=elapsed)
            output[index].extend(result["readings_newtons"])
            end = result["continuation_state"]
            states[index] = (end["mechanical_newtons"], end["thermal_newtons"],
                             end["elapsed_seconds"])
    return output


def estimate(y_p, y_r, order, arch, window, *, amplitude=None, omega=None,
             tau_hat=None, weight):
    """Offline estimator. Its inputs are the protocol's estimator_inputs only."""
    saturation = FAILS["reading_saturation_newtons"]
    for value in y_p+y_r:
        if not math.isfinite(value):
            raise OperationalFailure("non-finite reading")
        if abs(value) > saturation:
            raise OperationalFailure("reading saturated")
    means_p, means_r, ratios = [], [], []
    count = window[1]-window[0]+1
    pilot = arch.pilot and amplitude
    if pilot:
        times = window_times(arch, window)
        u_p = bounds.point_weights(tau_hat[0], times, omega)
        u_r = bounds.point_weights(tau_hat[1], times, omega)
    for i in range(arch.dwells):
        indices = list(window_indices(arch, window, i))
        window_p = [y_p[k] for k in indices]
        window_r = [y_r[k] for k in indices]
        means_p.append(math.fsum(window_p)/count)
        means_r.append(math.fsum(window_r)/count)
        if pilot:
            top = math.fsum(u*y for u, y in zip(u_p, window_p))
            bottom = math.fsum(u*y for u, y in zip(u_r, window_r))
            floor = PILOT["projection_floor_fraction"]*amplitude
            ceiling = PILOT["projection_ceiling_fraction"]*amplitude
            if not (floor <= top <= ceiling and floor <= bottom <= ceiling):
                raise OperationalFailure("pilot projection out of bounds")
            ratio = top/bottom
            low, high = PILOT["ratio_interval"]
            if not low <= ratio <= high:
                raise OperationalFailure("pilot ratio out of bounds")
            ratios.append(ratio)
    session = math.fsum(ratios)/len(ratios) if ratios else 1.0
    half = arch.dwells//2
    contrast = reference = 0.0
    values = []
    for i, sigma in enumerate(order):
        factor = ratios[i]/session if ratios else 1.0
        value = means_p[i]-weight*factor*means_r[i]
        values.append(sigma*value)
        reference += sigma*means_r[i]/half
    contrast = math.fsum(values)/half
    return {"contrast": contrast, "reference_contrast": reference,
            "ratios": ratios}


def pilot_amplitude(dose):
    if dose == 0:
        return PILOT["primary_amplitude_newtons"]
    return PILOT["dose_row_amplitudes_newtons"][dose-1]


def _mean(values, indices):
    indices = list(indices)
    return math.fsum(values[k] for k in indices)/len(indices)


def _unit_forces(arch, window):
    """Window mean response to unit force held in dwell j, one row per dwell i."""
    table = {"p": [], "r": []}
    for name, balance in (("p", PRIMARY), ("r", REFERENCE)):
        quiet = replace(balance, thermal_newtons_per_watt=0.0)
        columns = []
        for j in range(arch.dwells):
            drive = [1.0 if k//arch.size == j else 0.0 for k in range(SAMPLES)]
            states = run_channel(quiet, drive, [0.0]*SAMPLES)
            columns.append([_mean(states, window_indices(arch, window, i))
                            for i in range(arch.dwells)])
        table[name] = [[columns[j][i] for j in range(arch.dwells)]
                       for i in range(arch.dwells)]
    return table


def _heat_response(balance, arch, window):
    """Window mean response to unit heat at each sample, per dwell."""
    impulse = [1.0]+[0.0]*(SAMPLES-1)
    states = run_channel(balance, [0.0]*SAMPLES, impulse)
    cumulative = [0.0]
    for value in states:
        cumulative.append(cumulative[-1]+value)
    count = window[1]-window[0]+1
    rows = []
    for i in range(arch.dwells):
        indices = window_indices(arch, window, i)
        first, last = indices[0], indices[-1]
        rows.append([(cumulative[max(0, last-j+1)]
                      - cumulative[max(0, first-j)])/count
                     for j in range(SAMPLES)])
    return rows


def _rate_unit(coefficients):
    """Exact maximum over the slew polytope for s = 1, section 6.1."""
    steps = round(2/LEVELS["slew_fraction_of_amplitude_per_second"])
    levels = [-1+2*j/steps for j in range(steps+1)]
    value = [coefficients[0]*x for x in levels]
    for c in coefficients[1:]:
        value = [c*x+max(value[max(0, j-1):j+2])
                 for j, x in enumerate(levels)]
    return max(value)


def _sequence_terms(arch, window, order, states_p, states_r):
    """Per-unit-s drift and rate terms over all hold offsets.

    Gain multiplies the state sample by sample, so each coefficient uses the
    state at its own sample. A product of means is not this sum.
    """
    half = arch.dwells//2
    best_drift = {"p": 0.0, "r": 0.0}
    best_rate = {"p": 0.0, "r": 0.0}
    for offset in range(HOLD_SAMPLES):
        for name, states in (("p", states_p), ("r", states_r)):
            x_terms, q_terms = [], []
            weights = {}
            for i, sigma in enumerate(order):
                indices = list(window_indices(arch, window, i))
                unit = sigma/(half*len(indices))
                for k in indices:
                    block = hold_block(k, offset)
                    x = 2*block_centre(block, offset)/TOTAL-1
                    x_terms.append(unit*x*states[k])
                    q_terms.append(unit*(x*x-1/3)*states[k])
                    weights[block] = weights.get(block, 0.0)+unit*states[k]
            best_drift[name] = max(best_drift[name],
                                   abs(math.fsum(x_terms))
                                   + abs(math.fsum(q_terms)))
            top = hold_block(SAMPLES-1, offset)
            series = [weights.get(b, 0.0) for b in range(top+1)]
            best_rate[name] = max(best_rate[name], _rate_unit(series))
    return best_drift, best_rate


_shared_cache = {}


def _shared(arch, window, heat_centre):
    key = (arch.name, window, heat_centre)
    if key in _shared_cache:
        return _shared_cache[key]
    common = [COMMON]*SAMPLES
    heat = [heat_centre]*SAMPLES
    states_p = run_channel(PRIMARY, common, heat)
    states_r = run_channel(
        REFERENCE, [COUPLING*c for c in common],
        [HEAT_COUPLING*h for h in heat])
    result = {
        "means_p": [_mean(states_p, window_indices(arch, window, i))
                    for i in range(arch.dwells)],
        "means_r": [_mean(states_r, window_indices(arch, window, i))
                    for i in range(arch.dwells)],
        "states_p": states_p, "states_r": states_r,
        "forces": _unit_forces(arch, window),
        "heat_p": _heat_response(PRIMARY, arch, window),
        "heat_r": _heat_response(REFERENCE, arch, window),
    }
    _shared_cache[key] = result
    return result


def _corners():
    dg, dw = BASE["calibration_knowledge"], BASE["weight_knowledge"]
    return tuple(product(
        (PRIMARY.calibration_fraction-dg, PRIMARY.calibration_fraction+dg),
        (REFERENCE.calibration_fraction-dg, REFERENCE.calibration_fraction+dg),
        (WEIGHT-dw, WEIGHT+dw)))


def _tail_time(arch, window, i):
    indices = window_indices(arch, window, i)
    return (indices[0]+indices[-1]+2)*STEP/2


_base_cache = {}


def _base_and_heat(arch, window, shared, corners, heat_radius):
    key = (arch.name, window, corners, heat_radius, id(shared))
    if key not in _base_cache:
        _base_cache[key] = _base_and_heat_terms(arch, window, shared, corners,
                                                heat_radius)
    return _base_cache[key]


def _base_and_heat_terms(arch, window, shared, corners, heat_radius):
    half = arch.dwells//2
    base_max = heat_max = rho = 0.0
    forces_p, forces_r = shared["forces"]["p"], shared["forces"]["r"]
    dl = BASE["leakage_knowledge"]
    for order in permitted_orders(arch):
        for gp, gr, w in corners:
            total = 0.0
            for i, sigma in enumerate(order):
                t = _tail_time(arch, window, i)
                total += sigma*(
                    (1+gp)*shared["means_p"][i]-w*(1+gr)*shared["means_r"][i]
                    + PRIMARY.offset_newtons-w*REFERENCE.offset_newtons
                    + (PRIMARY.drift_newtons_per_second
                       - w*REFERENCE.drift_newtons_per_second)*t)
            base_max = max(base_max, abs(total)/half)
            coefficient = math.fsum(
                abs(math.fsum(
                    sigma*((1+gp)*shared["heat_p"][i][j]
                           - w*(1+gr)*HEAT_COUPLING*shared["heat_r"][i][j])
                    for i, sigma in enumerate(order)))
                for j in range(0, SAMPLES))/half
            heat_max = max(heat_max, coefficient*heat_radius)
            for leak in (max(0.0, LEAK-dl), LEAK+dl):
                transfer = (1+gp)-w*leak*(1+gr)
                deviation = 0.0
                for j, sigma_j in enumerate(order):
                    c_force = math.fsum(sigma*(1+gp)*forces_p[i][j]
                                        for i, sigma in enumerate(order))/half
                    c_ref = math.fsum(-sigma*w*(1+gr)*forces_r[i][j]
                                      for i, sigma in enumerate(order))/half
                    deviation += abs(c_force+leak*c_ref
                                     - transfer*sigma_j/half)
                rho = max(rho, deviation/2)
    return base_max, heat_max, rho


def transfer_box(weights=None):
    dl = BASE["leakage_knowledge"]
    values = []
    for gp, gr, w in _corners():
        for chosen in (weights or (w,)):
            for leak in (max(0.0, LEAK-dl), LEAK+dl):
                values.append((1+gp)-chosen*leak*(1+gr))
    return [min(values), max(values)]


def _level(balance, gain, means, arch, window, extra=0.0):
    best = 0.0
    for i, mean in enumerate(means):
        best = max(best, abs((1+gain)*(mean+extra))+abs(balance.offset_newtons)
                   + abs(balance.drift_newtons_per_second)
                   * _tail_time(arch, window, i)+balance.vibration_newtons)
    return best


def _plain_terms(arch, window, settings, optical, scale=1.0):
    """Class terms of section 6.1, for non-pilot architectures and A3's A1 part."""
    heat_centre = (optical["heat_minimum_watts"]
                   + optical["heat_maximum_watts"])/2
    heat_radius = (optical["heat_maximum_watts"]
                   - optical["heat_minimum_watts"])/2
    if arch.pilot:
        # The nominal actuator heat is baseline, and only its label part is a
        # radius, so cold start and levels follow what the generator injects.
        heat_centre += PILOT["actuator_heat_watts"]
        heat_radius += (PILOT["actuator_heat_watts"]
                        * PILOT["actuator_heat_label_fraction_bound"])
    shared = _shared(arch, window, heat_centre)
    corners = _corners()
    base, heat, rho = _base_and_heat(arch, window, shared, corners, heat_radius)
    wmax = WEIGHT+BASE["weight_knowledge"]
    factor = (1+settings["common"])
    reach = factor*(1+settings["blind"])
    gp = PRIMARY.calibration_fraction+BASE["calibration_knowledge"]
    gr = REFERENCE.calibration_fraction+BASE["calibration_knowledge"]
    means_p = [m*factor for m in shared["means_p"]]
    means_r = [m*reach for m in shared["means_r"]]
    p_level = _level(PRIMARY, gp, means_p, arch, window)
    r_level = _level(REFERENCE, gr, means_r, arch, window)
    s_p, s_r = settings["s_p"], settings["s_r"]
    classes = settings["classes"]
    label = 2*(s_p*p_level+wmax*s_r*r_level) if classes & {
        "label_correlated", "label_within_window"} else 0.0
    drift = rate = 0.0
    if classes & {"slow_drift", "bounded_rate"}:
        states_p = [x*factor for x in shared["states_p"]]
        states_r = [x*reach for x in shared["states_r"]]
        for order in permitted_orders(arch):
            unit_drift, unit_rate = _sequence_terms(
                arch, window, order, states_p, states_r)
            if "slow_drift" in classes:
                drift = max(drift, s_p*unit_drift["p"]
                            + wmax*s_r*unit_drift["r"])
            if "bounded_rate" in classes:
                rate = max(rate, s_p*unit_rate["p"]+wmax*s_r*unit_rate["r"])
    shat_p = amplitude_factor(settings)*s_p
    shat_r = amplitude_factor(settings)*s_r
    dg = BASE["calibration_knowledge"]
    gamma_r = 1+gr+shat_r
    forces_p, forces_r = shared["forces"]["p"], shared["forces"]["r"]
    settled = forces_r[arch.dwells-1][arch.dwells-1]
    blind = (2*settings["blind"]*wmax*gamma_r*COUPLING*COMMON*factor*settled
             if settings["blind"] else 0.0)
    common = 0.0
    if settings["common"]:
        residual = 0.0
        step_p = forces_p[arch.dwells-1][arch.dwells-1]
        for g_p, g_r, (_, _, w) in product(
                (1+gp-2*dg-shat_p, 1+gp+shat_p),
                (1+gr-2*dg-shat_r, 1+gr+shat_r), corners):
            residual = max(residual, abs(
                g_p*step_p-w*COUPLING*(1+settings["blind"])*g_r*settled))
        common = 2*settings["common"]*residual*COMMON
    return {"base": base, "heat": heat, "rho": rho, "label": label,
            "drift": drift, "rate": rate, "blind": blind, "common": common,
            "p_level": p_level, "r_level": r_level, "shared": shared,
            "means_p": means_p, "means_r": means_r, "wmax": wmax,
            "heat_centre": heat_centre, "heat_radius": heat_radius}


_pilot_cache = {}


def _pilot_tables(arch, window, omega):
    """Relative pilot quantities, independent of amplitude and scenario."""
    key = (arch.name, window, omega)
    if key in _pilot_cache:
        return _pilot_cache[key]
    knowledge = PILOT["response_time_estimator_knowledge_fraction"]
    times = window_times(arch, window)
    enclosures = []
    out = {}
    bound = PILOT["timing_label_bound_seconds"]
    cosine = math.cos(omega*bound)
    sine = math.sin(omega*bound)
    a_bound = PILOT["actuator_label_fraction_bound"]
    k_bound = PILOT["coupling_label_fraction_bound"]
    floor = GAP["dimensionless_floor"]
    limit = GAP["maximum_relative_gap"]
    for name, balance in (("p", PRIMARY), ("r", REFERENCE)):
        tau = balance.response_seconds
        cells = bounds.weight_cells(
            tau, knowledge, COVER["xi_cells_per_channel"], times, omega)
        small = bounds.weight_cells(
            tau, knowledge, COVER["xi_cells_for_vibration_kernel"], times, omega)
        quiet = replace(balance, thermal_newtons_per_watt=0.0)
        vectors_sin, vectors_cos = [], []
        for j in range(arch.dwells):
            for table, wave in ((vectors_sin, math.sin), (vectors_cos, math.cos)):
                drive = [wave(omega*(k+1)*STEP) if k//arch.size == j else 0.0
                         for k in range(SAMPLES)]
                states = run_channel(quiet, drive, [0.0]*SAMPLES)
                table.append(states)

        def part(table, i, j):
            return [table[j][k] for k in window_indices(arch, window, i)]

        cycles = arch.size*STEP*omega/(2*math.pi)
        alternating = abs(cycles-round(cycles)) > 1e-9

        def signed(table, i, j):
            # A dwell of a half-odd number of cycles flips the tone each dwell.
            flip = (-1)**i if alternating else 1
            return [flip*value for value in part(table, i, j)]

        def full(table, i):
            rows = [signed(table, i, j) for j in range(i+1)]
            return [math.fsum(column) for column in zip(*rows)]

        last = arch.dwells-1
        steady = full(vectors_sin, last)
        ratio = 1.0
        if name == "r":
            ratio = ((1+a_bound)*(1+k_bound)
                     / ((1-a_bound)*(1-k_bound)))-1
        else:
            ratio = (1+a_bound)/(1-a_bound)-1
        nu, nu_point, low, top, carry, tilt = [], [], [], [], [], []
        tilt_range, nu_range, w_range, v_range = [], [], [], []
        for i in range(arch.dwells):
            current = full(vectors_sin, i)
            difference = [x-y for x, y in zip(current, steady)]
            value, point = bounds.ratio_sup_abs(cells, difference, steady)
            nu.append(value)
            nu_point.append(point)
            nu_range.append(bounds.ratio_range(cells, difference, steady))
            w_range.append([bounds.ratio_range(
                cells, signed(vectors_sin, i, j), current) for j in range(i)])
            v_range.append([bounds.ratio_range(
                cells, signed(vectors_cos, i, j), current) for j in range(i)])
            enclosures.append(bounds.gap_check(
                f"nu_{name}_{i}", "supremum", value, point, floor, limit))
            down, up, point_low, _ = bounds.linear_range(cells, current)
            low.append(down)
            top.append(up)
            enclosures.append(bounds.gap_check(
                f"projection_{name}_{i}", "infimum", down, point_low, floor,
                limit))
            quadrature = full(vectors_cos, i)
            value, point = bounds.ratio_sup_abs(cells, quadrature, current)
            tilt.append(value)
            tilt_range.append(bounds.ratio_range(cells, quadrature, current))
            total = 0.0
            for j in range(i):
                sup_i = bounds.sup_abs(cells, part(vectors_sin, i, j))[0]
                sup_d = bounds.sup_abs(cells, part(vectors_cos, i, j))[0]
                total += ((ratio+1-cosine)*sup_i+(2+ratio)*sine*sup_d)
            carry.append(total/(cosine*down))
        gain, point = bounds.noise_gain(cells, steady)
        enclosures.append(bounds.gap_check(
            f"noise_gain_{name}", "supremum", gain, point, floor, limit))
        size = max(math.fsum(abs(m)+r for m, r in zip(mid, rad))
                   for mid, rad in cells)
        kernel, point = bounds.kernel(small, times, BAND,
                                      COVER["vibration_frequency_cells"])
        enclosures.append(bounds.gap_check(
            f"kernel_{name}", "supremum", kernel, point, floor, limit))
        out[name] = {
            "nu": nu, "nu_point": nu_point, "low": low, "top": top,
            "carry": carry, "tilt": tilt, "tilt_range": tilt_range,
            "nu_range": nu_range, "w_range": w_range, "v_range": v_range,
            "parts_sin": [[signed(vectors_sin, i, j) for j in range(i+1)]
                          for i in range(arch.dwells)],
            "parts_cos": [[signed(vectors_cos, i, j) for j in range(i+1)]
                          for i in range(arch.dwells)],
            "gain": gain, "size": size, "kernel": kernel, "cells": cells,
            "steady": steady, "times": times,
            "quadrature": full(vectors_cos, last),
            "mean_sin": [abs(_mean([math.fsum(column) for column in zip(
                *[part(vectors_sin, i, j) for j in range(i+1)])],
                range(window[1]-window[0]+1))) for i in range(arch.dwells)],
            "mean_cos": [abs(_mean([math.fsum(column) for column in zip(
                *[part(vectors_cos, i, j) for j in range(i+1)])],
                range(window[1]-window[0]+1))) for i in range(arch.dwells)],
        }
    out["cosine"], out["sine"] = cosine, sine
    out["enclosures"] = enclosures
    _pilot_cache[key] = out
    return out


_mix_cache = {}


def _mix_units(arch, window, omega, tables, name):
    """Per unit step: projection and mean mixing over offsets and cells."""
    key = (arch.name, window, omega, name)
    if key in _mix_cache:
        return _mix_cache[key]
    channel = tables[name]
    steady, quadrature = channel["steady"], channel["quadrature"]
    cells = channel["cells"]
    indices = list(window_indices(arch, window, arch.dwells-1))
    count = len(indices)
    best = {"sin": 0.0, "cos": 0.0, "one": 0.0, "mean_sin": 0.0, "mean_cos": 0.0}
    points = dict(best)
    for offset in range(HOLD_SAMPLES):
        blocks = [hold_block(k, offset) for k in indices]
        ordered = sorted(set(blocks))
        paths = bounds.vertex_paths(len(ordered), 1.0)
        for path in paths:
            if path[1:] and path[1] < 0:
                continue
            values = dict(zip(ordered, path))
            series = [values[b] for b in blocks]
            mean = math.fsum(series)/count
            deviation = [v-mean for v in series]
            if not any(deviation):
                continue
            times = channel["times"]
            for label, vector in (("sin", steady), ("cos", quadrature)):
                weighted = [d*v for d, v in zip(deviation, vector)]
                upper, point = bounds.sup_abs(
                    cells, bounds.orthogonal_part(weighted, times))
                best[label] = max(best[label], upper)
                points[label] = max(points[label], point)
                total = abs(math.fsum(weighted))/count
                best["mean_"+label] = max(best["mean_"+label], total)
            upper, point = bounds.sup_abs(
                cells, bounds.orthogonal_part(deviation, times))
            best["one"] = max(best["one"], upper)
            points["one"] = max(points["one"], point)
    result = (best, points)
    _mix_cache[key] = result
    return result


def _trans_unit(arch, window, tables, shared, name):
    """Projection of settled-level transients per dwell, for unit force steps."""
    cells = tables[name]["cells"]
    balance = PRIMARY if name == "p" else REFERENCE
    quiet = replace(balance, thermal_newtons_per_watt=0.0)
    states = shared["states_p"] if name == "p" else shared["states_r"]
    rows, steps, checks = [], [], []
    columns = []
    floor = GAP["force_floor_newtons"]
    limit = GAP["maximum_relative_gap"]
    for j in range(arch.dwells):
        drive = [1.0 if k//arch.size == j else 0.0 for k in range(SAMPLES)]
        columns.append(run_channel(quiet, drive, [0.0]*SAMPLES))
    times = tables[name]["times"]
    for i in range(arch.dwells):
        indices = list(window_indices(arch, window, i))
        value, point = bounds.sup_abs(cells, bounds.orthogonal_part(
            [states[k] for k in indices], times))
        rows.append(value)
        checks.append(bounds.gap_check(f"trans_{name}_{i}", "supremum", value,
                                       point, floor, limit))
        vectors = [bounds.orthogonal_part([columns[j][k] for k in indices],
                                          times) for j in range(i+1)]
        total = math.fsum(bounds.sup_abs(cells, v)[0] for v in vectors)
        # One cell for every dwell of the sum: a jointly admissible point.
        joint = max(math.fsum(abs(math.fsum(m*x for m, x in zip(mid, v)))
                              for v in vectors) for mid, _ in cells)
        steps.append(total)
        checks.append(bounds.gap_check(
            f"trans_step_{name}_{i}", "supremum", total, joint,
            GAP["dimensionless_floor"], limit))
    return rows, steps, checks


def q_constants(actuator, coupling, delta):
    """Coefficient bounds of protocol section 6.6, for |delta_j| <= delta."""
    c0, s0 = math.cos(delta), math.sin(delta)
    t0, sec0 = s0/c0, 1/c0
    gmax = (1+actuator)/(1-actuator)
    outward = bounds.OUTWARD
    return {"A": outward*max(gmax/c0-1, 1-c0/gmax), "B": outward*(gmax*t0+t0),
            "RHO": outward*gmax*((1+coupling)/(1-coupling)-1),
            "sec0": outward*sec0, "t0": outward*t0, "k": coupling}


def _largest(interval):
    return max(abs(interval[0]), abs(interval[1]))


def _gap_of(x, y):
    """Largest |a - b| for a in x and b in y, independently."""
    return max(abs(x[1]-y[0]), abs(y[1]-x[0]))


def q_enclosure(p_i, r_i, constants):
    """Upper bound of |q_i| from signed, correlation-keeping ranges.

    p_i and r_i hold nu, t and per-dwell w and v ranges for one dwell.
    """
    A, B, rho = constants["A"], constants["B"], constants["RHO"]
    sec0, t0, k = constants["sec0"], constants["t0"], constants["k"]
    delta = t0*_gap_of(p_i["t"], r_i["t"])
    floor = t0*_largest(r_i["t"])
    for w_p, v_p, w_r, v_r in zip(p_i["w"], p_i["v"], r_i["w"], r_i["v"]):
        mag_w, mag_v = _largest(w_r), _largest(v_r)
        delta += (A*_gap_of(w_p, w_r)+B*_gap_of(v_p, v_r)
                  + rho*sec0*mag_w+rho*t0*mag_v)
        floor += (A+rho*sec0)*mag_w+(B+rho*t0)*mag_v
    if floor >= 1:
        raise OperationalFailure("q denominator floor not below one")
    if 1+r_i["nu"][0] <= 0 or 1+p_i["nu"][0] <= 0 or k >= 1:
        raise OperationalFailure("q denominator not positive")
    spread = delta/(1-floor)
    if spread >= 1:
        raise OperationalFailure("q relative change not below one")
    high = (1+p_i["nu"][1])/(1+r_i["nu"][0])/(1-k)*(1+spread)
    low = (1+p_i["nu"][0])/(1+r_i["nu"][1])/(1+k)*(1-spread)
    return max(high-1, 1-low)*bounds.OUTWARD


def _legacy_q(tables, i, k):
    """Revision 4 diagnostics at df82d1c, kept as evidence and never used.

    The clamp and unrelated maxima below are the defect that revision 5
    removed: this point value is not jointly admissible.
    """
    p, r = tables["p"], tables["r"]
    tangent = tables["sine"]/tables["cosine"]
    difference = max(p["tilt_range"][i][1]-r["tilt_range"][i][0],
                     r["tilt_range"][i][1]-p["tilt_range"][i][0])
    eta = p["carry"][i]+r["carry"][i]+tangent*difference
    shift = r["carry"][i]+tangent*r["tilt"][i]
    high = (1+p["nu"][i])/(1-r["nu"][i])/(1-k)*(1+eta/(1-shift))
    low = (1-p["nu"][i])/(1+r["nu"][i])/(1+k)*(1-eta/(1-shift))
    bound = max(high-1, 1-low)
    point = max(abs((1+s*p["nu_point"][i])/(1-s*r["nu_point"][i])/(1-s*k)-1)
                for s in (-1, 1))
    point = min(point, bound)
    return {"bound": bound, "point": point, "gap": (bound-point)/bound}


_joint_cache = {}


def _joint_table(arch, window, omega, tables):
    """Projection coefficients on the search grid, per channel and dwell."""
    key = (arch.name, window, omega)
    if key in _joint_cache:
        return _joint_cache[key]
    points = SEARCH["xi_grid_points"]
    knowledge = PILOT["response_time_estimator_knowledge_fraction"]
    grid = [knowledge*(2*g/(points-1)-1) for g in range(points)]
    result = {"grid": grid}
    for name, balance in (("p", PRIMARY), ("r", REFERENCE)):
        channel = tables[name]
        rows = []
        for xi in grid:
            u = bounds.point_weights(balance.response_seconds*(1+xi),
                                     channel["times"], omega)
            rows.append([[(math.fsum(a*x for a, x in zip(u, s)),
                           math.fsum(a*x for a, x in zip(u, c)))
                          for s, c in zip(channel["parts_sin"][i],
                                          channel["parts_cos"][i])]
                         for i in range(arch.dwells)])
        result[name] = rows
        result["steady_"+name] = [
            math.fsum(pair[0] for pair in row[arch.dwells-1]) for row in rows]
    _joint_cache[key] = result
    return result


def q_search(arch, window, omega, joint, dwell, k_bound, deadline):
    """Capped coordinate ascent. Returns a lower witness and its full tuple."""
    a_bound = PILOT["actuator_label_fraction_bound"]
    bound = PILOT["timing_label_bound_seconds"]
    taus = [bound*f for f in SEARCH["timing_points_fraction"]]
    cosines = [math.cos(omega*t) for t in taus]
    sines = [math.sin(omega*t) for t in taus]
    table_p, table_r = joint["p"], joint["r"]
    steady_p, steady_r = joint["steady_p"], joint["steady_r"]
    points = SEARCH["xi_grid_points"]
    n = arch.dwells

    def value(gp, gr, a, k, t):
        top = bottom = 0.0
        row_p, row_r = table_p[gp][dwell], table_r[gr][dwell]
        for j in range(dwell+1):
            c, s = cosines[t[j]], sines[t[j]]
            weight = 1+a[j]
            top += weight*(c*row_p[j][0]+s*row_p[j][1])
            bottom += weight*(1+k[j])*(c*row_r[j][0]+s*row_r[j][1])
        return top/bottom/(steady_p[gp]/steady_r[gr])-1

    best = None
    low, high = SEARCH["search_seeds"]
    for seed in range(low, high+1):
        for sign in (1, -1):
            if time.monotonic() > deadline:
                raise OperationalFailure("witness search exceeded its limit")
            rng = random.Random(stream(
                "pf002-stationarity-v1", "q-search", arch.name, window, dwell,
                k_bound, seed, sign))
            gp, gr = rng.randrange(points), rng.randrange(points)
            a = [rng.choice((-a_bound, a_bound)) for _ in range(n)]
            k = [rng.choice((-k_bound, k_bound)) for _ in range(n)]
            t = [rng.randrange(len(taus)) for _ in range(n)]
            score = sign*value(gp, gr, a, k, t)
            evaluations = 1
            limit = SEARCH["maximum_evaluations_per_start"]
            for _ in range(SEARCH["maximum_passes"]):
                moved = False
                for g in range(points):
                    for pair in ((g, gr), (gp, g)):
                        if evaluations >= limit:
                            break
                        evaluations += 1
                        trial = sign*value(pair[0], pair[1], a, k, t)
                        if trial > score+1e-16:
                            score, moved = trial, True
                            gp, gr = pair
                for j in range(dwell+1):
                    for vector, options in ((a, (-a_bound, a_bound)),
                                            (k, (-k_bound, k_bound)),
                                            (t, range(len(taus)))):
                        keep = vector[j]
                        for option in options:
                            if evaluations >= limit:
                                break
                            evaluations += 1
                            vector[j] = option
                            trial = sign*value(gp, gr, a, k, t)
                            if trial > score+1e-16:
                                score, keep, moved = trial, option, True
                        vector[j] = keep
                if not moved or evaluations >= limit:
                    break
            if best is None or abs(score) > best["point"]:
                best = {"point": abs(score), "dwell": dwell,
                        "xi_p": joint["grid"][gp], "xi_r": joint["grid"][gr],
                        "a": list(a), "k": list(k),
                        "tau": [taus[x] for x in t], "seed": seed,
                        "sign": sign, "evaluations": evaluations}
    return best


_q_cache = {}


def _q_bounds(arch, window, omega, tables, k_bound):
    """qbar per dwell, gap records, witnesses and legacy diagnostics."""
    key = (arch.name, window, omega, k_bound)
    if key in _q_cache:
        return _q_cache[key]
    a_bound = PILOT["actuator_label_fraction_bound"]
    constants = q_constants(a_bound, k_bound,
                            omega*PILOT["timing_label_bound_seconds"])
    p, r = tables["p"], tables["r"]
    joint = _joint_table(arch, window, omega, tables)
    deadline = time.monotonic()+SEARCH["maximum_seconds_per_table"]
    limit = PILOT["ratio_interval"]
    values, rows = [], []
    for i in range(arch.dwells):
        channels = [{"nu": c["nu_range"][i], "t": c["tilt_range"][i],
                     "w": c["w_range"][i], "v": c["v_range"][i]}
                    for c in (p, r)]
        q_bar = q_enclosure(channels[0], channels[1], constants)
        witness = q_search(arch, window, omega, joint, i, k_bound, deadline)
        replayed = abs(oracle.replay_q(
            witness, primary=PRIMARY, reference=REFERENCE, omega=omega,
            step=STEP, samples=SAMPLES, size=arch.size, dwells=arch.dwells,
            first=window[0], last=window[1], reported_times=p["times"]))
        tolerance = SEARCH["replay_relative_tolerance"]*witness["point"]
        replay_ok = abs(replayed-witness["point"]) <= tolerance+1e-15
        row = bounds.gap_check(f"q_{i}", "supremum", q_bar, witness["point"],
                               GAP["dimensionless_floor"],
                               GAP["maximum_relative_gap"])
        row["replay_ok"] = replay_ok
        row["passed"] = row["passed"] and replay_ok
        row["witness"] = witness
        row["legacy"] = _legacy_q(tables, i, k_bound)
        values.append(q_bar)
        rows.append(row)
    result = {"q_bar": values, "rows": rows}
    _q_cache[key] = result
    return result


_trans_cache = {}


def _pilot_terms(arch, window, settings, optical, amplitude, omega, plain,
                 kappa_bound=None, reference_force=None, load=None):
    """Section 6.2 and 6.3 for one window.

    reference_force replaces the leaked signal with a reference-only force
    amplitude, for the mimic of section 6.8. load replaces it with a fixed
    waveform's window peak, range and line residuals, for the lag controls.
    """
    tables = _pilot_tables(arch, window, omega)
    enclosures = list(tables["enclosures"])
    s_factor = amplitude_factor(settings)
    shat_p = s_factor*settings["s_p"]
    shat_r = s_factor*settings["s_r"]
    dg = BASE["calibration_knowledge"]
    gamma_p = (1+PRIMARY.calibration_fraction-dg-shat_p,
               1+PRIMARY.calibration_fraction+dg+shat_p)
    gamma_r = (1+REFERENCE.calibration_fraction-dg-shat_r,
               1+REFERENCE.calibration_fraction+dg+shat_r)
    if gamma_p[0] <= 0 or gamma_r[0] <= 0:
        raise OperationalFailure("gain range reaches zero")
    a = PILOT["actuator_label_fraction_bound"]
    k = (PILOT["coupling_label_fraction_bound"] if kappa_bound is None
         else kappa_bound)
    low_kappa, high_kappa = PILOT["coupling_constant_interval"]
    scale = {"p": (1.0, 1.0), "r": (low_kappa*(1-k), high_kappa*(1+k))}
    step_p, step_r = window_step(settings)
    steps = {"p": step_p, "r": step_r}
    cosine, sine = tables["cosine"], tables["sine"]
    shared = plain["shared"]
    q_data = _q_bounds(arch, window, omega, tables, k)
    enclosures += q_data["rows"]
    allowance_force = (optical["signal_maximum_newtons"]/2)
    leak_top = LEAK+BASE["leakage_knowledge"]
    drive = {"p": allowance_force,
             "r": (allowance_force if reference_force is None
                   else reference_force)}
    step_force = {"p": allowance_force,
                  "r": (leak_top*allowance_force if reference_force is None
                        else reference_force)}
    if load:
        drive, step_force = load["peak"], {"p": 0.0, "r": 0.0}
    walk = optical["walk_newtons"]/2
    thermal = {"p": PRIMARY.thermal_newtons_per_watt,
               "r": REFERENCE.thermal_newtons_per_watt*HEAT_COUPLING}
    results = {}
    for mode, signal in (("null", 0.0), ("signal", 1.0)):
        theta, denominators = [], {"p": [], "r": []}
        mixing = {}
        for name in ("p", "r"):
            channel = tables[name]
            key = (arch.name, window, omega, name, plain["heat_centre"])
            if key not in _trans_cache:
                _trans_cache[key] = _trans_unit(arch, window, tables, shared,
                                                name)
            trans_rows, trans_steps, trans_checks = _trans_cache[key]
            unit, unit_points = _mix_units(arch, window, omega, tables, name)
            if mode == "null":
                enclosures += trans_checks
                if steps[name]:
                    enclosures += [bounds.gap_check(
                        f"mix_{label}_{name}", "supremum", unit[label],
                        unit_points[label], GAP["dimensionless_floor"],
                        GAP["maximum_relative_gap"])
                        for label in ("sin", "cos", "one")]
            pilot_top = amplitude*(1+a)*scale[name][1]
            level = plain["p_level"] if name == "p" else plain["r_level"]
            mix = steps[name]*(pilot_top*(unit["sin"]+sine*unit["cos"])
                               + (level+drive[name]*signal)*unit["one"])
            force_step = 2*step_force[name]*signal
            force_step += 2*settings["common"]*COMMON*(
                1 if name == "p" else COUPLING)
            if name == "r":
                force_step += 2*settings["blind"]*COUPLING*COMMON
            balance = PRIMARY if name == "p" else REFERENCE
            states = shared["states_p"] if name == "p" else shared["states_r"]
            settled = math.exp(-(window[0]-1)*STEP/balance.response_seconds)
            spread = max(
                max(states[k] for k in window_indices(arch, window, i))
                - min(states[k] for k in window_indices(arch, window, i))
                for i in range(arch.dwells))
            load_range = load["range"][name]*signal if load else 0.0
            mean_mix = steps[name]*(
                pilot_top*(unit["mean_sin"]+sine*unit["mean_cos"])
                + 2*(spread+force_step*settled+load_range))
            mixing[name] = (mix, mean_mix)
            vibration = (PRIMARY if name == "p"
                         else REFERENCE).vibration_newtons*channel["kernel"]
            heat_part = (channel["size"]*abs(thermal[name])
                         * plain["heat_radius"])
            walk_part = channel["size"]*walk*signal*(
                1 if name == "p" else LEAK+BASE["leakage_knowledge"])
            noise = (PRIMARY if name == "p" else REFERENCE).noise_bound_newtons
            rows = []
            for i in range(arch.dwells):
                trans = (trans_rows[i]*(1+settings["common"])
                         * (1+settings["blind"])+force_step*trans_steps[i])
                if load:
                    # Weights annihilate a line, so only its residual projects.
                    trans += channel["size"]*load["residual"][name][i]*signal
                trans *= (gamma_p if name == "p" else gamma_r)[1]
                additive = (mix+trans+vibration+heat_part+walk_part)
                safe = (amplitude*(1-a)*scale[name][0]*cosine*channel["low"][i]
                        * (1-channel["carry"][i]
                           - (sine/cosine)*channel["tilt"][i]))
                gamma_low = (gamma_p if name == "p" else gamma_r)[0]
                lambda_value = (gamma_low*safe-additive
                                - noise*channel["size"])
                relative = (noise*channel["gain"]*(1+channel["nu"][i])
                            / (gamma_low*amplitude*(1-a)*scale[name][0]*cosine)
                            + additive/(gamma_low*safe))
                rows.append({"lambda": lambda_value, "relative": relative,
                             "safe": safe})
            denominators[name] = rows
        worst_relative = 0.0
        for i in range(arch.dwells):
            q_bar = q_data["q_bar"][i]
            x_bar = denominators["p"][i]["relative"]
            y_bar = denominators["r"][i]["relative"]
            limit = PILOT["error_ratio_refusal_maximum"]
            if x_bar > limit or y_bar >= limit:
                raise OperationalFailure("pilot error ratio refused")
            floor = PILOT["projection_floor_fraction"]*amplitude
            if (denominators["p"][i]["lambda"] <= floor
                    or denominators["r"][i]["lambda"] <= floor):
                raise OperationalFailure("pilot denominator refused")
            theta.append(bounds.OUTWARD*((1+q_bar)*(1+x_bar)/(1-y_bar)-1))
            worst_relative = max(worst_relative, x_bar, y_bar)
        results[mode] = {"theta": theta, "mixing": mixing,
                         "denominators": denominators,
                         "q_relative": worst_relative}
    return {"results": results, "gamma_p": gamma_p, "gamma_r": gamma_r,
            "shat_p": shat_p, "shat_r": shat_r, "enclosures": enclosures,
            "tables": tables}


def _a3_error(arch, window, settings, optical, amplitude, plain, terms, mode):
    """Conservative contrast bound from the identity of section 6.3."""
    data = terms["results"][mode]
    theta = data["theta"]
    theta_max = max(theta)
    gamma_p, gamma_r = terms["gamma_p"], terms["gamma_r"]
    n = arch.dwells
    half = n//2
    r_low = gamma_p[0]/gamma_r[1]
    r_high = gamma_p[1]/gamma_r[0]
    w_low = WEIGHT-BASE["weight_knowledge"]
    w_high = WEIGHT+BASE["weight_knowledge"]
    eff_low = w_low/(r_high*(1+theta_max))
    eff_high = w_high/(r_low*(1-theta_max))
    spread = n*r_high/(r_high+(n-1)*r_low)
    weight_r = w_high*spread*(1+theta_max)/(1-theta_max)
    tables = terms["tables"]
    signal = (optical["signal_maximum_newtons"]/2 if mode == "signal" else 0.0)
    leak_top = LEAK+BASE["leakage_knowledge"]
    means_p = [m+signal for m in plain["means_p"]]
    means_r = [m+leak_top*signal for m in plain["means_r"]]
    residual = 0.0
    for eff in (eff_low, eff_high):
        for p, r in zip(means_p, means_r):
            residual = max(residual, abs(p-eff*r),
                           abs(p-2*signal-eff*(r-2*leak_top*signal)))
    e_gamma = 2*terms["shat_p"]*residual
    e_theta = 2*math.fsum(t*eff_high*gamma_p[1]*abs(m)
                          for t, m in zip(theta, means_r))/n
    e_mod = 2*math.fsum(
        eff_high*((r_high-r_low)+t*r_high)
        * (abs(REFERENCE.offset_newtons)+abs(REFERENCE.drift_newtons_per_second)
           * _tail_time(arch, window, i))
        for i, t in enumerate(theta))/n
    e_noise = 2*(PRIMARY.noise_bound_newtons
                 + weight_r*REFERENCE.noise_bound_newtons)
    charged = PILOT["vibration_kernel_samples_charged"]
    kernel = bounds.mean_kernel(charged, BAND[0], STEP)
    e_vib = 2*(PRIMARY.vibration_newtons
               + weight_r*REFERENCE.vibration_newtons)*kernel
    a = PILOT["actuator_label_fraction_bound"]
    high_kappa = PILOT["coupling_constant_interval"][1]
    k = PILOT["coupling_label_fraction_bound"]
    sine = tables["sine"]
    e_cold = 0.0
    for i in range(n):
        e_cold += (gamma_p[1]*amplitude*(1+a)*(
            tables["p"]["mean_sin"][i]+sine*tables["p"]["mean_cos"][i])
            + weight_r*gamma_r[1]*amplitude*(1+a)*high_kappa*(1+k)*(
                tables["r"]["mean_sin"][i]+sine*tables["r"]["mean_cos"][i]))
    e_cold *= 2/n
    mix_p, mean_p = data["mixing"]["p"]
    mix_r, mean_r = data["mixing"]["r"]
    e_mix = 2*(mean_p+weight_r*mean_r)
    wmax = plain["wmax"]
    dg = BASE["calibration_knowledge"]
    corners = tuple((PRIMARY.calibration_fraction+s*dg, 0.0, eff)
                    for s in (-1, 1) for eff in (eff_low, eff_high))
    base, heat, _ = _base_and_heat(arch, window, plain["shared"], corners,
                                   plain["heat_radius"])
    blind = plain["blind"]*(weight_r/wmax)
    common = plain["common"]*(eff_high/wmax if eff_high > wmax else 1.0)
    parts = {"base": base, "heat": heat, "gamma": e_gamma, "theta": e_theta,
             "mod": e_mod, "noise": e_noise, "vibration": e_vib, "cold": e_cold,
             "mix": e_mix, "blind": blind, "common": common}
    return bounds.OUTWARD*math.fsum(parts.values()), parts, (eff_low, eff_high)


def signal_gain_term(settings, contrast):
    """E_G of section 6.1: gain times a signal state bounded by contrast/2."""
    factor = amplitude_factor(settings)
    return (factor*settings["s_p"]*contrast
            + (WEIGHT+BASE["weight_knowledge"])*factor*settings["s_r"]
            * (LEAK+BASE["leakage_knowledge"])*contrast)


def _plain_error(arch, window, plain, gain_signal=0.0):
    count = window[1]-window[0]+1
    wmax = plain["wmax"]
    noise = 2*(PRIMARY.noise_bound_newtons
               + wmax*REFERENCE.noise_bound_newtons)
    kernel = bounds.mean_kernel(count, BAND[0], STEP)
    vibration = 2*(PRIMARY.vibration_newtons
                   + wmax*REFERENCE.vibration_newtons)*kernel
    label = plain["label"]
    parts = {"base": plain["base"], "heat": plain["heat"], "noise": noise,
             "vibration": vibration, "drift": plain["drift"],
             "rate": plain["rate"], "label": label, "blind": plain["blind"],
             "common": plain["common"]}
    if gain_signal:
        parts["gain_signal"] = gain_signal
    return math.fsum(parts.values()), parts


def stimulus_contrast():
    """Declared S_x from the fixed injected force, never from any reading."""
    factor = PROTOCOL["large_stimulus_audit"][
        "declared_contrast_factor_of_out_of_window_force"]
    return factor*PROTOCOL["out_of_window_impostor_force_newtons"]


def transfer_shift(terms, theta_max):
    """D_T of section 6.7: w_eff against the actual weight that truth uses."""
    shat_p, shat_r = terms["shat_p"], terms["shat_r"]
    dg = BASE["calibration_knowledge"]
    g_p = 1+PRIMARY.calibration_fraction-dg
    g_r = 1+REFERENCE.calibration_fraction+dg
    ratio = (g_p+shat_p)/(g_p-shat_p)
    top = WEIGHT+BASE["weight_knowledge"]
    return top*max((g_r+shat_r)*ratio/(1-theta_max)-g_r,
                   g_r-(g_r-shat_r)/(ratio*(1+theta_max)))


def mimic_shift(terms, theta_max, settings):
    """D_M of section 6.8: normalisation and gain on a reference-only state."""
    shat_p, shat_r = terms["shat_p"], terms["shat_r"]
    dg = BASE["calibration_knowledge"]
    g_p = 1+PRIMARY.calibration_fraction-dg
    top = 1+REFERENCE.calibration_fraction+dg
    low = 1+REFERENCE.calibration_fraction-dg
    spread = (g_p+shat_p)/(g_p-shat_p)*(1+theta_max)/(1-theta_max)
    mixing = min(2*window_step(settings)[1], 2*shat_r)
    return (max((top+shat_r)*spread-top, top-(top-shat_r)/spread)
            + spread*(low+shat_r)/(low-shat_r)*mixing)


def mimic_error(settings, shift):
    """E_R: w cancels against the coupling change, so no leakage or W enters."""
    return (1+settings["common"])*nominal_contrast()*shift


def _quiet_pilot_terms(arch, window, settings, window_data, amplitude, omega,
                       plain, kappa, **extra):
    """Budget with no force row. A refusal propagates as a design-time one."""
    quiet = dict(window_data, signal_maximum_newtons=0.0)
    terms = _pilot_terms(arch, window, settings, quiet, amplitude, omega, plain,
                         kappa, **extra)
    failed = [e["name"] for e in terms["enclosures"] if not e["passed"]]
    if failed:
        raise OperationalFailure(f"enclosure gap failed: {failed[0]}")
    total, _, _ = _a3_error(arch, window, settings, quiet, amplitude, plain,
                            terms, "signal")
    return terms, total, max(terms["results"]["signal"]["theta"])


def pilot_mimic_bound(arch, window, settings, window_data, amplitude, omega,
                      plain, kappa):
    """E_M,A3 of section 6.8."""
    force = (nominal_contrast()/2*(1+settings["common"])
             / (WEIGHT-BASE["weight_knowledge"]))
    terms, total, theta_max = _quiet_pilot_terms(
        arch, window, settings, window_data, amplitude, omega, plain, kappa,
        reference_force=force)
    return bounds.OUTWARD*(total+mimic_error(
        settings, mimic_shift(terms, theta_max, settings)))


_lag_cache = {}


def lag_waveform(arch, order, lag):
    """The fixed force of a lag control: forces() with lock_i = sigma_i."""
    weight = -math.expm1(-STEP/lag)
    impostor = nominal_contrast()/2
    scale = lag_scale(arch, list(order), lag)
    state = 0.0
    waveform = []
    for k in range(SAMPLES):
        state += weight*(order[k//arch.size]*impostor-state)
        waveform.append(scale*state)
    return waveform


def line_residual(values):
    """Largest residual from the least-squares line through equal samples."""
    centre = (len(values)-1)/2
    mean = math.fsum(values)/len(values)
    slope = (math.fsum((n-centre)*(v-mean) for n, v in enumerate(values))
             / math.fsum((n-centre)**2 for n in range(len(values))))
    return max(abs(v-mean-slope*(n-centre)) for n, v in enumerate(values))


def lag_envelope(arch, window):
    """Finite sums of section 6.8 over permitted orders and both lags."""
    key = (arch.name, window)
    if key in _lag_cache:
        return _lag_cache[key]
    half = arch.dwells//2
    quiet = {"p": replace(PRIMARY, thermal_newtons_per_watt=0.0),
             "r": replace(REFERENCE, thermal_newtons_per_watt=0.0)}
    rows = []
    peak, span = {"p": 0.0, "r": 0.0}, {"p": 0.0, "r": 0.0}
    residual = {"p": [0.0]*arch.dwells, "r": [0.0]*arch.dwells}
    for order in permitted_orders(arch):
        for lag in PROTOCOL["impostor_lag_seconds"]:
            force = lag_waveform(arch, order, lag)
            difference = []
            totals = {"p": [], "r": []}
            for name, balance in quiet.items():
                states = run_channel(balance, force, [0.0]*SAMPLES)
                means = []
                for i in range(arch.dwells):
                    values = [states[k] for k in window_indices(arch, window, i)]
                    means.append(order[i]*math.fsum(values)/len(values))
                    totals[name].append(math.fsum(abs(v) for v in values)
                                        / len(values))
                    peak[name] = max(peak[name], max(abs(v) for v in values))
                    span[name] = max(span[name], max(values)-min(values))
                    residual[name][i] = max(residual[name][i],
                                            line_residual(values))
                difference.append(means)
            rows.append({
                "d": abs(math.fsum(difference[1])
                         - math.fsum(difference[0]))/half,
                "u_p": math.fsum(totals["p"])/half,
                "u_r": math.fsum(totals["r"])/half})
    result = {"rows": rows, "peak": peak, "range": span, "residual": residual}
    _lag_cache[key] = result
    return result


def plain_lag_error(arch, window, settings):
    """E_L of section 6.8, for A0, A1 and A2."""
    factor = amplitude_factor(settings)
    shat_p, shat_r = factor*settings["s_p"], factor*settings["s_r"]
    w_l = (WEIGHT+BASE["weight_knowledge"])*(LEAK+BASE["leakage_knowledge"])
    top = 1+REFERENCE.calibration_fraction+BASE["calibration_knowledge"]
    return bounds.OUTWARD*max(
        w_l*top*row["d"]+shat_p*row["u_p"]+w_l*shat_r*row["u_r"]
        for row in lag_envelope(arch, window)["rows"])


def pilot_lag_bound(arch, window, settings, window_data, amplitude, omega,
                    plain, kappa):
    """E_L,A3 of section 6.8, with theta recomputed for the waveform."""
    leak_top = LEAK+BASE["leakage_knowledge"]
    envelope = lag_envelope(arch, window)
    load = {"peak": {"p": envelope["peak"]["p"],
                     "r": leak_top*envelope["peak"]["r"]},
            "range": {"p": envelope["range"]["p"],
                      "r": leak_top*envelope["range"]["r"]},
            "residual": {"p": envelope["residual"]["p"],
                         "r": [leak_top*x for x in envelope["residual"]["r"]]}}
    terms, total, theta_max = _quiet_pilot_terms(
        arch, window, settings, window_data, amplitude, omega, plain, kappa,
        load=load)
    shift = mimic_shift(terms, theta_max, settings)
    w_l = (WEIGHT+BASE["weight_knowledge"])*leak_top
    top = 1+REFERENCE.calibration_fraction+BASE["calibration_knowledge"]
    return bounds.OUTWARD*(total+max(
        terms["shat_p"]*row["u_p"]+w_l*(shift*row["u_r"]+top*row["d"])
        for row in envelope["rows"]))


def stimulus_bound(arch, settings, window_data, amplitude, omega, plain, late,
                   kappa):
    """E_x of section 6.7. An audit bound only, and never a decision input.

    A copy of the optical window carrying S_x re-runs the reviewed budget at
    the enlarged force, including A3's denominators and refusals, so nothing is
    borrowed from S_max. optical_window, B and both margins are untouched.
    """
    s_x = stimulus_contrast()
    leak_top = LEAK+BASE["leakage_knowledge"]
    settling = plain["rho"]*s_x
    if not arch.pilot:
        gain = signal_gain_term(settings, s_x)
        return {"status": "valid", "reason": None, "contrast_newtons": s_x,
                "bound_newtons": bounds.OUTWARD*(late["null"]+settling+gain),
                "settling_newtons": settling, "gain_newtons": gain,
                "transfer_newtons": 0.0}
    stimulus = dict(window_data, signal_maximum_newtons=s_x)
    try:
        terms = _pilot_terms(arch, arch.late, settings, stimulus, amplitude,
                             omega, plain, kappa)
    except OperationalFailure as refusal:
        return {"status": "unproved", "reason": str(refusal),
                "contrast_newtons": s_x, "bound_newtons": None}
    failed = [e["name"] for e in terms["enclosures"] if not e["passed"]]
    if failed:
        return {"status": "unproved", "reason": f"enclosure gap: {failed[0]}",
                "contrast_newtons": s_x, "bound_newtons": None}
    total, _, _ = _a3_error(arch, arch.late, settings, stimulus, amplitude,
                            plain, terms, "signal")
    theta_max = max(terms["results"]["signal"]["theta"])
    transfer = s_x*leak_top*transfer_shift(terms, theta_max)
    return {"status": "valid", "reason": None, "contrast_newtons": s_x,
            "bound_newtons": bounds.OUTWARD*(total+settling+transfer),
            "settling_newtons": settling, "gain_newtons": None,
            "transfer_newtons": transfer}


def null_margin(lower, null_error, half):
    """Worst-case gap between C + half and the optical edge, section 6.5.

    half is the one half-width the decision uses. A wider half makes this
    smaller, so it is never replaced by a narrower null half-width.
    """
    return lower-null_error-half


def signal_margin(transferred, signal_error, half):
    """Worst-case clearance of the decision interval from zero."""
    return transferred-signal_error-half


_plan_cache = {}


def design(arch, scenario, dose=0, *, optical=None, overrides=()):
    """Bound, margins and enclosure status for one configuration.

    optical may inject a window for fixtures. Cohorts always compute it.
    """
    settings = scenario_settings(scenario)
    options = dict(overrides)
    if "blind" in options:
        settings["blind"] = options["blind"]
    key = (arch.name, scenario, dose, tuple(sorted(options.items())),
           None if optical is None else tuple(sorted(optical.items())))
    if key in _plan_cache:
        return _plan_cache[key]
    window_data = optical or optical_window(arch.additive)
    amplitude = options.get("amplitude", pilot_amplitude(dose))
    omega = 2*math.pi*options.get("frequency", PILOT["frequency_hertz"])
    allowance = 2*STRUCTURAL*options.get("structural", 1.0)
    enclosures, valid, reason = [], True, None
    output = {"architecture": arch.name, "scenario": scenario, "dose": dose}
    planned = {}
    s_max = window_data["signal_maximum_newtons"]
    for name, window in (("late", arch.late), ("early", arch.early)):
        plain = _plain_terms(arch, window, settings, window_data)
        if arch.pilot:
            try:
                terms = _pilot_terms(arch, window, settings, window_data,
                                     amplitude, omega, plain,
                                     options.get("kappa"))
            except OperationalFailure as error:
                valid, reason = False, str(error)
                planned[name] = None
                continue
            enclosures += terms["enclosures"]
            null, null_parts, eff = _a3_error(
                arch, window, settings, window_data, amplitude, plain, terms,
                "null")
            signal, signal_parts, _ = _a3_error(
                arch, window, settings, window_data, amplitude, plain, terms,
                "signal")
            theta_max = max(terms["results"]["signal"]["theta"])
            leak_top = LEAK+BASE["leakage_knowledge"]
            transfer = s_max*leak_top*transfer_shift(terms, theta_max)
            force_class = signal+plain["rho"]*s_max+transfer
            try:
                mimic_class = pilot_mimic_bound(
                    arch, window, settings, window_data, amplitude, omega,
                    plain, options.get("kappa"))
                lag_class = pilot_lag_bound(
                    arch, window, settings, window_data, amplitude, omega,
                    plain, options.get("kappa"))
            except OperationalFailure as error:
                # Design-time refusal: the row stays, and validity reports it.
                valid, reason = False, str(error)
                mimic_class = lag_class = None
            box = transfer_box(eff)
        else:
            null, null_parts = _plain_error(arch, window, plain)
            signal, signal_parts = _plain_error(
                arch, window, plain, signal_gain_term(settings, s_max))
            transfer = 0.0
            force_class = signal+plain["rho"]*s_max
            shat_r = amplitude_factor(settings)*settings["s_r"]
            mimic_class = null+mimic_error(settings, shat_r)
            lag_class = null+plain_lag_error(arch, window, settings)
            box = transfer_box()
        # One half-width serves every row, and a row is of one class only.
        signal = max(x for x in (force_class, mimic_class, lag_class)
                     if x is not None)
        planned[name] = {"null": null, "signal": signal, "rho": plain["rho"],
                         "parts": null_parts, "signal_parts": signal_parts,
                         "classes": {"force": force_class,
                                     "reference_mimic": mimic_class,
                                     "lag": lag_class,
                                     "transfer": transfer},
                         "box": box, "plain": plain}
    late = planned["late"]
    failed = [e["name"] for e in enclosures if not e["passed"]]
    if failed:
        valid, reason = False, f"enclosure gap failed: {failed[0]}"
    output.update({"valid": valid, "reason": reason,
                   "enclosures": enclosures, "planned": planned})
    if late is not None:
        box = late["box"]
        walk = window_data["walk_newtons"]
        lower = box[0]*(window_data["optical_minimum_newtons"]-walk)
        upper = box[1]*(window_data["optical_maximum_newtons"]+walk)
        half = late["signal"]+allowance
        output.update({
            "lower_newtons": lower, "upper_newtons": upper,
            "null_bound_newtons": late["null"],
            "signal_bound_newtons": late["signal"],
            "m_null_newtons": null_margin(lower, late["null"], half),
            "m_signal_newtons": signal_margin(
                box[0]*window_data["signal_minimum_newtons"], late["signal"],
                half),
            "allowance_newtons": allowance, "walk_newtons": walk,
            "half_newtons": half,
            "stimulus": stimulus_bound(
                arch, settings, window_data, amplitude, omega, late["plain"],
                late, options.get("kappa")),
        })
    _plan_cache[key] = output
    return output


def _canonical(value):
    return json.dumps(value, sort_keys=True, ensure_ascii=True,
                      separators=(",", ":"), allow_nan=False)


def enclosure_rows(plan):
    """Every enclosure's bound, point, gap and status, section 6.6."""
    rows = []
    for entry in plan["enclosures"]:
        row = {key: entry[key] for key in ("name", "kind", "bound", "point",
                                           "gap", "floor", "passed")}
        if "witness" in entry:
            row["replay_ok"] = entry["replay_ok"]
            row["legacy_gap"] = entry["legacy"]["gap"]
            row["witness_sha256"] = "sha256:"+hashlib.sha256(_canonical(
                entry["witness"]).encode("ascii")).hexdigest()
        rows.append(row)
    return rows


def deduplicate_enclosures(designs):
    """Move rows to one store, with a stable content reference per design."""
    store = {}
    for design_row in designs:
        rows = design_row.pop("enclosures")
        if not rows:
            design_row["enclosures_ref"] = None
            continue
        text = _canonical(rows)
        reference = "sha256:"+hashlib.sha256(text.encode("ascii")).hexdigest()
        store[reference] = rows
        design_row["enclosures_ref"] = reference
    return store


def public_design(plan):
    keep = ("architecture", "scenario", "dose", "valid", "reason",
            "lower_newtons", "upper_newtons", "null_bound_newtons",
            "signal_bound_newtons", "m_null_newtons", "m_signal_newtons",
            "half_newtons", "stimulus")
    result = {key: plan.get(key) for key in keep}
    result["enclosure_failures"] = [e["name"] for e in plan["enclosures"]
                                    if not e["passed"]]
    result["largest_enclosure_gap"] = max(
        (e["gap"] for e in plan["enclosures"]), default=0.0)
    result["enclosures"] = enclosure_rows(plan)
    late = plan["planned"].get("late")
    if late:
        result["terms_newtons"] = late["parts"]
        result["signal_classes_newtons"] = late["classes"]
    return result


def q_diagnostics(plan):
    """Old and new q gaps with each witness tuple, capped for the record."""
    rows = []
    for row in plan["enclosures"]:
        if row["name"].startswith("q_"):
            rows.append({key: row[key] for key in (
                "name", "bound", "point", "gap", "passed", "replay_ok",
                "witness", "legacy")})
    return rows[:SEARCH["maximum_retained_tuples"]]


def judge(contrast, half, predicted):
    low, high = contrast-half, contrast+half
    return low > 0 or high < 0, max(low, predicted[0]) <= min(high, predicted[1])


def optical_contrast(draws, detector=None):
    arch = draws["arch"]
    detector = detector or detector_interval
    half = arch.dwells//2
    low = high = 0.0
    orientation = draws["orientation"]
    for i, sigma in enumerate(draws["order"]):
        phase, feed = draws["phases"][i], draws["feeds"][i]
        power = feed*SOURCE["optical_feed_watts"]*_unit(phase)[0]
        interval = detector(phase, power, (i+1)*arch.size*STEP, arch.additive)
        if orientation == -1:
            interval = [-interval[1], -interval[0]]
        if sigma > 0:
            low += interval[0]/half
            high += interval[1]/half
        else:
            low -= interval[1]/half
            high -= interval[0]/half
    return [low, high]


SINGLE = {
    "opposite-phase": (True, True), "phase-null": (False, True),
    "force-decoupled": (False, False),
    "impostor-lab-fixed-in-window": (True, True),
    "impostor-source-fixed-instant": (True, True),
    "impostor-source-fixed-lag-10s": (True, True),
    "impostor-source-fixed-lag-0p1s": (True, True),
    "reference-path-label-mimic": (True, True),
    "impostor-out-of-window": (True, False),
}
DUAL = {
    "opposite-phase": (True, True, False), "phase-null": (False, True, False),
    "force-decoupled": (False, False, False),
    "impostor-lab-fixed-in-window": (False, False, True),
    "impostor-source-fixed-instant": (True, True, False),
    "impostor-source-fixed-lag-10s": (True, True, False),
    "impostor-source-fixed-lag-0p1s": (True, True, False),
    "reference-path-label-mimic": (True, True, False),
}
MIMIC = frozenset({
    "impostor-lab-fixed-in-window", "impostor-source-fixed-instant",
    "impostor-source-fixed-lag-10s", "impostor-source-fixed-lag-0p1s",
    "reference-path-label-mimic"})


def single_expectation(control, orientation):
    if control == "impostor-lab-fixed-in-window" and orientation == -1:
        return (True, False)
    return SINGLE[control]


def _early_ratio(arch, order, tau):
    balance = replace(PRIMARY, response_seconds=tau,
                      thermal_newtons_per_watt=0.0)
    drive = [order[k//arch.size]*1.0 for k in range(SAMPLES)]
    states = run_channel(balance, drive, [0.0]*SAMPLES)

    def contrast(window):
        return math.fsum(order[i]*_mean(states, window_indices(arch, window, i))
                         for i in range(arch.dwells))
    return contrast(arch.early)/contrast(arch.late)


def assess(draws, plan, *, detector=None, noise_path=None, readings=None):
    """One acquisition. Only readings and public values reach the estimator."""
    arch = draws["arch"]
    amplitude = pilot_amplitude(plan["dose"]) if arch.pilot else None
    if readings is None:
        inputs = forces(draws, amplitude)
        readings = read_channels(draws, inputs, noise_path=noise_path)
    y_p, y_r = readings
    omega = 2*math.pi*PILOT["frequency_hertz"]
    tau_hat = (PRIMARY.response_seconds*(1+draws["xi_p"]),
               REFERENCE.response_seconds*(1+draws["xi_r"]))
    late = estimate(y_p, y_r, draws["order"], arch, arch.late,
                    amplitude=amplitude, omega=omega, tau_hat=tau_hat,
                    weight=draws["w"])
    early = estimate(y_p, y_r, draws["order"], arch, arch.early,
                     amplitude=amplitude, omega=omega, tau_hat=tau_hat,
                     weight=draws["w"])
    raw = optical_contrast(draws, detector=detector)
    planned = plan["planned"]["late"]
    box = planned["box"]
    walk = plan["walk_newtons"]
    predicted = map_interval([raw[0]-walk, raw[1]+walk], box)
    half = plan["half_newtons"]
    resolved, overlap = judge(late["contrast"], half, predicted)
    return {
        "contrast_newtons": late["contrast"],
        "early_contrast_newtons": early["contrast"],
        "reference_contrast_newtons": late["reference_contrast"],
        "optical_raw_newtons": raw, "predicted_newtons": predicted,
        "half_newtons": half, "resolved": resolved, "overlap": overlap,
        "reference_flag": reference_flag(
            late["reference_contrast"], plan, predicted),
    }


def reference_flag(reference_contrast, plan, predicted):
    """Reference contrast above its leak band and read bound, section 8."""
    terms = plan["planned"]["late"]["plain"]
    settings = scenario_settings(plan["scenario"])
    band = ((LEAK+BASE["leakage_knowledge"])
            * max(abs(predicted[0]), abs(predicted[1]))
            + 2*REFERENCE.noise_bound_newtons
            + 2*settings["s_r"]*terms["r_level"]
            + 2*REFERENCE.vibration_newtons
            * bounds.mean_kernel(10, BAND[0], STEP))
    return abs(reference_contrast) > band


def truth_value(draws, inputs):
    """Audit only. Actual transfer times injected contrast; never estimated."""
    arch = draws["arch"]
    half = arch.dwells//2
    total = 0.0
    signal = inputs["signal"]
    if draws["control"] in ("impostor-source-fixed-lag-10s",
                            "impostor-source-fixed-lag-0p1s"):
        # Not held per dwell, so settling is not the rho term: the injected
        # contrast is defined after the channel's own response.
        quiet = replace(PRIMARY, thermal_newtons_per_watt=0.0)
        signal = run_channel(quiet, signal, [0.0]*SAMPLES)
    if draws["control"] == "reference-path-label-mimic":
        # The injected contrast travels through coupling, so it is audited there.
        quiet = replace(REFERENCE, thermal_newtons_per_watt=0.0)
        change = [(inputs["coupling"][k//arch.size]
                   - COUPLING*(1+draws["blind"][k//arch.size]))
                  * inputs["common"][k] for k in range(SAMPLES)]
        states = run_channel(quiet, change, [0.0]*SAMPLES)
        return -draws["w"]*(1+draws["gr"])*math.fsum(
            sigma*_mean(states, window_indices(arch, arch.late, i))
            for i, sigma in enumerate(draws["order"]))/half
    for i, sigma in enumerate(draws["order"]):
        total += sigma*_mean(signal, window_indices(arch, arch.late, i))
    actual = (1+draws["gp"])-draws["w"]*draws["leak"]*(1+draws["gr"])
    return actual*total/half


def _aligned(interval):
    if interval[0] > 0:
        return 1, interval
    if interval[1] < 0:
        return -1, [-interval[1], -interval[0]]
    return 1, interval


def dual_frame(plus, minus, plan):
    """Optical coefficients and half-widths of one pair, for every dual use."""
    sign_p, optical_p = _aligned(plus["optical_raw_newtons"])
    sign_m, optical_m = _aligned(
        [-minus["optical_raw_newtons"][1], -minus["optical_raw_newtons"][0]])
    half = (plus["half_newtons"]+minus["half_newtons"])/2
    box = plan["planned"]["late"]["box"]
    walk = plan.get("walk_newtons") or 0.0
    raw = [(optical_p[0]+optical_m[0])/2-walk, (optical_p[1]+optical_m[1])/2+walk]
    predicted = map_interval(raw, [box[0]-FLIP, box[1]+FLIP])
    return {"signs": (sign_p, sign_m), "half": half, "predicted": predicted,
            "sigma_half": half+FLIP*max(abs(predicted[0]), abs(predicted[1]))}


def dual_combine(frame, value_plus, value_minus):
    """D and Sigma of two values. Contrasts and truths both pass through here."""
    k_p = frame["signs"][0]*value_plus
    k_m = frame["signs"][1]*value_minus
    return (k_p-k_m)/2, (k_p+k_m)/2


def dual(plus, minus, plan, control):
    """Source-frame difference D and lab-frame sum Sigma; no averaging credit."""
    frame = dual_frame(plus, minus, plan)
    difference, total = dual_combine(frame, plus["contrast_newtons"],
                                     minus["contrast_newtons"])
    resolved, overlap = judge(difference, frame["half"], frame["predicted"])
    return (resolved, overlap, abs(total) > frame["sigma_half"])


def dual_truth_pair(plus, minus, truth_plus, truth_minus, plan):
    """Errors of D and Sigma against truths under the decision's own frame."""
    frame = dual_frame(plus, minus, plan)
    d, s = dual_combine(frame, plus["contrast_newtons"],
                        minus["contrast_newtons"])
    t_d, t_s = dual_combine(frame, truth_plus, truth_minus)
    return {"d": abs(d-t_d), "d_half": frame["half"], "sigma": abs(s-t_s),
            "sigma_half": frame["sigma_half"]}


def dual_truth_audit(pairs, expected):
    """Condition 3, dual: counts, worst cases and any failing pair, compactly.

    pairs holds [seed, control, plus row index, minus row index, result].
    """
    fields = ["seed", "control", "plus_row", "minus_row", "d_error", "d_half",
              "sigma_error", "sigma_half"]

    def compact(pair):
        seed, control, first, second, r = pair
        return [seed, control, first, second, r["d"], r["d_half"], r["sigma"],
                r["sigma_half"]]

    def covered(pair):
        return pair[4]["d"] <= pair[4]["d_half"] and (
            pair[4]["sigma"] <= pair[4]["sigma_half"])

    def worst(key, half):
        return max(pairs, key=lambda p: p[4][key]/p[4][half], default=None)

    failing = [compact(pair) for pair in pairs if not covered(pair)]
    worst_d, worst_sigma = worst("d", "d_half"), worst("sigma", "sigma_half")
    return {"passed": bool(pairs) and len(pairs) == expected and not failing,
            "expected": expected, "checked": len(pairs),
            "covered": len(pairs)-len(failing), "fields": fields,
            "worst_d": compact(worst_d) if worst_d else None,
            "worst_sigma": compact(worst_sigma) if worst_sigma else None,
            "failing": failing}


def lag_decision(row, arch, order, tau_hat, plan):
    """Lambda_lag of section 8, from the estimator's own constants."""
    k = _early_ratio(arch, order, tau_hat)
    dk = max(abs(_early_ratio(arch, order, tau_hat*(1+s*LAG_KNOWLEDGE))-k)
             for s in (-1, 1))
    statistic = row["early_contrast_newtons"]-k*row["contrast_newtons"]
    early = plan["planned"]["early"]
    half_early = early["signal"]+plan["allowance_newtons"]
    half = (half_early+k*row["half_newtons"]
            + abs(row["contrast_newtons"])*dk)
    return {"statistic_newtons": statistic, "half_newtons": half,
            "separated": abs(statistic) > half}


def rank_matrix(arch, order, lag, tau, leak=LEAK, coupling=COUPLING):
    """Scaled J of section 8, for numeric rank and smallest singular value."""
    k = _early_ratio(arch, order, tau)
    balance = replace(PRIMARY, thermal_newtons_per_watt=0.0)
    drive = [float(order[i//arch.size]) for i in range(SAMPLES)]
    weight = -math.expm1(-STEP/lag)
    state, lagged = 0.0, []
    for value in drive:
        state += weight*(value-state)
        lagged.append(state)
    states = run_channel(balance, lagged, [0.0]*SAMPLES)

    def contrast(window):
        return math.fsum(order[i]*_mean(states, window_indices(arch, window, i))
                         for i in range(arch.dwells))/arch.dwells
    q_l, q_e = contrast(arch.late), contrast(arch.early)
    return [[1, 1, q_l, 0, 1],
            [0, 0, 0, 1, 0],
            [k, k, q_e, 0, k],
            [0, 0, 0, k, 0],
            [leak, leak, leak*q_l, leak, coupling]]


def singular_values(matrix, sweeps=64):
    """Square roots of the eigenvalues of J^T*J, by cyclic Jacobi rotations."""
    columns = list(zip(*matrix))
    n = len(columns)
    a = [[math.fsum(x*y for x, y in zip(columns[i], columns[j]))
          for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = math.fsum(a[i][j]**2 for i in range(n) for j in range(n) if i != j)
        if off < 1e-40:
            break
        for p in range(n-1):
            for q in range(p+1, n):
                if a[p][q] == 0.0:
                    continue
                angle = (a[q][q]-a[p][p])/(2*a[p][q])
                tangent = math.copysign(1, angle)/(
                    abs(angle)+math.sqrt(1+angle*angle))
                cosine = 1/math.sqrt(1+tangent*tangent)
                sine = tangent*cosine
                for k in range(n):
                    x, y = a[k][p], a[k][q]
                    a[k][p], a[k][q] = cosine*x-sine*y, sine*x+cosine*y
                for k in range(n):
                    x, y = a[p][k], a[q][k]
                    a[p][k], a[q][k] = cosine*x-sine*y, sine*x+cosine*y
    return sorted(math.sqrt(max(0.0, a[i][i])) for i in range(n))


def rank_diagnostics(arch):
    """Structural properties of J only, never evidence of separation.

    Columns r and s_i are the same expressions, so the full J has a smallest
    singular value of exactly zero. That is stated by the exact equality, not
    by numerics. The value without s_i is a different matrix, and is labelled.
    """
    order = permitted_orders(arch)[0]
    matrix = rank_matrix(arch, order, PROTOCOL["impostor_lag_seconds"][0],
                         PRIMARY.response_seconds)
    columns = list(zip(*matrix))
    duplicated = columns[0] == columns[1]
    reduced = [row[:1]+row[2:] for row in matrix]
    return {
        "numeric_rank": numeric_rank(matrix), "columns": len(columns),
        "recoil_and_instant_columns_identical": duplicated,
        "sigma_min_full_j": 0.0 if duplicated else singular_values(matrix)[0],
        "sigma_min_full_j_scope":
            "exactly_zero_by_duplicate_columns" if duplicated else "numerical",
        "sigma_min_without_instant_column": singular_values(reduced)[0],
    }


def numeric_rank(matrix, tolerance=1e-9):
    rows = [list(map(float, row)) for row in matrix]
    rank = 0
    for column in range(len(rows[0])):
        pivot = max(range(rank, len(rows)), key=lambda r: abs(rows[r][column]),
                    default=None)
        if pivot is None or abs(rows[pivot][column]) < tolerance:
            continue
        rows[rank], rows[pivot] = rows[pivot], rows[rank]
        for r in range(rank+1, len(rows)):
            factor = rows[r][column]/rows[rank][column]
            rows[r] = [x-factor*y for x, y in zip(rows[r], rows[rank])]
        rank += 1
    return rank


def evidence_state(*, certified, valid, m_uniform_up, pointwise):
    """Section 9.2. Bound nonattainment never enters this decision."""
    if not valid:
        return "inconclusive_invalid_envelope"
    if certified:
        return "certified"
    if any(value < REQUIRED for value in pointwise):
        return "admissible_pointwise_failure"
    if m_uniform_up is not None and m_uniform_up < REQUIRED:
        return "uniform_criterion_nonqualification"
    return "certification_gap"


def pointwise_null(contrast_w, truth_w, predicted_w, allowance):
    """Signed distance of C +/- h from this witness's own predicted interval.

    h is the smallest half-width truthful for this realisation. Positive is
    disjoint and negative is overlap by that depth. Error is never reflected
    toward the optical window.
    """
    half = abs(contrast_w-truth_w)+allowance
    return max(predicted_w[0]-(contrast_w+half),
               (contrast_w-half)-predicted_w[1])


def pointwise_signal(contrast_w, truth_w, allowance):
    """Signed distance of C +/- h from zero, on the side of the truth."""
    half = abs(contrast_w-truth_w)+allowance
    return math.copysign(1, truth_w)*contrast_w-half


def uniform_upper(lower, errors, allowance):
    return lower-2*max(errors)-allowance


def chase_path(arch, order, s, offset):
    """Slew-limited path that follows the label: admissible by construction."""
    slew = abs(s)*LEVELS["slew_fraction_of_amplitude_per_second"]
    state = {"value": s*order[0], "block": 0}

    def value(block):
        while state["block"] < block:
            state["block"] += 1
            sample = min(SAMPLES-1, max(0, offset+HOLD_SAMPLES*state["block"]-1))
            target = s*order[sample//arch.size]
            change = max(-slew, min(slew, target-state["value"]))
            state["value"] += change
        return state["value"]
    return block_values(offset, value)


def witness_draws(arch, scenario, dose, kind, sign):
    """Adversarial realisation: admissible, endpoint-reaching and deterministic."""
    control = "force-decoupled" if kind == "null" else "opposite-phase"
    settings = scenario_settings(scenario)
    draws = draw(arch, scenario, dose, 1, control, 1, "witness")
    order = permitted_orders(arch)[0 if sign > 0 else 1]
    draws["order"] = order
    positive = QUARTER if recoil(QUARTER, 1) > 0 else -QUARTER
    draws["phases"] = [sigma*draws["mapping"]*positive for sigma in order]
    draws["feeds"] = [1.0]*arch.dwells
    dg, dw = BASE["calibration_knowledge"], BASE["weight_knowledge"]
    draws["gp"] = PRIMARY.calibration_fraction+sign*dg
    draws["gr"] = REFERENCE.calibration_fraction-sign*dg
    draws["w"] = WEIGHT+dw
    draws["xi_p"] = PILOT["response_time_estimator_knowledge_fraction"]*sign
    draws["xi_r"] = -PILOT["response_time_estimator_knowledge_fraction"]*sign
    size = arch.size
    classes = settings["classes"]
    s_p, s_r = settings["s_p"], settings["s_r"]
    e_p, e_r = [0.0]*SAMPLES, [0.0]*SAMPLES
    offset = draws["offset"]
    if "slow_drift" in classes:
        e_p = [x+y for x, y in zip(e_p, slow_path(s_p, s_p, offset))]
        e_r = [x+y for x, y in zip(e_r, slow_path(-s_r, -s_r, offset))]
    if "bounded_rate" in classes:
        e_p = [x+y for x, y in zip(e_p, chase_path(arch, order, s_p, offset))]
        e_r = [x+y for x, y in zip(e_r, chase_path(arch, order, -s_r, offset))]
    if "label_correlated" in classes:
        e_p = [x+order[k//size]*s_p for k, x in enumerate(e_p)]
        e_r = [x-order[k//size]*s_r for k, x in enumerate(e_r)]
    if "label_within_window" in classes:
        e_p = [x+y for x, y in zip(e_p, within_window_path(
            arch, order, s_p, 1, offset))]
        e_r = [x+y for x, y in zip(e_r, within_window_path(
            arch, order, s_r, -1, offset))]
    draws["e_p"], draws["e_r"] = e_p, e_r
    draws["blind"] = [s*settings["blind"] for s in order]
    draws["common"] = [s*settings["common"] for s in order]
    draws["a"] = [s*PILOT["actuator_label_fraction_bound"] for s in order]
    draws["k"] = [s*PILOT["coupling_label_fraction_bound"] for s in order]
    draws["tau"] = [s*PILOT["timing_label_bound_seconds"] for s in order]
    draws["kappa"] = PILOT["coupling_constant_interval"][0]
    return draws


def bound_noise(arch, order, sign, mode, tau_hat, omega):
    """Read noise at its bound; "aligned" follows the sign of the weights."""
    path_p, path_r = [0.0]*SAMPLES, [0.0]*SAMPLES
    if mode == "off":
        return path_p, path_r
    n_p = PRIMARY.noise_bound_newtons
    n_r = REFERENCE.noise_bound_newtons
    times = window_times(arch, arch.late)
    if mode == "aligned" and arch.pilot:
        u_p = bounds.point_weights(tau_hat[0], times, omega)
        u_r = bounds.point_weights(tau_hat[1], times, omega)
    for i, sigma in enumerate(order):
        for q, k in enumerate(window_indices(arch, arch.late, i)):
            path_p[k] = sign*sigma*n_p
            path_r[k] = -sign*sigma*n_r
            if mode == "aligned" and arch.pilot:
                path_p[k] = sign*sigma*n_p*math.copysign(1, u_p[q])
                path_r[k] = -sign*sigma*n_r*math.copysign(1, u_r[q])
    return path_p, path_r


def witness_limits(scenario):
    """Declared class of a scenario, as plain numbers for the validator."""
    settings = scenario_settings(scenario)
    factor = amplitude_factor(settings)
    step_p, step_r = window_step(settings)
    labelled = settings["classes"] & {"label_correlated", "label_within_window"}
    return {
        "gp_centre": PRIMARY.calibration_fraction,
        "gr_centre": REFERENCE.calibration_fraction,
        "calibration": BASE["calibration_knowledge"],
        "weight_centre": WEIGHT, "weight": BASE["weight_knowledge"],
        "xi": PILOT["response_time_estimator_knowledge_fraction"],
        "kappa": PILOT["coupling_constant_interval"],
        "a": PILOT["actuator_label_fraction_bound"],
        "k": PILOT["coupling_label_fraction_bound"],
        "tau": PILOT["timing_label_bound_seconds"],
        "blind": settings["blind"], "common": settings["common"],
        "amplitude_p": factor*settings["s_p"],
        "amplitude_r": factor*settings["s_r"],
        "slew_p": None if labelled else step_p,
        "slew_r": None if labelled else step_r,
        "dwell_slew_p": step_p, "dwell_slew_r": step_r,
        "noise_p": PRIMARY.noise_bound_newtons,
        "noise_r": REFERENCE.noise_bound_newtons,
        "phase_jitter": BASE["phase_jitter_radians"],
        "feed_variation": BASE["feed_variation_fraction"],
        "leak_centre": LEAK, "leak": BASE["leakage_knowledge"],
        "vibration_band": BAND,
        "hold_samples": HOLD_SAMPLES, "samples": SAMPLES,
    }


def witness_provenance(draws, arch, scenario, dose, kind, sign, noise):
    """Generating arguments, scalars and a digest of paths, to regenerate it."""
    paths = {key: draws[key] for key in (
        "e_p", "e_r", "a", "k", "tau", "blind", "common", "phases", "feeds",
        "psi", "xi")}
    digest = hashlib.sha256(json.dumps(
        paths, sort_keys=True, separators=(",", ":")).encode("ascii"))
    return {
        "source": "witness_draws", "architecture": arch.name,
        "scenario": scenario, "dose": dose, "kind": kind, "sign": sign,
        "noise": noise, "offset": draws["offset"],
        "order": list(draws["order"]), "gp": draws["gp"], "gr": draws["gr"],
        "w": draws["w"], "leak": draws["leak"], "xi_p": draws["xi_p"],
        "xi_r": draws["xi_r"], "kappa": draws["kappa"],
        "vibration": draws["vibration"],
        "paths_sha256": "sha256:"+digest.hexdigest()}


def run_witness(arch, scenario, dose, kind, sign, plan, *, detector=None,
                noise="bound"):
    """One admissible realisation. An inadmissible one makes no reading."""
    draws = witness_draws(arch, scenario, dose, kind, sign)
    amplitude = pilot_amplitude(dose) if arch.pilot else None
    omega = 2*math.pi*PILOT["frequency_hertz"]
    tau_hat = (PRIMARY.response_seconds*(1+draws["xi_p"]),
               REFERENCE.response_seconds*(1+draws["xi_r"]))
    path = bound_noise(arch, draws["order"], sign, noise, tau_hat, omega)
    limits = {**witness_limits(scenario), "orders": permitted_orders(arch),
              "dwell_samples": arch.size}
    violations = oracle.admissible(draws, limits, noise_path=path)
    provenance = witness_provenance(draws, arch, scenario, dose, kind, sign,
                                    noise)
    if violations:
        return {"kind": kind, "sign": sign, "admissible": False,
                "violations": violations, "provenance": provenance,
                "within_bound": False, "decision_matches": False}
    inputs = forces(draws, amplitude)
    row = assess(draws, plan, detector=detector, noise_path=path,
                 readings=read_channels(draws, inputs, noise_path=path))
    truth = truth_value(draws, inputs)
    error = abs(row["contrast_newtons"]-truth)
    limit = (plan["null_bound_newtons"] if kind == "null"
             else plan["signal_bound_newtons"])
    predicted = row["predicted_newtons"]
    allowance = plan["allowance_newtons"]
    if kind == "null":
        pointwise = pointwise_null(row["contrast_newtons"], truth, predicted,
                                   allowance)
        expected = SINGLE["force-decoupled"]
    else:
        pointwise = pointwise_signal(row["contrast_newtons"], truth, allowance)
        expected = SINGLE["opposite-phase"]
    return {
        "kind": kind, "sign": sign, "admissible": True, "violations": [],
        "provenance": provenance, "contrast_newtons": row["contrast_newtons"],
        "truth_newtons": truth, "error_newtons": error,
        "predicted_newtons": predicted, "pointwise_newtons": pointwise,
        "decision_matches": (row["resolved"], row["overlap"]) == expected,
        "bound_newtons": limit, "within_bound": error <= limit+NUMERIC,
        "bound_nonattainment_newtons": limit-error,
        "attainment_fraction": error/limit,
    }


OUTLIER = "impostor-out-of-window"


def stimulus_row(identifier, contrast, truth, half, resolved, overlap, plan):
    """Every audit field, with the legacy containment beside the amended one."""
    stimulus = plan["stimulus"]
    error = abs(contrast-truth)
    within = (stimulus["status"] == "valid"
              and error <= stimulus["bound_newtons"]+NUMERIC)
    return [identifier, contrast, truth, error, half, error <= half,
            stimulus["bound_newtons"], within, resolved, overlap]


def run_stimulus_witness(arch, scenario, dose, sign, plan, *, detector=None):
    """Deterministic adversarial outlier, admissible and through the channels."""
    draws = witness_draws(arch, scenario, dose, "null", sign)
    draws["control"] = OUTLIER
    amplitude = pilot_amplitude(dose) if arch.pilot else None
    omega = 2*math.pi*PILOT["frequency_hertz"]
    tau_hat = (PRIMARY.response_seconds*(1+draws["xi_p"]),
               REFERENCE.response_seconds*(1+draws["xi_r"]))
    path = bound_noise(arch, draws["order"], sign, "aligned", tau_hat, omega)
    limits = {**witness_limits(scenario), "orders": permitted_orders(arch),
              "dwell_samples": arch.size}
    violations = oracle.admissible(draws, limits, noise_path=path)
    provenance = witness_provenance(draws, arch, scenario, dose, "stimulus",
                                    sign, "aligned")
    if violations:
        return {"sign": sign, "admissible": False, "violations": violations,
                "provenance": provenance, "row": None}
    inputs = forces(draws, amplitude)
    row = assess(draws, plan, detector=detector, noise_path=path,
                 readings=read_channels(draws, inputs, noise_path=path))
    truth = truth_value(draws, inputs)
    return {"sign": sign, "admissible": True, "violations": [],
            "provenance": provenance,
            "row": stimulus_row(f"witness{sign:+d}", row["contrast_newtons"],
                                truth, row["half_newtons"], row["resolved"],
                                row["overlap"], plan)}


def stimulus_audit(plan, rows, witnesses, legacy_contained):
    """Section 6.7. E_x is audit only, and the legacy result stays visible."""
    stimulus = plan["stimulus"]
    counted = rows+[w["row"] for w in witnesses if w["row"] is not None]
    passed = (stimulus["status"] == "valid" and bool(counted)
              and all(row[7] for row in counted)
              and all(w["admissible"] for w in witnesses))
    return {"passed": passed, "bound_status": stimulus["status"],
            "bound_reason": stimulus["reason"],
            "legacy_all_rows_contained_by_B": legacy_contained,
            "fields": ["id", "contrast", "truth", "error", "half",
                       "contained_by_B", "bound", "within_bound", "resolved",
                       "overlap"],
            "rows": rows, "witnesses": witnesses}


def configurations():
    rows = [(arch, scenario, 0) for arch in ARCHITECTURES
            for scenario in PROTOCOL["scenarios"]]
    arch = next(a for a in ARCHITECTURES
                if a.name == PROTOCOL["dose_rows"]["architecture"])
    rows += [(arch, PROTOCOL["dose_rows"]["scenario"], dose)
             for dose in (1, 2)]
    return rows


def classify(plan, seeded_ok, mimic_ok, truth_ok, witnesses, failed, *,
             stimulus_ok):
    """Section 9.1 precedence: validity is read before any margin.

    stimulus_ok has no default, so a missing audit cannot pass by omission.
    """
    if failed:
        return "operational_failure"
    bound_ok = all(w["within_bound"] for w in witnesses)
    admissible = all(w["admissible"] for w in witnesses)
    if (not plan["valid"] or not bound_ok or not mimic_ok or not admissible
            or not stimulus_ok):
        return "inconclusive_invalid_envelope"
    margins = (plan["m_null_newtons"] >= REQUIRED
               and plan["m_signal_newtons"] >= REQUIRED)
    rejected = all(w["decision_matches"] for w in witnesses
                   if w["kind"] == "null")
    if seeded_ok and truth_ok and margins and rejected:
        return "stationarity_margin_positive_conditional"
    if seeded_ok and truth_ok:
        return "seeded_pass_not_robust"
    return "negative"


def hypothesis_one(outcome, evidence):
    """H1 from its row. Class 1 or 2 is inconclusive whatever its margin."""
    if outcome in ("operational_failure", "inconclusive_invalid_envelope"):
        return {"status": "inconclusive", "evidence": None}
    if outcome == "stationarity_margin_positive_conditional":
        return {"status": "certified_conditional", "evidence": evidence}
    return {"status": "certification_not_met", "evidence": evidence}


def hypothesis_ten(row):
    """Validity precedence first. Structural rank is reported elsewhere."""
    if row["outcome"] in ("operational_failure",
                          "inconclusive_invalid_envelope"):
        return {"status": "inconclusive", "row_outcome": row["outcome"]}
    return {"status": row["lag_state"], "row_outcome": row["outcome"]}


def sweep_evaluations():
    """Declared envelope-only sweeps, one at a time, capped by the protocol."""
    sweeps = PROTOCOL["exploratory"]["envelope_only_sweeps"]
    arch = by_prefix("A3")
    scenario = PROTOCOL["primary_decision"]["scenario"]
    rows = [("pilot_amplitude_newtons", v, {"amplitude": v})
            for v in sweeps["pilot_amplitude_newtons"]]
    rows += [("pilot_frequency_hertz", v, {"frequency": v})
             for v in sweeps["pilot_frequency_hertz"]]
    windows = dict(zip(sweeps["pilot_frequency_hertz"],
                       sweeps["pilot_frequency_window_samples"]))
    rows += [("pilot_coupling_bound_fraction", v, {"kappa": v})
             for v in sweeps["pilot_coupling_bound_fraction"]]
    rows += [("blind_level_fraction", v, {"blind": v})
             for v in sweeps["blind_level_fraction"]]
    rows += [("structural_allowance_scale", v, {"structural": v})
             for v in sweeps["structural_allowance_scale"]]
    rows += [("dwell_seconds", v, {"dwell": v}) for v in sweeps["dwell_seconds"]]
    if len(rows) > sweeps["maximum_evaluations"]:
        raise ValueError("sweep cap exceeded")
    output = []
    for name, value, options in rows:
        if name == "dwell_seconds":
            length = sweeps["dwell_order_length"][
                sweeps["dwell_seconds"].index(value)]
            size = round(value/STEP)
            variant = Architecture(
                f"sweep-dwell-{value}", length, size, (size-9, size),
                (size//2-9, size//2), False, 1e-5, "ABBA_thue_morse")
            plan = design(variant, "S03-rate-retained")
        elif name == "pilot_frequency_hertz":
            count = windows[value]
            variant = replace(arch, name=f"sweep-frequency-{value}",
                              late=(arch.size-count+1, arch.size))
            plan = design(variant, scenario, overrides=tuple(options.items()))
        else:
            plan = design(arch, scenario, overrides=tuple(options.items()))
        output.append({"sweep": name, "value": value,
                       "result": public_design(plan)})
    return output


def direct_comparison(arch, scenario, dose, seed, mode):
    """Largest reading difference between the two formulations, noise off."""
    draws = draw(arch, scenario, dose, seed, "force-decoupled", 1, mode)
    inputs = forces(draws, pilot_amplitude(dose) if arch.pilot else None)
    silent = ([0.0]*SAMPLES, [0.0]*SAMPLES)
    primary = read_channels(draws, inputs, noise_path=silent)
    direct = read_direct(draws, inputs)
    return max(abs(x-y) for pair_a, pair_b in zip(primary, direct)
               for x, y in zip(pair_a, pair_b))


def mimics(outcome, expected, paired):
    """A mimic matches its expectation, or the recoil row of its own seed.

    When the half-width is too wide for recoil itself to resolve, a mimic that
    behaves as recoil does is still a mimic, not a model defect.
    """
    return outcome == expected or outcome == paired


def run_configuration(arch, scenario, dose, seeds, mode):
    plan = design(arch, scenario, dose)
    usable = plan["planned"].get("late") and plan["planned"].get("early")
    failed = not usable
    seeded_ok, mimic_ok, truth_ok = True, True, True
    rows, largest, lag_rows, lab_rows = [], 0.0, [], []
    stimulus_rows, legacy_contained, dual_pairs = [], True, []
    reference_hits = {"mimic": 0, "total": 0}
    amplitude = pilot_amplitude(dose) if arch.pilot else None
    for seed in seeds if usable else ():
        recoil_rows, recoil_dual = {}, None
        for control in PROTOCOL["controls"]:
            orientations = ((1,) if control == "impostor-out-of-window"
                            else (1, -1))
            pair = {}
            for orientation in orientations:
                draws = draw(arch, scenario, dose, seed, control, orientation,
                             mode)
                try:
                    inputs = forces(draws, amplitude)
                    row = assess(draws, plan,
                                 readings=read_channels(draws, inputs))
                except OperationalFailure:
                    failed = True
                    continue
                truth = truth_value(draws, inputs)
                error = abs(row["contrast_newtons"]-truth)
                largest = max(largest, error)
                legacy_contained = (legacy_contained
                                    and error <= row["half_newtons"])
                if control == OUTLIER:
                    stimulus_rows.append(stimulus_row(
                        seed, row["contrast_newtons"], truth,
                        row["half_newtons"], row["resolved"], row["overlap"],
                        plan))
                else:
                    truth_ok = truth_ok and error <= row["half_newtons"]
                outcome = (row["resolved"], row["overlap"])
                expected = single_expectation(control, orientation)
                if control == "opposite-phase":
                    recoil_rows[orientation] = outcome
                detection_row = (control == "impostor-lab-fixed-in-window"
                                 and orientation == -1)
                if control in MIMIC and not detection_row:
                    mimic_ok = mimic_ok and mimics(
                        outcome, expected, recoil_rows.get(orientation))
                else:
                    seeded_ok = seeded_ok and outcome == expected
                if control == "reference-path-label-mimic":
                    reference_hits["total"] += 1
                    reference_hits["mimic"] += row["reference_flag"]
                if orientation == 1 and control in (
                        "impostor-source-fixed-instant",
                        "impostor-source-fixed-lag-10s",
                        "impostor-source-fixed-lag-0p1s"):
                    tau = PRIMARY.response_seconds*(1+draws["xi_p"])
                    lag = lag_decision(row, arch, draws["order"], tau, plan)
                    lag_rows.append([seed, control, lag["separated"],
                                     lag["statistic_newtons"],
                                     lag["half_newtons"]])
                pair[orientation] = (row, truth, len(rows))
                rows.append([seed, control, orientation,
                             row["contrast_newtons"], truth, row["resolved"],
                             row["overlap"]])
            if len(pair) == 2 and control in DUAL:
                (plus, truth_p, row_p), (minus, truth_m, row_m) = (pair[1],
                                                                   pair[-1])
                dual_pairs.append([seed, control, row_p, row_m, dual_truth_pair(
                    plus, minus, truth_p, truth_m, plan)])
                outcome = dual(plus, minus, plan, control)
                if control == "opposite-phase":
                    recoil_dual = outcome
                if control == "impostor-lab-fixed-in-window":
                    row = lab_detection_row(seed, outcome, recoil_dual)
                    lab_rows.append(row)
                    seeded_ok = seeded_ok and row[4]
                elif control in MIMIC:
                    mimic_ok = mimic_ok and mimics(outcome, DUAL[control],
                                                   recoil_dual)
                else:
                    seeded_ok = seeded_ok and outcome == DUAL[control]
    witnesses = []
    if usable:
        try:
            for kind, sign in product(("null", "signal"), (1, -1)):
                witnesses.append(run_witness(arch, scenario, dose, kind, sign,
                                             plan))
            for sign in (1, -1):
                witnesses.append(run_witness(
                    arch, scenario, dose, "null", sign, plan,
                    noise="aligned" if arch.pilot else "off"))
            stimulus_witnesses = [run_stimulus_witness(arch, scenario, dose,
                                                       sign, plan)
                                  for sign in (1, -1)]
        except OperationalFailure:
            failed = True
    audit = (stimulus_audit(plan, stimulus_rows, stimulus_witnesses,
                            legacy_contained) if usable and not failed
             else {"passed": False, "bound_status": "not_evaluated",
                   "bound_reason": None,
                   "legacy_all_rows_contained_by_B": legacy_contained,
                   "fields": [], "rows": stimulus_rows, "witnesses": []})
    dual_audit = dual_truth_audit(dual_pairs, len(seeds)*len(DUAL))
    return evaluate(plan, seeded_ok, mimic_ok, truth_ok and dual_audit["passed"],
                    witnesses, failed, rows, largest, lag_rows,
                    lag_classification(lag_rows), reference_hits, lab_rows,
                    audit, dual_audit)


def lab_detection_row(seed, outcome, recoil_dual):
    """Full tuple, the section 9 predicate and the revision 8 flag.

    The predicate is exactly the section 3.2 tuple. This is a contradiction
    row, not a mimic row, so a miss fails condition 2 and never model validity.
    The last field records what revision 8 did, as evidence, and decides nothing.
    """
    expected = DUAL["impostor-lab-fixed-in-window"]
    excused = recoil_dual if not (recoil_dual and recoil_dual[0]) else None
    return [seed, outcome[0], outcome[1], outcome[2], outcome == expected,
            not mimics(outcome, expected, excused)]


def lag_classification(lag_rows):
    """Section 8: achieved separation, decided on rows, never from rank."""
    def separated(control):
        return [row[2] for row in lag_rows if row[1] == control]

    adverse = (separated("impostor-source-fixed-instant")
               + separated("impostor-source-fixed-lag-0p1s"))
    lagged = separated("impostor-source-fixed-lag-10s")
    if any(adverse):
        return "inconclusive_invalid_envelope"
    if lagged and all(lagged):
        return "attribution_separated_conditional"
    return "rank_raised_not_resolved"


def evaluate(plan, seeded_ok, mimic_ok, truth_ok, witnesses, failed, rows,
             largest, lag_rows, lag_state, reference_hits, lab_rows, audit,
             dual_audit):
    lower = plan.get("lower_newtons", 0.0)
    allowance = plan.get("allowance_newtons", 0.0)
    counted = [w for w in witnesses if w["admissible"]]
    errors = [w["error_newtons"] for w in counted if w["kind"] == "null"]
    up = uniform_upper(lower, errors, allowance) if errors else None
    result = classify(plan, seeded_ok, mimic_ok, truth_ok, witnesses, failed,
                      stimulus_ok=audit["passed"])
    state = None
    if result not in ("operational_failure", "inconclusive_invalid_envelope"):
        state = evidence_state(
            certified=result == "stationarity_margin_positive_conditional",
            valid=True, m_uniform_up=up,
            pointwise=[w["pointwise_newtons"] for w in counted])
    return {"outcome": result, "evidence": state, "design": public_design(plan),
            "m_uniform_up_newtons": up, "witnesses": witnesses,
            "witness_failures": [
                {"violations": w["violations"], "provenance": w["provenance"]}
                for w in witnesses if not w["admissible"]],
            "largest_seeded_error_newtons": largest, "rows": rows,
            "lag_rows": lag_rows, "lag_state": lag_state,
            "reference_mimic_detected": reference_hits,
            "large_stimulus_audit": audit, "dual_truth_audit": dual_audit,
            "lab_detection": {
                "fields": ["seed", "d_resolved", "overlap", "sigma_resolved",
                           "detected", "revision_8_mimic_flag"],
                "rows": list(lab_rows),
                "detected": sum(row[4] for row in lab_rows),
                "total": len(lab_rows)}}


def v1_form_margin(level):
    """H7: robustness v1 wander form with baseline terms, from A0 constants."""
    arch = by_prefix("A0")
    plan = design(arch, "S01-constant")
    plain = plan["planned"]["late"]["plain"]
    wmax = plain["wmax"]
    noise = 2*(PRIMARY.noise_bound_newtons
               + (wmax+level)*REFERENCE.noise_bound_newtons)
    vibration = (2*(PRIMARY.vibration_newtons
                    + (wmax+level)*REFERENCE.vibration_newtons)
                 * bounds.mean_kernel(10, BAND[0], STEP))
    gain = 2*(level*plain["p_level"]+(wmax+level)*level*plain["r_level"]
              + level*plain["r_level"])
    total = plain["base"]+plain["heat"]+noise+vibration+gain
    return plan["lower_newtons"]-2*total-2*STRUCTURAL


def v1_form_witness(level, detector=None):
    """H7 witness through the channels, with v1's per-dwell weight wander."""
    arch = by_prefix("A0")
    plan = design(arch, "S01-constant")
    draws = witness_draws(arch, "S01-constant", 0, "null", 1)
    order = draws["order"]
    draws["e_p"] = [order[k//arch.size]*level for k in range(SAMPLES)]
    draws["e_r"] = [-order[k//arch.size]*level for k in range(SAMPLES)]
    path = bound_noise(arch, order, 1, "bound", None, None)
    # A label class held per dwell: it may step at a dwell boundary only.
    limits = {**witness_limits("S01-constant"), "amplitude_p": level,
              "amplitude_r": level, "slew_p": None, "slew_r": None,
              "orders": permitted_orders(arch), "dwell_samples": arch.size}
    violations = oracle.admissible(draws, limits, noise_path=path)
    if violations:
        return {"level": level, "admissible": False, "violations": violations}
    inputs = forces(draws, None)
    y_p, y_r = read_channels(draws, inputs, noise_path=path)
    half = arch.dwells//2
    total = 0.0
    for i, sigma in enumerate(order):
        indices = window_indices(arch, arch.late, i)
        weight = draws["w"]-sigma*level
        total += sigma*(_mean(y_p, indices)-weight*_mean(y_r, indices))
    contrast = total/half
    raw = optical_contrast(draws, detector=detector)
    walk = plan["walk_newtons"]
    predicted = map_interval([raw[0]-walk, raw[1]+walk],
                             plan["planned"]["late"]["box"])
    return {"level": level, "admissible": True, "violations": [],
            "error_newtons": abs(contrast),
            "pointwise_newtons": pointwise_null(contrast, 0.0, predicted,
                                                plan["allowance_newtons"])}


def candidate_decision(detector=None):
    """H7. The bound decides; witnesses show how far the bracket is attained."""
    low, high = PROTOCOL["candidate_bracket"]["levels"]
    margins = (v1_form_margin(low), v1_form_margin(high))
    witnesses = [v1_form_witness(low, detector), v1_form_witness(high, detector)]
    if not all(w["admissible"] for w in witnesses):
        return {"status": "inconclusive", "margins_newtons": margins,
                "witnesses": witnesses, "attained_by_witness": False}
    bound_holds = margins[0] >= REQUIRED > margins[1]
    return {"status": "supported" if bound_holds else "refuted",
            "margins_newtons": margins, "witnesses": witnesses,
            "attained_by_witness": (witnesses[0]["pointwise_newtons"] >= REQUIRED
                                    > witnesses[1]["pointwise_newtons"])}


def decide_hypotheses(outcomes):
    """H1 to H11 from retained rows. Rows in class 1 or 2 make a test inconclusive."""
    def row(arch, scenario, dose=0):
        name = next(a.name for a in ARCHITECTURES if a.name.startswith(arch))
        return outcomes[f"{name}|{scenario}|{dose}"]

    def usable(*items):
        return all(item["outcome"] not in (
            "operational_failure", "inconclusive_invalid_envelope")
            for item in items)

    def term(item, name):
        return item["design"]["terms_newtons"].get(name, 0.0)

    def judged(items, test):
        if not usable(*items):
            return "inconclusive"
        return "supported" if test() else "refuted"

    limits = PROTOCOL["hypothesis_thresholds"]
    s02, s03 = "S02-drift-retained", "S03-rate-retained"
    s05, s06 = "S05-label-retained", "S06-label-candidate"
    s07, s08 = "S07-blind-monitored", "S08-blind-candidate"
    s11 = "S11-label-within-window"
    a1_label = row("A1", s05)
    a3 = row("A3", s05)
    doses = [row("A3", s05, 1), a3, row("A3", s05, 2)]
    amplitudes = [PILOT["dose_row_amplitudes_newtons"][0],
                  PILOT["primary_amplitude_newtons"],
                  PILOT["dose_row_amplitudes_newtons"][1]]

    def exponent():
        values = [math.log(term(d, "theta")) for d in doses]
        logs = [math.log(a) for a in amplitudes]
        mean_x, mean_y = sum(logs)/3, sum(values)/3
        return (sum((x-mean_x)*(y-mean_y) for x, y in zip(logs, values))
                / sum((x-mean_x)**2 for x in logs))

    results = {
        "H1": hypothesis_one(a3["outcome"], a3["evidence"]),
        "H2": judged([row(a, s) for a in ("A0", "A1", "A2") for s in (s05, s06)],
                     lambda: abs(term(row("A0", s05), "label")
                                 - term(row("A1", s05), "label")) < 1e-13),
        "H3": judged([row(a, s02) for a in ("A0", "A1", "A2")], lambda: max(
            term(row("A1", s02), "drift"), term(row("A2", s02), "drift"))
            <= term(row("A0", s02), "drift")/limits["drift_reduction_factor"]),
        "H4": judged([row("A1", s03), row("A2", s03)], lambda: (
            term(row("A2", s03), "rate")
            <= limits["fast_rate_ratio_maximum"]*term(row("A1", s03), "rate"))),
        "H5": judged([a3, a1_label], lambda: (
            term(a3, "theta")+term(a3, "gamma")+term(a3, "mod")
            <= limits["pilot_correction_ratio_maximum"]
            * term(a1_label, "label"))),
        "H6": judged(doses, lambda: limits["dose_exponent_range"][0]
                     <= exponent() <= limits["dose_exponent_range"][1]),
        "H7": candidate_decision(),
        "H8": judged([row("A1", s07), row("A3", s07), row("A1", s08),
                      row("A3", s08)], lambda: all(
            term(row("A3", s), "blind") >= term(row("A1", s), "blind")
            for s in (s07, s08))),
        "H9": judged([row(a.name[:2], s05) for a in ARCHITECTURES], lambda: not any(
            r[2] for a in ARCHITECTURES for r in row(a.name[:2], s05)["lag_rows"]
            if r[1] == "impostor-source-fixed-instant")),
        "H10": hypothesis_ten(row("A3", "S01-constant")),
        "H11": judged([row("A3", s11), row("A1", s11)], lambda: max(
            w["error_newtons"] for w in row("A3", s11)["witnesses"])
            > row("A1", s11)["design"]["null_bound_newtons"]),
    }
    return results


def source_block(mode, commit):
    """Commit and a fixed sanitised command: no path, user or machine."""
    if (type(commit) is not str or len(commit) != 40
            or set(commit) - set("0123456789abcdef")):
        raise ValueError("commit must be 40 lowercase hexadecimal digits")
    return {"commit": commit, "mode": mode,
            "argv": ["python3", "-B", "experiments/pf-001/pf002_stationarity_v1.py",
                     mode, "--commit", commit]}


def run_cohort(mode, commit):
    """Primary execution. Refused until the twin authorises it."""
    if PROTOCOL["execution_authorised"] is not True:
        raise PermissionError("cohort execution is not authorised")
    source = source_block(mode, commit)
    check_runtime(PROTOCOL)
    cohort = PROTOCOL[mode]
    low, high = cohort["seeds"]
    outcomes = {}
    for arch, scenario, dose in configurations():
        name = f"{arch.name}|{scenario}|{dose}"
        outcomes[name] = run_configuration(arch, scenario, dose,
                                           range(low, high+1), mode)
        if mode == "exploratory":
            difference = direct_comparison(
                arch, scenario, dose, cohort["direct_injection_comparison_seed"],
                mode)
            outcomes[name]["direct_injection_difference_newtons"] = difference
            limit = PROTOCOL["tolerances"]["acquire_versus_direct_injection_newtons"]
            if difference > limit:
                outcomes[name]["outcome"] = "inconclusive_invalid_envelope"
                outcomes[name]["evidence"] = None
    record = {
        "study": PROTOCOL["study"], "kind": f"predeclared_{mode}_validation",
        "label": ENVIRONMENT, "source": source,
        "status": "virtual_lab_simulated_experiment_not_physical_evidence",
        "warning": "A failed certificate is not a statement of impossibility.",
        "runtime": check_runtime(PROTOCOL), "protocol_revision":
            PROTOCOL["protocol_revision"],
        "hypotheses": decide_hypotheses(outcomes),
        "q_diagnostics": q_diagnostics(design(
            by_prefix("A3"), PROTOCOL["primary_decision"]["scenario"])),
        "rank": {arch.name: rank_diagnostics(arch) for arch in ARCHITECTURES},
        "outcomes": outcomes,
        "implementation": {name: "sha256:"+hashlib.sha256(
            (ROOT/name).read_bytes()).hexdigest() for name in IMPLEMENTATION},
    }
    if mode == "exploratory":
        record["sweeps"] = sweep_evaluations()
    designs = [row["design"] for row in outcomes.values()]
    designs += [row["result"] for row in record.get("sweeps", [])]
    record["enclosure_sets"] = deduplicate_enclosures(designs)
    return record


def main(arguments=None):
    arguments = sys.argv[1:] if arguments is None else arguments
    if (len(arguments) != 3 or arguments[0] not in ("exploratory", "confirmatory")
            or arguments[1] != "--commit"):
        print("usage: pf002_stationarity_v1.py exploratory|confirmatory "
              "--commit COMMIT", file=sys.stderr)
        return 2
    try:
        record = run_cohort(arguments[0], arguments[2])
    except (PermissionError, ValueError) as error:
        print(error, file=sys.stderr)
        return 2
    print(json.dumps(record, sort_keys=True, ensure_ascii=True,
                     separators=(",", ":")))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
