"""Read-only independent audits of remaining-class sources and tracing requests.

Run after the builders finish: --sources DIR and/or --requests DIR. Request-only
verification uses --source-output (default: the v1 source audit). Successful
independent_verification.json seals are exclusive; builder self-checks are never
treated as independent evidence. No generator, review application or live writer
is imported or invoked. Only independent reports/seals in these new outputs are
written. This is not activation, labeling, confirmation or transfer authorization.
"""
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
from pathlib import Path
import re
import sqlite3
import sys
from urllib.parse import parse_qs, urlsplit

import cv2
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
from pallet.mask_template_refined import QUARANTINE
from pallet.mask_template_transfer import ImageEvidence, rectangle, unchanged_rectangle
from pallet.pose_review_geometry import canonical, polygon_value
from scripts import verify_mask_template_refined as helpers
from scripts.verify_mask_quota_completion import check_assets as check_manual_assets
from scripts.build_mask_template_requests import native_quality

# Intentionally not inherited from any five-class engine.
CLASSES = (3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22)
BASELINE = PROJECT/'outputs/pallet_mask_quota_100_complete_v1'
SOURCES = PROJECT/'outputs/pallet_mask_remaining_classes_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_remaining_requests_v1'
CLASSIFICATION = PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'
POSE = PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
GALLERY = PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3'
ACCESS = PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json'
OLD_REQUESTS = tuple(PROJECT/'outputs'/name/'requests.jsonl' for name in (
    'pallet_mask_template_requests_v1', 'pallet_mask_class10_manual_supplement_v2',
    'pallet_mask_quota_100_requests_v2', 'pallet_mask_quota_100_final_requests_v2'))
BASELINE_PINS = {
    'manifest.json': 'f2ef2f8c29ff2f6ab4968acab9e151ab11abb66f319d17dd979792e7a6e20d5b',
    'verification.json': '303d693278d95b4b4e54fdfae04cbbf1e6e7313ef59421df1cf9fd0e4c0bc172',
    'proposals.jsonl': 'f85012a0b23279de8f7b68fcd390f35eab3ada284910f9a2b84b651a2fad1145',
    'artifact_hashes.json': '3c5c1f848e93d42500cccac62086914123a488cd62097eb80ecf643301f1dcfa',
    'protected_formal_before.json': '02de366b0c0f691c2c11457c3f6976fe0bed32579992403bfbee3ea2be8ee4b1',
}
IDENTITY = ('target_key', 'target_id', 'frame_id', 'split', 'group_id', 'box_index',
    'bbox', 'size', 'policy_id', 'source_pcd_sha256')
FALSE_FLAGS = ('human_mask_confirmed', 'human_pose_confirmed', 'metric_pose_confirmed',
    'automatic_training_eligible', 'robot_command_eligible', 'ground_truth_eligible', 'human_confirmed')
AUTO = {'unit_normalization', 'axes_normalization', 'mask_template_proposal'}
GEOMETRY = ('pose', 'ruler', 'sensor', 'selected_faces', 'exclusions')
REPORT = 'independent_validation_report.json'
SEAL = 'independent_verification.json'
require, sha = helpers.require, helpers.sha
read_json, read_jsonl, indexed = helpers.read_json, helpers.read_jsonl, helpers.indexed


def file_inventory(root):
    root = Path(root)
    result = {}
    for path in sorted(root.rglob('*')):
        require(not path.is_symlink(), f'Symlink in frozen inventory: {path}')
        if path.is_file():
            result[str(path.relative_to(root))] = digest(path)
    return result


