#!/usr/bin/env python3 """Anchor probe for the rescue of route 139. Question: is the pre-image of a served accepted patch recoverable from SERVED BYTES ALONE by content, even though no blob identity is recorded? A unified hunk body carries its own pre-image slice (` `/`-` lines in order), so the test is whether that slice occurs in a served version of the target path. Read-only on the server. Writes anchor_probe.json + stdout. """ import json, os, sys, hashlib, re 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")) import sah 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", "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} CACHE = os.path.join(HERE, "served-cache") os.makedirs(CACHE, exist_ok=True) def get(url): """GET a served object with an on-disk cache keyed by the URL. A URL starting with "host:" is read at the server root (where /files/ lives); anything else is read under the project base, as in the route's other probes. """ key = hashlib.sha256(url.encode()).hexdigest()[:24] cp = os.path.join(CACHE, key + ".txt") if os.path.exists(cp): return open(cp).read(), "cache" full = (sah.SERVER + url[5:]) if url.startswith("host:") else (sah.PROJECT + url) xrid, status, txt = sah.request(LAUNCH, "GET", full, headers=H) if status != 200: return None, f"status {status}" open(cp, "w").write(txt) return txt, "served" def clean_path(p): p = p.split("\t")[0].strip() if p.startswith("a/") or p.startswith("b/"): p = p[2:] return p def parse_patch(text): """-> list of {old,new,hunks:[{header, pre_slice, post_slice, removed, ctx}]}""" sections, cur, hunk = [], None, None for line in text.splitlines(): if line.startswith("--- "): cur = {"old": clean_path(line[4:]), "new": None, "hunks": []} sections.append(cur) hunk = None elif line.startswith("+++ ") and cur is not None: cur["new"] = clean_path(line[4:]) elif line.startswith("@@") and cur is not None: hunk = {"header": line, "pre": [], "post": []} cur["hunks"].append(hunk) elif hunk is not None: if line.startswith("\\"): continue if line.startswith("-"): hunk["pre"].append(line[1:]) elif line.startswith("+"): hunk["post"].append(line[1:]) elif line.startswith(" ") or line == "": body = line[1:] if line.startswith(" ") else "" hunk["pre"].append(body) hunk["post"].append(body) for s in sections: for h in s["hunks"]: h["pre_slice"] = "\n".join(h["pre"]) + "\n" if h["pre"] else "" h["post_slice"] = "\n".join(h["post"]) + "\n" if h["post"] else "" return sections def occ_offsets(text, needle, cap=64): """ALL occurrence offsets, overlapping included. str.count() counts NON-overlapping matches, so a slice that occurs twice in a run of repeated context lines can report 1; using it for uniqueness or for a first-match replacement silently mis-applies. Caught by control C1 (2026-09-23); all uniqueness and offset decisions go through this function. """ offs, i = [], text.find(needle) while i >= 0 and len(offs) < cap: offs.append(i) i = text.find(needle, i + 1) return offs def locate(text, needle, min_len=120): """Occurrences of needle (overlapping), plus a long-anchor fallback for diagnosis.""" if not needle: return {"occ": 0, "offsets": [], "long_anchor": None, "long_occ": 0} offs = occ_offsets(text, needle) occ = len(offs) res = {"occ": occ, "offsets": offs[:5], "long_anchor": None, "long_occ": 0} if occ == 0: # longest prefix of the slice (line-wise) still occurring in the text lines = needle.splitlines() lo, hi, best = 0, len(lines), None while lo < hi: mid = (lo + hi + 1) // 2 cand = "\n".join(lines[:mid]) + "\n" if len(cand) >= min_len and cand in text: best, lo = cand, mid else: hi = mid - 1 if best: res["long_anchor"] = best res["long_occ"] = text.count(best) return res def probe_row(rid, patch_text, served_cache): rep = {"return_id": rid, "patch_sha256": hashlib.sha256(patch_text.encode()).hexdigest(), "sections": [], "verdict": None} sections = parse_patch(patch_text) for s in sections: path = s["new"] or s["old"] entry = {"path": path, "n_hunks": len(s["hunks"]), "candidates": [], "hunks": []} if not path or "/" not in path: entry["note"] = "not a corpus path (bare script / rename target)" else: docs, how = get("/docs/" + path) if docs is None: entry["note"] = f"/docs/{path}: {how}" else: h, _ = get("/history/" + path) versions = [] if h: try: versions = json.loads(h).get("versions") or [] except Exception: versions = [] texts = [("docs", hashlib.sha256(docs.encode()).hexdigest(), docs)] for v in versions: if v.get("content_sha"): t, _ = get("host:/files/" + v["content_sha"]) if t: texts.append((f"v{v.get('version')}", v["content_sha"], t)) entry["n_versions"] = len(texts) for hk in s["hunks"]: row = {"header": hk["header"], "pre_len": len(hk["pre_slice"]), "recovered_from_patch_text": bool(hk["pre_slice"]) or not hk["pre"], "found_in": []} for label, sha, t in texts: loc = locate(t, hk["pre_slice"]) if loc["occ"]: row["found_in"].append({"where": label, "content_sha": sha, "occ": loc["occ"], "unique": loc["occ"] == 1, "offsets": loc["offsets"][:5]}) if not row["found_in"]: # diagnosis: how far does the slice survive in the newest text? best = None for label, sha, t in texts: loc = locate(t, hk["pre_slice"]) if loc["long_anchor"] and (best is None or len(loc["long_anchor"]) > len(best[1])): best = (label, loc["long_anchor"], loc["long_occ"]) if best: row["longest_anchor"] = {"where": best[0], "chars": len(best[1]), "occ": best[2]} entry["hunks"].append(row) entry["candidates"] = [{"where": l, "content_sha": s2} for l, s2, _ in texts] if docs is not None else [] corpus_hunks = [r for r in entry["hunks"]] if corpus_hunks: all_present = all(r["found_in"] for r in corpus_hunks) all_unique = all(any(f["unique"] for f in r["found_in"]) for r in corpus_hunks) entry["row_class"] = ("anchored_unique" if all_unique else "anchored_present" if all_present else "partial" if any(r["found_in"] for r in corpus_hunks) else "absent") rep["sections"].append(entry) classes = [e.get("row_class") for e in rep["sections"] if e.get("row_class")] rep["verdict"] = (classes[0] if len(set(classes)) == 1 and classes else ("mixed:" + ",".join(classes) if classes else "no-corpus-path")) return rep def main(): sample = json.load(open(os.path.join(HERE, "patch_sample.json"))) order = [13, 20, 80, 101, 151, 152, 97, 1328, 12, 454, 85] queue = {12, 97, 1328, 454} results = [] for rid in order: p = os.path.join(HERE, "patches", f"return-{rid}.patch") if not os.path.exists(p): continue txt = open(p).read() if not txt.strip(): continue rep = probe_row(str(rid), txt, None) rep["queue_status"] = rid in queue results.append(rep) print(f"#{rid:<5} queue={rid in queue!s:<5} {rep['verdict']:<20} " f"sections={len(rep['sections'])}") for e in rep["sections"]: if e.get("row_class"): print(f" {e['path']}: {e['row_class']} hunks={e['n_hunks']} " f"versions={e.get('n_versions')}") out = {"order": order, "results": results, "queue_rows": [r["return_id"] for r in results if r["queue_status"]], "verdicts": {r["return_id"]: r["verdict"] for r in results}} json.dump(out, open(os.path.join(HERE, "anchor_probe.json"), "w"), indent=1) print("\nverdicts:", json.dumps(out["verdicts"])) anchored = [r["return_id"] for r in results if r["verdict"].startswith("anchored")] print(f"anchored rows: {len(anchored)}/{len(results)} -> {anchored}") print(f"queue anchored: {[r['return_id'] for r in results if r['queue_status'] and r['verdict'].startswith('anchored')]}") if __name__ == "__main__": main()