"""Zero-inotify, event-driven receipts for authoritative Linux file commits."""
from __future__ import annotations

import ctypes
import errno
import fcntl
import hashlib
import os
import select
import signal
import stat
import struct
import sys
import threading
import time
from pathlib import Path

from gateway._commit_receipts import CommitObservationError, CommitReceiptLog

# Kept as the public commit-interest contract used by existing callers.  The
# dnotify backend maps it to directory mutation notifications below.
IN_CLOSE_WRITE = 0x08
IN_MOVED_TO = 0x80
IN_CREATE = 0x100
COMMIT_MASK = IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE
BACKEND = "dnotify_signalfd_v1"
_DNOTIFY_MASK = (
    fcntl.DN_MODIFY
    | fcntl.DN_CREATE
    | fcntl.DN_DELETE
    | fcntl.DN_RENAME
    | fcntl.DN_ATTRIB
    | fcntl.DN_MULTISHOT
)
_F_SETOWN_EX = 15
_F_OWNER_TID = 0
_SIGNAL = signal.SIGRTMIN + 7
_SIGNALFD_RECORD_SIZE = 128
_SIGNALFD_PREFIX = struct.Struct("IiiIIiIIIIii")
_OWNER = struct.Struct("ii")
_EMPTY_SHA256 = hashlib.sha256(b"").hexdigest()
_LIBC = ctypes.CDLL(None, use_errno=True)

class _SigSet(ctypes.Structure):
    _fields_ = [("bits", ctypes.c_ulong * 16)]

_LIBC.sigemptyset.argtypes = [ctypes.POINTER(_SigSet)]
_LIBC.sigemptyset.restype = ctypes.c_int
_LIBC.sigaddset.argtypes = [ctypes.POINTER(_SigSet), ctypes.c_int]
_LIBC.sigaddset.restype = ctypes.c_int
_LIBC.signalfd.argtypes = [ctypes.c_int, ctypes.POINTER(_SigSet), ctypes.c_int]
_LIBC.signalfd.restype = ctypes.c_int

class _BackendSetupError(OSError):
    def __init__(self, code: str, error: OSError) -> None:
        super().__init__(error.errno, error.strerror)
        self.code = code

