"""Read-only, independent audit of the small under-50 human-contour worklist.

Run only after the producer explicitly announces completion. The new builder is
never imported. The already independent quality-v2 auditor supplies raw-source
validation and an independent scan-line raster, not the producer's source counts.
Passing verifies provenance, geometry validity, exports and preservation, NOT
semantic class correctness or contour accuracy. No real editor save is performed.
"""
from __future__ import annotations

import argparse
from collections import Counter
from contextlib import closing
from datetime import datetime, timezone
import hashlib
from html.parser import HTMLParser
import math
import os
from pathlib import Path
import re
import sqlite3
import sys

sys.dont_write_bytecode = True
PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))

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

from scripts import verify_mask_quality_recovery as sources

ROOT = PROJECT/'outputs/pallet_mask_under50_requests_v1'
PARENT = PROJECT/'outputs/pallet_mask_remaining_round5_v1'
QUALITY = PROJECT/'outputs/pallet_mask_quality_recovery_v2'
POSE = PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
GALLERY = PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3'
CLASSES = (11, 12, 16, 17, 19, 20)
EXPECTED_COUNTS = {11: 17, 12: 47, 16: 34, 17: 43, 19: 39, 20: 45}
CLASS_SCOPE = 'real_saved_distinct_human_research_contours_under_50_not_machine_coverage'
QUALITY_SEAL_SHA256 = '61b73d8e0dbc7b99db01b75e912c797beacc34c8c0b3d31434058eac3d376428'
PARENT_PINS = {
    'manifest.json': 'eced4c61119ee63bef7f80e4ae92d76db3d28f3228daef049fa00ad5da69e487',
    'verification.json': '5165170284205283adfaa6514c65cc8126773f49be54ed6398f1dba55f321631',
    'proposals.jsonl': '0d288c12e502cc3781ce782a3b1b81f58e97a80578812c6a4430833345b004b6',
}
FROZEN_INTERFACE_PINS = {
    'scripts/build_mask_preannotated_requests_v3.py': 'e9927173576b457674d21df36719544bf21d08bc1b606df630e78fbae2028cfc',
    'pallet/mask_preannotation.py': '3bcd2298eba0989eb7e8697871a23584426ffa96e221b7b319cbb35070f45668',
    'pallet/mask_template_requests.py': 'e89b69bffea69a639fa6df66dd996b03626aa3041e1ff98564c450233742c29e',
}
FALSE_FLAGS = ('human_edited', 'human_mask_confirmed', 'human_pose_confirmed', 'ground_truth_eligible',
    'automatic_training_eligible', 'robot_command_eligible', 'production_saved', 'counts_as_completed_annotation',
    'accepted_candidate', 'propagation_seed_eligible')
CONFIRMATION_FLAGS = FALSE_FLAGS + ('metric_pose_confirmed', 'human_confirmed', 'full_six_dof')
SEALS = ('verification.json', 'independent_verification.json')
require, read, read_jsonl = sources.require, sources.read, sources.read_jsonl
canonical, sha, digest = sources.canonical, sources.sha, sources.digest
inventory, member, equal = sources.inventory, sources.member, sources.equal


def database_fingerprint(path):
    """Independently reproduce the staging fingerprint without normalizing JSON.

    Payload TEXT remains an exact UTF-8 string inside each relational row. This
    fingerprint intentionally differs from quality-v2's list-of-rows hash format.
    """
    with closing(sqlite3.connect(Path(path).resolve().as_uri()+'?mode=ro', uri=True)) as db:
        db.execute('PRAGMA query_only=ON'); db.execute('BEGIN')
        schema = list(db.execute('SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name'))
        hashes, counts = {}, {}
        for kind, name, _, _ in schema:
            if kind != 'table':
                continue
            require(re.fullmatch(r'[A-Za-z_][A-Za-z_0-9]*', name), 'Unsafe database identifier')
            rows = sorted(canonical(list(row)) for row in db.execute('SELECT * FROM "'+name+'"'))
            hashes[name] = hashlib.sha256(b'\n'.join(rows)).hexdigest()
            counts[name] = len(rows)
    return dict(schema_sha256=sha(schema), table_sha256=hashes, table_counts=counts)


