"""One-time Task22 supplemental owner-review recovery.

This is intentionally not a reusable re-review facility.  It recognizes one
fully pinned, append-only transaction over an already-finalized onboarding
bundle.  Existing answers, attestation, baseline, readiness, and historical
publication records are read and digest-bound but are never rewritten.
"""

from __future__ import annotations

import base64
import fcntl
import hashlib
import hmac
import json
import os
import re
import stat
import tempfile
from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Final, cast

from gateway.platforms.telegram_nutrition_onboarding import encode_callback_hash
from gateway.platforms.telegram_nutrition_onboarding_publication_outbox import (
    GatewayOnboardingPublicationOutbox,
    GatewayOwnerCallbackReceipt,
    GatewayPublicationReceipt,
)

_SCHEMA: Final = "task22-supplemental-owner-review-v1"
_APPROVAL_SCHEMA: Final = "task22-supplemental-owner-approval-v1"
_TERMINAL_BINDING_SCHEMA: Final = "task22-supplemental-terminal-binding-v1"
_CLASSIFICATION: Final = "historical_provenance_incomplete"
_JOURNAL_NAME: Final = "task22-supplemental-owner-review-v1.json"
_RESEAL_RECEIPT_NAME: Final = "task22-supplemental-owner-review-reseal-v1.json"
_RESEAL_RECEIPT_SCHEMA: Final = "task22-supplemental-owner-review-reseal-v1"
_LOCK_NAME: Final = ".task22-supplemental-owner-review-v1.lock"
_DIGEST = re.compile(r"^[a-f0-9]{64}$")
_PRIVATE_FILE = 0o600
_PRIVATE_DIRECTORY = 0o700
_NOATIME = getattr(os, "O_NOATIME", 0)
_MAX_PERSISTED_INTEGER: Final = (1 << 63) - 1
_TASK22_COMPATIBILITY: Final = "task22-historical-prepared-generation-27-v1"
_TASK22_PROFILE: Final = "dualcoachtest"
_TASK22_CUSTOMER: Final = "task22_dm_rehearsal"
_TASK22_SESSION: Final = "rb_Ar-NuKG3LH8CqHPXUgc88g"
_TASK22_HISTORICAL_CANDIDATE: Final = (
    "c160085a64454c23f789464170b299543324c743a489bac68ed5430fab42d291"
)
_TASK22_HISTORICAL_MANIFEST_NAME: Final = "dualcoach-candidate-manifest.json"
_TASK22_HISTORICAL_MANIFEST_SHA256: Final = (
    "e9bc7dff8060425aa001f6a4501107bb9685be9248a7753f0969f89c2cf5d5c8"
)
_TASK22_HISTORICAL_CANDIDATE_DIFF_SHA256: Final = (
    "64099acdf8667cf52fff50216fe37dca180d5515727f3923aceabdea2248c8d1"
)
_TASK22_FREEZE_NAME: Final = "dualcoach-owner-v1-freeze-receipt.json"
_TASK22_FREEZE_SHA256: Final = (
    "cbb8f9b14c961113ac06cf474b1d73ca302440ee1b7d0b73941c2cd2c2d3b80a"
)
_TASK22_FREEZE_DIGEST: Final = (
    "f02f8b5ee211e571c70cf928da4b7862ae20e9cf56189815789c13e1cb4af995"
)
_TASK22_PRE_SUPPLEMENTAL_NAME: Final = "dualcoach-task-22-pre-supplemental-evidence.json"
_TASK22_PRE_SUPPLEMENTAL_SHA256: Final = (
    "9c27354011d4050e4fc5bbb18efbdd8f56360d74e8b8dc18098fa6cc9e6b55b3"
)
_TASK22_PRE_SUPPLEMENTAL_DIGEST: Final = (
    "359adbba7bca9cfebfdeb049bc8a06c970e415d3250178910e187b745ca5987d"
)
_TASK22_SUCCESSOR_CANDIDATE: Final = (
    "cae3f885c66e6c1174f8761ec47db4ba585eba034a6f275f3e81fc5e986401ba"
)
_TASK22_SUCCESSOR_MANIFEST_SHA256: Final = (
    "bd0c6dbbf26e6f6d50e9d03db0ba8e7725da8d4a3cdd377f8eefacb9900732ea"
)
_TASK22_PREDECESSOR_MANIFEST_NAME: Final = "dualcoach-trainer-removal-successor-manifest.json"
_TASK22_PREDECESSOR_MANIFEST_SHA256: Final = (
    "9b52c89bd483d64dc48f83dd5cd3d61f99c2bedc47f57f905508779e29de14f1"
)
_TASK22_PREDECESSOR_CANDIDATE: Final = (
    "18a54bfebc9e81c70da8c1a4829a84892ad93e0e346378685f5f21ad6b89685b"
)
_TASK22_GENERATION_27_DISPATCH: Final = (
    "c6e06b11125e4ea6e17c30d8b372a382ba6cff4dadb19d9ff0de3bfab844c239"
)
_TASK22_GENERATION_27_RENDER: Final = (
    "e8755dd5f864bfead5c1fc0de8ff0f0cbd43af70a80a78c655cfc4b9c4f162cd"
)
_TASK22_CALLBACK_EVENT_INTEGRITY: Final = (
    "987cdde4e245b1d316ab5000271a755db148153b5207156b8082f97c2a1f5c18"
)
_TASK22_CALLBACK_DATA: Final = (
    "non2:owner_ok:27:8ECJo9Mzz7Ncb9_4-SAbCgIaf9DvpTklqa8ZVUb2GdY"
)
_TASK22_EMBEDDED_SID_HASH: Final = (
    "f04089a3d333cfb35c6fdff8f9201b0a021a7fd0efa53925a9af195546f619d6"
)
_TASK22_SESSION_SHA256: Final = (
    "259312739d9f8d31c42e56d5741fc00b419f2ad927de09095461406bd6628b46"
)
_TASK22_ANSWERS_DIGEST: Final = (
    "f1aced0350c473a01aa4e1382bc810e072fccfe84ccd3ea8780ee83c324dfe55"
)
_TASK22_INGRESS_RECEIPT_NAME: Final = (
    "telegram-ingress-receipts-v1-d0aacf0f4bdbb7c0.json"
)
_TASK22_CALLBACK_UPDATE_ID: Final = 629525051
_TASK22_CALLBACK_MESSAGE_ID: Final = 122
_TASK22_PREVIOUS_RECOVERY_UPDATE_ID: Final = 629525050
_TASK22_PREVIOUS_RECOVERY_PROVENANCE: Final = (
    "6a998ed1222fbfac36f43d8c124a74dca4e72b7cd6e92d4bfc79328dc19cddff"
)
_TASK22_OWNER_ID: Final = 8693203710
_TASK22_OWNER_AUTHORITY: Final = (8693203710, 8693203710, 0)
_TASK22_OWNER_ROUTE: Final = ("8693203710", "0")
_TASK22_SUCCESSOR_BINDING: Final = {
    "schema_version": 9,
    "candidate_digest": _TASK22_SUCCESSOR_CANDIDATE,
    "candidate_diff_sha256": "83193884d094df6fe3ca531a0d8f60b3b4ff8bb3b92d9cfe7a0a47bd330b7237",
    "gateway_candidate_digest": "6627944cabedd266b6417b6de8cf1e6736ab8c362c441705943ac10525cd5b47",
    "gateway_diff_sha256": "0d86b64b5f9eb8494ded2bba0c8c77071807983d82dcd38616d6cce6108ba062",
    "predecessor": {
        "candidate_digest": _TASK22_PREDECESSOR_CANDIDATE,
        "manifest_digest": _TASK22_PREDECESSOR_MANIFEST_SHA256,
        "classification": (
            "historical Task22 recovery successor retained; supplemental replay "
            "successor is PREPARED-only"
        ),
    },
    "successor_scope": {
        "candidate_path_scope_preserved": True,
        "changed_candidate_paths": [
            "gateway:gateway/platforms/rehearsal_reset.py",
            "gateway:gateway/platforms/task22_trainer_authority_recovery.py",
            "gateway:gateway/platforms/task22_trainer_authority_removal.py",
            "gateway:gateway/platforms/telegram_nutrition_onboarding_supplemental_review.py",
            "gateway:scripts/task22-supplemental-owner-review",
            "gateway:tests/gateway/test_task22_supplemental_owner_review.py",
            "gateway:tests/gateway/test_task22_trainer_authority_removal.py",
        ],
        "gateway_status_scope_preserved": True,
        "live_profile_accessed": False,
    },
    "verification": {
        "mode": "offline-code-only-successor-reseal",
        "predecessor_candidate_retained": True,
        "live_profile_accessed": False,
    },
}
_JOURNAL_FIELDS: Final = frozenset({
    "schema",
    "profile",
    "customer_key",
    "session_id",
    "original_transaction_id",
    "review_epoch",
    "candidate_digest",
    "candidate_manifest_path",
    "candidate_manifest_digest",
    "baseline_candidate_digest",
    "baseline_digest",
    "attestation_receipt_integrity",
    "readiness_bundle_digest",
    "original_journal_digest",
    "registry_digest",
    "callback_storage_adoption_binding",
    "trainer_removal_binding",
    "bootstrap_digest",
    "sealed_sources",
    "file_identities",
    "authority_digest",
    "owner_route",
    "classifications",
    "publication_bindings",
    "phase_events",
    "review_update_id",
    "callback_event_integrity",
    "callback_envelope_digest",
    "approval_digest",
    "review_commit_digest",
    "terminal_publication_binding",
    "terminal_transition_digest",
    "terminal_receipt_integrity",
    "transaction_id",
    "integrity",
})

