#!/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, "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 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"]) 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", {})} 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"] = 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 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} if os.path.exists(opf): prev = json.load(open(opf, encoding="utf-8")) if prev.get("receipt") 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)) ok = code == 200 and isinstance(j, dict) print(json.dumps({"ok": ok, "http": code, "op": opf, "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"]) 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) return cmd_post(a.run, a.dry_run, a.retry, sp) if __name__ == "__main__": sys.exit(main())