"""Independently seal publication 7: authorized human reuse, 100-per-class cap.

Run only after generation. This verifier does not import the quota-100 generator,
write databases, or change active configuration. The original image registration
and beam audit are shared, pinned algorithms; counts, human provenance, seed union,
attempt coverage and diversity selection are recovered independently here.
"""
from __future__ import annotations

import argparse
from collections import Counter
from contextlib import closing
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import sqlite3
import sys
from urllib.parse import parse_qs, urlsplit

import cv2

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from scripts import verify_mask_quota_saved_extension as inherited
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, annotation_inventory, compatible, correlate, transfer
from pallet.pose_review_geometry import canonical, polygon_value

v1, prior = inherited.v1, inherited.prior
require, sha = prior.require, prior.sha
read_json, read_jsonl, indexed = prior.read_json, prior.read_jsonl, prior.indexed
CLASSES, LIMIT, QUARANTINE = prior.CLASSES, 100, prior.QUARANTINE
POSE_ORIGIN, GALLERY_ORIGIN = v1.POSE_ORIGIN, v1.GALLERY_ORIGIN
FALSE_FLAGS = v1.FALSE_FLAGS
NAMESPACE = 'quota100_generation'
PARENT = PROJECT/'outputs/pallet_mask_quota_completion_v2'
OUTPUT = PROJECT/'outputs/pallet_mask_quota_100_v2'
GENERATOR_SHA = '883f4dda8dd81c361f8c8c7a05221afb5405f1f70ffcdafcb682976cdb705a73'
REQUESTS = PROJECT/'outputs/pallet_mask_class10_manual_supplement_v2'
PARENT_PINS = {
    'manifest.json': '2f72df9f13d07885fb684be83ccea30c66f9c4416f09f3c4629bb84825a6fbd5',
    'verification.json': 'b49382696e2d4832a2be803bc85f948d225f01dc06367f8040f8ee594755e94c',
    'proposals.jsonl': '9abdf6f9e6f1b624c265e64fb5f76785f55cf81563eb2084bb75727ad213d18a',
    'artifact_hashes.json': '73eaabfe695000bc92be740036131de300c545da7a20ffb600a16ff9fe73a2bb',
    'template_inventory.json': 'c88c0a9f8b116f93b6d38f3b26fa42d09dc09d3bbb2667a75b92e3393a6c6bef',
    'manual_proposals.jsonl': 'e54c7af518faceba342c245ddb5c3dea9b0f8050d36f3d020bcb67eea015c4b5',
    'manual_source_records.jsonl': '3a8cde3ca0f9db101ad91eee09892988218cbb016deb02ee0e70d686b9297e16',
    'protected_formal_before.json': '02de366b0c0f691c2c11457c3f6976fe0bed32579992403bfbee3ea2be8ee4b1',
    'used_image_hashes.json': 'eedd08b1ef589c42dc0a69ceedb4c82dd4a4a9038aca15086c89a427872592eb',
    'delivery_verification.json': '71a89054f5547924d42b4765228aad1e1b9e47c8a5a79854288c53f07b0db277',
    'pallet_mask_refined_review.zip': '6a362349c8e90d1a85807f48750bbaf43b2993a8938e5b3c59fec983e0ee776c',
}
REQUEST_PINS = {
    'manifest.json': '279ccb9091ee3ef000a8761a7e66aa65adc00310c0fbfa97bdd50f39ed27a077',
    'requests.jsonl': 'b3e711c5fa97ce38ea3aa9e63e0cd7aa0acb7396a88e2625f225f22814fe3be4',
    'verification.json': '8afebc835cb64418d4630ea1119b8b9f0a4eceac12ff60518ebca487bbcaf220',
}
REQUEST_KEYS = frozenset({
    'c3f61efbb64accbbd71ca166', 'd9c2c8a3d7a9abfda3a3bca1', '3986404faf57fbe77449a0a7',
    'b1e615d7fedaab6533759265', 'b36308b768afba163c86276c', '201e2c973a4edac7c4f093a6',
    '53ba0983f0d15d0a2a68c031', '9b7aa309dbf99f376b205eb3', '6890d57090773e451d8c0060',
    '8ee3e8919513e00ae7a3bb56', '8da5ffa1748366aed21b599a', '905122c848e4b20bf15c379b',
    '67838228711c32a1b7be1f28',
})
ORIGINAL_CODE = {
    **inherited.CODE_PINS,
    'scripts/verify_mask_quota_saved_extension.py': 'edd504ad0be9b084175c26bfb9e7af999b47e4a2c17fc45815664bac0c3e76f1',
    'pallet/mask_quota_saved_extension.py': '14cdee9dd7907f40cfe63a14fb5d7c1aa584611dd3c8a6e61939ed076edd0101',
}


def check_frozen_inputs():
    publications = v1.check_frozen_inputs()
    for name, expected in PARENT_PINS.items():
        require(digest(PARENT/name) == expected, f'Frozen publication 6 changed: {name}')
    for name, expected in REQUEST_PINS.items():
        require(digest(REQUESTS/name) == expected, f'Frozen 13-target worklist changed: {name}')
    for name, expected in ORIGINAL_CODE.items():
        require(digest(PROJECT/name) == expected, f'Frozen original algorithm/verifier changed: {name}')
    manifest, seal = read_json(PARENT/'manifest.json'), read_json(PARENT/'verification.json')
    require(seal['state'] == 'passed' and seal['publication_version'] == manifest['publication_version'] == 6
            and seal['proposals_verified'] == manifest['proposals'] == 237
            and seal['manual_verified'] == manifest['manual_proposals'] == 30,
            'Publication 6 independent seal inventory differs')
    require(seal['manifest_sha256'] == PARENT_PINS['manifest.json']
            and seal['proposals_sha256'] == manifest['proposals_sha256'] == PARENT_PINS['proposals.jsonl']
            and seal['artifact_hashes_sha256'] == PARENT_PINS['artifact_hashes.json'],
            'Publication 6 independent seal hashes differ')
    require(digest(PARENT/'validation_report.json') == seal['validation_report_sha256'], 'Parent validation report changed')
    require(read_json(PARENT/'validation_report.json') == {k: v for k, v in seal.items() if k != 'validation_report_sha256'},
            'Parent validation report is not the sealed audit')
    artifacts = read_json(PARENT/'artifact_hashes.json')
    prior.check_artifacts(PARENT, artifacts)
    paths = {str(p.relative_to(PARENT)) for p in PARENT.rglob('*') if p.is_file()}
    require(paths == set(artifacts) | {'artifact_hashes.json', 'verification.json', 'validation_report.json',
            'delivery_verification.json', 'pallet_mask_refined_review.zip'},
            'Parent frozen artifact inventory coverage differs')
    proposals = indexed(read_jsonl(PARENT/'proposals.jsonl'))
    require(len(proposals) == 237, 'Expected all 237 canonical parent objects')
    publications[6] = dict(path=PARENT, proposals=proposals, manifest=manifest)
    requests = indexed(read_jsonl(REQUESTS/'requests.jsonl'))
    require(set(requests) == REQUEST_KEYS and all(r['class_id'] == 10 for r in requests.values()),
            'Exactly the 13 requested Class-10 targets are required')
    return publications


