"""Independent bulk supplement audit; await explicit producer READY to run.

Replays raw source history and every exact publication/hash/key binding. Bulk
capacity replaces the old two-issued/three-staged limits, not source quality or
preservation gates. No producer is imported, old globals changed, service touched,
production save made, or new training output inspected. Only new twin seals write.
"""
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_v5 as previous
from scripts import verify_mask_quality_recovery as sources

ROOT = PROJECT/'outputs/pallet_mask_under50_requests_v6'
SNAPSHOT = PROJECT/'outputs/pallet_mask_continuation_sources_v10'
QUALITY, PARENT, POSE, GALLERY = geometry.QUALITY, geometry.PARENT, geometry.POSE, geometry.GALLERY
CLASSES, SEALS = (11, 12, 16, 19), geometry.SEALS
EXPECTED_COUNTS = {11: 27, 12: 47, 16: 44, 17: 50, 19: 43, 20: 50}
REMAINING = {11: 23, 12: 3, 16: 6, 19: 7}
SAVED_COUNT, GALLERY_COUNT, EVENT_COUNT = 1520, 1038, 1144
# The source snapshot, unlike the worklist, was explicitly declared READY.
SOURCE_AUDIT_SHA256 = '537b3aa097267a8e16e91a3623903f1299d557c18125f3d1fcdcf4bd9bd09a58'
SOURCE_CATALOG_CODE_SHA256 = previous.SOURCE_CATALOG_CODE_SHA256
TRAINING_RECORDS, TRAINING_RECORDS_SHA256 = previous.TRAINING_RECORDS, previous.TRAINING_RECORDS_SHA256
SEALED_PACK_PINS = {**previous.SEALED_PACK_PINS,
    'pallet_mask_under50_requests_v5': dict(
        manifest_sha256='969e889515f094c9212fb707e918e3951d06961ed73fee1f83e3074a46f0bec7',
        verification_sha256='58f2a118b17c79f38f6df66d9cc071a52cf890c6de704c4d344d895b1301ff0d',
        request_count=4, event_count=5, staged_count=12, classes=previous.CLASSES),
}
HELPER_PINS = {**previous.HELPER_PINS,
    'scripts/verify_mask_under50_requests_v5.py': '0a4fef1b37011bfd6567506beb6943b9d1e09702f42071555fdbd96842018a48',
    'tests/test_verify_mask_under50_requests_v5.py': 'e96c8d88f0e4b1c021c857524ad5fd2a99e9d8da8c5e859a0ad1d60075a4b731',
    'scripts/build_mask_under50_requests_v5.py': 'bfdd6af874e03c8f93567ced33d5918465c4e0a52842c2b912a25da28c819d65',
}
HISTORICAL_SNAPSHOTS = {**previous.HISTORICAL_SNAPSHOTS,
    'pallet_mask_continuation_sources_v8': dict(audit_sha256=previous.SOURCE_AUDIT_SHA256, current_count=1034, event_count=1139),
    'pallet_mask_continuation_sources_v9': dict(
        audit_sha256='39d2e86c4487b0cf5ed26697843bdc42b1c7e10d1f95542d8a49151b1f8fa527', current_count=1034, event_count=1139),
}
OLD_MODEL_PINS = {
    'm1/best.pt': '7ce604339b0e0c6ea25a72bb97e42988a69e01f5f92619e81cbf5c5c5fead8a2',
    'm1/last.pt': '41d81a0bafc1787af7a020ef5e2117fd4e1aa099ad7396a880e1facb60ed70e6',
    'm1/completion.json': '21c9ef91ca3a65f367a581f936f5fbedd2f8240b7344bb93e6efeb13e030d95a',
    'm1/frozen_selection.json': 'd3edc7769cc3bb1ecb67c8e9fd380c974626e1efe5fafbf927547f1799af3f98',
    'm2_retry1/attempt_00/checkpoint_best_total.pth': 'c1095581f9198a81fa6182dcfc7d62eca876f73f7573dc6683f215c98e04add4',
    'm2_retry1/attempt_00/checkpoint_best_ema.pth': '933da8fbe919e75598542561f3b01162381dfca46976bece36d95f2deddffd86',
    'm2_retry1/attempt_00/last_ema.pth': '10da6a7b1b1df57a10853b931f69d2756a9bdac3d514cdac666c0061fe03b348',
    'm2_retry1/completion.json': '084af5c886dcc583c8dbd17fad9086f43a24b711d4a524fbf8b4669b6388144b',
    'm2_retry1/frozen_selection.json': '1c9fbe2825807981ce54eaaba6be8fd655920bccded63970db8c05569ba2b90d',
}
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_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}) == SAVED_COUNT,
        '1520 distinct actual saved research contours required')
    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 actual under50 counts differ')
    equal(inputs['actual_counted_saved_basis'], SAVED_COUNT, 'real1520_saved_count')
    equal(inputs['actual_class_counts'], {str(c): n for c, n in counts.items()}, 'all22_actual_counts')
    equal(manifest['actual_human_saved_counts_before'], inputs['actual_class_counts'], 'manifest_real_counts')
    equal(inputs['shortlisted_classes'], list(CLASSES), 'bulk_staged_scope')
    equal(manifest['filter_classes'], list(CLASSES), 'bulk_filter_scope')
    for value in (inputs, manifest):
        equal(value['class_scope'], geometry.CLASS_SCOPE, 'actual_saved_not_machine_scope')
        equal(value['maximum_issued_by_class'], {str(c): n for c, n in REMAINING.items()}, 'bulk_class_caps')
        equal(value['target_per_class_this_pilot'], 50, 'actual_target50')
        equal(value['consolidated_remaining_gap_batch'], True, 'bulk_not_pilot')
        require('maximum_issued_per_class' not in value, 'Obsolete uniform pilot limit declared')
    require({c: 50-counts[c] for c in CLASSES} == REMAINING, 'Authorized bulk remaining39 differs')
    return counts