def native_quality(row, evidence):
    """Replay the unchanged native-image gates; these are not contour metrics."""
    x, y, w, h = (row['bbox'][k] for k in ('x', 'y', 'width', 'height'))
    width, height = row['size']
    require(all(math.isfinite(v) for v in (x, y, w, h)), 'Nonfinite source box')
    require(w >= 50 and h >= 14 and w*h >= 1000, 'Native source box too small')
    require(x >= 1 and y >= 1 and x+w <= width-1 and y+h <= height-1
        and not row.get('crop_touches_image_edge'), 'Native source truncated/edge touching')
    require(not row.get('processing_error') and row.get('appearance_status') == 'ok', 'Source processing issue')
    image = evidence.image(row['frame_id'])
    crop = image[max(0, math.floor(y)):min(height, math.ceil(y+h)),
        max(0, math.floor(x)):min(width, math.ceil(x+w))]
    low, high = np.percentile(crop, [5, 95])
    contrast, bright, saturated = float(high-low), float(np.mean(crop >= 48)), float(np.mean(crop >= 250))
    gradients = cv2.magnitude(cv2.Sobel(crop, cv2.CV_32F, 1, 0), cv2.Sobel(crop, cv2.CV_32F, 0, 1))
    edges = float(np.mean(gradients >= 60))
    require(contrast >= 35 and bright >= .12 and saturated <= .65 and edges >= .025, 'Weak native intensity structure')
    clarity = .5*min(contrast/180, 1) + .2*min(bright/.65, 1) + .3*min(edges/.25, 1)
    return dict(bbox_area_native_pixels=w*h, bbox_width_native_pixels=w, bbox_height_native_pixels=h,
        intensity_p05=float(low), intensity_p95=float(high), intensity_contrast_p95_p05=contrast,
        usable_brightness_fraction=bright, saturated_fraction=saturated,
        native_gradient_fraction=edges, clarity_score=float(clarity))


def crop_bounds(row):
    x, y, w, h = (row['bbox'][k] for k in ('x', 'y', 'width', 'height'))
    width, height = row['size']
    return [max(0, math.floor(x-max(12, .1*w))), max(0, math.floor(y-max(12, .6*h))),
        min(width, math.ceil(x+w+max(12, .1*w))), min(height, math.ceil(y+h+max(12, .6*h)))]


def check_count_basis(catalog, inputs, manifest):
    require(len(catalog) == 1484 and len({r['target_key'] for r in catalog}) == 1484
        and len({r['row']['frame_id'] for r in catalog}) == 1484, '1484 distinct actual human source images required')
    counts = Counter(r['row']['final_class_id'] for r in catalog)
    require(set(counts) == set(range(1, 23)) and all(type(c) is int for c in counts), 'All22 class counts required')
    require(tuple(c for c in range(1, 23) if counts[c] < 50) == CLASSES
        and {c: counts[c] for c in CLASSES} == EXPECTED_COUNTS, 'Current under-50 human-source class scope differs')
    equal(inputs['actual_class_counts'], {str(c): n for c, n in counts.items()}, 'all_actual_class_counts')
    equal(inputs['actual_counted_saved_basis'], 1484, 'actual_human_count_not_1550_machine_coverage')
    equal(manifest['actual_human_saved_counts_before'], inputs['actual_class_counts'], 'manifest_real_human_counts')
    for value in (inputs, manifest):
        equal(value['maximum_issued_per_class'], 2, 'maximum_issued_per_class')
        equal(value['target_per_class_this_pilot'], 50, 'pilot_target')
        equal(value['class_scope'], CLASS_SCOPE, 'class_scope')
    equal(inputs['shortlisted_classes'], list(CLASSES), 'staged_class_scope')
    equal(manifest['filter_classes'], list(CLASSES), 'report_filter_scope')
    return counts


def prior_inspections(project, own_root, rows):
    """Exclude only this exact pack, not other requests or withheld alternatives."""
    hashes, keys = {}, set()
    for pattern in ('requests.jsonl', 'shortlist.jsonl'):
        for path in sorted((project/'outputs').rglob(pattern)):
            if path.is_relative_to(own_root):
                continue
            name = str(path.relative_to(project))
            member(project, name)
            hashes[name] = digest(path)
            for record in read_jsonl(path):
                key = record.get('target_key')
                if key is not None:
                    require(key in rows, 'Unknown previous inspection target: '+str(key))
                    keys.add(key)
    return hashes, keys


def protected_keys(rows, pose, gallery, catalog, parent_proposals, prior_keys, quarantine):
    result = set(quarantine) | set(prior_keys) | {r['target_key'] for r in catalog}
    result.update(p['target_key'] for p in parent_proposals)
    result.update(gallery['current']); result.update(gallery['histories'])
    for key in set(pose['current']) | set(pose['histories']):
        require(key in rows, 'Unknown pose source')
        values = [e[3] for e in pose['histories'].get(key, [])]
        if key in pose['current']:
            values.append(pose['current'][key][2])
        if key not in pose['current'] or any(
                v.get('state') in ('deleted', 'deferred', 'confirmed')
                or any(v.get(f, False) is not False or (v.get('pose') or {}).get(f, False) is not False
                    for f in CONFIRMATION_FLAGS)
                or not sources.original_rectangle(v.get('polygon'), rows[key]) for v in values):
            result.add(key)
    require(result <= rows.keys(), 'Unknown protected source')
    return result


