"""Independent publication-13 audit; run once generation is complete, never poll.

The round-3 generator is not imported or called. Frozen historical readers and
the original registration/beam algorithms are reused only after code hash checks.
Only validation_report.json and an exclusive successful verification.json may be
written. Saved original rectangles without a scoped inspection statement remain
pending evidence, not coverage, edited masks, or propagation seeds.
"""
from __future__ import annotations

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

import cv2
import numpy as np

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

helpers = sources.helpers
require, sha = helpers.require, helpers.sha
read_json, read_jsonl, indexed = helpers.read_json, helpers.read_jsonl, helpers.indexed
file_inventory = sources.file_inventory
claim, no_confirmation = matching.claim, matching.no_confirmation
CLASSES = tuple(range(1, 23))
REMAINING = (3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22)
OLD_CLASSES = (1, 2, 9, 10, 15)
COMPLETED = (1, 2, 3, 6, 9, 10, 13, 15)
LIMIT, PUBLICATION = 100, 13
NAMESPACE = 'remaining_round3_generation'
POSE_ORIGIN, GALLERY_ORIGIN = history.POSE_ORIGIN, history.GALLERY_ORIGIN
ORIGINAL_REVIEWS = dict(previous.ORIGINAL_REVIEWS)
PENDING_RECTANGLES = {'966203cd4e5ebd979e98ab2a': (4, 13), '0cb41390d16d3bcee50315e5': (7, 1)}
USER_STATEMENT = '已经完成185张候选复核和54张新图的标注。新图的人工任务应当在标注后再提供，继续'
PARENT = PROJECT/'outputs/pallet_mask_remaining_round2_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_remaining_round2_requests_v1'
OUTPUT = PROJECT/'outputs/pallet_mask_remaining_round3_v1'
POSE, GALLERY = sources.POSE, sources.GALLERY
GENERATOR = 'pallet/mask_remaining_round3.py'
REPORT, SEAL = 'validation_report.json', 'verification.json'
ASSETS, ACCEPTED_REASONS = matching.ASSETS, matching.ACCEPTED_REASONS
PARENT_PINS = {
    'manifest.json': 'c76c845420a35b69ed860e8efed3d15b9dc3083629013c3a5dd5ab6b3b2d747e',
    'verification.json': '724cd94da93f9c3ff5a103ca8becf014a9b90857b4f8efda0b3cce318c820a65',
    'validation_report.json': '4a5e2dbbc75905cd1fd56b3ef925a2c437df7585cbdfc906c25e10cf1cf999e5',
    'proposals.jsonl': 'e3f1fdf32f6672238481d2cf69e08ae1cf0c12fd3f817851e33131367649f26e',
    'new_proposals.jsonl': '8e23bdbb5e641b510399ddee5366b3445966e80bff0f7b5f33777a527d83f395',
    'artifact_hashes.json': 'e92c1f3f8aeec83b3ad61132f4d86aa23b655ea59a2d25c3b91eb207997cead0',
    'all_manual_sources.jsonl': '2ff51607050be6a9f759e03cd79c1ccb320a0a1aa54d7bd8211bae05faf74586',
    'reviewed_original_rectangle_source_records.jsonl': 'e0370bfb8ccd384e14078433d3920ee2e17aa054d39e012cf72905c0c4d2867f',
    'review_completion_statement.json': '5173db46a432eb9a5708781b150ac7dea957b3202f0088369d223017a475bf68',
    'pallet_mask_refined_review.zip': '14a5d9f8a2ef85b096969349526d9d391ec911f3e6c88bd4bffc2419b4c3a3ae',
}
REQUEST_PINS = {
    'manifest.json': 'addbe5516f031a0ea2f792d286be94cbbfa3cda54c2856ea6c3a2d002f0b1e15',
    'verification.json': '1b804a2d8f8f662243050a6d563e7e0799de31410b268176cb5486999e16786d',
    'independent_verification.json': '1b804a2d8f8f662243050a6d563e7e0799de31410b268176cb5486999e16786d',
    'requests.jsonl': '0b10ba72c4cd6b02b9776c7bf5f9d3343a331a24be06d8139d05854006274a4a',
}
BASE_COUNTS = {**dict.fromkeys(COMPLETED, 100), 4: 35, 5: 42, 7: 34, 8: 75,
    11: 14, 12: 46, 14: 51, 16: 31, 17: 40, 18: 50, 19: 33, 20: 43, 21: 56, 22: 99}
template_binding = history.template_binding


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


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


def check_inputs():
    for root, pins in ((PARENT, PARENT_PINS), (REQUESTS, REQUEST_PINS)):
        for name, expected in pins.items():
            require(digest(root/name) == expected, 'Pinned immutable input changed: '+str(root/name))
    manifest, seal = read_json(PARENT/'manifest.json'), read_json(PARENT/SEAL)
    require(seal['state'] == 'passed' and seal['publication_version'] == manifest['publication_version'] == 12
        and seal['proposals_verified'] == manifest['proposals'] == 1401 and seal['new_verified'] == 51,
        'Need actual independently sealed publication12 1401/51')
    for field, name in (('manifest_sha256', 'manifest.json'), ('proposals_sha256', 'proposals.jsonl'),
            ('artifact_hashes_sha256', 'artifact_hashes.json'), ('validation_report_sha256', REPORT)):
        claim(seal, field, digest(PARENT/name))
    require(read_json(PARENT/REPORT) == {k: v for k, v in seal.items() if k != 'validation_report_sha256'},
        'Parent independent report/seal differs')
    require(seal['verification_script_sha256'] == digest(previous.__file__), 'Frozen publication12 verifier changed')
    for field in ('all_new_registrations_and_metrics_recomputed', 'all_rejected_attempts_and_metrics_recomputed',
            'manual_exact_sqlite_payloads_and_human_events_verified', 'live_dependencies_unchanged'):
        claim(seal, field, True)
    helpers.check_artifacts(PARENT, read_json(PARENT/'artifact_hashes.json'))
    request_seal = read_json(REQUESTS/'independent_verification.json')
    require(request_seal['state'] == 'passed' and request_seal['request_count'] == 50
        and request_seal['manifest_sha256'] == digest(REQUESTS/'manifest.json')
        and request_seal['requests_sha256'] == digest(REQUESTS/'requests.jsonl')
        and request_seal['parent_verification_sha256'] == PARENT_PINS[SEAL], 'Exact50 independent request binding differs')
    helpers.check_artifacts(REQUESTS, read_json(REQUESTS/'artifact_hashes.json'))
    helpers.check_artifacts(REQUESTS, read_json(REQUESTS/'manifest.json')['public_assets'])
    old, old_new, requests = (indexed(read_jsonl(path)) for path in
        (PARENT/'proposals.jsonl', PARENT/'new_proposals.jsonl', REQUESTS/'requests.jsonl'))
    require(len(old) == 1401 and len(old_new) == 51 and all(old[k] == v for k, v in old_new.items()),
        'Parent actual1401/51 canonical partitions differ')
    require(len(requests) == 50 and Counter(r['class_id'] for r in requests.values()) == dict.fromkeys((4, 5, 7, 14, 22), 10)
        and set(PENDING_RECTANGLES) <= set(requests), 'All and only sealed50 tasks required')
    prior = previous.check_inputs()
    publications = dict(prior['publications'])
    publications[12] = dict(path=PARENT, proposals=old, manifest=manifest)
    return dict(old=old, old_new=old_new, requests=requests, parent_manifest=manifest, publications=publications,
        inputs={**prior['inputs'], PARENT: file_inventory(PARENT), REQUESTS: file_inventory(REQUESTS)})


