"""Independent publication-14 audit, run only after a completion notification.

No round-4 generator or source helper is imported. Frozen original registration
and independent historical verifiers supply algorithms, never new inventories.
The 37 preannotation saves are gallery events, not pose edits or transfer seeds.
Only a failed/passed validation report and an exclusive success seal 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
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, overlay, transfer
from pallet.pose_review_geometry import canonical, polygon_value, raster_mask
from scripts import verify_mask_remaining_round3 as previous

history, matching, sources = previous.history, previous.matching, previous.sources
helpers, baseline = previous.helpers, previous.baseline
require, sha = helpers.require, helpers.sha
read_json, read_jsonl, indexed = helpers.read_json, helpers.read_jsonl, helpers.indexed
file_inventory, claim, no_confirmation = sources.file_inventory, matching.claim, matching.no_confirmation
template_binding = history.template_binding
CLASSES, REMAINING, LIMIT = previous.CLASSES, previous.REMAINING, 100
COMPLETED = (1, 2, 3, 6, 8, 9, 10, 13, 15)
PUBLICATION, NAMESPACE = 14, 'remaining_round4_generation'
POSE_ORIGIN, GALLERY_ORIGIN = previous.POSE_ORIGIN, previous.GALLERY_ORIGIN
ORIGINAL_REVIEWS, PENDING_RECTANGLES = dict(previous.ORIGINAL_REVIEWS), dict(previous.PENDING_RECTANGLES)
PARENT = PROJECT/'outputs/pallet_mask_remaining_round3_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_preannotated_requests_v1'
OUTPUT = PROJECT/'outputs/pallet_mask_remaining_round4_v1'
POSE, GALLERY = sources.POSE, sources.GALLERY
GENERATOR = 'pallet/mask_remaining_round4.py'
REPORT, SEAL = 'validation_report.json', 'verification.json'
USER_STATEMENT = '完成复核和修正，继续'
ASSETS, ACCEPTED_REASONS = matching.ASSETS, matching.ACCEPTED_REASONS
PARENT_PINS = {
    'manifest.json': 'f2f985337f5efb17543e1f2df5588196fb6c597fc9f6167be52a14e68381e8d1',
    'verification.json': '7d234a89eb44c1b799d9dea7594faa404f98c131d0bc424f23ca15a3f5893388',
    'proposals.jsonl': '87fbde4aa3ddfdfd4b608364673c7a5d4d392d57f21312743852c650515d846a',
    'artifact_hashes.json': 'df2dda6cf0ee2bee5f42ff60439026f000faef73807055579fc4c360b60e4d85',
}
REQUEST_PINS = {
    'manifest.json': 'ce4052c2c9cd739894b55b98b5c1c12e156191f2abf78bc92e2fcdc34cfa9cb7',
    'verification.json': '8403c2f92a2bd73da4f874278d83af7dc4a2380b0e29a0af83e9481ed8e8e054',
    'independent_verification.json': '8403c2f92a2bd73da4f874278d83af7dc4a2380b0e29a0af83e9481ed8e8e054',
    'proposals.jsonl': '1d2d4856ad4602d21e4bbd98f3e8dca6e372cd9c5a1d1d33fb5d511bd7e95a28',
    'requests.jsonl': 'fe7b568365cef9bf12db8ee19d93c3aee9cb8ce02a6fe494cbc3c1f2aff83adc',
}
OUTPUT_PINS = {
    'manifest.json': '1cf30d3628f69adbc573260ec66c335fd174ffdb89550b6772f8bb2d274b005a',
    'artifact_hashes.json': '05d75289e9cf38ad389f2ce752fb07f9e828e7bdf493edfc145dd31496279c97',
    'proposals.jsonl': 'b012d4a6570b3f66ab974795b347a2dad517bba6d8fcca37a73a137184d6390d',
}
BASE_COUNTS = {1: 100, 2: 100, 3: 100, 4: 45, 5: 49, 6: 100, 7: 44, 8: 100,
    9: 100, 10: 100, 11: 14, 12: 46, 13: 100, 14: 61, 15: 100, 16: 31,
    17: 40, 18: 50, 19: 37, 20: 43, 21: 56, 22: 99}


def raw_sha(raw):
    return hashlib.sha256(raw.encode('utf-8')).hexdigest()


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', 'assistant_prelabels_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'] == 13
        and seal['proposals_verified'] == manifest['proposals'] == 1478 and seal['new_verified'] == 29,
        'Actual independently sealed publication13 1478/29 required')
    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'}
        and seal['verification_script_sha256'] == digest(previous.__file__), 'Frozen independent parent verifier/report changed')
    helpers.check_artifacts(PARENT, read_json(PARENT/'artifact_hashes.json'))
    task_manifest, task_seal = read_json(REQUESTS/'manifest.json'), read_json(REQUESTS/SEAL)
    require(task_seal['state'] == 'passed' and task_seal['request_count'] == task_manifest['request_count'] == 37
        and task_seal['manifest_sha256'] == digest(REQUESTS/'manifest.json')
        and task_seal['parent_verification_sha256'] == digest(PARENT/SEAL), 'Independent exact37 preannotation task seal differs')
    for field, name in (('proposals_sha256', 'proposals.jsonl'), ('requests_sha256', 'requests.jsonl')):
        require(task_seal[field] == task_manifest[field] == digest(REQUESTS/name), 'Frozen task inventory differs')
    helpers.check_artifacts(REQUESTS, task_seal['public_assets'])
    require(task_manifest['public_assets'] == task_seal['public_assets'], 'Task public resource registry differs')
    old, old_new, tasks, drafts = (indexed(read_jsonl(p)) for p in (PARENT/'proposals.jsonl',
        PARENT/'new_proposals.jsonl', REQUESTS/'requests.jsonl', REQUESTS/'proposals.jsonl'))
    require(len(old) == 1478 and len(old_new) == 29 and all(old[k] == v for k, v in old_new.items())
        and Counter(p['class_id'] for p in old_new.values()) == {8: 25, 19: 4}, 'Parent canonical1478/new29 partition differs')
    require(set(tasks) == set(drafts) and len(tasks) == 37 and not set(tasks) & set(old)
        and Counter(p['class_id'] for p in drafts.values()) == {4: 10, 5: 7, 7: 10, 14: 10}, 'Exact37 independent draft/task scope differs')
    prior = previous.check_inputs()
    publications = dict(prior['publications'])
    publications[13] = dict(path=PARENT, proposals=old, manifest=manifest)
    return dict(old=old, old_new=old_new, requests=tasks, drafts=drafts, parent_manifest=manifest,
        task_manifest=task_manifest, publications=publications,
        inputs={**prior['inputs'], PARENT: file_inventory(PARENT), REQUESTS: file_inventory(REQUESTS)})


def check_partition(old, requests, manual, new, combined, accepted):
    require(len(old) == 1478 and len(requests) == len(manual) == 37 and set(manual) == set(requests),
        'Need exact immutable1478 plus37 real gallery saves')
    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 from1478+37+N')
    require(set(accepted).isdisjoint(set(old) | set(manual) | set(PENDING_RECTANGLES)) and set(new) <= set(accepted),
        'Preannotation/self-source/old object became a machine acceptance')
    require(not set(PENDING_RECTANGLES) & set(combined), 'Unscoped old original rectangles cannot count')
    for inventory in (old, manual, new):
        require(all(combined[k] == p for k, p in inventory.items()), 'Canonical cumulative object 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()),
        'Generation entered completed class, including newly completed8')
    require(Counter(p['class_id'] for p in list(old.values())+list(manual.values())) == BASE_COUNTS,
        'Exact1515 baseline per-class counts differ')
    require({k for k, p in old.items() if p.get('schema') == previous.previous.REVIEW_SCHEMA} == set(ORIGINAL_REVIEWS)
        and all(p.get('schema') != previous.previous.REVIEW_SCHEMA for p in manual.values()), 'Five old review-only records changed')
    counts = matching.count_frames(combined)
    require(all(counts[str(c)]['proposals'] == LIMIT for c in COMPLETED), 'Completed class lost or overfilled')
    return counts


def check_store_delta(parent_snapshots, snapshots, parent_stores, stores, requests, old_new):
    result = {}
    authorized = set(requests) | set(old_new)
    for kind, table in (('pose', 'annotations'), ('gallery', 'reviews')):
        before, after = parent_stores[kind], stores[kind]
        helpers.preserve_events(before, after)
        require(after['events'][:len(before['events'])] == before['events'], 'Historical exact raw event prefix changed')
        added = after['events'][len(before['events']):]
        oldraw, newraw = previous.previous.raw_rows(parent_snapshots[kind], table), previous.previous.raw_rows(snapshots[kind], table)
        changed = {k for k in set(oldraw) | set(newraw) if oldraw.get(k) != newraw.get(k)}
        if kind == 'pose':
            require(not added and oldraw == newraw and after['metadata'] == before['metadata'], 'No new pose save was authorized or observed')
        else:
            require(len(added) == 71 and {e[1] for e in added} == authorized and changed == authorized
                and set(oldraw) <= set(newraw) and len(newraw)-len(oldraw) == 66,
                'Gallery delta must be only66 new keys/71 real events for29+37')
            for key in authorized:
                revision, raw, (_, event_revision, event_raw) = history.raw_current(snapshots[kind], table, key)
                require(revision == event_revision and raw == event_raw and key not in oldraw, 'New gallery source lacks exact latest raw event')
        result[kind] = dict(historical_events_preserved=len(before['events']), new_events=len(added),
            current_changed_keys=sorted(changed), unrelated_source_changes=0)
    return result


def validate_draft(proposal, task, row, formal_sha, image_sha, pose_current=None):
    """Independent check of pinned prelabel authority, never a human edit claim."""
    require(proposal['source'] == row and proposal['class_id'] == task['class_id'] == row['final_class_id']
        and proposal['target_key'] == task['target_key'] == row['target_key'], 'Draft/task formal identity differs')
    sources.same_identity(task['source'], row, 'Preannotation task')
    require(task['source'].get('viewpoint_candidate') == row.get('viewpoint_candidate'), 'Preannotation task view differs')
    require(proposal['schema'] == 'assistant_visual_preannotation_v1' and proposal['origin'] == 'assistant_visual_preannotation'
        and proposal['status'] == 'assistant_preannotated_draft_pending_human_review' and 'template' not in proposal,
        'Task proposal is not an independent assistant draft')
    for field in ('human_edited', 'human_mask_confirmed', 'human_pose_confirmed', 'ground_truth_eligible',
            'automatic_training_eligible', 'robot_command_eligible', 'production_saved', 'counts_as_completed_annotation',
            'accepted_candidate', 'propagation_seed_eligible'):
        claim(proposal, field, False)
    proof = proposal['preannotation']
    require(proposal['formal_manifest_sha256'] == formal_sha and proof['image_sha256'] == image_sha
        and proof['polygon_sha256'] == sha(proposal['polygon']) and proof['human_saved'] is False
        and proof['method'] == 'assistant_direct_native_image_contour_not_template_transfer'
        and proof['crop_inspected'] is True and proof['full_image_inspected'] is True and proof['note_zh'], 'Draft inspected/native contour proof differs')
    reference = dict(target_key=row['target_key'], origin='assistant_visual_preannotation',
        snapshot_revision=proposal['target_expected_revision'], current_payload_sha256=proposal['target_snapshot_payload_sha256'])
    require(proposal['target_expected_revision'] == (pose_current['revision'] if pose_current else 0)
        and proposal['target_snapshot_payload_sha256'] == (sha(pose_current) if pose_current else None),
        'Protected original pose changed since preannotation')
    if pose_current:
        require(sources.original_rectangle(pose_current.get('polygon'), row) and not sources.protected_state(pose_current),
            'Preannotation cannot cover a protected/modified pose')
        reference['pose_review'] = dict(target_key=row['target_key'], revision=pose_current['revision'],
            payload_sha256=sha(pose_current), polygon_sha256=sha(pose_current['polygon']))
    require(proposal['draft_source'] == reference, 'Draft protected-pose reference differs')
    require(task['assistant_polygon'] == proposal['polygon'] and task['preannotation'] == proof
        and task['status'] == 'preannotated_awaiting_human_review' and task['counts_as_completed_annotation'] is False
        and task['preserve_existing_pose_until_intentional_human_edit'] is True
        and task['existing_pose_revision'] == proposal['target_expected_revision']
        and task['existing_pose_payload_sha256'] == proposal['target_snapshot_payload_sha256'], 'Task draft/current-reference differs')
    polygon_value(proposal['polygon'], *row['size'])
    require(not sources.original_rectangle(proposal['polygon'], row), 'Assistant prelabel cannot be the original rectangle')


def independent_gallery(gallery, pose, rows, old, publications, drafts, tasks, formal_sha, gallery_sha):
    """All events resolve either historical canonical source or separate task source.

    Prelabels retain publication13's main editor binding, but their base proposal
    hashes and images resolve against the independently sealed task registry.
    """
    from pallet.mask_gallery_review import VERSION as EDITOR_VERSION
    histories, images = defaultdict(list), {}
    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 relational/formal identity differs')
        version = value.get('proposal_publication')
        require(type(version) is int and version in publications, 'Unknown actual gallery publication')
        pub, row = publications[version], rows[key]
        prelabel = key in drafts
        if prelabel:
            require(version == 13 and key not in old and key not in pub['proposals'], 'Task save laundered through main canonical publication13')
            proposal, image_root = drafts[key], REQUESTS
        else:
            proposal, image_root = pub['proposals'].get(key), pub['path']
            require(proposal is not None and old.get(key) == proposal and proposal['source'] == row,
                'Historical gallery canonical source differs')
        cache = (str(image_root), key)
        if cache not in images:
            images[cache] = digest(image_root/'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=images[cache])
        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('binding') == sha(dict(formal=formal_sha, proposals=digest(pub['path']/'proposals.jsonl'), editor_version=EDITOR_VERSION)),
            'Gallery historical publication/proposal/native source binding differs')
        if prelabel:
            validate_draft(proposal, tasks[key], row, formal_sha, images[cache], pose['current'].get(key))
            for _, pose_key, _, pose_raw in pose['events']:
                if pose_key == key:
                    prior = json.loads(pose_raw)
                    require(sources.original_rectangle(prior.get('polygon'), row) and not sources.protected_state(prior),
                        'Returned original rectangle cannot erase protected preannotation history')
            require(value.get('template_provenance') is None and value.get('human_source_provenance') is None
                and value.get('preannotation_provenance') == dict(assistant_draft=proposal['preannotation'],
                    assistant_draft_not_human_edit=True, proposal_sha256=sha(proposal), worklist_manifest_sha256=digest(REQUESTS/'manifest.json')),
                'Saved task must bind exact independent draft/worklist, never main template or pose source')
        else:
            require(value.get('template_provenance') == proposal['template'], 'Historical template provenance 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.get('vertex_count') == len(value.get('polygon', [])),
            'Gallery event is not an actual direct-human saved contour')
        require(len(value['polygon']) == 4 if prelabel else len(value['polygon']) > 4,
            'Gallery event changed its independently established source topology')
        no_confirmation(value, key)
        for field in ('pose_store_written', 'original_proposal_modified'):
            claim(value, field, False)
        polygon_value(value['polygon'], *row['size'])
        histories[key].append((event_id, revision, raw, value))
    require(set(gallery['current']) == set(histories), 'All current/latest gallery sources required')
    result = {}
    for key, value in gallery['current'].items():
        events = histories[key]
        require(len({e[1] for e in events}) == len(events) and max(e[1] for e in events) == events[-1][1] == value['revision']
            and events[-1][3] == value, 'Gallery current is not unique latest actual event')
        require(value.get('state') not in ('deleted', 'deferred', 'confirmed')
            and not sources.protected_state(pose['current'].get(key, {})), 'Protected pose/gallery current used as source')
        version, row, current = value['proposal_publication'], rows[key], 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 manual_gallery_binding(row, record, gallery_sha, publication_proposals_sha, task_manifest_sha):
    """Self-source binding derived solely from the independently checked raw save."""
    value = record['current_payload']
    review = dict(target_key=row['target_key'], revision=record['revision'], payload_sha256=sha(value),
        source_binding=value['source_binding'], polygon_sha256=sha(value['polygon']), snapshot_sha256=gallery_sha,
        proposal_publication=value['proposal_publication'], publication_proposals_sha256=publication_proposals_sha,
        task_manifest_sha256=task_manifest_sha, base_proposal_id=value['base_proposal_id'],
        current_payload_raw_sha256=record['current_payload_raw_sha256'], human_event_id=record['human_event_id'],
        human_event_raw_sha256=record['human_event_sha256'], preannotation_provenance=value['preannotation_provenance'])
    return dict(target_key=row['target_key'], origin=GALLERY_ORIGIN, gallery_review=review,
        polygon_sha256=sha(value['polygon']), image_sha256=value['source']['image_sha256'])


def check_manual(proposal, task, draft, row, source, record, gallery_sha, formal_sha, class_sha):
    key = row['target_key']
    require(proposal['target_key'] == key and proposal['source'] == row and proposal['class_id'] == row['final_class_id'],
        'Manual gallery canonical identity differs')
    require(proposal['schema'] == 'saved_gallery_mask_entry_v1' and proposal['origin'] == GALLERY_ORIGIN
        and proposal['status'] == 'saved_gallery_human_contour_draft_pending_confirmation' and proposal['human_edited'] is True
        and proposal['saved_gallery_manual_source'] is True,
        'New source must honestly be an actual gallery save, never a pose revision')
    require(proposal['polygon'] == source['polygon'] == record['current_payload']['polygon']
        and proposal['vertex_count'] == len(proposal['polygon']) == 4
        and proposal['manual_four_point_source'] is True and proposal['propagation_seed_eligible'] is False,
        'Manual gallery save must retain exact latest real four-point contour')
    binding = manual_gallery_binding(row, record, gallery_sha, digest(PARENT/'proposals.jsonl'), digest(REQUESTS/'manifest.json'))
    require('template' not in proposal and proposal['human_source'] == binding,
        'Gallery quad must bind itself, not a pose event or propagation template')
    require(proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == class_sha,
        'Manual gallery dataset/class identity differs')
    require(proposal['manual_request_sha256'] == sha(task) and proposal['metrics'] == {} and 'continuation' not in proposal,
        'Manual gallery save invents request/transfer metrics')
    for field in ('pose_store_written', 'gallery_store_written', 'machine_transfer_performed', 'new_human_edit_created'):
        claim(proposal, field, False)
    claim(proposal, 'gallery_snapshot_sha256', gallery_sha)
    claim(proposal, 'assistant_draft_proposal_sha256', sha(draft))
    claim(proposal, 'preannotation_provenance', record['current_payload']['preannotation_provenance'])
    claim(proposal, 'polygon_changed_from_assistant_draft', proposal['polygon'] != draft['polygon'])
    require(proposal['target_expected_revision'] == draft['target_expected_revision']
        and proposal['target_snapshot_payload_sha256'] == draft['target_snapshot_payload_sha256'],
        'Saved gallery canonical entry must preserve its original protected pose reference')
    require(proposal['rendering_id'] == NAMESPACE+':manual_source:'+key, 'Manual gallery rendering namespace differs')
    no_confirmation(proposal, key)
    require(record['revision'] == source['human_polygon_revision'] and record['current_payload']['base_proposal_id'] == sha(draft),
        'Manual gallery source is not latest actual save of exact draft')


def check_gallery_assets(out, proposal, row, evidence):
    key = proposal['target_key']
    require(re.fullmatch('[0-9a-f]{24}', key) is not None, 'Unsafe gallery source asset key')
    for folder, ext in ASSETS:
        path = out/folder/f'{key}.{ext}'
        require(path.is_file() and not path.is_symlink() and path.resolve().is_relative_to(out), 'Missing/unsafe saved gallery asset')
    native = evidence.image(row['frame_id'])
    with Image.open(out/'images'/f'{key}.png') as image:
        require(image.format == 'PNG' and image.mode == 'L' and image.size == tuple(row['size']), 'Saved gallery native image shape differs')
        np.testing.assert_array_equal(np.asarray(image), native)
    with Image.open(out/'masks'/f'{key}.png') as mask:
        require(mask.format == 'PNG' and mask.mode == 'L' and mask.size == tuple(row['size']), 'Saved gallery mask shape differs')
        np.testing.assert_array_equal(np.asarray(mask), raster_mask(proposal['polygon'], *row['size']).astype(np.uint8)*255)
    with Image.open(out/'cases'/f'{key}.png') as panel:
        require(panel.format == 'PNG', 'Saved gallery preview must be PNG')
        expected = overlay(native, row, proposal['polygon'], '#55ceff')
        np.testing.assert_array_equal(np.asarray(panel.convert('RGB').crop((0, 30, 740, 280))),
            np.asarray(expected.crop((0, 0, 740, 250))))
    label = read_json(out/'labelme'/f'{key}.json')
    require(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 and label['mask_gallery_provenance'] == proposal
        and label['saved_gallery_source'] == proposal['human_source'] and 'mask_template_provenance' not in label
        and label['annotation_scope'] == 'single_target_mask_review_not_full_frame' and label['other_objects_unchanged'] is True,
        'Saved gallery LabelMe native identity/self 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', 'Saved gallery LabelMe polygon differs')
    for flags in (label['flags'], shape['flags']):
        require(flags['human_confirmed'] is False and flags['human_edited'] is True and flags['machine_draft'] is False,
            'Saved gallery LabelMe must describe actual unconfirmed human save')
        for field in ('automatic_training_eligible', 'robot_command_eligible', 'ground_truth_eligible', 'propagation_seed_eligible'):
            claim(flags, field, False)
        claim(flags, 'pose_snapshot_saved', False, required=False)


def independent_seeds(pose_keys, recovered, gallery, parent_seed_keys, old_new, pose_sha, manual_keys=()):
    require(set(pose_keys) <= set(recovered) and set(old_new) <= set(gallery), 'Actual current human sources 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, source in sorted(gallery.items()):
        if key not in manual_keys and source['row']['final_class_id'] in REMAINING:
            require(key not in result and len(source['polygon']) > 4, 'Quad or duplicate human source entered seeds')
            result[key] = source
    require(set(result) == set(parent_seed_keys) | set(old_new), 'Seed set must be exact parent650 plus real reviewed29')
    require(not (set(manual_keys) | set(ORIGINAL_REVIEWS) | set(PENDING_RECTANGLES)) & set(result),
        'Quad/prelabel/original rectangle entered propagation')
    return result


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 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/history/reserved/completed frame 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 source 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 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',
                    'Unchanged original registration/beam gates failed')
                require(len(polygon) == len(templates[trial['template_key']]['polygon']), 'Inherited vertex count changed')
                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/acceptance outside eligible pool')
    require({k for k, o in outcomes.items() if o['reason'] in ACCEPTED_REASONS} == set(accepted), 'Accepted outcome set differs')
    return eligible


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), 'Parent1478 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 canonical asset/namespace changed: '+name)
    require(file_inventory(out/'parent_evidence') == file_inventory(PARENT), 'Complete frozen private parent archive differs')
    require(file_inventory(out/'preannotation_source_evidence') == file_inventory(REQUESTS), 'Complete independently sealed task evidence archive differs')
    for name in ('review_dispositions.jsonl', 'reviewed_original_rectangle_source_records.jsonl',
            'review_completion_statement.json', 'new_review_completion_statement.json', 'review_disposition_statement.json'):
        require((out/name).read_bytes() == (PARENT/name).read_bytes(), 'Historical sidecar/scoped authority changed: '+name)


def check_instruction(out, groups, requests, old_new):
    instruction = read_json(out/'current_user_instruction.json')
    claim(instruction, 'statement_zh', USER_STATEMENT)
    for field in ('creates_human_event', 'confirms_ground_truth', 'authorizes_propagation'):
        claim(instruction, field, False)
    claim(instruction, 'current_original_rectangle_no_change_authorized', False)
    claim(instruction, 'historical_original_rectangle_statement_bindings_unchanged', True)
    claim(instruction, 'observed_current_request_keys', sorted(requests))
    claim(instruction, 'observed_parent_candidate_keys', sorted(old_new))
    binding = read_json(out/'review_statement_bindings.json')
    claim(binding, 'historical_groups', groups)
    claim(binding, 'no_current_original_rectangle_review_statement_created', True)
    claim(binding, 'pending_original_rectangle_keys', sorted(PENDING_RECTANGLES))
    claim(binding, 'current_instruction_path', 'current_user_instruction.json')


def check_saved_reviews(out, old_new, gallery, records, gallery_sha, manifest, prelabel=False):
    name = 'completed_preannotation_source_audit' if prelabel else 'saved_review_source_audit'
    audits = indexed(read_jsonl(out/(name+'.jsonl')))
    require(set(audits) == set(old_new), 'Every actual saved review needs exact audit 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 latest/raw/changed status differs: '+key)
        if same:
            unchanged.append(key)
    expected = dict(parent_new_machine_candidates=0 if prelabel else 29, actually_saved=len(old_new), 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 gallery current/raw latest event pairs with every historical binding checked',
        unchanged_save_is_real_review_not_new_human_modification=True, new_human_edits_created=0)
    if prelabel:
        expected.update(completed_preannotation_tasks=37,
            source_kind='independent_assistant_preannotation_followed_by_real_gallery_human_save')
    name = 'completed_preannotation_status' if prelabel else 'saved_review_status'
    require(read_json(out/(name+'.json')) == manifest[name] == expected
        and len(unchanged) == (1 if prelabel else 9), 'Actual changed/saved-unchanged review counts differ')


def check_gallery_records(out, snapshot, gallery, gallery_sha, manual_keys):
    records = indexed(read_jsonl(out/'gallery_source_records.jsonl'))
    require(set(records) == set(gallery['current']), 'All941 current gallery raw source records required')
    histories = defaultdict(list)
    for event_id, key, revision, raw in gallery['events']:
        histories[key].append((event_id, revision, raw))
    for key, value in gallery['current'].items():
        revision, raw, (event_id, _, event_raw) = history.raw_current(snapshot, 'reviews', key)
        require(json.loads(raw) == value and raw == event_raw and histories[key][-1] == (event_id, revision, raw),
            'Gallery current must equal exact UTF8 bytes of latest real event')
        expected = dict(target_key=key, revision=revision, current_payload_raw=raw, current_payload_raw_sha256=raw_sha(raw),
            current_payload=value, current_payload_sha256=sha(value), human_event_id=event_id,
            human_event_payload_raw=event_raw, human_event_sha256=raw_sha(event_raw), snapshot_sha256=gallery_sha,
            history_event_ids=[e[0] for e in histories[key]],
            proposal_registry='independent_preannotation' if key in manual_keys else 'canonical_publication')
        require(records[key] == expected, 'Exact941 gallery source/history/raw bytes differ: '+key)
    manual_records = indexed(read_jsonl(out/'manual_source_records.jsonl'))
    require(manual_records == {k: records[k] for k in manual_keys}, 'New37 raw sources must be actual gallery records, not fabricated pose sources')
    return records


def check_source_registry(out, publications, gallery, drafts, formal_sha):
    from pallet.mask_gallery_review import VERSION as EDITOR_VERSION
    inventory = dict(schema='canonical_publications_and_independent_prelabel_registry_v1',
        canonical_gallery_saved=len(gallery['current'])-len(drafts), independent_prelabel_gallery_saved=len(drafts),
        publications={}, prelabels={})
    for version, pub in publications.items():
        proposal_sha = digest(pub['path']/'proposals.jsonl')
        inventory['publications'][str(version)] = dict(binding=sha(dict(formal=formal_sha, proposals=proposal_sha, editor_version=EDITOR_VERSION)),
            manifest_sha256=digest(pub['path']/'manifest.json'), proposals_sha256=proposal_sha,
            verification_sha256=digest(pub['path']/SEAL))
    for key, draft in drafts.items():
        value = gallery['current'][key]
        inventory['prelabels'][key] = dict(base_proposal_id=sha(draft), main_gallery_binding=inventory['publications']['13']['binding'],
            main_gallery_proposals_sha256=digest(PARENT/'proposals.jsonl'), preannotation_provenance=value['preannotation_provenance'],
            proposal_publication=13, source=value['source'], source_binding=sha(value['source']), task_manifest_sha256=digest(REQUESTS/'manifest.json'))
    require(read_json(out/'source_inventory.json') == inventory, 'Separate task/main-publication source registry differs from independent reconstruction')


def check_pose_audits(out, pose_records, recovered, rows):
    expected = {k: dict(target_key=k, class_id=rows[k]['final_class_id'], source_store='pose',
        current_revision=recovered[k]['current_revision'], current_payload_raw_sha256=r['current_payload_raw_sha256'],
        exact_current_and_event_validated=True, modified_human_contour=True, vertex_count=recovered[k]['vertex_count'])
        for k, r in pose_records.items()}
    require(indexed(read_jsonl(out/'human_source_audit.jsonl')) == expected, 'All482 pose-only human source audits differ')


def historical_task_protection(rows):
    keys, inventories = set(PENDING_RECTANGLES), {}
    for path in sorted((PROJECT/'outputs').glob('*/requests.jsonl')):
        if path.parent == OUTPUT or path.parent.name == 'pallet_mask_preannotated_requests_v2':
            continue
        inventories[path] = digest(path)
        keys.update(r['target_key'] for r in read_jsonl(path))
    # Rejected assistant drafts are historical tasks too, not free strict targets.
    decisions = REQUESTS/'internal/build_decisions.json'
    inventories[decisions] = digest(decisions)
    keys.update(read_json(decisions)['decisions'])
    require(keys <= set(rows), 'Historical task/rejection outside formal inventory')
    return keys, {rows[k]['frame_id'] for k in keys}, inventories


def scan_inventory(rows, pose, gallery, base, quarantine, outcomes, task_keys=(), task_frames=()):
    require(set(PENDING_RECTANGLES) <= set(rows), 'Pending old task outside formal inventory')
    reasons, pose_protected, locked = matching.scan_reasons(rows, pose, gallery, base, quarantine)
    protected_keys, protected_frames, _ = sources.protection(rows, pose, gallery, base, {}, quarantine)
    protected_keys.update(task_keys); protected_keys.update(PENDING_RECTANGLES)
    reserved = {rows[k]['frame_id'] for k in PENDING_RECTANGLES}
    protected_frames.update(task_frames); protected_frames.update(reserved)
    excluded = set()
    for key, row in rows.items():
        reason = reasons[key]
        if reason == 'eligible' and row['final_class_id'] in COMPLETED:
            reason = 'locked_class_quota_full'
        if reason != 'eligible':
            require(outcomes[key]['reason'] == reason and outcomes[key]['registration_attempts'] == 0,
                'Protected/completed scan disposition differs: '+key)
            excluded.add(key)
        elif key in protected_keys or row['frame_id'] in protected_frames:
            require(outcomes[key]['registration_attempts'] == 0 and outcomes[key]['reason'] not in ACCEPTED_REASONS,
                'Historical task/rejection/reserved whole frame was scanned')
            excluded.add(key)
    return excluded, protected_keys, protected_frames, locked | protected_frames, pose_protected


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 rendering includes quad/draft/unreviewed source')
    for key, source in templates.items():
        require(all(latest[NAMESPACE+':'+key].get(f) == v for f, v in source.items()), 'New seed provenance differs: '+key)
        exported = read_json(out/NAMESPACE/'templates'/f'{key}.json')
        require(all(exported.get(f) == v for f, v in source.items()), 'Exported seed provenance differs')
        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}, '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 target binding differs')
    for field, expected in dict(generation_template_namespace=NAMESPACE, generation_template_keys=sorted(templates),
            generation_templates=len(templates)).items():
        claim(inventory, field, expected)
    historical_sources = parent.get('manual_source_renderings', []) + parent.get('review_only_source_renderings', [])
    actual_sources = indexed(inventory.get('manual_source_renderings', [])+inventory.get('review_only_source_renderings', []), 'rendering_id')
    require(set(actual_sources) == {v['rendering_id'] for v in historical_sources} | {p['rendering_id'] for p in manual.values()},
        'Only37 saved gallery quads may add nonseed renderings')
    for item in historical_sources:
        require(actual_sources[item['rendering_id']] == item, 'Historical nonseed rendering changed')
    for key, p in manual.items():
        item = actual_sources[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, 'Gallery quad rendering lost exact self-source')


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 canonical 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 default ALL22')
    only = parsed.inputs.get('only-new', {})
    require(only.get('type') == 'checkbox' and 'disabled' not in only, 'Only-new control missing/disabled')
    only_new = 'checked' in only
    require(not new or only_new, 'A nonempty new machine batch must be the report default')
    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 (only_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:
            require(not any(t in parsed.card_text['target-'+key] for t in ('新增人工改绘', '新增机器候选')),
                'Historical original rectangle described as a new contour or candidate')
    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 cls in CLASSES for v in (cls, *(counts[str(cls)][f] for f in fields))],
        'Report table differs from independently counted22-class coverage')
    require(all(text in page for text in (USER_STATEMENT, '1423', '1428', '941', '482', '679', '1515', '36份', '1份', '20份', '9份')),
        'Report omits actual contour/old-review/seed/frozen denominator distinctions')
    require(not any(text in page for text in ('current_payload_raw', 'saved_event_payload_raw', '.sqlite3', 'fetch(')),
        'Report exposes private raw sources/database/network route')
    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')


def audit(out, pose_live=POSE, gallery_live=GALLERY):
    out = Path(out)
    verifier_before = digest(__file__)
    data = check_inputs()
    manifest, artifacts = read_json(out/'manifest.json'), read_json(out/'artifact_hashes.json')
    for name, expected in OUTPUT_PINS.items():
        require(digest(out/name) == expected, 'Completed generation handoff bytes changed: '+name)
    check_claims(manifest)
    before = file_inventory(out)
    require({k: v for k, v in before.items() if k not in (REPORT, SEAL, 'artifact_hashes.json')} == artifacts,
        'Every builder artifact must be hashed, with no embedded unreviewed tasks')
    for field, expected in manifest.items():
        if field.endswith('_sha256') and isinstance(expected, str):
            for ext in ('.json', '.jsonl'):
                name = field[:-7]+ext
                if name in before:
                    require(before[name] == expected, 'Manifest artifact binding differs: '+name)
    config = sources.check_configuration(out, manifest)
    pose_config, gallery_config, request_config = (read_json(PROJECT/'configs'/name) for name 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 read-only production stores')
    require((PROJECT/gallery_config['directory']).resolve() == PARENT.resolve() and gallery_config['publication_version'] == 13,
        'Publication13 must remain active until independent publication14 pass')
    require((PROJECT/request_config['directory']).resolve() == REQUESTS.resolve(), 'Exact37 tasks must remain active during audit')
    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 original engines omitted/changed')
    for name, expected in code.items():
        path = (PROJECT/name).resolve()
        require(path.is_relative_to(PROJECT) and digest(path) == expected, 'Frozen dependency changed: '+name)
    claim(manifest, 'code_sha256', code[GENERATOR])
    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 source 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 denominator 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((len(pose['current']), len(pose['events']), len(gallery['current']), len(gallery['events'])) == (4946, 11926, 941, 1023),
        'Actual unchanged pose4946/11926 and gallery941/1023 required')
    binding = json.loads(pose['metadata']['binding'])
    require(binding['formal_manifest_sha256'] == formal_sha == gallery['metadata']['formal_manifest_sha256']
        and binding['formal_annotations_sha256'] == digest(formal/'annotations/frames.jsonl')
        and binding['formal_frames_sha256'] == digest(formal/'frames.jsonl'), 'Full review metadata 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 exact29+37 store delta differs')
    spec = read_json(out/'snapshot_manifest.json')
    for kind, store in stores.items():
        for field, expected in dict(path=snapshots[kind].name, backup='backups/'+snapshots[kind].name,
                sha256=digest(snapshots[kind]), saved=len(store['current']), events=len(store['events']), metadata=store['metadata']).items():
            claim(spec[kind], field, expected)
        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 changed')
    fingerprints = history.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)
    require(all(p['source'] == rows[k] and p['class_id'] == rows[k]['final_class_id'] for k, p in combined.items()),
        'Canonical native/formal identity/class differs')
    check_preservation(out, data['old'])
    require((out/'requests.jsonl').read_bytes() == (REQUESTS/'requests.jsonl').read_bytes(), 'Immutable task37 JSONL bytes changed')
    quarantine = set(sources.QUARANTINE) | set(data['parent_manifest'].get('preserved_quarantined_targets', []))
    require(set(manifest['preserved_quarantined_targets']) == quarantine and not quarantine & set(combined), 'Quarantine changed/resurrected')
    previous.check_pose_history(out, pose, rows)
    recovered = {k: v for k, v in sources.recover_pose_sources(pose, rows, quarantine).items() if k not in gallery['history_keys']}
    pose_records = indexed(read_jsonl(out/'all_manual_sources.jsonl'))
    inherited = indexed(read_jsonl(PARENT/'all_manual_sources.jsonl'))
    require(len(pose_records) == 482 and set(pose_records) == set(inherited) and not set(pose_records) & set(manual),
        'all_manual_sources must remain482 genuine POSE records, not gallery37')
    sources.check_source_records(pose_records, {k: dict(polygon=recovered[k]['polygon']) for k in inherited}, recovered, snapshots['pose'])
    for key, record in inherited.items():
        for field in ('current_payload_raw', 'current_payload_raw_sha256', 'human_event_payload_raw', 'human_event_sha256'):
            require(pose_records[key][field] == record[field], 'Inherited pose raw/event bytes changed')
    pose_sha, gallery_sha = digest(snapshots['pose']), digest(snapshots['gallery'])
    pending = {k: previous.saved_rectangle_source(k, pose, rows[k], snapshots['pose']) for k in PENDING_RECTANGLES}
    previous.check_pending_records(indexed(read_jsonl(out/'pending_original_rectangle_saves.jsonl')), pending, pose_sha)
    reserved = {rows[k]['frame_id'] for k in pending}
    require(len(reserved) == 2 and not reserved & {p['source']['frame_id'] for p in combined.values()}, 'Old pending two frames counted')
    parent_groups = read_json(PARENT/'review_statement_bindings.json')['historical_groups']
    groups = []
    for group in parent_groups:
        path = PARENT/group['path']
        require(digest(path) == group['file_sha256'] and sha(read_json(path)) == group['statement_sha256'], 'Old scoped statement bytes changed')
        groups.append(dict(group, path='parent_evidence/'+group['path']))
    originals = previous.check_original_records(out, pose, rows, snapshots['pose'], groups)
    check_instruction(out, groups, data['requests'], data['old_new'])
    gallery_sources = independent_gallery(gallery, pose, rows, data['old'], data['publications'], data['drafts'], data['requests'], formal_sha, gallery_sha)
    gallery_records = check_gallery_records(out, snapshots['gallery'], gallery, gallery_sha, manual)
    check_saved_reviews(out, data['old_new'], gallery, gallery_records, gallery_sha, manifest)
    check_saved_reviews(out, data['drafts'], gallery, gallery_records, gallery_sha, manifest, prelabel=True)
    check_source_registry(out, data['publications'], gallery, data['drafts'], formal_sha)
    expected_events = [dict(target_key=k, event_id=i, revision=r, payload_raw_sha256=raw_sha(raw),
        proposal_publication=json.loads(raw)['proposal_publication'], source_binding=json.loads(raw)['source_binding'],
        base_proposal_id=json.loads(raw)['base_proposal_id'], historical_binding_validated=True,
        preannotation_provenance_validated=k in manual, proposal_registry='independent_preannotation' if k in manual else 'canonical_publication')
        for i, k, r, raw in gallery['events']]
    require(read_jsonl(out/'gallery_event_binding_audit.jsonl') == expected_events, 'All1023 event-binding audits differ')
    changed_parent = {k for k, p in data['old_new'].items() if gallery['current'][k]['polygon'] != p['polygon']}
    changed_manual = {k for k, p in data['drafts'].items() if gallery['current'][k]['polygon'] != p['polygon']}
    require(len(changed_parent) == 20 and len(changed_manual) == 36
        and all(len(gallery['current'][k]['polygon']) == 8 for k in data['old_new'])
        and all(len(gallery['current'][k]['polygon']) == 4 for k in manual), 'Actual29:20/9 eight-points and37:36/1 quads differ')
    for key, p in manual.items():
        check_manual(p, data['requests'][key], data['drafts'][key], rows[key], gallery_sources[key], gallery_records[key], gallery_sha, formal_sha, class_sha)
        claim(p, 'snapshot_sha256', pose_sha)
    for key, source in gallery_sources.items():
        if key in manual:
            continue
        value, record = gallery['current'][key], gallery_records[key]
        same = value['polygon'] == data['old'][key]['polygon']
        source.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=record['current_payload_raw_sha256'],
            saved_review_event_id=record['human_event_id'], saved_review_event_raw_sha256=record['human_event_sha256'])
    parent_seeds = read_json(PARENT/'template_inventory.json')['generation_template_keys']
    templates = independent_seeds(inherited, recovered, gallery_sources, parent_seeds, data['old_new'], pose_sha, manual)
    require(len(templates) == 679 and Counter(t['origin'] for t in templates.values()) == {POSE_ORIGIN: 45, GALLERY_ORIGIN: 634},
        'Expected679 seeds:45 pose+634 gallery; no37 quads')
    check_pose_audits(out, pose_records, recovered, rows)
    remaining_records = indexed(read_jsonl(out/'remaining_current_manual_source_records.jsonl'))
    require(remaining_records == {k: r for k, r in pose_records.items() if rows[k]['final_class_id'] in REMAINING},
        'Remaining pose records cannot be substituted by gallery saves')
    for name in ('all_manual_sources.jsonl', 'manual_source_records.jsonl', 'remaining_current_manual_source_records.jsonl',
            'gallery_source_records.jsonl', 'pending_original_rectangle_saves.jsonl', 'reviewed_original_rectangle_source_records.jsonl', 'requests.jsonl'):
        require((out/name).stat().st_mode & 0o077 == 0, 'Raw source/request payload must remain private: '+name)
    dispositions = indexed(read_jsonl(out/'review_dispositions.jsonl'))
    require(len(dispositions) == 45 and not set(dispositions) & (set(inherited) | set(gallery_sources) | set(originals))
        and len(set(data['old'])-set(inherited)-set(gallery_sources)-set(originals)-set(dispositions)) == 42,
        'Old45 conversation dispositions/42 unsaved may not acquire fake save or seed authority')
    counts = history.source_counts(data['old'], manual, new, inherited, gallery_sources, dispositions, originals)
    require(sum(c['saved_human'] for c in counts.values()) == 1423 and sum(c['saved_pose_human'] for c in counts.values()) == 482
        and sum(c['saved_gallery_human'] for c in counts.values()) == 941, 'Real1423 contours=482 pose+941 gallery required')
    inventory = read_json(out/'template_inventory.json')
    check_rendering(out, inventory, templates, manual, new)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    task_keys, task_frames, task_files = historical_task_protection(rows)
    base = {**data['old'], **manual}
    excluded, protected_keys, protected_frames, scan_frames, pose_protected = scan_inventory(rows, pose, gallery, base, quarantine, outcomes, task_keys, task_frames)
    for p in accepted.values():
        history.check_machine(p, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha)
        require(p['class_id'] not in COMPLETED and p['rendering_id'] == NAMESPACE+':'+p['template']['target_key'], 'Completed class/new rendering differs')
    attempts = read_jsonl(out/'registration_attempts.jsonl')
    evidence = ImageEvidence(formal, rows, source_rows)
    eligible = audit_attempts(attempts, rows, templates, accepted, outcomes, evidence, excluded, scan_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), 'Residual capacity not maximum')
    maximum_counts = Counter(p['class_id'] for p in list(base.values())+list(capacity_selected.values()))
    claim(manifest, 'capacity_matching_order', capacity_order)
    claim(manifest, 'capacity_matching_total', sum(maximum_counts.values()))
    claim(manifest, 'class19_additional_new_distinct_images_required_at_least', LIMIT-maximum_counts[19])
    require(frame_counts['19']['proposals'] <= maximum_counts[19] <= LIMIT, 'Dynamic class19 capacity concealed')
    for field, expected in dict(previous_proposals=1478, base_proposals=1515, proposals=len(combined), new_proposals=len(new),
            new_machine_pending=len(new), generation_templates=679, accepted_before_diversity=len(accepted), registration_attempts=len(attempts),
            scanned_eligible_targets=len(eligible), all_manual_sources=482, saved_pose_human=482, saved_gallery_human=941,
            saved_human=1423, saved_human_contour_source=1423, db_stored_human_review=1428, reviewed_original_rectangle=5,
            new_reviewed_original_rectangle=0, pending_original_rectangle=2).items():
        claim(manifest, field, expected)
    require(manifest['classes'] == inventory['classes'] and set(manifest['classes']) == {str(c) for c in CLASSES}, 'All22 statistics required')
    for cls in CLASSES:
        declared = manifest['classes'][str(cls)]
        for field in ('total', 'missing', 'saved_human', 'saved_pose_human', 'saved_gallery_human', 'new_candidates', 'user_reviewed_no_change', 'no_new_server_review'):
            claim(declared, field, counts[str(cls)][field])
        for field, expected in 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))).items():
            claim(declared, field, expected)
    shortfalls = read_json(out/'shortfalls.json')
    require(set(shortfalls) == {str(c) for c in REMAINING}, 'All17 remaining shortfalls required')
    for cls in REMAINING:
        for field, expected in dict(missing=counts[str(cls)]['missing'], capacity=maximum_counts[cls],
                capacity_shortfall=LIMIT-maximum_counts[cls], templates=sum(t['row']['final_class_id'] == cls for t in templates.values()),
                additional_new_distinct_images_required_at_least=LIMIT-maximum_counts[cls],
                outcomes=dict(Counter(o['reason'] for o in outcomes.values() if o['class_id'] == cls))).items():
            claim(shortfalls[str(cls)], field, expected)
    protected_info = read_json(out/'protected_targets.json')
    for field, expected in dict(locked_keys=sorted(base), locked_frames=sorted(p['source']['frame_id'] for p in base.values()),
            quarantine=sorted(quarantine), reserved_pending_original_rectangle_keys=sorted(PENDING_RECTANGLES),
            reserved_pending_original_rectangle_frames=sorted(reserved), pending_original_rectangles_excluded_from_coverage=True,
            all_current_task_keys_protected=sorted(data['requests']), previous_machine_task_keys_protected=sorted(data['old_new']),
            pose_mask_or_state_history_protected=sorted(pose_protected), gallery_saved_or_history=sorted(gallery['history_keys']),
            counted_manual_source_keys=sorted(inherited), reviewed_original_rectangle_keys=sorted(ORIGINAL_REVIEWS),
            conversation_dispositions_not_seed_authorization=True).items():
        claim(protected_info, field, expected)
    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'), 'Locked1515/residual frame assignments differ')
    for key, p in {**manual, **new}.items():
        if key in manual:
            check_gallery_assets(out, p, rows[key], evidence)
        else:
            previous.check_assets(out, p, rows[key], evidence)
    for key in manual:
        require(digest(out/'images'/f'{key}.png') == digest(REQUESTS/'images'/f'{key}.png'), 'New saved gallery native image bytes differ')
    for folder, ext in ASSETS:
        require({p.name for p in (out/folder).iterdir()} == {k+'.'+ext for k in combined}, 'Canonical asset inventory differs')
    require(indexed(read_jsonl(out/'refined_annotations.jsonl')) == gallery['current'], 'Latest saved941 gallery annotations differ')
    check_report(out, combined, new, counts)
    used = read_json(out/'used_image_hashes.json')
    require(all(used.get(n) == h for n, h in evidence.used.items()), 'Native image evidence omitted')
    for name, expected in used.items():
        require((formal/name).resolve().is_relative_to(formal) and digest(formal/name) == expected, 'Native source image 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 path, expected in task_files.items():
        require(digest(path) == expected, 'Historical request/rejection input changed during audit')
    for name, expected in code.items():
        require(digest(PROJECT/name) == expected, 'Frozen code changed during audit')
    require(digest(__file__) == verifier_before and file_inventory(out) == before, 'Verifier/output changed during read-only audit')
    require(history.check_live(stores, snapshots, pose_live, gallery_live) == fingerprints, 'Live source changed before seal')
    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=37, manual_gallery_saved_verified=37, manual_gallery_actually_changed=36, manual_gallery_saved_unchanged=1,
        parent_new_gallery_reviewed_saved=29, parent_new_gallery_actually_changed=20, parent_new_gallery_saved_unchanged=9,
        old_canonical_objects_preserved=1478, actual_saved_human=1423, actual_saved_pose=482, actual_saved_gallery=941,
        saved_database_polygons_including_original_rectangle_review_only=1428, original_rectangle_review_only_verified=5,
        pending_original_rectangles_verified=2, pending_original_rectangles_counted=0, reserved_uncounted_frames=2,
        templates_verified=679, pose_templates_verified=45, gallery_templates_verified=634, four_point_sources_used_as_seeds=0,
        historical_user_reviewed_no_change=45, old500_other_no_new_server_review=42, human_confirmation_inferred=False,
        classes=counts, distinct_frame_quotas=frame_counts, capacity_matching_distinct_frames=dict(maximum_counts),
        class19_additional_new_distinct_images_required_at_least=LIMIT-maximum_counts[19], 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,
        assistant_prelabels_counted=0, human_requests_created=0, automatic_training_eligible=False, robot_command_eligible=False,
        ground_truth_eligible=False, generator_code_sha256=code[GENERATOR], verification_script_sha256=verifier_before,
        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_round4_v[0-9]+', out.name) and out.is_dir()
        and out not in {PARENT.resolve(), REQUESTS.resolve()}, 'Only a new completed round4 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')
    failed_raw = None
    if (out/REPORT).exists():
        require((out/REPORT).is_file(), 'Unsafe validation report path')
        failed_raw = (out/REPORT).read_text()
        require(json.loads(failed_raw).get('state') == 'failed', 'Refusing to replace successful validation report')
    cv2.setNumThreads(1)
    try:
        result = (operation or audit)(out)
        require(result.get('state') == 'passed', 'Audit did not pass')
    except Exception as exc:
        result = dict(state='failed', publication_version=PUBLICATION, error_type=type(exc).__name__, error=str(exc),
            verification_script_sha256=digest(__file__))
        if failed_raw is not None:
            result.update(previous_failed_validation_report_raw=failed_raw, previous_failed_validation_report_sha256=raw_sha(failed_raw))
        (out/REPORT).write_bytes(canonical(result)+b'\n')
        raise
    result = dict(result)
    if failed_raw is not None:
        result.update(previous_failed_validation_report_raw=failed_raw, previous_failed_validation_report_sha256=raw_sha(failed_raw))
    (out/REPORT).write_bytes(canonical(result)+b'\n')
    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()
