"""Bounded offline adoption of the exact Task22 initialized callback storage.

The operation publishes one authenticated receipt.  It never writes, replaces,
unlinks, or renames either callback authority file.
"""

from __future__ import annotations

import base64
import contextvars
import fcntl
import hashlib
import hmac
import json
import os
import stat
import subprocess
import time
from collections.abc import Callable, Generator, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Final, Literal, TypeGuard, TypedDict

from gateway.platforms.telegram_nutrition_onboarding_publication_outbox import (
    GatewayOnboardingPublicationOutbox,
    GatewayPublicationReceipt,
)

PROFILE: Final = "dualcoachtest"
_TARGET_UNIT: Final = "hermes-gateway-dualcoachtest.service"
_USER_SYSTEMD_CMDLINE: Final = b"/usr/lib/systemd/systemd\0--user\0"
_SSH_AGENT_EXECUTABLE: Final = Path("/usr/bin/ssh-agent")
_PTRACE_SCOPE: Final = Path("/proc/sys/kernel/yama/ptrace_scope")
_BOOT_ID: Final = Path("/proc/sys/kernel/random/boot_id")
CUSTOMER: Final = "task22_dm_rehearsal"
SESSION: Final = "rb_Ar-NuKG3LH8CqHPXUgc88g"
CANDIDATE_DIGEST: Final = "a6dc172050add2d352ebfb7efc7615c837ef2365656b8ca6f361255cb3b0157a"
MANIFEST_DIGEST: Final = "c5f198be3e04a5df8d49d827a22b43eaf6fcc3791334d983edc5ad1abf30a72a"
FREEZE_DIGEST: Final = "a85689de997916ff05b63531f137bc30c1c5ef72ef61b8587452d5d39e420bcc"
HISTORICAL_ABSENT_DIGEST: Final = "359adbba7bca9cfebfdeb049bc8a06c970e415d3250178910e187b745ca5987d"
PRESENT_EVIDENCE_DIGEST: Final = "f70b060035b5c798d07104ac8d1aa236ab44e8f65156da18d1d75e61f64e29ad"
REGISTRY_DIGEST: Final = "b5b95afa818b0c7460141403e0bfe434fb987a31fe5285f6e6e98b70cb738aa1"
OWNER_JOURNAL_DIGEST: Final = "e774b2b01edb90391389ea304b7d10f06f908302cf28aac39a57e3c52b289474"
OUTBOX_DIGEST: Final = "d1d12dc1d7fbda1ab706a2547701b6d6355d205468c39df705711d84a856822e"
SERVICE_STATE_DIGEST: Final = "81c1e581cb84aac6f44044747e0e8e77a2d7498c71d626f1f9b5ec2f9d09a261"
_CALLBACK_BYTES: Final = b'{"records":[],"schema":"telegram-nutrition-onboarding-owner-callback-v1"}\n'
_EMPTY_HASH: Final = hashlib.sha256(b"").hexdigest()
_SCHEMA: Final = "task22-callback-storage-adoption-v1"
_CLASSIFICATION: Final = "initialized_empty_canonical_callback_storage"
_RECEIPT_NAME: Final = "task22-callback-storage-adoption-v1.json"
_STAGE_NAME: Final = f".{_RECEIPT_NAME}.staged"
_TERMINAL_NAME: Final = f".{_RECEIPT_NAME}.terminal"
_TERMINAL_STAGE_NAME: Final = f"{_TERMINAL_NAME}.staged"
_TERMINAL_SCHEMA: Final = "task22-callback-storage-adoption-terminal-v1"
_PRIVATE_FILE: Final = 0o600
_AUTHORITY_COMMAND_TIMEOUT_SECONDS: Final = 5.0
_PROCESS_INVENTORY_COMMAND_BUDGET_SECONDS: Final = 10.0
_PROCESS_INVENTORY_COMMAND_DEADLINE: contextvars.ContextVar[float | None] = (
    contextvars.ContextVar("task22_process_inventory_command_deadline", default=None)
)
_TRANSACTION_ID: Final = hashlib.sha256(
    f"{_SCHEMA}\0{PROFILE}\0{CUSTOMER}\0{SESSION}\0{HISTORICAL_ABSENT_DIGEST}\0{PRESENT_EVIDENCE_DIGEST}".encode()
).hexdigest()

class CallbackStorageAdoptionError(RuntimeError):
    """The exact initialized-empty storage cannot be safely adopted."""

class _ArtifactPayload(TypedDict):
    name: str
    relative_path: str
    device: int
    inode: int
    uid: int
    gid: int
    mode: int
    links: int
    size: int
    sha256: str
    bytes_b64: str

class _TargetFence(TypedDict):
    load_state: str
    active_state: str
    sub_state: str
    main_pid: int
    unit_file_state: str
    control_group: str
    n_file_descriptor_store: int

class _ServiceFence(_TargetFence):
    fenced: bool

class _ProfileIdentity(TypedDict):
    device: int
    inode: int

class _PackageFileIdentity(TypedDict):
    path: str
    device: int
    inode: int
    uid: int
    gid: int
    mode: int
    sha256: str
    package: str
    version: str

class _SshAgentUnitProof(TypedDict):
    LoadState: str
    ActiveState: str
    SubState: str
    MainPID: str
    ControlGroup: str
    FragmentPath: str
    DropInPaths: str
    ExecStart: str
    WorkingDirectory: str
    fragment: _PackageFileIdentity
    binary: _PackageFileIdentity
    home_cwd: str

class _PtraceScope(TypedDict):
    configured: int
    current: int

@dataclass(frozen=True, slots=True)
class ArtifactPin:
    name: str
    device: int
    inode: int
    uid: int
    gid: int
    mode: int
    links: int
    size: int
    sha256: str
    content: bytes

ARTIFACT_PINS: Final = (
    ArtifactPin("owner-callbacks.json", 66306, 33166555, 1000, 1000, 0o600, 1, 74, hashlib.sha256(_CALLBACK_BYTES).hexdigest(), _CALLBACK_BYTES),
    ArtifactPin(".owner-callbacks.lock", 66306, 33166551, 1000, 1000, 0o600, 1, 0, _EMPTY_HASH, b""),
)