def check_public(root, manifest, proposals):
    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', '真实人工轮廓', '剩余补样合并复核', '已预标注', '未保存不计完成',
        '不自动获得GT、传播、训练或机器人资格', '有效四点保持四点', '不强迫增点', 'val/test保持原划分',
        '不是严格配准通过或真实人工保存', '不凑数')), 'Missing bulk/research/draft-only report scope')
    require('每类最多2张' 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 stale pilot cap exposed')
    equal([(int(c), int(n)) for c, n in re.findall(r'Class (\d+)：(\d+)份', page)],
        [(c, EXPECTED_COUNTS[c]) for c in CLASSES], 'four_current_class_count_rows')
    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], 'bulk_four_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 pack')
        if not any(flags):
            continue
        require(root.name in SEALED_PACK_PINS, 'Unpinned sealed prior pack')
        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 pack pin differs: '+root.name+'/'+name)
        result[root.name] = root
    require(result.keys() == SEALED_PACK_PINS.keys(), 'All five sealed prior packs required')
    return result


def extend_registry(pack_roots, rows, formal_sha, pose, publication, registry, evidence):
    extended, inspected, tasks, frames, hashes = dict(registry), set(), {}, 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 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/12 inspections changed')
        decisions = read(root/'internal/build_decisions.json')['decisions']
        require(set(decisions) == staged.keys() and drafts.keys() <= staged.keys(), 'Prior staged decisions differ')
        previous.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 prior inspected key')
        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 triple')
            extended[identity] = dict(kind='independent_preannotation', namespace=namespace, proposal=proposal, path=root)
    require(len(inspected) == 77 and len(set.union(*tasks.values())) == 36, 'Exact77 inspected/36 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, '1520 distinct 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/1038 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_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 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 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 five prior task namespaces required')
    all_tasks = set.union(*task_keys.values())
    require(len(all_tasks) == sum(len(keys) for keys in task_keys.values()) == 36, '36 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'] == 56
        and len(extension['new_distinct_saved_keys']) == 36, 'Expected56 events:17 old revisions plus39 saves on36 images')
    routes = Counter(references[e[0]].get('namespace') for e in gallery['events'][len(baseline['events']):])
    equal(dict(routes), {'v3': 17, **{name: SEALED_PACK_PINS[name]['event_count'] for name in task_keys}}, 'all56_event_specific_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 task first genuine revision must be1')
            value, latest = sources.exact_latest(gallery, key)
            for event_id, _, raw, old in history:
                require(sources.loads(raw) == old, 'Historical decoded payload differs from raw UTF8')
                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 wrong exact package/hash/key binding')
                require(old.get('event_kind') == 'human_mask_gallery_revision' and old.get('human_edited') is True,
                    'Fabricated assistant/human event')
                require(old['polygon'] != reference['proposal']['polygon'], 'Real task event unchanged from 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(root, staged, decisions, rows, formal, evidence, pose, forbidden):
    """Unlimited alternatives, unchanged native gates and complete private-state replay."""
    import numpy as np
    from PIL import Image, ImageDraw
    records = sources.indexed(staged)
    require(records and set(decisions) == records.keys(), 'Every staged source needs exactly one decision')
    require(all(type(r['class_id']) is int and r['class_id'] in CLASSES for r in staged), 'Staged class17/20 or out-of-scope class')
    blocked_frames = {rows[k]['frame_id'] for k in forbidden}
    blocked_hashes = {digest(member(formal, rows[k]['image'])) for k in forbidden}
    frames, hashes = set(), set()
    for order, record in enumerate(staged, 1):
        key = record['target_key']; row = rows[key]; decision = decisions[key]
        require(re.fullmatch(r'[0-9a-f]{24}', key), 'Unsafe staged key')
        require(record['source'] == row and record['class_id'] == row['final_class_id'], 'Staged formal identity differs')
        equal(record['request_order'], order, 'staged_order')
        equal(record['native_image'], f'images/{key}.png', 'staged_native_path')
        equal(record['contact_crop'], f'cases/{key}.png', 'staged_crop_path')
        equal(record['crop_native_bounds'], geometry.crop_bounds(row), 'native_crop_bounds')
        require(type(decision.get('approved')) is bool and decision.get('full_image_inspected') is True
            and decision.get('crop_inspected') is True and isinstance(decision.get('note_zh'), str)
            and decision['note_zh'].strip(), 'Explicit full/crop decision required, including withheld images')
        image_sha = digest(member(formal, row['image']))
        require(key not in forbidden and row['frame_id'] not in blocked_frames and image_sha not in blocked_hashes,
            'Previously saved/canonical/inspected/protected source or duplicate image bytes staged')
        require(row['frame_id'] not in frames and image_sha not in hashes, 'Duplicate staged frame/native bytes')
        frames.add(row['frame_id']); hashes.add(image_sha)
        require(digest(member(root/'internal', record['native_image'])) == image_sha, 'Staged native image bytes differ')
        equal(record['image_quality'], geometry.native_quality(row, evidence), 'unchanged_native_quality')
        value = pose['current'].get(key); current = value[2] if value else None
        equal(record['existing_pose_current_payload'], current, 'all_preserved_pose_fields')
        equal(record['existing_pose_revision'], value[0] if value else 0, 'staged_pose_revision')
        equal(record['existing_pose_payload_sha256'], sha(current) if value else None, 'staged_pose_payload')
        equal(record['existing_pose_history_sha256'], sha([e[3] for e in pose['histories'].get(key, [])]), 'staged_pose_history')
        equal(record['no_pose_current_or_history'], key not in pose['current'] and key not in pose['histories'], 'pose_presence')
        image = Image.fromarray(evidence.image(row['frame_id'])).convert('RGB')
        left, top, right, bottom = record['crop_native_bounds']; crop = image.crop((left, top, right, bottom))
        x, y, w, h = (row['bbox'][f] for f in ('x', 'y', 'width', 'height'))
        ImageDraw.Draw(crop).rectangle((x-left, y-top, x+w-left, y+h-top), outline=(255, 180, 40), width=1)
        with Image.open(member(root/'internal', record['contact_crop'])) as actual:
            require(np.array_equal(np.asarray(actual), np.asarray(crop)), 'Staged native crop differs')
    return records, hashes


def check_issued_inventory(proposals, tasks, staged, decisions, manifest, actual_counts):
    proposal_map, task_map = sources.indexed(proposals), sources.indexed(tasks)
    caps = {c: max(0, 50-actual_counts[c]) for c in CLASSES}
    require(proposals and len(proposals) == len(tasks) <= sum(caps.values()), 'Empty, unpaired or over39 bulk batch')
    equal(manifest['request_count'], len(proposals), 'bulk_request_count')
    staged_keys = {r['target_key'] for r in staged}
    require(len(staged_keys) == len(staged) and set(decisions) == staged_keys, 'Missing/duplicate/foreign staged decision')
    require(all(type(decisions[k].get('approved')) is bool for k in staged_keys), 'Approval must be 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, '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 <= caps[c] for c, n in counts.items()), 'Bulk issued class remaining gap exceeded')
    equal(manifest['class_counts'], {str(c): n for c, n in counts.items()}, 'bulk_issued_counts')
    equal(manifest['classes'], sorted(counts), 'bulk_issued_classes')
    return counts, [dict(target_key=r['target_key'], reason='explicitly_withheld_after_inspection', decision=decisions[r['target_key']])
        for r in staged if r['target_key'] not in proposal_map]


