"""Read-only independent publication-11 audit; never import the new generator.

Run after construction has finished. Every accepted and rejected registration is
replayed with the frozen original algorithms. Only validation_report.json and an
exclusively created verification.json in a fresh continuation output are written.
Saved unchanged gallery reviews are real reviews, not newly edited contours.
The two saved original rectangles are review-only coverage, never edit/seed proof.
"""
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
from PIL import Image

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, raster_mask
from scripts import verify_mask_remaining_expand as previous
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 = previous.alias, previous.claim, previous.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, 6, 9, 10, 13, 15)
LIMIT, PUBLICATION = 100, 11
NAMESPACE = 'remaining_continue_generation'
POSE_ORIGIN, GALLERY_ORIGIN = baseline.POSE_ORIGIN, baseline.GALLERY_ORIGIN
REVIEW_ORIGIN = 'explicit_review_not_modification'
REVIEW_SCHEMA = 'reviewed_original_rectangle_entry_v1'
REVIEW_ORIGINS = {REVIEW_ORIGIN, REVIEW_SCHEMA}
USER_STATEMENT = '已经完成269张候选复核和50张新图的标注，其中没有修改记录的是检验后无需修改的。继续'
ORIGINAL_REVIEWS = {'c64837a264b02755b52495c6': (4, 4), '3756ced3791a9669463f6fb0': (7, 1)}
PARENT = PROJECT/'outputs/pallet_mask_remaining_expand_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_remaining_direct_requests_v2'
OUTPUT = PROJECT/'outputs/pallet_mask_remaining_continue_v1'
POSE, GALLERY = sources.POSE, sources.GALLERY
GENERATOR = 'pallet/mask_remaining_continue.py'
REPORT, SEAL = 'validation_report.json', 'verification.json'
ASSETS = previous.ASSETS
ACCEPTED_REASONS = previous.ACCEPTED_REASONS
PARENT_PINS = {
    'manifest.json': '237613bab6ab8274babc6ac0f33ef66973dbf45b9f25381924431d9644413649',
    'verification.json': '03a69478b67d48d3573480c27a1842840bd1457ffb9fcf6f6cb57255aad9291b',
    'validation_report.json': 'c16aead314780778c143e8b3871b1001f78b467fe8712052e3ededb006a86f74',
    'proposals.jsonl': '024deaf1d2ca5ce9b6e9d12735cc2a7e24acdec36404c0a8cbd96aa6809888d2',
    'new_proposals.jsonl': 'ebc61908621aafc313acb2dfce46ab5cd333b81ace23e488762fb6ca8e84ec11',
    'manual_proposals.jsonl': '47988f36d51bcfde3f3b9bde02b15204dc22b1f22a3e2b65554f180e29589890',
    'artifact_hashes.json': '4d611c41444bb92c8461075d2e0320061d22df54068058dd60242ecddd90ca7f',
}
REQUEST_PINS = {
    'manifest.json': '9f7e9a6327ac652fa78057e3d256a10a80cae1ec6524e9dd5fb365ed8ca88c8b',
    'independent_verification.json': '819bf24bf9881804fc1f2a7e12e3e347bfe33ad491a8f939ba1ede4f0ee302ce',
    'requests.jsonl': 'd44050d6ceea723c223e7219625778c77c6bd917932d297d2277efdb50f98cdb',
}


def check_claims(manifest):
    claim(manifest, 'publication_version', PUBLICATION)
    claim(manifest, 'method', 'original')
    claim(manifest, 'target_per_class', LIMIT)
    claim(manifest, 'generation_template_namespace', NAMESPACE)
    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)
    claim(manifest, 'original_splits_preserved', True)
    claim(manifest, 'classification_is_candidate_not_truth', True)


def check_inputs():
    for root, pins in ((PARENT, PARENT_PINS), (REQUESTS, REQUEST_PINS)):
        for name, expected in pins.items():
            require(digest(root/name) == expected, f'Pinned immutable input changed: {root.name}/{name}')
    manifest, seal = read_json(PARENT/'manifest.json'), read_json(PARENT/SEAL)
    require(seal['state'] == 'passed' and seal['publication_version'] == 10
        and seal['proposals_verified'] == manifest['proposals'] == 1061 and seal['new_verified'] == 369,
        'Need the independently sealed publication10 1061/369 baseline')
    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 successful report differs from its independent seal')
    require(seal['verification_script_sha256'] == digest(previous.__file__), 'Pinned publication10 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 = read_json(REQUESTS/'independent_verification.json')
    require(request_seal['state'] == 'passed' and request_seal['request_count'] == 50
        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], 'Exact50 requests lack independent parent binding')
    helpers.check_artifacts(REQUESTS, request_seal['public_assets'])
    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) == 1061 and len(old_manual) == 192 and len(old_new) == 369
        and all(old.get(k) == p for k, p in {**old_manual, **old_new}.items()), 'Parent1061 canonical partitions differ')
    require(len(requests) == 50 and Counter(r['class_id'] for r in requests.values()) == dict.fromkeys((4, 5, 7, 14, 22), 10),
        'All and only the independently sealed50 requests are required')
    publications = baseline.check_frozen_inputs()
    original, _, pm = sources.check_baseline()
    publications[9] = dict(path=sources.BASELINE, proposals=original, manifest=pm)
    publications[10] = dict(path=PARENT, proposals=old, manifest=manifest)
    return dict(old=old, old_manual=old_manual, old_new=old_new, requests=requests,
        parent_manifest=manifest, publications=publications,
        inputs={PARENT: file_inventory(PARENT), REQUESTS: file_inventory(REQUESTS),
            **{p['path']: file_inventory(p['path']) for p in publications.values()}})


