File size: 36,440 Bytes
cc4d2ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
#!/usr/bin/env python3
"""Independently validate proof-review transport/provenance, not mathematical truth."""
from __future__ import annotations
import argparse
from collections import Counter
import gzip
import hashlib
import json
from pathlib import Path
import re
import subprocess

COMMIT = '4eaee87548250b2682affda7d05d947c05554bae'
MODEL = 'deepseek-v4.1-flash'
PROVIDER = 'damn-grok'
REVIEW_KEYS = {'family_id', 'paper_id', 'main_claim', 'assumptions', 'proof_steps', 'adversarial_checks', 'findings', 'assessment', 'review_limitations', 'formal_verification'}
FINDING_KEYS = {'id', 'severity', 'kind', 'claim', 'source_quote', 'location', 'explanation', 'reproduction', 'confidence'}

def ensure(condition, message):
    if not condition:
        raise ValueError(message)

def canonical(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))

def digest(value):
    return hashlib.sha256(value).hexdigest()

def sha(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b''):
            h.update(chunk)
    return h.hexdigest()

def read_json(path):
    if str(path).endswith('.gz'):
        with gzip.open(path, 'rt', encoding='utf-8') as f:
            return json.load(f)
    return json.loads(Path(path).read_text(encoding='utf-8'))

def read_rows(path):
    opener = gzip.open if str(path).endswith('.gz') else open
    with opener(path, 'rt', encoding='utf-8') as f:
        return [json.loads(line) for line in f if line.strip()]

def safe_path(root, relative):
    ensure(not Path(relative).is_absolute(), 'Absolute source/evidence path')
    p = (root / relative).resolve()
    ensure(p.is_relative_to(root.resolve()), 'Path escapes its declared root')
    return p

def text(value, name):
    ensure(isinstance(value, str) and value.strip(), name + ' must be nonempty text')

def source_lines(paper):
    rows = paper.get('source_lines')
    ensure(isinstance(rows, list) and rows, 'Missing labeled source lines')
    line_map = {}
    previous = 0
    for row in rows:
        match = re.fullmatch(r'L([0-9]+)', str(row.get('line_id', '')))
        ensure(match is not None and isinstance(row.get('text'), str), 'Invalid source line')
        n = int(match[1])
        ensure(n > previous, 'Source lines out of order or duplicated')
        line_map[n] = row['text']
        previous = n
    return line_map

def parse_location(location, line_map):
    ensure(isinstance(location, str), 'Source location must be text')
    m = re.fullmatch(r'L([0-9]+)(?: *- *L?([0-9]+))?', location.strip())
    ensure(m is not None, 'Invalid source location')
    lo, hi = int(m[1]), int(m[2] or m[1])
    ensure(0 <= hi-lo < 20 and all(i in line_map for i in range(lo, hi+1)), 'Absent or overlong source location')
    return lo, hi

def quote_at(quote, location, line_map):
    text(quote, 'Source quote')
    lo, hi = parse_location(location, line_map)
    source = '\n'.join(line_map[i] for i in range(lo, hi+1))
    ensure(' '.join(quote.split()) in ' '.join(source.split()), 'Quote differs from source at ' + location)

