"""Independent continuation audit: separate later revisions from new saved images.

The continuation producer and builders are never imported. Frozen quality-v2 is
checked as historical evidence, NOT as a claim that live gallery current rows are
unchanged. Each fresh event is resolved by publication/proposal-hash/target triple.
Only the v2 twin seals may be written, after an explicit completion notification.
"""
from __future__ import annotations

import argparse
from collections import Counter
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import sys

sys.dont_write_bytecode = True
PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))

from scripts import verify_mask_under50_requests as previous
from scripts import verify_mask_quality_recovery as sources

ROOT = PROJECT/'outputs/pallet_mask_under50_requests_v2'
PARENT, QUALITY, POSE, GALLERY = previous.PARENT, previous.QUALITY, previous.POSE, previous.GALLERY
SNAPSHOT = PROJECT/'outputs/pallet_mask_continuation_sources_v2'
EARLIER_SNAPSHOT = PROJECT/'outputs/pallet_mask_continuation_sources_v1'
EARLIER_AUDIT_SHA256 = 'c64f0e5a389faa3c2d109080dbbd1b57e35d64f7407c900177ca79a04742d01a'
PREVIOUS = previous.ROOT
TRAINING_RECORDS = PROJECT/'outputs/pallet_mask_model_training_v1/private/training_records.jsonl'
SOURCE_AUDIT_SHA256 = '94c7d007a58d3fdddfe5acdb4aa83c30207ac66cf04e26e90d1e3d672556a027'
EXPECTED_COUNTS = {11: 19, 12: 47, 16: 36, 17: 45, 19: 41, 20: 47}
PREVIOUS_PINS = {
    'manifest.json': '2b34627da485b88a1a198511b7d549711b0bfd09b3c4b1b904c43c8be2bc2bea',
    'verification.json': '87d868e53d396acf37a161019b71144fbff906c62091e7d4b9d68458f9083e5a',
    'independent_verification.json': '87d868e53d396acf37a161019b71144fbff906c62091e7d4b9d68458f9083e5a',
}
HELPER_PINS = {
    'scripts/verify_mask_under50_requests.py': '354db76211ecf7ed24daf5241a0e11bfdc3ebcaaf013e40a192c0137ab76e60c',
    'tests/test_verify_mask_under50_requests.py': 'd0e99da04f56252183c51a421551b0c612aa1e39bf554dd660256fc2f1419575',
    'scripts/build_mask_under50_requests.py': '415e1a9591958204bb9dfbd9155cbadea58def47b2ba29da06f99478f9e90007',
}
CLASSES, SEALS = previous.CLASSES, previous.SEALS
require, read, read_jsonl = sources.require, sources.read, sources.read_jsonl
canonical, sha, digest = sources.canonical, sources.sha, sources.digest
inventory, member, equal = sources.inventory, sources.member, sources.equal


def check_revision_extension(baseline, fresh, expected_new_keys=()):
    """Exact raw prefix/current-revision recovery; no canonicalization of payloads."""
    require(fresh['events'][:len(baseline['events'])] == baseline['events'], 'Baseline raw event prefix changed')
    equal(fresh['metadata'], baseline['metadata'], 'gallery_metadata_preserved')
    equal(fresh['fingerprint']['schema_sha256'], baseline['fingerprint']['schema_sha256'], 'gallery_schema_preserved')
    require(set(fresh['histories']) == set(fresh['current']), 'Fresh gallery orphan history/current')
    require(set(baseline['current']) <= set(fresh['current']), 'Baseline saved image disappeared')
    new_keys = set(fresh['current'])-set(baseline['current'])
    require(new_keys == set(expected_new_keys), 'New distinct saved images differ from the exact prior ten tasks')
    for key in new_keys:
        sources.exact_latest(fresh, key)
    changed = []
    for key, old in baseline['current'].items():
        sources.exact_latest(fresh, key)
        require(any(event[1:3] == old[:2] for event in fresh['histories'][key]), 'Baseline current raw revision no longer recoverable: '+key)
        if fresh['current'][key] != old:
            changed.append(key)
    return dict(baseline_gallery_raw_event_prefix_preserved=len(baseline['events']),
        appended_gallery_events=len(fresh['events'])-len(baseline['events']),
        changed_baseline_current_keys=sorted(changed), new_distinct_saved_keys=sorted(new_keys),
        baseline_gallery_current_unchanged=not changed,
        baseline_current_revisions_preserved_in_history=True)


