"""Read-only, independent publication-10 remaining-class expansion audit.

Run only after generation finishes. The generator is never imported or invoked.
Original registration and beam algorithms are shared only after their historical
code hashes are checked. Every attempted registration, including every rejection
and accepted-but-unselected candidate, is replayed. Only validation_report.json
and an exclusively created successful verification.json may be written.
"""
from __future__ import annotations

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

import cv2
import numpy as np

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_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
# Never inherit the original engines' five-class CLASSES or their quota helpers.
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)
LIMIT, PUBLICATION = 100, 10
NAMESPACE = 'remaining_expand_generation'
PARENT = PROJECT/'outputs/pallet_mask_quota_100_complete_v1'
SOURCES = PROJECT/'outputs/pallet_mask_remaining_classes_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_remaining_requests_v2'
OUTPUT = PROJECT/'outputs/pallet_mask_remaining_expand_v1'
POSE, GALLERY = sources.POSE, sources.GALLERY
GENERATOR = 'pallet/mask_remaining_expand.py'
FALSE_FLAGS = sources.FALSE_FLAGS
REPORT, SEAL = 'validation_report.json', 'verification.json'
SOURCE_PINS = {
    'manifest.json': 'c343df29d0a5de57b9c224f41d186f8559b152ae3e55f827aeaaf9b2bd12dd8d',
    'manual_proposals.jsonl': '09d564ec89bfa92ffa3b29c64baca7c5dda0cea4dbc83fd4e8f0b1429f9618ef',
    'artifact_hashes.json': 'bf3d63e88057b02f27e7b5900002c7a7d4eaf53beff817e02db3c62279df99b8',
    'independent_verification.json': '14446bf82465d1c06dfd1f7a2048e724a87eab2e6505372c6292683a744daaa6',
}
REQUEST_PINS = {
    'manifest.json': 'b2a101ba5a60404835e08051bb49590988d8bc38c0dd2d19e03c99673f35becc',
    'requests.jsonl': '94818117ebe877035efe6a3bb7a6cd7b471d3bc020372125fd4fe2f3a9992dec',
    'independent_verification.json': '8a195dc89e28916d7fafb5f6397f2cd705d24a06111545b507a3938f9a8c4eff',
}
ASSETS = (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json'))
ACCEPTED_REASONS = {'new_proposal', 'accepted_duplicate_frame_not_selected', 'accepted_quota_full_not_selected'}


def alias(value, names, required=True):
    """Accept actual schema aliases, but never let one hide a conflicting claim."""
    found = [value[n] for n in names if n in value]
    require(found or not required, 'Missing claim: '+', '.join(names))
    if not found:
        return None
    require(all(canonical(v) == canonical(found[0]) for v in found), 'Conflicting aliases: '+', '.join(names))
    return found[0]


def claim(value, names, expected, required=True):
    if isinstance(names, str):
        names = (names,)
    actual = alias(value, names, required)
    if actual is not None or any(n in value for n in names):
        require(type(actual) is type(expected) and actual == expected, 'Incorrect claim: '+', '.join(names))


def no_confirmation(value, label):
    for flag in FALSE_FLAGS:
        require(value.get(flag, False) is False, f'{label}: unauthorized {flag}')


def check_claims(manifest):
    claim(manifest, 'publication_version', PUBLICATION)
    claim(manifest, 'method', 'original')
    claim(manifest, 'target_per_class', LIMIT)
    for field in ('production_database_writes', 'configuration_writes', 'service_writes'):
        claim(manifest, field, 0)
    for field in ('new_human_edits_created', 'research_candidates_added', 'cross_split_template_transfers'):
        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', '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)
    claim(manifest, 'original_splits_preserved', True)
    claim(manifest, 'generation_template_namespace', NAMESPACE)
    claim(manifest, 'classification_is_candidate_not_truth', True, required=False)


def check_input_seal(root, pins, count_field, count):
    for name, expected in pins.items():
        require(digest(root/name) == expected, f'Pinned immutable input changed: {root.name}/{name}')
    seal = read_json(root/'independent_verification.json')
    require(seal['state'] == 'passed' and seal[count_field] == count
        and seal['manifest_sha256'] == digest(root/'manifest.json')
        and seal['validation_report_sha256'] == digest(root/'independent_validation_report.json'),
        'Matching independent source/request seal required')
    require(read_json(root/'independent_validation_report.json') == {
        k: v for k, v in seal.items() if k != 'validation_report_sha256'}, 'Independent source/request report differs')
    artifact_path = root/'artifact_hashes.json'
    if artifact_path.exists():
        helpers.check_artifacts(root, read_json(artifact_path))
    if 'public_assets' in seal:
        helpers.check_artifacts(root, seal['public_assets'])
    require(seal['verification_script_sha256'] == digest(sources.__file__), 'Frozen independent source/request verifier changed')
    for name, expected in read_json(root/'manifest.json').get('frozen_code_sha256', {}).items():
        path = (PROJECT/name).resolve()
        require(path.is_relative_to(PROJECT) and digest(path) == expected, 'Immutable source/request engine dependency changed')
    return seal


def check_inputs():
    old, parent_files, parent_manifest = sources.check_baseline()
    check_input_seal(SOURCES, SOURCE_PINS, 'saved_sources_verified', 141)
    request_seal = check_input_seal(REQUESTS, REQUEST_PINS, 'request_count', 51)
    require(request_seal['sources_independent_verification_sha256'] == SOURCE_PINS['independent_verification.json'],
        'Requests are not bound to the independent remaining-source seal')
    manual = indexed(read_jsonl(SOURCES/'manual_proposals.jsonl'))
    requests = indexed(read_jsonl(REQUESTS/'requests.jsonl'))
    require(len(manual) == 141 and Counter(p['class_id'] for p in manual.values()) == {
        4: 3, 5: 9, 7: 2, 12: 35, 14: 18, 16: 1, 20: 6, 21: 1, 22: 66}, 'Immutable old-141 source inventory differs')
    require(len(requests) == 51 and Counter(r['class_id'] for r in requests.values()) == dict.fromkeys(REMAINING, 3),
        'All and only the independently sealed 51 requests are required')
    return dict(old=old, previous_manual=manual, requests=requests, parent_manifest=parent_manifest,
        inputs={PARENT: parent_files, SOURCES: file_inventory(SOURCES), REQUESTS: file_inventory(REQUESTS)})


