"""Independent fifth under50 audit: 32 completed images, four remaining classes.

Await explicit producer READY before reading staging. No builder/source producer is
imported, no old helper globals are changed, and no production save is performed.
Exclusive twin seals certify provenance, exports and preservation, not accuracy,
confirmed GT, training/robot eligibility or subjective visual inspection.
"""
from __future__ import annotations

import argparse
from collections import Counter
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import re
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_under50_requests_v4 as previous
from scripts import verify_mask_quality_recovery as sources

ROOT = PROJECT/'outputs/pallet_mask_under50_requests_v5'
SNAPSHOT = PROJECT/'outputs/pallet_mask_continuation_sources_v8'
QUALITY, PARENT, POSE, GALLERY = geometry.QUALITY, geometry.PARENT, geometry.POSE, geometry.GALLERY
CLASSES, SEALS = (11, 12, 16, 19), geometry.SEALS
EXPECTED_COUNTS = {11: 25, 12: 47, 16: 42, 17: 50, 19: 43, 20: 50}
SAVED_COUNT, GALLERY_COUNT, EVENT_COUNT = 1516, 1034, 1139
# Pinned completed snapshot bytes after the producer explicitly announced READY.
SOURCE_AUDIT_SHA256 = 'f46b147144d04e874d1f97289f4a2c5924f8646a3f4838a3e12284dea3db481d'
SOURCE_CATALOG_CODE_SHA256 = previous.SOURCE_CATALOG_CODE_SHA256
TRAINING_RECORDS, TRAINING_RECORDS_SHA256 = previous.TRAINING_RECORDS, previous.TRAINING_RECORDS_SHA256
TRAINING_PINS = dict(previous.TRAINING_PINS)
SEALED_PACK_PINS = {
    **{name: {**pins, 'classes': geometry.CLASSES} for name, pins in previous.SEALED_PACK_PINS.items()},
    'pallet_mask_under50_requests_v4': dict(
        manifest_sha256='c85030906694d37d9dd3d7e721bd2e5d1ba6db55d3e67844f9846152803ce31d',
        verification_sha256='35a166ea9f5dc8b9df2a3fd352a04419c9b681baefaeb43d66b4e17ce1b8af7b',
        request_count=6, event_count=6, staged_count=13, classes=previous.CLASSES),
}
HELPER_PINS = {**previous.HELPER_PINS,
    'scripts/verify_mask_under50_requests_v4.py': '8554c3d71122c1828e54be56e8f87c46119d342d3182cc9413fb3f99cb35e1d1',
    'tests/test_verify_mask_under50_requests_v4.py': 'aaf3666774cbaa558d6d5a288c8666dd39e2365fa066c4886ee4c6cb17d35004',
    'scripts/build_mask_under50_requests_v4.py': 'f7c2af7c2aa71b227d44347602c847f56591c0deb652454007456348b093c254',
}
HISTORICAL_SNAPSHOTS = {**previous.HISTORICAL_SNAPSHOTS,
    'pallet_mask_continuation_sources_v6': dict(audit_sha256=previous.SOURCE_AUDIT_SHA256, current_count=1028, event_count=1133),
    'pallet_mask_continuation_sources_v7': dict(
        audit_sha256='64f95c9c80cffc3dcaf968dd0e47f1738acbabb07acb83a9d57369de817052a2', current_count=1028, event_count=1133),
}
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 require_source_pin():
    require(isinstance(SOURCE_AUDIT_SHA256, str) and re.fullmatch(r'[0-9a-f]{64}', SOURCE_AUDIT_SHA256),
        'Completed source audit is not pinned; await explicit producer READY')


def check_public(root, manifest, proposals, expected_counts=None, classes=CLASSES):
    return previous.check_public(root, manifest, proposals,
        EXPECTED_COUNTS if expected_counts is None else expected_counts, classes)