def check_partition(old, requests, manual, new, combined, accepted):
    require(len(old) == 1401 and len(requests) == 50 and len(manual) == 48
        and set(manual) == set(requests)-set(PENDING_RECTANGLES), 'Expected immutable1401 plus exact48, not pending2')
    require(not (set(old) & set(manual) or set(new) & (set(old) | set(manual))), 'Human/history/machine partitions overlap')
    require(set(combined) == set(old) | set(manual) | set(new), 'Cumulative inventory differs from1401+48+N')
    require(set(accepted).isdisjoint(set(old) | set(manual) | set(PENDING_RECTANGLES)) and set(new) <= set(accepted),
        'Invalid accepted-machine partition')
    require(not set(PENDING_RECTANGLES) & set(combined), 'Saved original rectangles without scoped inspection cannot count')
    for inventory in (old, manual, new):
        require(all(combined[k] == p for k, p in inventory.items()), 'Canonical cumulative proposal changed')
    require(all(accepted[k] == p for k, p in new.items()), 'Selected object differs from accepted object')
    require(all(p['class_id'] in REMAINING and p['class_id'] not in COMPLETED for p in accepted.values()),
        'Machine generation entered a completed class')
    require({k for k, p in old.items() if p.get('schema') == previous.REVIEW_SCHEMA} == set(ORIGINAL_REVIEWS)
        and not any(p.get('schema') == previous.REVIEW_SCHEMA for p in manual.values()),
        'Only five inherited original rectangles have historical scoped inspection authority')
    require(Counter(p['class_id'] for p in list(old.values())+list(manual.values())) == BASE_COUNTS,
        'Exact locked1449 per-class baseline differs')
    result = matching.count_frames(combined)
    require(all(result[str(c)]['proposals'] == LIMIT for c in COMPLETED), 'Completed class lost or overfilled')
    reserved = {requests[k]['source']['frame_id'] for k in PENDING_RECTANGLES}
    require(len(reserved) == 2 and not reserved & {p['source']['frame_id'] for p in combined.values()},
        'Pending two frames are reserved, not additional quota slots')
    return result


def check_preservation(out, old):
    current, historic = matching.raw_lines(out/'proposals.jsonl'), matching.raw_lines(PARENT/'proposals.jsonl')
    require(all(current[k] == historic[k] for k in old), 'Parent1401 canonical JSONL bytes changed')
    names = {f'{folder}/{key}.{ext}' for key in old for folder, ext in ASSETS}
    for directory in PARENT.iterdir():
        if directory.is_dir() and (directory.name in ('templates', 'refined', 'generation') or directory.name.endswith('_generation')):
            names.update(str(p.relative_to(PARENT)) for p in directory.rglob('*') if p.is_file())
    for name in names:
        require((out/name).is_file() and not (out/name).is_symlink() and digest(out/name) == digest(PARENT/name),
            'Historical asset/namespace changed: '+name)
    require(file_inventory(out/'parent_evidence') == file_inventory(PARENT), 'Complete frozen private parent archive differs')
    for name in ('review_dispositions.jsonl', 'reviewed_original_rectangle_source_records.jsonl'):
        require((out/name).read_bytes() == (PARENT/name).read_bytes(), 'Historical45/five original-review bytes changed: '+name)
    # These old private files need not exist at root: preserve their real chain.
    for name in ('review_disposition_statement.json', 'disposition_scope_source.jsonl'):
        history.preserved_private(out, name, digest(sources.BASELINE/name))
    for name in ('review_completion_statement.json', 'review_statement_bindings.json'):
        require((out/'parent_evidence'/name).read_bytes() == (PARENT/name).read_bytes(), 'Historical scoped authority changed: '+name)


def check_store_delta(parent_snapshots, snapshots, parent_stores, stores, requests, old_new):
    result = {}
    for kind, table, authorized, events, records in (
            ('pose', 'annotations', set(requests), 228, 30), ('gallery', 'reviews', set(old_new), 62, 51)):
        before, after = parent_stores[kind], stores[kind]
        helpers.preserve_events(before, after)
        require(after['events'][:len(before['events'])] == before['events'], 'Historical raw event prefix changed')
        added = after['events'][len(before['events']):]
        require(len(added) == events and {e[1] for e in added} == authorized, 'Exact current-batch event scope differs: '+kind)
        oldraw, newraw = previous.raw_rows(parent_snapshots[kind], table), previous.raw_rows(snapshots[kind], table)
        require(set(oldraw) <= set(newraw) and len(newraw)-len(oldraw) == records, 'Current record delta differs: '+kind)
        changed = {k for k in set(oldraw) | set(newraw) if oldraw.get(k) != newraw.get(k)}
        require(changed == authorized, 'Current raw bytes changed outside exact saved task/review set')
        for key in authorized:
            revision, raw, (_, event_revision, event_raw) = history.raw_current(snapshots[kind], table, key)
            require(raw == event_raw and revision == event_revision
                and (key not in oldraw or revision > oldraw[key]['revision']), 'Source is not its exact latest new save: '+key)
        result[kind] = dict(historical_events_preserved=len(before['events']), new_events=len(added),
            current_changed_keys=sorted(changed), unrelated_source_changes=0)
    return result


def saved_rectangle_source(key, pose, row, snapshot):
    """Read pending saved-current evidence, deliberately not review/seed authority."""
    require(key in PENDING_RECTANGLES and key in pose['current'], 'Pending original rectangle outside exact two')
    cls, expected_revision = PENDING_RECTANGLES[key]
    binding = sha(json.loads(pose['metadata']['binding']))
    history_rows = []
    for event_id, target, revision, raw in pose['events']:
        if target != key:
            continue
        value = json.loads(raw)
        sources.same_identity(value.get('source'), row, 'Pending original rectangle history')
        require(value.get('target_key') == key and value.get('revision') == revision and value.get('binding') == binding,
            'Pending source historical relational/formal binding differs')
        history_rows.append((event_id, revision, raw))
    revision, raw, (event_id, event_revision, event_raw) = history.raw_current(snapshot, 'annotations', key)
    value = pose['current'][key]
    require(row['final_class_id'] == cls and revision == expected_revision and json.loads(raw) == value
        and history_rows and history_rows[-1] == (event_id, revision, raw) and event_revision == revision and raw == event_raw
        and value.get('state') == 'draft' and value.get('binding') == binding and not sources.machine_marked(value)
        and value.get('event_kind') not in sources.AUTO and sources.original_rectangle(value.get('polygon'), row),
        'Pending original rectangle is not its exact latest real saved current/event')
    no_confirmation(value, key)
    polygon_value(value['polygon'], *row['size'])
    return dict(target_key=key, source=row, current_revision=revision, current_payload_raw=raw, current_payload=value,
        current_payload_sha256=sha(value), current_payload_raw_sha256=raw_sha(raw),
        saved_event_id=event_id, saved_event_revision=revision, saved_event_payload_raw=event_raw,
        saved_event_payload=json.loads(event_raw), saved_event_raw_sha256=raw_sha(event_raw),
        history_event_ids=[i for i, _, _ in history_rows], polygon_sha256=sha(value['polygon']))


