"""Synthetic fifth-batch attacks: four scopes, 32 real saves and full raw replay."""
import ast
import copy
import json
from pathlib import Path

import pytest

from scripts import verify_mask_under50_requests_v5 as audit
from test_verify_mask_under50_requests import staged, draft, export, write, row, KEY, POLYGON
from test_verify_mask_under50_requests_v2 import catalog_case, gallery, event
from test_verify_mask_under50_requests_v3 import completed_batches as previous_completed, fresh_catalog as previous_catalog
from test_verify_mask_under50_requests_v4 import (
    completed_batches as fourth_completed, fresh_catalog as fourth_catalog,
    count_case as fourth_count_case, source_claims_case as fourth_source_claims_case,
)


def test_no_builder_source_producer_import_old_global_mutation_or_live_save():
    tree = ast.parse(Path(audit.__file__).read_text())
    for node in ast.walk(tree):
        if isinstance(node, (ast.Import, ast.ImportFrom)):
            names = [value.name for value in node.names] + [getattr(node, 'module', '') or '']
            assert not any('build_mask' in name or 'mask_review_continuation' in name for name in names)
        if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
            targets = node.targets if isinstance(node, ast.Assign) else [node.target]
            assert not any(isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name)
                and target.value.id in ('geometry', 'continuation', 'previous', 'sources') for target in targets)
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            assert node.func.attr not in ('save_review', 'save_annotation', 'backup', 'setup')
            if isinstance(node.func.value, ast.Name) and node.func.value.id in ('geometry', 'continuation', 'previous'):
                assert node.func.attr not in ('audit', 'check_sources')
                if node.func.attr == 'check_count_basis':
                    assert {keyword.arg for keyword in node.keywords} >= {'saved_count', 'classes', 'expected_counts'}


def test_direct_audit_refuses_unready_and_unpinned_output_before_any_read(tmp_path, monkeypatch):
    monkeypatch.setattr(audit, 'inventory', lambda _: pytest.fail('unfinished staging read'))
    with pytest.raises(ValueError, match='READY'):
        audit.audit(tmp_path/'not-built')
    monkeypatch.setattr(audit, 'SOURCE_AUDIT_SHA256', None)
    with pytest.raises(ValueError, match='not pinned'):
        audit.audit(tmp_path/'not-built', producer_complete=True)


@pytest.fixture
def sealed_roots(tmp_path, monkeypatch):
    outputs = tmp_path/'outputs'; pins = {}
    for number in (1, 2, 3, 4):
        namespace = f'pallet_mask_under50_requests_v{number}'; root = outputs/namespace
        write(root/'manifest.json', dict(number=number))
        for name in audit.SEALS:
            write(root/name, dict(state='passed', number=number))
        pins[namespace] = dict(manifest_sha256=audit.digest(root/'manifest.json'), verification_sha256=audit.digest(root/'verification.json'))
    monkeypatch.setattr(audit, 'SEALED_PACK_PINS', pins)
    return outputs, outputs/'pallet_mask_under50_requests_v5', pins


def test_all_four_prior_sealed_packs_registered_not_own_partial_root(sealed_roots):
    outputs, own, pins = sealed_roots; write(own/'verification.json', {})
    assert set(audit.discover_sealed_packs(outputs, own)) == set(pins)


@pytest.mark.parametrize('attack', ['missing', 'half', 'manifest', 'twins', 'unknown', 'symlink'])
def test_missing_or_changed_prior_v4_seal_and_unpinned_new_packs_fail_closed(sealed_roots, attack):
    outputs, own, _ = sealed_roots; root = outputs/'pallet_mask_under50_requests_v4'
    if attack == 'missing':
        for name in audit.SEALS:
            (root/name).unlink()
    elif attack == 'half':
        (root/'independent_verification.json').unlink()
    elif attack == 'manifest':
        write(root/'manifest.json', dict(altered=True))
    elif attack == 'twins':
        write(root/'independent_verification.json', dict(altered=True))
    elif attack == 'unknown':
        for name in audit.SEALS:
            write(outputs/'pallet_mask_under50_requests_v6'/name, dict(state='passed'))
    else:
        (root/'manifest.json').rename(root/'real_manifest.json')
        (root/'manifest.json').symlink_to(root/'real_manifest.json')
    with pytest.raises(ValueError):
        audit.discover_sealed_packs(outputs, own)