def count_frames(proposals):
    require(len({p['target_key'] for p in proposals}) == len(proposals), 'Repeated quota target')
    require(len({p['source']['frame_id'] for p in proposals}) == len(proposals), 'Repeated frame across classes')
    require({p['class_id'] for p in proposals} <= set(CLASSES), 'Unexpected quota class')
    counts = {}
    for cls in CLASSES:
        values = [p for p in proposals if p['class_id'] == cls]
        require(len(values) <= LIMIT, f'Class {cls} exceeds {LIMIT} distinct frames')
        counts[str(cls)] = dict(proposals=len(values), distinct_frames=len(values), shortfall=LIMIT-len(values))
    return counts


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=template['human_mask_confirmed'],
        origin=template['origin'], **{field: template[field]})


def check_manual(proposal, request, pose, direct, row, pose_sha, formal_sha, classification_sha):
    key = proposal['target_key']
    require(key in direct and key in pose['current'], f'Manual source lacks a current direct human polygon: {key}')
    value, template = pose['current'][key], direct[key]
    require(proposal['class_id'] == row['final_class_id'] and row['final_class_id'] in CLASSES
            and proposal['source'] == row, f'Manual identity/class differs: {key}')
    if request is not None:
        require(request['target_key'] == key and request['class_id'] == row['final_class_id'] == 10,
                f'Manual requested identity/class differs: {key}')
    for field in ('target_key', 'target_id', 'frame_id', 'split', 'group_id', 'box_index', 'bbox',
                  'size', 'policy_id', 'source_pcd_sha256'):
        require(row[field] == value['source'][field], f'Manual original source {field} differs: {key}')
        if request is not None:
            require(request['source'][field] == row[field], f'Manual request source {field} differs: {key}')
    if request is not None:
        require(request['source']['viewpoint_candidate'] == row['viewpoint_candidate']
                and request['source']['formal_manifest_sha256'] == formal_sha, f'Manual requested dataset binding differs: {key}')
    require(proposal['formal_manifest_sha256'] == formal_sha
            and proposal['class_assignments_sha256'] == classification_sha, f'Manual dataset binding differs: {key}')
    require(value.get('state') == 'draft'
            and proposal['polygon'] == template['polygon'] == value['polygon']
            and proposal['vertex_count'] == len(value['polygon']) > 4, f'Manual actual polygon/topology differs: {key}')
    polygon_value(proposal['polygon'], *row['size'])
    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'
            and proposal['source_label_kind'] == 'human_mask_source_manual_template_draft', f'Manual status/provenance differs: {key}')
    v1.no_confirmation(proposal, f'Manual {key}')
    require(not value.get('ground_truth_eligible'), f'Manual source falsely claims GT: {key}')
    for flag in FALSE_FLAGS[:-1]:
        require(value[flag] is False, f'Manual source {flag} must remain false: {key}')
    require(proposal.get('production_saved', False) is False and proposal['pose_snapshot_saved'] is True
            and proposal['pose_store_written'] is False and proposal['gallery_store_written'] is False,
            f'Manual source falsely claims store writes: {key}')
    require(proposal['machine_transfer_performed'] is False and proposal['new_human_edit_created'] is False,
            f'Manual source falsely claims a newly created edit or transfer: {key}')
    if request is not None:
        require(proposal['manual_request_sha256'] == sha(request)
                and proposal['original_pose_url'] == request['pose_annotation_url']
                and proposal['manual_source_kind'] == 'completed_manual_request', f'Manual exact request binding differs: {key}')
    else:
        require('manual_request_sha256' not in proposal, f'Existing saved source invents a manual request: {key}')
        require(proposal['manual_source_kind'] == 'existing_saved_human_reuse_for_100_goal',
                f'Existing saved source is not explicitly identified as authorized reuse: {key}')
        require('existing_human_reuse_not_new_edit' in proposal['flags']
                and proposal['manual_reuse_authorization'] == 'Explicit user authorization to count existing genuine saved '
                    'original-pose human masks toward the 100-per-class goal; no synthetic request',
                f'Existing human reuse lacks explicit honest authorization/provenance: {key}')
        url = urlsplit(proposal['original_pose_url'])
        require(url.scheme == 'https' and bool(url.netloc) and parse_qs(url.query).get('target') == [key],
                f'Existing human reuse URL does not identify its original source: {key}')
    require(proposal['rendering_id'] == NAMESPACE+':'+key, f'Manual exact rendering binding differs: {key}')
    require(proposal['snapshot_sha256'] == pose_sha and proposal['target_expected_revision'] == value['revision']
            and proposal['target_snapshot_payload_sha256'] == sha(value), f'Manual latest snapshot binding differs: {key}')
    expected = dict(template, origin=POSE_ORIGIN, pose_review=v1.pose_provenance(template, pose_sha))
    require(proposal['template'] == template_binding(expected), f'Manual self-source/human event provenance differs: {key}')
    require(proposal.get('metrics') == {} and 'continuation' not in proposal,
            f'Manual source claims machine transfer metrics/status: {key}')
    require('manual_source_not_machine_transfer' in proposal['flags'], f'Manual non-transfer flag missing: {key}')


def independent_reuse_keys(pose, direct, rows, old, requests):
    """Explicitly authorized reuse universe, independently derived from raw human events."""
    excluded_frames = {p['source']['frame_id'] for p in old.values()} | {r['source']['frame_id'] for r in requests.values()}
    selected = set()
    for key, template in direct.items():
        value, row = pose['current'][key], rows[key]
        if key in old or key in requests or key == QUARANTINE or row['frame_id'] in excluded_frames:
            continue
        if row['final_class_id'] not in CLASSES or value.get('state') != 'draft' or any(value.get(f) for f in FALSE_FLAGS):
            continue
        require(template['polygon'] == value['polygon'] and len(value['polygon']) > 4,
                f'Reused source is not the actual latest human polygon: {key}')
        for field in ('target_key', 'target_id', 'frame_id', 'split', 'group_id', 'box_index', 'bbox', 'size', 'policy_id', 'source_pcd_sha256'):
            require(value['source'][field] == row[field], f'Reused human original source {field} differs: {key}')
        selected.add(key)
    require(len({rows[k]['frame_id'] for k in selected}) == len(selected), 'Authorized reused human sources repeat a frame')
    return selected


def independent_gallery_templates(pose, gallery, rows, old, formal_sha, gallery_sha, publications):
    """Resolve all saved reviews against their *actual* frozen pub3/4/5/6 source."""
    from pallet.mask_gallery_review import VERSION as EDITOR_VERSION
    templates = {}
    for key, value in gallery['current'].items():
        require(key in old and key in rows, f'Unknown gallery human source: {key}')
        row = rows[key]
        version = value['proposal_publication']
        require(type(version) is int and version in publications, f'Unknown gallery publication: {key}')
        pub = publications[version]
        proposal = pub['proposals'].get(key)
        require(proposal is not None and proposal == old[key] and proposal['source'] == row,
                f'Gallery frozen source proposal differs: {key}')
        proposal_sha = digest(pub['path']/'proposals.jsonl')
        require(value['base_proposal_id'] == sha(proposal) and value['proposal_polygon'] == proposal['polygon']
                and value['template_provenance'] == proposal['template']
                and value['binding'] == sha(dict(formal=formal_sha, proposals=proposal_sha, editor_version=EDITOR_VERSION)),
                f'Gallery historical publication binding differs: {key}')
        source = {field: row[field] for field in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
        source.update(formal_manifest_sha256=formal_sha, image_sha256=digest(pub['path']/'images'/f'{key}.png'))
        require(value['source'] == source and value['source_binding'] == sha(source)
                and digest(PARENT/'images'/f'{key}.png') == source['image_sha256'], f'Gallery source binding differs: {key}')
        require(value['event_kind'] == 'human_mask_gallery_revision' and value['human_edited'] is True,
                f'Gallery seed is not an actual saved human revision: {key}')
        for flag in ('human_mask_confirmed', 'human_pose_confirmed', 'automatic_training_eligible',
                     'robot_command_eligible', 'pose_store_written', 'original_proposal_modified'):
            require(value[flag] is False, f'Gallery source {flag} must remain false: {key}')
        require(not value.get('ground_truth_eligible') and value['pose'] is None, f'Gallery source falsely claims GT/pose: {key}')
        polygon_value(value['polygon'], *row['size'])
        require(value['vertex_count'] == len(value['polygon']), f'Gallery vertex count differs: {key}')
        current = pose['current'].get(key)
        if len(value['polygon']) <= 4 or value.get('state') in ('deleted', 'deferred') \
                or (current and current.get('state') in ('deleted', 'deferred')):
            continue
        templates[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=sha(source), polygon_sha256=sha(value['polygon']), snapshot_sha256=gallery_sha,
                proposal_publication=version, publication_proposals_sha256=proposal_sha))
    return templates


