"""Immutable direct-human worklists from independently sealed publication 12.

Every stage is explicit. Review/restage only prepare private native-image
inspection rounds; build requires decisions for every inspected source. Verify
is read-only self-checking, never an independent seal or activation operation.
No database is copied into the worklist and no live store/config/service is
written. The separate independent verifier must not rewrite the pending HTML.

--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. Ambiguous, multishelf/multi-three-hole ambiguous, or clipped
sources must be rejected, not approved to fill a quota. Rejections and their
frames remain locked across rounds. Class 3 is complete and is never requested.
"""
from __future__ import annotations

import argparse
from collections import Counter
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_followup_requests as followup
from scripts import build_mask_remaining_direct_requests as direct
from pallet.cluster_targets import target_key

# Read-only, class/count-independent frozen helpers only. Never patch their
# globals or call either frozen builder's orchestration/selection functions.
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
alias_claim, original_review = followup.alias_claim, followup.original_review
original_pose_only, merge_decisions = followup.original_pose_only, followup.merge_decisions

CLASSES = (4, 5, 7, 14, 22)
COMPLETED_CLASSES = (3, 4, 5, 7, 14, 22)
FALSE_FLAGS, QUALITY_GATES = direct.FALSE_FLAGS, direct.QUALITY_GATES
PARENT = PROJECT/'outputs/pallet_mask_remaining_round2_v1'
DEFAULT = PROJECT/'outputs/pallet_mask_remaining_round2_requests_v1'
POSE, GALLERY, CLASSIFICATION = direct.POSE, direct.GALLERY, direct.CLASSIFICATION
PARENT_AUDIT_NAMES = direct.PARENT_AUDIT_NAMES
PARENT_VERIFIER = 'scripts/verify_mask_remaining_round2.py'
OLD_ORIGINAL_REVIEWS = dict(followup.ORIGINAL_REVIEWS)
NEW_ORIGINAL_REVIEWS = {
    '0f62405fc643c71371c8a0ec': (4, 1),
    '7041455b447a160ccc16d9df': (4, 1),
    'db94cf18b0c6e9f8641a9be0': (4, 1),
}
ORIGINAL_REVIEWS = OLD_ORIGINAL_REVIEWS | NEW_ORIGINAL_REVIEWS
OLD_REQUEST_DIRS = followup.OLD_REQUEST_DIRS + ('pallet_mask_remaining_followup_requests_v2',)
DECISION_SCHEMA = 'remaining_round2_source_decisions_v1'
PREFERENCE_FIELDS = dict(followup.PREFERENCE_FIELDS)
RISK_FIELDS = ('classification_ambiguous', 'multishelf_ambiguous', 'multi3hole_ambiguous', 'clipped_source')


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_round2_requests_v[1-9][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_round2_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 parent_seal(parent, manifest, required=True):
    seals, values = {}, []
    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') == 12
            and value.get('manifest_sha256') == digest(parent/'manifest.json')
            and value.get('proposals_sha256') == digest(parent/'proposals.jsonl'),
            'Publication 12 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/PARENT_VERIFIER),
            'Publication 12 independent verifier provenance differs')
        seals[name] = digest(path); values.append(value)
    require(not values or all(v == values[0] for v in values), 'Conflicting parent independent seals')
    require(bool(seals) or not required, 'Review/build requires independently verified publication 12')
    return seals


