"""Seal the same-publication-6 saved-human extension without rerunning transfers.

The complete v1 machine audit is inherited only through its matching independent
seal, pinned code and byte-identical artifacts. Six existing saved human polygons
are checked directly against the original read-only SQLite snapshot and live
dependencies. No generation, configuration, live database or frozen file writes.
"""
from __future__ import annotations

import argparse
from collections import Counter
from contextlib import closing
from datetime import datetime, timezone
from pathlib import Path
import hashlib
import json
import sqlite3
import sys
from urllib.parse import parse_qs, urlsplit

import cv2

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from scripts import verify_mask_quota_completion as v1
from pallet.cluster_targets import digest, protected_snapshot
from pallet.mask_template_transfer import ImageEvidence, annotation_inventory
from pallet.pose_review_geometry import canonical, polygon_value

prior = v1.prior
require, sha = v1.require, v1.sha
read_json, read_jsonl, indexed = v1.read_json, v1.read_jsonl, v1.indexed
BASE = PROJECT/'outputs/pallet_mask_quota_completion_v1'
OUTPUT = PROJECT/'outputs/pallet_mask_quota_completion_v2'
DIAGNOSTIC = PROJECT/'outputs/pallet_mask_class10_completion_diagnostic_v1/existing_human_reuse.jsonl'
DIAGNOSTIC_SHA = 'e40ac5877f5c51dbc5956b70f336ae986a254982cc3fe70555a038df1dbb19b8'
ARCHIVED_METADATA = frozenset({
    'manifest.json', 'proposals.jsonl', 'manual_proposals.jsonl', 'manual_source_records.jsonl',
    'outcomes.jsonl', 'template_inventory.json', 'protected_targets.json', 'shortfalls.json',
    'report_zh.html', 'report-font.otf', 'font_coverage.json', 'snapshot_manifest.json',
    'used_image_hashes.json', 'artifact_hashes.json', 'GENERATION_HANDOFF.md',
    'generation_validation.json', 'validation_report.json', 'verification.json',
})
EXTRA_KEYS = frozenset({
    '5a50c8a3f3b203f4a73302c5', '769e10f2f395d177eee6ee8f', '77c50239649469197cae6b04',
    '82570f9f6b30bb2c1d696306', '8515501d58bc1f637a826f4b', 'b62526c40d7f972094b41bdb',
})
BASE_PINS = {
    'manifest.json': '97bf43a6eec1e3f587e645a73ce75d52833745904a05462fd4eb197e0dc7aa5a',
    'proposals.jsonl': 'e4fe0f6ed5f40c76e8c6b1fbc9e90a4b5a52543d4403e6aa1626f83f15f76dae',
    'artifact_hashes.json': '915a6f7575eb2b1a751af54f9b8789998fa5866e41b9bedcbb0b88ce6395e050',
}
CODE_PINS = {
    **v1.ORIGINAL_CODE,
    'scripts/verify_mask_quota_completion.py': '7f78496e79b62a7039ce2e817838ccfde706f926db8e5eabfa165c33e0192a27',
    'pallet/mask_quota_completion.py': '6046f7076b48ec76453b2b97f69344d730ed83b28cfadd1b8a16999a3b9fa5a1',
}