def independent_seed_union(pose, gallery_templates, rows, pose_sha, old, inherited_manual):
    direct = v1.independent_pose_templates(pose, rows)
    templates = {k: dict(t, origin=POSE_ORIGIN, pose_review=v1.pose_provenance(t, pose_sha)) for k, t in direct.items()}
    templates.update(gallery_templates)  # Latest real gallery human wins a same-key tie.
    templates.pop(QUARANTINE, None)
    pending = set(old)-set(gallery_templates)-set(inherited_manual)
    require(not pending & set(templates), 'Unreviewed historical machine proposal used as a human seed')
    return direct, templates


def check_partition(old, inherited_manual, manual, new, combined, accepted, all_manual):
    require(set(inherited_manual) <= set(old), 'Inherited manual is not a subset of canonical parent')
    v1.check_partition(old, manual, new, combined, accepted)
    require(set(all_manual) == set(inherited_manual) | set(manual), 'All-manual inventory must contain inherited plus explicit added human sources')
    for key, value in {**inherited_manual, **manual}.items():
        require(canonical(all_manual[key]) == canonical(value), f'All-manual canonical record changed: {key}')


def check_inherited_manual(out, manual, snapshot, pose, direct, pose_sha, all_sources):
    """Never rebind legacy canonical objects; verify the explicit current-source overlay."""
    historical = indexed(read_jsonl(PARENT/'manual_source_records.jsonl'))
    audits = indexed(read_jsonl(out/'inherited_manual_source_audit.jsonl'))
    require(set(historical) == set(audits) == set(manual) and len(manual) == 30,
            'Expected exactly 30 inherited saved human source audits')
    changed, live_records = [], {}
    for key, proposal in manual.items():
        record = historical[key]
        require(proposal['polygon'] == record['current_payload']['polygon']
                and proposal['snapshot_sha256'] == record['snapshot_sha256']
                and proposal['target_snapshot_payload_sha256'] == record['current_payload_sha256']
                and proposal['template']['human_event_sha256'] == record['human_event_sha256'],
                f'Inherited human source historical provenance differs: {key}')
        v1.no_confirmation(proposal, f'Inherited manual {key}')
        value = pose['current'].get(key)
        require(key in direct and value is not None and value['polygon'] == direct[key]['polygon'],
                f'Inherited saved-human source no longer active/direct: {key}')
        require(value.get('state') == 'draft', f'Inherited current source is no longer an unconfirmed draft: {key}')
        for field in ('target_key', 'target_id', 'frame_id', 'split', 'group_id', 'box_index', 'bbox', 'size', 'policy_id', 'source_pcd_sha256'):
            require(value['source'][field] == direct[key]['row'][field], f'Inherited current source {field} differs: {key}')
        for flag in FALSE_FLAGS:
            require(not value.get(flag), f'Inherited current source {flag} must remain false: {key}')
        current_audit = dict(target_key=key, original_proposal_sha256=sha(proposal),
            historical_revision=proposal['target_expected_revision'], current_revision=value['revision'],
            current_payload_sha256=sha(value), latest_active_direct_human=True,
            source_changed=sha(value) != proposal['target_snapshot_payload_sha256'],
            polygon_changed=value['polygon'] != proposal['polygon'], historical_assets_preserved=True)
        require(audits[key] == current_audit, f'Inherited human current-source change audit differs: {key}')
        source = all_sources[key]
        require(source.get('inherited_manual_source') is True and source.get('legacy_source_audit') == current_audit,
                f'Inherited human current-source overlay missing/misleading: {key}')
        live_records[key] = {k: v for k, v in source.items() if k not in ('inherited_manual_source', 'legacy_source_audit')}
        if current_audit['source_changed']:
            changed.append(key)
    check_new_manual_records(live_records, {k: dict(polygon=direct[k]['polygon'], template=direct[k]) for k in manual}, snapshot, pose_sha)
    return live_records, sorted(changed)


def check_diversity(base, accepted, new, outcomes):
    """Replay selection independently; the complete 294-frame base consumes quotas."""
    count_frames(list(base.values()))
    selected, frames = set(), {p['source']['frame_id'] for p in base.values()}
    require({p['class_id'] for p in accepted.values()} <= set(CLASSES), 'Accepted candidate has unrequested class')
    for cls in CLASSES:
        previous = [p for p in base.values() if p['class_id'] == cls]
        groups, remaining = Counter(p['source']['group_id'] for p in previous), LIMIT-len(previous)
        pending = [p for p in accepted.values() if p['class_id'] == cls]
        while pending:
            candidate = min(pending, key=lambda p: (groups[p['source']['group_id']],
                -p['metrics']['boundary_ncc'], -p['metrics']['ecc'], p['target_key']))
            pending.remove(candidate)
            key, frame = candidate['target_key'], candidate['source']['frame_id']
            if frame in frames:
                reason = 'accepted_duplicate_frame_not_selected'
            elif remaining == 0:
                reason = 'accepted_quota_full_not_selected'
            else:
                reason = 'new_proposal'
                frames.add(frame)
                groups[candidate['source']['group_id']] += 1
                selected.add(key)
                remaining -= 1
            require(outcomes[key]['reason'] == reason, f'Diversity disposition differs: {key}')
    require(selected == set(new), 'Selected machine candidates differ from diversity/quota policy')


def expected_counts(old, inherited_manual, manual, new, gallery, requested_keys=REQUEST_KEYS):
    counts = count_frames(list(old.values())+list(manual.values())+list(new.values()))
    require(set(inherited_manual).isdisjoint(gallery['current']), 'Saved gallery/pose manual sources overlap')
    result = {}
    for cls in CLASSES:
        historic = [p for p in old.values() if p['class_id'] == cls]
        added = [p for p in manual.values() if p['class_id'] == cls]
        machines = [p for p in new.values() if p['class_id'] == cls]
        gallery_keys = {p['target_key'] for p in historic} & set(gallery['current'])
        pose_keys = {k for k, p in inherited_manual.items() if p['class_id'] == cls}
        requested = sum(p['target_key'] in requested_keys for p in added)
        reused = len(added)-requested
        total = counts[str(cls)]['distinct_frames']
        result[str(cls)] = dict(old_total=len(historic), manual_added=len(added), newmanual=requested,
            manual_requested=requested, manual_existing_reused=reused, added_saved_human=len(added),
            inherited_manual_sources=len(pose_keys), existing_saved_pose_human=len(pose_keys),
            saved_gallery_human=len(gallery_keys), saved_pose_human=len(pose_keys)+len(added),
            saved_human=len(gallery_keys)+len(pose_keys)+len(added),
            prior_machine_pending=len(historic)-len(gallery_keys)-len(pose_keys),
            old_pending_machine=len(historic)-len(gallery_keys)-len(pose_keys),
            new_candidates=len(machines), new_machine_pending=len(machines),
            total=total, missing=LIMIT-total, goal=LIMIT, target_per_class=LIMIT, distinct_frames=total,
            saved_fine_edits=sum(len(gallery['current'][k]['polygon']) > 4 for k in gallery_keys)+len(pose_keys)+len(added))
    return result, counts