@pytest.fixture
def completed_batches(fourth_completed, tmp_path):
    old_fresh, baseline, task_keys, registry, refs = fourth_completed
    namespace = 'pallet_mask_under50_requests_v4'; task_keys[namespace] = {f'{n+401:024x}' for n in range(6)}
    values = [audit.sources.loads(raw) for _, _, _, raw in old_fresh['events']]
    for key in sorted(task_keys[namespace]):
        proposal = dict(target_key=key, polygon=[[x+1, y] for x, y in POLYGON])
        value = event(key, marker='真实完成第四批保存')
        value.update(base_proposal_id=audit.sha(proposal), proposal_publication=15,
            human_edited=True, event_kind='human_mask_gallery_revision')
        values.append(value)
        registry[15, audit.sha(proposal), key] = dict(kind='independent_preannotation', namespace=namespace, proposal=proposal)
    fresh = gallery(tmp_path/'current-v5.sqlite3', values)
    for event_id, key, _, raw in fresh['events']:
        if key in task_keys[namespace]:
            value = audit.sources.loads(raw); refs[event_id] = registry[15, value['base_proposal_id'], key]
    return fresh, baseline, task_keys, registry, refs


def test32_completed_images_are34_save_events_plus17_revisions_not51_new_training_labels(completed_batches):
    extension, completed = audit.check_saved_batches(*completed_batches)
    assert list(completed.values()) == [10, 9, 7, 6]
    assert extension['appended_gallery_events'] == 51 and len(extension['new_distinct_saved_keys']) == 32
    assert len(extension['changed_baseline_current_keys']) == 14
    assert extension['baseline_gallery_current_unchanged'] is False
    assert extension['baseline_current_revisions_preserved_in_history']


@pytest.mark.parametrize('attack', ['raw_prefix', 'new_key', 'missing_v4_save', 'namespace', 'hash', 'draft_copy',
    'assistant_event', 'first_revision', 'route', 'old_raw_revision', 'missing_pack', 'wrong_publication', 'duplicate_task_key'])
def test_all_six_v4_completions_need_correct_package_triples_and_exact_raw_history(completed_batches, attack):
    fresh, baseline, tasks, registry, refs = copy.deepcopy(completed_batches)
    namespace = 'pallet_mask_under50_requests_v4'; key = sorted(tasks[namespace])[0]
    history = fresh['histories'][key]; event_id = history[-1][0]
    if attack == 'raw_prefix':
        entry = list(fresh['events'][0]); entry[3] = json.dumps(json.loads(entry[3])); fresh['events'][0] = tuple(entry)
    elif attack == 'new_key':
        fresh['current']['unknown'] = fresh['current'][key]; fresh['histories']['unknown'] = history
    elif attack == 'missing_v4_save':
        fresh['current'].pop(key); fresh['histories'].pop(key)
    elif attack == 'namespace':
        refs[event_id]['namespace'] = 'pallet_mask_under50_requests_v3'
    elif attack == 'hash':
        history[-1][3]['base_proposal_id'] = 'bad'
    elif attack == 'draft_copy':
        history[-1][3]['polygon'] = refs[event_id]['proposal']['polygon']
        fresh['current'][key][2]['polygon'] = refs[event_id]['proposal']['polygon']
    elif attack == 'assistant_event':
        history[-1][3]['human_edited'] = False
    elif attack == 'first_revision':
        entry = list(history[0]); entry[1] = 2; history[0] = tuple(entry)
    elif attack == 'route':
        refs[fresh['events'][len(baseline['events'])][0]]['namespace'] = namespace
    elif attack == 'old_raw_revision':
        old_key = next(iter(baseline['current'])); first = list(fresh['histories'][old_key][0])
        first[2] = json.dumps(json.loads(first[2])); fresh['histories'][old_key][0] = tuple(first)
    elif attack == 'missing_pack':
        tasks.pop('pallet_mask_under50_requests_v1')
    elif attack == 'duplicate_task_key':
        tasks['pallet_mask_under50_requests_v3'].add(key)
    else:
        proposal_sha = history[-1][3]['base_proposal_id']; registry[14, proposal_sha, key] = registry.pop((15, proposal_sha, key))
    with pytest.raises(ValueError):
        audit.check_saved_batches(fresh, baseline, tasks, registry, refs)


