"""Question: does245's index-only patch equal actual source regeneration? Compare an immutable public-only snapshot using the primary generator's own summarise function. No mathematics, source edits, network or private headers. """ import hashlib import json import pathlib import re import resource import subprocess import sys import tempfile import time def sha(text): return hashlib.sha256(text.encode()).hexdigest() def ledger(text): m = re.search(r'', '\n'.join(text.splitlines()[:60])) assert m fields = dict(re.findall(r'^([a-z]+):\s*(.*)$', m[1], re.MULTILINE)) fields = {k: v.strip() for k, v in fields.items()} todo = [] for item in fields.get('todo', 'none').split(','): item = item.strip() if item and item != 'none': todo.append({'id': re.sub(r'\s*\(retired\)\s*$', '', item), 'retired': bool(re.search(r'\(retired\)', item))}) fields['todo'] = todo return fields def rows(text, allow_malformed=False): # Generator cell() escapes bars. Decode only that escape, retaining # backslashes in mathematical text, and read the by-id section alone. section = text.split('## 2. Every question, by id', 1)[1].split('## 3.', 1)[0] out = {} for line in section.splitlines(): if not line.startswith('| `Q-'): continue cells = [c.strip().replace('\\|', '|') for c in re.split(r'(? \{[\s\S]*?\n \};', generator).group(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" records = [{'file': p, 'block': ledger(d['docs'][p])} for p in sorted(unique_paths)] p = subprocess.run(['node', '-e', source], input=json.dumps(records), text=True, capture_output=True, check=True) generated = json.loads(p.stdout) mismatches = [] for g in generated: assert norm(g['status']) == norm(current[g['id']]['status']) assert norm(g['verdict']) == norm(current[g['id']]['verdict']) if altered[g['id']]['verdict'] is None or norm(g['verdict']) != norm(altered[g['id']]['verdict']): mismatches.append(g['id']) expected_ids = sorted(['Q-rec-cheapest-0830', 'Q-recon-0904-sifting-limit-floor', 'Q-xchannel-closedform', 'Q-xchannel-offset']) assert sorted(mismatches) == expected_ids assert len(generated) == 15 malformed = {qid: row['malformed_cells'] for qid, row in altered.items() if 'malformed_cells' in row} assert malformed == {'Q-xchannel-offset': 8} # A cleanly applying patch and a source-regenerated index are different claims. # Validate every file header before applying the supplied patch to an isolated # work/ copy. Its only permitted target is research/QUESTIONS.md. patch = d['files']['questions-rows38-52.patch'] headers = re.findall(r'^(?:---|\+\+\+) ([^\t\n]+)', patch, re.MULTILINE) assert headers == ['a/research/QUESTIONS.md', 'b/research/QUESTIONS.md'] pathlib.Path('work').mkdir(exist_ok=True) with tempfile.TemporaryDirectory(prefix='regen-709-', dir='work') as task_tmp: task_dir = pathlib.Path(task_tmp).resolve() (task_dir/'research').mkdir() (task_dir/'research/QUESTIONS.md').write_text(registry) (task_dir/'change.patch').write_text(patch) p = subprocess.run(['patch', '--binary', '-p1', '-i', str(task_dir/'change.patch')], cwd=task_dir, capture_output=True, text=True, check=True) assert (task_dir/'research/QUESTIONS.md').read_text() == corrected result = {'schema': 'sah-regeneration-check-v1', 'target_return': 245, 'artifact_hashes_matched': len(d['artifact_hashes']), 'owning_notes_unchanged': len(unique_paths), 'rows_current': len(generated), 'primary_generator_fields_match_current': True, 'patch_applies_to_published_corrected_hash': True, 'primary_generator_disagrees_with_patch_ids': sorted(mismatches), 'patched_by_id_malformed_rows': malformed, 'scope': 'finite documentary comparison, not a mathematical rerun'} pathlib.Path(sys.argv[2]).write_text(json.dumps(result, indent=2)+'\n') children_after = resource.getrusage(resource.RUSAGE_CHILDREN) timing = {'wall_seconds': time.monotonic()-start, 'cpu_seconds': time.process_time()-cpu_start+children_after.ru_utime+ children_after.ru_stime-children_before.ru_utime-children_before.ru_stime} if len(sys.argv)>3: pathlib.Path(sys.argv[3]).write_text(json.dumps(timing, indent=2)+'\n') print(json.dumps(result))