def audit_attempts(out, rows, status, gallery, old, manual, templates, accepted, outcomes, evidence):
    attempts, bytarget = read_jsonl(out/'registration_attempts.jsonl'), {}
    for trial in attempts:
        key = trial['target_key']
        require(key in rows and trial['class_id'] == rows[key]['final_class_id'], 'Attempt identity differs')
        bytarget.setdefault(key, []).append(trial)
    eligible = set()
    for key, row in rows.items():
        protected = ('previously_quarantined' if key == QUARANTINE else 'already_published' if key in old else
                     'saved_manual_source_counted' if key in manual else
                     'gallery_history_protected' if key in gallery['history_keys'] else status[key])
        if protected == 'eligible' and row['final_class_id'] not in CLASSES:
            protected = 'class_not_requested'
        if protected != 'eligible':
            require(outcomes[key]['reason'] == protected and key not in bytarget and key not in accepted,
                    f'Protected outcome/attempt differs: {key}')
            continue
        eligible.add(key)
        choices = [k for k, t in templates.items() if compatible(t['row'], row)]
        if not choices:
            require(outcomes[key]['reason'] == 'no_compatible_template' and key not in bytarget and key not in accepted,
                    f'False no-compatible-template outcome: {key}')
            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]
        trials = bytarget.get(key, [])
        if key in accepted:
            source = accepted[key]['template']['target_key']
            require(source in passing, f'Accepted template below initial gate: {key}')
            expected = passing[:passing.index(source)+1]
            continuation = accepted[key]['continuation']
            require(continuation['batch'] == 7 and continuation['all_compatible_targets_scanned'] is True
                    and continuation['recursive_candidate_propagation'] is False
                    and continuation['template_rank'] == next(i for i, (_, k) in enumerate(ranked, 1) if k == source),
                    f'Original first-success continuation/rank differs: {key}')
        else:
            expected = passing
            require(outcomes[key]['reason'] == ('registration_or_boundary_rejected' if passing else 'image_similarity_below_gate'),
                    f'False rejection outcome: {key}')
        require([t['template_key'] for t in trials] == expected, f'Attempt coverage/order differs: {key}')
        for i, trial in enumerate(trials):
            if key in accepted and i == len(trials)-1:
                prior.equal_metrics(trial['metrics'], accepted[key]['metrics'], f'{key}.accepted_attempt')
                continue  # Every accepted geometry/metric leaf is recomputed separately, even if not selected.
            template = templates[trial['template_key']]
            polygon, metrics = transfer(evidence.patch(trial['template_key']), evidence.patch(key),
                                        template['polygon'], template['row'], row)
            if polygon is not None:
                reference = affine_reference(dict(source=row, metrics=metrics), template)
                guard = beam_boundary_audit(evidence.image(row['frame_id']), polygon, reference)
                metrics['boundary_guard'] = guard
                if guard['state'] != 'passed':
                    polygon = None
                    metrics['rejection'] = 'local_beam_boundary_review_required'
            require(polygon is None, f'Passing attempt falsely rejected: {key}/{trial["template_key"]}')
            prior.equal_metrics(trial['metrics'], metrics, f'{key}.{trial["template_key"]}.rejected_attempt')
    require(set(bytarget) <= eligible and set(accepted) <= eligible, 'Attempt/candidate outside eligible targets')
    accepted_reasons = {'new_proposal', 'accepted_duplicate_frame_not_selected', 'accepted_quota_full_not_selected'}
    require({k for k, v in outcomes.items() if v['reason'] in accepted_reasons} == set(accepted),
            'Accepted outcomes do not exactly cover machine candidates')
    require({k for k, v in outcomes.items() if v['reason'] == 'new_proposal'} == set(indexed(read_jsonl(out/'new_proposals.jsonl'))),
            'Selected machine outcomes differ')
    return eligible, len(attempts)


def check_machine(proposal, pose, templates, rows, status, gallery, old, manual, pose_sha, formal_sha, classification_sha, evidence):
    key = proposal['target_key']
    prior.require_target_eligible(key, status, gallery, rows)
    row = rows[key]
    require(key not in old and key not in manual and proposal['source'] == row
            and proposal['class_id'] == row['final_class_id'], f'Accepted machine identity differs: {key}')
    v1.no_confirmation(proposal, f'Machine {key}')
    require(proposal['production_saved'] is False and proposal['status'] == 'machine_draft_pending_visual_review',
            f'Machine status differs: {key}')
    require(proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == classification_sha,
            f'Machine frozen dataset binding differs: {key}')
    binding = proposal['template']
    require(binding['target_key'] in templates, f'Machine uses a non-direct template: {key}')
    template = templates[binding['target_key']]
    require(compatible(template['row'], row), f'Cross-class/split/policy/view or same-frame transfer: {key}')
    require(binding == template_binding(template)
            and proposal['vertex_count'] == len(proposal['polygon']) == len(template['polygon']) > 4,
            f'Machine direct-human template binding/topology differs: {key}')
    value = pose['current'].get(key)
    require(proposal['snapshot_sha256'] == pose_sha
            and proposal['target_expected_revision'] == (value['revision'] if value else 0)
            and proposal['target_snapshot_payload_sha256'] == (sha(value) if value else None), f'Machine target snapshot differs: {key}')
    require(proposal['generation_method'] == dict(name='original', version='attempt_target_v1',
            code_sha256=ORIGINAL_CODE['pallet/mask_template_continue.py']), f'Non-original machine method: {key}')
    prior.recompute(proposal, template, evidence)