def extend_under50_registry(root, rows, formal_sha, pose, publication, registry, evidence):
    """Register the sealed v1 tasks, without reusing v1's stale-live-store audit."""
    for name, expected in PREVIOUS_PINS.items():
        require(digest(root/name) == expected, 'Frozen under50-v1 task pack changed: '+name)
    manifest, seal, inputs = read(root/'manifest.json'), read(root/'verification.json'), read(root/'input_manifest.json')
    require(seal['state'] == 'passed' and seal['preannotations_verified'] is True, 'Sealed under50-v1 registry required')
    require(digest(root/'verification.json') == digest(root/'independent_verification.json'), 'Previous twin seals differ')
    for field, name in (('proposals_sha256', 'proposals.jsonl'), ('requests_sha256', 'requests.jsonl'),
            ('input_manifest_sha256', 'input_manifest.json'), ('decisions_sha256', 'internal/build_decisions.json')):
        require(manifest[field] == digest(root/name), 'Previous task source/geometry binding differs')
    for field in ('manifest_sha256', 'proposals_sha256', 'verification_sha256'):
        require(manifest['parent_'+field] == publication[field], 'Previous task publication15 binding differs')
    require(manifest['formal_manifest_sha256'] == formal_sha and seal['manifest_sha256'] == digest(root/'manifest.json')
        and seal['requests_sha256'] == manifest['requests_sha256'] and seal['proposals_sha256'] == manifest['proposals_sha256'], 'Previous task seal binding differs')
    proposals, tasks = read_jsonl(root/'proposals.jsonl'), read_jsonl(root/'requests.jsonl')
    drafts, task_map = sources.indexed(proposals), sources.indexed(tasks)
    require(len(proposals) == len(tasks) == manifest['request_count'] == seal['request_count'] == 10
        and drafts.keys() == task_map.keys(), 'Previous ten pending task identities differ')
    require(manifest['public_assets'] == seal['public_assets'], 'Previous public assets differ from their seal')
    previous.check_public(root, manifest, proposals)
    shortlist = read_jsonl(root/'internal/shortlist.jsonl'); staged = sources.indexed(shortlist)
    require(len(staged) == 18 and digest(root/'internal/shortlist.jsonl') == inputs['shortlist_sha256'], 'All18 previous inspections must remain protected')
    decisions = read(root/'internal/build_decisions.json')['decisions']
    require(set(decisions) == set(staged) and drafts.keys() <= staged.keys(), 'Previous own staged/decision scope differs')
    extended = dict(registry)
    for key, proposal in drafts.items():
        row = rows[key]; record = staged[key]; value = pose['current'].get(key)
        require(proposal['source'] == record['source'] == row, 'Previous formal image identity differs')
        equal(record['existing_pose_current_payload'], value[2] if value else None, 'previous_preserved_pose_payload')
        equal(record['existing_pose_revision'], value[0] if value else 0, 'previous_pose_revision')
        equal(record['existing_pose_payload_sha256'], sha(value[2]) if value else None, 'previous_pose_payload_sha256')
        image_sha = digest(member(evidence.formal, row['image']))
        previous.check_draft(proposal, task_map[key], record, decisions[key], formal_sha, digest(root/'input_manifest.json'), image_sha)
        previous.check_exports(root, proposal, record, image_sha)
        evidence.image(row['frame_id'])
        identity = (15, sha(proposal), key)
        require(identity not in extended, 'Duplicate publication/hash/key registry triple')
        extended[identity] = dict(kind='independent_preannotation', namespace=root.name, proposal=proposal, path=root)
    return extended, set(staged), set(drafts), {root.name: digest(root/'manifest.json')}


def check_fresh_catalog(snapshot, baseline_catalog, pose, gallery, rows, publications, registry, formal_sha, evidence):
    """Recompute every event source and each exact latest research contour."""
    catalog = read_jsonl(snapshot/'private/source_catalog.jsonl'); records = sources.indexed(catalog)
    require(len(records) == 1494 and len({r['row']['frame_id'] for r in catalog}) == 1494, '1494 distinct actual human source images required')
    baseline = sources.indexed(baseline_catalog)
    pose_sources = {key: record for key, record in baseline.items() if record['origin'] == 'saved_pose'}
    require(len(pose_sources) == 482 and set(records) == set(pose_sources) | set(gallery['current'])
        and len(gallery['current']) == 1012 and not set(pose_sources) & set(gallery['current']), 'Current482 pose/1012 gallery partition differs')
    for key, record in pose_sources.items():
        value, _ = sources.exact_latest(pose, key)
        require(record['payload_sha256'] == sha(value) and record['polygon'] == value['polygon'], 'Frozen pose contour differs')
        equal(records[key], record, 'preserved_saved_pose_catalog.'+key)
    event_audit, references = [], {}
    for event_id, key, revision, raw in gallery['events']:
        require(key in rows, 'Foreign gallery event target')
        value = sources.loads(raw)
        reference = sources.resolve_event(value, publications, registry)
        sources.check_gallery_event(value, rows[key], reference, publications[value['proposal_publication']], formal_sha, evidence)
        require(value['revision'] == revision, 'Event relational revision differs')
        references[event_id] = reference
        event_audit.append(dict(event_id=event_id, target_key=key, revision=revision,
            payload_raw_sha256=sources.raw_sha(raw), proposal_publication=value['proposal_publication'],
            base_proposal_id=value['base_proposal_id'], namespace=reference.get('namespace'), event_specific_source_verified=True))
    for key in gallery['current']:
        value, last = sources.exact_latest(gallery, key)
        history = gallery['histories'][key]; first = history[0]; row = rows[key]
        require(not sources.original_rectangle(value['polygon'], row), 'Original box counted as gallery contour')
        sources.unconfirmed(value); sources.polygon(value['polygon'], row['size'])
        reference = references[last[0]]
        expected = dict(target_key=key, row=row, polygon=value['polygon'], origin='saved_gallery', revision=value['revision'],
            payload_sha256=sha(value), event_raw_sha256=sources.raw_sha(last[2]), initial_polygon=first[3]['proposal_polygon'],
            batch=reference.get('namespace') or 'historical_gallery', history_revisions=len(history), actual_saved_research_reference_not_GT=True)
        equal(records[key], expected, 'fresh_exact_latest_catalog.'+key)
    equal(read_jsonl(snapshot/'private/event_binding_audit.jsonl'), event_audit, 'all_raw_event_publication_hash_target_bindings')
    return catalog, references