def check_staged(root, staged, decisions, rows, formal, evidence, pose, forbidden):
    records = sources.indexed(staged)
    require(records and set(decisions) == set(records), 'Every own staged source needs exactly one decision')
    counts = Counter(r['class_id'] for r in staged)
    require(len(staged) <= 18 and all(c in CLASSES and n <= 3 for c, n in counts.items()), 'Staged per-class maximum3 exceeded')
    blocked_frames = {rows[k]['frame_id'] for k in forbidden}
    blocked_hashes = {digest(member(formal, rows[k]['image'])) for k in forbidden}
    frames, hashes = set(), set()
    for order, record in enumerate(staged, 1):
        key = record['target_key']; row = rows[key]; decision = decisions[key]
        require(re.fullmatch(r'[0-9a-f]{24}', key), 'Unsafe staged key')
        require(record['source'] == row and record['class_id'] == row['final_class_id'], 'Staged formal identity differs')
        equal(record['request_order'], order, 'staged_order')
        equal(record['native_image'], f'images/{key}.png', 'staged_native_path')
        equal(record['contact_crop'], f'cases/{key}.png', 'staged_crop_path')
        equal(record['crop_native_bounds'], crop_bounds(row), 'native_crop_bounds')
        require(type(decision.get('approved')) is bool and decision.get('full_image_inspected') is True
            and decision.get('crop_inspected') is True and isinstance(decision.get('note_zh'), str)
            and decision['note_zh'].strip(), 'Explicit full/crop decision required, including withheld images')
        image_sha = digest(member(formal, row['image']))
        require(key not in forbidden and row['frame_id'] not in blocked_frames and image_sha not in blocked_hashes,
            'Previously saved/canonical/inspected/protected source or duplicate image bytes staged')
        require(row['frame_id'] not in frames and image_sha not in hashes, 'Duplicate staged frame/native bytes')
        frames.add(row['frame_id']); hashes.add(image_sha)
        require(digest(member(root/'internal', record['native_image'])) == image_sha, 'Staged image not byte-identical native input')
        equal(record['image_quality'], native_quality(row, evidence), 'staged_native_quality')
        value = pose['current'].get(key)
        current = value[2] if value else None
        history = [e[3] for e in pose['histories'].get(key, [])]
        equal(record['existing_pose_current_payload'], current, 'all_preserved_pose_fields')
        equal(record['existing_pose_revision'], value[0] if value else 0, 'staged_pose_revision')
        equal(record['existing_pose_payload_sha256'], sha(current) if value else None, 'staged_pose_payload')
        equal(record['existing_pose_history_sha256'], sha(history), 'staged_pose_history')
        equal(record['no_pose_current_or_history'], key not in pose['current'] and key not in pose['histories'], 'pose_presence')
        # The staged crop must actually depict the native region declared in the record.
        image = Image.fromarray(evidence.image(row['frame_id'])).convert('RGB')
        left, top, right, bottom = record['crop_native_bounds']
        crop = image.crop((left, top, right, bottom))
        box = row['bbox']; x, y, w, h = (box[f] for f in ('x', 'y', 'width', 'height'))
        ImageDraw.Draw(crop).rectangle((x-left, y-top, x+w-left, y+h-top), outline=(255, 180, 40), width=1)
        with Image.open(member(root/'internal', record['contact_crop'])) as actual:
            require(np.array_equal(np.asarray(actual), np.asarray(crop)), 'Staged native crop differs')
    return records, hashes


