KB-3616 rev 2

FIX7 Recheck-9 Packet V2 — KB fresh-fetch reconstruction tool (R9-B4)

6 min read Revision 2

#!/usr/bin/env python3

============================================================================

FIX7 Recheck-9 Packet V2 — KB fresh-fetch reconstruction tool (R9-B4).

Rebuilds the ENTIRE runnable packet from the governed KB surface alone:

- every packet-root file is fetched from the KB packet root;

- the 10 active members are fetched from their CANONICAL blueprint

document ids (the governed authority surface — the packet does NOT keep

a duplicate KB copy of the corpus, by design: one authority, one nature).

Writes the fetched bytes verbatim, prints sha256 per file, then (if

HASH_MANIFEST.txt was fetched) verifies the reconstructed tree against it

bidirectionally and FAILS CLOSED on any gap or mismatch.

Usage:

MCP_URL=https://… MCP_KEY=… python3 kb_fetch_reconstruct.py <outdir>

(falls back to ~/.claude.json mcpServers["agent-data"] if env not set)

Then:

cd <outdir> && bash RERUN.sh

READ-ONLY: performs only get_document_for_rewrite calls (full content);

writes only inside <outdir>. No KB write, no production surface. The MCP

API key is NEVER embedded here — supply your own governed access.

============================================================================

import json, os, ssl, sys, hashlib, urllib.request

PACKET_ROOT = "knowledge/dev/laws/tool-kiem-thu/packets/fix7-codex-recheck-9-2026-06-10/" BLUEPRINT = "knowledge/dev/reports/architecture/t1-fix7-existing-system-refactor-execution-blueprint-2026-06-08/"

ROOT_FILES = ["README_FOR_CODEX.md","RERUN.sh","HASH_MANIFEST.txt","manifest.json", "manifest_tool.py","adversarial_suite.py","kb_fetch_reconstruct.py", "blackbox_negative_suite.py","failopen_regression.py", "evidence/canonicalizer-fix7-canon-v1-ssot.md","evidence/canonicalizer-fix7-canon-v1-ssot.py", "evidence/fix7_canon_v1_ssot_extended.py","evidence/materialize_canonicalizer.py", "evidence/selftest-expected-output.txt","evidence/produce-expected-output.txt", "logs/materialized-selftest.log","logs/extended-selftest.log","logs/produce.log", "logs/forbidden-scope.log","logs/manifest-verify.log","logs/adversarial-suite.log", "logs/blackbox-negative-suite.log","logs/failopen-regression.log"]

DOCS = ["00-readme-first.md","01-live-existing-system-inventory.md","02-design-to-live-mapping.md", "03-gap-classification.md","04-dependency-safe-construction-order.md","05-rollback-blueprint.md", "06-test-guard-blueprint.md","07-implementation-package-split.md","08-hard-blocks-do-not-touch-list.md", "12-final-verdict.md"]

def cfg(): url, key = os.environ.get("MCP_URL"), os.environ.get("MCP_KEY") if url and key: return url, key c = json.load(open(os.path.expanduser("~/.claude.json")))["mcpServers"]["agent-data"] return c["url"], c["headers"]["X-API-Key"]

def ctx(): try: return ssl.create_default_context(cafile="/etc/ssl/cert.pem") except Exception: return ssl.create_default_context()

def fetch(url, key, doc_id, rid): body = json.dumps({"jsonrpc":"2.0","id":rid,"method":"tools/call","params":{ "name":"get_document_for_rewrite","arguments":{"document_id":doc_id}}}).encode() req = urllib.request.Request(url, data=body, headers={"Content-Type":"application/json", "Accept":"application/json, text/event-stream","X-API-Key":key}) with urllib.request.urlopen(req, timeout=120, context=ctx()) as r: resp = json.loads(r.read().decode()) if "error" in resp: raise SystemExit(f"FETCH_FAILED {doc_id}: {resp['error']}") d = json.loads(resp["result"]["content"][0]["text"]) if "content" not in d: raise SystemExit(f"FETCH_FAILED {doc_id}: no content: {str(d)[:200]}") return d

def main(): if len(sys.argv) != 2: print("usage: kb_fetch_reconstruct.py <outdir>"); return 2 out = sys.argv[1] url, key = cfg() plan = [(PACKET_ROOT+f, f) for f in ROOT_FILES] + [(BLUEPRINT+d, "docs/"+d) for d in DOCS] rid = 0 for doc_id, rel in plan: rid += 1 d = fetch(url, key, doc_id, rid) p = os.path.join(out, rel) os.makedirs(os.path.dirname(p) or ".", exist_ok=True) data = d["content"].encode("utf-8") open(p, "wb").write(data) print(f"{hashlib.sha256(data).hexdigest()} {rel} (rev={d.get('revision')}, {len(data)} bytes)") hm = os.path.join(out, "HASH_MANIFEST.txt") bad = [] entries = {} for line in open(hm): line = line.strip() if not line or line.startswith("#"): continue h, _, rel = line.partition(" ") entries[rel] = h fetched = {rel for _, rel in plan if rel != "HASH_MANIFEST.txt"} for rel in sorted(fetched): h = hashlib.sha256(open(os.path.join(out, rel), "rb").read()).hexdigest() if rel not in entries: bad.append(f"fetched file not pinned by HASH_MANIFEST: {rel}") elif entries[rel] != h: bad.append(f"hash mismatch vs HASH_MANIFEST: {rel}") for rel in sorted(entries): if rel not in fetched: bad.append(f"HASH_MANIFEST entry not reconstructed: {rel}") if bad: print("RECONSTRUCTION: FAIL (KB tree != pinned packet tree)") for b in bad: print(" -", b) return 1 print(f"RECONSTRUCTION: OK ({len(fetched)} files fetched from KB; tree matches HASH_MANIFEST bidirectionally)") print(f"next: cd {out} && bash RERUN.sh") return 0

if name == "main": sys.exit(main())

Back to Knowledge Hub knowledge/dev/laws/tool-kiem-thu/packets/fix7-codex-recheck-9-2026-06-10/kb_fetch_reconstruct.py