"""Independent, read-only audit of publication-12's next direct-human worklist.

No round-2 builder/generator is imported or patched. The frozen original native
quality gate is reused, but identities, history exclusions, source accounting,
review chains and pixels are checked here. Only two new, identical independent
seals may be written, and only after the complete audit succeeds.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from contextlib import closing
from datetime import datetime, timezone
import hashlib
from html.parser import HTMLParser
import json
import math
import os
from pathlib import Path
import re
import sys
from urllib.parse import urlsplit

import numpy as np
from PIL import Image, ImageDraw

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from pallet.cluster_targets import digest, protected_snapshot, target_key
from pallet.mask_quota_saved_extension import file_inventory, load_formal_evidence
from pallet.mask_remaining_classes import original_rectangle
from pallet.mask_template_refined import QUARANTINE, read_jsonl, readonly, verify_history_preserved
from pallet.mask_template_transfer import AUTO_EVENTS, rectangle
from pallet.pose_review_geometry import canonical
from scripts.build_mask_template_requests import database_fingerprint, native_quality

CLASSES = (4, 5, 7, 14, 22)
DEFAULT = PROJECT/'outputs/pallet_mask_remaining_round2_requests_v1'
PARENT = PROJECT/'outputs/pallet_mask_remaining_round2_v1'
FLAGS = ('human_mask_confirmed', 'human_pose_confirmed', 'metric_pose_confirmed',
    'human_confirmed', 'ground_truth_eligible', 'automatic_training_eligible', 'robot_command_eligible')
IDENTITY = ('target_key', 'target_id', 'frame_id', 'box_index', 'bbox', 'size',
    'split', 'group_id', 'policy_id', 'source_pcd_sha256')
GEOMETRY = ('pose', 'ruler', 'sensor', 'selected_faces', 'exclusions')
QUALITY_GATES = dict(min_width=50, min_height=14, min_area=1000, min_image_margin=1,
    min_p95_p05=35, min_brightness_fraction_above_48=.12,
    max_saturated_fraction_above_250=.65, min_sobel_magnitude_above_60_fraction=.025)
OLD_ORIGINAL_REVIEWS = {'c64837a264b02755b52495c6': (4, 4), '3756ced3791a9669463f6fb0': (7, 1)}
NEW_ORIGINAL_REVIEWS = dict.fromkeys(('0f62405fc643c71371c8a0ec',
    '7041455b447a160ccc16d9df', 'db94cf18b0c6e9f8641a9be0'), (4, 1))
ORIGINAL_REVIEWS = {**OLD_ORIGINAL_REVIEWS, **NEW_ORIGINAL_REVIEWS}
AUDIT_NAMES = frozenset(('verification.json', 'independent_verification.json',
    'validation_report.json', 'independent_validation_report.json'))
OLD_REQUEST_DIRS = ('pallet_mask_template_requests_v1', 'pallet_mask_class10_manual_supplement_v2',
    'pallet_mask_quota_100_requests_v2', 'pallet_mask_quota_100_final_requests_v2',
    'pallet_mask_remaining_requests_v1', 'pallet_mask_remaining_requests_v2',
    'pallet_mask_remaining_direct_requests_v1', 'pallet_mask_remaining_direct_requests_v2',
    'pallet_mask_remaining_followup_requests_v2')
CODE_REQUIRED = frozenset(('scripts/build_mask_remaining_round2_requests.py',
    'scripts/build_mask_remaining_direct_requests.py', 'scripts/build_mask_remaining_followup_requests.py',
    'scripts/build_mask_template_requests.py', 'scripts/verify_mask_remaining_round2.py',
    'pallet/mask_remaining_classes.py',
    'pallet/mask_quota_saved_extension.py', 'pallet/mask_template_transfer.py',
    'pallet/mask_template_refined.py', 'pallet/cluster_targets.py', 'pallet/pose_review_geometry.py'))
DECISION_SCHEMA = 'remaining_round2_source_decisions_v1'
RISK_FIELDS = ('classification_ambiguous', 'multishelf_ambiguous', 'multi3hole_ambiguous', 'clipped_source')


def require(value, message):
    if not value:
        raise ValueError(message)


def read_json(path):
    return json.loads(Path(path).read_text())


def sha(value):
    return hashlib.sha256(canonical(value)).hexdigest()


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


def indexed(values):
    result = {v['target_key']: v for v in values}
    require(len(result) == len(values), 'Duplicate target key')
    return result


def member(root, name):
    root, relative = Path(root), Path(name)
    require(bool(name) and not relative.is_absolute() and '..' not in relative.parts,
        'Unsafe bound artifact path')
    path = root/relative
    require(path.resolve().is_relative_to(root.resolve()) and
        not any(p.is_symlink() for p in (path, *path.parents) if p != root.parent),
        'Unsafe bound artifact symlink')
    return path


def check_hashes(root, hashes, message):
    require(isinstance(hashes, dict) and bool(hashes), message)
    for name, expected in hashes.items():
        path = member(root, name)
        require(path.is_file() and digest(path) == expected, message+': '+name)


def valid_output(root, parent):
    root, parent = Path(root).absolute(), Path(parent).resolve()
    require(not root.is_symlink() and root.resolve() == root and root.parent == PROJECT/'outputs'
        and re.fullmatch(r'pallet_mask_remaining_round2_requests_v[0-9]+', root.name)
        and not root.is_relative_to(parent) and not parent.is_relative_to(root),
        'Use a separate outputs/pallet_mask_remaining_round2_requests_vN directory')
    require(parent.is_relative_to(PROJECT/'outputs'), 'Parent must be a local outputs generation')
    return root


def matching_parent(parent):
    manifest = read_json(parent/'manifest.json')
    seal_path = parent/'verification.json'
    require(seal_path.is_file(), 'Matching publication-12 seal required')
    seal = read_json(seal_path)
    require(seal.get('state') == 'passed' and seal.get('publication_version') == 12
        and manifest.get('publication_version') == 12
        and seal.get('manifest_sha256') == digest(parent/'manifest.json')
        and seal.get('proposals_sha256') == digest(parent/'proposals.jsonl'),
        'Matching publication-12 seal required')
    require(seal.get('verification_script_sha256') == digest(PROJECT/'scripts/verify_mask_remaining_round2.py')
        and manifest.get('code_sha256') == digest(PROJECT/'pallet/mask_remaining_round2.py'),
        'Publication-12 generator/verifier provenance differs')
    require(seal.get('artifact_hashes_sha256') == digest(parent/'artifact_hashes.json'),
        'Parent independent artifact binding differs')
    if 'validation_report_sha256' in seal:
        require(seal['validation_report_sha256'] == digest(parent/'validation_report.json'),
            'Parent independent report binding differs')
    if (parent/'independent_verification.json').exists():
        other = read_json(parent/'independent_verification.json')
        require(other == seal, 'Conflicting parent independent seals')
    check_hashes(parent, read_json(parent/'artifact_hashes.json'), 'Parent frozen artifact differs')
    check_hashes(PROJECT, manifest['frozen_code_sha256'], 'Parent frozen source code differs')
    require(manifest['frozen_code_sha256'].get('pallet/mask_remaining_round2.py') == manifest['code_sha256'],
        'Parent generation code pin missing')
    inventory = file_inventory(parent)
    for field, expected in manifest.items():
        if field.endswith('_sha256'):
            for extension in ('.jsonl', '.json'):
                name = field[:-7]+extension
                if name in inventory:
                    require(inventory[name] == expected, 'Parent bound source artifact differs: '+name)
    validation = read_json(parent/'generation_validation.json')
    require(validation.get('state') == 'self_checks_passed_not_independent_verification'
        and validation.get('publication_version') == 12, 'Parent generation is incomplete')
    proposals = read_jsonl(parent/'proposals.jsonl')
    require(len(indexed(proposals)) == manifest['proposals'] == seal.get('proposals_verified', seal.get('proposals')),
        'Parent independently verified cumulative count differs')
    return manifest, proposals, inventory


def class_quotas(proposals):
    indexed(proposals)
    counts = Counter(p['class_id'] for p in proposals)
    require(len({p['source']['frame_id'] for p in proposals}) == len(proposals)
        and all(type(c) is int and 1 <= c <= 22 and n <= 100 for c, n in counts.items()),
        'Parent class quota or global frame identity differs')
    require(counts[3] == 100, 'Class 3 is complete and must not be requested again')
    return {c: min(10, 100-counts[c]) for c in CLASSES}


def original_review(value):
    return (value.get('original_rectangle_review_only') is True
        or value.get('reviewed_original_rectangle') is True
        or value.get('schema') == 'reviewed_original_rectangle_entry_v1'
        or value.get('source_label_kind') == 'REVIEWED_ORIGINAL_RECTANGLE')


def check_parent_partition(parent, manifest, proposals, rows):
    previous = read_jsonl(parent/'parent_evidence/proposals.jsonl')
    completed = read_jsonl(parent/'completed_request_manual_proposals.jsonl')
    new = read_jsonl(parent/'new_proposals.jsonl')
    combined = indexed(proposals)
    require(len(previous) == 1296 and len(completed) == 54 and len(proposals) == 1350+len(new)
        and indexed(previous+completed+new) == combined,
        'Parent must preserve the actual canonical1296 + completed54 + new machines')
    old_lines = {json.loads(line)['target_key']: line for line in
        (parent/'parent_evidence/proposals.jsonl').read_bytes().splitlines()}
    new_lines = {json.loads(line)['target_key']: line for line in (parent/'proposals.jsonl').read_bytes().splitlines()}
    require(all(new_lines.get(k) == raw for k, raw in old_lines.items()), 'Canonical1296 historical JSONL bytes changed')
    for p in proposals:
        require(p['target_key'] in rows and p['source'] == rows[p['target_key']]
            and p['class_id'] == rows[p['target_key']]['final_class_id'], 'Parent formal source/class differs')
    require(Counter(p['class_id'] for p in completed) == {3: 4, 4: 10, 5: 10, 7: 10, 14: 10, 22: 10},
        'Actual completed54 class scope differs')
    boxes = {p['target_key']: p for p in completed if original_review(p)}
    edited = [p for p in completed if not original_review(p)]
    require(set(boxes) == set(NEW_ORIGINAL_REVIEWS) and len(edited) == 51
        and Counter((p['class_id'], len(p['polygon'])) for p in edited if p['class_id'] == 3) == {(3, 8): 4}
        and sum(len(p['polygon']) == 4 for p in edited) == 47
        and all(p.get('human_edited') is True and not original_rectangle(p['polygon'], p['source']) for p in edited),
        '51 actual edits must remain four Class3 eight-point contours and47 real quads')
    reviews = {p['target_key']: p for p in proposals if original_review(p)}
    require(set(reviews) == set(ORIGINAL_REVIEWS), 'Exactly five separate original-box reviews required')
    for key, p in reviews.items():
        cls, revision = ORIGINAL_REVIEWS[key]
        require(p['class_id'] == cls and p['target_expected_revision'] == revision
            and p.get('human_edited') is False and p.get('propagation_seed_eligible') is False
            and original_rectangle(p['polygon'], rows[key]), 'Original-box review cannot be an edit or seed')
    for p in edited:
        require(p.get('propagation_seed_eligible') is (len(p['polygon']) > 4), 'Quad seed policy differs')
    for cls in range(1, 23):
        count = sum(p['class_id'] == cls for p in proposals)
        v = manifest['classes'][str(cls)]
        require(v['total'] == v['distinct_frames'] == count and v['missing'] == 100-count,
            'Parent actual class counts differ')
    require(manifest['base_proposals'] == 1350 and manifest['previous_proposals'] == 1296
        and manifest['saved_human'] == manifest['saved_human_contour_source'] == 1258
        and manifest['saved_pose_human'] == 434 and manifest['saved_gallery_human'] == 824
        and manifest['db_stored_human_review'] == 1263 and manifest['reviewed_original_rectangle'] == 5
        and manifest['user_reviewed_no_change'] == 45 and manifest['no_new_server_review'] == 42+len(new),
        'Saved contours1258 / separate original reviews5 / historical45 and42 accounting differs')
    return previous, completed, new


def read_store(path, table, rows):
    require(table in ('annotations', 'reviews'), 'Unexpected human-store table')
    with closing(readonly(path, True)) as db:
        records = list(db.execute(f'SELECT target_key,revision,payload FROM {table}'))
        events = list(db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'))
        metadata = dict(db.execute('SELECT key,value FROM metadata'))
    current, raw_current, latest = {}, {}, {}
    require(len({e[0] for e in events}) == len(events), 'Duplicate human event ID')
    for _, key, revision, raw in events:
        value = json.loads(raw)
        require(key in rows and value.get('target_key') == key and value.get('revision') == revision,
            'Human event relational identity differs')
        fields = IDENTITY if table == 'annotations' else ('target_key', 'frame_id', 'box_index', 'bbox', 'size', 'split', 'source_pcd_sha256')
        require(all(value.get('source', {}).get(f) == rows[key][f] for f in fields), 'Human event source identity differs')
        latest[key] = (revision, raw)
    for key, revision, raw in records:
        value = json.loads(raw)
        require(key not in current and key in rows and value.get('target_key') == key
            and value.get('revision') == revision and latest.get(key) == (revision, raw),
            'Human current is not its exact raw latest event')
        current[key], raw_current[key] = value, raw
    return dict(current=current, raw=raw_current, events=events, metadata=metadata)


def clean_original_pose(value, row):
    pose = value.get('pose') or {}
    return (value.get('state') == 'draft' and original_rectangle(value.get('polygon'), row)
        and isinstance(pose, dict)
        and all(value.get(f, False) is False and pose.get(f, False) is False for f in (*FLAGS, 'full_six_dof'))
        and value.get('event_kind') not in AUTO_EVENTS | {'annotation_deleted', 'annotation_restored', 'mask_template_auto_accepted'}
        and value.get('origin') in (None, 'original_pose_human_revision')
        and not any(value.get(f) is True for f in ('machine_draft', 'machine_transfer_performed',
            'automatic_generated', 'machine_generated', 'human_edited', 'saved_human_review',
            'user_reviewed_no_change', 'original_rectangle_review_only', 'reviewed_original_rectangle')))


def protection(rows, pose, gallery, proposals, old_requests, quarantine=()):
    protected = set(quarantine) | {p['target_key'] for p in proposals+old_requests}
    protected.update(gallery['current'])
    protected.update(k for _, k, _, _ in gallery['events'])
    history = defaultdict(list)
    for event_id, key, revision, raw in pose['events']:
        require(key in rows, 'Unknown historical target')
        value = json.loads(raw); clean = clean_original_pose(value, rows[key])
        if not clean:
            protected.add(key)
        history[key].append(dict(event_id=event_id, revision=revision, payload_raw_sha256=raw_sha(raw),
            original_rectangle=original_rectangle(value.get('polygon'), rows[key]), original_pose_only=clean,
            state=value.get('state'), event_kind=value.get('event_kind')))
    for key, value in pose['current'].items():
        require(key in rows, 'Unknown current target')
        if not clean_original_pose(value, rows[key]):
            protected.add(key)
    protected.update(set(history)-set(pose['current']))
    require(protected <= set(rows), 'Unknown protected target/frame identity')
    return protected, {rows[k]['frame_id'] for k in protected}, history


def check_snapshots(parent, manifest, inputs, formal, rows):
    specs = read_json(parent/'snapshot_manifest.json')
    stores, fingerprints, snapshots = {}, {}, {}
    for kind, table, live, field, prefix, saved, events in (
            ('pose', 'annotations', PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3',
                'snapshot_sha256', 'snapshot', 4916, 11698),
            ('gallery', 'reviews', PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3',
                'gallery_snapshot_sha256', 'gallery_snapshot', 824, 890)):
        spec = specs[kind]; frozen, backup = member(parent, spec['path']), member(parent, spec['backup'])
        require(spec.get('immutable') is True and not (frozen.stat().st_mode & 0o222)
            and not (backup.stat().st_mode & 0o222)
            and digest(frozen) == digest(backup) == spec['sha256'] == manifest[field],
            'Parent immutable snapshot/backup/hash differs')
        fingerprint = database_fingerprint(frozen, True)
        require(fingerprint['table_counts'][table] == spec['saved'] == manifest[prefix+'_saved'] == saved
            and fingerprint['table_counts']['events'] == spec['events'] == manifest[prefix+'_events'] == events,
            'Complete pose4916/11698 or gallery824/890 inventory differs')
        verify_history_preserved(live, frozen)
        require(database_fingerprint(live) == fingerprint, 'Complete live human store differs from frozen parent')
        stores[kind] = read_store(frozen, table, rows)
        fingerprints[kind] = fingerprint
        snapshots[kind] = dict(path=str(frozen.relative_to(PROJECT)), sha256=digest(frozen),
            backup=str(backup.relative_to(PROJECT)), backup_sha256=digest(backup))
    require(inputs['snapshots'] == snapshots and inputs['database_logical_fingerprints'] == fingerprints,
        'Frozen worklist snapshots/logical fingerprints differ')
    binding = json.loads(stores['pose']['metadata']['binding'])
    require(binding.get('formal_manifest_sha256') == manifest['formal_manifest_sha256']
        and binding.get('formal_annotations_sha256') == digest(formal/'annotations/frames.jsonl')
        and binding.get('formal_frames_sha256') == digest(formal/'frames.jsonl')
        and stores['gallery']['metadata'].get('formal_manifest_sha256') == manifest['formal_manifest_sha256'],
        'Human stores formal metadata binding differs')
    for value in stores['pose']['current'].values():
        require(value.get('binding') == sha(binding), 'Pose current formal binding differs')
    for _, _, _, raw in stores['pose']['events']:
        require(json.loads(raw).get('binding') == sha(binding), 'Pose historical formal binding differs')
    return stores, fingerprints, snapshots


def check_source_records(parent, pose, gallery, previous, completed):
    humans = indexed(read_jsonl(parent/'all_manual_sources.jsonl'))
    originals = indexed(read_jsonl(parent/'reviewed_original_rectangle_source_records.jsonl'))
    galleries = indexed(read_jsonl(parent/'gallery_source_records.jsonl'))
    require(len(humans) == 434 and set(originals) == set(ORIGINAL_REVIEWS)
        and len(galleries) == 824 and set(galleries) == set(gallery['current'])
        and not (set(humans) & set(originals) or (set(humans) | set(originals)) & set(galleries)),
        'Exact434 genuine pose /5 separate original-box /824 gallery source scope differs')
    for records, store in ((humans, pose), (originals, pose), (galleries, gallery)):
        events = {i: (k, rev, raw) for i, k, rev, raw in store['events']}
        for key, r in records.items():
            value, raw = store['current'][key], store['raw'][key]
            require(r['current_payload'] == value and r['current_payload_raw'] == raw
                and r['current_payload_sha256'] == sha(value) and r['current_payload_raw_sha256'] == raw_sha(raw)
                and r.get('current_revision', r.get('revision')) == value['revision'],
                'Counted human source current/revision/raw bytes differ')
            event_id = r.get('human_event_id', r.get('saved_review_event_id'))
            event_raw = r.get('human_event_payload_raw', r.get('saved_review_event_payload_raw'))
            revision = r.get('human_polygon_revision', r.get('saved_review_revision', r.get('revision')))
            event_hash = r.get('human_event_sha256', r.get('saved_review_event_sha256'))
            require(events.get(event_id) == (key, revision, event_raw) and raw_sha(event_raw) == event_hash,
                'Counted human source actual historical raw event differs')
            event = json.loads(event_raw)
            require(event['polygon'] == value['polygon'], 'Counted human source polygon differs from real event')
            for payload in (value, event):
                active = payload.get('state') not in ('deleted', 'deferred', 'confirmed') if records is galleries else payload.get('state') == 'draft'
                require(active and all(payload.get(f, False) is False for f in FLAGS),
                    'Counted human source cannot imply confirmed or protected masks')
            if records is galleries:
                require(event_raw == raw and value.get('event_kind') == 'human_mask_gallery_revision'
                    and value.get('human_edited') is True, 'Gallery source is not a real latest saved review')
            elif records is originals:
                cls, revision = ORIGINAL_REVIEWS[key]
                require(r.get('human_edited') is False and r.get('propagation_seed_eligible') is False
                    and original_review(r) and value['revision'] == revision and r['source']['final_class_id'] == cls
                    and original_rectangle(value['polygon'], r['source']), 'Original-box source is not edit/seed proof')
            else:
                require(not original_rectangle(value['polygon'], r['source'])
                    and event.get('event_kind') not in AUTO_EVENTS and event.get('human_edited') is not False
                    and event.get('origin') in (None, 'original_pose_human_revision')
                    and not any(event.get(f) is True for f in ('machine_draft', 'machine_transfer_performed',
                        'automatic_generated', 'machine_generated')),
                    'Genuine pose source is an original box or automatic event')
    old_records_path = parent/'parent_evidence/reviewed_original_rectangle_source_records.jsonl'
    require(read_jsonl(old_records_path) == [originals[k] for k in indexed(read_jsonl(old_records_path))]
        and set(indexed(read_jsonl(old_records_path))) == set(OLD_ORIGINAL_REVIEWS)
        and (parent/'reviewed_original_rectangle_source_records.jsonl').read_bytes().startswith(old_records_path.read_bytes()),
        'Inherited original-box records must retain their literal old bytes')
    old_statement = read_json(parent/'parent_evidence/review_completion_statement.json')
    statement = read_json(parent/'review_completion_statement.json')
    prior_new = indexed(read_jsonl(parent/'parent_evidence/new_proposals.jsonl'))
    require(len(prior_new) == 185 and statement['scoped_request_keys'] == sorted(p['target_key'] for p in completed)
        and statement['scoped_candidate_keys'] == sorted(prior_new)
        and statement['reviewed_original_rectangle_keys'] == sorted(NEW_ORIGINAL_REVIEWS)
        and statement['old_42_unsaved_not_inferred_reviewed'] is True
        and all(statement[f] is False for f in ('creates_human_event', 'confirms_ground_truth', 'authorizes_propagation')),
        'Latest statement must be limited to actual185 candidates and completed54 requests')
    for key, r in originals.items():
        require(r['user_statement_sha256'] == sha(old_statement if key in OLD_ORIGINAL_REVIEWS else statement),
            'Original-box review statement scope was overwritten')
    saved_audit = indexed(read_jsonl(parent/'saved_review_source_audit.jsonl'))
    require(set(saved_audit) == set(prior_new) <= set(galleries), 'All185 candidates need real saved gallery evidence')
    unchanged = []
    for key, p in prior_new.items():
        r, a = galleries[key], saved_audit[key]
        same = r['current_payload']['polygon'] == p['polygon']
        require(a['actual_saved'] is True and a['saved_review_unchanged'] is same
            and a['polygon_changed_from_proposal'] is (not same) and a['human_new_edit_claim'] is False
            and a['proposal_sha256'] == sha(p) and a['current_payload_sha256'] == r['current_payload_sha256']
            and a['current_payload_raw_sha256'] == r['current_payload_raw_sha256']
            and a['human_event_id'] == r['human_event_id'] and a['human_event_sha256'] == r['human_event_sha256'],
            'Actual saved185 changed/unchanged source accounting differs')
        if same:
            unchanged.append(key)
    status = read_json(parent/'saved_review_status.json')
    require(len(unchanged) == 53 and status['actually_saved'] == 185 and status['pending'] == 0
        and status['polygon_changed_from_proposal'] == 132 and status['saved_unchanged'] == 53
        and status['unchanged_keys'] == sorted(unchanged)
        and status['unchanged_review_interpretation_statement_sha256'] == sha(statement),
        'Saved132 changed /53 unchanged must not become185 newly edited masks')
    dispositions = indexed(read_jsonl(parent/'review_dispositions.jsonl'))
    saved_keys = set(humans) | set(galleries)
    require(len(dispositions) == 45 and set(dispositions) <= set(indexed(previous))
        and not set(dispositions) & (saved_keys | set(originals))
        and len(set(indexed(previous))-saved_keys-set(originals)-set(dispositions)) == 42,
        'Old45 conversation-only dispositions and42 older unreviewed candidates must remain separate from real saved sources')
    for name in ('review_dispositions.jsonl', 'review_disposition_statement.json'):
        require((parent/name).read_bytes() == (parent/'parent_evidence'/name).read_bytes(),
            'Historical45 conversation disposition/statement bytes changed')
    check_history_delta(parent, pose, 'annotations', {p['target_key'] for p in completed}, 145)
    check_history_delta(parent, gallery, 'reviews', set(prior_new), 201)
    return saved_keys


def check_history_delta(parent, store, table, allowed, expected_new_events):
    filename = 'reviews_snapshot.sqlite3' if table == 'annotations' else 'gallery_reviews_snapshot.sqlite3'
    with closing(readonly(parent/'parent_evidence'/filename, True)) as db:
        historical = list(db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'))
        old = {k: (revision, raw) for k, revision, raw in db.execute(f'SELECT target_key,revision,payload FROM {table}')}
    require(store['events'][:len(historical)] == historical
        and len(store['events'])-len(historical) == expected_new_events
        and all(k in allowed for _, k, _, _ in store['events'][len(historical):]),
        'All historical raw events must remain an exact prefix, with only scoped real new saves')
    current = {k: (v['revision'], store['raw'][k]) for k, v in store['current'].items()}
    require({k for k in set(old) | set(current) if old.get(k) != current.get(k)} <= allowed,
        'Human current bytes changed outside the actual saved task/candidate scope')


def old_request_inputs(root, inputs, rows):
    paths = {p for p in (PROJECT/'outputs').rglob('requests.jsonl') if not p.is_relative_to(root)}
    declared = inputs['old_request_sha256']
    require({str(p.relative_to(PROJECT)) for p in paths} == set(declared),
        'Every historical request namespace must be declared as a frozen input')
    check_hashes(PROJECT, declared, 'Historical request namespace changed')
    mandatory = [PROJECT/'outputs'/name/'requests.jsonl' for name in OLD_REQUEST_DIRS]
    require(all(p in paths for p in mandatory), 'Original86/latest51/previous50/completed54 request evidence required')
    require(len(indexed([r for p in mandatory[:4] for r in read_jsonl(p)])) == 86
        and len(indexed(read_jsonl(mandatory[5]))) == 51
        and all(len(indexed(read_jsonl(p))) == 50 for p in mandatory[6:8])
        and len(indexed(read_jsonl(mandatory[8]))) == 54, 'Historical86/51/50/54 request scope differs')
    requests = []
    for path in sorted(paths):
        for r in read_jsonl(path):
            key, source = r['target_key'], r['source']
            require(key in rows and r['class_id'] == rows[key]['final_class_id']
                and source['frame_id'] == rows[key]['frame_id']
                and all(source[f] == rows[key].get(f) for f in (*IDENTITY, 'viewpoint_candidate') if f in source),
                'Historical request formal source/class/policy/view differs')
            requests.append(r)
    return requests, declared


def pose_binding(key, pose, history):
    old, raw = pose['current'].get(key), pose['raw'].get(key)
    return dict(existing_pose_record=old is not None, existing_pose_revision=old['revision'] if old else 0,
        existing_pose_payload_sha256=sha(old) if old else None,
        existing_pose_payload_raw_sha256=raw_sha(raw) if old else None,
        existing_pose_geometry_sha256=sha({f: old.get(f) for f in GEOMETRY}) if old else None,
        pose_history_present=bool(history.get(key)), pose_history_flags=history.get(key, []),
        all_pose_history_masks_unmodified=True, preserve_existing_pose_until_intentional_human_edit=True,
        preserve_current_selected_ruler_sensor_faces_and_revision=True,
        existing_pose_revision_is_expected_not_overwrite_authorization=True)


def check_pose_binding(record, key, pose, history, include_payload=False):
    require(all(record.get(f) == v and type(record.get(f)) is type(v)
        for f, v in pose_binding(key, pose, history).items()), 'Existing pose revision/raw/geometry/history protection differs')
    if include_payload:
        require(record.get('existing_pose_current_payload') == pose['current'].get(key)
            and record.get('existing_pose_current_payload_raw') == pose['raw'].get(key),
            'Full existing pose payload/raw bytes must remain untouched')
    require(record.get('no_pose_current_or_history') is (key not in pose['current'] and key not in history),
        'Virgin/pre-existing pose identity differs')


def inspectable_images(directory, record, row, formal, evidence):
    key = row['target_key']
    require(record['native_image'] == f'images/{key}.png' and record['contact_crop'] == f'cases/{key}.png',
        'Unsafe image/crop path')
    image = evidence.image(row['frame_id'])
    x, y, w, h = (row['bbox'][f] for f in ('x', 'y', 'width', 'height'))
    bounds = [max(0, math.floor(x-max(12, .1*w))), max(0, math.floor(y-max(12, .6*h))),
        min(image.shape[1], math.ceil(x+w+max(12, .1*w))), min(image.shape[0], math.ceil(y+h+max(12, .6*h)))]
    require(record['crop_native_bounds'] == bounds, 'Original native crop bounds differ')
    l, t, r, b = bounds
    crop = Image.fromarray(image[t:b, l:r]).convert('RGB')
    ImageDraw.Draw(crop).rectangle((x-l, y-t, x+w-l, y+h-t), outline=(255, 180, 40), width=1)
    with Image.open(member(directory, record['contact_crop'])) as actual:
        require(actual.mode == 'RGB' and np.array_equal(np.asarray(crop), np.asarray(actual)), 'Native rectangle-only crop pixels differ')
    require(digest(member(directory, record['native_image'])) == digest(member(formal, row['image'])),
        'Full native image bytes differ from formal source')
    quality, reason = native_quality(row, evidence)
    require(reason is None, 'Original native image-quality gate failed')
    actual = record.get('image_quality', record.get('quality'))
    require(isinstance(actual, dict) and set(actual) == set(quality)
        and all(type(actual[f]) in (float, int) and math.isfinite(actual[f])
            and abs(actual[f]-v) < 1e-8 for f, v in quality.items()), 'Native image-quality evidence differs')


def checked_decisions(value):
    require(isinstance(value, dict) and isinstance(value.get('decisions'), dict)
        and value.get('schema', DECISION_SCHEMA) == DECISION_SCHEMA, 'Invalid private review decisions')
    for key, d in value['decisions'].items():
        require(isinstance(key, str) and isinstance(d, dict) and type(d.get('approved')) is bool
            and d.get('crop_inspected') is True and d.get('full_image_inspected') is True
            and isinstance(d.get('note_zh'), str) and bool(d['note_zh'].strip())
            and set(d) <= {'approved', 'crop_inspected', 'full_image_inspected', 'note_zh'} | set(RISK_FIELDS)
            and all(type(d.get(f, False)) is bool for f in RISK_FIELDS), 'Explicit crop/full-image inspection and note required')
        require(not d['approved'] or not any(d.get(f, False) for f in RISK_FIELDS),
            'Ambiguous multishelf/multi3hole/classification or clipped sources cannot be approved')
    return value['decisions']


def check_review_chain(root, manifest, tasks, rows, formal, evidence, pose, history, protected, frames):
    path = root/'internal/build_decisions.json'
    require(manifest['source_visual_decisions_sha256'] == digest(path), 'Private build decisions binding differs')
    decisions = checked_decisions(read_json(path))
    directory = root/'internal/review'
    rounds = sorted(directory.iterdir())
    require(bool(rounds) and [p.name for p in rounds] == [f'round_{i:04d}' for i in range(1, len(rounds)+1)]
        and all(p.is_dir() and not p.is_symlink() for p in rounds), 'Review rounds must be contiguous immutable history')
    previous, records, frozen_decisions, seen_frames = None, {}, {}, set()
    for review in rounds:
        inventory = read_json(review/'artifact_hashes.json')
        require({n: h for n, h in file_inventory(review).items() if n != 'artifact_hashes.json'} == inventory,
            'Frozen review round files differ')
        info = read_json(review/'round_manifest.json')
        require(info['previous_round_sha256'] == previous
            and info['input_manifest_sha256'] == digest(root/'input_manifest.json'), 'Review round chain/input binding differs')
        incoming = checked_decisions(read_json(review/'review_input.json'))
        require(set(incoming) <= set(records), 'Decision predates its inspected shortlist')
        for key, d in incoming.items():
            require(key not in frozen_decisions or frozen_decisions[key] == d, 'Frozen approval/rejection was rewritten')
            frozen_decisions[key] = d
        shortlist = read_jsonl(review/'shortlist.jsonl')
        require(info['new_shortlist_keys'] == [r['target_key'] for r in shortlist], 'Round shortlist manifest differs')
        for record in shortlist:
            key = record['target_key']
            require(key in rows and key not in records and key not in protected and rows[key]['frame_id'] not in frames
                and rows[key]['frame_id'] not in seen_frames and rows[key]['final_class_id'] in CLASSES
                and record['source'] == rows[key], 'Review shortlist repeats a protected or historical image')
            check_pose_binding(record, key, pose, history)
            inspectable_images(review, record, rows[key], formal, evidence)
            require(record['native_image_sha256'] == digest(review/record['native_image'])
                and record['contact_crop_sha256'] == digest(review/record['contact_crop']), 'Inspected image hashes differ')
            records[key] = (review, record); seen_frames.add(rows[key]['frame_id'])
        previous = digest(review/'artifact_hashes.json')
    require(manifest['review_round_hashes'] == {p.name: digest(p/'artifact_hashes.json') for p in rounds},
        'Final manifest review-round binding differs')
    require(set(decisions) == set(records) and all(decisions.get(k) == d for k, d in frozen_decisions.items()),
        'Final decisions must account for all frozen approvals and rejections')
    require({k for k, d in decisions.items() if d['approved']} == {r['target_key'] for r in tasks},
        'Tasks must be exactly the explicitly approved inspected images')
    for task in tasks:
        key = task['target_key']; decision = decisions[key]; review, record = records[key]
        require(task['source_visual_review_zh'] == decision['note_zh'] and task.get('review_decision') == decision,
            'Task visual decision/note differs from private build decisions')
        expected_binding = dict(review_round=review.name, round_manifest_sha256=digest(review/'round_manifest.json'),
            shortlist_sha256=digest(review/'shortlist.jsonl'), native_image_sha256=record['native_image_sha256'],
            contact_crop_sha256=record['contact_crop_sha256'], canonical_source_row_sha256=sha(record['source']),
            decision_sha256=sha(decision))
        require(task.get('source_visual_review_binding') == expected_binding,
            'Task source visual review binding differs from immutable round/decision/image hashes')
        for field in ('native_image', 'contact_crop'):
            require(digest(root/task[field]) == digest(review/record[field]), 'Final image differs from the actual inspected PNG')
    return decisions


class ReportAssets(HTMLParser):
    def __init__(self):
        super().__init__()
        self.articles, self.links, self.images, self.options, self.scripts = [], [], [], [], []
        self.in_script, self.in_option = False, False

    def handle_starttag(self, tag, attrs):
        values = dict(attrs)
        if tag == 'article':
            self.articles.append(values)
        if tag == 'option':
            values['_text'] = ''
            self.options.append(values)
            self.in_option = True
        if tag == 'script':
            require('src' not in values, 'External report script forbidden')
            self.in_script = True
        for name in ('href', 'src', 'action', 'poster', 'data'):
            if name in values:
                self.links.append(values[name])
        if tag == 'img':
            self.images.append(values.get('src'))
        require(tag not in ('iframe', 'object', 'embed', 'form', 'base'), 'Unexpected report export/embedded private route')

    def handle_endtag(self, tag):
        if tag == 'script':
            self.in_script = False
        elif tag == 'option':
            self.in_option = False

    def handle_data(self, data):
        if self.in_script:
            self.scripts.append(data)
        if self.in_option:
            self.options[-1]['_text'] += data


def check_public(root, manifest, tasks, pose_url):
    public = {'report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'}
    public.update(r[f] for r in tasks for f in ('native_image', 'contact_crop'))
    require(set(manifest['public_assets']) == public and len(public) == 3+2*len(tasks), 'Exact public allowlist differs')
    check_hashes(root, manifest['public_assets'], 'Public asset differs')
    require(not (root/'masks').exists() and not (root/'labelme').exists(), 'A task-only worklist cannot contain masks/LabelMe')
    for p in root.rglob('*'):
        require(not p.is_symlink(), 'Worklist symlinks are forbidden')
        require(not {'masks', 'labelme'} & set(p.relative_to(root).parts),
            'A task-only worklist cannot hide generated masks/LabelMe in private directories')
        require(not p.is_file() or not (p.suffix.lower() in ('.db', '.sqlite', '.sqlite3')
            or '.sqlite' in p.name.lower() or re.search(r'\.db(?:3)?(?:\.|$)', p.name.lower())
            or p.name.lower().endswith(('-wal', '-shm', '-journal'))),
            'Private database or sidecar copied into worklist')
        if p.is_file():
            with p.open('rb') as handle:
                require(handle.read(16) != b'SQLite format 3\x00', 'Disguised private database copied into worklist')
    text = (root/'report_zh.html').read_text()
    require('待独立验收，尚未激活' in text and '四点' in text, 'Frozen report must remain pending, with valid-four-point instructions')
    require(not any(s in text for s in ('current_payload_raw', 'existing_pose_current_payload',
        'human_event_payload_raw', 'access_key', 'access_code', 'password', '.sqlite', 'internal/', 'input_manifest.json',
        'requests.jsonl', 'fetch(', 'XMLHttpRequest', 'sendBeacon', 'WebSocket')), 'Private payload or private/network route exposed')
    parsed = ReportAssets(); parsed.feed(text)
    cards = {a.get('id'): a for a in parsed.articles}
    require(len(cards) == len(parsed.articles) == len(tasks) and set(cards) == {r['target_key'] for r in tasks},
        'Report card inventory differs')
    require(parsed.options and parsed.options[0].get('value') == ''
        and not any('selected' in o for o in parsed.options[1:])
        and [o['_text'].strip() for o in parsed.options[1:]] == [str(c) for c in CLASSES],
        'Report must default to all five task classes')
    expected_script = ("const f=document.querySelector('#request-filter');f.addEventListener('change',()=>{let n=0;"
        "for(const a of document.querySelectorAll('article')){a.hidden=!!f.value&&a.dataset.class!==f.value;"
        "if(!a.hidden)n++;}document.querySelector('#request-count').textContent=n;});")
    require(re.sub(r'\s+', '', ''.join(parsed.scripts)) == re.sub(r'\s+', '', expected_script),
        'Report class filter must not hide tasks by default or expose private routes')
    expected_images = {r[f] for r in tasks for f in ('native_image', 'contact_crop')}
    require(set(parsed.images) == expected_images, 'Report images differ from approved crops/full images')
    external = {r['pose_annotation_url'] for r in tasks} | {pose_url, pose_url+'/'}
    for link in parsed.links+re.findall(r'url\([\"\']?([^\"\')]+)[\"\']?\)', text):
        require(link in public or link in external or link.startswith('#'), 'Report links outside exact public allowlist/pose authority')
    for task in tasks:
        card = cards[task['target_key']]
        require(card.get('data-class') == str(task['class_id']) and 'hidden' not in card,
            'Report hides or misclassifies a final task')
    from fontTools.ttLib import TTFont
    with TTFont(root/'report-font.otf') as font:
        require({ord(c) for c in text if '\u3400' <= c <= '\u9fff'} <= set(font.getBestCmap()), 'Chinese report glyphs missing')
    require(digest(root/'FONT_LICENSE.txt') == digest(PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt'),
        'Report font license differs')


def check_task(task, row, original, source_record, formal_sha, class_sha):
    source = task['source']
    expected = dict(row, image_sha256=source['image_sha256'], formal_manifest_sha256=formal_sha,
        classification_sha256=class_sha, canonical_source_row_sha256=sha(row),
        formal_source_record_sha256=sha(source_record), classification_row_sha256=sha(original))
    require(source == expected and task['original_classification_row'] == original
        and task['class_id'] == row['final_class_id'] in CLASSES, 'Formal source/class/policy/view/hash identity differs')
    require(task.get('classification_is_candidate_not_truth') is True
        and task['class_identity'] == dict(candidate_class=row.get('final_class'), final_class_id=row['final_class_id'],
            human_class_confirmed=False, classification_row_sha256=sha(original)), 'Candidate classification cannot become truth')
    require(task.get('status') == 'needs_manual_tracing' and task.get('source_label_kind') == 'ORIGINAL_RECTANGLE'
        and task.get('original_rectangle') == rectangle(row)
        and not any(f in task for f in ('polygon', 'mask', 'masks', 'labelme', 'template')),
        'Original rectangle baseline is not a completed mask or GT')
    false_fields = (*FLAGS, 'counts_as_completed_annotation', 'accepted_candidate', 'production_saved',
        'counts_toward_published_coverage', 'human_edited', 'propagation_seed_eligible')
    require(all(task.get(f) is False for f in false_fields), 'Unsupported completion/edit/confirmation/seed claim')
    for field in ('valid_four_point_manual_contour_allowed', 'extra_vertices_must_not_be_forced',
            'valid_four_point_manual_contour_is_not_transfer_seed', 'topology_must_be_manually_determined',
            'original_rectangle_alone_is_not_completed_manual_coverage', 'preserve_closed_real_quad_topology'):
        require(task.get(field) is True, 'Real four-point geometry must not be forced into artificial topology')
    require(task.get('neighbor_propagation_promised') is False and task.get('requested_required_vertex_count') is None,
        'Direct task cannot promise propagation or force a reference topology')
    require(task.get('task_kind') == 'remaining_round2_direct_human_coverage'
        and task.get('minimum_direct_manual_coverage_vertices') == 4
        and task.get('classification_review_required') is True and task.get('classification_ambiguous') is False,
        'Final direct tasks require unambiguous inspected candidate sources and valid real four-point coverage')
    require(type(task.get('generated_polygons')) is int and task['generated_polygons'] == 0, 'Task generated a polygon')


def audit(root, parent):
    root, parent = Path(root), Path(parent)
    pm, proposals, parent_before = matching_parent(parent)
    verifier_before = digest(__file__)
    manifest, inputs = read_json(root/'manifest.json'), read_json(root/'input_manifest.json')
    before = file_inventory(root)
    require({n: h for n, h in before.items() if n not in AUDIT_NAMES | {'artifact_hashes.json'}}
        == read_json(root/'artifact_hashes.json'), 'Frozen worklist artifact inventory differs')
    require(manifest['input_manifest_sha256'] == digest(root/'input_manifest.json')
        and manifest['parent_manifest_sha256'] == digest(parent/'manifest.json')
        and manifest['parent_proposals_sha256'] == digest(parent/'proposals.jsonl')
        and manifest['parent_publication_version'] == 12, 'Frozen worklist parent/input bindings differ')
    require(inputs['parent_directory'] == manifest['parent_directory'] == str(parent.relative_to(PROJECT))
        and inputs['formal_manifest_sha256'] == manifest['formal_manifest_sha256'] == pm['formal_manifest_sha256']
        and inputs['classification_sha256'] == manifest['classification_sha256'] == pm['classification_sha256'],
        'Frozen formal/classification/parent directory bindings differ')
    binding = manifest.get('parent_verification_sha256', manifest.get('parent_verification_binding', {}).get('verification.json'))
    require(binding == digest(parent/'verification.json'), 'Worklist must bind the actual independent publication-12 seal')
    if 'parent_verification_binding' in manifest:
        require(set(manifest['parent_verification_binding']) <= {'verification.json', 'independent_verification.json'},
            'Unexpected parent independent-seal alias')
        check_hashes(parent, manifest['parent_verification_binding'], 'Parent independent-seal binding differs')
    # A later public ZIP/audit may be added, but no artifact present at staging may change.
    check_hashes(parent, inputs['parent_generation_inventory'], 'Frozen staged parent artifact differs')
    for name, expected in inputs['parent_existing_audit_hashes'].items():
        require(name in AUDIT_NAMES and parent_before.get(name) == expected, 'Existing parent audit bytes changed')
    declared = set(inputs['parent_generation_inventory']) | set(inputs['parent_existing_audit_hashes'])
    require(all(n in declared or n in AUDIT_NAMES or (Path(n).parent == Path('.') and n.endswith('.zip'))
        for n in parent_before), 'Undeclared non-public parent artifact added after staging')
    if 'parent_file_inventory' in manifest:
        check_hashes(parent, manifest['parent_file_inventory'], 'Build-time parent inventory differs')
    require(CODE_REQUIRED <= set(inputs['code_sha256']), 'Required original/helper/generation code pins missing')
    check_hashes(PROJECT, inputs['code_sha256'], 'Frozen worklist code differs')
    require(manifest['code_sha256'] == digest(PROJECT/'scripts/build_mask_remaining_round2_requests.py'),
        'Worklist builder provenance differs')
    configs = file_inventory(PROJECT/'configs')
    require(inputs['configuration_sha256'] == manifest['configuration_sha256'] == configs
        == read_json(parent/'configuration_input_hashes.json'), 'Complete frozen configuration inventory differs')
    formal, rows, evidence = load_formal_evidence(pm)
    original_rows = indexed(read_jsonl(PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'))
    require(len(rows) == 12344, 'Fixed original classification denominator must remain12344')
    for key, row in rows.items():
        native = evidence.sources[row['frame_id']]
        require(key == target_key(row['frame_id'], row['box_index']) and row['image'] == native['image']
            and row['size'] == native['size'], 'Canonical formal/native source identity differs')
    formal_before = protected_snapshot(formal)
    require(len(formal_before) == 20768 and formal_before == inputs['protected_formal_files']
        == read_json(parent/'protected_formal_before.json') == read_json(parent/'protected_formal_after.json')
        == read_json(root/'protected_formal_before.json') == read_json(root/'protected_formal_after.json'),
        'Protected20768 formal files changed')
    previous, completed, new = check_parent_partition(parent, pm, proposals, rows)
    quotas = class_quotas(proposals)
    stores, fingerprints, snapshots = check_snapshots(parent, pm, inputs, formal, rows)
    require(manifest['database_logical_fingerprints'] == fingerprints
        and manifest['reused_parent_frozen_snapshots'] == snapshots
        and manifest['snapshots_copied_into_worklist'] is False
        and manifest['live_stores_match_frozen_at_start_and_finish'] is True
        and manifest['protected_formal_files_verified'] == 20768
        and manifest['protected_formal_before_sha256'] == digest(root/'protected_formal_before.json')
        and manifest['protected_formal_after_sha256'] == digest(root/'protected_formal_after.json'),
        'Worklist snapshot/formal protection manifest differs from actual frozen evidence')
    check_source_records(parent, stores['pose'], stores['gallery'], previous, completed)
    old_requests, old_hashes = old_request_inputs(root, inputs, rows)
    quarantine = set(QUARANTINE) | set(pm.get('preserved_quarantined_targets', [])) | set(pm.get('quarantined_targets', []))
    protected, frames, history = protection(rows, stores['pose'], stores['gallery'], proposals, old_requests, quarantine)
    tasks = read_jsonl(root/'requests.jsonl'); counts = Counter(r['class_id'] for r in tasks)
    require(counts == {c: n for c, n in quotas.items() if n} and len(indexed(tasks)) == len(tasks)
        == len({r['source']['frame_id'] for r in tasks}), 'Expected distinct new images for actual per-class shortfalls')
    require(manifest['request_count'] == len(tasks) and manifest['requests_sha256'] == digest(root/'requests.jsonl')
        and manifest['classes'] == list(CLASSES) and manifest['class_counts'] == {str(c): counts[c] for c in CLASSES}
        and manifest['requested_class_counts'] == {str(c): n for c, n in quotas.items()}
        and manifest['unfilled_requested_class_counts'] == dict.fromkeys(map(str, CLASSES), 0),
        'Worklist task counts/hash/quota differs')
    require(manifest['schema'] == 'remaining_round2_direct_human_requests_v1'
        and manifest['state'] == 'prepared_for_independent_verification'
        and manifest['target_per_class'] == 100 and manifest['completed_class3_not_requested'] is True
        and manifest['parent_cumulative_count'] == len(proposals) and manifest['parent_new_machine_drafts'] == len(new)
        and manifest['parent_class_counts'] == pm['classes']
        and manifest['parent_saved_human_contour_sources'] == 1258,
        'Worklist publication12 scope/source accounting differs')
    accounting = dict(saved_human_contours=1258, pose_modified_sources=434, gallery_saved_sources=824,
        original_rectangle_review_only=5, stored_human_review_coverage=1263,
        latest_machine_actually_saved=185, latest_machine_polygon_changed=132, latest_machine_saved_unchanged=53,
        latest_manual_tasks=54, latest_manual_modified=51, latest_manual_eight_point_class3=4,
        latest_manual_modified_quads=47, latest_manual_original_rectangle_review_only=3,
        inherited_original_rectangle_review_only=2, old_conversation_no_change=45, older_unreviewed_preserved=42,
        original_reviews_are_edited=False, original_reviews_seed_eligible=False,
        actual_candidate_count_authority='immutable current and exact latest raw event evidence')
    require(manifest['parent_source_accounting'] == accounting
        and manifest['old_original_rectangle_review_keys'] == sorted(ORIGINAL_REVIEWS)
        and manifest['old_requests_and_all_cumulative_frames_protected'] is True
        and manifest['ambiguous_multishelf_multi3hole_or_clipped_sources_rejected'] is True,
        'Worklist misstates genuine sources, review-only coverage, old45/42 scope or risk rejections')
    require(inputs.get('per_class') == 10 and manifest['quality_gates'] == QUALITY_GATES
        and manifest['quality_helper_sha256'] == digest(PROJECT/'scripts/build_mask_template_requests.py'),
        'Original per-class cap or native quality gates changed')
    pose_url = read_json(PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json')['public_url'].rstrip('/')
    parsed = urlsplit(pose_url)
    require(parsed.scheme == 'https' and parsed.netloc and not parsed.query and not parsed.fragment
        and parsed.username is None and parsed.password is None
        and inputs['pose_public_url'] == manifest['pose_public_url'] == pose_url, 'Managed pose annotation authority differs')
    for order, task in enumerate(tasks, 1):
        key = task['target_key']; require(key in rows and re.fullmatch('[0-9a-f]{24}', key), 'Unsafe or unknown task key')
        row = rows[key]
        require(key not in protected and row['frame_id'] not in frames, 'Counted, historical, gallery or protected image requested again')
        require(task['request_order'] == order, 'Task order differs')
        check_task(task, row, original_rows[key], evidence.sources[row['frame_id']], pm['formal_manifest_sha256'], pm['classification_sha256'])
        check_pose_binding(task, key, stores['pose'], history, True)
        inspectable_images(root, task, row, formal, evidence)
        require(task['source']['image_sha256'] == digest(formal/row['image'])
            and task['pose_annotation_url'] == pose_url+'/?target='+key, 'Native image hash/annotation target differs')
    check_review_chain(root, manifest, tasks, rows, formal, evidence, stores['pose'], history, protected, frames)
    check_public(root, manifest, tasks, pose_url)
    for field in ('production_database_writes', 'configuration_writes', 'service_writes', 'generated_polygons', 'completed_new_manual_labels'):
        require(type(manifest.get(field)) is int and manifest[field] == 0, 'Nonzero/invalid worklist write/completion claim')
    for field in (*FLAGS, 'counts_as_completed_annotation', 'activated', 'published', 'human_confirmation_inferred'):
        require(manifest.get(field) is False, 'Unsupported worklist activation/confirmation/completion claim')
    require(manifest.get('classification_is_candidate_not_truth') is True, 'Classification is only a candidate')
    require(file_inventory(root) == before and file_inventory(parent) == parent_before
        and file_inventory(PROJECT/'configs') == configs and protected_snapshot(formal) == formal_before
        and digest(__file__) == verifier_before,
        'Worklist, parent, configurations or formal files changed during audit')
    check_hashes(PROJECT, inputs['code_sha256'], 'Frozen code changed during audit')
    check_hashes(PROJECT, old_hashes, 'Historical requests changed during audit')
    require({str(p.relative_to(PROJECT)) for p in (PROJECT/'outputs').rglob('requests.jsonl') if not p.is_relative_to(root)}
        == set(old_hashes), 'Historical request namespaces changed during audit')
    require(read_json(PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json')['public_url'].rstrip('/') == pose_url,
        'Managed pose annotation authority changed during audit')
    require(digest(PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl') == pm['classification_sha256'],
        'Fixed classification source bytes changed during audit')
    for kind, live in (('pose', PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'),
            ('gallery', PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3')):
        require(database_fingerprint(live) == fingerprints[kind], 'Complete human store changed during audit')
        check_hashes(PROJECT, {snapshots[kind]['path']: snapshots[kind]['sha256'],
            snapshots[kind]['backup']: snapshots[kind]['backup_sha256']}, 'Snapshot changed during audit')
    return dict(state='passed', schema='remaining_round2_direct_human_requests_independent_verification_v1',
        parent_publication_version=12, request_count=len(tasks), class_counts=dict(counts),
        requests_sha256=digest(root/'requests.jsonl'), manifest_sha256=digest(root/'manifest.json'),
        input_manifest_sha256=digest(root/'input_manifest.json'), artifact_hashes_sha256=digest(root/'artifact_hashes.json'),
        parent_verification_sha256=digest(parent/'verification.json'), public_assets=manifest['public_assets'],
        parent_cumulative_count=len(proposals), parent_new_machine_candidates=len(new),
        saved_human_contour_sources=1258, separate_original_rectangle_reviews=5, saved_review_coverage=1263,
        private_databases_excluded=True, quality_gates_unchanged=True, all_review_rounds_and_inspected_pngs_verified=True,
        old_images_and_modified_history_excluded=True, complete_live_logical_fingerprints_unchanged=True,
        protected_formal_files=20768, fixed_formal_targets=12344,
        existing_pose_records_preserved=sum(r['existing_pose_record'] for r in tasks),
        tasks_counted_as_completed=False, production_annotation_writes=0, production_database_writes=0,
        configuration_writes=0, service_writes=0, human_confirmation_inferred=False,
        ground_truth_eligible=False, automatic_training_eligible=False, robot_command_eligible=False,
        activated=False, verification_script_sha256=verifier_before, verified_at=datetime.now(timezone.utc).isoformat())


def write_seals(root, result):
    """Acquire both exclusive destinations before writing either successful seal."""
    require(result.get('state') == 'passed', 'Only a full successful audit may issue independent seals')
    paths = [Path(root)/n for n in ('verification.json', 'independent_verification.json')]
    require(not any(p.exists() or p.is_symlink() for p in paths), 'Preserve existing independent worklist seals')
    raw = canonical(result)+b'\n'; owned, files = [], []
    try:
        for path in paths:
            files.append(path.open('xb'))
            owned.append(path)
        for handle in files:
            handle.write(raw); handle.flush(); os.fsync(handle.fileno())
    except BaseException:
        for handle in files:
            handle.close()
        for path in owned:
            path.unlink()
        raise
    finally:
        for handle in files:
            handle.close()


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--directory', '--output', dest='directory', type=Path, default=DEFAULT)
    parser.add_argument('--parent', type=Path, default=PARENT)
    args = parser.parse_args(argv); parent = args.parent.resolve(); root = valid_output(args.directory, parent)
    require(not any((root/n).exists() or (root/n).is_symlink() for n in ('verification.json', 'independent_verification.json')),
        'Preserve completed independent worklist seals')
    result = audit(root, parent)
    write_seals(root, result)
    print(json.dumps({k: v for k, v in result.items() if k != 'public_assets'}, ensure_ascii=False), flush=True)


if __name__ == '__main__':
    main()
