"""Private, restageable direct-human follow-up to publication 11.

No stage runs implicitly. Review may use a completed, not-yet-sealed generation;
build requires its matching independent seal. Only the separate worklist is
written, never a database, configuration, service, mask, or propagation result.

--decisions accepts {"decisions": {key: {"approved": bool,
"crop_inspected": true, "full_image_inspected": true, "note_zh": "..."}},
"preferences": {"class_groups": {"5": ["group-id"]}}}. Optional preference
maps are class_groups, class_splits, class_policies, class_views; preferred_keys
is an ordered list. Rejections lock that image for subsequent review rounds.
Each round and its input remain immutable; no source-code edits are necessary.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from contextlib import closing
from datetime import datetime, timezone
import html
import json
import math
from pathlib import Path
import re
import shutil
import sys

import cv2

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from scripts import build_mask_remaining_direct_requests as direct
from pallet.cluster_targets import target_key
from pallet.mask_template_transfer import AUTO_EVENTS

# Pure frozen helpers only: do not call the previous builder's pub10 orchestration.
require, read_json, sha, raw_sha = direct.require, direct.read_json, direct.sha, direct.raw_sha
digest, private_json, member = direct.digest, direct.private_json, direct.member
read_jsonl, indexed, file_inventory = direct.read_jsonl, direct.indexed, direct.file_inventory
readonly, protected_snapshot = direct.readonly, direct.protected_snapshot
load_formal_evidence, native_quality = direct.load_formal_evidence, direct.native_quality
database_fingerprint, render_case, signature = direct.database_fingerprint, direct.render_case, direct.signature
pose_rows, pose_binding, contact, build_font = direct.pose_rows, direct.pose_binding, direct.contact, direct.build_font
assert_frozen = direct.assert_frozen
CLASSES = (3, 4, 5, 7, 14, 22)
COMPLETED_CLASSES = direct.CLASSES
FALSE_FLAGS, QUALITY_GATES = direct.FALSE_FLAGS, direct.QUALITY_GATES
PARENT = PROJECT/'outputs/pallet_mask_remaining_continue_v1'
DEFAULT = PROJECT/'outputs/pallet_mask_remaining_followup_requests_v1'
POSE, GALLERY, CLASSIFICATION = direct.POSE, direct.GALLERY, direct.CLASSIFICATION
PARENT_AUDIT_NAMES = direct.PARENT_AUDIT_NAMES
ORIGINAL_REVIEWS = {'c64837a264b02755b52495c6': (4, 4), '3756ced3791a9669463f6fb0': (7, 1)}
OLD_REQUEST_DIRS = direct.OLD_REQUEST_DIRS + (
    'pallet_mask_remaining_direct_requests_v1', 'pallet_mask_remaining_direct_requests_v2')
DECISION_SCHEMA = 'remaining_followup_source_decisions_v1'
PREFERENCE_FIELDS = {'class_groups': 'group_id', 'class_splits': 'split',
    'class_policies': 'policy_id', 'class_views': 'viewpoint_candidate'}


def valid_output(out, parent):
    out, parent = Path(out).absolute(), Path(parent).resolve()
    require(not out.is_symlink() and out.resolve() == out and out.parent == PROJECT/'outputs'
        and re.fullmatch(r'pallet_mask_remaining_followup_requests_v[0-9]+', out.name)
        and not out.is_relative_to(parent) and not parent.is_relative_to(out),
        'Use a separate outputs/pallet_mask_remaining_followup_requests_vN directory')
    return out


def class_quotas(proposals, per_class=10):
    require(type(per_class) is int and 1 <= per_class <= 10, 'Per-class limit must be 1–10')
    indexed(proposals)
    require(len({p['source']['frame_id'] for p in proposals}) == len(proposals),
        'Parent cumulative frames are not globally distinct')
    counts = Counter(p['class_id'] for p in proposals)
    require(all(type(c) is int and 1 <= c <= 22 and n <= 100 for c, n in counts.items()),
        'Parent class identity/quota differs')
    return {c: min(per_class, 100-counts[c]) for c in CLASSES}


def alias_claim(value, names, expected, required=False):
    found = [name for name in names if name in value]
    require(bool(found) or not required, 'Missing parent claim: '+names[0])
    require(all(value[n] == expected for n in found), 'Parent claim differs: '+names[0])


def original_review(p):
    """Infer from actual source properties, not one generator's field spelling."""
    return (p.get('original_rectangle_review_only') is True or p.get('reviewed_original_rectangle') is True
        or p.get('schema') == 'reviewed_original_rectangle_entry_v1'
        or p.get('source_label_kind') == 'REVIEWED_ORIGINAL_RECTANGLE')


def parent_seal(parent, manifest, required):
    seals = {}
    for name in ('verification.json', 'independent_verification.json'):
        path = parent/name
        if not path.exists():
            continue
        value = read_json(path)
        require(value.get('state') == 'passed' and value.get('publication_version') == 11
            and value.get('manifest_sha256') == digest(parent/'manifest.json')
            and value.get('proposals_sha256') == digest(parent/'proposals.jsonl'),
            'Publication 11 requires a matching passed independent seal')
        alias_claim(value, ('proposals_verified', 'proposals'), manifest['proposals'], True)
        for field, artifact in (('artifact_hashes_sha256', 'artifact_hashes.json'),
                ('validation_report_sha256', 'validation_report.json')):
            if field in value:
                require(value[field] == digest(parent/artifact), 'Parent independent artifact binding changed')
        require(value.get('verification_script_sha256') == digest(PROJECT/'scripts/verify_mask_remaining_continue.py'),
            'Publication 11 independent verifier provenance differs')
        seals[name] = digest(path)
    require(bool(seals) or not required, 'Build requires independently verified publication 11; review is not a seal')
    return seals