def check_completed_previous_tasks(gallery, baseline, previous_tasks, registry, references):
    """All ten first saves must be real, changed, and bound to the sealed v1 pack."""
    new_keys = set(gallery['current'])-set(baseline['current'])
    require(len(previous_tasks) == 10 and new_keys == set(previous_tasks), 'Exactly the prior ten tasks must be the new distinct saved images')
    for key in new_keys:
        history = gallery['histories'][key]
        require(len(history) == 1 and history[0][1] == gallery['current'][key][0] == 1,
            'Each of the ten actual completed tasks requires its first unique revision1 event')
        event_id, _, _, value = history[0]
        reference = references[event_id]
        require(reference['kind'] == 'independent_preannotation' and reference.get('namespace') == PREVIOUS.name,
            'New saved task resolved to the wrong package')
        identity = (15, value['base_proposal_id'], key)
        require(identity in registry and registry[identity] == reference
            and reference['proposal']['target_key'] == key, 'New human save publication/hash/key registry binding differs')
        require(value['polygon'] != reference['proposal']['polygon'] and value.get('event_kind') == 'human_mask_gallery_revision'
            and value.get('human_edited') is True, 'All ten reported completions must be actual changed human saves, not draft copies')
    appended = gallery['events'][len(baseline['events']):]
    old_events = [entry for entry in appended if entry[1] in baseline['current']]
    new_events = [entry for entry in appended if entry[1] in new_keys]
    require(len(appended) == 27 and len(old_events) == 17 and len(new_events) == 10,
        'Expected17 old-image revisions plus10 actual new completed task events')
    require(all(references[e[0]].get('namespace') == 'v3' for e in old_events)
        and all(references[e[0]].get('namespace') == PREVIOUS.name for e in new_events), 'Appended event-specific namespaces differ')


def check_trained_revisions(path, baseline_catalog, changed_keys):
    """Report newer research references; never replace a frozen training label."""
    baseline = sources.indexed(baseline_catalog); trained = sources.indexed(read_jsonl(path))
    for key, record in trained.items():
        require(key in baseline, 'Unknown frozen training reference')
        source, row = baseline[key], baseline[key]['row']
        require(row['split'] == record['formal_split'] == 'train' and row['frame_id'] == record['frame_id']
            and row['final_class_id'] == record['class_id'] and source['polygon'] == record['polygon'], 'Frozen train-only source identity differs')
        require(record['source_payload_sha256'] == source['payload_sha256']
            and record['source_event_raw_sha256'] == source['event_raw_sha256'], 'Frozen training source raw/canonical hashes differ')
        require(isinstance(record['development_split'], str) and record['development_split'], 'Frozen development split missing')
    return {key: trained[key]['development_split'] for key in sorted(changed_keys) if key in trained}


def check_source_claims(summary, catalog, pose, gallery, extension, registry_manifests, trained_changes):
    equal(summary['state'], 'passed_event_provenance_and_distinct_saved_count_not_contour_accuracy', 'producer_source_audit_scope')
    for field, value in dict(total_contours=1494, gallery_contours=1012, gallery_events=1115, pose_contours=482,
            old_raw_event_prefix_preserved=1088, production_annotation_writes=0).items():
        equal(summary[field], value, 'fresh_source_summary.'+field)
    equal(summary['pose_fingerprint'], pose['fingerprint'], 'fresh_pose_snapshot_fingerprint')
    equal(summary['gallery_fingerprint'], gallery['fingerprint'], 'fresh_gallery_snapshot_fingerprint')
    equal(summary['class_counts'], {str(c): n for c, n in Counter(r['row']['final_class_id'] for r in catalog).items()}, 'fresh_distinct_class_counts')
    require(len(summary['changed_baseline_current_keys']) == len(set(summary['changed_baseline_current_keys']))
        and sorted(summary['changed_baseline_current_keys']) == extension['changed_baseline_current_keys'], 'Changed current revisions misreported')
    equal(summary['new_distinct_saved_keys'], extension['new_distinct_saved_keys'], 'actual_ten_new_distinct_saved_images')
    for field in ('actual_changed_baseline_revisions_not_new_distinct_images', 'baseline_current_revisions_preserved_in_history'):
        equal(summary[field], True, field)
    equal(summary['frozen_training_dataset_modified'], False, 'frozen_training_not_rewritten')
    equal(summary['source_registry_task_manifests'], registry_manifests, 'actual_task_registry_manifests')
    equal(summary['trained_reference_keys_with_newer_human_revision'], trained_changes, 'newer_revisions_of_frozen_training_references')


