"""Publication 8: continue the quota from actual saved human masks, never claims.

Only a fresh output directory is written. A genuine modified four-point manual
mask counts as human coverage, but is never a propagation/rendering template.
The frozen publication-7 generator and original registration engine are reused
without mutation. Independent verification/publication is a separate operation.
"""
from __future__ import annotations

import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
import hashlib
import html
import json
from pathlib import Path
import shutil

import cv2
import numpy as np
from PIL import Image, ImageDraw

from . import mask_quota_100 as legacy
from . import mask_quota_completion as original
from .cluster_targets import digest, protected_snapshot
from .mask_quota_saved_extension import file_inventory, load_formal_evidence
from .mask_template_continue import attempt_target, sha
from .mask_template_refined import (CLASSES, QUARANTINE, read_jsonl, readonly,
    select_diverse, snapshot_database, verify_history_preserved, write_jsonl)
from .mask_template_transfer import (AUTO_EVENTS, PROJECT, annotation_inventory,
    overlay, package_preview, unchanged_rectangle, write_json)
from .pose_review_geometry import canonical, polygon_value, raster_mask

VERSION = 'direct_human_union_quota100_continue_v1'
PUBLICATION_VERSION = 8
TARGET_PER_CLASS = 100
GENERATION_NAMESPACE = 'quota100_continue_generation'
PARENT = PROJECT/'outputs/pallet_mask_quota_100_v2'
OUTPUT = PROJECT/'outputs/pallet_mask_quota_100_continue_v1'
REQUESTS = PROJECT/'outputs/pallet_mask_quota_100_requests_v2'
SOURCE_PUBLICATIONS = dict(legacy.SOURCE_PUBLICATIONS)
SOURCE_PUBLICATIONS[7] = PARENT
FALSE_FLAGS = original.FALSE_FLAGS
POSE_ORIGIN, GALLERY_ORIGIN = original.POSE_ORIGIN, original.GALLERY_ORIGIN
MANUAL_SCHEMA = original.MANUAL_SCHEMA
PARENT_PINS = {
    'manifest.json': 'f90a847a4ddf51fde32c7f1e2cd5a5082a76fcfd3f7295ff48e1a6630f0b772c',
    'verification.json': 'f68664e4f335ec8aed0b6f6ce8b1a623d84887a1976c227ca9303809ffefade2',
    'proposals.jsonl': '397bb3fc39f2305f4bafa28b0b77d446e1867a5c52cae18d1a1c95ed46282e64',
    'artifact_hashes.json': '466ea1c895fed79da711f60a13e8f6f55bee1635246200ea841af6d883897338',
    'template_inventory.json': '05884d5d63752ff0937db1a356cfe36d2168b86c0103849f6401a7e499fa95fd',
    'all_manual_sources.jsonl': 'efdd431eb0283fa60682d582a977f4fc61e07ce3df51797200d773395109ce97',
    'manual_proposals.jsonl': '458649339a32998655bbf367a9e3f15329dce76e63eb8d784d3352347546dede',
    'manual_source_records.jsonl': 'c256e1b758a026ecc210e2446144737832270cd658518b2b5cc529089d45e6f5',
    'new_proposals.jsonl': '718167efd033c885c6b12a386932cf019b46e063eb8f18f78c0e9fae94a1debc',
}
REQUEST_PINS = {
    'manifest.json': '3a41f88be99d6eeef3bf70660355376560b503afafaf067e8a8c07fde936a936',
    'requests.jsonl': 'de8342da1ac56b82009f4a96f664fa5470b3c987774873fa754b827a5db59f23',
    'verification.json': '35e2529b7bed52cc201d1dd690d8ab9510f68973c8f5a66b41b6fbc33ad6ce91',
}
IDENTITY_FIELDS = ('target_key', 'target_id', 'frame_id', 'split', 'group_id',
    'box_index', 'bbox', 'size', 'source_pcd_sha256', 'policy_id')
read_json, indexed, active_polygon = legacy.read_json, legacy.indexed, legacy.active_polygon


def exact_manual_source(db, key, row, pose_sha):
    """Recover real human provenance from raw events, including four-point edits.

    Automatic normalization is not a human edit. Never infer a missing event or
    add vertices to make a source pass the strictly >4-vertex seed inventory.
    """
    values = db.execute('SELECT revision,payload FROM annotations WHERE target_key=?', (key,)).fetchall()
    if len(values) != 1:
        raise ValueError('Manual source lacks unique current payload')
    revision, raw = values[0]; value = json.loads(raw)
    if (value.get('target_key') != key or value.get('revision') != revision or
            value.get('state') != 'draft' or len(value.get('polygon', [])) < 4 or
            unchanged_rectangle(value.get('polygon'), row) or
            any(value.get(flag, False) is not False for flag in FALSE_FLAGS) or
            any(value.get('source', {}).get(f) != row[f] for f in IDENTITY_FIELDS)):
        raise ValueError('Manual source is not an active modified human draft')
    polygon_value(value['polygon'], *row['size'])
    human = None
    for event_id, event_revision, event_raw in db.execute(
            'SELECT id,revision,payload FROM events WHERE target_key=? ORDER BY id', (key,)):
        event = json.loads(event_raw)
        if event.get('target_key') != key or event.get('revision') != event_revision:
            raise ValueError('Manual event relational identity mismatch')
        if event.get('event_kind') not in AUTO_EVENTS:
            human = event_id, event_revision, event_raw, event
    if human is None:
        raise ValueError('Manual source has no actual human event')
    event_id, event_revision, event_raw, event = human
    if (event_revision > revision or event.get('state') != 'draft' or
            event.get('polygon') != value['polygon'] or
            any(event.get('source', {}).get(f) != row[f] for f in IDENTITY_FIELDS) or
            any(event.get(flag, False) is not False for flag in FALSE_FLAGS)):
        raise ValueError('Latest actual human event does not match current manual source')
    event_sha = hashlib.sha256(event_raw.encode()).hexdigest()
    pose_review = dict(target_key=key, snapshot_sha256=pose_sha, revision=revision,
        payload_sha256=sha(value), human_polygon_revision=event_revision,
        human_event_sha256=event_sha, polygon_sha256=sha(value['polygon']))
    metadata = dict(target_key=key, class_id=row['final_class_id'], split=row['split'],
        snapshot_revision=revision, current_payload_sha256=sha(value),
        human_polygon_revision=event_revision, human_event_sha256=event_sha,
        vertex_count=len(value['polygon']), template_human_confirmed=False,
        origin=POSE_ORIGIN, pose_review=pose_review)
    four = len(value['polygon']) == 4
    record = dict(schema='saved_pose_mask_source_freeze_v1', target_key=key,
        snapshot_sha256=pose_sha, current_revision=revision, current_payload_sha256=sha(value),
        current_payload_raw=raw, current_payload=value,
        current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
        human_event_id=event_id, human_polygon_revision=event_revision,
        human_event_sha256=event_sha, human_event_payload_raw=event_raw,
        human_event_payload=event, polygon_sha256=sha(value['polygon']),
        vertex_count=len(value['polygon']), manual_four_point_source=four,
        propagation_seed_eligible=not four)
    return value, metadata, record