@dataclass(frozen=True, slots=True)
class AdoptionPaths:
    profile_root: Path
    candidate_manifest: Path
    freeze_receipt: Path
    historical_absent_evidence: Path
    present_evidence: Path
    registry: Path
    owner_journal: Path
    service_state: Path
    outbox_root: Path
    receipt: Path

    @classmethod
    def canonical(
        cls,
        profile_root: Path | str,
        *,
        candidate_manifest: Path | str,
        freeze_receipt: Path | str,
        historical_absent_evidence: Path | str,
        present_evidence: Path | str,
    ) -> "AdoptionPaths":
        root = Path(profile_root).absolute()
        migrations = root / "data" / "customers" / CUSTOMER / "nutrition-onboarding" / "migrations"
        outbox = root / "data" / "onboarding" / "telegram-publication-outbox-v1"
        return cls(
            root,
            Path(candidate_manifest).absolute(),
            Path(freeze_receipt).absolute(),
            Path(historical_absent_evidence).absolute(),
            Path(present_evidence).absolute(),
            root / "customers" / "registry.json",
            migrations / "owner-v1.json",
            root / "data" / "owner-actions" / "customer-service-state.json",
            outbox,
            migrations / _RECEIPT_NAME,
        )

    @property
    def authority_locks(self) -> tuple[Path, ...]:
        data = self.profile_root / "data"
        return (
            self.profile_root / "gateway.lock",
            data / ".adaptive-authority.lock",
            data / ".nutrition-onboarding-projection.lock",
            data / ".scheduled-deliveries.lock",
            data / "activation-completion-notices.lock",
            data / "onboarding" / "telegram-room-bootstrap-v1" / "ledger.lock",
            data / "onboarding" / "telegram-room-bootstrap-v1" / "role-invites.lock",
            self.outbox_root / ".lock",
            self.outbox_root / ".emergency.lock",
            self.outbox_root / ".owner-callbacks.lock",
            data / "owner-actions" / "customer-service-state.json.lock",
            data / "owner-actions" / "draft-deliveries.json.lock",
            self.owner_journal.parent.parent / ".lock",
        )

@dataclass(frozen=True, slots=True)
class AdoptionSnapshot:
    transaction_id: str
    adopted: bool
    classification: str
    callback_record_count: int
    grants: tuple[str, ...]
    ready: bool

@dataclass(slots=True)
class _RetainedAdoptionAuthority:
    directory_bindings: tuple[tuple[int, str, int], ...]
    private_directory_fds: tuple[int, ...]
    migrations_fd: int
    owner_fd: int
    stage_fd: int | None
    receipt_fd: int | None
    terminal_stage_fd: int | None
    terminal_fd: int | None

    def assert_bound(self) -> None:
        for parent_fd, name, descriptor in self.directory_bindings:
            path_info = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)
            descriptor_info = os.fstat(descriptor)
            if (
                path_info.st_dev,
                path_info.st_ino,
            ) != (descriptor_info.st_dev, descriptor_info.st_ino):
                raise CallbackStorageAdoptionError("adoption directory path drifted")
        self.assert_file_bound("owner-v1.json", self.owner_fd, "owner-v1 journal")
        if self.stage_fd is not None:
            self.assert_file_bound(_STAGE_NAME, self.stage_fd, "adoption receipt staging")
        if self.receipt_fd is not None:
            self.assert_file_bound(
                _RECEIPT_NAME, self.receipt_fd, "adoption receipt"
            )
        if self.terminal_stage_fd is not None:
            self.assert_file_bound(
                _TERMINAL_STAGE_NAME,
                self.terminal_stage_fd,
                "adoption terminal binding staging",
            )
        if self.terminal_fd is not None:
            self.assert_file_bound(
                _TERMINAL_NAME, self.terminal_fd, "adoption terminal binding"
            )

    def assert_file_bound(self, name: str, descriptor: int, label: str) -> None:
        try:
            path_info = os.stat(
                name, dir_fd=self.migrations_fd, follow_symlinks=False
            )
        except FileNotFoundError as exc:
            raise CallbackStorageAdoptionError(f"{label} pathname was replaced") from exc
        descriptor_info = os.fstat(descriptor)
        if (path_info.st_dev, path_info.st_ino) != (
            descriptor_info.st_dev,
            descriptor_info.st_ino,
        ):
            raise CallbackStorageAdoptionError(f"{label} pathname was replaced")

ServiceFenceCheck = Callable[[Path], Mapping[str, object]]
FaultHook = Callable[[str], None]

def _no_fault(_boundary: str) -> None:
    return None

class _LockHeldAdoptionOutbox(GatewayOnboardingPublicationOutbox):
    """Expose the authenticated primary reader to its existing lock owner."""

    def records_with_primary_lock_held(self) -> tuple[GatewayPublicationReceipt, ...]:
        return self._read_primary_unlocked()