def check_pending_records(records, actual, pose_sha):
    require(set(records) == set(actual) == set(PENDING_RECTANGLES), 'Exactly two separately pending original rectangles required')
    for key, source in actual.items():
        record = records[key]
        for field, expected in source.items():
            claim(record, field, expected)
        for field, expected in dict(snapshot_sha256=pose_sha, human_edited=False, propagation_seed_eligible=False,
                counts_toward_published_coverage=False).items():
            claim(record, field, expected)
        claim(record, 'user_reviewed_no_change', False, required=False)
        require(not any(f in record for f in ('user_statement_sha256', 'human_polygon_revision', 'human_event_id',
            'human_event_sha256', 'template', 'human_source')), 'Pending evidence invents inspection/edit/seed authority')
        no_confirmation(record, key)


def check_manual(proposal, request, row, recovered, pose_sha, formal_sha, class_sha):
    key = proposal['target_key']
    require(key in recovered and key not in PENDING_RECTANGLES and recovered[key]['vertex_count'] == 4,
        'New manual source must be an actual changed quad, never a saved original rectangle')
    source = recovered[key]
    require(source['human_polygon_revision'] == source['current_revision'], 'New task must use actual latest direct human revision')
    require(proposal['source'] == row and request['class_id'] == proposal['class_id'] == row['final_class_id'], 'Manual class/source differs')
    sources.same_identity(request['source'], row, 'Completed request')
    require(request['source'].get('viewpoint_candidate') == row.get('viewpoint_candidate'), 'Manual request view differs')
    require(proposal['polygon'] == source['polygon'] and proposal['vertex_count'] == 4
        and proposal['manual_four_point_source'] is True and proposal['propagation_seed_eligible'] is False,
        'Manual source changes inherited quad topology or authorizes propagation')
    require(proposal['schema'] == 'saved_pose_mask_gallery_entry_v1' and proposal['origin'] == POSE_ORIGIN
        and proposal['human_edited'] is True and proposal['status'] == 'human_edited_draft_pending_confirmation', 'Manual provenance differs')
    no_confirmation(proposal, key)
    for field in ('pose_store_written', 'gallery_store_written', 'machine_transfer_performed', 'new_human_edit_created'):
        claim(proposal, field, False)
    require('template' not in proposal and proposal['human_source'] == template_binding(matching.pose_template(source, pose_sha)),
        'Manual quad must bind actual human raw event, not become a template')
    require(proposal['snapshot_sha256'] == pose_sha and proposal['target_expected_revision'] == source['current_revision']
        and proposal['target_snapshot_payload_sha256'] == source['current_payload_sha256']
        and proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == class_sha,
        'Manual current/formal binding differs')
    require(proposal['manual_request_sha256'] == sha(request) and proposal['original_pose_url'] == request['pose_annotation_url']
        and proposal['metrics'] == {} and 'continuation' not in proposal, 'Manual invents request/transfer')
    require(proposal['rendering_id'] == NAMESPACE+':manual_source:'+key, 'Manual rendering namespace differs')


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


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


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


def protection(rows, pose, gallery, base, quarantine):
    keys, frames, _ = sources.protection(rows, pose, gallery, base, {}, quarantine)
    require(set(PENDING_RECTANGLES) <= set(rows), 'Pending source outside formal inventory')
    keys.update(PENDING_RECTANGLES)
    frames.update(rows[k]['frame_id'] for k in PENDING_RECTANGLES)
    return keys, frames


def check_machine(proposal, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha):
    history.check_machine(proposal, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha)
    require(proposal['class_id'] not in COMPLETED and proposal['human_edited'] is False
        and proposal['template'] == template_binding(templates[proposal['template']['target_key']]),
        'Machine is not bound to actual latest saved human source')
    require(proposal['rendering_id'] == NAMESPACE+':'+proposal['template']['target_key'], 'Machine rendering namespace differs')


def check_instruction(out, requests, old_new):
    instruction = read_json(out/'current_user_instruction.json')
    for field, expected in dict(schema='continuation_user_instruction_v1', statement_zh=USER_STATEMENT,
            mentioned_candidate_count=185, mentioned_manual_count=54,
            mentioned_batches_already_accounted_in_parent_publication=12,
            actual_parent_new_candidate_count=51, actual_current_request_count=50,
            observed_current_request_keys=sorted(requests), observed_parent_candidate_keys=sorted(old_new),
            future_new_manual_tasks_require_assistant_preannotation=True,
            current_original_rectangle_no_change_authorized=False,
            historical_original_rectangle_statement_bindings_unchanged=True,
            creates_human_event=False, confirms_ground_truth=False, authorizes_propagation=False).items():
        claim(instruction, field, expected)
    for name in ('review_completion_statement.json', 'new_review_completion_statement.json'):
        require((out/name).read_bytes() == (PARENT/name).read_bytes(), 'Old185/54 inspection statement rebound to new50')
    old_bindings = read_json(PARENT/'review_statement_bindings.json')
    groups = []
    for group in old_bindings.values():
        path = PARENT/group['path']
        statement = read_json(path)
        require(sha(statement) == group['statement_sha256'], 'Historical statement hash differs')
        groups.append(dict(path='parent_evidence/'+group['path'], file_sha256=digest(path),
            statement_sha256=sha(statement), target_keys=sorted(group['target_keys'])))
    expected = dict(historical_groups=groups, no_current_original_rectangle_review_statement_created=True,
        pending_original_rectangle_keys=sorted(PENDING_RECTANGLES), current_instruction_path='current_user_instruction.json')
    require(read_json(out/'review_statement_bindings.json') == expected, 'Historical/current statement authority differs')
    return groups


def check_original_records(out, pose, rows, snapshot, groups):
    records = indexed(read_jsonl(out/'reviewed_original_rectangle_source_records.jsonl'))
    require(set(records) == set(ORIGINAL_REVIEWS), 'Exactly five inherited review-only sources required')
    sources_now = {}
    for key, record in records.items():
        source = previous.original_review_source(key, pose, rows[key], snapshot)
        for field in ('current_revision', 'current_payload_raw', 'current_payload', 'current_payload_sha256',
                'current_payload_raw_sha256', 'saved_review_event_id', 'saved_review_revision',
                'saved_review_event_sha256', 'saved_review_event_payload_raw', 'saved_review_event_payload', 'history_event_ids'):
            require(record[field] == source[field], 'Inherited original-review raw/latest evidence changed: '+key)
        group = next(g for g in groups if key in g['target_keys'])
        require(record['user_statement_sha256'] == group['statement_sha256']
            and record['human_edited'] is False and record['propagation_seed_eligible'] is False,
            'Old original review lost its scoped statement/nonseed binding')
        require(key not in PENDING_RECTANGLES, 'Pending rectangle acquired historical inspection authority')
        sources_now[key] = dict(source, user_statement_sha256=group['statement_sha256'], original_statement_path=group['path'])
    return sources_now