def check_base():
    publications = v1.check_frozen_inputs()
    for name, expected in CODE_PINS.items():
        require(digest(PROJECT/name) == expected, f'Frozen independently audited code changed: {name}')
    for name, expected in BASE_PINS.items():
        require(digest(BASE/name) == expected, f'Frozen v1 generation changed: {name}')
    require((BASE/'verification.json').is_file(), 'Wait for the complete v1 independent verification seal')
    manifest, seal = read_json(BASE/'manifest.json'), read_json(BASE/'verification.json')
    require(seal['state'] == 'passed' and seal['publication_version'] == manifest['publication_version'] == 6
            and seal['proposals_verified'] == manifest['proposals'] == 231
            and seal['manual_verified'] == manifest['manual_proposals'] == 24
            and seal['new_verified'] == manifest['new_proposals'] == 67
            and seal['old_canonical_objects_preserved'] == manifest['previous_proposals'] == 140,
            'v1 independent seal inventory differs')
    require(seal['proposals_sha256'] == manifest['proposals_sha256'] == BASE_PINS['proposals.jsonl']
            and seal['manifest_sha256'] == BASE_PINS['manifest.json']
            and seal['artifact_hashes_sha256'] == BASE_PINS['artifact_hashes.json']
            and seal['verification_script_sha256'] == CODE_PINS['scripts/verify_mask_quota_completion.py']
            and manifest['code_sha256'] == CODE_PINS['pallet/mask_quota_completion.py'], 'v1 independent seal/code/hash binding differs')
    require(seal['validation_report_sha256'] == digest(BASE/'validation_report.json'), 'v1 independent validation report differs')
    report = read_json(BASE/'validation_report.json')
    require(canonical(report) == canonical({k: v for k, v in seal.items() if k != 'validation_report_sha256'}),
            'v1 report is not the sealed successful audit')
    for field in ('all_new_registrations_and_metrics_recomputed', 'all_rejected_attempts_and_metrics_recomputed',
                  'manual_exact_sqlite_payloads_and_human_events_verified', 'manual_sources_not_machine_transfers',
                  'live_dependencies_unchanged', 'authorization_dependencies_unchanged'):
        require(seal[field] is True, f'v1 lacks required full independent audit: {field}')
    require(seal['method'] == manifest['method'] == 'original' and seal['thresholds_relaxed'] is False
            and seal['forced_fill'] is False and seal['human_confirmation_inferred'] is False
            and seal['production_database_writes'] == 0, 'v1 did not verify the strict original draft policy')
    artifacts = read_json(BASE/'artifact_hashes.json')
    prior.check_artifacts(BASE, artifacts)
    actual_paths = {str(p.relative_to(BASE)) for p in BASE.rglob('*') if p.is_file()
                    and str(p.relative_to(BASE)) not in ('artifact_hashes.json', 'validation_report.json', 'verification.json')}
    require(actual_paths == set(artifacts), 'v1 sealed artifact inventory coverage differs')
    require(seal['registration_attempts_verified'] == len(read_jsonl(BASE/'registration_attempts.jsonl')) == 13347
            and seal['accepted_before_diversity_recomputed'] == manifest['accepted_before_diversity'] == 144
            and seal['templates_verified'] == manifest['generation_templates'] == 175, 'v1 complete attempt/template audit counts differ')
    return dict(manifest=manifest, seal=seal, seal_sha256=digest(BASE/'verification.json'),
                artifacts=artifacts, publications=publications)


def check_inherited_files(out, artifacts):
    """Hash inheritance covers all 231 cards and every machine-attempt byte."""
    namespaces = ('cases/', 'images/', 'masks/', 'labelme/', 'templates/', 'refined/', 'generation/', 'quota_generation/', 'backups/')
    fixed = {'new_proposals.jsonl', 'accepted_candidates.jsonl', 'registration_attempts.jsonl', 'requests.jsonl',
             'reviews_snapshot.sqlite3', 'gallery_reviews_snapshot.sqlite3', 'refined_annotations.jsonl',
             'protected_formal_before.json', 'protected_formal_after.json', 'preserved_parent_assets.json',
             'vertex2_before_after.png', 'FONT_LICENSE.txt'}
    required = {name for name in artifacts if name.startswith(namespaces) or name in fixed}
    require(fixed <= required, 'v1 lacks required inherited verification evidence')
    for name in required:
        path = out/name
        require(path.is_file() and not path.is_symlink() and path.resolve().is_relative_to(out)
                and digest(path) == artifacts[name] == digest(BASE/name), f'Inherited v1 asset/evidence changed: {name}')
    return required


def check_partition(base, old, original_manual, manual, extra, machines, combined, accepted):
    require(len(base) == 231 and len(old) == 140 and len(original_manual) == 24 and len(machines) == 67,
            'Unexpected inherited inventory')
    require(set(extra) == EXTRA_KEYS and len(extra) == 6, 'Expected exactly the six approved existing saved-human targets')
    require(set(manual) == set(original_manual) | EXTRA_KEYS and len(manual) == 30
            and not (set(base) & EXTRA_KEYS), 'Manual extension overlaps or replaces prior work')
    require(set(combined) == set(base) | EXTRA_KEYS and len(combined) == 237, 'Expected cumulative 237, not a new publication batch')
    for key, proposal in base.items():
        require(canonical(proposal) == canonical(combined[key]), f'Original v1 canonical object changed: {key}')
    for key, proposal in original_manual.items():
        require(canonical(proposal) == canonical(manual[key]), f'Original 24 manual request completion changed: {key}')
    for key, proposal in extra.items():
        require(canonical(proposal) == canonical(manual[key]) == canonical(combined[key]), f'Additional manual cumulative object differs: {key}')
    require(set(manual).isdisjoint(accepted), 'Saved-human self-source treated as accepted transfer')
    v1.check_partition(old, manual, machines, combined, accepted)