def check_partition(old, requests, manual, new, combined, accepted):
    require(len(old) == 1061 and len(manual) == 50 and set(manual) == set(requests), 'Expected immutable1061 plus exact new50')
    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 from1061+50+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 candidate 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 previously completed class')
    require({k for k, p in manual.items() if p.get('schema') == REVIEW_SCHEMA} == set(ORIGINAL_REVIEWS),
        'Exactly two original rectangles must remain distinct review-only entries')
    result = previous.count_frames(combined)
    require(all(result[str(c)]['proposals'] == LIMIT for c in COMPLETED), 'A completed class was lost or overfilled')
    return result


def preserved_private(root, name, expected):
    """Resolve the real retained scope path, including nested parent evidence."""
    candidates = [p for p in root.rglob(name) if p.is_file()]
    require(candidates and all(not p.is_symlink() and digest(p) == expected for p in candidates),
        'Private historical scope/statement bytes changed or missing: '+name)
    return candidates[0]


def check_preservation(out, old):
    current, historical = previous.raw_lines(out/'proposals.jsonl'), previous.raw_lines(PARENT/'proposals.jsonl')
    require(all(current[k] == historical[k] for k in old), 'Parent1061 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((out/'review_dispositions.jsonl').read_bytes() == (PARENT/'review_dispositions.jsonl').read_bytes(),
        'Public old45 dispositions must remain byte-identical at root')
    for name in ('review_disposition_statement.json', 'disposition_scope_source.jsonl'):
        source = preserved_private(PARENT, name, digest(sources.BASELINE/name))
        preserved_private(out, name, digest(source))
    if (out/'parent_evidence').is_dir():
        require(file_inventory(out/'parent_evidence') == file_inventory(PARENT), 'Complete frozen parent archive differs')


