"""Independent publication-15 audit; invoke only after the completion notification.

No new generator/source helper is imported. Original frozen registration code is
replayed for every actual attempt, including failures. Independent task proposals
and canonical publication proposals have distinct (publication, hash, key)
registries. Only a validation report and an exclusive success seal are written.
"""
from __future__ import annotations

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

sys.dont_write_bytecode = True

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_round4 as previous

history, matching, sources = previous.history, previous.matching, previous.sources
helpers, baseline = previous.helpers, previous.baseline
require, sha = helpers.require, helpers.sha
read_json, read_jsonl, indexed = helpers.read_json, helpers.read_jsonl, helpers.indexed
file_inventory, claim, no_confirmation = sources.file_inventory, matching.claim, matching.no_confirmation
CLASSES, REMAINING, COMPLETED = previous.CLASSES, previous.REMAINING, previous.COMPLETED
PUBLICATION, LIMIT, NAMESPACE = 15, 100, 'remaining_round5_generation'
POSE_ORIGIN, GALLERY_ORIGIN = previous.POSE_ORIGIN, previous.GALLERY_ORIGIN
ORIGINAL_REVIEWS, PENDING_RECTANGLES = dict(previous.ORIGINAL_REVIEWS), dict(previous.PENDING_RECTANGLES)
PARENT = PROJECT/'outputs/pallet_mask_remaining_round4_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_preannotated_requests_v2'
OLD_REQUESTS = PROJECT/'outputs/pallet_mask_preannotated_requests_v1'
OUTPUT = PROJECT/'outputs/pallet_mask_remaining_round5_v1'
POSE, GALLERY = previous.POSE, previous.GALLERY
GENERATOR = 'pallet/mask_remaining_round5.py'
REPORT, SEAL = 'validation_report.json', 'verification.json'
USER_STATEMENT = '完成复核和修正，继续'
ASSETS, ACCEPTED_REASONS = previous.ASSETS, previous.ACCEPTED_REASONS
BASE_COUNTS = {**previous.BASE_COUNTS, 4: 55, 5: 54, 7: 54, 14: 71}
PARENT_PINS = {
    'manifest.json': '1cf30d3628f69adbc573260ec66c335fd174ffdb89550b6772f8bb2d274b005a',
    'verification.json': 'a60e6c7d8f946532f36f9c84adbfc991f5a14c84ec187b4f2e13aab0339ecb5a',
    'proposals.jsonl': 'b012d4a6570b3f66ab974795b347a2dad517bba6d8fcca37a73a137184d6390d',
    'artifact_hashes.json': '05d75289e9cf38ad389f2ce752fb07f9e828e7bdf493edfc145dd31496279c97',
    'new_proposals.jsonl': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
}
REQUEST_PINS = {
    'manifest.json': '6a348bb6606ad2d02e66713924798a19348e6b6f2addfbd32919285c8a08ab33',
    'verification.json': '4730c01bc4fd16dbe0f4095336ab8edd0606aed8e021ce7c6a1bedb41f37ee65',
    'independent_verification.json': '4730c01bc4fd16dbe0f4095336ab8edd0606aed8e021ce7c6a1bedb41f37ee65',
    'proposals.jsonl': 'fb52204df2463bedc21f4b549a320af3de0676f03e42b769a1bf017c86d01673',
    'requests.jsonl': '4e0f47eaad071af61697ded55034f082224846476f3e82bc60e00d9b960ccbaa',
}
OUTPUT_PINS = {
    'manifest.json': 'eced4c61119ee63bef7f80e4ae92d76db3d28f3228daef049fa00ad5da69e487',
    'proposals.jsonl': '0d288c12e502cc3781ce782a3b1b81f58e97a80578812c6a4430833345b004b6',
    'artifact_hashes.json': 'bcba234b5404a92d501d2f6c208d6176a2648687c56cc39a6733a249a9eb4c48',
    'registration_attempts.jsonl': '88494cdd285c19a66dc6c2afa399754928227bd33cda8d74d0df8f06ba154790',
}
# A private next-batch inspection is not an issued historical task. This explicit
# exclusion is stable even if the other session stages it while this audit runs.
UPCOMING_TASKS = {'pallet_mask_preannotated_requests_v3'}


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


def check_claims(manifest):
    for field, expected in dict(publication_version=PUBLICATION, method='original', target_per_class=LIMIT,
            generation_template_namespace=NAMESPACE, original_splits_preserved=True,
            classification_is_candidate_not_truth=True).items():
        claim(manifest, field, expected)
    for field in ('production_database_writes', 'configuration_writes', 'service_writes', 'new_human_edits_created'):
        claim(manifest, field, 0)
    for field in ('research_candidates_added', 'cross_split_template_transfers', 'human_requests_created',
            'assistant_prelabels_created', 'human_events_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'] == 14
        and seal['proposals_verified'] == manifest['proposals'] == 1515 and seal['new_verified'] == 0,
        'Actual independently sealed publication14 1515/0 required')
    for field, name in (('manifest_sha256', 'manifest.json'), ('proposals_sha256', 'proposals.jsonl'),
            ('artifact_hashes_sha256', 'artifact_hashes.json'), ('validation_report_sha256', REPORT)):
        claim(seal, field, digest(PARENT/name))
    require(read_json(PARENT/REPORT) == {k: v for k, v in seal.items() if k != 'validation_report_sha256'}
        and seal['verification_script_sha256'] == digest(previous.__file__), 'Frozen parent verifier/report changed')
    helpers.check_artifacts(PARENT, read_json(PARENT/'artifact_hashes.json'))
    task_manifest, task_seal = read_json(REQUESTS/'manifest.json'), read_json(REQUESTS/SEAL)
    require(task_seal['state'] == 'passed' and task_seal['request_count'] == task_manifest['request_count'] == 35
        and task_seal['manifest_sha256'] == digest(REQUESTS/'manifest.json')
        and task_seal['parent_verification_sha256'] == digest(PARENT/SEAL), 'Independent exact35 task seal differs')
    require(task_seal['verification_script_sha256'] == digest(PROJECT/'scripts/verify_mask_preannotated_requests_v2.py'),
        'Frozen independent task verifier changed')
    for field, name in (('proposals_sha256', 'proposals.jsonl'), ('requests_sha256', 'requests.jsonl')):
        require(task_seal[field] == task_manifest[field] == digest(REQUESTS/name), 'Frozen task inventory differs')
    helpers.check_artifacts(REQUESTS, task_seal['public_assets'])
    require(task_manifest['public_assets'] == task_seal['public_assets'], 'Task public registry differs')
    for field, name in (('input_manifest_sha256', 'input_manifest.json'), ('decisions_sha256', 'internal/build_decisions.json')):
        claim(task_manifest, field, digest(REQUESTS/name))
    old, old_new, tasks, drafts = (indexed(read_jsonl(p)) for p in (PARENT/'proposals.jsonl',
        PARENT/'new_proposals.jsonl', REQUESTS/'requests.jsonl', REQUESTS/'proposals.jsonl'))
    require(len(old) == 1515 and old_new == {}, 'Parent has no new machine candidates to complete')
    require(set(tasks) == set(drafts) and len(tasks) == 35 and not set(tasks) & set(old)
        and Counter(p['class_id'] for p in drafts.values()) == {4: 10, 5: 5, 7: 10, 14: 10}, 'Exact35 task scope differs')
    prior = previous.check_inputs()
    publications = dict(prior['publications'])
    publications[14] = dict(path=PARENT, proposals=old, manifest=manifest)
    registries = [dict(path=OLD_REQUESTS, publication=13, namespace='v1', drafts=prior['drafts'], tasks=prior['requests']),
        dict(path=REQUESTS, publication=14, namespace='v2', drafts=drafts, tasks=tasks)]
    require(len(registries[0]['drafts']) == 37 and not set(registries[0]['drafts']) & set(drafts), 'Independent37/35 registries overlap')
    return dict(old=old, old_new=old_new, requests=tasks, drafts=drafts, parent_manifest=manifest,
        task_manifest=task_manifest, publications=publications, registries=registries,
        inputs={**prior['inputs'], PARENT: file_inventory(PARENT), REQUESTS: file_inventory(REQUESTS)})