def validate_review(review, paper):
    ensure(isinstance(review, dict) and set(review) == REVIEW_KEYS, 'Review schema differs')
    ensure(review['family_id'] == paper['family_id'] and review['paper_id'] == paper['paper_id'], 'Review identity mismatch')
    ensure(review['formal_verification'] is False, 'Model review claims formal verification')
    line_map = source_lines(paper)
    main = review['main_claim']
    ensure(isinstance(main, dict) and set(main) == {'quote', 'location'}, 'Main claim schema')
    quote_at(main['quote'], main['location'], line_map)
    for key in ('assumptions', 'review_limitations'):
        ensure(isinstance(review[key], list) and review[key], key + ' absent')
        for item in review[key]:
            text(item, key)
    steps = review['proof_steps']
    ensure(isinstance(steps, list) and len(steps) <= 8, 'Proof step list invalid')
    ensure(len(steps) >= 3 or review['assessment'] == 'insufficient_review', 'Too few proof steps without insufficient_review')
    for i, step in enumerate(steps, 1):
        ensure(isinstance(step, dict) and set(step) == {'claim', 'location', 'depends_on', 'check_result'}, 'Step schema')
        text(step['claim'], 'Step claim'); text(step['check_result'], 'Step check_result')
        parse_location(step['location'], line_map)
        ensure(isinstance(step['depends_on'], list), 'Step dependencies invalid')
        for dep in step['depends_on']:
            text(dep, 'Step dependency')
            m = re.fullmatch(r'step_([0-9]+)', dep)
            ensure(m is None or 1 <= int(m[1]) < i, 'Invalid step dependency ordering')
    checks = review['adversarial_checks']
    ensure(isinstance(checks, list) and len(checks) >= 3, 'Fewer than three adversarial checks')
    check_names = set()
    for item in checks:
        ensure(isinstance(item, dict) and set(item) == {'check', 'derivation', 'result', 'locations'}, 'Adversarial schema')
        for key in ('check', 'derivation', 'result'):
            text(item[key], 'Adversarial ' + key)
        check_names.add(' '.join(item['check'].split()).casefold())
        ensure(isinstance(item['locations'], list) and item['locations'], 'Adversarial locations absent')
        for location in item['locations']:
            parse_location(location, line_map)
    ensure(len(check_names) >= 3, 'Adversarial checks not distinct')
    findings = review['findings']
    ensure(isinstance(findings, list), 'Findings not an array')
    seen = set()
    for item in findings:
        ensure(isinstance(item, dict) and set(item) == FINDING_KEYS, 'Finding schema differs')
        for key in ('id', 'claim', 'source_quote', 'location', 'explanation', 'reproduction'):
            text(item[key], 'Finding ' + key)
        ensure(item['id'] not in seen, 'Duplicate finding ID'); seen.add(item['id'])
        ensure(item['severity'] in {'critical', 'major', 'minor'}, 'Finding severity')
        ensure(item['kind'] in {'potential_gap', 'candidate_counterexample', 'missing_hypothesis', 'circularity', 'algebraic_error', 'other'}, 'Finding kind')
        ensure(item['confidence'] in {'low', 'medium', 'high'}, 'Finding confidence')
        quote_at(item['source_quote'], item['location'], line_map)
    ensure(review['assessment'] in {'potential_issue_found', 'no_concrete_issue_found', 'insufficient_review'}, 'Invalid review assessment')
    ensure(bool(findings) == (review['assessment'] == 'potential_issue_found'), 'Finding/assessment inconsistency')

def parse_final_events(raw):
    final = None
    fallback = None
    for line in raw.decode('utf-8', errors='replace').splitlines():
        try:
            event = json.loads(line)
        except json.JSONDecodeError:
            continue
        if event.get('type') in {'message_end', 'turn_end'} and event.get('message', {}).get('role') == 'assistant':
            final = event['message']
        if event.get('type') == 'agent_end':
            candidates = [m for m in event.get('messages', []) if m.get('role') == 'assistant']
            if candidates:
                fallback = candidates[-1]
    final = final or fallback
    ensure(final is not None, 'No final assistant response')
    ensure(final.get('model') == MODEL and final.get('provider') == PROVIDER, 'OMP log model/provider mismatch')
    ensure(final.get('stopReason') in {'stop', 'end_turn'}, 'OMP response abnormal stop')
    blocks = final.get('content', [])
    response_text = blocks if isinstance(blocks, str) else ''.join(x.get('text', '') for x in blocks if x.get('type') == 'text')
    response_text = response_text.strip()
    if response_text.startswith('```') and response_text.endswith('```'):
        response_text = re.sub(r'^```(?:json)?\s*', '', response_text)
        response_text = re.sub(r'\s*```$', '', response_text)
    return json.loads(response_text), final