@pytest.fixture
def fresh_catalog(fourth_catalog):
    case = fourth_catalog
    for n in range(1510, 1516):
        key = f'{n+1:024x}'; source = row(key); proposal = dict(target_key=key, polygon=copy.deepcopy(POLYGON))
        value = event(key, marker='真实第四批来源')
        value.update(proposal_publication=15, base_proposal_id=audit.sha(proposal), proposal_polygon=copy.deepcopy(POLYGON))
        raw = json.dumps(value, ensure_ascii=False, indent=2); event_id = len(case['gallery']['events'])+1
        case['rows'][key] = source; case['gallery']['current'][key] = (1, raw, value)
        case['gallery']['histories'][key] = [(event_id, 1, raw, value)]; case['gallery']['events'].append((event_id, key, 1, raw))
        case['registry'][15, audit.sha(proposal), key] = dict(kind='independent_preannotation', namespace='pallet_mask_under50_requests_v4',
            proposal=proposal, path=Path('synthetic-v4'))
        case['catalog'].append(dict(target_key=key, row=source, polygon=copy.deepcopy(POLYGON), origin='saved_gallery', revision=1,
            payload_sha256=audit.sha(value), event_raw_sha256=audit.sources.raw_sha(raw), initial_polygon=copy.deepcopy(POLYGON),
            batch='pallet_mask_under50_requests_v4', history_revisions=1, actual_saved_research_reference_not_GT=True))
        case['event_audit'].append(dict(event_id=event_id, target_key=key, revision=1, payload_raw_sha256=audit.sources.raw_sha(raw),
            proposal_publication=15, base_proposal_id=value['base_proposal_id'], namespace='pallet_mask_under50_requests_v4', event_specific_source_verified=True))
    write(case['snapshot']/'private/source_catalog.jsonl', case['catalog'], True)
    write(case['snapshot']/'private/event_binding_audit.jsonl', case['event_audit'], True)
    return case


def check_catalog(case):
    return audit.check_fresh_catalog(case['snapshot'], case['baseline'], case['pose'], case['gallery'], case['rows'],
        case['publications'], case['registry'], 'f'*64, None)


def test1516_current_sources_and_all1139_events_are_independently_replayed(fresh_catalog):
    catalog, refs = check_catalog(fresh_catalog)
    assert len(catalog) == 1516 and len(fresh_catalog['gallery']['current']) == 1034
    assert len(refs) == len(fresh_catalog['checked']) == 1139


@pytest.mark.parametrize('attack', ['stale_polygon', 'canonical_raw_hash', 'namespace', 'duplicate_frame', 'original_box',
    'event_raw_hash', 'event_target', 'event_revision', 'event_publication', 'event_hash', 'duplicate_event_id', 'stale_current'])
def test_latest_catalog_and_raw_utf8_event_hashes_cannot_be_stale_or_laundered(fresh_catalog, attack):
    case = fresh_catalog; record = case['catalog'][-1]; key = record['target_key']
    if attack == 'stale_polygon':
        record['polygon'][0][0] += 1
    elif attack == 'canonical_raw_hash':
        record['event_raw_sha256'] = audit.sha(case['gallery']['current'][key][2])
    elif attack == 'namespace':
        record['batch'] = 'pallet_mask_under50_requests_v3'
    elif attack == 'duplicate_frame':
        record['row']['frame_id'] = case['catalog'][-2]['row']['frame_id']
    elif attack == 'original_box':
        case['gallery']['current'][key][2]['polygon'] = [[20, 30], [80, 30], [80, 50], [20, 50]]
    elif attack == 'event_raw_hash':
        case['event_audit'][-1]['payload_raw_sha256'] = audit.sha(case['gallery']['current'][key][2])
    elif attack.startswith('event_'):
        entry = list(case['gallery']['events'][-1]); value = audit.sources.loads(entry[3])
        if attack == 'event_target':
            entry[1] = case['catalog'][-2]['target_key']
        elif attack == 'event_revision':
            entry[2] = 999
        else:
            value['proposal_publication' if attack == 'event_publication' else 'base_proposal_id'] = 14 if attack == 'event_publication' else 'bad'
            entry[3] = json.dumps(value)
        case['gallery']['events'][-1] = tuple(entry)
    elif attack == 'duplicate_event_id':
        entry = list(case['gallery']['events'][-1]); entry[0] = 1; case['gallery']['events'][-1] = tuple(entry)
    else:
        current = list(case['gallery']['current'][key]); current[1] = json.dumps(json.loads(current[1])); case['gallery']['current'][key] = tuple(current)
    write(case['snapshot']/'private/source_catalog.jsonl', case['catalog'], True)
    write(case['snapshot']/'private/event_binding_audit.jsonl', case['event_audit'], True)
    with pytest.raises((ValueError, AssertionError)):
        check_catalog(case)


