**Preparing independent verifier run without cache**

**Testing isolated Python environment for package imports**

**Auditing delivery receipt validation risks**

**Assessing delivery validation and privacy handling**

**Verifying archive permissions and artifact integrity**

**Verifying package environment closure**

bash

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10; env -i PATH=/home/cube/miniconda3/bin:/usr/bin:/bin HOME=/nonexistent PYTHONDONTWRITEBYTECODE=1 /home/cube/miniconda3/bin/python3.12 -I "$ROOT/verification-tools/independent_verify_candidate.py" "$ROOT"; printf 'exit=%s\n' "$?"

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
/home/cube/miniconda3/bin/python3.12 -I - "$ROOT" <<'PY'
import email.parser,email.policy,hashlib,sys,zipfile
from pathlib import Path
from packaging.requirements import Requirement
root=Path(sys.argv[1]); wheels=[*(root/'artifacts').glob('*.whl'),*(root/'wheelhouse').rglob('*.whl')]
projects={}; urls=[]; mismatches=[]
for p in wheels:
 with zipfile.ZipFile(p) as z:
  names=z.namelist(); meta=[n for n in names if n.endswith('.dist-info/METADATA')]
  msg=email.parser.BytesParser(policy=email.policy.compat32).parsebytes(z.read(meta[0]))
  name='-'.join(msg['Name'].lower().replace('_','-').split('-')); ver=msg['Version']
  if name in projects: mismatches.append(f'duplicate:{name}')
  projects[name]=(ver,p.name)
  for raw in msg.get_all('Requires-Dist') or []:
   req=Requirement(raw)
   if req.url: urls.append(f'{p.name}:{raw}')
   if req.marker is None or req.marker.evaluate():
    target='-'.join(req.name.lower().replace('_','-').split('-'))
    if target not in projects: pass
# second pass after all projects known
missing=[]
for p in wheels:
 with zipfile.ZipFile(p) as z:
  meta=next(n for n in z.namelist() if n.endswith('.dist-info/METADATA'))
  msg=email.parser.BytesParser(policy=email.policy.compat32).parsebytes(z.read(meta))
  for raw in msg.get_all('Requires-Dist') or []:
   req=Requirement(raw)
   if req.marker is not None and not req.marker.evaluate(): continue
   name='-'.join(req.name.lower().replace('_','-').split('-'))
   if name not in projects: missing.append(f'{p.name}:{req.name}')
   elif req.specifier and not req.specifier.contains(projects[name][0],prereleases=True): mismatches.append(f'{p.name}:{raw} selected={projects[name][0]}')
print({'python':sys.version.split()[0], 'wheel_count':len(wheels), 'project_count':len(projects), 'missing':missing, 'direct_urls':urls, 'mismatches':mismatches})
PY

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
printf '%s\n' '--- exact source / installed module parity ---'
/home/cube/miniconda3/bin/python3.12 -I - "$ROOT" <<'PY'
import hashlib,sys,zipfile
from pathlib import Path
root=Path(sys.argv[1])
checks=[('gateway/platforms/task26_candidate_authority.py','hermes_agent-0.17.0-py3-none-any.whl'),('gateway/platforms/task26_evidence_contract.py','hermes_agent-0.17.0-py3-none-any.whl'),('gateway/platforms/task26_final_state.py','hermes_agent-0.17.0-py3-none-any.whl')]
for member,wheel in checks:
 source=(root/member).read_bytes()
 with zipfile.ZipFile(root/'artifacts'/wheel) as z: payload=z.read(member)
 print(member, source==payload, hashlib.sha256(source).hexdigest())
PY
printf '%s\n' '--- audit receipt test outcomes/warnings ---'
for f in "$ROOT"/receipts/{security-attacks-installed.log,security-attacks-source.log,direct-url-attack-installed.json,direct-url-attack-source.json,manual-installed.json,manual-source.json,pip-check.log}; do echo ===$(basename "$f")===; grep -E 'passed|failed|warning|Warning|ERROR|error|No broken requirements|status|reason' "$f" || cat "$f"; done

W=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts/hermes_agent-0.17.0-py3-none-any.whl
/home/cube/miniconda3/bin/python3.12 -I - "$W" <<'PY'
import sys,zipfile
z=zipfile.ZipFile(sys.argv[1]); name='gateway/platforms/nutrition_coaching.py'; L=z.read(name).decode().splitlines()
for marker in ('def validate_delivery_transport','def _validate_delivery_capability','def _ensure_live_registry','def _record_eligibility_error','def _selection_eligibility_error'):
 i=next(i for i,x in enumerate(L,1) if marker in x); a=max(1,i-10); b=min(len(L),i+220); print(f'=== {marker}:{a}-{b} ===');print('\n'.join(f'{n}: {x}' for n,x in enumerate(L[a-1:b],a)))
PY

W=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts/hermes_agent-0.17.0-py3-none-any.whl
/home/cube/miniconda3/bin/python3.12 -I - "$W" <<'PY'
import sys,zipfile
z=zipfile.ZipFile(sys.argv[1])
for name in ['gateway/platforms/telegram_nutrition_onboarding_runtime_authority.py','gateway/platforms/telegram_nutrition_onboarding_runtime_publication.py','gateway/platforms/telegram_nutrition_onboarding_runtime_publication_transport.py']:
 print('===',name,'===');print(z.read(name).decode())
PY


Traceback (most recent call last):
  File "/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/independent_verify_candidate.py", line 174, in <module>
    raise SystemExit(main())
                     ^^^^^^
  File "/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/independent_verify_candidate.py", line 165, in main
    result = verify(args.bundle, args.rehydrated_runtime, allow_mutable=args.allow_mutable)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/independent_verify_candidate.py", line 113, in verify
    contract = verifier_module.verify_task26_contract(bundle / "installed-golden-bundle")
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/verify_source_golden_path.py", line 760, in verify_task26_contract
    from checkin_cli.nutrition_onboarding import QUESTION_FIELDS
ModuleNotFoundError: No module named 'checkin_cli'
exit=1


{'python': '3.12.9', 'wheel_count': 109, 'project_count': 109, 'missing': [], 'direct_urls': [], 'mismatches': []}