def check_partition(old, previous_manual, requests, manual, new, combined, accepted):
    require(set(previous_manual).isdisjoint(requests) and set(manual) == set(previous_manual) | set(requests),
        'Manual sidecar must retain old141 and add exactly the completed51')
    require(len(manual) == 192 and len(old) == 500, 'Expected manual192 plus original500 base')
    require(not (set(old) & set(manual) or set(new) & (set(old) | set(manual))), 'Source/machine partitions overlap')
    require(set(combined) == set(old) | set(manual) | set(new), 'Cumulative inventory differs')
    require(set(accepted).isdisjoint(set(old) | set(manual)) and set(new) <= set(accepted), 'Invalid accepted-machine partition')
    for inventory in (old, manual, new):
        require(all(combined[k] == p for k, p in inventory.items()), 'Canonical cumulative proposal was changed')
    require(all(manual[k] == p for k, p in previous_manual.items()), 'Old141 canonical manual objects were changed')
    require(all(accepted[k] == p for k, p in new.items()), 'Selected candidate differs from accepted object')
    require(all(p['class_id'] in REMAINING for p in list(manual.values())+list(accepted.values())),
        'New human/transfer source uses an old completed class')
    return count_frames(combined)


def count_frames(proposals):
    values = list(proposals.values())
    require(len({p['source']['frame_id'] for p in values}) == len(values), 'Global cross-class frame reuse')
    require(all(p['class_id'] in CLASSES for p in values), 'Unknown class')
    result = {}
    for cls in CLASSES:
        items = [p for p in values if p['class_id'] == cls]
        require(len(items) <= LIMIT, f'Class {cls} exceeds quota')
        result[str(cls)] = dict(proposals=len(items), distinct_frames=len(items), shortfall=LIMIT-len(items))
    require(all(result[str(c)]['proposals'] == LIMIT for c in OLD_CLASSES), 'Original five completed quotas changed')
    return result


def raw_lines(path):
    result = {}
    for line in path.read_bytes().splitlines(keepends=True):
        require(bool(line.strip()), 'Blank canonical JSONL record')
        key = json.loads(line)['target_key']
        require(key not in result, 'Duplicate canonical JSONL target')
        result[key] = line
    return result


def check_preservation(out, old, previous_manual):
    combined_lines, manual_lines = raw_lines(out/'proposals.jsonl'), raw_lines(out/'manual_proposals.jsonl')
    for root, name, records in ((PARENT, 'proposals.jsonl', old), (SOURCES, 'manual_proposals.jsonl', previous_manual)):
        historical = raw_lines(root/name)
        for key in records:
            require(combined_lines[key] == historical[key], f'Historical canonical JSONL bytes changed: {key}')
            if root == SOURCES:
                require(manual_lines[key] == historical[key], f'Old141 manual sidecar bytes changed: {key}')
        names = {f'{folder}/{key}.{ext}' for key in records for folder, ext in ASSETS}
        namespaces = [p for p in root.iterdir() if p.is_dir() and (p.name == 'templates'
            or p.name in ('refined', 'generation') or p.name.endswith('_generation'))]
        names.update(str(p.relative_to(root)) for directory in namespaces for p in directory.rglob('*') if p.is_file())
        for name in names:
            require((out/name).is_file() and digest(out/name) == digest(root/name), f'Historical asset/namespace changed: {name}')
    require((out/'review_dispositions.jsonl').read_bytes() == (PARENT/'review_dispositions.jsonl').read_bytes(),
        'Public old45 review dispositions must remain byte-identical at root')
    for name in ('review_disposition_statement.json', 'disposition_scope_source.jsonl'):
        found = [p for p in (out/name, out/'parent_evidence'/name) if p.is_file()]
        require(found and all(not p.is_symlink() and p.read_bytes() == (PARENT/name).read_bytes() for p in found),
            f'Private historical old45 scope/statement bytes changed or missing: {name}')


def check_inherited_audits(out, historical, manual, recovered, records, pose_sha):
    """Audit the actual all335 current-source schema, not an invented v9 overlay."""
    audits = indexed(read_jsonl(out/'human_source_audit.jsonl'))
    require(set(audits) == set(records) == set(historical) | set(manual),
        'Every counted335 pose source needs its own exact current-source audit')
    for key, record in records.items():
        source, item = recovered[key], audits[key]
        proposal = historical.get(key)
        expected = dict(target_key=key, class_id=source['row']['final_class_id'],
            exact_current_direct_human_validated=True, current_revision=source['current_revision'],
            current_payload_sha256=source['current_payload_sha256'], vertex_count=source['vertex_count'],
            historical_canonical_preserved=proposal is not None,
            canonical_proposal_sha256=sha(proposal) if proposal else None,
            historical_polygon_changed=proposal['polygon'] != source['polygon'] if proposal else False,
            current_template_selected=key in manual and source['vertex_count'] > 4,
            current_snapshot_sha256=pose_sha, human_event_sha256=source['human_event_sha256'])
        require(item == expected, f'Exact current/historical human-source audit differs: {key}')
        claim(record, 'latest_human_source', template_binding(pose_template(source, pose_sha)), required=False)