class ProductionCommitObserver:
    """Observe authoritative parent directories through dnotify and signalfd."""

    def __init__(self, authoritative_roots: tuple[Path, ...], receipt_path: Path) -> None:
        if not authoritative_roots:
            raise CommitObservationError("path_outside_roots")
        self._roots = tuple(self._normalize(path) for path in authoritative_roots)
        self._receipt_path = self._normalize(receipt_path)
        self._receipts = CommitReceiptLog(self._receipt_path)
        self._signal_fd = -1
        self._directory_fds: dict[int, Path] = {}
        self._paths_by_parent: dict[Path, tuple[Path, ...]] = {}
        self._old_signal_mask: set[int] | None = None
        self._owner_thread = -1
        self._armed = False
        self._watcher_id = ""
        self._cursor = -1
        self._states: dict[Path, tuple[str, str, int]] = {}

    def __enter__(self) -> ProductionCommitObserver:
        return self

    def __exit__(self, *_args: object) -> None:
        self.close()

    def close(self) -> None:
        for descriptor in tuple(self._directory_fds):
            try:
                fcntl.fcntl(descriptor, fcntl.F_NOTIFY, 0)
            except OSError:
                pass
            try:
                os.close(descriptor)
            except OSError:
                pass
        self._directory_fds.clear()
        self._paths_by_parent.clear()
        if self._signal_fd >= 0:
            try:
                while True:
                    try:
                        if not os.read(self._signal_fd, _SIGNALFD_RECORD_SIZE * 256):
                            break
                    except BlockingIOError:
                        break
                os.close(self._signal_fd)
            finally:
                self._signal_fd = -1
        if self._old_signal_mask is not None:
            signal.pthread_sigmask(signal.SIG_SETMASK, self._old_signal_mask)
            self._old_signal_mask = None
        self._owner_thread = -1
        self._armed = False

    def arm(
        self,
        *,
        candidate_id: str,
        profile_id: str,
        watched_paths: tuple[Path, ...],
        watcher_id: str,
        mask: int,
        starting_cursor: int,
        update_offset: int,
        armed_at: str,
    ) -> dict[str, object]:
        if self._armed or not all((candidate_id, profile_id, watcher_id, armed_at)):
            raise CommitObservationError("duplicate_watcher_identity")
        if type(starting_cursor) is not int or starting_cursor < 0:
            raise CommitObservationError("sequence_not_forward")
        if type(update_offset) is not int or update_offset < 0:
            raise CommitObservationError("invalid_subscription")
        if type(mask) is not int or mask <= 0 or not watched_paths:
            raise CommitObservationError("invalid_subscription")
        if sys.platform != "linux" or _SIGNAL > signal.SIGRTMAX:
            raise CommitObservationError("backend_unavailable")
        for root in self._roots:
            self._validate_root(root)
        trusted_paths: set[Path] = {self._trusted(path) for path in watched_paths}
        paths: tuple[Path, ...] = tuple(
            sorted(trusted_paths, key=lambda path: path.as_posix())
        )
        self._prepare_receipt_parent()
        try:
            self._setup_backend(paths)
            # Subscription is live before this snapshot.  A commit racing the
            # snapshot is either represented here or remains queued in signalfd.
            self._states = {path: self._state(path) for path in paths}
            initial = [
                {"path": str(path), "byte_hash": value[0], "inode_hash": value[1]}
                for path, value in self._states.items()
            ]
            resources = self._resource_receipt()
            record = self._receipts.append(
                {
                    "kind": "subscription_armed",
                    "candidate_id": candidate_id,
                    "profile_id": profile_id,
                    "watched_paths": [str(path) for path in paths],
                    "watcher_id": watcher_id,
                    "mask": mask,
                    "starting_cursor": starting_cursor,
                    "update_offset": update_offset,
                    "initial_states": initial,
                    "armed_at": armed_at,
                    **resources,
                },
                reject_watcher=watcher_id,
            )
        except _BackendSetupError as exc:
            try:
                self._receipts.append(
                    {
                        "kind": "subscription_error",
                        "candidate_id": candidate_id,
                        "profile_id": profile_id,
                        "watched_paths": [str(path) for path in paths],
                        "watcher_id": watcher_id,
                        "backend": BACKEND,
                        "errno": exc.errno,
                        "error": exc.code,
                    },
                    reject_watcher=watcher_id,
                )
            finally:
                self.close()
            raise CommitObservationError(exc.code) from exc
        except BaseException:
            self.close()
            raise
        self._watcher_id = watcher_id
        self._cursor = starting_cursor
        self._armed = True
        return record

    def observe(self, *, sequence: int, timeout: float) -> dict[str, object]:
        if not self._armed:
            raise CommitObservationError("subscription_not_armed")
        if threading.get_native_id() != self._owner_thread:
            raise CommitObservationError("observer_thread_changed")
        if type(sequence) is not int or sequence <= self._cursor:
            raise CommitObservationError("sequence_not_forward")
        if sequence != self._cursor + 1:
            raise CommitObservationError("sequence_not_contiguous")
        if timeout < 0:
            raise ValueError("timeout must be non-negative")
        deadline = time.monotonic() + timeout
        candidates = self._states
        while True:
            changed = self._changed(candidates)
            if changed:
                path, value = changed[0]
                record = self._receipts.append(
                    {
                        "kind": "commit_observed",
                        "watcher_id": self._watcher_id,
                        "path": str(path),
                        "inode": value[2],
                        "sequence": sequence,
                        "commit_byte_hash": value[0],
                        **self._resource_receipt(),
                    }
                )
                self._states[path] = value
                self._cursor = sequence
                return record
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise CommitObservationError("event_timeout")
            parents = self._next_kernel_parents(remaining)
            candidates = {
                path: self._states[path]
                for parent in parents
                for path in self._paths_by_parent[parent]
            }

    def _setup_backend(self, paths: tuple[Path, ...]) -> None:
        current_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set())
        if _SIGNAL in current_mask:
            raise _BackendSetupError(
                "signal_unavailable", OSError(errno.EBUSY, os.strerror(errno.EBUSY))
            )
        try:
            self._old_signal_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {_SIGNAL})
        except OSError as exc:
            raise _BackendSetupError("signal_mask_failed", exc) from exc
        self._owner_thread = threading.get_native_id()
        try:
            self._signal_fd = self._create_signalfd()
        except OSError as exc:
            raise _BackendSetupError("signalfd_setup_failed", exc) from exc
        grouped: dict[Path, list[Path]] = {}
        for path in paths:
            grouped.setdefault(path.parent, []).append(path)
        for parent, children in sorted(
            grouped.items(), key=lambda item: item[0].as_posix()
        ):
            try:
                descriptor = os.open(
                    parent,
                    os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW,
                )
            except OSError as exc:
                raise _BackendSetupError("directory_open_failed", exc) from exc
            self._directory_fds[descriptor] = parent
            self._paths_by_parent[parent] = tuple(
                sorted(children, key=lambda path: path.as_posix())
            )
            try:
                fcntl.fcntl(
                    descriptor,
                    _F_SETOWN_EX,
                    _OWNER.pack(_F_OWNER_TID, self._owner_thread),
                )
                fcntl.fcntl(descriptor, fcntl.F_SETSIG, _SIGNAL)
                fcntl.fcntl(descriptor, fcntl.F_NOTIFY, _DNOTIFY_MASK)
            except OSError as exc:
                raise _BackendSetupError("dnotify_setup_failed", exc) from exc

    def _create_signalfd(self) -> int:
        mask = _SigSet()
        if _LIBC.sigemptyset(ctypes.byref(mask)) != 0:
            error = ctypes.get_errno()
            raise OSError(error, os.strerror(error))
        if _LIBC.sigaddset(ctypes.byref(mask), _SIGNAL) != 0:
            error = ctypes.get_errno()
            raise OSError(error, os.strerror(error))
        descriptor = _LIBC.signalfd(
            -1, ctypes.byref(mask), os.O_CLOEXEC | os.O_NONBLOCK
        )
        if descriptor < 0:
            error = ctypes.get_errno()
            raise OSError(error, os.strerror(error))
        return descriptor

    def _resource_receipt(self) -> dict[str, object]:
        return {
            "backend": BACKEND,
            "directory_resource_count": len(self._directory_fds),
            "signal_fd_count": 1 if self._signal_fd >= 0 else 0,
            "inotify_watch_count": 0,
        }

    def _next_kernel_parents(self, timeout: float) -> tuple[Path, ...]:
        self._wait_signal(timeout)
        descriptors = self._read_notifications()
        parents = {self._directory_fds[descriptor] for descriptor in descriptors}
        return tuple(sorted(parents, key=lambda path: path.as_posix()))

    def _wait_signal(self, timeout: float) -> None:
        ready, _, exceptional = select.select(
            (self._signal_fd,), (), (self._signal_fd,), timeout
        )
        if exceptional:
            raise CommitObservationError("notification_lost")
        if not ready:
            raise CommitObservationError("event_timeout")

    def _read_notifications(self) -> tuple[int, ...]:
        try:
            data = os.read(self._signal_fd, _SIGNALFD_RECORD_SIZE * 256)
        except BlockingIOError as exc:
            raise CommitObservationError("notification_malformed") from exc
        if not data or len(data) % _SIGNALFD_RECORD_SIZE:
            raise CommitObservationError("notification_malformed")
        descriptors: set[int] = set()
        for offset in range(0, len(data), _SIGNALFD_RECORD_SIZE):
            values = _SIGNALFD_PREFIX.unpack_from(data, offset)
            signo, descriptor, overrun = values[0], values[5], values[8]
            if signo != _SIGNAL or descriptor not in self._directory_fds:
                raise CommitObservationError("notification_malformed")
            if overrun:
                raise CommitObservationError("notification_lost")
            descriptors.add(descriptor)
        if not descriptors:
            raise CommitObservationError("notification_malformed")
        return tuple(sorted(descriptors))

    def _changed(
        self, prior: dict[Path, tuple[str, str, int]]
    ) -> list[tuple[Path, tuple[str, str, int]]]:
        changed = []
        for path, old in prior.items():
            try:
                current = self._state(path)
            except CommitObservationError as exc:
                if str(exc) != "state_not_regular":
                    raise
                current = self._state(path)
            if current != old and current[0] != _EMPTY_SHA256:
                changed.append((path, current))
        return changed

    def _state(self, path: Path) -> tuple[str, str, int]:
        self._no_symlinks(path)
        try:
            descriptor = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW)
        except OSError as exc:
            raise CommitObservationError("state_unavailable") from exc
        try:
            metadata = os.fstat(descriptor)
            if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1:
                raise CommitObservationError("state_not_regular")
            if stat.S_IMODE(metadata.st_mode) & 0o077:
                raise CommitObservationError("state_not_private")
            digest = hashlib.sha256()
            while chunk := os.read(descriptor, 65536):
                digest.update(chunk)
        finally:
            os.close(descriptor)
        inode_hash = hashlib.sha256(
            f"{metadata.st_dev}:{metadata.st_ino}".encode()
        ).hexdigest()
        return digest.hexdigest(), inode_hash, metadata.st_ino

    def _trusted(self, path: Path) -> Path:
        normalized = self._normalize(path)
        if not any(self._within(normalized, root) for root in self._roots):
            raise CommitObservationError("path_outside_roots")
        self._no_symlinks(normalized)
        return normalized

    def _prepare_receipt_parent(self) -> None:
        root = next(
            (root for root in self._roots if self._within(self._receipt_path, root)),
            None,
        )
        if root is None:
            raise CommitObservationError("path_outside_roots")
        current = root
        for part in self._receipt_path.parent.relative_to(root).parts:
            current /= part
            try:
                current.mkdir(mode=0o700)
            except FileExistsError:
                pass
            self._validate_directory(current)
        if os.path.lexists(self._receipt_path):
            self._no_symlinks(self._receipt_path)

    def _no_symlinks(self, path: Path) -> None:
        root = next((root for root in self._roots if self._within(path, root)), None)
        if root is None:
            raise CommitObservationError("path_outside_roots")
        current = root
        for part in ("", *path.relative_to(root).parts):
            current = current if not part else current / part
            try:
                if stat.S_ISLNK(os.lstat(current).st_mode):
                    raise CommitObservationError("symlink_rejected")
            except FileNotFoundError:
                return

    def _validate_root(self, path: Path) -> None:
        current = Path(path.anchor)
        for part in path.parts[1:]:
            current /= part
            try:
                if stat.S_ISLNK(os.lstat(current).st_mode):
                    raise CommitObservationError("symlink_rejected")
            except OSError as exc:
                raise CommitObservationError("state_unavailable") from exc
        self._validate_directory(path)

    @staticmethod
    def _validate_directory(path: Path) -> None:
        try:
            metadata = os.lstat(path)
        except OSError as exc:
            raise CommitObservationError("state_unavailable") from exc
        if stat.S_ISLNK(metadata.st_mode):
            raise CommitObservationError("symlink_rejected")
        if not stat.S_ISDIR(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) & 0o077:
            raise CommitObservationError("state_not_private")

    @staticmethod
    def _normalize(path: Path) -> Path:
        return Path(os.path.abspath(os.path.normpath(os.fspath(path))))

    @staticmethod
    def _within(path: Path, root: Path) -> bool:
        try:
            return os.path.commonpath((path, root)) == str(root)
        except ValueError:
            return False