class SupplementalReviewError(RuntimeError):
    """The bounded supplemental transaction cannot proceed safely."""

class SupplementalReviewPhase(StrEnum):
    PREPARED = "PREPARED"
    REVIEW_COMMITTED = "REVIEW_COMMITTED"
    PUBLICATION_COMMITTED = "PUBLICATION_COMMITTED"

@dataclass(frozen=True, slots=True)
class SupplementalReviewPins:
    profile: str
    customer_key: str
    session_id: str
    original_transaction_id: str
    candidate_digest: str
    review_epoch: int = 1
    historical_review_generation: int = 25
    historical_ready_generation: int = 26
    review_generation: int = 27
    confirmation_generation: int = 28

    def __post_init__(self) -> None:
        text = (
            self.profile,
            self.customer_key,
            self.session_id,
            self.original_transaction_id,
        )
        if any(not isinstance(item, str) or not item or len(item) > 256 for item in text):
            raise SupplementalReviewError("supplemental review pins are invalid")
        if _DIGEST.fullmatch(self.candidate_digest) is None:
            raise SupplementalReviewError("supplemental candidate digest is invalid")
        generations = (
            self.historical_review_generation,
            self.historical_ready_generation,
            self.review_generation,
            self.confirmation_generation,
        )
        if (
            type(self.review_epoch) is not int
            or self.review_epoch != 1
            or any(type(item) is not int for item in generations)
            or generations != (25, 26, 27, 28)
        ):
            raise SupplementalReviewError("supplemental review epoch is not authorized")