def manual_source_proposals(db, requests, pose_templates, current, rows, previous,
                            pose_sha, formal_sha, classification_sha, quarantine=()):
    indexed(requests)
    previous_keys = set(indexed(previous))
    frames = {p['source']['frame_id'] for p in previous}
    direct = original.seed_union(pose_templates, {}, pose_sha, quarantine)
    result, records = [], []
    for request in sorted(requests, key=lambda r: r['target_key']):
        key = request['target_key']; row = rows[key]
        if key in previous_keys or row['frame_id'] in frames or key in quarantine:
            raise ValueError('Manual source repeats a published frame or is quarantined')
        if (request['class_id'] != row['final_class_id'] or
                request['source']['formal_manifest_sha256'] != formal_sha or
                any(request['source'].get(f) != row[f] for f in IDENTITY_FIELDS+('viewpoint_candidate',))):
            raise ValueError('Manual request source identity changed')
        value, metadata, record = exact_manual_source(db, key, row, pose_sha)
        if current.get(key) != value:
            raise ValueError('Manual source differs from snapshot inventory')
        four = len(value['polygon']) == 4
        if not four and (key not in direct or original.template_metadata(direct[key]) != metadata):
            raise ValueError('Manual source lacks a matching direct human seed')
        if four and key in pose_templates:
            raise ValueError('Four-point manual source entered the seed inventory')
        frames.add(row['frame_id'])
        p = dict(schema=MANUAL_SCHEMA, generation_schema=VERSION, origin=POSE_ORIGIN,
            target_key=key, class_id=row['final_class_id'], source=row,
            polygon=value['polygon'], vertex_count=len(value['polygon']),
            status='human_edited_draft_pending_confirmation', human_edited=True,
            source_label_kind='human_mask_source_manual_template_draft',
            manual_source_kind='completed_manual_request', **dict.fromkeys(FALSE_FLAGS, False),
            pose_snapshot_saved=True, pose_store_written=False, gallery_store_written=False,
            machine_transfer_performed=False, new_human_edit_created=False,
            manual_four_point_source=four, propagation_seed_eligible=not four,
            mask_semantics='saved_human_fork_face_contour_pending_confirmation',
            rendering_id=GENERATION_NAMESPACE+(':manual_source:' if four else ':')+key,
            target_expected_revision=value['revision'], target_snapshot_payload_sha256=sha(value),
            snapshot_sha256=pose_sha, formal_manifest_sha256=formal_sha,
            class_assignments_sha256=classification_sha, metrics={},
            flags=['manual_source_not_machine_transfer', 'saved_human_mask_requires_confirmation']+
                (['four_point_source_coverage_only_not_propagation_template'] if four else []),
            manual_request_sha256=sha(request), original_pose_url=request.get('pose_annotation_url'),
            geometry_pose_policy='original_pose_unchanged; independent_gallery_review_not_imported')
        # Four-point provenance is a source, deliberately not a template.
        p['human_source' if four else 'template'] = metadata
        result.append(p); records.append(record)
    return result, records


def quota_counts(previous, new, reviews, current, pose_templates, inherited_manual=(),
                 manual=(), goal=TARGET_PER_CLASS):
    """Coverage and propagation eligibility are separate, key-deduplicated facts."""
    combined = list(previous)+list(manual)+list(new)
    by_key = indexed(combined)
    if len({p['source']['frame_id'] for p in combined}) != len(combined):
        raise ValueError('Quota repeats a target or frame')
    if any(p['class_id'] not in CLASSES for p in combined):
        raise ValueError('Unexpected quota class')
    inherited = indexed(inherited_manual)
    if not set(inherited) <= set(indexed(previous)):
        raise ValueError('Inherited manual source absent from parent')
    explicit = dict(inherited); explicit.update(indexed(manual))
    gallery_keys = {k for k, v in reviews.items() if k in by_key and active_polygon(v)
        and v.get('human_edited') is True and v.get('event_kind') == 'human_mask_gallery_revision'
        and current.get(k, {}).get('state') not in ('deleted', 'deferred')}
    pose_keys, four_keys = set(), set()
    for key, p in explicit.items():
        value = current.get(key)
        if not value or value.get('state') != 'draft' or any(value.get(f) for f in FALSE_FLAGS):
            continue
        if (active_polygon(value) and key in pose_templates and
                pose_templates[key]['polygon'] == value['polygon']):
            pose_keys.add(key)
        elif (p.get('manual_four_point_source') is True and p.get('propagation_seed_eligible') is False
                and 'template' not in p and len(value.get('polygon', [])) == 4
                and p['polygon'] == value['polygon']
                and p['target_expected_revision'] == value['revision']
                and p['target_snapshot_payload_sha256'] == sha(value)
                and p.get('human_source', {}).get('human_event_sha256')):
            pose_keys.add(key); four_keys.add(key)
    result = {}
    for cls in CLASSES:
        old = [p for p in previous if p['class_id'] == cls]
        human = [p for p in manual if p['class_id'] == cls]
        added = [p for p in new if p['class_id'] == cls]
        keys, old_keys = {p['target_key'] for p in old+human+added}, {p['target_key'] for p in old}
        saved_gallery, saved_pose = keys & gallery_keys, keys & pose_keys
        saved = saved_gallery | saved_pose; total = len(keys)
        if total > goal:
            raise ValueError('Quota exceeds goal')
        pending = len(old_keys-saved)
        requested = sum(p.get('manual_source_kind') == 'completed_manual_request' for p in human)
        reused = len(human)-requested
        result[cls] = dict(old_total=len(old), manual_added=len(human), newmanual=requested,
            manual_requested=requested, manual_existing_reused=reused, added_saved_human=len(human),
            inherited_manual_sources=len(old_keys & set(inherited)),
            existing_saved_pose_human=len(old_keys & saved_pose), saved_gallery_human=len(saved_gallery),
            saved_pose_human=len(saved_pose), saved_human=len(saved), saved_fine_edits=len(saved)-len(keys & four_keys),
            manual_four_point_sources=len(keys & four_keys), prior_machine_pending=pending,
            old_pending_machine=pending, new_candidates=len(added), new_machine_pending=len(added),
            total=total, missing=goal-total, goal=goal, target_per_class=goal, distinct_frames=total)
    return result


