"""Repair four stale source verdicts and verify their generated registry copies. Public snapshot inputs only. This checks document consistency, not the cited mathematical calculations. Existing pending audits retain their ownership. """ import difflib import hashlib import json from pathlib import Path import re import resource import subprocess import sys import tempfile import time def sha(text): return hashlib.sha256(text.encode()).hexdigest() def cells(line): return [c.strip() for c in re.split(r'(?', '\n'.join(text.splitlines()[:60])) assert block fields = dict(re.findall(r'^([a-z]+):\s*(.*)$', block[1], re.M)) fields = {k: v.strip() for k, v in fields.items()} fields['todo'] = [{'id': item.strip(), 'retired': False} for item in fields.get('todo', 'none').split(',') if item.strip() and item.strip() != 'none'] return fields def index_rows(text): section = text.split('## 2. Every question, by id', 1)[1].split('## 3.', 1)[0] rows = {} for line in section.splitlines(): if not line.startswith('| `Q-'): continue c = cells(line) assert len(c) == 6 rows[c[0].strip('`')] = {'status': c[1], 'verdict': c[3].replace('\\|', '|'), 'owners': ['research/'+p for p in re.findall(r'\]\(([^)]+)\)', c[5])]} return rows started = time.monotonic() cpu_start = time.process_time() children_start = resource.getrusage(resource.RUSAGE_CHILDREN) bundle = json.loads(Path(sys.argv[1]).read_text()) dest = Path(sys.argv[2]) dest.mkdir(parents=True, exist_ok=True) docs = bundle['docs'] assert all(sha(text) == bundle['sha256'][path] for path, text in docs.items()) selected = bundle['selected_ids'] assert len(selected) == 15 registry = docs['research/QUESTIONS.md'] before = index_rows(registry) owners = sorted({p for identifier in selected for p in before[identifier]['owners']}) assert len(owners) == 16 assert all(ledger(docs[p])['id'] in selected for p in owners) # Execute the actual primary summarise expression on the same path ordering. # Its corpus scanner is intentionally excluded: this is a 15-row comparison. generator = docs['research/qc/questions.js'] expression = re.search(r'const summarise = id => \{[\s\S]*?\n \};', generator)[0] source = "const path=require('node:path');const fs=require('node:fs');\n" source += "const records=JSON.parse(fs.readFileSync(0,'utf8'));const byId=new Map();\n" source += "for(const r of records){if(!byId.has(r.block.id))byId.set(r.block.id,[]);byId.get(r.block.id).push(r);}\n" source += expression + "\nprocess.stdout.write(JSON.stringify([...byId.keys()].sort().map(summarise)));\n" def generated(snapshot): records = [{'file': p, 'block': ledger(snapshot[p])} for p in owners] proc = subprocess.run(['node', '-e', source], input=json.dumps(records), text=True, capture_output=True, check=True) return {row['id']: {'status': row['status'], 'verdict': row['verdict']} for row in json.loads(proc.stdout)} def mismatches(actual, expected): return sorted(identifier for identifier in selected if any(actual[identifier][key] != expected[identifier][key] for key in ['status', 'verdict'])) assert mismatches(generated(docs), before) == ['Q-derive-0904-L7-transfer'] targets = { 'Q-rec-cheapest-0830': 'research/history/staging/attack-0830-rec-cheapest.md', 'Q-recon-0904-sifting-limit-floor': 'research/history/staging/recon-0904-sifting-limit-floor.md', 'Q-xchannel-closedform': 'research/history/staging/xchan-at29.md', 'Q-xchannel-offset': 'research/history/staging/item-x-offset.md', } verdicts = {} old = ledger(docs[targets['Q-rec-cheapest-0830']])['verdict'] assert 'so REC(s, u0) is false' in old and '251 against z^{u0} = 1.05e6' in old verdicts['Q-rec-cheapest-0830'] = old.replace( 'so REC(s, u0) is false', 'with hypothesis s <= 3 and conditional on that DERIVED growth, REC(s, u0) is false').replace( '251 against z^{u0} = 1.05e6', '251 against z^{u0} = 7.188e7 (1.05e6 is HM(u0), not z^{u0}; redteam-0830-floor-sign.md)').replace( '; no exponent moved.', '; the September 4 rider reports the exact construction onset z = 1.875e6 at s = 2.698721, not the early analytic 1.055e6; no exponent moved.') verdicts['Q-recon-0904-sifting-limit-floor'] = ( 'PARTIAL on the barrier question. The September 4 rider from redteam-0904-sifting-limit.md ' 'refutes this note\'s METHOD ARTEFACT at rung MEASURED headline as stated: the LP fixes one ' 'legal profile rather than the axiom-only class, a legal x = 13 profile scores 5.0113 above beta2, ' 'the one-point calibration misses the second proven anchor, and the pooled statistic is not ' 'the definitional sifting limit. The 3.3152 reading is 22.3 percent below 4.26645, not 18. ' 'The rider replaces 1.8394 with the proved-facts lower bound 1.819592 and confirms beta(2) >= 2 ' 'from the one-sided condition and beta(1) >= 2. No barrier theorem or axiom-only argument ' 'inside (2, 4.26645] is exhibited; the LP number remains a finite-level measurement for one ' 'profile. These are the rider\'s conclusions, not new source verification here.') old = ledger(docs[targets['Q-xchannel-closedform']])['verdict'] verdicts['Q-xchannel-closedform'] = old.replace( '4.93 sigma low at @31 where sigma_J falls to 0.000024', '4.93 sigma low at @31 under the inherited sigma_J = 0.000024 (section 7), while ' 'item-x-offset.md section 4\'s calibrated slot-clustered sigma scores the same law at ' 'z = -0.43 at @29 and -2.32 at @31, inside the preregistered HIT band; the @31 ' 'detection verdict is error-model dependent, as accepted audit #85\'s also_fix records') assert verdicts['Q-xchannel-closedform'] != old old = ledger(docs[targets['Q-xchannel-offset']])['verdict'] assert 'the deciding blind test at @37 is pre-registered and committed alone.' in old verdicts['Q-xchannel-offset'] = old.replace( 'the deciding blind test at @37 is pre-registered and committed alone.', 'the blind test at @37 was sealed alone and is now scored in xchan-at37-score.md: ' 'MEASURED 1 - J = 0.020823, all seven registered candidates killed at |z| = 104 to 122, ' 'survivor set EMPTY. The finite-level-correction family is closed as this offset\'s ' 'description; the larger structural question stays open. The sealed and historical body ' 'below is retained.') revised = dict(docs) for identifier, path in targets.items(): original = docs[path] old = ledger(original)['verdict'] revised[path] = original.replace('verdict: '+old+'\n', 'verdict: '+verdicts[identifier]+'\n') assert original.split('-->', 1)[1] == revised[path].split('-->', 1)[1] assert sum(a != b for a, b in zip(original.splitlines(), revised[path].splitlines())) == 1 assert ledger(original)['status'] == ledger(revised[path])['status'] == 'PARTIAL' counts = {identifier: 0 for identifier in targets} updated = [] for line in registry.splitlines(keepends=True): m = re.search(r'`(Q-[^`]+)`', line) if line.startswith('|') and m and m[1] in targets: c = cells(line) assert len(c) in [5, 6] c[3] = verdicts[m[1]].replace('|', '\\|') line = '| '+' | '.join(c)+' |'+ ('\n' if line.endswith('\n') else '') counts[m[1]] += 1 updated.append(line) assert set(counts.values()) == {2} revised['research/QUESTIONS.md'] = ''.join(updated) after = index_rows(revised['research/QUESTIONS.md']) assert all(before[x]['status'] == after[x]['status'] for x in before) assert len(before) == len(after) assert sum(a != b for a, b in zip(registry.splitlines(), revised['research/QUESTIONS.md'].splitlines())) == 8 assert mismatches(generated(revised), after) == ['Q-derive-0904-L7-transfer'] # Negative gate: reverting the four source changes restores precisely the # four old verdicts. An index-only correction therefore cannot pass this gate. assert mismatches(generated(docs), after) == sorted(list(targets)+['Q-derive-0904-L7-transfer']) files = {} patch = '' for path in list(targets.values())+['research/QUESTIONS.md']: filename = 'registry-712-'+Path(path).name (dest/filename).write_text(revised[path]) files[path] = {'filename': filename, 'base_sha256': sha(docs[path]), 'revised_sha256': sha(revised[path])} patch += ''.join(difflib.unified_diff(docs[path].splitlines(True), revised[path].splitlines(True), fromfile='a/'+path, tofile='b/'+path, n=1)) (dest/'registry-712.patch').write_text(patch) with tempfile.TemporaryDirectory(prefix='registry-712-', dir='work') as temp: directory = Path(temp).resolve() for path in files: destination = directory/path destination.parent.mkdir(parents=True, exist_ok=True) destination.write_text(docs[path]) (directory/'change.patch').write_text(patch) subprocess.run(['patch', '--binary', '-p1', '-i', str(directory/'change.patch')], cwd=directory, check=True, capture_output=True) assert all(sha((directory/path).read_text()) == spec['revised_sha256'] for path, spec in files.items()) result = {'job_id': 712, 'window': [37, 51], 'ids_checked': 15, 'owners_checked': 16, 'input_hashes_matched': len(docs), 'by_id_rows_well_formed': len(after), 'source_verdict_lines_changed': 4, 'index_lines_changed': 8, 'statuses_changed': 0, 'body_preserved': True, 'source_regeneration_verified': True, 'unchanged_existing_pending_index_audit': {'id': 232, 'question': 'Q-derive-0904-L7-transfer'}, 'negative_index_only_gate': True, 'patch_applied_hashes_matched': 5, 'changed_ids': sorted(targets), 'files': files, 'scope': 'Documentary rider and index consistency, not independent mathematics.'} (dest/'registry-712-verification.json').write_text(json.dumps(result, indent=2, sort_keys=True)+'\n') children_end = resource.getrusage(resource.RUSAGE_CHILDREN) timing = {'wall_seconds': time.monotonic()-started, 'cpu_seconds': time.process_time()-cpu_start + children_end.ru_utime + children_end.ru_stime - children_start.ru_utime - children_start.ru_stime} if len(sys.argv) > 3: Path(sys.argv[3]).write_text(json.dumps(timing, indent=2)+'\n') print(json.dumps(result, sort_keys=True))