--- .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts/physique_checkin_cli-0.1.0-py3-none-any.whl
checkin_cli/__init__.py | customer
checkin_cli/activation_token_rotation_policy.py | owner,customer
checkin_cli/adaptive_nutrition.py | provider,owner,customer,callback
checkin_cli/cli.py | callback
checkin_cli/coaching_grounding.py | customer
checkin_cli/customer_admin.py | provider,role,owner,customer,revoke
checkin_cli/customer_cleanup.py | customer
checkin_cli/customer_cleanup_fs.py | owner,customer
checkin_cli/customer_cleanup_inventory.py | owner,customer
checkin_cli/customer_cleanup_models.py | customer
checkin_cli/customer_cleanup_shared.py | provider,owner,customer
checkin_cli/customer_coaching.py | owner,customer
checkin_cli/customer_grounding.py | owner,customer
checkin_cli/customer_reporting.py | owner,customer
checkin_cli/customer_schedule.py | provider,owner,customer
checkin_cli/diagnostic_evidence.py | customer
checkin_cli/diagnostic_isolation.py | provider,role,owner,customer,revoke
checkin_cli/knowledge_retrieval.py | owner
checkin_cli/models.py | owner,customer
checkin_cli/nutrition_onboarding.py | role,owner,customer,current_authority
checkin_cli/nutrition_onboarding_artifacts.py | owner
checkin_cli/nutrition_onboarding_authority.py | role,owner,customer
checkin_cli/nutrition_onboarding_calculations.py | customer
checkin_cli/nutrition_onboarding_clarification_policy.py | customer
checkin_cli/nutrition_onboarding_cli.py | role,owner,customer,current_authority
checkin_cli/nutrition_onboarding_contract.py | owner,customer
checkin_cli/nutrition_onboarding_finalization.py | role,owner,customer
checkin_cli/nutrition_onboarding_finalize_service.py | owner,customer,current_authority
checkin_cli/nutrition_onboarding_fs.py | owner
checkin_cli/nutrition_onboarding_migration.py | owner,customer
checkin_cli/nutrition_onboarding_models.py | owner,customer,revoke
checkin_cli/nutrition_onboarding_projection.py | owner,customer
checkin_cli/nutrition_onboarding_session.py | role,owner,customer
checkin_cli/nutrition_onboarding_store.py | provider
checkin_cli/nutrition_readiness.py | customer
checkin_cli/nutrition_readiness_contract.py | owner,customer
checkin_cli/nutrition_readiness_validators.py | owner,customer
checkin_cli/nutrition_restriction_kb.py | owner,customer
checkin_cli/operator_console.py | prepare_delivery,mark_delivered,mark_sent,role,owner,customer,callback
checkin_cli/readiness_cli.py | customer
checkin_cli/staff_membership_evidence.py | customer
checkin_cli/store.py | provider,customer
checkin_cli/wizard.py | owner,customer
checkin_cli/wizard_models.py | owner,customer,callback
checkin_cli/wizard_storage.py | owner,callback
checkin_cli/policies/__init__.py | provider,customer
--- .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts/hermes_agent-0.17.0-py3-none-any.whl
batch_runner.py | provider,role
cli.py | provider,role,owner,callback
hermes_state.py | provider,role,owner,callback
mcp_serve.py | role
model_tools.py | provider,role,observer
run_agent.py | provider,role,callback
toolsets.py | provider,role,callback
trajectory_compressor.py | provider,role
utils.py | provider,owner
acp_adapter/auth.py | provider
acp_adapter/entry.py | provider
acp_adapter/events.py | callback
acp_adapter/permissions.py | callback
acp_adapter/server.py | provider,role,callback
acp_adapter/session.py | provider,role
acp_adapter/tools.py | role
agent/account_usage.py | provider
agent/agent_init.py | provider,role,callback
agent/agent_runtime_helpers.py | provider,role,callback
agent/anthropic_adapter.py | provider,role,callback
agent/async_utils.py | callback
agent/auxiliary_client.py | provider,role
agent/azure_identity_adapter.py | provider
agent/background_review.py | provider,role,callback
agent/bedrock_adapter.py | provider,role,callback
agent/billing_view.py | role
agent/browser_provider.py | provider
agent/browser_registry.py | provider
agent/chat_completion_helpers.py | provider,role,owner,callback
agent/codex_responses_adapter.py | provider,role
agent/codex_runtime.py | provider,role,callback
agent/context_compressor.py | provider,role
agent/context_engine.py | provider
agent/conversation_compression.py | provider,role,callback
agent/conversation_loop.py | provider,role,revoke,callback
agent/copilot_acp_client.py | provider,role
agent/credential_persistence.py | provider
agent/credential_pool.py | provider,revoke
agent/credential_sources.py | provider
agent/credits_tracker.py | provider,callback
agent/curator.py | provider
agent/error_classifier.py | provider,revoke
agent/file_safety.py | provider,owner
agent/gemini_cloudcode_adapter.py | provider,role
agent/gemini_native_adapter.py | provider,role
agent/google_code_assist.py | provider
agent/google_oauth.py | provider,owner,revoke,callback
agent/image_gen_provider.py | provider
agent/image_gen_registry.py | provider
agent/image_routing.py | provider
agent/insights.py | provider,role
agent/memory_manager.py | provider
agent/memory_provider.py | provider
agent/message_sanitization.py | provider,role
agent/model_metadata.py | provider
agent/models_dev.py | provider
agent/moonshot_schema.py | provider
agent/nous_rate_guard.py | provider
agent/plugin_llm.py | provider,role
agent/prompt_builder.py | provider,role
agent/prompt_caching.py | role
agent/rate_limit_tracker.py | provider
agent/redact.py | callback
agent/retry_utils.py | provider
agent/secret_scope.py | provider
agent/shell_hooks.py | revoke,callback
agent/skill_commands.py | provider
agent/skill_utils.py | provider
agent/stream_diag.py | provider
agent/system_prompt.py | provider
agent/think_scrubber.py | callback
agent/title_generator.py | role,callback
agent/tool_dispatch_helpers.py | provider,role
agent/tool_executor.py | provider,role,callback
agent/tool_guardrails.py | role
agent/transcription_provider.py | provider
agent/transcription_registry.py | provider
agent/tts_provider.py | provider
agent/tts_registry.py | provider
agent/turn_context.py | provider,role,callback
agent/turn_finalizer.py | provider,role,callback
agent/turn_retry_state.py | provider
agent/usage_pricing.py | provider
agent/video_gen_provider.py | provider
agent/video_gen_registry.py | provider
agent/web_search_provider.py | provider
agent/web_search_registry.py | provider
agent/lsp/client.py | provider
agent/secret_sources/bitwarden.py | provider
agent/transports/__init__.py | provider
agent/transports/anthropic.py | provider
agent/transports/base.py | provider
agent/transports/chat_completions.py | provider,role
agent/transports/codex.py | provider,role
agent/transports/codex_app_server_session.py | provider,role,callback
agent/transports/codex_event_projector.py | role
agent/transports/hermes_tools_mcp_server.py | callback
agent/transports/types.py | provider
cron/jobs.py | provider,owner
cron/physique_inline_card.py | owner
cron/scheduler.py | provider,callback
cron/scheduler_provider.py | provider
cron/scripts/classify_items.py | provider,role
gateway/_commit_receipts.py | observer
gateway/authz_mixin.py | role,owner
gateway/commit_observer.py | owner,dnotify,observer
gateway/config.py | provider,callback
gateway/delivery.py | provider
gateway/display_config.py | customer,callback
gateway/kanban_watchers.py | owner
gateway/memory_monitor.py | provider
gateway/mirror.py | role
gateway/pairing.py | owner,revoke
gateway/run.py | provider,role,owner,customer,revoke,callback
gateway/session.py | role,owner,callback
gateway/slash_commands.py | provider,role,callback
gateway/status.py | owner,observer
gateway/stream_consumer.py | callback
gateway/stream_dispatch.py | callback
gateway/stream_events.py | callback
gateway/whatsapp_identity.py | role
gateway/platforms/_http_client_limits.py | callback
gateway/platforms/api_server.py | provider,role,owner,callback
gateway/platforms/base.py | provider,role,owner,callback
gateway/platforms/bluebubbles.py | callback
gateway/platforms/diagnostic_isolation.py | provider,role,owner,customer
gateway/platforms/dingtalk.py | callback
gateway/platforms/dualcoach_activation_cutover.py | role,owner,customer
gateway/platforms/dualcoach_admin.py | provider,role,owner,customer
gateway/platforms/dualcoach_tasks21_25_controller.py | delivery_capability,provider,owner,customer,callback
gateway/platforms/feishu.py | owner,callback
gateway/platforms/feishu_comment.py | provider,role
gateway/platforms/korean_humanizer.py | provider,customer,revoke,callback
gateway/platforms/matrix.py | provider,owner,callback
gateway/platforms/msgraph_webhook.py | callback
gateway/platforms/nutrition_coaching.py | delivery_capability,prepare_delivery,claim_delivery,mark_delivered,mark_sent,provider,role,owner,customer,unknown_provider,revoke,callback
gateway/platforms/nutrition_coaching_config.py | customer
gateway/platforms/nutrition_coaching_judgment.py | customer
gateway/platforms/nutrition_coaching_judgment_adaptive.py | customer
gateway/platforms/nutrition_coaching_judgment_request.py | customer
gateway/platforms/nutrition_coaching_judgment_types.py | customer
gateway/platforms/nutrition_coaching_proposal.py | provider,owner,customer
gateway/platforms/nutrition_coaching_proposal_validation.py | owner,customer
gateway/platforms/nutrition_onboarding_reconciler.py | provider,role
gateway/platforms/nutrition_onboarding_reconciliation.py | customer
gateway/platforms/nutrition_operator_projection.py | customer
gateway/platforms/nutrition_service_state.py | customer
gateway/platforms/physique_checkin.py | owner,customer,callback
gateway/platforms/physique_checkin_bindings.py | owner
gateway/platforms/physique_checkin_config.py | owner
gateway/platforms/physique_checkin_prompts.py | callback
gateway/platforms/signal.py | provider,callback
gateway/platforms/slack.py | revoke,callback
gateway/platforms/sms.py | callback
gateway/platforms/task26_candidate_authority.py | revoke
gateway/platforms/task26_final_state.py | role,owner,current_authority
gateway/platforms/telegram.py | prepare_delivery,claim_delivery,mark_delivered,mark_sent,provider,role,owner,customer,revoke,observer,callback
gateway/platforms/telegram_activation_notice.py | mark_delivered,provider,customer
gateway/platforms/telegram_customer_bootstrap.py | provider,role,owner,customer
gateway/platforms/telegram_customer_bootstrap_registration.py | role,owner,customer
gateway/platforms/telegram_customer_surface_receipts.py | provider,owner,customer
gateway/platforms/telegram_network.py | provider
gateway/platforms/telegram_nutrition_addresses.py | role,owner,customer
gateway/platforms/telegram_nutrition_onboarding.py | callback
gateway/platforms/telegram_nutrition_onboarding_authority.py | customer
gateway/platforms/telegram_nutrition_onboarding_copy.py | owner,customer
gateway/platforms/telegram_nutrition_onboarding_preview.py | callback
gateway/platforms/telegram_nutrition_onboarding_preview_callback.py | callback
gateway/platforms/telegram_nutrition_onboarding_preview_completion.py | customer
gateway/platforms/telegram_nutrition_onboarding_publication_outbox.py | provider,role,owner,customer,callback
gateway/platforms/telegram_nutrition_onboarding_runtime.py | role,owner,customer,current_authority,callback
gateway/platforms/telegram_nutrition_onboarding_runtime_authority.py | role,owner,customer,current_authority
gateway/platforms/telegram_nutrition_onboarding_runtime_callback.py | role,owner,customer,current_authority,callback
gateway/platforms/telegram_nutrition_onboarding_runtime_collection.py | customer,current_authority
gateway/platforms/telegram_nutrition_onboarding_runtime_notice.py | customer
gateway/platforms/telegram_nutrition_onboarding_runtime_publication.py | role,owner,customer,current_authority
gateway/platforms/telegram_nutrition_onboarding_runtime_publication_transport.py | role,owner,customer,callback
gateway/platforms/telegram_nutrition_operator_console.py | owner,customer,callback
gateway/platforms/telegram_polling_receipts.py | callback
gateway/platforms/telegram_staff_membership_gate.py | role,owner,customer
gateway/platforms/webhook.py | provider,callback
gateway/platforms/wecom.py | callback
gateway/platforms/wecom_callback.py | callback
gateway/platforms/wecom_crypto.py | callback
gateway/platforms/yuanbao.py | role,owner,callback
gateway/platforms/yuanbao_proto.py | role,owner,callback
gateway/platforms/qqbot/adapter.py | provider,callback
gateway/platforms/qqbot/keyboards.py | callback
gateway/relay/auth.py | customer
gateway/relay/transport.py | callback
gateway/relay/ws_transport.py | revoke,callback
hermes_cli/_parser.py | provider
hermes_cli/auth.py | provider,role,owner,unknown_provider,revoke,callback
hermes_cli/auth_commands.py | provider,revoke
hermes_cli/azure_detect.py | provider,role
hermes_cli/banner.py | owner
hermes_cli/callbacks.py | callback
hermes_cli/claw.py | provider
hermes_cli/cli_agent_setup_mixin.py | provider,role,callback
hermes_cli/cli_commands_mixin.py | provider,role,callback
hermes_cli/codex_models.py | provider
hermes_cli/codex_runtime_switch.py | provider,callback
hermes_cli/commands.py | provider,callback
hermes_cli/config.py | provider,role,owner,callback
hermes_cli/container_boot.py | role,owner
hermes_cli/curses_ui.py | provider,callback
hermes_cli/dashboard_register.py | provider,revoke,callback
hermes_cli/debug.py | provider
hermes_cli/doctor.py | provider,owner
hermes_cli/dump.py | provider,callback
hermes_cli/env_loader.py | provider
hermes_cli/fallback_cmd.py | provider
hermes_cli/fallback_config.py | provider
hermes_cli/gateway.py | provider,owner,callback
hermes_cli/gateway_enroll.py | customer
hermes_cli/goals.py | provider,role
hermes_cli/hooks.py | provider,role,revoke,observer,callback
hermes_cli/inventory.py | provider
hermes_cli/kanban.py | owner
hermes_cli/kanban_db.py | provider,role,owner
hermes_cli/kanban_decompose.py | role
hermes_cli/kanban_diagnostics.py | provider
hermes_cli/kanban_specify.py | provider,role
hermes_cli/main.py | provider,role
hermes_cli/managed_scope.py | provider
hermes_cli/mcp_catalog.py | provider
hermes_cli/mcp_config.py | provider,revoke,callback
hermes_cli/memory_providers.py | provider
hermes_cli/memory_setup.py | provider
hermes_cli/middleware.py | provider,observer,callback
hermes_cli/model_catalog.py | provider
hermes_cli/model_cost_guard.py | provider
hermes_cli/model_normalize.py | provider
hermes_cli/model_setup_flows.py | provider,role
hermes_cli/model_switch.py | provider,role
hermes_cli/models.py | provider,role
hermes_cli/nous_account.py | provider
hermes_cli/nous_billing.py | provider,role
hermes_cli/nous_subscription.py | provider
hermes_cli/oneshot.py | provider,callback
hermes_cli/pairing.py | revoke
hermes_cli/partial_compress.py | provider,role
hermes_cli/platforms.py | callback
hermes_cli/plugins.py | provider,role,observer,callback
hermes_cli/plugins_cmd.py | provider,owner
hermes_cli/portal_cli.py | provider
hermes_cli/profile_describer.py | provider,role
hermes_cli/profiles.py | provider,role,owner,callback
hermes_cli/prompt_size.py | provider
hermes_cli/provider_catalog.py | provider
hermes_cli/providers.py | provider
hermes_cli/runtime_provider.py | provider,role,revoke
hermes_cli/secrets_cli.py | revoke
hermes_cli/security_advisories.py | provider
hermes_cli/service_manager.py | owner
hermes_cli/session_recap.py | provider,role
hermes_cli/setup.py | provider,owner
hermes_cli/setup_whatsapp_cloud.py | role,customer
hermes_cli/skills_hub.py | owner,callback
hermes_cli/status.py | provider
hermes_cli/telegram_managed_bot.py | owner
hermes_cli/timeouts.py | provider
hermes_cli/tips.py | provider,role,owner
hermes_cli/tools_config.py | provider,role,revoke
hermes_cli/voice.py | provider,callback
hermes_cli/web_server.py | provider,role,owner,revoke,callback
hermes_cli/xai_retirement.py | provider
hermes_cli/dashboard_auth/__init__.py | provider
hermes_cli/dashboard_auth/audit.py | revoke
hermes_cli/dashboard_auth/base.py | provider,revoke,callback
hermes_cli/dashboard_auth/cookies.py | provider,callback
hermes_cli/dashboard_auth/login_page.py | provider,role
hermes_cli/dashboard_auth/middleware.py | provider,revoke,callback
hermes_cli/dashboard_auth/prefix.py | callback
hermes_cli/dashboard_auth/public_paths.py | provider,callback
hermes_cli/dashboard_auth/registry.py | provider
hermes_cli/dashboard_auth/routes.py | provider,revoke,callback
hermes_cli/dashboard_auth/ws_tickets.py | provider
hermes_cli/proxy/__init__.py | provider
hermes_cli/proxy/cli.py | provider
hermes_cli/proxy/adapters/__init__.py | provider
hermes_cli/proxy/adapters/base.py | provider
hermes_cli/proxy/adapters/nous_portal.py | provider
hermes_cli/subcommands/acp.py | provider
hermes_cli/subcommands/auth.py | provider,callback
hermes_cli/subcommands/dashboard.py | callback
hermes_cli/subcommands/gateway.py | provider
hermes_cli/subcommands/hooks.py | revoke
hermes_cli/subcommands/login.py | provider
hermes_cli/subcommands/logout.py | provider
hermes_cli/subcommands/memory.py | provider
hermes_cli/subcommands/model.py | provider,callback
hermes_cli/subcommands/pairing.py | revoke
hermes_cli/subcommands/plugins.py | owner
hermes_cli/subcommands/profile.py | role
hermes_cli/subcommands/setup.py | provider
hermes_cli/subcommands/skills.py | owner
hermes_cli/subcommands/tools.py | provider
plugins/browser/browser_use/__init__.py | provider
plugins/browser/browser_use/provider.py | provider
plugins/browser/browserbase/__init__.py | provider
plugins/browser/browserbase/provider.py | provider
plugins/browser/firecrawl/__init__.py | provider
plugins/browser/firecrawl/provider.py | provider
plugins/context_engine/__init__.py | provider
plugins/cron/__init__.py | provider
plugins/cron/chronos/__init__.py | provider,callback
plugins/cron/chronos/_nas_client.py | provider,callback
plugins/dashboard_auth/basic/__init__.py | provider,revoke
plugins/dashboard_auth/nous/__init__.py | provider,owner,revoke,callback
plugins/dashboard_auth/self_hosted/__init__.py | provider,revoke,callback
plugins/google_meet/meet_bot.py | role,observer
plugins/google_meet/node/server.py | owner
plugins/google_meet/realtime/openai_client.py | role
plugins/hermes-achievements/dashboard/plugin_api.py | provider,role,callback
plugins/hermes-achievements/tests/test_achievement_engine.py | provider,role
plugins/image_gen/fal/__init__.py | provider
plugins/image_gen/krea/__init__.py | provider
plugins/image_gen/openai/__init__.py | provider
plugins/image_gen/openai-codex/__init__.py | provider,role
plugins/image_gen/xai/__init__.py | provider
plugins/kanban/dashboard/plugin_api.py | provider,owner
plugins/memory/__init__.py | provider
plugins/memory/byterover/__init__.py | provider,role
plugins/memory/hindsight/__init__.py | provider,role
plugins/memory/holographic/__init__.py | provider,role
plugins/memory/holographic/holographic.py | role
plugins/memory/holographic/retrieval.py | role
plugins/memory/honcho/__init__.py | provider,role
plugins/memory/honcho/cli.py | provider
plugins/memory/honcho/session.py | role,observer
plugins/memory/mem0/__init__.py | provider,role
plugins/memory/openviking/__init__.py | provider,role,callback
plugins/memory/retaindb/__init__.py | provider,role
plugins/memory/supermemory/__init__.py | provider,role
plugins/model-providers/alibaba/__init__.py | provider
plugins/model-providers/alibaba-coding-plan/__init__.py | provider
plugins/model-providers/anthropic/__init__.py | provider
plugins/model-providers/arcee/__init__.py | provider
plugins/model-providers/azure-foundry/__init__.py | provider
plugins/model-providers/bedrock/__init__.py | provider
plugins/model-providers/copilot/__init__.py | provider
plugins/model-providers/copilot-acp/__init__.py | provider
plugins/model-providers/custom/__init__.py | provider
plugins/model-providers/deepseek/__init__.py | provider
plugins/model-providers/gemini/__init__.py | provider
plugins/model-providers/gmi/__init__.py | provider
plugins/model-providers/huggingface/__init__.py | provider
plugins/model-providers/kilocode/__init__.py | provider
plugins/model-providers/kimi-coding/__init__.py | provider
plugins/model-providers/minimax/__init__.py | provider
plugins/model-providers/nous/__init__.py | provider
plugins/model-providers/novita/__init__.py | provider
plugins/model-providers/nvidia/__init__.py | provider
plugins/model-providers/ollama-cloud/__init__.py | provider
plugins/model-providers/openai-codex/__init__.py | provider
plugins/model-providers/opencode-zen/__init__.py | provider
plugins/model-providers/openrouter/__init__.py | provider
plugins/model-providers/qwen-oauth/__init__.py | provider,role
plugins/model-providers/stepfun/__init__.py | provider
plugins/model-providers/xai/__init__.py | provider
plugins/model-providers/xiaomi/__init__.py | provider
plugins/model-providers/zai/__init__.py | provider
plugins/observability/langfuse/__init__.py | provider,role
plugins/observability/nemo_relay/__init__.py | provider,role,callback
plugins/platforms/discord/adapter.py | provider,role,owner,callback
plugins/platforms/google_chat/adapter.py | role,revoke,callback
plugins/platforms/google_chat/oauth.py | owner,revoke,callback
plugins/platforms/line/adapter.py | mark_delivered
plugins/platforms/photon/auth.py | provider,callback
plugins/platforms/photon/cli.py | callback
plugins/platforms/teams/adapter.py | provider
plugins/security-guidance/patterns.py | callback
plugins/spotify/__init__.py | provider
plugins/teams_pipeline/cli.py | provider
plugins/teams_pipeline/pipeline.py | role
plugins/teams_pipeline/subscriptions.py | provider
plugins/video_gen/fal/__init__.py | provider
plugins/video_gen/xai/__init__.py | provider
plugins/web/__init__.py | provider
plugins/web/brave_free/__init__.py | provider
plugins/web/brave_free/provider.py | provider
plugins/web/ddgs/__init__.py | provider
plugins/web/ddgs/provider.py | provider
plugins/web/exa/__init__.py | provider
plugins/web/exa/provider.py | provider
plugins/web/firecrawl/__init__.py | provider
plugins/web/firecrawl/provider.py | provider
plugins/web/parallel/__init__.py | provider
plugins/web/parallel/provider.py | provider
plugins/web/searxng/__init__.py | provider
plugins/web/searxng/provider.py | provider
plugins/web/tavily/__init__.py | provider
plugins/web/tavily/provider.py | provider
plugins/web/xai/__init__.py | provider
plugins/web/xai/provider.py | provider,role,revoke
providers/__init__.py | provider
providers/base.py | provider,role
tools/approval.py | role,observer,callback
tools/async_delegation.py | role
tools/blueprints.py | provider
tools/browser_camofox.py | role
tools/browser_cdp_tool.py | provider
tools/browser_tool.py | provider,role,owner,callback
tools/clarify_gateway.py | callback
tools/clarify_tool.py | callback
tools/code_execution_tool.py | owner,callback
tools/computer_use_tool.py | callback
tools/cronjob_tools.py | provider
tools/delegate_tool.py | provider,role,owner,callback
tools/discord_tool.py | role,owner
tools/env_passthrough.py | provider
tools/file_operations.py | provider
tools/image_generation_tool.py | provider
tools/kanban_tools.py | owner
tools/lazy_deps.py | provider,callback
tools/managed_tool_gateway.py | provider
tools/mcp_oauth.py | provider,callback
tools/mcp_oauth_manager.py | provider,callback
tools/mcp_tool.py | provider,role,owner,callback
tools/memory_tool.py | role
tools/microsoft_graph_client.py | provider
tools/mixture_of_agents_tool.py | role
tools/openrouter_client.py | provider
tools/process_registry.py | role
tools/read_terminal_tool.py | callback
tools/schema_sanitizer.py | provider,owner
tools/session_search_tool.py | role,owner
tools/skill_usage.py | owner
tools/skills_guard.py | role
tools/skills_hub.py | role,owner,callback
tools/skills_tool.py | provider,callback
tools/slash_confirm.py | provider,callback
tools/terminal_tool.py | owner,callback
tools/thread_context.py | callback
tools/threat_patterns.py | role
tools/tool_backend_helpers.py | provider
tools/tool_search.py | provider
tools/transcription_tools.py | provider
tools/tts_tool.py | provider,role,callback
tools/video_generation_tool.py | provider
tools/vision_tools.py | provider,role
tools/voice_mode.py | provider,callback
tools/web_tools.py | provider,role
tools/write_approval.py | callback
tools/x_search_tool.py | provider,role
tools/xai_http.py | provider
tools/yuanbao_tools.py | role,owner
tools/computer_use/__init__.py | callback
tools/computer_use/backend.py | role
tools/computer_use/cua_backend.py | role
tools/computer_use/tool.py | provider,role,callback
tools/computer_use/vision_routing.py | provider
tools/environments/base.py | callback
tools/environments/docker.py | owner
tools/environments/file_sync.py | callback
tools/environments/local.py | provider,role
tui_gateway/server.py | provider,role,owner,callback
tui_gateway/transport.py | callback


