"""Independently seal publication 8 after its original-method generation finishes.

Only validation_report.json and an exclusive, successful verification.json are
written. No generator is imported, no live store/configuration is written, and
actual four-vertex human work is never promoted to a >4-vertex transfer seed.
"""
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_100 as previous
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, unchanged_rectangle
from pallet.pose_review_geometry import canonical, polygon_value

v1, prior = previous.v1, previous.prior
require, sha = prior.require, prior.sha
read_json, read_jsonl, indexed = prior.read_json, prior.read_jsonl, prior.indexed
CLASSES, LIMIT, QUARANTINE = previous.CLASSES, 100, previous.QUARANTINE
FALSE_FLAGS = previous.FALSE_FLAGS
POSE_ORIGIN, GALLERY_ORIGIN = previous.POSE_ORIGIN, previous.GALLERY_ORIGIN
NAMESPACE = 'quota100_continue_generation'
PARENT = PROJECT/'outputs/pallet_mask_quota_100_v2'
OUTPUT = PROJECT/'outputs/pallet_mask_quota_100_continue_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_quota_100_requests_v2'
GENERATOR = 'pallet/mask_quota_100_continue.py'
GENERATOR_SHA = '7764b378abb651bafe820eeed961bd792d4c53c35eb8e2ba8fa6d2e5f77f56ab'
FOUR_VERTEX_KEY = '3b702879c30d94bb85fd9a56'
FOUR_VERTEX_RAW_SHA = '7b00f606edd478b37041e5231663adb4bf2c5886606d20b3046f8d944cf3115c'
PARENT_PINS = {
    'manifest.json': 'f90a847a4ddf51fde32c7f1e2cd5a5082a76fcfd3f7295ff48e1a6630f0b772c',
    'verification.json': 'f68664e4f335ec8aed0b6f6ce8b1a623d84887a1976c227ca9303809ffefade2',
    'proposals.jsonl': '397bb3fc39f2305f4bafa28b0b77d446e1867a5c52cae18d1a1c95ed46282e64',
    'artifact_hashes.json': '466ea1c895fed79da711f60a13e8f6f55bee1635246200ea841af6d883897338',
    'template_inventory.json': '05884d5d63752ff0937db1a356cfe36d2168b86c0103849f6401a7e499fa95fd',
    'all_manual_sources.jsonl': 'efdd431eb0283fa60682d582a977f4fc61e07ce3df51797200d773395109ce97',
    'manual_proposals.jsonl': '458649339a32998655bbf367a9e3f15329dce76e63eb8d784d3352347546dede',
    'manual_source_records.jsonl': 'c256e1b758a026ecc210e2446144737832270cd658518b2b5cc529089d45e6f5',
    'protected_formal_before.json': '02de366b0c0f691c2c11457c3f6976fe0bed32579992403bfbee3ea2be8ee4b1',
    'used_image_hashes.json': 'eedd08b1ef589c42dc0a69ceedb4c82dd4a4a9038aca15086c89a427872592eb',
    'delivery_verification.json': 'b786ab5cf106e58cf886fb31455584c75661f6600d071a92d616aed6de826bbe',
    'pallet_mask_refined_review.zip': '78e57bdc5355eb9bd13bf36e3455d5c491738ee19a1ef36fc147efe5dc285e1a',
}
REQUEST_PINS = {
    'manifest.json': '3a41f88be99d6eeef3bf70660355376560b503afafaf067e8a8c07fde936a936',
    'verification.json': '35e2529b7bed52cc201d1dd690d8ab9510f68973c8f5a66b41b6fbc33ad6ce91',
    'requests.jsonl': 'de8342da1ac56b82009f4a96f664fa5470b3c987774873fa754b827a5db59f23',
}
REQUEST_KEYS = frozenset({
    'fbde147654acaefeb6996cc2', '78743a5834f786661f1f76e7', 'ecc660e0810933ae4ca52980',
    '79a71c1054b395930284d7c3', '82d495d69006b82f91bfe5cc', '20bfdc2be54b003a9679d954',
    'abe0495a098b3f3f93d384c1', '306b3cb6c69d3f27691fd04a', '61c3b7b434a549ccb22db2b3',
    '986233a6f6bc97dd98887d2e', 'e931b2c37bf2f56c8af4ea1e', '0d707a13265e2f6ce6c24f85',
    'be8b7705942bdc3256a943ca', '3133bbb89bb161783a2fa501', '80d701b22185ffb176740982',
    '7e10cd91433aeb7c6842d052', '8af9cf91999e259d4be07832', 'e1953a22b9b424dfb6602564',
    '6eced58e36b6e62895c64607', 'e37a3a9ac0b2024531585c72', FOUR_VERTEX_KEY,
    'cd6dda56f35d6ba270a15318', '125bbb53ac7c82652f341714', '78f59eaee4143452e8d26fc4',
})
ORIGINAL_CODE = {
    **previous.ORIGINAL_CODE,
    'pallet/mask_quota_100.py': previous.GENERATOR_SHA,
    'scripts/verify_mask_quota_100.py': '99fd65f40a8ec342cd63c3e8e59629171ee669992290fc3edd47e2c53c0bee3b',
}
count_frames = previous.count_frames
template_binding = previous.template_binding
check_diversity = previous.check_diversity
check_machine = previous.check_machine
file_inventory = previous.file_inventory