def check_pose_history(out, pose, rows):
    binding = sha(json.loads(pose['metadata']['binding']))
    histories = defaultdict(list)
    for event_id, key, revision, raw in pose['events']:
        value = json.loads(raw)
        require(key in rows, 'Unknown pose historical source')
        sources.same_identity(value.get('source'), rows[key], 'Pose historical source')
        require(value.get('binding') == binding and value['target_key'] == key and value['revision'] == revision,
            'Pose historical formal/relational binding differs')
        histories[key].append((event_id, revision, raw, value))
    expected = {}
    for key, value in pose['current'].items():
        require(key in rows and value.get('binding') == binding, 'Pose current formal binding differs')
        sources.same_identity(value.get('source'), rows[key], 'Pose current source')
        events = histories[key]
        changed = any(v.get('polygon') and not sources.original_rectangle(v['polygon'], rows[key]) for _, _, _, v in events)
        expected[key] = dict(target_key=key, current_revision=value['revision'], history_events=len(events),
            current_state=value.get('state'), historical_modified_polygon=changed,
            deleted_history=any(v.get('state') == 'deleted' for _, _, _, v in events),
            deferred_history=any(v.get('state') == 'deferred' for _, _, _, v in events),
            confirmed_history=any(v.get('state') == 'confirmed' or any(v.get(f, False) is not False
                for f in sources.FALSE_FLAGS) for _, _, _, v in events),
            returned_to_original_rectangle=bool(changed and sources.original_rectangle(value.get('polygon'), rows[key])),
            current_payload_sha256=sha(value), formal_source_identity_validated=True)
    require(indexed(read_jsonl(out/'pose_history_audit.jsonl')) == expected, 'Full pose current/history risk audit differs')


def check_human_audits(out, inherited, manual, originals, pending, raw_records, pose_sha, templates):
    audits = indexed(read_jsonl(out/'human_source_audit.jsonl'))
    require(set(audits) == set(raw_records) | set(originals) | set(pending), 'All482 modified/five old/two pending audits required')
    for key, item in audits.items():
        source = raw_records.get(key) or originals.get(key) or pending[key]
        row = source.get('source') or source['row']
        expected = dict(target_key=key, class_id=row['final_class_id'], current_revision=source['current_revision'],
            current_payload_sha256=source['current_payload_sha256'], current_payload_raw_sha256=source['current_payload_raw_sha256'],
            exact_current_and_event_validated=True, modified_human_contour=key in raw_records,
            vertex_count=len(source['current_payload']['polygon']), historical_canonical_preserved=key in inherited or key in originals,
            current_template_selected=key in templates, snapshot_sha256=pose_sha)
        if key in originals:
            expected.update(original_rectangle_review_only=True, original_statement_path=source['original_statement_path'],
                original_statement_sha256=source['user_statement_sha256'])
        else:
            expected['pending_original_rectangle'] = key in pending
        require(item == expected, 'Modified versus old-reviewed versus pending source audit differs: '+key)


def check_gallery(out, gallery, pose, rows, old, publications, formal_sha, gallery_sha, snapshot):
    templates = history.independent_gallery(gallery, pose, rows, old, publications, formal_sha, gallery_sha)
    records = history.check_gallery_records(out, snapshot, gallery, gallery_sha)
    expected = []
    for event_id, key, revision, raw in gallery['events']:
        value = json.loads(raw)
        expected.append(dict(target_key=key, event_id=event_id, revision=revision, payload_raw_sha256=raw_sha(raw),
            proposal_publication=value['proposal_publication'], source_binding=value['source_binding'],
            base_proposal_id=value['base_proposal_id'], historical_binding_validated=True))
    require(read_jsonl(out/'gallery_event_binding_audit.jsonl') == expected, 'All952 historical gallery event-binding audits differ')
    require(set(templates) == set(records) == set(gallery['current']) and len(templates) == 875,
        'Every real gallery current/latest source required')
    for key, template in templates.items():
        source, value = records[key], gallery['current'][key]
        same = value['polygon'] == old[key]['polygon']
        template.update(saved_human_review=True, new_human_edit_created=False, saved_review_unchanged=same,
            polygon_modified_from_proposal=not same, current_gallery_payload_raw_sha256=source['current_payload_raw_sha256'],
            saved_review_event_id=source['human_event_id'], saved_review_event_raw_sha256=source['human_event_sha256'])
    return templates, records


def check_saved_reviews(out, old_new, gallery, records, gallery_sha, manifest):
    audits = indexed(read_jsonl(out/'saved_review_source_audit.jsonl'))
    require(set(audits) == set(old_new), 'All actual parent51 require real saved-review evidence')
    unchanged = []
    for key, p in old_new.items():
        value, raw = gallery['current'][key], records[key]
        same = value['polygon'] == p['polygon']
        expected = dict(target_key=key, class_id=p['class_id'], actual_saved=True, polygon_changed_from_proposal=not same,
            saved_review_unchanged=same, human_new_edit_claim=False, new_human_edit_created=False,
            proposal_sha256=sha(p), proposal_polygon_sha256=sha(p['polygon']), current_revision=value['revision'],
            current_polygon_sha256=sha(value['polygon']), current_payload_sha256=sha(value),
            current_payload_raw_sha256=raw['current_payload_raw_sha256'], human_event_id=raw['human_event_id'],
            human_event_sha256=raw['human_event_sha256'], gallery_snapshot_sha256=gallery_sha,
            source_binding=value['source_binding'], proposal_publication=value['proposal_publication'],
            binding=value['binding'], base_proposal_id=value['base_proposal_id'])
        require(audits[key] == expected, 'Actual saved51 current/raw/event/changed status differs: '+key)
        if same:
            unchanged.append(key)
    expected = dict(parent_new_machine_candidates=51, actually_saved=51, pending=0,
        polygon_changed_from_proposal=51-len(unchanged), saved_unchanged=len(unchanged), saved_keys=sorted(old_new),
        pending_keys=[], unchanged_keys=sorted(unchanged),
        saved_evidence_authority='real frozen current/raw latest events with historical publication/image/source bindings',
        unchanged_save_is_real_review_not_new_human_modification=True, new_dispositions_created=0,
        new_human_edits_created=0, unsaved_candidates_are_seeds=False)
    require(read_json(out/'saved_review_status.json') == manifest['saved_review_status'] == expected
        and len(unchanged) == 15, 'Actual36 changed/15 saved unchanged cannot become51 new modifications')
    return set(unchanged)


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