--- sealed-tree integrity independently recomputed ---
{"actual_file_count": 362, "candidate_digest": "310632f25b112373d97355c5ce3290dc55fb6d036a735e2b53861d983c4fd648", "candidate_self_hash_ok": true, "declared_file_count": 362, "evidence_inventory_exact": true, "seal_candidate_binding": true, "seal_self_hash_ok": true, "symlink_count": 0}
--- postfreeze receipt seal recomputed ---
{"file_count": 9, "inventory_exact": true, "seal_self_hash_ok": true, "symlink_count": 0}


**Verifying selected Python 3.12 interpreter availability**

**Analyzing verifier import and environment setup challenges**

**Identifying rehydration write conflict with read-only mode**

**Examining bundle verification module**

**Planning offline verifier test with Python 3.12**

bash

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
printf '%s\n' '--- selected-toolchain availability ---'
for py in /home/cube/miniconda3/bin/python3.12 /home/cube/miniconda3/bin/python /usr/bin/python3; do if [ -x "$py" ]; then printf '%s: ' "$py"; "$py" -I -c 'import sys; print(sys.version.replace("\n"," "))'; fi; done
printf '%s\n' '--- original runtime cache state ---'
R=/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10
find "$R" -maxdepth 3 -printf '%m %y %p -> %l\n' 2>/dev/null | sort | head -200
printf '%s\n' '--- configured installed authority ---'
jq -c . "$ROOT/installed-golden-bundle/config.yaml" 2>/dev/null || true
rg -n 'profile_package_authority|site_packages|runtime_mode|candidate_digest' "$ROOT/installed-golden-bundle"/{config.yaml,driver-input.json,installed-provenance.json,source-provenance.json}