def check_frozen_inputs():
    publications = previous.check_frozen_inputs()
    for name, expected in PARENT_PINS.items():
        require(digest(PARENT/name) == expected, f'Frozen publication 7 changed: {name}')
    for name, expected in REQUEST_PINS.items():
        require(digest(REQUESTS/name) == expected, f'Frozen 24-target request worklist changed: {name}')
    for name, expected in ORIGINAL_CODE.items():
        require(digest(PROJECT/name) == expected, f'Frozen original code changed: {name}')
    manifest, seal = read_json(PARENT/'manifest.json'), read_json(PARENT/'verification.json')
    require(manifest['publication_version'] == seal['publication_version'] == 7 and seal['state'] == 'passed'
            and manifest['proposals'] == seal['proposals_verified'] == 378
            and seal['all_manual_sources_verified'] == 87 and seal['new_verified'] == 84,
            'Publication 7 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'], 'Parent independent seal hashes differ')
    require(digest(PARENT/'validation_report.json') == seal['validation_report_sha256']
            and read_json(PARENT/'validation_report.json') == {k: v for k, v in seal.items() if k != 'validation_report_sha256'},
            'Parent validation report is not its sealed audit')
    artifacts = read_json(PARENT/'artifact_hashes.json')
    prior.check_artifacts(PARENT, artifacts)
    require(set(file_inventory(PARENT)) == set(artifacts) | {'artifact_hashes.json', 'verification.json',
            'validation_report.json', 'delivery_verification.json', 'pallet_mask_refined_review.zip'},
            'Parent frozen file inventory coverage differs')
    old = indexed(read_jsonl(PARENT/'proposals.jsonl'))
    require(len(old) == 378 and Counter(p['class_id'] for p in old.values()) == {1: 58, 2: 100, 9: 83, 10: 54, 15: 83},
            'Expected all 378 canonical parent objects')
    require(sum(p.get('schema') == 'saved_pose_mask_gallery_entry_v1' for p in old.values()) == 87,
            'Parent must inherit all 87 manual objects, not just its 57 additions')
    publications[7] = dict(path=PARENT, proposals=old, manifest=manifest)
    requests = indexed(read_jsonl(REQUESTS/'requests.jsonl'))
    require(set(requests) == REQUEST_KEYS and Counter(r['class_id'] for r in requests.values()) == {1: 10, 9: 2, 10: 10, 15: 2},
            'Exact frozen 24 requested targets/classes are required')
    request_seal = read_json(REQUESTS/'verification.json')
    require(request_seal['state'] == 'passed' and request_seal['request_count'] == 24
            and request_seal['requests_sha256'] == REQUEST_PINS['requests.jsonl'], 'Request worklist seal differs')
    prior.check_artifacts(REQUESTS, request_seal['public_assets'])
    return publications