def existing_human_reuse(pose_templates, current, rows, previous, requested, pose_sha,
                        formal_sha, classification_sha, quarantine=()):
    candidates, inventory = legacy.existing_human_reuse(pose_templates, current, rows, previous,
        requested, pose_sha, formal_sha, classification_sha, quarantine)
    counts = Counter(p['class_id'] for p in list(previous)+list(requested))
    result = []
    for p in candidates:
        if counts[p['class_id']] >= TARGET_PER_CLASS:
            next(v for v in inventory if v['target_key'] == p['target_key'])['reason'] = 'quota_full'
            continue
        counts[p['class_id']] += 1
        result.append(dict(p, generation_schema=VERSION,
            rendering_id=GENERATION_NAMESPACE+':'+p['target_key'],
            manual_four_point_source=False, propagation_seed_eligible=True))
    return result, inventory


def proposal_from_attempt(key, row, accepted, templates, current, pose_sha, formal_sha, classification_sha):
    p = original.proposal_from_attempt(key, row, accepted, templates, current,
        pose_sha, formal_sha, classification_sha)
    return dict(p, schema=VERSION, continuation=dict(p['continuation'], batch=PUBLICATION_VERSION,
        all_compatible_templates_considered=True), target_per_class=TARGET_PER_CLASS)


def rendering_inventory(parent_inventory, templates, combined, new_keys, manual=()):
    inherited = parent_inventory['templates']
    generation = [dict(t, rendering_id=GENERATION_NAMESPACE+':'+k) for k, t in sorted(templates.items())]
    ids = [t['rendering_id'] for t in inherited+generation]
    if len(ids) != len(set(ids)):
        raise ValueError('Rendering template namespace collision')
    sources = [dict(target_key=p['target_key'], rendering_id=p['rendering_id'],
        polygon=p['polygon'], human_source=p['human_source'], manual_four_point_source=True,
        propagation_seed_eligible=False) for p in manual if p.get('manual_four_point_source')]
    source_by_key = indexed(sources); manual_by_key = indexed(manual)
    mapping = {}
    for p in combined:
        key = p['target_key']
        mapping[key] = (source_by_key[key]['rendering_id'] if key in source_by_key else
            GENERATION_NAMESPACE+':'+p['template']['target_key'] if key in new_keys or key in manual_by_key else
            parent_inventory['rendering_by_target'][key])
    if not set(mapping.values()) <= set(ids) | {s['rendering_id'] for s in sources}:
        raise ValueError('Rendering source missing')
    return dict(templates=inherited+generation, rendering_by_target=mapping,
        manual_source_renderings=sources, generation_template_namespace=GENERATION_NAMESPACE,
        generation_template_keys=sorted(templates), historical_templates=len(inherited),
        deferred_manual_template_keys=sorted(source_by_key),
        generation_templates_by_origin=dict(Counter(t['origin'] for t in templates.values())))


def preserve_parent_assets(parent, out, previous):
    hashes = {}
    (out/GENERATION_NAMESPACE).mkdir()
    (out/'templates').rename(out/GENERATION_NAMESPACE/'templates')
    for p in previous:
        for folder, extension in (('cases', 'png'), ('images', 'png'), ('masks', 'png'), ('labelme', 'json')):
            relative = f'{folder}/{p["target_key"]}.{extension}'
            if (out/relative).exists():
                raise ValueError('Historical asset collision')
            shutil.copyfile(parent/relative, out/relative); hashes[relative] = digest(parent/relative)
    for directory in ('templates', 'refined', 'generation', 'quota_generation', 'quota100_generation'):
        shutil.copytree(parent/directory, out/directory)
        for file in sorted((parent/directory).rglob('*')):
            if file.is_file():
                hashes[str(file.relative_to(parent))] = digest(file)
    if (parent/'vertex2_before_after.png').exists():
        shutil.copyfile(parent/'vertex2_before_after.png', out/'vertex2_before_after.png')
        hashes['vertex2_before_after.png'] = digest(parent/'vertex2_before_after.png')
    if any(digest(out/name) != value for name, value in hashes.items()):
        raise ValueError('Historical asset copy mismatch')
    return hashes


def package_manual_preview(out, manual, evidence):
    for p in manual:
        key, row = p['target_key'], p['source']; image = evidence.image(row['frame_id'])
        source = p.get('human_source') or p['template']
        panel = Image.new('RGB', (1480, 305), '#121923'); draw = ImageDraw.Draw(panel)
        draw.text((15, 8), f'Class {p["class_id"]} | SAVED HUMAN POSE MASK | {p["vertex_count"]} vertices | NOT machine; NOT confirmed GT', fill='white')
        panel.paste(overlay(image, row, p['polygon'], '#55ceff'), (0, 30))
        draw.text((765, 55), 'Actual saved human polygon; no generated points or machine scores.', fill='white')
        draw.text((765, 85), f'Current revision: {p["target_expected_revision"]}; human event: {source["human_polygon_revision"]}', fill='white')
        draw.text((765, 115), 'Coverage only; NOT a propagation template.' if p.get('manual_four_point_source') else 'Direct human contour; pending confirmation.', fill='white')
        draw.text((765, 145), 'Independent gallery history has NOT been imported.', fill='white')
        draw.text((765, 175), 'GT / automatic training / robot control: all disabled.', fill='white')
        draw.text((15, 284), f'original pose target {key} | {row["split"]} | human draft pending confirmation', fill='white')
        panel.save(out/'cases'/f'{key}.png'); Image.fromarray(image).save(out/'images'/f'{key}.png')
        Image.fromarray(raster_mask(p['polygon'], *row['size']).astype(np.uint8)*255).save(out/'masks'/f'{key}.png')
        flags = dict(human_edited=True, human_confirmed=False, machine_draft=False,
            automatic_training_eligible=False, robot_command_eligible=False, ground_truth_eligible=False,
            pose_snapshot_saved=True, independent_gallery_saved=False,
            manual_four_point_source=p.get('manual_four_point_source', False))
        write_json(out/'labelme'/f'{key}.json', dict(version='5.0.0', imagePath=f'../images/{key}.png',
            imageData=None, imageWidth=row['size'][0], imageHeight=row['size'][1],
            annotation_scope='single_target_mask_review_not_full_frame', other_objects_unchanged=True,
            flags=flags, shapes=[dict(label='pallet', points=p['polygon'], shape_type='polygon',
                group_id=row['box_index'], flags=flags)], mask_template_provenance=p))


def saved_review_status(parent_new, gallery, templates):
    keys = set(indexed(parent_new)); saved = keys & set(gallery); pending = keys-saved
    if pending & set(templates):
        raise ValueError('Unsaved prior machine candidate entered propagation seeds')
    return dict(parent_new_machine_candidates=len(keys), actually_saved=len(saved),
        pending=len(pending), saved_keys=sorted(saved), pending_keys=sorted(pending),
        user_completion_claim_used_as_evidence=False, unsaved_candidates_are_seeds=False)