W=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts
python3 - "$W/physique_checkin_cli-0.1.0-py3-none-any.whl" "$W/hermes_agent-0.17.0-py3-none-any.whl" <<'PY'
import sys, zipfile
wheel=dict(zip(('profile','hermes'),sys.argv[1:]))
requests={
'profile':['checkin_cli/nutrition_onboarding_clarification_policy.py','checkin_cli/nutrition_onboarding_authority.py','checkin_cli/customer_cleanup_fs.py','checkin_cli/customer_cleanup_inventory.py'],
'hermes':['gateway/platforms/nutrition_coaching.py','gateway/platforms/telegram_customer_bootstrap.py','gateway/platforms/telegram_staff_membership_gate.py','gateway/platforms/telegram_nutrition_onboarding_runtime_callback.py']}
for role, files in requests.items():
 with zipfile.ZipFile(wheel[role]) as z:
  for name in files:
   print(f'=== {role}:{name} ===')
   text=z.read(name).decode()
   print(text)
PY

W=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts/hermes_agent-0.17.0-py3-none-any.whl
python3 - "$W" <<'PY'
import zipfile,sys
z=zipfile.ZipFile(sys.argv[1]); name='gateway/platforms/telegram_nutrition_onboarding_publication_outbox.py'; text=z.read(name).decode().splitlines()
for start,end in ((1,340),(630,970),(970,1360)):
 print(f'=== {name}:{start}-{end} ===')
 print('\n'.join(f'{i}: {s}' for i,s in enumerate(text[start-1:end],start)))
