"""Independent third under50 worklist audit, including all19 prior real saves.

No producer/builder is imported, no sealed verifier globals are changed, and no
production editor save is performed. A pass certifies raw provenance and export
consistency, never semantic contour accuracy or ground truth. Await explicit READY.
"""
from __future__ import annotations

import argparse
from collections import Counter
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import sys

sys.dont_write_bytecode = True
PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from scripts import verify_mask_under50_requests as geometry
from scripts import verify_mask_under50_requests_v2 as continuation
from scripts import verify_mask_quality_recovery as sources

ROOT = PROJECT/'outputs/pallet_mask_under50_requests_v3'
SNAPSHOT = PROJECT/'outputs/pallet_mask_continuation_sources_v4'
QUALITY, PARENT, POSE, GALLERY = geometry.QUALITY, geometry.PARENT, geometry.POSE, geometry.GALLERY
CLASSES, SEALS = geometry.CLASSES, geometry.SEALS
EXPECTED_COUNTS = {11: 21, 12: 47, 16: 38, 17: 47, 19: 42, 20: 49}
SOURCE_AUDIT_SHA256 = '58b59bee8412ef0eefe5cbfe07a1c53805e0f94a8bf0ffb9a3b2f9ae74030b84'
TRAINING_RECORDS = continuation.TRAINING_RECORDS
TRAINING_RECORDS_SHA256 = '41cdc85d7ac6e2a77c41ac191c7830b3a5420af424fce7c6f0db990f6d95d658'
SEALED_PACK_PINS = {
    'pallet_mask_under50_requests_v1': dict(manifest_sha256='2b34627da485b88a1a198511b7d549711b0bfd09b3c4b1b904c43c8be2bc2bea',
        verification_sha256='87d868e53d396acf37a161019b71144fbff906c62091e7d4b9d68458f9083e5a', request_count=10, event_count=10),
    'pallet_mask_under50_requests_v2': dict(manifest_sha256='d124294bd75ea7a8caccbfc1d3fc8129fa26629734309f32dd22ae5f80c05894',
        verification_sha256='4faa3fd5193c02319a746064ecbe9f699dccd98bd10cef03826e119acb69625b', request_count=9, event_count=11),
}
HELPER_PINS = {**continuation.HELPER_PINS,
    'scripts/verify_mask_under50_requests_v2.py': 'dd2b8dcbe87d887b50a88176927a3c733a9b67f90ea30e222b084387b7a4042c',
    'tests/test_verify_mask_under50_requests_v2.py': 'd1025b110c16a697ad68cd734bc5c899f3e9425ca5feeb83e807ffb37f70de12',
    'scripts/build_mask_under50_requests_v2.py': '407e2f3fdffdc5a57fa3c84e5d987245bdf6e6fe3d0386bd6b9e383aefa30d5c',
}
HISTORICAL_SNAPSHOTS = {
    'pallet_mask_continuation_sources_v1': dict(audit_sha256=continuation.EARLIER_AUDIT_SHA256, current_count=1002, event_count=1105),
    'pallet_mask_continuation_sources_v2': dict(audit_sha256=continuation.SOURCE_AUDIT_SHA256, current_count=1012, event_count=1115),
}
require, read, read_jsonl = sources.require, sources.read, sources.read_jsonl
canonical, sha, digest = sources.canonical, sources.sha, sources.digest
inventory, member, equal = sources.inventory, sources.member, sources.equal