def build_report(out, combined, new_keys, counts, reviews, current, inherited_manual=(), manual=(), review_status=None):
    manual_keys = set(indexed(inherited_manual)) | set(indexed(manual)); added_manual = set(indexed(manual))
    total = lambda f: sum(c[f] for c in counts.values())
    status = review_status or dict(actually_saved=0, parent_new_machine_candidates=0, pending=0)
    table = ''.join(f'<tr><td>{cls}</td>'+''.join(f'<td>{c[f]}</td>' for f in
        ('old_total', 'manual_added', 'saved_gallery_human', 'saved_pose_human', 'old_pending_machine',
         'new_candidates', 'total', 'missing'))+'</tr>' for cls, c in counts.items())
    cards = []
    for p in sorted(combined, key=lambda v: (v['class_id'], v['target_key'])):
        key = p['target_key']; is_manual = key in manual_keys
        if key in new_keys:
            label = '【本轮新增机器候选】待人工复核'
        elif key in added_manual and p.get('manual_four_point_source'):
            label = f'【本轮计入四点人工轮廓 r{p["target_expected_revision"]}】计入覆盖，不作传播模板'
        elif key in added_manual:
            label = f'【本轮计入人工描绘 r{p["target_expected_revision"]}】不是新人工编辑，不是机器迁移，未确认真值'
        elif key in reviews and active_polygon(reviews[key]):
            label = f'【已保存图册人工修订 r{reviews[key]["revision"]}】历史候选对照，不是新候选'
        elif is_manual and active_polygon(current.get(key)):
            label = f'【既有原位姿人工描绘 r{current[key]["revision"]}】保留历史快照，未确认真值'
        else:
            label = '【历史候选】待人工复核，未计为已保存人工轮廓'
        link = (f'<p><a href="{html.escape(p.get("original_pose_url") or "", quote=True)}">打开原位姿人工标注</a>；'
            '发布时真实人工快照，没有机器评分；独立图册保存历史未导入。</p>' if is_manual else '')
        cards.append(f'<article id="target-{key}" data-class="{p["class_id"]}" '
            f'data-batch="{"new" if key in new_keys else "previous"}" data-kind="{"manual" if is_manual else "machine"}"'
            f'{"" if key in new_keys else " hidden"}><h2>类别 {p["class_id"]} · {label}</h2>'
            f'<img loading="lazy" src="cases/{key}.png?revision=8" alt="{"人工快照" if is_manual else "直接人工模板与候选对照"}">'
            f'<p>{html.escape(p["source"]["frame_id"])} ／ {p["source"]["split"]} ／ {key}</p>{link}'
            f'<a href="labelme/{key}.json?revision=8">多边形（LabelMe）</a> · '
            f'<a href="masks/{key}.png?revision=8">掩膜</a></article>')
    page = '''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>第八版 · 每类一百帧掩膜续批</title><style>@font-face{font-family:PreviewSans;src:url('report-font.otf?revision=8')}*{box-sizing:border-box}body{background:#101720;color:#e7edf5;font:16px PreviewSans,sans-serif;margin:auto;padding:20px;max-width:1800px}a{color:#77ceff}img{width:100%;height:auto}article{border:1px solid #425269;margin:20px 0;padding:12px;min-width:0}p{overflow-wrap:anywhere}.table-wrap{overflow-x:auto}td,th{padding:9px;border:1px solid #425269;white-space:nowrap}table{border-collapse:collapse;min-width:1100px;width:100%}select{font:inherit;padding:6px}[hidden]{display:none!important}@media(max-width:700px){body{padding:10px}article{padding:7px}h2{font-size:18px}}</style>
<h1>第八版 · 每类一百个不同帧（待独立核验）</h1>
<p>以数据库实际已保存记录为准，不把口头完成数量当作人工来源。只使用最新已保存图册与原位姿人工多边形的直接并集，同目标优先图册；传播种子必须超过四点。真实修改过的四点人工轮廓计入人工覆盖，但不作传播模板；不补造顶点。</p>
<p>仅同类、同划分、同传感器配置及兼容视角迁移，保持顶点数、顺序和原严格配准及横梁边界检查。所有合格目标使用原方法扫描，不递归传播、不放宽门槛、不强行补满。全部草稿未确认真值，不自动进入训练或机器人控制。</p>
<p>历史378份候选对象及所有历史命名空间的图像、掩膜、标注逐字节保留。历史卡片不是最新人工修订渲染；最新保存请在在线编辑器查看或导出。只有本轮机器卡片为左侧直接人工模板、右侧候选对照；人工快照没有虚构机器评分。</p>
'''
    page += (f'<p>上一轮新增 {status["parent_new_machine_candidates"]} 份机器候选，实际已保存复核 '
        f'{status["actually_saved"]}/{status["parent_new_machine_candidates"]} 份，另 {status["pending"]} 份未保存，不作种子。'
        f'本轮计入已保存人工描绘 {total("manual_added")} 份（四点来源 {total("manual_four_point_sources")} 份）；'
        f'已保存图册人工 {total("saved_gallery_human")} 份，原位姿人工 {total("saved_pose_human")} 份，'
        f'去重人工覆盖 {total("saved_human")} 份，历史待复核 {total("old_pending_machine")} 份。'
        f'本轮新增机器候选 {total("new_candidates")} 份，累计 {total("total")} 个不同帧，距500帧缺 {total("missing")} 帧。</p>')
    page += '<div class="table-wrap"><table><tr><th>类别</th><th>历史总数</th><th>新计入人工</th><th>已保存图册人工</th><th>已保存原位姿人工</th><th>历史待复核</th><th>新增机器候选</th><th>累计不同帧</th><th>缺额</th></tr>'+table+'</table></div>'
    page += '<p>筛选类别 <select id="filter"><option value="">全部</option>'+''.join(f'<option>{c}</option>' for c in CLASSES)+'</select> '
    page += '<label><input type="checkbox" id="only-new" checked>只看本轮新增机器候选</label></p>'+''.join(cards)
    page += """<script>const cls=document.querySelector('#filter'),only=document.querySelector('#only-new');function filter(){document.querySelectorAll('article').forEach(a=>a.hidden=(!!cls.value&&a.dataset.class!==cls.value)||(only.checked&&a.dataset.batch!=='new'));}cls.onchange=only.onchange=filter;filter();</script></html>"""
    (out/'report_zh.html').write_text(page)
    from fontTools import subset
    from fontTools.ttLib import TTFont
    source = Path('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf')
    required = {ord(c) for c in page if '\u3400' <= c <= '\u9fff'}
    with TTFont(source) as font:
        if not required <= set(font.getBestCmap()):
            raise ValueError('Report source font coverage failure')
        sub = subset.Subsetter(); sub.populate(text=page); sub.subset(font); font.save(out/'report-font.otf')
    with TTFont(out/'report-font.otf') as font:
        if not required <= set(font.getBestCmap()):
            raise ValueError('Report font coverage failure')
    write_json(out/'font_coverage.json', dict(chinese_glyphs=len(required), all_report_Chinese_present=True,
        font_source_sha256=digest(source), font_sha256=digest(out/'report-font.otf')))