PY

W=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts/hermes_agent-0.17.0-py3-none-any.whl
python3 - "$W" <<'PY'
import zipfile,sys
z=zipfile.ZipFile(sys.argv[1]); name='gateway/platforms/nutrition_coaching.py'; text=z.read(name).decode().splitlines()
for i,line in enumerate(text,1):
 if any(token in line for token in ('def issue_delivery_capability','def prepare_delivery','def claim_delivery_transport','def mark_delivered','def mark_sent_audited','unknown_provider_outcome','delivery capability','_delivery_ledger_path','def persist_approved_delivery_card')):
  start=max(1,i-12); end=min(len(text),i+75); print(f'=== {name}:{start}-{end} ==='); print('\n'.join(f'{n}: {s}' for n,s in enumerate(text[start-1:end],start)))
PY


(no output)

[Showing lines 9-8 of 8 (50.0KB limit). Full output: /tmp/pi-bash-ea5fdfd287794ef2.log]


def lines(path: Path, label: str) -> list[dict[str, Any]]:
    return [obj(json.loads(line), label) for line in path.read_text(encoding="utf-8").splitlines() if line]

def private(
    path: Path, *, directory: bool = False, frozen: bool | None = None
) -> None:
    info = path.lstat()
    if stat.S_ISLNK(info.st_mode) or info.st_uid != os.geteuid():
        raise ValueError(f"unsafe artifact path: {path}")
    expected_type = stat.S_ISDIR if directory else stat.S_ISREG
    if not expected_type(info.st_mode) or (not directory and info.st_nlink != 1):
        raise ValueError(f"artifact type is invalid: {path}")
    mutable_modes = {0o700} if directory else {0o600}
    frozen_modes = {0o500} if directory else {0o400}
    allowed = mutable_modes if frozen is False else mutable_modes | frozen_modes
    if stat.S_IMODE(info.st_mode) not in allowed:
        raise ValueError(f"artifact permissions are invalid: {path}")

def verify_bootstrap_active_lineage(path: Path, customer: str) -> str:
    private(path)
    ledger = read_json(path, "bootstrap ledger")
    if set(ledger) != {"schema", "sessions", "digest"}:
        raise ValueError("bootstrap ledger schema is invalid")
    sessions = ledger["sessions"]
    payload = {"schema": ledger["schema"], "sessions": sessions}
    if (
        ledger["schema"] != "telegram-customer-bootstrap-v1"
        or ledger["digest"] != hashlib.sha256(canonical(payload)).hexdigest()
        or not isinstance(sessions, list)
        or len(sessions) != 1
    ):
        raise ValueError("bootstrap ledger authority is invalid")
    session = obj(sessions[0], "bootstrap session")
    customer_draft = obj(session.get("customer_draft"), "bootstrap customer draft")
    session_id = session.get("session_id")
    if (
        customer_draft.get("customer_key") != customer
        or session.get("state") != "ACTIVE"
        or not isinstance(session_id, str)
        or not session_id
    ):
        raise ValueError("bootstrap ACTIVE lineage is invalid")
    return session_id

def verify_provenance(
    root: Path, *, offline_recorded_source: bool = False
) -> tuple[str, Path]:
    path = root / "source-provenance.json"
    private(path)
    provenance = read_json(path, "source provenance")
    if provenance.get("schema") != "source-golden-provenance-v1":
        raise ValueError("source provenance schema is invalid")
    source = Path(str(provenance.get("source_root", "")))
    if source != DEFAULT_SOURCE or (not offline_recorded_source and (source.is_symlink() or not source.is_dir())):
        raise ValueError("source provenance root is unavailable")
    rows = provenance.get("files")
    if not isinstance(rows, list) or not rows:
        raise ValueError("source provenance inventory is empty")
    expected_paths: list[str] = []
    for raw in rows:
        row = obj(raw, "source provenance row")
        relative = row.get("path")
        if not isinstance(relative, str) or Path(relative).is_absolute() or ".." in Path(relative).parts:
            raise ValueError("source provenance path is invalid")
        target = source / relative
        if not offline_recorded_source:
            if target.is_symlink() or not target.is_file() or target.stat().st_nlink != 1:
                raise ValueError("source provenance file is unavailable")
            if sha(target) != row.get("sha256") or target.stat().st_size != row.get("size"):
                raise ValueError("source provenance file changed")
        expected_paths.append(relative)
    actual = expected_paths if offline_recorded_source else sorted(
        path.relative_to(source).as_posix()
        for path in source.rglob("*.py")
        if path.is_file() and not path.is_symlink() and not any(part in {".venv", "__pycache__"} for part in path.parts)
    )
    if expected_paths != actual or hashlib.sha256(canonical(rows)).hexdigest() != provenance.get("tree_digest"):
        raise ValueError("source provenance inventory is incomplete")
    return str(provenance["tree_digest"]), source