def check_bulk_claims(inputs, manifest, staged, issued_counts, capacity):
    budgets = inputs['stage_budget_by_class']
    require(set(budgets) == {str(c) for c in CLASSES} and all(type(n) is int and n > 0 for n in budgets.values()),
        'Explicit four-class stage budgets required')
    staged_counts = Counter(r['class_id'] for r in staged)
    require(all(c in CLASSES and n <= budgets[str(c)] for c, n in staged_counts.items()), 'Actual staging exceeded declared budget')
    for value in (inputs, manifest):
        equal(value['unprotected_native_quality_capacity_by_class'], {str(c): n for c, n in capacity.items()}, 'recomputed_native_quality_capacity')
    equal(manifest['remaining_gap_after_all_drafts_saved'], {str(c): REMAINING[c]-issued_counts[c] for c in CLASSES},
        'conditional_remaining_gap_not_current_human_count')


def check_staging_extensions(root, inputs, staged):
    """Recover the complete preseal receipt chain, including the earlier interface.

    Only receipt bytes and append-only native-source identities are certified.
    Earlier unsealed builder digests are historical, not frozen current code pins.
    """
    roots = sorted((root/'internal').glob('staging_before_class*_extension'))
    receipts = {}
    for path in roots:
        name = str(path.relative_to(root)); match = re.fullmatch(r'internal/staging_before_class(\d+)_extension', name)
        require(match is not None and int(match[1]) in CLASSES, 'Unrecognized staging extension receipt')
        hashes = inventory(member(root, name))
        require(set(hashes) == {'input_manifest.json', 'shortlist.jsonl'}, 'Incomplete/extra staging receipt files')
        old_inputs, old_staged = read(path/'input_manifest.json'), read_jsonl(path/'shortlist.jsonl')
        require(old_inputs['shortlist_sha256'] == hashes['shortlist.jsonl'], 'Earlier shortlist binding differs')
        receipts[name] = dict(hashes=hashes, inputs=old_inputs, staged=old_staged, class_id=int(match[1]), path=path)
    # Validate explicit entries without assuming all old versions supplied a list.
    for extension in inputs.get('staging_extensions', []):
        name = extension['earlier_receipt_directory']; require(name in receipts, 'Missing explicit staging receipt')
        receipt = receipts[name]; equal(extension['earlier_receipt_sha256'], receipt['hashes'], 'explicit_earlier_receipt_bytes')
        require(type(extension['count']) is int and extension['count'] > 0 and extension['class_id'] == receipt['class_id'], 'Wrong explicit extension class/count')
        start, end = len(receipt['staged']), len(receipt['staged'])+extension['count']
        require(end <= len(staged) and all(r['class_id'] == receipt['class_id'] for r in staged[start:end]), 'Explicit extension source segment differs')
    current_inputs, current_staged = inputs, staged
    current_raw = (root/'internal/shortlist.jsonl').read_bytes(); visited, chain = set(), []
    mutable = {'shortlist_sha256', 'stage_budget_by_class', 'continuation_builder_sha256',
        'earlier_staging_preserved_sha256', 'extension_reason', 'staging_extensions'}
    while 'earlier_staging_preserved_sha256' in current_inputs:
        expected = current_inputs['earlier_staging_preserved_sha256']
        matches = [name for name, receipt in receipts.items() if receipt['hashes'] == expected]
        require(len(matches) == 1 and matches[0] not in visited, 'Missing/ambiguous/cyclic earlier staging receipt')
        name = matches[0]; visited.add(name); receipt = receipts[name]
        old_inputs, old_staged, cls = receipt['inputs'], receipt['staged'], receipt['class_id']
        old_raw = (receipt['path']/'shortlist.jsonl').read_bytes()
        require(old_raw and current_raw.startswith(old_raw) and len(current_staged) > len(old_staged)
            and current_staged[:len(old_staged)] == old_staged, 'Earlier staged bytes/records were lost or rewritten')
        added = current_staged[len(old_staged):]
        require(all(r['class_id'] == cls for r in added), 'Extension added unexpected class')
        equal({k: v for k, v in current_inputs.items() if k not in mutable},
            {k: v for k, v in old_inputs.items() if k not in mutable}, 'extension_preserved_source_count_config_and_prior_protection')
        old_budget, new_budget = old_inputs['stage_budget_by_class'], current_inputs['stage_budget_by_class']
        require(set(old_budget) == set(new_budget) == {str(c) for c in CLASSES}, 'Extension budget scope differs')
        require(all(type(n) is int and n > 0 for n in [*old_budget.values(), *new_budget.values()]), 'Extension budget is not integer')
        equal(new_budget, {c: old_budget[c]+(len(added) if c == str(cls) else 0) for c in old_budget}, 'exact_extension_budget_increase')
        require(isinstance(current_inputs['extension_reason'], str) and current_inputs['extension_reason'].strip(), 'Missing extension reason')
        chain.append(dict(directory=name, receipt_sha256=receipt['hashes'], class_id=cls, added_sources=len(added),
            historical_unsealed_builder_sha256=old_inputs['continuation_builder_sha256']))
        current_inputs, current_staged, current_raw = old_inputs, old_staged, old_raw
    require(visited == receipts.keys(), 'Unreferenced earlier staging receipt was not preserved in the chain')
    return list(reversed(chain))