def check_count_basis(catalog, inputs, manifest):
    # This helper is parameterized: never use the old1484/six-class counter.
    return previous.check_count_basis(catalog, inputs, manifest,
        saved_count=SAVED_COUNT, classes=CLASSES, expected_counts=EXPECTED_COUNTS)


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 independent registry')
        for name, field in (('manifest.json', 'manifest_sha256'), ('verification.json', 'verification_sha256'),
                ('independent_verification.json', 'verification_sha256')):
            require(digest(member(root, name)) == SEALED_PACK_PINS[root.name][field], 'Frozen under50 pack pin differs: '+root.name+'/'+name)
        result[root.name] = root
    require(result.keys() == SEALED_PACK_PINS.keys(), 'All four 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(), {}
    frames, hashes = set(), 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')
        equal(manifest['filter_classes'], list(pins['classes']), 'prior_filter_class_scope')
        equal(inputs['shortlisted_classes'], list(pins['classes']), 'prior_shortlist_class_scope')
        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) == pins['staged_count'] and digest(root/'internal/shortlist.jsonl') == inputs['shortlist_sha256']
            == seal['shortlist_sha256'], 'Prior18/18/16/13 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 pins['classes']}, pins['classes'])
        require(not inspected & staged.keys(), 'Repeated inspected key across sealed packs')
        for key, record in staged.items():
            require(key in rows and record['source'] == rows[key], 'Prior inspected formal source differs')
            row = rows[key]; image_sha = digest(member(evidence.formal, row['image']))
            require(row['frame_id'] not in frames and image_sha not in hashes, 'Repeated prior inspected frame/image bytes')
            frames.add(row['frame_id']); hashes.add(image_sha)
        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) == 65 and len(set.union(*tasks.values())) == 32, 'Exact65 inspected/32 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}) == SAVED_COUNT, '1516 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']) == GALLERY_COUNT
        and records.keys() == pose_sources.keys() | gallery['current'].keys()
        and not pose_sources.keys() & gallery['current'].keys(), 'Actual482 pose/1034 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['target_key'] == key and type(value['revision']) is int and value['revision'] == revision, 'Relational event identity differs')
        require(event_id not in references, 'Duplicate gallery event ID')
        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):
    require(task_keys.keys() == SEALED_PACK_PINS.keys(), 'All four prior task namespaces required')
    all_tasks = set.union(*task_keys.values())
    require(len(all_tasks) == sum(len(keys) for keys in task_keys.values()) == 32, '32 distinct prior tasks required')
    extension = continuation.check_revision_extension(baseline, gallery, all_tasks)
    require(len(extension['changed_baseline_current_keys']) == 14 and extension['appended_gallery_events'] == 51
        and len(extension['new_distinct_saved_keys']) == 32, 'Expected51 events:17 old revisions plus34 saves on32 new images')
    appended = gallery['events'][len(baseline['events']):]
    routes = Counter(references[e[0]].get('namespace') for e in appended)
    equal(dict(routes), {'v3': 17, **{name: SEALED_PACK_PINS[name]['event_count'] for name in task_keys}}, 'all51_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, 'Prior tasks require a genuine first revision1')
            if namespace != 'pallet_mask_under50_requests_v2':
                require(len(history) == 1, 'Prior v1/v3/v4 tasks require exactly one real save each')
            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(old['polygon'] != reference['proposal']['polygon'], 'Real completed task event is unchanged from its draft')
            require(value['polygon'] != references[latest[0]]['proposal']['polygon'], 'Current real saved task unchanged from draft')
        completed[namespace] = len(keys)
    return extension, completed


def check_staged_limits(staged, counts):
    staged_counts = Counter(r['class_id'] for r in staged)
    require(staged and len(staged) <= sum(min(3, 50-counts[c]) for c in CLASSES)
        and all(type(c) is int and c in CLASSES and n <= min(3, 50-counts[c]) for c, n in staged_counts.items()),
        'Staged four-class/gap cap exceeded: max3 each; Classes17/20 excluded')


def check_issued_inventory(proposals, tasks, staged, decisions, manifest, actual_counts):
    proposal_map, task_map = sources.indexed(proposals), sources.indexed(tasks)
    require(proposals and len(proposals) == len(tasks) <= sum(min(2, 50-actual_counts[c]) for c in CLASSES), 'Empty, unpaired or oversized request batch')
    equal(manifest['request_count'], len(proposals), 'request_count')
    staged_keys = {record['target_key'] for record in staged}
    require(set(decisions) == staged_keys and len(staged_keys) == len(staged), 'Missing/unknown/duplicate staged decision')
    require(all(type(decisions[key].get('approved')) is bool for key in staged_keys), 'Decision approval is not boolean')
    issued = [r['target_key'] for r in staged if decisions[r['target_key']]['approved'] is True]
    require([p['target_key'] for p in proposals] == [t['target_key'] for t in tasks] == issued
        and proposal_map.keys() == task_map.keys() <= staged_keys, 'Own approved/proposal/task order or scope differs')
    counts = Counter(p['class_id'] for p in proposals)
    require(all(type(c) is int and c in CLASSES and n <= min(2, 50-actual_counts[c]) for c, n in counts.items()),
        'Under50 issued class maximum/gap exceeded: max2 each; Classes17/20 excluded')
    equal(manifest['class_counts'], {str(c): n for c, n in counts.items()}, 'issued_class_counts')
    equal(manifest['classes'], sorted(counts), 'issued_classes')
    return counts, [dict(target_key=r['target_key'], reason='source_withheld_counted_or_class_quota', decision=decisions[r['target_key']])
        for r in staged if r['target_key'] not in proposal_map]


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=SAVED_COUNT, gallery_contours=GALLERY_COUNT, gallery_events=EVENT_COUNT, 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'], '32_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_frozen_training(root=None):
    root = TRAINING_RECORDS.parents[1] if root is None else Path(root)
    for name, expected in TRAINING_PINS.items():
        require(digest(member(root, name)) == expected, 'Frozen229 training metadata changed: '+name)
    require(len(sources.indexed(read_jsonl(root/'private/training_records.jsonl'))) == 229, 'Frozen229 source keys changed')
    manifest = read(root/'dataset_manifest.json')
    for field in ('automatic_training_eligible', 'ground_truth_eligible', 'human_mask_confirmed', 'human_pose_confirmed', 'robot_command_eligible'):
        equal(manifest[field], False, 'frozen_training_research_only.'+field)
    for name, expected in manifest['files'].items():
        require(digest(member(root, name)) == expected, 'Frozen training file changed: '+name)
    for directory in ('dataset', 'dataset_rfdetr', 'private/native_masks'):
        actual = {directory+'/'+name: value for name, value in inventory(root/directory).items()}
        equal(actual, {name: value for name, value in manifest['files'].items() if name.startswith(directory+'/')}, 'no_new_training_labels.'+directory)
    return {**TRAINING_PINS, **manifest['files']}


def check_sources(snapshot, parent_manifest, pack_roots):
    require_source_pin()
    require(digest(snapshot/'audit.json') == SOURCE_AUDIT_SHA256, 'Exact fresh v8 source audit changed')
    summary = read(snapshot/'audit.json')
    require(summary['source_catalog_sha256'] == digest(snapshot/'private/source_catalog.jsonl')
        and summary['code_sha256'] == SOURCE_CATALOG_CODE_SHA256 == digest(PROJECT/'pallet/mask_review_continuation.py'), 'Fresh source catalog/code pin 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)
    require(len(seal['frozen_code_sha256']) == 19, 'All19 frozen qualification engines required')
    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, GALLERY_COUNT, EVENT_COUNT), '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')
        prior_extension = continuation.check_revision_extension(earlier_gallery, gallery, set(gallery['current'])-set(earlier_gallery['current']))
        require(not prior_extension['changed_baseline_current_keys'], 'Later saves unexpectedly changed earlier snapshot current images')
    require(digest(TRAINING_RECORDS) == TRAINING_RECORDS_SHA256, 'Frozen229 training records changed')
    trained_changes = continuation.check_trained_revisions(TRAINING_RECORDS, baseline_catalog, extension['changed_baseline_current_keys'])
    require(len(trained_changes) == 3 and Counter(trained_changes.values()) == {'train': 2, 'dev': 1}, 'Expected newer references:2train/1dev, no relabeling')
    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', 'private/event_binding_audit.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,
        event_routes=previous.event_namespace_counts(references))


