#!/usr/bin/env python3 """Give every patch/revision-bearing accepted return a content-addressed base. Job 2866 (pursue route 139), continuing return #1517. Input: lane-index.json written by enumerate_lane.py. For each bearing return this produces a certificate: return_id, path, base_sha256, post_sha256, applying_candidates, proof, needs_publication Resolution: * revision rows: the store's own version history names the base (the version preceding the one authored by this return) and the post (the version whose return_id is this return). * patch rows, corpus path: candidates = /docs rendering + every /history version whose bytes are served at host root; a candidate is a base when every hunk applies at a unique overlapping occurrence; the post-image is pinned when all applying candidates agree. * patch rows, bare script: candidates = the files this return itself uploaded (host root /files/), since a script patch's base is another uploaded script, not a corpus path. Read-only. Writes base-certificates.json + base-certificates.md + stdout. """ import json, os, sys, hashlib HERE = os.path.dirname(os.path.abspath(__file__)) SAH_HOME = os.path.abspath(os.path.join(HERE, "..", "..", "..")) sys.path.insert(0, os.path.join(SAH_HOME, "tools")) sys.path.insert(0, HERE) import sah from anchor_probe import get, parse_patch, occ_offsets LAUNCH = "launch-zdvw3ktup0yka1yia4jkri3g" state = sah.state_dir() run_dir = os.path.join(state, "runs", LAUNCH) launch = json.load(open(os.path.join(run_dir, "launch.json"))) binding = json.load(open(os.path.join(state, "device-binding.json"))) iden = sah.identity() H = {"Authorization": "Bearer " + sah.cred(), "Accept": "application/json", "X-Model": iden["model"], "X-Effort": iden["effort"], "X-Department": binding["department_id"], "X-Session": launch["session"], "X-Attempt": launch["attempt_id"], "User-Agent": "deepseek-harness/sah-tools " + sah.TOOL_VERSION} sha = lambda t: hashlib.sha256(t.encode()).hexdigest() def apply_hunks(base_text, hunks): cur, notes = base_text, [] for hk in hunks: pre, post = hk["pre_slice"], hk["post_slice"] offs = occ_offsets(cur, pre) notes.append({"header": hk["header"], "pre_occ": len(offs)}) if len(offs) != 1: return None, notes o = offs[0] cur = cur[:o] + post + cur[o + len(pre):] return cur, notes def history_versions(path): h, _ = get("/history/" + path) if not h: return [] try: return json.loads(h).get("versions") or [] except Exception: return [] def version_texts(path): out = [] d, _ = get("/docs/" + path) if d is not None: out.append({"name": "docs(current)", "sha": sha(d), "text": d}) for v in history_versions(path): s = v.get("content_sha") if not s: continue t, _ = get("host:/files/" + s) if t: out.append({"name": f"v{v.get('version')}", "sha": s, "text": t, "return_id": v.get("return_id"), "summary": (v.get("summary") or "")[:60]}) return out def resolve_patch(rid, patch_text, corpus=True, own_files=()): certs = [] for s in parse_patch(patch_text): path = s["new"] or s["old"] is_corpus = bool(path) and "/" in path if corpus != is_corpus: continue if is_corpus: cands = version_texts(path) else: cands = [] for f in own_files: t, _ = get("host:/files/" + (f.get("sha256") or "none")) if t: cands.append({"name": f"file:{f.get('name')}", "sha": f.get("sha256"), "text": t}) applying, posts = [], {} for c in cands: res, _ = apply_hunks(c["text"], s["hunks"]) if res is None: continue p = sha(res) applying.append({"candidate": c["name"], "content_sha": c["sha"], "post_sha256": p, "candidate_sha256": sha(c["text"])}) posts.setdefault(p, []).append(c["name"]) proof = None if len(posts) == 1: p = list(posts)[0] matches = [c["name"] for c in cands if sha(c["text"]) == p] if matches: proof = {"kind": "post_equals_served_version", "post_sha256": p, "matches": matches} certs.append({"return_id": rid, "path": path, "is_corpus_path": is_corpus, "n_candidates": len(cands), "n_applying": len(applying), "applying": applying, "post_sha256": list(posts)[0] if len(posts) == 1 else None, "post_ambiguous": len(posts) > 1, "base_sha256": applying[0]["content_sha"] if applying else None, "base_class": sorted({a["content_sha"] for a in applying}), "proof": proof, "needs_publication": (not applying) or len(posts) > 1}) return certs def resolve_revision(rid, rec, patch_certs): path = rec.get("revision_path") if not path: return None vers = history_versions(path) post = [v for v in vers if str(v.get("return_id")) == str(rid)] or \ [v for v in vers if v.get("content_sha") == rec.get("revision_sha")] post_sha = (post[0].get("content_sha") if post else rec.get("revision_sha")) idxs = [i for i, v in enumerate(vers) if v.get("content_sha") == post_sha] base = None if idxs and idxs[0] > 0: base = vers[idxs[0] - 1] served_post, _ = get("host:/files/" + (post_sha or "none")) return {"return_id": rid, "path": path, "is_corpus_path": True, "kind": "revision", "base_sha256": (base or {}).get("content_sha"), "base_version": (base or {}).get("version"), "post_sha256": post_sha, "post_sha_served": served_post is not None, "post_version": (post[0] if post else {}).get("version"), "n_versions": len(vers), "proof": ({"kind": "store_revision", "post_sha256": post_sha, "served": served_post is not None} if post_sha else None), "needs_publication": bool(post_sha) and (base is None), "patch_certificates": patch_certs} def main(): lane = json.load(open(os.path.join(HERE, "lane-index.json"))) bearing = lane["bearing"] certs, summary, out_of_lane = [], [], [] for rid in bearing: rec = lane["index"][str(rid)] if rec.get("status") != "accepted": out_of_lane.append({"return_id": rid, "status": rec.get("status"), "type": rec.get("type"), "has_patch": rec.get("has_patch"), "revision_sha": rec.get("revision_sha")}) continue patch = "" pp = os.path.join(HERE, "patches", f"lane-{rid}.patch") if os.path.exists(pp): patch = open(pp).read() pc = resolve_patch(rid, patch, corpus=True) if patch.strip() else [] pc += resolve_patch(rid, patch, corpus=False, own_files=rec.get("files") or []) if patch.strip() else [] rev = resolve_revision(rid, rec, pc) entry = {"return_id": rid, "job_id": rec.get("job_id"), "type": rec.get("type"), "patch_status": rec.get("patch_status"), "has_patch": rec["has_patch"], "patch_certificates": pc, "revision_certificate": rev} certs.append(entry) kinds = [] for c in pc: kinds.append(("corpus" if c["is_corpus_path"] else "script") + (":proven" if c["proof"] else ":unproven" if c["post_sha256"] else ":UNRESOLVED")) if rev: kinds.append("revision" + (":proven" if rev["proof"] else ":UNRESOLVED")) summary.append((rid, rec.get("job_id"), ",".join(kinds) or "none")) print(f"#{rid:<5} job {str(rec.get('job_id')):<6} {','.join(kinds) or 'none'}", flush=True) for c in pc: print(f" {c['path']}: cands={c['n_candidates']} applying={c['n_applying']} " f"base={str(c['base_sha256'])[:16]} post={str(c['post_sha256'])[:16]} " f"proof={bool(c['proof'])}", flush=True) if rev: print(f" rev {rev['path']}: base={str(rev['base_sha256'])[:16]} " f"post={str(rev['post_sha256'])[:16]} served={rev['post_sha_served']}", flush=True) json.dump({"walked": lane["walked"], "bearing": bearing, "accepted_bearing": [e["return_id"] for e in certs], "out_of_lane_bearing": out_of_lane, "certificates": certs}, open(os.path.join(HERE, "base-certificates.json"), "w"), indent=1) rows = [c for e in certs for c in e["patch_certificates"]] + \ [e["revision_certificate"] for e in certs if e["revision_certificate"]] n_rows = len(rows) proven = [r for r in rows if r.get("proof")] unresolved = [r for r in rows if r.get("needs_publication")] corpus_rows = [r for r in rows if r.get("is_corpus_path")] script_rows = [r for r in rows if not r.get("is_corpus_path")] md = ["# Base certificates for the accepted lane (job 2866, route 139)", "", f"Walked {lane['walked']} served returns; {len(bearing)} carry a patch or a revision, of " f"which {len(certs)} are accepted (lane) and {len(out_of_lane)} are not accepted and are " f"out of lane scope; {n_rows} (return, target) rows certified.", "", f"- rows with a content-addressed base: **{n_rows - len(unresolved)}/{n_rows}**", f"- rows whose base identification is proven: **{len(proven)}**", f"- corpus-path rows: {len(corpus_rows)}; bare-script rows: {len(script_rows)}", f"- rows needing base bytes published: **{len(unresolved)}**", "", "| return | target | base_sha256 | post_sha256 | proof |", "|---|---|---|---|---|"] for r in rows: p = (r.get("proof") or {}) md.append(f"| #{r['return_id']} | `{r['path']}` | `{str(r.get('base_sha256'))[:16]}…` | " f"`{str(r.get('post_sha256'))[:16]}…` | {p.get('kind', '—')} |") md.append("") md.append("Generated by `certify_bases.py`; see `base-certificates.json` for the full records.") open(os.path.join(HERE, "base-certificates.md"), "w").write("\n".join(md) + "\n") print(f"\nrows={n_rows} resolved={n_rows-len(unresolved)} proven={len(proven)} " f"needing_publication={len(unresolved)} corpus={len(corpus_rows)} script={len(script_rows)}") for r in unresolved: print(" NEEDS PUBLICATION:", r["return_id"], r["path"]) print("wrote base-certificates.json + base-certificates.md") if __name__ == "__main__": main()