class Task22CallbackStorageAdoption:
    def __init__(
        self,
        paths: AdoptionPaths,
        *,
        service_fence_check: ServiceFenceCheck | None = None,
        fault_hook: FaultHook = _no_fault,
    ) -> None:
        self.paths: AdoptionPaths = paths
        self._service_fence_check: ServiceFenceCheck = (
            service_fence_check or _default_service_fence
        )
        self._fault: FaultHook = fault_hook
        self._fence: _ServiceFence | None = None
        self._inventory: _ProtectedSessionInventory | None = None
        self._inventory_digest: str = ""

    def preflight(self) -> AdoptionSnapshot:
        with _retain_adoption_authority(self.paths) as authority:
            self._validate_roots(authority)
            authority.assert_bound()
            self._assert_quiescent()
            inventory_a = self._inventory_digest
            with self._ordered_locks():
                authority.assert_bound()
                # Read-only preflight proves the same stable, lock-bounded
                # infrastructure inventory required by execute.
                self._assert_quiescent(ignore_locks=True)
                if self._inventory_digest != inventory_a:
                    raise CallbackStorageAdoptionError(
                        "protected process inventory changed between scans"
                    )
                self._verify_pair()
                self._assert_state_pins(authority)
                receipt = self._read_receipt(authority, optional=True)
                stage = self._read_stage(authority, optional=True)
                terminal = self._read_terminal(authority, optional=True)
                terminal_stage = self._read_terminal_stage(authority, optional=True)
                self._assert_publication_phase(
                    authority, stage, receipt, terminal_stage, terminal
                )
                if stage is not None:
                    self._verify_receipt(stage)
                if receipt is not None:
                    self._verify_receipt(receipt)
                if terminal_stage is not None:
                    if receipt is None:
                        raise CallbackStorageAdoptionError(
                            "adoption terminal binding has no receipt"
                        )
                    self._verify_terminal(receipt, terminal_stage)
                if terminal is not None:
                    assert receipt is not None
                    self._verify_terminal(receipt, terminal)
                authority.assert_bound()
                return AdoptionSnapshot(
                    _TRANSACTION_ID,
                    terminal is not None,
                    _CLASSIFICATION,
                    0,
                    (),
                    True,
                )

    def execute(self) -> AdoptionSnapshot:
        with _retain_adoption_authority(self.paths) as authority:
            self._validate_roots(authority)
            authority.assert_bound()
            self._assert_quiescent()
            inventory_a = self._inventory_digest
            with self._ordered_locks():
                authority.assert_bound()
                self._verify_pair()
                self._assert_state_pins(authority)
                # Scan B is under every authority lock and is the final
                # observation before receipt construction/publication.
                self._assert_quiescent(ignore_locks=True)
                if self._inventory_digest != inventory_a:
                    raise CallbackStorageAdoptionError(
                        "protected process inventory changed between scans"
                    )
                expected = self._receipt_payload()
                receipt = self._read_receipt(authority, optional=True)
                stage = self._read_stage(authority, optional=True)
                terminal = self._read_terminal(authority, optional=True)
                terminal_stage = self._read_terminal_stage(authority, optional=True)
                self._assert_publication_phase(
                    authority, stage, receipt, terminal_stage, terminal
                )
                if receipt is not None:
                    self._verify_receipt(receipt)
                    if receipt != expected:
                        raise CallbackStorageAdoptionError(
                            "immutable adoption receipt conflicts"
                        )
                else:
                    if stage is None:
                        self._write_stage(authority, expected)
                        stage = expected
                        self._fault("after_stage_fsync")
                    elif stage != expected:
                        raise CallbackStorageAdoptionError(
                            "adoption receipt staging is tampered"
                        )
                    self._verify_pair()
                    self._fault("before_receipt_link")
                    authority.assert_bound()
                    try:
                        os.link(
                            _STAGE_NAME,
                            _RECEIPT_NAME,
                            src_dir_fd=authority.migrations_fd,
                            dst_dir_fd=authority.migrations_fd,
                            follow_symlinks=False,
                        )
                    except FileExistsError as exc:
                        raise CallbackStorageAdoptionError(
                            "adoption receipt appeared during publication"
                        ) from exc
                    authority.receipt_fd = _open_private_entry(
                        authority.migrations_fd,
                        _RECEIPT_NAME,
                        "adoption receipt",
                        links=(2,),
                    )
                    assert authority.stage_fd is not None
                    if _identity(authority.receipt_fd) != _identity(
                        authority.stage_fd
                    ):
                        raise CallbackStorageAdoptionError(
                            "adoption receipt publication identity changed"
                        )
                    receipt = expected
                    self._fault("after_receipt_link")
                    os.fsync(authority.migrations_fd)
                    self._fault("after_receipt_parent_fsync")

                authority.assert_bound()
                self._verify_pair()
                self._assert_state_pins(authority)
                final = self._read_receipt(authority, optional=False)
                assert final is not None
                self._verify_receipt(final)
                expected_terminal = self._terminal_payload(final)
                if terminal is not None:
                    self._verify_terminal(final, terminal)
                    if terminal != expected_terminal:
                        raise CallbackStorageAdoptionError(
                            "immutable adoption terminal binding conflicts"
                        )
                else:
                    if terminal_stage is None:
                        self._write_terminal_stage(authority, expected_terminal)
                        terminal_stage = expected_terminal
                        self._fault("after_terminal_stage_fsync")
                    elif terminal_stage != expected_terminal:
                        raise CallbackStorageAdoptionError(
                            "adoption terminal binding staging is tampered"
                        )
                    authority.assert_bound()
                    try:
                        os.link(
                            _TERMINAL_STAGE_NAME,
                            _TERMINAL_NAME,
                            src_dir_fd=authority.migrations_fd,
                            dst_dir_fd=authority.migrations_fd,
                            follow_symlinks=False,
                        )
                    except FileExistsError as exc:
                        raise CallbackStorageAdoptionError(
                            "adoption terminal binding appeared during publication"
                        ) from exc
                    authority.terminal_fd = _open_private_entry(
                        authority.migrations_fd,
                        _TERMINAL_NAME,
                        "adoption terminal binding",
                        links=(2,),
                    )
                    assert authority.terminal_stage_fd is not None
                    if _identity(authority.terminal_fd) != _identity(
                        authority.terminal_stage_fd
                    ):
                        raise CallbackStorageAdoptionError(
                            "adoption terminal publication identity changed"
                        )
                    self._fault("after_terminal_link")
                    os.fsync(authority.migrations_fd)
                    self._fault("after_terminal_parent_fsync")
                self._clear_stage(authority, expected)
                self._fault("after_receipt_stage_clear")
                self._clear_terminal_stage(authority, expected_terminal)
                authority.assert_bound()
                committed = self._read_terminal(authority, optional=False)
                assert committed is not None
                self._verify_terminal(final, committed)
                os.fsync(authority.migrations_fd)
            return AdoptionSnapshot(
                _TRANSACTION_ID, True, _CLASSIFICATION, 0, (), True
            )

    def _write_stage(
        self,
        authority: _RetainedAdoptionAuthority,
        receipt: Mapping[str, object],
    ) -> None:
        try:
            descriptor = os.open(
                _STAGE_NAME,
                os.O_RDWR
                | os.O_CREAT
                | os.O_EXCL
                | os.O_CLOEXEC
                | getattr(os, "O_NOFOLLOW", 0),
                _PRIVATE_FILE,
                dir_fd=authority.migrations_fd,
            )
        except FileExistsError as exc:
            raise CallbackStorageAdoptionError(
                "adoption receipt staging appeared"
            ) from exc
        authority.stage_fd = descriptor
        os.fchmod(descriptor, _PRIVATE_FILE)
        _write_all(descriptor, _canonical(receipt))
        os.fsync(descriptor)
        authority.assert_file_bound(
            _STAGE_NAME, descriptor, "adoption receipt staging"
        )

    def _clear_stage(
        self,
        authority: _RetainedAdoptionAuthority,
        expected: Mapping[str, object],
    ) -> None:
        stage = self._read_stage(authority, optional=True)
        if stage is None:
            return
        if stage != expected:
            raise CallbackStorageAdoptionError(
                "adoption receipt staging is tampered"
            )
        assert authority.stage_fd is not None
        authority.assert_file_bound(
            _STAGE_NAME, authority.stage_fd, "adoption receipt staging"
        )
        os.unlink(_STAGE_NAME, dir_fd=authority.migrations_fd)
        os.fsync(authority.migrations_fd)
        os.close(authority.stage_fd)
        authority.stage_fd = None

    def _write_terminal_stage(
        self,
        authority: _RetainedAdoptionAuthority,
        terminal: Mapping[str, object],
    ) -> None:
        try:
            descriptor = os.open(
                _TERMINAL_STAGE_NAME,
                os.O_RDWR
                | os.O_CREAT
                | os.O_EXCL
                | os.O_CLOEXEC
                | getattr(os, "O_NOFOLLOW", 0),
                _PRIVATE_FILE,
                dir_fd=authority.migrations_fd,
            )
        except FileExistsError as exc:
            raise CallbackStorageAdoptionError(
                "adoption terminal binding staging appeared"
            ) from exc
        authority.terminal_stage_fd = descriptor
        os.fchmod(descriptor, _PRIVATE_FILE)
        _write_all(descriptor, _canonical(terminal))
        os.fsync(descriptor)
        authority.assert_file_bound(
            _TERMINAL_STAGE_NAME,
            descriptor,
            "adoption terminal binding staging",
        )

    def _clear_terminal_stage(
        self,
        authority: _RetainedAdoptionAuthority,
        expected: Mapping[str, object],
    ) -> None:
        terminal_stage = self._read_terminal_stage(authority, optional=True)
        if terminal_stage is None:
            return
        if terminal_stage != expected:
            raise CallbackStorageAdoptionError(
                "adoption terminal binding staging is tampered"
            )
        assert authority.terminal_stage_fd is not None
        authority.assert_file_bound(
            _TERMINAL_STAGE_NAME,
            authority.terminal_stage_fd,
            "adoption terminal binding staging",
        )
        os.unlink(_TERMINAL_STAGE_NAME, dir_fd=authority.migrations_fd)
        os.fsync(authority.migrations_fd)
        os.close(authority.terminal_stage_fd)
        authority.terminal_stage_fd = None

    def _read_stage(
        self,
        authority: _RetainedAdoptionAuthority,
        *,
        optional: bool,
    ) -> dict[str, object] | None:
        if authority.stage_fd is None:
            if optional:
                return None
            raise FileNotFoundError(_STAGE_NAME)
        return _read_json_descriptor(
            authority.stage_fd,
            "adoption receipt staging",
            links=(1, 2),
        )

    def _read_receipt(
        self,
        authority: _RetainedAdoptionAuthority,
        *,
        optional: bool,
    ) -> dict[str, object] | None:
        if authority.receipt_fd is None:
            if optional:
                return None
            raise FileNotFoundError(_RECEIPT_NAME)
        return _read_json_descriptor(
            authority.receipt_fd, "adoption receipt", links=(1, 2)
        )

    def _read_terminal_stage(
        self,
        authority: _RetainedAdoptionAuthority,
        *,
        optional: bool,
    ) -> dict[str, object] | None:
        if authority.terminal_stage_fd is None:
            if optional:
                return None
            raise FileNotFoundError(_TERMINAL_STAGE_NAME)
        return _read_json_descriptor(
            authority.terminal_stage_fd,
            "adoption terminal binding staging",
            links=(1, 2),
        )

    def _read_terminal(
        self,
        authority: _RetainedAdoptionAuthority,
        *,
        optional: bool,
    ) -> dict[str, object] | None:
        if authority.terminal_fd is None:
            if optional:
                return None
            raise FileNotFoundError(_TERMINAL_NAME)
        return _read_json_descriptor(
            authority.terminal_fd, "adoption terminal binding", links=(1, 2)
        )

    def _assert_publication_phase(
        self,
        authority: _RetainedAdoptionAuthority,
        stage: Mapping[str, object] | None,
        receipt: Mapping[str, object] | None,
        terminal_stage: Mapping[str, object] | None,
        terminal: Mapping[str, object] | None,
    ) -> None:
        if receipt is None and (terminal_stage is not None or terminal is not None):
            raise CallbackStorageAdoptionError(
                "adoption terminal binding has no receipt"
            )
        if receipt is not None and stage is None and terminal is None:
            raise CallbackStorageAdoptionError(
                "linked adoption receipt has no terminal provenance"
            )
        if stage is not None and receipt is not None:
            assert authority.stage_fd is not None and authority.receipt_fd is not None
            if _identity(authority.stage_fd) != _identity(authority.receipt_fd):
                raise CallbackStorageAdoptionError(
                    "adoption receipt staging conflicts"
                )
        if terminal_stage is not None and terminal is not None:
            assert (
                authority.terminal_stage_fd is not None
                and authority.terminal_fd is not None
            )
            if _identity(authority.terminal_stage_fd) != _identity(
                authority.terminal_fd
            ):
                raise CallbackStorageAdoptionError(
                    "adoption terminal binding staging conflicts"
                )

    def _receipt_payload(self) -> dict[str, object]:
        if self._fence is None or self._inventory is None:
            raise CallbackStorageAdoptionError("quiescence proof is unavailable")
        unsigned: dict[str, object] = {
            "schema": _SCHEMA,
            "transaction_id": _TRANSACTION_ID,
            "profile": PROFILE,
            "customer_key": CUSTOMER,
            "session_id": SESSION,
            "release_candidate_digest": CANDIDATE_DIGEST,
            "manifest_digest": MANIFEST_DIGEST,
            "freeze_receipt_digest": FREEZE_DIGEST,
            "historical_absent_evidence_digest": HISTORICAL_ABSENT_DIGEST,
            "current_present_evidence_digest": PRESENT_EVIDENCE_DIGEST,
            "observed_evidence_window": {"absent_captured_at": "2026-08-11T05:51:30+09:00", "present_captured_at": "2026-08-11T11:36:37+09:00", "creator_claim": None},
            "classification": _CLASSIFICATION,
            "callback_record_count": 0,
            "business_transition_count": 0,
            "grants": [],
            "callback_schema": "telegram-nutrition-onboarding-owner-callback-v1",
            "callback_records": [],
            "artifacts": [_pin_payload(pin) for pin in ARTIFACT_PINS],
            "registry_digest": REGISTRY_DIGEST,
            "owner_journal_digest": OWNER_JOURNAL_DIGEST,
            "publication_ledger_digest": OUTBOX_DIGEST,
            "service_state_digest": SERVICE_STATE_DIGEST,
            "authenticated_generations": [23, 25, 26],
            "generation_27_or_later_absent": True,
            "customer_disabled": True,
            "trainer_present_at_adoption": True,
            "activation_count": 0,
            "draft_count": 0,
            "delivery_count": 0,
            "service_manager_fence_proof": self._fence,
            "protected_process_inventory": self._inventory,
            "protected_process_inventory_digest": self._inventory_digest,
            "quiescence_fence_digest": _digest(
                {
                    "service_manager_fence_proof": self._fence,
                    "protected_process_inventory_digest": self._inventory_digest,
                }
            ),
        }
        digest = _digest(unsigned)
        signed = {**unsigned, "receipt_digest": digest}
        return {**signed, "integrity": hmac.new(self._key(), _canonical(signed), hashlib.sha256).hexdigest()}

    def _terminal_payload(
        self, receipt: Mapping[str, object]
    ) -> dict[str, object]:
        return _terminal_payload(receipt, self._key())

    def _verify_terminal(
        self,
        receipt: Mapping[str, object],
        terminal: Mapping[str, object],
    ) -> None:
        _verify_terminal_binding(receipt, terminal, self._key())

    def _verify_receipt(self, receipt: Mapping[str, object]) -> None:
        expected = self._receipt_payload()
        if receipt != expected:
            integrity = receipt.get("integrity")
            signed = dict(receipt)
            _ = signed.pop("integrity", None)
            unsigned = dict(signed)
            digest = unsigned.pop("receipt_digest", None)
            if not isinstance(integrity, str) or not isinstance(digest, str) or not hmac.compare_digest(digest, _digest(unsigned)) or not hmac.compare_digest(integrity, hmac.new(self._key(), _canonical(signed), hashlib.sha256).hexdigest()):
                raise CallbackStorageAdoptionError("adoption receipt authentication is invalid")
            raise CallbackStorageAdoptionError("adoption receipt pins conflict")

    def _assert_state_pins(
        self, authority: _RetainedAdoptionAuthority
    ) -> None:
        manifest_bytes = _read_evidence(self.paths.candidate_manifest, "candidate manifest")
        manifest = _object(manifest_bytes, "candidate manifest")
        freeze = _object(_read_evidence(self.paths.freeze_receipt, "freeze receipt"), "freeze receipt")
        absent = _object(_read_evidence(self.paths.historical_absent_evidence, "historical absent evidence"), "historical absent evidence")
        present = _object(_read_evidence(self.paths.present_evidence, "current present evidence"), "current present evidence")
        absent_facts = _object_field(
            absent, "facts", "historical absent evidence facts"
        )
        if (
            _sha(manifest_bytes) != MANIFEST_DIGEST
            or manifest.get("candidate_digest") != CANDIDATE_DIGEST
            or freeze.get("receipt_digest") != FREEZE_DIGEST
            or freeze.get("release_candidate_digest") != CANDIDATE_DIGEST
            or freeze.get("manifest_digest") != MANIFEST_DIGEST
            or absent.get("evidence_digest") != HISTORICAL_ABSENT_DIGEST
            or _digest_without(absent, "evidence_digest") != HISTORICAL_ABSENT_DIGEST
            or absent_facts.get("callback_envelope_present") is not False
            or present.get("evidence_digest") != PRESENT_EVIDENCE_DIGEST
            or _digest_without(present, "evidence_digest") != PRESENT_EVIDENCE_DIGEST
        ):
            raise CallbackStorageAdoptionError("release or evidence lineage changed")
        registry_bytes = _read_private(self.paths.registry, "customer registry")
        owner_bytes = _read_private_descriptor(
            authority.owner_fd, "owner-v1 journal"
        )
        authority.assert_file_bound(
            "owner-v1.json", authority.owner_fd, "owner-v1 journal"
        )
        service_bytes = _read_private(self.paths.service_state, "customer service state")
        if _sha(registry_bytes) != REGISTRY_DIGEST or _sha(owner_bytes) != OWNER_JOURNAL_DIGEST or _sha(service_bytes) != SERVICE_STATE_DIGEST:
            raise CallbackStorageAdoptionError("business authority pin changed")
        registry = _object(registry_bytes, "customer registry")
        rows: list[dict[str, object]] = []
        for row in _list_field(registry, "customers", "customer registry"):
            customer = _mapping(row, "customer registry customer")
            if customer.get("customer_key") == CUSTOMER:
                rows.append(customer)
        if len(rows) != 1 or rows[0].get("enabled") is not False or "trainer" not in rows[0]:
            raise CallbackStorageAdoptionError("customer authority is not the pinned disabled trainer-present source")
        if _object(owner_bytes, "owner-v1 journal").get("phase") != "PUBLICATION_COMMITTED" or _object(service_bytes, "service state").get("states") not in ({}, None):
            raise CallbackStorageAdoptionError("owner or service authority changed")
        outbox = _LockHeldAdoptionOutbox(self.paths.profile_root, initialize=False)
        if _sha(_read_private(self.paths.outbox_root / "ledger.json", "publication ledger")) != OUTBOX_DIGEST:
            raise CallbackStorageAdoptionError("publication ledger pin changed")
        # The adoption transaction already holds the primary outbox lock during
        # execute; parse the authenticated ledger without recursively flocking.
        records = tuple(
            row for row in outbox.records_with_primary_lock_held()
            if row.session_id == SESSION
        )
        expected = {23: ("customer", "customer_attestation"), 25: ("owner", "owner_review"), 26: ("owner", "ready")}
        for generation, (role, state) in expected.items():
            matches = tuple(row for row in records if row.generation == generation)
            if len(matches) != 1 or matches[0].role != role or matches[0].state != "COMMITTED" or matches[0].payload.get("state") != state or matches[0].receipt_integrity is None:
                raise CallbackStorageAdoptionError(f"generation {generation} authority changed")
        if any(row.generation >= 27 for row in records):
            raise CallbackStorageAdoptionError("generation 27 or later authority is present")
        migration_authorities = (
            "task22-supplemental-owner-review-v1.json",
            ".task22-supplemental-owner-review-v1.lock",
            "trainer-authority-removal-v1",
            ".trainer-authority-removal-v1.lock",
        )
        profile_authorities = (
            self.paths.profile_root / "data" / "customer-activation-journal.json",
            self.paths.profile_root / "data" / "scheduled-deliveries.jsonl",
            self.paths.profile_root / "data" / "nutrition-plans" / "feature-epoch.json",
            self.paths.profile_root / "data" / "owner-actions" / "draft-deliveries.json",
        )
        if any(
            _contains_authority_at(authority.migrations_fd, name)
            for name in migration_authorities
        ) or any(_contains_authority(path) for path in profile_authorities):
            raise CallbackStorageAdoptionError(
                "supplemental, removal, activation, draft, or delivery authority is present"
            )

    def _verify_pair(self) -> None:
        for pin in ARTIFACT_PINS:
            data, info = _read_bound(self.paths.outbox_root / pin.name, "callback storage")
            if (info.st_dev, info.st_ino, info.st_uid, info.st_gid, stat.S_IMODE(info.st_mode), info.st_nlink, info.st_size, _sha(data), data) != (pin.device, pin.inode, pin.uid, pin.gid, pin.mode, pin.links, pin.size, pin.sha256, pin.content):
                raise CallbackStorageAdoptionError("callback storage pair drifted")
        document = _object(ARTIFACT_PINS[0].content, "callback ledger")
        if set(document) != {"schema", "records"} or document.get("schema") != "telegram-nutrition-onboarding-owner-callback-v1" or document.get("records") != []:
            raise CallbackStorageAdoptionError("callback ledger is not the exact initialized-empty schema")

    def _validate_roots(self, authority: _RetainedAdoptionAuthority) -> None:
        if self.paths.profile_root.name != PROFILE:
            raise CallbackStorageAdoptionError("profile is not authorized")
        for descriptor in authority.private_directory_fds:
            info = os.fstat(descriptor)
            if (
                not stat.S_ISDIR(info.st_mode)
                or stat.S_IMODE(info.st_mode) != 0o700
                or info.st_uid != os.geteuid()
            ):
                raise CallbackStorageAdoptionError(
                    "adoption authority directory is unsafe"
                )
        outbox_info = self.paths.outbox_root.lstat()
        if (
            stat.S_ISLNK(outbox_info.st_mode)
            or not stat.S_ISDIR(outbox_info.st_mode)
            or stat.S_IMODE(outbox_info.st_mode) != 0o700
            or outbox_info.st_uid != os.geteuid()
        ):
            raise CallbackStorageAdoptionError(
                "adoption authority directory is unsafe"
            )

    def _assert_quiescent(self, *, ignore_locks: bool = False) -> None:
        proof = _service_fence(self._service_fence_check(self.paths.profile_root))
        if (
            proof.get("fenced") is not True
            or proof.get("load_state") != "masked"
            or proof.get("active_state") != "inactive"
            or proof.get("sub_state") != "dead"
            or proof.get("main_pid") != 0
            or proof.get("unit_file_state") != "masked-runtime"
            or proof.get("control_group") != ""
            or proof.get("n_file_descriptor_store") != 0
        ):
            raise CallbackStorageAdoptionError(
                "exact runtime service-manager fence is not active"
            )
        inventory = _scan_process_inventory(self.paths.profile_root, proof)
        self._fence = proof
        self._inventory = inventory
        self._inventory_digest = _digest(inventory)
        if not ignore_locks:
            self._assert_locks_available()

    def _assert_locks_available(self) -> None:
        for path in self.paths.authority_locks:
            _assert_lock_available(path)

    @contextmanager
    def _ordered_locks(self) -> Generator[None, None, None]:
        descriptors: list[int] = []
        try:
            for path in self.paths.authority_locks:
                fd = os.open(path, os.O_RDWR | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0))
                info = os.fstat(fd)
                if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or stat.S_IMODE(info.st_mode) != _PRIVATE_FILE:
                    raise CallbackStorageAdoptionError("authority lock is unsafe")
                callback_pin = next((pin for pin in ARTIFACT_PINS if pin.name == ".owner-callbacks.lock"), None)
                if path == self.paths.outbox_root / ".owner-callbacks.lock" and callback_pin is not None and (info.st_dev, info.st_ino) != (callback_pin.device, callback_pin.inode):
                    raise CallbackStorageAdoptionError("callback lock identity drifted")
                fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
                descriptors.append(fd)
            yield
        except BlockingIOError as exc:
            raise CallbackStorageAdoptionError("authority lock is held") from exc
        finally:
            for fd in reversed(descriptors):
                os.close(fd)

    def _key(self) -> bytes:
        return _read_private(self.paths.outbox_root / ".receipt-key", "publication receipt key")