def load_parent(parent, require_seal=True):
    manifest = read_json(parent/'manifest.json')
    require(manifest.get('publication_version') == 12, 'Expected publication 12')
    validation = read_json(parent/'generation_validation.json')
    require(validation.get('state') == 'self_checks_passed_not_independent_verification'
        and validation.get('publication_version') == 12, 'Publication 12 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)
        member(parent, name)
    for field, expected in manifest.items():
        if field.endswith('_sha256'):
            for extension in ('.jsonl', '.json'):
                name = field[:-7]+extension
                if name in inventory:
                    require(inventory[name] == expected, 'Parent bound 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) == 1296 and len(completed) == 54
        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 1296 + completed54 + 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) == {3: 4, 4: 10, 5: 10, 7: 10, 14: 10, 22: 10}
        and {p['target_key'] for p in boxes} == set(NEW_ORIGINAL_REVIEWS)
        and len(edited) == 51 and all(p.get('human_edited') is True for p in edited)
        and all(p.get('human_edited') is False and p.get('propagation_seed_eligible') is False for p in boxes)
        and all(len(p['polygon']) == (8 if p['class_id'] == 3 else 4) for p in completed)
        and all(p.get('propagation_seed_eligible') is False for p in edited if p['class_id'] != 3),
        'Completed54 must distinguish 4 eight-point/47 quad edits from 3 non-edited original-box reviews')
    require({p['target_key'] for p in proposals if original_review(p)} == set(ORIGINAL_REVIEWS),
        'All five original-box reviews must remain separate and protected')
    for p in proposals:
        if p['target_key'] in ORIGINAL_REVIEWS:
            cls, revision = ORIGINAL_REVIEWS[p['target_key']]
            require(p['class_id'] == cls and p.get('target_expected_revision') == revision
                and p.get('human_edited') is False and p.get('propagation_seed_eligible') is False,
                'Protected original-box review class/revision/edit/seed changed')
    counts = Counter(p['class_id'] for p in proposals)
    require(counts[3] == 100, 'Publication 12 must preserve completed Class 3; never request it again')
    for cls in range(1, 23):
        v = manifest['classes'][str(cls)]
        alias_claim(v, ('total', 'preview'), counts[cls], True)
        alias_claim(v, ('distinct_frames',), counts[cls], True)
        alias_claim(v, ('missing',), 100-counts[cls], True)
    for names, expected in ((('previous_proposals',), 1296), (('base_proposals',), 1350),
            (('new_proposals', 'new_machine_pending'), len(new)),
            (('modified_manual_proposals', 'manual_modified_added'), 51),
            (('reviewed_original_rectangle', 'original_rectangle_review_only'), 5),
            (('saved_human', 'saved_human_contour_source'), 1258),
            (('saved_pose_human', 'modified_pose_source_records', 'all_manual_sources'), 434),
            (('saved_gallery_human',), 824), (('db_stored_human_review',), 1263)):
        alias_claim(manifest, names, expected)
    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), completed=completed)


def protection(rows, current, events, gallery_keys, proposals, old_requests, quarantine=()):
    # An old explicit original-box review is never a new pose-only task.
    return followup.protection(rows, current, events, gallery_keys, proposals, old_requests,
        set(quarantine) | (set(ORIGINAL_REVIEWS) & set(rows)))