def check_draft(proposal, task, record, decision, formal_sha, input_sha, image_sha):
    """Exact independent schema replay; a valid polygon is not an accuracy pass."""
    key, row = record['target_key'], record['source']
    require(decision['approved'] is True and decision.get('polygon') == proposal['polygon'], 'Issued polygon not explicitly approved')
    polygon = decision['polygon']; sources.polygon(polygon, row['size'])
    require(not sources.original_rectangle(polygon, row), 'Original rectangle relabelled as contour')
    proof = dict(method='assistant_direct_native_image_contour_not_template_transfer', author_role='AI_assistant',
        crop_inspected=True, full_image_inspected=True, note_zh=decision['note_zh'], image_sha256=image_sha,
        polygon_sha256=sha(polygon), human_saved=False, counts_toward_coverage_before_real_human_save=False,
        input_manifest_sha256=input_sha)
    reference = dict(origin='assistant_visual_preannotation', target_key=key,
        snapshot_revision=record['existing_pose_revision'], current_payload_sha256=record['existing_pose_payload_sha256'])
    value = record['existing_pose_current_payload']
    if value:
        reference['pose_review'] = dict(target_key=key, revision=value['revision'], payload_sha256=sha(value), polygon_sha256=sha(value['polygon']))
    expected = dict(schema='assistant_visual_preannotation_v1', origin='assistant_visual_preannotation', target_key=key,
        class_id=row['final_class_id'], source=row, polygon=polygon, vertex_count=len(polygon),
        status='assistant_preannotated_draft_pending_human_review', formal_manifest_sha256=formal_sha,
        preannotation=proof, draft_source=reference, target_expected_revision=record['existing_pose_revision'],
        target_snapshot_payload_sha256=record['existing_pose_payload_sha256'],
        mask_semantics='assistant_direct_visible_fork_face_contour_draft_not_GT', **dict.fromkeys(FALSE_FLAGS, False))
    equal(proposal, expected, 'direct_native_proposal')
    expected_task = dict(target_key=key, class_id=row['final_class_id'], source=row,
        status='preannotated_awaiting_human_review', assistant_polygon=polygon, preannotation=proof,
        existing_pose_revision=record['existing_pose_revision'], existing_pose_payload_sha256=record['existing_pose_payload_sha256'],
        existing_pose_record=value is not None, native_image=record['native_image'], contact_crop=record['contact_crop'],
        image_quality=record['image_quality'], valid_four_point_manual_contour_allowed=True,
        extra_vertices_must_not_be_forced=True, preserve_existing_pose_until_intentional_human_edit=True,
        counts_as_completed_annotation=False)
    equal(task, expected_task, 'direct_native_task')


def check_exports(root, proposal, record, image_sha):
    key, row, polygon = proposal['target_key'], proposal['source'], proposal['polygon']
    require(digest(member(root, f'images/{key}.png')) == image_sha, 'Export changed native image bytes')
    expected_mask = sources.raster(polygon, row['size']).astype(np.uint8)*255
    require(expected_mask.any(), 'Raster-empty draft')
    with Image.open(member(root, f'masks/{key}.png')) as actual:
        require(actual.mode == 'L' and np.array_equal(np.asarray(actual), expected_mask), 'Target-only raster differs')
    expected_label = dict(version='5.0.0', imagePath=f'../images/{key}.png', imageData=None,
        imageWidth=row['size'][0], imageHeight=row['size'][1],
        flags=dict(assistant_preannotation=True, human_confirmed=False, ground_truth_eligible=False),
        annotation_scope='single_target_not_full_frame', shapes=[dict(label='pallet', shape_type='polygon',
            points=polygon, group_id=row['box_index'], flags=dict(human_confirmed=False))])
    equal(read(member(root, f'labelme/{key}.json')), expected_label, 'single_target_labelme')
    with Image.open(member(root, f'images/{key}.png')) as image:
        require(list(image.size) == row['size'], 'Native export dimensions differ')
        preview = image.convert('RGB')
    draw = ImageDraw.Draw(preview)
    draw.line([tuple(p) for p in polygon]+[tuple(polygon[0])], fill='#55d5ff', width=1)
    for i, point in enumerate(polygon, 1):
        draw.text(tuple(point), str(i), fill='#ffce33')
    left, top, right, bottom = record['crop_native_bounds']
    preview = preview.crop((left, top, right, bottom)).resize(((right-left)*3, (bottom-top)*3), Image.Resampling.NEAREST)
    with Image.open(member(root, f'cases/{key}.png')) as actual:
        require(np.array_equal(np.asarray(actual), np.asarray(preview)), 'Published crop/coordinates do not match native polygon')


def check_issued_inventory(proposals, tasks, staged, decisions, manifest, actual_counts):
    proposal_map, task_map = sources.indexed(proposals), sources.indexed(tasks)
    require(proposals and len(proposals) == len(tasks) <= 12, 'Empty, unpaired or oversized request batch')
    equal(manifest['request_count'], len(proposals), 'request_count')
    staged_keys = {record['target_key'] for record in staged}
    require(set(decisions) == staged_keys, 'Missing/unknown own staged decision')
    issued = [r['target_key'] for r in staged if decisions[r['target_key']]['approved'] is True]
    require([p['target_key'] for p in proposals] == [t['target_key'] for t in tasks] == issued
        and set(proposal_map) == set(task_map) <= staged_keys, 'Own staged/approved/proposal/task inventory or order differs')
    counts = Counter(p['class_id'] for p in proposals)
    require(all(c in CLASSES and n <= min(2, 50-actual_counts[c]) for c, n in counts.items()), 'Under-50 issued class maximum/gap exceeded')
    equal(manifest['class_counts'], {str(c): n for c, n in counts.items()}, 'issued_class_counts')
    equal(manifest['classes'], sorted(counts), 'issued_classes')
    return counts, [dict(target_key=r['target_key'], reason='source_withheld_counted_or_class_quota', decision=decisions[r['target_key']])
        for r in staged if r['target_key'] not in proposal_map]