def verify_callback_storage_adoption_receipt(
    profile_root: Path | str,
    *,
    receipt_path: Path | str | None = None,
    key_path: Path | str | None = None,
    require_empty_pair: bool = True,
    require_original_identity: bool = True,
) -> dict[str, object]:
    """Verify the immutable receipt and its phase-appropriate callback authority."""
    root = Path(profile_root).absolute()
    migrations = root / "data" / "customers" / CUSTOMER / "nutrition-onboarding" / "migrations"
    receipt = Path(receipt_path).absolute() if receipt_path is not None else migrations / _RECEIPT_NAME
    key = Path(key_path).absolute() if key_path is not None else root / "data" / "onboarding" / "telegram-publication-outbox-v1" / ".receipt-key"
    document = _read_json(receipt, "adoption receipt", optional=False, links=(1,))
    assert document is not None
    signed = dict(document)
    integrity = signed.pop("integrity", None)
    unsigned = dict(signed)
    digest = unsigned.pop("receipt_digest", None)
    receipt_digest = _string_field(document, "receipt_digest", "adoption receipt")
    inventory_value = document.get("protected_process_inventory")
    _ = _protected_inventory(
        inventory_value, "adoption receipt protected process inventory"
    )
    if (
        document.get("schema") != _SCHEMA
        or document.get("transaction_id") != _TRANSACTION_ID
        or document.get("classification") != _CLASSIFICATION
        or document.get("callback_record_count") != 0
        or document.get("business_transition_count") != 0
        or document.get("grants") != []
        or document.get("protected_process_inventory_digest")
        != _digest(inventory_value)
        or document.get("quiescence_fence_digest")
        != _digest(
            {
                "service_manager_fence_proof": document.get(
                    "service_manager_fence_proof"
                ),
                "protected_process_inventory_digest": document.get(
                    "protected_process_inventory_digest"
                ),
            }
        )
        or not isinstance(digest, str)
        or digest != receipt_digest
        or digest != _digest(unsigned)
        or not isinstance(integrity, str)
        or not hmac.compare_digest(integrity, hmac.new(_read_private(key, "publication receipt key"), _canonical(signed), hashlib.sha256).hexdigest())
    ):
        raise CallbackStorageAdoptionError("adoption receipt authentication or contract is invalid")
    terminal_path = receipt.with_name(_TERMINAL_NAME)
    terminal = _read_json(
        terminal_path,
        "adoption terminal binding",
        optional=False,
        links=(1,),
    )
    assert terminal is not None
    _verify_terminal_binding(
        document,
        terminal,
        _read_private(key, "publication receipt key"),
    )
    outbox_root = root / "data" / "onboarding" / "telegram-publication-outbox-v1"
    artifacts = _artifact_payloads(document, "adoption receipt artifacts")
    if len(artifacts) < 2:
        raise CallbackStorageAdoptionError("adoption receipt artifacts are incomplete")
    lock_pin = artifacts[1]
    lock_data, lock_info = _read_bound(
        outbox_root / ".owner-callbacks.lock", "adopted callback lock"
    )
    if require_original_identity and (lock_info.st_dev, lock_info.st_ino) != (
        lock_pin["device"], lock_pin["inode"]
    ):
        raise CallbackStorageAdoptionError("adopted callback lock identity drifted")
    if (
        stat.S_IMODE(lock_info.st_mode), lock_info.st_size,
        _sha(lock_data),
    ) != (lock_pin["mode"], lock_pin["size"], lock_pin["sha256"]):
        raise CallbackStorageAdoptionError("adopted callback lock content drifted")
    if require_empty_pair:
        for item in artifacts:
            data, info = _read_bound(outbox_root / item["name"], "adopted callback storage")
            actual = (
                info.st_size, _sha(data), base64.b64encode(data).decode(),
                stat.S_IMODE(info.st_mode),
            )
            expected = (
                item["size"], item["sha256"], item["bytes_b64"], item["mode"],
            )
            identity_matches = (info.st_dev, info.st_ino, info.st_uid, info.st_gid, info.st_nlink) == (
                item["device"], item["inode"], item["uid"], item["gid"], item["links"]
            )
            if actual != expected or (require_original_identity and not identity_matches):
                raise CallbackStorageAdoptionError("adopted callback storage drifted")
    else:
        outbox = GatewayOnboardingPublicationOutbox(root, initialize=False)
        event = outbox.owner_callback(SESSION)
        publications = tuple(row for row in outbox.records() if row.session_id == SESSION and row.generation == 27)
        if event is None or event.publication_generation != 27 or len(publications) != 1 or publications[0].state != "COMMITTED" or publications[0].receipt_integrity is None:
            raise CallbackStorageAdoptionError("authenticated generation 27 callback authority is unavailable")
    return {"schema": _SCHEMA, "transaction_id": _TRANSACTION_ID, "receipt_digest": receipt_digest, "classification": _CLASSIFICATION, "callback_record_count": 0, "grants": []}