def verify_installed_provenance(
    root: Path,
    source_provenance: dict[str, Any],
    *,
    runtime_override: dict[str, object] | None = None,
) -> tuple[str, Path]:
    path = root / "installed-provenance.json"
    document = read_private_json(path)
    if set(document) != {"schema", "binding", "candidate_digest", "loaded_modules"} or document.get("schema") != "installed-golden-provenance-v1":
        raise ValueError("installed provenance schema is invalid")
    binding = obj(document.get("binding"), "installed candidate binding")
    if binding.get("schema") != "installed-golden-candidate-binding-v1":
        raise ValueError("installed candidate binding schema is invalid")
    expected_candidate = hashlib.sha256(canonical(binding)).hexdigest()
    if document.get("candidate_digest") != expected_candidate:
        raise ValueError("installed candidate digest binding is invalid")
    if binding.get("source_provenance") != source_provenance:
        raise ValueError("installed source metadata binding is invalid")
    config = obj(binding.get("config"), "installed config binding")
    if config.get("runtime_mode") != "installed" or config.get("profile_source_metadata_only") != str(DEFAULT_SOURCE):
        raise ValueError("installed config binding is invalid")
    scripts = Path(__file__).resolve().parent
    expected_tools = {
        "harness_sha256": sha(scripts / "source_golden_path.py"),
        "provenance_helper_sha256": sha(scripts / "installed_wheel_provenance.py"),
        "verifier_sha256": sha(Path(__file__)),
        "task26_contract_module": "gateway.platforms.task26_evidence_contract",
        "task26_contract_module_sha256": (
            str(binding.get("task26_contract_module_sha256", ""))
            if runtime_override is not None
            else sha(
                Path(str(config.get("profile_package_authority", "")))
                / "gateway/platforms/task26_evidence_contract.py"
            )
        ),
    }
    if any(binding.get(key) != value for key, value in expected_tools.items()):
        raise ValueError("installed harness or verifier digest changed")
    runtime = obj(binding.get("runtime"), "installed runtime")
    distributions = obj(runtime.get("distributions"), "installed distributions")
    profile = obj(distributions.get("profile"), "installed profile distribution")
    hermes = obj(distributions.get("hermes"), "installed Hermes distribution")
    parity = obj(binding.get("task26_contract_parity"), "Task26 contract parity")
    installed_contract = Path(str(config.get("profile_package_authority", ""))) / "gateway/platforms/task26_evidence_contract.py"
    contract_rows = [
        row for row in cast(list[dict[str, object]], hermes.get("installed_inventory", []))
        if row.get("path") == "gateway/platforms/task26_evidence_contract.py"
    ]
    if (
        len(contract_rows) != 1
        or parity.get("module") != "gateway.platforms.task26_evidence_contract"
        or parity.get("sha256") != contract_rows[0].get("sha256")
        or parity.get("size") != contract_rows[0].get("size")
        or parity.get("wheel_path") != hermes.get("wheel_path")
        or (
            runtime_override is None
            and parity.get("installed_path") != str(installed_contract.resolve(strict=True))
        )
    ):
        raise ValueError("Task26 source-wheel-installed parity binding is invalid")
    active_runtime = runtime if runtime_override is None else runtime_override
    active_distributions = obj(active_runtime.get("distributions"), "active installed distributions")
    active_profile = obj(active_distributions.get("profile"), "active profile distribution")
    active_hermes = obj(active_distributions.get("hermes"), "active Hermes distribution")
    recomputed = collect_installed_runtime(
        venv=Path(str(active_runtime.get("venv", ""))),
        site_packages=Path(str(active_runtime.get("site_packages", ""))),
        profile_wheel=Path(str(active_profile.get("wheel_path", ""))),
        hermes_wheel=Path(str(active_hermes.get("wheel_path", ""))),
    )
    active_runtime_core = {
        key: value
        for key, value in active_runtime.items()
        if key != "origin_proof"
    }
    if recomputed != active_runtime_core:
        raise ValueError("installed runtime receipt differs from installed bytes")
    if runtime_override is None:
        if recomputed != runtime:
            raise ValueError("installed runtime receipt differs from original installed bytes")
    elif portable_installed_runtime(recomputed) != binding.get("runtime_portable"):
        raise ValueError("rehydrated runtime differs from sealed portable binding")
    roots = tuple(
        Path(root_path)
        for distribution in (active_profile, active_hermes)
        for root_path in cast(list[str], distribution.get("package_roots"))
    )
    declarations = document.get("loaded_modules")
    if not isinstance(declarations, list) or not declarations:
        raise ValueError("installed loaded-module receipts are unavailable")
    declared_names: list[str] = []
    for raw in declarations:
        row = obj(raw, "loaded module receipt")
        name = row.get("module")
        if not isinstance(name, str) or not (name == "checkin_cli" or name.startswith("checkin_cli.") or name == "gateway" or name.startswith("gateway.")):
            raise ValueError("installed loaded-module name is invalid")
        declared_names.append(name)
    if declared_names != sorted(set(declared_names)):
        raise ValueError("installed loaded-module receipt set is invalid")
    actual_modules: dict[str, Path] = {}
    for name in declared_names:
        spec = importlib.util.find_spec(name)
        origin = None if spec is None else spec.origin
        if not isinstance(origin, str):
            raise ValueError(f"installed loaded-module origin is unavailable: {name}")
        actual_modules[name] = Path(origin)
    actual_receipts = loaded_module_receipts(actual_modules, allowed_roots=roots)
    if runtime_override is None:
        if actual_receipts != declarations:
            raise ValueError("installed loaded-module declarations differ from import reality")
    else:
        portable_declarations = [
            {key: row.get(key) for key in ("module", "sha256", "size")}
            for row in declarations
        ]
        portable_actual = [
            {key: row.get(key) for key in ("module", "sha256", "size")}
            for row in actual_receipts
        ]
        if portable_actual != portable_declarations:
            raise ValueError("rehydrated import origins differ from sealed module bytes")
    authority = config.get("profile_package_authority")
    if runtime_override is None:
        if not isinstance(authority, str) or Path(authority).resolve(strict=True) != Path(str(runtime["site_packages"])):
            raise ValueError("installed profile package authority is invalid")
        active_authority = Path(authority)
    else:
        active_authority = Path(str(active_runtime["site_packages"]))
    return expected_candidate, active_authority

[774 more lines in file. Use offset=393 to continue.]


def _validate_portable_origin_contract(runtime_portable: object) -> None:
    runtime = _object(runtime_portable, "portable installed runtime")
    proof = _object(runtime.get("origin_proof"), "portable origin proof")
    execution = _object(proof.get("execution"), "portable origin execution")
    modules = proof.get("modules")
    if (
        runtime.get("schema") != "installed-golden-runtime-portable-v1"
        or proof.get("schema") != "task26-installed-origin-proof-v1"
        or execution
        != {
            "cwd_authority": "private_empty_controlled",
            "python_isolated": True,
            "pythonpath_inherited": False,
        }
        or not isinstance(modules, list)
        or len(modules) != 2
    ):
        raise ValueError("portable installed origin proof is invalid")
    expected_pairs = [("gateway", "hermes"), ("checkin_cli", "profile")]
    for raw, (module, distribution) in zip(modules, expected_pairs, strict=True):
        row = _object(raw, "portable origin module")
        relative = row.get("installed_relative_path")
        if (
            set(row)
            != {
                "distribution",
                "module",
                "installed_relative_path",
                "sha256",
                "size",
            }
            or row.get("module") != module
            or row.get("distribution") != distribution
            or not isinstance(relative, str)
            or Path(relative).is_absolute()
            or ".." in Path(relative).parts
            or _HEX_DIGEST.fullmatch(str(row.get("sha256", ""))) is None
            or type(row.get("size")) is not int
            or row["size"] < 1
        ):
            raise ValueError("portable installed origin module proof is invalid")