def verified_parent(parent):
    for name, expected in PARENT_PINS.items():
        if digest(parent/name) != expected:
            raise ValueError('Pinned publication 7 changed: '+name)
    manifest, seal = read_json(parent/'manifest.json'), read_json(parent/'verification.json')
    if (manifest.get('publication_version') != 7 or manifest.get('proposals') != 378 or
            manifest.get('previous_proposals') != 237 or manifest.get('new_proposals') != 84 or
            manifest.get('manual_proposals') != 57 or manifest.get('all_manual_sources') != 87 or
            seal.get('state') != 'passed' or seal.get('publication_version') != 7 or
            seal.get('proposals_verified') != 378 or seal.get('all_manual_sources_verified') != 87 or
            seal.get('manifest_sha256') != digest(parent/'manifest.json') or
            seal.get('proposals_sha256') != manifest.get('proposals_sha256') or
            seal.get('artifact_hashes_sha256') != digest(parent/'artifact_hashes.json')):
        raise ValueError('Parent requires matching independent publication-7 verification')
    hashes = file_inventory(parent)
    for name, expected in read_json(parent/'artifact_hashes.json').items():
        if hashes.get(name) != expected:
            raise ValueError('Frozen parent artifact changed: '+name)
    frozen = dict(manifest['frozen_code_sha256'])
    if frozen.get('pallet/mask_quota_100.py') != manifest['code_sha256']:
        raise ValueError('Parent generator provenance mismatch')
    for name, expected in frozen.items():
        if digest(PROJECT/name) != expected:
            raise ValueError('Frozen transfer/generator changed: '+name)
    frozen['pallet/mask_quota_100_continue.py'] = digest(__file__)
    return manifest, hashes, frozen


def verify_sources_current(live, snapshot, table):
    """Fail closed if concurrent saves invalidate seed/protection/count evidence."""
    with closing(readonly(live)) as db, closing(readonly(snapshot, True)) as frozen:
        db.execute('BEGIN')
        for name, fields, order in ((table, 'target_key,revision,payload', 'target_key'),
                ('events', 'id,target_key,revision,payload', 'id')):
            if list(db.execute(f'SELECT {fields} FROM {name} ORDER BY {order}')) != list(
                    frozen.execute(f'SELECT {fields} FROM {name} ORDER BY {order}')):
                raise ValueError('Concurrent human saves require a fresh generation: '+table)