def old_request_paths(out):
    """Protect requests in every namespace/archive, not only mask-named 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/latest54 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[6:8])
        and len(indexed(read_jsonl(mandatory[-1]))) == 54, 'Historical request scope changed')
    latest = mandatory[-1].parent
    seal = read_json(latest/'independent_verification.json')
    require(seal.get('state') == 'passed' and seal.get('request_count') == 54
        and seal.get('manifest_sha256') == digest(latest/'manifest.json')
        and seal.get('requests_sha256') == digest(latest/'requests.jsonl'),
        'Latest54 requests require their matching independent seal')
    requests, hashes = [], {}
    # Shortlists alone are not published requests. Even an unsealed requests.jsonl
    # is conservatively protected, but never counted as completed or as a seed.
    for path in sorted(old_request_paths(out)):
        require(not path.is_symlink() and path.resolve().is_relative_to(PROJECT/'outputs'),
            'Historical request symlink/escape is not allowed')
        hashes[str(path.relative_to(PROJECT))] = digest(path)
        for r in read_jsonl(path):
            key, source = r['target_key'], 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/build_mask_remaining_round2_requests.py', PARENT_VERIFIER}
    return {n: digest(PROJECT/n) for n in sorted(names)}


def original_records(parent):
    names = ('reviewed_original_rectangle_source_records.jsonl', 'review_only_source_records.jsonl',
        'original_rectangle_review_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')
    paths = [parent/n for n in names if (parent/n).is_file()]
    require(bool(paths), 'Separate original-box review source records are required')
    records = read_jsonl(paths[0])
    require(all(read_jsonl(p) == records for p in paths), 'Conflicting original-box source aliases')
    return records


def exact_source_records(parent, current, current_raw, events, gallery):
    """Bind all 1258 contours and five separately statement-backed box reviews."""
    humans = read_jsonl(parent/'all_manual_sources.jsonl'); originals = original_records(parent)
    gallery_records = read_jsonl(parent/'gallery_source_records.jsonl')
    require(len(indexed(humans)) == 434 and len(indexed(originals)) == 5
        and set(indexed(originals)) == set(ORIGINAL_REVIEWS) and len(indexed(gallery_records)) == 824,
        'Parent actual modified434/original-review5/gallery824 source records differ')
    old_humans = indexed(read_jsonl(parent/'parent_evidence/all_manual_sources.jsonl'))
    old_gallery = indexed(read_jsonl(parent/'parent_evidence/gallery_source_records.jsonl'))
    human_by_key, gallery_by_key = indexed(humans), indexed(gallery_records)
    require(len(old_humans) == 383 and len(old_gallery) == 639
        and set(old_humans) <= set(human_by_key) and set(old_gallery) <= set(gallery_by_key),
        'Inherited modified383/gallery639 source scope changed')
    pin_fields = ('current_payload', 'current_payload_raw', 'current_payload_sha256',
        'current_payload_raw_sha256', 'human_event_id', 'human_event_payload_raw', 'human_event_sha256')
    for old_records, records in ((old_humans, human_by_key), (old_gallery, gallery_by_key)):
        for key, old in old_records.items():
            require(all(records[key].get(f) == old.get(f) for f in pin_fields),
                'Inherited pose/gallery current/raw/event source pins changed')
    newly_modified = set(human_by_key)-set(old_humans)
    require(len(newly_modified) == 51, 'Exactly51 newly modified pose sources are required')
    event_by_id = {i: (k, rev, raw) for i, k, rev, raw in events}
    require(len(event_by_id) == len(events), 'Duplicate pose event identity')
    latest = {k: (i, rev, raw) for i, k, rev, raw in events}
    history = {}
    for _, key, _, raw in events:
        history.setdefault(key, []).append(json.loads(raw))
    old_originals = indexed(original_records(parent/'parent_evidence'))
    require(set(old_originals) == set(OLD_ORIGINAL_REVIEWS), 'Inherited two original reviews changed scope')
    statements = {
        'old': read_json(parent/'parent_evidence/review_completion_statement.json'),
        'new': read_json(parent/'review_completion_statement.json'),
    }
    for r in humans+originals:
        key = r['target_key']; value, raw = current.get(key), 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)
            and latest.get(key, (None, None, None))[1:] == (value['revision'], raw),
            'Counted pose source current/raw latest 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:
            statement = statements['old' if key in OLD_ORIGINAL_REVIEWS else 'new']
            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 r['source']['final_class_id'] == ORIGINAL_REVIEWS[key][0]
                and latest[key] == (event_id, revision, event_raw)
                and all(original_pose_only(v, r['source']) for v in history[key])
                and r.get('user_statement_sha256') == sha(statement)
                and key in statement.get('scoped_request_keys', [])
                and key in statement.get('reviewed_original_rectangle_keys', [])
                and all(statement.get(f) is False for f in
                    ('creates_human_event', 'confirms_ground_truth', 'authorizes_propagation')),
                'Original-box review requires exact unmodified history, latest event and its own statement')
            if key in OLD_ORIGINAL_REVIEWS:
                require(r == old_originals[key], 'Inherited original-box review source pins changed')
        else:
            require(not direct.original_rectangle(value.get('polygon'), r['source']),
                'An original rectangle cannot be counted as a modified contour')
            if key in newly_modified:
                require(latest[key] == (event_id, revision, event_raw),
                    'Each newly modified manual source must bind its exact latest real revision/event')
    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_gallery = {k: (i, rev, raw) for i, (k, rev, raw) in gallery_events.items()}
    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_gallery[key] == (r['human_event_id'], 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')
    previous_new = indexed(read_jsonl(parent/'parent_evidence/new_proposals.jsonl'))
    require(len(previous_new) == 185 and set(previous_new) == set(gallery_by_key)-set(old_gallery),
        'All185 previous machine targets must have new actual gallery saves; no inferred completion')
    changed = sum(gallery_by_key[k]['current_payload'].get('polygon') != p['polygon'] for k, p in previous_new.items())
    require(changed == 132 and len(previous_new)-changed == 53,
        'Actual185 gallery saves must distinguish132 changed from53 inspected unchanged')
    human_keys = set(indexed(humans)) | set(raw_current)
    require(len(human_keys) == 1258 and not human_keys & set(ORIGINAL_REVIEWS),
        '1258 saved contour sources must exclude the five original-box reviews')
    return human_keys


def frozen_snapshots(parent, manifest):
    specs = read_json(parent/'snapshot_manifest.json'); snapshots, fingerprints = {}, {}
    for kind, live, field in (('pose', POSE, 'snapshot_sha256'), ('gallery', GALLERY, 'gallery_snapshot_sha256')):
        spec = specs[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')
        saved, events = (4916, 11698) if kind == 'pose' else (824, 890)
        require(fingerprints[kind]['table_counts'][table] == spec['saved'] == manifest[prefix+'_saved'] == saved
            and fingerprints[kind]['table_counts']['events'] == spec['events'] == manifest[prefix+'_events'] == events,
            'Parent complete pose4916/11698 or gallery824/890 inventory differs')
        require(database_fingerprint(live) == fingerprints[kind], kind+' live contents differ from frozen publication 12')
        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=True):
    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 and set(ORIGINAL_REVIEWS) <= set(rows), '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 12')
    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'} | set(RISK_FIELDS)
            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 all(type(decision.get(f, False)) is bool for f in RISK_FIELDS),
            'Each approval/rejection requires actual crop/full inspection and a nonempty note')
        require(not decision['approved'] or not any(decision.get(f, False) for f in RISK_FIELDS),
            'Ambiguous multishelf/multi3hole/classification or clipped sources must be rejected')
    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(set(quotas) == set(CLASSES) and all(type(n) is int and 0 <= n <= 10 for n in quotas.values()),
        'Only actual five-class quotas are allowed')
    require(len(set(selected)) == len(selected) and all(k in usable and rows[k]['final_class_id'] in CLASSES for k in selected),
        'Retained task keys repeat or leave the strict usable pool')
    require(len({rows[k]['frame_id'] for k in selected}) == len(selected), 'Retained task frames 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 no_database_copies(out):
    for path in out.rglob('*'):
        require(not path.is_symlink(), 'Worklist symlinks are not allowed')
        if path.is_file():
            name = path.name.lower()
            require(not ('.sqlite' in name or re.search(r'\.db(?:3)?(?:\.|$)', name)
                or name.endswith(('-wal', '-shm', '-journal'))), 'No private database copies, including backups, are allowed')
            with path.open('rb') as stream:
                require(stream.read(16) != b'SQLite format 3\x00', 'No private database copies, including disguised files, are allowed')


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', 'FONT_LICENSE.txt')),
        'Never overwrite partially built public assets')


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')
        incoming = decision_input(root/'review_input.json'); decisions = merge_decisions(records, 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]
        expected = select_tasks(data['rows'], data['usable'], data['quotas'], incoming['preferences'], retained,
            {r['source']['frame_id'] for r in records.values()})
        new_records = read_jsonl(root/'shortlist.jsonl'); new_keys = [k for k in expected if k not in records]
        require([r['target_key'] for r in new_records] == new_keys == info['new_shortlist_keys'],
            '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 r['request_order'] == len(records)+1
                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(r['native_image'] == f'images/{key}.png' and r['contact_crop'] == f'cases/{key}.png'
                and digest(member(root, r['native_image'])) == r['native_image_sha256'] == digest(data['formal']/r['source']['image'])
                and digest(member(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 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')
    no_database_copies(data['out'])


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
    # Even private review waits for the pub12 seal: failed pre-seal reports must
    # never become immutable staging inputs to the new worklist.
    data = prepare(out, parent, frozen['per_class'] if restage else per_class, True)
    if restage:
        assert_frozen(frozen, data['frozen'])
    default = out/'internal/source_visual_decisions.json'
    incoming = decision_input(decisions_path or (default if restage and default.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 = Path(decisions_path) if decisions_path else out/'internal/source_visual_decisions.json'
    require(decisions_path is None or path.is_file(), 'Explicit decisions file does not exist')
    incoming = decision_input(path) if 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):
    r = direct.request_record(key, order, data, decision)
    r.update(task_kind='remaining_round2_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 review_binding(out, record, decision):
    root = out/'internal/review'/record['review_round']
    return dict(review_round=record['review_round'], round_manifest_sha256=digest(root/'round_manifest.json'),
        shortlist_sha256=digest(root/'shortlist.jsonl'), native_image_sha256=record['native_image_sha256'],
        contact_crop_sha256=record['contact_crop_sha256'], canonical_source_row_sha256=sha(record['source']),
        decision_sha256=sha(decision))


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 '')
        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>候选分类待人工判断，不是语义真值。</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"]} 个不同帧 = 完整保留第十一版1296 + 上批54份人工任务覆盖 + 本轮新增机器候选 {parent["new_count"]}；新增机器仍待人工复核。本批仅 {len(requests)} 项待办，不提前计覆盖。</p>' + f'<p>Class 3已满100张，不再请求。仅类别4、5、7、14、22，每类最多10张且不超过第十二版距100张的实际缺额；五类本批总上限 {sum(data["quotas"].values())}。</p>' + '''
<p>实际保存轮廓来源1258 = 434份位姿改绘 + 824份图册保存复核；另5份原矩形明确复核无需修改，单独计复核覆盖，数据库已存复核合计1263，不是人工改绘或传播种子。本构建器未创建任何新编辑或完成标签。</p>
<p>用户明确已完成上一批185个机器候选和54个人工任务，未改动也已检查。185份全部真实保存复核：132份轮廓变化、53份保持原候选，不称185份新增改绘。图册824份当前记录／890个事件；其中185个新目标对应201个事件，旧639份保持不变。</p>
<p>54个人工目标全部有真实新修订和精确最新事件：51份有效改绘 = 4份Class 3八点 + 47份其他类别四点；另3份Class 4原框复核r1，与旧2份原框分开绑定各自用户声明。位姿4916份当前记录／11698个事件，54个新目标对应145个事件；旧383份真实改绘及2份原框复核保持不变。</p>
<p>旧45份仅对话无需改动和更早42份未复核继续保留，不将42份推断为本次已复核，不扫入传播种子。原生超过四点来源池599 = 位姿45 + 图册554；Class 3已满，不能因此再派任务。</p>
<p>全部旧请求86／51／50／54、所有命名空间、所有第十二版累计帧、图册824全部目标及所有事件、所有掩膜编辑／确认／暂缓／删除／隔离历史受保护；五份原框复核绝不重派。不是要求重画上批54份或旧四点标签。</p>
<p>真实闭合四点人工轮廓可计直接覆盖，但不是超过四点传播种子，不强加第五点。未来用户明确原框无需修改须另列复核元数据，不能伪造编辑或事件。仅原矩形位姿历史可用于独立新任务，但既有完整载荷、修订、位姿、标尺、选面等必须原样保护。</p>
<p>Class 5等候选存在多层货架／多组三孔歧义，或目标被裁切时，本轮拒绝该来源并换新图；不能为凑数批准。已通过原图和局部可描绘性检查也不是人工类别确认。所有分类都是候选，不是真值；默认显示全部本批类别。</p>
<p>仅原生图像与原矩形，沿用原生50宽／14高／1000面积／35对比度等全部严格门槛，不放宽。原始20768文件及12344目标、原划分／传感器／观察面绑定不变；不生成掩膜、假GT或模板，不承诺传播。研究确认、自动训练、机器人控制资格全部关闭。不改生产库、配置、服务、正式GT、PCD、历史或旧ZIP。</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 source_accounting():
    return dict(saved_human_contours=1258, pose_modified_sources=434, gallery_saved_sources=824,
        original_rectangle_review_only=5, stored_human_review_coverage=1263,
        latest_machine_actually_saved=185, latest_machine_polygon_changed=132, latest_machine_saved_unchanged=53,
        latest_manual_tasks=54, latest_manual_modified=51, latest_manual_eight_point_class3=4,
        latest_manual_modified_quads=47, latest_manual_original_rectangle_review_only=3,
        inherited_original_rectangle_review_only=2, old_conversation_no_change=45, older_unreviewed_preserved=42,
        original_reviews_are_edited=False, original_reviews_seed_eligible=False,
        actual_candidate_count_authority='immutable current and exact latest raw event evidence')


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']
        r['source_visual_review_binding'] = review_binding(out, record, decisions[key]); 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_round2_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},
        completed_class3_not_requested=True, parent_directory=str(parent.relative_to(PROJECT)), parent_publication_version=12,
        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=1258,
        parent_source_accounting=source_accounting(), old_requests_and_all_cumulative_frames_protected=True,
        old_original_rectangle_review_keys=sorted(ORIGINAL_REVIEWS),
        source_seed_policy='Real saved valid quads count as direct coverage, never >4-point seeds; original-box reviews require separate actual provenance. No forced 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, ambiguous_multishelf_multi3hole_or_clipped_sources_rejected=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 self-audit: no passed seal and no pending-page rewriting."""
    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')
    require(manifest['classes'] == list(CLASSES) and manifest['parent_publication_version'] == 12
        and manifest['parent_source_accounting'] == source_accounting()
        and manifest['completed_class3_not_requested'] is True, 'Publication12 source accounting/scope 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])
        record = reviewed[key]; root = out/'internal/review'/record['review_round']
        expected.update(crop_native_bounds=record['crop_native_bounds'],
            source_visual_review_binding=review_binding(out, record, decisions[key]))
        require(r == expected, 'Request payload/binding changed')
        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(member(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 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()