def independent_human_sources(store, rows, allow_four=False):
    """Recover current human polygons from raw events, not source-record claims.

    A machine proposal invalidates an older human event even if the polygons
    happen to be equal. Unit/axis normalization may follow a real human save.
    Four vertices are permitted for manual work, never for transfer templates.
    """
    last_human = {}
    for event_id, key, revision, raw in store['events']:
        value = json.loads(raw)
        kind = value.get('event_kind')
        if kind == 'mask_template_proposal' or value.get('state') in ('deleted', 'deferred'):
            last_human.pop(key, None)
        elif kind not in {'unit_normalization', 'axes_normalization'}:
            last_human[key] = (event_id, revision, value, hashlib.sha256(raw.encode()).hexdigest())
    result = {}
    for key, value in store['current'].items():
        polygon, human = value.get('polygon', []), last_human.get(key)
        if value.get('state') in ('deleted', 'deferred') or len(polygon) < (4 if allow_four else 5):
            continue
        if human is None or human[2].get('polygon') != polygon:
            continue
        require(key in rows, f'Unknown human source: {key}')
        if len(polygon) == 4 and unchanged_rectangle(polygon, rows[key]):
            continue  # An unchanged default rectangle is not evidence of mask editing.
        polygon_value(polygon, *rows[key]['size'])
        result[key] = dict(row=rows[key], polygon=polygon, revision=value['revision'],
            human_polygon_revision=human[1], human_event_sha256=human[3],
            current_payload_sha256=sha(value), human_mask_confirmed=value.get('human_mask_confirmed', False))
    return result


def independent_gallery_templates(pose, gallery, rows, old, formal_sha, gallery_sha, publications):
    """Resolve every latest gallery save to its actual pub3/4/5/6/7 original."""
    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, version = rows[key], 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 = {f: row[f] for f 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 original image/source binding differs: {key}')
        require(value['event_kind'] == 'human_mask_gallery_revision' and value['human_edited'] is True,
                f'Gallery source is not an actual saved human revision: {key}')
        for flag in (*FALSE_FLAGS[:-1], '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, old_manual):
    direct = independent_human_sources(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)
    templates.pop(QUARANTINE, None)
    pending = set(old)-set(gallery_templates)-set(old_manual)
    require(not pending & set(templates), 'Unreviewed historical machine proposal used as a human seed')
    require(all(len(t['polygon']) > 4 for t in templates.values()), 'Four-vertex manual source used as a transfer seed')
    return direct, templates


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]
    human_events = [json.loads(raw) for _, k, rev, raw in pose['events']
        if k == key and rev == template['human_polygon_revision'] and hashlib.sha256(raw.encode()).hexdigest() == template['human_event_sha256']]
    require(len(human_events) == 1 and human_events[0].get('state') == 'draft'
            and human_events[0].get('polygon') == value['polygon']
            and human_events[0].get('event_kind') not in {'mask_template_proposal', 'unit_normalization', 'axes_normalization'}
            and not any(human_events[0].get(f) for f in FALSE_FLAGS), f'Manual actual human event is invalid: {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}')
    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}')
        require(row[field] == human_events[0]['source'][field], f'Manual human-event original source {field} differs: {key}')
        if request is not None:
            require(request['source'][field] == row[field], f'Manual request source {field} 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}')
    require(len(value['polygon']) > 4 or (request is not None and not unchanged_rectangle(value['polygon'], row)),
            f'Unchanged rectangle or unrequested four-vertex source counted: {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}')
    for flag in FALSE_FLAGS:
        require(not value.get(flag), 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
            and proposal['machine_transfer_performed'] is False and proposal['new_human_edit_created'] is False,
            f'Manual falsely claims a store write, new edit or transfer: {key}')
    if request is not None:
        require(request['target_key'] == key and request['class_id'] == row['final_class_id']
                and request['source']['viewpoint_candidate'] == row['viewpoint_candidate']
                and request['source']['formal_manifest_sha256'] == formal_sha, f'Manual exact request source differs: {key}')
        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 and proposal['manual_source_kind'] == 'existing_saved_human_reuse_for_100_goal'
                and 'existing_human_reuse_not_new_edit' in proposal['flags'], f'Existing saved source invents a request or new edit: {key}')
        require(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 reuse authorization differs: {key}')
        url = urlsplit(proposal['original_pose_url'])
        require(url.scheme == 'https' and bool(url.netloc) and parse_qs(url.query).get('target') == [key], f'Reuse original source URL differs: {key}')
    four = len(value['polygon']) == 4
    binding_field = 'human_source' if four and 'human_source' in proposal else 'template'
    require(not (four and 'human_source' in proposal and 'template' in proposal), f'Ambiguous four-vertex self-source binding: {key}')
    require(proposal.get('manual_four_point_source') is four and proposal.get('propagation_seed_eligible') is (not four),
            f'Manual coverage/propagation flags differ: {key}')
    rendering_id = NAMESPACE+(':manual_source:' if binding_field == 'human_source' else ':')+key
    require(proposal['rendering_id'] == rendering_id and proposal['snapshot_sha256'] == pose_sha
            and proposal['target_expected_revision'] == value['revision']
            and proposal['target_snapshot_payload_sha256'] == sha(value), f'Manual latest snapshot/rendering binding differs: {key}')
    expected = dict(template, origin=POSE_ORIGIN, pose_review=v1.pose_provenance(template, pose_sha))
    require(proposal[binding_field] == template_binding(expected), f'Manual self-source/human event provenance differs: {key}')
    require(proposal.get('metrics') == {} and 'continuation' not in proposal
            and 'manual_source_not_machine_transfer' in proposal['flags'], f'Manual source claims transfer metrics/status: {key}')


def check_new_manual_records(records, manual, snapshot, pose_sha):
    """Compare exact bytes; new records additionally declare topology/seed policy."""
    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():
            binding = proposal.get('human_source') or proposal['template']
            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, binding['human_polygon_revision'])).fetchall()
            require(len(current) == len(events) == 1, f'Ambiguous manual 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']))
            if 'manual_four_point_source' in proposal:
                four = len(proposal['polygon']) == 4
                expected.update(vertex_count=len(proposal['polygon']), manual_four_point_source=four, propagation_seed_eligible=not four)
            require(records[key] == expected, f'Manual exact raw SQLite payload/event freeze differs: {key}')