def count_case():
    catalog, inputs, manifest = fourth_count_case()
    for cls, count in {11: 2, 16: 2, 17: 1, 19: 1}.items():
        for n in range(count):
            key = f'{cls+500:022x}{n:02x}'; catalog.append(dict(target_key=key, row=row(key, cls)))
    counts = audit.Counter(r['row']['final_class_id'] for r in catalog)
    inputs.update(actual_counted_saved_basis=1516, actual_class_counts={str(c): n for c, n in counts.items()}, shortlisted_classes=list(audit.CLASSES))
    manifest.update(actual_human_saved_counts_before=copy.deepcopy(inputs['actual_class_counts']), filter_classes=list(audit.CLASSES))
    return catalog, inputs, manifest


def test1516_real_counts_exclude_both_class17_and20_without_old_helper_mutation():
    counts = audit.check_count_basis(*count_case())
    assert sum(counts.values()) == 1516 and counts[17] == counts[20] == 50
    assert {c: counts[c] for c in audit.CLASSES} == {11: 25, 12: 47, 16: 42, 19: 43}
    assert audit.previous.CLASSES == (11, 12, 16, 17, 19)
    assert audit.previous.EXPECTED_COUNTS[17] == 49 and audit.geometry.CLASSES == (11, 12, 16, 17, 19, 20)


@pytest.mark.parametrize('attack', ['stale1510', 'machine1550', 'old5scope', 'class17under50', 'class20under50', 'duplicate_frame', 'duplicate_key', 'bool_count'])
def test_wrong_real_saved_denominator_or_four_class_scope_is_rejected(attack):
    catalog, inputs, manifest = count_case()
    if attack == 'stale1510':
        inputs['actual_counted_saved_basis'] = 1510
    elif attack == 'machine1550':
        inputs['actual_counted_saved_basis'] = 1550
    elif attack == 'old5scope':
        manifest['filter_classes'].insert(3, 17)
    elif attack in ('class17under50', 'class20under50'):
        inputs['actual_class_counts']['17' if attack == 'class17under50' else '20'] = 49
    elif attack == 'duplicate_frame':
        catalog[-1]['row']['frame_id'] = catalog[-2]['row']['frame_id']
    elif attack == 'duplicate_key':
        catalog[-1]['target_key'] = catalog[-2]['target_key']
    else:
        inputs['actual_class_counts']['11'] = True
    with pytest.raises(ValueError):
        audit.check_count_basis(catalog, inputs, manifest)


def issued_case(classes=(11, 16, 19), count=2):
    staged_rows, proposals, decisions = [], [], {}
    for cls in classes:
        for n in range(3):
            key = f'{cls:022x}{n:02x}'; record = dict(target_key=key, class_id=cls); staged_rows.append(record)
            decisions[key] = dict(approved=n < count)
            if n < count:
                proposals.append(copy.deepcopy(record))
    counts = audit.Counter(p['class_id'] for p in proposals)
    manifest = dict(request_count=len(proposals), class_counts={str(c): n for c, n in counts.items()}, classes=sorted(counts))
    return proposals, copy.deepcopy(proposals), staged_rows, decisions, manifest, audit.EXPECTED_COUNTS.copy()


def test_four_classes_may_stage12_and_issue8_but_dark_classes_need_not_be_issued():
    full = issued_case(audit.CLASSES); counts, withheld = audit.check_issued_inventory(*full)
    assert sum(counts.values()) == 8 and len(withheld) == 4
    audit.check_staged_limits(full[2], audit.EXPECTED_COUNTS)
    partial = issued_case(); counts, withheld = audit.check_issued_inventory(*partial)
    assert counts == {11: 2, 16: 2, 19: 2} and 12 not in counts and len(withheld) == 3