def check_public(root, manifest, proposals, expected_counts=EXPECTED_COUNTS):
    """Count scope is explicit for each frozen pack, without global overrides."""
    allowed = {'report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'}
    for proposal in proposals:
        for folder, ext in (('images', 'png'), ('cases', 'png'), ('masks', 'png'), ('labelme', 'json')):
            allowed.add(f'{folder}/{proposal["target_key"]}.{ext}')
    require(set(manifest['public_assets']) == allowed, 'Public asset allowlist differs')
    for name, expected in manifest['public_assets'].items():
        require(digest(member(root, name)) == expected, 'Public asset changed: '+name)
    page = member(root, 'report_zh.html').read_text(encoding='utf-8')
    require(all(text in page for text in ('少于50', '真实人工轮廓', '每类最多2张', '第15版', '已预标注', '保存前不计覆盖',
        '不自动确认GT、训练或机器人资格', '有效四点保持四点', '不为传播模板强行增点')), 'Missing real-human/draft-only report scope')
    require('第三批多类别' not in page and not any(token in page for token in ('existing_pose_current_payload', 'current_payload_raw',
        'human_event_payload_raw', 'access_key', 'access_code', 'selected_faces', 'ruler', 'fetch(')), 'Private payload or old third-batch label exposed')
    require(all(f'Class {c}：{expected_counts[c]}份' in page for c in CLASSES), 'Wrong real-human counts for this pack')
    parsed = geometry.PageInventory(page)
    equal(parsed.articles, [(f'target-{p["target_key"]}', str(p['class_id'])) for p in proposals], 'report_target_cards')
    equal(parsed.options, ['']+[str(c) for c in CLASSES], 'under50_class_filter')
    require(all(name in allowed for name in parsed.assets), 'Private/unallowlisted report link')
    from fontTools.ttLib import TTFont
    with TTFont(member(root, 'report-font.otf')) as font:
        require({ord(c) for c in page if '\u3400' <= c <= '\u9fff'} <= set(font.getBestCmap()), 'Chinese glyph missing')
    require(digest(root/'FONT_LICENSE.txt') == digest(PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt'), 'Font license differs')
    return allowed


def discover_sealed_packs(outputs, own_root):
    result = {}
    for root in sorted(outputs.glob('pallet_mask_under50_requests_v*')):
        if root == own_root:
            continue
        flags = [(root/name).is_file() for name in SEALS]
        require(flags[0] == flags[1], 'Half-sealed prior under50 pack')
        if not any(flags):
            continue
        require(root.name in SEALED_PACK_PINS, 'Unpinned sealed under50 pack; refresh the independent registry')
        pins = SEALED_PACK_PINS[root.name]
        for name, field in (('manifest.json', 'manifest_sha256'), ('verification.json', 'verification_sha256'),
                ('independent_verification.json', 'verification_sha256')):
            require(digest(member(root, name)) == pins[field], 'Frozen under50 pack pin differs: '+root.name+'/'+name)
        result[root.name] = root
    require(result.keys() == SEALED_PACK_PINS.keys(), 'All sealed prior under50 packs must be registered')
    return result


def extend_registry(pack_roots, rows, formal_sha, pose, publication, registry, evidence):
    extended, inspected, tasks = dict(registry), set(), {}
    for namespace, root in pack_roots.items():
        pins = SEALED_PACK_PINS[namespace]
        manifest, seal, inputs = read(root/'manifest.json'), read(root/'verification.json'), read(root/'input_manifest.json')
        require(seal['state'] == 'passed' and seal['preannotations_verified'] is True
            and seal['manifest_sha256'] == pins['manifest_sha256'], 'Prior independent task seal differs')
        for field, name in (('proposals_sha256', 'proposals.jsonl'), ('requests_sha256', 'requests.jsonl'),
                ('input_manifest_sha256', 'input_manifest.json'), ('decisions_sha256', 'internal/build_decisions.json')):
            require(manifest[field] == digest(root/name), 'Prior source/geometry/decision binding differs')
        for field in ('proposals_sha256', 'requests_sha256', 'formal_manifest_sha256', 'public_assets'):
            equal(seal[field], manifest[field], 'prior_seal_manifest.'+field)
        require(manifest['formal_manifest_sha256'] == formal_sha and all(manifest['parent_'+field] == publication[field]
            for field in ('manifest_sha256', 'verification_sha256', 'proposals_sha256')), 'Prior task publication15/formal binding differs')
        proposals, requests = read_jsonl(root/'proposals.jsonl'), read_jsonl(root/'requests.jsonl')
        drafts, request_map = sources.indexed(proposals), sources.indexed(requests)
        require(len(drafts) == len(request_map) == manifest['request_count'] == seal['request_count'] == pins['request_count']
            and drafts.keys() == request_map.keys(), 'Prior request inventory differs')
        staged = sources.indexed(read_jsonl(root/'internal/shortlist.jsonl'))
        require(len(staged) == 18 and digest(root/'internal/shortlist.jsonl') == inputs['shortlist_sha256'], 'Prior18 inspections changed')
        decisions = read(root/'internal/build_decisions.json')['decisions']
        require(set(decisions) == staged.keys() and drafts.keys() <= staged.keys(), 'Prior own staged decisions differ')
        check_public(root, manifest, proposals, {c: inputs['actual_class_counts'][str(c)] for c in CLASSES})
        require(not inspected & staged.keys(), 'Repeated inspected image across sealed prior packs')
        inspected.update(staged); tasks[namespace] = set(drafts)
        for key, proposal in drafts.items():
            row = rows[key]; record = staged[key]; current = pose['current'].get(key)
            require(proposal['source'] == record['source'] == row, 'Prior formal source differs')
            equal(record['existing_pose_current_payload'], current[2] if current else None, 'prior_all_pose_fields')
            equal(record['existing_pose_revision'], current[0] if current else 0, 'prior_pose_revision')
            equal(record['existing_pose_payload_sha256'], sha(current[2]) if current else None, 'prior_pose_snapshot')
            image_sha = digest(member(evidence.formal, row['image']))
            geometry.check_draft(proposal, request_map[key], record, decisions[key], formal_sha, digest(root/'input_manifest.json'), image_sha)
            geometry.check_exports(root, proposal, record, image_sha); evidence.image(row['frame_id'])
            identity = (15, sha(proposal), key)
            require(identity not in extended, 'Duplicate publication/proposal-hash/target registry triple')
            extended[identity] = dict(kind='independent_preannotation', namespace=namespace, proposal=proposal, path=root)
    require(len(inspected) == 36 and len(set.union(*tasks.values())) == 19, 'Exact36 inspected/19 issued prior images required')
    return extended, inspected, tasks


def check_fresh_catalog(snapshot, baseline_catalog, pose, gallery, rows, publications, registry, formal_sha, evidence):
    catalog = read_jsonl(snapshot/'private/source_catalog.jsonl'); records = sources.indexed(catalog)
    require(len(records) == len({r['row']['frame_id'] for r in catalog}) == 1503, '1503 distinct current human source images required')
    pose_sources = {r['target_key']: r for r in baseline_catalog if r['origin'] == 'saved_pose'}
    require(len(pose_sources) == 482 and len(gallery['current']) == 1021
        and records.keys() == pose_sources.keys() | gallery['current'].keys()
        and not pose_sources.keys() & gallery['current'].keys(), 'Actual482 pose/1021 gallery partition differs')
    for key, record in pose_sources.items():
        value, _ = sources.exact_latest(pose, key)
        require(record['payload_sha256'] == sha(value) and record['polygon'] == value['polygon'], 'Original pose contour changed')
        equal(records[key], record, 'frozen_saved_pose_catalog.'+key)
    references, event_audit = {}, []
    for event_id, key, revision, raw in gallery['events']:
        require(key in rows, 'Foreign gallery target')
        value = sources.loads(raw); reference = sources.resolve_event(value, publications, registry)
        sources.check_gallery_event(value, rows[key], reference, publications[value['proposal_publication']], formal_sha, evidence)
        require(value['revision'] == revision, 'Relational event revision differs')
        references[event_id] = reference
        event_audit.append(dict(event_id=event_id, target_key=key, revision=revision, payload_raw_sha256=sources.raw_sha(raw),
            proposal_publication=value['proposal_publication'], base_proposal_id=value['base_proposal_id'],
            namespace=reference.get('namespace'), event_specific_source_verified=True))
    for key in gallery['current']:
        value, last = sources.exact_latest(gallery, key); history = gallery['histories'][key]; row = rows[key]
        require(not sources.original_rectangle(value['polygon'], row), 'Original rectangle counted as saved human contour')
        sources.unconfirmed(value); sources.polygon(value['polygon'], row['size'])
        expected = dict(target_key=key, row=row, polygon=value['polygon'], origin='saved_gallery', revision=value['revision'],
            payload_sha256=sha(value), event_raw_sha256=sources.raw_sha(last[2]), initial_polygon=history[0][3]['proposal_polygon'],
            batch=references[last[0]].get('namespace') or 'historical_gallery', history_revisions=len(history), actual_saved_research_reference_not_GT=True)
        equal(records[key], expected, 'fresh_raw_latest_catalog.'+key)
    equal(read_jsonl(snapshot/'private/event_binding_audit.jsonl'), event_audit, 'every_raw_event_triple_binding')
    return catalog, references


def check_saved_batches(gallery, baseline, task_keys, registry, references):
    all_tasks = set.union(*task_keys.values())
    extension = continuation.check_revision_extension(baseline, gallery, all_tasks)
    require(len(extension['changed_baseline_current_keys']) == 14 and extension['appended_gallery_events'] == 38
        and len(extension['new_distinct_saved_keys']) == 19, 'Expected38 new events:17 old revisions plus21 saves of19 new images')
    appended = gallery['events'][len(baseline['events']):]
    routes = Counter(references[e[0]].get('namespace') for e in appended)
    expected_routes = {'v3': 17, **{name: SEALED_PACK_PINS[name]['event_count'] for name in task_keys}}
    equal(dict(routes), expected_routes, 'all38_event_specific_package_routes')
    completed = {}
    for namespace, keys in task_keys.items():
        require(len(keys) == SEALED_PACK_PINS[namespace]['request_count'], 'Prior completion denominator differs')
        for key in keys:
            history = gallery['histories'][key]
            require(history[0][1] == 1, 'First genuine saved task revision must be1')
            value, latest = sources.exact_latest(gallery, key)
            for event_id, _, _, old in history:
                reference = references[event_id]; identity = (15, old['base_proposal_id'], key)
                require(reference['kind'] == 'independent_preannotation' and reference.get('namespace') == namespace
                    and identity in registry and registry[identity] == reference, 'Saved task event has wrong exact package/hash/key binding')
                require(old.get('event_kind') == 'human_mask_gallery_revision' and old.get('human_edited') is True,
                    'Saved task history contains fabricated assistant/human event')
            require(value['polygon'] != references[latest[0]]['proposal']['polygon'], 'Current real saved task is not changed from its draft')
        completed[namespace] = len(keys)
    return extension, completed


def check_count_basis(catalog, inputs, manifest):
    require(len(catalog) == len({r['target_key'] for r in catalog}) == len({r['row']['frame_id'] for r in catalog}) == 1503,
        '1503 distinct saved human contours required, not1494 or1550 machine coverage')
    counts = Counter(r['row']['final_class_id'] for r in catalog)
    require(set(counts) == set(range(1, 23)) and all(type(c) is int for c in counts)
        and tuple(c for c in range(1, 23) if counts[c] < 50) == CLASSES
        and {c: counts[c] for c in CLASSES} == EXPECTED_COUNTS, 'Current under50 class counts differ')
    equal(inputs['actual_counted_saved_basis'], 1503, 'real1503_human_sources')
    equal(inputs['actual_class_counts'], {str(c): n for c, n in counts.items()}, 'all22_actual_class_counts')
    equal(manifest['actual_human_saved_counts_before'], inputs['actual_class_counts'], 'manifest_current_human_counts')
    for value in (inputs, manifest):
        equal(value['maximum_issued_per_class'], 2, 'pilot_class_maximum')
        equal(value['target_per_class_this_pilot'], 50, 'pilot_target')
        equal(value['class_scope'], geometry.CLASS_SCOPE, 'real_saved_under50_scope')
    equal(inputs['shortlisted_classes'], list(CLASSES), 'staged_class_scope')
    equal(manifest['filter_classes'], list(CLASSES), 'filter_class_scope')
    return counts


def check_source_claims(summary, catalog, pose, gallery, extension, task_manifests, trained_changes):
    equal(summary['state'], 'passed_event_provenance_and_distinct_saved_count_not_contour_accuracy', 'source_audit_scope')
    for field, value in dict(total_contours=1503, gallery_contours=1021, gallery_events=1126, pose_contours=482,
            old_raw_event_prefix_preserved=1088, production_annotation_writes=0).items():
        equal(summary[field], value, 'source_summary.'+field)
    equal(summary['pose_fingerprint'], pose['fingerprint'], 'pose_snapshot_fingerprint')
    equal(summary['gallery_fingerprint'], gallery['fingerprint'], 'gallery_snapshot_fingerprint')
    equal(summary['class_counts'], {str(c): n for c, n in Counter(r['row']['final_class_id'] for r in catalog).items()}, 'source_class_counts')
    require(len(summary['changed_baseline_current_keys']) == len(set(summary['changed_baseline_current_keys']))
        and sorted(summary['changed_baseline_current_keys']) == extension['changed_baseline_current_keys'], 'Changed old revisions misreported')
    equal(summary['new_distinct_saved_keys'], extension['new_distinct_saved_keys'], '19_actual_new_distinct_images')
    for field in ('actual_changed_baseline_revisions_not_new_distinct_images', 'baseline_current_revisions_preserved_in_history'):
        equal(summary[field], True, field)
    equal(summary['frozen_training_dataset_modified'], False, 'frozen_training_not_rewritten')
    equal(summary['source_registry_task_manifests'], task_manifests, 'source_task_registry_manifests')
    equal(summary['trained_reference_keys_with_newer_human_revision'], trained_changes, 'three_frozen_training_references_now_revised')


def check_sources(snapshot, parent_manifest, pack_roots):
    require(digest(snapshot/'audit.json') == SOURCE_AUDIT_SHA256, 'Exact fresh source audit changed')
    summary = read(snapshot/'audit.json')
    require(summary['source_catalog_sha256'] == digest(snapshot/'private/source_catalog.jsonl')
        and summary['code_sha256'] == digest(PROJECT/'pallet/mask_review_continuation.py'), 'Fresh source catalog/producer binding differs')
    require(digest(QUALITY/'independent_verification.json') == geometry.QUALITY_SEAL_SHA256, 'Historical independent quality seal changed')
    seal, result = read(QUALITY/'independent_verification.json'), read(QUALITY/'result.json')
    require(seal['state'] == 'passed' and seal['result_sha256'] == digest(QUALITY/'result.json')
        and seal['source_catalog_sha256'] == digest(QUALITY/'private/source_catalog.jsonl'), 'Historical source evidence binding differs')
    for name, expected in result['output_artifacts'].items():
        require(digest(member(QUALITY, name)) == expected, 'Historical quality artifact changed: '+name)
    for name, expected in {**seal['code_sha256'], **seal['frozen_code_sha256'], **geometry.FROZEN_INTERFACE_PINS, **HELPER_PINS}.items():
        require(digest(member(PROJECT, name)) == expected, 'Frozen code/helper/qualification changed: '+name)
    old_pose = sources.read_store(QUALITY/'private/pose_snapshot.sqlite3', 'pose', True)
    old_gallery = sources.read_store(QUALITY/'private/gallery_snapshot.sqlite3', 'gallery', True)
    pose = sources.read_store(snapshot/'private/pose_snapshot.sqlite3', 'pose', True)
    gallery = sources.read_store(snapshot/'private/gallery_snapshot.sqlite3', 'gallery', True)
    equal(pose, old_pose, 'all4946_pose_records11926_events_and_private_fields_unchanged')
    require((len(pose['current']), len(pose['events']), len(old_gallery['current']), len(old_gallery['events']),
        len(gallery['current']), len(gallery['events'])) == (4946, 11926, 1002, 1088, 1021, 1126), 'Current/historical source denominator differs')
    for kind, store in (('pose', old_pose), ('gallery', old_gallery)):
        equal(store['fingerprint'], seal['source_fingerprints'][kind], 'historical_seal_fingerprint_'+kind)
        equal(store['fingerprint'], result['source_fingerprints'][kind], 'historical_result_fingerprint_'+kind)
    for kind, path, store in (('pose', POSE, pose), ('gallery', GALLERY, gallery)):
        equal(sources.read_store(path, kind), store, 'exact_fresh_preactivation_live_'+kind)
        for key in store['current']:
            sources.exact_latest(store, key)
    formal, rows, frames = sources.load_formal(parent_manifest); evidence = sources.NativeEvidence(formal, rows, frames)
    publications, registry, old_task_pins = sources.registries(rows, parent_manifest['formal_manifest_sha256'], pose)
    baseline_catalog = read_jsonl(QUALITY/'private/source_catalog.jsonl')
    sources.check_catalog(QUALITY, baseline_catalog, old_pose, old_gallery, rows, publications, registry,
        parent_manifest['formal_manifest_sha256'], evidence)
    equal(result['source_summary']['task_inputs'], old_task_pins, 'historical_old_task_pins')
    equal(result['source_summary']['publication_inputs'], {str(v): {field: p[field] for field in
        ('manifest_sha256', 'proposals_sha256', 'verification_sha256')} for v, p in publications.items()}, 'all_historical_publication_pins')
    registry, inspected, task_keys = extend_registry(pack_roots, rows, parent_manifest['formal_manifest_sha256'], pose, publications[15], registry, evidence)
    catalog, references = check_fresh_catalog(snapshot, baseline_catalog, pose, gallery, rows, publications, registry,
        parent_manifest['formal_manifest_sha256'], evidence)
    extension, completed = check_saved_batches(gallery, old_gallery, task_keys, registry, references)
    for name, pins in HISTORICAL_SNAPSHOTS.items():
        path = PROJECT/'outputs'/name
        require(digest(path/'audit.json') == pins['audit_sha256'], 'Prior continuation audit changed')
        earlier_pose = sources.read_store(path/'private/pose_snapshot.sqlite3', 'pose', True)
        earlier_gallery = sources.read_store(path/'private/gallery_snapshot.sqlite3', 'gallery', True)
        equal(earlier_pose, pose, 'prior_snapshot_pose_preserved')
        require(len(earlier_gallery['current']) == pins['current_count'] and len(earlier_gallery['events']) == pins['event_count'], 'Prior snapshot denominator differs')
        expected_new = set(gallery['current'])-set(earlier_gallery['current'])
        prior_extension = continuation.check_revision_extension(earlier_gallery, gallery, expected_new)
        require(not prior_extension['changed_baseline_current_keys'], 'Later saves unexpectedly changed earlier snapshot current images')
    require(digest(TRAINING_RECORDS) == TRAINING_RECORDS_SHA256 and len(read_jsonl(TRAINING_RECORDS)) == 229, 'Frozen229 training records changed')
    trained_changes = continuation.check_trained_revisions(TRAINING_RECORDS, baseline_catalog, extension['changed_baseline_current_keys'])
    require(len(trained_changes) == 3, 'Exactly three frozen training references have newer human revisions')
    manifests = {f'v{n}': digest(PROJECT/f'outputs/pallet_mask_preannotated_requests_v{n}/manifest.json') for n in (1, 2, 3)}
    manifests.update({name: digest(root/'manifest.json') for name, root in pack_roots.items()})
    check_source_claims(summary, catalog, pose, gallery, extension, manifests, trained_changes)
    for name in ('private', 'private/pose_snapshot.sqlite3', 'private/gallery_snapshot.sqlite3', 'private/source_catalog.jsonl'):
        require((snapshot/name).stat().st_mode & 0o077 == 0, 'Fresh private source evidence is not private')
    return dict(summary=summary, baseline_seal=seal, formal=formal, rows=rows, evidence=evidence, pose=pose, gallery=gallery,
        catalog=catalog, extension=extension, inspected=inspected, completed=completed, trained_changes=trained_changes)


def check_source_binding(inputs, manifest, snapshot=SNAPSHOT):
    expected = digest(snapshot/'audit.json')
    require(expected == SOURCE_AUDIT_SHA256, 'Unrecognized source audit')
    equal(inputs['source_audit_sha256'], expected, 'explicit_fresh_input_audit_binding')
    equal(manifest['source_audit_sha256'], expected, 'explicit_fresh_manifest_audit_binding')
    if 'source_quality_audit_sha256' in inputs:
        equal(inputs['source_quality_audit_sha256'], geometry.QUALITY_SEAL_SHA256, 'historical_quality_not_fresh_audit')


def check_staged_limits(staged, counts):
    staged_counts = Counter(r['class_id'] for r in staged)
    require(all(c in CLASSES and n <= min(3, 50-counts[c]) for c, n in staged_counts.items()),
        'Staged class gap exceeded; class20 permits only1')


def audit(root=ROOT, parent=PARENT, snapshot=SNAPSHOT):
    root, parent, snapshot = Path(root), Path(parent), Path(snapshot)
    before = inventory(root); require(not set(SEALS) & before.keys(), 'Preserve existing v3 seals')
    manifest, inputs, parent_manifest = read(root/'manifest.json'), read(root/'input_manifest.json'), read(parent/'manifest.json')
    pack_roots = discover_sealed_packs(PROJECT/'outputs', root)
    protected_roots = geometry.old_evidence_roots(PROJECT, root, parent, QUALITY, inputs['prior_request_inventories_sha256'])
    protected_roots.update(pack_roots.values()); protected_roots.add(snapshot)
    protected_roots.update(PROJECT/'outputs'/name for name in HISTORICAL_SNAPSHOTS)
    protected_roots.update(path for path in (PROJECT/'outputs').glob('pallet_mask_continuation_sources_v*') if path.is_dir())
    old_before = {str(path.relative_to(PROJECT)): inventory(path) for path in sorted(protected_roots)}
    config = inventory(PROJECT/'configs')
    code = {name: digest(member(PROJECT, name)) for name in ('scripts/build_mask_under50_requests_v3.py',
        'scripts/verify_mask_under50_requests_v3.py', 'tests/test_verify_mask_under50_requests_v3.py',
        'pallet/mask_review_continuation.py', *geometry.FROZEN_INTERFACE_PINS, *HELPER_PINS)}
    for name, expected in geometry.PARENT_PINS.items():
        require(digest(parent/name) == expected, 'Frozen publication15 changed')
    parent_seal = read(parent/'verification.json')
    require(parent_seal['state'] == 'passed' and parent_seal['publication_version'] == 15, 'Independent publication15 required')
    for field, name in (('parent_manifest_sha256', 'manifest.json'), ('parent_proposals_sha256', 'proposals.jsonl'),
            ('parent_verification_sha256', 'verification.json')):
        require(manifest[field] == digest(parent/name), 'Task parent binding differs')
    equal(manifest['parent_directory'], str(parent.relative_to(PROJECT)), 'parent_directory')
    for field, name in (('input_manifest_sha256', 'input_manifest.json'), ('proposals_sha256', 'proposals.jsonl'),
            ('requests_sha256', 'requests.jsonl'), ('decisions_sha256', 'internal/build_decisions.json')):
        require(manifest[field] == digest(root/name), 'Task source/geometry/decision binding differs')
    require(inputs['shortlist_sha256'] == digest(root/'internal/shortlist.jsonl'), 'Own shortlist changed')
    check_source_binding(inputs, manifest, snapshot); context = check_sources(snapshot, parent_manifest, pack_roots)
    formal, rows, evidence = (context[field] for field in ('formal', 'rows', 'evidence'))
    pose, gallery, catalog = (context[field] for field in ('pose', 'gallery', 'catalog'))
    for value in (inputs['configuration_sha256'], context['summary']['configuration_sha256'], context['baseline_seal']['configuration_sha256']):
        equal(config, value, 'global_configs_unchanged')
    counts = check_count_basis(catalog, inputs, manifest); protected = sources.protected_inventory(formal)
    require(len(protected) == 20768 and protected == inputs['formal_protected'] == read(parent/'protected_formal_after.json')
        == read(QUALITY/'private/protected_formal_before.json'), 'All20768 frozen formal files differ')
    for value in (inputs['formal_manifest_sha256'], manifest['formal_manifest_sha256']):
        equal(value, parent_manifest['formal_manifest_sha256'], 'fixed_formal_manifest')
    fingerprints = {str(path.relative_to(PROJECT)): geometry.database_fingerprint(path) for path in (POSE, GALLERY)}
    equal(inputs['database_fingerprints'], fingerprints, 'current_preactivation_raw_store_fingerprints')
    prior_hashes, prior_keys = geometry.prior_inspections(PROJECT, root, rows)
    equal(inputs['prior_request_inventories_sha256'], prior_hashes, 'all_prior_requests_and_withheld_shortlists')
    require(context['inspected'] <= prior_keys, 'All36 prior inspected sources must remain protected')
    canonical_proposals = read_jsonl(parent/'proposals.jsonl')
    require(len(canonical_proposals) == len({p['source']['frame_id'] for p in canonical_proposals}) == 1550, 'All1550 canonical frames remain protected')
    from pallet.mask_template_refined import QUARANTINE
    require(not set(QUARANTINE) & {r['target_key'] for r in catalog}, 'Quarantined source resurrected')
    forbidden = geometry.protected_keys(rows, pose, gallery, catalog, canonical_proposals, prior_keys, QUARANTINE)
    staged = read_jsonl(root/'internal/shortlist.jsonl'); decisions = read(root/'internal/build_decisions.json')['decisions']
    check_staged_limits(staged, counts)
    records, image_hashes = geometry.check_staged(root, staged, decisions, rows, formal, evidence, pose, forbidden)
    proposals, tasks = read_jsonl(root/'proposals.jsonl'), read_jsonl(root/'requests.jsonl')
    issued_counts, deferred = geometry.check_issued_inventory(proposals, tasks, staged, decisions, manifest, counts)
    equal(read(root/'internal/deferred_sources.json'), deferred, 'all_withheld_sources')
    for proposal, task in zip(proposals, tasks):
        key = proposal['target_key']; record = records[key]; image_sha = digest(member(formal, rows[key]['image']))
        geometry.check_draft(proposal, task, record, decisions[key], manifest['formal_manifest_sha256'], digest(root/'input_manifest.json'), image_sha)
        geometry.check_exports(root, proposal, record, image_sha)
    check_public(root, manifest, proposals)
    require(not any(path.suffix.lower() in ('.db', '.sqlite', '.sqlite3') for path in root.rglob('*')), 'Private DB copied into worklist')
    equal(manifest['schema'], 'preannotated_mask_worklist_v1', 'request_schema')
    for field in ('assistant_drafts_not_counted_as_completed', 'strict_registration_gates_not_relaxed', 'source_stores_preserved',
            'old_publications_and_tasks_not_modified', 'training_snapshot_not_modified'):
        equal(manifest[field], True, field)
    equal(inputs['all_prior_inspected_sources_excluded'], True, 'all_previous_inspections_excluded')
    equal(manifest['template_transfer_used'], False, 'not_template_transfer')
    for field in ('production_annotation_writes', 'human_events_created', 'configuration_writes'):
        equal(manifest[field], 0, field)
    require(manifest['generation_code_sha256'] == code['scripts/build_mask_under50_requests_v3.py']
        and manifest['reused_exporter_code_sha256'] == geometry.FROZEN_INTERFACE_PINS['scripts/build_mask_preannotated_requests_v3.py'], 'Actual v3 wrapper/frozen exporter binding differs')
    require(inventory(root) == before and inventory(PROJECT/'configs') == config and sources.protected_inventory(formal) == protected,
        'Task/config/formal files changed during audit')
    for kind, path, store in (('pose', POSE, pose), ('gallery', GALLERY, gallery)):
        equal(sources.read_store(path, kind), store, 'live_source_changed_during_audit_'+kind)
        require(geometry.database_fingerprint(path) == fingerprints[str(path.relative_to(PROJECT))], 'Live source fingerprint changed')
    require(geometry.prior_inspections(PROJECT, root, rows)[0] == prior_hashes, 'Global inspection history changed during audit')
    for name, expected in evidence.used.items():
        require(digest(member(formal, name)) == expected, 'Used native image changed')
    for name, expected in code.items():
        require(digest(member(PROJECT, name)) == expected, 'Generator/verifier/frozen helper changed during audit')
    for name, expected in old_before.items():
        require(inventory(PROJECT/name) == expected, 'Old task/source snapshot changed during audit')
    require(digest(TRAINING_RECORDS) == TRAINING_RECORDS_SHA256, 'Frozen229 training records changed')
    return dict(state='passed', request_count=len(proposals), class_counts=dict(issued_counts), filter_classes=list(CLASSES),
        public_assets=manifest['public_assets'], requests_sha256=digest(root/'requests.jsonl'), proposals_sha256=digest(root/'proposals.jsonl'),
        manifest_sha256=digest(root/'manifest.json'), preannotations_verified=True, formal_manifest_sha256=manifest['formal_manifest_sha256'],
        parent_proposals_sha256=digest(parent/'proposals.jsonl'), parent_verification_sha256=digest(parent/'verification.json'),
        parent_pins=geometry.PARENT_PINS, historical_quality_seal_sha256=geometry.QUALITY_SEAL_SHA256,
        source_audit_sha256=digest(snapshot/'audit.json'), source_audit_independently_verified=True,
        source_audit_directory=str(snapshot.relative_to(PROJECT)), source_catalog_sha256=digest(snapshot/'private/source_catalog.jsonl'),
        input_manifest_sha256=digest(root/'input_manifest.json'), decisions_sha256=digest(root/'internal/build_decisions.json'),
        shortlist_sha256=digest(root/'internal/shortlist.jsonl'), actual_human_saved_sources=1503, actual_class_counts=dict(counts),
        completed_previous_batches=context['completed'], all19_previous_tasks_are_real_changed_human_saves=True,
        all36_previous_staged_sources_excluded=True, previous_pack_pins=SEALED_PACK_PINS,
        maximum_issued_per_class=2, class20_maximum_issued=1, maximum_staged_per_class=3, class_scope=geometry.CLASS_SCOPE,
        own_staged_source_count=len(staged), withheld_source_count=len(deferred), all_prior_inspected_sources_excluded=True,
        prior_request_inventories_sha256=prior_hashes, preactivation_database_fingerprints=fingerprints,
        source_fingerprints=dict(pose=pose['fingerprint'], gallery=gallery['fingerprint']), **context['extension'],
        all_current_pose_records_preserved=4946, all_pose_events_preserved=11926, gallery_contours_verified=1021, gallery_events_verified=1126,
        trained_reference_keys_with_newer_human_revision=context['trained_changes'], frozen_training_records_sha256=TRAINING_RECORDS_SHA256,
        frozen_training_records=229, frozen_training_references_not_rewritten=True, configuration_sha256=config,
        protected_formal_files=20768, fixed_formal_targets=12344, protected_formal_inventory_sha256=sha(protected),
        old_root_inventory_sha256={name: sha(value) for name, value in old_before.items()}, output_inventory_sha256=sha(before),
        code_sha256=code, verification_script_sha256=digest(__file__), frozen_code_sha256=context['baseline_seal']['frozen_code_sha256'],
        distinct_staged_native_image_hashes=len(image_hashes), distinct_native_image_hashes=len(proposals),
        topology_counts=dict(Counter(p['vertex_count'] for p in proposals)), assistant_direct_annotation_not_template_transfer=True,
        original_rectangle_not_used_as_preannotation=True, original_native_quality_gates_unchanged=True,
        all_actual_polygons_before_publication=True, assistant_drafts_not_counted_as_completed=True,
        production_annotation_writes=0, human_events_created=0, configuration_writes=0,
        semantic_contour_accuracy_established=False, human_inspection_independently_observed=False,
        limitations=['Passing certifies raw provenance, exact latest revisions, native exports and preservation, not contour accuracy or GT.',
            'The38 appended gallery events comprise17 revisions of14 old v3 images,10 v1 saves, and11 v2 save events on9 images.',
            'Old gallery current rows legitimately changed; their raw revisions remain recoverable in the preserved event history.',
            'All19 prior tasks have real changed saved human contours, but these research contours are not confirmed ground truth.',
            'Visual full/crop inspection is assistant-reported, not independently observed by this numerical audit.',
            'Three frozen training references have newer human revisions; the229 frozen records are not rewritten or automatically extended.',
            'Four-point contours remain valid without forced vertices or old strict propagation-seed qualification.',
            'No algorithm quality threshold, live service, access-code equivalence or editor save is tested here.',
            'This preactivation seal requires exact current snapshot/live equality; later human saves require fresh provenance evidence.'],
        verified_at=datetime.now(timezone.utc).isoformat())


def seal(root=ROOT, *, producer_complete=False, auditor=None):
    require(producer_complete is True, 'Explicit producer completion required; do not audit unfinished staging')
    root = Path(root)
    require(not root.is_symlink() and root.is_absolute() and root == root.resolve()
        and root == PROJECT/'outputs/pallet_mask_under50_requests_v3', 'Only the exact new v3 output may receive seals')
    for name in SEALS:
        require(not (root/name).exists() and not (root/name).is_symlink(), 'Never overwrite existing verification seals')
    require((root/'manifest.json').is_file(), 'Producer manifest is not complete')
    result = (auditor or audit)(root); require(result.get('state') == 'passed', 'Independent v3 audit did not pass')
    raw = canonical(result)+b'\n'; owned = []
    try:
        for name in SEALS:
            path = root/name
            with path.open('xb') as stream:
                owned.append((path, os.fstat(stream.fileno()).st_ino)); os.fchmod(stream.fileno(), 0o600)
                stream.write(raw); stream.flush(); os.fsync(stream.fileno())
    except BaseException:
        for path, inode in owned:
            if not path.is_symlink() and path.exists() and path.stat().st_ino == inode:
                path.unlink()
        raise
    return result


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('--producer-complete', action='store_true')
    args = parser.parse_args(); verified = seal(producer_complete=args.producer_complete)
    print(json.dumps({key: verified[key] for key in ('state', 'request_count', 'class_counts', 'completed_previous_batches',
        'actual_human_saved_sources', 'gallery_events_verified', 'semantic_contour_accuracy_established')}, ensure_ascii=False), flush=True)