def validate_rebuttals(root, inputs, first_reviews):
    folder = root / 'rebuttals'
    if not folder.exists():
        return None
    index = read_json(folder / 'evidence-index.json')['files']
    evidence = {r['original_path']: r for r in index}
    ensure(len(evidence) == len(index), 'Duplicate rebuttal evidence path')
    def raw(rel):
        ensure(rel in evidence, 'Rebuttal evidence missing: ' + rel)
        item = evidence[rel]
        with gzip.open(safe_path(root, item['path']), 'rb') as f:
            data = f.read()
        ensure(len(data) == item['original_bytes'] and digest(data) == item['original_sha256'], 'Rebuttal original evidence digest mismatch')
        return data
    for rel in evidence:
        raw(rel)
    status, run = json.loads(raw('status.json')), json.loads(raw('run.json'))
    policy = raw('rebuttal-policy.md')
    ensure(status['status'] == 'complete' and status['failed_families'] == 0 and status['formal_verifications'] == 0, 'Rebuttal run incomplete/formal state mismatch')
    ensure(run['formal_verification'] is False and run['model'] == MODEL and run['provider'] == PROVIDER, 'Rebuttal run scope/identity')
    ensure(status['thinking'] == run['thinking'], 'Rebuttal status thinking differs')
    ensure(run['policy_sha256'] == digest(policy), 'Rebuttal policy digest differs')
    wrappers = read_rows(folder / 'reviews.jsonl.gz')
    raw_wrappers = [json.loads(line) for line in raw('reviews.jsonl').decode().splitlines() if line.strip()]
    ensure(wrappers == raw_wrappers, 'Rebuttal aggregate differs from original')
    ensure(len(wrappers) == status['completed_families'] == run['families'] and {r['family_id'] for r in wrappers} == set(run['family_ids']), 'Rebuttal selected-family coverage differs')
    first_by_id = {r['family_id']: r for r in first_reviews}
    dispositions = Counter()
    payloads = {}
    for wrapper in wrappers:
        fid = wrapper['family_id']; paper = inputs[fid]; first = first_by_id[fid]
        payload_data = raw(f'families/family-{fid}/input.json')
        payload = json.loads(payload_data); payloads[fid] = payload
        ensure(payload['primary_manuscript'] == paper and payload['first_review_wrapper'] == first and payload['first_review'] == first['review'], 'Rebuttal source/first review snapshot differs')
        ensure(digest(payload_data) == wrapper['stored_input_sha256'] and digest(canonical(payload).encode()) == wrapper['source_input_sha256'], 'Rebuttal input digest differs')
        ensure(wrapper['primary_manuscript_sha256'] == digest(canonical(paper).encode()) and wrapper['first_review_sha256'] == digest(canonical(first['review']).encode()), 'Rebuttal first-review/source hash differs')
        ensure(payload['first_review_provenance']['first_review_wrapper_sha256'] == digest(canonical(first).encode()), 'Rebuttal original wrapper hash differs')
        ensure(wrapper['first_review_provenance'] == payload['first_review_provenance'], 'Rebuttal provenance differs')
        ensure(wrapper['model'] == MODEL and wrapper['provider'] == PROVIDER and wrapper['runner'] == 'oh-my-pi', 'Rebuttal worker identity differs')
        ensure(wrapper['formal_verification'] is False and wrapper['run_id'] == run['run_id'] and wrapper['source_commit'] == COMMIT, 'Rebuttal run/state differs')
        ensure(wrapper['thinking'] == run['thinking'], 'Rebuttal wrapper thinking differs')
        prompt = raw(wrapper['prompt_path']); events = raw(wrapper['log_path'])
        ensure(digest(prompt) == wrapper['prompt_sha256'] and prompt.startswith(policy), 'Rebuttal prompt differs')
        ensure(prompt.endswith((json.dumps(payload, ensure_ascii=False, separators=(',', ':'))+'\n').encode()), 'Rebuttal prompt does not end in exact source payload')
        ensure(wrapper['policy_sha256'] == digest(policy) and digest(events) == wrapper['log_sha256'], 'Rebuttal policy/event digest differs')
        review, message = parse_final_events(events)
        ensure(review == wrapper['review'] and message.get('responseId') == wrapper.get('inference_response_id'), 'Rebuttal final worker response differs')
        ensure(set(review) == {'family_id','paper_id','findings','summary','review_limitations','formal_verification'}, 'Rebuttal schema differs')
        ensure(review['formal_verification'] is False and review['family_id'] == fid and review['paper_id'] == paper['paper_id'], 'Rebuttal review identity/state differs')
        text(review['summary'], 'Rebuttal summary')
        ensure(isinstance(review['review_limitations'], list) and review['review_limitations'], 'Rebuttal limitations absent')
        for limit in review['review_limitations']:
            text(limit, 'Rebuttal limit')
        ensure([f['finding_id'] for f in review['findings']] == [f['id'] for f in first['review']['findings']], 'Rebuttal does not address each exact first finding')
        lines = source_lines(paper)
        for item in review['findings']:
            ensure(set(item) == {'finding_id','disposition','author_defense','reasoning','source_evidence','minimal_test'}, 'Rebuttal finding schema differs')
            ensure(item['disposition'] in {'concern_survives','concern_refuted','unresolved'}, 'Rebuttal disposition invalid')
            dispositions[item['disposition']] += 1
            for key in ('author_defense', 'reasoning', 'minimal_test'):
                text(item[key], 'Rebuttal ' + key)
            ensure(isinstance(item['source_evidence'], list) and item['source_evidence'], 'Rebuttal quoted evidence absent')
            for item_evidence in item['source_evidence']:
                ensure(set(item_evidence) == {'quote','location'}, 'Rebuttal evidence schema differs')
                quote_at(item_evidence['quote'], item_evidence['location'], lines)
        ensure(json.loads(raw(f'families/family-{fid}/result.json')) == wrapper, 'Rebuttal family result differs')
    ordered_payloads = [payloads[fid] for fid in run['family_ids']]
    ensure(digest(canonical(ordered_payloads).encode()) == run['selected_input_sha256'], 'Rebuttal selected-payload fingerprint differs')
    expected_counts = {name: dispositions[name] for name in ('concern_refuted','concern_survives','unresolved')}
    ensure(status['disposition_counts'] == expected_counts, 'Rebuttal disposition counts differ')
    return {'reviewed_families': len(wrappers), 'thinking': run['thinking'], 'disposition_counts': expected_counts, 'formal_verifications': 0,
            'scope': 'selected_first_pass_findings_only_same_model_second_call'}