def check_preserved_assets(out, old):
    hashes = read_json(out/'preserved_parent_assets.json')
    names = {f'{folder}/{key}.{ext}' for key in old for folder, ext in
             (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json'))}
    names |= {str(p.relative_to(PARENT)) for directory in ('templates', 'refined', 'generation', 'quota_generation')
              for p in (PARENT/directory).rglob('*') if p.is_file()}
    names.add('vertex2_before_after.png')
    require(set(hashes) == names, 'Preserved 237-parent assets/namespaces inventory differs')
    artifacts = read_json(PARENT/'artifact_hashes.json')
    for name, expected in hashes.items():
        require(expected == artifacts[name] == digest(PARENT/name) == digest(out/name), f'Historical asset differs: {name}')


def file_inventory(directory):
    return {str(p.relative_to(directory)): digest(p) for p in sorted(directory.rglob('*')) if p.is_file()}


def check_archives(out, manifest, generator_sha):
    expected = file_inventory(PARENT)
    require(read_json(out/'parent_file_inventory.json') == expected, 'Full frozen parent-file inventory differs')
    names = {'manifest.json', 'verification.json', 'proposals.jsonl', 'manual_proposals.jsonl',
             'manual_source_records.jsonl', 'new_proposals.jsonl', 'template_inventory.json', 'requests.jsonl'}
    require(file_inventory(out/'parent_evidence') == {n: expected[n] for n in names}, 'Archived parent canonical records/seal differ')
    require(read_json(out/'configuration_input_hashes.json') == file_inventory(PROJECT/'configs'), 'Generation configuration dependencies changed')
    code = manifest['frozen_code_sha256']
    require(file_inventory(out/'frozen_code') == code, 'Frozen algorithm/generator code archive differs')
    require(code.get('pallet/mask_quota_100.py') == generator_sha, 'Frozen quota-100 generator archive differs')
    diagnostic = manifest.get('preserved_diagnostic_generation')
    if diagnostic is not None:
        path = (PROJECT/diagnostic).resolve()
        require(path == PROJECT/'outputs/pallet_mask_quota_100_v1' and path != out,
                'Unexpected preserved diagnostic directory')
        hashes = read_json(out/'preserved_diagnostic_file_inventory.json')
        require(file_inventory(path) == hashes and manifest['preserved_diagnostic_manifest_sha256'] == hashes.get('manifest.json'),
                'Unpublished earlier diagnostic generation changed')


def check_rendering(out, inventory, parent_inventory, templates, old, manual, new):
    actual = indexed(inventory['templates'], 'rendering_id')
    historical = indexed(parent_inventory['templates'], 'rendering_id')
    require(all(actual.get(k) == v for k, v in historical.items()), 'Historical rendering namespace/payload changed')
    latest = {NAMESPACE+':'+k: dict(t, rendering_id=NAMESPACE+':'+k) for k, t in templates.items()}
    require(not set(latest) & set(historical) and set(actual) == set(historical) | set(latest),
            'Historical/latest rendering namespace coverage differs')
    for rendering_id, template in latest.items():
        key = template['row']['target_key']
        require(actual[rendering_id] == template
                and read_json(out/NAMESPACE/'templates'/f'{key}.json') == templates[key], f'Latest direct-human template differs: {key}')
    mapping = {k: parent_inventory['rendering_by_target'][k] for k in old}
    mapping.update({k: NAMESPACE+':'+p['template']['target_key'] for k, p in {**manual, **new}.items()})
    require(inventory['rendering_by_target'] == mapping, 'Proposal rendering/source mapping differs')
    require(inventory['historical_templates'] == len(historical)
            and inventory['generation_template_namespace'] == NAMESPACE
            and inventory['generation_template_keys'] == sorted(templates)
            and inventory['generation_templates'] == len(templates)
            and inventory['generation_templates_by_origin'] == dict(Counter(t['origin'] for t in templates.values())),
            'Latest rendering inventory counts/origins differ')


def check_snapshot_manifest(out, snapshots, frozen, publications, manifest, formal_sha):
    from pallet.mask_gallery_review import VERSION as EDITOR_VERSION
    snapshot_manifest = read_json(out/'snapshot_manifest.json')
    require(snapshot_manifest['formal_manifest_sha256'] == formal_sha, 'Snapshot formal binding differs')
    for kind, path in snapshots.items():
        store = frozen[kind]
        require(snapshot_manifest[kind] == dict(path=path.name, backup='backups/'+path.name,
            sha256=digest(path), saved=len(store['current']), events=len(store['events'])), f'{kind} snapshot manifest differs')
    request_hashes = {str(REQUESTS/name): value for name, value in REQUEST_PINS.items()}
    require(snapshot_manifest['manual_requests'] == dict(directory=str(REQUESTS), count=13, frozen_input_sha256=request_hashes)
            and manifest['manual_request_input_sha256'] == request_hashes, '13-target request input binding differs')
    source_publications = {}
    for version, pub in publications.items():
        path = pub['path']
        proposal_sha = digest(path/'proposals.jsonl')
        source_publications[str(version)] = dict(path=str(path), proposals_sha256=proposal_sha,
            manifest_sha256=digest(path/'manifest.json'), verification_sha256=digest(path/'verification.json'),
            binding=sha(dict(formal=formal_sha, proposals=proposal_sha, editor_version=EDITOR_VERSION)))
    require(snapshot_manifest['source_publications'] == source_publications, 'Frozen gallery source-publication inventory differs')


def check_report(out, combined, old_manual, manual, new, classes):
    from fontTools.ttLib import TTFont
    page = (out/'report_zh.html').read_text()
    parsed = prior.ReportInventory()
    parsed.feed(page)
    articles = indexed(parsed.articles, 'id')
    require(set(articles) == {'target-'+k for k in combined}, 'Report target inventory differs')
    for key, proposal in combined.items():
        card = articles['target-'+key]
        require(card['data-class'] == str(proposal['class_id'])
                and card['data-kind'] == ('manual' if key in old_manual or key in manual else 'machine')
                and card['data-batch'] == ('new' if key in new else 'previous'), f'Report card identity/kind differs: {key}')
    cells = []
    for cls in CLASSES:
        c = classes[str(cls)]
        cells.extend(str(v) for v in (cls, c['old_total'], c['manual_added'], c['saved_gallery_human'],
            c['saved_pose_human'], c['old_pending_machine'], c['new_candidates'], c['total'], c['missing']))
    require(parsed.cells == cells, 'Report old/manual/machine/distinct-frame/shortfall counters differ')
    require('100' in page and '251' in page and '43' in page
            and '不是机器迁移' in page and '未确认真值' in page and 'id="only-new" checked' in page,
            'Report lacks honest 251-human/43-pending/100-goal draft status')
    require(all(text in page for text in ('完成人工请求 13 份', '既有已保存人工轮廓复用 44 份',
            '不是新人工编辑', '已保存图册人工修订 164 份', '原位姿人工轮廓 87 份')),
            'Report conflates completed requests, existing reuse, new edits or saved human source counts')
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(out/'report-font.otf') as font:
        require(required <= set(font.getBestCmap()), 'Report Chinese 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 coverage evidence differs')
    require((out/'FONT_LICENSE.txt').is_file(), 'Missing report font license')


def audit(out, pose_live, gallery_live):
    verifier_sha, config_hashes = digest(__file__), v1.configuration_hashes()
    pose_config, gallery_config = (read_json(PROJECT/'configs'/name) for name in ('active_pose_review.json', 'active_mask_gallery.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 inputs must be the configured production review stores')
    publications = check_frozen_inputs()
    old, parent_manifest = publications[6]['proposals'], publications[6]['manifest']
    manifest, artifacts = read_json(out/'manifest.json'), read_json(out/'artifact_hashes.json')
    artifact_sha = digest(out/'artifact_hashes.json')
    prior.check_artifacts(out, artifacts)
    paths = {str(p.relative_to(out)) for p in out.rglob('*') if p.is_file()
             and str(p.relative_to(out)) not in ('artifact_hashes.json', 'validation_report.json')}
    require(paths == set(artifacts), 'Artifact inventory does not cover every generated file')
    require(manifest['publication_version'] == 7 and manifest['method'] == 'original', 'Expected publication 7 original method only')
    require(manifest['target_per_class'] == 100 and manifest['target_total'] == 500
            and manifest['forced_fill'] is False and manifest['unexpected_pose_seeds_implicitly_counted'] == 0,
            'Quota policy must be 100 per class / at most 500, without implicit human counting or forced fill')
    require((PROJECT/manifest['parent']).resolve() == PARENT.resolve()
            and manifest['parent_proposals_sha256'] == PARENT_PINS['proposals.jsonl']
            and manifest['parent_verification_sha256'] == PARENT_PINS['verification.json'], 'Frozen publication-6 parent binding differs')
    generator_sha = digest(PROJECT/'pallet/mask_quota_100.py')
    require(manifest['code_sha256'] == generator_sha == GENERATOR_SHA, 'Pinned quota-100 generator hash differs')
    for field, name in (('transfer_code_sha256', 'pallet/mask_template_transfer.py'),
                        ('boundary_code_sha256', 'pallet/mask_boundary_review.py'),
                        ('attempt_code_sha256', 'pallet/mask_template_continue.py')):
        require(manifest[field] == ORIGINAL_CODE[name], f'Original algorithm/gate provenance differs: {field}')
    for name, expected in manifest['frozen_code_sha256'].items():
        require(name in ORIGINAL_CODE or name == 'pallet/mask_quota_100.py', f'Unexpected frozen code dependency: {name}')
        require(expected == (generator_sha if name == 'pallet/mask_quota_100.py' else ORIGINAL_CODE[name])
                == digest(PROJECT/name), f'Frozen code hash differs: {name}')
    check_archives(out, manifest, generator_sha)
    for flag in ('thresholds_relaxed', 'recursive_candidate_propagation', 'automatic_human_confirmation',
                 'automatic_training_eligible', 'robot_command_eligible', 'ground_truth_eligible',
                 'manual_source_snapshots_imported_into_gallery_store'):
        require(manifest[flag] is False, f'Manifest {flag} must remain false')
    require(manifest['production_database_writes'] == manifest['cross_split_template_transfers'] == 0
            and manifest['original_splits_preserved'] is True, 'Manifest database-write/split policy differs')
    for field in ('configuration_writes', 'service_writes', 'new_human_edits_created', 'research_candidates_added'):
        require(manifest[field] == 0, f'Manifest {field} must be zero')
    for name, field in (('proposals.jsonl', 'proposals_sha256'), ('new_proposals.jsonl', 'new_proposals_sha256'),
                        ('manual_proposals.jsonl', 'manual_proposals_sha256'), ('manual_source_records.jsonl', 'manual_source_records_sha256'),
                        ('requests.jsonl', 'requests_sha256'), ('template_inventory.json', 'template_inventory_sha256'),
                        ('refined_annotations.jsonl', 'refined_annotations_sha256')):
        require(digest(out/name) == manifest[field], f'Manifest artifact hash differs: {name}')
    combined, manual, new, accepted = (indexed(read_jsonl(out/name)) for name in
        ('proposals.jsonl', 'manual_proposals.jsonl', 'new_proposals.jsonl', 'accepted_candidates.jsonl'))
    old_manual = indexed(read_jsonl(PARENT/'manual_proposals.jsonl'))
    all_manual = {**old_manual, **manual}
    requests = indexed(read_jsonl(REQUESTS/'requests.jsonl'))
    require(set(requests) == REQUEST_KEYS and set(requests) <= set(manual)
            and len(manual) == 57 and len(all_manual) == 87,
            'Exactly 13 requested + 44 existing reused + 30 inherited human sources are required')
    require(read_jsonl(out/'requests.jsonl') == read_jsonl(REQUESTS/'requests.jsonl'), 'Copied 13-target request worklist differs')
    check_partition(old, old_manual, manual, new, combined, accepted, all_manual)
    for folder, ext in (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json')):
        require({p.name for p in (out/folder).iterdir()} == {k+'.'+ext for k in combined},
                f'Only selected machine and explicit human/parent assets may be published: {folder}')
    require(manifest['previous_proposals'] == 237 and manifest['manual_added'] == 57
            and manifest['manual_proposals'] == 57 and manifest['inherited_manual_sources'] == 30
            and manifest['all_manual_sources'] == 87 and manifest['base_proposals'] == 294
            and manifest['manual_requested'] == 13 and manifest['manual_existing_reused'] == 44
            and manifest['new_proposals'] == len(new) and manifest['proposals'] == len(combined)
            and manifest['accepted_before_diversity'] == len(accepted), 'Manifest old/manual/base/machine counts differ')
    require(QUARANTINE not in combined and manifest['preserved_quarantined_targets'] == [QUARANTINE], 'Quarantine not preserved')
    check_preserved_assets(out, old)
    formal = (PROJECT/read_json(PROJECT/'configs/active_formal_dataset.json')['dataset']).resolve()
    classification = PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'
    formal_sha, classification_sha = digest(formal/'manifest.json'), digest(classification)
    require(formal_sha == manifest['formal_manifest_sha256'] == parent_manifest['formal_manifest_sha256']
            and classification_sha == manifest['classification_sha256'] == parent_manifest['classification_sha256'], 'Formal/classification hashes changed')
    protected = read_json(out/'protected_formal_before.json')
    require(len(protected) == 20768 and protected == read_json(PARENT/'protected_formal_before.json')
            == protected_snapshot(formal) == read_json(out/'protected_formal_after.json'), 'Protected 20,768 formal files differ')
    rows, sources = prior.formal_rows(formal, classification)
    require(len(rows) == 12344, 'Expected all 12,344 formal target identities')
    snapshots = prior.find_snapshots(out, manifest)
    frozen = {kind: prior.read_store(path, kind, frozen=True) for kind, path in snapshots.items()}
    pose, gallery = frozen['pose'], frozen['gallery']
    pose_sha, gallery_sha = digest(snapshots['pose']), digest(snapshots['gallery'])
    require(len(gallery['current']) == 164 and len(gallery['events']) == 171
            and len(pose['current']) >= 4772 and len(pose['events']) >= 10477, 'Snapshots predate completed gallery/manual work')
    require(json.loads(pose['metadata']['binding'])['formal_manifest_sha256'] == formal_sha
            and gallery['metadata']['formal_manifest_sha256'] == formal_sha, 'Snapshot dataset binding differs')
    for kind, prefix in (('pose', 'snapshot'), ('gallery', 'gallery_snapshot')):
        require(manifest[prefix+'_saved'] == len(frozen[kind]['current'])
                and manifest[prefix+'_events'] == len(frozen[kind]['events']), f'{kind} snapshot counters differ')
    check_snapshot_manifest(out, snapshots, frozen, publications, manifest, formal_sha)
    for kind, path in prior.find_snapshots(PARENT, parent_manifest).items():
        prior.preserve_events(prior.read_store(path, kind, frozen=True), frozen[kind])
    status = prior.pose_status(pose, rows)
    gallery_templates = independent_gallery_templates(pose, gallery, rows, old, formal_sha, gallery_sha, publications)
    require(len(gallery_templates) == 164, 'All 164 counted gallery humans must be active actual >4-vertex sources')
    direct, templates = independent_seed_union(pose, gallery_templates, rows, pose_sha, old, old_manual)
    with closing(sqlite3.connect(snapshots['pose'].resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        reference_current, reference_templates, reference_status = annotation_inventory(db, rows)
    require((pose['current'], direct, status) == (reference_current, reference_templates, reference_status),
            'Independent human history/templates/status differ from pinned original annotation_inventory')
    old_pose_path = prior.find_snapshots(PARENT, parent_manifest)['pose']
    old_pose = prior.read_store(old_pose_path, 'pose', frozen=True)
    old_direct = v1.independent_pose_templates(old_pose, rows)
    all_source_records = indexed(read_jsonl(out/'all_manual_sources.jsonl'))
    require(set(all_source_records) == set(all_manual), 'All-87 current manual source coverage differs')
    inherited_records, changed_manual = check_inherited_manual(out, old_manual, snapshots['pose'], pose, direct, pose_sha, all_source_records)
    require(manifest['inherited_manual_source_revisions_changed'] == changed_manual, 'Manifest inherited manual change flags differ')
    reuse_keys = independent_reuse_keys(pose, direct, rows, old, requests)
    require(set(manual) == set(requests) | reuse_keys and len(reuse_keys) == 44
            and Counter(rows[k]['final_class_id'] for k in reuse_keys) == {1: 5, 2: 2, 9: 8, 15: 29},
            'Existing-human quota additions do not match the independently recovered 44 authorized sources')
    reuse_inventory = indexed(read_jsonl(out/'manual_reuse_inventory.jsonl'))
    require(reuse_inventory == {k: dict(target_key=k, class_id=rows[k]['final_class_id'], reason='counted') for k in reuse_keys}
            and manifest['manual_reuse_excluded'] == [], 'Explicit existing-human reuse inventory differs')
    require(manifest['manual_reuse_keys'] == sorted(reuse_keys) and manifest['requested_manual_keys'] == sorted(requests),
            'Manifest requested/reused manual partitions differ')
    seed_only = sorted(set(direct)-set(old_direct)-set(manual))
    require(manifest['unexpected_new_pose_seed_only'] == seed_only, 'New pose-only seeds were silently counted as quota or omitted from provenance')
    allowed_origins = {urlsplit(r['pose_annotation_url']).netloc for r in requests.values()}
    for key, proposal in manual.items():
        check_manual(proposal, requests.get(key), pose, direct, rows[key], pose_sha, formal_sha, classification_sha)
        require(urlsplit(proposal['original_pose_url']).netloc in allowed_origins, f'Manual source URL origin differs: {key}')
        if key in requests:
            source = sources[rows[key]['frame_id']]
            require(requests[key]['source']['image'] == source['image']
                    and requests[key]['source']['image_sha256'] == digest(formal/source['image']), f'Manual original source image differs: {key}')
    records = indexed(read_jsonl(out/'manual_source_records.jsonl'))
    require(set(records) == set(manual) and all(all_source_records[k] == r for k, r in records.items()),
            'Added-57 exact source records differ from all-87 current-source inventory')
    check_new_manual_records(records, manual, snapshots['pose'], pose_sha)
    for name in ('all_manual_sources', 'inherited_manual_source_audit', 'manual_reuse_inventory', 'accepted_candidates', 'registration_attempts', 'outcomes'):
        require(manifest[name+'_sha256'] == digest(out/f'{name}.jsonl'), f'Manifest provenance/attempt artifact binding differs: {name}')
    inventory = read_json(out/'template_inventory.json')
    check_rendering(out, inventory, read_json(PARENT/'template_inventory.json'), templates, old, manual, new)
    origins = dict(Counter(t['origin'] for t in templates.values()))
    require(manifest['generation_templates'] == len(templates) and manifest['generation_templates_by_origin'] == origins
            and manifest['generation_template_namespace'] == NAMESPACE, 'Latest human seed-union totals differ')
    require(indexed(read_jsonl(out/'refined_annotations.jsonl')) == gallery['current'], 'Latest gallery export differs')
    evidence = ImageEvidence(formal, rows, sources)
    for key, proposal in combined.items():
        require(proposal['source'] == rows[key] and proposal['formal_manifest_sha256'] == formal_sha
                and proposal['class_assignments_sha256'] == classification_sha, f'Cumulative original source binding differs: {key}')
        v1.check_assets(out, proposal, rows[key], evidence, manual=key in all_manual)
    for proposal in accepted.values():
        check_machine(proposal, pose, templates, rows, status, gallery, old, manual, pose_sha, formal_sha, classification_sha, evidence)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    require(set(outcomes) == set(rows) and all(v['class_id'] == rows[k]['final_class_id'] for k, v in outcomes.items()),
            'Outcomes must cover all 12,344 formal identities exactly once')
    require(manifest['outcomes'] == dict(Counter(v['reason'] for v in outcomes.values())), 'Manifest outcome counts differ')
    eligible, attempt_count = audit_attempts(out, rows, status, gallery, old, manual, templates, accepted, outcomes, evidence)
    require(manifest['scanned_eligible_targets'] == len(eligible), 'Eligible scan count differs')
    check_diversity({**old, **manual}, accepted, new, outcomes)
    classes, counts = expected_counts(old, old_manual, manual, new, gallery)
    base_classes, base_counts = expected_counts(old, old_manual, manual, {}, gallery)
    require({c: v['distinct_frames'] for c, v in base_counts.items()} == {'1': 55, '2': 52, '9': 58, '10': 50, '15': 79}
            and sum(c['saved_human'] for c in base_classes.values()) == 251
            and sum(c['prior_machine_pending'] for c in base_classes.values()) == 43, 'Expected 294-frame base: 251 saved humans and 43 pending machines')
    require(manifest['base_classes'] == base_classes, 'Independent 294-frame base counters differ')
    shortfalls = read_json(out/'shortfalls.json')
    require(set(shortfalls) == set(classes) == set(manifest['classes']), 'Shortfall/class inventory differs')
    for cls, values in classes.items():
        n = int(cls)
        class_outcomes = Counter(v['reason'] for v in outcomes.values() if v['class_id'] == n)
        values.update(templates=sum(t['row']['final_class_id'] == n for t in templates.values()),
            eligible=sum(rows[k]['final_class_id'] == n for k in eligible),
            compatible_targets=sum(class_outcomes[r] for r in ('new_proposal', 'image_similarity_below_gate',
                'registration_or_boundary_rejected', 'accepted_duplicate_frame_not_selected', 'accepted_quota_full_not_selected')),
            preview=values['total'], outcomes=dict(class_outcomes))
        require(manifest['classes'][cls] == values, f'Class {cls} independent quota/scan counters differ')
        require(shortfalls[cls]['missing'] == values['missing'] and shortfalls[cls]['outcomes'] == values['outcomes'], f'Class {cls} shortfalls differ')
    require(inventory['classes'] == classes and inventory['eligibility'] == status
            and inventory['snapshot_saved'] == len(pose['current']) and inventory['snapshot_events'] == len(pose['events'])
            and inventory['gallery_snapshot_saved'] == len(gallery['current']), 'Inventory snapshot/eligibility/class counters differ')
    require(inventory['unexpected_new_pose_seed_only'] == seed_only, 'Inventory seed-only pose-source audit differs')
    require(manifest['new_by_class'] == {str(c): n for c, n in Counter(p['class_id'] for p in new.values()).items()}
            and manifest['manual_by_class'] == {'1': 5, '2': 2, '9': 8, '10': 13, '15': 29},
            'Machine/all-human class counters differ')
    require(manifest['counted_manual_source_keys'] == inventory['counted_manual_source_keys'] == sorted(all_manual), 'All-87 human source-key inventory differs')
    require(manifest['newly_counted_manual_source_keys'] == inventory['newly_counted_manual_source_keys'] == sorted(manual)
            and inventory['previous_proposals'] == 237 and inventory['manual_proposals'] == 57
            and inventory['inherited_manual_sources'] == 30 and inventory['all_manual_sources'] == 87,
            'Inventory original/new-human counters differ')
    require(inventory['manual_reuse_keys'] == sorted(reuse_keys) and inventory['requested_manual_keys'] == sorted(requests)
            and inventory['manual_requested'] == 13 and inventory['manual_existing_reused'] == 44,
            'Rendering inventory requested/reused manual partitions differ')
    for field in ('saved_gallery_human', 'existing_saved_pose_human', 'saved_pose_human', 'saved_human', 'old_pending_machine', 'missing'):
        require(manifest[field] == sum(c[field] for c in classes.values()), f'Manifest saved/pending/shortfall total differs: {field}')
    require(manifest['new_machine_pending'] == len(new) and manifest['registration_attempts'] == attempt_count,
            'Manifest selected-machine/registration counts differ')
    protection = read_json(out/'protected_targets.json')
    require(protection['previous'] == sorted(old) and protection['gallery_saved_or_history'] == sorted(gallery['history_keys'])
            and protection['pose_mask_history_or_noneligible'] == sorted(k for k, v in status.items() if v != 'eligible')
            and protection['quarantine'] == [QUARANTINE] and protection['eligibility'] == status, 'Protected-history inventory differs')
    require(protection['counted_manual_source_keys'] == sorted(all_manual)
            and protection['newly_counted_manual_source_keys'] == sorted(manual), 'Protected manual quota-key inventory differs')
    require(protection['manual_reuse_keys'] == sorted(reuse_keys) and protection['requested_manual_keys'] == sorted(requests),
            'Protected requested/reused manual partitions differ')
    check_report(out, combined, old_manual, manual, new, classes)
    used = read_json(out/'used_image_hashes.json')
    for name, expected in {**read_json(PARENT/'used_image_hashes.json'), **evidence.used}.items():
        require(used.get(name) == expected, f'Original/used source image hash missing: {name}')
    for name, expected in used.items():
        path = (formal/name).resolve()
        require(path.is_relative_to(formal) and digest(path) == expected, f'Original source image changed: {name}')
    require(protected_snapshot(formal) == protected and digest(classification) == classification_sha, 'Formal/classification changed during audit')
    for kind, path in snapshots.items():
        require(digest(path) == (pose_sha if kind == 'pose' else gallery_sha), f'{kind} immutable snapshot changed during audit')
    prior.check_artifacts(out, artifacts)
    require(digest(out/'artifact_hashes.json') == artifact_sha, 'Artifact inventory changed during audit')
    check_frozen_inputs()
    check_archives(out, manifest, generator_sha)
    require(digest(PROJECT/'pallet/mask_quota_100.py') == generator_sha, 'Generator changed during audit')
    live = {'pose': prior.read_store(pose_live, 'pose'), 'gallery': prior.read_store(gallery_live, 'gallery')}
    v1.check_live_dependencies(frozen, live, templates, accepted, all_manual, rows)
    require(v1.independent_pose_templates(live['pose'], rows) == direct, 'Latest human pose seed inventory changed during audit')
    inherited.check_live_manual_records(pose_live, {**inherited_records, **records})
    require(v1.configuration_hashes() == config_hashes and digest(__file__) == verifier_sha, 'Authorization/configuration/verifier changed during audit')
    return dict(state='passed', publication_version=7, proposals_verified=len(combined), proposals_sha256=manifest['proposals_sha256'],
        manifest_sha256=digest(out/'manifest.json'), artifact_hashes_sha256=artifact_sha,
        new_verified=len(new), manual_verified=57, all_manual_sources_verified=87, manual_added=57, manual_requested_verified=13,
        manual_existing_reused_verified=44, inherited_manual_verified=30,
        old_canonical_objects_preserved=237, base_distinct_frames=294, saved_human_sources_verified=251,
        prior_machine_pending=43, classes=counts, templates_verified=len(templates), templates_by_origin=origins,
        accepted_before_diversity_recomputed=len(accepted), registration_attempts_verified=attempt_count,
        all_new_registrations_and_metrics_recomputed=True, all_rejected_attempts_and_metrics_recomputed=True,
        manual_exact_sqlite_payloads_and_human_events_verified=True, inherited_manual_current_raw_records_verified=True,
        manual_sources_not_machine_transfers=True, manual_snapshots_not_imported_into_gallery_store=True,
        authorized_existing_human_reuse_without_fake_requests=True, new_human_edits_created=0,
        requested_manual_targets_preserved=13, existing_reused_manual_targets=44,
        outcomes_verified=len(outcomes), protected_formal_files_verified=len(protected), metric_absolute_tolerance=prior.ATOL,
        original_events_preserved={kind: len(store['events']) for kind, store in frozen.items()},
        pose_snapshot_sha256=pose_sha, gallery_snapshot_sha256=gallery_sha,
        method='original', thresholds_relaxed=False, forced_fill=False, production_database_writes=0,
        human_confirmation_inferred=False, automatic_training_eligible=False, robot_command_eligible=False, ground_truth_eligible=False,
        live_dependencies_unchanged=True, authorization_dependencies_unchanged=True,
        extra_public_images=['vertex2_before_after.png'], verification_script_sha256=verifier_sha,
        verified_at=datetime.now(timezone.utc).isoformat())


def check_new_manual_records(records, manual, snapshot, pose_sha):
    with closing(sqlite3.connect(snapshot.resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        for key, proposal in manual.items():
            current = db.execute('SELECT revision,payload FROM annotations WHERE target_key=?', (key,)).fetchall()
            events = db.execute('SELECT id,revision,payload FROM events WHERE target_key=? AND revision=?',
                (key, proposal['template']['human_polygon_revision'])).fetchall()
            require(len(current) == len(events) == 1, f'Ambiguous new human SQLite source: {key}')
            revision, raw = current[0]
            event_id, event_revision, event_raw = events[0]
            expected = dict(schema='saved_pose_mask_source_freeze_v1', target_key=key, snapshot_sha256=pose_sha,
                current_revision=revision, current_payload_sha256=sha(json.loads(raw)), current_payload_raw=raw,
                current_payload=json.loads(raw), current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
                human_event_id=event_id, human_polygon_revision=event_revision,
                human_event_sha256=hashlib.sha256(event_raw.encode()).hexdigest(), human_event_payload_raw=event_raw,
                human_event_payload=json.loads(event_raw), polygon_sha256=sha(proposal['polygon']))
            require(records[key] == expected, f'New manual exact raw SQLite payload/event freeze differs: {key}')


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=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3')
    parser.add_argument('--gallery-live', type=Path, default=PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3')
    args = parser.parse_args(argv)
    out = args.output.resolve()
    allowed = out == OUTPUT.absolute() or (out.parent == PROJECT/'outputs' and re.fullmatch(r'pallet_mask_quota_100_v[0-9]+', out.name))
    require(not args.output.is_symlink() and not OUTPUT.is_symlink() and allowed and out.is_dir(), 'Use the completed publication-7 quota-100 outputs directory only')
    require(out != PARENT.resolve(), 'Cannot verify over the frozen parent')
    require(not (out/'verification.json').exists(), 'Refusing to overwrite a frozen verification')
    require((out/'manifest.json').is_file(), 'Generation is not complete: manifest.json missing')
    require(not (out/'validation_report.json').is_symlink() and not (out/'verification.json').is_symlink(), 'Unsafe report/seal path')
    cv2.setNumThreads(1)
    try:
        result = audit(out, args.pose_live, args.gallery_live)
    except Exception as exc:
        report = dict(state='failed', publication_version=7, error_type=type(exc).__name__, error=str(exc), verification_script_sha256=digest(__file__))
        (out/'validation_report.json').write_bytes(canonical(report)+b'\n')
        raise
    (out/'validation_report.json').write_bytes(canonical(result)+b'\n')
    result['validation_report_sha256'] = digest(out/'validation_report.json')
    with (out/'verification.json').open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    print(json.dumps(result, ensure_ascii=False), flush=True)


if __name__ == '__main__':
    main()