def independent_reuse(pose, direct, rows, old, requested):
    """Deterministic genuine-human reuse, only where a distinct-frame quota fits."""
    frames = {p['source']['frame_id'] for p in list(old.values())+list(requested.values())}
    counts = Counter(p['class_id'] for p in list(old.values())+list(requested.values()))
    selected, inventory = set(), {}
    for key, template in sorted(direct.items()):
        row, value = rows[key], pose['current'][key]
        cls = row['final_class_id']
        if key in old or key in requested or cls not in CLASSES:
            continue
        fields = ('target_key', 'target_id', 'frame_id', 'split', 'group_id', 'box_index', 'bbox', 'size', 'source_pcd_sha256', 'policy_id')
        reason = ('quarantined' if key == QUARANTINE else
            'duplicate_frame' if row['frame_id'] in frames else
            'inactive_or_mismatched_current' if value.get('state') != 'draft' or template['polygon'] != value['polygon'] else
            'source_identity_mismatch' if any(value.get('source', {}).get(f) != row[f] for f in fields) else
            'confirmed_or_eligible' if any(value.get(flag) for flag in FALSE_FLAGS) else
            'quota_full' if counts[cls] >= LIMIT else 'counted')
        inventory[key] = dict(target_key=key, class_id=cls, reason=reason)
        if reason == 'counted':
            selected.add(key)
            frames.add(row['frame_id'])
            counts[cls] += 1
    return selected, inventory