def validate_supplements(root, by_family):
    folder = root / 'supplements'
    if not folder.exists():
        return []
    checkpoints = []
    for metadata in sorted(folder.glob('*-checkpoint.json')):
        info = read_json(metadata)
        source = safe_path(folder, info['name'])
        files = {r['path']: r['sha256'] for r in info['files']}
        ensure(len(files) == len(info['files']), 'Supplement duplicate checkpoint file')
        actual = {p.relative_to(source).as_posix() for p in source.rglob('*') if p.is_file()}
        ensure(set(files) == actual, 'Supplement checkpoint file coverage differs')
        for rel, expected in files.items():
            ensure(sha(safe_path(source, rel)) == expected, 'Supplement checkpoint file digest differs')
        run = read_json(source / 'run.json')
        status = read_json(source / 'status.json')
        reviews = read_rows(source / 'reviews.jsonl') if (source / 'reviews.jsonl').exists() else []
        ensure(len({r['family_id'] for r in reviews}) == len(reviews), 'Supplement duplicate accepted family')
        ensure(run['run_id'] == info['run_id'] and run['thinking'] == info['thinking'], 'Supplement thinking/run checkpoint differs')
        ensure(run['thinking'] in {'off','minimal','low','medium','high','xhigh','max','auto'} and status.get('thinking') == run['thinking'], 'Supplement status thinking differs')
        ensure(status['status'] == info['checkpoint_status'] and status['failed_families'] == info['failed_families'], 'Supplement run status checkpoint differs')
        ensure(status['status'] in {'complete', 'interrupted', 'incomplete'} and not status.get('in_flight_families'), 'Supplement is not a stopped checkpoint')
        ensure(len(reviews) == info['accepted_families'] == status['completed_families'], 'Supplement accepted-family coverage differs')
        ensure(run['formal_verification'] is False and status['formal_verifications'] == 0, 'Supplement claims formal verification')
        policy = (source / 'review-policy.md').read_bytes()
        ensure(digest(policy) == run['policy_sha256'], 'Supplement policy differs')
        for wrapper in reviews:
            fid = wrapper['family_id']; paper = by_family[fid]
            ensure(wrapper['run_id'] == run['run_id'] and wrapper['thinking'] == run['thinking'], 'Supplement wrapper thinking/run differs')
            ensure(wrapper['formal_verification'] is False and wrapper['source_commit'] == COMMIT, 'Supplement wrapper formal/source state differs')
            ensure(wrapper['model'] == MODEL and wrapper['provider'] == PROVIDER and wrapper['runner'] == 'oh-my-pi', 'Supplement worker identity differs')
            ensure(wrapper['source_input_sha256'] == digest(canonical(paper).encode()), 'Supplement input fingerprint differs')
            stored = safe_path(source, f'families/family-{fid}/input.json').read_bytes()
            ensure(digest(stored) == wrapper['stored_input_sha256'] and json.loads(stored) == paper, 'Supplement stored input differs')
            prompt = safe_path(source, wrapper['prompt_path']).read_bytes()
            events = safe_path(source, wrapper['log_path']).read_bytes()
            ensure(digest(prompt) == wrapper['prompt_sha256'] and prompt.startswith(policy), 'Supplement prompt differs')
            ensure(prompt.endswith((json.dumps(paper, ensure_ascii=False, separators=(',', ':'))+'\n').encode()), 'Supplement prompt source differs')
            ensure(digest(events) == wrapper['log_sha256'], 'Supplement event digest differs')
            review, message = parse_final_events(events)
            ensure(review == wrapper['review'] and message.get('responseId') == wrapper.get('inference_response_id'), 'Supplement final model response differs')
            validate_review(review, paper)
        ensure(info['scope'] == 'supplemental_checkpoint_not_added_to_primary_coverage', 'Supplement scope differs')
        checkpoints.append({k:v for k,v in info.items() if k != 'files'})
    return checkpoints