def capacity_audit(rows, old, manual, protected_keys, protected_frames):
    """Population, protected capacity and completed coverage remain separate."""
    old_frames = {p['source']['frame_id'] for p in old.values()}
    result = {}
    for cls in REMAINING:
        population = {r['frame_id'] for r in rows.values() if r['final_class_id'] == cls}
        usable = {r['frame_id'] for k, r in rows.items() if r['final_class_id'] == cls
            and k not in protected_keys and r['frame_id'] not in protected_frames}
        counted = {p['source']['frame_id'] for p in manual.values() if p['class_id'] == cls}
        capacity = min(LIMIT, len(usable | counted))
        result[str(cls)] = dict(original_distinct_frames=len(population),
            baseline_disjoint_frames=len(population-old_frames), protected_aware_capacity=capacity,
            capacity_shortfall=LIMIT-capacity, saved_human=len(counted))
    return result


def pose_template(source, pose_sha):
    return dict(row=source['row'], polygon=source['polygon'], revision=source['current_revision'],
        current_payload_sha256=source['current_payload_sha256'], human_polygon_revision=source['human_polygon_revision'],
        human_event_sha256=source['human_event_sha256'], human_mask_confirmed=False, origin='original_pose_human_revision',
        pose_review=dict(target_key=source['target_key'], revision=source['current_revision'],
            payload_sha256=source['current_payload_sha256'], human_polygon_revision=source['human_polygon_revision'],
            human_event_sha256=source['human_event_sha256'], polygon_sha256=sha(source['polygon']), snapshot_sha256=pose_sha))


def template_binding(template):
    row = template['row']
    return dict(target_key=row['target_key'], class_id=row['final_class_id'], split=row['split'],
        snapshot_revision=template['revision'], current_payload_sha256=template['current_payload_sha256'],
        human_polygon_revision=template['human_polygon_revision'], human_event_sha256=template['human_event_sha256'],
        vertex_count=len(template['polygon']), template_human_confirmed=False,
        origin='original_pose_human_revision', pose_review=template['pose_review'])


def independent_seeds(manual, recovered, pose_sha):
    require(set(manual) <= set(recovered), 'Counted manual source is no longer actual current human work')
    return {k: pose_template(recovered[k], pose_sha) for k in sorted(manual)
        if len(recovered[k]['polygon']) > 4 and recovered[k]['row']['final_class_id'] in REMAINING}