def scan_inventory(rows, pose, gallery, base, quarantine, outcomes):
    reasons, pose_protected, locked = matching.scan_reasons(rows, pose, gallery, base, quarantine)
    protected_keys, protected_frames = protection(rows, pose, gallery, base, quarantine)
    reserved = {rows[k]['frame_id'] for k in PENDING_RECTANGLES}
    excluded = set()
    for key, row in rows.items():
        reason = reasons[key]
        if reason == 'eligible' and row['final_class_id'] in COMPLETED:
            reason = 'locked_class_quota_full'
        elif reason == 'eligible' and row['frame_id'] in reserved:
            reason = 'pending_original_rectangle_frame_reserved'
        if reason != 'eligible':
            require(outcomes[key]['reason'] == reason and outcomes[key]['registration_attempts'] == 0,
                'Protected/reserved/completed scan disposition differs: '+key)
            excluded.add(key)
        elif row['frame_id'] in protected_frames:
            require(outcomes[key]['reason'] == 'no_compatible_template' and outcomes[key]['registration_attempts'] == 0,
                'History-protected sibling must remain untouched no-template diagnostic: '+key)
    return excluded, protected_keys, protected_frames, locked | reserved, pose_protected


def check_report(out, combined, new, counts):
    from fontTools.ttLib import TTFont
    page = (out/'report_zh.html').read_text()
    parsed = baseline.ReportControls(); parsed.feed(page)
    cards = indexed(parsed.articles, 'id')
    require(set(cards) == {'target-'+k for k in combined}, 'Report canonical card inventory differs')
    options = parsed.options.get('filter', [])
    require(options and options[0].get('value') == '' and not any('selected' in o for o in options[1:])
        and [o['_text'].strip() for o in options[1:]] == [str(c) for c in CLASSES], 'Report requires all22 and ALL default')
    only = parsed.inputs.get('only-new', {})
    require(only.get('type') == 'checkbox' and 'disabled' not in only and ('checked' in only) is bool(new), 'Only-new default differs')
    for key, p in combined.items():
        card = cards['target-'+key]
        require(card['data-class'] == str(p['class_id']) and card['data-batch'] == ('new' if key in new else 'previous')
            and ('hidden' in card) is (bool(new) and key not in new), 'Report class/batch/default visibility differs')
        require('display:none' not in card.get('style', '').replace(' ', '').lower(), 'Report card unconditionally hidden')
        if key in ORIGINAL_REVIEWS:
            require('原框' in parsed.card_text['target-'+key] and '不是人工改绘' in parsed.card_text['target-'+key],
                'Historical original review presented as modified human contour')
    script = ("const cls=document.querySelector('#filter'),only=document.querySelector('#only-new');"
        "function filter(){document.querySelectorAll('article').forEach(a=>a.hidden="
        "(!!cls.value&&a.dataset.class!==cls.value)||(only.checked&&a.dataset.batch!=='new'));}"
        "cls.onchange=only.onchange=filter;filter();")
    require(re.sub(r'\s+', '', ''.join(parsed.scripts)) == re.sub(r'\s+', '', script), 'Report filter behavior differs')
    fields = ('old_total', 'manual_modified_added', 'original_rectangle_review_only', 'saved_human', 'new_candidates', 'total', 'missing')
    require(parsed.cells == [str(v) for c in CLASSES for v in (c, *(counts[str(c)][f] for f in fields))], 'Report all22 exact counts differ')
    require(USER_STATEMENT in page and all(text in page for text in ('48份', '另2份', '不计覆盖', '36份', '15份',
        '1357', '1362', '650', '1449', '20768', '12344', '旧45', '42份', '不作传播模板', '不确认为GT')),
        'Report omits pending/source/unchanged/nontruth distinctions')
    require(not any(text in page for text in ('current_payload_raw', 'saved_event_payload_raw', '.sqlite3', 'fetch(')),
        'Private raw source or database/network route exposed in report')
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(out/'report-font.otf') as font:
        require(required <= set(font.getBestCmap()), 'Chinese report font coverage incomplete')
    coverage = read_json(out/'font_coverage.json')
    require(coverage['all_report_Chinese_present'] is True and coverage['chinese_glyphs'] == len(required)
        and coverage['font_sha256'] == digest(out/'report-font.otf'), 'Report font evidence differs')
    require((out/'FONT_LICENSE.txt').is_file(), 'Missing font license')