def check_saved_human(proposal, direct, pose, rows, pose_sha, formal_sha, classification_sha, extra=False):
    key = proposal['target_key']
    require(key in direct and key in pose['current'] and key in rows, f'Saved human source is missing or no longer a direct human polygon: {key}')
    row, current, template = rows[key], pose['current'][key], direct[key]
    require(current.get('state') not in ('deleted', 'deferred') and proposal['source'] == row
            and proposal['class_id'] == row['final_class_id'], f'Saved-human identity/state differs: {key}')
    for field in ('target_key', 'target_id', 'frame_id', 'split', 'group_id', 'box_index', 'bbox', 'size', 'policy_id', 'source_pcd_sha256'):
        require(current['source'][field] == row[field], f'Saved-human original source {field} differs: {key}')
    require(proposal['polygon'] == current['polygon'] == template['polygon']
            and proposal['vertex_count'] == len(current['polygon']) > 4, f'Saved-human exact latest polygon/topology differs: {key}')
    polygon_value(proposal['polygon'], *row['size'])
    require(proposal['schema'] == 'saved_pose_mask_gallery_entry_v1' and proposal['origin'] == v1.POSE_ORIGIN
            and proposal['status'] == 'human_edited_draft_pending_confirmation' and proposal['human_edited'] is True
            and proposal['source_label_kind'] == 'human_mask_source_manual_template_draft'
            and proposal['pose_snapshot_saved'] is True and proposal['pose_store_written'] is False
            and proposal['gallery_store_written'] is False, f'Saved-human provenance/status/write claims differ: {key}')
    v1.no_confirmation(proposal, f'Saved human {key}')
    require('production_saved' not in proposal or proposal['production_saved'] is False, f'Saved-human claims production write: {key}')
    for flag in ('human_mask_confirmed', 'human_pose_confirmed', 'automatic_training_eligible', 'robot_command_eligible'):
        require(current[flag] is False, f'Original saved-human {flag} must remain false: {key}')
    require(not current.get('ground_truth_eligible') and 'continuation' not in proposal and proposal['metrics'] == {},
            f'Saved-human source falsely claims GT or machine transfer metrics: {key}')
    require(proposal['formal_manifest_sha256'] == formal_sha and proposal['class_assignments_sha256'] == classification_sha
            and proposal['snapshot_sha256'] == pose_sha and proposal['target_expected_revision'] == current['revision']
            and proposal['target_snapshot_payload_sha256'] == sha(current), f'Saved-human dataset/current snapshot binding differs: {key}')
    expected = dict(target_key=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=template['human_mask_confirmed'],
        origin=v1.POSE_ORIGIN, pose_review=v1.pose_provenance(template, pose_sha))
    require(proposal['template'] == expected and proposal['rendering_id'] == v1.NAMESPACE+':'+key,
            f'Saved-human honest self-source/revision/event binding differs: {key}')
    require('manual_source_not_machine_transfer' in proposal['flags'], f'Saved-human source lacks honest non-transfer flag: {key}')
    if extra:
        require(row['final_class_id'] == 10 and key in EXTRA_KEYS, 'Additional saved label is not an approved Class-10 target')
        require('manual_request_sha256' not in proposal, f'Additional existing label pretends to complete an original request: {key}')
        require(proposal['manual_source_kind'] == 'authorized_existing_human_mask_reuse'
                and proposal['machine_transfer_performed'] is False and proposal['new_human_edit_created'] is False,
                f'Additional saved label claims a new human edit or machine transfer: {key}')


def check_outcomes(base_outcomes, outcomes, extra):
    require(set(base_outcomes) == set(outcomes), 'Extension changed formal outcome coverage')
    for key, old in base_outcomes.items():
        expected = dict(old, reason='saved_human_source_added') if key in extra else old
        require(outcomes[key] == expected, f'Extension changed unrelated outcome: {key}')
        if key in extra:
            require(old['reason'] == 'human_mask_history_protected' and old['class_id'] == 10,
                    f'Additional saved-human source was not already protected human history: {key}')


def check_rendering(base_inventory, inventory, old, manual, machines, extra):
    for field in ('templates', 'generation_template_namespace', 'generation_template_keys', 'historical_templates',
                  'generation_templates_by_origin', 'generation_templates', 'eligibility', 'snapshot_saved',
                  'snapshot_events', 'gallery_snapshot_saved', 'previous_proposals'):
        require(inventory[field] == base_inventory[field], f'Extension changed frozen template/eligibility inventory: {field}')
    templates = indexed(base_inventory['templates'], 'rendering_id')
    mapping = dict(base_inventory['rendering_by_target'])
    for key in extra:
        rendering_id = v1.NAMESPACE+':'+key
        require(rendering_id in templates and templates[rendering_id]['origin'] == v1.POSE_ORIGIN,
                f'Extra saved label was not an existing v1 direct-human seed: {key}')
        mapping[key] = rendering_id
    require(inventory['rendering_by_target'] == mapping, 'Extension rendering map changed historical cards or lacks six self-sources')
    require(inventory['manual_proposals'] == 30 and inventory['counted_manual_source_keys'] == sorted(manual),
            'Extension template inventory manual counts differ')
    require(inventory['manual_supplement_keys'] == sorted(EXTRA_KEYS), 'Extension inventory supplement keys differ')
    require(set(mapping) == set(old) | set(manual) | set(machines), 'Rendering map cumulative target set differs')
    return {t['row']['target_key']: v1.previous.template_payload(t) for t in templates.values()
            if t['rendering_id'].startswith(v1.NAMESPACE+':')}