def check_sources(snapshot, parent_manifest, baseline=QUALITY, previous_root=PREVIOUS):
    """Verify the new unsealed producer audit as part of this task's own chain."""
    require(digest(snapshot/'audit.json') == SOURCE_AUDIT_SHA256, 'Exact continuation source audit.json changed')
    summary = read(snapshot/'audit.json')
    require(summary['source_catalog_sha256'] == digest(snapshot/'private/source_catalog.jsonl'), 'Fresh source catalog binding differs')
    require(summary['code_sha256'] == digest(PROJECT/'pallet/mask_review_continuation.py'), 'Source snapshot producer code changed')
    require(digest(baseline/'independent_verification.json') == previous.QUALITY_SEAL_SHA256, 'Historical independent quality-v2 seal changed')
    seal, result = read(baseline/'independent_verification.json'), read(baseline/'result.json')
    require(seal['state'] == 'passed' and seal['result_sha256'] == digest(baseline/'result.json')
        and seal['source_catalog_sha256'] == digest(baseline/'private/source_catalog.jsonl'), 'Historical source seal binding differs')
    for name, expected in result['output_artifacts'].items():
        require(digest(member(baseline, name)) == expected, 'Historical quality artifact changed: '+name)
    for name, expected in {**seal['code_sha256'], **seal['frozen_code_sha256'], **previous.FROZEN_INTERFACE_PINS, **HELPER_PINS}.items():
        require(digest(member(PROJECT, name)) == expected, 'Frozen source/qualification/helper code changed: '+name)
    old_pose = sources.read_store(baseline/'private/pose_snapshot.sqlite3', 'pose', True)
    old_gallery = sources.read_store(baseline/'private/gallery_snapshot.sqlite3', 'gallery', True)
    pose = sources.read_store(snapshot/'private/pose_snapshot.sqlite3', 'pose', True)
    gallery = sources.read_store(snapshot/'private/gallery_snapshot.sqlite3', 'gallery', True)
    equal(pose, old_pose, 'all_original_pose_fields_and_raw_history_unchanged')
    require((len(pose['current']), len(pose['events']), len(old_gallery['current']), len(old_gallery['events']),
        len(gallery['current']), len(gallery['events'])) == (4946, 11926, 1002, 1088, 1012, 1115), 'Exact current/historical source denominator differs')
    for kind, store in (('pose', old_pose), ('gallery', old_gallery)):
        equal(store['fingerprint'], seal['source_fingerprints'][kind], 'historical_quality_fingerprint_'+kind)
        equal(store['fingerprint'], result['source_fingerprints'][kind], 'historical_result_fingerprint_'+kind)
    for kind, path, store in (('pose', POSE, pose), ('gallery', GALLERY, gallery)):
        equal(sources.read_store(path, kind), store, 'fresh_preactivation_live_store_'+kind)
        for key in store['current']:
            sources.exact_latest(store, key)
    formal, rows, frames = sources.load_formal(parent_manifest)
    evidence = sources.NativeEvidence(formal, rows, frames)
    publications, registry, task_pins = sources.registries(rows, parent_manifest['formal_manifest_sha256'], pose)
    baseline_catalog = read_jsonl(baseline/'private/source_catalog.jsonl')
    sources.check_catalog(baseline, baseline_catalog, old_pose, old_gallery, rows, publications, registry,
        parent_manifest['formal_manifest_sha256'], evidence)
    equal(result['source_summary']['task_inputs'], task_pins, 'historical_task_pins')
    equal(result['source_summary']['publication_inputs'], {str(v): {f: p[f] for f in
        ('manifest_sha256', 'proposals_sha256', 'verification_sha256')} for v, p in publications.items()}, 'historical_publication_pins')
    registry, previous_staged, previous_tasks, extra_manifests = extend_under50_registry(previous_root, rows,
        parent_manifest['formal_manifest_sha256'], pose, publications[15], registry, evidence)
    extension = check_revision_extension(old_gallery, gallery, previous_tasks)
    require(len(extension['changed_baseline_current_keys']) == 14 and extension['appended_gallery_events'] == 27,
        'Expected27 appended events:17 revisions of14 old images plus10 real newly completed images')
    catalog, references = check_fresh_catalog(snapshot, baseline_catalog, pose, gallery, rows, publications,
        registry, parent_manifest['formal_manifest_sha256'], evidence)
    check_completed_previous_tasks(gallery, old_gallery, previous_tasks, registry, references)
    require(digest(EARLIER_SNAPSHOT/'audit.json') == EARLIER_AUDIT_SHA256, 'Earlier1105-event source audit was not preserved')
    earlier_pose = sources.read_store(EARLIER_SNAPSHOT/'private/pose_snapshot.sqlite3', 'pose', True)
    earlier_gallery = sources.read_store(EARLIER_SNAPSHOT/'private/gallery_snapshot.sqlite3', 'gallery', True)
    equal(earlier_pose, pose, 'earlier_pose_fields_preserved')
    require(len(earlier_gallery['current']) == 1002 and len(earlier_gallery['events']) == 1105, 'Earlier snapshot denominator differs')
    later_extension = check_revision_extension(earlier_gallery, gallery, previous_tasks)
    require(later_extension['appended_gallery_events'] == 10 and not later_extension['changed_baseline_current_keys'],
        'Latest snapshot must add only the ten real saves after the1105-event snapshot')
    registry_manifests = {f'v{n}': digest(PROJECT/f'outputs/pallet_mask_preannotated_requests_v{n}/manifest.json') for n in (1, 2, 3)}
    registry_manifests.update(extra_manifests)
    trained_changes = check_trained_revisions(TRAINING_RECORDS, baseline_catalog, extension['changed_baseline_current_keys'])
    require(len(trained_changes) == 3, 'Expected three frozen training references with later human revisions')
    check_source_claims(summary, catalog, pose, gallery, extension, registry_manifests, trained_changes)
    for name in ('private', 'private/pose_snapshot.sqlite3', 'private/gallery_snapshot.sqlite3', 'private/source_catalog.jsonl'):
        require((snapshot/name).stat().st_mode & 0o077 == 0, 'Fresh source evidence is not private: '+name)
    return dict(baseline_seal=seal, summary=summary, formal=formal, rows=rows, evidence=evidence,
        pose=pose, gallery=gallery, catalog=catalog, extension=extension, previous_staged=previous_staged,
        previous_tasks=previous_tasks, trained_reference_keys_with_newer_human_revision=trained_changes)