@dataclass(frozen=True, slots=True)
class SupplementalReviewPaths:
    profile_root: Path
    candidate_manifest: Path
    onboarding_root: Path
    baseline_candidate: Path
    baseline: Path
    ready: Path
    readiness_pointer: Path
    readiness_receipt: Path
    original_journal: Path
    registry: Path
    bootstrap: Path
    publication_projection: Path
    journal: Path
    lock: Path

    @classmethod
    def canonical(
        cls,
        profile_root: Path | str,
        *,
        candidate_manifest: Path | str,
        customer_key: str,
    ) -> "SupplementalReviewPaths":
        root = Path(profile_root).absolute()
        onboarding = root / "data" / "customers" / customer_key / "nutrition-onboarding"
        return cls(
            profile_root=root,
            candidate_manifest=Path(candidate_manifest).absolute(),
            onboarding_root=onboarding,
            baseline_candidate=onboarding / "baseline-candidate.json",
            baseline=onboarding / "baseline-v1.json",
            ready=onboarding / "ready.json",
            readiness_pointer=onboarding / "readiness-current.json",
            readiness_receipt=onboarding / "readiness-receipt-v1.json",
            original_journal=onboarding / "migrations" / "owner-v1.json",
            registry=root / "customers" / "registry.json",
            bootstrap=root / "data" / "onboarding" / "telegram-room-bootstrap-v1" / "ledger.json",
            publication_projection=onboarding / "session.json",
            journal=onboarding / "migrations" / _JOURNAL_NAME,
            lock=onboarding / "migrations" / _LOCK_NAME,
        )

@dataclass(frozen=True, slots=True)
class SupplementalReviewSnapshot:
    transaction_id: str
    phase: SupplementalReviewPhase
    baseline_digest: str
    readiness_bundle_digest: str
    authority_digest: str
    candidate_digest: str
    review_update_id: int | None

@dataclass(frozen=True, slots=True)
class SupplementalPublicationStatus:
    state: Any
    answer_count: int = 22
    next_field: None = None

    @classmethod
    def owner_review(cls) -> "SupplementalPublicationStatus":
        return cls(SimpleNamespace(value="owner_review"))

    @classmethod
    def ready(cls) -> "SupplementalPublicationStatus":
        return cls(SimpleNamespace(value="ready"))