def check_partition(old, requests, manual, new, combined, accepted):
    require(len(old) == 1515 and len(requests) == len(manual) == 35 and set(manual) == set(requests),
        'Need exact immutable1515 plus35 actual gallery saves')
    require(not (set(old) & set(manual) or set(new) & (set(old) | set(manual))), 'History/human/machine partitions overlap')
    require(set(combined) == set(old) | set(manual) | set(new), 'Cumulative inventory differs from1515+35+N')
    require(set(accepted).isdisjoint(set(old) | set(manual) | set(PENDING_RECTANGLES)) and set(new) <= set(accepted),
        'Task/self-source/history became a machine acceptance')
    require(not set(PENDING_RECTANGLES) & set(combined), 'Unscoped original rectangles cannot count')
    for inventory in (old, manual, new):
        require(all(combined[k] == p for k, p in inventory.items()), 'Canonical cumulative object changed')
    require(all(accepted[k] == p for k, p in new.items()), 'Selected 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(Counter(p['class_id'] for p in list(old.values())+list(manual.values())) == BASE_COUNTS,
        'Exact1550 baseline per-class counts differ')
    schema = previous.previous.previous.REVIEW_SCHEMA
    require({k for k, p in old.items() if p.get('schema') == schema} == set(ORIGINAL_REVIEWS)
        and all(p.get('schema') != schema for p in manual.values()), 'Five old review-only records changed')
    counts = matching.count_frames(combined)
    require(all(counts[str(c)]['proposals'] == LIMIT for c in COMPLETED), 'Completed class lost or overfilled')
    return counts


def check_store_delta(parent_snapshots, snapshots, parent_stores, stores, requests, old_new):
    require(not old_new and len(requests) == 35, 'No parent machine-review completion may be fabricated')
    result = {}
    for kind, table in (('pose', 'annotations'), ('gallery', 'reviews')):
        before, after = parent_stores[kind], stores[kind]
        helpers.preserve_events(before, after)
        require(after['events'][:len(before['events'])] == before['events'], 'Historical exact raw event prefix changed')
        added = after['events'][len(before['events']):]
        oldraw = previous.previous.previous.raw_rows(parent_snapshots[kind], table)
        newraw = previous.previous.previous.raw_rows(snapshots[kind], table)
        changed = {k for k in set(oldraw) | set(newraw) if oldraw.get(k) != newraw.get(k)}
        if kind == 'pose':
            require(not added and oldraw == newraw and after['metadata'] == before['metadata'], 'No new pose save was authorized')
        else:
            require(len(added) == 38 and {e[1] for e in added} == changed == set(requests)
                and set(oldraw) <= set(newraw) and len(newraw)-len(oldraw) == 35, 'Gallery delta must be exact35 new keys/38 events')
            for key in requests:
                revision, raw, (_, event_revision, event_raw) = history.raw_current(snapshots[kind], table, key)
                require(revision == event_revision and raw == event_raw and key not in oldraw, 'New source lacks exact raw latest event')
        result[kind] = dict(historical_events_preserved=len(before['events']), new_events=len(added),
            current_changed_keys=sorted(changed), unrelated_source_changes=0,
            raw_historical_prefix_bytewise_preserved=True, all_new_events_within_authorized_current_task_scope=True,
            new_event_target_keys=sorted({e[1] for e in added}), new_event_counts_by_target=dict(sorted(Counter(e[1] for e in added).items())),
            new_event_raw_records=[dict(event_id=i, target_key=k, revision=r, payload_raw_sha256=raw_sha(raw)) for i, k, r, raw in added])
    return result


def event_identity(value):
    return value.get('proposal_publication'), value.get('base_proposal_id'), value.get('target_key')


def independent_registry(registries):
    result = {}
    for group in registries:
        require(set(group['drafts']) == set(group['tasks']), 'Unpaired independent draft/task inventory')
        for key, proposal in group['drafts'].items():
            identity = group['publication'], sha(proposal), key
            require(identity not in result, 'Duplicate independent publication/hash/key binding')
            result[identity] = dict(group, proposal=proposal, task=group['tasks'][key])
    return result


def resolve_event(value, publications, registry):
    """A target key alone never determines whether the save used a task draft."""
    version, base, key = event_identity(value)
    require(type(version) is int and version in publications, 'Unknown actual gallery publication')
    independent = registry.get((version, base, key))
    if independent is not None:
        return independent['proposal'], independent['path'], independent
    pub = publications[version]
    proposal = pub['proposals'].get(key)
    require(proposal is not None and base == sha(proposal), 'Unknown canonical or independent publication/hash/key source')
    return proposal, pub['path'], None