def check_source_binding(inputs, manifest, snapshot=SNAPSHOT):
    require_source_pin()
    expected = digest(snapshot/'audit.json')
    require(expected == SOURCE_AUDIT_SHA256, 'Unrecognized v8 source audit')
    for value in (inputs, manifest):
        equal(value['source_audit_sha256'], expected, 'explicit_fresh_audit_binding')
        equal(value['continuation_source_audit_sha256'], expected, 'continuation_audit_binding')
        equal(value['excluded_classes_already_at_50'], [17, 20], 'completed_classes17_and20_excluded')
    equal(inputs['continuation_source_directory'], str(snapshot.relative_to(PROJECT)), 'explicit_source_snapshot_v8')
    equal(inputs['continuation_source_catalog_sha256'], digest(snapshot/'private/source_catalog.jsonl'), 'explicit_source_catalog_binding')
    equal(inputs['previous_batch_directory'], 'outputs/pallet_mask_under50_requests_v4', 'previous_v4_directory')
    equal(inputs['previous_batch_manifest_sha256'], SEALED_PACK_PINS['pallet_mask_under50_requests_v4']['manifest_sha256'], 'previous_v4_manifest')
    for value in (inputs, manifest):
        equal(value['previous_batch_actual_completed'], 6, 'six_real_v4_completions')
    equal(inputs['source_snapshot_never_added_to_frozen_training'], True, 'no_new_training_sources')
    if 'source_quality_audit_sha256' in inputs:
        equal(inputs['source_quality_audit_sha256'], geometry.QUALITY_SEAL_SHA256, 'historical_quality_not_fresh_audit')