def _terminal_payload(
    receipt: Mapping[str, object], key: bytes
) -> dict[str, object]:
    authority_keys = (
        "release_candidate_digest",
        "manifest_digest",
        "freeze_receipt_digest",
        "historical_absent_evidence_digest",
        "current_present_evidence_digest",
        "registry_digest",
        "owner_journal_digest",
        "publication_ledger_digest",
        "service_state_digest",
        "authenticated_generations",
        "generation_27_or_later_absent",
        "customer_disabled",
        "trainer_present_at_adoption",
        "activation_count",
        "draft_count",
        "delivery_count",
        "service_manager_fence_proof",
        "protected_process_inventory",
        "protected_process_inventory_digest",
        "quiescence_fence_digest",
    )
    unsigned: dict[str, object] = {
        "schema": _TERMINAL_SCHEMA,
        "transaction_id": _TRANSACTION_ID,
        "receipt_digest": receipt.get("receipt_digest"),
        "pair_identity": receipt.get("artifacts"),
        "authority_snapshot": {
            name: receipt.get(name) for name in authority_keys
        },
    }
    terminal_digest = _digest(unsigned)
    signed = {**unsigned, "terminal_digest": terminal_digest}
    return {
        **signed,
        "integrity": hmac.new(key, _canonical(signed), hashlib.sha256).hexdigest(),
    }