def load_parent(parent, require_seal=False):
    manifest = read_json(parent/'manifest.json')
    require(manifest.get('publication_version') == 11, 'Expected publication 11')
    validation = read_json(parent/'generation_validation.json')
    require(validation.get('state') == 'self_checks_passed_not_independent_verification'
        and validation.get('publication_version') == 11, 'Publication 11 generation is not complete')
    inventory = file_inventory(parent)
    for name, expected in read_json(parent/'artifact_hashes.json').items():
        require(inventory.get(name) == expected, 'Parent frozen artifact changed: '+name)
    for field, expected in manifest.items():
        for extension in ('.jsonl', '.json'):
            name = field[:-7]+extension
            if field.endswith('_sha256') and name in inventory:
                require(inventory[name] == expected, 'Parent bound artifact changed: '+field)
    proposals = read_jsonl(parent/'proposals.jsonl')
    quotas = class_quotas(proposals)
    require(len(proposals) == manifest['proposals'] and manifest.get('proposals_sha256') == inventory['proposals.jsonl'],
        'Parent cumulative count/hash differs')
    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) == 1061 and len(completed) == 50
        and len(previous+completed+new) == len(proposals)
        and set(indexed(previous+completed+new)) == set(combined)
        and all(combined[p['target_key']] == p for p in previous+completed+new),
        'Parent must preserve actual 1061 + completed50 + actual new machines')
    boxes = [p for p in completed if original_review(p)]
    edited = [p for p in completed if not original_review(p)]
    require(Counter(p['class_id'] for p in completed) == dict.fromkeys(COMPLETED_CLASSES, 10)
        and {p['target_key'] for p in boxes} == set(ORIGINAL_REVIEWS)
        and len(edited) == 48 and all(p.get('human_edited') is True for p in edited)
        and all(p.get('human_edited') is False for p in boxes)
        and all(len(p['polygon']) == 4 and p.get('propagation_seed_eligible') is False for p in completed),
        'Completed50 must distinguish 48 real quad edits from 2 non-edited original-box reviews, never seeds')
    for p in boxes:
        cls, revision = ORIGINAL_REVIEWS[p['target_key']]
        require(p['class_id'] == cls and p.get('target_expected_revision') == revision,
            'Protected original-box review class/revision changed')
    for cls in range(1, 23):
        n = sum(p['class_id'] == cls for p in proposals)
        v = manifest['classes'][str(cls)]
        alias_claim(v, ('total', 'preview'), n, True)
        alias_claim(v, ('distinct_frames',), n, True)
        alias_claim(v, ('missing',), 100-n, True)
    alias_claim(manifest, ('previous_proposals',), 1061)
    alias_claim(manifest, ('base_proposals',), 1111)
    alias_claim(manifest, ('new_proposals', 'new_machine_pending'), len(new))
    alias_claim(manifest, ('modified_manual_proposals', 'manual_modified_added'), 48)
    alias_claim(manifest, ('reviewed_original_rectangle', 'original_rectangle_review_only'), 2)
    alias_claim(manifest, ('saved_human', 'saved_human_contour_source'), 1022)
    pins = manifest['frozen_code_sha256']
    require(bool(pins), 'Parent frozen helper pins are required')
    for name, expected in pins.items():
        require(digest(member(PROJECT, name)) == expected, 'Frozen original helper changed: '+name)
    seals = parent_seal(parent, manifest, require_seal)
    return dict(manifest=manifest, proposals=proposals, quotas=quotas, inventory=inventory, seals=seals,
        new_count=len(new))


def original_pose_only(value, row):
    flags = FALSE_FLAGS + ('full_six_dof',)
    pose = value.get('pose') or {}
    return (direct.original_pose_only(value, row) and value.get('event_kind') not in AUTO_EVENTS
        and isinstance(pose, dict)
        and not any(value.get(f, False) is not False or pose.get(f, False) is not False
            for f in flags)
        and not any(value.get(f) is True for f in ('human_edited', 'saved_human_review',
            'user_reviewed_no_change', 'original_rectangle_review_only', 'reviewed_original_rectangle')))