def check_count_basis(catalog, inputs, manifest):
    require(len(catalog) == len({r['target_key'] for r in catalog}) == len({r['row']['frame_id'] for r in catalog}) == 1494,
        '1494 distinct actual saved research contours required')
    counts = Counter(r['row']['final_class_id'] for r in catalog)
    require(set(counts) == set(range(1, 23)) and all(type(c) is int for c in counts), 'All22 actual class counts required')
    require(tuple(c for c in range(1, 23) if counts[c] < 50) == CLASSES
        and {c: counts[c] for c in CLASSES} == EXPECTED_COUNTS, 'Refreshed under50 counts differ after the ten real saves')
    equal(inputs['actual_class_counts'], {str(c): n for c, n in counts.items()}, 'current_all22_human_counts')
    equal(inputs['actual_counted_saved_basis'], 1494, 'real_saved1494_not_stale1484_or_machine1550')
    equal(manifest['actual_human_saved_counts_before'], inputs['actual_class_counts'], 'manifest_current_human_counts')
    for value in (inputs, manifest):
        equal(value['maximum_issued_per_class'], 2, 'pilot_class_maximum')
        equal(value['target_per_class_this_pilot'], 50, 'pilot_target')
        equal(value['class_scope'], previous.CLASS_SCOPE, 'real_saved_under50_scope')
    equal(inputs['shortlisted_classes'], list(CLASSES), 'staged_class_scope')
    equal(manifest['filter_classes'], list(CLASSES), 'page_filter_scope')
    return counts