def logical_fingerprint(path, frozen=False):
    """Include every table/column and raw payload byte, not just JSON/counts."""
    uri = Path(path).resolve().as_uri()+'?mode=ro'+('&immutable=1' if frozen else '')
    with closing(sqlite3.connect(uri, uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        db.execute('BEGIN')
        require(db.execute('PRAGMA quick_check').fetchone()[0] == 'ok', 'Database integrity failure')
        schema = list(db.execute('SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name'))
        hashes, counts = {}, {}
        for kind, name, _, _ in schema:
            if kind != 'table':
                continue
            require(re.fullmatch(r'[A-Za-z_][A-Za-z_0-9]*', name), 'Unsafe SQL table identifier')
            records = sorted(canonical(list(row)) for row in db.execute(f'SELECT * FROM "{name}"'))
            hashes[name] = hashlib.sha256(b'\n'.join(records)).hexdigest()
            counts[name] = len(records)
        return dict(schema_sha256=sha(schema), table_sha256=hashes, table_counts=counts)


def same_identity(value, row, label):
    require(isinstance(value, dict) and all(value.get(f) == row[f] for f in IDENTITY),
        f'{label}: original source identity differs')


def protected_state(value):
    return value.get('state') in ('deleted', 'deferred', 'confirmed') or any(
        value.get(flag, False) is not False for flag in FALSE_FLAGS)


def original_rectangle(polygon, row):
    """Reordering the original four corners is not a human mask edit."""
    return (polygon is not None and np.shape(polygon) == (4, 2)
        and bool(np.allclose(sorted(polygon), sorted(rectangle(row)), rtol=0, atol=1e-5)))


def machine_marked(value):
    return (value.get('event_kind') == 'mask_template_proposal'
        or value.get('origin') not in (None, 'original_pose_human_revision')
        or any(value.get(f) is True for f in ('machine_draft', 'machine_transfer_performed',
            'automatic_generated', 'machine_generated')))


def recover_pose_sources(pose, rows, quarantine=()):
    """Recover latest direct-human events; normalization is not a human edit.

    A machine revision clears older human provenance even for identical polygons.
    Original rectangles and protected histories are never counted. Actual changed
    four-point polygons are kept verbatim and can never become >4-point seeds.
    """
    latest, special, last_machine = {}, set(quarantine), {}
    binding = json.loads(pose.get('metadata', {}).get('binding', 'null'))
    for event_id, key, revision, raw in pose['events']:
        require(key in rows, f'Unknown pose history target: {key}')
        value = json.loads(raw)
        same_identity(value.get('source'), rows[key], f'Pose event {event_id}')
        if protected_state(value):
            special.add(key)
        kind = value.get('event_kind')
        if machine_marked(value):
            last_machine[key] = value
        if protected_state(value) or machine_marked(value):
            latest.pop(key, None)
        elif kind not in AUTO:
            if (value.get('human_edited') is False or (key in last_machine
                    and last_machine[key].get('polygon') == value.get('polygon'))):
                latest.pop(key, None)
            else:
                latest[key] = (event_id, revision, raw, value)
    recovered = {}
    for key, value in pose['current'].items():
        require(key in rows, f'Unknown current pose target: {key}')
        row = rows[key]
        same_identity(value.get('source'), row, f'Current pose {key}')
        human = latest.get(key)
        polygon = value.get('polygon') or []
        if (key in special or protected_state(value) or value.get('state') != 'draft'
                or machine_marked(value) or human is None
                or human[3].get('state') != 'draft' or human[3].get('polygon') != polygon
                or len(polygon) < 4 or original_rectangle(polygon, row)):
            continue
        if binding is not None:
            require(value.get('binding') == human[3].get('binding') == sha(binding), f'Human formal binding differs: {key}')
        for payload in (value, human[3]):
            for field in ('final_class_id', 'viewpoint_candidate'):
                require(field not in payload['source'] or payload['source'][field] == row.get(field),
                    f'Human source candidate-class/view binding differs: {key}')
        try:
            polygon_value(polygon, *row['size'])
        except (TypeError, ValueError):
            continue
        recovered[key] = dict(target_key=key, row=row, polygon=polygon,
            current_revision=value['revision'], current_payload_sha256=sha(value),
            human_event_id=human[0], human_polygon_revision=human[1],
            human_event_payload_raw=human[2], human_event_payload=human[3],
            human_event_sha256=hashlib.sha256(human[2].encode()).hexdigest(),
            vertex_count=len(polygon), manual_four_point_source=len(polygon) == 4,
            propagation_seed_eligible=len(polygon) > 4)
    return recovered


def protection(rows, pose, gallery, baseline, old_requests, quarantine=()):
    """Protect whole frames, including returned rectangles and other-class boxes."""
    keys = set(quarantine) | set(baseline) | set(old_requests) | set(gallery['current']) | set(gallery['history_keys'])
    history = defaultdict(list)
    for event in pose['events']:
        _, key, _, raw = event
        require(key in rows, f'Unknown historical target: {key}')
        value = json.loads(raw)
        history[key].append(event)
        if protected_state(value) or not original_rectangle(value.get('polygon'), rows[key]):
            keys.add(key)
    for key, value in pose['current'].items():
        if protected_state(value) or not original_rectangle(value.get('polygon'), rows[key]):
            keys.add(key)
    require(keys <= set(rows), 'Protected inventory contains an unknown formal target')
    return keys, {rows[k]['frame_id'] for k in keys}, history


def maximum_assignment(rows, excluded_frames=(), cap=100):
    """Independent class-to-frame b-matching, with scarce classes visited first.

    This computes a capacity, not labels or permission to fill it. Augmenting paths
    avoid reporting false shortfalls from a greedy cross-class frame conflict.
    """
    pools = {c: defaultdict(list) for c in CLASSES}
    excluded = set(excluded_frames)
    for key, row in rows.items():
        cls, frame = row['final_class_id'], row['frame_id']
        if cls in pools and frame not in excluded:
            pools[cls][frame].append(key)
    order = sorted(CLASSES, key=lambda c: (len(pools[c]), c))
    owner, assigned = {}, {c: set() for c in CLASSES}

    def augment(cls, seen_frames, seen_classes):
        if cls in seen_classes:
            return False
        seen_classes.add(cls)
        for frame in sorted(pools[cls]):
            if frame in seen_frames or frame in assigned[cls]:
                continue
            seen_frames.add(frame)
            old = owner.get(frame)
            if old is None or augment(old, seen_frames, seen_classes):
                if old is not None:
                    assigned[old].remove(frame)
                owner[frame] = cls
                assigned[cls].add(frame)
                return True
        return False

    for cls in order:
        for _ in range(min(cap, len(pools[cls]))):
            if not augment(cls, set(), set()):
                break
    return {min(pools[cls][frame]): rows[min(pools[cls][frame])]
        for frame, cls in owner.items()}


def formal_inventory(rows, baseline_frames=()):
    assigned = maximum_assignment(rows, baseline_frames)
    result = {}
    for cls in CLASSES:
        items = [r for r in rows.values() if r['final_class_id'] == cls]
        frames = {r['frame_id'] for r in items}
        available = frames-set(baseline_frames)
        capacity = sum(r['final_class_id'] == cls for r in assigned.values())
        result[str(cls)] = dict(boxes=len(items), distinct_frames=len(frames),
            baseline_disjoint_frames=len(available), population_shortfall=max(0, 100-len(frames)),
            globally_unique_capacity=capacity, capacity_shortfall=100-capacity,
            splits={split: dict(boxes=sum(r['split'] == split for r in items),
                distinct_frames=len({r['frame_id'] for r in items if r['split'] == split}))
                for split in sorted({r['split'] for r in items})})
    return result


def check_baseline():
    for name, expected in BASELINE_PINS.items():
        require(digest(BASELINE/name) == expected, f'Pinned baseline changed: {name}')
    manifest, seal = read_json(BASELINE/'manifest.json'), read_json(BASELINE/'verification.json')
    require(seal['state'] == 'passed' and seal['publication_version'] == manifest['publication_version'] == 9
        and seal['proposals_verified'] == manifest['proposals'] == 500, 'Need the independently sealed baseline 500')
    require(seal['manifest_sha256'] == digest(BASELINE/'manifest.json')
        and seal['proposals_sha256'] == digest(BASELINE/'proposals.jsonl')
        and seal['artifact_hashes_sha256'] == digest(BASELINE/'artifact_hashes.json')
        and seal['validation_report_sha256'] == digest(BASELINE/'validation_report.json'), 'Baseline seal binding differs')
    helpers.check_artifacts(BASELINE, read_json(BASELINE/'artifact_hashes.json'))
    old = indexed(read_jsonl(BASELINE/'proposals.jsonl'))
    require(len(old) == len({p['source']['frame_id'] for p in old.values()}) == 500
        and Counter(p['class_id'] for p in old.values()) == {1: 100, 2: 100, 9: 100, 10: 100, 15: 100}, 'Baseline quota inventory differs')
    require(manifest['user_reviewed_no_change'] == 45 and manifest['no_new_server_review'] == 43
        and len(read_jsonl(BASELINE/'review_dispositions.jsonl')) == 45, 'Historical acknowledgment/pending inventory differs')
    for name, expected in manifest['frozen_code_sha256'].items():
        require(digest(PROJECT/name) == expected, f'Old pinned code changed: {name}')
    return old, file_inventory(BASELINE), manifest


def artifact(root, names, required=True):
    """Accept builder naming differences, never ambiguous competing artifacts."""
    found = [root/name for name in names if (root/name).is_file()]
    require(found or not required, 'Missing artifact: '+', '.join(names))
    if not found:
        return None
    values = [read_jsonl(p) if p.suffix == '.jsonl' else read_json(p) for p in found]
    require(all(v == values[0] for v in values), 'Conflicting aliases: '+', '.join(names))
    return found[0]


def check_claims(manifest):
    for field in ('production_database_writes', 'configuration_writes', 'service_writes'):
        require(field in manifest and type(manifest[field]) is int and manifest[field] == 0,
            f'Must explicitly report zero {field}')
    # The sealed source schema explicitly denies new machine proposals, transfer
    # and new human edits instead of using the request schema's generated count.
    # All output polygons must independently equal actual raw saved-human bytes.
    if 'generated_polygons' not in manifest:
        require(type(manifest.get('new_machine_proposals')) is int and manifest['new_machine_proposals'] == 0
            and manifest.get('machine_transfer_performed') is False
            and type(manifest.get('new_human_edits_created')) is int and manifest['new_human_edits_created'] == 0,
            'Must explicitly report zero generated_polygons or equivalent no-new-proposal/transfer/edit claims')
    else:
        require(type(manifest['generated_polygons']) is int and manifest['generated_polygons'] == 0,
            'Must explicitly report zero generated_polygons')
    for field in ('ground_truth_eligible', 'automatic_training_eligible'):
        require(field in manifest and manifest[field] is False, f'Must explicitly deny {field}')
    if 'human_confirmation_inferred' not in manifest:
        require(manifest.get('automatic_human_confirmation') is False
            and manifest.get('classification_is_candidate_not_truth') is True,
            'Must explicitly deny inferred confirmation or automatic confirmation with candidate-not-truth classification')
    else:
        require(manifest['human_confirmation_inferred'] is False, 'Must explicitly deny human_confirmation_inferred')
    for field in ('new_human_edits_created', 'registration_attempts', 'completed_manual_labels',
            'publication_changes', 'new_machine_proposals'):
        require(type(manifest.get(field, 0)) is int and manifest.get(field, 0) == 0, f'Unexpected {field}')
    for field in ('robot_command_eligible', 'thresholds_relaxed', 'forced_fill', 'duplicate_fill',
            'machine_transfer_performed', 'automatic_human_confirmation'):
        require(manifest.get(field, False) is False, f'Must not claim {field}')
    for field in ('activated', 'counts_as_completed_annotation', 'all_classes_complete'):
        require(manifest.get(field, False) is False, f'Unwarranted activation/completion: {field}')


def check_declared_hashes(root, manifest):
    for field, expected in manifest.items():
        if not field.endswith('_sha256') or not isinstance(expected, str):
            continue
        stem = field[:-7]
        files = [root/(stem+ext) for ext in ('.json', '.jsonl') if (root/(stem+ext)).is_file()]
        for path in files:
            require(digest(path) == expected, f'Manifest artifact binding differs: {field}')
    hashes = artifact(root, ('artifact_hashes.json',), required=False)
    if hashes:
        declared = read_json(hashes)
        helpers.check_artifacts(root, declared)
        actual = set(file_inventory(root))-{REPORT, SEAL, 'artifact_hashes.json'}
        require(actual == set(declared), 'Artifact inventory does not cover every builder file')


def check_configuration(root, manifest):
    path = artifact(root, ('configuration_input_hashes.json', 'configuration_hashes.json'), required=False)
    expected = read_json(path) if path else manifest.get('configuration_sha256')
    require(isinstance(expected, dict) and bool(expected), 'Missing configuration freeze from before construction')
    require(expected == file_inventory(PROJECT/'configs'), 'Frozen live configuration changed')
    return expected


def common_inputs(root, manifest):
    check_claims(manifest)
    old, baseline_files, baseline_manifest = check_baseline()
    formal = (PROJECT/read_json(PROJECT/'configs/active_formal_dataset.json')['dataset']).resolve()
    formal_sha, class_sha = digest(formal/'manifest.json'), digest(CLASSIFICATION)
    require(manifest.get('formal_manifest_sha256') == formal_sha == baseline_manifest['formal_manifest_sha256'],
        'Formal manifest binding differs')
    require(manifest.get('classification_sha256', manifest.get('class_assignments_sha256')) == class_sha
        == baseline_manifest['classification_sha256'], 'Candidate-classification binding differs')
    rows, sources = helpers.formal_rows(formal, CLASSIFICATION)
    require(len(rows) == 12344, 'Formal target inventory differs')
    for key, row in rows.items():
        require(row['image'] == sources[row['frame_id']]['image'], f'Formal image path differs: {key}')
    before = read_json(root/'protected_formal_before.json')
    require(len(before) == 20768 and before == read_json(BASELINE/'protected_formal_before.json')
        == read_json(root/'protected_formal_after.json') == protected_snapshot(formal), 'Protected 20,768 formal files changed')
    config = check_configuration(root, manifest)
    check_declared_hashes(root, manifest)
    for name, expected in manifest.get('frozen_code_sha256', {}).items():
        path = (PROJECT/name).resolve()
        require(path.is_relative_to(PROJECT) and digest(path) == expected, f'Frozen source code changed: {name}')
    return dict(old=old, baseline_files=baseline_files, formal=formal, rows=rows, sources=sources,
        formal_sha=formal_sha, class_sha=class_sha, protected=before, config=config)


def frozen_stores(root, manifest):
    snapshots = helpers.find_snapshots(root, manifest)
    stores = {kind: helpers.read_store(path, kind, frozen=True) for kind, path in snapshots.items()}
    for kind, name in (('pose', 'reviews_snapshot.sqlite3'), ('gallery', 'gallery_reviews_snapshot.sqlite3')):
        baseline = helpers.read_store(BASELINE/name, kind, frozen=True)
        helpers.preserve_events(baseline, stores[kind])
    metadata = read_json(root/'snapshot_manifest.json')
    for kind, path in snapshots.items():
        expected = metadata[kind]
        store = stores[kind]
        require(expected['path'] == path.name and expected['backup'] == 'backups/'+path.name
            and expected['sha256'] == digest(path) and expected['saved'] == len(store['current'])
            and expected['events'] == len(store['events']), f'{kind} snapshot inventory differs')
        if 'metadata' in expected:
            require(expected['metadata'] == store['metadata'], f'{kind} frozen metadata differs')
    formal_sha = manifest['formal_manifest_sha256']
    pose_binding = json.loads(stores['pose']['metadata']['binding'])
    require(pose_binding['formal_manifest_sha256'] == formal_sha
        == stores['gallery']['metadata']['formal_manifest_sha256'], 'Review stores are bound to a different formal dataset')
    return snapshots, stores


def check_live(stores, snapshots, rows):
    fingerprints = {}
    for kind, path in (('pose', POSE), ('gallery', GALLERY)):
        live = helpers.read_store(path, kind)
        helpers.preserve_events(stores[kind], live)
        require(live['current'] == stores[kind]['current'], f'{kind} current records changed since frozen audit')
        frozen = logical_fingerprint(snapshots[kind], True)
        require(logical_fingerprint(path) == frozen, f'{kind} complete logical database differs')
        fingerprints[kind] = frozen
        # Validate original identity even for records that are not counted.
        for _, key, _, raw in live['events']:
            require(key in rows, f'Unknown {kind} event target: {key}')
            if kind == 'pose':
                same_identity(json.loads(raw).get('source'), rows[key], f'Live event {key}')
    return fingerprints


def check_source_records(records, proposals, recovered, snapshot):
    require(set(records) == set(proposals), 'Exact raw source records must cover all counted human sources')
    snapshot_sha = digest(snapshot)
    with closing(sqlite3.connect(snapshot.resolve().as_uri()+'?mode=ro&immutable=1', uri=True)) as db:
        db.execute('PRAGMA query_only=ON')
        for key, p in proposals.items():
            require(key in recovered, f'Not a current direct human source: {key}')
            source, record = recovered[key], records[key]
            found = db.execute('SELECT revision,payload FROM annotations WHERE target_key=?', (key,)).fetchall()
            require(len(found) == 1, f'Ambiguous current raw source: {key}')
            revision, raw = found[0]
            expected = dict(target_key=key, snapshot_sha256=snapshot_sha, current_revision=revision,
                current_payload_raw=raw, current_payload=json.loads(raw), current_payload_sha256=sha(json.loads(raw)),
                current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
                human_event_id=source['human_event_id'], human_polygon_revision=source['human_polygon_revision'],
                human_event_payload_raw=source['human_event_payload_raw'], human_event_payload=source['human_event_payload'],
                human_event_sha256=source['human_event_sha256'], polygon_sha256=sha(source['polygon']))
            for field, value in expected.items():
                require(record.get(field) == value, f'Raw SQLite source/event binding differs: {key}/{field}')
            for field in ('vertex_count', 'manual_four_point_source', 'propagation_seed_eligible'):
                if field in record:
                    require(type(record[field]) is type(source[field]) and record[field] == source[field],
                        f'Raw source topology/seed policy differs: {key}/{field}')
            if 'source' in record:
                require(record['source'] == source['row'] and record.get('source_identity_sha256') == sha(source['row'])
                    and record.get('classification_is_candidate_not_truth') is True, f'Raw source original identity differs: {key}')
            require(p['polygon'] == source['polygon'], f'Synthetic or stale polygon: {key}')


def check_saved_sources(proposals, recovered, rows, baseline_frames):
    eligible = {k: r for k, r in recovered.items() if r['row']['final_class_id'] in CLASSES
        and r['row']['frame_id'] not in baseline_frames}
    feasible = maximum_assignment({k: v['row'] for k, v in eligible.items()})
    require(len(proposals) == len(feasible), 'Counted saved-human coverage omits available globally unique sources')
    frames, counts = set(baseline_frames), Counter()
    for key, p in proposals.items():
        require(key in eligible, f'Nonhuman/protected/baseline source counted: {key}')
        source, row = eligible[key], rows[key]
        require(p['source'] == row and p['class_id'] == row['final_class_id'] in CLASSES,
            f'Counted source candidate class/identity differs: {key}')
        require(row['frame_id'] not in frames, f'Global image reuse: {key}')
        frames.add(row['frame_id']); counts[p['class_id']] += 1
        require(counts[p['class_id']] <= 100, 'Saved source coverage exceeds quota')
        require(p['polygon'] == source['polygon'] and p['vertex_count'] == source['vertex_count']
            and p['manual_four_point_source'] is source['manual_four_point_source']
            and p['propagation_seed_eligible'] is source['propagation_seed_eligible'], 'Four-point source/seed distinction differs')
        require(p.get('human_edited') is True and not protected_state(p), 'Source is not an unconfirmed human draft')
        for field, expected in (('target_expected_revision', source['current_revision']),
                ('target_snapshot_payload_sha256', source['current_payload_sha256'])):
            if field in p:
                require(p[field] == expected, f'Counted proposal current-source binding differs: {key}/{field}')
        for field in ('template', 'human_source'):
            if field in p:
                require(p[field].get('human_polygon_revision') == source['human_polygon_revision']
                    and p[field].get('human_event_sha256') == source['human_event_sha256'],
                    f'Counted proposal human-event binding differs: {key}')
        for flag in ('pose_store_written', 'gallery_store_written', 'machine_transfer_performed', 'new_human_edit_created'):
            require(p.get(flag, False) is False, f'Source falsely claims write/transfer: {flag}')
        if len(p['polygon']) == 4:
            require('template' not in p, f'Four-point source masquerades as a transfer template: {key}')
    return {str(c): dict(saved_human=counts[c], missing=100-counts[c],
        four_point_manual=sum(p['class_id'] == c and len(p['polygon']) == 4 for p in proposals.values()),
        seeds=sum(p['class_id'] == c and len(p['polygon']) > 4 for p in proposals.values())) for c in CLASSES}


def check_seed_inventory(root, recovered):
    """An audit may list human templates, but never promote four-point sources."""
    path = artifact(root, ('template_inventory.json', 'seed_inventory.json'), required=False)
    if not path:
        return
    inventory = read_json(path)
    templates = inventory.get('templates', inventory.get('seeds', []))
    templates = list(templates.values()) if isinstance(templates, dict) else templates
    require(isinstance(templates, list), 'Malformed human seed inventory')
    seen = set()
    for template in templates:
        key = template.get('target_key', template.get('row', {}).get('target_key'))
        require(key not in seen, 'Duplicate human seed')
        seen.add(key)
        require(key in recovered and recovered[key]['row']['final_class_id'] in CLASSES,
            'Seed inventory contains a nonhuman/protected/unrequested-class source')
        expected = recovered[key]
        require(template.get('polygon') == expected['polygon'] and len(template['polygon']) > 4,
            'Seed inventory invents vertices or uses a four-point source')
        if 'human_event_sha256' in template:
            require(template['human_event_sha256'] == expected['human_event_sha256'], 'Seed event provenance differs')
    return seen


def source_population_audit(root, manifest, data, stores, recovered, proposals, records, snapshots):
    """Recompute the actual source schema's population, eligibility and capacity.

    Formal population capacity excludes only the inherited 500. Protected-aware
    source capacity additionally excludes ineligible targets. Neither is coverage.
    The builder's chosen ownership is checked for legality and maximum capacity,
    not mistaken for a uniquely determined semantic classification.
    """
    rows, pose, gallery = data['rows'], stores['pose'], stores['gallery']
    frames = {p['source']['frame_id'] for p in data['old'].values()}
    remaining = {k: r for k, r in rows.items() if r['final_class_id'] in CLASSES}
    direct = {k: s for k, s in recovered.items() if k in remaining}
    candidates = {k: s for k, s in direct.items() if s['row']['frame_id'] not in frames
        and k not in QUARANTINE and k not in gallery['history_keys']}
    validated = indexed(read_jsonl(root/'validated_manual_source_records.jsonl'))
    require(set(validated) == set(candidates), 'Validated raw records must cover all actual unprotected human sources')
    check_source_records(validated, {k: dict(polygon=s['polygon']) for k, s in candidates.items()}, recovered, snapshots['pose'])
    require(all(validated.get(k) == v for k, v in records.items()), 'Counted and validated raw records disagree')
    for name in ('manual_source_records.jsonl', 'validated_manual_source_records.jsonl'):
        require((root/name).stat().st_mode & 0o077 == 0, 'Raw human payload records must remain private')

    status = helpers.pose_status(pose, rows)
    special_history = {k for _, k, _, raw in pose['events'] if protected_state(json.loads(raw))}
    expected_reasons, pool = {}, {}
    for key, row in remaining.items():
        value = pose['current'].get(key, {})
        confirmation = value.get('state') == 'confirmed' or any(value.get(f, False) is not False for f in FALSE_FLAGS)
        reason = ('quarantined' if key in QUARANTINE else
            'inherited_500_frame_protected' if row['frame_id'] in frames else
            'gallery_history_protected' if key in gallery['history_keys'] else
            'confirmed_protected' if confirmation else
            'validated_reusable_human' if key in candidates else status[key])
        expected_reasons[key] = reason
        if reason in ('eligible', 'validated_reusable_human'):
            require(key not in special_history, 'Historically confirmed/deferred/deleted target entered source capacity pool')
            pool[key] = row
    targets = indexed(read_jsonl(root/'target_inventory.jsonl'))
    require(set(targets) == set(remaining), 'Statistical target inventory must cover exactly the 17 classes')
    for key, target in targets.items():
        require(target['source'] == rows[key] and target['class_id'] == rows[key]['final_class_id']
            and target['reason'] == expected_reasons[key] and target['exact_saved_human'] is (key in candidates)
            and target['fresh_eligible'] is (expected_reasons[key] == 'eligible')
            and target['manual_reused'] is (key in proposals) and target['sidecar'] is None,
            f'Statistical target/source eligibility differs: {key}')

    audits = indexed(read_jsonl(root/'human_source_audit.jsonl'))
    current_keys = set(pose['current']) & set(remaining)
    require(set(audits) == current_keys, 'Human source audit omits current remaining-class records')
    for key, item in audits.items():
        current = pose['current'][key]
        require(item['class_id'] == rows[key]['final_class_id'] and item['frame_id'] == rows[key]['frame_id']
            and item['current_revision'] == current['revision'] and item['current_payload_sha256'] == sha(current)
            and item['vertex_count'] == len(current.get('polygon') or [])
            and item['exact_human_validated'] is (key in direct) and item['reused'] is (key in proposals)
            and item['classification_is_candidate_not_truth'] is True, f'Actual human source audit differs: {key}')

    assignments = indexed(read_jsonl(root/'frame_assignments.jsonl'), 'frame_id')
    pool_frames = {r['frame_id'] for r in pool.values()}
    require(set(assignments) == pool_frames, 'Frame ownership omits or invents eligible source frames')
    quota = Counter()
    for frame, assignment in assignments.items():
        key, cls = assignment['target_key'], assignment['class_id']
        require(key in pool and rows[key]['frame_id'] == frame and rows[key]['final_class_id'] == cls,
            'Frame ownership crosses candidate class or uses an ineligible source')
        require(assignment['actual_saved_human'] is (key in candidates), 'Frame ownership fabricates a saved human label')
        phase = assignment['phase']
        require(phase in ('quota_capacity_matching', 'remaining_pool_ownership'), 'Unknown source ownership phase')
        if phase == 'quota_capacity_matching':
            quota[cls] += 1
    maximum = maximum_assignment(pool)
    maximum_counts = Counter(r['final_class_id'] for r in maximum.values())
    require(all(quota[c] == maximum_counts[c] <= 100 for c in CLASSES), 'Protected-aware matching is not maximum scarce-class capacity')
    matched_humans = {a['target_key'] for a in assignments.values()
        if a['phase'] == 'quota_capacity_matching' and a['actual_saved_human']}
    require(matched_humans == set(proposals), 'Counted manual records differ from actual matched human sources')
    for key, target in targets.items():
        assignment = assignments.get(rows[key]['frame_id'])
        expected_class = assignment['class_id'] if assignment else None
        expected_key = assignment['target_key'] if assignment else None
        require(target['frame_owner_class'] == expected_class and target['frame_owner_target_key'] == expected_key
            and target['frame_owned_by_class'] is (expected_class == target['class_id']), 'Target frame ownership binding differs')

    inventory = read_json(root/'class_inventory.json')
    require(set(inventory) == {str(c) for c in CLASSES} and manifest['classes'] == inventory
        == read_json(root/'template_inventory.json')['classes'], 'Class inventories disagree or include old five classes')
    seeds = check_seed_inventory(root, candidates)
    require(seeds == {k for k, s in candidates.items() if len(s['polygon']) > 4}, 'Direct >4 human seed inventory is incomplete')
    template_inventory = read_json(root/'template_inventory.json')
    namespace = manifest['generation_template_namespace']
    require(namespace == 'remaining_classes_generation'
        and template_inventory['generation_template_namespace'] == namespace
        and template_inventory['template_inventory_is_source_audit_only'] is True
        and template_inventory['machine_transfer_performed'] is False and template_inventory['sidecar'] is None,
        'Seed inventory falsely claims transfer or changes its rendering namespace')
    seed_files = root/namespace/'templates'
    require({p.name for p in seed_files.iterdir()} == {k+'.json' for k in seeds}, 'Seed files contain missing/extra/four-point sources')
    for template in template_inventory['templates']:
        key = template['row']['target_key']
        require(read_json(seed_files/(key+'.json')) == template and template['row'] == rows[key]
            and template['current_payload_sha256'] == candidates[key]['current_payload_sha256']
            and template['human_polygon_revision'] == candidates[key]['human_polygon_revision'], 'Exported seed source binding differs')
    require(template_inventory['templates_by_class'] == {str(c): sorted(k for k in seeds if rows[k]['final_class_id'] == c) for c in CLASSES},
        'Seed class inventory differs')
    require(template_inventory['rendering_by_target'] == {k: p['rendering_id'] for k, p in proposals.items()}, 'Manual rendering map differs')
    four_renderings = indexed(template_inventory['manual_source_renderings'])
    require(set(four_renderings) == {k for k, p in proposals.items() if len(p['polygon']) == 4}, 'Four-point rendering inventory differs')
    for key, rendering in four_renderings.items():
        require(rendering == dict(target_key=key, polygon=proposals[key]['polygon'], rendering_id=proposals[key]['rendering_id'],
            human_source=proposals[key]['human_source'], propagation_seed_eligible=False), 'Four-point rendering falsely promotes a template')
    expected_counts = {}
    for cls in CLASSES:
        keys = {k for k, r in remaining.items() if r['final_class_id'] == cls}
        population = {rows[k]['frame_id'] for k in keys}
        usable = keys & set(pool)
        usable_frames = {rows[k]['frame_id'] for k in usable}
        owned = {f for f in usable_frames if assignments[f]['class_id'] == cls}
        manual = {k: p for k, p in proposals.items() if p['class_id'] == cls}
        expected_counts[str(cls)] = dict(class_id=cls, proposed_target=100, target_per_class=100,
            total_targets=len(keys), distinct_frames=len(population), inherited_500_blocked_frames=len(population & frames),
            distinct_frames_after_inherited_500=len(population-frames), unprotected_targets=len(usable),
            remaining_unique_unprotected=len(usable_frames),
            protected_or_noneligible_frames_after_inherited_500=len(population-frames-usable_frames),
            assigned_unique_frames=len(owned), crossclass_blocked_by_other_class=len(usable_frames-owned),
            capacity_matching_distinct_frames=quota[cls], capacity_shortfall=100-quota[cls],
            structural_shortfall_before_inherited_constraints=max(0, 100-len(population)),
            inherited_image_crossclass_constraint_shortfall=max(0, min(100, len(population))-min(100, len(population-frames))),
            actual_human_labels_validated=len(keys & set(direct)), actual_human_labels_reused=len(manual),
            manual_four_count=sum(len(p['polygon']) == 4 for p in manual.values()),
            manual_more_than_four_count=sum(len(p['polygon']) > 4 for p in manual.values()),
            templates=len(keys & seeds), reused_unique_frames=len(manual), total=len(manual), missing=100-len(manual),
            capacity_remaining_after_human_reuse=quota[cls]-len(manual),
            fresh_unprotected_targets=len(usable-set(proposals)-set(direct)),
            human_mask_confirmed=0, ground_truth_eligible=0, new_machine_candidates=0,
            classification_is_candidate_not_truth=True)
    require(inventory == expected_counts, 'Protected-aware class population/capacity/coverage inventory differs')
    frames_per_class = {c: len({r['frame_id'] for r in pool.values() if r['final_class_id'] == c}) for c in CLASSES}
    require(manifest['scarcity_order'] == sorted(CLASSES, key=lambda c: (frames_per_class[c], c)), 'Source scarcity order differs')
    expected_manifest = dict(actual_human_labels_reused=len(proposals), exact_validated_human_targets=len(direct),
        validated_unprotected_human_targets=len(candidates), generation_templates=len(seeds),
        manual_four_point_sources=sum(len(p['polygon']) == 4 for p in proposals.values()),
        capacity_total=sum(quota.values()), capacity_shortfall=1700-sum(quota.values()),
        missing_labels=1700-len(proposals), inherited_canonical_preserved=500, proposed_target_per_class=100,
        proposed_target_total=1700, original_classification_targets=len(rows), original_classification_classes=22,
        protected_formal_files=20768)
    for field, expected in expected_manifest.items():
        require(type(manifest.get(field)) is int and manifest[field] == expected, f'Source manifest {field} differs')
    require(manifest['manual_by_class'] == {str(c): n for c, n in Counter(p['class_id'] for p in proposals.values()).items()},
        'Source manifest manual class counts differ')
    require(manifest['classification_is_candidate_not_truth'] is True and manifest['original_splits_preserved'] is True
        and manifest['inherited_resources_bytewise_unchanged'] is True and manifest['sidecar'] is None,
        'Source audit must preserve original candidate classes, splits and parent resources')
    return dict(validated_raw_sources=len(validated), exact_human_sources=len(direct),
        protected_aware_class_inventory=expected_counts, protected_aware_capacity=sum(quota.values()),
        validated_seed_count=len(seeds), population_and_capacity_not_completed_labels=True)


def finish_inputs(data, root, manifest):
    require(file_inventory(BASELINE) == data['baseline_files'], 'Baseline files changed during independent audit')
    require(protected_snapshot(data['formal']) == data['protected'] and digest(CLASSIFICATION) == data['class_sha'],
        'Formal/classification inputs changed during audit')
    require(file_inventory(PROJECT/'configs') == data['config'], 'Configuration changed during audit')
    check_declared_hashes(root, manifest)
    for name, expected in manifest.get('frozen_code_sha256', {}).items():
        require(digest(PROJECT/name) == expected, f'Frozen source code changed during audit: {name}')


def audit_sources(root):
    manifest = read_json(root/'manifest.json')
    data = common_inputs(root, manifest)
    snapshots, stores = frozen_stores(root, manifest)
    baseline_frames = {p['source']['frame_id'] for p in data['old'].values()}
    recovered = recover_pose_sources(stores['pose'], data['rows'], QUARANTINE)
    recovered = {k: v for k, v in recovered.items() if k not in stores['gallery']['history_keys']}
    path = artifact(root, ('manual_proposals.jsonl', 'proposals.jsonl', 'manual_sources.jsonl'))
    proposals = indexed(read_jsonl(path))
    records = indexed(read_jsonl(artifact(root, ('manual_source_records.jsonl', 'source_records.jsonl'))))
    counts = check_saved_sources(proposals, recovered, data['rows'], baseline_frames)
    require(set(proposals) <= set(records) <= {
        k for k, v in recovered.items() if v['row']['final_class_id'] in CLASSES},
        'Raw source inventory must cover counted sources and contain only actual remaining-class humans')
    # Builders may freeze all actual sources as well as the selected unique-frame
    # subset. Audit every extra raw record too, rather than discard its evidence.
    record_polygons = {k: dict(polygon=recovered[k]['polygon']) for k in records}
    check_source_records(records, record_polygons, recovered, snapshots['pose'])
    population_audit = source_population_audit(root, manifest, data, stores, recovered, proposals, records, snapshots)
    require(read_json(root/'parent_file_inventory.json') == data['baseline_files'], 'Complete inherited baseline file inventory differs')
    for name, field in (('manifest.json', 'parent_manifest_sha256'), ('verification.json', 'parent_verification_sha256'),
            ('proposals.jsonl', 'parent_proposals_sha256'), ('pallet_mask_refined_review.zip', 'parent_archive_sha256')):
        require(manifest[field] == digest(BASELINE/name), f'Source parent binding differs: {field}')
    evidence = ImageEvidence(data['formal'], data['rows'], data['sources'])
    pose_sha = digest(snapshots['pose'])
    for key, p in proposals.items():
        source = recovered[key]
        field = 'human_source' if len(p['polygon']) == 4 else 'template'
        expected_provenance = dict(target_key=key, revision=source['current_revision'],
            payload_sha256=source['current_payload_sha256'], human_polygon_revision=source['human_polygon_revision'],
            human_event_sha256=source['human_event_sha256'], polygon_sha256=sha(source['polygon']), snapshot_sha256=pose_sha)
        expected_metadata = dict(target_key=key, class_id=p['class_id'], split=data['rows'][key]['split'],
            snapshot_revision=source['current_revision'], human_polygon_revision=source['human_polygon_revision'],
            human_event_sha256=source['human_event_sha256'], current_payload_sha256=source['current_payload_sha256'],
            template_human_confirmed=False, vertex_count=len(p['polygon']), origin='original_pose_human_revision',
            pose_review=expected_provenance)
        require(p[field] == expected_metadata and ('human_source' not in p if field == 'template' else 'template' not in p),
            f'Exact manual self-source metadata differs: {key}')
        require(p['schema'] == 'saved_pose_mask_gallery_entry_v1' and p['status'] == 'human_edited_draft_pending_confirmation'
            and p['source_label_kind'] == 'human_mask_source_manual_template_draft'
            and p['manual_source_kind'] == 'existing_saved_human_reuse_remaining_classes'
            and p['origin'] == 'original_pose_human_revision' and p['snapshot_sha256'] == pose_sha
            and p['formal_manifest_sha256'] == data['formal_sha'] and p['class_assignments_sha256'] == data['class_sha']
            and p['pose_snapshot_saved'] is True and p['metrics'] == {} and p['classification_is_candidate_not_truth'] is True,
            f'Actual saved manual status/formal provenance differs: {key}')
        require(p['rendering_id'] == 'remaining_classes_generation'+(':manual_source:' if field == 'human_source' else ':')+key,
            'Manual rendering namespace/source differs')
        check_manual_assets(root, p, data['rows'][key], evidence, manual=True)
    for folder, ext in (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json')):
        require({p.name for p in (root/folder).iterdir()} == {k+'.'+ext for k in proposals}, 'Manual asset inventory differs')
    used = read_json(root/'used_image_hashes.json')
    require(all(used.get(name) == expected for name, expected in evidence.used.items()), 'Formal human-source image evidence omitted')
    for name, expected in used.items():
        require((data['formal']/name).resolve().is_relative_to(data['formal']) and digest(data['formal']/name) == expected,
            'Formal image evidence changed')
    for field in ('proposals', 'manual_proposals'):
        if field in manifest:
            require(type(manifest[field]) is int and manifest[field] == len(proposals), f'Manifest {field} count differs')
    for name in ('new_proposals.jsonl', 'accepted_candidates.jsonl', 'registration_attempts.jsonl'):
        if (root/name).exists():
            require((root/name).read_bytes() == b'', 'Source reuse must not invent machine proposals/attempts')
    fingerprints = check_live(stores, snapshots, data['rows'])
    inventory = formal_inventory(data['rows'], baseline_frames)
    # Do not hardcode an approximate 154: derive counts from actual raw events.
    finish_inputs(data, root, manifest)
    return dict(state='passed', kind='remaining_classes_saved_source_audit', classes=list(CLASSES),
        manifest_sha256=digest(root/'manifest.json'), artifact_hashes_sha256=digest(root/'artifact_hashes.json'),
        proposals_sha256=digest(path),
        source_records_sha256=digest(artifact(root, ('manual_source_records.jsonl', 'source_records.jsonl'))),
        saved_sources_verified=len(proposals), raw_source_records_verified=len(records),
        class_counts=counts, formal_class_inventory=inventory, **population_audit,
        actual_current_human_sources_in_remaining_classes=sum(v['row']['final_class_id'] in CLASSES for v in recovered.values()),
        candidate_class_inventory_is_not_semantic_truth=True, baseline_distinct_frames_preserved=500,
        baseline_verification_sha256=BASELINE_PINS['verification.json'],
        baseline_acknowledged_no_change_preserved=45, baseline_other_no_new_server_review_preserved=43,
        current_raw_payloads_and_latest_human_events_verified=True, globally_unique_with_baseline=True,
        four_point_sources_used_as_seeds=0, protected_formal_files_verified=20768,
        database_logical_fingerprints=fingerprints, generated_polygons=0, completed_new_manual_labels=0,
        production_database_writes=0, configuration_writes=0, service_writes=0,
        automatic_training_eligible=False, robot_command_eligible=False, ground_truth_eligible=False,
        activated=False, verification_script_sha256=digest(__file__))


def check_request(request, row, pose, history, protected_frames, evidence, root, pose_url, recovered):
    key, source = row['target_key'], request['source']
    same_identity(source, row, f'Request {key}')
    require(request['target_key'] == key and request['class_id'] == row['final_class_id'] in CLASSES,
        'Request class/target differs')
    require(row['frame_id'] not in protected_frames, f'Request reuses a protected frame: {key}')
    require(source.get('image') == row['image'] and source.get('viewpoint_candidate') == row.get('viewpoint_candidate'),
        'Request original image/view differs')
    require(request.get('original_rectangle') == rectangle(row) and request.get('source_label_kind') == 'ORIGINAL_RECTANGLE'
        and request.get('status') == 'needs_manual_tracing' and 'polygon' not in request, 'Request invents a completed/new polygon')
    require(request.get('minimum_manual_template_vertices') == 5
        and request.get('valid_four_point_manual_contour_allowed') is True
        and request.get('extra_vertices_must_not_be_forced') is True
        and request.get('topology_must_be_manually_determined') is True, 'Manual topology/seed policy differs')
    for flag in (*FALSE_FLAGS, 'accepted_candidate', 'production_saved', 'counts_as_completed_annotation'):
        require(request.get(flag, False) is False, f'Request falsely claims {flag}')
    require(request.get('generated_polygons', 0) == 0, 'A request is not a generated mask')
    old = pose['current'].get(key)
    events = history.get(key, [])
    require(request['existing_pose_record'] is (old is not None)
        and request['pose_history_present'] is bool(events)
        and request['existing_pose_revision'] == (old['revision'] if old else 0)
        and request['existing_pose_payload_sha256'] == (sha(old) if old else None), 'Request stale pose binding')
    require(all(unchanged_rectangle(json.loads(e[3]).get('polygon'), row)
        and not protected_state(json.loads(e[3])) for e in events), 'Request has edited/protected history')
    if old:
        require(unchanged_rectangle(old.get('polygon'), row) and not protected_state(old), 'Existing pose is not original-rectangle-only')
        require(request.get('existing_pose_geometry_sha256') == sha({f: old.get(f) for f in GEOMETRY}),
            'Existing pose/ruler/sensor/selected-face preservation binding differs')
        require(request.get('preserve_existing_pose_until_intentional_human_edit') is True
            and request.get('preserve_current_selected_ruler_sensor_faces_and_revision') is True
            and request.get('existing_pose_revision_is_expected_not_overwrite_authorization') is True,
            'Existing pose preservation must be explicit')
        if 'existing_pose_current_payload' in request:
            require(request['existing_pose_current_payload'] == old, 'Existing complete pose payload differs')
    quality, reason = native_quality(row, evidence)
    require(reason is None, f'Request fails unchanged native-quality gates: {key}/{reason}')
    helpers.equal_metrics(request['image_quality'], quality, 'native_quality')
    image_sha = digest(evidence.dataset/row['image'])
    require(source['image_sha256'] == image_sha == digest(root/request['native_image']), 'Request native image bytes differ')
    require(request['native_image'] == f'images/{key}.png' and request['contact_crop'] == f'cases/{key}.png',
        'Unexpected public image/crop path')
    check_crop(request, row, evidence, root)
    url = urlsplit(request['pose_annotation_url'])
    require(request['pose_annotation_url'] == pose_url+'/?target='+key
        and url.scheme == 'https' and parse_qs(url.query) == {'target': [key]}, 'Request pose URL target/authority differs')
    ref = request.get('closest_human_reference_key')
    if ref:
        require(ref in recovered and len(recovered[ref]['polygon']) > 4, 'Reference is not a saved eligible human seed')
        reference = recovered[ref]['row']
        require(tuple(reference.get(f) for f in ('final_class_id', 'split', 'policy_id', 'viewpoint_candidate'))
            == tuple(row.get(f) for f in ('final_class_id', 'split', 'policy_id', 'viewpoint_candidate'))
            and reference['frame_id'] != row['frame_id'], 'Reference crosses class/split/policy/view/frame')


def check_crop(request, row, evidence, root):
    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(request['crop_native_bounds'] == bounds, 'Crop native bounds differ')
    left, top, right, bottom = bounds
    expected = Image.fromarray(image[top:bottom, left:right]).convert('RGB')
    ImageDraw.Draw(expected).rectangle((x-left, y-top, x+w-left, y+h-top), outline=(255, 180, 40), width=1)
    with Image.open(root/request['contact_crop']) as actual:
        require(np.array_equal(np.asarray(actual), np.asarray(expected)), 'Crop is not the original native image plus original rectangle')


class PublicPage(HTMLParser):
    def __init__(self):
        super().__init__()
        self.images, self.cards, self.text, self.current = [], {}, [], None

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == 'img':
            self.images.append(attrs.get('src'))
        if tag == 'article':
            key = attrs.get('id', '').removeprefix('target-')
            require(key not in self.cards, 'Duplicate request report card')
            require('hidden' not in attrs and 'display:none' not in attrs.get('style', '').replace(' ', ''), 'Hidden request card')
            self.cards[key] = ''
            self.current = key

    def handle_data(self, text):
        self.text.append(text)
        if self.current:
            self.cards[self.current] += text

    def handle_endtag(self, tag):
        if tag == 'article':
            self.current = None


def check_public(root, manifest, requests):
    expected = {'report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'} | {
        f'{folder}/{k}.png' for k in requests for folder in ('cases', 'images')}
    public = manifest.get('public_assets')
    require(isinstance(public, dict) and set(public) == expected and len(public) == 3+2*len(requests),
        'Public assets must be exactly report/font/license plus two original-source images per request')
    for name, expected_sha in public.items():
        path = root/name
        require(not path.is_symlink() and path.resolve().is_relative_to(root.resolve()) and digest(path) == expected_sha,
            f'Public asset hash/path differs: {name}')
    page = (root/'report_zh.html').read_text()
    for private in ('current_payload_raw', 'human_event_payload_raw', 'geometry_token', '"reviewer"',
            'existing_pose_current_payload', '.sqlite3', 'access_code', 'password'):
        require(private not in page, f'Private payload/credential exposed in report: {private}')
    parsed = PublicPage(); parsed.feed(page)
    require(set(parsed.cards) == set(requests), 'Report cards must cover every request exactly once')
    require(Counter(parsed.images) == Counter(r[f] for r in requests.values() for f in ('native_image', 'contact_crop')),
        'Report images are not exactly each crop/full source pair')
    for key, request in requests.items():
        if request['existing_pose_record']:
            text = parsed.cards[key]
            require(str(request['existing_pose_revision']) in text
                and all(word in text for word in ('位姿', '标尺', '面', '保留')), 'Existing pose revision/protection absent from request card')
    require('四点' in page and ('不强' in page or '不为' in page or '不应' in page)
        and '待' in page and ('未激活' in page or '待命' in page), 'Report must state unsaved/standby and honest four-point policy')
    from fontTools.ttLib import TTFont
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(root/'report-font.otf') as font:
        require(required <= set(font.getBestCmap()), 'Chinese report font coverage incomplete')
    return public


def visual_decisions(root, requests, manifest):
    path = artifact(root, ('internal/source_visual_decisions.json', 'source_visual_decisions.json',
        'visual_review_decisions.json', 'visual_decisions.jsonl'))
    values = read_jsonl(path) if path.suffix == '.jsonl' else read_json(path)
    values = indexed(values) if isinstance(values, list) else values
    for key, request in requests.items():
        value = values.get(key, {})
        require(value.get('approved') is True and value.get('crop_inspected') is True
            and value.get('full_image_inspected') is True and bool(value.get('note_zh', '').strip()),
            f'Missing explicit crop/full-image source decision: {key}')
        require(request.get('source_visual_review_zh') == value['note_zh'], f'Source visual decision differs: {key}')
    expected = manifest.get('source_visual_decisions_sha256')
    require(expected == digest(path), 'Visual source decisions must be bound in manifest')


def audit_requests(root, source_root=SOURCES):
    manifest = read_json(root/'manifest.json')
    # A request package need not carry SQLite; it must bind the immutable source audit.
    data = common_inputs(root, manifest)
    source_manifest = read_json(source_root/'manifest.json')
    source_seal = read_json(source_root/SEAL)
    require(source_seal['state'] == 'passed' and source_seal['manifest_sha256'] == digest(source_root/'manifest.json')
        and source_seal['verification_script_sha256'] == digest(__file__), 'Need this independent source-audit seal')
    require(source_seal['validation_report_sha256'] == digest(source_root/REPORT), 'Source independent report changed')
    require(source_seal['artifact_hashes_sha256'] == digest(source_root/'artifact_hashes.json'), 'Source independent artifact inventory changed')
    check_declared_hashes(source_root, source_manifest)
    source_files = file_inventory(source_root)
    snapshots, stores = frozen_stores(source_root, source_manifest)
    source_binding = manifest.get('sources_manifest_sha256', manifest.get('source_manifest_sha256'))
    require(source_binding == digest(source_root/'manifest.json'), 'Request manifest must bind source audit')
    requests = indexed(read_jsonl(root/'requests.jsonl'))
    require(len(requests) == 51 and Counter(r['class_id'] for r in requests.values()) == {c: 3 for c in CLASSES},
        'First worklist must contain exactly three tasks for each of the 17 remaining classes')
    require(manifest['request_count'] == 51 and manifest['requests_sha256'] == digest(root/'requests.jsonl'), 'Request count/hash differs')
    require(len({r['source']['frame_id'] for r in requests.values()}) == 51, 'Requests repeat an image across boxes/classes')
    require(sorted(r['request_order'] for r in requests.values()) == list(range(1, 52)), 'Request ordering is not a permutation of 1..51')
    old_requests = indexed([r for path in OLD_REQUESTS for r in read_jsonl(path)])
    require(len(old_requests) == 86, 'Expected original 86 historical requests')
    protected, frames, history = protection(data['rows'], stores['pose'], stores['gallery'], data['old'], old_requests, QUARANTINE)
    recovered = recover_pose_sources(stores['pose'], data['rows'], QUARANTINE)
    pose_url = read_json(ACCESS)['public_url'].rstrip('/')
    require(manifest['pose_public_url'] == pose_url, 'Managed pose URL changed')
    evidence = ImageEvidence(data['formal'], data['rows'], data['sources'])
    for key, request in requests.items():
        require(re.fullmatch(r'[0-9a-f]{24}', key) and key in data['rows'] and key not in protected, 'Protected/unknown request key')
        require(request['source']['formal_manifest_sha256'] == data['formal_sha'], 'Request formal binding differs')
        check_request(request, data['rows'][key], stores['pose'], history, frames, evidence, root, pose_url, recovered)
    visual_decisions(root, requests, manifest)
    public = check_public(root, manifest, requests)
    require(not any(p.suffix in ('.db', '.sqlite', '.sqlite3') for p in root.rglob('*'))
        and not (root/'masks').exists() and not (root/'labelme').exists(), 'Worklist must not contain private databases or generated masks')
    fingerprints = check_live(stores, snapshots, data['rows'])
    finish_inputs(data, root, manifest)
    require(file_inventory(source_root) == source_files, 'Bound source audit changed during request verification')
    return dict(state='passed', kind='remaining_classes_manual_request_audit', classes=list(CLASSES),
        manifest_sha256=digest(root/'manifest.json'), requests_sha256=digest(root/'requests.jsonl'),
        request_count=51, class_counts={str(c): 3 for c in CLASSES}, public_assets=public,
        sources_manifest_sha256=digest(source_root/'manifest.json'), sources_independent_verification_sha256=digest(source_root/SEAL),
        native_images_byte_identical=True, native_quality_gates_unchanged=True,
        all_crops_and_full_images_have_explicit_source_decisions=True, globally_unique_and_protected_frames_excluded=True,
        original_86_request_frames_excluded=True, baseline_500_frames_preserved=True,
        existing_pose_ruler_sensor_faces_revision_protected=True, exact_class_split_policy_view_references=True,
        candidate_classes_not_human_truth=True, generated_polygons=0, completed_manual_labels=0,
        protected_formal_files_verified=20768, database_logical_fingerprints=fingerprints,
        production_database_writes=0, configuration_writes=0, service_writes=0,
        ground_truth_eligible=False, automatic_training_eligible=False, robot_command_eligible=False,
        activated=False, verification_script_sha256=digest(__file__))


def seal(root, kind, operation):
    root = Path(root)
    resolved = root.resolve()
    prefix = 'pallet_mask_remaining_classes_v' if kind == 'sources' else 'pallet_mask_remaining_requests_v'
    require(not root.is_symlink() and resolved.parent == PROJECT/'outputs'
        and re.fullmatch(re.escape(prefix)+r'[0-9]+', resolved.name) and resolved.is_dir(),
        'Only the new remaining-class output directory may receive independent audit files')
    require((resolved/'manifest.json').is_file(), 'Builder has not finished: manifest.json missing')
    require(not (resolved/SEAL).exists() and not (resolved/SEAL).is_symlink(), 'Refusing to overwrite an independent verification seal')
    require(not (resolved/REPORT).is_symlink(), 'Unsafe independent validation report path')
    try:
        result = operation(resolved)
    except Exception as exc:
        failure = dict(state='failed', kind=kind, error_type=type(exc).__name__, error=str(exc),
            verification_script_sha256=digest(__file__))
        (resolved/REPORT).write_bytes(canonical(failure)+b'\n')
        raise
    require(result.get('state') == 'passed', 'An unsuccessful audit cannot create a seal')
    result['verified_at'] = datetime.now(timezone.utc).isoformat()
    (resolved/REPORT).write_bytes(canonical(result)+b'\n')
    result['validation_report_sha256'] = digest(resolved/REPORT)
    with (resolved/SEAL).open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    return result


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--sources', type=Path, help='Verify the completed source-audit output')
    parser.add_argument('--requests', type=Path, help='Verify the completed 51-task worklist')
    parser.add_argument('--source-output', type=Path, default=SOURCES, help='Sealed source audit for request-only verification')
    args = parser.parse_args(argv)
    require(args.sources is not None or args.requests is not None, 'Specify --sources and/or --requests')
    cv2.setNumThreads(1)
    results = {}
    if args.sources:
        results['sources'] = seal(args.sources, 'sources', audit_sources)
    if args.requests:
        source = (args.sources or args.source_output).resolve()
        results['requests'] = seal(args.requests, 'requests', lambda root: audit_requests(root, source))
    print(json.dumps(results, ensure_ascii=False), flush=True)
    return results


if __name__ == '__main__':
    main()