def numerical_capacity(rows, formal, evidence, forbidden):
    """Native-quality candidates are only an upper bound, never semantic approvals."""
    blocked_frames = {rows[k]['frame_id'] for k in forbidden}
    blocked_hashes = {digest(member(formal, rows[k]['image'])) for k in forbidden}
    frames, hashes, counts = set(), set(), Counter()
    for key, row in sorted(rows.items()):
        if row['final_class_id'] not in CLASSES or key in forbidden or row['frame_id'] in blocked_frames:
            continue
        image_sha = digest(member(formal, row['image']))
        if image_sha in blocked_hashes or row['frame_id'] in frames or image_sha in hashes:
            continue
        try:
            geometry.native_quality(row, evidence)
        except ValueError:
            continue
        frames.add(row['frame_id']); hashes.add(image_sha); counts[row['final_class_id']] += 1
    return {c: counts[c] for c in CLASSES}


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'], '36_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, 'old_training_not_rewritten')
    equal(summary['source_registry_task_manifests'], task_manifests, 'source_task_manifests')
    equal(summary['trained_reference_keys_with_newer_human_revision'], trained_changes, 'three_old_training_references_now_revised')


def check_old_models(root=None):
    root = TRAINING_RECORDS.parents[1] if root is None else Path(root)
    for name, expected in OLD_MODEL_PINS.items():
        require(digest(member(root, name)) == expected, 'Old checkpoint/selection changed: '+name)
    return dict(OLD_MODEL_PINS)