def check_new_manual(proposal, request, row, recovered, pose_sha, formal_sha, class_sha):
    key = proposal['target_key']
    require(key in recovered, f'Completed request lacks genuine human source: {key}')
    source = recovered[key]
    sources.same_identity(request['source'], row, f'Completed request {key}')
    require(request['class_id'] == proposal['class_id'] == row['final_class_id'] in REMAINING
        and proposal['source'] == row and request['source'].get('viewpoint_candidate') == row.get('viewpoint_candidate'),
        'Completed request class/split/policy/view/source identity differs')
    require(proposal['polygon'] == source['polygon'] and proposal['vertex_count'] == source['vertex_count'],
        'Manual polygon is not the actual saved human contour')
    four = source['vertex_count'] == 4
    require(proposal['manual_four_point_source'] is four and proposal['propagation_seed_eligible'] is (not four),
        'Four-point coverage/seed distinction differs')
    require(proposal['schema'] == 'saved_pose_mask_gallery_entry_v1' and proposal['origin'] == 'original_pose_human_revision'
        and proposal['status'] == 'human_edited_draft_pending_confirmation' and proposal['human_edited'] is True
        and proposal['manual_source_kind'] == 'completed_manual_request', 'Manual request status/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)
    claim(proposal, 'pose_snapshot_saved', True)
    require(proposal['snapshot_sha256'] == pose_sha and proposal['formal_manifest_sha256'] == formal_sha
        and proposal['class_assignments_sha256'] == class_sha and proposal['target_expected_revision'] == source['current_revision']
        and proposal['target_snapshot_payload_sha256'] == source['current_payload_sha256'], 'Manual current-source binding differs')
    field = 'human_source' if four else 'template'
    require(field in proposal and ('template' not in proposal if four else 'human_source' not in proposal)
        and proposal[field] == template_binding(pose_template(source, pose_sha)), 'Manual raw-human-event metadata differs')
    require(proposal['rendering_id'] == NAMESPACE+(':manual_source:' if four else ':')+key
        and proposal['manual_request_sha256'] == sha(request) and proposal['original_pose_url'] == request['pose_annotation_url'],
        'Manual request/rendering provenance differs')
    require(proposal['metrics'] == {} and 'continuation' not in proposal, 'Human source invents transfer evidence')


def target_protection(rows, pose, gallery, old, manual, quarantine=()):
    """Global frame locks protect all mask/protected history, not only current state."""
    keys, frames, _ = sources.protection(rows, pose, gallery, old, {}, quarantine)
    frames.update(p['source']['frame_id'] for p in manual.values())
    return keys | set(manual), frames


def scan_reasons(rows, pose, gallery, base, quarantine):
    """Original scanning protects target history; counted692 lock whole frames.

    Rejected diagnostic attempts on an uncounted sibling box are still replayed;
    they are not a saved label or permission to replace that sibling's history.
    Accepted outputs additionally pass target_protection's conservative frame guard.
    """
    pose_keys = set()
    payloads = [(key, value) for key, value in pose['current'].items()]
    payloads.extend((key, json.loads(raw)) for _, key, _, raw in pose['events'])
    for key, value in payloads:
        polygon = value.get('polygon')
        if sources.protected_state(value) or (polygon and not sources.original_rectangle(polygon, rows[key])):
            pose_keys.add(key)
    locked_frames = {p['source']['frame_id'] for p in base.values()}
    reasons = {}
    for key, row in rows.items():
        reasons[key] = ('quarantined' if key in quarantine else 'locked_counted_source' if key in base else
            'locked_counted_frame' if row['frame_id'] in locked_frames else 'gallery_history_protected'
            if key in gallery['history_keys'] else 'pose_mask_or_state_history_protected' if key in pose_keys else
            'class_not_requested' if row['final_class_id'] not in REMAINING else 'eligible')
    return reasons, pose_keys, locked_frames


def check_machine(proposal, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha):
    key = proposal['target_key']
    require(key in rows and key not in protected_keys and rows[key]['frame_id'] not in protected_frames,
        'Machine target uses a protected key/frame')
    row = rows[key]
    require(proposal['source'] == row and proposal['class_id'] == row['final_class_id'] in REMAINING,
        'Machine original class/split/policy/view/image identity differs')
    no_confirmation(proposal, key)
    claim(proposal, 'production_saved', False)
    require(proposal['status'] == 'machine_draft_pending_visual_review' and not proposal.get('human_edited', False),
        'Machine candidate misrepresented as human work')
    require(proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == class_sha,
        'Machine formal source binding differs')
    binding = proposal['template']
    template = templates.get(binding['target_key'])
    require(template is not None and compatible(template['row'], row), 'Machine uses an incompatible or unauthorized seed')
    require(binding == template_binding(template) and proposal['vertex_count'] == len(proposal['polygon']) == len(template['polygon']) > 4,
        'Machine actual-human template binding/topology differs')
    polygon_value(proposal['polygon'], *row['size'])
    current = pose['current'].get(key)
    require(proposal['snapshot_sha256'] == pose_sha and proposal['target_expected_revision'] == (current['revision'] if current else 0)
        and proposal['target_snapshot_payload_sha256'] == (sha(current) if current else None), 'Machine target revision/hash binding differs')
    method = proposal['generation_method']
    require(method == dict(name='original', version='attempt_target_v1',
        code_sha256=digest(PROJECT/'pallet/mask_template_continue.py')), 'Machine does not use original attempt_target')
    require('explicit_adoption_only' in proposal['geometry_pose_policy'], 'Machine draft permits implicit adoption')


def replay(template, row, evidence):
    """Original gates and full beam audit, without the generation wrapper."""
    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 = None
            metrics['rejection'] = '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-target 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'] not in REMAINING:
            require(key not in bytarget and key not in accepted and outcome['reason'] not in ACCEPTED_REASONS,
                'Protected/completed-class target attempted or accepted')
            continue
        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-compatible-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 initial 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 rejected/similarity outcome')
        require([t['template_key'] for t in trials] == expected, f'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, f'Passing/rejected registration disposition differs: {key}')
            helpers.equal_metrics(trial['metrics'], metrics, key+'.attempt')
            if success:
                proposal = accepted[key]
                require(metrics['initial_ncc'] >= .55 and metrics['ecc'] >= .84 and metrics['boundary_ncc'] >= .78
                    and max(metrics['forward_backward_error_patch_pixels']) <= 1.5, 'Original exact gates failed')
                np.testing.assert_allclose(proposal['polygon'], polygon, rtol=0, atol=helpers.ATOL)
                helpers.equal_metrics(proposal['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 diverse_matching(base, candidates):
    """Independent scarce-first residual b-matching; never move a locked human.

    Representatives maximize boundary NCC, ECC, then deterministic key within a
    frame/class. Group balancing applies to the CURRENT matching, including the
    decrements when augmenting paths move a newly selected machine frame.
    """
    locked = {p['source']['frame_id'] for p in base.values()}
    require(len(locked) == len(base), 'Base repeats frames')
    require(all(p['class_id'] in REMAINING for p in candidates.values()), 'Accepted transfer in original completed class')
    counts = Counter(p['class_id'] for p in base.values())
    require(all(n <= LIMIT for n in counts.values()), 'Base exceeds quota')
    quality = lambda p: (-p.get('metrics', {}).get('boundary_ncc', 0), -p.get('metrics', {}).get('ecc', 0), p['target_key'])
    representatives = {c: {} for c in REMAINING}
    groups = {c: Counter(p['source']['group_id'] for p in base.values() if p['class_id'] == c) for c in REMAINING}
    for key, p in sorted(candidates.items()):
        cls, frame = p['class_id'], p['source']['frame_id']
        if frame in locked:
            continue
        previous = representatives[cls].get(frame)
        if previous is None or quality(p) < quality(previous):
            representatives[cls][frame] = p
    order = sorted(REMAINING, key=lambda c: (len(representatives[c])/max(1, LIMIT-counts[c]), len(representatives[c]), c))
    owner, held = {}, {c: set() for c in REMAINING}

    def place(frame, cls):
        old = owner.get(frame)
        if old is not None:
            held[old].remove(frame)
            groups[old][representatives[old][frame]['source']['group_id']] -= 1
        owner[frame] = cls
        held[cls].add(frame)
        groups[cls][representatives[cls][frame]['source']['group_id']] += 1

    def extend(cls, seen):
        if cls in seen:
            return False
        seen.add(cls)
        preferences = sorted(representatives[cls], key=lambda f: (
            groups[cls][representatives[cls][f]['source']['group_id']], quality(representatives[cls][f])))
        available = next((f for f in preferences if f not in owner), None)
        if available is not None:
            place(available, cls)
            return True
        for frame in preferences:
            old = owner[frame]
            if old != cls and extend(old, seen):
                place(frame, cls)
                return True
        return False

    for cls in order:
        while len(held[cls]) < LIMIT-counts[cls] and extend(cls, set()):
            pass
    selected = {representatives[c][f]['target_key']: representatives[c][f] for f, c in owner.items()}
    return selected, owner, order


def residual_maximum_size(base, candidates):
    """A second, frame-first augmenting matcher proves maximum cardinality.

    It does not use quality, scarcity order, or the class-first implementation's
    selected records, so a nonmaximum deterministic replay cannot self-certify.
    """
    locked = {p['source']['frame_id'] for p in base.values()}
    counts = Counter(p['class_id'] for p in base.values())
    limits = {c: LIMIT-counts[c] for c in REMAINING}
    options = defaultdict(set)
    for p in candidates.values():
        if p['source']['frame_id'] not in locked:
            options[p['source']['frame_id']].add(p['class_id'])
    held, owners = {c: set() for c in REMAINING}, {}

    def add(frame, seen):
        if frame in seen:
            return False
        seen.add(frame)
        # A recursive frame must leave its previous class. Re-entering that
        # class after moving another held frame would leave a ghost owner when
        # the caller removes it from the old class on successful return.
        choices = sorted(options[frame]-{owners.get(frame)})
        for cls in choices:
            if len(held[cls]) < limits[cls]:
                held[cls].add(frame); owners[frame] = cls
                return True
        for cls in choices:
            for other in sorted(held[cls]):
                if add(other, seen):
                    held[cls].remove(other); held[cls].add(frame); owners[frame] = cls
                    return True
        return False

    for frame in sorted(options):
        add(frame, set())
    require(all(len(held[c]) <= limits[c] and all(owners[f] == c for f in held[c]) for c in REMAINING)
        and set(owners) == set().union(*held.values()), 'Independent residual matcher ownership bookkeeping differs')
    return len(owners)


def check_diversity(base, accepted, new, outcomes):
    selected, owners, order = diverse_matching(base, accepted)
    require(len(selected) == residual_maximum_size(base, accepted), 'Residual frame/quota matching is not maximum')
    frames = {p['source']['frame_id'] for p in base.values()} | set(owners)
    for key, p in accepted.items():
        reason = ('new_proposal' if key in selected else 'accepted_duplicate_frame_not_selected'
            if p['source']['frame_id'] in frames else 'accepted_quota_full_not_selected')
        require(outcomes[key]['reason'] == reason, f'Diversity/quota outcome differs: {key}')
    require(selected == new, 'Selected machine sidecar differs from maximum diversity/quota replay')
    return owners, order


def check_rendering(out, inventory, templates, old, previous_manual, manual, new):
    actual = indexed(inventory['templates'], 'rendering_id')
    historical = {}
    mapping = {}
    for root, records in ((PARENT, old), (SOURCES, previous_manual)):
        previous = read_json(root/'template_inventory.json')
        for t in previous['templates']:
            rid = t['rendering_id']
            require(rid not in historical or historical[rid] == t, 'Conflicting historical rendering namespace')
            historical[rid] = t
        mapping.update({k: previous['rendering_by_target'][k] for k in records})
    require(all(actual.get(k) == t for k, t in historical.items()), 'Historical rendering payload was changed')
    latest = {rid: t for rid, t in actual.items() if rid not in historical}
    require(set(latest) == {NAMESPACE+':'+k for k in templates}, 'New seed inventory omits/invents/four-point sources')
    for key, template in templates.items():
        require(all(latest[NAMESPACE+':'+key].get(f) == v for f, v in template.items()), 'New rendering human provenance differs')
        exported = read_json(out/NAMESPACE/'templates'/f'{key}.json')
        require(all(exported.get(f) == v for f, v in template.items()), 'Exported latest template differs')
    require({p.name for p in (out/NAMESPACE/'templates').iterdir()} == {k+'.json' for k in templates},
        'New template files include an extra/non-counted/four-point seed')
    for key in set(manual)-set(previous_manual):
        mapping[key] = manual[key]['rendering_id']
    mapping.update({k: NAMESPACE+':'+p['template']['target_key'] for k, p in new.items()})
    require(inventory['rendering_by_target'] == mapping, 'Cumulative rendering target binding differs')
    claim(inventory, 'generation_template_namespace', NAMESPACE)
    claim(inventory, 'generation_template_keys', sorted(templates), required=False)
    claim(inventory, 'generation_templates', len(templates), required=False)
    four = {k for k, p in manual.items() if len(p['polygon']) == 4}
    source_renderings = indexed(inventory.get('manual_source_renderings', []))
    require(four <= set(source_renderings), 'Four-point manual rendering omitted')
    for key in four:
        rendering = source_renderings[key]
        require(rendering['polygon'] == manual[key]['polygon'] and rendering['human_source'] == manual[key]['human_source']
            and rendering['rendering_id'] == manual[key]['rendering_id'] and rendering['propagation_seed_eligible'] is False,
            'Four-point source rendering changed or masquerades as seed')


def source_counts(old, manual, new, inherited, gallery, dispositions):
    combined = {**old, **manual, **new}
    pose_keys, gallery_keys = set(inherited) | set(manual), set(gallery['current'])
    require(pose_keys.isdisjoint(gallery_keys), 'Pose/gallery coverage must be deduplicated')
    require(set(dispositions) <= set(old), 'No-change scope extends beyond the old500')
    actual = pose_keys | gallery_keys
    result = {}
    for cls in CLASSES:
        keys = {k for k, p in combined.items() if p['class_id'] == cls}
        historic = keys & set(old)
        raw = keys-actual
        result[str(cls)] = dict(old_total=len(historic), manual_added=len(keys & set(manual)),
            manual_existing_reused=sum(manual[k].get('manual_source_kind') != 'completed_manual_request' for k in keys & set(manual)),
            manual_requested=sum(manual[k].get('manual_source_kind') == 'completed_manual_request' for k in keys & set(manual)),
            saved_pose_human=len(keys & pose_keys), saved_gallery_human=len(keys & gallery_keys), saved_human=len(keys & actual),
            manual_four_point_sources=sum(len(combined[k]['polygon']) == 4 for k in keys & pose_keys),
            user_reviewed_no_change=len(keys & set(dispositions)), pending_machine_raw=len(raw),
            no_new_server_review=len(raw-set(dispositions)), old_pending_machine=len(historic-actual),
            new_candidates=len(keys & set(new)), new_machine_pending=len(keys & set(new)),
            total=len(keys), preview=len(keys), distinct_frames=len(keys), missing=LIMIT-len(keys), goal=LIMIT, target_per_class=LIMIT)
    return result


def check_counts(manifest, inventory, counts, old, manual, new, accepted, attempts, eligible, templates):
    require(set(manifest['classes']) == set(inventory['classes']) == {str(c) for c in CLASSES}, 'All22 class statistics required')
    require(manifest['classes'] == inventory['classes'], 'Manifest/rendering class counts disagree')
    for cls, expected in counts.items():
        actual = manifest['classes'][cls]
        for field, value in expected.items():
            claim(actual, field, value, required=field in ('total', 'missing', 'saved_human', 'new_candidates'))
    for names, expected in ((('previous_proposals',), len(old)), (('manual_proposals', 'manual_added'), len(manual)),
            (('new_proposals',), len(new)), (('proposals',), len(old)+len(manual)+len(new)),
            (('base_proposals',), len(old)+len(manual)), (('accepted_before_diversity',), len(accepted)),
            (('registration_attempts',), len(attempts)), (('scanned_eligible_targets',), len(eligible)),
            (('generation_templates',), len(templates))):
        claim(manifest, names, expected)
    claim(manifest, 'manual_requested', 51, required=False)
    claim(manifest, 'manual_existing_reused', 141, required=False)
    claim(manifest, 'new_by_class', {str(c): n for c, n in Counter(p['class_id'] for p in new.values()).items()}, required=False)
    claim(manifest, 'new_by_vertices', {str(c): n for c, n in Counter(p['vertex_count'] for p in new.values()).items()}, required=False)
    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()))


def check_report(out, combined, manual_keys, 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 cumulative card inventory differs')
    options = parsed.options.get('filter', [])
    require(options and options[0].get('value') == '' and not any('selected' in o for o in options[1:])
        and [o['_text'].strip() for o in options[1:]] == [str(c) for c in CLASSES], 'Report must offer ALL22 with ALL class 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 must follow actual new-machine sidecar, not manual additions')
    for key, p in combined.items():
        card = cards['target-'+key]
        require(card['data-class'] == str(p['class_id']) and card['data-kind'] == ('manual' if key in manual_keys else 'machine')
            and card['data-batch'] == ('new' if key in new else 'previous'), 'Report card source/batch tag differs')
        require('display:none' not in card.get('style', '').replace(' ', '').lower(), 'Report card unconditionally hidden')
        require(('hidden' in card) is (bool(new) and key not in new), 'Report initial visibility differs from controls')
    expected_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+', '', expected_script), 'Report filter behavior differs')
    require(all(text in page for text in ('四点', '不作传播模板', '未确认真值', str(len(new)), str(len(combined)), '45')),
        'Report omits manual/seed/non-truth/no-change/machine status')
    for count in counts.values():
        require(str(count['total']) in page and str(count['missing']) in page, 'Report omits quota counts/shortfalls')
    fields = ('old_total', 'manual_existing_reused', 'manual_requested', 'saved_human', 'new_candidates', 'total', 'missing')
    expected_cells = [str(value) for cls in CLASSES for value in (cls, *(counts[str(cls)][f] for f in fields))]
    require(parsed.cells == expected_cells, 'Report exact all22 source counts/new-machine totals/shortfalls differ')
    totals = lambda field: sum(c[field] for c in counts.values())
    rest = lambda field: sum(counts[str(c)][field] for c in REMAINING)
    summaries = (f'本轮新增机器候选 {len(new)} 份',
        f'实际保存人工 {rest("saved_human")} + 新机器候选 {rest("new_candidates")} = 覆盖 {rest("total")}/1700 个不同帧，仍缺 {rest("missing")}',
        f'全部22类累计 {totals("total")}/2200，实际保存人工 {totals("saved_human")} = 原位姿 {totals("saved_pose_human")} + 图册 {totals("saved_gallery_human")}')
    require(all(text in page for text in summaries), 'Report saved-human/manual versus new-machine coverage summary differs')
    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'), 'Font coverage/hash evidence differs')
    require((out/'FONT_LICENSE.txt').is_file(), 'Missing report font license')
    return parsed


def check_live(stores, snapshots, pose_live, gallery_live):
    result = {}
    for kind, live_path in (('pose', pose_live), ('gallery', gallery_live)):
        live = helpers.read_store(live_path, kind)
        helpers.preserve_events(stores[kind], live)
        require(live['current'] == stores[kind]['current'], f'{kind} current records changed since generation')
        frozen = sources.logical_fingerprint(snapshots[kind], frozen=True)
        require(sources.logical_fingerprint(live_path) == frozen, f'{kind} full raw logical database changed since generation')
        result[kind] = frozen
    return result


def audit(out, pose_live=POSE, gallery_live=GALLERY):
    data = check_inputs()
    manifest, artifacts = read_json(out/'manifest.json'), read_json(out/'artifact_hashes.json')
    check_claims(manifest)
    helpers.check_artifacts(out, artifacts)
    require(set(file_inventory(out))-{REPORT, SEAL, 'artifact_hashes.json'} == set(artifacts), 'Artifact hashes must cover every builder file')
    config = sources.check_configuration(out, manifest)
    pose_config, gallery_config = (read_json(PROJECT/'configs'/n) for n in ('active_pose_review.json', 'active_mask_gallery.json'))
    require(Path(pose_live).resolve() == (PROJECT/pose_config['database']).resolve()
        and Path(gallery_live).resolve() == (PROJECT/gallery_config['review_directory']/'mask_reviews.sqlite3').resolve(),
        'Live guard must use configured production read-only stores')
    require((PROJECT/gallery_config['directory']).resolve() == PARENT.resolve() and gallery_config['publication_version'] == 9,
        'Publication9 must remain active until expansion is independently sealed')
    code = manifest['frozen_code_sha256']
    parent_code = 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 engine dependencies omitted/changed')
    for name, expected in code.items():
        path = (PROJECT/name).resolve()
        require(path.is_relative_to(PROJECT) and digest(path) == expected, f'Frozen engine/generator changed: {name}')
    require(manifest['code_sha256'] == code[GENERATOR], 'Generator provenance differs')
    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']
    require(json.loads(pose['metadata']['binding'])['formal_manifest_sha256'] == formal_sha
        == gallery['metadata']['formal_manifest_sha256'], 'Review dataset binding differs')
    # The request output intentionally has no SQLite files: its independent
    # seal binds the immutable source audit's snapshots instead.
    for root in (PARENT, SOURCES):
        parent_manifest = read_json(root/'manifest.json')
        for kind, path in helpers.find_snapshots(root, parent_manifest).items():
            helpers.preserve_events(helpers.read_store(path, kind, frozen=True), stores[kind])
    snapshot_manifest = read_json(out/'snapshot_manifest.json')
    for kind, store in stores.items():
        expected = snapshot_manifest[kind]
        for field, value in dict(path=snapshots[kind].name, backup='backups/'+snapshots[kind].name,
                sha256=digest(snapshots[kind]), saved=len(store['current']), events=len(store['events'])).items():
            claim(expected, field, value)
        prefix = 'snapshot' if kind == 'pose' else 'gallery_snapshot'
        claim(manifest, prefix+'_saved', len(store['current']))
        claim(manifest, prefix+'_events', len(store['events']))
        claim(expected, 'metadata', store['metadata'], required=False)
        for path in (snapshots[kind], out/'backups'/snapshots[kind].name):
            require(path.stat().st_mode & 0o077 == 0, 'Private raw database snapshot/backup must not be public-readable')
    fingerprints = 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['previous_manual'], data['requests'], manual, new, combined, accepted)
    check_preservation(out, data['old'], data['previous_manual'])
    require((out/'requests.jsonl').read_bytes() == (REQUESTS/'requests.jsonl').read_bytes(), 'Completed51 requests changed')
    quarantine = set(sources.QUARANTINE) | set(data['parent_manifest'].get('preserved_quarantined_targets', []))
    require(set(manifest.get('preserved_quarantined_targets', [])) == quarantine and not quarantine & set(combined),
        'Frozen quarantine changed, broadened to hide eligible targets, or resurrected')
    recovered = sources.recover_pose_sources(pose, rows, quarantine)
    recovered = {k: s for k, s in recovered.items() if k not in gallery['history_keys']}
    inherited = {k: p for k, p in data['old'].items() if p.get('schema') == 'saved_pose_mask_gallery_entry_v1'}
    require(len(inherited) == 143 and set(inherited).isdisjoint(manual), 'All143 parent pose sources must remain explicit')
    all_humans = {**inherited, **manual}
    require(len(all_humans) == 335 and set(all_humans) <= set(recovered), 'All335 counted pose sources need latest actual-human audits')
    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_humans}, recovered, snapshots['pose'])
    manual_records = indexed(read_jsonl(out/'manual_source_records.jsonl'))
    sources.check_source_records(manual_records, {k: dict(polygon=recovered[k]['polygon']) for k in manual}, recovered, snapshots['pose'])
    require(all(raw_records[k] == v or all(raw_records[k].get(f) == val for f, val in v.items())
        for k, v in manual_records.items()), 'Manual192/current335 raw evidence conflicts')
    for name in ('all_manual_sources.jsonl', 'manual_source_records.jsonl'):
        require((out/name).stat().st_mode & 0o077 == 0, 'Raw human payload records must remain private')
    pose_sha, gallery_sha = digest(snapshots['pose']), digest(snapshots['gallery'])
    check_inherited_audits(out, {**inherited, **data['previous_manual']}, manual, recovered, raw_records, pose_sha)
    for key, request in data['requests'].items():
        check_new_manual(manual[key], request, rows[key], recovered, pose_sha, formal_sha, class_sha)
    templates = independent_seeds(manual, recovered, pose_sha)
    # These task-specific counts are checked against recovered raw events, never
    # used as an alternative source of provenance or to fabricate missing labels.
    require(len(templates) == 41 and sum(len(recovered[k]['polygon']) == 4 for k in manual) == 151,
        'Expected genuine151 four-point coverage sources and41 strictly >4 seeds')
    requested_four = Counter(manual[k]['class_id'] for k in data['requests'] if len(recovered[k]['polygon']) == 4)
    require(requested_four == {4: 3, 5: 3, 7: 3, 14: 3, 22: 3}, 'Actual completed51 topology distribution differs')
    publications = baseline.check_frozen_inputs()
    publications[9] = dict(path=PARENT, proposals=data['old'], manifest=data['parent_manifest'])
    gallery_sources = baseline.independent_gallery(gallery, pose, rows, data['old'], publications, formal_sha, gallery_sha)
    require(len(gallery_sources) == len(gallery['current']), 'Every latest gallery save needs actual historical provenance')
    baseline.check_gallery_source_records(out, snapshots['gallery'], gallery, gallery_sha)
    dispositions = indexed(read_jsonl(out/'review_dispositions.jsonl'))
    counts = source_counts(data['old'], manual, new, inherited, gallery, dispositions)
    require(len(dispositions) == 45 and not set(dispositions) & set(gallery['current']), 'Old45 no-change cannot become saved edits')
    inventory = read_json(out/'template_inventory.json')
    check_rendering(out, inventory, templates, data['old'], data['previous_manual'], manual, new)
    protected_keys, protected_frames = target_protection(rows, pose, gallery, data['old'], manual, quarantine)
    capacity = capacity_audit(rows, data['old'], manual, protected_keys, protected_frames)
    require(capacity['19']['original_distinct_frames'] == 96 and capacity['19']['protected_aware_capacity'] <= 90
        and frame_counts['19']['proposals'] <= capacity['19']['protected_aware_capacity'],
        'Class19 protected capacity/at-least10 shortfall must not be concealed')
    for p in accepted.values():
        check_machine(p, pose, templates, rows, protected_keys, protected_frames, pose_sha, formal_sha, class_sha)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    attempts = read_jsonl(out/'registration_attempts.jsonl')
    evidence = ImageEvidence(formal, rows, source_rows)
    base = {**data['old'], **manual}
    reasons, pose_protected, locked_frames = scan_reasons(rows, pose, gallery, base, quarantine)
    scan_protected = {k for k, reason in reasons.items() if reason != 'eligible'}
    for key in scan_protected:
        require(outcomes[key]['reason'] == reasons[key] and outcomes[key]['registration_attempts'] == 0,
            'Original protected target outcome/attempt count differs')
    eligible = audit_attempts(attempts, rows, templates, accepted, outcomes, evidence, scan_protected, locked_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')
    owners, order = 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_owners, capacity_order = diverse_matching(base, potential)
    require(len(capacity_selected) == residual_maximum_size(base, potential), 'Protected residual capacity is not maximum')
    claim(manifest, 'capacity_matching_order', capacity_order)
    maximum_counts = Counter(p['class_id'] for p in list(base.values())+list(capacity_selected.values()))
    claim(manifest, 'capacity_matching_total', sum(maximum_counts.values()))
    expected_assignments = [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()]
    expected_assignments.extend(dict(frame_id=f, class_id=c, target_key=next(k for k, p in new.items() if p['source']['frame_id'] == f),
        locked=False, phase='accepted_candidate_maximum_matching') for f, c in owners.items())
    require(indexed(read_jsonl(out/'frame_assignments.jsonl'), 'frame_id') == indexed(expected_assignments, 'frame_id'),
        'Locked692/new-machine frame assignment evidence differs')
    capacity_assignments = [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 capacity_selected.items()]
    require(indexed(read_jsonl(out/'capacity_frame_assignments.jsonl'), 'frame_id') == indexed(capacity_assignments, 'frame_id'),
        'Independent full residual-capacity frame assignment evidence differs')
    shortfalls = read_json(out/'shortfalls.json')
    require(set(shortfalls) == {str(c) for c in REMAINING}, 'Remaining17 shortfall coverage differs')
    for cls in CLASSES:
        declared = manifest['classes'][str(cls)]
        claim(declared, 'capacity_matching_distinct_frames', maximum_counts[cls])
        claim(declared, 'capacity_shortfall', LIMIT-maximum_counts[cls])
        claim(declared, 'templates', sum(t['row']['final_class_id'] == cls for t in templates.values()))
        claim(declared, 'eligible', sum(rows[k]['final_class_id'] == cls for k in eligible))
        class_outcomes = dict(Counter(o['reason'] for o in outcomes.values() if o['class_id'] == cls))
        claim(declared, 'outcomes', class_outcomes)
        if cls in REMAINING:
            item = shortfalls[str(cls)]
            claim(item, 'missing', counts[str(cls)]['missing'])
            claim(item, 'capacity', maximum_counts[cls])
            claim(item, 'capacity_shortfall', LIMIT-maximum_counts[cls])
            claim(item, 'outcomes', class_outcomes)
            claim(item, 'templates', sum(t['row']['final_class_id'] == cls for t in templates.values()))
    check_counts(manifest, inventory, counts, data['old'], manual, new, accepted, attempts, eligible, templates)
    claim(manifest, 'outcomes', dict(Counter(o['reason'] for o in outcomes.values())))
    for key, p in {**{k: v for k, v in manual.items() if k not in data['previous_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}, 'Published cumulative asset inventory differs')
    check_report(out, combined, set(all_humans), new, counts)
    used = read_json(out/'used_image_hashes.json')
    require(all(used.get(name) == value for name, value in evidence.used.items()), 'Used image evidence omitted')
    for name, expected in used.items():
        require((formal/name).resolve().is_relative_to(formal) and digest(formal/name) == expected, 'Original image bytes 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, f'Immutable input changed during audit: {root.name}')
    for name, expected in code.items():
        require(digest(PROJECT/name) == expected, 'Frozen engine code changed during audit')
    helpers.check_artifacts(out, artifacts)
    # Recheck after the potentially long full replay, including raw DB whitespace
    # and metadata, not merely revisions or semantically equivalent JSON.
    require(check_live(stores, snapshots, pose_live, gallery_live) == fingerprints, 'Live review guard changed during 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=len(manual), completed_requests_verified=51, old_canonical_objects_preserved=500,
        old_remaining_manual_objects_preserved=141, inherited_manual_sources_verified=143, all_manual_sources_verified=335,
        actual_saved_human=sum(v['saved_human'] for v in counts.values()), actual_saved_gallery=len(gallery_sources),
        actual_saved_pose=len(all_humans), old500_actual_saved_human=len(set(data['old']) & (set(all_humans) | set(gallery_sources))),
        historical_user_reviewed_no_change=len(dispositions), old500_pending_machine_raw=sum(v['old_pending_machine'] for v in counts.values()),
        old500_other_no_new_server_review=len(set(data['old'])-set(all_humans)-set(gallery_sources)-set(dispositions)),
        manual_four_point_sources_verified=151, four_point_sources_used_as_seeds=0, templates_verified=len(templates),
        classes=counts, distinct_frame_quotas=frame_counts, protected_class_capacity=capacity, 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, inherited_manual_current_raw_records_verified=True,
        historical_canonical_resources_bytewise_preserved=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,
        automatic_training_eligible=False, robot_command_eligible=False, ground_truth_eligible=False, human_confirmation_inferred=False,
        generator_code_sha256=code[GENERATOR], verification_script_sha256=digest(__file__),
        verified_at=datetime.now(timezone.utc).isoformat())


def seal(out, operation=audit):
    requested = Path(out).absolute()
    out = requested.resolve()
    require(requested == out and out.parent == (PROJECT/'outputs').resolve() and out.name.startswith('pallet_mask_remaining_expand_')
        and out.is_dir() and out not in {PARENT.resolve(), SOURCES.resolve(), REQUESTS.resolve()}, 'Only a new completed expansion 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 an independent verification seal')
    require(not (out/REPORT).is_symlink(), 'Unsafe validation report path')
    cv2.setNumThreads(1)
    try:
        result = operation(out)
        require(result.get('state') == 'passed', 'Audit did not pass')
    except Exception as exc:
        report = dict(state='failed', publication_version=PUBLICATION, error_type=type(exc).__name__, error=str(exc),
            verification_script_sha256=digest(__file__))
        (out/REPORT).write_bytes(canonical(report)+b'\n')
        raise
    (out/REPORT).write_bytes(canonical(result)+b'\n')
    result = dict(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()