def independent_gallery(gallery, pose, rows, old, publications, registries, formal_sha, gallery_sha):
    from pallet.mask_gallery_review import VERSION as EDITOR_VERSION
    registry = independent_registry(registries)
    histories, images = defaultdict(list), {}
    for event_id, key, revision, raw in gallery['events']:
        value = json.loads(raw)
        require(key in rows and value.get('target_key') == key and value.get('revision') == revision,
            'Gallery relational/formal identity differs')
        proposal, image_root, independent = resolve_event(value, publications, registry)
        row, version = rows[key], value['proposal_publication']
        require(proposal['source'] == row and proposal['class_id'] == row['final_class_id'], 'Gallery proposal formal identity differs')
        if independent is None:
            require(old.get(key) == proposal, 'Historical canonical source differs')
        cache = str(image_root), key
        if cache not in images:
            images[cache] = digest(image_root/'images'/f'{key}.png')
        identity = {f: row[f] for f in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
        identity.update(formal_manifest_sha256=formal_sha, image_sha256=images[cache])
        require(value.get('source') == identity and value.get('source_binding') == sha(identity)
            and value.get('proposal_polygon') == proposal['polygon']
            and value.get('binding') == sha(dict(formal=formal_sha,
                proposals=digest(publications[version]['path']/'proposals.jsonl'), editor_version=EDITOR_VERSION)),
            'Gallery source/native image/main editor binding differs')
        if independent is not None:
            previous.validate_draft(proposal, independent['task'], row, formal_sha, images[cache], pose['current'].get(key))
            for _, pose_key, _, pose_raw in pose['events']:
                if pose_key == key:
                    prior = json.loads(pose_raw)
                    require(sources.original_rectangle(prior.get('polygon'), row) and not sources.protected_state(prior),
                        'Returned rectangle cannot erase protected task history')
            expected = dict(assistant_draft=proposal['preannotation'], assistant_draft_not_human_edit=True,
                proposal_sha256=sha(proposal), worklist_manifest_sha256=digest(image_root/'manifest.json'))
            require(value.get('template_provenance') is None and value.get('human_source_provenance') is None
                and value.get('preannotation_provenance') == expected, 'Independent task provenance differs')
        elif proposal.get('schema') == 'saved_gallery_mask_entry_v1':
            require(value.get('template_provenance') is None and value.get('preannotation_provenance') is None
                and value.get('human_source_provenance') == proposal['human_source'], 'Canonical saved-gallery self-source differs')
        else:
            require(value.get('template_provenance') == proposal['template'], 'Historical template provenance differs')
        require(value.get('event_kind') == 'human_mask_gallery_revision' and value.get('human_edited') is True
            and value.get('pose') is None and value.get('vertex_count') == len(value.get('polygon', [])),
            'Gallery source is not a real direct-human contour save')
        no_confirmation(value, key)
        for field in ('pose_store_written', 'original_proposal_modified'):
            claim(value, field, False)
        for field in ('machine_draft', 'machine_transfer_performed', 'automatic_human_confirmation'):
            claim(value, field, False, required=False)
        polygon_value(value['polygon'], *row['size'])
        histories[key].append((event_id, revision, raw, value))
    require(set(gallery['current']) == set(histories), 'Every gallery current/history source required')
    result = {}
    for key, value in gallery['current'].items():
        events = histories[key]
        require(len({e[1] for e in events}) == len(events) and max(e[1] for e in events) == events[-1][1] == value['revision']
            and events[-1][3] == value, 'Gallery current is not unique latest actual event')
        require(value.get('state') not in ('deleted', 'deferred', 'confirmed')
            and not sources.protected_state(pose['current'].get(key, {})), 'Protected current used as a human source')
        current = pose['current'].get(key)
        result[key] = dict(row=rows[key], polygon=value['polygon'], revision=current['revision'] if current else 0,
            current_payload_sha256=sha(current) if current else None, human_polygon_revision=value['revision'],
            human_event_sha256=sha(value), human_mask_confirmed=False, origin=GALLERY_ORIGIN,
            gallery_review=dict(target_key=key, revision=value['revision'], payload_sha256=sha(value),
                source_binding=value['source_binding'], polygon_sha256=sha(value['polygon']), snapshot_sha256=gallery_sha,
                proposal_publication=value['proposal_publication'],
                publication_proposals_sha256=digest(publications[value['proposal_publication']]['path']/'proposals.jsonl')))
    return result


def check_gallery_records(out, snapshot, gallery, gallery_sha, manual_keys, registry):
    records = indexed(read_jsonl(out/'gallery_source_records.jsonl'))
    require(set(records) == set(gallery['current']), 'Every976 actual gallery current needs raw evidence')
    histories = defaultdict(list)
    for event_id, key, revision, raw in gallery['events']:
        histories[key].append((event_id, revision, raw))
    for key, value in gallery['current'].items():
        revision, raw, (event_id, _, event_raw) = history.raw_current(snapshot, 'reviews', key)
        require(json.loads(raw) == value and raw == event_raw and histories[key][-1] == (event_id, revision, raw),
            'Gallery current must equal exact UTF8 latest-event bytes')
        expected = dict(target_key=key, revision=revision, current_payload_raw=raw, current_payload_raw_sha256=raw_sha(raw),
            current_payload=value, current_payload_sha256=sha(value), human_event_id=event_id,
            human_event_payload_raw=event_raw, human_event_sha256=raw_sha(event_raw), snapshot_sha256=gallery_sha,
            history_event_ids=[e[0] for e in histories[key]],
            proposal_registry='independent_preannotation' if event_identity(value) in registry else 'canonical_publication',
            preannotation_namespace=registry[event_identity(value)]['namespace'] if event_identity(value) in registry else None)
        require(records[key] == expected, 'Exact gallery raw/current/history record differs: '+key)
    require(indexed(read_jsonl(out/'manual_source_records.jsonl')) == {k: records[k] for k in manual_keys},
        'Only new35 gallery records may be manual sources, never fabricated pose events')
    return records


def check_manual(proposal, task, draft, row, source, record, gallery_sha, formal_sha, class_sha):
    key, value = row['target_key'], record['current_payload']
    require(proposal['target_key'] == key and proposal['source'] == row and proposal['class_id'] == row['final_class_id'], 'Manual formal identity differs')
    require(proposal['schema'] == 'saved_gallery_mask_entry_v1' and proposal['origin'] == GALLERY_ORIGIN
        and proposal['status'] == 'saved_gallery_human_contour_draft_pending_confirmation'
        and proposal['human_edited'] is True and proposal['saved_gallery_manual_source'] is True, 'Manual must honestly describe a gallery save')
    require(proposal['polygon'] == source['polygon'] == value['polygon'] and proposal['vertex_count'] == len(value['polygon']) == 4
        and not sources.original_rectangle(value['polygon'], row) and proposal['manual_four_point_source'] is True
        and proposal['propagation_seed_eligible'] is False, 'Preserve actual saved quad, not original rectangle or forced seed')
    binding = previous.manual_gallery_binding(row, record, gallery_sha, digest(PARENT/'proposals.jsonl'), digest(REQUESTS/'manifest.json'))
    require('template' not in proposal and proposal['human_source'] == binding, 'Gallery source must bind its own real event, not pose/template')
    require(proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == class_sha,
        'Manual formal/class binding differs')
    require(proposal['manual_request_sha256'] == sha(task) and proposal['metrics'] == {} and 'continuation' not in proposal,
        'Manual invents request or machine registration')
    for field in ('pose_store_written', 'gallery_store_written', 'machine_transfer_performed', 'new_human_edit_created'):
        claim(proposal, field, False)
    claim(proposal, 'gallery_snapshot_sha256', gallery_sha)
    claim(proposal, 'assistant_draft_proposal_sha256', sha(draft))
    claim(proposal, 'preannotation_provenance', value['preannotation_provenance'])
    claim(proposal, 'polygon_changed_from_assistant_draft', value['polygon'] != draft['polygon'])
    require(proposal['target_expected_revision'] == draft['target_expected_revision']
        and proposal['target_snapshot_payload_sha256'] == draft['target_snapshot_payload_sha256'], 'Manual protected pose reference changed')
    require(proposal['rendering_id'] == NAMESPACE+':manual_source:'+key and record['revision'] == source['human_polygon_revision']
        and value['base_proposal_id'] == sha(draft) and value['proposal_publication'] == 14, 'Manual latest task/publication/rendering differs')
    no_confirmation(proposal, key)


def independent_seeds(pose_keys, recovered, gallery, parent_seed_keys, pose_sha, quad_keys):
    require(set(pose_keys) <= set(recovered), 'Counted pose source no longer exists')
    result = {k: matching.pose_template(recovered[k], pose_sha) for k in sorted(pose_keys)
        if recovered[k]['vertex_count'] > 4 and recovered[k]['row']['final_class_id'] in REMAINING}
    for key, source in sorted(gallery.items()):
        if key not in quad_keys and source['row']['final_class_id'] in REMAINING:
            require(key not in result and len(source['polygon']) > 4, 'Quad/duplicate gallery source entered seeds')
            result[key] = source
    require(set(result) == set(parent_seed_keys), 'Exact unchanged parent679 seed domain required')
    require(not (set(quad_keys) | set(ORIGINAL_REVIEWS) | set(PENDING_RECTANGLES)) & set(result), 'Task/original rectangle used as a seed')
    return result


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


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


def historical_task_protection(rows):
    keys, inventories = set(PENDING_RECTANGLES), {}
    for path in sorted((PROJECT/'outputs').glob('*/requests.jsonl')):
        if path.parent in (OUTPUT, PARENT) or path.parent.name in UPCOMING_TASKS:
            continue
        inventories[path] = digest(path)
        keys.update(r['target_key'] for r in read_jsonl(path))
    for root in (OLD_REQUESTS, REQUESTS):
        for name in ('build_decisions.json', 'assistant_decisions.json'):
            decisions = root/'internal'/name
            inventories[decisions] = digest(decisions)
            keys.update(read_json(decisions)['decisions'])
        for name in ('deferred_sources.json', 'shortlist.jsonl'):
            path = root/'internal'/name
            inventories[path] = digest(path)
            records = read_jsonl(path) if path.suffix == '.jsonl' else read_json(path)
            keys.update(r['target_key'] for r in records)
    require(keys <= set(rows), 'Historical task/rejection outside formal inventory')
    return keys, {rows[k]['frame_id'] for k in keys}, inventories


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), 'Parent1515 canonical JSONL bytes changed')
    names = {f'{folder}/{key}.{ext}' for key in old for folder, ext in ASSETS}
    for directory in PARENT.iterdir():
        if directory.is_dir() and (directory.name in ('templates', 'refined', 'generation') or directory.name.endswith('_generation')):
            names.update(str(p.relative_to(PARENT)) for p in directory.rglob('*') if p.is_file())
    for name in names:
        require((out/name).is_file() and not (out/name).is_symlink() and digest(out/name) == digest(PARENT/name),
            'Historical canonical asset/namespace changed: '+name)
    require(file_inventory(out/'parent_evidence') == file_inventory(PARENT), 'Complete private parent/archive chain differs')
    expected_packs = {}
    require({p.name for p in (out/'preannotation_source_evidence').iterdir()} == {'v1', 'v2'}, 'Independent task pack namespaces differ')
    for namespace, root in (('v1', OLD_REQUESTS), ('v2', REQUESTS)):
        expected_packs[namespace] = file_inventory(root)
        require(file_inventory(out/'preannotation_source_evidence'/namespace) == expected_packs[namespace], 'Complete independent task evidence differs: '+namespace)
    require(read_json(out/'preannotation_input_file_inventories.json') == expected_packs, 'Independent task input inventories differ')
    for name in ('all_manual_sources.jsonl', 'review_dispositions.jsonl', 'reviewed_original_rectangle_source_records.jsonl',
            'review_completion_statement.json', 'new_review_completion_statement.json', 'review_disposition_statement.json'):
        require((out/name).read_bytes() == (PARENT/name).read_bytes(), 'Historical raw/source/scoped authority changed: '+name)


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 quad/draft/unreviewed source')
    for key, source in templates.items():
        require(all(latest[NAMESPACE+':'+key].get(f) == v for f, v in source.items()), 'New seed latest-human provenance differs')
        exported = read_json(out/NAMESPACE/'templates'/f'{key}.json')
        require(all(exported.get(f) == v for f, v in source.items()), 'Exported seed provenance differs')
        no_confirmation(exported, key); claim(exported, 'propagation_seed_eligible', True)
    require({p.name for p in (out/NAMESPACE/'templates').iterdir()} == {k+'.json' for k in templates}, 'Seed file inventory differs')
    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, expected in dict(generation_template_namespace=NAMESPACE, generation_template_keys=sorted(templates), generation_templates=len(templates)).items():
        claim(inventory, field, expected)
    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 new35 gallery 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, 'Gallery nonseed rendering lost actual self-source')


