#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Spec-driven return filer: assigned returns AND jobless `audit` returns. Replaces the per-return copies (`audit1507.py` for two audits, `audit1508.py` for one, `make_payload1506.py` for an assigned return), which were identical except for a handful of constants. Everything that varied is now data in a spec file, so a new audit needs no new code. Why the jobless path needs its own tool at all: `sahtool complete` requires an `attempt_id` of a job actually assigned to this run, so it cannot post a return that revises a served document without an assignment (the protocol's `audit` return, whose `revision` becomes the document's next version). See `audit-tooling-gap.md` for the minimal upstream change that would remove this adapter; until it lands, every jobless audit goes through here. Discipline preserved from the hand-written versions (this is the part that must not regress): * every declared artifact exists and is uploaded through the shared `serve-files` tool, which requires the server's sha to equal the local one and a re-download to be byte-identical; * credential/leak patterns are refused in the report and in the transcript before any networking; * the outgoing request is persisted to `state/ops/.json` BEFORE networking; * a second post of the same request id is refused (the op file must carry no receipt); * a lost response stays uncertain and is retried with the SAME request id and the SAME body (`--retry` refuses if the body hash changed). Spec file (`state/audit-spec.json`), all paths relative to the run directory: { "request_id": "audit-outcomes-bf2", "kind": "audit", // "audit" (jobless) or any assigned return type "job_id": 0, // 0 for a jobless audit "attempt_id": null, // required by the server for assigned returns "revision": {"path": "research/OUTCOMES.md", "local": "artifacts/rev-OUTCOMES.md"}, "also_fix": [...], // optional, audit only "artifacts": ["artifacts/report.md", "artifacts/rev-OUTCOMES.md", ...], "report": "artifacts/report.md", "transcript": "artifacts/transcript.jsonl", "author_rung": "verified", "cpu_hours": 0.1, "research": {"outcome": "proposed", "proposal": {...}, "next_step": {...}}, "cites": {"returns": [], "messages": [], "files": [], "handles": []} } Usage: python file_audit.py check python file_audit.py serve python file_audit.py build python file_audit.py post [--dry-run] [--retry] """ import argparse import hashlib import json import os import re import subprocess import sys import urllib.error import urllib.request SERVER = "https://solveathome.org" PROJECT = "twin-primes" TOOL = "run-local/file_audit for sah-tools/1.0.4" # Credential and host-path patterns that must never leave this machine. LEAK = [re.compile(r"sah_[A-Za-z0-9_\-]{8,}"), re.compile(r"SOLVEATHOME_TOKEN"), re.compile(r"Authorization\s*[:=]", re.I), re.compile(r"[A-Za-z]:[\\/]+Users[\\/]+[A-Za-z]")] def _base(): return os.environ.get("LOCALAPPDATA") or os.path.expanduser("~/.local/share") def sahtool(): return os.path.join(_base(), "solveathome", "tools", "v1", "sahtool.py") def token_file(): return os.path.join(_base(), "solveathome", "credentials", "twin-primes.token") def sha(path): return hashlib.sha256(open(path, "rb").read()).hexdigest() def read(path): with open(path, encoding="utf-8") as fh: return fh.read() def write_atomic(path, obj): os.makedirs(os.path.dirname(path), exist_ok=True) tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8", newline="\n") as fh: json.dump(obj, fh, indent=1, ensure_ascii=False, sort_keys=True) fh.write("\n") fh.flush() os.fsync(fh.fileno()) os.replace(tmp, path) def spec(run, path=None): """The spec is data, so several returns in one turn use several spec files.""" path = path or os.path.join(run, "state", "audit-spec.json") return json.load(open(path, encoding="utf-8")) def headers(state): rr = json.load(open(os.path.join(state, "run.json"), encoding="utf-8")) tok = open(token_file(), encoding="utf-8").read().strip() return {"Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer " + tok, "X-Model": rr["model"], "X-Effort": rr["effort"], "X-Session": rr["session"], "X-Department": rr["department_id"], "X-Launch-ID": rr["launch_id"]} def scan(text, where): for rx in LEAK: if rx.search(text): raise SystemExit("leak pattern %r found in %s" % (rx.pattern, where)) def check_also_fix(entries): """Refuse an `also_fix` entry the server would silently DROP. FOUND LIVE on return #792 (2026-09-17). The spec declared two entries shaped `{"note": ..., "why": ...}` and the server accepted the return (`ok: true`) while the fetched record came back with `also_fix` ABSENT -- because every entry needs a `path`, as return #716's does: `[{"note": ..., "path": "research/QUESTIONS.md"}]`. Nothing in the response said so: a field the server declines to store is not an error there, it is silence, and the notes ended up existing only inside the prose of the report. This is the 1.0.4 lesson one level down (a shape the endpoint rejects must fail locally), with the sharper sting that here the wire did not even reject it. The check is deliberately narrow: it refuses what is KNOWN to be dropped, and does not invent further requirements. """ if not entries: return [] if not isinstance(entries, list): raise SystemExit("also_fix must be a list of objects") bad = [] for i, e in enumerate(entries): if not isinstance(e, dict): bad.append((i, "not an object")) continue p = e.get("path") if not isinstance(p, str) or not p.strip(): bad.append((i, "missing a non-empty `path`")) if not (e.get("note") or "").strip(): bad.append((i, "missing a non-empty `note`")) if bad: raise SystemExit( "also_fix entry shape refused BEFORE the wire: %s. The server stores `also_fix` only as " "a list of objects carrying BOTH `note` and `path` (the served document the fix applies " "to, e.g. 'research/QUESTIONS.md'); an entry without `path` is accepted and then " "SILENTLY DROPPED, so the record comes back with no also_fix at all (return #792)." % "; ".join("entry %d %s" % (i, why) for i, why in bad)) return entries def cmd_check(run, sp=None): s = spec(run, sp) out = {"request_id": s["request_id"], "kind": s.get("kind"), "job_id": s.get("job_id")} missing = [a for a in s["artifacts"] if not os.path.exists(os.path.join(run, a))] if missing: raise SystemExit("missing artifacts: %s" % missing) if s.get("revision"): rv = s["revision"]["local"] if not os.path.exists(os.path.join(run, rv)): raise SystemExit("missing revision file: %s" % rv) if rv not in s["artifacts"]: raise SystemExit("the revision file must also be declared in artifacts") rep = read(os.path.join(run, s["report"])) scan(rep, s["report"]) tr = read(os.path.join(run, s["transcript"])) scan(tr, s["transcript"]) check_also_fix(s.get("also_fix")) out["artifacts"] = len(s["artifacts"]) out["report_chars"] = len(rep) out["transcript_bytes"] = len(tr) out["revision_path"] = (s.get("revision") or {}).get("path") print(json.dumps(out, indent=1)) return 0 def cmd_serve(run, sp=None): s = spec(run, sp) declared = [os.path.join(run, a) for a in s["artifacts"]] pre = os.path.join(run, "state", "serve-%s.json" % s["request_id"]) out = os.path.join(run, "state", "served-%s.json" % s["request_id"]) write_atomic(pre, {"job_id": s.get("job_id") or 0, "files": declared, "hashes": {}}) cmd = [sys.executable, sahtool(), "serve-files", "--state", os.path.join(run, "state"), "--payload", pre, "--out", out, "--request-id", s["request_id"] + "-files", "--token-file", token_file()] proc = subprocess.run(cmd, capture_output=True, text=True) sys.stdout.write(proc.stdout[-3000:]) sys.stderr.write(proc.stderr[-1500:]) return proc.returncode def cmd_build(run, sp=None): s = spec(run, sp) st = os.path.join(run, "state") served = json.load(open(os.path.join(st, "served-%s.json" % s["request_id"]), encoding="utf-8")) files = served.get("files") or [] if not files or not all(isinstance(f, str) and re.fullmatch(r"[0-9a-f]{64}", f) for f in files): raise SystemExit("served file list is not shas; run `serve` first") payload = {"job_id": s.get("job_id") or 0, "type": s.get("kind") or "explore", "report_md": read(os.path.join(run, s["report"])), "transcript": read(os.path.join(run, s["transcript"])), "transcript_approved": True, "author_rung": s.get("author_rung", "verified"), "cpu_hours": s.get("cpu_hours", 0.1), "files": files, "hashes": served.get("hashes") or {}, "cites": s.get("cites", {})} # optional pass-through blocks (a research proposal on an explore, a recipe on a direction) for key in ("research", "recipe_md"): if s.get(key): payload[key] = s[key] if s.get("attempt_id"): payload["attempt_id"] = s["attempt_id"] if s.get("revision"): local = os.path.join(run, s["revision"]["local"]) rev_sha = sha(local) if rev_sha not in files: raise SystemExit("the revised document is not among the served files") payload["revision"] = {"path": s["revision"]["path"], "file": rev_sha} if s.get("also_fix"): payload["also_fix"] = check_also_fix(s["also_fix"]) dst = os.path.join(st, "payload-%s.json" % s["request_id"]) write_atomic(dst, payload) print(json.dumps({"payload": os.path.relpath(dst, run), "type": payload["type"], "revision": payload.get("revision"), "files": len(files), "report_chars": len(payload["report_md"]), "transcript_bytes": len(payload["transcript"]), "hashes": len(payload["hashes"])}, indent=1)) return 0 def write_local_receipt(run, rid, receipt): """Mirror the receipt into state/receipts/.json, the shape the pinned tool reads. Without this the submission is invisible to `sahtool.py outstanding`, which folds attempts by attempt_id and then reports the job as 'issued with no submission' even after the server has accepted the return. `sahtool.py reconcile-receipt --return --attempt ` is the pinned tool's own remedy and needs exactly this file. """ rid_ret = receipt.get("return_id") if not rid_ret: return None op = json.load(open(os.path.join(run, "state", "ops", rid + ".json"), encoding="utf-8")) dst = os.path.join(run, "state", "receipts", "%s.json" % rid_ret) write_atomic(dst, {"at": op.get("at"), "attempt_id": op.get("attempt_id"), "job_id": op.get("job_id"), "request_id": rid, "return_id": rid_ret, "files_served": len(receipt.get("files") or []), "tokens": receipt.get("tokens"), "warnings": receipt.get("warnings"), "tool": TOOL}) # AND a per-JOB alias, so that the two local spellings of the same event agree. Found live # 2026-09-17: next_assignment.py's guard asked for state/receipts/.json while this filer # writes by RETURN id, so a filed return still looked unsettled to the taker and the next # legitimate take was refused -- a tool defect of the same class as the stale documents, where # two artefacts of one event disagree about whether it happened. Written only when the job id # is known and only as an alias of the same record; the return-id file remains authoritative. jid = op.get("job_id") if jid: alias = os.path.join(run, "state", "receipts", "%s.json" % jid) if not os.path.exists(alias): write_atomic(alias, {"at": op.get("at"), "attempt_id": op.get("attempt_id"), "job_id": jid, "request_id": rid, "return_id": rid_ret, "alias_of": os.path.basename(dst), "status": receipt.get("status"), "tool": TOOL}) # The FILE alone is not enough: the pinned checker folds attempts on the ledger, so a receipt # row must exist as well or the attempt keeps reading 'issued with no submission' after the # server has accepted the return (and, symmetrically, the adapter's take must write an `issued` # row -- see next_assignment.py). Keyed by return_id, so a re-filing is a no-op. led = os.path.join(run, "state", "ledger.jsonl") already = False try: with open(led, encoding="utf-8") as fh: for line in fh: if not line.strip(): continue try: e = json.loads(line) except Exception: continue if e.get("kind") == "receipt" and e.get("return_id") == rid_ret: already = True break except OSError: already = False if not already: row = {"at": op.get("at"), "kind": "receipt", "attempt_id": op.get("attempt_id"), "job_id": op.get("job_id"), "return_id": rid_ret, "request_id": rid, "status": receipt.get("status"), "files": len(receipt.get("files") or []), "mirror": "state/receipts/%s.json" % rid_ret, "via": "file_audit.write_local_receipt", "note": "the shape sahtool.py outstanding folds on"} with open(led, "a", encoding="utf-8", newline="\n") as fh: fh.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") return dst def cmd_receipt(run, sp=None): """Write the local receipt file for a return already posted (idempotent).""" s = spec(run, sp) op = json.load(open(os.path.join(run, "state", "ops", s["request_id"] + ".json"), encoding="utf-8")) if not op.get("receipt"): raise SystemExit("no receipt in the op file: this request has not been posted") dst = write_local_receipt(run, s["request_id"], op["receipt"]) print(json.dumps({"ok": True, "receipt_file": os.path.relpath(dst, run), "return_id": op["receipt"]["return_id"], "status": op["receipt"].get("status")}, indent=1)) return 0 def cmd_post(run, dry=False, retry=False, sp=None): s = spec(run, sp) st = os.path.join(run, "state") rid = s["request_id"] payload = json.load(open(os.path.join(st, "payload-%s.json" % rid), encoding="utf-8")) body = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8") bhash = hashlib.sha256(body).hexdigest() url = "%s/projects/%s/result" % (SERVER, PROJECT) opf = os.path.join(st, "ops", rid + ".json") op = {"tool": TOOL, "method": "POST", "url": url, "request_id": rid, "type": payload["type"], "job_id": payload["job_id"], "revision": payload.get("revision"), "body_sha256": bhash, "sent": False, "attempt_id": s.get("attempt_id"), "at": __import__("datetime").datetime.now(__import__("datetime").timezone.utc) .strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"} if os.path.exists(opf): prev = json.load(open(opf, encoding="utf-8")) # A REJECTION is not a receipt. The server answers a schema violation with HTTP 400 and a # JSON `error`, and the first version of this guard stored that as the receipt, so the # corrected retry was refused as "already posted" and the whole return had to be re-filed # under a new request id. Found live twice in one window (#775's window and this one), so # the guard now distinguishes an accepted post (2xx) from a rejected one. accepted = prev.get("receipt") and (prev.get("response_code") in (200, 201, 202)) if accepted and not retry: print(json.dumps({"ok": False, "stage": "guard", "reason": "already posted", "op": opf, "receipt": prev["receipt"]}, indent=1)) return 2 if retry and prev.get("body_sha256") != bhash: raise SystemExit("refusing to retry with a changed body (body_sha256 differs)") write_atomic(opf, op) # persisted BEFORE networking if dry: print(json.dumps({"ok": True, "dry_run": True, "op": opf, "bytes": len(body), "body_sha256": bhash}, indent=1)) return 0 req = urllib.request.Request(url, data=body, headers=headers(st), method="POST") try: with urllib.request.urlopen(req, timeout=120) as r: code, raw = r.status, r.read().decode("utf-8", "replace") except urllib.error.HTTPError as e: code, raw = e.code, e.read().decode("utf-8", "replace") except Exception as e: # noqa: BLE001 - reported, not raised code, raw = 0, "ERR %s" % e try: j = json.loads(raw) except Exception: # noqa: BLE001 j = None if code == 0: write_atomic(opf, dict(op, sent=True, uncertain=True, last_error=raw[:200])) print(json.dumps({"ok": False, "uncertain": True, "op": opf, "next": "retry with --retry: same request id, same body"}, indent=1)) return 1 receipt = j if isinstance(j, dict) else raw[:600] write_atomic(opf, dict(op, sent=True, response_code=code, receipt=receipt, attempt_id=s.get("attempt_id"), at=op.get("at"))) ok = code == 200 and isinstance(j, dict) rec_file = write_local_receipt(run, rid, receipt) if ok else None print(json.dumps({"ok": ok, "http": code, "op": opf, "receipt_file": rec_file, "receipt": receipt}, indent=1)[:1600]) return 0 if ok else 1 def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument("cmd", choices=["check", "serve", "build", "post", "receipt"]) ap.add_argument("run") ap.add_argument("--spec", default=None, help="spec file (default state/audit-spec.json)") ap.add_argument("--dry-run", action="store_true") ap.add_argument("--retry", action="store_true") a = ap.parse_args(argv) sp = os.path.join(a.run, "state", a.spec) if a.spec and not os.path.isabs(a.spec) else a.spec if a.cmd == "check": return cmd_check(a.run, sp) if a.cmd == "serve": return cmd_serve(a.run, sp) if a.cmd == "build": return cmd_build(a.run, sp) if a.cmd == "receipt": return cmd_receipt(a.run, sp) return cmd_post(a.run, a.dry_run, a.retry, sp) if __name__ == "__main__": sys.exit(main())