def audit(out, pose_live=POSE, gallery_live=GALLERY):
    out = Path(out)
    verifier_before = digest(__file__)
    data = check_inputs()
    manifest, artifacts = read_json(out/'manifest.json'), read_json(out/'artifact_hashes.json')
    check_claims(manifest)
    before = file_inventory(out)
    require({k: v for k, v in before.items() if k not in (REPORT, SEAL, 'artifact_hashes.json')} == artifacts,
        'Every builder artifact must be hashed, with no extra task/draft outputs')
    for field, expected in manifest.items():
        if field.endswith('_sha256') and isinstance(expected, str):
            for extension in ('.json', '.jsonl'):
                name = field[:-7]+extension
                if name in before:
                    require(before[name] == expected, 'Manifest actual artifact binding differs: '+name)
    config = sources.check_configuration(out, manifest)
    pose_config, gallery_config, request_config = (read_json(PROJECT/'configs'/n) for n in
        ('active_pose_review.json', 'active_mask_gallery.json', 'active_mask_template_requests.json'))
    require(Path(pose_live).resolve() == (PROJECT/pose_config['database']).resolve()
        and Path(gallery_live).resolve() == (PROJECT/gallery_config['review_directory']/'mask_reviews.sqlite3').resolve(),
        'Live guards must use configured production read-only stores')
    require((PROJECT/gallery_config['directory']).resolve() == PARENT.resolve() and gallery_config['publication_version'] == 12,
        'Publication12 must remain active until publication13 independently passes')
    require((PROJECT/request_config['directory']).resolve() == REQUESTS.resolve(), 'Exact50 tasks must remain active during audit')
    code, parent_code = manifest['frozen_code_sha256'], data['parent_manifest']['frozen_code_sha256']
    require(set(parent_code) | {GENERATOR} <= set(code) and all(code[n] == h for n, h in parent_code.items()),
        'Frozen dependencies omitted/changed')
    for name, expected in code.items():
        path = (PROJECT/name).resolve()
        require(path.is_relative_to(PROJECT) and digest(path) == expected, 'Frozen code changed: '+name)
    require(manifest['code_sha256'] == code[GENERATOR], 'Generator code provenance differs')
    for field, name in (('parent_manifest_sha256', 'manifest.json'), ('parent_proposals_sha256', 'proposals.jsonl'),
            ('parent_verification_sha256', SEAL)):
        claim(manifest, field, digest(PARENT/name))
    formal = (PROJECT/read_json(PROJECT/'configs/active_formal_dataset.json')['dataset']).resolve()
    formal_sha, class_sha = digest(formal/'manifest.json'), digest(sources.CLASSIFICATION)
    require(manifest['formal_manifest_sha256'] == formal_sha == data['parent_manifest']['formal_manifest_sha256']
        and manifest['classification_sha256'] == class_sha == data['parent_manifest']['classification_sha256'], 'Formal/class binding differs')
    rows, source_rows = helpers.formal_rows(formal, sources.CLASSIFICATION)
    require(len(rows) == 12344 and {r['final_class_id'] for r in rows.values()} == set(CLASSES), 'Fixed12344/22-class inventory differs')
    protected = read_json(out/'protected_formal_before.json')
    require(len(protected) == 20768 and protected == read_json(PARENT/'protected_formal_before.json')
        == read_json(out/'protected_formal_after.json') == protected_snapshot(formal), 'Protected20768 formal files changed')
    snapshots = helpers.find_snapshots(out, manifest)
    stores = {kind: helpers.read_store(path, kind, frozen=True) for kind, path in snapshots.items()}
    pose, gallery = stores['pose'], stores['gallery']
    binding = json.loads(pose['metadata']['binding'])
    require(binding['formal_manifest_sha256'] == formal_sha == gallery['metadata']['formal_manifest_sha256']
        and binding['formal_annotations_sha256'] == digest(formal/'annotations/frames.jsonl')
        and binding['formal_frames_sha256'] == digest(formal/'frames.jsonl'), 'Full review dataset metadata binding differs')
    parent_snapshots = helpers.find_snapshots(PARENT, data['parent_manifest'])
    parent_stores = {kind: helpers.read_store(path, kind, frozen=True) for kind, path in parent_snapshots.items()}
    delta = check_store_delta(parent_snapshots, snapshots, parent_stores, stores, data['requests'], data['old_new'])
    require(read_json(out/'source_delta_audit.json') == delta, 'Declared exact-batch source delta differs')
    spec = read_json(out/'snapshot_manifest.json')
    for kind, store in stores.items():
        for field, expected in dict(path=snapshots[kind].name, backup='backups/'+snapshots[kind].name,
                sha256=digest(snapshots[kind]), saved=len(store['current']), events=len(store['events']), metadata=store['metadata']).items():
            claim(spec[kind], field, expected)
        prefix = 'snapshot' if kind == 'pose' else 'gallery_snapshot'
        claim(manifest, prefix+'_saved', len(store['current']))
        claim(manifest, prefix+'_events', len(store['events']))
        for path in (snapshots[kind], out/'backups'/snapshots[kind].name):
            require(path.stat().st_mode & 0o077 == 0 and digest(path) == digest(snapshots[kind]), 'Raw snapshot/backup differs or publicly readable')
    require((len(pose['current']), len(pose['events']), len(gallery['current']), len(gallery['events'])) == (4946, 11926, 875, 952),
        'Actual pose4946/11926 and gallery875/952 inventory differs')
    fingerprints = history.check_live(stores, snapshots, pose_live, gallery_live)
    combined, manual, new, accepted = (indexed(read_jsonl(out/(name+'.jsonl'))) for name in
        ('proposals', 'manual_proposals', 'new_proposals', 'accepted_candidates'))
    frame_counts = check_partition(data['old'], data['requests'], manual, new, combined, accepted)
    require(all(p['source'] == rows[k] and p['class_id'] == rows[k]['final_class_id'] for k, p in combined.items()),
        'Canonical proposal formal source/class identity differs')
    check_preservation(out, data['old'])
    require((out/'requests.jsonl').read_bytes() == (REQUESTS/'requests.jsonl').read_bytes(), 'Current50 raw requests changed')
    groups = check_instruction(out, data['requests'], data['old_new'])
    quarantine = set(sources.QUARANTINE) | set(data['parent_manifest'].get('preserved_quarantined_targets', []))
    require(set(manifest['preserved_quarantined_targets']) == quarantine and not quarantine & set(combined), 'Quarantine changed/resurrected')
    check_pose_history(out, pose, rows)
    recovered = {k: v for k, v in sources.recover_pose_sources(pose, rows, quarantine).items() if k not in gallery['history_keys']}
    inherited = indexed(read_jsonl(PARENT/'all_manual_sources.jsonl'))
    all_pose = {**inherited, **manual}
    require(len(inherited) == 434 and len(all_pose) == 482 and set(all_pose) <= set(recovered)
        and not (set(all_pose) & set(PENDING_RECTANGLES)), 'All434 inherited plus48 changed sources required')
    require(Counter((p['class_id'], p['vertex_count']) for p in manual.values()) == {(4, 4): 9, (5, 4): 10,
        (7, 4): 9, (14, 4): 10, (22, 4): 10}, 'Actual48 modified quad topology distribution differs')
    pose_sha, gallery_sha = digest(snapshots['pose']), digest(snapshots['gallery'])
    raw_records = indexed(read_jsonl(out/'all_manual_sources.jsonl'))
    sources.check_source_records(raw_records, {k: dict(polygon=recovered[k]['polygon']) for k in all_pose}, recovered, snapshots['pose'])
    manual_records = indexed(read_jsonl(out/'manual_source_records.jsonl'))
    sources.check_source_records(manual_records, manual, recovered, snapshots['pose'])
    for key in inherited:
        for field in ('current_payload_raw', 'current_payload_raw_sha256', 'human_event_payload_raw', 'human_event_sha256'):
            require(raw_records[key][field] == inherited[key][field], 'Inherited pose raw source/event prefix changed: '+key)
    require(all(all(raw_records[k].get(f) == v for f, v in r.items()) for k, r in manual_records.items()), 'New48/all482 raw evidence conflicts')
    for key, p in manual.items():
        check_manual(p, data['requests'][key], rows[key], recovered, pose_sha, formal_sha, class_sha)
        require(p['target_expected_revision'] > data['requests'][key]['existing_pose_revision'], 'Current task lacks new saved revision')
    pending = {k: saved_rectangle_source(k, pose, rows[k], snapshots['pose']) for k in PENDING_RECTANGLES}
    pending_records = indexed(read_jsonl(out/'pending_original_rectangle_saves.jsonl'))
    check_pending_records(pending_records, pending, pose_sha)
    for key, record in pending_records.items():
        for field, expected in dict(schema='pending_original_rectangle_save_v1', source_identity_sha256=sha(rows[key]),
                manual_request_sha256=sha(data['requests'][key]), pending_excluded_from_coverage=True,
                pending_specific_original_rectangle_review=True, source_frame_reserved=True,
                classification_is_candidate_not_truth=True).items():
            claim(record, field, expected)
        require(record['current_revision'] > data['requests'][key]['existing_pose_revision'], 'Pending source lacks new real save')
    originals = check_original_records(out, pose, rows, snapshots['pose'], groups)
    gallery_sources, gallery_records = check_gallery(out, gallery, pose, rows, data['old'], data['publications'], formal_sha,
        gallery_sha, snapshots['gallery'])
    unchanged = check_saved_reviews(out, data['old_new'], gallery, gallery_records, gallery_sha, manifest)
    require(Counter(len(gallery['current'][k]['polygon']) for k in data['old_new']) == {8: 46, 10: 3, 12: 2}, 'Saved51 actual topology differs')
    parent_seeds = read_json(PARENT/'template_inventory.json')['generation_template_keys']
    templates = independent_seeds(all_pose, recovered, gallery_sources, parent_seeds, data['old_new'], pose_sha)
    require(len(templates) == 650 and Counter(t['origin'] for t in templates.values()) == {POSE_ORIGIN: 45, GALLERY_ORIGIN: 605},
        'Expected45 pose +605 remaining gallery, excluding old-five270')
    check_human_audits(out, inherited, manual, originals, pending, raw_records, pose_sha, templates)
    remaining_records = indexed(read_jsonl(out/'remaining_current_manual_source_records.jsonl'))
    require(remaining_records == {k: raw_records[k] for k in all_pose if rows[k]['final_class_id'] in REMAINING}, 'Remaining pose records differ')
    for name in ('all_manual_sources.jsonl', 'manual_source_records.jsonl', 'remaining_current_manual_source_records.jsonl',
            'gallery_source_records.jsonl', 'pending_original_rectangle_saves.jsonl', 'reviewed_original_rectangle_source_records.jsonl', 'requests.jsonl'):
        require((out/name).stat().st_mode & 0o077 == 0, 'Raw source/request payloads must remain private: '+name)
    require(indexed(read_jsonl(out/'refined_annotations.jsonl')) == gallery['current'], 'Latest saved gallery annotations differ')
    require((out/'completed_request_manual_proposals.jsonl').read_bytes() == (out/'manual_proposals.jsonl').read_bytes(), 'Completed48 sidecar differs')
    dispositions = indexed(read_jsonl(out/'review_dispositions.jsonl'))
    require(len(dispositions) == 45 and not set(dispositions) & (set(all_pose) | set(gallery_sources) | set(originals)), 'Old45 is not saved edit evidence')
    require(len(set(data['old'])-set(all_pose)-set(gallery_sources)-set(dispositions)-set(originals)) == 42, 'Old42 cannot become inferred reviewed')
    counts = history.source_counts(data['old'], manual, new, all_pose, gallery_sources, dispositions, originals)
    require(sum(v['saved_human'] for v in counts.values()) == 1357
        and sum(v['original_rectangle_review_only'] for v in counts.values()) == 5, 'Saved1357 contours and five old reviews must stay separate')
    inventory = read_json(out/'template_inventory.json')
    check_rendering(out, inventory, templates, manual, new)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    require(set(outcomes) == set(rows), 'All12344 explicit outcomes required')
    base = {**data['old'], **manual}
    excluded, protected_keys, protected_frames, scan_frames, pose_protected = scan_inventory(rows, pose, gallery, base, quarantine, outcomes)
    for p in accepted.values():
        check_machine(p, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha)
    attempts = read_jsonl(out/'registration_attempts.jsonl')
    evidence = ImageEvidence(formal, rows, source_rows)
    eligible = audit_attempts(attempts, rows, templates, accepted, outcomes, evidence, excluded, scan_frames)
    attempt_counts = Counter(t['target_key'] for t in attempts)
    require(all(o['registration_attempts'] == attempt_counts[k] for k, o in outcomes.items()), 'Outcome attempt totals differ')
    _, order = matching.check_diversity(base, accepted, new, outcomes)
    claim(manifest, 'scarcity_order', order)
    potential = {k: dict(target_key=k, class_id=rows[k]['final_class_id'], source=rows[k], metrics={}) for k in eligible}
    capacity_selected, _, capacity_order = matching.diverse_matching(base, potential)
    require(len(capacity_selected) == matching.residual_maximum_size(base, potential), 'Residual capacity is not maximum')
    maximum_counts = Counter(p['class_id'] for p in list(base.values())+list(capacity_selected.values()))
    safe_potential = {k: p for k, p in potential.items() if rows[k]['frame_id'] not in protected_frames}
    safe_capacity, _, _ = matching.diverse_matching(base, safe_potential)
    require(len(safe_capacity) == matching.residual_maximum_size(base, safe_potential), 'Whole-frame-safe capacity is not maximum')
    safe_counts = Counter(p['class_id'] for p in list(base.values())+list(safe_capacity.values()))
    require(maximum_counts == safe_counts, 'Capacity requires history-protected or reserved frames')
    claim(manifest, 'capacity_matching_order', capacity_order)
    claim(manifest, 'capacity_matching_total', sum(maximum_counts.values()))
    claim(manifest, 'class19_additional_new_distinct_images_required_at_least', LIMIT-maximum_counts[19])
    require(frame_counts['19']['proposals'] <= maximum_counts[19] <= LIMIT, 'Dynamic class19 original-frame capacity concealed')
    protected_info = read_json(out/'protected_targets.json')
    for field, expected in dict(locked_keys=sorted(base), locked_frames=sorted(p['source']['frame_id'] for p in base.values()),
            quarantine=sorted(quarantine), reserved_pending_original_rectangle_keys=sorted(PENDING_RECTANGLES),
            reserved_pending_original_rectangle_frames=sorted(rows[k]['frame_id'] for k in PENDING_RECTANGLES),
            pending_original_rectangles_excluded_from_coverage=True, all_current_task_keys_protected=sorted(data['requests']),
            previous_machine_task_keys_protected=sorted(data['old_new']), pose_mask_or_state_history_protected=sorted(pose_protected),
            gallery_saved_or_history=sorted(gallery['history_keys']), counted_manual_source_keys=sorted(all_pose),
            reviewed_original_rectangle_keys=sorted(ORIGINAL_REVIEWS), conversation_dispositions_not_seed_authorization=True).items():
        claim(protected_info, field, expected)
    for name, candidates, locked in (('frame_assignments', new, True), ('capacity_frame_assignments', capacity_selected, False)):
        expected = [dict(frame_id=p['source']['frame_id'], class_id=p['class_id'], target_key=k,
            locked=False, phase='accepted_candidate_maximum_matching') for k, p in candidates.items()]
        if locked:
            expected += [dict(frame_id=p['source']['frame_id'], class_id=p['class_id'], target_key=k,
                locked=True, phase='previously_counted_source') for k, p in base.items()]
        require(indexed(read_jsonl(out/(name+'.jsonl')), 'frame_id') == indexed(expected, 'frame_id'), 'Locked1449/residual assignments differ')
    require(manifest['classes'] == inventory['classes'] and set(manifest['classes']) == {str(c) for c in CLASSES}, 'All22 statistics required')
    shortfalls = read_json(out/'shortfalls.json')
    require(set(shortfalls) == {str(c) for c in REMAINING}, 'All17 remaining shortfalls required')
    for cls in CLASSES:
        declared = manifest['classes'][str(cls)]
        for field, expected in counts[str(cls)].items():
            names = ('original_rectangle_review_only', 'reviewed_original_rectangle') if field == 'original_rectangle_review_only' else (field,)
            claim(declared, names, expected, required=field in ('total', 'missing', 'saved_human', 'new_candidates'))
        expected = dict(capacity_matching_distinct_frames=maximum_counts[cls], capacity_shortfall=LIMIT-maximum_counts[cls],
            templates=sum(t['row']['final_class_id'] == cls for t in templates.values()),
            eligible=sum(rows[k]['final_class_id'] == cls for k in eligible),
            outcomes=dict(Counter(o['reason'] for o in outcomes.values() if o['class_id'] == cls)))
        for field, value in expected.items():
            claim(declared, field, value)
        if cls in REMAINING:
            for field, value in dict(missing=counts[str(cls)]['missing'], capacity=maximum_counts[cls],
                    capacity_shortfall=LIMIT-maximum_counts[cls], templates=expected['templates'], outcomes=expected['outcomes'],
                    additional_new_distinct_images_required_at_least=LIMIT-maximum_counts[cls]).items():
                claim(shortfalls[str(cls)], field, value)
    for field, expected in dict(previous_proposals=1401, manual_proposals=48, completed_request_manual_proposals=48,
            actual_saved_current_requests=50, modified_manual_proposals=48, base_proposals=1449, proposals=len(combined),
            new_proposals=len(new), new_machine_pending=len(new), generation_templates=650, accepted_before_diversity=len(accepted),
            registration_attempts=len(attempts), scanned_eligible_targets=len(eligible), all_manual_sources=482,
            inherited_manual_sources=434, modified_pose_source_records=482, db_stored_human_review=1362,
            saved_human_contour_source=1357, reviewed_original_rectangle=5, new_reviewed_original_rectangle=0,
            pending_original_rectangle=2, manual_four_point_sources=48, all_pose_four_point_sources=296,
            assistant_prelabels_created=0).items():
        claim(manifest, field, expected)
    for field in ('missing', 'saved_human', 'saved_pose_human', 'saved_gallery_human', 'pending_machine_raw',
            'old_pending_machine', 'user_reviewed_no_change', 'no_new_server_review'):
        claim(manifest, field, sum(c[field] for c in counts.values()))
    claim(manifest, 'outcomes', dict(Counter(o['reason'] for o in outcomes.values())))
    for key, p in {**manual, **new}.items():
        check_assets(out, p, rows[key], evidence, manual=key in manual)
    for folder, ext in ASSETS:
        require({p.name for p in (out/folder).iterdir()} == {k+'.'+ext for k in combined}, 'Canonical asset inventory differs')
    check_report(out, combined, new, counts)
    used = read_json(out/'used_image_hashes.json')
    require(all(used.get(n) == h for n, h in evidence.used.items()), 'Used native image evidence omitted')
    for name, expected in used.items():
        require((formal/name).resolve().is_relative_to(formal) and digest(formal/name) == expected, 'Native source image changed')
    require(protected_snapshot(formal) == protected and digest(sources.CLASSIFICATION) == class_sha
        and file_inventory(PROJECT/'configs') == config, 'Formal/classification/config changed during audit')
    for root, expected in data['inputs'].items():
        require(file_inventory(root) == expected, 'Immutable input changed during audit: '+root.name)
    for name, expected in code.items():
        require(digest(PROJECT/name) == expected, 'Frozen code changed during audit')
    require(digest(__file__) == verifier_before, 'Verifier changed during audit')
    require(file_inventory(out) == before, 'Output artifacts changed during read-only audit')
    require(history.check_live(stores, snapshots, pose_live, gallery_live) == fingerprints, 'Live source changed before sealing')
    return dict(state='passed', publication_version=PUBLICATION, method='original', proposals_verified=len(combined),
        proposals_sha256=digest(out/'proposals.jsonl'), new_verified=len(new), new_proposals_sha256=digest(out/'new_proposals.jsonl'),
        manifest_sha256=digest(out/'manifest.json'), artifact_hashes_sha256=digest(out/'artifact_hashes.json'),
        manual_verified=48, completed_requests_verified=50, modified_manual_sources_verified=48,
        original_rectangle_review_only_verified=5, new_original_rectangle_review_only_verified=0,
        pending_original_rectangles_verified=2, pending_original_rectangles_counted=0, reserved_uncounted_frames=2,
        original_rectangle_reviews_used_as_seeds=0, old_canonical_objects_preserved=1401,
        inherited_manual_sources_verified=434, all_manual_sources_verified=482, actual_saved_human=1357,
        actual_saved_pose=482, actual_saved_gallery=875, saved_database_polygons_including_original_rectangle_review_only=1362,
        parent_new_gallery_reviewed_saved=51, parent_new_gallery_actually_changed=51-len(unchanged), parent_new_gallery_saved_unchanged=len(unchanged),
        saved_unchanged_gallery_reviews_are_not_new_edits=True, historical_user_reviewed_no_change=45,
        old500_other_no_new_server_review=42, human_confirmation_inferred=False, templates_verified=650,
        pose_templates_verified=45, gallery_templates_verified=605, four_point_sources_used_as_seeds=0,
        classes=counts, distinct_frame_quotas=frame_counts, capacity_matching_distinct_frames=dict(maximum_counts),
        protected_frame_capacity_distinct_frames=dict(safe_counts), class19_additional_new_distinct_images_required_at_least=LIMIT-maximum_counts[19],
        outcomes_verified=len(outcomes), accepted_before_diversity_recomputed=len(accepted), registration_attempts_verified=len(attempts),
        all_new_registrations_and_metrics_recomputed=True, all_rejected_attempts_and_metrics_recomputed=True,
        manual_exact_sqlite_payloads_and_human_events_verified=True, all_gallery_history_bindings_verified=True,
        historical_canonical_resources_bytewise_preserved=True, historical_statement_scopes_preserved=True,
        current_batch_only_store_deltas_verified=True, live_dependencies_unchanged=True, protected_formal_files_verified=20768,
        database_logical_fingerprints=fingerprints, metric_absolute_tolerance=helpers.ATOL,
        thresholds_relaxed=False, forced_fill=False, production_database_writes=0, configuration_writes=0, service_writes=0,
        assistant_prelabels_counted=0, human_requests_created=0, automatic_training_eligible=False,
        robot_command_eligible=False, ground_truth_eligible=False, generator_code_sha256=code[GENERATOR],
        verification_script_sha256=verifier_before, verified_at=datetime.now(timezone.utc).isoformat())