def _verify_terminal_binding(
    receipt: Mapping[str, object],
    terminal: Mapping[str, object],
    key: bytes,
) -> None:
    expected = _terminal_payload(receipt, key)
    if terminal != expected:
        raise CallbackStorageAdoptionError(
            "adoption terminal binding is invalid or conflicts"
        )

def _pin_payload(pin: ArtifactPin) -> _ArtifactPayload:
    return {"name": pin.name, "relative_path": f"data/onboarding/telegram-publication-outbox-v1/{pin.name}", "device": pin.device, "inode": pin.inode, "uid": pin.uid, "gid": pin.gid, "mode": pin.mode, "links": pin.links, "size": pin.size, "sha256": pin.sha256, "bytes_b64": base64.b64encode(pin.content).decode("ascii")}

@contextmanager
def _retain_adoption_authority(
    paths: AdoptionPaths,
) -> Generator[_RetainedAdoptionAuthority, None, None]:
    target = paths.receipt.parent
    try:
        relative = target.relative_to(paths.profile_root)
    except ValueError as exc:
        raise CallbackStorageAdoptionError(
            "adoption receipt parent escapes profile"
        ) from exc
    descriptors: list[int] = []
    authority: _RetainedAdoptionAuthority | None = None
    try:
        root_fd = os.open(
            "/", os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC
        )
        descriptors.append(root_fd)
        parent_fd = root_fd
        bindings: list[tuple[int, str, int]] = []
        profile_fd: int | None = None
        current = Path("/")
        for component in target.parts[1:]:
            descriptor = os.open(
                component,
                os.O_RDONLY
                | os.O_DIRECTORY
                | os.O_CLOEXEC
                | getattr(os, "O_NOFOLLOW", 0),
                dir_fd=parent_fd,
            )
            descriptors.append(descriptor)
            bindings.append((parent_fd, component, descriptor))
            current /= component
            if current == paths.profile_root:
                profile_fd = descriptor
            parent_fd = descriptor
        if profile_fd is None or relative.parts != (
            "data",
            "customers",
            CUSTOMER,
            "nutrition-onboarding",
            "migrations",
        ):
            raise CallbackStorageAdoptionError(
                "adoption authority path is not canonical"
            )
        profile_position = next(
            index
            for index, (_parent, _name, descriptor) in enumerate(bindings)
            if descriptor == profile_fd
        )
        owner_fd = _open_private_entry(
            parent_fd, "owner-v1.json", "owner-v1 journal", links=(1,)
        )
        descriptors.append(owner_fd)
        stage_fd = _open_optional_private_entry(
            parent_fd,
            _STAGE_NAME,
            "adoption receipt staging",
            links=(1, 2),
        )
        if stage_fd is not None:
            descriptors.append(stage_fd)
        receipt_fd = _open_optional_private_entry(
            parent_fd, _RECEIPT_NAME, "adoption receipt", links=(1, 2)
        )
        if receipt_fd is not None:
            descriptors.append(receipt_fd)
        terminal_stage_fd = _open_optional_private_entry(
            parent_fd,
            _TERMINAL_STAGE_NAME,
            "adoption terminal binding staging",
            links=(1, 2),
        )
        if terminal_stage_fd is not None:
            descriptors.append(terminal_stage_fd)
        terminal_fd = _open_optional_private_entry(
            parent_fd,
            _TERMINAL_NAME,
            "adoption terminal binding",
            links=(1, 2),
        )
        if terminal_fd is not None:
            descriptors.append(terminal_fd)
        authority = _RetainedAdoptionAuthority(
            directory_bindings=tuple(bindings[profile_position:]),
            private_directory_fds=tuple(
                descriptor
                for _parent, _name, descriptor in bindings[profile_position:]
            ),
            migrations_fd=parent_fd,
            owner_fd=owner_fd,
            stage_fd=stage_fd,
            receipt_fd=receipt_fd,
            terminal_stage_fd=terminal_stage_fd,
            terminal_fd=terminal_fd,
        )
        yield authority
    except CallbackStorageAdoptionError:
        raise
    except OSError as exc:
        raise CallbackStorageAdoptionError(
            "adoption authority descriptor chain is unavailable"
        ) from exc
    finally:
        retained = set(descriptors)
        if authority is not None:
            if authority.stage_fd is not None:
                retained.add(authority.stage_fd)
            if authority.receipt_fd is not None:
                retained.add(authority.receipt_fd)
            if authority.terminal_stage_fd is not None:
                retained.add(authority.terminal_stage_fd)
            if authority.terminal_fd is not None:
                retained.add(authority.terminal_fd)
        for descriptor in reversed(tuple(retained)):
            try:
                os.close(descriptor)
            except OSError:
                pass

def _open_private_entry(
    parent_fd: int,
    name: str,
    label: str,
    *,
    links: tuple[int, ...],
) -> int:
    descriptor = os.open(
        name,
        os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0),
        dir_fd=parent_fd,
    )

[Showing lines 1-1221 of 2726 (50.0KB limit). Use offset=1222 to continue.]