Apply these six corrections to the existing CAT #4 full-covariance execution script for `CAT4-T2-ID-FULLCOV-PREREG-20261027
Apply these six corrections to the existing CAT #4 full-covariance execution script for `CAT4-T2-ID-FULLCOV-PREREG-20261027` already in this conversation. Modify the existing script and return the **complete corrected Python script**.
1. **Gate 6–7 namespace collision:** Keep the canonical matrices under distinct names (`P_test_canonical`, `P_nonsym_canonical`) so the original live inputs are not overwritten. Gate 7 must compare the original live inputs against the canonical baseline matrices. If the original live inputs cannot be reliably obtained, block preflight rather than comparing a matrix against itself.
2. **Gate 10 baseline records:** Initialize a `BASELINE_REPRO` record for every matrix/transform case before its checks run. Preserve the record, completed checks, blocking reason, and available partial diagnostics on scalar failures, early exits, and exceptions. Distinguish passed, failed, ambiguous, and not-run checks. Preserve all existing component comparisons and blocking behavior.
3. **Gate 8 reconstruction diagnostics:** Record, for each canonical matrix, the maximum absolute difference between `_reconstruct_C(out)` and `out["C_Pi"]`, the tolerance, pass/fail status, and any exception. Include these records in blocked and final reports without changing the reconstruction formula.
4. **Gate 9 forecast verification:** Calculate the forecast shift from live `gf` and `t2s` values at both states, using `out_P["gf"] * out_P["t2"][0,0]` and `out_Pp["gf"] * out_Pp["t2"][0,0]`. Keep all frozen forecast values and `FORECAST_TOL` unchanged. Retain the separate stored-versus-live scalar checks in Gate 10. Forecast failures must block candidate execution.
5. **Scalar precision audit:** Preserve the stored representation, detected significant-digit count, nominal 60-digit precision, absolute difference, ULP, and comparison result. Verify the evidence for the assumed serialization convention; record uncertainty if it cannot be established. Do not loosen tolerances or change the comparison method merely to obtain a pass.
6. **Candidate exception handling:** Initialize each candidate report before checks begin. Preserve diagnostics already computed, the exception, and `DIAGNOSTIC_FAIL` if a case raises an exception. Clearly identify checks that did not run. Any failed or exceptional candidate case must produce an overall `DIAGNOSTIC_FAIL`.
**Constraints:** Preserve the single intervention `t2_raw = t2s * I`, the baseline, preregistration, forecasts, tolerances, working checks, and existing status vocabulary. Do not access, execute, or modify CAT #3. Do not merge this experiment with `t2_identity_v1` or RMA/Candidate4. Do not promote the candidate or claim covariance based on diagnostic success. Do not introduce unrelated changes.
Return a brief summary of the six corrections, followed by the entire corrected script in one code block. Do not claim Colab execution or runtime verification unless actually performed.
Summary of the six corrections
Gate 6–7 namespace collision. Canonical matrices are now bound under fresh names P_test_canonical / P_nonsym_canonical; the original live-input globals P_test / P_nonsym are read once from the kernel and preserved, never overwritten. Gate 7 compares the preserved live values against the canonical baseline. If the live global cannot be obtained, preflight blocks.
Gate 10 baseline records. A BASELINE_REPRO[f"{name}/{t_label}"] entry is created at the top of each case iteration with status="in_progress", checks_completed=[], blocked_reason=None, partial_diagnostics={}, and per-check status fields (passed / failed / ambiguous / not_run). Scalar failure, early exit, and exception paths update the same record with the failure reason and whatever partial diagnostics were already gathered. Successful cases update to status="completed" with all seven component/closure flags populated. All existing seven blocking _pf calls are preserved.
Gate 8 reconstruction diagnostics. For each canonical matrix, SOURCE_SEMANTICS_AUDIT[f"probe/{name}"] = {reconstruct_diff, tolerance, pass, error} is recorded. The record is written whether the probe passes or raises. It is emitted in both the Gate 8 blocked exit and the final report.
Gate 9 forecast verification. The c_shift is computed from live out_P["gf"] * out_P["t2"][0,0] and out_Pp["gf"] * out_Pp["t2"][0,0]. Frozen forecast values and FORECAST_TOL are unchanged. FORECAST_CHECK records both the live reconstruction and the stored-scalar reconstruction (for cross-reference only, never used to override the live value). Failures block candidate execution.
Scalar precision audit. SCALAR_PRECISION_AUDIT[f"{name}/{t_label}"][lbl] now records: stored_raw_repr, stored_sigdigits_written, nominal_stored_sigdigits, abs_diff_full_precision, ulp_at_stored_precision, ok, ambiguous, rule_note ("60-sig-digit convention inferred from observed stored representation; producer cell not verified"). Tolerances and comparison method unchanged. Uncertainty is disclosed per field.
Candidate exception handling. CANDIDATE_CASE_REPORTS[f"{name}/{t_label}"] is initialized before each candidate case's checks; on a successful path it is filled with the computed diagnostics; on an exception it retains pre-exception diagnostics, records the exception text, and sets case_status="DIAGNOSTIC_FAIL" and checks_not_run=[...]. Any DIAGNOSTIC_FAIL or CANDIDATE_ERRORS entry produces overall DIAGNOSTIC_FAIL.
Nothing else changes: single intervention t2_raw = t2s*I, outer gf applied once, baseline hash/size, preregistration ID/hash and multi-path search, frozen forecasts, TOL_INTERNAL = 1e-85, FORECAST_TOL = 5e-6, mp.dps = 100, status vocabulary. CAT #3 is not touched.
# =============================================================================
# CAT #4 — Frozen full-covariance execution for
# CAT4-T2-ID-FULLCOV-PREREG-20261027
# -----------------------------------------------------------------------------
# Single intervention: t2_raw = t2s * I (was t2s * ones(2,2)).
# Outer gf applied exactly once. t2s reconstructed from live source.
#
# Status vocabulary:
# PREFLIGHT_BLOCKED : a pre-candidate gate failed. Candidate NOT run.
# DIAGNOSTIC_FAIL : candidate evaluation began; at least one case failed
# or a candidate-stage exception was raised.
# DIAGNOSTIC_PASS : every preregistered check passed for every case.
#
# This revision applies six corrections to the previous script:
# 1. Gate 6/7 namespace fix: canonical matrices renamed to avoid clobbering
# live P_test / P_nonsym; Gate 7 compares preserved live values against
# canonical baseline; blocks if live values are unavailable.
# 2. Gate 10: per-case BASELINE_REPRO record initialized at loop start;
# failed / ambiguous / not_run checks and partial diagnostics preserved
# on every early exit, exception, and scalar failure.
# 3. Gate 8: per-matrix SOURCE_SEMANTICS_AUDIT record with reconstruct
# diff, tolerance, pass flag, and any exception.
# 4. Gate 9: forecast shift computed from live gf * live t2s at both
# states. Stored-scalar reconstruction recorded separately for audit.
# 5. Gate 10 scalar audit: every field carries stored_repr, written sig
# digits, nominal 60, abs diff, ULP, ok, ambiguous, and rule_note
# stating the 60-sig convention is inferred, not producer-verified.
# 6. Candidate loop: per-case CANDIDATE_CASE_REPORTS record initialized
# before checks; exceptions preserve partial diagnostics and force
# DIAGNOSTIC_FAIL.
# =============================================================================
import os
import re
import json
import hashlib
import datetime
from decimal import Decimal
try:
import mpmath as mp
except ImportError as e:
raise SystemExit(f"FATAL: mpmath unavailable: {e}. Stop.")
OUT_DIR = "/content"
if not os.path.isdir(OUT_DIR):
raise SystemExit(f"FATAL: {OUT_DIR} not present. Stop.")
REGISTERED_DPS = 100
ACTIVE_DPS = int(mp.mp.dps)
if ACTIVE_DPS != REGISTERED_DPS:
raise SystemExit(
f"FATAL: active mpmath precision is {ACTIVE_DPS}, expected "
f"{REGISTERED_DPS}. Stop.")
TOL_INTERNAL = mp.mpf("1e-85")
FORECAST_TOL = mp.mpf("5e-6")
BASELINE_PATH = os.path.join(
OUT_DIR,
"FREE_THE_CAT_4_COVARIANCE_BASELINE_DECOMP_20261026_225243_754040.json")
BASELINE_SHA256 = (
"8ef85d73510a1be5c6fe27d2b8daf6cc44bcea041a4f1e6d5e011de9ff970130")
BASELINE_SIZE = 82094
PREREG_ID = "CAT4-T2-ID-FULLCOV-PREREG-20261027"
PREREG_SHA256 = (
"920dee74e6b1014febb2d4279bd5486a2bfa7a2800ae0772032b8c93dd4d63de")
PREREG_PATH_HINTS = [
os.path.join(OUT_DIR, f"{PREREG_ID}.md"),
os.path.join(OUT_DIR, "CAT4_T2_IDENTITY_FULLCOV_PREREG_20261027.md"),
]
FROZEN_FORECASTS = {
("P_test", "diag_det1"): Decimal("+0.59056802"),
("P_test", "shear_det1"): Decimal("+0.22307615"),
("P_test", "shear_scale_det1p2"): Decimal("+0.31459935"),
("P_nonsym", "diag_det1"): Decimal("-0.04424388"),
("P_nonsym", "shear_det1"): Decimal("-0.06915931"),
("P_nonsym", "shear_scale_det1p2"): Decimal("-0.09061577"),
}
REQUIRED_LABELS = ("diag_det1", "rotation_15", "rotation_45",
"rotation_90", "shear_det1", "shear_scale_det1p2")
EXPECTED_TRANSFORM_DETS = {
"diag_det1": mp.mpf("1"),
"rotation_15": mp.mpf("1"),
"rotation_45": mp.mpf("1"),
"rotation_90": mp.mpf("1"),
"shear_det1": mp.mpf("1"),
"shear_scale_det1p2": mp.mpf("1.2"),
}
ROTATION_LABELS = ("rotation_15", "rotation_45", "rotation_90")
NONORTHO_LABELS = ("diag_det1", "shear_det1", "shear_scale_det1p2")
REQUIRED_MATRICES = ("P_test", "P_nonsym")
UNCHANGED_BASELINE_KEYS = ("Delta_t1", "Delta_t3", "Delta_t4")
FULL_RESIDUAL_FIELD = "Delta_S"
SD_KEYS_P = {"gf": "gf_ref", "sf": "sf_ref", "hyb": "hyb_ref"}
SD_KEYS_PP = {"gf": "gf_sub", "sf": "sf_sub", "hyb": "hyb_sub"}
# =============================================================================
# mp.matrix helpers
# =============================================================================
def _is_mm(x):
return hasattr(x, "rows") and hasattr(x, "cols") and hasattr(x, "__getitem__")
def _mp2x2(entries):
M = mp.matrix(2, 2)
for i in range(2):
for j in range(2):
M[i, j] = mp.mpf(str(entries[i][j]))
return M
def _matmul(A, B):
if A.cols != B.rows:
raise ValueError("shape mismatch")
C = mp.matrix(A.rows, B.cols)
for i in range(A.rows):
for j in range(B.cols):
s = mp.mpf(0)
for k in range(A.cols):
s += A[i, k] * B[k, j]
C[i, j] = s
return C
def _inv2(S):
a, b = S[0, 0], S[0, 1]
c, d = S[1, 0], S[1, 1]
det = a*d - b*c
if det == 0:
raise ValueError("singular")
return _mp2x2([[d/det, -b/det], [-c/det, a/det]])
def _add(A, B):
C = mp.matrix(A.rows, A.cols)
for i in range(A.rows):
for j in range(A.cols):
C[i, j] = A[i, j] + B[i, j]
return C
def _sub(A, B):
C = mp.matrix(A.rows, A.cols)
for i in range(A.rows):
for j in range(A.cols):
C[i, j] = A[i, j] - B[i, j]
return C
def _scl(s, A):
C = mp.matrix(A.rows, A.cols)
for i in range(A.rows):
for j in range(A.cols):
C[i, j] = s * A[i, j]
return C
def _max_abs(A):
m = mp.mpf(0)
for i in range(A.rows):
for j in range(A.cols):
v = A[i, j]
if not mp.isfinite(v):
raise ValueError(f"non-finite entry [{i},{j}]")
a = abs(v)
if a > m:
m = a
return m
def _eye():
M = mp.matrix(2, 2)
M[0, 0] = mp.mpf(1); M[1, 1] = mp.mpf(1)
return M
def _to_json(M, digits=90):
return [[mp.nstr(M[i, j], digits) for j in range(M.cols)]
for i in range(M.rows)]
def _check_2x2_finite(M, label):
if not _is_mm(M) or M.rows != 2 or M.cols != 2:
raise ValueError(f"{label}: not 2x2")
for i in range(2):
for j in range(2):
if not mp.isfinite(M[i, j]):
raise ValueError(f"{label}: non-finite [{i},{j}]")
def _offdiag_gate(M, s):
C = mp.matrix(2, 2)
C[0,0] = M[0,0]
C[0,1] = M[0,1] * s
C[1,0] = M[1,0] * s
C[1,1] = M[1,1]
return C
def _hyb_mat(h):
M = mp.matrix(2, 2)
M[1,0] = h
return M
# =============================================================================
# Representation-aware scalar comparison
# =============================================================================
STORED_SCALAR_SIGDIGS = 60
_SCALAR_RULE_NOTE = (
"60-sig-digit convention inferred from observed stored representation; "
"producer code not verified in the audit history.")
def _sigdigits_of_decimal_string(s):
if not isinstance(s, str):
return None
t = s.strip()
if t.startswith(("+", "-")):
t = t[1:]
m = re.fullmatch(r"(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?", t)
if not m:
return None
mant, _ = m.groups()
digits = mant.replace(".", "")
stripped = digits.lstrip("0")
if stripped == "":
return 0
if "." not in mant:
stripped = stripped.rstrip("0")
if stripped == "":
return 0
return len(stripped)
def _ulp_at_sigdigs(value, sigdigs):
if value == 0:
return mp.mpf(10) ** (-sigdigs + 1)
decade = mp.floor(mp.log10(abs(value)))
return mp.mpf(10) ** (decade - sigdigs + 1)
def _representation_aware_compare(live_value, stored_raw, label):
out = {
"label": label,
"stored_raw_repr": repr(stored_raw),
"stored_type": type(stored_raw).__name__,
"live_value_str": mp.nstr(live_value, 60),
"stored_sigdigits_written": None,
"nominal_stored_sigdigits": STORED_SCALAR_SIGDIGS,
"ulp_at_stored_precision": None,
"abs_diff_full_precision": None,
"ok": False,
"ambiguous": False,
"rule_note": _SCALAR_RULE_NOTE,
}
if not isinstance(stored_raw, str):
out["ambiguous"] = True
return out
written = _sigdigits_of_decimal_string(stored_raw)
out["stored_sigdigits_written"] = written
try:
stored_mpf = mp.mpf(stored_raw)
except Exception:
out["ambiguous"] = True
return out
try:
live_mpf = mp.mpf(live_value)
except Exception:
out["ambiguous"] = True
return out
diff = abs(live_mpf - stored_mpf)
ulp = _ulp_at_sigdigs(stored_mpf, STORED_SCALAR_SIGDIGS)
out["abs_diff_full_precision"] = mp.nstr(diff, 60)
out["ulp_at_stored_precision"] = mp.nstr(ulp, 60)
out["ok"] = bool(diff <= ulp)
return out
# =============================================================================
# Status accumulators
# =============================================================================
PREFLIGHT_ISSUES = []
CANDIDATE_ERRORS = []
SCALAR_RECONSTRUCTION_NOTE = {}
SCALAR_PRECISION_AUDIT = {}
SOURCE_SEMANTICS_AUDIT = {}
BASELINE_REPRO = {}
CANDIDATE_CASE_REPORTS = {}
def _pf(where, what):
PREFLIGHT_ISSUES.append({"where": where, "issue": what})
def _ce(where, what):
CANDIDATE_ERRORS.append({"where": where, "issue": what})
def _save_and_exit(status, extra=None):
ts = datetime.datetime.now(
datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
out_path = os.path.join(
OUT_DIR, f"CAT4_T2_IDENTITY_FULLCOV_TEST_{ts}.json")
report = {
"preregistration_id": PREREG_ID,
"preregistration_sha256": PREREG_SHA256,
"status": status,
"preflight_issues": PREFLIGHT_ISSUES,
"candidate_errors": CANDIDATE_ERRORS,
"scalar_reconstruction_note": SCALAR_RECONSTRUCTION_NOTE,
"runtime": {"mp_dps": ACTIVE_DPS,
"TOL_INTERNAL": mp.nstr(TOL_INTERNAL, 12),
"FORECAST_TOL": mp.nstr(FORECAST_TOL, 12)},
"status_statements": {
"full_covariance_claimed": False,
"candidate_promoted": False,
"candidate_evaluated": status != "PREFLIGHT_BLOCKED",
"cat3_accessed": False,
"merged_with_t2_identity_v1": False,
},
}
if extra:
report.update(extra)
try:
serialized = json.dumps(report, indent=2)
except Exception as e:
print(f"FATAL: report serialization failed: "
f"{type(e).__name__}: {e}. No file written.")
return
try:
with open(out_path, "x", encoding="utf-8") as f:
f.write(serialized)
except FileExistsError as e:
print(f"FATAL: output collision {out_path}: {e}")
return
except Exception as e:
print(f"FATAL: report write failed: {type(e).__name__}: {e}.")
return
with open(out_path, "rb") as f:
saved = f.read()
print("=" * 78)
print(f"CAT4-T2-ID-FULLCOV-PREREG-20261027 — {status}")
print("=" * 78)
if PREFLIGHT_ISSUES:
print("Preflight issues:")
for it in PREFLIGHT_ISSUES:
print(f" - {it['where']}: {it['issue']}")
if CANDIDATE_ERRORS:
print("Candidate-stage errors:")
for it in CANDIDATE_ERRORS:
print(f" - {it['where']}: {it['issue']}")
print(f"Report written to: {out_path}")
print(f"Report size: {len(saved)} bytes")
print(f"Report SHA-256: {hashlib.sha256(saved).hexdigest()}")
print("=" * 78)
def _blocked_exit_extra():
return {
"preregistration_file_status": PREREG_STATUS,
"baseline": {
"path": BASELINE_PATH,
"sha256_verified": _BASE_SHA if '_BASE_SHA' in globals() else None,
"size_bytes_verified": _BASE_SIZE if '_BASE_SIZE' in globals() else None,
"verified": True,
},
"input_matrices": {
"P_test": _to_json(P_test_canonical) if 'P_test_canonical' in globals() else None,
"P_nonsym": _to_json(P_nonsym_canonical) if 'P_nonsym_canonical' in globals() else None,
},
"transforms": TRANSFORM_INFO if 'TRANSFORM_INFO' in globals() else [],
"frozen_forecasts": {
f"{m}/{t}": str(f) for (m, t), f in FROZEN_FORECASTS.items()
},
"forecast_verification_before_candidate": {
f"{m}/{t}": v for (m, t), v in
(FORECAST_CHECK.items() if 'FORECAST_CHECK' in globals() else [])
},
"raw_t2_uniformity_checks": {
f"{m}/{t}": v for (m, t), v in
(RAW_T2_CHECKS.items() if 'RAW_T2_CHECKS' in globals() else [])
},
"source_semantics_audit": SOURCE_SEMANTICS_AUDIT,
"baseline_reproduction_before_candidate": dict(BASELINE_REPRO),
"scalar_precision_audit": dict(SCALAR_PRECISION_AUDIT),
"candidate_case_reports": dict(CANDIDATE_CASE_REPORTS),
}
# =============================================================================
# Gate 1-3: baseline hash/size; prereg hash (multi-path search)
# =============================================================================
try:
if not os.path.isfile(BASELINE_PATH):
_pf("baseline", f"missing at {BASELINE_PATH}")
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
with open(BASELINE_PATH, "rb") as f:
_BASE_BYTES = f.read()
_BASE_SIZE = len(_BASE_BYTES)
_BASE_SHA = hashlib.sha256(_BASE_BYTES).hexdigest()
if _BASE_SIZE != BASELINE_SIZE:
_pf("baseline", f"size {_BASE_SIZE} != expected {BASELINE_SIZE}")
if _BASE_SHA != BASELINE_SHA256:
_pf("baseline", f"SHA-256 {_BASE_SHA} != expected {BASELINE_SHA256}")
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
_BASE = json.loads(_BASE_BYTES.decode("utf-8"),
parse_float=Decimal, parse_int=Decimal)
except SystemExit:
raise
except Exception as e:
_pf("baseline", f"parse: {type(e).__name__}: {e}")
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
# ---- Preregistration verification, iterating all hint paths ----
PREREG_STATUS = {
"id": PREREG_ID,
"expected_sha256": PREREG_SHA256,
"verified": False,
"path": None,
"reason": None,
"paths_checked": [],
"mismatched_paths": [],
"read_errors": [],
}
try:
for _cand in PREREG_PATH_HINTS:
if not os.path.isfile(_cand):
continue
try:
with open(_cand, "rb") as f:
_prb = f.read()
except Exception as e:
PREREG_STATUS["paths_checked"].append(_cand)
PREREG_STATUS["read_errors"].append(
{"path": _cand, "error": f"{type(e).__name__}: {e}"})
continue
_prs = hashlib.sha256(_prb).hexdigest()
PREREG_STATUS["paths_checked"].append(_cand)
if _prs == PREREG_SHA256:
PREREG_STATUS["verified"] = True
PREREG_STATUS["path"] = _cand
PREREG_STATUS["reason"] = None
break
else:
PREREG_STATUS["mismatched_paths"].append(
{"path": _cand, "sha256": _prs})
if not PREREG_STATUS["verified"]:
_reason_parts = []
if PREREG_STATUS["mismatched_paths"]:
_reason_parts.append(
"mismatched: "
+ ", ".join(m["path"] for m in PREREG_STATUS["mismatched_paths"]))
if PREREG_STATUS["read_errors"]:
_reason_parts.append(
"unreadable: "
+ ", ".join(r["path"] for r in PREREG_STATUS["read_errors"]))
if not PREREG_STATUS["paths_checked"]:
_reason_parts.append(
"no hint path exists: " + ", ".join(PREREG_PATH_HINTS))
PREREG_STATUS["reason"] = (
"preregistration not verified (" + "; ".join(_reason_parts) + ")")
except Exception as e:
PREREG_STATUS["verified"] = False
PREREG_STATUS["reason"] = (
f"preregistration search error: {type(e).__name__}: {e}")
if not PREREG_STATUS["verified"]:
_pf("preregistration", PREREG_STATUS["reason"])
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
# =============================================================================
# Gate 4: schema
# =============================================================================
RECORDED_SCHEMA_NOTES = {}
try:
if "cases" not in _BASE or not isinstance(_BASE["cases"], list):
_pf("baseline", "missing 'cases' list")
if "transforms_validation" not in _BASE:
_pf("baseline", "missing 'transforms_validation'")
if "input_resolution" not in _BASE:
_pf("baseline", "missing 'input_resolution'")
_BASE_CASES = {}
for _c in (_BASE.get("cases") or []):
_key = (_c.get("matrix"), _c.get("transform"))
if _key in _BASE_CASES:
_pf("baseline", f"duplicate case {_key[0]}/{_key[1]}")
_BASE_CASES[_key] = _c
_seen_matrices = {k[0] for k in _BASE_CASES}
_seen_transforms = {k[1] for k in _BASE_CASES}
if _seen_matrices != set(REQUIRED_MATRICES):
_pf("baseline",
f"matrix set {sorted(_seen_matrices)} != "
f"{sorted(REQUIRED_MATRICES)}")
if _seen_transforms != set(REQUIRED_LABELS):
_pf("baseline",
f"transform set {sorted(_seen_transforms)} != "
f"{sorted(REQUIRED_LABELS)}")
RECORDED_SCHEMA_NOTES["baseline_case_fields_observed"] = sorted(
(_BASE.get("cases") or [{}])[0].keys()
if _BASE.get("cases") else [])
RECORDED_SCHEMA_NOTES["full_residual_field"] = FULL_RESIDUAL_FIELD
RECORDED_SCHEMA_NOTES["stored_p_prime_field_present"] = False
RECORDED_SCHEMA_NOTES["note_p_prime"] = (
"The frozen baseline does not store P_prime explicitly per case. "
"P_prime is reconstructed from the case S_matrix and canonical P.")
SCALAR_RECONSTRUCTION_NOTE = {
"state_scalars_field_present": False,
"gf_sf_hyb_storage": (
"gf, sf, and hyb at both states ARE stored in "
"case['structural_diagnostics'] as JSON strings. Gate 10 uses "
"representation-aware comparison at nominal 60 sig digits."),
"t2s_storage": (
"t2s at P and P' is NOT stored. It is reconstructed from the "
"live C_Pi_components via out['t2'][0,0]. No stored-versus-live "
"t2s check is attempted."),
}
for name in REQUIRED_MATRICES:
for t_label in REQUIRED_LABELS:
case = _BASE_CASES.get((name, t_label))
where = f"baseline {name}/{t_label}"
if case is None:
_pf(where, "case missing")
continue
for fld in ("component_residuals", "S_matrix",
"structural_diagnostics", FULL_RESIDUAL_FIELD):
if fld not in case or case[fld] is None:
_pf(where, f"missing field {fld!r}")
cr = case.get("component_residuals", {})
for k in ("Delta_t1", "Delta_t2", "Delta_t3", "Delta_t4",
"Delta_hyb"):
if k not in cr:
_pf(where, f"component_residuals.{k} missing")
sd = case.get("structural_diagnostics", {})
for side_map in (SD_KEYS_P, SD_KEYS_PP):
for k in side_map.values():
if k not in sd:
_pf(where, f"structural_diagnostics.{k} missing")
except Exception as e:
_pf("schema inspection", f"{type(e).__name__}: {e}")
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
# =============================================================================
# Gate 5: transforms
# =============================================================================
try:
_TRANSFORMS = {}
_LABEL_COUNTS = {}
for _rec in _BASE["transforms_validation"].get("records", []):
lbl = _rec.get("label")
rm = _rec.get("recorded_matrix")
if not lbl or rm is None:
continue
_LABEL_COUNTS[lbl] = _LABEL_COUNTS.get(lbl, 0) + 1
if _LABEL_COUNTS[lbl] > 1:
_pf(f"transforms/{lbl}",
f"duplicate label {lbl!r} in transforms_validation.records")
continue
try:
M = _mp2x2(rm)
_check_2x2_finite(M, f"transform:{lbl}")
except Exception as e:
_pf(f"transforms/{lbl}", f"{type(e).__name__}: {e}")
continue
_TRANSFORMS[lbl] = M
for lbl in REQUIRED_LABELS:
if _LABEL_COUNTS.get(lbl, 0) == 0:
_pf("transforms", f"transform {lbl!r} not recorded")
TRANSFORM_INFO = []
for lbl in REQUIRED_LABELS:
S = _TRANSFORMS.get(lbl)
if S is None:
continue
det = S[0,0]*S[1,1] - S[0,1]*S[1,0]
if not mp.isfinite(det):
_pf("transforms", f"{lbl!r} det is not finite")
continue
if det == 0:
_pf("transforms", f"{lbl!r} singular")
continue
expected_det = EXPECTED_TRANSFORM_DETS[lbl]
det_disc = abs(det - expected_det)
if det_disc > TOL_INTERNAL:
_pf("transforms",
f"{lbl!r} det={mp.nstr(det,20)}, expected "
f"{mp.nstr(expected_det,20)} (diff {mp.nstr(det_disc,12)})")
TRANSFORM_INFO.append({
"label": lbl,
"recorded_matrix": _to_json(S),
"det_S": mp.nstr(det, 60),
"expected_det": mp.nstr(expected_det, 60),
"det_agrees_with_expected": bool(det_disc <= TOL_INTERNAL),
})
except Exception as e:
_pf("transforms", f"{type(e).__name__}: {e}")
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
# =============================================================================
# Gate 6: canonical matrices (patched: distinct names)
# =============================================================================
def _canonical(name):
try:
entries = (_BASE["input_resolution"].get(name, {})
.get("canonical", {})
.get("entries"))
if entries is None:
_pf("canonical", f"missing entries for {name}")
return None
M = _mp2x2(entries)
_check_2x2_finite(M, f"canonical:{name}")
return M
except Exception as e:
_pf("canonical", f"{name}: {type(e).__name__}: {e}")
return None
P_test_canonical = _canonical("P_test")
P_nonsym_canonical = _canonical("P_nonsym")
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
MATRICES = [("P_test", P_test_canonical), ("P_nonsym", P_nonsym_canonical)]
# =============================================================================
# Gate 7: S vs transform; preserved live P vs canonical baseline
# =============================================================================
for name in REQUIRED_MATRICES:
for t_label in REQUIRED_LABELS:
where = f"S_matrix {name}/{t_label}"
try:
case_S = _mp2x2(_BASE_CASES[(name, t_label)]["S_matrix"])
_check_2x2_finite(case_S, where)
disc = _max_abs(_sub(case_S, _TRANSFORMS[t_label]))
if disc > TOL_INTERNAL:
_pf(where,
f"case S_matrix differs from recorded transform by "
f"{mp.nstr(disc, 12)} > {mp.nstr(TOL_INTERNAL, 12)}")
except Exception as e:
_pf(where, f"{type(e).__name__}: {e}")
def _live_kernel_lookup(name):
import __main__
import builtins
for holder in (__main__, builtins):
if hasattr(holder, name):
return getattr(holder, name)
return None
for name, canonical_P in MATRICES:
where = f"live P vs canonical {name}"
live = _live_kernel_lookup(name)
if live is None:
_pf(where, f"live kernel has no {name!r} symbol")
continue
try:
_check_2x2_finite(live, where)
disc = _max_abs(_sub(live, canonical_P))
if disc > TOL_INTERNAL:
_pf(where,
f"live {name} differs from canonical baseline by "
f"{mp.nstr(disc, 12)} > {mp.nstr(TOL_INTERNAL, 12)}")
except Exception as e:
_pf(where, f"{type(e).__name__}: {e}")
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
# =============================================================================
# Gate 8: source semantics probe + per-matrix audit (patched: audit)
# =============================================================================
def _require(name):
import __main__
import builtins
for holder in (__main__, builtins):
if hasattr(holder, name):
return getattr(holder, name)
raise SystemExit(f"FATAL: required symbol {name!r} not in kernel. Stop.")
try:
C_Pi_components = _require("C_Pi_components")
t3_reference = _require("t3_reference")
ALPHA_BASE = _require("ALPHA_BASE")
except SystemExit as e:
_pf("source", str(e))
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
_REQUIRED_OUT = ("C_Pi", "t1", "t2", "t3", "t4", "gf", "sf", "hyb")
def _assert_out_keys(out, where):
if not isinstance(out, dict):
raise ValueError(f"{where}: C_Pi_components returned non-dict")
missing = [k for k in _REQUIRED_OUT if k not in out]
if missing:
raise ValueError(f"{where}: C_Pi_components missing keys {missing}")
for k in ("t1", "t2", "t3", "t4", "C_Pi"):
_check_2x2_finite(out[k], f"{where}.{k}")
for k in ("gf", "sf", "hyb"):
if not mp.isfinite(mp.mpf(out[k])):
raise ValueError(f"{where}: {k} non-finite")
def _reconstruct_C(out):
gf = mp.mpf(out["gf"]); sf = mp.mpf(out["sf"]); hyb = mp.mpf(out["hyb"])
inner = _add(_add(_add(out["t1"], out["t2"]), out["t3"]), out["t4"])
base = _scl(gf, inner)
gated = _offdiag_gate(base, sf)
return _add(gated, _hyb_mat(hyb))
def _effective_component(out, key):
gf = mp.mpf(out["gf"]); sf = mp.mpf(out["sf"])
return _offdiag_gate(_scl(gf, out[key]), sf)
# --- per-matrix source semantics record ---
for name, P in MATRICES:
audit_key = f"probe/{name}"
try:
out = C_Pi_components(P, t3_reference, ALPHA_BASE)
_assert_out_keys(out, audit_key)
recon = _reconstruct_C(out)
disc = _max_abs(_sub(recon, out["C_Pi"]))
passed = bool(disc <= TOL_INTERNAL)
SOURCE_SEMANTICS_AUDIT[audit_key] = {
"reconstruct_diff_max_abs": mp.nstr(disc, 60),
"tolerance": mp.nstr(TOL_INTERNAL, 12),
"pass": passed,
"error": None,
}
if not passed:
_pf(audit_key,
f"C_Pi reconstruction diff {mp.nstr(disc,12)} > "
f"{mp.nstr(TOL_INTERNAL,12)}")
except Exception as e:
SOURCE_SEMANTICS_AUDIT[audit_key] = {
"reconstruct_diff_max_abs": None,
"tolerance": mp.nstr(TOL_INTERNAL, 12),
"pass": False,
"error": f"{type(e).__name__}: {e}",
}
_pf(audit_key, f"{type(e).__name__}: {e}")
RAW_T2_CHECKS = {}
for name, P in MATRICES:
for t_label in REQUIRED_LABELS:
where = f"raw t2 uniformity {name}/{t_label}"
S = _TRANSFORMS[t_label]; Sinv = _inv2(S)
Pp = _matmul(_matmul(Sinv, P), S)
try:
for side, Pstate in (("P", P), ("P'", Pp)):
out = C_Pi_components(Pstate, t3_reference, ALPHA_BASE)
_assert_out_keys(out, f"{where}/{side}")
raw = out["t2"]
t2s = raw[0,0]
for i in range(2):
for j in range(2):
d = abs(raw[i,j] - t2s)
if d > TOL_INTERNAL:
raise ValueError(
f"raw t2 not uniform t2s*ones at {side}: "
f"[{i},{j}] diff {mp.nstr(d,12)} > "
f"{mp.nstr(TOL_INTERNAL,12)}")
RAW_T2_CHECKS[(name, t_label)] = {"pass": True}
except Exception as e:
_pf(where, f"{type(e).__name__}: {e}")
RAW_T2_CHECKS[(name, t_label)] = {"pass": False, "error": str(e)}
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
# =============================================================================
# Gate 9: forecast verification (patched: live gf * live t2s)
# =============================================================================
FORECAST_CHECK = {}
for name, P in MATRICES:
for t_label in NONORTHO_LABELS:
where = f"forecast {name}/{t_label}"
try:
S = _TRANSFORMS[t_label]; Sinv = _inv2(S)
Pp = _matmul(_matmul(Sinv, P), S)
out_P = C_Pi_components(P, t3_reference, ALPHA_BASE)
out_Pp = C_Pi_components(Pp, t3_reference, ALPHA_BASE)
# Live reconstruction: both gf and t2s from current callable.
c_ref_live = mp.mpf(out_P["gf"]) * out_P["t2"][0,0]
c_sub_live = mp.mpf(out_Pp["gf"]) * out_Pp["t2"][0,0]
c_shift_live = c_sub_live - c_ref_live
# Stored-scalar reference (for cross-check only; not used to
# override the live computation).
sd = _BASE_CASES[(name, t_label)]["structural_diagnostics"]
c_ref_stored = mp.mpf(sd["gf_ref"]) * out_P["t2"][0,0]
c_sub_stored = mp.mpf(sd["gf_sub"]) * out_Pp["t2"][0,0]
c_shift_stored = c_sub_stored - c_ref_stored
fz = FROZEN_FORECASTS[(name, t_label)]
d_live = abs(c_shift_live - mp.mpf(str(fz)))
ok = bool(d_live <= FORECAST_TOL)
FORECAST_CHECK[(name, t_label)] = {
"forecast": str(fz),
"c_shift_live": mp.nstr(c_shift_live, 60),
"c_shift_stored_scalar": mp.nstr(c_shift_stored, 60),
"abs_diff_live": mp.nstr(d_live, 60),
"tolerance": mp.nstr(FORECAST_TOL, 12),
"pass": ok,
}
if not ok:
_pf(where,
f"live c-shift {mp.nstr(c_shift_live,20)} vs forecast "
f"{fz}, diff {mp.nstr(d_live,12)} > "
f"{mp.nstr(FORECAST_TOL,12)}")
except Exception as e:
_pf(where, f"{type(e).__name__}: {e}")
FORECAST_CHECK[(name, t_label)] = {
"pass": False, "error": f"{type(e).__name__}: {e}"}
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
# =============================================================================
# Gate 10: baseline reproduction (patched: per-case records; seven checks)
# =============================================================================
for name, P in MATRICES:
for t_label in REQUIRED_LABELS:
where = f"baseline repro {name}/{t_label}"
repro_key = f"{name}/{t_label}"
# --- Initialize the record before any check runs ---
BASELINE_REPRO[repro_key] = {
"status": "in_progress",
"checks_completed": [],
"checks_not_run": [
"delta_t2", "delta_hyb",
"delta_t1", "delta_t3", "delta_t4",
"delta_S", "component_sum_vs_Delta_S",
"scalar_audit",
],
"blocked_reason": None,
"partial_diagnostics": {},
"per_check_status": {
"delta_t2": {"status": "not_run"},
"delta_hyb": {"status": "not_run"},
"delta_t1": {"status": "not_run"},
"delta_t3": {"status": "not_run"},
"delta_t4": {"status": "not_run"},
"delta_S": {"status": "not_run"},
"component_sum_vs_Delta_S": {"status": "not_run"},
"scalar_audit": {"status": "not_run"},
},
"pass": False,
}
def _record_failure(status_tag, reason, extra_partial=None):
BASELINE_REPRO[repro_key]["status"] = status_tag
BASELINE_REPRO[repro_key]["blocked_reason"] = reason
BASELINE_REPRO[repro_key]["pass"] = False
if extra_partial:
BASELINE_REPRO[repro_key]["partial_diagnostics"].update(extra_partial)
S = _TRANSFORMS[t_label]; Sinv = _inv2(S)
Pp = _matmul(_matmul(Sinv, P), S)
case = _BASE_CASES[(name, t_label)]
try:
out_P = C_Pi_components(P, t3_reference, ALPHA_BASE)
out_Pp = C_Pi_components(Pp, t3_reference, ALPHA_BASE)
_assert_out_keys(out_P, f"{where}/P")
_assert_out_keys(out_Pp, f"{where}/Pp")
# ---------- Scalar audit ----------
sd = case["structural_diagnostics"]
scalar_checks = {}
scalar_all_ok = True
scalar_ambiguous = False
for lbl, live, key in (
("P.gf", mp.mpf(out_P["gf"]), "gf_ref"),
("P.sf", mp.mpf(out_P["sf"]), "sf_ref"),
("P.hyb", mp.mpf(out_P["hyb"]), "hyb_ref"),
("P'.gf", mp.mpf(out_Pp["gf"]), "gf_sub"),
("P'.sf", mp.mpf(out_Pp["sf"]), "sf_sub"),
("P'.hyb", mp.mpf(out_Pp["hyb"]), "hyb_sub"),
):
res = _representation_aware_compare(live, sd[key],
f"{where}/{lbl}")
scalar_checks[lbl] = res
if res["ambiguous"]:
scalar_ambiguous = True
elif not res["ok"]:
scalar_all_ok = False
scalar_checks["P.t2s"] = "reconstructed (not stored)"
scalar_checks["P'.t2s"] = "reconstructed (not stored)"
SCALAR_PRECISION_AUDIT[repro_key] = scalar_checks
if scalar_ambiguous:
BASELINE_REPRO[repro_key]["per_check_status"]["scalar_audit"] = {
"status": "ambiguous",
"detail": "one or more fields ambiguous",
}
_record_failure(
"ambiguous",
"representation-aware scalar comparison ambiguous",
{"scalar_audit": scalar_checks})
_pf(where,
"representation-aware scalar comparison could not "
"determine stored precision for at least one field")
continue
if not scalar_all_ok:
bad = {k: v for k, v in scalar_checks.items()
if isinstance(v, dict) and not v.get("ok")
and not v.get("ambiguous")}
BASELINE_REPRO[repro_key]["per_check_status"]["scalar_audit"] = {
"status": "failed",
"detail": str({k: {"stored": v["stored_raw_repr"],
"abs_diff": v["abs_diff_full_precision"],
"ulp": v["ulp_at_stored_precision"]}
for k, v in bad.items()}),
}
_record_failure(
"scalar_failed",
"live scalar does not match stored at stored precision",
{"scalar_audit": scalar_checks})
_pf(where,
"live scalar does not match stored at stored precision")
continue
BASELINE_REPRO[repro_key]["per_check_status"]["scalar_audit"] = {
"status": "passed"}
BASELINE_REPRO[repro_key]["checks_completed"].append("scalar_audit")
BASELINE_REPRO[repro_key]["checks_not_run"].remove("scalar_audit")
# ---------- Component reproduction: t2 ----------
cr = case["component_residuals"]
t2_eff_P = _effective_component(out_P, "t2")
t2_eff_Pp = _effective_component(out_Pp, "t2")
delta_t2 = _sub(t2_eff_Pp, _matmul(_matmul(Sinv, t2_eff_P), S))
stored_t2 = _mp2x2(cr["Delta_t2"])
t2_disc = _max_abs(_sub(delta_t2, stored_t2))
t2_pass = bool(t2_disc <= TOL_INTERNAL)
BASELINE_REPRO[repro_key]["per_check_status"]["delta_t2"] = {
"status": "passed" if t2_pass else "failed",
"max_abs_diff": mp.nstr(t2_disc, 60),
}
BASELINE_REPRO[repro_key]["checks_completed"].append("delta_t2")
BASELINE_REPRO[repro_key]["checks_not_run"].remove("delta_t2")
BASELINE_REPRO[repro_key]["partial_diagnostics"]["delta_t2"] = {
"max_abs_diff": mp.nstr(t2_disc, 60),
"pass": t2_pass,
}
if not t2_pass:
_pf(f"{where}/Delta_t2",
f"Delta_t2 recomputed vs stored "
f"component_residuals.Delta_t2: max_abs_diff="
f"{mp.nstr(t2_disc, 12)} > "
f"TOL_INTERNAL={mp.nstr(TOL_INTERNAL, 12)}")
# ---------- Component reproduction: hyb ----------
delta_hyb = _sub(_hyb_mat(mp.mpf(out_Pp["hyb"])),
_matmul(_matmul(Sinv, _hyb_mat(
mp.mpf(out_P["hyb"]))), S))
stored_hyb = _mp2x2(cr["Delta_hyb"])
hyb_disc = _max_abs(_sub(delta_hyb, stored_hyb))
hyb_pass = bool(hyb_disc <= TOL_INTERNAL)
BASELINE_REPRO[repro_key]["per_check_status"]["delta_hyb"] = {
"status": "passed" if hyb_pass else "failed",
"max_abs_diff": mp.nstr(hyb_disc, 60),
}
BASELINE_REPRO[repro_key]["checks_completed"].append("delta_hyb")
BASELINE_REPRO[repro_key]["checks_not_run"].remove("delta_hyb")
BASELINE_REPRO[repro_key]["partial_diagnostics"]["delta_hyb"] = {
"max_abs_diff": mp.nstr(hyb_disc, 60),
"pass": hyb_pass,
}
if not hyb_pass:
_pf(f"{where}/Delta_hyb",
f"Delta_hyb recomputed vs stored "
f"component_residuals.Delta_hyb: max_abs_diff="
f"{mp.nstr(hyb_disc, 12)} > "
f"TOL_INTERNAL={mp.nstr(TOL_INTERNAL, 12)}")
# ---------- Component reproduction: t1, t3, t4 ----------
unchanged = {}
for key, base_key in zip(("t1", "t3", "t4"),
UNCHANGED_BASELINE_KEYS):
e_P = _effective_component(out_P, key)
e_Pp = _effective_component(out_Pp, key)
delta = _sub(e_Pp, _matmul(_matmul(Sinv, e_P), S))
stored = _mp2x2(cr[base_key])
disc = _max_abs(_sub(delta, stored))
_pass = bool(disc <= TOL_INTERNAL)
unchanged[key] = {"max_abs_diff": mp.nstr(disc, 60),
"pass": _pass}
check_key = f"delta_{key}"
BASELINE_REPRO[repro_key]["per_check_status"][check_key] = {
"status": "passed" if _pass else "failed",
"max_abs_diff": mp.nstr(disc, 60),
}
BASELINE_REPRO[repro_key]["checks_completed"].append(check_key)
BASELINE_REPRO[repro_key]["checks_not_run"].remove(check_key)
BASELINE_REPRO[repro_key]["partial_diagnostics"][check_key] = {
"max_abs_diff": mp.nstr(disc, 60),
"pass": _pass,
}
if not _pass:
_pf(f"{where}/Delta_{key}",
f"Delta_{key} recomputed vs stored "
f"component_residuals.{base_key}: max_abs_diff="
f"{mp.nstr(disc, 12)} > "
f"TOL_INTERNAL={mp.nstr(TOL_INTERNAL, 12)}")
unchanged_pass = all(v["pass"] for v in unchanged.values())
# ---------- Full residual vs Delta_S ----------
stored_full = _mp2x2(case[FULL_RESIDUAL_FIELD])
baseline_full_recomputed = _sub(
out_Pp["C_Pi"], _matmul(_matmul(Sinv, out_P["C_Pi"]), S))
full_disc = _max_abs(_sub(baseline_full_recomputed, stored_full))
full_pass = bool(full_disc <= TOL_INTERNAL)
BASELINE_REPRO[repro_key]["per_check_status"]["delta_S"] = {
"status": "passed" if full_pass else "failed",
"max_abs_diff": mp.nstr(full_disc, 60),
}
BASELINE_REPRO[repro_key]["checks_completed"].append("delta_S")
BASELINE_REPRO[repro_key]["checks_not_run"].remove("delta_S")
BASELINE_REPRO[repro_key]["partial_diagnostics"]["delta_S"] = {
"max_abs_diff": mp.nstr(full_disc, 60),
"pass": full_pass,
}
if not full_pass:
_pf(f"{where}/Delta_S",
f"full residual recomputed vs stored case['Delta_S']: "
f"max_abs_diff={mp.nstr(full_disc, 12)} > "
f"TOL_INTERNAL={mp.nstr(TOL_INTERNAL, 12)}")
# ---------- Component-sum closure vs Delta_S ----------
base_comp_sum = _add(
_add(_sub(_effective_component(out_Pp, "t1"),
_matmul(_matmul(Sinv,
_effective_component(out_P, "t1")
), S)),
_sub(t2_eff_Pp, _matmul(_matmul(Sinv, t2_eff_P), S))),
_add(_add(_sub(_effective_component(out_Pp, "t3"),
_matmul(_matmul(Sinv,
_effective_component(out_P, "t3")
), S)),
_sub(_effective_component(out_Pp, "t4"),
_matmul(_matmul(Sinv,
_effective_component(out_P, "t4")
), S))),
delta_hyb))
sum_vs_full = _max_abs(_sub(base_comp_sum, stored_full))
sum_pass = bool(sum_vs_full <= TOL_INTERNAL)
BASELINE_REPRO[repro_key]["per_check_status"][
"component_sum_vs_Delta_S"] = {
"status": "passed" if sum_pass else "failed",
"max_abs_diff": mp.nstr(sum_vs_full, 60),
}
BASELINE_REPRO[repro_key]["checks_completed"].append(
"component_sum_vs_Delta_S")
BASELINE_REPRO[repro_key]["checks_not_run"].remove(
"component_sum_vs_Delta_S")
BASELINE_REPRO[repro_key]["partial_diagnostics"][
"component_sum_vs_Delta_S"] = {
"max_abs_diff": mp.nstr(sum_vs_full, 60),
"pass": sum_pass,
}
if not sum_pass:
_pf(f"{where}/component_sum_vs_Delta_S",
f"sum of recomputed component residuals vs stored "
f"case['Delta_S']: max_abs_diff="
f"{mp.nstr(sum_vs_full, 12)} > "
f"TOL_INTERNAL={mp.nstr(TOL_INTERNAL, 12)}")
# ---------- Final record for this case ----------
BASELINE_REPRO[repro_key].update({
"scalar_all_ok": True,
"t2_max_abs_diff": mp.nstr(t2_disc, 60),
"t2_pass": t2_pass,
"hyb_max_abs_diff": mp.nstr(hyb_disc, 60),
"hyb_pass": hyb_pass,
"unchanged": unchanged,
"unchanged_pass": unchanged_pass,
"full_residual_field": FULL_RESIDUAL_FIELD,
"full_residual_recomputed_vs_stored_max_abs":
mp.nstr(full_disc, 60),
"full_residual_pass": full_pass,
"component_sum_vs_stored_full_max_abs":
mp.nstr(sum_vs_full, 60),
"component_sum_pass": sum_pass,
"pass": bool(t2_pass and hyb_pass and unchanged_pass
and full_pass and sum_pass),
"status": "completed",
"checks_not_run": [],
})
except Exception as e:
_record_failure(
"exception",
f"{type(e).__name__}: {e}")
_pf(where, f"{type(e).__name__}: {e}")
# Gate 10 blocked exit
if PREFLIGHT_ISSUES:
_save_and_exit("PREFLIGHT_BLOCKED", extra=_blocked_exit_extra())
raise SystemExit(0)
# =============================================================================
# Candidate evaluation (patched: per-case record with exception preservation)
# =============================================================================
for name, P in MATRICES:
for t_label in REQUIRED_LABELS:
where = f"candidate {name}/{t_label}"
cand_key = f"{name}/{t_label}"
# --- Initialize the candidate record before checks run ---
CANDIDATE_CASE_REPORTS[cand_key] = {
"matrix": name,
"transform": t_label,
"case_status": "not_run",
"checks_completed": [],
"checks_not_run": [
"raw_candidate_t2",
"candidate_assembly",
"effective_t2_equals_cI",
"closed_form",
"candidate_component_sum_closure",
"unchanged_components",
"rotation_check",
],
"partial_diagnostics": {},
"error": None,
}
def _cand_fail(tag, err):
CANDIDATE_CASE_REPORTS[cand_key]["case_status"] = "DIAGNOSTIC_FAIL"
CANDIDATE_CASE_REPORTS[cand_key]["error"] = err
_ce(where, err)
S = _TRANSFORMS[t_label]; Sinv = _inv2(S)
Pp = _matmul(_matmul(Sinv, P), S)
case = _BASE_CASES[(name, t_label)]
try:
out_P = C_Pi_components(P, t3_reference, ALPHA_BASE)
out_Pp = C_Pi_components(Pp, t3_reference, ALPHA_BASE)
_assert_out_keys(out_P, f"{where}/P")
_assert_out_keys(out_Pp, f"{where}/Pp")
def _raw_cand_t2(out):
raw = out["t2"]
t2s = raw[0,0]
for i in range(2):
for j in range(2):
if abs(raw[i,j] - t2s) > TOL_INTERNAL:
raise ValueError("raw t2 non-uniform")
return _scl(t2s, _eye()), t2s
raw_t2_P, t2s_P = _raw_cand_t2(out_P)
raw_t2_Pp, t2s_Pp = _raw_cand_t2(out_Pp)
CANDIDATE_CASE_REPORTS[cand_key]["checks_completed"].append(
"raw_candidate_t2")
CANDIDATE_CASE_REPORTS[cand_key]["checks_not_run"].remove(
"raw_candidate_t2")
CANDIDATE_CASE_REPORTS[cand_key]["partial_diagnostics"][
"raw_candidate_t2"] = {
"t2s_P": mp.nstr(t2s_P, 60),
"t2s_Pp": mp.nstr(t2s_Pp, 60),
}
def _candidate_C_full(out, raw_t2):
gf = mp.mpf(out["gf"]); sf = mp.mpf(out["sf"])
hyb = mp.mpf(out["hyb"])
inner = _add(_add(_add(out["t1"], raw_t2), out["t3"]),
out["t4"])
base = _scl(gf, inner)
gated = _offdiag_gate(base, sf)
return _add(gated, _hyb_mat(hyb))
cand_C_P = _candidate_C_full(out_P, raw_t2_P)
cand_C_Pp = _candidate_C_full(out_Pp, raw_t2_Pp)
CANDIDATE_CASE_REPORTS[cand_key]["checks_completed"].append(
"candidate_assembly")
CANDIDATE_CASE_REPORTS[cand_key]["checks_not_run"].remove(
"candidate_assembly")
cand_t2_eff_P = _offdiag_gate(_scl(mp.mpf(out_P["gf"]),
raw_t2_P),
mp.mpf(out_P["sf"]))
cand_t2_eff_Pp = _offdiag_gate(_scl(mp.mpf(out_Pp["gf"]),
raw_t2_Pp),
mp.mpf(out_Pp["sf"]))
c_P = mp.mpf(out_P["gf"]) * t2s_P
c_Pp = mp.mpf(out_Pp["gf"]) * t2s_Pp
eff_disc_P = _max_abs(_sub(cand_t2_eff_P, _scl(c_P, _eye())))
eff_disc_Pp = _max_abs(_sub(cand_t2_eff_Pp, _scl(c_Pp, _eye())))
eff_pass = bool(eff_disc_P <= TOL_INTERNAL
and eff_disc_Pp <= TOL_INTERNAL)
CANDIDATE_CASE_REPORTS[cand_key]["checks_completed"].append(
"effective_t2_equals_cI")
CANDIDATE_CASE_REPORTS[cand_key]["checks_not_run"].remove(
"effective_t2_equals_cI")
CANDIDATE_CASE_REPORTS[cand_key]["partial_diagnostics"][
"effective_t2_equals_cI"] = {
"disc_at_P": mp.nstr(eff_disc_P, 60),
"disc_at_Pp": mp.nstr(eff_disc_Pp, 60),
"pass": eff_pass,
}
cand_delta_t2 = _sub(cand_t2_eff_Pp,
_matmul(_matmul(Sinv, cand_t2_eff_P), S))
c_shift = c_Pp - c_P
closed_form = _scl(c_shift, _eye())
cf_disc = _max_abs(_sub(cand_delta_t2, closed_form))
cf_pass = bool(cf_disc <= TOL_INTERNAL)
CANDIDATE_CASE_REPORTS[cand_key]["checks_completed"].append(
"closed_form")
CANDIDATE_CASE_REPORTS[cand_key]["checks_not_run"].remove(
"closed_form")
CANDIDATE_CASE_REPORTS[cand_key]["partial_diagnostics"][
"closed_form"] = {
"max_abs_diff": mp.nstr(cf_disc, 60),
"pass": cf_pass,
}
offdiag_max = max(abs(cand_delta_t2[0,1]),
abs(cand_delta_t2[1,0]))
diag_diff = abs(cand_delta_t2[0,0] - cand_delta_t2[1,1])
offdiag_pass = bool(offdiag_max <= TOL_INTERNAL)
diag_pass = bool(diag_diff <= TOL_INTERNAL)
base_t2_eff_P = _effective_component(out_P, "t2")
base_t2_eff_Pp = _effective_component(out_Pp, "t2")
base_delta_t2 = _sub(base_t2_eff_Pp,
_matmul(_matmul(Sinv, base_t2_eff_P), S))
cand_full_delta = _sub(cand_C_Pp,
_matmul(_matmul(Sinv, cand_C_P), S))
cand_comp_sum = _add(
_add(_sub(_effective_component(out_Pp, "t1"),
_matmul(_matmul(Sinv,
_effective_component(out_P, "t1")
), S)),
_sub(cand_t2_eff_Pp,
_matmul(_matmul(Sinv, cand_t2_eff_P), S))),
_add(_add(_sub(_effective_component(out_Pp, "t3"),
_matmul(_matmul(Sinv,
_effective_component(out_P, "t3")
), S)),
_sub(_effective_component(out_Pp, "t4"),
_matmul(_matmul(Sinv,
_effective_component(out_P, "t4")
), S))),
_sub(_hyb_mat(mp.mpf(out_Pp["hyb"])),
_matmul(_matmul(Sinv,
_hyb_mat(mp.mpf(out_P["hyb"]))),
S))))
comp_close_disc = _max_abs(_sub(cand_full_delta, cand_comp_sum))
comp_close_pass = bool(comp_close_disc <= TOL_INTERNAL)
CANDIDATE_CASE_REPORTS[cand_key]["checks_completed"].append(
"candidate_component_sum_closure")
CANDIDATE_CASE_REPORTS[cand_key]["checks_not_run"].remove(
"candidate_component_sum_closure")
CANDIDATE_CASE_REPORTS[cand_key]["partial_diagnostics"][
"candidate_component_sum_closure"] = {
"max_abs_diff": mp.nstr(comp_close_disc, 60),
"pass": comp_close_pass,
}
unchanged = {}
for key in ("t1", "t3", "t4"):
e_P = _effective_component(out_P, key)
e_Pp = _effective_component(out_Pp, key)
delta = _sub(e_Pp, _matmul(_matmul(Sinv, e_P), S))
base_key = {"t1": "Delta_t1", "t3": "Delta_t3",
"t4": "Delta_t4"}[key]
stored = _mp2x2(case["component_residuals"][base_key])
disc = _max_abs(_sub(delta, stored))
unchanged[key] = {"max_abs_diff": mp.nstr(disc, 60),
"pass": bool(disc <= TOL_INTERNAL)}
unchanged_pass = all(v["pass"] for v in unchanged.values())
CANDIDATE_CASE_REPORTS[cand_key]["checks_completed"].append(
"unchanged_components")
CANDIDATE_CASE_REPORTS[cand_key]["checks_not_run"].remove(
"unchanged_components")
CANDIDATE_CASE_REPORTS[cand_key]["partial_diagnostics"][
"unchanged_components"] = unchanged
rotation_check = None
if t_label in ROTATION_LABELS:
n = _max_abs(cand_delta_t2)
rotation_check = {"norm": mp.nstr(n, 60),
"pass": bool(n <= TOL_INTERNAL)}
CANDIDATE_CASE_REPORTS[cand_key]["checks_completed"].append(
"rotation_check")
CANDIDATE_CASE_REPORTS[cand_key]["checks_not_run"].remove(
"rotation_check")
CANDIDATE_CASE_REPORTS[cand_key]["partial_diagnostics"][
"rotation_check"] = rotation_check
else:
CANDIDATE_CASE_REPORTS[cand_key]["checks_not_run"].remove(
"rotation_check")
case_pass = (cf_pass and offdiag_pass and diag_pass
and eff_pass and comp_close_pass and unchanged_pass
and (rotation_check is None
or rotation_check["pass"]))
case_status = ("DIAGNOSTIC_PASS" if case_pass
else "DIAGNOSTIC_FAIL")
CANDIDATE_CASE_REPORTS[cand_key]["case_status"] = case_status
CANDIDATE_CASE_REPORTS[cand_key].update({
"scalars": {
"gf_P": mp.nstr(mp.mpf(out_P["gf"]), 60),
"t2s_P": mp.nstr(t2s_P, 60),
"c_P": mp.nstr(c_P, 60),
"gf_Pp": mp.nstr(mp.mpf(out_Pp["gf"]), 60),
"t2s_Pp": mp.nstr(t2s_Pp, 60),
"c_Pp": mp.nstr(c_Pp, 60),
"c_shift": mp.nstr(c_shift, 60),
},
"baseline_delta_t2": {
"matrix": _to_json(base_delta_t2),
"max_abs": mp.nstr(_max_abs(base_delta_t2), 60),
"stored_path": "component_residuals.Delta_t2",
# CAT #4 — FULL HANDOFF TO A NEW DEEPSEEK WINDOW
**Prepared:** 2026-10-27, from the state of record at the close of this window.
**Purpose:** restore research state, source distinctions, control-flow position, and safety constraints in a new DeepSeek window, without rerunning experiments, re-probing artifacts, or re-deriving prior work.
**Scope:** CAT #4 only. CAT #3 is a separate frozen notebook; it is not part of any CAT #4 implementation, analysis, execution, or decision.
---
## 0. How to read this document
Sections are ordered to answer the questions a new window asks first:
1. Where are we? (short answer)
2. What is CAT #4, and what is the objective?
3. Which run family are we in, and which are we *not* in?
4. What has been established, with evidence, at each layer?
5. What is the current script, and what has been patched into it?
6. What does the next action look like?
7. What is frozen, what is open, and what must never be reintroduced?
8. Appendix: numeric evidence, artifact registry, register anchors, workflow between you/I/ChatGPT, and known failure modes from this window.
If any single fact in the rest of this document conflicts with §1, §5, or §7, those three sections override.
---
## 1. Where we are — short answer
A single mechanism substitution — `t2_raw = t2s * ones(2,2)` → `t2_raw = t2s * I` — has been preregistered, coded, audited through multiple rounds, patched for four identified defects, and one final one-line correction (Gate 9's `gf` source) has just been accepted. The preflight has **not** been run with the final patched script. The candidate has **not** been evaluated. No baseline reproduction at `TOL_INTERNAL` has been established by an actual run. No covariance claim has been made.
The preflight is the gate. If it passes, the candidate runs and the report distinguishes `DIAGNOSTIC_PASS` from `DIAGNOSTIC_FAIL`. If it blocks, the emitted report records the exact gate, the exact case, and the exact discrepancy, and the next question is decided from that evidence.
The immediate next action, uncontroversial in both audit streams (yours and ChatGPT's), is: apply the Gate 9 correction, run the preflight once, inspect the emitted JSON.
---
## 2. What CAT #4 is, and the objective
CAT #4 is a coordinate-free tensor sandbox. The framework's single monad is **Π**, with the canonical identity `Π ≡ ∀`. `Πβ`, `Πγ`, `Πᴰ` are *sectoral regimes/operators of Π*, not separate substances or fields. There is no container, substrate, background arena, or medium; there is no particle/wave primacy; there is no bottle. There is no established Π → P mapping. In CAT #4, **P** is the computational 2×2 matrix state being evaluated by the assembly.
The objective the work is serving, in the user's words, is to build a model that **demonstrates the ontology and way of using mathematics** — not to stage proof/falsification of the ontology. A failed forecast is evidence about the current model construction, not a verdict on the framework. **Protect the record, not the framework.**
CAT #4 has, across earlier work, measured non-covariance of the full `C_Pi` assembly across 2 canonical matrices × 6 established transforms = 12 cases. The current intervention is one step of a longer program to understand *which structural feature* of the assembly prevents covariance, by testing a single mechanism at a time.
---
## 3. Run families — which one is current
Distinct run families exist. **Do not merge them.**
- **Historical RMA / Candidate-4 comparison** (`FREE_THE_CAT_4_RESIDUAL_MATRIX_ATTRIBUTION_20261026_165442_318777.json`). Contains the historical `−0.29315729025147826428…` scalar at `results.baseline_vs_candidate4.P_nonsym.rotation_45.delta_R`. This scalar is **not** the `t2_identity_v1` ablation's value for that case. Its provenance for that scalar is a separate question from the current test.
- **`t2_identity_v1` ablation family** (`FREE_THE_CAT_4_T2_IDENTITY_V1_ABLATION_20261026_181111_406166.json` + its dedicated ledger + component-delta audits). 12 cases, `ones → I` substitution on the *ablation* matrix set, with a distinct frozen prediction record `CAT4-T2-ID-V1-PREREG-20261026`. Two diag_det1 sign-forecast **mismatches** survive; component-delta audit supports t2-only attribution for those two cases.
- **Current full-covariance replication** (`CAT4-T2-ID-FULLCOV-PREREG-20261027`). **This is the current run.** Same matrices and transforms as the full-covariance baseline (`P_test = [[1.5, 0.4], [-0.3, 0.8]]`, `P_nonsym = [[2.0, -0.8], [0.5, 1.2]]`), same `ones → I` mechanism, scored against the *full-covariance baseline* JSON, tracked separately from `t2_identity_v1`.
- **Provenance search for `−0.073668…`** (closed at v3). Value's origin not found in saved artifacts at declared scope; the only occurrences in the saved evidence are "still unresolved" notes in derived reports and a handoff echo. Provenance remains **UNRESOLVED**, and the branch is **stopped** — no further provenance-search scripts.
---
## 4. What is established at each layer (with evidence)
Each item lists what it rests on. Nothing here was re-derived by guessing.
### 4.1 Baseline (frozen full-covariance diagnostic)
- `FREE_THE_CAT_4_COVARIANCE_BASELINE_DECOMP_20261026_225243_754040.json`
- Size **82,094 bytes**, SHA-256 **`8ef85d73510a1be5c6fe27d2b8daf6cc44bcea041a4f1e6d5e011de9ff970130`**.
- Established by read-only hash check across multiple windows and by the Colab-runtime probe. This is the baseline the current test compares against; its **contents and hash are frozen**.
- Schema (established by read-only probe):
- Top-level keys: `script_version`, `generated_utc`, `objective`, `scope`, `input_resolution`, `transforms_validation`, `component_semantics`, `callable`, `decomposition_method`, `cases`, `distinctions_preserved`.
- 12 unique cases: `matrix ∈ {P_test, P_nonsym}`, `transform ∈ {diag_det1, rotation_15, rotation_45, rotation_90, shear_det1, shear_scale_det1p2}`.
- Per-case `component_residuals` keys: `Delta_t1`, `Delta_t2`, `Delta_t3`, `Delta_t4`, `Delta_hyb`. Each a 2×2 nested list of decimal strings (per-entry written digit counts 89 or 90 after trailing-zero trim).
- Per-case full assembly residual: **`case["Delta_S"]`** (2×2 nested list of decimal strings, 89–90 digits per entry).
- Per-case scalar storage: `case["structural_diagnostics"]` with keys `gf_ref`, `sf_ref`, `hyb_ref`, `gf_sub`, `sf_sub`, `hyb_sub`, each a decimal string at **60 significant written digits** with occasional 58/59-digit cases from trailing-zero trimming. Empirical distribution from probe: `gf_ref` always 60; `sf_ref` always 60; `gf_sub` 58 or 60; `sf_sub` 59 or 60; `hyb_ref` 59 or 60; `hyb_sub` 58, 59, or 60.
- Per-case `S_matrix` (2×2), `invariants` block (I1–I4 at P and P'), `norm_metrics`, `closure`, `structural_diagnostics` (as above), `identity_equivalent_measured`, `case_status`.
- **Not present in the baseline:**
- `state_scalars` — does not exist. Read-only probe confirmed.
- `delta_t2`, `delta_hyb` as top-level case fields — do not exist. Prior preflight versions blocked on this; it was correct to block.
- `t2s` at either state — **not stored**. Only recoverable from the live `C_Pi_components` (raw `t2[0,0]`).
- `P_prime` per case — **not stored**. Reconstructed from `case["S_matrix"]` and canonical `P`.
- Scalar precision is **60 sig figs written**, but the producer cell that writes these into the baseline is **not yet recovered** from notebook history. The 60-sig-fig comparison rule is inferred from observed storage, not verified against producer code. This is a standing disclosure, not a defect to fix.
### 4.2 Upstream source file (for canonical matrices and transforms)
- `FREE_THE_CAT_4_FULL_COVARIANCE_TEST_20261026_162417_910442.json`
- Size **94,019 bytes**, SHA-256 **`d0af70913d61f96dd2a22ce1947fc258780d1b02c27e0e556b9ddf341a53baa5`**.
- Exists and matches at the time of the read-only check.
- Supplies `input_resolution.{P_test,P_nonsym}.canonical.entries` and `transforms_validation.records[*].recorded_matrix` for the current run's canonical inputs.
### 4.3 Preregistration
- `CAT4-T2-ID-FULLCOV-PREREG-20261027`
- Document SHA-256 **`920dee74e6b1014febb2d4279bd5486a2bfa7a2800ae0772032b8c93dd4d63de`**.
- Path hints in the script: `/content/CAT4-T2-ID-FULLCOV-PREREG-20261027.md` and `/content/CAT4_T2_IDENTITY_FULLCOV_PREREG_20261027.md`.
- Prescribes exactly one substitution: `t2_raw = t2s * ones(2,2)` → `t2_raw = t2s * I`, with everything else unchanged.
- Predicts `Delta_T2I = (c(P') − c(P)) * I` where `c = gf * t2s`.
- Freezes 6 coefficient shifts (with 5e-6 tolerance) and numerical-floor (≤ 1e-85) rotation predictions:
| Matrix | Transform | Forecast c(P') − c(P) |
|---|---|---:|
| `P_test` | `diag_det1` | `+0.59056802` |
| `P_test` | `shear_det1` | `+0.22307615` |
| `P_test` | `shear_scale_det1p2` | `+0.31459935` |
| `P_nonsym` | `diag_det1` | `−0.04424388` |
| `P_nonsym` | `shear_det1` | `−0.06915931` |
| `P_nonsym` | `shear_scale_det1p2` | `−0.09061577` |
- All six rotations (`rotation_15`, `_45`, `_90` on both matrices) predict `‖Δ_T2I‖max ≤ 1e-85`; `rotation_90` specifically is expected at numerical zero (both scalar terms exactly zero under that transform).
### 4.4 Canonical matrices and transforms (frozen for this run)
- **`P_test`** = `[[1.5, 0.4], [−0.3, 0.8]]`
- **`P_nonsym`** = `[[2.0, −0.8], [0.5, 1.2]]`
- **Six transforms** with expected determinants: `diag_det1` (1.0), `rotation_15` (1.0), `rotation_45` (1.0), `rotation_90` (1.0), `shear_det1` (1.0), `shear_scale_det1p2` (**1.2** — do not relabel it as det 1).
- Transform convention: `P_prime = S^{-1} P S`. Recorded matrices are read from `transforms_validation.records[*].recorded_matrix`; do **not** regenerate from angles or names.
- Transform matrices themselves are stored in `§8.3` of this handoff.
### 4.5 Constants and tolerances (frozen)
- `TOL_INTERNAL = 1e-85` for matrix-level comparisons.
- `FORECAST_TOL = 5e-6` for the six non-orthogonal forecast comparisons.
- `mp.dps = 100` (active precision; do not change).
- Registered context (from the register, not used in the current test but frozen in the record): `PI_MAX = 5.9259`, `I_G = 1.0`, `IK_COEFF = 2.01`, `BETA_HYB = 0.1`, `GAMMA_HYB = 0.1`, `EPS_PIVOT = 0.001`, `FIELD_PIVOT = 100.0`, `KO_SIGMA = 0.045`, `ALPHA_BASE = 1.0`, `SIGMA = [[0, 1], [−1, 0]]`.
### 4.6 The active operator (`C_Pi_components`) as the run will encounter it
- Signature: `C_Pi_components(P, t3_fn, alpha_base)` returning a dict with keys `C_Pi`, `t1`, `t2`, `t3`, `t4`, `gf`, `sf`, `hyb`, `t3_raw`, `t3_gated` (return-key set verified by read-only inspection).
- Assembly, per the source excerpt established earlier:
- `inner = t1 + t2 + t3 + t4`
- `base = gf * inner`
- `gated = off-diagonal gate of base by sf` (diagonal unchanged, off-diagonals × sf)
- `C_Pi = gated + hyb at [1,0]` (returned `hyb` already contains `sf`; do **not** multiply it by `sf` again)
- `t2` is returned as **raw** `t2s * ones(2,2)`, before any `gf` or `sf` multiplication. `t2s` is recovered as `out["t2"][0,0]` after verifying all four entries equal that scalar.
- `t3` is returned as the raw output of `t3_fn(P)`; `t3_raw` is the same value; `t3_gated` equals `gf * t3_raw` (not an off-diagonal gate).
- `gf` and `sf` are returned scalars.
### 4.7 Prior preflight reports (blocked, correctly)
Two earlier preflight runs were blocked. Their evidence stays in the record:
- `CAT4_T2_IDENTITY_FULLCOV_TEST_20261027T001210Z.json` — blocked, 84 issues, all schema-path mismatches (`state_scalars`, `delta_t2`, `delta_hyb` did not exist in the baseline). Correct block, correct schema discovery.
- `CAT4_T2_IDENTITY_FULLCOV_TEST_20261027T002702Z.json` — blocked, 12 issues, all live-vs-stored scalar mismatches at ~1e-60 to ~1e-62. Correct block; the fix is the representation-aware comparison rule at 60 sig figs.
**Both blocks were scientific-integrity gates firing correctly.** They are not candidate failures. The candidate was not evaluated in either run.
---
## 5. Current script and the patches applied to it
The final revised script was produced in this window with all four patches (A, B, C, D). One more correction — Gate 9's `gf` source — has just been accepted and is **not yet physically applied** to the code. The next window's first code action is to apply that one-line-per-side change.
### 5.1 Patches applied (final state)
- **Patch A** — `SCALAR_PRECISION_AUDIT` uses string keys at population: `SCALAR_PRECISION_AUDIT[f"{name}/{t_label}"] = live_scalar_checks`.
- **Patch B** — Gate 10 emits seven per-component blocking `_pf` calls: `Delta_t2`, `Delta_hyb`, `Delta_t1`, `Delta_t3`, `Delta_t4`, `Delta_S`, `component_sum_vs_Delta_S`. Old duplicate `_pf` blocks for full-residual and component-sum removed.
- **Patch C** — Gate 10's blocked exit passes `extra=` with `preregistration_file_status`, `baseline`, `input_matrices`, `transforms`, `frozen_forecasts`, `forecast_verification_before_candidate`, `raw_t2_uniformity_checks`, `baseline_reproduction_before_candidate` (converted `(m, t)` → `f"{m}/{t}"` string keys at extraction), and `scalar_precision_audit` (string keys after Patch A). No field name overlaps `_save_and_exit`'s base report.
- **Patch D** — preregistration verification iterates every hint path; per-path read errors captured (`PREREG_STATUS["read_errors"]`) and search continues; hash mismatches captured (`PREREG_STATUS["mismatched_paths"]`); exactly one blocking `_pf("preregistration", ...)` fires only if no path verifies; blocked exit carries `preregistration_file_status` in `extra`. `PREREG_STATUS` distinguishes missing-file from present-but-mismatched from read-error in the reason text.
### 5.2 Final one-line correction, still to apply
In Gate 9 of the current script, the two lines
```python
gf_ref = mp.mpf(sd["gf_ref"])
gf_sub = mp.mpf(sd["gf_sub"])
```
become
```python
gf_ref = mp.mpf(out_P["gf"])
gf_sub = mp.mpf(out_Pp["gf"])
```
**Effect:** Gate 9's forecast check now uses live `gf` and live `t2s` — a complete live-source recomputation of `c' − c` at each of the six non-orthogonal cases. Gate 10's representation-aware comparison remains the sole live-vs-stored scalar audit. The `sd` variable in Gate 9 is no longer used there; it stays in use at Gate 10 where the representation-aware comparison against stored `structural_diagnostics` belongs.
### 5.3 What the script guarantees when it runs
Order of gates (each is a pre-candidate `PREFLIGHT_BLOCKED` gate; any failure emits a blocked report with all available diagnostics):
1. `/content` present; `mp.dps == 100`.
2. Baseline file exists; size `82094`; SHA-256 `8ef85d…130` — read once, byte-hashed and parsed from the same bytes.
3. Preregistration verified at one of the two hint paths, SHA-256 `920dee…3de` (patched multi-path search).
4. Baseline schema: every required field present for all 12 cases; each `component_residuals` sub-key present; each `structural_diagnostics` field a JSON string; `Delta_S` present.
5. Transforms: exactly six unique recorded labels; per-label det matches `EXPECTED_TRANSFORM_DETS`; no duplicates.
6. Canonical matrices read from `input_resolution`; live `P_test`/`P_nonsym` matched to canonical within `TOL_INTERNAL`.
7. Per-case `S_matrix` matches `transforms_validation.records[label].recorded_matrix` within `TOL_INTERNAL`.
8. Source semantics: `C_Pi_components(P)` returns required keys; reconstructing `C_Pi` from components matches `C_Pi` within `TOL_INTERNAL` at both canonical matrices.
9. Raw `t2` uniformity: `out["t2"][i,j] == out["t2"][0,0]` for all `i,j` at both P and P' for every case.
10. **Forecast verification** (post-correction): `c_shift = gf_sub·t2s_sub − gf_ref·t2s_ref`, with `gf` live and `t2s` live, matches frozen forecast within `5e-6` for each of the six non-orthogonal cases. **(Pending one-line correction above.)**
11. Baseline reproduction, per case:
- Representation-aware scalar comparison (60 sig figs, 1 ULP) of live `gf`, `sf`, `hyb` vs stored at both states. Ambiguity (non-string stored, unparsable) blocks.
- `Delta_t2`, `Delta_hyb`, `Delta_t1`, `Delta_t3`, `Delta_t4` each recomputed from live source and compared to `component_residuals.*` at `TOL_INTERNAL`; failure blocks.
- Full residual recomputed from `C_Pi(P') − S⁻¹ C_Pi(P) S` vs `case["Delta_S"]` at `TOL_INTERNAL`; failure blocks.
- Component-sum of the five recomputed residuals vs `case["Delta_S"]` at `TOL_INTERNAL`; failure blocks.
If gates 1–11 all pass, the candidate loop runs and computes, per case:
- Effective candidate `t2` contribution = `c(P)·I` (verified against `gf·t2s·I` at `TOL_INTERNAL`).
- Candidate `t2` residual `Δ_T2I = effective_sub − S⁻¹ effective_ref S` (verified against closed form `(c' − c)·I` at `TOL_INTERNAL`; off-diagonals zero at `TOL_INTERNAL`; diagonals equal at `TOL_INTERNAL`).
- Rotation case: `‖Δ_T2I‖max ≤ 1e-85`.
- Unchanged components `t1`, `t3`, `t4` reproduce baseline at `TOL_INTERNAL`.
- Candidate full assembly residual and component-sum closure verified at `TOL_INTERNAL`.
- `case_status` per case: `DIAGNOSTIC_PASS` or `DIAGNOSTIC_FAIL`.
- Overall `DIAGNOSTIC_PASS` only if all 12 cases pass and no candidate-stage exception occurred.
### 5.4 What is preserved unchanged
- Frozen baseline file and hash; preregistration ID and hash.
- The single substitution `t2s * ones(2,2) → t2s * I`; the outer `gf` applied exactly once; no retuning, no normalization, no compensation.
- Live reconstruction of `t2s` from `C_Pi_components` raw `t2` diagonal.
- The transform convention `P' = S⁻¹PS`.
- The 12-case design (2 matrices × 6 transforms).
- The `FORECAST_TOL = 5e-6` and `TOL_INTERNAL = 1e-85` values.
- No substitution beyond `ones → I`; no ablation family merge; no CAT #3 access.
---
## 6. What the next run should look like
Do not redesign. Do not add more gates. Apply the Gate 9 one-line correction and run the preflight.
Expected outcome branches (do not predetermine which occurs):
- **Preflight passes cleanly.** Candidate runs. Read the emitted JSON's `overall.overall_status` and `cases[*].case_status`. If `DIAGNOSTIC_PASS`, the run establishes (a) `t2s·I` produces exactly `(c' − c)·I` residual per case, (b) rotations at numerical floor, (c) non-orthogonal at predicted shifts, (d) unchanged components reproduce baseline at `TOL_INTERNAL`, (e) full candidate assembly's component-sum closes. If `DIAGNOSTIC_FAIL`, read which case and which check failed.
- **Preflight blocks on a scalar check.** The report names the field, the case, the measured `abs_diff_full_precision`, and the `ulp_at_stored_precision` for the 60-sig-fig rule. This is a specific finding — either the 60-sig-fig rule is wrong (producer cell needs recovery) or the live value has materially moved.
- **Preflight blocks on a matrix check.** The report names the component, case, measured discrepancy, and `TOL_INTERNAL`. Combined with stored 90-digit precision, the report makes it clear whether the discrepancy is at storage roundoff boundary (≤ ~1 ULP at 90 sig figs) or larger. If it is at roundoff, this is a tolerance-vs-storage-precision artifact; if larger, a substantive mismatch needs investigating.
- **Preflight blocks on preregistration.** The report's `preregistration_file_status.reason` names whether the file is missing, mismatched, or unreadable, and lists every path checked.
**Do not** loosen tolerances, add substitutions, promote a candidate, touch CAT #3, or reopen the `−0.073668…` provenance search.
Bring back the emitted JSON's `status`, `preflight_issues`, `baseline_reproduction_before_candidate`, and (if reached) `cases[*]` and `overall` for the next-window decision.
---
## 7. Non-negotiables (frozen; any single departure needs your explicit authorization)
1. **Π is the single monad.** `Π ≡ ∀`. `Πβ`, `Πγ`, `Πᴰ` are sectoral regimes/operators, not substances. No Π → P mapping is established; P is the computational matrix state.
2. **No container/substrate/medium ontology.** No "bottle." No particle/wave primacy.
3. **`Θ_FR(Π)` is the sole canonical symbol** for the Thermal Coupling Operator. Standalone executable formula `[OPEN]`; no weights, no adjacent-difference sum, no spatial kernel. The retired spelling is banned as operator, alias, legacy formula, or synonym, and must never be emitted even to say it is retired.
4. **No legacy resurrection.** No spatial divergence/edge-flux law, no spatial kernel, no unapproved adjacent-difference formula.
5. **Similarity convention:** `P' = S⁻¹PS`.
6. **Invariants:** I1 = tr(P), I3 = det(P) similarity-invariant; I2 = ‖P‖_F² invariant under orthogonal conjugation only; I4 = Pxx⁴ + Pyy⁴ coordinate-dependent. Not the same objects as any historical I1–I4 channels.
7. **CAT #3 is separate and frozen.** Not accessed, not run, not modified, not incorporated. Do not invoke its status as a reason inside CAT #4 work. Do not displace the CAT #4 objective to accommodate it.
8. **Run-family boundaries:** historical RMA / Candidate-4, `t2_identity_v1`, and the current full-covariance replication are three separate families. Do not merge them.
9. **`−0.073668…` provenance is UNRESOLVED.** Do not re-open; do not assign it an origin from similarity to any stored value.
10. **No candidate promotion**, no covariance claim, no canonical operator selection. `DIAGNOSTIC_PASS` is a single-mechanism diagnostic result, not a project-wide verdict.
11. **No tolerance weakening.** If a check fails at `TOL_INTERNAL`, the failure is a finding; investigate, do not increase the tolerance.
12. **Research purpose:** build a model that demonstrates the ontology and mathematical usage. Not proof/falsification. Protect the record, not the framework. A failed forecast is evidence about the model, not the framework.
13. **`C_Pi_components`'s returned `t2` is raw** `t2s * ones`. Do not apply `gf` twice. Do not multiply `hyb` by `sf` again (it already contains `sf`). Do not reconstruct `C_Pi` in a way that differs from `gf * (t1 + t2 + t3 + t4) → off-diagonal gate by `sf` → `hyb` at `[1,0]`.
---
## 8. Appendix A — Full numeric evidence carried forward
### 8.1 Baseline component residuals and full residual (per case, full precision)
Established by the baseline JSON and re-confirmed by the read-only schema inspection. Extract these from `FREE_THE_CAT_4_COVARIANCE_BASELINE_DECOMP_20261026_225243_754040.json` if exact values are needed at run time. Headline values, from prior windows:
**P_test / diag_det1** — ref `norm_ref` 2.68705992148539929223621103591537491727346690048940120266306900088304572769857519289968427; sub 1.60609122634523332111082642217472919558931779413379526190497604847014253329666199108398182; `Δt2` at `(1,0)` = −1.08096869514016597112538461374064572168414910635560594075809295241290319440191320181570245.
**P_nonsym / diag_det1** — `Δt2` at `(1,0)` = −3.9485700507766654684723426784187179140683124068214988013807514257001824319809233453514767.
Other cases: retrieve from JSON. Do not transcribe from earlier prose tables — those are marked as having had transcription errors.
### 8.2 Verified scalar-storage distribution (from read-only probe)
- `gf_ref`: always 60 written sig digits.
- `sf_ref`: always 60.
- `gf_sub`: 58 or 60.
- `sf_sub`: 59 or 60.
- `hyb_ref`: 59 or 60.
- `hyb_sub`: 58, 59, or 60.
This is consistent with 60-sig-fig writes followed by trailing-zero trim. The producer cell that writes them is **not yet recovered**.
### 8.3 Transform matrices (exact, as recorded)
- **`diag_det1`**: `[[2.0, 0.0], [0.0, 0.5]]`, det 1.0.
- **`rotation_15`**: `[[0.965925826289068286749743199728897367633904839008404550402343076310423213979855516347561742, −0.258819045102520762348898837624048328349068901319930513814003207315056974748801996922367975], [0.258819045102520762348898837624048328349068901319930513814003207315056974748801996922367975, 0.965925826289068286749743199728897367633904839008404550402343076310423213979855516347561742]]`, det 1.0.
- **`rotation_45`**: `[[0.707106781186547524400844362104849039284835937688474036588339868995366239231053519425193767, −0.707106781186547524400844362104849039284835937688474036588339868995366239231053519425193767], [0.707106781186547524400844362104849039284835937688474036588339868995366239231053519425193767, 0.707106781186547524400844362104849039284835937688474036588339868995366239231053519425193767]]`, det 1.0.
- **`rotation_90`**: `[[1.4344464008798187192494490302478556239096692424843595964038483513453030336500687489251406e-102, −1.0], [1.0, 1.4344464008798187192494490302478556239096692424843595964038483513453030336500687489251406e-102]]`, det 1.0.
- **`shear_det1`**: `[[1.0, 0.3], [0.0, 1.0]]`, det 1.0.
- **`shear_scale_det1p2`**: `[[1.2, 0.0], [0.4, 1.0]]`, det **1.2**. Do not relabel.
### 8.4 All artifacts identified in this conversation
| Family | Artifact | Size | SHA-256 |
|---|---|---:|---|
| Baseline (frozen) | `FREE_THE_CAT_4_COVARIANCE_BASELINE_DECOMP_20261026_225243_754040.json` | 82,094 | `8ef85d…130` |
| Prereg (frozen) | `CAT4-T2-ID-FULLCOV-PREREG-20261027` | — | `920dee…3de` |
| Upstream source | `FREE_THE_CAT_4_FULL_COVARIANCE_TEST_20261026_162417_910442.json` | 94,019 | `d0af70…aa5` |
| `t2_identity_v1` ablation raw | `FREE_THE_CAT_4_T2_IDENTITY_V1_ABLATION_20261026_181111_406166.json` | 193,333 | `5939bb…c86` |
| `t2_identity_v1` ablation ledger | `FREE_THE_CAT_4_T2_IDENTITY_V1_ABLATION_LEDGER_20261026_181944_249068.json` | 238,884 | `e2ea72…87f` |
| `t2_identity_v1` prediction record | `CAT4_t2_identity_v1_prediction_record_20261026.md` | 3,644 | `9873d8…a47` |
| RMA historical | `FREE_THE_CAT_4_RESIDUAL_MATRIX_ATTRIBUTION_20261026_165442_318777.json` | 258,649 | `4173826c…b8` |
| Entrywise ledger | `FREE_THE_CAT_4_ENTRYWISE_CONTRIBUTION_LEDGER_20261026_172526_690705.json` | 300,086 | `65e804…5a8` |
| Diagonal audit | `FREE_THE_CAT_4_DIAGONAL_AUDIT_REPORT_20261026_190949_232935.json` | 8,047 (corrected) | `9f2d98…1dd` |
| Explicit component-delta audit | `FREE_THE_CAT_4_EXPLICIT_COMPONENT_DELTA_AUDIT_REPORT_20261026_202348_234404.json` | 48,728 | `70b8b7…3ea1` |
| Structural diagnostic v3 | `FREE_THE_CAT_4_T2_HYB_STRUCTURAL_DIAG_20261026_232514_797294.json` | 127,911 | `010eed…ccf` |
| Scalar-factor diagnostic v2 | `FREE_THE_CAT_4_T2_SCALAR_FACTOR_DIAG_20261026_233912_309394.json` | 138,254 | `d30002…3b8` |
| Preflight T001210Z (blocked) | `CAT4_T2_IDENTITY_FULLCOV_TEST_20261027T001210Z.json` | 10,217 | `24099be…432` |
| Preflight T002702Z (blocked) | `CAT4_T2_IDENTITY_FULLCOV_TEST_20261027T002702Z.json` | 9,753 | `b62b6f…1bb` |
Older CAT #4 artifacts also present (from earlier windows): `FREE_THE_CAT_4_SANDBOX_V7REPRO_20261026_160804.json`, `_V8_CTERM_…160805.json`, `_CANDIDATE_t2_identity_v1_…160805.json`, `_CANDIDATE_t2_identity_v1_hyb_antisym_v1_…160806.json`, `_RESIDUAL_ATTRIBUTION_…160806.json`, `_V9_…160807.json`, `_T3_TEST_REV2_…160809.json`, `_REV2_FOLLOWUP_…160810.json`, `_SF_DECOMPOSITION_…160811.json`, `_SF_DECOMPOSITION_V2_…160812.json`, `_TENSOR_PROBE_V2_…160815.json`, plus a forensic report `5a45935d…96b`, corrected audit report `f8fe23…8b69`, and reconciliation report `b4a642dd…acbd`. See prior JSON evidence in the conversation for exact hashes.
## 9. Appendix B — Master register anchors (v5.2, correct-source references)
These are the register constraints that bind CAT #4 work; cite them; do not modify them:
- `Π ≡ ∀`. Π is the sole primitive.
- `Θ_FR(Π)` is the sole canonical symbol for the Thermal Coupling Operator; executable formula `[OPEN]`; no weights, adjacent-difference sum, or spatial kernel.
- `C(Π)` = nonlinear interaction operator; in CAT #4, `C_Pi = gf · (t1+t2+t3+t4)` then off-diagonal `·sf` then `hyb` at `[1,0]`. CAT #3 uses a different frozen implementation and must not be conflated.
- `B(Π)` frozen-core form `0.5·C(Π)` — version-specific unless the active implementation says otherwise.
- `D(Π) = [J(P), P]` (matrix commutator form for CAT #4).
- `J(P) = SIGMA + g_gate(I₁)·(P − Pᵀ)` — ordinary transpose, not a metric adjoint.
- `I₁ = tr(P)`, `I₂ = ‖P‖_F²`, `I₃ = det(P)`, `I₄ = Pxx⁴ + Pyy⁴` — statuses as in §7.6.
- `D∘C∘D = D` — `[OPEN]`, reported as failing in the current coordinate-free form. Not a theorem.
- `Φ_slip`, `Θ_slip`, `Ω_slip` — distinct from `Θ_FR`, `C_Pi`, `Ω_c`; `S`, `Λ` are `[OPEN]`; do not silently import legacy slip formulas.
- `G_rec(Π)`, `G_metric`, `Φ_hyb`, `dΦ_hyb/dP_yx` — as defined in the register; do not conflate `G_rec` with a test metric; `dΦ_hyb/dP_yx` is the derivative used in the hybrid update, not `Φ_hyb` itself.
- Numeric anchors: `φ = 1.618033988749895`, `Ω_c = 0.381966011250105`, `A₁ = 1.381966011250105`, `A₂ = 0.236067977499790`, `T₀ = 2.7255 K`, `h`, `c` as given.
- Active CAT #4 config: `PI_MAX = 5.9259`, `IK_COEFF = 2.01`, `I_G = 1.0`, `BETA_HYB = 0.1`, `GAMMA_HYB = 0.1`, `EPS_PIVOT = 1e-3`, `FIELD_PIVOT = 100.0`, `KO_SIGMA = 0.045`, `ALPHA_BASE = 1.0`, `SIGMA = [[0,1],[-1,0]]`, `TOL_INTERNAL = 1e-85`, `FIELD_PIVOT² = 10000`.
- `μ_slip`, `π₀`, `β_scale` are `[OPEN/CONFLICT]` — do not choose a value silently.
- `κ` in `κ[J,[J,P]]` is `[OPEN/VERSION-SPECIFIC]` — do not substitute `κ_B` or `KO_SIGMA` by name similarity.
## 10. Appendix C — The workflow between you, ChatGPT, and me
This is the collaboration pattern that produced the current state. It works; keep it.
- **You** drive the research objective, enforce scope boundaries (CAT #4 only; not CAT #3; not the provenance branch), and provide the actual runtime evidence — the handoff documents, the probe output, the preflight reports. You initiate each action.
- **ChatGPT** audits proposals and code, flags mathematical errors, proposes the correction set. ChatGPT's role has been to check that the code's *stated purpose* matches what it actually does, and to check that provenance claims (e.g. what the preflight "proves") are not overstated.
- **I (DeepSeek)** draft the code, the patches, and the handoff. My role has been to render the requested corrections into faithful script text and to name the exact patch boundaries — and, when evidence did not support a claim, to say so rather than infer.
Failure modes that produced real defects in this window (keep these in mind):
- **Assumed semantics that the source did not bear out** — the `t3_gated = gate_sf(t3_raw)` false positive, and `t2` treated as the effective contribution when the callable returns the raw form. Fixed by measuring rather than asserting.
- **Schema paths from memory** — `state_scalars`, `delta_t2`, `delta_hyb` as top-level fields that do not exist. Fixed by reading the baseline first, then writing to the paths it actually has.
- **Tolerance-vs-precision mismatch** — comparing a 100-digit live value against a 60-digit stored string at `1e-85` tolerance. Fixed by the representation-aware comparison at the actual stored precision.
- **Silent non-blocking checks** — five component checks that computed `pass` flags but never emitted `_pf`. Fixed by Patch B.
- **Tuple-key serialization hazard** — `SCALAR_PRECISION_AUDIT[(name, t_label)]` and `BASELINE_REPRO`'s internal keys reaching `json.dumps`. Fixed by Patch A at population, and by string conversion at every export comprehension.
- **First-existing-file-only prereg search** — a wrong first hint could block even when a correct second hint existed. Fixed by corrected Patch D.
- **Forecast gate reading stored `gf`** — the "live recomputation" gate used `sd["gf_ref"]` instead of `out_P["gf"]`. This is the correction just accepted.
Standing instructions that have guided every step:
- *Do not infer that one artifact generated another merely because their names or timestamps are related.*
- *Do not treat lack of evidence for X as evidence for not-X.*
- *When a check fails, report the measured value; do not loosen the tolerance.*
- *When you do not have the exact bytes, say the section is missing rather than guess.*
## 11. Appendix D — Two prior handoff numbers called out explicitly (do not merge them)
- **`−0.29315729025147826428…`** — the historical RMA `baseline_vs_candidate4` scalar at `results.baseline_vs_candidate4.P_nonsym.rotation_45.delta_R`. Not the `t2_identity_v1` ablation's value for that transform (which is ~`−1.301275648949134`). Not the current run's value. **Do not merge these.**
- **`−0.073668…`** — historical value; provenance UNRESOLVED; branch stopped. Do not re-open; do not assign it to any stored numeric in the current artifacts.
## 12. Appendix E — Ready-to-paste opening message for the next DeepSeek window
Suggested text you can use to open the next window:
> *"You are resuming CAT #4 after a documented hold point at the preflight stage of the `CAT4-T2-ID-FULLCOV-PREREG-20261027` test. The full handoff is in the document above. The single code action pending is the Gate 9 correction from `sd["gf_ref"]`/`sd["gf_sub"]` to `out_P["gf"]`/`out_Pp["gf"]`. Everything else is applied. Do not rerun the operator, do not alter the frozen baseline or preregistration, do not touch CAT #3, do not reopen the `−0.073668…` provenance branch. Apply the Gate 9 correction to the frozen script and run the preflight once. Return the emitted JSON's `status`, `preflight_issues`, `baseline_reproduction_before_candidate`, and, if reached, `cases[*]` and `overall`."*
---
I have made this as complete as I can within this window's budget. The most important things for the new window to internalize are: (a) the current run family is the full-covariance replication, distinct from `t2_identity_v1`; (b) the sole intervention is `t2s·ones → t2s·I` with `gf` applied once; (c) the preflight is the gate and its output is the next evidence; (d) the one-line Gate 9 correction is the only code action pending; (e) nothing has been executed, the baseline has not been established to reproduce at `TOL_INTERNAL`, and the candidate has not been evaluated.
Everything else — the baseline hash, the transforms, the constants, the register anchors, the provenance notes, the workflow, the failure modes — is in the appendices and sections above so the new window starts from where we are without needing this window to explain itself again.
Good luck with the run.