def protection(rows, current, events, gallery_keys, proposals, old_requests, quarantine=()):
    protected = set(quarantine) | set(gallery_keys) | {p['target_key'] for p in proposals}
    protected.update(r['target_key'] for r in old_requests)
    history = defaultdict(list)
    for event_id, key, revision, raw in events:
        require(key in rows, 'Unknown historical target')
        value = json.loads(raw); clean = original_pose_only(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=direct.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 current.items():
        require(key in rows, 'Unknown current target')
        if not original_pose_only(value, rows[key]):
            protected.add(key)
    protected.update(set(history)-set(current))
    require(protected <= set(rows), 'Unknown protected target/frame identity')
    return protected, {rows[k]['frame_id'] for k in protected}, history


def old_request_paths(out):
    """Every namespace, including archived copies, not only selected mask roots."""
    return {PROJECT/'outputs'/n/'requests.jsonl' for n in OLD_REQUEST_DIRS} | {
        p for p in (PROJECT/'outputs').rglob('requests.jsonl') if not p.is_relative_to(out)}


def old_request_inputs(out, rows):
    mandatory = [PROJECT/'outputs'/n/'requests.jsonl' for n in OLD_REQUEST_DIRS]
    require(all(p.is_file() for p in mandatory), 'Original86/latest51/previous50 evidence is 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[-2:]),
        'Original86/latest51/previous50 request scope changed')
    requests, hashes = [], {}
    for path in sorted(old_request_paths(out)):
        require(not path.is_symlink(), 'Historical request symlink is not allowed')
        hashes[str(path.relative_to(PROJECT))] = digest(path)
        for r in read_jsonl(path):
            key = r['target_key']; source = r['source']
            require(key in rows and source['frame_id'] == rows[key]['frame_id']
                and r['class_id'] == rows[key]['final_class_id']
                and all(source[f] == rows[key].get(f) for f in direct.IDENTITY+('viewpoint_candidate',)
                    if f in source), 'Historical request formal/class/policy/view identity changed')
            requests.append(r)
    return requests, hashes


def code_inventory():
    names = set(direct.code_inventory()) | {'scripts/build_mask_remaining_followup_requests.py',
        'scripts/verify_mask_remaining_continue.py'}
    return {n: digest(PROJECT/n) for n in sorted(names)}


def exact_source_records(parent, current, current_raw, events, gallery):
    """Bind all counted old/new sources and real review events, not only tasks."""
    humans = read_jsonl(parent/'all_manual_sources.jsonl')
    original_paths = [parent/n for n in ('reviewed_original_rectangle_source_records.jsonl',
        'original_rectangle_review_source_records.jsonl', 'review_only_source_records.jsonl',
        'original_rectangle_review_records.jsonl', 'original_rectangle_source_records.jsonl',
        'original_rectangle_review_only_records.jsonl', 'review_only_original_rectangle_records.jsonl')
        if (parent/n).is_file()]
    require(bool(original_paths), 'Separate original-box review source records are required')
    originals = read_jsonl(original_paths[0])
    require(all(read_jsonl(p) == originals for p in original_paths), 'Conflicting original-box review source aliases')
    gallery_records = read_jsonl(parent/'gallery_source_records.jsonl')
    require(len(indexed(humans)) == 383 and len(indexed(originals)) == 2
        and set(indexed(originals)) == set(ORIGINAL_REVIEWS) and len(indexed(gallery_records)) == 639,
        'Parent actual modified383/original-review2/gallery639 source records differ')
    event_by_id = {i: (k, rev, raw) for i, k, rev, raw in events}
    for r in humans+originals:
        key = r['target_key']; value = current.get(key); raw = current_raw.get(key)
        require(value is not None and r['current_payload'] == value and r['current_payload_raw'] == raw
            and r['current_revision'] == value['revision'] and r['current_payload_sha256'] == sha(value)
            and r['current_payload_raw_sha256'] == raw_sha(raw), 'Counted pose source current/raw bytes changed')
        event_id = r.get('human_event_id', r.get('saved_review_event_id'))
        revision = r.get('human_polygon_revision', r.get('saved_review_revision'))
        event_raw = r.get('human_event_payload_raw', r.get('saved_review_event_payload_raw'))
        event_hash = r.get('human_event_sha256', r.get('saved_review_event_sha256'))
        require(event_by_id.get(event_id) == (key, revision, event_raw) and raw_sha(event_raw) == event_hash,
            'Counted pose source actual historical event changed')
        if key in ORIGINAL_REVIEWS:
            require(r.get('human_edited') is False and r.get('propagation_seed_eligible') is False
                and original_review(r) and value['revision'] == ORIGINAL_REVIEWS[key][1]
                and direct.original_rectangle(value.get('polygon'), r['source']),
                'Original-box source must remain exact, non-edited, and seed-ineligible')
    with closing(readonly(gallery, True)) as db:
        raw_current = dict(db.execute('SELECT target_key,payload FROM reviews'))
        revisions = dict(db.execute('SELECT target_key,revision FROM reviews'))
        gallery_events = {i: (k, rev, raw) for i, k, rev, raw in
            db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id')}
        latest = {k: (rev, raw) for k, rev, raw in gallery_events.values()}
    require(set(raw_current) == set(indexed(gallery_records)), 'Gallery source scope differs')
    for r in gallery_records:
        key = r['target_key']; raw = raw_current[key]
        require(r['current_payload_raw'] == raw and r['current_payload_raw_sha256'] == raw_sha(raw)
            and r['current_payload'] == json.loads(raw) and r['current_payload_sha256'] == sha(json.loads(raw))
            and r['revision'] == revisions[key] and latest[key] == (revisions[key], raw)
            and gallery_events.get(r['human_event_id']) == (key, revisions[key], r['human_event_payload_raw'])
            and raw_sha(r['human_event_payload_raw']) == r['human_event_sha256'],
            'Counted gallery source current/raw latest event changed')
    human_keys = set(indexed(humans)) | set(raw_current)
    require(len(human_keys) == 1022 and not human_keys & set(ORIGINAL_REVIEWS),
        '1022 saved contour sources must exclude the two original-box reviews')
    return human_keys


def frozen_snapshots(parent, manifest):
    snapshot_manifest = read_json(parent/'snapshot_manifest.json'); snapshots, fingerprints = {}, {}
    for kind, live, field in (('pose', POSE, 'snapshot_sha256'), ('gallery', GALLERY, 'gallery_snapshot_sha256')):
        spec = snapshot_manifest[kind]; frozen, backup = member(parent, spec['path']), member(parent, spec['backup'])
        require(spec.get('immutable') is True and digest(frozen) == digest(backup) == spec['sha256'] == manifest[field]
            and not (frozen.stat().st_mode & 0o222) and not (backup.stat().st_mode & 0o222),
            'Parent immutable snapshot/backup/hash differs')
        fingerprints[kind] = database_fingerprint(frozen, True)
        table, prefix = ('annotations', 'snapshot') if kind == 'pose' else ('reviews', 'gallery_snapshot')
        expected_saved, expected_events = (4882, 11553) if kind == 'pose' else (639, 689)
        require(fingerprints[kind]['table_counts'][table] == spec['saved'] == manifest[prefix+'_saved'] == expected_saved
            and fingerprints[kind]['table_counts']['events'] == spec['events'] == manifest[prefix+'_events'] == expected_events,
            'Parent complete pose4882/11553 or gallery639/689 inventory differs')
        require(database_fingerprint(live) == fingerprints[kind], kind+' complete live contents differ from frozen publication 11')
        snapshots[kind] = dict(path=str(frozen.relative_to(PROJECT)), sha256=digest(frozen),
            backup=str(backup.relative_to(PROJECT)), backup_sha256=digest(backup))
    return snapshots, fingerprints


def prepare(out, parent, per_class=10, require_seal=False):
    parent_data = load_parent(parent, require_seal); manifest = parent_data['manifest']
    formal, rows, evidence = load_formal_evidence(manifest)
    original_rows = indexed(read_jsonl(CLASSIFICATION))
    require(len(rows) == 12344, 'Canonical formal target denominator changed')
    for key, row in rows.items():
        source = evidence.sources[row['frame_id']]
        require(key == target_key(row['frame_id'], row['box_index']) and row['image'] == source['image']
            and row['size'] == source['size'] and isinstance(row['policy_id'], str)
            and (row.get('viewpoint_candidate') is None or isinstance(row['viewpoint_candidate'], str)),
            'Formal image/target/classification policy/view identity differs')
    for p in parent_data['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 canonical source/class differs')
    formal_hashes = protected_snapshot(formal)
    require(len(formal_hashes) == 20768 and formal_hashes == read_json(parent/'protected_formal_before.json')
        == read_json(parent/'protected_formal_after.json'), 'Protected formal 20768-file inventory changed')
    configs = file_inventory(PROJECT/'configs')
    require(configs == read_json(parent/'configuration_input_hashes.json'), 'Configurations differ from frozen publication 11')
    snapshots, fingerprints = frozen_snapshots(parent, manifest)
    current, current_raw, events, metadata = pose_rows(PROJECT/snapshots['pose']['path'], rows)
    binding = json.loads(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'), 'Pose formal binding changed')
    gallery = PROJECT/snapshots['gallery']['path']
    with closing(readonly(gallery, True)) as db:
        gallery_keys = {k for k, in db.execute('SELECT target_key FROM reviews')} | {
            k for k, in db.execute('SELECT target_key FROM events')}
        require(dict(db.execute('SELECT key,value FROM metadata')).get('formal_manifest_sha256')
            == manifest['formal_manifest_sha256'], 'Gallery formal binding changed')
    human_keys = exact_source_records(parent, current, current_raw, events, gallery)
    old_requests, old_hashes = old_request_inputs(out, rows)
    quarantine = set(direct.QUARANTINE) | set(manifest.get('preserved_quarantined_targets', []))
    protected, frames, history = protection(rows, current, events, gallery_keys,
        parent_data['proposals'], old_requests, quarantine)
    quotas = class_quotas(parent_data['proposals'], per_class)
    human_signatures = Counter(signature(rows[k]) for k in human_keys)
    human_groups = Counter((rows[k]['final_class_id'], rows[k]['group_id']) for k in human_keys)
    usable, rejections = {}, Counter()
    for key, row in sorted(rows.items()):
        if row['final_class_id'] not in CLASSES or not quotas[row['final_class_id']] or key in protected or row['frame_id'] in frames:
            continue
        quality, reason = native_quality(row, evidence)
        if reason:
            rejections[f'{row["final_class_id"]}:{reason}'] += 1
            continue
        usable[key] = dict(quality=quality, no_pose_current_or_history=key not in current and key not in history,
            existing_exact_signature_human_sources=human_signatures[signature(row)],
            existing_class_group_human_sources=human_groups[row['final_class_id'], row['group_id']])
    populations = {c: dict(usable=sum(rows[k]['final_class_id'] == c for k in usable),
        usable_virgin=sum(rows[k]['final_class_id'] == c and v['no_pose_current_or_history'] for k, v in usable.items()),
        actual_saved_contour_sources=sum(rows[k]['final_class_id'] == c for k in human_keys)) for c in CLASSES}
    return dict(out=out, parent=parent_data, formal=formal, rows=rows, original_rows=original_rows, evidence=evidence,
        current=current, current_raw=current_raw, history=history, protected=protected, protected_frames=frames,
        usable=usable, quotas=quotas, populations=populations, rejections=dict(rejections),
        frozen=dict(parent_directory=str(parent.relative_to(PROJECT)),
            parent_generation_inventory={n: h for n, h in parent_data['inventory'].items() if n not in PARENT_AUDIT_NAMES},
            parent_existing_audit_hashes={n: h for n, h in parent_data['inventory'].items() if n in PARENT_AUDIT_NAMES},
            configuration_sha256=configs, protected_formal_files=formal_hashes, snapshots=snapshots,
            database_logical_fingerprints=fingerprints, old_request_sha256=old_hashes,
            formal_manifest_sha256=manifest['formal_manifest_sha256'], classification_sha256=manifest['classification_sha256'],
            pose_public_url=direct.public_pose_url(), code_sha256=code_inventory(), per_class=per_class))


def decision_input(path=None):
    value = read_json(path) if path else {}
    require(isinstance(value, dict), 'Decisions input must be an object')
    if 'decisions' not in value and 'preferences' not in value and 'schema' not in value:
        value = dict(decisions=value)
    require(set(value) <= {'schema', 'decisions', 'preferences'}
        and value.get('schema', DECISION_SCHEMA) == DECISION_SCHEMA, 'Unknown decisions schema/fields')
    decisions, preferences = value.get('decisions', {}), value.get('preferences', {})
    require(isinstance(decisions, dict) and isinstance(preferences, dict), 'Invalid decisions/preferences')
    require(set(preferences) <= set(PREFERENCE_FIELDS) | {'preferred_keys'}, 'Unknown selection preference')
    for name, mapping in preferences.items():
        if name == 'preferred_keys':
            require(isinstance(mapping, list) and all(isinstance(k, str) for k in mapping)
                and len(set(mapping)) == len(mapping), 'preferred_keys must be unique strings')
        else:
            require(isinstance(mapping, dict) and set(mapping) <= {str(c) for c in CLASSES}
                and all(isinstance(v, list) and all(isinstance(s, str) for s in v) and len(set(v)) == len(v)
                    for v in mapping.values()), 'Class preferences must be ordered unique string lists')
    for key, decision in decisions.items():
        require(isinstance(key, str) and isinstance(decision, dict)
            and set(decision) <= {'approved', 'crop_inspected', 'full_image_inspected', 'note_zh', 'classification_ambiguous'}
            and type(decision.get('approved')) is bool and decision.get('crop_inspected') is True
            and decision.get('full_image_inspected') is True and isinstance(decision.get('note_zh'), str)
            and bool(decision['note_zh'].strip()) and type(decision.get('classification_ambiguous', False)) is bool,
            'Each approval/rejection requires actual crop/full inspection and a nonempty note')
    return dict(schema=DECISION_SCHEMA, decisions=decisions, preferences=preferences)


def select_tasks(rows, usable, quotas, preferences=None, retained=(), excluded_frames=()):
    preferences = preferences or {}; selected = list(retained)
    require(len(set(selected)) == len(selected), 'Retained task keys repeat')
    frames = set(excluded_frames) | {rows[k]['frame_id'] for k in selected}
    counts = Counter(rows[k]['final_class_id'] for k in selected)
    require(all(counts[c] <= quotas[c] for c in CLASSES), 'Retained tasks exceed quotas')
    order = sorted(CLASSES, key=lambda c: (len({rows[k]['frame_id'] for k in usable
        if rows[k]['final_class_id'] == c and rows[k]['frame_id'] not in frames}), c))
    preferred_keys = preferences.get('preferred_keys', [])
    for cls in order:
        existing = [rows[k] for k in selected if rows[k]['final_class_id'] == cls]
        signatures = Counter(signature(r) for r in existing)
        diversity = {f: Counter(r.get(f) for r in existing) for f in PREFERENCE_FIELDS.values()}
        for _ in range(quotas[cls]-counts[cls]):
            options = [k for k in usable if rows[k]['final_class_id'] == cls and rows[k]['frame_id'] not in frames]
            if not options:
                break
            def rank(key):
                row, v = rows[key], usable[key]; q = v['quality']
                score = .65*q['clarity_score'] + .35*min(math.log1p(q['bbox_area_native_pixels'])/math.log(10001), 1)
                prefs = tuple((values.index(row.get(field)) if row.get(field) in values else len(values))
                    for name, field in PREFERENCE_FIELDS.items() for values in [preferences.get(name, {}).get(str(cls), [])])
                return (not v['no_pose_current_or_history'],
                    preferred_keys.index(key) if key in preferred_keys else len(preferred_keys), *prefs,
                    row.get('viewpoint_candidate') in (None, 'unknown'), signatures[signature(row)],
                    v['existing_exact_signature_human_sources'], diversity['group_id'][row['group_id']],
                    v['existing_class_group_human_sources'], diversity['split'][row['split']],
                    diversity['policy_id'][row['policy_id']], diversity['viewpoint_candidate'][row.get('viewpoint_candidate')], -score, key)
            key = min(options, key=rank); row = rows[key]
            selected.append(key); frames.add(row['frame_id']); signatures[signature(row)] += 1
            for field in diversity:
                diversity[field][row.get(field)] += 1
    return sorted(selected, key=lambda k: (rows[k]['final_class_id'], k))


def require_unsealed(out):
    direct.require_unsealed(out)
    no_database_copies(out)
    require(not any((out/n).exists() for n in ('images', 'cases', 'report_zh.html', 'report-font.otf')),
        'Never overwrite partially built public assets')


def no_database_copies(out):
    require(not any(p.is_file() and (p.suffix in ('.sqlite', '.sqlite3', '.db') or '.sqlite' in p.name
        or p.name.endswith(('-wal', '-shm'))) for p in out.rglob('*')),
        'No private database copies, including backups, are allowed')


def round_directories(out):
    root = out/'internal/review'
    paths = sorted(root.iterdir()) if root.exists() else []
    require([p.name for p in paths] == [f'round_{i:04d}' for i in range(1, len(paths)+1)]
        and all(p.is_dir() and not p.is_symlink() for p in paths), 'Review history is not contiguous immutable rounds')
    return paths


def review_history(out, data):
    records, decisions, previous_hash = {}, {}, None
    for root in round_directories(out):
        inventory = read_json(root/'artifact_hashes.json')
        require({n: h for n, h in file_inventory(root).items() if n != 'artifact_hashes.json'} == inventory,
            'Review images/shortlist/input changed: '+root.name)
        info = read_json(root/'round_manifest.json')
        require(info['previous_round_sha256'] == previous_hash and info['input_manifest_sha256'] == digest(out/'input_manifest.json'),
            'Review round chain/input binding changed')
        review_input = decision_input(root/'review_input.json')
        require(set(review_input['decisions']) <= set(records), 'Decisions name an uninspected or unknown source')
        for key, value in review_input['decisions'].items():
            require(key not in decisions or decisions[key] == value, 'Previously frozen review decisions cannot be rewritten')
            decisions[key] = value
        rejected = {k for k, d in decisions.items() if not d['approved']}
        retained = [k for k in records if k not in rejected]
        expected = select_tasks(data['rows'], data['usable'], data['quotas'], review_input['preferences'], retained,
            {r['source']['frame_id'] for r in records.values()})
        new_records = read_jsonl(root/'shortlist.jsonl')
        require([r['target_key'] for r in new_records] == [k for k in expected if k not in records],
            'Review shortlist no longer matches frozen selection/preferences')
        for r in new_records:
            key = r['target_key']
            require(key not in records and key in data['usable'] and r['source'] == data['rows'][key]
                and all(r.get(f) == v for f, v in pose_binding(key, data).items())
                and all(r.get(f) == v for f, v in data['usable'][key].items()), 'Reviewed source/current/history binding changed')
            require(digest(root/r['native_image']) == r['native_image_sha256'] == digest(data['formal']/r['source']['image'])
                and digest(root/r['contact_crop']) == r['contact_crop_sha256'], 'Reviewed native image/crop changed')
            records[key] = dict(r, review_round=root.name)
        previous_hash = digest(root/'artifact_hashes.json')
    return records, decisions, previous_hash


def merge_decisions(records, frozen_decisions, incoming):
    require(set(incoming['decisions']) <= set(records), 'Decisions name an uninspected or unknown source')
    result = dict(frozen_decisions)
    for key, value in incoming['decisions'].items():
        require(key not in result or result[key] == value, 'Previously frozen review decisions cannot be rewritten')
        result[key] = value
    return result


def finish_stability(data, parent):
    for kind, live in (('pose', POSE), ('gallery', GALLERY)):
        spec = data['frozen']['snapshots'][kind]
        require(digest(PROJECT/spec['path']) == spec['sha256'] and digest(PROJECT/spec['backup']) == spec['backup_sha256']
            and database_fingerprint(live) == data['frozen']['database_logical_fingerprints'][kind], 'Source database changed during stage')
    require(file_inventory(parent) == data['parent']['inventory'], 'Parent changed during stage')
    require(protected_snapshot(data['formal']) == data['frozen']['protected_formal_files']
        and file_inventory(PROJECT/'configs') == data['frozen']['configuration_sha256']
        and code_inventory() == data['frozen']['code_sha256'] and direct.public_pose_url() == data['frozen']['pose_public_url'],
        'Formal/configuration/code/managed URL changed during stage')
    require({str(p.relative_to(PROJECT)): digest(p) for p in old_request_paths(data['out'])}
        == data['frozen']['old_request_sha256'] and all(digest(data['formal']/n) == h for n, h in data['evidence'].used.items()),
        'Historical requests/native sources changed during stage')


def review(out, parent=PARENT, per_class=10, decisions_path=None, restage=False):
    if restage:
        require(out.is_dir() and (out/'input_manifest.json').is_file(), 'Restage requires an existing private review')
    elif out.exists():
        return review(out, parent, per_class, decisions_path, True)
    require_unsealed(out)
    frozen = read_json(out/'input_manifest.json') if restage else None
    data = prepare(out, parent, frozen['per_class'] if restage else per_class, False)
    if restage:
        assert_frozen(frozen, data['frozen'])
    default_decisions = out/'internal/source_visual_decisions.json'
    incoming = decision_input(decisions_path or (default_decisions if restage and default_decisions.exists() else None))
    records, old_decisions, previous_hash = review_history(out, data) if restage else ({}, {}, None)
    decisions = merge_decisions(records, old_decisions, incoming)
    rejected = {k for k, d in decisions.items() if not d['approved']}
    retained = [k for k in records if k not in rejected]
    keys = [k for k in select_tasks(data['rows'], data['usable'], data['quotas'], incoming['preferences'], retained,
        {r['source']['frame_id'] for r in records.values()}) if k not in records]
    require(bool(keys) or (restage and decisions != old_decisions), 'No new candidates or decisions; nothing to restage')
    if not restage:
        out.mkdir(parents=True)
        private_json(out/'input_manifest.json', data['frozen'])
        private_json(out/'protected_formal_before.json', data['frozen']['protected_formal_files'])
    internal = out/'internal'; internal.mkdir(exist_ok=True); internal.chmod(0o700)
    root = internal/'review'/f'round_{len(round_directories(out))+1:04d}'
    (root/'images').mkdir(parents=True); (root/'cases').mkdir()
    private_json(root/'review_input.json', dict(incoming, decisions=decisions))
    shortlist = []
    for order, key in enumerate(keys, len(records)+1):
        row = data['rows'][key]
        bounds = render_case(row, data['evidence'], root/'cases'/f'{key}.png')
        shutil.copyfile(data['formal']/row['image'], root/'images'/f'{key}.png')
        shortlist.append(dict(target_key=key, request_order=order, source=row, native_image=f'images/{key}.png',
            contact_crop=f'cases/{key}.png', crop_native_bounds=bounds,
            native_image_sha256=digest(root/'images'/f'{key}.png'), contact_crop_sha256=digest(root/'cases'/f'{key}.png'),
            **data['usable'][key], **pose_binding(key, data)))
    private_json(root/'shortlist.jsonl', shortlist, True)
    for start in range(0, len(shortlist), 6):
        for full in (False, True):
            contact(root, shortlist[start:start+6], f'{"full" if full else "crop"}_{start+1:02d}.png', full)
    private_json(root/'diagnostic.json', dict(requested_class_counts=data['quotas'], populations=data['populations'],
        quality_rejections=data['rejections'], new_shortlist=len(shortlist), retained=len(retained), rejected=len(rejected),
        parent_cumulative_count=len(data['parent']['proposals']), parent_new_drafts=data['parent']['new_count'],
        parent_independently_verified=bool(data['parent']['seals']), source_visual_review_performed=False))
    private_json(root/'round_manifest.json', dict(previous_round_sha256=previous_hash,
        input_manifest_sha256=digest(out/'input_manifest.json'), new_shortlist_keys=keys))
    private_json(root/'artifact_hashes.json', file_inventory(root))
    finish_stability(data, parent)
    after = out/'protected_formal_after.json'
    if after.exists():
        require(read_json(after) == data['frozen']['protected_formal_files'], 'Protected formal after inventory changed')
    else:
        private_json(after, protected_snapshot(data['formal']))
    return dict(state='awaiting_actual_crop_and_full_image_inspection', round=root.name,
        new_shortlist=len(shortlist), active_shortlist=len(retained)+len(shortlist), quotas=data['quotas'])


def approved_sources(out, data, decisions_path=None):
    records, previous, _ = review_history(out, data)
    path = decisions_path or out/'internal/source_visual_decisions.json'
    incoming = decision_input(path) if Path(path).exists() else decision_input()
    decisions = merge_decisions(records, previous, incoming)
    require(set(decisions) == set(records), 'Every shortlisted source needs an explicit inspected approval or rejection')
    keys = sorted((k for k, d in decisions.items() if d['approved']), key=lambda k: (data['rows'][k]['final_class_id'], k))
    require(bool(keys), 'No approved sources; never publish an empty pending batch')
    require(len(keys) == len({data['rows'][k]['frame_id'] for k in keys})
        and all(sum(data['rows'][k]['final_class_id'] == c for k in keys) <= data['quotas'][c] for c in CLASSES),
        'Approved tasks exceed quota or repeat a global frame')
    return keys, decisions, records


def request_record(key, order, data, decision):
    # Pure source record helper: it has no pub10 counts or parent orchestration.
    r = direct.request_record(key, order, data, decision)
    r.update(task_kind='remaining_followup_direct_human_coverage', propagation_seed_eligible=False,
        minimum_direct_manual_coverage_vertices=4,
        reviewed_original_rectangle=False, original_rectangle_review_only=False, human_edited=False,
        future_explicit_original_rectangle_no_change_review_requires_separate_metadata=True,
        future_no_change_review_is_not_manual_edit_or_propagation_seed=True,
        classification_ambiguous=decision.get('classification_ambiguous', False),
        classification_review_required=True, review_decision=decision)
    return r


def page(requests, data):
    e = lambda v: html.escape(str(v), quote=True)
    parent = data['parent']; pm = parent['manifest']; cards, table = [], []
    for c in range(1, 23):
        v = pm['classes'][str(c)]
        table.append(f'<tr><td>{c}</td><td>{v["total"]}</td><td>{v["missing"]}</td>'
            f'<td>{sum(r["class_id"] == c for r in requests)}</td></tr>')
    for r in requests:
        s, key = r['source'], r['target_key']
        old = (f'仅原矩形位姿历史；预期修订 r{r["existing_pose_revision"]}。保留位姿、标尺、传感器、选面、排除设置；预期修订不是覆盖授权。'
            if r['existing_pose_record'] else '无位姿当前记录及历史；仅提供原生图像和原矩形。')
        hashes = (f'<details><summary>既有记录保护指纹</summary><p>原始载荷 SHA256：{r["existing_pose_payload_raw_sha256"]}<br>'
            f'位姿／标尺／传感器／选面／排除 SHA256：{r["existing_pose_geometry_sha256"]}</p></details>' if r['existing_pose_record'] else '')
        flag = '类别候选存在歧义，请直接人工复核，可暂缓。' if r['classification_ambiguous'] else '候选分类待人工判断，不是语义真值。'
        cards.append(f'<article id="{e(key)}" data-class="{r["class_id"]}"><h2>{r["request_order"]:02d} · Class {r["class_id"]} · 待人工描绘</h2>'
            f'<p><a class="action" target="_blank" rel="noopener" href="{e(r["pose_annotation_url"])}">打开原位姿标注</a> <code>{e(key)}</code></p>'
            f'<p>{e(old)}</p>{hashes}<p>{e(flag)}</p><p>划分 {e(s["split"])} · 传感器策略 {e(s["policy_id"])} · '
            f'观察面 {e(s.get("viewpoint_candidate"))} · 采集组 {e(s["group_id"])}<br>图像 {e(s["frame_id"])}</p>'
            f'<figure><img loading="lazy" src="{e(r["contact_crop"])}" alt="原生局部和原矩形"><figcaption>橙框仅为原矩形，不是完成轮廓。</figcaption></figure>'
            f'<p>可描绘性检查（非人工类别或GT确认）：{e(r["source_visual_review_zh"])}</p>'
            f'<details><summary>完整原生图像</summary><img loading="lazy" src="{e(r["native_image"])}" alt="完整原生图像"></details>'
            '<p>真实闭合四点保持四点，不凑第五点，不强画凹槽。只在人工需要时修改并保存；类别可疑或结构不清可暂缓。</p></article>')
    return '''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>后续新图人工任务 · 待独立验收</title><style>@font-face{font-family:RequestSans;src:url('report-font.otf')}*{box-sizing:border-box}body{font:16px/1.65 RequestSans,sans-serif;background:#111923;color:#edf2f7;max-width:1200px;margin:auto;padding:20px;min-width:0}a{color:#8ed7ff}p,code,h1,h2,td,th,summary{overflow-wrap:anywhere}article,.notice{padding:16px;border:1px solid #536479;border-radius:10px;margin:18px 0;min-width:0}img{display:block;max-width:100%;height:auto}figure{margin:12px 0}figure img{width:100%;image-rendering:pixelated}.action{display:inline-block;padding:9px;background:#17496b;border-radius:6px}table{table-layout:fixed;width:100%;border-collapse:collapse}td,th{border:1px solid #536479;padding:6px}select{font:inherit;max-width:100%;padding:6px}[hidden]{display:none!important}@media(max-width:480px){body{padding:10px;font-size:15px}article,.notice{padding:10px}td,th{font-size:12px;padding:3px}h1{font-size:23px}h2{font-size:19px}}</style></head><body>
<h1>后续新图直接人工任务 · 待独立验收，尚未激活</h1><div class="notice"><strong>本批尚未保存，不是新增完成标签。</strong>
''' + f'<p>第十一版实际累计 {pm["proposals"]} 个不同帧，本轮新增机器候选 {parent["new_count"]}，仍待人工复核；本批仅 {len(requests)} 项待办，不提前计覆盖。</p>' + f'<p>类别3当前 {pm["classes"]["3"]["total"]} 张，本批最多补 {data["quotas"][3]} 张；六类请求总上限 {sum(data["quotas"].values())}，实际数量取决于严格来源检查及真实复核决定。</p>' + '''
<p>当前人工保存轮廓来源 1022 = 原605 + 上轮369份真实图册保存复核 + 新48份四点改绘；另2份原矩形经用户明确复核无需修改，仅计复核覆盖，不是人工改绘或传播种子。369份中260份轮廓变化、109份复核保持原候选，109份不称新增改绘。用户对话数字269与真实冻结证据369不同，以真实保存证据为准。</p>
<p>类别3、4、5、7、14、22，每类最多10张且不超过第十一版距100张的实际缺额；已满100的类别不再请求。全部旧请求50／51／86及所有命名空间、所有累计帧、图册全部639份及掩膜编辑／确认／暂缓／删除／隔离历史受保护；不是重画上一批50张。</p>
<p>有效真实闭合四点人工轮廓可计直接覆盖，但不是超过四点传播种子，不强加第五点。原矩形本身不算人工改绘；未来若用户明确说明原框无需修改，须另列复核元数据，不能伪造编辑或保存事件。已计入的原框2份不再请求。</p>
<p>Class 5可能存在多孔结构或候选分类歧义，允许直接交用户复核，不据此推断描错，也不自动确认类别。所有分类都是候选，不是真值；默认显示本批全部类别。</p>
<p>仅原生图像与原矩形，沿用原生50宽／14高／1000面积及对比度等严格门槛，不生成掩膜、假GT或模板，不承诺传播。所有研究确认、自动训练、机器人控制资格均关闭。不改生产库、配置、服务或既有位姿历史。</p></div>
<table><tr><th>类别</th><th>第十一版累计不同帧</th><th>距100缺额</th><th>本批待办</th></tr>''' + ''.join(table) + f'</table><p>筛选 <select id="request-filter"><option value="">全部本批类别</option>{"".join(f"<option>{c}</option>" for c in CLASSES)}</select> <span id="request-count">{len(requests)}</span> 张</p>' + ''.join(cards) + '''
<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;});</script>
<footer><p>独立验收及明确上线决定之前保持待办草稿；本构建器不会激活。<a href="FONT_LICENSE.txt">字体许可</a></p></footer></body></html>'''


def build(out, parent=PARENT, decisions_path=None):
    require_unsealed(out)
    frozen = read_json(out/'input_manifest.json')
    data = prepare(out, parent, frozen['per_class'], True)
    assert_frozen(frozen, data['frozen'])
    keys, decisions, reviewed = approved_sources(out, data, decisions_path)
    require(read_json(out/'protected_formal_before.json') == read_json(out/'protected_formal_after.json')
        == data['frozen']['protected_formal_files'], 'Worklist protected formal inventories changed')
    for folder in ('images', 'cases'):
        (out/folder).mkdir()
    requests = []
    for order, key in enumerate(keys, 1):
        r = request_record(key, order, data, decisions[key]); record = reviewed[key]
        root = out/'internal/review'/record['review_round']
        for field in ('native_image', 'contact_crop'):
            shutil.copyfile(root/record[field], out/r[field])
        r['crop_native_bounds'] = record['crop_native_bounds']
        requests.append(r)
    private_json(out/'requests.jsonl', requests, True)
    private_json(out/'internal/build_decisions.json', dict(schema=DECISION_SCHEMA, decisions=decisions))
    private_json(out/'internal/protected_targets.json', dict(keys=sorted(data['protected']), frames=sorted(data['protected_frames'])))
    private_json(out/'internal/class_population.json', data['populations'])
    private_json(out/'internal/used_image_hashes.json', data['evidence'].used)
    text = page(requests, data); (out/'report_zh.html').write_text(text); build_font(out, text)
    finish_stability(data, parent)
    counts = Counter(r['class_id'] for r in requests)
    public = ['report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'] + [r[f] for r in requests for f in ('native_image', 'contact_crop')]
    manifest = dict(schema='remaining_followup_direct_human_requests_v1', state='prepared_for_independent_verification',
        created_at=datetime.now(timezone.utc).isoformat(), classes=list(CLASSES), target_per_class=100,
        request_count=len(requests), class_counts={c: counts[c] for c in CLASSES}, requested_class_counts=data['quotas'],
        unfilled_requested_class_counts={c: data['quotas'][c]-counts[c] for c in CLASSES},
        parent_directory=str(parent.relative_to(PROJECT)), parent_publication_version=11,
        parent_manifest_sha256=digest(parent/'manifest.json'), parent_proposals_sha256=digest(parent/'proposals.jsonl'),
        parent_verification_binding=data['parent']['seals'], parent_file_inventory=data['parent']['inventory'],
        parent_cumulative_count=len(data['parent']['proposals']), parent_new_machine_drafts=data['parent']['new_count'],
        parent_class_counts=data['parent']['manifest']['classes'], parent_saved_human_contour_sources=1022,
        parent_source_accounting=dict(previous_saved=605, previous_batch_actually_saved=369, latest_modified_quads=48,
            latest_original_rectangle_review_only=2, original_reviews_are_edited=False, original_reviews_seed_eligible=False,
            conversational_candidate_count=269, actual_candidate_count_authority='immutable current and raw event evidence'),
        old_requests_and_all_cumulative_frames_protected=True, old_original_rectangle_review_keys=sorted(ORIGINAL_REVIEWS),
        source_seed_policy='Valid real quads count after saved intentional edits, never >4-point seeds; explicit original-box no-change reviews require separate metadata. No forced extra vertices.',
        formal_manifest_sha256=frozen['formal_manifest_sha256'], classification_sha256=frozen['classification_sha256'],
        classification_is_candidate_not_truth=True, requests_sha256=digest(out/'requests.jsonl'),
        input_manifest_sha256=digest(out/'input_manifest.json'), source_visual_decisions_sha256=digest(out/'internal/build_decisions.json'),
        review_round_hashes={p.name: digest(p/'artifact_hashes.json') for p in round_directories(out)},
        configuration_sha256=frozen['configuration_sha256'], database_logical_fingerprints=frozen['database_logical_fingerprints'],
        reused_parent_frozen_snapshots=frozen['snapshots'], snapshots_copied_into_worklist=False,
        live_stores_match_frozen_at_start_and_finish=True, protected_formal_files_verified=len(frozen['protected_formal_files']),
        protected_formal_before_sha256=digest(out/'protected_formal_before.json'), protected_formal_after_sha256=digest(out/'protected_formal_after.json'),
        quality_gates=QUALITY_GATES, quality_helper_sha256=digest(PROJECT/'scripts/build_mask_template_requests.py'),
        source_visual_inspections_required=True, public_assets={n: digest(out/n) for n in sorted(public)},
        private_request_payload_never_public=True, pose_public_url=frozen['pose_public_url'],
        selected_group_counts=dict(Counter(r['source']['group_id'] for r in requests)),
        selected_split_counts=dict(Counter(r['source']['split'] for r in requests)),
        selected_policy_counts=dict(Counter(r['source']['policy_id'] for r in requests)),
        selected_view_counts=dict(Counter(str(r['source'].get('viewpoint_candidate')) for r in requests)),
        production_database_writes=0, configuration_writes=0, service_writes=0, generated_polygons=0,
        completed_new_manual_labels=0, counts_as_completed_annotation=False, activated=False, published=False,
        human_confirmation_inferred=False, **dict.fromkeys(FALSE_FLAGS, False), code_sha256=digest(__file__))
    private_json(out/'manifest.json', manifest)
    private_json(out/'artifact_hashes.json', file_inventory(out))
    return dict(state=manifest['state'], request_count=len(requests), class_counts=manifest['class_counts'],
        public_assets=len(public), independent_verification_still_required=True)


def verify(out, parent=PARENT):
    """Read-only builder self-audit; never creates an independent successful seal."""
    manifest = read_json(out/'manifest.json'); artifacts = read_json(out/'artifact_hashes.json')
    actual = {n: h for n, h in file_inventory(out).items() if n != 'artifact_hashes.json' and n not in PARENT_AUDIT_NAMES}
    require(actual == artifacts, 'Worklist frozen file inventory changed')
    no_database_copies(out)
    require(not (out/'masks').exists() and not (out/'labelme').exists(), 'Worklist cannot contain generated masks/proposals')
    frozen = read_json(out/'input_manifest.json'); data = prepare(out, parent, frozen['per_class'], True)
    assert_frozen(frozen, data['frozen'])
    require(manifest['parent_file_inventory'] == data['parent']['inventory']
        and manifest['parent_verification_binding'] == data['parent']['seals'], 'Sealed parent inventory changed')
    keys, decisions, reviewed = approved_sources(out, data, out/'internal/build_decisions.json')
    requests = read_jsonl(out/'requests.jsonl'); counts = Counter(r['class_id'] for r in requests)
    require([r['target_key'] for r in requests] == keys and manifest['request_count'] == len(keys)
        and manifest['requests_sha256'] == digest(out/'requests.jsonl'), 'Sealed request keys/count/hash changed')
    for field, expected in (('class_counts', {str(c): counts[c] for c in CLASSES}),
            ('requested_class_counts', {str(c): data['quotas'][c] for c in CLASSES}),
            ('unfilled_requested_class_counts', {str(c): data['quotas'][c]-counts[c] for c in CLASSES})):
        require(manifest[field] == expected, 'Sealed quota/count changed: '+field)
    require(read_json(out/'protected_formal_before.json') == read_json(out/'protected_formal_after.json')
        == frozen['protected_formal_files'], 'Protected formal inventory changed')
    public = {'report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'}
    for order, r in enumerate(requests, 1):
        key = r['target_key']; expected = request_record(key, order, data, decisions[key])
        require({k: v for k, v in r.items() if k != 'crop_native_bounds'} == expected, 'Request payload/binding changed')
        record = reviewed[key]; root = out/'internal/review'/record['review_round']
        require(r['crop_native_bounds'] == record['crop_native_bounds'], 'Reviewed crop bounds differ')
        for field in ('native_image', 'contact_crop'):
            public.add(r[field]); require(digest(out/r[field]) == digest(root/record[field]), 'Published image differs from inspected source')
        require(key not in data['protected'] and r['source']['frame_id'] not in data['protected_frames'], 'Protected key/frame requested')
    require(set(manifest['public_assets']) == public and len(public) == 3+2*len(requests)
        and all(digest(out/n) == h for n, h in manifest['public_assets'].items()), 'Public allowlist/hash changed')
    text = (out/'report_zh.html').read_text()
    require(text == page(requests, data), 'Pending report content changed')
    require(not any(s in text for s in ('existing_pose_current_payload', 'current_payload_raw', '.sqlite', 'access_code', 'password')),
        'Private payload/credential in public report')
    from fontTools.ttLib import TTFont
    with TTFont(out/'report-font.otf') as font:
        require({ord(c) for c in text if '\u3400' <= c <= '\u9fff'} <= set(font.getBestCmap()), 'Chinese report glyph missing')
    finish_stability(data, parent)
    return dict(state='self_checks_passed_not_independent_verification', request_count=len(requests),
        independent_verification_still_required=True, activated=False)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--stage', choices=('review', 'restage', 'build', 'verify'), required=True)
    parser.add_argument('--output', type=Path, default=DEFAULT)
    parser.add_argument('--parent', type=Path, default=PARENT)
    parser.add_argument('--per-class', type=int, default=10)
    parser.add_argument('--decisions', type=Path, help='Explicit inspection decisions and optional selection preferences JSON')
    args = parser.parse_args(); parent = args.parent.resolve(); out = valid_output(args.output, parent)
    require(parent.is_relative_to(PROJECT/'outputs'), 'Parent must be a local outputs generation')
    require(args.stage != 'verify' or args.decisions is None, 'Verify uses the frozen build decisions only')
    cv2.setNumThreads(1)
    if args.stage in ('review', 'restage'):
        result = review(out, parent, args.per_class, args.decisions, args.stage == 'restage')
    elif args.stage == 'build':
        result = build(out, parent, args.decisions)
    else:
        result = verify(out, parent)
    print(json.dumps(result, ensure_ascii=False), flush=True)


if __name__ == '__main__':
    main()