def verify_expected_state(
    bundle: Path,
    expected_path: Path,
    *,
    hermes_wheel: Path,
    profile_wheel: Path,
) -> dict[str, Any]:
    """Validate the hash-bound portable expectation before creating a runtime."""
    _private(bundle, directory=True)
    _private(expected_path)
    _private(hermes_wheel)
    _private(profile_wheel)
    expected = _object(
        json.loads(expected_path.read_text(encoding="utf-8")),
        "sealed expected state",
    )
    if set(expected) != {
        "schema",
        "candidate_digest",
        "runtime_portable",
        "hermes_wheel",
        "profile_wheel",
        "wheelhouse",
        "verifier",
        "provenance_helper",
        "expected_status",
        "expected_result_sha256",
        "authority",
        "trust_boundary",
        "document_sha256",
    } or expected.get("schema") != "task26-sealed-final-state-v1":
        raise ValueError("sealed expected-state schema is invalid")
    if expected.get("trust_boundary") != TRUST_BOUNDARY:
        raise ValueError("sealed evidence trust boundary is invalid")
    _validate_portable_origin_contract(expected.get("runtime_portable"))
    claimed = expected.get("document_sha256")
    unsigned = {key: value for key, value in expected.items() if key != "document_sha256"}
    if claimed != hashlib.sha256(canonical(unsigned)).hexdigest():
        raise ValueError("sealed expected-state digest is invalid")
    for label, path in (
        ("hermes_wheel", hermes_wheel),
        ("profile_wheel", profile_wheel),
    ):
        binding = _object(expected.get(label), label)
        if binding != {"filename": path.name, "sha256": sha256_file(path)}:
            raise ValueError(f"sealed {label} digest differs")
    wheelhouse = _object(expected.get("wheelhouse"), "sealed wheelhouse inventory")
    if set(wheelhouse) != {
        "schema",
        "root_mode",
        "directories",
        "entries",
        "inventory_sha256",
    }:
        raise ValueError("sealed wheelhouse inventory schema is invalid")
    for label in ("verifier", "provenance_helper"):
        binding = _object(expected.get(label), label)
        relative = binding.get("relative_path")
        if (
            not isinstance(relative, str)
            or Path(relative).is_absolute()
            or ".." in Path(relative).parts
        ):
            raise ValueError(f"sealed {label} path is invalid")
        target = bundle / relative
        _private(target)
        if binding.get("sha256") != sha256_file(target):
            raise ValueError(f"sealed {label} digest differs")
    authority = _object(expected.get("authority"), "sealed authority")
    for name in ("registry.json", "qualification-ledger.json"):
        target = bundle / "candidate-authority" / name
        _private(target)
        if authority.get(name.removesuffix(".json") + "_sha256") != sha256_file(
            target
        ):
            raise ValueError("sealed authority digest differs")
    return expected

def _portable_verifier_result(result: Mapping[str, object]) -> dict[str, object]:
    return {
        key: value
        for key, value in result.items()
        if key not in {"package_authority", "rehydration_origin_proof"}
    }

def build_expected_state(
    bundle: Path,
    *,
    candidate_digest: str,
    runtime_portable: Mapping[str, object],
    hermes_wheel: Path,
    profile_wheel: Path,
    verifier_relative_path: str,
    provenance_relative_path: str,
    verifier_result: Mapping[str, object],
    wheelhouse: Path | None = None,
) -> dict[str, object]:
    """Build, but do not write or freeze, one successor expected-state document."""
    authority_result = _object(
        verifier_result.get("candidate_authority"), "candidate authority result"
    )
    _validate_portable_origin_contract(runtime_portable)
    wheelhouse_inventory = (
        dict(_EMPTY_WHEELHOUSE)
        if wheelhouse is None
        else build_wheelhouse_inventory(
            wheelhouse, required_wheels=(profile_wheel, hermes_wheel)
        )
    )
    document: dict[str, object] = {
        "schema": "task26-sealed-final-state-v1",
        "candidate_digest": candidate_digest,
        "runtime_portable": dict(runtime_portable),
        "hermes_wheel": {
            "filename": hermes_wheel.name,
            "sha256": sha256_file(hermes_wheel),
        },
        "profile_wheel": {
            "filename": profile_wheel.name,
            "sha256": sha256_file(profile_wheel),
        },
        "wheelhouse": wheelhouse_inventory,
        "verifier": {
            "relative_path": verifier_relative_path,
            "sha256": sha256_file(bundle / verifier_relative_path),
        },
        "provenance_helper": {
            "relative_path": provenance_relative_path,
            "sha256": sha256_file(bundle / provenance_relative_path),
        },
        "expected_status": verifier_result.get("status"),
        "expected_result_sha256": hashlib.sha256(
            canonical(_portable_verifier_result(verifier_result))
        ).hexdigest(),
        "authority": {
            "registry_sha256": sha256_file(
                bundle / "candidate-authority/registry.json"
            ),
            "qualification-ledger_sha256": sha256_file(
                bundle / "candidate-authority/qualification-ledger.json"
            ),
            "registry_head_sha256": authority_result.get("registry_head_sha256"),
            "ledger_head_sha256": authority_result.get("ledger_head_sha256"),
        },
        "trust_boundary": TRUST_BOUNDARY,
    }
    document["document_sha256"] = hashlib.sha256(canonical(document)).hexdigest()
    return document

def verify_runtime_origin_proof(
    runtime: Mapping[str, object],
    site_packages: Path,
    probe: object,
    *,
    controlled_cwd: Path | None = None,
) -> dict[str, object]:
    """Bind imported package origins to exact installed inventory rows."""
    evidence = _object(probe, "rehydrated origin probe")
    modules = _object(evidence.get("modules"), "rehydrated module origins")
    if (
        evidence.get("schema") != "task26-rehydrated-origin-probe-v1"
        or evidence.get("isolated") != 1
        or evidence.get("pythonpath_present") is not False
        or set(modules) != {"gateway", "checkin_cli"}
        or not isinstance(evidence.get("cwd"), str)
        or (
            controlled_cwd is not None
            and Path(str(evidence["cwd"])).resolve(strict=True)
            != controlled_cwd.resolve(strict=True)
        )
    ):
        raise ValueError("rehydrated Python isolation proof is invalid")
    distributions = _object(runtime.get("distributions"), "runtime distributions")
    proof_rows: list[dict[str, object]] = []
    for module, role in (("gateway", "hermes"), ("checkin_cli", "profile")):
        raw_path = modules.get(module)
        if not isinstance(raw_path, str):
            raise ValueError("rehydrated module origin is invalid")
        path = Path(raw_path)
        try:
            resolved = path.resolve(strict=True)
            relative = resolved.relative_to(site_packages.resolve(strict=True)).as_posix()
        except (OSError, ValueError) as exc:
            raise ValueError(
                "module origin is outside rehydrated site-packages"
            ) from exc
        metadata = resolved.stat()
        if (
            resolved.is_symlink()
            or not stat.S_ISREG(metadata.st_mode)
            or metadata.st_nlink != 1
        ):
            raise ValueError("rehydrated module origin is not a regular file")
        distribution = _object(distributions.get(role), f"{role} distribution")
        inventory = distribution.get("installed_inventory")
        if not isinstance(inventory, list):
            raise ValueError("installed inventory is invalid")
        matches = [
            _object(row, "installed inventory row")
            for row in inventory
            if isinstance(row, dict) and row.get("path") == relative
        ]
        digest = sha256_file(resolved)
        if (
            len(matches) != 1
            or matches[0].get("sha256") != digest
            or matches[0].get("size") != metadata.st_size
        ):
            raise ValueError("module origin differs from installed RECORD inventory")
        proof_rows.append(
            {
                "distribution": role,
                "module": module,
                "installed_relative_path": relative,
                "sha256": digest,
                "size": metadata.st_size,
            }
        )
    return {
        "schema": "task26-installed-origin-proof-v1",
        "execution": {
            "cwd_authority": "private_empty_controlled",
            "python_isolated": True,
            "pythonpath_inherited": False,
        },
        "modules": proof_rows,
    }

def _portable_runtime(runtime: Mapping[str, object]) -> dict[str, object]:
    distributions = _object(runtime.get("distributions"), "runtime distributions")
    portable_distributions: dict[str, object] = {}
    for role in ("profile", "hermes"):
        distribution = _object(distributions.get(role), f"{role} distribution")
        raw_inventory = distribution.get("installed_inventory")
        if not isinstance(raw_inventory, list) or any(
            not isinstance(row, dict) for row in raw_inventory
        ):
            raise ValueError(f"{role} installed inventory is invalid")
        inventory = [
            row
            for row in raw_inventory
            if ".." not in Path(str(row.get("path", ""))).parts
            and not str(row.get("path", "")).endswith(".dist-info/RECORD")
        ]
        portable_distribution: dict[str, object] = {
            key: distribution.get(key)
            for key in (
                "distribution_name",
                "distribution_version",
                "metadata_sha256",
                "wheel_filename",
                "wheel_sha256",
                "wheel_record_sha256",
            )
        }
        portable_distribution["installed_inventory"] = inventory
        portable_distribution["installed_inventory_sha256"] = hashlib.sha256(
            canonical(inventory)
        ).hexdigest()
        portable_distributions[role] = portable_distribution
    interpreter = _object(runtime.get("interpreter"), "runtime interpreter")
    return {
        "schema": "installed-golden-runtime-portable-v1",
        "interpreter": {
            "sha256": interpreter.get("sha256"),
            "version": interpreter.get("version"),
        },
        "distributions": portable_distributions,
        "origin_proof": runtime.get("origin_proof"),
    }

def _clean_environment() -> dict[str, str]:

[273 more lines in file. Use offset=650 to continue.]