#!/usr/bin/env python3 """Publish the 17 missing bases by REVERSE-applying each patch to its served post file (job 2872). Reconstruction from the patch alone fails: every one of the 17 patches has gaps in its pre-image coverage (measured). But outside its hunks a patch changes nothing, so the base is determined by the POST image: reverse-apply each hunk (replace its post-image slice by its pre-image slice) in a served upload, then check line-number alignment -- hunk i's pre-slice must sit at line `a_i` of the rebuilt base and its post-slice at line `c_i` of the served post. Alignment for every hunk is the proof. Publishes each verified base as `base-` and records the hashes; failures are reported, not published. """ import json, os, re, 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" st = sah.state_dir(); run_dir = os.path.join(st, "runs", LAUNCH) launch = json.load(open(os.path.join(run_dir, "launch.json"))) binding = json.load(open(os.path.join(st, "device-binding.json"))); iden = sah.identity() assert str(launch["job_id"]) == "2872", f"launch holds {launch['job_id']}, expected 2872" H = {"Authorization": "Bearer " + sah.cred(), "Accept": "application/json", "Content-Type": "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() line_of = lambda text, off: text.count("\n", 0, off) + 1 lane = json.load(open(os.path.join(HERE, "lane-index.json"))) slices = json.load(open(os.path.join(HERE, "slice-certificates.json"))) TARGETS = [r for r in slices["certificates"] if not r["whole_file_base_served"]] def slices_of(h): pre = "\n".join(h["pre"]) + ("\n" if h["pre"] else "") post = "\n".join(h["post"]) + ("\n" if h["post"] else "") return pre, post def reverse_apply(post_text, hunks): """Replace each hunk's post-slice by its pre-slice, uniquely. Returns (base, detail) or (None, d).""" cur, detail = post_text, [] for h in hunks: pre, post = slices_of(h) m = re.match(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", h["header"]) a, c = int(m.group(1)), int(m.group(3)) offs = occ_offsets(cur, post) if post else [] if len(offs) != 1: detail.append({"header": h["header"], "post_occ": len(offs)}) return None, detail o = offs[0] detail.append({"header": h["header"], "post_occ": 1, "post_line_at": line_of(cur, o), "c": c}) cur = cur[:o] + pre + cur[o + len(post):] return cur, detail def forward_check(base_text, hunks): cur = base_text for h in hunks: pre, post = slices_of(h) offs = occ_offsets(cur, pre) if pre else [0] if len(offs) != 1: return None o = offs[0] cur = cur[:o] + post + cur[o + len(pre):] return cur def main(): out = {"published": [], "not_published": []} for r in TARGETS: rid, path = str(r["return_id"]), r["path"] hunks = [h for s in parse_patch(open(os.path.join(HERE, "patches", f"lane-{rid}.patch")).read()) if (s["new"] or s["old"]) == path for h in s["hunks"]] ranges = [re.match(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", h["header"]) for h in hunks] rec = {"return_id": int(rid), "path": path, "n_hunks": len(hunks), "candidates": []} best = None for f in (lane["index"][rid].get("files") or []): t, _ = get("host:/files/" + (f.get("sha256") or "none")) if not t: continue base, detail = reverse_apply(t, hunks) if base is None: rec["candidates"].append({"upload": f.get("name"), "reverse": "failed"}) continue aligned = sum(1 for h, (_, _, d) in zip(hunks, [(x, y, dd) for x, y, dd in zip([0], [0], detail)]) for _ in [0]) # placeholder replaced below aligned = 0 for h, d in zip(hunks, detail): pre, _ = slices_of(h) offs = occ_offsets(base, pre) if pre else [0] a = int(re.match(r"@@ -(\d+)(?:,(\d+))?", h["header"]).group(1)) if len(offs) == 1 and line_of(base, offs[0]) == a: aligned += 1 fwd = forward_check(base, hunks) rec["candidates"].append({"upload": f.get("name"), "reverse": "ok", "aligned_hunks": aligned, "n_hunks": len(hunks), "forward_roundtrip": fwd == t}) if aligned == len(hunks) and fwd == t: best = (f, base) break if best: f, base = best name = re.sub(r"[^A-Za-z0-9._-]", "_", f"base-{path.split('/')[-1]}") xrid, status, txt = sah.request(LAUNCH, "POST", sah.SERVER + "/files", headers=H, body={"name": name, "content": base, "job_id": 2872}) b = json.loads(txt) rec.update({"published_name": name, "upload_status": status, "base_sha256": b.get("sha256") or sha(base), "base_bytes": len(base), "post_sha256": sha([t for n, t in [(f.get('name'), get('host:/files/' + (f.get('sha256') or 'none'))[0])]][0][1]), "proven_by": f"reverse-applied to served upload {f.get('name')} with all " f"{len(hunks)} hunks line-aligned and forward round-trip exact"}) out["published"].append(rec) print(f"PUBLISHED #{rid} {path}: base {rec['base_sha256'][:16]} ({len(base)}B) " f"from upload {f.get('name')} hunks={len(hunks)} aligned={len(hunks)}") else: rec["reason"] = "no served upload reverse-applies with full line alignment" out["not_published"].append(rec) print(f"NOT PUBLISHED #{rid} {path}: {rec['reason']} " f"(candidates tried: {len(rec['candidates'])})") json.dump(out, open(os.path.join(HERE, "published-bases.json"), "w"), indent=1) print(f"\npublished={len(out['published'])} not_published={len(out['not_published'])}") if __name__ == "__main__": main()