def check_public(root, manifest, proposals):
    """V2 uses the refreshed counts; do not mutate the sealed v1 page validator."""
    allowed = {'report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'}
    for proposal in proposals:
        for folder, ext in (('images', 'png'), ('cases', 'png'), ('masks', 'png'), ('labelme', 'json')):
            allowed.add(f'{folder}/{proposal["target_key"]}.{ext}')
    require(set(manifest['public_assets']) == allowed, 'Public asset allowlist differs')
    for name, expected in manifest['public_assets'].items():
        require(digest(member(root, name)) == expected, 'Public asset hash differs: '+name)
    page = member(root, 'report_zh.html').read_text(encoding='utf-8')
    require(all(text in page for text in ('少于50', '真实人工轮廓', '每类最多2张', '第15版', '已预标注', '保存前不计覆盖',
        '不自动确认GT、训练或机器人资格', '有效四点保持四点', '不为传播模板强行增点')), 'Report omits under50/draft-only scope')
    require('第三批' not in page and not any(token in page for token in ('existing_pose_current_payload', 'current_payload_raw',
        'human_event_payload_raw', 'access_key', 'access_code', 'selected_faces', 'ruler', 'fetch(')), 'Private payload/old-batch label in report')
    require(all(f'Class {c}：{EXPECTED_COUNTS[c]}份' in page for c in CLASSES), 'Report uses stale counts before the ten real saves')
    parsed = previous.PageInventory(page)
    equal(parsed.articles, [(f'target-{p["target_key"]}', str(p['class_id'])) for p in proposals], 'public_target_cards')
    equal(parsed.options, ['']+[str(c) for c in CLASSES], 'under50_filter_scope')
    require(all(name in allowed for name in parsed.assets), 'Private/unallowlisted/external report asset')
    from fontTools.ttLib import TTFont
    with TTFont(member(root, 'report-font.otf')) as font:
        require({ord(c) for c in page if '\u3400' <= c <= '\u9fff'} <= set(font.getBestCmap()), 'Chinese glyph missing')
    require(digest(root/'FONT_LICENSE.txt') == digest(PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt'), 'Font license differs')
    return allowed


def check_refresh_receipt(root, inputs):
    backup = root/'internal/input_manifest_before_real10_completion.json'
    require(inputs['previous_staging_evidence_sha256'] == digest(backup), 'Pre-completion staging receipt not preserved')
    old = read(backup)
    equal(old['actual_counted_saved_basis'], 1484, 'genuine_before_completion1484_receipt')
    equal(inputs['previous10_actual_completed_saves_at_refresh'], 10, 'ten_real_saved_tasks_at_refresh')
    for field in ('formal_manifest_sha256', 'formal_protected', 'configuration_sha256', 'shortlist_sha256',
            'prior_request_inventories_sha256', 'shortlisted_classes', 'maximum_issued_per_class', 'class_scope'):
        equal(inputs[field], old[field], 'refresh_preserved_staging_identity.'+field)
    equal(old['continuation_source_audit_sha256'], EARLIER_AUDIT_SHA256, 'before_completion_source_audit')
    equal(inputs['continuation_source_audit_sha256'], SOURCE_AUDIT_SHA256, 'after_completion_source_audit')


def check_source_binding(inputs, manifest, snapshot=SNAPSHOT):
    expected = digest(snapshot/'audit.json')
    require(expected == SOURCE_AUDIT_SHA256, 'Unrecognized continuation source audit bytes')
    equal(inputs['source_audit_sha256'], expected, 'explicit_fresh_audit_json_binding')
    if 'source_audit_sha256' in manifest:
        equal(manifest['source_audit_sha256'], expected, 'manifest_fresh_audit_json_binding')
    # The old seal may identify historical evidence, never the fresh snapshot.
    if 'source_quality_audit_sha256' in inputs:
        equal(inputs['source_quality_audit_sha256'], previous.QUALITY_SEAL_SHA256, 'historical_quality_seal_not_fresh_audit')


def audit(root=ROOT, parent=PARENT, snapshot=SNAPSHOT):
    root, parent, snapshot = Path(root), Path(parent), Path(snapshot)
    before = inventory(root)
    require(not set(SEALS) & before.keys(), 'Preserve existing v2 seals')
    manifest, inputs, parent_manifest = read(root/'manifest.json'), read(root/'input_manifest.json'), read(parent/'manifest.json')
    old_roots = previous.old_evidence_roots(PROJECT, root, parent, QUALITY, inputs['prior_request_inventories_sha256']) | {PREVIOUS, snapshot, EARLIER_SNAPSHOT}
    old_before = {str(path.relative_to(PROJECT)): inventory(path) for path in sorted(old_roots)}
    configuration = inventory(PROJECT/'configs')
    code = {name: digest(member(PROJECT, name)) for name in (
        'scripts/build_mask_under50_requests_v2.py', 'scripts/verify_mask_under50_requests_v2.py',
        'tests/test_verify_mask_under50_requests_v2.py', 'pallet/mask_review_continuation.py',
        *previous.FROZEN_INTERFACE_PINS, *HELPER_PINS)}
    training_before = digest(TRAINING_RECORDS)
    for name, expected in previous.PARENT_PINS.items():
        require(digest(parent/name) == expected, 'Pinned publication15 changed: '+name)
    parent_seal = read(parent/'verification.json')
    require(parent_seal['state'] == 'passed' and parent_seal['publication_version'] == 15, 'Independent publication15 required')
    for field, name in (('parent_manifest_sha256', 'manifest.json'), ('parent_proposals_sha256', 'proposals.jsonl'),
            ('parent_verification_sha256', 'verification.json')):
        require(manifest[field] == digest(parent/name), 'New task parent binding differs')
    equal(manifest['parent_directory'], str(parent.relative_to(PROJECT)), 'parent_directory')
    for field, name in (('input_manifest_sha256', 'input_manifest.json'), ('proposals_sha256', 'proposals.jsonl'),
            ('requests_sha256', 'requests.jsonl'), ('decisions_sha256', 'internal/build_decisions.json')):
        require(manifest[field] == digest(root/name), 'Task source/decision/geometry binding differs: '+name)
    require(inputs['shortlist_sha256'] == digest(root/'internal/shortlist.jsonl'), 'Own staged shortlist changed')
    check_source_binding(inputs, manifest, snapshot)
    check_refresh_receipt(root, inputs)
    context = check_sources(snapshot, parent_manifest)
    formal, rows, evidence = (context[field] for field in ('formal', 'rows', 'evidence'))
    pose, gallery, catalog = (context[field] for field in ('pose', 'gallery', 'catalog'))
    for value in (inputs['configuration_sha256'], context['summary']['configuration_sha256'], context['baseline_seal']['configuration_sha256']):
        equal(configuration, value, 'unchanged_global_configs')
    counts = check_count_basis(catalog, inputs, manifest)
    protected = sources.protected_inventory(formal)
    require(len(protected) == 20768 and protected == inputs['formal_protected'] == read(parent/'protected_formal_after.json')
        == read(QUALITY/'private/protected_formal_before.json'), 'All20768 frozen formal files differ')
    for value in (inputs['formal_manifest_sha256'], manifest['formal_manifest_sha256']):
        equal(value, parent_manifest['formal_manifest_sha256'], 'fixed_formal_manifest')
    fingerprints = {str(path.relative_to(PROJECT)): previous.database_fingerprint(path) for path in (POSE, GALLERY)}
    equal(inputs['database_fingerprints'], fingerprints, 'fresh_preactivation_raw_store_fingerprints')
    prior_hashes, prior_keys = previous.prior_inspections(PROJECT, root, rows)
    equal(inputs['prior_request_inventories_sha256'], prior_hashes, 'all_old_requests_and_rejected_shortlists')
    require(context['previous_staged'] <= prior_keys, 'Some of the18 previous inspected images were not excluded')
    parent_proposals = read_jsonl(parent/'proposals.jsonl')
    require(len(parent_proposals) == len({p['source']['frame_id'] for p in parent_proposals}) == 1550, 'All1550 canonical frames remain protected')
    from pallet.mask_template_refined import QUARANTINE
    require(not set(QUARANTINE) & {r['target_key'] for r in catalog}, 'Quarantined source resurrected')
    forbidden = previous.protected_keys(rows, pose, gallery, catalog, parent_proposals, prior_keys, QUARANTINE)
    staged = read_jsonl(root/'internal/shortlist.jsonl'); decisions = read(root/'internal/build_decisions.json')['decisions']
    records, image_hashes = previous.check_staged(root, staged, decisions, rows, formal, evidence, pose, forbidden)
    proposals, tasks = read_jsonl(root/'proposals.jsonl'), read_jsonl(root/'requests.jsonl')
    issued_counts, deferred = previous.check_issued_inventory(proposals, tasks, staged, decisions, manifest, counts)
    equal(read(root/'internal/deferred_sources.json'), deferred, 'all_withheld_sources')
    for proposal, task in zip(proposals, tasks):
        key = proposal['target_key']; record = records[key]; image_sha = digest(member(formal, rows[key]['image']))
        previous.check_draft(proposal, task, record, decisions[key], manifest['formal_manifest_sha256'], digest(root/'input_manifest.json'), image_sha)
        previous.check_exports(root, proposal, record, image_sha)
    check_public(root, manifest, proposals)
    require(not any(path.suffix.lower() in ('.db', '.sqlite', '.sqlite3') for path in root.rglob('*')), 'Private store copied into worklist')
    equal(manifest['schema'], 'preannotated_mask_worklist_v1', 'request_schema')
    for field in ('assistant_drafts_not_counted_as_completed', 'strict_registration_gates_not_relaxed', 'source_stores_preserved',
            'old_publications_and_tasks_not_modified', 'training_snapshot_not_modified'):
        equal(manifest[field], True, field)
    equal(inputs['all_prior_inspected_sources_excluded'], True, 'all_previous_inspections_excluded')
    equal(manifest['template_transfer_used'], False, 'not_template_transfer')
    for field in ('production_annotation_writes', 'human_events_created', 'configuration_writes'):
        equal(manifest[field], 0, field)
    require(manifest['generation_code_sha256'] == code['scripts/build_mask_under50_requests_v2.py']
        and manifest['reused_exporter_code_sha256'] == previous.FROZEN_INTERFACE_PINS['scripts/build_mask_preannotated_requests_v3.py'], 'Actual v2 generator/frozen exporter binding differs')
    require(inventory(root) == before and inventory(PROJECT/'configs') == configuration
        and sources.protected_inventory(formal) == protected, 'New pack/config/formal files changed during audit')
    for kind, path, frozen in (('pose', POSE, pose), ('gallery', GALLERY, gallery)):
        equal(sources.read_store(path, kind), frozen, 'fresh_preactivation_source_changed_during_audit_'+kind)
        require(previous.database_fingerprint(path) == fingerprints[str(path.relative_to(PROJECT))], 'Live store changed during audit')
    require(previous.prior_inspections(PROJECT, root, rows)[0] == prior_hashes, 'Prior inspection inventory changed during audit')
    for name, expected in evidence.used.items():
        require(digest(member(formal, name)) == expected, 'Used native source changed during audit')
    for name, expected in code.items():
        require(digest(member(PROJECT, name)) == expected, 'Generator/verifier/interface code changed during audit')
    for name, expected in old_before.items():
        require(inventory(PROJECT/name) == expected, 'Old task/evidence root changed during audit')
    require(digest(TRAINING_RECORDS) == training_before, 'Frozen original training records changed during audit')
    return dict(state='passed', request_count=len(proposals), class_counts=dict(issued_counts), filter_classes=list(CLASSES),
        public_assets=manifest['public_assets'], requests_sha256=digest(root/'requests.jsonl'), proposals_sha256=digest(root/'proposals.jsonl'),
        manifest_sha256=digest(root/'manifest.json'), preannotations_verified=True, formal_manifest_sha256=manifest['formal_manifest_sha256'],
        parent_proposals_sha256=digest(parent/'proposals.jsonl'), parent_verification_sha256=digest(parent/'verification.json'),
        parent_pins=previous.PARENT_PINS, historical_quality_seal_sha256=previous.QUALITY_SEAL_SHA256,
        source_audit_sha256=digest(snapshot/'audit.json'), source_audit_independently_verified=True,
        source_audit_directory=str(snapshot.relative_to(PROJECT)), source_catalog_sha256=digest(snapshot/'private/source_catalog.jsonl'),
        input_manifest_sha256=digest(root/'input_manifest.json'), decisions_sha256=digest(root/'internal/build_decisions.json'),
        shortlist_sha256=digest(root/'internal/shortlist.jsonl'), actual_human_saved_sources=1494, actual_class_counts=dict(counts),
        previous_under50_completed_requests=10, previous_under50_request_count=10, previous_under50_human_polygons_changed=10,
        all18_previous_staged_images_excluded=True,
        previous_under50_pins=PREVIOUS_PINS, maximum_issued_per_class=2, maximum_staged_per_class=3, class_scope=previous.CLASS_SCOPE,
        own_staged_source_count=len(staged), withheld_source_count=len(deferred), all_prior_inspected_sources_excluded=True,
        prior_request_inventories_sha256=prior_hashes, preactivation_database_fingerprints=fingerprints,
        source_fingerprints=dict(pose=pose['fingerprint'], gallery=gallery['fingerprint']), **context['extension'],
        all_current_pose_records_preserved=4946, all_pose_events_preserved=11926, gallery_contours_verified=1012, gallery_events_verified=1115,
        trained_reference_keys_with_newer_human_revision=context['trained_reference_keys_with_newer_human_revision'],
        frozen_training_records_sha256=training_before, frozen_training_references_not_rewritten=True,
        configuration_sha256=configuration, protected_formal_files=20768, fixed_formal_targets=12344,
        protected_formal_inventory_sha256=sha(protected), old_root_inventory_sha256={name: sha(value) for name, value in old_before.items()},
        output_inventory_sha256=sha(before), code_sha256=code, verification_script_sha256=digest(__file__),
        frozen_code_sha256=context['baseline_seal']['frozen_code_sha256'], distinct_staged_native_image_hashes=len(image_hashes),
        distinct_native_image_hashes=len(proposals), topology_counts=dict(Counter(p['vertex_count'] for p in proposals)),
        assistant_direct_annotation_not_template_transfer=True, original_rectangle_not_used_as_preannotation=True,
        original_native_quality_gates_unchanged=True, all_actual_polygons_before_publication=True,
        assistant_drafts_not_counted_as_completed=True, production_annotation_writes=0, human_events_created=0, configuration_writes=0,
        semantic_contour_accuracy_established=False, human_inspection_independently_observed=False,
        limitations=['Passing certifies raw event provenance, exact latest revisions, native exports and preservation, not contour accuracy or GT.',
            'Of27 appended events,17 revise14 old v3 images and10 are first real changed human saves of the ten under50-v1 tasks.',
            'Baseline gallery current rows legitimately changed; their old raw revisions remain recoverable in the preserved event prefix.',
            'Full/crop visual inspection is assistant-reported, not independently observed by this numerical audit.',
            'Three frozen training references now have newer research revisions; existing training labels are not rewritten or declared current.',
            'Four-point contours are permitted without forced vertices or old strict propagation-seed qualification.',
            'No algorithm quality threshold, service activation or real editor save is authorized or tested here.',
            'This preactivation seal requires exact fresh live-store equality now; later intentional human saves can extend history.'],
        verified_at=datetime.now(timezone.utc).isoformat())


def seal(root=ROOT, *, producer_complete=False, auditor=None):
    require(producer_complete is True, 'Explicit producer completion required; do not audit unfinished staging')
    root = Path(root)
    require(not root.is_symlink() and root.is_absolute() and root == root.resolve()
        and root == PROJECT/'outputs/pallet_mask_under50_requests_v2', 'Only the exact new v2 output may receive seals')
    for name in SEALS:
        require(not (root/name).exists() and not (root/name).is_symlink(), 'Never overwrite existing verification seals')
    require((root/'manifest.json').is_file(), 'Producer manifest is not complete')
    result = (auditor or audit)(root)
    require(result.get('state') == 'passed', 'Independent continuation audit did not pass')
    raw = canonical(result)+b'\n'; owned = []
    try:
        for name in SEALS:
            path = root/name
            with path.open('xb') as stream:
                owned.append((path, os.fstat(stream.fileno()).st_ino)); os.fchmod(stream.fileno(), 0o600)
                stream.write(raw); stream.flush(); os.fsync(stream.fileno())
    except BaseException:
        for path, inode in owned:
            if not path.is_symlink() and path.exists() and path.stat().st_ino == inode:
                path.unlink()
        raise
    return result


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--producer-complete', action='store_true')
    args = parser.parse_args(); verified = seal(producer_complete=args.producer_complete)
    print(json.dumps({key: verified[key] for key in ('state', 'request_count', 'class_counts',
        'previous_under50_completed_requests', 'gallery_events_verified', 'semantic_contour_accuracy_established')}, ensure_ascii=False), flush=True)