def check_sources(snapshot, parent_manifest, pack_roots):
    require(digest(snapshot/'audit.json') == SOURCE_AUDIT_SHA256, 'Exact ready v10 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'), 'Source catalog/code pin differs')
    require(digest(QUALITY/'independent_verification.json') == geometry.QUALITY_SEAL_SHA256, 'Historical 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), 'Raw store denominators differ')
    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_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()}, '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)
    historical_extensions = {}
    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')
        # Legitimate later revisions may change prior current rows. Preserve exact
        # raw prefixes and recover old currents in history, never demand stasis.
        historical_extensions[name] = continuation.check_revision_extension(
            earlier_gallery, gallery, set(gallery['current'])-set(earlier_gallery['current']))
    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 historical changes2train/1dev')
    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 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,
        historical_extensions=historical_extensions, event_routes=previous.previous.event_namespace_counts(references))


def check_source_binding(inputs, manifest, snapshot=SNAPSHOT):
    expected = digest(snapshot/'audit.json')
    require(expected == SOURCE_AUDIT_SHA256, 'Unrecognized ready v10 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(value['previous_batch_actual_completed'], 4, 'four_real_v5_completions')
    equal(inputs['continuation_source_directory'], str(snapshot.relative_to(PROJECT)), 'explicit_source_snapshot_v10')
    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_v5', 'previous_v5_directory')
    equal(inputs['previous_batch_manifest_sha256'], SEALED_PACK_PINS['pallet_mask_under50_requests_v5']['manifest_sha256'], 'previous_v5_manifest')
    equal(inputs['source_snapshot_never_added_to_frozen_training'], True, 'no_append_to_old_training')
    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')
    root, parent, snapshot = Path(root), Path(parent), Path(snapshot)
    before = inventory(root); require(not set(SEALS) & before.keys(), 'Preserve existing v6 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, models = inventory(PROJECT/'configs'), previous.check_frozen_training(), check_old_models()
    code = {name: digest(member(PROJECT, name)) for name in ('scripts/build_mask_under50_requests_v6.py',
        'scripts/verify_mask_under50_requests_v6.py', 'tests/test_verify_mask_under50_requests_v6.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_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, 'All77 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']
    staging_extensions = check_staging_extensions(root, inputs, staged)
    records, image_hashes = 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)
    capacity = numerical_capacity(rows, formal, evidence, forbidden)
    check_bulk_claims(inputs, manifest, staged, issued_counts, capacity)
    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, 'prior_inspection_exclusion')
    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_v6.py'], 'Actual bulk builder code binding differs')
    for value in (inputs, manifest):
        equal(value['continuation_builder_sha256'], code['scripts/build_mask_under50_requests_v6.py'], 'bulk_builder_code_pin')
    equal(manifest['reused_continuation_context_sha256'], HELPER_PINS['scripts/build_mask_under50_requests_v2.py'], 'frozen_v2_context_pin')
    require(inventory(root) == before and inventory(PROJECT/'configs') == config and sources.protected_inventory(formal) == protected, 'Task/config/formal changed during audit')
    for kind, path, store in (('pose', POSE, pose), ('gallery', GALLERY, gallery)):
        equal(sources.read_store(path, kind), store, 'live_source_changed_'+kind)
        require(geometry.database_fingerprint(path) == fingerprints[str(path.relative_to(PROJECT))], 'Live fingerprint changed')
    require(geometry.prior_inspections(PROJECT, root, rows)[0] == prior_hashes, 'Global inspection history changed')
    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')
    for name, expected in old_before.items():
        require(inventory(PROJECT/name) == expected, 'Old task/source snapshot changed')
    equal(previous.check_frozen_training(), training, 'frozen229_dataset_and_source_keys_preserved')
    equal(check_old_models(), models, 'old_models_preserved_separate_from_authorized_new_training')
    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=36,
        all36_previous_tasks_are_real_changed_human_saves=True, all77_previous_staged_sources_excluded=True, previous_pack_pins=SEALED_PACK_PINS,
        remaining_authorized_per_class=REMAINING, total_remaining_authorized=39, issued_per_class_cap='remaining_to50_not_old_max2',
        staged_alternatives_not_capped_at_old3=True, excluded_classes_already_at_50=[17, 20], class_scope=geometry.CLASS_SCOPE,
        native_quality_candidate_capacity=capacity, numerical_capacity_not_semantic_approval=True,
        remaining_unissued_per_class={c: REMAINING[c]-issued_counts[c] for c in CLASSES},
        minimum_source_capacity_shortfall_per_class={c: max(0, REMAINING[c]-capacity[c]) for c in CLASSES},
        own_staged_source_count=len(staged), withheld_source_count=len(deferred), all_prior_inspected_sources_excluded=True,
        staging_extensions_independently_verified=staging_extensions,
        prior_request_inventories_sha256=prior_hashes, preactivation_database_fingerprints=fingerprints, source_fingerprints=dict(pose=pose['fingerprint'], gallery=gallery['fingerprint']),
        **context['extension'], historical_snapshot_extensions=context['historical_extensions'],
        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, old_model_pins=models,
        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.',
            'The56 appended events comprise17 revisions on14 old images plus10/11/7/6/5 events on10/9/7/6/4 prior under50 images.',
            'Repeated real human saves are legitimate revisions, not additional distinct sources; old raw currents remain recoverable in history.',
            'All36 prior tasks are changed real human saves;1520 saved research contours are not automatically GT or training/robot eligible.',
            'Bulk dispatch is bounded by remaining23/3/6/7, not the obsolete two-image pilot cap; staging alternatives may exceed the gap.',
            'Numerical native-quality capacity is an upper bound. Semantic uncertainty or insufficient fresh sources cannot be waived to fill quotas.',
            'Full/crop/grid/final-overlay inspection is assistant-reported, not independently observed subjective accuracy.',
            'Validation/test sources retain formal splits; valid four-point contours need no forced vertices and gain no old seed eligibility.',
            'Three old training references have newer research revisions (2train/1dev); old229 labels, source keys and checkpoints stay frozen.',
            'Separately authorized new-version training is outside this worklist audit; no new model files or services are inspected or changed.',
            'This preactivation seal requires exact current 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 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_v6', 'Only exact new v6 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 v6 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')
    verified = seal(producer_complete=parser.parse_args().producer_complete)
    print(json.dumps({key: verified[key] for key in ('state', 'request_count', 'class_counts', 'actual_completed_previous_under50_tasks',
        'actual_human_saved_sources', 'gallery_events_verified', 'remaining_unissued_per_class', 'semantic_contour_accuracy_established')}, ensure_ascii=False), flush=True)