def seal(out, operation=None):
    requested = Path(out).absolute()
    out = requested.resolve()
    require(requested == out and out.parent == (PROJECT/'outputs').resolve()
        and re.fullmatch(r'pallet_mask_remaining_round3_v[0-9]+', out.name) and out.is_dir()
        and out not in {PARENT.resolve(), REQUESTS.resolve()}, 'Only a new completed round3 output may be sealed')
    require((out/'manifest.json').is_file(), 'Generation is not complete: manifest.json missing')
    require(not (out/SEAL).exists() and not (out/SEAL).is_symlink(), 'Refusing to overwrite independent verification seal')
    require(not (out/REPORT).is_symlink(), 'Unsafe validation report path')
    failed_raw = None
    if (out/REPORT).exists():
        require((out/REPORT).is_file(), 'Unsafe validation report path')
        failed_raw = (out/REPORT).read_text()
        require(json.loads(failed_raw).get('state') == 'failed', 'Refusing to replace a successful validation report')
    cv2.setNumThreads(1)
    try:
        result = (operation or audit)(out)
        require(result.get('state') == 'passed', 'Audit did not pass')
    except Exception as exc:
        result = dict(state='failed', publication_version=PUBLICATION, error_type=type(exc).__name__, error=str(exc),
            verification_script_sha256=digest(__file__))
        if failed_raw is not None:
            result['previous_failed_validation_report_raw'] = failed_raw
            result['previous_failed_validation_report_sha256'] = raw_sha(failed_raw)
        (out/REPORT).write_bytes(canonical(result)+b'\n')
        raise
    result = dict(result)
    if failed_raw is not None:
        result['previous_failed_validation_report_raw'] = failed_raw
        result['previous_failed_validation_report_sha256'] = raw_sha(failed_raw)
    (out/REPORT).write_bytes(canonical(result)+b'\n')
    result['validation_report_sha256'] = digest(out/REPORT)
    with (out/SEAL).open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    return result


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


if __name__ == '__main__':
    main()