@pytest.mark.parametrize('classes', [(17,), (20,), (11, 11, 11, 11), (22,)])
def test_staging_max3_per_class_and_both_completed_classes_are_excluded(classes):
    with pytest.raises(ValueError, match='Classes17/20 excluded'):
        audit.check_staged_limits([dict(class_id=c) for c in classes], audit.EXPECTED_COUNTS)


@pytest.mark.parametrize('attack', ['class17', 'class20', 'third_per_class', 'unpaired', 'order', 'bool_approval', 'bool_count', 'foreign_key', 'approved_missing', 'gap'])
def test_issued_scope_gap_caps_and_approved_pairing_cannot_be_relaxed(attack):
    args = list(issued_case()); proposals, tasks, staged_rows, decisions, manifest, actual_counts = args
    if attack in ('class17', 'class20'):
        cls = 17 if attack == 'class17' else 20
        for record in (proposals[0], tasks[0], staged_rows[0]):
            record['class_id'] = cls
        counts = audit.Counter(p['class_id'] for p in proposals); manifest.update(class_counts={str(c): n for c, n in counts.items()}, classes=sorted(counts))
    elif attack == 'third_per_class':
        args = list(issued_case(count=3))
    elif attack == 'unpaired':
        tasks.pop()
    elif attack == 'order':
        tasks.reverse()
    elif attack == 'bool_approval':
        decisions[proposals[0]['target_key']]['approved'] = 1
    elif attack == 'bool_count':
        manifest['request_count'] = True
    elif attack == 'foreign_key':
        proposals[0]['target_key'] = tasks[0]['target_key'] = 'f'*24
    elif attack == 'gap':
        actual_counts[11] = 49
    else:
        decisions[staged_rows[2]['target_key']]['approved'] = True
    with pytest.raises(ValueError):
        audit.check_issued_inventory(*args)


def test_all65_prior_inspected_images_including33_withheld_are_globally_protected(tmp_path):
    own = tmp_path/'outputs/pallet_mask_under50_requests_v5'; rows = {}
    for version, staged_count, issued_count in ((1, 18, 10), (2, 18, 9), (3, 16, 7), (4, 13, 6)):
        records = []
        for n in range(staged_count):
            key = f'{version:022x}{n:02x}'; rows[key] = row(key); records.append(dict(target_key=key, approved=False))
        root = tmp_path/f'outputs/pallet_mask_under50_requests_v{version}'
        write(root/'internal/shortlist.jsonl', records, True); write(root/'requests.jsonl', records[:issued_count], True)
    write(own/'internal/shortlist.jsonl', [dict(target_key='f'*24)], True)
    hashes, keys = audit.geometry.prior_inspections(tmp_path, own, rows)
    assert len(keys) == 65 and len(hashes) == 8
    assert [pins['staged_count'] for pins in audit.SEALED_PACK_PINS.values()] == [18, 18, 16, 13]
    assert [pins['request_count'] for pins in audit.SEALED_PACK_PINS.values()] == [10, 9, 7, 6]


@pytest.mark.parametrize('attack', ['key', 'frame', 'bytes'])
def test_protected_native_key_frame_and_bytes_are_not_reused(staged, attack):
    old = row('b'*24)
    if attack == 'frame':
        old['frame_id'] = staged['row']['frame_id']
    (staged['formal']/old['image']).write_bytes((staged['formal']/staged['row']['image']).read_bytes())
    rows = {KEY: staged['row'], old['target_key']: old}; forbidden = {KEY if attack == 'key' else old['target_key']}
    with pytest.raises(ValueError, match='protected source|duplicate image bytes'):
        audit.geometry.check_staged(staged['root'], [staged['record']], {KEY: staged['decision']}, rows,
            staged['formal'], staged['evidence'], dict(current={}, histories={}), forbidden)