def check_report(out, combined, new, counts):
    from fontTools.ttLib import TTFont
    page = (out/'report_zh.html').read_text()
    parsed = baseline.ReportControls(); parsed.feed(page)
    cards = indexed(parsed.articles, 'id')
    require(set(cards) == {'target-'+k for k in combined}, 'Report canonical card inventory differs')
    options = parsed.options.get('filter', [])
    require(options and options[0].get('value') == '' and not any('selected' in o for o in options[1:])
        and [o['_text'].strip() for o in options[1:]] == [str(c) for c in CLASSES], 'Report requires ALL22 default')
    only = parsed.inputs.get('only-new', {})
    require(only.get('type') == 'checkbox' and 'disabled' not in only, 'Only-new control missing/disabled')
    only_new = 'checked' in only
    require(not new or only_new, 'Nonempty machine batch must be default')
    for key, p in combined.items():
        card = cards['target-'+key]
        require(card['data-class'] == str(p['class_id']) and card['data-batch'] == ('new' if key in new else 'previous')
            and ('hidden' in card) is (only_new and key not in new), 'Report class/batch/visibility differs')
        require('display:none' not in card.get('style', '').replace(' ', '').lower(), 'Report card unconditionally hidden')
        if key in ORIGINAL_REVIEWS:
            require(not any(t in parsed.card_text['target-'+key] for t in ('新增人工改绘', '新增机器候选')), 'Old original review described as a new edit/candidate')
    script = ("const cls=document.querySelector('#filter'),only=document.querySelector('#only-new');"
        "function filter(){document.querySelectorAll('article').forEach(a=>a.hidden="
        "(!!cls.value&&a.dataset.class!==cls.value)||(only.checked&&a.dataset.batch!=='new'));}"
        "cls.onchange=only.onchange=filter;filter();")
    require(re.sub(r'\s+', '', ''.join(parsed.scripts)) == re.sub(r'\s+', '', script), 'Report filter behavior differs')
    fields = ('old_total', 'manual_modified_added', 'original_rectangle_review_only', 'saved_human', 'new_candidates', 'total', 'missing')
    require(parsed.cells == [str(v) for cls in CLASSES for v in (cls, *(counts[str(cls)][f] for f in fields))], 'Report22-class table differs')
    require(all(text in page for text in (USER_STATEMENT, '1458', '1463', '976', '482', '679', '1550', '旧两份', '旧五份', '旧45', '42', '不补造顶点', '未派发v3')),
        'Report omits actual contour/review/seed/frozen denominator distinctions')
    require(not re.search(r'(?<![A-Za-z0-9_])(?:current_payload_raw|human_event_payload_raw|saved_event_payload_raw|access_key)(?![A-Za-z0-9_])', page)
        and '.sqlite3' not in page and 'fetch(' not in page,
        'Report exposes private raw sources/database/network route')
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(out/'report-font.otf') as font:
        require(required <= set(font.getBestCmap()), 'Chinese report font 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'), 'Font coverage evidence differs')
    require((out/'FONT_LICENSE.txt').is_file(), 'Missing font license')