def generate(output=OUTPUT, workers=4, method='original', parent=PARENT, requests_directory=REQUESTS):
    if method != 'original':
        raise ValueError('Only the frozen original method is implemented')
    if not 1 <= workers <= 8:
        raise ValueError('Workers must be 1–8')
    out, parent, request_dir = Path(output).resolve(), Path(parent).resolve(), Path(requests_directory).resolve()
    if out.exists() or not out.is_relative_to(PROJECT/'outputs'):
        raise ValueError('Use a new outputs directory')
    manifest, parent_hashes, frozen_code = verified_parent(parent)
    configuration_hashes = file_inventory(PROJECT/'configs')
    request_hashes = file_inventory(request_dir)
    if any(request_hashes.get(n) != value for n, value in REQUEST_PINS.items()):
        raise ValueError('Pinned 24-item manual request queue changed')
    requests, request_seal = read_jsonl(request_dir/'requests.jsonl'), read_json(request_dir/'verification.json')
    if (len(requests) != 24 or Counter(r['class_id'] for r in requests) != {1: 10, 9: 2, 10: 10, 15: 2}
            or request_seal.get('state') != 'passed' or request_seal.get('request_count') != 24
            or request_seal.get('requests_sha256') != request_hashes['requests.jsonl']):
        raise ValueError('Expected verified unchanged 24-item request queue')
    active = read_json(PROJECT/'configs/active_mask_template_requests.json')
    if (PROJECT/active['directory']).resolve() != request_dir:
        raise ValueError('Manual request queue is no longer active')
    formal, rows, evidence = load_formal_evidence(manifest)
    formal_sha, classification_sha = manifest['formal_manifest_sha256'], manifest['classification_sha256']
    paths = dict(SOURCE_PUBLICATIONS); paths[7] = parent
    publications = original.publication_inventory(paths, formal_sha)
    source_hashes = {v: file_inventory(path) for v, path in paths.items() if path != parent}
    protected = protected_snapshot(formal)
    if (len(protected) != 20768 or protected != read_json(parent/'protected_formal_before.json') or
            protected != read_json(parent/'protected_formal_after.json')):
        raise ValueError('Protected 20768 formal files differ from parent')
    previous = read_jsonl(parent/'proposals.jsonl'); previous_keys = set(indexed(previous))
    # all_manual_sources is a raw source freeze, NOT a proposal inventory.
    inherited_manual = [p for p in previous if p.get('schema') == MANUAL_SCHEMA]
    inherited_keys = set(indexed(inherited_manual))
    if (len(previous) != 378 or len(inherited_manual) != 87 or
            Counter(p['class_id'] for p in previous) != {1: 58, 2: 100, 9: 83, 10: 54, 15: 83} or
            len({p['source']['frame_id'] for p in previous}) != 378 or
            inherited_keys != set(indexed(read_jsonl(parent/'all_manual_sources.jsonl'))) or
            any(p['source'] != rows[p['target_key']] or p['formal_manifest_sha256'] != formal_sha for p in previous)):
        raise ValueError('Parent canonical/source inventory changed')
    out.mkdir(parents=True)
    write_json(out/'protected_formal_before.json', protected)
    write_json(out/'parent_file_inventory.json', parent_hashes)
    write_json(out/'configuration_input_hashes.json', configuration_hashes)
    write_json(out/'request_file_inventory.json', request_hashes)
    write_json(out/'source_publication_file_inventories.json', source_hashes)
    (out/'parent_evidence').mkdir()
    for name in ('manifest.json', 'verification.json', 'proposals.jsonl', 'manual_proposals.jsonl',
            'manual_source_records.jsonl', 'all_manual_sources.jsonl', 'new_proposals.jsonl', 'template_inventory.json'):
        shutil.copyfile(parent/name, out/'parent_evidence'/name)
    for name in frozen_code:
        destination = out/'frozen_code'/name; destination.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(PROJECT/name, destination)
    pose_live = PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    gallery_live = PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3'
    pose_snapshot, gallery_snapshot = out/'reviews_snapshot.sqlite3', out/'gallery_reviews_snapshot.sqlite3'
    pose_sha, gallery_sha = snapshot_database(pose_live, pose_snapshot), snapshot_database(gallery_live, gallery_snapshot)
    with closing(readonly(pose_snapshot, True)) as db:
        current, pose_templates, status = annotation_inventory(db, rows)
        pose_events = db.execute('SELECT COUNT(*) FROM events').fetchone()[0]
        if json.loads(db.execute("SELECT value FROM metadata WHERE key='binding'").fetchone()[0])['formal_manifest_sha256'] != formal_sha:
            raise ValueError('Pose formal binding mismatch')
        for table in ('annotations', 'events'):
            legacy.validate_snapshot_rows(db, rows, table)
        inherited_sources, inherited_audit = legacy.audit_inherited_manual(db, inherited_manual, pose_templates, current, pose_sha)
    with closing(readonly(gallery_snapshot, True)) as db:
        if db.execute("SELECT value FROM metadata WHERE key='formal_manifest_sha256'").fetchone()[0] != formal_sha:
            raise ValueError('Gallery formal binding mismatch')
        reviews = {k: json.loads(raw) for k, raw in db.execute('SELECT target_key,payload FROM reviews')}
        gallery_events = [json.loads(raw) for raw, in db.execute('SELECT payload FROM events ORDER BY id')]
        for table in ('reviews', 'events'):
            legacy.validate_snapshot_rows(db, rows, table)
    gallery = original.gallery_templates(previous, reviews, gallery_events, current, rows,
        parent, formal_sha, gallery_sha, publication_paths=paths)
    quarantine = QUARANTINE | set(manifest.get('preserved_quarantined_targets', [])) | set(manifest.get('quarantined_targets', []))
    templates = original.seed_union(pose_templates, gallery, pose_sha, quarantine)
    with closing(readonly(pose_snapshot, True)) as db:
        requested_manual, manual_sources = manual_source_proposals(db, requests, pose_templates, current,
            rows, previous, pose_sha, formal_sha, classification_sha, quarantine)
        reused_manual, reuse_inventory = existing_human_reuse(pose_templates, current, rows, previous,
            requested_manual, pose_sha, formal_sha, classification_sha, quarantine)
        for p in reused_manual:
            _, metadata, record = exact_manual_source(db, p['target_key'], p['source'], pose_sha)
            if p['template'] != metadata:
                raise ValueError('Reused human source provenance mismatch')
            manual_sources.append(record)
    manual = sorted(requested_manual+reused_manual, key=lambda p: p['target_key'])
    manual_keys, manual_reuse_keys = set(indexed(manual)), set(indexed(reused_manual))
    deferred_keys = sorted(p['target_key'] for p in manual if p.get('manual_four_point_source'))
    if set(deferred_keys) & set(templates):
        raise ValueError('Four-point manual source became a propagation seed')
    review_status = saved_review_status(read_jsonl(parent/'new_proposals.jsonl'), gallery, templates)
    write_json(out/'saved_review_status.json', review_status)
    with closing(readonly(parent/'reviews_snapshot.sqlite3', True)) as db:
        _, old_pose_templates, _ = annotation_inventory(db, rows)
    new_pose_seed_only = sorted(set(pose_templates)-set(old_pose_templates)-manual_keys)
    base_counts = quota_counts(previous, [], reviews, current, pose_templates, inherited_manual, manual)
    if len(requested_manual) != 24:
        raise ValueError('Completed manual request partition mismatch')
    all_sources = sorted(inherited_sources+manual_sources, key=lambda p: p['target_key'])
    if set(indexed(all_sources)) != inherited_keys | manual_keys:
        raise ValueError('Explicit manual source freeze inventory mismatch')
    shutil.copyfile(request_dir/'requests.jsonl', out/'requests.jsonl')
    for name, values in (('manual_proposals', manual), ('manual_source_records', manual_sources),
            ('all_manual_sources', all_sources), ('manual_reuse_inventory', reuse_inventory),
            ('inherited_manual_source_audit', inherited_audit),
            ('refined_annotations', [reviews[k] for k in sorted(reviews)])):
        write_jsonl(out/f'{name}.jsonl', values)
    gallery_protected = set(reviews) | {v['target_key'] for v in gallery_events}
    pose_protected = {k for k, reason in status.items() if reason != 'eligible'}
    work, outcomes = original.target_inventory(rows, previous, status, gallery_protected, quarantine, manual_keys)
    write_json(out/'protected_targets.json', dict(previous=sorted(previous_keys),
        counted_manual_source_keys=sorted(inherited_keys | manual_keys), newly_counted_manual_source_keys=sorted(manual_keys),
        manual_reuse_keys=sorted(manual_reuse_keys), requested_manual_keys=sorted(indexed(requested_manual)),
        pose_mask_history_or_noneligible=sorted(pose_protected), gallery_saved_or_history=sorted(gallery_protected),
        quarantine=sorted(quarantine), deferred_manual_template_keys=deferred_keys, eligibility=status))
    write_json(out/'snapshot_manifest.json', dict(formal_manifest_sha256=formal_sha,
        pose=dict(path=pose_snapshot.name, backup='backups/'+pose_snapshot.name, sha256=pose_sha,
            saved=len(current), events=pose_events),
        gallery=dict(path=gallery_snapshot.name, backup='backups/'+gallery_snapshot.name, sha256=gallery_sha,
            saved=len(reviews), events=len(gallery_events)),
        manual_requests=dict(directory=str(request_dir), count=len(requests), frozen_input_sha256=request_hashes),
        source_publications={v: {k: str(value) if k == 'path' else value for k, value in pub.items()
            if k != 'proposals'} for v, pub in publications.items()}))
    for request in requests:
        evidence.image(rows[request['target_key']]['frame_id'])
        if request['source']['image_sha256'] != evidence.used[request['source']['image']]:
            raise ValueError('Manual request formal image changed')
    for p in previous:
        with Image.open(parent/'images'/f'{p["target_key"]}.png') as image:
            if not np.array_equal(np.asarray(image), evidence.image(p['source']['frame_id'])):
                raise ValueError('Parent image differs from formal pixels')
    print(json.dumps(dict(state='scanning', publication_version=PUBLICATION_VERSION,
        templates=len(templates), templates_by_origin=dict(Counter(t['origin'] for t in templates.values())),
        gallery_saved=len(reviews), gallery_events=len(gallery_events), pose_saved=len(current), pose_events=pose_events,
        saved_review_status=review_status, manual_added=len(manual), manual_requested=len(requested_manual),
        manual_existing_reused=len(reused_manual), inherited_manual_sources=len(inherited_manual),
        deferred_manual_template_keys=deferred_keys, base_count=len(previous)+len(manual),
        base_classes={cls: c['total'] for cls, c in base_counts.items()},
        base_gaps={cls: c['missing'] for cls, c in base_counts.items()},
        saved_human=sum(c['saved_human'] for c in base_counts.values()),
        old_pending_machine=sum(c['old_pending_machine'] for c in base_counts.values()),
        eligible_targets=len(work), workers=workers, method=method)), flush=True)
    attempts, accepted_proposals = [], []
    def worker(item):
        return item, attempt_target(*item, templates, evidence)
    with ThreadPoolExecutor(max_workers=workers) as pool:
        for number, ((key, row), (accepted, trials, outcome)) in enumerate(pool.map(worker, work), 1):
            attempts.extend(trials); outcomes.append(outcome)
            if accepted:
                accepted_proposals.append(proposal_from_attempt(key, row, accepted, templates,
                    current, pose_sha, formal_sha, classification_sha))
            if number % 200 == 0:
                print(json.dumps(dict(scanned=number, accepted=len(accepted_proposals), attempts=len(attempts))), flush=True)
    new, dispositions = select_diverse(previous+manual, accepted_proposals, goal=TARGET_PER_CLASS)
    for outcome in outcomes:
        if outcome['target_key'] in dispositions:
            outcome['reason'] = dispositions[outcome['target_key']]
    combined = sorted(previous+manual+new, key=lambda p: p['target_key']); new_keys = set(indexed(new))
    if new_keys & (previous_keys | manual_keys | quarantine | gallery_protected | pose_protected):
        raise ValueError('Protected target selected')
    if len(outcomes) != len(rows) or set(indexed(outcomes)) != set(rows):
        raise ValueError('Incomplete outcome inventory')
    for name, values in (('proposals', combined), ('new_proposals', new), ('accepted_candidates', accepted_proposals),
            ('registration_attempts', attempts), ('outcomes', outcomes)):
        write_jsonl(out/f'{name}.jsonl', values)
    restored = indexed(read_jsonl(out/'proposals.jsonl'))
    if any(canonical(restored[k]) != canonical(p) for k, p in indexed(previous).items()):
        raise ValueError('Historical canonical proposal changed')
    counts = quota_counts(previous, new, reviews, current, pose_templates, inherited_manual, manual)
    for cls, c in counts.items():
        class_outcomes = [v for v in outcomes if v['class_id'] == cls]
        c.update(templates=sum(t['row']['final_class_id'] == cls for t in templates.values()),
            eligible=sum(row['final_class_id'] == cls for _, row in work),
            compatible_targets=sum(v['reason'] in ('new_proposal', 'image_similarity_below_gate',
                'registration_or_boundary_rejected', 'accepted_duplicate_frame_not_selected',
                'accepted_quota_full_not_selected') for v in class_outcomes), preview=c['total'],
            outcomes=dict(Counter(v['reason'] for v in class_outcomes)))
    inventory = rendering_inventory(read_json(parent/'template_inventory.json'), templates, combined, new_keys, manual)
    inventory.update(schema=VERSION, publication_version=PUBLICATION_VERSION, target_per_class=TARGET_PER_CLASS,
        classes=counts, eligibility=status, snapshot_saved=len(current), snapshot_events=pose_events,
        generation_templates=len(templates), gallery_snapshot_saved=len(reviews), previous_proposals=len(previous),
        manual_proposals=len(manual), inherited_manual_sources=len(inherited_manual), all_manual_sources=len(all_sources),
        manual_requested=len(requested_manual), manual_existing_reused=len(reused_manual),
        counted_manual_source_keys=sorted(inherited_keys | manual_keys), saved_review_status=review_status)
    write_json(out/'template_inventory.json', inventory)
    package_preview(out, new, templates, rows, evidence, counts)
    package_manual_preview(out, manual, evidence)
    copied = preserve_parent_assets(parent, out, previous); write_json(out/'preserved_parent_assets.json', copied)
    for key, t in templates.items():
        write_json(out/GENERATION_NAMESPACE/'templates'/f'{key}.json', t)
    build_report(out, combined, new_keys, counts, reviews, current, inherited_manual, manual, review_status)
    contact = Image.new('RGB', (1480, len(CLASSES)*305), '#121923')
    for i, cls in enumerate(CLASSES):
        p = next(p for p in new+manual+previous if p['class_id'] == cls)
        with Image.open(out/'cases'/f'{p["target_key"]}.png') as image:
            contact.paste(image, (0, i*305))
    contact.save(out/'preview_all_classes.png')
    used = read_json(parent/'used_image_hashes.json')
    for name, value in evidence.used.items():
        if name in used and used[name] != value:
            raise ValueError('Parent source image hash conflict')
        used[name] = value
    if any(digest(formal/name) != value for name, value in used.items()):
        raise ValueError('Used formal image changed')
    write_json(out/'used_image_hashes.json', used)
    after = protected_snapshot(formal); write_json(out/'protected_formal_after.json', after)
    if after != protected:
        raise ValueError('Protected formal files changed')
    verify_history_preserved(pose_live, pose_snapshot); verify_history_preserved(gallery_live, gallery_snapshot)
    try:
        verify_sources_current(pose_live, pose_snapshot, 'annotations')
        verify_sources_current(gallery_live, gallery_snapshot, 'reviews')
    except ValueError as exc:
        write_json(out/'source_stability_check.json', dict(state='changed_requires_fresh_generation',
            reason=str(exc), published=False, production_database_writes=0))
        raise
    write_json(out/'source_stability_check.json', dict(state='stable', seeds_current=True,
        current_payloads_and_events_unchanged=True, production_database_writes=0))
    if (digest(pose_snapshot) != pose_sha or digest(gallery_snapshot) != gallery_sha or
            any(digest(out/'backups'/p.name) != digest(p) for p in (pose_snapshot, gallery_snapshot))):
        raise ValueError('Frozen snapshot/backup changed')
    if (file_inventory(parent) != parent_hashes or file_inventory(PROJECT/'configs') != configuration_hashes or
            file_inventory(request_dir) != request_hashes or
            any(file_inventory(paths[v]) != values for v, values in source_hashes.items()) or
            any(digest(PROJECT/name) != value for name, value in frozen_code.items()) or
            digest(out/'requests.jsonl') != request_hashes['requests.jsonl'] or
            any(digest(out/name) != value for name, value in copied.items())):
        raise ValueError('Frozen parent/code/config/request/publication/assets changed')
    write_json(out/'shortfalls.json', {cls: dict(missing=c['missing'], outcomes=c['outcomes'],
        explanation='All eligible targets scanned using every compatible direct-human template above the frozen '
            'initial gate, original ECC/NCC/forward-backward/beam gates and distinct-frame selection at goal 100. '
            'Actual saved manual sources count separately, including a modified four-point human polygon which '
            'is excluded from propagation seeds. Unsaved prior machine candidates are never seeds; no forced fill.')
        for cls, c in counts.items()})
    result = dict(state='quota_pending_independent_verification', schema=VERSION, version=VERSION,
        publication_version=PUBLICATION_VERSION, target_per_class=TARGET_PER_CLASS, target_total=500,
        parent=str(parent), parent_manifest_sha256=parent_hashes['manifest.json'],
        parent_proposals_sha256=parent_hashes['proposals.jsonl'], parent_verification_sha256=parent_hashes['verification.json'],
        previous_proposals=len(previous), new_proposals=len(new), manual_proposals=len(manual), manual_added=len(manual),
        manual_requested=len(requested_manual), manual_existing_reused=len(reused_manual),
        manual_reuse_keys=sorted(manual_reuse_keys), requested_manual_keys=sorted(indexed(requested_manual)),
        manual_reuse_excluded=[v for v in reuse_inventory if v['reason'] != 'counted'],
        inherited_manual_sources=len(inherited_manual), all_manual_sources=len(all_sources),
        inherited_manual_source_revisions_changed=[v['target_key'] for v in inherited_audit if v['source_changed']],
        base_proposals=len(previous)+len(manual), base_classes=base_counts, proposals=len(combined), classes=counts,
        manual_by_class=dict(Counter(p['class_id'] for p in manual)), manual_source_schema=MANUAL_SCHEMA,
        counted_manual_source_keys=sorted(inherited_keys | manual_keys), newly_counted_manual_source_keys=sorted(manual_keys),
        manual_source_snapshots_imported_into_gallery_store=False, manual_four_point_sources=len(deferred_keys),
        deferred_manual_template_keys=deferred_keys, saved_review_status=review_status,
        new_by_class=dict(Counter(p['class_id'] for p in new)), formal_manifest_sha256=formal_sha,
        classification_sha256=classification_sha, snapshot_sha256=pose_sha, gallery_snapshot_sha256=gallery_sha,
        snapshot_saved=len(current), snapshot_events=pose_events, gallery_snapshot_saved=len(reviews),
        gallery_snapshot_events=len(gallery_events), generation_templates=len(templates),
        generation_template_namespace=GENERATION_NAMESPACE,
        generation_templates_by_origin=dict(Counter(t['origin'] for t in templates.values())),
        unexpected_new_pose_seed_only=new_pose_seed_only, unexpected_pose_seeds_implicitly_counted=0,
        method=method, scanned_eligible_targets=len(work), accepted_before_diversity=len(accepted_proposals),
        registration_attempts=len(attempts), outcomes=dict(Counter(v['reason'] for v in outcomes)),
        saved_gallery_human=sum(c['saved_gallery_human'] for c in counts.values()),
        existing_saved_pose_human=sum(c['existing_saved_pose_human'] for c in counts.values()),
        saved_pose_human=sum(c['saved_pose_human'] for c in counts.values()),
        saved_human=sum(c['saved_human'] for c in counts.values()),
        old_pending_machine=sum(c['old_pending_machine'] for c in counts.values()), new_machine_pending=len(new),
        missing=sum(c['missing'] for c in counts.values()), preserved_quarantined_targets=sorted(quarantine),
        manual_request_input_sha256={str(request_dir/n): v for n, v in REQUEST_PINS.items()},
        code_sha256=digest(__file__), frozen_code_sha256=frozen_code,
        transfer_code_sha256=frozen_code['pallet/mask_template_transfer.py'],
        boundary_code_sha256=frozen_code['pallet/mask_boundary_review.py'],
        attempt_code_sha256=frozen_code['pallet/mask_template_continue.py'], source_current_stable=True,
        production_database_writes=0, configuration_writes=0, service_writes=0,
        protected_formal_files=len(protected), original_splits_preserved=True, cross_split_template_transfers=0,
        recursive_candidate_propagation=False, thresholds_relaxed=False, forced_fill=False,
        new_human_edits_created=0, research_candidates_added=0, automatic_human_confirmation=False,
        automatic_training_eligible=False, robot_command_eligible=False, ground_truth_eligible=False)
    for name in ('proposals', 'new_proposals', 'manual_proposals', 'manual_source_records', 'all_manual_sources',
            'inherited_manual_source_audit', 'requests', 'refined_annotations', 'manual_reuse_inventory',
            'accepted_candidates', 'registration_attempts', 'outcomes'):
        result[name+'_sha256'] = digest(out/f'{name}.jsonl')
    result['template_inventory_sha256'] = digest(out/'template_inventory.json')
    write_json(out/'manifest.json', result)
    write_json(out/'generation_validation.json', dict(state='self_checks_passed_not_independent_verification',
        publication_version=PUBLICATION_VERSION, old_canonical_preserved=len(previous), old_assets_bytewise_preserved=len(copied),
        inherited_manual_sources=len(inherited_manual), newly_counted_manual_sources=len(manual), all_manual_sources=len(all_sources),
        independent_verification_performed=False, published=False, live_database_writes=0,
        configuration_writes=0, service_writes=0, protected_formal_files=len(protected)))
    (out/'GENERATION_HANDOFF.md').write_text(
        '# Publication 8 — pending independent verification\n\n'
        f'{len(combined)} distinct frames = unchanged parent {len(previous)} + actual requested saved-human '
        f'{len(requested_manual)} + authorized existing-human reuse {len(reused_manual)} + strict new-machine {len(new)}. '
        f'Goal 100 per class / 500 total; missing {result["missing"]}.\n\n'
        f'Prior publication-7 new machine reviews: actually saved {review_status["actually_saved"]}/'
        f'{review_status["parent_new_machine_candidates"]}; {review_status["pending"]} UNSAVED, not seeds. '
        'Claims of completion are not evidence. Pending keys are in manifest.saved_review_status.\n\n'
        f'`new_proposals.jsonl` is ONLY this round’s machine drafts. `manual_proposals.jsonl` and '
        f'`manual_source_records.jsonl` contain {len(manual)} actual human sources; `all_manual_sources.jsonl` '
        f'freezes all {len(all_sources)} = inherited {len(inherited_manual)} + added {len(manual)}, with exact '
        'current and actual non-automatic human event payloads/raw hashes. All 87 inherited human proposals '
        'were selected from canonical parent proposals, NOT from source-freeze records or only the last 57.\n\n'
        f'Four-point sources {deferred_keys} count as human coverage, not templates. Their actual shape is '
        'unchanged; `human_source`, not `template`, carries provenance. Rendering metadata is separate from '
        'the propagation template inventory. No generated points or machine scores.\n\n'
        'Latest human gallery edits are validated against frozen publications 3–7 and win duplicate seeds. '
        f'`{GENERATION_NAMESPACE}` is new; all five parent template namespaces and 378 canonical assets '
        'are byte-identical. Parent evidence is archived, not represented as new verification.\n\n'
        'Original attempt_target and .55 initial / .84 ECC / .78 boundary NCC / 1.5 forward-backward / beam gates '
        'unchanged; select_diverse goal explicitly 100. No multiscale research, threshold relaxation, forced fill, '
        'recursive candidates, database/config/service writes, automatic confirmation, training or robot eligibility. '
        'Current sources/events were checked again at completion; concurrent saves require a new generation.\n')
    write_json(out/'artifact_hashes.json', file_inventory(out))
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, default=OUTPUT)
    parser.add_argument('--workers', type=int, default=4)
    parser.add_argument('--method', choices=('original',), default='original')
    args = parser.parse_args(); cv2.setNumThreads(1)
    print(json.dumps(generate(args.output, args.workers, args.method)), flush=True)


if __name__ == '__main__':
    main()