@pytest.fixture
def public_pack(staged, monkeypatch):
    import fontTools.ttLib
    root = staged['root']; proposal = export(staged)
    (root/'FONT_LICENSE.txt').write_bytes((audit.PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt').read_bytes())
    (root/'report-font.otf').write_bytes(b'synthetic font')
    page = ('少于50 · 真实人工轮廓 · 每类最多2张 · 第15版 · 已预标注 · 保存前不计覆盖 · '
        '不自动确认GT、训练或机器人资格 · 有效四点保持四点 · 不为传播模板强行增点\n'
        + '、'.join(f'Class {c}：{audit.EXPECTED_COUNTS[c]}份' for c in audit.CLASSES)
        + '<select id="request-filter"><option value="">全部</option>'
        + ''.join(f'<option value="{c}">{c}</option>' for c in audit.CLASSES) + '</select>'
        + f'<article id="target-{KEY}" data-class="11"><img src="cases/{KEY}.png">'
        + f'<a href="images/{KEY}.png">原图</a><a href="masks/{KEY}.png">掩膜</a><a href="labelme/{KEY}.json">LabelMe</a></article>')
    (root/'report_zh.html').write_text(page); glyphs = {ord(c) for c in page}
    class Font:
        def __init__(self, path):
            assert path == root/'report-font.otf'
        def __enter__(self):
            return self
        def __exit__(self, *args):
            return False
        def getBestCmap(self):
            return {value: str(value) for value in glyphs}
    monkeypatch.setattr(fontTools.ttLib, 'TTFont', Font)
    manifest = dict(public_assets={name: audit.digest(root/name) for name in
        ('report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt', *(f'{folder}/{KEY}.{ext}' for folder, ext in
        (('images', 'png'), ('cases', 'png'), ('masks', 'png'), ('labelme', 'json'))))})
    return root, manifest, [proposal], glyphs


def test_public_page_contains_only_four_current_counts_and_four_filters(public_pack):
    root, manifest, proposals, _ = public_pack
    assert audit.check_public(root, manifest, proposals) == set(manifest['public_assets'])


@pytest.mark.parametrize('attack', ['class17count', 'class20count', 'class17filter', 'class20filter', 'private_link', 'wrong_count', 'missing_asset', 'font'])
def test_public_old_scope_private_assets_stale_counts_or_missing_glyphs_are_rejected(public_pack, attack):
    root, manifest, proposals, glyphs = public_pack; page = (root/'report_zh.html').read_text()
    if attack in ('class17count', 'class20count'):
        page += f'Class {17 if attack == "class17count" else 20}：50份'
    elif attack in ('class17filter', 'class20filter'):
        c = 17 if attack == 'class17filter' else 20; page = page.replace('</select>', f'<option value="{c}">{c}</option></select>')
    elif attack == 'private_link':
        page += '<a href="internal/shortlist.jsonl">private</a>'
    elif attack == 'wrong_count':
        page = page.replace('Class 11：25份', 'Class 11：23份')
    elif attack == 'missing_asset':
        manifest['public_assets'].pop(f'masks/{KEY}.png')
    else:
        glyphs.remove(ord('少'))
    (root/'report_zh.html').write_text(page); manifest['public_assets']['report_zh.html'] = audit.digest(root/'report_zh.html')
    with pytest.raises(ValueError):
        audit.check_public(root, manifest, proposals)


def source_binding_case(tmp_path, monkeypatch):
    monkeypatch.setattr(audit, 'PROJECT', tmp_path); snapshot = tmp_path/'outputs/pallet_mask_continuation_sources_v8'
    write(snapshot/'audit.json', dict(source='completed synthetic v8')); write(snapshot/'private/source_catalog.jsonl', [], True)
    value = audit.digest(snapshot/'audit.json'); monkeypatch.setattr(audit, 'SOURCE_AUDIT_SHA256', value)
    inputs = dict(source_audit_sha256=value, continuation_source_audit_sha256=value,
        continuation_source_directory='outputs/pallet_mask_continuation_sources_v8',
        continuation_source_catalog_sha256=audit.digest(snapshot/'private/source_catalog.jsonl'), excluded_classes_already_at_50=[17, 20],
        previous_batch_directory='outputs/pallet_mask_under50_requests_v4', previous_batch_actual_completed=6,
        previous_batch_manifest_sha256=audit.SEALED_PACK_PINS['pallet_mask_under50_requests_v4']['manifest_sha256'],
        source_snapshot_never_added_to_frozen_training=True)
    manifest = dict(source_audit_sha256=value, continuation_source_audit_sha256=value,
        excluded_classes_already_at_50=[17, 20], previous_batch_actual_completed=6)
    return inputs, manifest, snapshot


def test_explicit_v8_audit_catalog_and_previous_six_v4_saves_are_bound(tmp_path, monkeypatch):
    audit.check_source_binding(*source_binding_case(tmp_path, monkeypatch))


@pytest.mark.parametrize('field', ['source_audit_sha256', 'continuation_source_audit_sha256', 'continuation_source_directory',
    'continuation_source_catalog_sha256', 'excluded_classes_already_at_50', 'previous_batch_directory',
    'previous_batch_actual_completed', 'previous_batch_manifest_sha256', 'source_snapshot_never_added_to_frozen_training'])
def test_stale_audit_exclusion_or_v4_manifest_claims_fail(tmp_path, monkeypatch, field):
    inputs, manifest, snapshot = source_binding_case(tmp_path, monkeypatch); inputs[field] = audit.geometry.QUALITY_SEAL_SHA256
    with pytest.raises(ValueError):
        audit.check_source_binding(inputs, manifest, snapshot)


def source_claims_case():
    summary, catalog, pose, gallery_store, extension, manifests, trained = fourth_source_claims_case()
    catalog.extend(dict(row=dict(final_class_id=11)) for _ in range(6)); extension['new_distinct_saved_keys'] = [f'{n:024x}' for n in range(32)]
    manifests['pallet_mask_under50_requests_v4'] = 'g'
    summary.update(total_contours=1516, gallery_contours=1034, gallery_events=1139, class_counts={'11': 1516},
        new_distinct_saved_keys=copy.deepcopy(extension['new_distinct_saved_keys']), source_registry_task_manifests=copy.deepcopy(manifests))
    return summary, catalog, pose, gallery_store, extension, manifests, trained


def test_source_summary_claims_recomputed_against_current_evidence():
    audit.check_source_claims(*source_claims_case())


@pytest.mark.parametrize('attack', ['stale1510', 'old1133', 'not32', 'training_changed', 'no_v4', 'fingerprint', 'accuracy', 'bool_writes'])
def test_untrue_source_denominator_or_training_claims_fail_closed(attack):
    args = source_claims_case(); summary = args[0]
    if attack == 'stale1510':
        summary['total_contours'] = 1510
    elif attack == 'old1133':
        summary['gallery_events'] = 1133
    elif attack == 'not32':
        summary['new_distinct_saved_keys'].pop()
    elif attack == 'training_changed':
        summary['frozen_training_dataset_modified'] = True
    elif attack == 'no_v4':
        summary['source_registry_task_manifests'].pop('pallet_mask_under50_requests_v4')
    elif attack == 'fingerprint':
        summary['gallery_fingerprint']['schema_sha256'] = 'old'
    elif attack == 'accuracy':
        summary['state'] = 'passed_accuracy'
    else:
        summary['production_annotation_writes'] = False
    with pytest.raises(ValueError):
        audit.check_source_claims(*args)


def test_four_point_native_draft_remains_unconfirmed_not_old_seed_or_automatic_training(staged):
    proposal, task = draft(staged); image_sha = audit.digest(staged['formal']/staged['row']['image'])
    audit.geometry.check_draft(proposal, task, staged['record'], staged['decision'], 'e'*64, 'f'*64, image_sha)
    audit.geometry.check_exports(staged['root'], export(staged), staged['record'], image_sha)
    assert len(proposal['polygon']) == 4 and all(proposal[field] is False for field in audit.geometry.FALSE_FLAGS)


@pytest.mark.parametrize('split', ['val', 'test'])
def test_class19_formal_holdout_split_is_preserved_not_relabeled_as_training(staged, split):
    staged['row'].update(final_class_id=19, split=split)
    proposal, task = draft(staged); proposal['class_id'] = task['class_id'] = 19
    image_sha = audit.digest(staged['formal']/staged['row']['image'])
    audit.geometry.check_draft(proposal, task, staged['record'], staged['decision'], 'e'*64, 'f'*64, image_sha)
    assert proposal['source']['split'] == split and proposal['automatic_training_eligible'] is False
    proposal['source']['split'] = 'train'
    with pytest.raises(ValueError):
        audit.geometry.check_draft(proposal, task, staged['record'], staged['decision'], 'e'*64, 'f'*64, image_sha)


@pytest.fixture
def frozen_training(tmp_path, monkeypatch):
    root = tmp_path/'frozen-training'; records = [dict(target_key=f'{n:024x}') for n in range(229)]
    write(root/'private/training_records.jsonl', records, True)
    for directory in ('dataset', 'dataset_rfdetr', 'private/native_masks'):
        path = root/directory/'synthetic.png'; path.parent.mkdir(parents=True); path.write_bytes(b'frozen native bytes')
    files = audit.inventory(root)
    manifest = dict(files=files, **dict.fromkeys(('automatic_training_eligible', 'ground_truth_eligible',
        'human_mask_confirmed', 'human_pose_confirmed', 'robot_command_eligible'), False)); write(root/'dataset_manifest.json', manifest)
    monkeypatch.setattr(audit, 'TRAINING_PINS', {name: audit.digest(root/name) for name in ('dataset_manifest.json', 'private/training_records.jsonl')})
    return root


def test_frozen229_source_keys_and_all_dataset_labels_remain_read_only(frozen_training):
    before = audit.inventory(frozen_training); assert audit.check_frozen_training(frozen_training)
    assert audit.inventory(frozen_training) == before


@pytest.mark.parametrize('attack', ['add_label', 'change_label', 'add_source_key', 'change_source_key'])
def test_new_saved_human_sources_do_not_automatically_rewrite_frozen_training(frozen_training, attack):
    if attack == 'add_label':
        (frozen_training/'dataset/new-label.json').write_text('{}')
    elif attack == 'change_label':
        (frozen_training/'private/native_masks/synthetic.png').write_bytes(b'newer human revision')
    else:
        path = frozen_training/'private/training_records.jsonl'; records = audit.read_jsonl(path)
        if attack == 'add_source_key':
            records.append(dict(target_key='f'*24))
        else:
            records[0]['target_key'] = 'f'*24
        write(path, records, True)
    with pytest.raises(ValueError):
        audit.check_frozen_training(frozen_training)


@pytest.fixture
def seal_root(tmp_path, monkeypatch):
    monkeypatch.setattr(audit, 'PROJECT', tmp_path); root = tmp_path/'outputs/pallet_mask_under50_requests_v5'
    write(root/'manifest.json', {}); return root


def test_no_ready_notification_means_no_audit_or_seals(seal_root):
    with pytest.raises(ValueError, match='READY'):
        audit.seal(seal_root, auditor=lambda _: pytest.fail('unready staging audited'))
    assert set(audit.inventory(seal_root)) == {'manifest.json'}


def test_ready_success_creates_identical_private_exclusive_seals(seal_root):
    result = dict(state='passed', request_count=6, semantic_contour_accuracy_established=False)
    audit.seal(seal_root, producer_complete=True, auditor=lambda _: result)
    assert (seal_root/audit.SEALS[0]).read_bytes() == (seal_root/audit.SEALS[1]).read_bytes() == audit.canonical(result)+b'\n'
    assert all((seal_root/name).stat().st_mode & 0o777 == 0o600 for name in audit.SEALS)
    with pytest.raises(ValueError, match='Never overwrite'):
        audit.seal(seal_root, producer_complete=True, auditor=lambda _: result)


@pytest.mark.parametrize('state', ['failed', 'pending', 'passed_event_provenance'])
def test_failed_or_partial_audit_never_creates_seals(seal_root, state):
    with pytest.raises(ValueError, match='did not pass'):
        audit.seal(seal_root, producer_complete=True, auditor=lambda _: dict(state=state))
    assert set(audit.inventory(seal_root)) == {'manifest.json'}


def test_second_seal_race_preserves_other_writer_and_rolls_back_only_own_first_file(seal_root):
    def raced(root):
        (root/'independent_verification.json').write_bytes(b'other writer'); return dict(state='passed')
    with pytest.raises(FileExistsError):
        audit.seal(seal_root, producer_complete=True, auditor=raced)
    assert not (seal_root/'verification.json').exists() and (seal_root/'independent_verification.json').read_bytes() == b'other writer'


def test_old_output_and_symlink_alias_cannot_receive_v5_seals(seal_root):
    old = seal_root.parent/'pallet_mask_under50_requests_v4'; write(old/'manifest.json', {})
    alias = seal_root.parent/'alias'; alias.symlink_to(seal_root, target_is_directory=True)
    for root in (old, alias):
        with pytest.raises(ValueError, match='exact new v5'):
            audit.seal(root, producer_complete=True, auditor=lambda _: dict(state='passed'))