class PageInventory(HTMLParser):
    def __init__(self, page):
        super().__init__(); self.articles = []; self.options = []; self.assets = []; self.in_filter = False
        self.feed(page)

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == 'article':
            self.articles.append((attrs.get('id'), attrs.get('data-class')))
        if tag == 'select':
            self.in_filter = attrs.get('id') == 'request-filter'
        if tag == 'option' and self.in_filter:
            self.options.append(attrs.get('value'))
        if tag in ('a', 'img'):
            self.assets.append(attrs.get('href' if tag == 'a' else 'src'))

    def handle_endtag(self, tag):
        if tag == 'select':
            self.in_filter = False


def check_public(root, manifest, proposals):
    allowed = {'report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt'}
    for proposal in proposals:
        for folder, extension in (('images', 'png'), ('cases', 'png'), ('masks', 'png'), ('labelme', 'json')):
            allowed.add(f'{folder}/{proposal["target_key"]}.{extension}')
    require(set(manifest['public_assets']) == allowed, 'Public asset allowlist differs/private source exposed')
    for name, expected in manifest['public_assets'].items():
        require(digest(member(root, name)) == expected, 'Public asset hash differs: '+name)
    page = member(root, 'report_zh.html').read_text(encoding='utf-8')
    require(all(text in page for text in ('少于50', '真实人工轮廓', '每类最多2张', '第15版', '已预标注', '保存前不计覆盖',
        '不自动确认GT、训练或机器人资格', '有效四点保持四点', '不为传播模板强行增点')), 'Report omits under-50/manual-count/draft-only scope')
    require('第三批' not in page and not any(token in page for token in
        ('existing_pose_current_payload', 'current_payload_raw', 'human_event_payload_raw', 'access_key', 'access_code',
         'selected_faces', 'ruler', 'fetch(')), 'Report exposes secrets or mislabels this as an old batch')
    require(all(f'Class {c}：{EXPECTED_COUNTS[c]}份' in page for c in CLASSES), 'Report actual manual count table differs')
    parsed = PageInventory(page)
    equal(parsed.articles, [(f'target-{p["target_key"]}', str(p['class_id'])) for p in proposals], 'report_target_cards')
    equal(parsed.options, ['']+[str(c) for c in CLASSES], 'under50_filter_options')
    require(all(name in allowed for name in parsed.assets), 'Unallowlisted/private/external report asset')
    from fontTools.ttLib import TTFont
    with TTFont(member(root, 'report-font.otf')) as font:
        require({ord(c) for c in page if '\u3400' <= c <= '\u9fff'} <= set(font.getBestCmap()), 'Chinese font glyph missing')
    require(digest(root/'FONT_LICENSE.txt') == digest(PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt'), 'Font license differs')
    return allowed


def check_sources(quality, parent_manifest):
    """Recheck sealed raw evidence and all current/history fields, never recount machines."""
    require(digest(quality/'independent_verification.json') == QUALITY_SEAL_SHA256, 'Pinned independent quality-v2 seal differs')
    seal, result = read(quality/'independent_verification.json'), read(quality/'result.json')
    require(seal['state'] == 'passed' and seal['result_sha256'] == digest(quality/'result.json')
        and seal['source_catalog_sha256'] == digest(quality/'private/source_catalog.jsonl'), 'Quality source seal binding differs')
    for name, expected in result['output_artifacts'].items():
        require(digest(member(quality, name)) == expected, 'Sealed quality artifact changed: '+name)
    for name, expected in {**seal['code_sha256'], **seal['frozen_code_sha256'], **FROZEN_INTERFACE_PINS}.items():
        require(digest(member(PROJECT, name)) == expected, 'Frozen source auditor/exporter/qualification changed: '+name)
    pose = sources.read_store(quality/'private/pose_snapshot.sqlite3', 'pose', True)
    gallery = sources.read_store(quality/'private/gallery_snapshot.sqlite3', 'gallery', True)
    require((len(pose['current']), len(pose['events']), len(gallery['current']), len(gallery['events'])) == (4946, 11926, 1002, 1088),
        'Exact pose4946/11926 and gallery1002/1088 evidence required')
    for kind, path, frozen in (('pose', POSE, pose), ('gallery', GALLERY, gallery)):
        live = sources.read_store(path, kind)
        equal(live, frozen, 'all_raw_live_and_quality_snapshot_'+kind)
        equal(frozen['fingerprint'], seal['source_fingerprints'][kind], 'quality_fingerprint_'+kind)
        equal(result['source_fingerprints'][kind], frozen['fingerprint'], 'result_fingerprint_'+kind)
        for key in frozen['current']:
            sources.exact_latest(frozen, key)
    formal, rows, frames = sources.load_formal(parent_manifest)
    evidence = sources.NativeEvidence(formal, rows, frames)
    publications, registry, task_pins = sources.registries(rows, parent_manifest['formal_manifest_sha256'], pose)
    catalog = read_jsonl(quality/'private/source_catalog.jsonl')
    sources.check_catalog(quality, catalog, pose, gallery, rows, publications, registry,
        parent_manifest['formal_manifest_sha256'], evidence)
    equal(result['source_summary']['task_inputs'], task_pins, 'sealed_previous_task_pins')
    equal(result['source_summary']['publication_inputs'], {str(v): {field: p[field] for field in
        ('manifest_sha256', 'proposals_sha256', 'verification_sha256')} for v, p in publications.items()}, 'sealed_publication_pins')
    return seal, formal, rows, evidence, pose, gallery, catalog


def old_evidence_roots(project, own_root, parent, quality, prior_names):
    roots = {parent, quality, *(project/'outputs'/name for name in sources.PUBLICATIONS.values()),
        *(project/f'outputs/pallet_mask_preannotated_requests_v{n}' for n in (1, 2, 3))}
    for name in prior_names:
        member(project, name)
        parts = Path(name).parts
        require(len(parts) >= 3 and parts[0] == 'outputs', 'Prior inspection is not in a separate output root')
        roots.add(project/parts[0]/parts[1])
    roots.discard(own_root)
    return roots


def audit(root=ROOT, parent=PARENT, quality=QUALITY):
    """Audit a completed preactivation pack; no files or stores are written here."""
    root, parent, quality = Path(root), Path(parent), Path(quality)
    before = inventory(root)
    require(not set(SEALS) & before.keys(), 'Never re-audit into existing seals')
    manifest, inputs, parent_manifest = read(root/'manifest.json'), read(root/'input_manifest.json'), read(parent/'manifest.json')
    # Only old evidence/task roots are frozen. Unrelated training output is not.
    old_roots = old_evidence_roots(PROJECT, root, parent, quality, inputs['prior_request_inventories_sha256'])
    old_before = {str(path.relative_to(PROJECT)): inventory(path) for path in sorted(old_roots)}
    code = {name: digest(member(PROJECT, name)) for name in (
        'scripts/build_mask_under50_requests.py', 'scripts/verify_mask_under50_requests.py', 'tests/test_verify_mask_under50_requests.py',
        *FROZEN_INTERFACE_PINS)}
    for name, expected in PARENT_PINS.items():
        require(digest(parent/name) == expected, 'Pinned publication15 changed: '+name)
    parent_seal = read(parent/'verification.json')
    require(parent_seal['state'] == 'passed' and parent_seal['publication_version'] == 15, 'Publication15 independent seal required')
    for field, name in (('parent_manifest_sha256', 'manifest.json'), ('parent_proposals_sha256', 'proposals.jsonl'),
            ('parent_verification_sha256', 'verification.json')):
        require(manifest[field] == digest(parent/name), 'Task parent binding differs')
    equal(manifest['parent_directory'], str(parent.relative_to(PROJECT)), 'parent_directory')
    for field, name in (('input_manifest_sha256', 'input_manifest.json'), ('proposals_sha256', 'proposals.jsonl'),
            ('requests_sha256', 'requests.jsonl'), ('decisions_sha256', 'internal/build_decisions.json')):
        require(manifest[field] == digest(root/name), 'Task input/decision/geometry hash differs: '+name)
    require(inputs['shortlist_sha256'] == digest(root/'internal/shortlist.jsonl'), 'Staged shortlist changed')
    require(inputs['source_quality_audit_sha256'] == QUALITY_SEAL_SHA256, 'Wrong actual-human source audit')
    configuration = inventory(PROJECT/'configs')
    equal(configuration, inputs['configuration_sha256'], 'configurations_preserved_since_staging')
    quality_seal, formal, rows, evidence, pose, gallery, catalog = check_sources(quality, parent_manifest)
    equal(configuration, quality_seal['configuration_sha256'], 'quality_configurations_preserved')
    counts = check_count_basis(catalog, inputs, manifest)
    protected = sources.protected_inventory(formal)
    require(len(protected) == 20768 and protected == inputs['formal_protected']
        == read(parent/'protected_formal_after.json') == read(quality/'private/protected_formal_before.json'), 'All20768 formal protected files differ')
    equal(inputs['formal_manifest_sha256'], parent_manifest['formal_manifest_sha256'], 'staging_formal_manifest')
    equal(manifest['formal_manifest_sha256'], parent_manifest['formal_manifest_sha256'], 'task_formal_manifest')
    fingerprints = {str(path.relative_to(PROJECT)): database_fingerprint(path) for path in (POSE, GALLERY)}
    equal(inputs['database_fingerprints'], fingerprints, 'exact_live_preactivation_store_fingerprints')
    prior_hashes, prior_keys = prior_inspections(PROJECT, root, rows)
    equal(inputs['prior_request_inventories_sha256'], prior_hashes, 'all_previous_requests_and_shortlists_including_rejects')
    parent_proposals = read_jsonl(parent/'proposals.jsonl')
    require(len(parent_proposals) == 1550 and len({p['source']['frame_id'] for p in parent_proposals}) == 1550,
        'All1550 frozen canonical frames must remain protected, not recounted as actual human sources')
    # Quarantine membership is itself covered by the frozen old-code pins.
    from pallet.mask_template_refined import QUARANTINE
    forbidden = protected_keys(rows, pose, gallery, catalog, parent_proposals, prior_keys, QUARANTINE)
    staged = read_jsonl(root/'internal/shortlist.jsonl'); decisions = read(root/'internal/build_decisions.json')['decisions']
    records, staged_hashes = check_staged(root, staged, decisions, rows, formal, evidence, pose, forbidden)
    proposals, tasks = read_jsonl(root/'proposals.jsonl'), read_jsonl(root/'requests.jsonl')
    issued_counts, expected_deferred = check_issued_inventory(proposals, tasks, staged, decisions, manifest, counts)
    equal(read(root/'internal/deferred_sources.json'), expected_deferred, 'all_withheld_decisions')
    for proposal, task in zip(proposals, tasks):
        key = proposal['target_key']; record = records[key]
        image_sha = digest(member(formal, rows[key]['image']))
        check_draft(proposal, task, record, decisions[key], manifest['formal_manifest_sha256'], digest(root/'input_manifest.json'), image_sha)
        check_exports(root, proposal, record, image_sha)
    check_public(root, manifest, proposals)
    require(not any(p.suffix.lower() in ('.db', '.sqlite', '.sqlite3') for p in root.rglob('*')), 'Private database copied into worklist')
    equal(manifest['schema'], 'preannotated_mask_worklist_v1', 'request_schema')
    for field in ('assistant_drafts_not_counted_as_completed', 'strict_registration_gates_not_relaxed', 'source_stores_preserved',
            'old_publications_and_tasks_not_modified', 'training_snapshot_not_modified'):
        equal(manifest[field], True, field)
    equal(inputs['all_prior_inspected_sources_excluded'], True, 'prior_inspection_exclusion')
    equal(manifest['template_transfer_used'], False, 'not_template_transfer')
    for field in ('production_annotation_writes', 'human_events_created', 'configuration_writes'):
        equal(manifest[field], 0, field)
    require(manifest['generation_code_sha256'] == code['scripts/build_mask_under50_requests.py']
        and manifest['reused_exporter_code_sha256'] == FROZEN_INTERFACE_PINS['scripts/build_mask_preannotated_requests_v3.py'], 'Generator/exporter code binding differs')
    require(inventory(root) == before and inventory(PROJECT/'configs') == configuration
        and sources.protected_inventory(formal) == protected, 'Pack/config/formal files changed during audit')
    for kind, path, frozen in (('pose', POSE, pose), ('gallery', GALLERY, gallery)):
        equal(sources.read_store(path, kind), frozen, 'raw_source_changed_during_audit_'+kind)
        require(database_fingerprint(path) == fingerprints[str(path.relative_to(PROJECT))], 'Store changed during audit')
    require(prior_inspections(PROJECT, root, rows)[0] == prior_hashes, 'Global inspection history changed during audit')
    for name, expected in evidence.used.items():
        require(digest(member(formal, name)) == expected, 'Used native source changed during audit')
    for name, expected in code.items():
        require(digest(member(PROJECT, name)) == expected, 'Verifier/generator/interface code changed during audit')
    for name, expected in old_before.items():
        require(inventory(PROJECT/name) == expected, 'Old evidence/task root changed during audit')
    return dict(state='passed', request_count=len(proposals), class_counts=dict(issued_counts), filter_classes=list(CLASSES),
        public_assets=manifest['public_assets'], requests_sha256=digest(root/'requests.jsonl'), proposals_sha256=digest(root/'proposals.jsonl'),
        manifest_sha256=digest(root/'manifest.json'), preannotations_verified=True, formal_manifest_sha256=manifest['formal_manifest_sha256'],
        parent_proposals_sha256=digest(parent/'proposals.jsonl'), parent_verification_sha256=digest(parent/'verification.json'),
        parent_pins=PARENT_PINS, source_quality_audit_sha256=QUALITY_SEAL_SHA256,
        source_catalog_sha256=digest(quality/'private/source_catalog.jsonl'), input_manifest_sha256=digest(root/'input_manifest.json'),
        decisions_sha256=digest(root/'internal/build_decisions.json'), shortlist_sha256=digest(root/'internal/shortlist.jsonl'),
        actual_human_saved_sources=1484, actual_class_counts=dict(counts), maximum_issued_per_class=2, maximum_staged_per_class=3,
        class_scope=CLASS_SCOPE, own_staged_source_count=len(staged), withheld_source_count=len(expected_deferred),
        all_prior_inspected_sources_excluded=True, prior_request_inventories_sha256=prior_hashes,
        source_fingerprints=quality_seal['source_fingerprints'], preactivation_database_fingerprints=fingerprints,
        configuration_sha256=configuration, protected_formal_files=20768, protected_formal_inventory_sha256=sha(protected),
        old_root_inventory_sha256={name: sha(value) for name, value in old_before.items()}, output_inventory_sha256=sha(before),
        code_sha256=code, verification_script_sha256=digest(__file__), frozen_code_sha256=quality_seal['frozen_code_sha256'],
        all_current_pose_records_preserved=4946, all_pose_events_preserved=11926, gallery_contours_verified=1002, gallery_events_verified=1088,
        distinct_native_image_hashes=len({digest(root/'images'/f'{p["target_key"]}.png') for p in proposals}),
        distinct_staged_native_image_hashes=len(staged_hashes), topology_counts=dict(Counter(p['vertex_count'] for p in proposals)),
        assistant_direct_annotation_not_template_transfer=True, original_rectangle_not_used_as_preannotation=True,
        original_native_quality_gates_unchanged=True, all_actual_polygons_before_publication=True,
        assistant_drafts_not_counted_as_completed=True, production_annotation_writes=0, human_events_created=0, configuration_writes=0,
        semantic_contour_accuracy_established=False, human_inspection_independently_observed=False,
        limitations=['Schema, source provenance, native coordinate/export consistency and preservation are verified; contour accuracy is not.',
            'Full-image/crop inspection is recorded by the assistant; this audit cannot prove the subjective visual judgments.',
            'Class labels and saved human contours are unconfirmed research references, not independent ground truth.',
            'Four-point contours are permitted, without forcing vertices or qualifying them as old strict propagation seeds.',
            'This is a preactivation seal: live stores must be unchanged now. Later intentional human saves may extend history.',
            'No live service, access-code equivalence or editor save is tested here; publication and temporary-store smoke tests are separate.'],
        verified_at=datetime.now(timezone.utc).isoformat())


def seal(root=ROOT, *, producer_complete=False, auditor=None):
    """Write identical exclusive seals only after an explicitly ready, passing audit."""
    require(producer_complete is True, 'Explicit producer completion notification required; do not inspect unfinished staging')
    root = Path(root)
    require(not root.is_symlink() and root.is_absolute() and root == root.resolve()
        and root == PROJECT/'outputs/pallet_mask_under50_requests_v1', 'Only the exact own independent output may receive seals')
    for name in SEALS:
        require(not (root/name).exists() and not (root/name).is_symlink(), 'Never overwrite existing verification seals')
    require((root/'manifest.json').is_file(), 'Producer has not completed the manifest')
    result = (auditor or audit)(root)
    require(result.get('state') == 'passed', 'Independent audit did not pass')
    raw = canonical(result)+b'\n'
    owned = []
    try:
        for name in SEALS:
            path = root/name
            with path.open('xb') as stream:
                owned.append((path, os.fstat(stream.fileno()).st_ino))
                os.fchmod(stream.fileno(), 0o600)
                stream.write(raw); stream.flush(); os.fsync(stream.fileno())
    except BaseException:
        for path, inode in owned:
            if not path.is_symlink() and path.exists() and path.stat().st_ino == inode:
                path.unlink()  # Only files exclusively created by this call.
        raise
    return result


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--producer-complete', action='store_true', help='Producer explicitly announced pack completion')
    args = parser.parse_args()
    verified = seal(producer_complete=args.producer_complete)
    import json
    print(json.dumps({key: verified[key] for key in ('state', 'request_count', 'class_counts', 'semantic_contour_accuracy_established')},
        ensure_ascii=False), flush=True)