class SupplementalReviewStore:
    """Descriptor-safe state machine for the sole Task22 recovery epoch."""

    def __init__(
        self,
        paths: SupplementalReviewPaths,
        pins: SupplementalReviewPins,
        *,
        outbox: GatewayOnboardingPublicationOutbox | None = None,
    ) -> None:
        self.paths = paths
        self.pins = pins
        self.outbox = outbox or GatewayOnboardingPublicationOutbox(
            paths.profile_root, initialize=False
        )

    def preflight(
        self,
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> dict[str, object]:
        """Inspect readiness without creating a transaction or lock authority."""
        document = self._read_journal(optional=True)
        if document is not None and (
            document.get("candidate_digest") != self.pins.candidate_digest
            or document.get("candidate_manifest_path")
            != str(self.paths.candidate_manifest)
        ):
            return self._verify_task22_historical_prepared_compatibility(
                document,
                authority=authority,
                route=route,
            )
        self._assert_quiescent()
        if document is None:
            return self._source_bindings(authority=authority, route=route)
        return self._verify_document(document, authority=authority, route=route)

    def inspect(
        self,
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> SupplementalReviewSnapshot:
        """Verify one stable snapshot without mutating lock or profile metadata."""
        document = self._required_journal()
        self._verify_document(document, authority=authority, route=route)
        return self._snapshot(document)

    def prepare(self, *, authority: tuple[int, int, int], route: tuple[str, str]) -> SupplementalReviewSnapshot:
        self._assert_quiescent()
        with self._locked():
            existing = self._read_journal(optional=True)
            if existing is not None:
                self._verify_document(existing, authority=authority, route=route)
                return self._snapshot(existing)
            bindings = self._source_bindings(authority=authority, route=route)
            unsigned: dict[str, object] = {
                "schema": _SCHEMA,
                "profile": self.pins.profile,
                "customer_key": self.pins.customer_key,
                "session_id": self.pins.session_id,
                "original_transaction_id": self.pins.original_transaction_id,
                "review_epoch": self.pins.review_epoch,
                "candidate_digest": self.pins.candidate_digest,
                "candidate_manifest_path": str(self.paths.candidate_manifest),
                "candidate_manifest_digest": bindings["candidate_manifest_digest"],
                "baseline_candidate_digest": bindings["baseline_candidate_digest"],
                "baseline_digest": bindings["baseline_digest"],
                "attestation_receipt_integrity": bindings["attestation_receipt_integrity"],
                "readiness_bundle_digest": bindings["readiness_bundle_digest"],
                "original_journal_digest": bindings["original_journal_digest"],
                "registry_digest": bindings["registry_digest"],
                "callback_storage_adoption_binding": bindings[
                    "callback_storage_adoption_binding"
                ],
                "trainer_removal_binding": bindings["trainer_removal_binding"],
                "bootstrap_digest": bindings["bootstrap_digest"],
                "sealed_sources": bindings["sealed_sources"],
                "file_identities": bindings["file_identities"],
                "authority_digest": bindings["authority_digest"],
                "owner_route": list(route),
                "classifications": {
                    "25": _CLASSIFICATION,
                    "26": "historical_ready",
                    "27": "canonical_supplemental_review",
                    "28": "supplemental_terminal_confirmation",
                },
                "publication_bindings": {
                    "25": bindings["generation_25"],
                    "26": bindings["generation_26"],
                },
                "phase_events": [{"phase": SupplementalReviewPhase.PREPARED.value, "sequence": 0}],
                "review_update_id": None,
                "callback_event_integrity": None,
                "callback_envelope_digest": None,
                "approval_digest": None,
                "review_commit_digest": None,
                "terminal_publication_binding": None,
                "terminal_transition_digest": None,
                "terminal_receipt_integrity": None,
            }
            unsigned["transaction_id"] = self._transaction_id(unsigned)
            document = self._sign(unsigned)
            self._write(document)
            return self._snapshot(document)

    def reseal_prepared(
        self,
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> SupplementalReviewSnapshot:
        """Rebind one unconsumed prepared journal to its successor candidate.

        The original journal is retained by an authenticated receipt before its
        successor replaces it. No callback or generation-27/28 publication may
        exist, and every non-candidate source binding must still be identical.
        """
        self._assert_quiescent()
        with self._locked():
            predecessor = self._required_journal()
            predecessor_digest = _sha(_canonical(predecessor))
            receipt = self._read_reseal_receipt(optional=True)
            if receipt is not None:
                self._verify_reseal_receipt(receipt, authority=authority, route=route)
                if predecessor_digest == receipt["successor_journal_digest"]:
                    self._verify_document(predecessor, authority=authority, route=route)
                    return self._snapshot(predecessor)
                if predecessor_digest != receipt["predecessor_journal_digest"]:
                    raise SupplementalReviewError("supplemental reseal receipt conflicts with journal")

            successor, expected_receipt = self._reseal_documents(
                predecessor, authority=authority, route=route
            )
            if receipt is None:
                self._write_reseal_receipt(expected_receipt)
            elif receipt != expected_receipt:
                raise SupplementalReviewError("supplemental reseal receipt conflicts with journal")
            self._write(successor)
            return self._snapshot(successor)

    def load(
        self,
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> SupplementalReviewSnapshot | None:
        with self._locked():
            document = self._read_journal(optional=True)
            if document is None:
                return None
            self._verify_document(document, authority=authority, route=route)
            return self._snapshot(document)

    def commit_review(
        self,
        *,
        event: GatewayOwnerCallbackReceipt,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> SupplementalReviewSnapshot:
        with self._locked():
            document = self._required_journal()
            self._verify_document(document, authority=authority, route=route)
            phase = self._phase(document)
            if phase in {SupplementalReviewPhase.REVIEW_COMMITTED, SupplementalReviewPhase.PUBLICATION_COMMITTED}:
                if (
                    document.get("review_update_id") != event.update_id
                    or document.get("callback_event_integrity") != event.event_integrity
                ):
                    raise SupplementalReviewError("supplemental approval conflicts with immutable evidence")
                return self._snapshot(document)
            self._verify_callback(document, event, authority=authority, route=route)
            envelope = _callback_envelope(event)
            envelope_digest = _digest(envelope)
            approval = {
                "schema": _APPROVAL_SCHEMA,
                "transaction_id": document["transaction_id"],
                "baseline_digest": document["baseline_digest"],
                "readiness_bundle_digest": document["readiness_bundle_digest"],
                "review_epoch": self.pins.review_epoch,
                "update_id": event.update_id,
                "callback_event_integrity": event.event_integrity,
                "callback_envelope_digest": envelope_digest,
                "actor_user_id": event.actor_user_id,
                "authority_digest": document["authority_digest"],
                "publication_generation": self.pins.review_generation,
                "review_sequence": 1,
            }
            approval_digest = _digest(approval)
            review_commit_digest = _digest({
                "domain": "task22-supplemental-review-commit-v1",
                "transaction_id": document["transaction_id"],
                "approval_digest": approval_digest,
                "callback_envelope": envelope,
                "review_sequence": 1,
            })
            updated = dict(document)
            updated.pop("integrity", None)
            updated["phase_events"] = [
                *self._phase_events(document),
                {"phase": SupplementalReviewPhase.REVIEW_COMMITTED.value, "sequence": 1},
            ]
            updated["review_update_id"] = event.update_id
            updated["callback_event_integrity"] = event.event_integrity
            updated["callback_envelope_digest"] = envelope_digest
            updated["approval_digest"] = approval_digest
            updated["review_commit_digest"] = review_commit_digest
            signed = self._sign(updated)
            self._write(signed)
            return self._snapshot(signed)

    def terminal_publication_binding(
        self,
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> dict[str, object]:
        """Return the sole gen28 authority, only after the immutable review commit."""
        with self._locked():
            document = self._required_journal()
            self._verify_document(document, authority=authority, route=route)
            if self._phase(document) not in {
                SupplementalReviewPhase.REVIEW_COMMITTED,
                SupplementalReviewPhase.PUBLICATION_COMMITTED,
            }:
                raise SupplementalReviewError("supplemental review is not committed")
            return self._terminal_binding(document)

    def commit_publication(
        self,
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> SupplementalReviewSnapshot:
        with self._locked():
            document = self._required_journal()
            self._verify_document(document, authority=authority, route=route)
            phase = self._phase(document)
            if phase is SupplementalReviewPhase.PUBLICATION_COMMITTED:
                return self._snapshot(document)
            if phase is not SupplementalReviewPhase.REVIEW_COMMITTED:
                raise SupplementalReviewError("supplemental review is not committed")
            expected_binding = self._terminal_binding(document)
            terminal = self._publication(self.pins.confirmation_generation)
            if (
                terminal.role != "owner"
                or terminal.route != route
                or terminal.state != "COMMITTED"
                or terminal.payload.get("state") != "ready"
                or terminal.payload.get("supplemental_review_binding") != expected_binding
                or terminal.receipt_integrity is None
            ):
                raise SupplementalReviewError(
                    "supplemental terminal publication binding is unavailable or predates review"
                )
            publication_binding = _publication_binding(terminal)
            transition_digest = _digest({
                "domain": "task22-supplemental-terminal-transition-v1",
                "review_binding": expected_binding,
                "publication_binding": publication_binding,
                "terminal_sequence": 2,
            })
            updated = dict(document)
            updated.pop("integrity", None)
            updated["phase_events"] = [
                *self._phase_events(document),
                {"phase": SupplementalReviewPhase.PUBLICATION_COMMITTED.value, "sequence": 2},
            ]
            updated["terminal_publication_binding"] = publication_binding
            updated["terminal_transition_digest"] = transition_digest
            updated["terminal_receipt_integrity"] = terminal.receipt_integrity
            signed = self._sign(updated)
            self._write(signed)
            return self._snapshot(signed)

    def callback_if_captured(self) -> GatewayOwnerCallbackReceipt | None:
        return self.outbox.owner_callback(self.pins.session_id)

    def authorize_exact_task22_terminal_recovery(
        self,
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> tuple[SupplementalReviewSnapshot, GatewayOwnerCallbackReceipt]:
        """Authorize only the captured Task22 callback for offline recovery."""
        self._assert_quiescent()
        with self._locked():
            document = self._required_journal()
            self._verify_document(document, authority=authority, route=route)
            event = self.callback_if_captured()
            if event is None:
                raise SupplementalReviewError(
                    "exact Task22 callback recovery authority is unavailable"
                )
            self._verify_callback(
                document,
                event,
                authority=authority,
                route=route,
            )
            self._verify_exact_task22_historical_callback(
                document,
                event,
                authority=authority,
                route=route,
            )
            return self._snapshot(document), event

    def _reseal_documents(
        self,
        predecessor: dict[str, object],
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> tuple[dict[str, object], dict[str, object]]:
        if not self._valid_signature(predecessor):
            raise SupplementalReviewError("supplemental review journal integrity is invalid")
        if self._phase(predecessor) is not SupplementalReviewPhase.PREPARED:
            raise SupplementalReviewError("supplemental review is no longer eligible for reseal")
        if self.callback_if_captured() is not None or any(
            item.session_id == self.pins.session_id
            and item.generation in {
                self.pins.review_generation,
                self.pins.confirmation_generation,
            }
            for item in self.outbox.records()
        ):
            raise SupplementalReviewError("supplemental review publication authority is already present")
        expected = {
            "profile": self.pins.profile,
            "customer_key": self.pins.customer_key,
            "session_id": self.pins.session_id,
            "original_transaction_id": self.pins.original_transaction_id,
            "review_epoch": self.pins.review_epoch,
            "owner_route": list(route),
            "authority_digest": _authority_digest(authority, route),
        }
        if any(predecessor.get(key) != value for key, value in expected.items()):
            raise SupplementalReviewError("supplemental review authority is stale or mismatched")
        if (
            not isinstance(predecessor.get("candidate_manifest_path"), str)
            or predecessor.get("candidate_digest") == self.pins.candidate_digest
        ):
            raise SupplementalReviewError("supplemental review candidate is already sealed")
        if predecessor.get("transaction_id") != self._transaction_id(predecessor):
            raise SupplementalReviewError("supplemental review transaction binding is invalid")

        bindings = self._source_bindings_for_replay(
            predecessor, authority=authority, route=route
        )
        preserved_fields = (
            "baseline_candidate_digest",
            "baseline_digest",
            "readiness_bundle_digest",
            "original_journal_digest",
            "registry_digest",
            "callback_storage_adoption_binding",
            "trainer_removal_binding",
            "bootstrap_digest",
            "authority_digest",
        )
        if any(predecessor.get(key) != bindings.get(key) for key in preserved_fields):
            raise SupplementalReviewError("supplemental review freeze drift detected")
        old_sources = predecessor.get("sealed_sources")
        new_sources = bindings.get("sealed_sources")
        old_identities = predecessor.get("file_identities")
        new_identities = bindings.get("file_identities")
        if not all(
            isinstance(value, dict)
            for value in (old_sources, new_sources, old_identities, new_identities)
        ):
            raise SupplementalReviewError("supplemental review freeze drift detected")
        typed_old_sources = cast(dict[str, object], old_sources)
        typed_new_sources = cast(dict[str, object], new_sources)
        typed_old_identities = cast(dict[str, object], old_identities)
        typed_new_identities = cast(dict[str, object], new_identities)
        old_candidate_keys = [
            key for key in typed_old_sources if key.startswith("candidate:")
        ]
        new_candidate_keys = [
            key for key in typed_new_sources if key.startswith("candidate:")
        ]
        if (
            len(old_candidate_keys) != 1
            or len(new_candidate_keys) != 1
            or old_candidate_keys[0] not in typed_old_identities
            or new_candidate_keys[0] not in typed_new_identities
            or {
                key: value
                for key, value in typed_old_sources.items()
                if key not in old_candidate_keys
            }
            != {
                key: value
                for key, value in typed_new_sources.items()
                if key not in new_candidate_keys
            }
            or {
                key: value
                for key, value in typed_old_identities.items()
                if key not in old_candidate_keys
            }
            != {
                key: value
                for key, value in typed_new_identities.items()
                if key not in new_candidate_keys
            }
        ):
            raise SupplementalReviewError("supplemental review freeze drift detected")

        unsigned = dict(predecessor)
        unsigned.pop("integrity", None)
        unsigned.update({
            "candidate_digest": self.pins.candidate_digest,
            "candidate_manifest_path": str(self.paths.candidate_manifest),
            "candidate_manifest_digest": bindings["candidate_manifest_digest"],
            "sealed_sources": new_sources,
            "file_identities": new_identities,
        })
        unsigned["transaction_id"] = self._transaction_id(unsigned)
        successor = self._sign(unsigned)
        receipt_unsigned = {
            "schema": _RESEAL_RECEIPT_SCHEMA,
            "profile": self.pins.profile,
            "customer_key": self.pins.customer_key,
            "session_id": self.pins.session_id,
            "review_epoch": self.pins.review_epoch,
            "owner_route": list(route),
            "authority_digest": unsigned["authority_digest"],
            "predecessor_journal_digest": _sha(_canonical(predecessor)),
            "predecessor_transaction_id": predecessor["transaction_id"],
            "predecessor_candidate_digest": predecessor["candidate_digest"],
            "predecessor_manifest_path": predecessor["candidate_manifest_path"],
            "predecessor_manifest_digest": predecessor["candidate_manifest_digest"],
            "successor_journal_digest": _sha(_canonical(successor)),
            "successor_transaction_id": successor["transaction_id"],
            "successor_candidate_digest": successor["candidate_digest"],
            "successor_manifest_path": successor["candidate_manifest_path"],
            "successor_manifest_digest": successor["candidate_manifest_digest"],
            "baseline_candidate_digest": successor["baseline_candidate_digest"],
            "baseline_digest": successor["baseline_digest"],
            "readiness_bundle_digest": successor["readiness_bundle_digest"],
            "original_journal_digest": successor["original_journal_digest"],
            "registry_digest": successor["registry_digest"],
            "bootstrap_digest": successor["bootstrap_digest"],
        }
        return successor, self._sign_reseal_receipt(receipt_unsigned)

    @staticmethod
    def _transaction_id(document: Mapping[str, object]) -> str:
        return _digest({
            key: document[key]
            for key in (
                "profile", "customer_key", "session_id", "original_transaction_id",
                "review_epoch", "candidate_digest", "baseline_candidate_digest",
                "baseline_digest", "attestation_receipt_integrity",
                "readiness_bundle_digest", "callback_storage_adoption_binding",
                "trainer_removal_binding", "sealed_sources",
                "publication_bindings", "authority_digest",
            )
        })

    def _source_bindings(
        self,
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> dict[str, object]:
        self._validate_tree()
        sources, sealed_sources = self._read_sealed_sources()
        manifest_bytes = sources[self.paths.candidate_manifest]
        try:
            manifest = json.loads(manifest_bytes)
        except (TypeError, json.JSONDecodeError) as exc:
            raise SupplementalReviewError("candidate manifest is invalid") from exc
        if not isinstance(manifest, dict) or manifest.get("candidate_digest") != self.pins.candidate_digest:
            raise SupplementalReviewError("candidate manifest does not match immutable candidate")
        baseline_candidate_bytes = sources[self.paths.baseline_candidate]
        baseline_bytes = sources[self.paths.baseline]
        ready_bytes = sources[self.paths.ready]
        pointer_bytes = sources[self.paths.readiness_pointer]
        receipt_bytes = sources[self.paths.readiness_receipt]
        original_bytes = sources[self.paths.original_journal]
        registry_bytes = sources[self.paths.registry]
        bootstrap_bytes = sources[self.paths.bootstrap]
        baseline_candidate = _object(baseline_candidate_bytes, "baseline candidate")
        baseline = _object(baseline_bytes, "baseline")
        ready = _object(ready_bytes, "ready bundle")
        original = _object(original_bytes, "owner-v1 journal")
        registry = _object(registry_bytes, "customer registry")
        bootstrap = _object(bootstrap_bytes, "bootstrap ledger")
        source_answers = baseline_candidate.get("source_answers")
        if not isinstance(source_answers, dict) or len(source_answers) != 22:
            raise SupplementalReviewError("sealed onboarding answer set is incomplete")
        if original.get("phase") != "PUBLICATION_COMMITTED" or original.get("transaction_id") != self.pins.original_transaction_id:
            raise SupplementalReviewError("original owner-v1 transaction is unavailable")
        if ready.get("state") != "ready" or ready.get("owner_reviewed") is not True:
            raise SupplementalReviewError("historical ready bundle is unavailable")
        customers = registry.get("customers")
        sessions = bootstrap.get("sessions")
        customer_matches: list[dict[str, object]] = [
            cast(dict[str, object], item)
            for item in customers
            if isinstance(item, dict)
            and cast(dict[str, object], item).get("customer_key") == self.pins.customer_key
        ] if isinstance(customers, list) else []
        session_matches: list[dict[str, object]] = [
            cast(dict[str, object], item)
            for item in sessions
            if isinstance(item, dict)
            and cast(dict[str, object], item).get("session_id") == self.pins.session_id
        ] if isinstance(sessions, list) else []
        if (
            len(customer_matches) != 1
            or customer_matches[0].get("enabled") is not False
            or "trainer" in customer_matches[0]
            or len(session_matches) != 1
            or session_matches[0].get("customer_key") not in {None, self.pins.customer_key}
            or any(
                _contains_authority(path)
                for path in (
                    self.paths.profile_root / "data" / "customer-activation-journal.json",
                    self.paths.profile_root / "data" / "activation-completion-notices.jsonl",
                    self.paths.profile_root / "data" / "scheduled-deliveries.jsonl",
                    self.paths.profile_root / "data" / "owner-actions" / "draft-deliveries.json",
                )
            )
            or (self.paths.onboarding_root.parent / "nutrition-plans" / "feature-epoch.json").exists()
        ):
            raise SupplementalReviewError("downstream, trainer, or activation authority is present")
        trainer_removal_binding: dict[str, object] | None = None
        callback_storage_adoption_binding: dict[str, object] | None = None
        if self.pins.customer_key == "task22_dm_rehearsal":
            try:
                from gateway.platforms.task22_callback_storage_adoption import (
                    verify_callback_storage_adoption_receipt,
                )
                from gateway.platforms.task22_trainer_authority_removal import (
                    verify_committed_removal_receipt,
                )

                callback_storage_adoption_binding = (
                    verify_callback_storage_adoption_receipt(
                        self.paths.profile_root,
                        require_empty_pair=True,
                    )
                )
                trainer_removal_binding = verify_committed_removal_receipt(
                    self.paths.profile_root,
                    registry_path=self.paths.registry,
                )
                if trainer_removal_binding.get(
                    "callback_storage_adoption_binding"
                ) != callback_storage_adoption_binding:
                    raise SupplementalReviewError(
                        "trainer removal does not bind callback storage adoption"
                    )
            except (OSError, RuntimeError, ValueError) as exc:
                raise SupplementalReviewError(
                    "adoption and committed trainer-authority removal receipts are unavailable"
                ) from exc
        baseline_digest = baseline.get("digest")
        ready_baseline = ready.get("baseline_digest")
        if not isinstance(baseline_digest, str) or baseline_digest != ready_baseline:
            raise SupplementalReviewError("sealed baseline binding is invalid")
        historical = self.outbox.owner_callback(self.pins.session_id)
        if historical is not None:
            raise SupplementalReviewError("historical callback provenance classification conflicts")
        review = self._publication(self.pins.historical_review_generation)
        ready_publication = self._publication(self.pins.historical_ready_generation)
        if (
            review.role != "owner" or review.state != "COMMITTED"
            or review.payload.get("state") != "owner_review"
            or ready_publication.role != "owner" or ready_publication.state != "COMMITTED"
            or ready_publication.payload.get("state") != "ready"
            or review.route != route or ready_publication.route != route
            or review.receipt_integrity is None or ready_publication.receipt_integrity is None
        ):
            raise SupplementalReviewError("historical publication provenance is incomplete")
        attestation = tuple(
            item for item in self.outbox.records()
            if item.session_id == self.pins.session_id
            and item.role == "customer"
            and item.payload.get("state") == "customer_attestation"
            and item.state == "COMMITTED"
            and item.generation == 23
        )
        if len(attestation) != 1 or attestation[0].receipt_integrity is None:
            raise SupplementalReviewError("attestation publication provenance is unavailable")
        return {
            "candidate_manifest_digest": _sha(manifest_bytes),
            "baseline_candidate_digest": _sha(baseline_candidate_bytes),
            "baseline_digest": baseline_digest,
            "attestation_receipt_integrity": attestation[0].receipt_integrity,
            "readiness_bundle_digest": _digest({
                "ready": _sha(ready_bytes),
                "pointer": _sha(pointer_bytes),
                "receipt": _sha(receipt_bytes),
            }),
            "original_journal_digest": _sha(original_bytes),
            "registry_digest": _sha(registry_bytes),
            "callback_storage_adoption_binding": callback_storage_adoption_binding,
            "trainer_removal_binding": trainer_removal_binding,
            "bootstrap_digest": _sha(bootstrap_bytes),
            "sealed_sources": sealed_sources,
            "authority_digest": _authority_digest(authority, route),
            "generation_25": _publication_binding(review),
            "generation_26": _publication_binding(ready_publication),
            "file_identities": {
                key: binding["file_identity"]
                for key, binding in sealed_sources.items()
            },
        }

    def _verify_document(
        self,
        document: dict[str, object],
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> dict[str, object]:
        if document.get("schema") != _SCHEMA or not self._valid_signature(document):
            raise SupplementalReviewError("supplemental review journal integrity is invalid")
        expected = {
            "profile": self.pins.profile,
            "customer_key": self.pins.customer_key,
            "session_id": self.pins.session_id,
            "original_transaction_id": self.pins.original_transaction_id,
            "review_epoch": self.pins.review_epoch,
            "candidate_digest": self.pins.candidate_digest,
            "candidate_manifest_path": str(self.paths.candidate_manifest),
            "owner_route": list(route),
            "authority_digest": _authority_digest(authority, route),
        }
        if any(document.get(key) != value for key, value in expected.items()):
            raise SupplementalReviewError("supplemental review authority is stale or mismatched")
        classifications = document.get("classifications")
        if classifications != {
            "25": _CLASSIFICATION,
            "26": "historical_ready",
            "27": "canonical_supplemental_review",
            "28": "supplemental_terminal_confirmation",
        }:
            raise SupplementalReviewError("supplemental provenance classification is invalid")
        current = self._source_bindings_for_replay(document, authority=authority, route=route)
        for key, value in current.items():
            if document.get(key) != value:
                raise SupplementalReviewError("supplemental review freeze drift detected")
        phase = self._phase(document)
        self._verify_review_and_terminal_bindings(
            document,
            phase=phase,
            authority=authority,
            route=route,
        )
        return current

    def _verify_task22_historical_prepared_compatibility(
        self,
        document: dict[str, object],
        *,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> dict[str, object]:
        """Authenticate the sole historical PREPARED journal without repairing it.

        The current Task22 source successor is intentionally different from the
        historical journal candidate. This is not a reseal or stale-candidate
        escape hatch: every historical source and receipt remains exact, while
        the successor chain and the already committed generation-27 card are
        pinned independently.
        """
        if (
            self.pins.profile != _TASK22_PROFILE
            or self.pins.customer_key != _TASK22_CUSTOMER
            or self.pins.session_id != _TASK22_SESSION
            or self.pins.candidate_digest != _TASK22_SUCCESSOR_CANDIDATE
            or self.pins.original_transaction_id
            != document.get("original_transaction_id")
        ):
            raise SupplementalReviewError(
                "historical Task22 compatibility authority is not authorized"
            )
        successor_bytes = _read_private(
            self.paths.candidate_manifest,
            "Task22 supplemental successor manifest",
        )
        successor = _object(successor_bytes, "Task22 supplemental successor manifest")
        if (
            _sha(successor_bytes) != _TASK22_SUCCESSOR_MANIFEST_SHA256
            or any(
                successor.get(key) != value
                for key, value in _TASK22_SUCCESSOR_BINDING.items()
            )
        ):
            raise SupplementalReviewError(
                "Task22 supplemental successor binding is invalid"
            )
        evidence_root = self.paths.candidate_manifest.parent
        historical_manifest = evidence_root / _TASK22_HISTORICAL_MANIFEST_NAME
        if document.get("candidate_manifest_path") != str(historical_manifest):
            raise SupplementalReviewError(
                "historical Task22 journal manifest path is not authorized"
            )
        historical_bytes = _read_private(
            historical_manifest,
            "historical Task22 candidate manifest",
        )
        historical = _object(historical_bytes, "historical Task22 candidate manifest")
        freeze_bytes = _read_private(
            evidence_root / _TASK22_FREEZE_NAME,
            "historical Task22 freeze receipt",
        )
        freeze = _object(freeze_bytes, "historical Task22 freeze receipt")
        pre_bytes = _read_private(
            evidence_root / _TASK22_PRE_SUPPLEMENTAL_NAME,
            "historical Task22 pre-supplemental evidence",
        )
        pre = _object(pre_bytes, "historical Task22 pre-supplemental evidence")
        predecessor_bytes = _read_task22_pinned_evidence(
            evidence_root / _TASK22_PREDECESSOR_MANIFEST_NAME,
            "Task22 successor predecessor manifest",
            expected_sha256=_TASK22_PREDECESSOR_MANIFEST_SHA256,
        )
        predecessor = _object(
            predecessor_bytes,
            "Task22 successor predecessor manifest",
        )
        if (
            _sha(historical_bytes) != _TASK22_HISTORICAL_MANIFEST_SHA256
            or historical.get("candidate_digest") != _TASK22_HISTORICAL_CANDIDATE
            or historical.get("candidate_diff_sha256")
            != _TASK22_HISTORICAL_CANDIDATE_DIFF_SHA256
            or _sha(freeze_bytes) != _TASK22_FREEZE_SHA256
            or freeze.get("release_candidate_digest") != _TASK22_HISTORICAL_CANDIDATE
            or freeze.get("manifest_digest") != _TASK22_HISTORICAL_MANIFEST_SHA256
            or freeze.get("receipt_digest") != _TASK22_FREEZE_DIGEST
            or _sha(pre_bytes) != _TASK22_PRE_SUPPLEMENTAL_SHA256
            or pre.get("release_candidate_digest") != _TASK22_HISTORICAL_CANDIDATE
            or pre.get("manifest_digest") != _TASK22_HISTORICAL_MANIFEST_SHA256
            or pre.get("freeze_receipt_digest") != _TASK22_FREEZE_DIGEST
            or pre.get("evidence_digest") != _TASK22_PRE_SUPPLEMENTAL_DIGEST
            or _sha(predecessor_bytes) != _TASK22_PREDECESSOR_MANIFEST_SHA256
            or predecessor.get("candidate_digest") != _TASK22_PREDECESSOR_CANDIDATE
        ):
            raise SupplementalReviewError(
                "historical Task22 source or successor chain drifted"
            )
        historical_store = SupplementalReviewStore(
            SupplementalReviewPaths.canonical(
                self.paths.profile_root,
                candidate_manifest=historical_manifest,
                customer_key=_TASK22_CUSTOMER,
            ),
            SupplementalReviewPins(
                profile=_TASK22_PROFILE,
                customer_key=_TASK22_CUSTOMER,
                session_id=_TASK22_SESSION,
                original_transaction_id=cast(str, document["original_transaction_id"]),
                candidate_digest=_TASK22_HISTORICAL_CANDIDATE,
            ),
            outbox=self.outbox,
        )
        bindings = historical_store._verify_document(
            document,
            authority=authority,
            route=route,
        )
        if historical_store._phase(document) is not SupplementalReviewPhase.PREPARED:
            raise SupplementalReviewError(
                "historical Task22 journal is not the accepted PREPARED journal"
            )
        try:
            os.lstat(historical_store.paths.journal.parent / _RESEAL_RECEIPT_NAME)
        except FileNotFoundError:
            pass
        else:
            raise SupplementalReviewError("historical Task22 reseal authority is present")
        captured = historical_store.callback_if_captured()
        if captured is not None:
            historical_store._verify_callback(
                document,
                captured,
                authority=authority,
                route=route,
            )
        records = tuple(
            item
            for item in self.outbox.records()
            if item.session_id == _TASK22_SESSION
        )
        generations = tuple(sorted(item.generation for item in records))
        expected_generations = (23, 25, 26, 27)
        if 0 in generations:
            expected_generations = (*range(22), 23, 24, 25, 26, 27)
        generation_27 = tuple(item for item in records if item.generation == 27)
        if (
            generations != expected_generations
            or len(generation_27) != 1
            or generation_27[0].role != "owner"
            or generation_27[0].state != "COMMITTED"
            or generation_27[0].payload.get("state") != "owner_review"
            or generation_27[0].route != route
            or generation_27[0].message_id != 122
            or generation_27[0].render_identity != _TASK22_GENERATION_27_RENDER
            or generation_27[0].dispatch_identity != _TASK22_GENERATION_27_DISPATCH
            or generation_27[0].receipt_integrity is None
        ):
            raise SupplementalReviewError(
                "historical Task22 generation-27 publication is not authorized"
            )
        return {
            **bindings,
            "compatibility": _TASK22_COMPATIBILITY,
            "journal_candidate_digest": _TASK22_HISTORICAL_CANDIDATE,
            "successor_candidate_digest": _TASK22_SUCCESSOR_CANDIDATE,
            "publication_generation": 27,
            "message_id": 122,
        }

    def _verify_review_and_terminal_bindings(
        self,
        document: Mapping[str, object],
        *,
        phase: SupplementalReviewPhase,
        authority: tuple[int, int, int],
        route: tuple[str, str],
    ) -> None:
        review_fields = (
            "review_update_id",

[Showing lines 1-1147 of 2347 (50.0KB limit). Use offset=1148 to continue.]