"""Independent fourth under50 audit: 26 completed images, five remaining classes.

Do not run against staging: await explicit READY. No producer is imported, no old
helper globals are changed, and no editor save or service operation is performed.
Only exclusive, identical v4 seals may be written after an actual passing audit.
Provenance/export validity is not contour accuracy, confirmed GT or eligibility.
"""
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_v3 as previous
from scripts import verify_mask_quality_recovery as sources

ROOT = PROJECT/'outputs/pallet_mask_under50_requests_v4'
SNAPSHOT = PROJECT/'outputs/pallet_mask_continuation_sources_v6'
QUALITY, PARENT, POSE, GALLERY = geometry.QUALITY, geometry.PARENT, geometry.POSE, geometry.GALLERY
CLASSES, SEALS = (11, 12, 16, 17, 19), geometry.SEALS
EXPECTED_COUNTS = {11: 23, 12: 47, 16: 40, 17: 49, 19: 42, 20: 50}
SAVED_COUNT, GALLERY_COUNT, EVENT_COUNT = 1510, 1028, 1133
# Pinned from completed snapshot bytes only after the producer's explicit READY.
SOURCE_AUDIT_SHA256 = '182c3f210def5c9d868568451218c15853a15a4d10b0ac5cad43bdd2d4b8cd61'
SOURCE_CATALOG_CODE_SHA256 = '300e289f763bd4bad1747b9b0610241b9bf90351517d0b3e40c84154dff27c2e'
TRAINING_RECORDS = continuation.TRAINING_RECORDS
TRAINING_RECORDS_SHA256 = previous.TRAINING_RECORDS_SHA256
TRAINING_PINS = {
    'dataset_manifest.json': '563326cddcd97962a8f2cd8ceb5fe760cb76a0c5f0572a6e9535d01b2ccc13db',
    'preparation_complete.json': '1031171d5daf6173fb268563bfd897c5d99c62a510ff53095093b0d1e8c80d1e',
    'private/dataset_verification.json': 'e91670a7f268cc07edcfbe14d3f551865a9c13c4120808fc999f825d65fab1f4',
    'private/training_records.jsonl': TRAINING_RECORDS_SHA256,
}
SEALED_PACK_PINS = {
    **{name: {**pins, 'staged_count': 18} for name, pins in previous.SEALED_PACK_PINS.items()},
    'pallet_mask_under50_requests_v3': dict(
        manifest_sha256='0c182489c178edb746da6052791c71439ebebb03dd906dcf14fc4155eda56aba',
        verification_sha256='d5c44266a45aea90386174a7cddb008138c71259ff22cb8e2bfe954217d15897',
        request_count=7, event_count=7, staged_count=16),
}
HELPER_PINS = {**previous.HELPER_PINS,
    'scripts/verify_mask_under50_requests_v3.py': '364c26f439a40687a732b81dff95819f0db2086bcc79077b27fd49fc46798808',
    'tests/test_verify_mask_under50_requests_v3.py': 'eb652f951180c1c436750a90186e6473d05ebf4ef3922e220795fca750bfb79e',
    'scripts/build_mask_under50_requests_v3.py': '1a6c1392ecfc84f09955778e3422f65328eb5644ef3033600f03251f7d02e89b',
}
HISTORICAL_SNAPSHOTS = {**previous.HISTORICAL_SNAPSHOTS,
    'pallet_mask_continuation_sources_v4': dict(audit_sha256=previous.SOURCE_AUDIT_SHA256, current_count=1021, event_count=1126),
    'pallet_mask_continuation_sources_v5': dict(
        audit_sha256='d3476dca88ab0d51e58e421c45fa10a1ca433dc0411985696e3a0c35ddf075c7', current_count=1021, event_count=1126),
}
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):
    """Explicit pack-local scope: historical six-class pages never mutate helpers."""
    expected_counts = EXPECTED_COUNTS if expected_counts is None else expected_counts
    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 batch label exposed')
    count_rows = [(int(c), int(n)) for c, n in re.findall(r'Class (\d+)：(\d+)份', page)]
    equal(count_rows, [(c, expected_counts[c]) for c in classes], 'real_human_count_table_scope')
    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 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 three 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')
        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 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 geometry.CLASSES}, geometry.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) == 52 and len(set.union(*tasks.values())) == 26, 'Exact52 inspected/26 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, '1510 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/1028 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 three prior task namespaces required')
    all_tasks = set.union(*task_keys.values())
    require(len(all_tasks) == sum(len(keys) for keys in task_keys.values()) == 26, '26 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'] == 45
        and len(extension['new_distinct_saved_keys']) == 26, 'Expected45 events:17 old revisions plus28 saves on26 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}}, 'all45_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.endswith(('_v1', '_v3')):
                require(len(history) == 1, 'Prior v1/v3 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_count_basis(catalog, inputs, manifest, *, saved_count=SAVED_COUNT, classes=CLASSES, expected_counts=None):
    """Parameterized independently; never call the old1484/six-class counter."""
    expected_counts = EXPECTED_COUNTS if expected_counts is None else expected_counts
    require(len(catalog) == len({r['target_key'] for r in catalog}) == len({r['row']['frame_id'] for r in catalog}) == saved_count,
        '1510 distinct saved human contours required, not stale or 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 expected_counts} == expected_counts, 'Current five-class under50 counts differ; Class20 already50')
    equal(inputs['actual_counted_saved_basis'], saved_count, 'real1510_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_five_class_scope')
    equal(manifest['filter_classes'], list(classes), 'filter_five_class_scope')
    return counts


def check_staged_limits(staged, counts, classes=CLASSES):
    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 five-class/gap cap exceeded: Class17 permits only1; Class20 excluded')


def check_issued_inventory(proposals, tasks, staged, decisions, manifest, actual_counts, classes=CLASSES):
    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: Class17 max1; Class20 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'], '26_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 event_namespace_counts(references):
    # Canonical historical events have namespace=None, not a JSON object key.
    return dict(Counter(reference.get('namespace') or 'historical_gallery' for reference in references.values()))


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)
    records = sources.indexed(read_jsonl(root/'private/training_records.jsonl'))
    require(len(records) == 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 v6 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=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 v6 source audit')
    equal(inputs['source_audit_sha256'], expected, 'explicit_fresh_input_audit_binding')
    equal(manifest['source_audit_sha256'], expected, 'explicit_fresh_manifest_audit_binding')
    equal(inputs['continuation_source_audit_sha256'], expected, 'continuation_input_audit_binding')
    equal(manifest['continuation_source_audit_sha256'], expected, 'continuation_manifest_audit_binding')
    equal(inputs['continuation_source_directory'], str(snapshot.relative_to(PROJECT)), 'explicit_source_snapshot_v6')
    equal(inputs['continuation_source_catalog_sha256'], digest(snapshot/'private/source_catalog.jsonl'), 'explicit_source_catalog_binding')
    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 v4 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_v4.py',
        'scripts/verify_mask_under50_requests_v4.py', 'tests/test_verify_mask_under50_requests_v4.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, 'All52 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'):
        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_v4.py']
        and manifest['reused_exporter_code_sha256'] == geometry.FROZEN_INTERFACE_PINS['scripts/build_mask_preannotated_requests_v3.py'],
        'Actual v4 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=26,
        all26_previous_tasks_are_real_changed_human_saves=True, all52_previous_staged_sources_excluded=True, previous_pack_pins=SEALED_PACK_PINS,
        maximum_issued_per_class=2, class17_maximum_issued=1, class20_actual_saved=50, class20_excluded=True,
        maximum_staged_per_class=3, class17_maximum_staged=1, 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.',
            'The45 appended events comprise17 revisions of14 old v3 images,10 under50-v1 saves,11 v2 events on9 images and7 v3 saves.',
            'Old gallery current rows legitimately changed; their raw revisions remain recoverable in the preserved1088-event prefix.',
            'All26 prior tasks are real changed human saves; the1510 saved research contours are not automatically ground truth.',
            'Only Classes11/12/16/17/19 remain below50. Class20 is50 and excluded; Class17 permits only one further issued image.',
            'Full/crop/grid visual checks are assistant-reported; this numerical audit does not independently observe subjective inspection.',
            'Three frozen training references have newer revisions (2train/1dev); the229 frozen labels and source keys are not rewritten or extended.',
            'Valid four-point contours remain 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_v4', 'Only the exact new v4 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 v4 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)