def check_public_payload(value):
    """Traceability hashes are public metadata; their underlying raw saves are not."""
    forbidden = {'current_payload_raw', 'human_event_payload_raw', 'saved_event_payload_raw',
        'current_payload', 'human_event_payload', 'saved_event_payload', 'human_event_raw', 'saved_event_raw', 'access_key'}
    raw_hashes = {'current_payload_raw_sha256', 'human_event_raw_sha256', 'human_event_payload_raw_sha256',
        'saved_event_raw_sha256', 'saved_event_payload_raw_sha256', 'current_gallery_payload_raw_sha256',
        'saved_review_event_raw_sha256', 'payload_raw_sha256'}
    if isinstance(value, list):
        for item in value:
            check_public_payload(item)
    elif isinstance(value, dict):
        for key, item in value.items():
            require(key not in forbidden, 'Private raw save exposed through public metadata: '+key)
            if key in raw_hashes or key.startswith(('current_payload_raw_', 'human_event_payload_raw_', 'saved_event_payload_raw_')):
                require(key in raw_hashes and isinstance(item, str) and re.fullmatch('[0-9a-f]{64}', item) is not None,
                    'Invalid public raw-event traceability hash: '+key)
            check_public_payload(item)


def check_public_exports(out):
    names = {'manifest.json', 'proposals.jsonl', 'new_proposals.jsonl', 'manual_proposals.jsonl', 'shortfalls.json', 'template_inventory.json'}
    for directory in out.iterdir():
        if directory.is_dir() and (directory.name in ('labelme', 'templates', 'refined', 'generation') or directory.name.endswith('_generation')):
            names.update(str(p.relative_to(out)) for p in directory.rglob('*.json'))
    for name in names:
        path = out/name
        values = read_jsonl(path) if path.suffix == '.jsonl' else [read_json(path)]
        for value in values:
            check_public_payload(value)
    # Public packaging follows the successful independent seal, never precedes it.
    # Parent ZIP bytes are retained and checked inside private parent_evidence.
    require(not list(out.glob('*.zip')), 'A public archive must be independently checked after the generation seal')


def check_saved_reviews(out, proposals, gallery, records, gallery_sha, manifest, prelabel=False):
    name = 'completed_preannotation_source_audit' if prelabel else 'saved_review_source_audit'
    audits = indexed(read_jsonl(out/(name+'.jsonl')))
    require(set(audits) == set(proposals), 'Every actual saved review needs exact evidence, including empty parent batch')
    unchanged = []
    for key, p in proposals.items():
        value, raw = gallery['current'][key], records[key]
        same = value['polygon'] == p['polygon']
        expected = dict(target_key=key, class_id=p['class_id'], actual_saved=True, polygon_changed_from_proposal=not same,
            saved_review_unchanged=same, human_new_edit_claim=False, new_human_edit_created=False,
            proposal_sha256=sha(p), proposal_polygon_sha256=sha(p['polygon']), current_revision=value['revision'],
            current_polygon_sha256=sha(value['polygon']), current_payload_sha256=sha(value),
            current_payload_raw_sha256=raw['current_payload_raw_sha256'], human_event_id=raw['human_event_id'],
            human_event_sha256=raw['human_event_sha256'], gallery_snapshot_sha256=gallery_sha,
            source_binding=value['source_binding'], proposal_publication=value['proposal_publication'],
            binding=value['binding'], base_proposal_id=value['base_proposal_id'])
        require(audits[key] == expected, 'Actual saved latest/raw/changed status differs: '+key)
        if same:
            unchanged.append(key)
    expected = dict(parent_new_machine_candidates=0, actually_saved=len(proposals), pending=0,
        polygon_changed_from_proposal=len(proposals)-len(unchanged), saved_unchanged=len(unchanged), saved_keys=sorted(proposals),
        pending_keys=[], unchanged_keys=sorted(unchanged),
        saved_evidence_authority='real gallery current/raw latest event pairs with every historical binding checked',
        unchanged_save_is_real_review_not_new_human_modification=True, new_human_edits_created=0)
    if prelabel:
        expected.update(completed_preannotation_tasks=35, source_kind='independent_assistant_preannotation_followed_by_real_gallery_human_save')
    name = 'completed_preannotation_status' if prelabel else 'saved_review_status'
    require(read_json(out/(name+'.json')) == manifest[name] == expected and not unchanged, 'Actual35 all-changed/empty-parent review counts differ')


def check_source_registry(out, publications, gallery, registries, formal_sha):
    from pallet.mask_gallery_review import VERSION as EDITOR_VERSION
    registry = independent_registry(registries)
    independent_count = sum(event_identity(v) in registry for v in gallery['current'].values())
    inventory = dict(schema='canonical_and_independent_prelabel_event_registry_v2', current_task_namespace='v2',
        canonical_gallery_saved=len(gallery['current'])-independent_count,
        independent_prelabel_gallery_saved=independent_count, independent_task_registry_entries=len(registry),
        registry_key_fields=['proposal_publication', 'base_proposal_id', 'target_key'], publications={}, prelabels=[])
    for version, pub in publications.items():
        proposal_sha = digest(pub['path']/'proposals.jsonl')
        inventory['publications'][str(version)] = dict(binding=sha(dict(formal=formal_sha, proposals=proposal_sha, editor_version=EDITOR_VERSION)),
            manifest_sha256=digest(pub['path']/'manifest.json'), proposals_sha256=proposal_sha, verification_sha256=digest(pub['path']/SEAL))
    for (version, base, key), reference in sorted(registry.items()):
        value = gallery['current'][key]
        inventory['prelabels'].append(dict(target_key=key, namespace=reference['namespace'], base_proposal_id=base,
            main_gallery_binding=inventory['publications'][str(version)]['binding'],
            main_gallery_proposals_sha256=digest(publications[version]['path']/'proposals.jsonl'),
            preannotation_provenance=dict(assistant_draft=reference['proposal']['preannotation'], assistant_draft_not_human_edit=True,
                proposal_sha256=base, worklist_manifest_sha256=digest(reference['path']/'manifest.json')),
            proposal_publication=version, source=value['source'], source_binding=sha(value['source']),
            task_manifest_sha256=digest(reference['path']/'manifest.json'), task_verification_sha256=digest(reference['path']/SEAL)))
    require(read_json(out/'source_inventory.json') == inventory, 'Separate independent/main publication source inventory differs')