def raw_current(snapshot, table, key):
    with closing(sqlite3.connect(snapshot.resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        values = db.execute(f'SELECT revision,payload FROM {table} WHERE target_key=?', (key,)).fetchall()
        require(len(values) == 1, 'Ambiguous exact current source: '+key)
        revision, raw = values[0]
        events = db.execute('SELECT id,revision,payload FROM events WHERE target_key=? AND revision=?', (key, revision)).fetchall()
        require(len(events) == 1 and json.loads(events[0][2]) == json.loads(raw), 'Exact current/latest event differs: '+key)
        return revision, raw, events[0]


def original_review_source(key, pose, row, snapshot):
    require(key in ORIGINAL_REVIEWS and key in pose['current'], 'Original review is outside the exact authorized two')
    cls, expected_revision = ORIGINAL_REVIEWS[key]
    value = pose['current'][key]
    sources.same_identity(value.get('source'), row, 'Original rectangle review')
    require(row['final_class_id'] == cls and value['revision'] == expected_revision
        and value.get('state') == 'draft' and sources.original_rectangle(value.get('polygon'), row),
        'Original review current class/revision/rectangle differs')
    binding = json.loads(pose['metadata']['binding'])
    require(value.get('binding') == sha(binding), 'Original review formal binding differs')
    history = []
    for event_id, k, event_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('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 and event.get('binding') == sha(binding)
            and event.get('target_key') == key and event.get('revision') == event_revision,
            'Original review has edited/machine/protected history')
        require(all(event.get('source', {}).get(f, row.get(f)) == row.get(f)
            for f in ('final_class_id', 'viewpoint_candidate')), 'Original review class/view identity differs')
        require(event.get('full_six_dof', False) is False
            and all(event.get('pose', {}).get(f, False) is False for f in sources.FALSE_FLAGS),
            'Original review cannot imply confirmed pose or six degrees of freedom')
        history.append((event_id, event_revision, raw))
    no_confirmation(value, key)
    revision, raw, (event_id, event_revision, event_raw) = raw_current(snapshot, 'annotations', key)
    require(json.loads(raw) == value and revision == expected_revision 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 raw/latest history binding differs')
    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_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 template_binding(template):
    row = template['row']
    field = 'gallery_review' if template['origin'] == GALLERY_ORIGIN else 'pose_review'
    return dict(target_key=row['target_key'], class_id=row['final_class_id'], split=row['split'],
        snapshot_revision=template['revision'], current_payload_sha256=template['current_payload_sha256'],
        human_polygon_revision=template['human_polygon_revision'], human_event_sha256=template['human_event_sha256'],
        vertex_count=len(template['polygon']), template_human_confirmed=False, origin=template['origin'], **{field: template[field]})


def independent_gallery(gallery, pose, rows, old, publications, formal_sha, gallery_sha):
    """Validate all real historical events, including saved unchanged contours."""
    from pallet.mask_gallery_review import VERSION as EDITOR_VERSION
    histories = defaultdict(list)
    image_hashes = {}
    for event_id, key, revision, raw in gallery['events']:
        value = json.loads(raw)
        require(key in rows and value.get('target_key') == key and value.get('revision') == revision,
            'Gallery historical event identity differs')
        version = value.get('proposal_publication')
        require(type(version) is int and version in publications, 'Unknown gallery source publication')
        pub, row = publications[version], rows[key]
        proposal = pub['proposals'].get(key)
        require(proposal is not None and old.get(key) == proposal and proposal['source'] == row,
            'Gallery actual historical canonical source differs')
        cache_key = (version, key)
        if cache_key not in image_hashes:
            image_hashes[cache_key] = digest(pub['path']/'images'/f'{key}.png')
        identity = {f: row[f] for f in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
        identity.update(formal_manifest_sha256=formal_sha, image_sha256=image_hashes[cache_key])
        proposal_sha = digest(pub['path']/'proposals.jsonl')
        require(value.get('source') == identity and value.get('source_binding') == sha(identity)
            and value.get('base_proposal_id') == sha(proposal) and value.get('proposal_polygon') == proposal['polygon']
            and value.get('template_provenance') == proposal['template']
            and value.get('binding') == sha(dict(formal=formal_sha, proposals=proposal_sha, editor_version=EDITOR_VERSION)),
            'Gallery historical publication/proposal/source binding differs')
        require(value.get('event_kind') == 'human_mask_gallery_revision' and value.get('human_edited') is True
            and value.get('pose') is None and value['vertex_count'] == len(value['polygon']) > 4,
            'Gallery event is not a direct actual saved human review')
        no_confirmation(value, key)
        for field in ('pose_store_written', 'original_proposal_modified'):
            claim(value, field, False, required=False)
        polygon_value(value['polygon'], *row['size'])
        histories[key].append((revision, event_id, raw, value))
    result = {}
    require(set(gallery['current']) == set(histories), 'Gallery latest source/history inventory differs')
    for key, value in gallery['current'].items():
        history = histories[key]
        require(len({e[0] for e in history}) == len(history) and max(history, key=lambda e: e[0])[3] == value,
            'Gallery current is not its unique latest actual event')
        require(value.get('state') not in ('deleted', 'deferred', 'confirmed')
            and not sources.protected_state(pose['current'].get(key, {})), 'Protected gallery/pose state cannot seed')
        version, row = value['proposal_publication'], rows[key]
        current = pose['current'].get(key)
        result[key] = dict(row=row, polygon=value['polygon'], revision=current['revision'] if current else 0,
            current_payload_sha256=sha(current) if current else None, human_polygon_revision=value['revision'],
            human_event_sha256=sha(value), human_mask_confirmed=False, origin=GALLERY_ORIGIN,
            gallery_review=dict(target_key=key, revision=value['revision'], payload_sha256=sha(value),
                source_binding=value['source_binding'], polygon_sha256=sha(value['polygon']), snapshot_sha256=gallery_sha,
                proposal_publication=version, publication_proposals_sha256=digest(publications[version]['path']/'proposals.jsonl')))
    return result


def independent_seeds(old_manual, recovered, gallery, old_new, pose_sha):
    require(set(old_manual) <= set(recovered) and set(old_new) <= set(gallery), 'Counted propagation sources lost actual current review evidence')
    result = {k: previous.pose_template(recovered[k], pose_sha) for k in sorted(old_manual)
        if recovered[k]['vertex_count'] > 4 and recovered[k]['row']['final_class_id'] in REMAINING}
    for key in sorted(old_new):
        template = gallery[key]
        require(key not in result and template['row']['final_class_id'] in REMAINING and len(template['polygon']) > 4,
            'Gallery seed is duplicated, old-five-class, or a quad')
        result[key] = template
    require(all(t['row']['final_class_id'] not in OLD_CLASSES and len(t['polygon']) > 4 for t in result.values()),
        'Unreviewed machine/old-five/quad source entered remaining generation')
    return result


def check_gallery_records(out, snapshot, gallery, gallery_sha):
    records = indexed(read_jsonl(out/'gallery_source_records.jsonl'))
    require(set(records) == set(gallery['current']), 'All639 exact gallery current/event records are required')
    for key, value in gallery['current'].items():
        revision, raw, (event_id, _, event_raw) = raw_current(snapshot, 'reviews', key)
        require(json.loads(raw) == value and raw == event_raw, 'Gallery current is not its exact raw latest saved event')
        expected = dict(target_key=key, revision=revision, current_payload_raw=raw,
            current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(), current_payload=value,
            current_payload_sha256=sha(value), human_event_id=event_id, human_event_payload_raw=event_raw,
            human_event_sha256=hashlib.sha256(event_raw.encode()).hexdigest(), snapshot_sha256=gallery_sha)
        require(records[key] == expected, 'Exact raw gallery current/latest event bytes differ: '+key)
    return records


def check_saved_reviews(out, old_new, gallery, records, templates, gallery_sha, statement, manifest):
    audits = indexed(read_jsonl(out/'saved_review_source_audit.jsonl'))
    require(set(audits) == set(old_new), 'All369 parent new candidates require actual saved-review evidence')
    unchanged = []
    for key, p in old_new.items():
        value, raw = gallery['current'][key], records[key]
        same = value['polygon'] == p['polygon']
        expected = dict(target_key=key, class_id=p['class_id'], actual_saved=True,
            polygon_changed_from_proposal=not same, saved_review_unchanged=same,
            human_new_edit_claim=False, new_human_edit_created=False, proposal_sha256=sha(p),
            proposal_polygon_sha256=sha(p['polygon']), current_revision=value['revision'],
            current_polygon_sha256=sha(value['polygon']), current_payload_sha256=sha(value),
            current_payload_raw_sha256=raw['current_payload_raw_sha256'], human_event_id=raw['human_event_id'],
            human_event_sha256=raw['human_event_sha256'], gallery_snapshot_sha256=gallery_sha,
            source_binding=value['source_binding'], proposal_publication=value['proposal_publication'],
            binding=value['binding'], base_proposal_id=value['base_proposal_id'])
        require(audits[key] == expected, 'Actual saved gallery changed/unchanged current/raw-event audit differs: '+key)
        templates[key].update(saved_human_review=True, new_human_edit_created=False,
            saved_review_unchanged=same, polygon_modified_from_proposal=not same,
            current_gallery_payload_raw_sha256=raw['current_payload_raw_sha256'],
            saved_review_event_id=raw['human_event_id'], saved_review_event_raw_sha256=raw['human_event_sha256'])
        if same:
            unchanged.append(key)
    expected = dict(parent_new_machine_candidates=len(old_new), actually_saved=len(audits), pending=0,
        polygon_changed_from_proposal=len(old_new)-len(unchanged), saved_unchanged=len(unchanged),
        saved_keys=sorted(old_new), pending_keys=[], unchanged_keys=sorted(unchanged),
        saved_evidence_authority='real frozen current/raw latest events with historical publication/image/source bindings',
        unchanged_review_interpretation_statement_sha256=sha(statement), new_dispositions_created=0,
        new_human_edits_created=0, unsaved_candidates_are_seeds=False)
    require(read_json(out/'saved_review_status.json') == manifest['saved_review_status'] == expected,
        'Saved369/changed260/unchanged109 cannot become inferred or newly edited masks')
    return set(unchanged)


def check_human_audits(out, inherited, modified, originals, records, pose_sha, old_manual):
    audits = indexed(read_jsonl(out/'human_source_audit.jsonl'))
    require(set(audits) == set(inherited) | set(modified) | set(originals), 'All383 modified and2 review-only pose audits are required')
    for key, item in audits.items():
        source = records[key] if key in records else originals[key]
        polygon = source['current_payload']['polygon']
        cls = originals[key]['row']['final_class_id'] if key in originals else (inherited.get(key) or modified[key])['class_id']
        expected = dict(target_key=key, class_id=cls,
            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(polygon), historical_canonical_preserved=key in inherited,
            current_template_selected=key in old_manual and len(polygon) > 4, snapshot_sha256=pose_sha)
        require(item == expected, 'Actual pose-current/source-kind/historical audit differs: '+key)


def check_manual(proposal, request, row, recovered, pose_sha, formal_sha, class_sha):
    key = proposal['target_key']
    require(key in recovered and len(recovered[key]['polygon']) == 4, 'New modified source must be an actual saved changed quad')
    source = recovered[key]
    require(proposal['source'] == row and request['class_id'] == proposal['class_id'] == row['final_class_id'],
        'New manual original identity/class differs')
    sources.same_identity(request['source'], row, 'Completed request')
    require(request['source'].get('viewpoint_candidate') == row.get('viewpoint_candidate'), 'New manual request view differs')
    require(proposal['polygon'] == source['polygon'] and proposal['vertex_count'] == 4
        and proposal['manual_four_point_source'] is True and proposal['propagation_seed_eligible'] is False,
        'New manual changes quad topology or seed policy')
    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', 'New 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)
    require('template' not in proposal and proposal['human_source'] == template_binding(previous.pose_template(source, pose_sha)),
        'New quad must use actual raw human source, never a propagation template')
    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,
        'New quad 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, 'New quad invents a request/transfer')
    require(proposal['rendering_id'] == NAMESPACE+':manual_source:'+key, 'New quad source rendering namespace differs')


def check_original_review(proposal, request, source, pose_sha, formal_sha, class_sha):
    key, row = proposal['target_key'], source['row']
    require(key in ORIGINAL_REVIEWS and proposal['schema'] == REVIEW_SCHEMA and proposal['origin'] in REVIEW_ORIGINS,
        'Original rectangle must remain an explicit 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 rectangle review cannot masquerade as human edit/template')
    claim(proposal, 'manual_four_point_source', False, required=False)
    no_confirmation(proposal, key)
    for field in ('pose_store_written', 'gallery_store_written', 'machine_transfer_performed', 'new_human_edit_created'):
        claim(proposal, field, 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 rectangle review identity/polygon differs')
    sources.same_identity(request['source'], row, 'Original review request')
    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 rectangle exact 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 a transfer/request')
    require(proposal['rendering_id'].startswith(NAMESPACE+':') and proposal['rendering_id'].endswith(':'+key),
        'Original review source rendering namespace differs')
    binding = proposal['human_source']
    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(binding == expected, 'Original review exact saved-review 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 must not invent a modified-polygon human event')
    claim(proposal, 'source_label_kind', 'REVIEWED_ORIGINAL_RECTANGLE')
    claim(proposal, 'status', 'user_reviewed_original_rectangle_pending_confirmation')
    claim(proposal, 'saved_pose_review_source', True)
    claim(proposal, 'user_reviewed_no_change', True)


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 = None
            metrics['rejection'] = '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-target 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-compatible-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 original 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 check_machine(proposal, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha):
    key = proposal['target_key']
    require(key in rows and key not in protected_keys and rows[key]['frame_id'] not in protected_frames,
        'Machine target uses protected key/frame')
    row = rows[key]
    require(proposal['source'] == row and proposal['class_id'] == row['final_class_id'] in REMAINING
        and proposal['class_id'] not in COMPLETED, 'Machine source/class/split/policy/view differs')
    no_confirmation(proposal, key)
    claim(proposal, 'production_saved', False)
    require(proposal['status'] == 'machine_draft_pending_visual_review' and proposal.get('human_edited') is False,
        'Machine candidate misrepresented as human work')
    template = templates.get(proposal['template']['target_key'])
    require(template is not None and compatible(template['row'], row) and proposal['template'] == template_binding(template),
        'Machine uses an incompatible/unreviewed/stale template')
    require(proposal['vertex_count'] == len(proposal['polygon']) == len(template['polygon']) > 4, 'Machine topology differs')
    polygon_value(proposal['polygon'], *row['size'])
    current = pose['current'].get(key)
    require(proposal['snapshot_sha256'] == pose_sha and proposal['target_expected_revision'] == (current['revision'] if current else 0)
        and proposal['target_snapshot_payload_sha256'] == (sha(current) if current else None), 'Machine target current binding differs')
    require(proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == class_sha,
        'Machine dataset/class binding differs')
    require(proposal['generation_method'] == dict(name='original', version='attempt_target_v1',
        code_sha256=digest(PROJECT/'pallet/mask_template_continue.py')) and 'explicit_adoption_only' in proposal['geometry_pose_policy'],
        'Machine does not use original explicit-adoption-only transfer')


def source_counts(old, manual, new, pose_keys, gallery, dispositions, original_keys):
    combined = {**old, **manual, **new}
    pose_keys, gallery_keys, review_keys = set(pose_keys), set(gallery), set(original_keys)
    require(not (pose_keys & gallery_keys or review_keys & (pose_keys | gallery_keys)), 'Human/review-only coverage is not disjoint')
    saved = pose_keys | gallery_keys
    result = {}
    for cls in CLASSES:
        keys = {k for k, p in combined.items() if p['class_id'] == cls}
        raw = keys-saved-review_keys
        result[str(cls)] = dict(old_total=len(keys & set(old)), manual_added=len(keys & set(manual)),
            manual_requested=len(keys & set(manual)), saved_pose_human=len(keys & pose_keys),
            manual_modified_added=len((keys & set(manual))-review_keys),
            saved_gallery_human=len(keys & gallery_keys), saved_human=len(keys & saved),
            original_rectangle_review_only=len(keys & review_keys), pending_machine_raw=len(raw),
            old_pending_machine=len(set(old) & raw), user_reviewed_no_change=len(keys & set(dispositions)),
            no_new_server_review=len(raw-set(dispositions)), new_candidates=len(keys & set(new)),
            new_machine_pending=len(keys & set(new)), total=len(keys), preview=len(keys), distinct_frames=len(keys),
            missing=LIMIT-len(keys), goal=LIMIT, target_per_class=LIMIT)
    return result


def check_review_records(out, originals, snapshot, pose_sha):
    path = sources.artifact(out, ('reviewed_original_rectangle_source_records.jsonl', 'original_rectangle_review_source_records.jsonl',
        'review_only_source_records.jsonl', 'original_rectangle_review_records.jsonl',
        'original_rectangle_source_records.jsonl', 'original_rectangle_review_only_records.jsonl',
        'review_only_original_rectangle_records.jsonl'))
    records = indexed(read_jsonl(path))
    require(set(records) == set(originals), 'Exactly two original-rectangle raw review records are required')
    require(path.stat().st_mode & 0o077 == 0, 'Raw review-only records must remain private')
    statement = read_json(sources.artifact(out, ('review_completion_statement.json',)))
    check_statement(statement)
    for key, source in originals.items():
        record = records[key]
        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')
        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=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(statement),
            classification_is_candidate_not_truth=True)
        expected.update(dict.fromkeys(baseline.previous.FALSE_FLAGS, False))
        require(record == expected, 'Exact raw SQLite original-review current/event/source/statement record differs: '+key)
        source['user_statement_sha256'] = sha(statement)
        no_confirmation(record, key)
    return records


def check_review_statement(out, proposals, records):
    """Validate the actual scoped statement and its canonical metadata hash."""
    path = sources.artifact(out, ('review_completion_statement.json',))
    value = read_json(path)
    check_statement(value)
    claim(value, 'schema', 'explicit_user_review_no_change_statement_v1')
    claim(value, 'scoped_request_keys', sorted(indexed(read_jsonl(out/'requests.jsonl'))))
    claim(value, 'reviewed_original_rectangle_keys', sorted(ORIGINAL_REVIEWS))
    claim(value, 'candidate_count_in_statement', 269)
    claim(value, 'actual_parent_batch_saved_count', 369)
    claim(value, 'old_42_unsaved_not_inferred_reviewed', True)
    for field in ('creates_human_event', 'confirms_ground_truth', 'authorizes_propagation'):
        claim(value, field, False)
    for key in ORIGINAL_REVIEWS:
        require(proposals[key]['original_box_review_basis'] == path.name
            and proposals[key]['human_source']['pose_review']['user_statement_sha256'] == sha(value)
            and records[key]['user_statement_sha256'] == sha(value), 'Original review does not bind the exact scoped statement')
    return value


def check_rendering(out, inventory, templates, old, manual, new):
    parent = read_json(PARENT/'template_inventory.json')
    historic = indexed(parent['templates'], 'rendering_id')
    actual = indexed(inventory['templates'], 'rendering_id')
    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():
        rid = NAMESPACE+':'+key
        for field, value in template.items():
            require(latest[rid].get(field) == value, 'New seed rendering actual human 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)
    require({p.name for p in (out/NAMESPACE/'templates').iterdir()} == {k+'.json' for k in templates},
        'New template files include extra/quad/non-counted source')
    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 and set(mapping) == set(old) | set(manual) | set(new),
        'Cumulative rendering target binding differs')
    claim(inventory, 'generation_template_namespace', NAMESPACE)
    claim(inventory, 'generation_template_keys', sorted(templates), required=False)
    claim(inventory, 'generation_templates', len(templates), required=False)
    current = list(inventory.get('manual_source_renderings', []))
    current += list(inventory.get('review_only_source_renderings', []))
    byrid = indexed(current, 'rendering_id')
    for item in parent.get('manual_source_renderings', []):
        require(byrid.get(item['rendering_id']) == item, 'Historical four-point source rendering changed')
    require(len(current) == len(parent.get('manual_source_renderings', []))+len(manual),
        'New quad/review-only source rendering inventory differs')
    for key, p in manual.items():
        item = byrid.get(p['rendering_id'])
        require(item is not None and item['target_key'] == key and item['polygon'] == p['polygon']
            and item['human_source'] == p['human_source'] and item['propagation_seed_eligible'] is False,
            'New quad/review-only rendering must use its own actual source, not a template')
        if key in ORIGINAL_REVIEWS:
            claim(item, 'original_rectangle_review_only', True)
            claim(item, 'human_edited', False, required=False)


def scan_inventory(rows, pose, gallery, base, quarantine, outcomes):
    """Replay the original key scanner, with whole-frame guards on outputs.

    Untouched sibling boxes can appear in read-only no-template diagnostics. They
    are neither saved labels nor permission to replace another box's history.
    All accepted outputs still pass check_machine's conservative frame guard.
    """
    reasons, _, locked_frames = previous.scan_reasons(rows, pose, gallery, base, quarantine)
    protected_keys, protected_frames = previous.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:
            require(outcomes[key]['reason'] == 'no_compatible_template' and outcomes[key]['registration_attempts'] == 0,
                'Protected-frame sibling must remain an untouched no-template diagnostic: '+key)
            continue
        elif 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-class target scan disposition differs: '+key)
        excluded.add(key)
    return excluded, protected_keys, protected_frames, locked_frames


def check_original_assets(out, proposal, row, evidence):
    key = proposal['target_key']
    require(re.fullmatch('[0-9a-f]{24}', key) is not None, 'Unsafe review-only asset key')
    for folder, ext in ASSETS:
        path = out/folder/f'{key}.{ext}'
        require(path.is_file() and not path.is_symlink(), 'Missing review-only own-source asset')
    with Image.open(out/'images'/f'{key}.png') as image:
        require(image.mode == 'L' and image.size == tuple(row['size']), 'Review-only native image differs')
        np.testing.assert_array_equal(np.asarray(image), evidence.image(row['frame_id']))
    with Image.open(out/'masks'/f'{key}.png') as image:
        np.testing.assert_array_equal(np.asarray(image), raster_mask(proposal['polygon'], *row['size']).astype(np.uint8)*255)
    with Image.open(out/'cases'/f'{key}.png') as image:
        image.verify()
    label = read_json(out/'labelme'/f'{key}.json')
    require(label['mask_template_provenance'] == proposal and label['imageWidth'] == row['size'][0]
        and label['imageHeight'] == row['size'][1] and label['imagePath'] == f'../images/{key}.png'
        and label['imageData'] is None and len(label['shapes']) == 1, 'Review-only LabelMe provenance differs')
    shape = label['shapes'][0]
    require(shape['points'] == proposal['polygon'] and shape['shape_type'] == 'polygon'
        and shape['group_id'] == row['box_index'] and shape['label'] == 'pallet', 'Review-only LabelMe polygon differs')
    for flags in (label['flags'], shape['flags']):
        no_confirmation(flags, key)
        claim(flags, 'human_edited', False)
        claim(flags, 'machine_draft', False)
        claim(flags, 'original_rectangle_review_only', True)
        claim(flags, 'independent_gallery_saved', False, required=False)


def check_report(out, combined, manual, 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 must offer ALL22 with 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 report default must follow the actual new-machine sidecar')
    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 card source/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 ('仅复核' in text or '未修改' in text or '非修改' in text or '无需修改' in text),
                'Original rectangle report card masquerades as an edited human contour')
    expected_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+', '', expected_script), 'Report filter behavior differs')
    require(all(text in page for text in ('四点', '不作传播模板', '未确认真值', '109', '260', '369', '48', '45', '42')),
        'Report omits saved-unchanged/changed/review-only/manual/topology/nontruth status')
    for cls, count in counts.items():
        require(str(count['total']) in page and str(count['missing']) in page, 'Report omits class quota/shortfall')
    require(str(sum(v['saved_human'] for v in counts.values())) in page and ('原矩形' in page or '原框' in page),
        'Report conflates actual saved-human contours and original rectangle reviews')
    fields = ('old_total', 'manual_modified_added', 'original_rectangle_review_only', 'saved_human', 'new_candidates', 'total', 'missing')
    expected_cells = [str(value) for cls in CLASSES for value in (cls, *(counts[str(cls)][f] for f in fields))]
    require(parsed.cells == expected_cells, 'Report exact all22 modified-human/review-only/machine/quota counts differ')
    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 report 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), 'Artifact hashes must cover every builder file')
    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 guard must use configured production read-only stores')
    require((PROJECT/gallery_config['directory']).resolve() == PARENT.resolve() and gallery_config['publication_version'] == 10,
        'Publication10 must remain active until continuation is independently sealed')
    require((PROJECT/request_config['directory']).resolve() == REQUESTS.resolve(), 'Exact50 direct requests must remain active')
    code = manifest['frozen_code_sha256']
    parent_code = 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 original engine 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], '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')
    for kind, path in helpers.find_snapshots(PARENT, data['parent_manifest']).items():
        helpers.preserve_events(helpers.read_store(path, kind, frozen=True), stores[kind])
    snapshot_manifest = read_json(out/'snapshot_manifest.json')
    for kind, store in stores.items():
        expected = snapshot_manifest[kind]
        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(expected, field, value)
        claim(expected, '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]), 'Private raw snapshot/backup differs or is public-readable')
    require((len(pose['current']), len(pose['events']), len(gallery['current']), len(gallery['events'])) == (4882, 11553, 639, 689),
        'Actual completed pose4882/11553 and gallery639/689 snapshot inventory differs')
    fingerprints = 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(), 'Completed50 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), 'Frozen quarantine changed or resurrected')
    recovered = sources.recover_pose_sources(pose, rows, quarantine)
    recovered = {k: s for k, s in recovered.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 ORIGINAL_REVIEWS}
    require(len(inherited) == 335 and len(modified) == 48 and len(inherited | modified) == 383
        and set(inherited) | set(modified) <= set(recovered), 'All335 inherited plus48 actual modified human sources must be distinct')
    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()), 'New48/all383 exact-source records conflict')
    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 remain 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 = check_review_records(out, originals, snapshots['pose'], pose_sha)
    for key, source in originals.items():
        check_original_review(manual[key], data['requests'][key], source, pose_sha, formal_sha, class_sha)
    statement = check_review_statement(out, manual, original_records)
    check_human_audits(out, inherited, modified, originals, raw_records, pose_sha, data['old_manual'])
    gallery_sources = independent_gallery(gallery, pose, rows, data['old'], data['publications'], formal_sha, gallery_sha)
    gallery_records = check_gallery_records(out, snapshots['gallery'], gallery, gallery_sha)
    require(len(gallery_sources) == 639 and set(data['old_new']) <= set(gallery_sources), 'All369 parent candidates need actual saved direct gallery reviews')
    unchanged = check_saved_reviews(out, data['old_new'], gallery, gallery_records, gallery_sources, gallery_sha, statement, manifest)
    changed = set(data['old_new'])-unchanged
    require(len(unchanged) == 109 and len(changed) == 260, 'Saved unchanged109 versus actually changed260 gallery partition differs')
    templates = independent_seeds(data['old_manual'], recovered, gallery_sources, data['old_new'], pose_sha)
    require(len(templates) == 410 and Counter(t['origin'] for t in templates.values()) == {POSE_ORIGIN: 41, GALLERY_ORIGIN: 369},
        'Expected only41 old remaining pose plus369 actual reviewed gallery seeds')
    require(sum(recovered[k]['vertex_count'] == 4 for k in data['old_manual']) == 151
        and not set(ORIGINAL_REVIEWS) & set(templates) and not set(modified) & set(templates), 'Original/modified quads must never seed')
    dispositions = indexed(read_jsonl(out/'review_dispositions.jsonl'))
    require(len(dispositions) == 45 and not set(dispositions) & (set(all_pose) | set(gallery_sources)), 'Old45 no-change 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()) == 1022 and sum(v['original_rectangle_review_only'] for v in counts.values()) == 2,
        'Human1022 and original-review2 must be separately counted')
    require(len(set(data['old'])-set(all_pose)-set(gallery_sources)-set(dispositions)) == 42, 'Old42 unsaved must not become inferred reviewed/confirmed')
    inventory = read_json(out/'template_inventory.json')
    check_rendering(out, inventory, templates, data['old'], manual, new)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    require(set(outcomes) == set(rows), 'All12344 targets need explicit outcomes')
    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')
    owners, order = previous.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 = previous.diverse_matching(base, potential)
    require(len(capacity_selected) == previous.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, _, _ = previous.diverse_matching(base, safe_potential)
    require(len(safe_capacity) == previous.residual_maximum_size(base, safe_potential), 'Whole-frame-protected capacity is not maximum')
    safe_capacity_counts = Counter(p['class_id'] for p in list(base.values())+list(safe_capacity.values()))
    require(maximum_counts == safe_capacity_counts,
        'Declared per-class capacity cannot be attained without 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], 'Class19 protected dynamic capacity/shortfall 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'), 'Locked1111/residual frame assignments differ')
    require(manifest['classes'] == inventory['classes'] and set(manifest['classes']) == {str(c) for c in CLASSES}, 'All22 class 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', 'review_only_original_rectangle', 'original_rectangle_review_only_count', '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:
            item = shortfalls[str(cls)]
            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(item, field, value)
    for names, expected in ((('previous_proposals',), 1061), (('manual_proposals', 'manual_added'), 50),
            (('new_proposals',), len(new)), (('proposals',), len(combined)), (('base_proposals',), 1111),
            (('generation_templates',), 410), (('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()))
    claim(manifest, ('original_rectangle_review_only', 'review_only_original_rectangle', 'original_rectangle_review_only_count', 'reviewed_original_rectangle'), 2)
    claim(manifest, 'modified_manual_proposals', len(modified))
    claim(manifest, 'modified_pose_source_records', len(all_pose))
    claim(manifest, 'db_stored_human_review', len(all_pose)+len(gallery_sources)+len(originals))
    claim(manifest, 'saved_human_contour_source', len(all_pose)+len(gallery_sources))
    claim(manifest, 'all_manual_sources', 383)
    claim(manifest, 'manual_four_point_sources', 48, required=False)
    claim(manifest, 'all_pose_four_point_sources', 201, required=False)
    for names, expected in ((('parent_new_gallery_reviewed_saved', 'parent_batch_saved_reviews'), 369),
            (('parent_new_gallery_actually_changed', 'parent_batch_changed_polygons'), 260),
            (('parent_new_gallery_saved_unchanged', 'parent_batch_saved_unchanged'), 109)):
        claim(manifest, names, expected, required=False)
    claim(manifest, 'outcomes', dict(Counter(o['reason'] for o in outcomes.values())))
    for key, p in {**manual, **new}.items():
        if key in originals:
            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 public asset inventory differs')
    check_report(out, combined, manual, 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(check_live(stores, snapshots, pose_live, gallery_live) == fingerprints, 'Live source/target 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=50, completed_requests_verified=50, modified_manual_sources_verified=48,
        original_rectangle_review_only_verified=2, original_rectangle_reviews_used_as_seeds=0,
        old_canonical_objects_preserved=1061, inherited_manual_sources_verified=335, all_manual_sources_verified=383,
        actual_saved_human=1022, actual_saved_pose=383, actual_saved_gallery=639,
        saved_database_polygons_including_original_rectangle_review_only=1024,
        parent_new_gallery_reviewed_saved=369, parent_new_gallery_actually_changed=260,
        parent_new_gallery_saved_unchanged=109, 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=len(templates), pose_templates_verified=41,
        gallery_templates_verified=369, 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_capacity_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, 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 check_live(stores, snapshots, pose_live, gallery_live):
    return previous.check_live(stores, snapshots, pose_live, gallery_live)


def seal(out, operation=None):
    requested = Path(out).absolute()
    out = requested.resolve()
    require(requested == out and out.parent == (PROJECT/'outputs').resolve() and out.name.startswith('pallet_mask_remaining_continue_')
        and out.is_dir() and out not in {PARENT.resolve(), REQUESTS.resolve()}, 'Only a new completed continuation 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 an independent verification seal')
    require(not (out/REPORT).is_symlink(), 'Unsafe validation report path')
    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()