--- exact source / installed module parity ---
gateway/platforms/task26_candidate_authority.py True faec2e5616e399f02df82ce5e12d8d94ca79cbe3eb9d8a96446f673866eca431
gateway/platforms/task26_evidence_contract.py True 1ecb5d824507f9ea57e4646bb418ebd5750e79244748d298598890a456e8d9c3
gateway/platforms/task26_final_state.py True 1887ccc24c4ab7da25765da9d1c413f063ddbfa6059f48303806e76ba2dc9042
--- audit receipt test outcomes/warnings ---
===security-attacks-installed.log===
9 passed, 7 deselected in 1.46s
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup/archives/cfa1412d228c4359b98ca14a23a446d6/files/data/customers/client_001/onboarding
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup/archives/cfa1412d228c4359b98ca14a23a446d6/files/data/customers/client_001/outbox
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup/archives/cfa1412d228c4359b98ca14a23a446d6/files/data/customers/client_001
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup/archives/cfa1412d228c4359b98ca14a23a446d6/files/data/customers
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup/archives/cfa1412d228c4359b98ca14a23a446d6/files/data
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup/archives/cfa1412d228c4359b98ca14a23a446d6/files
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup/archives/cfa1412d228c4359b98ca14a23a446d6
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup/archives
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data/customer-cleanup
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile/data
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0/profile
  warnings.warn(
/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/lib/python3.12/site-packages/_pytest/pathlib.py:96: PytestWarning: (rm_rf) error removing /tmp/pytest-of-cube/garbage-a0c0fb0d-3ac5-4f97-8002-ac7f027151f0/test_duplicate_and_concurrent_0
  warnings.warn(
===security-attacks-source.log===
9 passed, 7 deselected in 1.42s
===direct-url-attack-installed.json===
{"attack":"direct-URL dependency","reason":"direct URL dependencies are forbidden","status":"PASS"}
===direct-url-attack-source.json===
{"attack":"direct-URL dependency","reason":"direct URL dependencies are forbidden","status":"PASS"}
===manual-installed.json===
{"accepted":11,"ambiguous_unresolved":3,"status":"PASS"}
===manual-source.json===
{"accepted":11,"ambiguous_unresolved":3,"status":"PASS"}
===pip-check.log===
No broken requirements found.


=== def validate_delivery_transport:2619-2849 ===
2619:         canonical = resolved.customer.spec.telegram
2620:         if destination is not None:
2621:             destination_key = tuple(
2622:                 str(getattr(destination, field, "") or "")
2623:                 for field in ("user_id", "chat_id", "topic_id")
2624:             )
2625:             if destination_key != tuple(str(value) for value in canonical.key):
2626:                 return False
2627:         return not self._customer_has_safety_hold(resolved)
2628:
2629:     def validate_delivery_transport(
2630:         self,
2631:         draft_id: str,
2632:         owner: IncomingAddress,
2633:         destination: object | None = None,
2634:         text: str | None = None,
2635:         *,
2636:         kst_date: date | datetime | None = None,
2637:         card_route: IncomingAddress | None = None,
2638:         card_message_id: str | None = None,
2639:         card_nonce: str | None = None,
2640:         card_payload_digest: str | None = None,
2641:         now: datetime | None = None,
2642:     ) -> bool:
2643:         """Atomically consume one pending reservation immediately before transport."""
2644:         if not self._ensure_live_registry() or owner.key != self._registry.owner.key:
2645:             return False
2646:         with self._delivery_lock():
2647:             if not self._ensure_live_registry():
2648:                 return False
2649:             try:
2650:                 drafts = self._read_drafts()
2651:                 deliveries = self._read_deliveries()
2652:                 generations = self._read_draft_generations()
2653:             except DraftLedgerError:
2654:                 return False
2655:             record = drafts.get(draft_id)
2656:             if (
2657:                 not isinstance(record, dict)
2658:                 or self._record_eligibility_error(record, owner) is not None
2659:             ):
2660:                 return False
2661:             selection = self._draft_selection_from_record(record, owner)
2662:             if selection is None:
2663:                 return False
2664:             customer_spec = getattr(selection.customer, "spec", None)
2665:             if (
2666:                 customer_spec is None
2667:                 or self._selection_eligibility_error(selection) is not None
2668:                 or record.get("status") != "approved"
2669:                 or self._approved_record_error(draft_id, selection, record) is not None
2670:             ):
2671:                 return False
2672:             customer_key = str(getattr(customer_spec, "customer_key", ""))
2673:             record_text = str(record.get("text", "")).strip()
2674:             if (
2675:                 not isinstance(text, str)
2676:                 or text.strip() != record_text
2677:                 or telegram_utf16_length(record_text)
2678:                 > TELEGRAM_SINGLE_MESSAGE_LIMIT_UTF16
2679:             ):
2680:                 return False
2681:             canonical_destination = customer_spec.telegram
2682:             supplied_destination = destination if destination is not None else canonical_destination
2683:             supplied_key = tuple(
2684:                 str(getattr(supplied_destination, field, "") or "")
2685:                 for field in ("user_id", "chat_id", "topic_id")
2686:             )
2687:             canonical_key = tuple(
2688:                 str(getattr(canonical_destination, field, "") or "")
2689:                 for field in ("user_id", "chat_id", "topic_id")
2690:             )
2691:             if supplied_key != canonical_key:
2692:                 return False
2693:             history = generations.get(draft_id)
2694:             if history is None:
2695:                 return False
2696:             generation = history[-1]
2697:             if generation.state is not DraftGenerationState.DELIVERY_PENDING:
2698:                 return False
2699:             delivery = deliveries.get(self._delivery_key(draft_id, record_text))
2700:             revision = self._draft_revision(record_text)
2701:             capability = delivery.get("delivery_capability") if isinstance(delivery, dict) else None
2702:             approved_card = delivery.get("approved_card") if isinstance(delivery, dict) else None
2703:             supplied_card_route = self._route_projection(card_route)
2704:             try:
2705:                 expires_at = datetime.fromisoformat(str(capability["expires_at"]))
2706:             except (KeyError, TypeError, ValueError):
2707:                 expires_at = None
2708:             claim_time = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
2709:             if (
2710:                 not isinstance(delivery, dict)
2711:                 or delivery.get("status") != "pending"
2712:                 or delivery.get("customer_key") != customer_key
2713:                 or delivery.get("session_id") != str(record.get("session_id", ""))
2714:                 or delivery.get("text") != record_text
2715:                 or delivery.get("revision") != revision
2716:                 or delivery.get("approved_revision") != record.get("approved_revision")
2717:                 or delivery.get("approved_event_id") != record.get("approved_event_id")
2718:                 or delivery.get("checkin_revision") != generation.checkin_revision
2719:                 or delivery.get("canonical_payload_digest") != revision
2720:                 or delivery.get("provider_user_id") != canonical_key[0]
2721:                 or delivery.get("provider_chat_id") != canonical_key[1]
2722:                 or delivery.get("provider_topic_id") != canonical_key[2]
2723:                 or delivery.get("idempotency_key")
2724:                 != self._delivery_idempotency_key(
2725:                     customer_key,
2726:                     generation.checkin_revision,
2727:                     revision,
2728:                 )
2729:                 or not isinstance(capability, dict)
2730:                 or capability.get("schema") != "draft-delivery-capability-v1"
2731:                 or capability.get("status") != "issued"
2732:                 or not isinstance(approved_card, dict)
2733:                 or approved_card.get("route") != supplied_card_route
2734:                 or approved_card.get("message_id") != card_message_id
2735:                 or approved_card.get("nonce") != card_nonce
2736:                 or approved_card.get("payload_digest") != card_payload_digest
2737:                 or expires_at is None
2738:                 or expires_at.tzinfo is None
2739:                 or claim_time >= expires_at.astimezone(timezone.utc)
2740:                 or not isinstance(capability.get("bindings"), dict)
2741:                 or capability["bindings"].get("customer_route") != {
2742:                     "user_id": canonical_key[0],
2743:                     "chat_id": canonical_key[1],
2744:                     "topic_id": canonical_key[2],
2745:                 }
2746:                 or capability["bindings"].get("owner_route") != self._route_projection(owner)
2747:                 or capability["bindings"].get("draft_id") != draft_id
2748:                 or capability["bindings"].get("generation") != delivery.get("generation")
2749:                 or capability["bindings"].get("generation_record_digest") != delivery.get("generation_record_digest")
2750:                 or capability["bindings"].get("checkin_revision") != generation.checkin_revision
2751:                 or capability["bindings"].get("draft_revision") != generation.draft_revision
2752:                 or capability["bindings"].get("approved_revision") != record.get("approved_revision")
2753:                 or capability["bindings"].get("approved_event_id") != record.get("approved_event_id")
2754:                 or capability["bindings"].get("payload_digest") != revision
2755:                 or capability["bindings"].get("approved_card") != approved_card
2756:                 or any(
2757:                     _DRAFT_GENERATION_DIGEST.fullmatch(
2758:                         str(capability["bindings"].get(field, ""))
2759:                     ) is None
2760:                     for field in (
2761:                         "candidate_digest", "full_digest", "core_digest",
2762:                         "inventory_digest", "manifest_digest", "wheel_digest",
2763:                         "provider_config_digest", "profile_authorization_digest",
2764:                     )
2765:                 )
2766:                 or getattr(self, "_delivery_enabled", False) is not False
2767:                 or not self.customer_transport_allowed(
2768:                     customer_key,
2769:                     canonical_destination,
2770:                     kst_date=kst_date,
2771:                 )
2772:             ):
2773:                 return False
2774:             consumed = dict(delivery)
2775:             consumed["status"] = "unknown_provider_outcome"
2776:             consumed_capability = dict(capability)
2777:             consumed_capability["status"] = "consumed"
2778:             consumed_capability["consumed_at"] = claim_time.isoformat()
2779:             consumed["delivery_capability"] = consumed_capability
2780:             next_deliveries = dict(deliveries)
2781:             next_deliveries[self._delivery_key(draft_id, record_text)] = consumed
2782:             try:
2783:                 self._write_json_private(
2784:                     self._delivery_ledger_path(),
2785:                     next_deliveries,
2786:                 )
2787:             except (OSError, ValueError):
2788:                 return False
2789:             return True
2790:
2791:
2792:     def claim_delivery_transport(
2793:         self,
2794:         draft_id: str,
2795:         owner: IncomingAddress,
2796:         destination: object,
2797:         text: str | None,
2798:         *,
2799:         card_route: IncomingAddress,
2800:         card_message_id: str,
2801:         card_nonce: str,
2802:         card_payload_digest: str,
2803:         now: datetime | None = None,
2804:         kst_date: date | datetime | None = None,
2805:     ) -> DeliveryDispatchClaim | None:
2806:         """Return an opaque claim only after capability consumption is durable."""
2807:         claimed = self.validate_delivery_transport(
2808:             draft_id, owner, destination, text, kst_date=kst_date,
2809:             card_route=card_route, card_message_id=card_message_id,
2810:             card_nonce=card_nonce, card_payload_digest=card_payload_digest, now=now,
2811:         )
2812:         if not claimed:
2813:             return None
2814:         return DeliveryDispatchClaim(hashlib.sha256(
2815:             f"{draft_id}\0{card_message_id}\0{card_nonce}".encode("utf-8")
2816:         ).hexdigest())
2817:
2818:     def record_customer_surface_receipt(
2819:         self,
2820:         claim: DeliveryDispatchClaim,
2821:         draft_id: str,
2822:         destination: object,
2823:         customer_text: str,
2824:         provider_message_id: str | int,
2825:     ) -> CustomerSurfaceReceipt:
2826:         """Corroborate a provider receipt without changing delivery state."""
2827:         message_id = str(provider_message_id).strip()
2828:         if (
2829:             not isinstance(claim, DeliveryDispatchClaim)
2830:             or not message_id
2831:             or len(message_id) > 128
2832:         ):
2833:             raise AdaptiveWorkflowError("customer surface receipt binding is invalid")
2834:         with self._delivery_lock():
2835:             try:
2836:                 deliveries = self._read_deliveries()
2837:                 row = deliveries.get(self._delivery_key(draft_id, customer_text))
2838:                 capability_value = (
2839:                     row.get("delivery_capability") if isinstance(row, dict) else None
2840:                 )
2841:                 capability = (
2842:                     cast(dict[str, object], capability_value)
2843:                     if isinstance(capability_value, dict)
2844:                     else None
2845:                 )
2846:                 bindings_value = capability.get("bindings") if capability is not None else None
2847:                 bindings = (
2848:                     cast(dict[str, object], bindings_value)
2849:                     if isinstance(bindings_value, dict)
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
StopIteration

Command exited with code 1


=== gateway/platforms/telegram_nutrition_onboarding_runtime_authority.py ===
from __future__ import annotations

import importlib
from pathlib import Path
from typing import Any, Protocol, cast

from gateway.platforms.telegram_nutrition_addresses import (
    AddressConfigurationError,
    CustomerPrivateDeliveryAddress,
    StaffReviewAddress,
    StaffReviewRole,
    parse_customer_private_delivery_address,
    parse_staff_review_address,
)
from gateway.platforms.telegram_customer_bootstrap import BootstrapState, Role
from gateway.platforms.telegram_nutrition_onboarding_runtime_errors import (
    NutritionOnboardingRuntimeError,
)

class _BootstrapStore(Protocol):
    def list_sessions(self) -> tuple[Any, ...]: ...

class _BootstrapTransport(Protocol):
    store: _BootstrapStore

class _RuntimeContext(Protocol):
    adapter: Any
    bootstrap: _BootstrapTransport
    domain: Any
    profile_root: Path

class TelegramNutritionOnboardingRuntimeAuthorityMixin:
    def _context(self) -> _RuntimeContext:
        return cast(_RuntimeContext, cast(object, self))

    def _registry_document(self) -> Any:
        module = importlib.import_module("checkin_cli.customer_coaching")
        profile_root = self._context().profile_root
        return module.load_customer_registry(
            profile_root / "customers" / "registry.json",
            profile_root,
        )

    def _registry_owner(self) -> Any:
        return self._registry_document().owner

    def _registry_customer(self, session: Any) -> Any:
        matches = tuple(
            runtime.spec
            for runtime in self._registry_document().customers
            if runtime.spec.customer_key == session.customer_key
        )
        if len(matches) != 1:
            raise NutritionOnboardingRuntimeError(
                "canonical customer registry binding is unavailable"
            )
        return matches[0]

    @staticmethod
    def _customer_address(customer: Any) -> CustomerPrivateDeliveryAddress:
        address = customer.telegram
        try:
            return parse_customer_private_delivery_address(
                {
                    "user_id": address.user_id,
                    "chat_id": address.chat_id,
                    "topic_id": address.topic_id,
                }
            )
        except AddressConfigurationError as exc:
            raise NutritionOnboardingRuntimeError(
                "customer DM binding is unavailable or invalid"
            ) from exc

    @staticmethod
    def _staff_address(
        role: StaffReviewRole,
        address: Any,
    ) -> StaffReviewAddress:
        try:
            return parse_staff_review_address(
                role,
                {
                    "user_id": address.user_id,
                    "chat_id": address.chat_id,
                    "topic_id": address.topic_id,
                },
            )
        except AddressConfigurationError as exc:
            raise NutritionOnboardingRuntimeError(
                f"{role.value} review binding is unavailable or invalid"
            ) from exc

    def _session_for_customer_message(self, message: Any) -> Any | None:
        actor_id = getattr(getattr(message, "from_user", None), "id", None)
        chat_id = getattr(getattr(message, "chat", None), "id", None)
        topic_id = getattr(message, "message_thread_id", None)
        if topic_id is None:
            topic_id = 0
        if type(actor_id) is not int or type(chat_id) is not int:
            return None
        for session in self._context().bootstrap.store.list_sessions():
            if session.state is not BootstrapState.AWAITING_ACTIVATION:
                continue
            try:
                customer = self._registry_customer(session)
                address = self._customer_address(customer)
            except NutritionOnboardingRuntimeError:
                continue
            if (
                address.user_id == actor_id
                and address.chat_id == chat_id
                and address.topic_id == topic_id
            ):
                return session
        return None

    def _authority(self, session: Any) -> Any:
        customer_claim = session.role_claim(Role.CUSTOMER)
        if customer_claim is None or session.owner_id is None:
            raise NutritionOnboardingRuntimeError(
                "bootstrap onboarding authority is incomplete"
            )
        registry_customer = self._registry_customer(session)
        customer = self._customer_address(registry_customer)
        owner = self._registry_owner()
        owner_address = self._staff_address(StaffReviewRole.OWNER, owner)
        if (
            str(customer.user_id) != customer_claim.user_id
            or str(owner_address.user_id) != str(session.owner_id)
        ):
            raise NutritionOnboardingRuntimeError(
                "bootstrap identity and registry authority disagree"
            )
        return self._context().domain.OnboardingAuthority(
            customer_key=session.customer_key,
            customer_user_id=customer.user_id,
            customer_chat_id=customer.chat_id,
            customer_topic_id=customer.topic_id,
            owner_user_id=owner_address.user_id,
            owner_chat_id=owner_address.chat_id,
            owner_topic_id=owner_address.topic_id,
            consent_notice_version="privacy-v1",
            consent_granted=True,
            customer_enabled=False,
        )

    def _current_authority(self, session: Any) -> Any:
        authority = self._authority(session)
        context = self._context()
        context.domain.validate_current_registry_authority(
            context.profile_root,
            authority,
        )
        return authority

    def _route(self, session: Any, role: str) -> tuple[str, str]:
        if role == "customer":
            customer = self._registry_customer(session)
            address = self._customer_address(customer)
            return str(address.chat_id), str(address.topic_id)
        if role == "owner":
            address = self._staff_address(
                StaffReviewRole.OWNER,
                self._registry_owner(),
            )
            return str(address.chat_id), str(address.topic_id)
        raise NutritionOnboardingRuntimeError(
            f"unsupported onboarding route role: {role}"
        )

    def _evidence(
        self,
        *,
        actor_id: Any,
        message: Any,
        update_id: Any,
    ) -> Any:
        chat = getattr(message, "chat", None)
        chat_id = getattr(chat, "id", None)
        if chat_id is None:
            chat_id = getattr(message, "chat_id", None)
        if chat_id is None:
            raise NutritionOnboardingRuntimeError(
                "onboarding message chat is missing"
            )
        topic_id = getattr(message, "message_thread_id", None)
        if topic_id is None:
            topic_id = 0
        return self._context().domain.MessageEvidence(
            actor_user_id=int(actor_id),
            chat_id=int(chat_id),
            topic_id=int(topic_id),
            message_id=int(message.message_id),
            update_id=int(update_id),
        )

    async def _member_present(
        self,
        chat_id: Any,
        actor_id: Any,
    ) -> bool:
        member = await self._context().adapter._bot.get_chat_member(
            chat_id=chat_id,
            user_id=actor_id,
        )
        return str(getattr(member, "status", "")).lower() not in {
            "left",
            "kicked",
        }

=== gateway/platforms/telegram_nutrition_onboarding_runtime_publication.py ===
from __future__ import annotations

import hashlib
import logging
from datetime import date
from typing import Any

from checkin_cli.nutrition_onboarding_clarification_policy import (
    compile_clarification_policy,
)
from checkin_cli.nutrition_onboarding_contract import QUESTION_FIELDS

from gateway.platforms.nutrition_onboarding_reconciliation import (
    ReconciliationError,
    ReconciliationUnavailable,
    NutritionOnboardingClarification,
    reconciliation_payload,
    render_authoritative_customer_summary,
)
from gateway.platforms.nutrition_onboarding_reconciliation_copy import (
    render_clarification_text,
)
from gateway.platforms.telegram_nutrition_onboarding import (
    OPTIONAL_QUESTION_DEFAULTS,
)
from gateway.platforms.telegram_nutrition_onboarding_copy import card
from gateway.platforms.telegram_nutrition_onboarding_runtime_publication_transport import (
    TelegramNutritionOnboardingRuntimePublicationTransportMixin,
    publication_generation,
)

logger = logging.getLogger(__name__)

class TelegramNutritionOnboardingRuntimePublicationMixin(
    TelegramNutritionOnboardingRuntimePublicationTransportMixin
):
    reconciler: Any = None
    adapter: Any

    def _current_authority(self, session: Any) -> Any:
        raise NotImplementedError

    def _route(self, session: Any, role: str) -> tuple[str, str]:
        raise NotImplementedError

    async def _publish(
        self,
        session: Any,
        service: Any,
        status: Any,
        *,
        reply_anchor_message_id: int | None = None,
    ) -> None:
        text, action, role = card(status)
        if status.state.value == "collecting":
            text = (
                f"[{status.answer_count + 1}/{len(QUESTION_FIELDS)}] "
                f"{text}\n\n"
                "입력창이 자동으로 연결됩니다. "
                "그대로 답을 쓰고 전송하세요."
            )
            if status.next_field in OPTIONAL_QUESTION_DEFAULTS:
                text += "\n답변이 없으면 '건너뛰기'라고 입력하세요."
        clarification = None
        revision_binding = None
        answers_digest = None
        if status.state.value == "customer_attestation":
            try:
                authority = self._current_authority(session)
                answers = service.reconciliation_answers(
                    authority=authority
                )
                policy = compile_clarification_policy(
                    answers,
                    reference_date=date.today(),
                )
                answers_digest = policy.answers_digest
                record = service.reconciliation_record(authority=authority)
                stale_answers_digest = None
                if (
                    record is not None
                    and record.get("answers_digest") != answers_digest
                ):
                    stale_answers_digest = str(record["answers_digest"])
                    record = None
                if record is None:
                    try:
                        advisory = await self.reconciler.reconcile(
                            answers,
                            consent_granted=bool(authority.consent_granted),
                        )
                        advisory_payload = reconciliation_payload(advisory)
                    except (ReconciliationError, ReconciliationUnavailable):
                        advisory_payload = {"status": "unavailable"}
                    record_payload = {
                        "answers_digest": answers_digest,
                        "advisory": advisory_payload,
                        "clarifications": [],
                        "authority": authority,
                        "reference_date": policy.reference_date,
                    }
                    if stale_answers_digest is None:
                        service.record_reconciliation(**record_payload)
                    else:
                        service.replace_stale_reconciliation(
                            expected_stale_answers_digest=stale_answers_digest,
                            **record_payload,
                        )
                    record = service.reconciliation_record(authority=authority)
                if record is not None:
                    raw_issues = record.get("issues", [])
                    issues = raw_issues if isinstance(raw_issues, list) else []
                    if record.get("state") == "clarifying" and issues:
                        issue = issues[0]
                        if not isinstance(issue, dict):
                            raise ValueError("persisted reconciliation issue is invalid")
                        clarification = NutritionOnboardingClarification(
                            field=str(issue["field"]),
                            kind="ambiguity",
                            question_ko=str(issue["question_ko"]),
                        )
                        revision_binding = {
                            "issue_id": str(issue["issue_id"]),
                            "field": clarification.field,
                            "answers_digest": answers_digest,
                            "reconciliation_digest": str(record["digest"]),
                        }
                        text = render_clarification_text(
                            clarification,
                            index=1,
                            total=min(len(issues), 3),
                        )
                        action = None
                    elif record.get("state") == "resolved":
                        text = (
                            "입력 내용을 정리했어요\n\n"
                            + render_authoritative_customer_summary(answers)
                            + "\n\n아래 버튼을 누르면 입력 확인이 저장되고 "
                            "운영자 검토로 넘어갑니다.\n"
                            "이 단계에서 영양 코칭이 시작되거나 "
                            "활성화되지는 않습니다."
                        )
            except (
                OSError,
                ValueError,
                ReconciliationError,
                ReconciliationUnavailable,
            ) as exc:
                logger.warning(
                    "Nutrition onboarding advisory summary unavailable: %s",
                    type(exc).__name__,
                )
        digest = hashlib.sha256(text.encode()).hexdigest()
        payload = {"body_digest": digest, "state": status.state.value}
        if status.state.value == "collecting":
            payload["force_reply_mode"] = (
                "anchored"
                if reply_anchor_message_id is not None
                else "broadcast"
            )
        if answers_digest is not None:
            payload["answers_digest"] = answers_digest
        if clarification is not None:
            payload["clarification_field"] = clarification.field
            payload["revision_binding"] = revision_binding
        actions: list[tuple[str, str]] = []
        match status.state.value:
            case "collecting":
                pass
            case "owner_review":
                actions.extend(
                    (
                        ("owner_ok", "Approve"),
                        ("op_rej", "Reject"),
                        ("op_hold", "Safety Hold"),
                    )
                )
            case _ if action == "attest":
                actions.extend(
                    (
                        ("attest", "입력 내용이 맞습니다"),
                        ("revise", "수정"),
                    )
                )
            case (
                "customer_attestation"
                | "safety_hold"
                | "rejected"
                | "finalizing"
                | "ready"
            ):
                pass
            case unexpected:
                raise RuntimeError(f"unsupported onboarding publication state: {unexpected}")
        await self._send_publication(
            session=session,
            service=service,
            status=status,
            text=text,
            role=role,
            payload=payload,
            actions=actions,
            force_reply=(
                status.state.value == "collecting"
                or clarification is not None
            ),
            reply_anchor_message_id=reply_anchor_message_id,
        )

    async def _publish_paused(
        self,
        session: Any,
        service: Any,
        status: Any,
    ) -> None:
        text = (
            "온보딩 진행 위치를 저장했습니다.\n"
            f"현재 진행: {status.answer_count}/{len(QUESTION_FIELDS)}\n"
            "준비되면 아래 버튼을 눌러 같은 온보딩을 이어서 진행해 주세요."
        )
        await self._send_publication(
            session=session,
            service=service,
            status=status,
            text=text,
            role="customer",
            payload={
                "body_digest": hashlib.sha256(text.encode()).hexdigest(),
                "state": status.state.value,
                "mode": "paused",
            },
            actions=[("resume", "계속하기")],
            force_reply=False,
        )

=== gateway/platforms/telegram_nutrition_onboarding_runtime_publication_transport.py ===
from __future__ import annotations

import hashlib
import json
from typing import Any

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

class PublicationReceiptPersistenceError(RuntimeError):
    """A sent Telegram card lacks the durable evidence required for replay."""

def publication_generation(
    status: Any,
    *,
    current: Any | None = None,
    payload: dict[str, Any] | None = None,
) -> int:
    candidate = status.answer_count + {
        "customer_attestation": 1,
        "owner_review": 3,
        "finalizing": 4,
        "ready": 4,
    }.get(status.state.value, 0)
    if current is None:
        return candidate
    if payload is not None and current.payload == payload:
        return current.generation
    return max(candidate, current.generation + 1)

class TelegramNutritionOnboardingRuntimePublicationTransportMixin:
    adapter: Any

    def _route(self, session: Any, role: str) -> tuple[str, str]:
        raise NotImplementedError

    async def _recover_publication_receipts(
        self,
        service: Any,
        *,
        session: Any | None = None,
        expected: GatewayPublicationReceipt | None = None,
    ) -> int:
        """Commit only receipted publications matching current durable authority."""
        outbox = getattr(self, "_publication_outbox", None)
        if not isinstance(outbox, GatewayOnboardingPublicationOutbox):
            return 0
        outbox.reconcile_emergency_receipts()
        recovered = 0
        for receipt in outbox.receipted():
            if (
                receipt.message_id is None
                or expected is not None
                and not self._same_publication_authority(receipt, expected)
                or not self._receipt_route_is_current(receipt, session)
            ):
                continue
            current = self._current_publication(service, receipt.session_id)
            if not self._current_matches_receipt(current, receipt):
                continue
            if getattr(current, "state", None) == "COMMITTED":
                if getattr(current, "message_id", None) != receipt.message_id:
                    continue
            else:
                try:
                    service.store.mark_committed(
                        session_id=receipt.session_id,
                        generation=receipt.generation,
                        message_id=receipt.message_id,
                    )
                except ValueError:
                    current = self._current_publication(service, receipt.session_id)
                    if (
                        not self._current_matches_receipt(current, receipt)
                        or getattr(current, "state", None) != "COMMITTED"
                        or getattr(current, "message_id", None) != receipt.message_id
                    ):
                        continue
            outbox.mark_committed(
                session_id=receipt.session_id,
                generation=receipt.generation,
                payload=receipt.payload,
                route=receipt.route,
                role=receipt.role,
                render_identity=receipt.render_identity,
                message_id=receipt.message_id,
            )
            recovered += 1
        return recovered

    def _receipt_route_is_current(
        self,
        receipt: GatewayPublicationReceipt,
        session: Any | None,
    ) -> bool:
        current_session = session
        if current_session is None:
            bootstrap = getattr(self, "bootstrap", None)
            store = getattr(bootstrap, "store", None)
            get = getattr(store, "get", None)
            if callable(get):
                try:
                    current_session = get(receipt.session_id)
                except (OSError, ValueError):
                    return False
            elif bootstrap is not None:
                return False
        if current_session is None:
            return True
        try:
            return self._route(current_session, receipt.role) == receipt.route
        except (OSError, TypeError, ValueError, AttributeError):
            return False

    @staticmethod
    def _same_publication_authority(
        left: GatewayPublicationReceipt,
        right: GatewayPublicationReceipt,
    ) -> bool:
        return (
            left.session_id == right.session_id
            and left.generation == right.generation
            and left.payload == right.payload
            and left.route == right.route
            and left.role == right.role
            and left.render_identity == right.render_identity
            and left.payload_digest == right.payload_digest
            and left.dispatch_identity == right.dispatch_identity
        )

    @staticmethod
    def _current_matches_receipt(
        current: Any | None,
        receipt: GatewayPublicationReceipt,
    ) -> bool:
        return bool(
            current is not None
            and getattr(current, "generation", None) == receipt.generation
            and getattr(current, "payload", None) == receipt.payload
            and getattr(current, "state", None) in {"PREPARED", "COMMITTED"}
        )

    def _publication_callback_is_current(
        self,
        *,
        session: Any,
        publication: Any,
        role: str,
        message: Any,
    ) -> bool:
        """Require a current signed receipt on the callback's exact route."""
        outbox = getattr(self, "_publication_outbox", None)
        if not isinstance(outbox, GatewayOnboardingPublicationOutbox):
            # Runtime construction always installs the outbox; only
            # transport-less unit seams omit it.
            return True
        chat_id = getattr(getattr(message, "chat", None), "id", None)
        if chat_id is None:
            chat_id = getattr(message, "chat_id", None)
        topic_id = getattr(message, "message_thread_id", None)
        if topic_id is None:
            topic_id = 0
        message_id = getattr(message, "message_id", None)
        if (
            type(chat_id) is not int
            or type(topic_id) is not int
            or type(message_id) is not int
            or message_id <= 0
        ):
            return False
        try:
            route = self._route(session, role)
            if route != (str(chat_id), str(topic_id)):
                return False
            matches = tuple(
                receipt
                for receipt in outbox.records()
                if (
                    receipt.session_id == str(session.session_id)
                    and receipt.generation == publication.generation
                    and receipt.payload == publication.payload
                    and receipt.route == route
                    and receipt.role == role
                    and receipt.message_id == message_id
                    and receipt.state in {"RECEIPTED", "COMMITTED"}
                )
            )
        except (OSError, ValueError, TypeError, AttributeError):
            return False
        return len(matches) == 1

    @staticmethod
    def _current_publication(
        service: Any,
        session_id: str,
    ) -> Any | None:
        try:
            return service.store.load_session(session_id)
        except ValueError:
            return None

    @staticmethod
    def _render_identity(
        *,
        session: Any,
        generation: int,
        route: tuple[str, str],
        text: str,
        role: str,
        payload: dict[str, Any],
        actions: list[tuple[str, str]],
        force_reply: bool,
        reply_anchor_message_id: int | None,
    ) -> str:
        try:
            canonical = json.dumps(
                {
                    "session_id": str(session.session_id),
                    "sid_hash": str(session.sid_hash),
                    "generation": generation,
                    "route": list(route),
                    "text": text,
                    "role": role,
                    "payload": payload,
                    "actions": [list(action) for action in actions],
                    "force_reply": force_reply,
                    "reply_anchor_message_id": reply_anchor_message_id,
                },
                ensure_ascii=False,
                sort_keys=True,
                separators=(",", ":"),
                allow_nan=False,
            )
        except (AttributeError, TypeError, ValueError) as exc:
            raise PublicationReceiptPersistenceError(
                "onboarding publication render identity is unavailable"
            ) from exc
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()

    @staticmethod
    def _message_id(sent: Any) -> int:
        message_id = getattr(sent, "message_id", None)
        if type(message_id) is not int or isinstance(message_id, bool) or message_id <= 0:
            raise PublicationReceiptPersistenceError(
                "Telegram publication returned no authoritative message ID"
            )
        return message_id

    @staticmethod
    def _mark_unknown(service: Any, session_id: str, generation: int) -> None:
        try:
            service.store.mark_uncertain(
                session_id=session_id,
                generation=generation,
            )
        except ValueError:
            pass

    async def _send_publication(
        self,
        *,
        session: Any,
        service: Any,
        status: Any,
        text: str,
        role: str,
        payload: dict[str, Any],
        actions: list[tuple[str, str]],
        force_reply: bool,
        reply_anchor_message_id: int | None = None,
    ) -> None:
        current = self._current_publication(service, str(session.session_id))
        route = self._route(session, role)
        generation = publication_generation(
            status,
            current=current,
            payload=payload,
        )
        render_identity = self._render_identity(
            session=session,
            generation=generation,
            route=route,
            text=text,
            role=role,
            payload=payload,
            actions=actions,
            force_reply=force_reply,
            reply_anchor_message_id=reply_anchor_message_id,
        )
        prepared_from_existing_record = False
        try:
            prepared = service.store.mark_prepared(
                session_id=session.session_id,
                generation=generation,
                payload=payload,
            )
        except ValueError:
            prepared_from_existing_record = True
            prepared = self._current_publication(service, str(session.session_id))
            if (
                prepared is None
                or getattr(prepared, "generation", None) != generation
                or getattr(prepared, "payload", None) != payload
                or getattr(prepared, "state", None) != "PREPARED"
            ):
                return
        if prepared.state in {"COMMITTED", "UNCERTAIN"}:
            return
        outbox = getattr(self, "_publication_outbox", None)
        receipt: GatewayPublicationReceipt | None = None
        dispatch = True
        if isinstance(outbox, GatewayOnboardingPublicationOutbox):
            outbox.reconcile_emergency_receipts()
            if prepared_from_existing_record:
                receipt = outbox.get(
                    session_id=session.session_id,
                    generation=generation,
                    payload=payload,
                    route=route,
                    role=role,
                    render_identity=render_identity,
                )
                if receipt is None:
                    self._mark_unknown(service, session.session_id, generation)
                    return
                dispatch = False
            else:
                receipt, dispatch = outbox.claim(
                    session_id=session.session_id,
                    generation=generation,
                    payload=payload,
                    route=route,
                    role=role,
                    render_identity=render_identity,
                )
            if not dispatch:
                if receipt.state == "RECEIPTED":
                    await self._recover_publication_receipts(
                        service,
                        session=session,
                        expected=receipt,
                    )
                elif receipt.state == "DISPATCHING":
                    self._mark_unknown(service, session.session_id, generation)
                return
        kwargs: dict[str, Any] = {"text": text}
        if force_reply:
            from telegram import ForceReply, ReplyParameters

            kwargs["reply_markup"] = ForceReply(
                selective=reply_anchor_message_id is not None,
                input_field_placeholder="답변을 입력하세요",
            )
            if reply_anchor_message_id is not None:
                kwargs["reply_parameters"] = ReplyParameters(
                    message_id=int(reply_anchor_message_id),
                )
        elif actions:
            from telegram import InlineKeyboardButton, InlineKeyboardMarkup

            kwargs["reply_markup"] = InlineKeyboardMarkup(
                [
                    [
                        InlineKeyboardButton(
                            label,
                            callback_data=encode_callback_hash(
                                action=action,
                                generation=generation,
                                sid_hash=session.sid_hash,
                            ),
                        )
                        for action, label in actions
                    ]
                ]
            )
        try:
            sent = await self.adapter._send_nutrition_topic(
                chat_id=route[0],
                topic_id=route[1],
                **kwargs,
            )
        except (OSError, RuntimeError, TypeError, ValueError):
            self._mark_unknown(service, session.session_id, generation)
            raise
        try:
            message_id = self._message_id(sent)
        except PublicationReceiptPersistenceError:
            self._mark_unknown(service, session.session_id, generation)
            raise
        if isinstance(outbox, GatewayOnboardingPublicationOutbox):
            if receipt is None:
                raise PublicationReceiptPersistenceError(
                    "onboarding publication outbox is unavailable"
                )
            try:
                outbox.record_receipt(
                    session_id=session.session_id,
                    generation=generation,
                    chat_id=route[0],
                    topic_id=route[1],
                    message_id=message_id,
                )
            except (OSError, ValueError) as primary_error:
                try:
                    outbox.record_emergency_receipt(
                        session_id=session.session_id,
                        generation=generation,
                        chat_id=route[0],
                        topic_id=route[1],
                        message_id=message_id,
                    )
                except (OSError, ValueError) as emergency_error:
                    self._mark_unknown(service, session.session_id, generation)
                    raise PublicationReceiptPersistenceError(
                        "primary and emergency publication receipt persistence failed"
                    ) from emergency_error
                try:
                    outbox.reconcile_emergency_receipts()
                except (OSError, ValueError) as merge_error:
                    raise PublicationReceiptPersistenceError(
                        "emergency publication receipt persisted but primary reconciliation failed"
                    ) from merge_error
        service.store.mark_committed(
            session_id=session.session_id,
            generation=generation,
            message_id=message_id,
        )
        if isinstance(outbox, GatewayOnboardingPublicationOutbox):
            outbox.mark_committed(
                session_id=session.session_id,
                generation=generation,
                payload=payload,
                route=route,
                role=role,
                render_identity=render_identity,
                message_id=message_id,
            )


Summary:
No prior history.

---

**Turn Context (split turn):**

## Original Request
Audit Task26 candidate `310632f...fd648` and v10/postfreeze receipts offline/read-only. Return PASS/FAIL/INCONCLUSIVE with threat evidence/blockers under the stated trusted-host/toolchain/sealed-wheel boundary.

## Early Progress
- Working directory is not a Git repository; audit target found under `.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10`.
- Identified paired postfreeze receipts directory: `...-v10-postfreeze-receipts`.
- Inspected bundle tree, permissions, seals, authority registry/ledger, wheelhouse inventory, installed/source evidence, verifier tools, and packaged wheels.
- Candidate binds digest `310632f...fd648`; v10 candidate/SEAL and postfreeze SEAL were independently recomputed as internally consistent, with exact inventories and zero symlinks.
- Wheelhouse inspection found 107 declared and 107 actual wheels; no extra/missing names or symlinks in the inspected top-level wheelhouse.
- Evidence receipt chain contains the seven required Task26 clauses, ordered and hash-linked, including ambiguity handling, projection gate, unknown-delivery/no-retry, lifecycle, and cleanup terminal state.
- Security-test logs report `9 passed, 7 deselected`, but also contain pytest cleanup warnings (`rm_rf` / directory-not-empty), requiring assessment rather than treating the log as unqualified proof.

## Context for Suffix
- Verifier executable is mode `0400`, so direct execution failed; invoking via Python is required.
- `/usr/bin/python3` is Python 3.13 and verifier failed there with `missing dependency: audioop-lts`; selected trusted toolchain exists at `/home/cube/miniconda3/bin/python3.12` (3.12.9). Original isolated runtime cache is absent.
- Relevant artifacts:
  - `verification-tools/independent_verify_candidate.py`
  - `verification-tools/verify_source_golden_path.py`
  - `verification-tools/installed_wheel_provenance.py`
  - packaged Hermes/Profile wheels under `artifacts/`
  - authority code at `gateway/platforms/task26_candidate_authority.py`
  - dnotify observer at `gateway/commit_observer.py`
- The verifier/source code includes checks for frozen modes, ownership, symlinks, exact receipt inventory/chain, wheel metadata and recursive wheelhouse integrity, isolated CWD/PYTHONPATH and pip environment, module origins, authority lineage, and rehydration cleanup.
- Potential privacy scan found only keyword matches in retained evidence/provenance and delivery records; no value-level secret disclosure conclusion has yet been made.

<read-files>
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/SEAL.json
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/candidate.json
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/gateway/commit_observer.py
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/gateway/platforms/task26_candidate_authority.py
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/gateway/platforms/task26_evidence_contract.py
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/gateway/platforms/task26_final_state.py
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/sealed-expected-state.json
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/independent_verify_candidate.py
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/installed_wheel_provenance.py
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/verify_source_golden_path.py
</read-files>


**Ensuring mandatory response routing line**

**Assessing CLI usage for offline verifier**

I read this as an offline, read-only security audit - I’m completing independent verification from an ephemeral runtime and will report a verdict with any evidence limitations.

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
find "$ROOT" -maxdepth 3 -type f \( -name '*rehydrat*' -o -name '*install*' -o -name '*verify*' \) -printf '%p\n' | sort
printf '%s\n' '--- candidate and receipt identities ---'
/home/cube/miniconda3/bin/python3.12 -I - "$ROOT" <<'PY'
import json,sys
from pathlib import Path
root=Path(sys.argv[1])
for p in [root/'candidate.json',root/'SEAL.json',root.with_name(root.name+'-postfreeze-receipts')/'SEAL.json']:
 print(p, json.loads(p.read_text()).get('candidate_digest'), json.loads(p.read_text()).get('seal_digest'))
PY

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
/home/cube/miniconda3/bin/python3.12 -I - "$ROOT" <<'PY'
import sys,zipfile
from pathlib import Path
z=zipfile.ZipFile(Path(sys.argv[1])/'artifacts'/'hermes_agent-0.17.0-py3-none-any.whl')
for n in z.namelist():
 if n.endswith('.py') and ('delivery' in n.lower() or 'transport' in n.lower()): print(n)
PY

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
printf '%s\n' '--- v10/postfreeze inventory and permissions ---'
stat -c '%a %U:%G %n' "$ROOT" "$ROOT"/SEAL.json "$ROOT"/candidate.json "$ROOT"/wheelhouse "$ROOT"/artifacts
find "$ROOT" -type l -printf 'SYMLINK %p -> %l\n'
POST="$ROOT-postfreeze-receipts"
stat -c '%a %U:%G %n' "$POST" "$POST"/SEAL.json
find "$POST" -type l -printf 'SYMLINK %p -> %l\n'
printf '%s\n' '--- externally writable paths ---'
find "$ROOT" "$POST" -xdev -perm -0002 -printf '%m %p\n'


#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import os
import stat
import sys
from pathlib import Path
from typing import Any, cast

def canonical(value: object) -> bytes:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()

def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()

def document(path: Path, label: str) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
        raise ValueError(f"{label} is invalid")
    return cast(dict[str, Any], value)

def load_module(path: Path, name: str) -> Any:
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ValueError(f"module unavailable: {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

def verify_modes(bundle: Path, *, allow_mutable: bool) -> None:
    for path in (bundle, *sorted(bundle.rglob("*"))):
        info = path.lstat()
        if stat.S_ISLNK(info.st_mode) or info.st_uid != os.geteuid():
            raise ValueError(f"unsafe bundle path: {path}")
        if path.is_dir():
            allowed = {0o500, 0o700} if allow_mutable else {0o500}
        elif path.is_file() and info.st_nlink == 1:
            allowed = {0o400, 0o600} if allow_mutable else {0o400}
        else:
            raise ValueError(f"bundle path type is invalid: {path}")
        if stat.S_IMODE(info.st_mode) not in allowed:
            raise ValueError(f"bundle mode is not frozen: {path}")

def verify(bundle: Path, runtime_path: Path | None, *, allow_mutable: bool) -> dict[str, object]:
    bundle = bundle.absolute()
    verify_modes(bundle, allow_mutable=allow_mutable)
    candidate = document(bundle / "candidate.json", "candidate manifest")
    unsigned_candidate = {key: value for key, value in candidate.items() if key != "document_sha256"}
    if candidate.get("document_sha256") != hashlib.sha256(canonical(unsigned_candidate)).hexdigest():
        raise ValueError("candidate manifest digest is invalid")
    candidate_digest = str(candidate.get("candidate_digest", ""))
    authority_module = load_module(bundle / "gateway/platforms/task26_candidate_authority.py", "sealed_task26_authority")
    authority = authority_module.verify_candidate_authority(bundle, candidate_digest)
    expected_heads = {
        "registry_head_sha256": candidate.get("authority_registry_head_sha256"),
        "ledger_head_sha256": candidate.get("authority_ledger_head_sha256"),
    }
    if any(authority.get(key) != value for key, value in expected_heads.items()):
        raise ValueError("candidate authority heads differ from manifest")
    expected = document(bundle / "sealed-expected-state.json", "sealed expected state")
    final_state_module = load_module(
        bundle / "gateway/platforms/task26_final_state.py", "sealed_task26_final_state"
    )
    hermes_wheel = next((bundle / "artifacts").glob("hermes_agent-*.whl"))
    profile_wheel = next((bundle / "artifacts").glob("physique_checkin_cli-*.whl"))
    final_state_module.verify_expected_state(
        bundle,
        bundle / "sealed-expected-state.json",
        hermes_wheel=hermes_wheel,
        profile_wheel=profile_wheel,
    )
    wheelhouse = final_state_module.verify_wheelhouse_inventory(
        bundle / "wheelhouse",
        expected.get("wheelhouse"),
        required_wheels=(profile_wheel, hermes_wheel),
    )
    ledger_ready = document(bundle / "ledger-ready-receipt.json", "ledger-ready receipt")
    if ledger_ready.get("document_sha256") != hashlib.sha256(canonical({key: value for key, value in ledger_ready.items() if key != "document_sha256"})).hexdigest():
        raise ValueError("ledger-ready receipt digest is invalid")
    if ledger_ready != {
        "schema": "task26-ledger-ready-receipt-v1",
        "candidate_digest": candidate_digest,
        "registry_head_sha256": authority["registry_head_sha256"],
        "ledger_head_sha256": authority["ledger_head_sha256"],
        "expected_state_sha256": sha256_file(bundle / "sealed-expected-state.json"),
        "document_sha256": ledger_ready["document_sha256"],
    }:
        raise ValueError("ledger-ready receipt binding is invalid")
    if candidate.get("expected_state_sha256") != sha256_file(bundle / "sealed-expected-state.json") or candidate.get("ledger_ready_sha256") != sha256_file(bundle / "ledger-ready-receipt.json"):
        raise ValueError("candidate final-state binding is invalid")
    excluded = {"candidate.json", "SEAL.json"}
    actual = [
        {"path": path.relative_to(bundle).as_posix(), "sha256": sha256_file(path), "size": path.stat().st_size}
        for path in sorted(bundle.rglob("*"))
        if path.is_file() and path.relative_to(bundle).as_posix() not in excluded
    ]
    if actual != candidate.get("evidence_inventory"):
        raise ValueError("candidate evidence inventory differs")
    seal = document(bundle / "SEAL.json", "bundle seal")
    unsigned_seal = {key: value for key, value in seal.items() if key != "document_sha256"}
    if seal.get("document_sha256") != hashlib.sha256(canonical(unsigned_seal)).hexdigest() or seal.get("candidate_manifest_sha256") != sha256_file(bundle / "candidate.json") or seal.get("candidate_digest") != candidate_digest or seal.get("registry_head_sha256") != authority["registry_head_sha256"] or seal.get("ledger_head_sha256") != authority["ledger_head_sha256"]:
        raise ValueError("bundle seal binding is invalid")
    verifier_module = load_module(bundle / "verification-tools/verify_source_golden_path.py", "sealed_golden_verifier")
    contract = verifier_module.verify_task26_contract(bundle / "installed-golden-bundle")
    installed_receipt = document(bundle / "receipts/installed-golden-verifier-1.json", "installed Golden receipt")
    if contract != installed_receipt.get("task26_contract") or installed_receipt.get("candidate_digest") != candidate_digest:
        raise ValueError("installed seven-clause receipt differs")
    observer = {
        "backend": installed_receipt.get("observer_backend"),
        "directory_resource_count": installed_receipt.get("observer_directory_resource_count"),
        "inotify_watch_count": installed_receipt.get("observer_inotify_watch_count"),
        "receipt_count": installed_receipt.get("observer_receipt_count"),
    }
    if observer != {
        "backend": "dnotify_signalfd_v1",
        "directory_resource_count": 1,
        "inotify_watch_count": 0,
        "receipt_count": 5,
    }:
        raise ValueError("zero-inotify observer receipt differs")
    rehydrated = False
    if runtime_path is not None:
        runtime = verifier_module.read_private_json(runtime_path)
        verified = verifier_module.verify(bundle / "installed-golden-bundle", runtime_override=runtime)
        if verified.get("status") != "ACTUAL_INSTALLED_GOLDEN_PATH_PASS" or verified.get("candidate_digest") != candidate_digest or verified.get("task26_contract") != contract:
            raise ValueError("rehydrated installed Golden verification differs")
        rehydrated = True
    result = {
        "status": "TASK26_FROZEN_CANDIDATE_PASS",
        "candidate_digest": candidate_digest,
        "product_digest": candidate.get("product_digest"),
        "golden_runtime_digest": candidate.get("golden_runtime_digest"),
        "candidate_authority": authority,
        "installed_task26_contract": contract,
        "observer": observer,
        "isolated_execution": expected["runtime_portable"]["origin_proof"]["execution"],
        "installed_origin_proof": expected["runtime_portable"]["origin_proof"],
        "trust_boundary": expected["trust_boundary"],
        "wheelhouse_inventory_sha256": wheelhouse["inventory_sha256"],
        "wheelhouse_entry_count": len(wheelhouse["entries"]),
        "frozen_modes_verified": not allow_mutable,
        "rehydrated_runtime_verified": rehydrated,
    }
    if runtime_path is not None and expected.get("candidate_digest") != candidate_digest:
        raise ValueError("sealed expected state candidate differs")
    return result

def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("bundle", type=Path)
    parser.add_argument("--rehydrated-runtime", type=Path)
    parser.add_argument("--allow-mutable", action="store_true")
    args = parser.parse_args()
    try:
        result = verify(args.bundle, args.rehydrated_runtime, allow_mutable=args.allow_mutable)
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        print(json.dumps({"status": "TASK26_FROZEN_CANDIDATE_FAIL", "reason": str(exc)}, sort_keys=True), file=sys.stderr)
        return 1
    print(json.dumps(result, ensure_ascii=False, sort_keys=True, separators=(",", ":")))
    return 0

if __name__ == "__main__":
    raise SystemExit(main())


#!/usr/bin/env python3
"""Verify a source Golden Path from native production artifacts only."""
from __future__ import annotations

import argparse
import hashlib
import importlib
import importlib.util
import json
import os
import stat
import sys
from collections.abc import Mapping
from datetime import date
from pathlib import Path
from typing import Any, cast

_PROVENANCE_SPEC = importlib.util.spec_from_file_location(
    "golden_verifier_installed_wheel_provenance",
    Path(__file__).with_name("installed_wheel_provenance.py"),
)
if _PROVENANCE_SPEC is None or _PROVENANCE_SPEC.loader is None:
    raise RuntimeError("installed provenance helper is unavailable")
_PROVENANCE_MODULE = importlib.util.module_from_spec(_PROVENANCE_SPEC)
_PROVENANCE_SPEC.loader.exec_module(_PROVENANCE_MODULE)
collect_installed_runtime = _PROVENANCE_MODULE.collect_installed_runtime
loaded_module_receipts = _PROVENANCE_MODULE.loaded_module_receipts
read_private_json = _PROVENANCE_MODULE.read_private_json
portable_installed_runtime = _PROVENANCE_MODULE.portable_installed_runtime

DEFAULT_SOURCE = Path("/home/cube/.cache/task26-strict-successor-1786976146/src-p")
TASK26_CLAUSES = (
    "onboarding_22_clear",
    "deterministic_ambiguity_revision",
    "preview_isolation",
    "approved_card_projection_gate",
    "unknown_delivery_no_retry",
    "successful_lifecycle",
    "cleanup_resume_terminal",
)
TASK26_ANSWERS = (
    "1990년 1월 15일입니다.", "남성입니다.", "키는 180cm입니다.",
    "현재 체중은 80kg입니다.", "보통 수준입니다.",
    "주 3회 60분 근력 운동을 하고 평일에는 하루 8천 보 정도 걷습니다.",
    "현재 체중을 유지하고 싶습니다.",
    "유지가 목표라 목표 체중은 정하지 않겠습니다.",
    "유지가 목표라 목표 날짜도 정하지 않겠습니다.",
    "음식 알레르기는 없습니다.", "음식 불내증은 없습니다.",
    "종교적 또는 윤리적으로 제외하는 음식은 없습니다.",
    "싫어해서 피하는 음식은 없습니다.", "특별한 식단 선호는 없습니다.",
    "진단받은 질환은 없습니다.", "복용 중인 약이나 보충제는 없습니다.",
    "임신 또는 수유에 해당하지 않습니다.",
    "섭식장애 위험이나 과거력은 없습니다.",
    "가스레인지, 전자레인지, 냉장고를 사용할 수 있고 기본 조리가 가능합니다.",
    "식비 예산은 보통입니다.", "하루 세 끼를 먹습니다.",
    "평일 점심은 12시, 저녁은 운동 후 8시쯤이며 그 외 제약은 없습니다.",
)
PHASES = (
    "OBSERVER_SUBSCRIBED", "INVITE_RECEIPTED", "CONSENT_COMMITTED",
    "ONBOARDING_22_COMMITTED", "RECONCILIATION_COMMITTED", "CUSTOMER_ATTESTED",
    "OWNER_REVIEW_PUBLISHED", "READY_DISABLED", "ACTIVATED", "CHECKIN_FINALIZED",
    "GENERATION_DRAFTED", "OWNER_APPROVED", "APPROVED_CARD_PROJECTED",
    "CAPABILITY_ISSUED", "CAPABILITY_CONSUMED", "SENT_AUDITED",
    "SURFACE_CAPTURED", "QUIESCED", "ARCHIVED", "CLEANUP_COMPLETE",
    "SOURCE_GOLDEN_PATH_PASS",
)
ZERO = "0" * 64
TERMINAL_CATEGORY_FIELDS = frozenset(
    {
        "registry",
        "bootstrap",
        "onboarding",
        "outbox",
        "key",
        "owner_action",
        "service_state",
        "event",
        "customer_data",
        "activation",
        "sent_event",
        "candidate",
    }
)
TERMINAL_INVENTORY_FIELDS = frozenset(
    {
        "customer_key",
        "disabled",
        "nonconsenting",
        "categories",
        "active_count",
        "pending_count",
        "unknown_count",
        "orphan_count",
        "archive_verified",
        "journal_committed",
        "terminal",
    }
)

def canonical(value: object, *, ascii_only: bool = False) -> bytes:
    return json.dumps(value, ensure_ascii=ascii_only, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()

def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()

def obj(value: object, label: str) -> dict[str, Any]:
    if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
        raise ValueError(f"{label} is not an object")
    return cast(dict[str, Any], value)

def read_json(path: Path, label: str) -> dict[str, Any]:
    return obj(json.loads(path.read_text(encoding="utf-8")), label)

def serialize_terminal_inventory(terminal: object) -> dict[str, object]:
    fields = getattr(type(terminal), "__dataclass_fields__", None)
    if not isinstance(fields, dict) or set(fields) != TERMINAL_INVENTORY_FIELDS:
        raise ValueError("terminal inventory schema is invalid")
    customer_key = getattr(terminal, "customer_key", None)
    disabled = getattr(terminal, "disabled", None)
    nonconsenting = getattr(terminal, "nonconsenting", None)
    raw_categories = getattr(terminal, "categories", None)
    if not isinstance(raw_categories, Mapping):
        raise ValueError("terminal inventory categories are invalid")
    categories = dict(raw_categories)
    counts = {
        name: getattr(terminal, name, None)
        for name in (
            "active_count",
            "pending_count",
            "unknown_count",
            "orphan_count",
        )
    }
    booleans = {
        name: getattr(terminal, name, None)

[1026 more lines in file. Use offset=141 to continue.]


agent/transports/__init__.py
agent/transports/anthropic.py
agent/transports/base.py
agent/transports/bedrock.py
agent/transports/chat_completions.py
agent/transports/codex.py
agent/transports/codex_app_server.py
agent/transports/codex_app_server_session.py
agent/transports/codex_event_projector.py
agent/transports/hermes_tools_mcp_server.py
agent/transports/types.py
gateway/delivery.py
gateway/platforms/telegram_nutrition_onboarding_runtime_publication_transport.py
gateway/relay/transport.py
gateway/relay/ws_transport.py
tui_gateway/transport.py


--- v10/postfreeze inventory and permissions ---
500 cube:cube .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
400 cube:cube .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/SEAL.json
400 cube:cube .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/candidate.json
500 cube:cube .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/wheelhouse
500 cube:cube .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts
500 cube:cube .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10-postfreeze-receipts
400 cube:cube .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10-postfreeze-receipts/SEAL.json
--- externally writable paths ---


**Inspecting runtime rehydration verification**

V=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/verify_source_golden_path.py
rg -n -C 4 'def verify\(|runtime_override|portable_installed_runtime|collect_installed_runtime|read_private_json|sys\.path|PYTHON' "$V"

P=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/verification-tools/installed_wheel_provenance.py
rg -n -C 4 'def (collect_installed_runtime|portable_installed_runtime|read_private_json|loaded_module_receipts)|sys\.path|site-packages|wheel' "$P"

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
/home/cube/miniconda3/bin/python3.12 -I - "$ROOT" <<'PY'
import json,sys
from pathlib import Path
root=Path(sys.argv[1]); r=json.loads((root/'receipts'/'rehydrated-expected.json').read_text()); print(json.dumps(r,indent=2,ensure_ascii=False)[:20000])
PY


Coherent compromise of the trusted operator account or host administrator, including coherent modification of the repository, ledger, or verifier, is outside the Task26 threat model.

These guarantees apply only while the trusted operator account, host kernel, selected Python/pip toolchain, and sealed wheel bytes remain trustworthy.


[Line 1 is 330.8KB, exceeds 50.0KB limit. Use bash: sed -n '1p' .omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/installed-golden-bundle/installed-provenance.json | head -c 51200]


22-if _PROVENANCE_SPEC is None or _PROVENANCE_SPEC.loader is None:
23-    raise RuntimeError("installed provenance helper is unavailable")
24-_PROVENANCE_MODULE = importlib.util.module_from_spec(_PROVENANCE_SPEC)
25-_PROVENANCE_SPEC.loader.exec_module(_PROVENANCE_MODULE)
26:collect_installed_runtime = _PROVENANCE_MODULE.collect_installed_runtime
27-loaded_module_receipts = _PROVENANCE_MODULE.loaded_module_receipts
28:read_private_json = _PROVENANCE_MODULE.read_private_json
29:portable_installed_runtime = _PROVENANCE_MODULE.portable_installed_runtime
30-
31-DEFAULT_SOURCE = Path("/home/cube/.cache/task26-strict-successor-1786976146/src-p")
32-TASK26_CLAUSES = (
33-    "onboarding_22_clear",
--
262-def verify_installed_provenance(
263-    root: Path,
264-    source_provenance: dict[str, Any],
265-    *,
266:    runtime_override: dict[str, object] | None = None,
267-) -> tuple[str, Path]:
268-    path = root / "installed-provenance.json"
269:    document = read_private_json(path)
270-    if set(document) != {"schema", "binding", "candidate_digest", "loaded_modules"} or document.get("schema") != "installed-golden-provenance-v1":
271-        raise ValueError("installed provenance schema is invalid")
272-    binding = obj(document.get("binding"), "installed candidate binding")
273-    if binding.get("schema") != "installed-golden-candidate-binding-v1":
--
287-        "verifier_sha256": sha(Path(__file__)),
288-        "task26_contract_module": "gateway.platforms.task26_evidence_contract",
289-        "task26_contract_module_sha256": (
290-            str(binding.get("task26_contract_module_sha256", ""))
291:            if runtime_override is not None
292-            else sha(
293-                Path(str(config.get("profile_package_authority", "")))
294-                / "gateway/platforms/task26_evidence_contract.py"
295-            )
--
313-        or parity.get("sha256") != contract_rows[0].get("sha256")
314-        or parity.get("size") != contract_rows[0].get("size")
315-        or parity.get("wheel_path") != hermes.get("wheel_path")
316-        or (
317:            runtime_override is None
318-            and parity.get("installed_path") != str(installed_contract.resolve(strict=True))
319-        )
320-    ):
321-        raise ValueError("Task26 source-wheel-installed parity binding is invalid")
322:    active_runtime = runtime if runtime_override is None else runtime_override
323-    active_distributions = obj(active_runtime.get("distributions"), "active installed distributions")
324-    active_profile = obj(active_distributions.get("profile"), "active profile distribution")
325-    active_hermes = obj(active_distributions.get("hermes"), "active Hermes distribution")
326:    recomputed = collect_installed_runtime(
327-        venv=Path(str(active_runtime.get("venv", ""))),
328-        site_packages=Path(str(active_runtime.get("site_packages", ""))),
329-        profile_wheel=Path(str(active_profile.get("wheel_path", ""))),
330-        hermes_wheel=Path(str(active_hermes.get("wheel_path", ""))),
--
335-        if key != "origin_proof"
336-    }
337-    if recomputed != active_runtime_core:
338-        raise ValueError("installed runtime receipt differs from installed bytes")
339:    if runtime_override is None:
340-        if recomputed != runtime:
341-            raise ValueError("installed runtime receipt differs from original installed bytes")
342:    elif portable_installed_runtime(recomputed) != binding.get("runtime_portable"):
343-        raise ValueError("rehydrated runtime differs from sealed portable binding")
344-    roots = tuple(
345-        Path(root_path)
346-        for distribution in (active_profile, active_hermes)
--
365-        if not isinstance(origin, str):
366-            raise ValueError(f"installed loaded-module origin is unavailable: {name}")
367-        actual_modules[name] = Path(origin)
368-    actual_receipts = loaded_module_receipts(actual_modules, allowed_roots=roots)
369:    if runtime_override is None:
370-        if actual_receipts != declarations:
371-            raise ValueError("installed loaded-module declarations differ from import reality")
372-    else:
373-        portable_declarations = [
--
380-        ]
381-        if portable_actual != portable_declarations:
382-            raise ValueError("rehydrated import origins differ from sealed module bytes")
383-    authority = config.get("profile_package_authority")
384:    if runtime_override is None:
385-        if not isinstance(authority, str) or Path(authority).resolve(strict=True) != Path(str(runtime["site_packages"])):
386-            raise ValueError("installed profile package authority is invalid")
387-        active_authority = Path(authority)
388-    else:
--
1059-        "terminal": True,
1060-    }
1061-
1062-
1063:def verify(
1064:    root: Path, *, runtime_override: dict[str, object] | None = None
1065-) -> dict[str, object]:
1066-    root = root.absolute()
1067-    private(root, directory=True)
1068-    if (root / "lifecycle-events.jsonl").exists():
1069-        raise ValueError("self-authored lifecycle/PASS declarations are forbidden")
1070-    source_candidate, source = verify_provenance(
1071:        root, offline_recorded_source=runtime_override is not None
1072-    )
1073-    source_document = read_json(root / "source-provenance.json", "source provenance")
1074-    input_doc = read_json(root / "driver-input.json", "driver input")
1075-    runtime_mode = input_doc.get("runtime_mode", "source")
1076-    if runtime_mode == "installed":
1077-        candidate, authority_root = verify_installed_provenance(
1078:            root, source_document, runtime_override=runtime_override
1079-        )
1080-    elif runtime_mode == "source":
1081-        candidate, authority_root = source_candidate, source
1082-        source_text = str(source)
1083:        if source_text not in sys.path:
1084:            sys.path.insert(0, source_text)
1085-    else:
1086-        raise ValueError("driver runtime mode is invalid")
1087-    observer = verify_observer(root, candidate)
1088-    customer = input_doc.get("customer_key")
--
1148-    parser.add_argument("bundle", type=Path)
1149-    parser.add_argument("--rehydrated-runtime", type=Path)
1150-    args = parser.parse_args()
1151-    try:
1152:        runtime_override = (
1153:            read_private_json(args.rehydrated_runtime)
1154-            if args.rehydrated_runtime is not None
1155-            else None
1156-        )
1157:        print(json.dumps(verify(args.bundle, runtime_override=runtime_override), sort_keys=True, separators=(",", ":")))
1158-    except (OSError, ValueError, json.JSONDecodeError) as exc:
1159-        print(json.dumps({"status": "SOURCE_GOLDEN_PATH_FAIL", "reason": str(exc)}, sort_keys=True), file=sys.stderr)
1160-        return 1
1161-    return 0


63-    if stat.S_IMODE(info.st_mode) not in {0o700, 0o500}:
64-        raise ValueError(f"{label} permissions are not private")
65-
66-
67:def read_private_json(path: Path) -> dict[str, Any]:
68-    _regular(path, "provenance", private=True)
69-    value = json.loads(path.read_text(encoding="utf-8"))
70-    if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
71-        raise ValueError("provenance is not an object")
--
113-        raise ValueError(f"{label} RECORD self-row is missing")
114-    return rows
115-
116-
117:def _wheel_inventory(
118:    wheel: Path,
119-    dist_info_name: str,
120-    installed_rows: Sequence[tuple[str, str, int | None]],
121-    label: str,
122-    *,
123-    site_packages: Path,
124-    venv: Path,
125-) -> str:
126:    _regular(wheel, f"{label} wheel", private=True)
127-    try:
128:        with zipfile.ZipFile(wheel) as archive:
129-            names = archive.namelist()
130-            if len(names) != len(set(names)) or any(name.startswith("/") or ".." in Path(name).parts for name in names):
131:                raise ValueError(f"{label} wheel members are invalid")
132-            record_relative = f"{dist_info_name}/RECORD"
133:            wheel_record = archive.read(record_relative)
134:            rows = _record_rows(wheel_record, record_relative, label)
135-            installed_by_path = {row[0]: row for row in installed_rows}
136-            if set(names) != {row[0] for row in rows}:
137:                raise ValueError(f"{label} wheel inventory differs from wheel RECORD")
138-            data_prefix = f"{dist_info_name.removesuffix('.dist-info')}.data/"
139-            for relative, expected_hash, expected_size in rows:
140-                if relative == record_relative:
141-                    continue
142-                try:
143-                    payload = archive.read(relative)
144-                except KeyError as exc:
145:                    raise ValueError(f"{label} wheel RECORD member is missing: {relative}") from exc
146-                if len(payload) != expected_size:
147:                    raise ValueError(f"{label} wheel RECORD size mismatch: {relative}")
148-                if hashlib.sha256(payload).hexdigest() != expected_hash:
149:                    raise ValueError(f"{label} wheel RECORD hash mismatch: {relative}")
150-                installed_relative = relative
151-                if relative.startswith(data_prefix):
152-                    scheme, separator, suffix = relative[len(data_prefix):].partition("/")
153-                    if not separator or not suffix:
154:                        raise ValueError(f"{label} wheel data member is invalid: {relative}")
155-                    if scheme in {"purelib", "platlib"}:
156-                        installed_relative = suffix
157-                    elif scheme == "data":
158-                        installed_relative = Path(os.path.relpath(venv / suffix, site_packages)).as_posix()
159-                    else:
160:                        raise ValueError(f"{label} unsupported wheel data scheme: {scheme}")
161-                installed = installed_by_path.get(installed_relative)
162-                if installed != (installed_relative, expected_hash, expected_size):
163:                    raise ValueError(f"{label} installed RECORD differs for wheel member: {relative}")
164:            return hashlib.sha256(wheel_record).hexdigest()
165-    except zipfile.BadZipFile as exc:
166:        raise ValueError(f"{label} wheel is invalid") from exc
167-
168-
169-def verify_packaged_module_parity(
170-    *,
171-    source: Path,
172:    wheel: Path,
173:    wheel_member: str,
174-    installed: Path,
175-) -> dict[str, object]:
176:    """Prove one packaged helper is byte-identical in source, wheel, and install."""
177-    _regular(source, "module source")
178:    _regular(wheel, "module wheel", private=True)
179-    _regular(installed, "installed module")
180:    member = Path(wheel_member)
181:    if not wheel_member or member.is_absolute() or ".." in member.parts:
182:        raise ValueError("wheel module path is invalid")
183-    try:
184:        with zipfile.ZipFile(wheel) as archive:
185-            names = archive.namelist()
186:            if wheel_member not in names:
187:                raise ValueError("packaged module is absent from wheel")
188:            payload = archive.read(wheel_member)
189-            record_names = [name for name in names if name.endswith(".dist-info/RECORD")]
190-            if len(record_names) != 1:
191:                raise ValueError("wheel RECORD cardinality is invalid")
192:            rows = _record_rows(archive.read(record_names[0]), record_names[0], "module wheel")
193:            row = next((item for item in rows if item[0] == wheel_member), None)
194-            if row is None or row[1] != hashlib.sha256(payload).hexdigest() or row[2] != len(payload):
195:                raise ValueError("packaged module wheel RECORD binding is invalid")
196-    except zipfile.BadZipFile as exc:
197:        raise ValueError("module wheel is invalid") from exc
198-    source_bytes = source.read_bytes()
199-    installed_bytes = installed.read_bytes()
200-    if source_bytes != payload or installed_bytes != payload:
201:        raise ValueError("source, wheel, and installed module bytes differ")
202-    digest = hashlib.sha256(payload).hexdigest()
203-    return {
204:        "module": wheel_member.removesuffix(".py").replace("/", "."),
205-        "sha256": digest,
206-        "size": len(payload),
207-        "source_path": str(source.resolve(strict=True)),
208:        "wheel_path": str(wheel.resolve(strict=True)),
209-        "installed_path": str(installed.resolve(strict=True)),
210-    }
211-
212-
213-def inspect_installed_distribution(
214-    *,
215-    venv: Path,
216-    site_packages: Path,
217:    wheel: Path,
218-    distribution_name: str,
219-    import_packages: Sequence[str],
220-) -> dict[str, object]:
221:    """Recompute one wheel's installed inventory from METADATA and RECORD."""
222-    venv = venv.absolute()
223-    site_packages = site_packages.absolute()
224:    wheel = wheel.absolute()
225-    _private_directory(venv, "installed venv")
226-    if not site_packages.is_dir() or not _within(site_packages, (venv,)):
227:        raise ValueError("site-packages is outside the installed venv")
228-    matches: list[tuple[Path, bytes, str, str]] = []
229-    for dist_info in sorted(site_packages.glob("*.dist-info")):
230-        if dist_info.is_symlink() or not dist_info.is_dir():
231-            continue
--
268-            actual_hash = sha256_file(target)
269-            if actual_hash != expected_hash:
270-                raise ValueError(f"{distribution_name} RECORD hash mismatch: {relative}")
271-        inventory.append({"path": relative, "sha256": actual_hash, "size": actual_size})
272:    wheel_record_sha256 = _wheel_inventory(
273:        wheel,
274-        dist_info.name,
275-        rows,
276-        distribution_name,
277-        site_packages=site_packages,
--
292-        "metadata_sha256": hashlib.sha256(metadata).hexdigest(),
293-        "package_roots": package_roots,
294-        "record_path": str(record.resolve(strict=True)),
295-        "record_sha256": hashlib.sha256(record_data).hexdigest(),
296:        "wheel_filename": wheel.name,
297:        "wheel_path": str(wheel),
298:        "wheel_sha256": sha256_file(wheel),
299:        "wheel_record_sha256": wheel_record_sha256,
300-        "installed_inventory": inventory,
301-        "installed_inventory_sha256": hashlib.sha256(canonical(inventory)).hexdigest(),
302-    }
303-
--
309-    import_packages: Sequence[str],
310-    search_path: Sequence[str] | None = None,
311-    executable: Path | None = None,
312-) -> dict[str, object]:
313:    """Reject another import authority ahead of the declared site-packages."""
314-    venv = venv.absolute()
315-    site_packages = site_packages.resolve(strict=True)
316-    declared_python = venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
317-    if not declared_python.exists():
--
322-    except OSError:
323-        same = False
324-    if not same:
325-        raise ValueError("running interpreter differs from declared installed interpreter")
326:    entries = tuple(sys.path if search_path is None else search_path)
327-    resolved_entries: list[Path] = []
328-    for entry in entries:
329-        candidate = Path(entry or os.getcwd()).absolute()
330-        if candidate.exists():
331-            resolved_entries.append(candidate.resolve(strict=True))
332-    try:
333-        site_index = resolved_entries.index(site_packages)
334-    except ValueError as exc:
335:        raise ValueError("declared site-packages is absent from interpreter search path") from exc
336-    for entry in resolved_entries[:site_index]:
337-        if entry == site_packages:
338-            continue
339-        if any((entry / package).exists() for package in import_packages):
340:            raise ValueError(f"import authority precedes declared site-packages: {entry}")
341-    interpreter = declared_python.resolve(strict=True)
342-    _regular(interpreter, "installed interpreter")
343-    return {
344-        "declared_path": str(declared_python.absolute()),
--
348-        "site_packages": str(site_packages),
349-    }
350-
351-
352:def loaded_module_receipts(
353-    modules: Mapping[str, Path], *, allowed_roots: Sequence[Path]
354-) -> list[dict[str, object]]:
355-    roots = tuple(root.resolve(strict=True) for root in allowed_roots)
356-    receipts: list[dict[str, object]] = []
--
369-        )
370-    return receipts
371-
372-
373:def portable_installed_runtime(runtime: Mapping[str, object]) -> dict[str, object]:
374-    """Remove ephemeral paths while retaining every byte and RECORD identity."""
375-    distributions = cast(Mapping[str, object], runtime.get("distributions"))
376-    portable_distributions: dict[str, object] = {}
377-    for role in ("profile", "hermes"):
--
385-        portable_distribution: dict[str, object] = {
386-            key: distribution.get(key)
387-            for key in (
388-                "distribution_name", "distribution_version", "metadata_sha256",
389:                "wheel_filename", "wheel_sha256", "wheel_record_sha256",
390-            )
391-        }
392-        portable_distribution["installed_inventory"] = inventory
393-        portable_distribution["installed_inventory_sha256"] = hashlib.sha256(
--
404-        "distributions": portable_distributions,
405-    }
406-
407-
408:def collect_installed_runtime(
409-    *,
410-    venv: Path,
411-    site_packages: Path,
412:    profile_wheel: Path,
413:    hermes_wheel: Path,
414-) -> dict[str, object]:
415-    interpreter = validate_import_environment(
416-        venv=venv,
417-        site_packages=site_packages,
--
419-    )
420-    profile = inspect_installed_distribution(
421-        venv=venv,
422-        site_packages=site_packages,
423:        wheel=profile_wheel,
424-        distribution_name="physique-checkin-cli",
425-        import_packages=("checkin_cli",),
426-    )
427-    hermes = inspect_installed_distribution(
428-        venv=venv,
429-        site_packages=site_packages,
430:        wheel=hermes_wheel,
431-        distribution_name="hermes-agent",
432-        import_packages=("gateway",),
433-    )
434-    return {