def audit(out, pose_live=POSE, gallery_live=GALLERY):
    out = Path(out)
    verifier_before = digest(__file__)
    data = check_inputs()
    manifest, artifacts = read_json(out/'manifest.json'), read_json(out/'artifact_hashes.json')
    for name, expected in OUTPUT_PINS.items():
        require(digest(out/name) == expected, 'Completed generation handoff bytes changed: '+name)
    check_claims(manifest)
    before = file_inventory(out)
    require({k: v for k, v in before.items() if k not in (REPORT, SEAL, 'artifact_hashes.json')} == artifacts,
        'Every builder artifact must be hashed, without unreviewed future tasks')
    for field, expected in manifest.items():
        if field.endswith('_sha256') and isinstance(expected, str):
            for ext in ('.json', '.jsonl'):
                name = field[:-7]+ext
                if name in before:
                    require(before[name] == expected, 'Manifest artifact binding differs: '+name)
    config = sources.check_configuration(out, manifest)
    pose_config, gallery_config, request_config = (read_json(PROJECT/'configs'/name) for name in
        ('active_pose_review.json', 'active_mask_gallery.json', 'active_mask_template_requests.json'))
    require(Path(pose_live).resolve() == (PROJECT/pose_config['database']).resolve()
        and Path(gallery_live).resolve() == (PROJECT/gallery_config['review_directory']/'mask_reviews.sqlite3').resolve(), 'Live guards must use configured read-only stores')
    require((PROJECT/gallery_config['directory']).resolve() == PARENT.resolve() and gallery_config['publication_version'] == 14,
        'Publication14 must remain active until independent publication15 pass')
    require((PROJECT/request_config['directory']).resolve() == REQUESTS.resolve(), 'Exact35 tasks must remain active during audit')
    code, parent_code = manifest['frozen_code_sha256'], data['parent_manifest']['frozen_code_sha256']
    require(set(parent_code) | {GENERATOR} <= set(code) and all(code[n] == h for n, h in parent_code.items()), 'Frozen original engines omitted/changed')
    for name, expected in code.items():
        path = (PROJECT/name).resolve()
        require(path.is_relative_to(PROJECT) and digest(path) == expected, 'Frozen dependency changed: '+name)
    claim(manifest, 'code_sha256', code[GENERATOR])
    for field, name in (('parent_manifest_sha256', 'manifest.json'), ('parent_proposals_sha256', 'proposals.jsonl'), ('parent_verification_sha256', SEAL)):
        claim(manifest, field, digest(PARENT/name))
    formal = (PROJECT/read_json(PROJECT/'configs/active_formal_dataset.json')['dataset']).resolve()
    formal_sha, class_sha = digest(formal/'manifest.json'), digest(sources.CLASSIFICATION)
    require(manifest['formal_manifest_sha256'] == formal_sha == data['parent_manifest']['formal_manifest_sha256']
        and manifest['classification_sha256'] == class_sha == data['parent_manifest']['classification_sha256'], 'Formal/class source binding differs')
    rows, source_rows = helpers.formal_rows(formal, sources.CLASSIFICATION)
    require(len(rows) == 12344 and {r['final_class_id'] for r in rows.values()} == set(CLASSES), 'Fixed12344/22 denominator differs')
    protected = read_json(out/'protected_formal_before.json')
    require(len(protected) == 20768 and protected == read_json(PARENT/'protected_formal_before.json')
        == read_json(out/'protected_formal_after.json') == protected_snapshot(formal), 'Protected20768 formal files changed')
    snapshots = helpers.find_snapshots(out, manifest)
    stores = {kind: helpers.read_store(path, kind, frozen=True) for kind, path in snapshots.items()}
    pose, gallery = stores['pose'], stores['gallery']
    require((len(pose['current']), len(pose['events']), len(gallery['current']), len(gallery['events'])) == (4946, 11926, 976, 1061),
        'Actual unchanged pose4946/11926 and gallery976/1061 required')
    binding = json.loads(pose['metadata']['binding'])
    require(binding['formal_manifest_sha256'] == formal_sha == gallery['metadata']['formal_manifest_sha256']
        and binding['formal_annotations_sha256'] == digest(formal/'annotations/frames.jsonl')
        and binding['formal_frames_sha256'] == digest(formal/'frames.jsonl'), 'Review metadata binding differs')
    parent_snapshots = helpers.find_snapshots(PARENT, data['parent_manifest'])
    parent_stores = {kind: helpers.read_store(path, kind, frozen=True) for kind, path in parent_snapshots.items()}
    delta = check_store_delta(parent_snapshots, snapshots, parent_stores, stores, data['requests'], data['old_new'])
    require(read_json(out/'source_delta_audit.json') == delta, 'Declared exact35/38 store delta differs')
    spec = read_json(out/'snapshot_manifest.json')
    for kind, store in stores.items():
        for field, expected in dict(path=snapshots[kind].name, backup='backups/'+snapshots[kind].name,
                sha256=digest(snapshots[kind]), saved=len(store['current']), events=len(store['events']), metadata=store['metadata']).items():
            claim(spec[kind], field, expected)
        for path in (snapshots[kind], out/'backups'/snapshots[kind].name):
            require(path.stat().st_mode & 0o077 == 0 and digest(path) == digest(snapshots[kind]), 'Private snapshot/backup changed')
    fingerprints = history.check_live(stores, snapshots, pose_live, gallery_live)
    combined, manual, new, accepted = (indexed(read_jsonl(out/(name+'.jsonl'))) for name in
        ('proposals', 'manual_proposals', 'new_proposals', 'accepted_candidates'))
    frame_counts = check_partition(data['old'], data['requests'], manual, new, combined, accepted)
    require(all(p['source'] == rows[k] and p['class_id'] == rows[k]['final_class_id'] for k, p in combined.items()), 'Canonical formal identity/class differs')
    check_preservation(out, data['old'])
    require((out/'requests.jsonl').read_bytes() == (REQUESTS/'requests.jsonl').read_bytes(), 'Immutable task35 JSONL bytes changed')
    quarantine = set(sources.QUARANTINE) | set(data['parent_manifest'].get('preserved_quarantined_targets', []))
    require(set(manifest['preserved_quarantined_targets']) == quarantine and not quarantine & set(combined), 'Quarantine changed/resurrected')
    previous.previous.check_pose_history(out, pose, rows)
    recovered = {k: v for k, v in sources.recover_pose_sources(pose, rows, quarantine).items() if k not in gallery['history_keys']}
    pose_records = indexed(read_jsonl(out/'all_manual_sources.jsonl'))
    inherited = indexed(read_jsonl(PARENT/'all_manual_sources.jsonl'))
    require(len(pose_records) == 482 and pose_records == inherited and not set(pose_records) & set(manual), 'Only unchanged482 POSE records permitted')
    sources.check_source_records(pose_records, {k: dict(polygon=recovered[k]['polygon']) for k in inherited}, recovered, snapshots['pose'])
    pose_sha, gallery_sha = digest(snapshots['pose']), digest(snapshots['gallery'])
    pending = {k: previous.previous.saved_rectangle_source(k, pose, rows[k], snapshots['pose']) for k in PENDING_RECTANGLES}
    previous.previous.check_pending_records(indexed(read_jsonl(out/'pending_original_rectangle_saves.jsonl')), pending, pose_sha)
    reserved = {rows[k]['frame_id'] for k in pending}
    require(len(reserved) == 2 and not reserved & {p['source']['frame_id'] for p in combined.values()}, 'Old pending frames counted')
    groups = []
    for group in read_json(PARENT/'review_statement_bindings.json')['historical_groups']:
        path = PARENT/group['path']
        require(digest(path) == group['file_sha256'] and sha(read_json(path)) == group['statement_sha256'], 'Old scoped statement changed')
        groups.append(dict(group, path='parent_evidence/'+group['path']))
    originals = previous.previous.check_original_records(out, pose, rows, snapshots['pose'], groups)
    instruction = read_json(out/'current_user_instruction.json')
    for field, expected in dict(statement_zh=USER_STATEMENT, creates_human_event=False, confirms_ground_truth=False,
            authorizes_propagation=False, current_original_rectangle_no_change_authorized=False,
            historical_original_rectangle_statement_bindings_unchanged=True, observed_current_request_keys=sorted(data['requests']),
            observed_parent_candidate_keys=[]).items():
        claim(instruction, field, expected)
    require(read_json(out/'review_statement_bindings.json') == 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'), 'Historical/current statement scopes differ')
    gallery_sources = independent_gallery(gallery, pose, rows, data['old'], data['publications'], data['registries'], formal_sha, gallery_sha)
    registry = independent_registry(data['registries'])
    quad_keys = {key for _, _, key in registry}
    require(len(quad_keys) == 72 and all(len(gallery_sources[k]['polygon']) == 4 for k in quad_keys), 'Actual old37 plus new35 gallery quads required')
    gallery_records = check_gallery_records(out, snapshots['gallery'], gallery, gallery_sha, manual, registry)
    check_saved_reviews(out, data['old_new'], gallery, gallery_records, gallery_sha, manifest)
    check_saved_reviews(out, data['drafts'], gallery, gallery_records, gallery_sha, manifest, prelabel=True)
    check_source_registry(out, data['publications'], gallery, data['registries'], formal_sha)
    expected_events = []
    for event_id, key, revision, raw in gallery['events']:
        value = json.loads(raw); independent = event_identity(value) in registry
        expected_events.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, preannotation_provenance_validated=independent,
            proposal_registry='independent_preannotation' if independent else 'canonical_publication',
            preannotation_namespace=registry[event_identity(value)]['namespace'] if independent else None))
    require(read_jsonl(out/'gallery_event_binding_audit.jsonl') == expected_events, 'All1061 event-binding audits differ')
    require(all(gallery['current'][k]['polygon'] != p['polygon'] for k, p in data['drafts'].items()), 'All35 current saves must actually differ from AI draft')
    for key, p in manual.items():
        check_manual(p, data['requests'][key], data['drafts'][key], rows[key], gallery_sources[key], gallery_records[key], gallery_sha, formal_sha, class_sha)
        claim(p, 'snapshot_sha256', pose_sha)
    for key, source in gallery_sources.items():
        if key in quad_keys:
            continue
        value, record = gallery['current'][key], gallery_records[key]
        same = value['polygon'] == data['old'][key]['polygon']
        source.update(saved_human_review=True, new_human_edit_created=False, saved_review_unchanged=same,
            polygon_modified_from_proposal=not same, current_gallery_payload_raw_sha256=record['current_payload_raw_sha256'],
            saved_review_event_id=record['human_event_id'], saved_review_event_raw_sha256=record['human_event_sha256'])
    templates = independent_seeds(inherited, recovered, gallery_sources,
        read_json(PARENT/'template_inventory.json')['generation_template_keys'], pose_sha, quad_keys)
    require(len(templates) == 679 and Counter(t['origin'] for t in templates.values()) == {POSE_ORIGIN: 45, GALLERY_ORIGIN: 634}, 'Unchanged679=45pose+634gallery seeds required')
    previous.check_pose_audits(out, pose_records, recovered, rows)
    require(indexed(read_jsonl(out/'remaining_current_manual_source_records.jsonl')) ==
        {k: r for k, r in pose_records.items() if rows[k]['final_class_id'] in REMAINING}, 'Remaining pose source 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 payload must remain private: '+name)
    dispositions = indexed(read_jsonl(out/'review_dispositions.jsonl'))
    require(len(dispositions) == 45 and not set(dispositions) & (set(inherited) | set(gallery_sources) | set(originals))
        and len(set(data['old'])-set(inherited)-set(gallery_sources)-set(originals)-set(dispositions)) == 42, 'Old45/42 unsaved acquired fake source authority')
    counts = history.source_counts(data['old'], manual, new, inherited, gallery_sources, dispositions, originals)
    require(sum(c['saved_human'] for c in counts.values()) == 1458 and sum(c['saved_pose_human'] for c in counts.values()) == 482
        and sum(c['saved_gallery_human'] for c in counts.values()) == 976, 'Real1458 contours=482pose+976gallery required')
    inventory = read_json(out/'template_inventory.json')
    check_rendering(out, inventory, templates, manual, new)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    task_keys, task_frames, task_files = historical_task_protection(rows)
    require(read_json(out/'historical_task_input_hashes.json') == {str(p.relative_to(PROJECT)): h for p, h in task_files.items()},
        'Issued historical task/rejection file inventory differs or includes unissued v3')
    base = {**data['old'], **manual}
    excluded, protected_keys, protected_frames, scan_frames, pose_protected = previous.scan_inventory(
        rows, pose, gallery, base, quarantine, outcomes, task_keys, task_frames)
    for p in accepted.values():
        history.check_machine(p, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha)
        require(p['class_id'] not in COMPLETED and p['rendering_id'] == NAMESPACE+':'+p['template']['target_key'], 'Machine completed class/rendering differs')
    attempts = read_jsonl(out/'registration_attempts.jsonl')
    evidence = ImageEvidence(formal, rows, source_rows)
    eligible = audit_attempts(attempts, rows, templates, accepted, outcomes, evidence, excluded, scan_frames)
    attempt_counts = Counter(t['target_key'] for t in attempts)
    require(all(o['registration_attempts'] == attempt_counts[k] for k, o in outcomes.items()), 'Outcome attempt totals differ')
    _, order = matching.check_diversity(base, accepted, new, outcomes)
    claim(manifest, 'scarcity_order', order)
    potential = {k: dict(target_key=k, class_id=rows[k]['final_class_id'], source=rows[k], metrics={}) for k in eligible}
    capacity_selected, _, capacity_order = matching.diverse_matching(base, potential)
    require(len(capacity_selected) == matching.residual_maximum_size(base, potential), 'Residual capacity not maximum')
    maximum_counts = Counter(p['class_id'] for p in list(base.values())+list(capacity_selected.values()))
    for field, expected in dict(capacity_matching_order=capacity_order, capacity_matching_total=sum(maximum_counts.values()),
            class19_additional_new_distinct_images_required_at_least=LIMIT-maximum_counts[19]).items():
        claim(manifest, field, expected)
    require(frame_counts['19']['proposals'] <= maximum_counts[19] <= LIMIT, 'Dynamic class19 capacity concealed')
    for field, expected in dict(previous_proposals=1515, base_proposals=1550, proposals=len(combined), new_proposals=len(new),
            new_machine_pending=len(new), generation_templates=679, accepted_before_diversity=len(accepted), registration_attempts=len(attempts),
            scanned_eligible_targets=len(eligible), all_manual_sources=482, saved_pose_human=482, saved_gallery_human=976,
            saved_human=1458, saved_human_contour_source=1458, db_stored_human_review=1463, reviewed_original_rectangle=5,
            new_reviewed_original_rectangle=0, pending_original_rectangle=2).items():
        claim(manifest, field, expected)
    require(manifest['classes'] == inventory['classes'] and set(manifest['classes']) == {str(c) for c in CLASSES}, 'All22 statistics required')
    for cls in CLASSES:
        declared = manifest['classes'][str(cls)]
        for field in ('total', 'missing', 'saved_human', 'saved_pose_human', 'saved_gallery_human', 'new_candidates', 'user_reviewed_no_change', 'no_new_server_review'):
            claim(declared, field, counts[str(cls)][field])
        for field, expected in dict(capacity_matching_distinct_frames=maximum_counts[cls], capacity_shortfall=LIMIT-maximum_counts[cls],
                templates=sum(t['row']['final_class_id'] == cls for t in templates.values()), eligible=sum(rows[k]['final_class_id'] == cls for k in eligible),
                outcomes=dict(Counter(o['reason'] for o in outcomes.values() if o['class_id'] == cls))).items():
            claim(declared, field, expected)
    shortfalls = read_json(out/'shortfalls.json')
    require(set(shortfalls) == {str(c) for c in REMAINING}, 'All17 remaining shortfalls required')
    for cls in REMAINING:
        for field, expected in dict(missing=counts[str(cls)]['missing'], capacity=maximum_counts[cls], capacity_shortfall=LIMIT-maximum_counts[cls],
                templates=sum(t['row']['final_class_id'] == cls for t in templates.values()), additional_new_distinct_images_required_at_least=LIMIT-maximum_counts[cls],
                outcomes=dict(Counter(o['reason'] for o in outcomes.values() if o['class_id'] == cls))).items():
            claim(shortfalls[str(cls)], field, expected)
    protected_info = read_json(out/'protected_targets.json')
    for field, expected in dict(locked_keys=sorted(base), locked_frames=sorted(p['source']['frame_id'] for p in base.values()),
            quarantine=sorted(quarantine), reserved_pending_original_rectangle_keys=sorted(PENDING_RECTANGLES),
            reserved_pending_original_rectangle_frames=sorted(reserved), pending_original_rectangles_excluded_from_coverage=True,
            all_current_task_keys_protected=sorted(data['requests']), previous_machine_task_keys_protected=[],
            pose_mask_or_state_history_protected=sorted(pose_protected), gallery_saved_or_history=sorted(gallery['history_keys']),
            counted_manual_source_keys=sorted(inherited), reviewed_original_rectangle_keys=sorted(ORIGINAL_REVIEWS),
            conversation_dispositions_not_seed_authorization=True, all_historical_task_keys=sorted(task_keys)).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'), 'Locked1550/residual frame assignments differ')
    for key, p in {**manual, **new}.items():
        if key in manual:
            previous.check_gallery_assets(out, p, rows[key], evidence)
            require(digest(out/'images'/f'{key}.png') == digest(REQUESTS/'images'/f'{key}.png'), 'Saved gallery native image bytes differ')
        else:
            previous.previous.check_assets(out, p, rows[key], evidence)
    for folder, ext in ASSETS:
        require({p.name for p in (out/folder).iterdir()} == {k+'.'+ext for k in combined}, 'Canonical asset inventory differs')
    require(indexed(read_jsonl(out/'refined_annotations.jsonl')) == gallery['current'], 'Latest976 gallery annotations differ')
    check_report(out, combined, new, counts)
    check_public_exports(out)
    used = read_json(out/'used_image_hashes.json')
    require(all(used.get(n) == h for n, h in evidence.used.items()), 'Native source 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/class/config changed during audit')
    for root, expected in data['inputs'].items():
        require(file_inventory(root) == expected, 'Immutable input changed during audit: '+root.name)
    for path, expected in task_files.items():
        require(digest(path) == expected, 'Historical request/rejection input changed during audit')
    for name, expected in code.items():
        require(digest(PROJECT/name) == expected, 'Frozen code changed during audit')
    require(digest(__file__) == verifier_before and file_inventory(out) == before, 'Verifier/output changed during read-only audit')
    require(history.check_live(stores, snapshots, pose_live, gallery_live) == fingerprints, 'Live sources changed before seal')
    return dict(state='passed', publication_version=PUBLICATION, method='original', proposals_verified=len(combined),
        proposals_sha256=digest(out/'proposals.jsonl'), new_verified=len(new), new_proposals_sha256=digest(out/'new_proposals.jsonl'),
        manifest_sha256=digest(out/'manifest.json'), artifact_hashes_sha256=digest(out/'artifact_hashes.json'),
        manual_verified=35, manual_gallery_saved_verified=35, manual_gallery_actually_changed=35, manual_gallery_saved_unchanged=0,
        parent_new_gallery_reviewed_saved=0, old_canonical_objects_preserved=1515, actual_saved_human=1458,
        actual_saved_pose=482, actual_saved_gallery=976, saved_database_polygons_including_original_rectangle_review_only=1463,
        original_rectangle_review_only_verified=5, pending_original_rectangles_verified=2, pending_original_rectangles_counted=0,
        reserved_uncounted_frames=2, templates_verified=679, pose_templates_verified=45, gallery_templates_verified=634,
        four_point_sources_used_as_seeds=0, historical_user_reviewed_no_change=45, old500_other_no_new_server_review=42,
        human_confirmation_inferred=False, classes=counts, distinct_frame_quotas=frame_counts, capacity_matching_distinct_frames=dict(maximum_counts),
        class19_additional_new_distinct_images_required_at_least=LIMIT-maximum_counts[19], outcomes_verified=len(outcomes),
        accepted_before_diversity_recomputed=len(accepted), registration_attempts_verified=len(attempts),
        all_new_registrations_and_metrics_recomputed=True, all_rejected_attempts_and_metrics_recomputed=True,
        manual_exact_sqlite_payloads_and_human_events_verified=True, all_gallery_history_bindings_verified=True,
        gallery_events_verified=len(gallery['events']), independent_task_registry_entries_verified=len(registry),
        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_round5_v[0-9]+', out.name) and out.is_dir()
        and out == (PROJECT/'outputs/pallet_mask_remaining_round5_v1').resolve()
        and out not in {PARENT.resolve(), REQUESTS.resolve()}, 'Only a new completed round5 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() and (out/REPORT).stat().st_nlink == 1, 'Unsafe validation report path')
        failed_raw = (out/REPORT).read_bytes().decode('utf-8')
        require(json.loads(failed_raw).get('state') == 'failed', 'Refusing to replace successful validation report')
    cv2.setNumThreads(1)
    try:
        result = (operation or audit)(out)
        require(result.get('state') == 'passed', 'Audit did not pass')
    except Exception as exc:
        result = dict(state='failed', publication_version=PUBLICATION, error_type=type(exc).__name__, error=str(exc), verification_script_sha256=digest(__file__))
        if failed_raw is not None:
            result.update(previous_failed_validation_report_raw=failed_raw, previous_failed_validation_report_sha256=raw_sha(failed_raw))
        (out/REPORT).write_bytes(canonical(result)+b'\n')
        raise
    result = dict(result)
    if failed_raw is not None:
        result.update(previous_failed_validation_report_raw=failed_raw, previous_failed_validation_report_sha256=raw_sha(failed_raw))
    (out/REPORT).write_bytes(canonical(result)+b'\n')
    result['validation_report_sha256'] = digest(out/REPORT)
    with (out/SEAL).open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    return result


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


if __name__ == '__main__':
    main()