def check_inherited_manual(out, manual, snapshot, pose, direct, pose_sha, all_sources):
    historical = indexed(read_jsonl(PARENT/'all_manual_sources.jsonl'))
    audits = indexed(read_jsonl(out/'inherited_manual_source_audit.jsonl'))
    require(set(historical) == set(audits) == set(manual) and len(manual) == 87,
            'All 87 parent manual objects need exact-source current audits')
    # Older canonical objects bind their original snapshots, not the parent overlay.
    historical_records = {}
    for root in (PARENT, previous.PARENT):
        historical_records.update(indexed(read_jsonl(root/'manual_source_records.jsonl')))
    changed, live_records = [], {}
    for key, proposal in manual.items():
        record = historical_records[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 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.get('state') == 'draft' and value['polygon'] == direct[key]['polygon'],
                f'Inherited saved-human source no longer current/direct: {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}')
        require(not any(value.get(f) for f in FALSE_FLAGS), f'Inherited source falsely confirmed/eligible: {key}')
        expected = 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] == expected, f'Inherited human current-source audit differs: {key}')
        source = all_sources[key]
        require(source.get('inherited_manual_source') is True and source.get('legacy_source_audit') == expected,
                f'Inherited 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 expected['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 expected_counts(old, old_manual, manual, new, gallery, requests=REQUEST_KEYS):
    counts = count_frames(list(old.values())+list(manual.values())+list(new.values()))
    require(set(old_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 old_manual.items() if p['class_id'] == cls}
        requested = sum(p['target_key'] in requests for p in added)
        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=len(added)-requested, 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,
            manual_four_point_sources=sum(len(p['polygon']) == 4 for p in added),
            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)+sum(len(p['polygon']) > 4 for p in 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'] == 8 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  # Geometry/metrics of every accepted candidate are recomputed separately.
            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')
    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 reasons} == set(accepted), 'Accepted outcome coverage differs')
    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_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', 'quota100_generation')
        for p in (PARENT/directory).rglob('*') if p.is_file()}
    names.add('vertex2_before_after.png')
    require(set(hashes) == names, 'Preserved 378-parent assets/all 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 check_archives(out, manifest, generator_sha, publications):
    expected = file_inventory(PARENT)
    require(read_json(out/'parent_file_inventory.json') == expected, 'Full frozen parent-file inventory differs')
    archived = file_inventory(out/'parent_evidence')
    required = {'manifest.json', 'verification.json', 'proposals.jsonl', 'manual_proposals.jsonl',
        'manual_source_records.jsonl', 'all_manual_sources.jsonl', 'new_proposals.jsonl', 'template_inventory.json'}
    require(required <= set(archived) <= set(expected) and all(expected[n] == h for n, h in archived.items()),
            'Archived parent canonical records/seal differ')
    require(read_json(out/'configuration_input_hashes.json') == file_inventory(PROJECT/'configs'), 'Configuration dependencies changed')
    require(read_json(out/'request_file_inventory.json') == file_inventory(REQUESTS), 'Full frozen request artifact inventory differs')
    require(read_json(out/'source_publication_file_inventories.json') ==
        {str(v): file_inventory(pub['path']) for v, pub in publications.items() if v != 7}, 'Historical source-publication files changed')
    code = manifest['frozen_code_sha256']
    require(file_inventory(out/'frozen_code') == code and code.get(GENERATOR) == generator_sha, 'Frozen code archive differs')
    require(set(read_json(PARENT/'manifest.json')['frozen_code_sha256']) | {GENERATOR} <= set(code), 'Frozen code omits inherited dependencies')


def check_rendering(out, inventory, parent_inventory, templates, old, manual, new):
    actual, historical = indexed(inventory['templates'], 'rendering_id'), indexed(parent_inventory['templates'], 'rendering_id')
    require(all(actual.get(k) == v for k, v in historical.items()), 'Historical rendering namespace/payload changed')
    # The four-vertex self-source is a manual binding only, not a seed inventory entry.
    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}')
    require({p.name for p in (out/NAMESPACE/'templates').iterdir()} == {k+'.json' for k in templates},
            'Latest template files contain an omitted or four-vertex non-seed source')
    mapping = {k: parent_inventory['rendering_by_target'][k] for k in old}
    mapping.update({k: p['rendering_id'] if p.get('manual_four_point_source') else NAMESPACE+':'+p['template']['target_key']
        for k, p in {**manual, **new}.items()})
    require(inventory['rendering_by_target'] == mapping, 'Proposal rendering/source mapping differs')
    for key, proposal in manual.items():
        if len(proposal['polygon']) == 4:
            require(key not in templates and NAMESPACE+':'+key not in actual, 'Manual four-vertex source leaked into seed inventory')
    four_sources = [dict(target_key=k, rendering_id=p['rendering_id'], polygon=p['polygon'],
        human_source=p.get('human_source') or p['template'], manual_four_point_source=True, propagation_seed_eligible=False)
        for k, p in sorted(manual.items()) if len(p['polygon']) == 4]
    require(inventory['manual_source_renderings'] == four_sources
            and inventory['deferred_manual_template_keys'] == [v['target_key'] for v in four_sources],
            'Manual-only source rendering inventory 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
    value = read_json(out/'snapshot_manifest.json')
    require(value['formal_manifest_sha256'] == formal_sha, 'Snapshot formal binding differs')
    for kind, path in snapshots.items():
        store = frozen[kind]
        require(value[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): h for name, h in REQUEST_PINS.items()}
    require(value['manual_requests'] == dict(directory=str(REQUESTS), count=24, frozen_input_sha256=file_inventory(REQUESTS))
            and manifest['manual_request_input_sha256'] == request_hashes, '24-target request input binding differs')
    expected = {}
    for version, pub in publications.items():
        path, proposal_sha = pub['path'], digest(pub['path']/'proposals.jsonl')
        expected[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(value['source_publications'] == expected, '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 manual/machine/distinct-frame/shortfall counters differ')
    require(all(text in page for text in ('39/84', '45', '四点', '不作传播模板', '不是机器迁移', '未确认真值', 'id="only-new" checked')),
            'Report omits honest 39/84 saved, 45 missing, manual/draft status')
    summaries = ('实际已保存复核 39/84 份，另 45 份未保存，不作种子',
        f'本轮计入已保存人工描绘 {len(manual)} 份', '四点来源 1 份',
        '已保存图册人工 203 份', f'原位姿人工 {len(old_manual)+len(manual)} 份',
        f'去重人工覆盖 {203+len(old_manual)+len(manual)} 份', '历史待复核 88 份',
        f'本轮新增机器候选 {len(new)} 份', f'累计 {len(combined)} 个不同帧')
    require(all(text in page for text in summaries), 'Report summary conflates unsaved drafts, saved humans or quota coverage')
    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'/n) for n 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')
    require((PROJECT/gallery_config['directory']).resolve() == PARENT.resolve()
            and gallery_config['publication_version'] == 7 and gallery_config['verification_sha256'] == PARENT_PINS['verification.json'],
            'Publication 7 must remain the active gallery until successful independent sealing')
    request_config = read_json(PROJECT/'configs/active_mask_template_requests.json')
    require((PROJECT/request_config['directory']).resolve() == REQUESTS.resolve(), 'Frozen 24-item manual worklist is no longer active')
    publications = check_frozen_inputs()
    old, parent_manifest = publications[7]['proposals'], publications[7]['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'] == 8 and manifest['method'] == 'original', 'Expected publication 8 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,
            'Expected 100-per-class cap, without forced fill or implicit human counting')
    require((PROJECT/manifest['parent']).resolve() == PARENT.resolve()
            and manifest['parent_manifest_sha256'] == PARENT_PINS['manifest.json']
            and manifest['parent_proposals_sha256'] == PARENT_PINS['proposals.jsonl']
            and manifest['parent_verification_sha256'] == PARENT_PINS['verification.json'], 'Frozen publication-7 parent binding differs')
    generator_sha = digest(PROJECT/GENERATOR)
    require(manifest['code_sha256'] == generator_sha == GENERATOR_SHA,
            'Reviewed, pinned continuation 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 == GENERATOR, f'Unexpected frozen code dependency: {name}')
        require(expected == (generator_sha if name == GENERATOR else ORIGINAL_CODE[name]) == digest(PROJECT/name),
                f'Frozen code hash differs: {name}')
    check_archives(out, manifest, generator_sha, publications)
    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 in ('proposals', 'new_proposals', 'manual_proposals', 'manual_source_records', 'all_manual_sources',
            'inherited_manual_source_audit', 'requests', 'refined_annotations', 'manual_reuse_inventory',
            'accepted_candidates', 'registration_attempts', 'outcomes', 'template_inventory'):
        extension = '.json' if name == 'template_inventory' else '.jsonl'
        require(digest(out/(name+extension)) == manifest[name+'_sha256'], f'Manifest artifact hash differs: {name}')
    combined, manual, new, accepted = (indexed(read_jsonl(out/n)) for n in
        ('proposals.jsonl', 'manual_proposals.jsonl', 'new_proposals.jsonl', 'accepted_candidates.jsonl'))
    old_manual = {k: p for k, p in old.items() if p.get('schema') == 'saved_pose_mask_gallery_entry_v1'}
    all_manual = {**old_manual, **manual}
    requests = indexed(read_jsonl(REQUESTS/'requests.jsonl'))
    require(set(requests) <= set(manual) and len(old_manual) == 87, 'All 24 requested and all 87 inherited manual sources are required')
    require(read_jsonl(out/'requests.jsonl') == read_jsonl(REQUESTS/'requests.jsonl'), 'Copied frozen request worklist differs')
    previous.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'Published asset inventory differs: {folder}')
    require(manifest['previous_proposals'] == 378 and manifest['manual_added'] == manifest['manual_proposals'] == len(manual)
            and manifest['inherited_manual_sources'] == 87 and manifest['all_manual_sources'] == len(all_manual)
            and manifest['base_proposals'] == 378+len(manual) and manifest['manual_requested'] == 24
            and manifest['manual_existing_reused'] == len(manual)-24 and manifest['new_proposals'] == len(new)
            and manifest['proposals'] == len(combined) and manifest['accepted_before_diversity'] == len(accepted),
            'Manifest historical/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 binding 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']) == 203 and len(gallery['events']) == 213
            and len(pose['current']) >= 4778 and len(pose['events']) >= 10731, 'Snapshots predate saved 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) == 203, 'All 203 counted gallery humans must be active actual >4-vertex sources')
    parent_machine = indexed(read_jsonl(PARENT/'new_proposals.jsonl'))
    reviewed = set(parent_machine) & set(gallery_templates)
    missing = set(parent_machine)-set(gallery_templates)
    require(len(parent_machine) == 84 and len(reviewed) == 39 and len(missing) == 45,
            'Parent new-machine review coverage must honestly remain 39/84 saved, 45 missing')
    review_status = dict(parent_new_machine_candidates=84, actually_saved=39, pending=45,
        saved_keys=sorted(reviewed), pending_keys=sorted(missing), user_completion_claim_used_as_evidence=False,
        unsaved_candidates_are_seeds=False)
    require(read_json(out/'saved_review_status.json') == manifest['saved_review_status'] == review_status,
            'Saved review status falsely claims unsaved candidates as human work/seeds')
    direct, templates = independent_seed_union(pose, gallery_templates, rows, pose_sha, old, old_manual)
    manual_direct = independent_human_sources(pose, rows, allow_four=True)
    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 sources/status differ from pinned original annotation_inventory')
    require(FOUR_VERTEX_KEY in manual_direct and FOUR_VERTEX_KEY not in direct and FOUR_VERTEX_KEY not in templates
            and len(manual_direct[FOUR_VERTEX_KEY]['polygon']) == 4
            and manual_direct[FOUR_VERTEX_KEY]['revision'] == manual_direct[FOUR_VERTEX_KEY]['human_polygon_revision'] == 6
            and manual_direct[FOUR_VERTEX_KEY]['human_event_sha256'] == FOUR_VERTEX_RAW_SHA,
            'Actual revision-6 four-vertex human request must be preserved, not invented or used as a seed')
    require(manifest['manual_four_point_sources'] == 1 and manifest['deferred_manual_template_keys'] == [FOUR_VERTEX_KEY],
            'Manual four-vertex source policy inventory differs')
    require(not missing & set(templates), 'Unsaved parent machine candidate used as a seed')
    all_records = indexed(read_jsonl(out/'all_manual_sources.jsonl'))
    require(set(all_records) == set(all_manual), 'Current-source inventory omits inherited or added manual sources')
    inherited_records, changed_manual = check_inherited_manual(out, old_manual, snapshots['pose'], pose, direct, pose_sha, all_records)
    require(manifest['inherited_manual_source_revisions_changed'] == changed_manual, 'Manifest inherited source changes differ')
    requested_manual = {k: manual[k] for k in requests}
    reuse_keys, reuse_inventory = independent_reuse(pose, direct, rows, old, requested_manual)
    require(set(manual) == set(requests) | reuse_keys, 'Manual additions do not match independently recovered requests/reuse')
    require(indexed(read_jsonl(out/'manual_reuse_inventory.jsonl')) == reuse_inventory
            and manifest['manual_reuse_excluded'] == [v for _, v in sorted(reuse_inventory.items()) if v['reason'] != 'counted'],
            'Explicit human reuse eligibility/quota inventory differs')
    require(manifest['manual_reuse_keys'] == sorted(reuse_keys) and manifest['requested_manual_keys'] == sorted(requests),
            'Manifest requested/reused manual partitions differ')
    old_pose = prior.read_store(prior.find_snapshots(PARENT, parent_manifest)['pose'], 'pose', frozen=True)
    seed_only = sorted(set(direct)-set(independent_human_sources(old_pose, rows))-set(manual))
    require(manifest['unexpected_new_pose_seed_only'] == seed_only, 'New pose seeds silently counted or omitted')
    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, manual_direct, rows[key], pose_sha, formal_sha, classification_sha)
        require(urlsplit(proposal['original_pose_url']).netloc in allowed_origins,
                f'Manual original 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'Request original image differs: {key}')
    records = indexed(read_jsonl(out/'manual_source_records.jsonl'))
    require(set(records) == set(manual) and all(all_records[k] == r for k, r in records.items()), 'Added manual exact-source partition differs')
    check_new_manual_records(records, manual, snapshots['pose'], pose_sha)
    require(records[FOUR_VERTEX_KEY]['current_payload_raw_sha256'] == records[FOUR_VERTEX_KEY]['human_event_sha256'] == FOUR_VERTEX_RAW_SHA,
            'Known actual four-vertex current/human-event raw payload hashes differ')
    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 outcomes 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, _ = expected_counts(old, old_manual, manual, {}, gallery)
    request_classes, request_counts = expected_counts(old, old_manual, requested_manual, {}, gallery)
    require({c: v['distinct_frames'] for c, v in request_counts.items()} == {'1': 68, '2': 100, '9': 85, '10': 64, '15': 85}
            and sum(c['saved_human'] for c in request_classes.values()) == 314
            and sum(c['prior_machine_pending'] for c in request_classes.values()) == 88,
            'Requested-only base must be 402 frames: 314 saved humans, 88 pending machines')
    require(manifest['base_classes'] == base_classes, 'Independent human-inclusive quota-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'])
            and inventory['saved_review_status'] == review_status, 'Inventory class/snapshot/source counters differ')
    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'] == {str(c): n for c, n in Counter(p['class_id'] for p in manual.values()).items()}, 'Machine/manual class counters differ')
    require(not any(p['class_id'] == 2 for p in new.values()), 'Full Class 2 quota cannot receive a new machine draft')
    for obj in (manifest, inventory):
        require(obj['counted_manual_source_keys'] == sorted(all_manual)
                and obj['previous_proposals'] == 378 and obj['manual_proposals'] == len(manual)
                and obj['inherited_manual_sources'] == 87 and obj['all_manual_sources'] == len(all_manual)
                and obj['manual_requested'] == 24 and obj['manual_existing_reused'] == len(reuse_keys), 'Explicit human source inventory differs')
    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, 'Machine/attempt totals differ')
    protection = read_json(out/'protected_targets.json')
    expected_protection = dict(previous=sorted(old), gallery_saved_or_history=sorted(gallery['history_keys']),
        pose_mask_history_or_noneligible=sorted(k for k, v in status.items() if v != 'eligible'), quarantine=[QUARANTINE], eligibility=status,
        counted_manual_source_keys=sorted(all_manual), newly_counted_manual_source_keys=sorted(manual),
        manual_reuse_keys=sorted(reuse_keys), requested_manual_keys=sorted(requests), deferred_manual_template_keys=[FOUR_VERTEX_KEY])
    require(protection == expected_protection, 'Protected target/history inventory differs')
    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} snapshot changed during audit')
    prior.find_snapshots(out, manifest)  # Recheck immutable backups as well.
    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, publications)
    require(digest(PROJECT/GENERATOR) == 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(independent_human_sources(live['pose'], rows) == direct
            and independent_human_sources(live['pose'], rows, allow_four=True) == manual_direct,
            'Latest human pose source inventory changed during audit')
    require(prior.pose_status(live['pose'], rows) == status, 'Target eligibility changed during audit; regenerate full scan')
    require(all(live[kind]['current'] == frozen[kind]['current'] and live[kind]['events'] == frozen[kind]['events']
        for kind in frozen), 'Live target payloads/events changed since generation; regenerate full scan')
    require(manifest['source_current_stable'] is True and read_json(out/'source_stability_check.json') ==
        dict(state='stable', seeds_current=True, current_payloads_and_events_unchanged=True, production_database_writes=0),
        'Generation current-source stability evidence differs')
    previous.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=8, 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=len(manual), all_manual_sources_verified=len(all_manual), manual_added=len(manual),
        manual_requested_verified=24, manual_existing_reused_verified=len(reuse_keys), inherited_manual_verified=87,
        old_canonical_objects_preserved=378, requested_only_base_distinct_frames=402, base_distinct_frames=378+len(manual),
        saved_human_sources_verified=sum(c['saved_human'] for c in classes.values()), prior_machine_pending=88,
        parent_new_machine_reviewed=39, parent_new_machine_total=84, parent_new_machine_missing=45,
        four_vertex_manual_sources_verified=[FOUR_VERTEX_KEY], four_vertex_sources_used_as_seeds=0,
        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,
        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, generator_code_sha256=generator_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 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_continue_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-8 quota-100 continuation 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=8, 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()