def validate_coverage(coverage, run, status, reviews, evidence_paths, pilot):
    planned = set(run['family_ids'])
    accepted = {r['family_id'] for r in reviews}
    failures = status.get('failures', {})
    ensure(isinstance(failures, dict) and len(failures) == status['failed_families'], 'Failure identity list/count differs')
    failed = set(failures)
    ensure(not (accepted & failed) and (accepted | failed) <= planned, 'Accepted/failed identities invalid')
    ensure(len(accepted) == len(reviews) == status['completed_families'], 'Accepted count/status differs')
    interrupted = status.get('interrupted_family_attempts', {})
    ensure(isinstance(interrupted, dict) and set(interrupted) <= planned, 'Interrupted attempt identity differs')
    attempted = set(accepted) | failed | set(interrupted)
    for relative in evidence_paths:
        match = re.fullmatch(r'families/family-([0-9]{3})/attempt-[^/]+', relative)
        if match:
            attempted.add(match[1])
    ensure(attempted <= planned, 'Attempt evidence outside plan')
    pending = planned-accepted-failed
    if status.get('pending_family_ids') is not None:
        ensure(set(status['pending_family_ids']) == pending, 'Status pending identity differs')
    ensure(not status.get('in_flight_families'), 'Checkpoint still declares in-flight families')
    expected = {'mode': 'pilot_partial_coverage' if pilot else 'complete_planned_coverage',
        'planned_families': len(planned), 'planned_family_ids': sorted(planned),
        'accepted_families': len(accepted), 'accepted_family_ids': sorted(accepted),
        'failed_families': len(failed), 'failed_family_ids': sorted(failed), 'failures': failures,
        'pending_family_ids': sorted(pending), 'not_attempted_family_ids': sorted(planned-attempted),
        'attempted_unresolved_family_ids': sorted(attempted-accepted-failed),
        'interrupted_family_attempts': interrupted, 'checkpoint_status': status['status'],
        'attempt_evidence_note': 'An attempt file may represent preparation, transport, quota or model failure; it does not prove successful inference.',
        'formal_verifications': 0, 'mathematical_truth_established': False}
    ensure(coverage == expected, 'Coverage manifest differs from actual plan, accepted responses, failures or attempt evidence')
    return expected

