"""Independent, read-only publication-12 audit, run ONLY after generation finishes.

The new generator is neither imported nor invoked. Frozen publication-11 audit
primitives are reusable evidence readers, not mutable policy: this module owns
the new counts, statement scopes, seed selection, scanning and full replay.
Only validation_report.json and an exclusive verification.json are written.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from contextlib import closing
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import sqlite3
import sys

import cv2
import numpy as np

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from pallet.cluster_targets import digest, protected_snapshot
from pallet.mask_boundary_review import affine_reference, beam_boundary_audit
from pallet.mask_template_transfer import ImageEvidence, compatible, correlate, transfer
from pallet.pose_review_geometry import canonical, polygon_value
from scripts import verify_mask_remaining_continue as previous
from scripts import verify_mask_remaining_expand as matching
from scripts import verify_mask_remaining_classes as sources
from scripts import verify_mask_quota_100_complete as baseline
from scripts.verify_mask_quota_completion import check_assets

helpers = sources.helpers
require, sha = helpers.require, helpers.sha
read_json, read_jsonl, indexed = helpers.read_json, helpers.read_jsonl, helpers.indexed
file_inventory = sources.file_inventory
alias, claim, no_confirmation = matching.alias, matching.claim, matching.no_confirmation
CLASSES = tuple(range(1, 23))
REMAINING = (3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22)
OLD_CLASSES = (1, 2, 9, 10, 15)
COMPLETED = (1, 2, 3, 6, 9, 10, 13, 15)
LIMIT, PUBLICATION = 100, 12
NAMESPACE = 'remaining_round2_generation'
POSE_ORIGIN, GALLERY_ORIGIN = previous.POSE_ORIGIN, previous.GALLERY_ORIGIN
REVIEW_SCHEMA, REVIEW_ORIGINS = previous.REVIEW_SCHEMA, previous.REVIEW_ORIGINS
USER_STATEMENT = '已经完成185张候选复核和54张新图的标注，其中没有修改记录的是检验后无需修改的。继续'
OLD_ORIGINAL_REVIEWS = dict(previous.ORIGINAL_REVIEWS)
NEW_ORIGINAL_REVIEWS = {key: (4, 1) for key in (
    '0f62405fc643c71371c8a0ec', '7041455b447a160ccc16d9df', 'db94cf18b0c6e9f8641a9be0')}
ORIGINAL_REVIEWS = {**OLD_ORIGINAL_REVIEWS, **NEW_ORIGINAL_REVIEWS}
PARENT = PROJECT/'outputs/pallet_mask_remaining_continue_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_remaining_followup_requests_v2'
OUTPUT = PROJECT/'outputs/pallet_mask_remaining_round2_v1'
POSE, GALLERY = sources.POSE, sources.GALLERY
GENERATOR = 'pallet/mask_remaining_round2.py'
REPORT, SEAL = 'validation_report.json', 'verification.json'
ASSETS, ACCEPTED_REASONS = matching.ASSETS, matching.ACCEPTED_REASONS
PARENT_PINS = {
    'manifest.json': '37a84183b68c93907bc9f1a4176b7b429629ec197a36f47b67e4f247ec59a301',
    'verification.json': 'b0ce96126faaeceb334cb0f9a09441951f5c8fd2181b875745a13b653a03ef78',
    'validation_report.json': 'f22314b53fda56e81840fcd34fd0f80da2ee67915b60ee2b97bc46964e5b510c',
    'proposals.jsonl': '8da4534ba1e947c66fc31d73559a8a3e6ae1cea2531c0869c99df2eb9509ab67',
    'new_proposals.jsonl': 'e2d505640aad83ee390de38f730381f5e721aa0f2d25f6a36cd9d6da8dc9978a',
    'manual_proposals.jsonl': '112a14b88f1c81106b72d97b0012ac7147847ccf446d8a4dd94af3f5a04ddde1',
    'artifact_hashes.json': '89b2e268103a799e35a233ec6c745e552a272360bdb5ca020e2462c13fcd2db7',
    'pallet_mask_refined_review.zip': 'a04747bf1cc380718a414b6644c946eb604f097a57e8265427be5b01c6e8c7d5',
}
REQUEST_PINS = {
    'manifest.json': 'd44e8b857b5097c5b11ad3fe22ef4146c5fc8a0cb965c657894bcded14789489',
    'independent_verification.json': '916ea1eaccc81ffd63048d787724b49bdb9be16cb9f5edff8555ec0e782b0a12',
    'verification.json': '916ea1eaccc81ffd63048d787724b49bdb9be16cb9f5edff8555ec0e782b0a12',
    'requests.jsonl': 'ddf7aaf685ace8c7e0061888b1f671c950247247bf093c841e7e5e6bfc29d416',
}
BASE_COUNTS = {**dict.fromkeys(COMPLETED, 100), 4: 26, 5: 32, 7: 25, 8: 53,
    11: 12, 12: 46, 14: 41, 16: 30, 17: 40, 18: 36, 19: 23, 20: 43, 21: 54, 22: 89}


def check_claims(manifest):
    for field, expected in dict(publication_version=PUBLICATION, method='original', target_per_class=LIMIT,
            generation_template_namespace=NAMESPACE, original_splits_preserved=True,
            classification_is_candidate_not_truth=True).items():
        claim(manifest, field, expected)
    for field in ('production_database_writes', 'configuration_writes', 'service_writes', 'new_human_edits_created'):
        claim(manifest, field, 0)
    for field in ('research_candidates_added', 'cross_split_template_transfers', 'human_requests_created'):
        claim(manifest, field, 0, required=False)
    for field in ('thresholds_relaxed', 'forced_fill', 'recursive_candidate_propagation',
            'automatic_human_confirmation', 'automatic_training_eligible', 'robot_command_eligible', 'ground_truth_eligible'):
        claim(manifest, field, False)
    for field in ('duplicate_fill', 'human_confirmation_inferred', 'activated', 'published', 'all_classes_complete',
            'manual_source_snapshots_imported_into_gallery_store', 'review_dispositions_are_saved_human_masks',
            'review_dispositions_seed_authorization'):
        claim(manifest, field, False, required=False)


def check_inputs():
    for root, pins in ((PARENT, PARENT_PINS), (REQUESTS, REQUEST_PINS)):
        for name, expected in pins.items():
            require(digest(root/name) == expected, 'Pinned immutable input changed: '+str(root/name))
    manifest, seal = read_json(PARENT/'manifest.json'), read_json(PARENT/SEAL)
    require(seal['state'] == 'passed' and seal['publication_version'] == manifest['publication_version'] == 11
        and seal['proposals_verified'] == manifest['proposals'] == 1296 and seal['new_verified'] == 185,
        'Need independently sealed publication11 1296/185')
    for field, name in (('manifest_sha256', 'manifest.json'), ('proposals_sha256', 'proposals.jsonl'),
            ('artifact_hashes_sha256', 'artifact_hashes.json'), ('validation_report_sha256', REPORT)):
        claim(seal, field, digest(PARENT/name))
    require(read_json(PARENT/REPORT) == {k: v for k, v in seal.items() if k != 'validation_report_sha256'},
        'Parent independent report/seal differs')
    require(seal['verification_script_sha256'] == digest(previous.__file__), 'Frozen publication11 verifier changed')
    for field in ('all_new_registrations_and_metrics_recomputed', 'all_rejected_attempts_and_metrics_recomputed',
            'manual_exact_sqlite_payloads_and_human_events_verified', 'live_dependencies_unchanged'):
        claim(seal, field, True)
    helpers.check_artifacts(PARENT, read_json(PARENT/'artifact_hashes.json'))
    request_seal, request_manifest = read_json(REQUESTS/'independent_verification.json'), read_json(REQUESTS/'manifest.json')
    require(request_seal['state'] == 'passed' and request_seal['request_count'] == 54
        and request_seal['manifest_sha256'] == digest(REQUESTS/'manifest.json')
        and request_seal['requests_sha256'] == digest(REQUESTS/'requests.jsonl')
        and request_seal['parent_verification_sha256'] == PARENT_PINS[SEAL], 'Exact54 independent request binding differs')
    helpers.check_artifacts(REQUESTS, request_manifest['public_assets'])
    helpers.check_artifacts(REQUESTS, read_json(REQUESTS/'artifact_hashes.json'))
    old, old_manual, old_new, requests = (indexed(read_jsonl(path)) for path in
        (PARENT/'proposals.jsonl', PARENT/'manual_proposals.jsonl', PARENT/'new_proposals.jsonl', REQUESTS/'requests.jsonl'))
    require(len(old) == 1296 and len(old_manual) == 50 and len(old_new) == 185
        and all(old.get(k) == p for k, p in {**old_manual, **old_new}.items()), 'Parent canonical partitions differ')
    require(len(requests) == 54 and Counter(r['class_id'] for r in requests.values()) == {3: 4, 4: 10, 5: 10, 7: 10, 14: 10, 22: 10},
        'All and only the sealed54 tasks must be imported')
    # Older checks are called with their real frozen inputs, never patched counts.
    prior_data = previous.check_inputs()
    publications = prior_data['publications']
    publications[11] = dict(path=PARENT, proposals=old, manifest=manifest)
    inputs = {**prior_data['inputs'], PARENT: file_inventory(PARENT), REQUESTS: file_inventory(REQUESTS)}
    return dict(old=old, old_manual=old_manual, old_new=old_new, requests=requests,
        parent_manifest=manifest, publications=publications, inputs=inputs)


def check_partition(old, requests, manual, new, combined, accepted):
    require(len(old) == 1296 and len(manual) == 54 and set(manual) == set(requests), 'Expected immutable1296 plus exact54')
    require(not (set(old) & set(manual) or set(new) & (set(old) | set(manual))), 'Human/history/machine partitions overlap')
    require(set(combined) == set(old) | set(manual) | set(new), 'Cumulative inventory differs from1296+54+N')
    require(set(accepted).isdisjoint(set(old) | set(manual)) and set(new) <= set(accepted), 'Invalid accepted-machine partition')
    for inventory in (old, manual, new):
        require(all(combined[k] == p for k, p in inventory.items()), 'Canonical cumulative proposal changed')
    require(all(accepted[k] == p for k, p in new.items()), 'Selected object differs from accepted object')
    require(all(p['class_id'] in REMAINING and p['class_id'] not in COMPLETED for p in accepted.values()),
        'Machine generation entered a completed class, including newly completed class3')
    require({k for k, p in manual.items() if p.get('schema') == REVIEW_SCHEMA} == set(NEW_ORIGINAL_REVIEWS),
        'Exactly three new original rectangles must remain review-only')
    require({k for k, p in old.items() if p.get('schema') == REVIEW_SCHEMA} == set(OLD_ORIGINAL_REVIEWS),
        'Two historical review-only original rectangles were lost')
    require(Counter(p['class_id'] for p in list(old.values())+list(manual.values())) == BASE_COUNTS,
        'Exact locked1350 per-class baseline differs')
    result = matching.count_frames(combined)
    require(all(result[str(c)]['proposals'] == LIMIT for c in COMPLETED), 'Completed class lost or overfilled')
    return result


def check_preservation(out, old):
    current, historic = matching.raw_lines(out/'proposals.jsonl'), matching.raw_lines(PARENT/'proposals.jsonl')
    require(all(current[k] == historic[k] for k in old), 'Parent1296 canonical JSONL bytes changed')
    names = {f'{folder}/{key}.{ext}' for key in old for folder, ext in ASSETS}
    for directory in PARENT.iterdir():
        if directory.is_dir() and (directory.name in ('templates', 'refined', 'generation') or directory.name.endswith('_generation')):
            names.update(str(p.relative_to(PARENT)) for p in directory.rglob('*') if p.is_file())
    for name in names:
        require((out/name).is_file() and not (out/name).is_symlink() and digest(out/name) == digest(PARENT/name),
            'Historical asset/namespace changed: '+name)
    require(file_inventory(out/'parent_evidence') == file_inventory(PARENT), 'Complete frozen private parent archive differs')
    require((out/'review_dispositions.jsonl').read_bytes() == (PARENT/'review_dispositions.jsonl').read_bytes(),
        'Old45 dispositions changed')
    for name in ('review_disposition_statement.json', 'disposition_scope_source.jsonl'):
        expected = digest(sources.BASELINE/name)
        previous.preserved_private(PARENT, name, expected)
        previous.preserved_private(out, name, expected)
    require(digest(out/'parent_evidence/review_completion_statement.json') == digest(PARENT/'review_completion_statement.json'),
        'Historical two-review statement must remain in parent_evidence, not gain latest54 scope')


def raw_rows(snapshot, table):
    require(table in ('annotations', 'reviews'), 'Unsafe current table')
    with closing(sqlite3.connect(snapshot.resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        records = list(db.execute(f'SELECT target_key,revision,payload FROM {table}'))
    return indexed([dict(target_key=k, revision=r, raw=raw) for k, r, raw in records])


def check_store_delta(parent_snapshots, snapshots, parent_stores, stores, requests, old_new):
    """No unrelated edit, even JSON-equivalent raw whitespace, can be hidden."""
    result = {}
    for kind, table, authorized, new_events, new_records in (
            ('pose', 'annotations', set(requests), 145, 34), ('gallery', 'reviews', set(old_new), 201, 185)):
        before, after = parent_stores[kind], stores[kind]
        helpers.preserve_events(before, after)
        require(after['events'][:len(before['events'])] == before['events'], 'Historical event prefix changed')
        added = after['events'][len(before['events']):]
        require(len(added) == new_events and {e[1] for e in added} == authorized,
            'Only exact current-batch task/review events may be added: '+kind)
        oldraw, newraw = raw_rows(parent_snapshots[kind], table), raw_rows(snapshots[kind], table)
        require(set(oldraw) <= set(newraw) and len(newraw)-len(oldraw) == new_records, 'Current record delta differs: '+kind)
        require(set(newraw)-set(oldraw) <= authorized, 'Unrelated current record created')
        for key, value in oldraw.items():
            if key not in authorized:
                require(newraw[key] == value, 'Unrelated historical current raw bytes changed: '+key)
        for key in authorized:
            revision, raw, (_, event_revision, event_raw) = previous.raw_current(snapshots[kind], table, key)
            require(raw == event_raw and revision == event_revision
                and (key not in oldraw or revision > oldraw[key]['revision']), 'New source is not a new exact latest save: '+key)
        result[kind] = dict(historical_events_preserved=len(before['events']), new_events=len(added),
            current_changed_keys=sorted(k for k in newraw if newraw[k] != oldraw.get(k)), unrelated_source_changes=0)
    return result


def check_statement(value):
    claim(value, ('user_statement', 'statement_zh'), USER_STATEMENT)
    claim(value, 'user_statement_sha256', hashlib.sha256(USER_STATEMENT.encode()).hexdigest(), required=False)
    claim(value, 'human_confirmation_inferred', False, required=False)


def original_review_source(key, pose, row, snapshot):
    require(key in ORIGINAL_REVIEWS and key in pose['current'], 'Original review outside exact authorized five')
    cls, expected_revision = ORIGINAL_REVIEWS[key]
    value, binding = pose['current'][key], sha(json.loads(pose['metadata']['binding']))
    history = []
    for event_id, k, revision, raw in pose['events']:
        if k != key:
            continue
        event = json.loads(raw)
        sources.same_identity(event.get('source'), row, 'Original review event')
        require(event.get('target_key') == key and event.get('revision') == revision and event.get('binding') == binding
            and event.get('state') == 'draft' and sources.original_rectangle(event.get('polygon'), row)
            and not sources.protected_state(event) and not sources.machine_marked(event)
            and event.get('event_kind') not in sources.AUTO, 'Original review has edited/machine/protected history')
        require(all(event['source'].get(f, row.get(f)) == row.get(f) for f in ('final_class_id', 'viewpoint_candidate')),
            'Original review candidate class/view differs')
        no_confirmation(event, key)
        require(event.get('full_six_dof', False) is False and all((event.get('pose') or {}).get(f, False) is False
            for f in (*sources.FALSE_FLAGS, 'full_six_dof')), 'Original review implies confirmed pose')
        history.append((event_id, revision, raw))
    sources.same_identity(value.get('source'), row, 'Original review current')
    revision, raw, (event_id, event_revision, event_raw) = previous.raw_current(snapshot, 'annotations', key)
    require(row['final_class_id'] == cls and revision == expected_revision and json.loads(raw) == value
        and raw == event_raw and history and history[-1] == (event_id, revision, raw)
        and len({r for _, r, _ in history}) == len(history) and max(r for _, r, _ in history) == revision,
        'Original review store/current exact latest binding differs')
    polygon_value(value['polygon'], *row['size'])
    return dict(target_key=key, row=row, polygon=value['polygon'], current_revision=revision,
        current_payload_sha256=sha(value), current_payload_raw=raw, current_payload=value,
        current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(), saved_review_event_id=event_id,
        saved_review_revision=event_revision, saved_review_event_sha256=hashlib.sha256(event_raw.encode()).hexdigest(),
        saved_review_event_payload_raw=event_raw, saved_review_event_payload=json.loads(event_raw), vertex_count=4,
        history_event_ids=[i for i, _, _ in history], original_rectangle_review_only=True,
        human_edited=False, propagation_seed_eligible=False)


def check_review_records(out, originals, pose_sha, requests):
    path = out/'reviewed_original_rectangle_source_records.jsonl'
    records = indexed(read_jsonl(path))
    require(set(records) == set(originals) == set(ORIGINAL_REVIEWS), 'All five distinct original-review raw records required')
    require(path.stat().st_mode & 0o077 == 0, 'Raw review-only records must be private')
    statement_path = out/'review_completion_statement.json'
    statement = read_json(statement_path)
    check_statement(statement)
    for field, expected in dict(schema='explicit_user_review_no_change_statement_v1', scoped_request_keys=sorted(requests),
            reviewed_original_rectangle_keys=sorted(NEW_ORIGINAL_REVIEWS), candidate_count_in_statement=185,
            actual_parent_batch_saved_count=185, old_42_unsaved_not_inferred_reviewed=True,
            creates_human_event=False, confirms_ground_truth=False, authorizes_propagation=False).items():
        claim(statement, field, expected)
    historical = read_json(out/'parent_evidence/review_completion_statement.json')
    previous.check_statement(historical)
    require(historical == read_json(PARENT/'review_completion_statement.json'), 'Historical review statement scope changed')
    inherited = indexed(read_jsonl(PARENT/'reviewed_original_rectangle_source_records.jsonl'))
    current_lines = matching.raw_lines(path)
    inherited_lines = matching.raw_lines(PARENT/'reviewed_original_rectangle_source_records.jsonl')
    fields = ('target_key', 'current_revision', 'current_payload_sha256', 'current_payload_raw', 'current_payload',
        'current_payload_raw_sha256', 'saved_review_event_id', 'saved_review_revision', 'saved_review_event_sha256',
        'saved_review_event_payload_raw', 'saved_review_event_payload', 'history_event_ids')
    for key, source in originals.items():
        authority = historical if key in OLD_ORIGINAL_REVIEWS else statement
        expected = {f: source[f] for f in fields}
        expected.update(schema='reviewed_original_rectangle_source_freeze_v1', source=source['row'],
            source_identity_sha256=sha(source['row']),
            snapshot_sha256=digest(PARENT/'reviews_snapshot.sqlite3') if key in OLD_ORIGINAL_REVIEWS else pose_sha,
            polygon_sha256=sha(source['polygon']),
            propagation_seed_eligible=False, human_edited=False, original_rectangle_review_only=True,
            saved_pose_review_source=True, user_reviewed_no_change=True, user_statement_sha256=sha(authority),
            classification_is_candidate_not_truth=True, **dict.fromkeys(baseline.previous.FALSE_FLAGS, False))
        require(records[key] == expected, 'Exact original-review raw/event/statement scope differs: '+key)
        if key in OLD_ORIGINAL_REVIEWS:
            require(records[key] == inherited[key] and current_lines[key] == inherited_lines[key],
                'Historical original-review raw records must remain byte-identical, not rebound to new snapshots')
        source['user_statement_sha256'] = sha(authority)
        no_confirmation(records[key], key)
    return records, statement


def check_original_review(proposal, request, source, pose_sha, formal_sha, class_sha):
    key, row = proposal['target_key'], source['row']
    require(key in NEW_ORIGINAL_REVIEWS and proposal['schema'] == REVIEW_SCHEMA and proposal['origin'] in REVIEW_ORIGINS,
        'New original rectangle must remain a review-only entry')
    require(proposal['human_edited'] is False and proposal['propagation_seed_eligible'] is False
        and proposal['original_rectangle_review_only'] is True and 'template' not in proposal,
        'Original review cannot masquerade as edit or seed')
    no_confirmation(proposal, key)
    for field in ('pose_store_written', 'gallery_store_written', 'machine_transfer_performed', 'new_human_edit_created'):
        claim(proposal, field, False)
    claim(proposal, 'manual_four_point_source', False, required=False)
    require(proposal['source'] == row and proposal['class_id'] == request['class_id'] == row['final_class_id']
        and proposal['polygon'] == source['polygon'] and proposal['vertex_count'] == 4, 'Original review identity/polygon differs')
    sources.same_identity(request['source'], row, 'Original review request')
    require(request['source'].get('viewpoint_candidate') == row.get('viewpoint_candidate'), 'Original request view differs')
    require(proposal['snapshot_sha256'] == pose_sha and proposal['target_expected_revision'] == source['current_revision']
        and proposal['target_snapshot_payload_sha256'] == source['current_payload_sha256']
        and proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == class_sha,
        'Original review current/formal binding differs')
    require(proposal['manual_request_sha256'] == sha(request) and proposal['original_pose_url'] == request['pose_annotation_url']
        and proposal['metrics'] == {} and 'continuation' not in proposal, 'Original review invents request/transfer')
    provenance = dict(target_key=key, snapshot_sha256=pose_sha, revision=source['current_revision'],
        payload_sha256=source['current_payload_sha256'], saved_review_revision=source['saved_review_revision'],
        saved_review_event_id=source['saved_review_event_id'], saved_review_event_sha256=source['saved_review_event_sha256'],
        polygon_sha256=sha(source['polygon']), user_statement_sha256=source['user_statement_sha256'])
    expected = dict(target_key=key, class_id=row['final_class_id'], split=row['split'],
        snapshot_revision=source['current_revision'], current_payload_sha256=source['current_payload_sha256'],
        origin=proposal['origin'], vertex_count=4, human_edited=False, saved_pose_review_source=True,
        user_reviewed_no_change=True, original_rectangle_review_only=True, propagation_seed_eligible=False, pose_review=provenance)
    require(proposal['human_source'] == expected, 'Original review saved event/statement/source binding differs')
    require(not any(f in proposal for f in ('human_polygon_revision', 'human_event_id', 'human_event_sha256')),
        'Original review invents modified-polygon event')
    require(proposal['original_box_review_basis'] == 'review_completion_statement.json'
        and proposal['rendering_id'].startswith(NAMESPACE+':') and proposal['rendering_id'].endswith(':'+key),
        'New review statement/rendering scope differs')
    for field, expected in dict(source_label_kind='REVIEWED_ORIGINAL_RECTANGLE',
            status='user_reviewed_original_rectangle_pending_confirmation', saved_pose_review_source=True,
            user_reviewed_no_change=True).items():
        claim(proposal, field, expected)


template_binding = previous.template_binding


def check_manual(proposal, request, row, recovered, pose_sha, formal_sha, class_sha):
    key = proposal['target_key']
    require(key in recovered and key not in ORIGINAL_REVIEWS, 'Manual source lacks a real modified human contour')
    source, four = recovered[key], recovered[key]['vertex_count'] == 4
    require(source['human_polygon_revision'] == source['current_revision'],
        'New completed task must use its actual latest direct human revision, not normalization')
    require(proposal['source'] == row and request['class_id'] == proposal['class_id'] == row['final_class_id'], 'Manual class/source differs')
    sources.same_identity(request['source'], row, 'Completed request')
    require(request['source'].get('viewpoint_candidate') == row.get('viewpoint_candidate'), 'Manual request view differs')
    require(proposal['polygon'] == source['polygon'] and proposal['vertex_count'] == source['vertex_count']
        and proposal['manual_four_point_source'] is four and proposal['propagation_seed_eligible'] is (not four),
        'Manual topology/seed policy differs')
    require(proposal['schema'] == 'saved_pose_mask_gallery_entry_v1' and proposal['origin'] == POSE_ORIGIN
        and proposal['human_edited'] is True and proposal['status'] == 'human_edited_draft_pending_confirmation', 'Manual provenance differs')
    no_confirmation(proposal, key)
    for field in ('pose_store_written', 'gallery_store_written', 'machine_transfer_performed', 'new_human_edit_created'):
        claim(proposal, field, False)
    field = 'human_source' if four else 'template'
    require(proposal[field] == template_binding(matching.pose_template(source, pose_sha))
        and ('template' not in proposal if four else 'human_source' not in proposal), 'Manual exact human-event binding differs')
    require(proposal['snapshot_sha256'] == pose_sha and proposal['target_expected_revision'] == source['current_revision']
        and proposal['target_snapshot_payload_sha256'] == source['current_payload_sha256']
        and proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == class_sha,
        'Manual current/formal binding differs')
    require(proposal['manual_request_sha256'] == sha(request) and proposal['original_pose_url'] == request['pose_annotation_url']
        and proposal['metrics'] == {} and 'continuation' not in proposal, 'Manual invents request/transfer')
    require(proposal['rendering_id'] == NAMESPACE+(':manual_source:' if four else ':')+key, 'Manual rendering namespace differs')


def independent_seeds(pose_keys, recovered, gallery, parent_seed_keys, old_new, manual, pose_sha):
    require(set(pose_keys) <= set(recovered) and set(old_new) <= set(gallery), 'Counted current human review evidence missing')
    result = {k: matching.pose_template(recovered[k], pose_sha) for k in sorted(pose_keys)
        if recovered[k]['vertex_count'] > 4 and recovered[k]['row']['final_class_id'] in REMAINING}
    for key, template in sorted(gallery.items()):
        if template['row']['final_class_id'] in REMAINING:
            require(key not in result and len(template['polygon']) > 4, 'Gallery seed duplicates pose or has only four points')
            result[key] = template
    new_fine = {k for k, p in manual.items() if p['class_id'] == 3 and p['vertex_count'] > 4}
    require(set(result) == set(parent_seed_keys) | set(old_new) | new_fine,
        'Seed inventory must be exact parent410 + saved185 + new class3 four')
    require(not set(ORIGINAL_REVIEWS) & set(result) and all(len(t['polygon']) > 4
        and t['row']['final_class_id'] not in OLD_CLASSES for t in result.values()), 'Quad/review-only/old-five entered seeds')
    return result


def check_human_audits(out, inherited, modified, originals, records, pose_sha, templates):
    audits = indexed(read_jsonl(out/'human_source_audit.jsonl'))
    require(set(audits) == set(inherited) | set(modified) | set(originals), 'All434 modified and5 review-only pose audits required')
    for key, item in audits.items():
        source = originals[key] if key in originals else records[key]
        expected = dict(target_key=key, class_id=source['current_payload']['source'].get('final_class_id',
                originals[key]['row']['final_class_id'] if key in originals else (inherited.get(key) or modified[key])['class_id']),
            current_revision=source['current_revision'], current_payload_sha256=source['current_payload_sha256'],
            current_payload_raw_sha256=source['current_payload_raw_sha256'], exact_current_and_event_validated=True,
            modified_human_contour=key not in originals, original_rectangle_review_only=key in originals,
            vertex_count=len(source['current_payload']['polygon']), historical_canonical_preserved=key in inherited or key in OLD_ORIGINAL_REVIEWS,
            current_template_selected=key in templates, snapshot_sha256=pose_sha)
        if key in OLD_ORIGINAL_REVIEWS:
            expected.update(original_statement_path='parent_evidence/review_completion_statement.json',
                original_statement_sha256=originals[key]['user_statement_sha256'])
        require(item == expected, 'Actual current/source-kind/historical audit differs: '+key)


def replay(template, row, evidence):
    polygon, metrics = transfer(evidence.patch(template['row']['target_key']), evidence.patch(row['target_key']),
        template['polygon'], template['row'], row)
    if polygon is not None:
        guard = beam_boundary_audit(evidence.image(row['frame_id']), polygon,
            affine_reference(dict(source=row, metrics=metrics), template))
        metrics['boundary_guard'] = guard
        if guard['state'] != 'passed':
            polygon, metrics['rejection'] = None, 'local_beam_boundary_review_required'
    return polygon, metrics


def audit_attempts(attempts, rows, templates, accepted, outcomes, evidence, protected_keys=(), protected_frames=()):
    require(set(outcomes) == set(rows), 'Outcomes must cover the fixed formal denominator')
    bytarget = defaultdict(list)
    for trial in attempts:
        key = trial['target_key']
        require(key in rows and trial['class_id'] == rows[key]['final_class_id'], 'Attempt identity/class differs')
        bytarget[key].append(trial)
    eligible = set()
    for key, row in sorted(rows.items()):
        outcome = outcomes[key]
        require(outcome['class_id'] == row['final_class_id'], 'Outcome class differs')
        if key in protected_keys or row['frame_id'] in protected_frames or row['final_class_id'] in COMPLETED:
            require(key not in bytarget and key not in accepted and outcome['reason'] not in ACCEPTED_REASONS,
                'Protected/completed-class target attempted or accepted')
            continue
        require(row['final_class_id'] in REMAINING, 'Unknown generation class')
        eligible.add(key)
        choices = [k for k, t in templates.items() if compatible(t['row'], row)]
        trials = bytarget.get(key, [])
        if not choices:
            require(not trials and key not in accepted and outcome['reason'] == 'no_compatible_template', 'False no-template outcome')
            continue
        ranked = sorted(((correlate(evidence.patch(k), evidence.patch(key)), k) for k in choices), reverse=True)
        passing = [k for similarity, k in ranked if similarity >= .55]
        if key in accepted:
            source = accepted[key]['template']['target_key']
            require(source in passing, 'Accepted template below unchanged correlation gate')
            expected = passing[:passing.index(source)+1]
            continuation = accepted[key]['continuation']
            claim(continuation, 'batch', PUBLICATION)
            claim(continuation, 'recursive_candidate_propagation', False)
            claim(continuation, ('all_compatible_targets_scanned', 'all_compatible_templates_considered'), True)
            claim(continuation, 'template_rank', next(i for i, (_, k) in enumerate(ranked, 1) if k == source))
        else:
            expected = passing
            require(outcome['reason'] == ('registration_or_boundary_rejected' if passing else 'image_similarity_below_gate'),
                'False registration/similarity rejection')
        require([t['template_key'] for t in trials] == expected, 'Compatible-template attempt coverage/order differs: '+key)
        for number, trial in enumerate(trials):
            polygon, metrics = replay(templates[trial['template_key']], row, evidence)
            success = key in accepted and number == len(trials)-1
            require((polygon is not None) is success, 'Passing/rejected registration disposition differs: '+key)
            helpers.equal_metrics(trial['metrics'], metrics, key+'.attempt')
            if success:
                require(metrics['initial_ncc'] >= .55 and metrics['ecc'] >= .84 and metrics['boundary_ncc'] >= .78
                    and max(metrics['forward_backward_error_patch_pixels']) <= 1.5
                    and metrics['boundary_guard']['state'] == 'passed', 'Original unchanged gates failed')
                np.testing.assert_allclose(accepted[key]['polygon'], polygon, rtol=0, atol=helpers.ATOL)
                helpers.equal_metrics(accepted[key]['metrics'], metrics, key+'.accepted')
    require(set(bytarget) <= eligible and set(accepted) <= eligible, 'Attempt/accepted target outside eligible pool')
    require({k for k, o in outcomes.items() if o['reason'] in ACCEPTED_REASONS} == set(accepted), 'Accepted outcome coverage differs')
    return eligible


def scan_inventory(rows, pose, gallery, base, quarantine, outcomes):
    reasons, _, locked_frames = matching.scan_reasons(rows, pose, gallery, base, quarantine)
    protected_keys, protected_frames = matching.target_protection(rows, pose, gallery, base, {}, quarantine)
    excluded = set()
    for key, row in rows.items():
        reason = reasons[key]
        if reason == 'eligible' and row['frame_id'] in protected_frames and row['final_class_id'] not in COMPLETED:
            require(outcomes[key]['reason'] == 'no_compatible_template' and outcomes[key]['registration_attempts'] == 0,
                'Protected-frame sibling must remain untouched no-template diagnostic: '+key)
            continue
        if reason == 'eligible' and row['final_class_id'] in COMPLETED:
            allowed = {'class_quota_already_full', 'class_quota_full', 'quota_already_complete', 'class_not_requested', 'locked_class_quota_full'}
        elif reason != 'eligible':
            allowed = {reason}
        else:
            continue
        require(outcomes[key]['reason'] in allowed and outcomes[key]['registration_attempts'] == 0,
            'Protected/completed target scan disposition differs: '+key)
        excluded.add(key)
    return excluded, protected_keys, protected_frames, locked_frames


def check_machine(proposal, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha):
    require(proposal['class_id'] not in COMPLETED, 'Machine generation entered a completed class')
    previous.check_machine(proposal, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha)
    require(proposal.get('human_edited') is False and proposal['template'] == template_binding(templates[proposal['template']['target_key']]),
        'Machine is not bound to the actual current saved source')
    require(proposal['rendering_id'] == NAMESPACE+':'+proposal['template']['target_key'], 'Machine rendering namespace differs')


def check_rendering(out, inventory, templates, manual, new):
    parent = read_json(PARENT/'template_inventory.json')
    historic, actual = (indexed(v['templates'], 'rendering_id') for v in (parent, inventory))
    require(all(actual.get(k) == v for k, v in historic.items()), 'Historical rendering payload changed')
    latest = {k: v for k, v in actual.items() if k not in historic}
    require(set(latest) == {NAMESPACE+':'+k for k in templates}, 'New generation rendering includes extra/quad/unreviewed seed')
    for key, template in templates.items():
        for field, value in template.items():
            require(latest[NAMESPACE+':'+key].get(field) == value, 'New seed provenance differs: '+key)
        exported = read_json(out/NAMESPACE/'templates'/f'{key}.json')
        require(all(exported.get(f) == v for f, v in template.items()), 'Exported new seed differs: '+key)
        no_confirmation(exported, key)
        claim(exported, 'propagation_seed_eligible', True)
    require({p.name for p in (out/NAMESPACE/'templates').iterdir()} == {k+'.json' for k in templates}, 'New seed files differ')
    mapping = dict(parent['rendering_by_target'])
    mapping.update({k: p['rendering_id'] for k, p in manual.items()})
    mapping.update({k: NAMESPACE+':'+p['template']['target_key'] for k, p in new.items()})
    require(inventory['rendering_by_target'] == mapping, 'Cumulative rendering binding differs')
    claim(inventory, 'generation_template_namespace', NAMESPACE)
    claim(inventory, 'generation_template_keys', sorted(templates))
    claim(inventory, 'generation_templates', len(templates))
    current = inventory.get('manual_source_renderings', []) + inventory.get('review_only_source_renderings', [])
    historic_sources = parent.get('manual_source_renderings', []) + parent.get('review_only_source_renderings', [])
    byrid = indexed(current, 'rendering_id')
    for item in historic_sources:
        require(byrid.get(item['rendering_id']) == item, 'Historical quad/review-only source rendering changed')
    nonseeds = {k: p for k, p in manual.items() if p['vertex_count'] == 4}
    require(set(byrid) == {p['rendering_id'] for p in historic_sources} | {p['rendering_id'] for p in nonseeds.values()},
        'Only new47 modified quads and3 original reviews use nonseed renderings')
    for key, p in nonseeds.items():
        item = byrid[p['rendering_id']]
        require(item['target_key'] == key and item['polygon'] == p['polygon'] and item['human_source'] == p['human_source']
            and item['propagation_seed_eligible'] is False, 'Quad/review rendering differs from actual own-source')


source_counts = previous.source_counts


def check_report(out, combined, new, counts):
    from fontTools.ttLib import TTFont
    page = (out/'report_zh.html').read_text()
    parsed = baseline.ReportControls()
    parsed.feed(page)
    cards = indexed(parsed.articles, 'id')
    require(set(cards) == {'target-'+k for k in combined}, 'Report cumulative card inventory differs')
    options = parsed.options.get('filter', [])
    require(options and options[0].get('value') == '' and not any('selected' in o for o in options[1:])
        and [o['_text'].strip() for o in options[1:]] == [str(c) for c in CLASSES], 'Report requires all22 and ALL default')
    only = parsed.inputs.get('only-new', {})
    require(only.get('type') == 'checkbox' and 'disabled' not in only and ('checked' in only) is bool(new), 'Only-new default differs')
    for key, p in combined.items():
        card = cards['target-'+key]
        require(card['data-class'] == str(p['class_id']) and card['data-batch'] == ('new' if key in new else 'previous')
            and ('hidden' in card) is (bool(new) and key not in new), 'Report class/batch/default visibility differs')
        require('display:none' not in card.get('style', '').replace(' ', '').lower(), 'Report card unconditionally hidden')
        if key in ORIGINAL_REVIEWS:
            text = parsed.card_text['target-'+key]
            require(('原矩形' in text or '原框' in text) and any(w in text for w in ('仅复核', '未修改', '非修改', '无需修改')),
                'Original review report card masquerades as edited human contour')
    script = ("const cls=document.querySelector('#filter'),only=document.querySelector('#only-new');"
        "function filter(){document.querySelectorAll('article').forEach(a=>a.hidden="
        "(!!cls.value&&a.dataset.class!==cls.value)||(only.checked&&a.dataset.batch!=='new'));}"
        "cls.onchange=only.onchange=filter;filter();")
    require(re.sub(r'\s+', '', ''.join(parsed.scripts)) == re.sub(r'\s+', '', script), 'Report filter behavior differs')
    fields = ('old_total', 'manual_modified_added', 'original_rectangle_review_only', 'saved_human', 'new_candidates', 'total', 'missing')
    require(parsed.cells == [str(v) for c in CLASSES for v in (c, *(counts[str(c)][f] for f in fields))], 'Report exact22 counts differ')
    require(all(text in page for text in ('四点', '132', '53', '185', '51', '45', '42', '1258'))
        and any(text in page for text in ('不作传播模板', '不作模板'))
        and any(text in page for text in ('未确认真值', '不确认为GT')),
        'Report omits modified/unchanged/review-only/nontruth accounting')
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(out/'report-font.otf') as font:
        require(required <= set(font.getBestCmap()), 'Chinese report font coverage incomplete')
    coverage = read_json(out/'font_coverage.json')
    require(coverage['all_report_Chinese_present'] is True and coverage['chinese_glyphs'] == len(required)
        and coverage['font_sha256'] == digest(out/'report-font.otf'), 'Report font evidence differs')
    require((out/'FONT_LICENSE.txt').is_file(), 'Missing font license')


def audit(out, pose_live=POSE, gallery_live=GALLERY):
    data = check_inputs()
    manifest, artifacts = read_json(out/'manifest.json'), read_json(out/'artifact_hashes.json')
    check_claims(manifest)
    helpers.check_artifacts(out, artifacts)
    require(set(file_inventory(out))-{REPORT, SEAL, 'artifact_hashes.json'} == set(artifacts), 'Every builder artifact must be hashed')
    config = sources.check_configuration(out, manifest)
    pose_config, gallery_config, request_config = (read_json(PROJECT/'configs'/n) for n in
        ('active_pose_review.json', 'active_mask_gallery.json', 'active_mask_template_requests.json'))
    require(Path(pose_live).resolve() == (PROJECT/pose_config['database']).resolve()
        and Path(gallery_live).resolve() == (PROJECT/gallery_config['review_directory']/'mask_reviews.sqlite3').resolve(),
        'Live guards must use configured production read-only stores')
    require((PROJECT/gallery_config['directory']).resolve() == PARENT.resolve() and gallery_config['publication_version'] == 11,
        'Publication11 must remain active until publication12 independently passes')
    require((PROJECT/request_config['directory']).resolve() == REQUESTS.resolve(), 'Exact54 followup tasks must remain active')
    code, parent_code = manifest['frozen_code_sha256'], data['parent_manifest']['frozen_code_sha256']
    require(set(parent_code) | {GENERATOR} <= set(code) and all(code[n] == h for n, h in parent_code.items()), 'Frozen dependencies omitted/changed')
    for name, expected in code.items():
        path = (PROJECT/name).resolve()
        require(path.is_relative_to(PROJECT) and digest(path) == expected, 'Frozen code changed: '+name)
    require(manifest['code_sha256'] == code[GENERATOR], 'New generator provenance differs')
    for field, name in (('parent_manifest_sha256', 'manifest.json'), ('parent_proposals_sha256', 'proposals.jsonl'), ('parent_verification_sha256', SEAL)):
        claim(manifest, field, digest(PARENT/name))
    formal = (PROJECT/read_json(PROJECT/'configs/active_formal_dataset.json')['dataset']).resolve()
    formal_sha, class_sha = digest(formal/'manifest.json'), digest(sources.CLASSIFICATION)
    require(manifest['formal_manifest_sha256'] == formal_sha == data['parent_manifest']['formal_manifest_sha256']
        and manifest['classification_sha256'] == class_sha == data['parent_manifest']['classification_sha256'], 'Formal/class binding differs')
    rows, source_rows = helpers.formal_rows(formal, sources.CLASSIFICATION)
    require(len(rows) == 12344 and {r['final_class_id'] for r in rows.values()} == set(CLASSES), 'Fixed12344/22-class inventory differs')
    protected = read_json(out/'protected_formal_before.json')
    require(len(protected) == 20768 and protected == read_json(PARENT/'protected_formal_before.json')
        == read_json(out/'protected_formal_after.json') == protected_snapshot(formal), 'Protected20768 formal files changed')
    snapshots = helpers.find_snapshots(out, manifest)
    stores = {kind: helpers.read_store(path, kind, frozen=True) for kind, path in snapshots.items()}
    pose, gallery = stores['pose'], stores['gallery']
    require(json.loads(pose['metadata']['binding'])['formal_manifest_sha256'] == formal_sha == gallery['metadata']['formal_manifest_sha256'],
        'Review dataset binding differs')
    parent_snapshots = helpers.find_snapshots(PARENT, data['parent_manifest'])
    parent_stores = {kind: helpers.read_store(path, kind, frozen=True) for kind, path in parent_snapshots.items()}
    delta = check_store_delta(parent_snapshots, snapshots, parent_stores, stores, data['requests'], data['old_new'])
    require(read_json(out/'source_delta_audit.json') == delta, 'Declared exact-batch store delta differs')
    snapshot_manifest = read_json(out/'snapshot_manifest.json')
    for kind, store in stores.items():
        for field, value in dict(path=snapshots[kind].name, backup='backups/'+snapshots[kind].name,
                sha256=digest(snapshots[kind]), saved=len(store['current']), events=len(store['events'])).items():
            claim(snapshot_manifest[kind], field, value)
        claim(snapshot_manifest[kind], 'metadata', store['metadata'], required=False)
        prefix = 'snapshot' if kind == 'pose' else 'gallery_snapshot'
        claim(manifest, prefix+'_saved', len(store['current']))
        claim(manifest, prefix+'_events', len(store['events']))
        for path in (snapshots[kind], out/'backups'/snapshots[kind].name):
            require(path.stat().st_mode & 0o077 == 0 and digest(path) == digest(snapshots[kind]), 'Raw snapshot/backup differs or publicly readable')
    require((len(pose['current']), len(pose['events']), len(gallery['current']), len(gallery['events'])) == (4916, 11698, 824, 890),
        'Actual pose4916/11698 and gallery824/890 snapshot inventory differs')
    fingerprints = previous.check_live(stores, snapshots, pose_live, gallery_live)
    combined, manual, new, accepted = (indexed(read_jsonl(out/(name+'.jsonl'))) for name in
        ('proposals', 'manual_proposals', 'new_proposals', 'accepted_candidates'))
    frame_counts = check_partition(data['old'], data['requests'], manual, new, combined, accepted)
    check_preservation(out, data['old'])
    require((out/'requests.jsonl').read_bytes() == (REQUESTS/'requests.jsonl').read_bytes(), 'Completed54 requests changed')
    quarantine = set(sources.QUARANTINE) | set(data['parent_manifest'].get('preserved_quarantined_targets', []))
    require(set(manifest.get('preserved_quarantined_targets', [])) == quarantine and not quarantine & set(combined), 'Quarantine changed/resurrected')
    recovered = {k: v for k, v in sources.recover_pose_sources(pose, rows, quarantine).items() if k not in gallery['history_keys']}
    inherited = {k: p for k, p in data['old'].items() if p.get('schema') == 'saved_pose_mask_gallery_entry_v1'}
    modified = {k: p for k, p in manual.items() if k not in NEW_ORIGINAL_REVIEWS}
    require(len(inherited) == 383 and len(modified) == 51 and len(inherited | modified) == 434
        and set(inherited) | set(modified) <= set(recovered), 'All383 inherited plus51 actual modified pose sources required')
    require(Counter((p['class_id'], p['vertex_count']) for p in modified.values()) == {
        (3, 8): 4, (4, 4): 7, (5, 4): 10, (7, 4): 10, (14, 4): 10, (22, 4): 10}, 'New51 actual topology distribution differs')
    pose_sha, gallery_sha = digest(snapshots['pose']), digest(snapshots['gallery'])
    all_pose = {**inherited, **modified}
    raw_records = indexed(read_jsonl(out/'all_manual_sources.jsonl'))
    sources.check_source_records(raw_records, {k: dict(polygon=recovered[k]['polygon']) for k in all_pose}, recovered, snapshots['pose'])
    manual_records = indexed(read_jsonl(out/'manual_source_records.jsonl'))
    sources.check_source_records(manual_records, modified, recovered, snapshots['pose'])
    require(all(all(raw_records[k].get(f) == v for f, v in record.items()) for k, record in manual_records.items()), 'New51/all434 raw evidence conflicts')
    for name in ('all_manual_sources.jsonl', 'manual_source_records.jsonl', 'gallery_source_records.jsonl'):
        require((out/name).stat().st_mode & 0o077 == 0, 'Raw source payloads must stay private')
    for key, p in modified.items():
        check_manual(p, data['requests'][key], rows[key], recovered, pose_sha, formal_sha, class_sha)
    originals = {k: original_review_source(k, pose, rows[k], snapshots['pose']) for k in ORIGINAL_REVIEWS}
    original_records, statement = check_review_records(out, originals, pose_sha, data['requests'])
    require((out/'new_review_completion_statement.json').read_bytes() == (out/'review_completion_statement.json').read_bytes(),
        'New statement alias differs')
    require(indexed(read_jsonl(out/'new_reviewed_original_rectangle_source_records.jsonl')) ==
        {k: original_records[k] for k in NEW_ORIGINAL_REVIEWS}, 'New review-only sidecar is not exactly the new three')
    require((out/'new_reviewed_original_rectangle_source_records.jsonl').stat().st_mode & 0o077 == 0,
        'New review-only raw records must remain private')
    claim(statement, 'scoped_candidate_keys', sorted(data['old_new']))
    for field, value in dict(old_original_rectangle_statement='parent_evidence/review_completion_statement.json',
            old_original_rectangle_statement_scope_unchanged=True, old_45_conversation_dispositions_unchanged=True).items():
        claim(statement, field, value)
    historical_statement = read_json(PARENT/'review_completion_statement.json')
    require(read_json(out/'review_statement_bindings.json') == dict(
        historical=dict(path='parent_evidence/review_completion_statement.json', statement_sha256=sha(historical_statement),
            file_sha256=digest(PARENT/'review_completion_statement.json'), target_keys=sorted(OLD_ORIGINAL_REVIEWS)),
        current=dict(path='review_completion_statement.json', statement_sha256=sha(statement),
            target_keys=sorted(NEW_ORIGINAL_REVIEWS), scoped_request_keys=sorted(data['requests']))),
        'Actual historical/current original-review statement bindings differ')
    for key in NEW_ORIGINAL_REVIEWS:
        check_original_review(manual[key], data['requests'][key], originals[key], pose_sha, formal_sha, class_sha)
    for key in OLD_ORIGINAL_REVIEWS:
        p = combined[key]
        basis = (out/'parent_evidence'/p['original_box_review_basis']).resolve()
        require(basis.is_relative_to(out/'parent_evidence') and digest(basis) == digest(PARENT/'review_completion_statement.json')
            and p['human_source']['pose_review']['user_statement_sha256'] == originals[key]['user_statement_sha256'],
            'Historical original review must keep its old scoped authority')
    gallery_sources = previous.independent_gallery(gallery, pose, rows, data['old'], data['publications'], formal_sha, gallery_sha)
    gallery_records = previous.check_gallery_records(out, snapshots['gallery'], gallery, gallery_sha)
    require(len(gallery_sources) == 824 and set(data['old_new']) <= set(gallery_sources), 'All185 actual direct reviews required')
    unchanged = previous.check_saved_reviews(out, data['old_new'], gallery, gallery_records, gallery_sources, gallery_sha, statement, manifest)
    require(len(unchanged) == 53 and len(set(data['old_new'])-unchanged) == 132, 'Actual saved185/changed132/unchanged53 partition differs')
    require(Counter(len(gallery['current'][k]['polygon']) for k in data['old_new']) == {8: 146, 10: 20, 12: 19}, 'Saved185 actual topology differs')
    parent_seed_keys = read_json(PARENT/'template_inventory.json')['generation_template_keys']
    templates = independent_seeds(all_pose, recovered, gallery_sources, parent_seed_keys, data['old_new'], manual, pose_sha)
    require(len(templates) == 599 and Counter(t['origin'] for t in templates.values()) == {POSE_ORIGIN: 45, GALLERY_ORIGIN: 554},
        'Expected45 remaining pose +554 remaining gallery seeds, excluding old-five270')
    check_human_audits(out, inherited, modified, originals, raw_records, pose_sha, templates)
    remaining_records = indexed(read_jsonl(out/'remaining_current_manual_source_records.jsonl'))
    remaining_pose = {k: p for k, p in all_pose.items() if p['class_id'] in REMAINING}
    require(remaining_records == {k: raw_records[k] for k in remaining_pose}, 'All291 remaining current pose raw records differ')
    require((out/'remaining_current_manual_source_records.jsonl').stat().st_mode & 0o077 == 0, 'Remaining pose raw records must remain private')
    require(indexed(read_jsonl(out/'refined_annotations.jsonl')) == gallery['current'], 'Latest gallery annotations sidecar differs')
    require((out/'completed_request_manual_proposals.jsonl').read_bytes() == (out/'manual_proposals.jsonl').read_bytes(),
        'Completed54 public manual sidecar differs')
    dispositions = indexed(read_jsonl(out/'review_dispositions.jsonl'))
    require(len(dispositions) == 45 and not set(dispositions) & (set(all_pose) | set(gallery_sources) | set(originals)), 'Old45 is not a saved edit')
    counts = source_counts(data['old'], manual, new, all_pose, gallery_sources, dispositions, originals)
    require(sum(v['saved_human'] for v in counts.values()) == 1258
        and sum(v['original_rectangle_review_only'] for v in counts.values()) == 5, 'Human1258 and review-only5 must remain separate')
    require(len(set(data['old'])-set(all_pose)-set(gallery_sources)-set(dispositions)-set(originals)) == 42, 'Old42 unsaved cannot become inferred reviewed')
    inventory = read_json(out/'template_inventory.json')
    check_rendering(out, inventory, templates, manual, new)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    require(set(outcomes) == set(rows), 'All12344 explicit outcomes required')
    base = {**data['old'], **manual}
    excluded, protected_keys, protected_frames, locked_frames = scan_inventory(rows, pose, gallery, base, quarantine, outcomes)
    for p in accepted.values():
        check_machine(p, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha)
    attempts = read_jsonl(out/'registration_attempts.jsonl')
    evidence = ImageEvidence(formal, rows, source_rows)
    eligible = audit_attempts(attempts, rows, templates, accepted, outcomes, evidence, excluded, locked_frames)
    attempt_counts = Counter(t['target_key'] for t in attempts)
    require(all(o['registration_attempts'] == attempt_counts[k] for k, o in outcomes.items()), 'Outcome attempt totals differ')
    _, order = matching.check_diversity(base, accepted, new, outcomes)
    claim(manifest, 'scarcity_order', order)
    potential = {k: dict(target_key=k, class_id=rows[k]['final_class_id'], source=rows[k], metrics={}) for k in eligible}
    capacity_selected, _, capacity_order = matching.diverse_matching(base, potential)
    require(len(capacity_selected) == matching.residual_maximum_size(base, potential), 'Protected residual capacity is not maximum')
    maximum_counts = Counter(p['class_id'] for p in list(base.values())+list(capacity_selected.values()))
    safe_potential = {k: p for k, p in potential.items() if p['source']['frame_id'] not in protected_frames}
    safe_capacity, _, _ = matching.diverse_matching(base, safe_potential)
    require(len(safe_capacity) == matching.residual_maximum_size(base, safe_potential), 'Whole-frame-safe capacity is not maximum')
    safe_counts = Counter(p['class_id'] for p in list(base.values())+list(safe_capacity.values()))
    require(maximum_counts == safe_counts, 'Declared per-class capacity requires history-protected frames')
    claim(manifest, 'capacity_matching_order', capacity_order)
    claim(manifest, 'capacity_matching_total', sum(maximum_counts.values()))
    require(maximum_counts[19] <= 90 and frame_counts['19']['proposals'] <= maximum_counts[19], 'Dynamic class19 capacity concealed')
    for name, candidates, locked in (('frame_assignments', new, True), ('capacity_frame_assignments', capacity_selected, False)):
        expected = [dict(frame_id=p['source']['frame_id'], class_id=p['class_id'], target_key=k,
            locked=False, phase='accepted_candidate_maximum_matching') for k, p in candidates.items()]
        if locked:
            expected += [dict(frame_id=p['source']['frame_id'], class_id=p['class_id'], target_key=k,
                locked=True, phase='previously_counted_source') for k, p in base.items()]
        require(indexed(read_jsonl(out/(name+'.jsonl')), 'frame_id') == indexed(expected, 'frame_id'), 'Locked1350/residual assignments differ')
    require(manifest['classes'] == inventory['classes'] and set(manifest['classes']) == {str(c) for c in CLASSES}, 'All22 statistics required')
    shortfalls = read_json(out/'shortfalls.json')
    require(set(shortfalls) == {str(c) for c in REMAINING}, 'All17 remaining shortfalls required')
    for cls in CLASSES:
        declared = manifest['classes'][str(cls)]
        for field, expected in counts[str(cls)].items():
            names = ('original_rectangle_review_only', 'reviewed_original_rectangle') if field == 'original_rectangle_review_only' else (field,)
            claim(declared, names, expected, required=field in ('total', 'missing', 'saved_human', 'new_candidates'))
        expected = dict(capacity_matching_distinct_frames=maximum_counts[cls], capacity_shortfall=LIMIT-maximum_counts[cls],
            templates=sum(t['row']['final_class_id'] == cls for t in templates.values()),
            eligible=sum(rows[k]['final_class_id'] == cls for k in eligible),
            outcomes=dict(Counter(o['reason'] for o in outcomes.values() if o['class_id'] == cls)))
        for field, value in expected.items():
            claim(declared, field, value)
        if cls in REMAINING:
            for field, value in dict(missing=counts[str(cls)]['missing'], capacity=maximum_counts[cls],
                    capacity_shortfall=LIMIT-maximum_counts[cls], templates=expected['templates'], outcomes=expected['outcomes']).items():
                claim(shortfalls[str(cls)], field, value)
    for names, expected in ((('previous_proposals',), 1296), (('manual_proposals', 'manual_added'), 54),
            (('new_proposals',), len(new)), (('proposals',), len(combined)), (('base_proposals',), 1350),
            (('generation_templates',), 599), (('accepted_before_diversity',), len(accepted)),
            (('registration_attempts',), len(attempts)), (('scanned_eligible_targets',), len(eligible))):
        claim(manifest, names, expected)
    for field in ('missing', 'saved_human', 'saved_pose_human', 'saved_gallery_human', 'pending_machine_raw',
            'old_pending_machine', 'user_reviewed_no_change', 'no_new_server_review'):
        claim(manifest, field, sum(c[field] for c in counts.values()))
    for names, expected in ((('original_rectangle_review_only', 'reviewed_original_rectangle'), 5),
            (('modified_manual_proposals',), 51), (('modified_pose_source_records',), 434),
            (('db_stored_human_review',), 1263), (('saved_human_contour_source',), 1258), (('all_manual_sources',), 434)):
        claim(manifest, names, expected)
    claim(manifest, 'manual_four_point_sources', 47, required=False)
    claim(manifest, 'all_pose_four_point_sources', 248, required=False)
    claim(manifest, 'outcomes', dict(Counter(o['reason'] for o in outcomes.values())))
    for key, p in {**manual, **new}.items():
        if key in NEW_ORIGINAL_REVIEWS:
            previous.check_original_assets(out, p, rows[key], evidence)
        else:
            check_assets(out, p, rows[key], evidence, manual=key in manual)
    for folder, ext in ASSETS:
        require({p.name for p in (out/folder).iterdir()} == {k+'.'+ext for k in combined}, 'Cumulative asset inventory differs')
    check_report(out, combined, new, counts)
    used = read_json(out/'used_image_hashes.json')
    require(all(used.get(name) == value for name, value in evidence.used.items()), 'Used native image evidence omitted')
    for name, expected in used.items():
        require((formal/name).resolve().is_relative_to(formal) and digest(formal/name) == expected, 'Native image bytes changed')
    require(protected_snapshot(formal) == protected and digest(sources.CLASSIFICATION) == class_sha
        and file_inventory(PROJECT/'configs') == config, 'Formal/classification/config changed during audit')
    for root, expected in data['inputs'].items():
        require(file_inventory(root) == expected, 'Immutable input changed during audit: '+root.name)
    for name, expected in code.items():
        require(digest(PROJECT/name) == expected, 'Frozen code changed during audit')
    helpers.check_artifacts(out, artifacts)
    require(previous.check_live(stores, snapshots, pose_live, gallery_live) == fingerprints, 'Live guard changed before sealing')
    return dict(state='passed', publication_version=PUBLICATION, method='original', proposals_verified=len(combined),
        proposals_sha256=digest(out/'proposals.jsonl'), new_verified=len(new), new_proposals_sha256=digest(out/'new_proposals.jsonl'),
        manifest_sha256=digest(out/'manifest.json'), artifact_hashes_sha256=digest(out/'artifact_hashes.json'),
        manual_verified=54, completed_requests_verified=54, modified_manual_sources_verified=51,
        original_rectangle_review_only_verified=5, new_original_rectangle_review_only_verified=3,
        historical_original_rectangle_review_only_verified=2, original_rectangle_reviews_used_as_seeds=0,
        old_canonical_objects_preserved=1296, inherited_manual_sources_verified=383, all_manual_sources_verified=434,
        actual_saved_human=1258, actual_saved_pose=434, actual_saved_gallery=824,
        saved_database_polygons_including_original_rectangle_review_only=1263,
        parent_new_gallery_reviewed_saved=185, parent_new_gallery_actually_changed=132, parent_new_gallery_saved_unchanged=53,
        saved_unchanged_gallery_reviews_are_not_new_edits=True, historical_user_reviewed_no_change=45,
        old500_other_no_new_server_review=42, human_confirmation_inferred=False, templates_verified=599,
        pose_templates_verified=45, gallery_templates_verified=554, four_point_sources_used_as_seeds=0, classes=counts,
        distinct_frame_quotas=frame_counts, capacity_matching_distinct_frames=dict(maximum_counts),
        protected_frame_capacity_distinct_frames=dict(safe_counts), outcomes_verified=len(outcomes),
        accepted_before_diversity_recomputed=len(accepted), registration_attempts_verified=len(attempts),
        all_new_registrations_and_metrics_recomputed=True, all_rejected_attempts_and_metrics_recomputed=True,
        manual_exact_sqlite_payloads_and_human_events_verified=True, all_gallery_history_bindings_verified=True,
        historical_canonical_resources_bytewise_preserved=True, historical_statement_scopes_preserved=True,
        current_batch_only_store_deltas_verified=True, live_dependencies_unchanged=True,
        protected_formal_files_verified=20768, database_logical_fingerprints=fingerprints, metric_absolute_tolerance=helpers.ATOL,
        thresholds_relaxed=False, forced_fill=False, production_database_writes=0, configuration_writes=0, service_writes=0,
        automatic_training_eligible=False, robot_command_eligible=False, ground_truth_eligible=False,
        generator_code_sha256=code[GENERATOR], verification_script_sha256=digest(__file__), verified_at=datetime.now(timezone.utc).isoformat())


def seal(out, operation=None):
    requested = Path(out).absolute()
    out = requested.resolve()
    require(requested == out and out.parent == (PROJECT/'outputs').resolve()
        and re.fullmatch(r'pallet_mask_remaining_round2_v[0-9]+', out.name) and out.is_dir()
        and out not in {PARENT.resolve(), REQUESTS.resolve()}, 'Only a new completed round2 output may be sealed')
    require((out/'manifest.json').is_file(), 'Generation is not complete: manifest.json missing')
    require(not (out/SEAL).exists() and not (out/SEAL).is_symlink(), 'Refusing to overwrite independent verification seal')
    require(not (out/REPORT).is_symlink(), 'Unsafe validation report path')
    if (out/REPORT).is_file():
        prior = read_json(out/REPORT)
        require(prior.get('state') == 'failed', 'Refusing to replace an already successful validation report')
        archive = PROJECT/'outputs/pallet_mask_remaining_round2_deployment_v1'
        require(not archive.is_symlink(), 'Unsafe failed-report archive path')
        archive.mkdir(exist_ok=True)
        raw = (out/REPORT).read_bytes()
        destination = archive/('failed_validation_report_'+hashlib.sha256(raw).hexdigest()+'.json')
        require(not destination.is_symlink(), 'Unsafe failed-report archive file')
        if destination.exists():
            require(destination.read_bytes() == raw, 'Conflicting failed-report archive')
        else:
            with destination.open('xb') as stream:
                stream.write(raw)
    cv2.setNumThreads(1)
    try:
        result = (operation or audit)(out)
        require(result.get('state') == 'passed', 'Audit did not pass')
    except Exception as exc:
        report = dict(state='failed', publication_version=PUBLICATION, error_type=type(exc).__name__, error=str(exc),
            verification_script_sha256=digest(__file__))
        (out/REPORT).write_bytes(canonical(report)+b'\n')
        raise
    (out/REPORT).write_bytes(canonical(result)+b'\n')
    result = dict(result, validation_report_sha256=digest(out/REPORT))
    with (out/SEAL).open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    return result


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, default=OUTPUT)
    parser.add_argument('--pose-live', type=Path, default=POSE)
    parser.add_argument('--gallery-live', type=Path, default=GALLERY)
    args = parser.parse_args(argv)
    result = seal(args.output, lambda out: audit(out, args.pose_live, args.gallery_live))
    print(json.dumps(result, ensure_ascii=False), flush=True)
    return result


if __name__ == '__main__':
    main()