def audit(root=ROOT, parent=PARENT, snapshot=SNAPSHOT, *, producer_complete=False):
    require(producer_complete is True, 'Explicit producer READY required; never audit unfinished staging')
    require_source_pin()
    root, parent, snapshot = Path(root), Path(parent), Path(snapshot)
    before = inventory(root); require(not set(SEALS) & before.keys(), 'Preserve existing v5 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, training = inventory(PROJECT/'configs'), check_frozen_training()
    code = {name: digest(member(PROJECT, name)) for name in ('scripts/build_mask_under50_requests_v5.py',
        'scripts/verify_mask_under50_requests_v5.py', 'tests/test_verify_mask_under50_requests_v5.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, 'All65 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 = 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', 'previous_batches_preserved'):
        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_v5.py']
        and manifest['reused_exporter_code_sha256'] == geometry.FROZEN_INTERFACE_PINS['scripts/build_mask_preannotated_requests_v3.py'], 'Actual v5 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')
    equal(check_frozen_training(), training, 'frozen229_dataset_and_source_keys_preserved')
    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'),
        source_catalog_code_sha256=SOURCE_CATALOG_CODE_SHA256, event_binding_audit_sha256=digest(snapshot/'private/event_binding_audit.jsonl'),
        every_gallery_event_exact_publication_hash_target_verified=True, gallery_event_namespace_counts=context['event_routes'],
        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=SAVED_COUNT, actual_class_counts=dict(counts),
        completed_previous_batches=context['completed'], actual_completed_previous_under50_tasks=32,
        all32_previous_tasks_are_real_changed_human_saves=True, all65_previous_staged_sources_excluded=True, previous_pack_pins=SEALED_PACK_PINS,
        maximum_issued_per_class=2, classes17_and20_actual_saved={17: 50, 20: 50}, excluded_classes_already_at_50=[17, 20],
        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=GALLERY_COUNT, gallery_events_verified=EVENT_COUNT,
        trained_reference_keys_with_newer_human_revision=context['trained_changes'], frozen_training_records_sha256=TRAINING_RECORDS_SHA256,
        frozen_training_records=229, frozen_training_dataset_inventory_sha256=sha(training), 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 accuracy or confirmed GT.',
            'The51 appended events comprise17 revisions of14 old v3 images,10 under50-v1 saves,11 v2 events on9 images,7 v3 saves and6 v4 saves.',
            'Old gallery current rows legitimately changed; their raw revisions remain recoverable in the preserved1088-event prefix.',
            'All32 prior tasks are real changed human saves; the1516 saved research contours are not automatically ground truth.',
            'Only Classes11/12/16/19 remain below50. Classes17/20 are50 and are excluded from staging, issued tasks and public filters.',
            'Full/crop/grid and final-overlay visual checks are assistant-reported, not independently observed by this numerical audit.',
            'Three frozen training references have newer revisions (2train/1dev); the229 frozen labels/source keys are not rewritten or extended.',
            'Formal validation/test sources retain their splits and are not training labels or cross-split propagation sources.',
            'Valid four-point contours stay four points, without forced vertices or old strict propagation-seed eligibility.',
            'No algorithm quality threshold, service, model, access-code equivalence or production editor save is tested here.',
            'This preactivation seal requires exact snapshot/live equality now; later real 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 READY 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_v5', 'Only the exact new v5 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(root) if auditor is not None else audit(root, producer_complete=True)
    require(result.get('state') == 'passed', 'Independent v5 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)