def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--package', type=Path, default=Path('work/proof-review/deliverable'))
    ap.add_argument('--component', type=Path, default=Path('/Users/zxy/Cayley-Math/components/openai-math'))
    ap.add_argument('--source-root', type=Path, default=Path('/Users/zxy/math'))
    ap.add_argument('--expected-families', type=int, default=373)
    ap.add_argument('--pilot', action='store_true', help='Explicitly validate a partial-coverage pilot package')
    args = ap.parse_args(argv)
    root, component, upstream = args.package.resolve(), args.component.resolve(), args.source_root.resolve()
    checks = []
    manifest = read_json(root / 'manifest.json')
    ensure(manifest.get('format') == 'openai-math-proof-review-file-manifest-v1', 'Manifest format')
    entries = manifest['files']
    names = [entry['path'] for entry in entries]
    ensure(len(names) == len(set(names)), 'Duplicate file manifest entry')
    actual = {p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file()} - {'manifest.json', 'validation.json'}
    ensure(set(names) == actual, 'File manifest does not cover exactly delivered files')
    for entry in entries:
        path = safe_path(root, entry['path'])
        ensure(path.stat().st_size == entry['bytes'] and sha(path) == entry['sha256'], 'File digest/size mismatch: ' + entry['path'])
    checks.append('all_delivered_file_hashes_and_exact_manifest_coverage')
    package = read_json(root / 'proof-review-package.json')
    ensure(package['source_commit'] == COMMIT and package['formal_verification'] is False, 'Package scope/commit')
    ensure(package.get('pilot', False) == args.pilot, 'Pilot package requires explicit --pilot; ordinary packages must use full-coverage validation')
    commit = subprocess.check_output(['git', '-C', str(upstream), 'rev-parse', 'HEAD'], text=True).strip()
    ensure(commit == COMMIT, 'Live source HEAD differs from fixed commit')
    input_manifest = read_json(root / 'input-manifest.json')
    ensure(input_manifest['source_commit'] == COMMIT and input_manifest['formal_verification'] is False, 'Input manifest scope/commit')
    with gzip.open(root / 'inputs.jsonl.gz', 'rb') as f:
        input_bytes = f.read()
    ensure(digest(input_bytes) == input_manifest['inputs_sha256'], 'Compressed input bytes differ from snapshot digest')
    inputs = [json.loads(line) for line in input_bytes.decode('utf-8').splitlines() if line.strip()]
    by_family = {r['family_id']: r for r in inputs}
    ensure(len(inputs) == len(by_family) == args.expected_families, 'Input coverage or duplicate families')
    catalog_families = read_json(component / 'audit/families.json')
    ensure(set(by_family) <= set(catalog_families), 'Review family absent from pinned catalog')
    if args.expected_families == len(catalog_families):
        ensure(set(by_family) == set(catalog_families), 'Expected pinned catalog family identities differ')
    for rel, expected in input_manifest['input_files'].items():
        ensure(sha(safe_path(component, rel)) == expected, 'Owning component snapshot mismatch: ' + rel)
    originals = {r['id']: r for r in read_rows(component / 'data/source-records.jsonl')}
    macro = {r['paper_id']: r for r in read_rows(component / 'data/macro-contexts.jsonl')}
    inventory = {r['paper_id']: r for r in read_rows(component / 'audit/manuscripts.jsonl') if r['status'] == 'current'}
    ensure(len(inventory) == 721, 'Current manuscript inventory changed')
    source_files = {}
    mappings = {}
    for family, paper in by_family.items():
        ensure(paper['source_commit'] == COMMIT and paper['paper_id'] in inventory, 'Input source commit/current paper mismatch')
        ensure(paper['input_scope'] == 'complete_extracted_primary_body_plus_macro_context', 'Input scope changed')
        line_map = source_lines(paper)
        mapping = read_json(root / 'line-maps' / (family + '.json.gz'))
        ensure(mapping['family_id'] == family and mapping['paper_id'] == paper['paper_id'], 'Line-map identity mismatch')
        mappings[family] = mapping
        reconstructed = []
        next_line = 1
        mapped_ids = []
        for entry in mapping['lines']:
            record = originals.get(entry['record_id'])
            ensure(record is not None and record['paper_id'] == paper['paper_id'], 'Mapped source record missing/wrong paper')
            ensure(entry['source_spans'] == record['source_spans'], 'Mapped source spans differ from original record')
            lo, hi = int(entry['first_line'][1:]), int(entry['last_line'][1:])
            text_lines = record['text'].splitlines()
            ensure(lo == next_line and hi == lo + len(text_lines)-1, 'Line-map continuity or source record size differs')
            for i, line in enumerate(text_lines, lo):
                ensure(line_map.get(i) == line, 'Source labeled line differs from original extraction')
            reconstructed.extend(text_lines); next_line = hi + 1; mapped_ids.append(record['id'])
            for span in entry['source_spans']:
                source_files[span['path']] = span['sha256']
        ensure(len(reconstructed) == len(line_map), 'Source lines not fully mapped')
        expected_records = sorted((r for r in originals.values() if r['paper_id'] == paper['paper_id']), key=lambda r: r['chunk_index'])
        ensure(mapped_ids == [r['id'] for r in expected_records], 'Representative paper extraction not completely supplied')
        ensure(paper['macro_context'] == macro[paper['paper_id']]['contexts'], 'Macro context differs')
        for context in paper['macro_context']:
            source_files[context['source_path']] = context['source_sha256']
        for entry in paper['source_dependencies']:
            source_files[entry['path']] = entry['sha256']
        formal = paper['formalization_scope_note']
        ensure(formal['formal_verification_executed'] is False, 'Formalization scope claims execution')
        if formal.get('source_path'):
            source_files[formal['source_path']] = formal['sha256']
            ensure(safe_path(upstream, formal['source_path']).read_text() == formal['text'], 'Scope document differs')
    for rel, expected in source_files.items():
        ensure(sha(safe_path(upstream, rel)) == expected, 'Original source file digest differs: ' + rel)
    checks.append('complete_representative_body_and_macro_line_mapping_to_fixed_source_hashes')
    evidence_index = read_json(root / 'audit/evidence-index.json')
    evidence = {r['original_path']: r for r in evidence_index['files']}
    ensure(len(evidence) == len(evidence_index['files']), 'Duplicate evidence source path')
    def evidence_bytes(rel):
        ensure(rel in evidence, 'Evidence missing: ' + rel)
        entry = evidence[rel]
        with gzip.open(safe_path(root, entry['path']), 'rb') as f:
            raw = f.read()
        ensure(len(raw) == entry['original_bytes'] and digest(raw) == entry['original_sha256'], 'Original evidence hash/size mismatch: ' + rel)
        return raw
    # Validate failed-attempt logs too, although only accepted responses are interpreted.
    for rel in evidence:
        evidence_bytes(rel)
    status = json.loads(evidence_bytes('status.json'))
    run = json.loads(evidence_bytes('run.json'))
    policy = evidence_bytes('review-policy.md')
    if args.pilot:
        ensure(status['status'] in {'complete','interrupted','incomplete'} and status['completed_families'] >= 1, 'Pilot lacks a stopped checkpoint with accepted results')
    else:
        ensure(status['status'] == 'complete' and status['failed_families'] == 0 and status['completed_families'] == args.expected_families, 'Run incomplete or failed; explicit --pilot required')
    ensure(status['formal_verifications'] == 0 and run['formal_verification'] is False, 'Run claims formal result')
    ensure(run['input_sha256'] == digest(input_bytes) and run['selected_input_sha256'] == digest(canonical(inputs).encode()), 'Run input fingerprint differs')
    ensure(run['family_ids'] == [r['family_id'] for r in inputs] and run['families'] == args.expected_families, 'Run family fingerprint differs')
    ensure(run['model'] == MODEL and run['provider'] == PROVIDER and run['runner'] == 'oh-my-pi', 'Run identity differs')
    ensure(run.get('thinking') in {'off','minimal','low','medium','high','xhigh','max','auto'} and status.get('thinking') == run['thinking'], 'Primary thinking level inconsistent')
    ensure(run['policy_sha256'] == digest(policy), 'Run policy digest differs')
    reviews = read_rows(root / 'reviews.jsonl.gz')
    accepted_ids = {r['family_id'] for r in reviews}
    ensure(len(accepted_ids) == len(reviews) and accepted_ids <= set(by_family), 'Duplicate/unplanned accepted review coverage')
    ensure(sorted(accepted_ids) == package['accepted_family_ids'], 'Package accepted IDs differ')
    if not args.pilot:
        ensure(len(reviews) == args.expected_families and accepted_ids == set(by_family), 'Incomplete full-coverage run')
    coverage = validate_coverage(read_json(root / 'coverage.json'), run, status, reviews, evidence, args.pilot)
    findings_expected = []
    for wrapper in reviews:
        family = wrapper['family_id']; paper = by_family[family]; review = wrapper['review']
        ensure(wrapper['paper_id'] == paper['paper_id'] and wrapper['source_commit'] == COMMIT, 'Wrapper identity/commit mismatch')
        ensure(wrapper['model'] == MODEL and wrapper['provider'] == PROVIDER and wrapper['runner'] == 'oh-my-pi', 'Wrapper model/runner mismatch')
        ensure(wrapper['run_id'] == run['run_id'] and wrapper['formal_verification'] is False, 'Wrapper run/formal state mismatch')
        ensure(wrapper.get('thinking') == run['thinking'], 'Wrapper thinking differs from selected run')
        ensure(wrapper['review_kind'] == 'llm_proof_review_attempt' and wrapper['input_scope'] == paper['input_scope'], 'Wrapper scope mismatch')
        ensure(wrapper['source_input_sha256'] == digest(canonical(paper).encode()), 'Wrapper input digest mismatch')
        ensure(wrapper['policy_sha256'] == digest(policy), 'Wrapper policy fingerprint differs')
        stored_input = evidence_bytes(f'families/family-{family}/input.json')
        ensure(digest(stored_input) == wrapper['stored_input_sha256'] and json.loads(stored_input) == paper, 'Stored family input differs')
        prompt = evidence_bytes(wrapper['prompt_path'])
        ensure(digest(prompt) == wrapper['prompt_sha256'] and prompt.startswith(policy), 'Prompt hash/policy differs')
        ensure(prompt.endswith((json.dumps(paper, ensure_ascii=False, separators=(',', ':'))+'\n').encode()), 'Prompt does not contain exact final source JSON')
        events = evidence_bytes(wrapper['log_path'])
        ensure(digest(events) == wrapper['log_sha256'], 'Wrapper log SHA mismatch')
        parsed, final = parse_final_events(events)
        ensure(parsed == review, 'Review differs from final actual OMP response')
        ensure(final.get('responseId') == wrapper.get('inference_response_id'), 'Inference response identity differs')
        validate_review(review, paper)
        saved = json.loads(evidence_bytes(f'families/family-{family}/result.json'))
        ensure(saved == wrapper, 'Family saved result differs from aggregate wrapper')
        for finding in review['findings']:
            lo, hi = parse_location(finding['location'], source_lines(paper))
            spans = [entry for entry in mappings[family]['lines'] if int(entry['first_line'][1:]) <= hi and int(entry['last_line'][1:]) >= lo]
            ensure(spans, 'Finding source span mapping absent')
            findings_expected.append({'family_id': family, 'paper_id': wrapper['paper_id'], 'run_id': wrapper['run_id'], 'model': MODEL,
                'source_commit': COMMIT, 'source_input_sha256': wrapper['source_input_sha256'], 'log_path': wrapper['log_path'],
                'log_sha256': wrapper['log_sha256'], 'formal_verification': False, **finding, 'source_record_spans': spans})
    findings = read_rows(root / 'findings.jsonl.gz')
    ensure(findings == findings_expected, 'Mapped finding output differs from actual reviews')
    checks.append('all_real_omp_response_input_prompt_policy_hashes_and_grounded_quotes')
    rebuttal_summary = validate_rebuttals(root, by_family, reviews)
    if rebuttal_summary:
        checks.append('selected_same_model_rebuttal_inputs_logs_quotes_and_original_finding_identity')
    supplement_checkpoints = validate_supplements(root, by_family)
    if supplement_checkpoints:
        checks.append('separate_supplemental_checkpoint_files_and_accepted_response_provenance')
    summary = read_json(root / 'summary.json')
    counts = dict(Counter(r['review']['assessment'] for r in reviews))
    ensure(summary['reviewed_families'] == len(reviews) and summary['reviewed_representative_papers'] == len({r['paper_id'] for r in reviews}), 'Summary coverage differs')
    ensure(summary['pilot'] == args.pilot and summary['coverage'] == coverage, 'Summary pilot/coverage differs')
    ensure(summary['source_current_papers'] == 721 and summary['assessment_counts'] == counts, 'Summary scope/count differs')
    ensure(summary['formal_verifications'] == 0 and summary['mathematical_truth_established'] is False, 'Summary upgrades model opinion to truth')
    ensure(summary['candidate_findings'] == len(findings) and summary['finding_severity_counts'] == dict(Counter(f['severity'] for f in findings)), 'Summary finding counts differ')
    ensure(summary.get('rebuttal') == rebuttal_summary, 'Rebuttal summary differs')
    ensure(summary.get('thinking') == run['thinking'], 'Summary misstates primary thinking level')
    ensure(summary.get('supplement_checkpoints', []) == supplement_checkpoints, 'Supplement checkpoint summary differs')
    ensure(status['assessment_counts'] == counts and status['candidate_findings'] == len(findings), 'Run status aggregate differs')
    risk_expected = {r['family_id'] for r in reviews if r['review']['findings'] or r['review']['assessment'] == 'insufficient_review'}
    ensure({r['family_id'] for r in summary['risk_papers']} == risk_expected, 'Risk family list differs')
    checks.append('summary_counts_scoped_model_assessments_without_mathematical_truth_claim')
    report = {'status': 'passed', 'source_commit': COMMIT, 'coverage_mode': coverage['mode'], 'coverage': coverage, 'reviewed_families': len(reviews),
        'source_current_papers': 721, 'formal_verifications': 0, 'mathematical_truth_established': False,
        'checks': checks, 'candidate_findings': len(findings), 'assessment_counts': counts,
        'source_files_hashed': len(source_files), 'manifest_files': len(entries), 'raw_evidence_files': len(evidence),
        'primary_thinking': run['thinking'], 'supplement_checkpoints': supplement_checkpoints,
        'limitations': ['Mechanical validation is not verification of mathematical claims.',
            'Only accepted representatives listed in coverage have completed reviews; planned inputs do not establish review coverage of all 721 manuscripts.',
            'External references and companion proofs were not fully supplied or checked.',
            'Finite checks and supplementary reviews have their independently stated scopes.']}
    (root / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
    print(json.dumps(report, ensure_ascii=False, indent=2))
    return 0

if __name__ == '__main__':
    raise SystemExit(main())