def check_source_archive(out, base):
    source_files = dict(base['artifacts'], **{
        'artifact_hashes.json': BASE_PINS['artifact_hashes.json'],
        'validation_report.json': base['seal']['validation_report_sha256'],
        'verification.json': base['seal_sha256'],
    })
    require(read_json(out/'source_generation_inventory.json') == source_files, 'Source generation full file inventory differs')
    preserved = {name: value for name, value in source_files.items() if name not in ARCHIVED_METADATA}
    require(read_json(out/'preserved_source_generation_assets.json') == preserved, 'Preserved v1 source file inventory differs')
    for name, expected in source_files.items():
        path = out/('source_generation_evidence/'+name if name in ARCHIVED_METADATA else name)
        require(path.is_file() and not path.is_symlink() and path.resolve().is_relative_to(out)
                and digest(path) == expected == digest(BASE/name), f'Frozen v1 source/archive changed: {name}')
    archived = {str(p.relative_to(out/'source_generation_evidence'))
                for p in (out/'source_generation_evidence').rglob('*') if p.is_file()}
    require(archived == set(source_files) & ARCHIVED_METADATA, 'Source generation archived metadata coverage differs')
    return source_files


def check_diagnostic(out, extra, records, snapshot):
    require(digest(DIAGNOSTIC) == DIAGNOSTIC_SHA, 'Approved saved-human diagnostic changed')
    original = read_jsonl(DIAGNOSTIC)
    exported = read_jsonl(out/'existing_human_reuse.jsonl')
    require(original == exported, 'Exported existing-human diagnostic records differ')
    diagnostic = indexed(exported)
    require(set(diagnostic) == set(extra) == EXTRA_KEYS, 'Diagnostic includes unapproved saved-human labels')
    with closing(sqlite3.connect(snapshot.resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        for key, proposal in extra.items():
            record, frozen = diagnostic[key], records[key]
            for field in ('target_key', 'class_id', 'source', 'polygon', 'vertex_count', 'template', 'snapshot_sha256',
                          'formal_manifest_sha256', 'class_assignments_sha256', 'rendering_id', 'origin'):
                require(record[field] == proposal[field], f'Diagnostic {field} differs from actual saved source: {key}')
            for field in ('current_payload', 'current_payload_raw', 'current_payload_raw_sha256', 'current_payload_sha256',
                          'human_event_id', 'human_polygon_revision', 'human_event_sha256'):
                require(record[field] == frozen[field], f'Diagnostic exact source payload/event {field} differs: {key}')
            history = [dict(id=i, revision=r, payload_raw=raw, payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest())
                       for i, r, raw in db.execute('SELECT id,revision,payload FROM events WHERE target_key=? ORDER BY id', (key,))]
            require(record['source_event_history'] == history, f'Diagnostic original full per-target event history differs: {key}')
            v1.no_confirmation(record, f'Diagnostic {key}')
            require(record['machine_transfer_performed'] is False and record['new_human_edit_created'] is False
                    and record['pose_store_written'] is False and record['gallery_store_written'] is False
                    and record['published'] is False and record['human_edited'] is True and record['metrics'] == {},
                    f'Diagnostic misrepresents existing saved work: {key}')
            require(proposal['manual_supplement_source'] == dict(schema='authorized_existing_pose_human_reuse_v1',
                    diagnostic_sha256=DIAGNOSTIC_SHA, diagnostic_record_sha256=sha(record),
                    authorization='Explicit user authorization to count these six existing saved human labels'),
                    f'Supplement diagnostic/authorization provenance differs: {key}')


def check_live_manual_records(path, records):
    """Check raw current/event bytes too, not just equal parsed JSON polygons."""
    with closing(sqlite3.connect(Path(path).resolve().as_uri()+'?mode=ro', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        db.execute('BEGIN')
        for key, record in records.items():
            current = db.execute('SELECT revision,payload FROM annotations WHERE target_key=?', (key,)).fetchall()
            event = db.execute('SELECT target_key,revision,payload FROM events WHERE id=?', (record['human_event_id'],)).fetchall()
            require(current == [(record['current_revision'], record['current_payload_raw'])]
                    and event == [(key, record['human_polygon_revision'], record['human_event_payload_raw'])],
                    f'Saved-human current/event raw SQLite bytes changed in live store: {key}')


def check_report(out, combined, manual, extra, classes):
    from fontTools.ttLib import TTFont
    page = (out/'report_zh.html').read_text()
    parsed = prior.ReportInventory()
    parsed.feed(page)
    articles = indexed(parsed.articles, 'id')
    require(set(articles) == {'target-'+k for k in combined}, 'Extension report target inventory differs')
    for key, proposal in combined.items():
        card = articles['target-'+key]
        require(card['data-class'] == str(proposal['class_id'])
                and card['data-kind'] == ('manual' if key in manual else 'machine')
                and card['data-batch'] == ('supplement' if key in extra else 'previous'), f'Extension report card identity/kind differs: {key}')
    cells = []
    for cls in v1.CLASSES:
        c = classes[str(cls)]
        cells.extend(str(x) for x in (cls, c['old_total'], c['manual_added'], c['new_candidates'], c['total'], c['missing']))
    require(parsed.cells == cells, 'Extension report manual/machine/cumulative/shortfall counters differ')
    honest = ('累计237个不同帧', '原队列24份人工描绘', '6份既有原位姿人工轮廓', '原67份严格方法机器草稿保持不变',
              '没有生成新机器候选', '没有创建新人工编辑', '已保存人工轮廓127份', '类别10累计37帧，仍缺13帧',
              '并未完成250帧目标', '不是本轮新描绘，不是机器迁移', 'id="only-supplement" checked')
    require(all(value in page for value in honest), 'Extension report conflates reused human labels, new edits, machine drafts or full completion')
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(out/'report-font.otf') as font:
        require(required <= set(font.getBestCmap()), 'Extension 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'), 'Extension font coverage evidence differs')


def check_manifest(out, manifest, base, extra):
    original = base['manifest']
    mutable = {'state', 'manual_proposals', 'manual_added', 'manual_by_class', 'base_proposals', 'base_classes',
               'proposals', 'classes', 'counted_manual_source_keys', 'outcomes', 'proposals_sha256',
               'manual_proposals_sha256', 'manual_source_records_sha256', 'template_inventory_sha256'}
    for field, expected in original.items():
        if field not in mutable:
            require(manifest[field] == expected, f'Extension modified frozen original manifest field: {field}')
    require(manifest['publication_version'] == 6 and manifest['previous_proposals'] == 140
            and manifest['proposals'] == 237 and manifest['new_proposals'] == 67
            and manifest['manual_added'] == manifest['manual_proposals'] == 30 and manifest['base_proposals'] == 170,
            'Same-publication-6 original-parent/manual/machine counters differ')
    require((PROJECT/manifest['source_generation']).resolve() == BASE.resolve()
            and manifest['source_generation_manifest_sha256'] == BASE_PINS['manifest.json']
            and manifest['source_generation_proposals_sha256'] == BASE_PINS['proposals.jsonl']
            and manifest['source_generation_verification_sha256'] == base['seal_sha256'], 'Extension source generation seal binding differs')
    require(manifest['extension_version'] == 'authorized_saved_human_quota_extension_v1'
            and manifest['extension_code_sha256'] == digest(PROJECT/'pallet/mask_quota_saved_extension.py'), 'Extension composer code provenance differs')
    require(manifest['manual_supplement_keys'] == sorted(extra) and manifest['manual_supplement_count'] == 6
            and manifest['manual_supplement_origin'] == v1.POSE_ORIGIN
            and manifest['manual_supplement_new_edits_created'] == 0
            and manifest['new_machine_proposals_generated_by_extension'] == 0 and manifest['research_candidates_added'] == 0,
            'Extension claims unauthorized new labels, transfers, or research candidates')
    require((PROJECT/manifest['manual_supplement_source']).resolve() == DIAGNOSTIC.resolve()
            and manifest['manual_supplement_source_sha256'] == DIAGNOSTIC_SHA, 'Extension approved diagnostic binding differs')
    for name, field in (('proposals.jsonl', 'proposals_sha256'), ('manual_proposals.jsonl', 'manual_proposals_sha256'),
                        ('manual_source_records.jsonl', 'manual_source_records_sha256'), ('template_inventory.json', 'template_inventory_sha256'),
                        ('manual_supplement.jsonl', 'manual_supplement_sha256'),
                        ('manual_supplement_source_records.jsonl', 'manual_supplement_source_records_sha256'),
                        ('source_generation_inventory.json', 'source_generation_inventory_sha256')):
        require(digest(out/name) == manifest[field], f'Extension artifact binding differs: {name}')


def audit(out, pose_live, gallery_live):
    verifier_sha, config_hashes = digest(__file__), v1.configuration_hashes()
    pose_config, gallery_config = (read_json(PROJECT/'configs'/name) for name in ('active_pose_review.json', 'active_mask_gallery.json'))
    require(Path(pose_live).resolve() == (PROJECT/pose_config['database']).resolve()
            and Path(gallery_live).resolve() == (PROJECT/gallery_config['review_directory']/'mask_reviews.sqlite3').resolve(),
            'Live inputs must be the configured production review stores')
    base = check_base()
    manifest, artifacts = read_json(out/'manifest.json'), read_json(out/'artifact_hashes.json')
    artifact_inventory_sha = digest(out/'artifact_hashes.json')
    prior.check_artifacts(out, artifacts)
    paths = {str(p.relative_to(out)) for p in out.rglob('*') if p.is_file()
             and str(p.relative_to(out)) not in ('artifact_hashes.json', 'validation_report.json')}
    require(paths == set(artifacts), 'Extension artifact inventory coverage differs')
    inherited_files = check_inherited_files(out, base['artifacts'])
    source_files = check_source_archive(out, base)
    base_proposals = indexed(read_jsonl(BASE/'proposals.jsonl'))
    old = base['publications'][5]['proposals']
    original_manual = indexed(read_jsonl(BASE/'manual_proposals.jsonl'))
    manual, extra, machines, combined, accepted = (indexed(read_jsonl(out/name)) for name in
        ('manual_proposals.jsonl', 'manual_supplement.jsonl', 'new_proposals.jsonl', 'proposals.jsonl', 'accepted_candidates.jsonl'))
    check_partition(base_proposals, old, original_manual, manual, extra, machines, combined, accepted)
    check_manifest(out, manifest, base, extra)
    extension_sha = manifest['extension_code_sha256']
    require(set(extra).isdisjoint(v1.indexed(read_jsonl(out/'requests.jsonl'))), 'The six existing labels must not become fake original worklist requests')
    formal = Path(read_json(PROJECT/'configs/active_formal_dataset.json')['dataset']).resolve()
    classification = PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'
    formal_sha, classification_sha = digest(formal/'manifest.json'), digest(classification)
    require(formal_sha == manifest['formal_manifest_sha256'] and classification_sha == manifest['classification_sha256'], 'Original formal/classification hashes changed')
    protected = read_json(BASE/'protected_formal_before.json')
    require(protected_snapshot(formal) == protected, 'Protected original formal files changed')
    rows, sources = prior.formal_rows(formal, classification)
    snapshots = prior.find_snapshots(out, manifest)
    frozen = {kind: prior.read_store(path, kind, frozen=True) for kind, path in snapshots.items()}
    pose, gallery = frozen['pose'], frozen['gallery']
    pose_sha, gallery_sha = digest(snapshots['pose']), digest(snapshots['gallery'])
    require(len(pose['current']) == 4758 and len(pose['events']) == 10290
            and len(gallery['current']) == 97 and len(gallery['events']) == 104, 'Extension must reuse the exact completed v1 snapshots')
    require(json.loads(pose['metadata']['binding'])['formal_manifest_sha256'] == formal_sha
            and gallery['metadata']['formal_manifest_sha256'] == formal_sha, 'Extension original review dataset binding differs')
    snapshot_manifest = read_json(out/'snapshot_manifest.json')
    expected_snapshot_manifest = read_json(BASE/'snapshot_manifest.json')
    expected_snapshot_manifest['manual_supplement'] = dict(keys=sorted(EXTRA_KEYS), count=6,
        origin=v1.POSE_ORIGIN, new_human_edit_created=False,
        diagnostic_source=str(DIAGNOSTIC.relative_to(PROJECT)), diagnostic_sha256=DIAGNOSTIC_SHA)
    require(snapshot_manifest == expected_snapshot_manifest, 'Extension snapshot manifest changed original snapshots/publications/24 requests')
    direct = v1.independent_pose_templates(pose, rows)
    status = prior.pose_status(pose, rows)
    with closing(sqlite3.connect(snapshots['pose'].resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        reference_current, reference_templates, reference_status = annotation_inventory(db, rows)
    require(direct == reference_templates and status == reference_status and pose['current'] == reference_current,
            'Independent exact human-event/template/status recovery differs from pinned original reference')
    requests = indexed(read_jsonl(out/'requests.jsonl'))
    require(len(requests) == 24 and set(requests) == set(original_manual), 'Original manual worklist/completion inventory differs')
    allowed_origins = {urlsplit(p['original_pose_url']).netloc for p in original_manual.values()}
    for key, proposal in manual.items():
        check_saved_human(proposal, direct, pose, rows, pose_sha, formal_sha, classification_sha, extra=key in extra)
        if key in original_manual:
            v1.check_manual(proposal, requests[key], pose, direct, rows[key], pose_sha, formal_sha, classification_sha)
        url = urlsplit(proposal['original_pose_url'])
        require(url.scheme == 'https' and url.netloc in allowed_origins and parse_qs(url.query).get('target') == [key],
                f'Saved-human original pose URL does not identify the actual source target: {key}')
    v1.check_manual_records(out, manual, snapshots['pose'], pose_sha)
    records = indexed(read_jsonl(out/'manual_source_records.jsonl'))
    supplement_records = indexed(read_jsonl(out/'manual_supplement_source_records.jsonl'))
    require(supplement_records == {k: records[k] for k in extra}, 'Six supplemental raw source freezes differ from all-30 record inventory')
    original_records = indexed(read_jsonl(BASE/'manual_source_records.jsonl'))
    require(all(records.get(k) == value for k, value in original_records.items()), 'Original 24 exact source/event freezes changed')
    check_diagnostic(out, extra, records, snapshots['pose'])
    inventory = read_json(out/'template_inventory.json')
    templates = check_rendering(read_json(BASE/'template_inventory.json'), inventory, old, manual, machines, extra)
    require(len(templates) == 175, 'Extension must not add or remove templates')
    for key in extra:
        require(templates[key] == dict(direct[key], origin=v1.POSE_ORIGIN,
                pose_review=v1.pose_provenance(direct[key], pose_sha)), f'Existing direct-human seed differs from original saved polygon: {key}')
    evidence = ImageEvidence(formal, rows, sources)
    for key, proposal in extra.items():
        v1.check_assets(out, proposal, rows[key], evidence, manual=True)
    outcomes = indexed(read_jsonl(out/'outcomes.jsonl'))
    check_outcomes(indexed(read_jsonl(BASE/'outcomes.jsonl')), outcomes, extra)
    classes, counts = v1.expected_counts(old, manual, machines, gallery)
    base_classes, _ = v1.expected_counts(old, manual, {}, gallery)
    require(manifest['base_classes'] == base_classes, 'Same-publication historical-plus-30-human base counts differ')
    require({c: v['total'] for c, v in classes.items()} == {'1': 50, '2': 50, '9': 50, '10': 37, '15': 50}, 'Expected per-class distinct-frame counts 50/50/50/37/50')
    for cls, values in classes.items():
        inherited = base['manifest']['classes'][cls]
        values.update({field: inherited[field] for field in ('templates', 'eligible', 'compatible_targets')})
        values.update(preview=values['total'], outcomes=dict(Counter(v['reason'] for v in outcomes.values() if v['class_id'] == int(cls))))
    require(manifest['classes'] == inventory['classes'] == classes and manifest['outcomes'] == dict(Counter(v['reason'] for v in outcomes.values())),
            'Extension independently recounted class/outcome inventory differs')
    require(manifest['counted_manual_source_keys'] == sorted(manual)
            and manifest['manual_by_class'] == {str(c): n for c, n in Counter(p['class_id'] for p in manual.values()).items()},
            'Extension all-30 manual key/class counts differ')
    protected_targets = read_json(BASE/'protected_targets.json')
    protected_targets.update(counted_manual_source_keys=sorted(manual), manual_supplement_keys=sorted(EXTRA_KEYS))
    require(read_json(out/'protected_targets.json') == protected_targets, 'Extension changed unrelated protection/eligibility policy')
    shortfalls = read_json(out/'shortfalls.json')
    require(set(shortfalls) == set(classes), 'Extension shortfall class coverage differs')
    for cls, values in classes.items():
        require(shortfalls[cls]['missing'] == values['missing'] and shortfalls[cls]['outcomes'] == values['outcomes'], f'Class {cls} shortfall report differs')
    check_report(out, combined, manual, extra, classes)
    used = read_json(out/'used_image_hashes.json')
    for name, expected in {**read_json(BASE/'used_image_hashes.json'), **evidence.used}.items():
        require(used.get(name) == expected, f'Inherited/extra original source image hash missing: {name}')
    for name, expected in used.items():
        path = (formal/name).resolve()
        require(path.is_relative_to(formal) and digest(path) == expected, f'Original source image changed: {name}')
    require(protected_snapshot(formal) == protected and digest(classification) == classification_sha, 'Original formal/classification changed during extension audit')
    prior.check_artifacts(out, artifacts)
    require(digest(out/'artifact_hashes.json') == artifact_inventory_sha, 'Extension artifact inventory changed during audit')
    require(digest(PROJECT/'pallet/mask_quota_saved_extension.py') == extension_sha and digest(DIAGNOSTIC) == DIAGNOSTIC_SHA,
            'Extension composer or approved diagnostic changed during audit')
    final_base = check_base()
    require(final_base['seal_sha256'] == base['seal_sha256'], 'v1 independent verification changed during extension audit')
    live = {'pose': prior.read_store(pose_live, 'pose'), 'gallery': prior.read_store(gallery_live, 'gallery')}
    v1.check_live_dependencies(frozen, live, templates, accepted, manual, rows)
    check_live_manual_records(pose_live, records)
    require(v1.configuration_hashes() == config_hashes, 'Live configuration/authorization dependencies changed during extension audit')
    require(digest(__file__) == verifier_sha, 'Independent extension verifier changed during audit')
    return dict(state='passed', publication_version=6, proposals_verified=237, new_verified=67, manual_verified=30,
        manual_added=30, original_requested_manual_verified=24, extra_saved_human_verified=6,
        old_canonical_objects_preserved=140, source_generation_canonical_objects_preserved=231,
        proposals_sha256=manifest['proposals_sha256'], new_proposals_sha256=manifest['new_proposals_sha256'],
        manual_proposals_sha256=manifest['manual_proposals_sha256'], manifest_sha256=digest(out/'manifest.json'),
        artifact_hashes_sha256=artifact_inventory_sha, classes=counts, method='original',
        source_generation=str(BASE.relative_to(PROJECT)), source_generation_verification_sha256=base['seal_sha256'],
        source_generation_manifest_sha256=BASE_PINS['manifest.json'], source_generation_proposals_sha256=BASE_PINS['proposals.jsonl'],
        original_registration_audit_inherited=True, inherited_registration_attempts_verified=base['seal']['registration_attempts_verified'],
        inherited_accepted_before_diversity_verified=144, inherited_source_generation_files_verified=len(source_files),
        inherited_assets_and_machine_evidence_verified=len(inherited_files), registrations_recomputed_by_extension=0,
        templates_verified=175, template_pool_unchanged=True, machine_sidecar_unchanged=True,
        manual_exact_sqlite_payloads_and_human_events_verified=True, manual_sources_not_machine_transfers=True,
        original_24_requests_preserved=True, no_synthetic_manual_requests=True, new_human_edits_created=0,
        research_candidates_added=0, new_machine_proposals_generated_by_extension=0,
        thresholds_relaxed=False, forced_fill=False, human_confirmation_inferred=False,
        ground_truth_eligible=False, automatic_training_eligible=False, robot_command_eligible=False,
        production_database_writes=0, manual_snapshots_not_imported_into_gallery_store=True,
        original_events_preserved={'pose': 10290, 'gallery': 104}, pose_snapshot_sha256=pose_sha, gallery_snapshot_sha256=gallery_sha,
        live_dependencies_unchanged=True, authorization_dependencies_unchanged=True,
        extra_public_images=['vertex2_before_after.png'], verification_script_sha256=verifier_sha,
        verified_at=datetime.now(timezone.utc).isoformat())


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, default=OUTPUT)
    parser.add_argument('--pose-live', type=Path, default=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3')
    parser.add_argument('--gallery-live', type=Path, default=PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3')
    args = parser.parse_args(argv)
    out = args.output.resolve()
    require(not OUTPUT.is_symlink() and out == OUTPUT.absolute() and out.is_dir(), 'Use the completed publication-6 v2 outputs directory only')
    require(out not in {BASE.resolve(), v1.PARENT.resolve(), v1.previous.PARENT.resolve(), prior.PARENT.resolve()},
            'Cannot verify over a frozen source/publication')
    require(not (out/'verification.json').exists(), 'Refusing to overwrite a frozen verification')
    require((out/'manifest.json').is_file(), 'Composition is not complete: manifest.json missing')
    require(not (out/'validation_report.json').is_symlink() and not (out/'verification.json').is_symlink(), 'Unsafe verification/report path')
    cv2.setNumThreads(1)
    try:
        result = audit(out, args.pose_live, args.gallery_live)
    except Exception as exc:
        report = dict(state='failed', publication_version=6, error_type=type(exc).__name__, error=str(exc),
                      verification_script_sha256=digest(__file__))
        (out/'validation_report.json').write_bytes(canonical(report)+b'\n')
        raise
    (out/'validation_report.json').write_bytes(canonical(result)+b'\n')
    result['validation_report_sha256'] = digest(out/'validation_report.json')
    with (out/'verification.json').open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    print(json.dumps(result, ensure_ascii=False), flush=True)


if __name__ == '__main__':
    main()
