--- hermes critical symbol lines ---
## gateway/platforms/telegram_nutrition_onboarding_runtime.py
20: from gateway.platforms.telegram_nutrition_onboarding_authority import (
27: from gateway.platforms.telegram_nutrition_onboarding_runtime_authority import (
28:     TelegramNutritionOnboardingRuntimeAuthorityMixin,
52: class TelegramNutritionOnboardingRuntime(
53:     TelegramNutritionOnboardingRuntimeAuthorityMixin,
58:     def __init__(
104:     async def start_after_consent(
132:             authority = self._current_authority(current)
149:             authority=authority,
159:     def _service(self, customer_key: str) -> Any:
166:     def _finalize_owner_approval(
171:         authority: Any,
176:             privacy_consent_digest=None,
181:             authority=authority,
184:     async def recover_waiting_session(self, session: Any) -> bool:
197:                     authority=self._current_authority(current),
206:     def _preserve_owner_callback_receipt(
212:         authority: Any,
221:             raise ValueError("owner callback consumed-update authority is invalid")
225:                 raise ValueError("owner callback consumed-update authority is invalid")
228:             raise ValueError("owner callback consumed-update authority is invalid")
237:         owner_user_id = getattr(authority, "owner_user_id", None)
238:         owner_chat_id = getattr(authority, "owner_chat_id", None)
239:         owner_topic_id = getattr(authority, "owner_topic_id", None)
251:             raise ValueError("owner callback event authority does not match")
252:         authority_values = (owner_user_id, owner_chat_id, owner_topic_id)
258:             authority=authority_values,
267:     def _reconcile_owner_callback_receipt(
314:             authority = self._current_authority(session)
321:                 and record.role == "owner"
334:                 and record.role == "owner"
344:             authority_values = (
345:                 authority.owner_user_id,
346:                 authority.owner_chat_id,
347:                 authority.owner_topic_id,
359:                 or event.actor_user_id != authority.owner_user_id
360:                 or event.authority != authority_values
396:     def replayed_status_if_consumed(
424:     def _rewind_collection(
428:         authority: Any,
440:             authority=authority,
442:             role="customer",
487:     async def _continue_later(
495:     async def _resume(self, session: Any, service: Any) -> None:
## gateway/platforms/telegram_nutrition_onboarding_runtime_authority.py
9:     CustomerPrivateDeliveryAddress,
11:     StaffReviewRole,
12:     parse_customer_private_delivery_address,
15: from gateway.platforms.telegram_customer_bootstrap import BootstrapState, Role
21: class _BootstrapStore(Protocol):
22:     def list_sessions(self) -> tuple[Any, ...]: ...
25: class _BootstrapTransport(Protocol):
29: class _RuntimeContext(Protocol):
36: class TelegramNutritionOnboardingRuntimeAuthorityMixin:
37:     def _context(self) -> _RuntimeContext:
40:     def _registry_document(self) -> Any:
48:     def _registry_owner(self) -> Any:
51:     def _registry_customer(self, session: Any) -> Any:
64:     def _customer_address(customer: Any) -> CustomerPrivateDeliveryAddress:
67:             return parse_customer_private_delivery_address(
80:     def _staff_address(
81:         role: StaffReviewRole,
86:                 role,
95:                 f"{role.value} review binding is unavailable or invalid"
98:     def _session_for_customer_message(self, message: Any) -> Any | None:
122:     def _authority(self, session: Any) -> Any:
123:         customer_claim = session.role_claim(Role.CUSTOMER)
126:                 "bootstrap onboarding authority is incomplete"
131:         owner_address = self._staff_address(StaffReviewRole.OWNER, owner)
137:                 "bootstrap identity and registry authority disagree"
139:         return self._context().domain.OnboardingAuthority(
147:             consent_notice_version="privacy-v1",
152:     def _current_authority(self, session: Any) -> Any:
153:         authority = self._authority(session)
155:         context.domain.validate_current_registry_authority(
157:             authority,
159:         return authority
161:     def _route(self, session: Any, role: str) -> tuple[str, str]:
162:         if role == "customer":
166:         if role == "owner":
168:                 StaffReviewRole.OWNER,
173:             f"unsupported onboarding route role: {role}"
176:     def _evidence(
202:     async def _member_present(
## gateway/platforms/telegram_nutrition_onboarding_runtime_callback.py
26: class _CallbackAnswerQuery(Protocol):
27:     async def answer(self, text: str | None = None) -> object: ...
30: class _CallbackActor(Protocol):
32:     def id(self) -> int | None: ...
35: class _OnboardingCallbackQuery(_CallbackAnswerQuery, Protocol):
37:     def id(self) -> str | None: ...
40:     def from_user(self) -> _CallbackActor | None: ...
43: class _OnboardingCallbackMessage(Protocol):
45:     def message_id(self) -> int | str | None: ...
48: class _BestEffortCallbackQuery:
49:     def __init__(
59:             else "unknown"
63:     def id(self) -> str | None:
67:     def from_user(self) -> _CallbackActor | None:
70:     async def answer(self, text: str | None = None) -> None:
100: def callback_update_id(query: _OnboardingCallbackQuery) -> int:
110: class TelegramNutritionOnboardingRuntimeCallbackMixin(
113:     async def handle_callback(
167:         route_roles = {
179:         role = route_roles.get(token.action)
184:             or role is None
188:                 role=role,
203:             member_chat_id, _ = self._route(session, role)
206:                 "authority",
220:                 "authority",
255:             authority = self._current_authority(session)
258:                 "authority",
260:                 reason_code="authority_unavailable",
267:         log_ingress_stage("authority", update_id, logger=logger)
269:             "nutrition_onboarding_callback_stage stage=authority_pass"
273:             if role is not None:
276:                         authority,
278:                         role=role,
328:                     authority=authority,
363:                     authority=authority,
373:                     authority=authority,
382:                     authority=authority,
399:                     "authority": authority,
445:                         authority=authority,
460:                         authority=authority,
## gateway/platforms/telegram_nutrition_onboarding_publication_outbox.py
33: class GatewayPublicationReceipt:
34:     """One exact publication authority and its optional provider receipt."""
40:     role: str
50: class GatewayOwnerCallbackReceipt:
57:     authority: tuple[int, int, int]
69: class GatewayOnboardingPublicationOutbox:
72:     def __init__(self, profile_root: Path | str, *, initialize: bool = True) -> None:
76:         self.lock_path = self.state_dir / ".lock"
78:         self.emergency_lock_path = self.state_dir / ".emergency.lock"
80:         self.callback_lock_path = self.state_dir / ".owner-callbacks.lock"
82:         self._callback_authority_absent = False
88:     def claim(
95:         role: str,
98:         """Claim one exact publication before the provider call."""
104:             role=role,
107:         with self._locked(self.lock_path):
108:             records = list(self._read_primary_unlocked())
112:                 self._write_primary_unlocked(records)
114:             if not self._same_authority(match, candidate):
115:                 raise ValueError("onboarding publication authority does not match")
118:     def get(
125:         role: str,
128:         """Resolve only an exact current publication authority."""
134:             role=role,
137:         with self._locked(self.lock_path):
139:                 self._read_primary_unlocked(), candidate.session_id, candidate.generation
143:         if not self._same_authority(record, candidate):
144:             raise ValueError("onboarding publication authority does not match")
147:     def record_receipt(
156:         """Attach an authenticated Telegram receipt to one dispatch authority."""
166:     def record_emergency_receipt(
185:     def reconcile_emergency_receipts(self) -> int:
187:         with self._locked(self.lock_path):
188:             records = list(self._read_primary_unlocked())
189:             with self._locked(self.emergency_lock_path):
190:                 emergency_records = self._read_emergency_unlocked()
196:                 if not self._same_authority(primary, emergency):
197:                     raise ValueError("emergency publication authority does not match")
213:                 self._write_primary_unlocked(records)
216:     def mark_committed(
223:         role: str,
233:             role=role,
236:         with self._locked(self.lock_path):
237:             records = list(self._read_primary_unlocked())
239:             if not self._same_authority(current, candidate):
240:                 raise ValueError("onboarding publication authority does not match")
249:             self._write_primary_unlocked(records)
253:     def receipted(self) -> tuple[GatewayPublicationReceipt, ...]:
254:         with self._locked(self.lock_path):
257:                 for record in self._read_primary_unlocked()
261:     def records(self) -> tuple[GatewayPublicationReceipt, ...]:
262:         with self._locked(self.lock_path):
263:             return self._read_primary_unlocked()
265:     def emergency_records(self) -> tuple[GatewayPublicationReceipt, ...]:
266:         with self._locked(self.emergency_lock_path):
267:             return self._read_emergency_unlocked()
269:     def record_owner_callback(
276:         authority: tuple[int, int, int],
285:         with self._locked(self.lock_path):
287:                 self._read_primary_unlocked(), session_id, publication_generation
292:             or publication.role != "owner"
297:             raise ValueError("owner callback publication authority does not match")
303:             authority=authority,
311:         with self._locked(self.callback_lock_path):
312:             records = list(self._read_owner_callbacks_unlocked())
319:             self._write_owner_callbacks_unlocked(records)
322:     def owner_callback(self, session_id: str) -> GatewayOwnerCallbackReceipt | None:
325:         if self._callback_authority_absent:
326:             if self._entry_exists(self.callback_path) or self._entry_exists(self.callback_lock_path):
327:                 raise ValueError("owner callback receipt authority changed during inspection")
329:         with self._locked(self.callback_lock_path):
332:                 for item in self._read_owner_callbacks_unlocked()
338:             raise ValueError("owner callback receipt is ambiguous")
341:     def _record_receipt(
353:         with self._locked(self.lock_path):
355:                 self._read_primary_unlocked(), session_id, generation
360:             raise ValueError("Telegram receipt route does not match dispatch authority")
369:                 raise ValueError("Telegram receipt conflicts with dispatch authority")
372:             with self._locked(self.emergency_lock_path):
373:                 records = list(self._read_emergency_unlocked())
377:                         not self._same_authority(existing, received)
384:                         raise ValueError("emergency publication receipt conflicts with dispatch authority")
387:                 self._write_emergency_unlocked(records)
389:         with self._locked(self.lock_path):
390:             records = list(self._read_primary_unlocked())
392:             if not self._same_authority(current, primary) or current.state != "DISPATCHING":
393:                 raise ValueError("onboarding publication dispatch authority is stale")
395:             self._write_primary_unlocked(records)
398:     def _mark_emergency_committed(self, primary: GatewayPublicationReceipt) -> None:
399:         with self._locked(self.emergency_lock_path):
400:             records = list(self._read_emergency_unlocked())
405:                 not self._same_authority(existing, primary)
414:             self._write_emergency_unlocked(records)
416:     def _candidate(
423:         role: str,
429:         current_role = self._role(role)
437:             current_role,
445:             current_role,
454:             current_role,
461:     def _with_receipt(
472:             record.role,
482:     def _with_state(
491:             record.role,
500:     def _same_authority(
510:             and left.role == right.role
516:     def _valid_receipt(self, record: GatewayPublicationReceipt) -> bool:
528:     def _session_id(value: str) -> str:
534:     def _generation(value: int) -> int:
540:     def _route(chat_id: str, topic_id: str) -> tuple[str, str]:
551:     def _role(value: str) -> str:
553:             raise ValueError("onboarding publication role is invalid")
557:     def _message_id(value: int) -> int:
563:     def _payload(value: Mapping[str, object]) -> dict[str, object]:
580:     def _canonical(value: Mapping[str, object]) -> bytes:
590:     def _payload_digest(
595:         role: str,
603:             "role": role,
609:     def _dispatch_identity(
614:         role: str,
623:             "role": role,
628:     def _receipt_integrity(
642:     def _prepare_paths(self) -> None:
645:         directory = os.stat(self.state_dir, follow_symlinks=False)
649:         self._ensure_private_file(self.lock_path)
650:         self._ensure_private_file(self.emergency_lock_path)
651:         self._ensure_private_file(self.callback_lock_path)
657:     def _inspect_paths(self) -> None:
658:         """Validate existing authorities without creating or repairing any path."""
660:         directory = os.stat(self.state_dir, follow_symlinks=False)
667:         for path in (self.lock_path, self.emergency_lock_path):
668:             self._inspect_private_file(path, "onboarding publication outbox authority")
675:         self._read_primary_unlocked()
676:         self._read_emergency_unlocked()
678:         callback_lock_exists = self._entry_exists(self.callback_lock_path)
679:         if callback_exists != callback_lock_exists:
680:             raise ValueError("owner callback receipt authority is incomplete")
681:         self._callback_authority_absent = not callback_exists
684:                 self.callback_lock_path, "onboarding publication outbox authority"
687:             self._read_owner_callbacks_unlocked()
689:     def _validate_path_ancestry(self, *, require_state_dir: bool) -> None:
698:                 raise ValueError("onboarding publication outbox path must not contain symlinks")
701:     def _entry_exists(path: Path) -> bool:
708:     def _inspect_private_file(self, path: Path, label: str) -> None:
712:                 os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) | _NOATIME,
721:     def _ensure_callback_ledger(self) -> None:
725:                 os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) | _NOATIME,
728:             self._write_owner_callbacks_unlocked(())
736:         self._read_owner_callbacks_unlocked()
738:     def _ensure_private_file(self, path: Path) -> None:
742:                 os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0),
748:                 os.O_RDWR | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0),
751:             raise ValueError("onboarding publication outbox authority is unavailable") from exc
753:             self._validate_private_descriptor(descriptor, "onboarding publication outbox authority")
757:     def _ensure_key(self) -> None:
761:                 os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0),
775:     def _read_key(self) -> bytes:
779:                 os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) | _NOATIME,
792:     def _ensure_ledger(self, path: Path, *, emergency: bool) -> None:
796:                 os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) | _NOATIME,
800:                 self._write_emergency_unlocked(())
802:                 self._write_primary_unlocked(())
811:             self._read_emergency_unlocked()
815:             self._read_primary_unlocked()
817:     def _ledger_schema(self, path: Path) -> str | None:
821:                 os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) | _NOATIME,
844:     def _quarantine_legacy_primary_ledger(self) -> None:
845:         """Preserve unauthenticated v1 evidence without letting it authorize sends."""
846:         with self._locked(self.lock_path):
869:             self._write_primary_unlocked(())
872:     def _locked(self, path: Path) -> Iterator[None]:
876:                 os.O_RDWR | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0),
879:             raise ValueError("onboarding publication outbox lock is unavailable") from exc
881:             self._validate_private_descriptor(descriptor, "onboarding publication outbox lock")
882:             fcntl.flock(descriptor, fcntl.LOCK_EX)
888:     def _validate_private_descriptor(descriptor: int, label: str) -> None:
897:     def _read_primary_unlocked(self) -> tuple[GatewayPublicationReceipt, ...]:
898:         return self._read_records_unlocked(self.ledger_path, emergency=False)
900:     def _read_emergency_unlocked(self) -> tuple[GatewayPublicationReceipt, ...]:
901:         return self._read_records_unlocked(self.emergency_path, emergency=True)
903:     def _read_records_unlocked(
912:                 os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) | _NOATIME,
930:             raise ValueError("onboarding publication outbox ledger is ambiguous")
933:     def _write_primary_unlocked(
937:         self._write_records_unlocked(self.ledger_path, records, emergency=False)
939:     def _write_emergency_unlocked(
943:         self._write_records_unlocked(self.emergency_path, records, emergency=True)
945:     def _write_records_unlocked(
977:     def _owner_callback_candidate(
984:         authority: tuple[int, int, int],
1000:             or len(authority) != 3
1001:             or type(authority[0]) is not int
1002:             or authority[0] < 0
1003:             or type(authority[1]) is not int
1004:             or type(authority[2]) is not int
1005:             or authority[2] < 0
1009:             raise ValueError("owner callback authority is invalid")
1027:             "authority": list(authority),
1047:             authority,
1059:     def _read_owner_callbacks_unlocked(self) -> tuple[GatewayOwnerCallbackReceipt, ...]:
1063:                 os.O_RDONLY | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) | _NOATIME,
1080:             raise ValueError("owner callback receipt is ambiguous")
1083:     def _write_owner_callbacks_unlocked(
1115:     def _owner_callback_to_dict(record: GatewayOwnerCallbackReceipt) -> dict[str, object]:
1121:             "authority": list(record.authority),
1133:     def _owner_callback_from_dict(self, value: object) -> GatewayOwnerCallbackReceipt:
1142:             "session_id", "customer_key", "action", "actor_user_id", "authority", "route",
1152:         authority = record["authority"]
1167:             or not isinstance(authority, list)
1168:             or len(authority) != 3
1181:         owner_user_id, owner_chat_id, owner_topic_id = authority
1214:             authority=(owner_user_id, owner_chat_id, owner_topic_id),
1227:     def _record_to_dict(record: GatewayPublicationReceipt) -> dict[str, object]:
1233:             "role": record.role,
1242:     def _record_from_dict(
1256:             "session_id", "generation", "payload", "route", "role", "render_identity",
1264:         role = record["role"]
1278:             or not isinstance(role, str)
1293:             role=role,
1300:             raise ValueError("onboarding publication authority integrity is invalid")
1322:     def _matching_record(
1335:             raise ValueError("onboarding publication receipt is ambiguous")
1339:     def _find(
## gateway/commit_observer.py
1: """Zero-inotify, event-driven receipts for authoritative Linux file commits."""
21: # dnotify backend maps it to directory mutation notifications below.
26: BACKEND = "dnotify_signalfd_v1"
27: _DNOTIFY_MASK = (
45: class _SigSet(ctypes.Structure):
57: class _BackendSetupError(OSError):
58:     def __init__(self, code: str, error: OSError) -> None:
63: class ProductionCommitObserver:
64:     """Observe authoritative parent directories through dnotify and signalfd."""
66:     def __init__(self, authoritative_roots: tuple[Path, ...], receipt_path: Path) -> None:
67:         if not authoritative_roots:
69:         self._roots = tuple(self._normalize(path) for path in authoritative_roots)
82:     def __enter__(self) -> ProductionCommitObserver:
85:     def __exit__(self, *_args: object) -> None:
88:     def close(self) -> None:
106:                     except BlockingIOError:
117:     def arm(
198:     def observe(self, *, sequence: int, timeout: float) -> dict[str, object]:
239:     def _setup_backend(self, paths: tuple[Path, ...]) -> None:
240:         current_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set())
246:             self._old_signal_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {_SIGNAL})
263:                     os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW,
278:                 fcntl.fcntl(descriptor, fcntl.F_NOTIFY, _DNOTIFY_MASK)
280:                 raise _BackendSetupError("dnotify_setup_failed", exc) from exc
282:     def _create_signalfd(self) -> int:
291:             -1, ctypes.byref(mask), os.O_CLOEXEC | os.O_NONBLOCK
298:     def _resource_receipt(self) -> dict[str, object]:
303:             "inotify_watch_count": 0,
306:     def _next_kernel_parents(self, timeout: float) -> tuple[Path, ...]:
312:     def _wait_signal(self, timeout: float) -> None:
321:     def _read_notifications(self) -> tuple[int, ...]:
324:         except BlockingIOError as exc:
341:     def _changed(
356:     def _state(self, path: Path) -> tuple[str, str, int]:
357:         self._no_symlinks(path)
359:             descriptor = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW)
378:     def _trusted(self, path: Path) -> Path:
382:         self._no_symlinks(normalized)
385:     def _prepare_receipt_parent(self) -> None:
401:             self._no_symlinks(self._receipt_path)
403:     def _no_symlinks(self, path: Path) -> None:
412:                     raise CommitObservationError("symlink_rejected")
416:     def _validate_root(self, path: Path) -> None:
422:                     raise CommitObservationError("symlink_rejected")
428:     def _validate_directory(path: Path) -> None:
434:             raise CommitObservationError("symlink_rejected")
439:     def _normalize(path: Path) -> Path:
443:     def _within(path: Path, root: Path) -> bool:
--- profile critical symbol lines ---
## checkin_cli/nutrition_onboarding.py
10: from checkin_cli.nutrition_onboarding_authority import (
12:     validate_authority,
13:     validate_current_registry_authority,
20:     OnboardingAuthority,
58: def record_current_registry_consent(
73:             notice_version="privacy-v1",
78: class NutritionOnboardingService(NutritionOnboardingFinalizationMixin):
79:     def __init__(
84:         enforce_current_authority: bool = True,
89:         self.enforce_current_authority = enforce_current_authority
107:     def _validate_storage(self) -> None:
110:     def _validate_current_authority(self, authority: OnboardingAuthority) -> None:
111:         if self.enforce_current_authority:
113:                 validate_current_registry_authority(self.profile_root, authority)
116:                     "current onboarding registry authority is unavailable"
119:     def start_or_resume(
122:         authority: OnboardingAuthority,
127:         self._validate_current_authority(authority)
128:         validate_authority(authority, customer_key=self.customer_key)
129:         validate_route(authority, evidence, role="customer")
133:                 "authority": authority.model_dump(mode="json"),
151:             "authority_digest": canonical_digest(authority.model_dump(mode="json")),
155:             "privacy_consent_digest": consent_digest,
160:     def submit_answer(
165:         authority: OnboardingAuthority,
169:         self._validate_current_authority(authority)
172:             authority=authority, evidence=evidence, role="customer",
188:     def attest_baseline(
191:         authority: OnboardingAuthority,
195:         self._validate_current_authority(authority)
198:             authority=authority, evidence=evidence, role="customer",
249:     def _review_receipt(
252:         role: str,
263:                 "role": role,
274:     def _reopen_revision(
307:     def review_as_owner(
311:         authority: OnboardingAuthority,
319:         self._validate_current_authority(authority)
322:             authority=authority, evidence=evidence, role="owner",
331:                     role="owner",
405:     def record_clinical_review(
410:         authority: OnboardingAuthority,
414:         self._validate_current_authority(authority)
417:             authority=authority, evidence=evidence, role="owner",
437:     def cancel(
440:         authority: OnboardingAuthority,
444:         self._validate_current_authority(authority)
447:             authority=authority, evidence=evidence, role="customer",
460:     def status(self) -> OnboardingStatus:
469:     def reconciliation_answers(
472:         authority: OnboardingAuthority,
475:         self._validate_current_authority(authority)
476:         validate_authority(authority, customer_key=self.customer_key)
478:         expected = canonical_digest(authority.model_dump(mode="json"))
479:         if document.get("authority_digest") != expected:
480:             raise ValueError("onboarding authority is stale")
491:     def record_reconciliation(
497:         authority: OnboardingAuthority,
501:         self._validate_current_authority(authority)
502:         validate_authority(authority, customer_key=self.customer_key)
504:         expected = canonical_digest(authority.model_dump(mode="json"))
505:         if document.get("authority_digest") != expected:
506:             raise ValueError("onboarding authority is stale")
530:     def reconciliation_record(
533:         authority: OnboardingAuthority,
536:         self._validate_current_authority(authority)
537:         validate_authority(authority, customer_key=self.customer_key)
539:         expected = canonical_digest(authority.model_dump(mode="json"))
540:         if document.get("authority_digest") != expected:
541:             raise ValueError("onboarding authority is stale")
545:     def replace_stale_reconciliation(
552:         authority: OnboardingAuthority,
556:         self._validate_current_authority(authority)
557:         validate_authority(authority, customer_key=self.customer_key)
558:         with self.store.locked():
560:             expected = canonical_digest(authority.model_dump(mode="json"))
561:             if document.get("authority_digest") != expected:
562:                 raise ValueError("onboarding authority is stale")
588:     def revise_reconciliation_answer(
594:         authority: OnboardingAuthority,
600:         self._validate_current_authority(authority)
606:             authority=authority,
608:             role="customer",
## checkin_cli/nutrition_onboarding_authority.py
1: """Current-authority checks for onboarding mutations."""
10:     OnboardingAuthority,
15: def validate_authority(authority: OnboardingAuthority, *, customer_key: str) -> None:
16:     if authority.customer_key != customer_key:
17:         raise ValueError("customer authority mismatch")
18:     if not authority.consent_granted or authority.consent_notice_version != "privacy-v1":
19:         raise ValueError("current privacy-v1 consent is required")
20:     if authority.customer_enabled:
24: def validate_route(
25:     authority: OnboardingAuthority,
28:     role: str,
31:         getattr(authority, f"{role}_user_id"),
32:         getattr(authority, f"{role}_chat_id"),
33:         getattr(authority, f"{role}_topic_id"),
37:         raise ValueError(f"{role} route does not match")
40: def validate_current_registry_authority(
42:     authority: OnboardingAuthority,
52:         if customer.spec.customer_key == authority.customer_key
55:         raise ValueError("current onboarding customer authority is unavailable")
60:         or customer.ai_processing_consent.notice_version != "privacy-v1"
69:             authority.customer_user_id,
70:             authority.customer_chat_id,
71:             authority.customer_topic_id,
74:             authority.owner_user_id,
75:             authority.owner_chat_id,
76:             authority.owner_topic_id,
83: def requires_safety_hold(baseline: NutritionOnboardingBaseline) -> bool:
## checkin_cli/nutrition_onboarding_clarification_policy.py
27: class _PolicyModel(BaseModel):
31: class ClarificationIssue(_PolicyModel):
38: class SafetyHold(_PolicyModel):
43: class ClarificationPolicyResult(_PolicyModel):
55: def _canonical_decimal(value: object) -> str | None:
65: def canonicalize_answer(field: str, value: object) -> object:
74: def _canonical_answers(answers: Mapping[str, object]) -> dict[str, object]:
82: def _is_ambiguous(value: object) -> bool:
86:         return any(_is_ambiguous(item) for item in value.values())
88:         return any(_is_ambiguous(item) for item in value)
92: def _valid_structured(value: object) -> bool:
108: def _sensitive(field: str, value: object) -> bool:
119: def _safe_adult_dob(reference_date: date) -> str:
126: def _decimal(value: object) -> Decimal | None:
133: def _type_reasons(answers: Mapping[str, object], reasons: dict[str, str]) -> None:
153: def _cross_field_reasons(answers: Mapping[str, object], reasons: dict[str, str]) -> None:
179: def _baseline_reasons(
216: def _issue(field: str, reason_code: str, value: object) -> ClarificationIssue:
233: def compile_clarification_policy(
245:         elif _is_ambiguous(canonical[field]):
## checkin_cli/nutrition_onboarding_projection.py
1: """Disabled-customer registry projection and activation authority receipts."""
17: def _require_digest(value: str, *, field: str) -> None:
22: def project_nutrition_document(
39:         raise ValueError(f"unknown customer: {customer_key}")
42:         raise ValueError("nutrition onboarding projection requires a disabled customer")
49: def apply_nutrition_onboarding_projection(
64:     lock_path = data_root / ".nutrition-onboarding-projection.lock"
65:     journal_path = data_root / "nutrition-onboarding-projection-journal.jsonl"
66:     descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)
67:     with os.fdopen(descriptor, "r+b") as lock:
68:         fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
78:         projection_digest = canonical_digest(projected)
79:         prior = _projection_rows(journal_path)
86:                 and row.get("customer_projection_digest") == projection_digest
89:             raise ValueError("conflicting nutrition onboarding projection replay")
95:                 "customer_projection_digest": projection_digest,
99:             "schema_version": "nutrition_projection_v1",
105:             "customer_projection_digest": projection_digest,
114: def build_nutrition_activation_receipt_v2(
119:     customer_projection_digest: str,
125:         ("customer_projection_digest", customer_projection_digest),
134:         "customer_projection_digest": customer_projection_digest,
140: def customer_nutrition_projection_digest(customer: dict[str, object]) -> str:
154: def build_legacy_activation_authority(
158:     registry_projection_digest: str,
163:         ("registry_projection_digest", registry_projection_digest),
168:         "schema_version": "nutrition_legacy_activation_authority_v1",
171:         "registry_projection_digest": registry_projection_digest,
177: def validate_legacy_activation_authority(
182:     registry_projection_digest: str,
185:     expected = build_legacy_activation_authority(
188:         registry_projection_digest=registry_projection_digest,
198: def _projection_rows(path: Path) -> list[dict[str, object]]:
205:             raise ValueError("invalid nutrition projection journal")
210: def _append_journal(path: Path, row: dict[str, object]) -> None:
221: def _atomic_registry_write(path: Path, document: dict[str, object]) -> None:
## checkin_cli/customer_cleanup.py
1: """Crash-safe, forward-only customer authority archive and cleanup."""
16:     profile_authority_lock,
19: from checkin_cli.customer_cleanup_fs import (
33: from checkin_cli.customer_cleanup_inventory import (
34:     post_cleanup_authority_inventory,
38: from checkin_cli.customer_cleanup_models import (
39:     AuthorityInventory,
40:     CleanupBlockedError,
41:     CleanupError,
42:     CleanupIntegrityError,
43:     CleanupReceipt,
45: from checkin_cli.customer_cleanup_shared import (
46:     SharedLedgerProjection,
47:     copy_shared_projections,
48:     prepare_shared_projections,
49:     verify_shared_projections,
53:     "AuthorityInventory", "CleanupBlockedError", "CleanupError",
54:     "CleanupIntegrityError", "CleanupReceipt", "SharedLedgerProjection",
55:     "archive_customer_cleanup", "post_cleanup_authority_inventory",
56:     "resume_customer_cleanup",
58: def _paths(root: Path, key: str) -> tuple[Path, Path]:
59:     cleanup = root / "data" / "customer-cleanup"
60:     return cleanup / f"{key}.journal.jsonl", cleanup / "archives"
63: def _bindings(root: Path, key: str, candidates: Iterable[Path]) -> dict[str, object]:
69:     sent_path = root / "data/scheduled-deliveries.jsonl"
88: def _load_manifest(path: Path) -> dict[str, Any]:
95:             or not isinstance(value.get("shared_ledger_projections", []), list)
99:         raise CleanupIntegrityError("cleanup manifest is invalid") from exc
103: def _receipt(root: Path, key: str, journal: Path, operation: str, phase: str) -> CleanupReceipt:
105:     return CleanupReceipt(key, operation, phase, archive, archive / "manifest.json", journal, phase == "committed")
108: def archive_customer_cleanup(
113:     shared_ledger_projections: Iterable[SharedLedgerProjection] = (),
116: ) -> CleanupReceipt:
117:     """Archive, byte-verify, and prune one withdrawn customer's authorities."""
121:     shared = tuple(shared_ledger_projections)
122:     with profile_authority_lock(root):
134:             shared_bindings = prepare_shared_projections(root, key, shared)
137:                 "schema_version": "customer-cleanup-archive-v2",
144:                 "shared_ledger_projections": shared_bindings,
156:         return _resume_locked(root, key, operation, journal, fault_injector)
159: def resume_customer_cleanup(
164: ) -> CleanupReceipt:
165:     """Resume the sole durable cleanup operation without moving backward."""
168:     with profile_authority_lock(root):
172:             raise CleanupError("customer cleanup operation has not been prepared")
173:         return _resume_locked(root, key, str(rows[0]["operation_id"]), journal, fault_injector)
176: def _resume_locked(
179: ) -> CleanupReceipt:
185:         raise CleanupIntegrityError("cleanup manifest digest mismatch")
187:         raise CleanupIntegrityError("cleanup manifest authority mismatch")
189:     shared = manifest.get("shared_ledger_projections", [])
193:         verify_shared_projections(root, archive, key, shared)
196:         copy_shared_projections(root, archive, key, shared)
198:         verify_shared_projections(root, archive, key, shared)
204:         authority = post_cleanup_authority_inventory(root, key)
205:         if authority.pending_count or authority.unknown_count:
206:             raise CleanupBlockedError("pending or unknown customer authority blocks cleanup")
214:         verify_shared_projections(root, archive, key, shared)
215:         authority = post_cleanup_authority_inventory(root, key)
216:         if authority.active_count or authority.pending_count or authority.unknown_count:
217:             raise CleanupBlockedError("customer authority remains after source pruning")
## checkin_cli/customer_cleanup_fs.py
1: """Private filesystem and journal primitives for customer cleanup."""
12: from checkin_cli.customer_cleanup_models import CleanupIntegrityError
17: def canonical(value: object) -> bytes:
21: def digest_bytes(value: bytes) -> str:
25: def ensure_private_dir(path: Path) -> None:
30:         raise CleanupIntegrityError("cleanup directory is not a regular directory")
32:         raise CleanupIntegrityError("cleanup directory is not owner-only")
35: def validate_file(path: Path) -> os.stat_result:
38:         raise CleanupIntegrityError(f"cleanup source symlink is forbidden: {path}")
40:         raise CleanupIntegrityError(f"cleanup source is not regular: {path}")
42:         raise CleanupIntegrityError(f"cleanup source is hard-linked: {path}")
44:         raise CleanupIntegrityError(f"cleanup source must be owner-only: {path}")
48: def safe_relative(path: Path, root: Path, customer_key: str) -> str:
53:         raise CleanupIntegrityError("cleanup path traversal escapes profile") from exc
57:         if current.is_symlink():
58:             raise CleanupIntegrityError(f"cleanup source symlink is forbidden: {current}")
62:             raise CleanupIntegrityError("cross-customer cleanup path is forbidden")
66: def source_inventory(
71:     if customer_root.exists() or customer_root.is_symlink():
72:         if customer_root.is_symlink():
73:             raise CleanupIntegrityError("cleanup customer root symlink is forbidden")
78:                 if child.is_symlink():
79:                     raise CleanupIntegrityError(f"cleanup source symlink is forbidden: {child}")
85:             raise CleanupIntegrityError("candidate path is not customer-scoped")
94:             raise CleanupIntegrityError("cleanup source changed while inventoried")
104: def write_private(path: Path, payload: bytes, *, exclusive: bool = False) -> None:
106:     flags = os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | os.O_NOFOLLOW
119: def append_phase(
129:         raise CleanupIntegrityError("cleanup journal phase is not forward-only")
135:     descriptor = os.open(journal, os.O_APPEND | os.O_CREAT | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
146: def read_journal(path: Path) -> list[dict[str, object]]:
153:         raise CleanupIntegrityError("cleanup journal is invalid") from exc
155:         raise CleanupIntegrityError("cleanup journal phase is not forward-only")
158:         raise CleanupIntegrityError("cleanup journal operation changed")
162:             raise CleanupIntegrityError("cleanup journal digest chain is invalid")
166: def copy_inventory(root: Path, archive: Path, rows: list[dict[str, object]]) -> None:
174:             raise CleanupIntegrityError("cleanup source changed before archive copy")
179: def verify_archive(archive: Path, rows: list[dict[str, object]]) -> None:
185:         except (OSError, CleanupIntegrityError) as exc:
186:             raise CleanupIntegrityError("archive verification failed") from exc
188:             raise CleanupIntegrityError("archive verification failed")
191: def prune_sources(root: Path, rows: list[dict[str, object]], customer_key: str) -> None:
199:             raise CleanupIntegrityError("cleanup source changed before pruning")
209: def freeze_archive(archive: Path) -> None:


--- retained sensitive artefacts pattern scan (names only) ---
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/installed-golden-bundle/data/onboarding/telegram-publication-outbox-v1/.receipt-key
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/installed-golden-bundle/raw-customer-transport-calls.jsonl
.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/installed-golden-bundle/raw-onboarding-calls.jsonl
--- secret-like content matches (redacted locations/counts) ---
/bin/bash: -c: 줄 5: `]'을(를) 찾는 도중 예상치 못한 파일의 끝

Command exited with code 2


**Planning isolated Python script execution**

**Planning source extraction from wheel files**

**Designing targeted zip content search script**

**Planning wheel source security scan**

bash

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10; env -i PATH=/usr/bin:/bin HOME=/nonexistent PYTHONDONTWRITEBYTECODE=1 /usr/bin/python3 -I "$ROOT/verification-tools/independent_verify_candidate.py" "$ROOT"; rc=$?; printf 'exit=%s\n' "$rc"; find "$ROOT" -newermt '1 minute ago' -printf 'unexpected modified: %p\n' | sort

W=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts
python3 - "$W/physique_checkin_cli-0.1.0-py3-none-any.whl" "$W/hermes_agent-0.17.0-py3-none-any.whl" <<'PY'
import sys, zipfile
terms=('delivery_capability','prepare_delivery','claim_delivery','mark_delivered','mark_sent','provider','role','owner','customer','unknown_provider','revoke','current_authority','dnotify','observer','callback')
for wheel in sys.argv[1:]:
  print('---',wheel)
  with zipfile.ZipFile(wheel) as z:
    for name in z.namelist():
      if not name.endswith('.py'): continue
      text=z.read(name).decode('utf-8')
      hits=tuple(t for t in terms if t in text)
      if hits:
       print(name, '|', ','.join(hits))
PY

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
printf '%s\n' '--- sealed-tree integrity independently recomputed ---'
/usr/bin/python3 - "$ROOT" <<'PY'
import hashlib,json,os,stat,sys
from pathlib import Path
root=Path(sys.argv[1]); canonical=lambda x: json.dumps(x,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False).encode()
sha=lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
candidate=json.loads((root/'candidate.json').read_text()); seal=json.loads((root/'SEAL.json').read_text())
actual=[{'path':p.relative_to(root).as_posix(),'sha256':sha(p),'size':p.stat().st_size} for p in sorted(root.rglob('*')) if p.is_file() and p.relative_to(root).as_posix() not in {'candidate.json','SEAL.json'}]
print(json.dumps({'candidate_self_hash_ok': candidate.get('document_sha256')==hashlib.sha256(canonical({k:v for k,v in candidate.items() if k!='document_sha256'})).hexdigest(),'candidate_digest':candidate.get('candidate_digest'),'evidence_inventory_exact': actual==candidate.get('evidence_inventory'),'actual_file_count':len(actual),'declared_file_count':len(candidate.get('evidence_inventory',[])),'seal_self_hash_ok':seal.get('document_sha256')==hashlib.sha256(canonical({k:v for k,v in seal.items() if k!='document_sha256'})).hexdigest(),'seal_candidate_binding':seal.get('candidate_manifest_sha256')==sha(root/'candidate.json'),'symlink_count':sum(p.is_symlink() for p in root.rglob('*'))},sort_keys=True))
PY
printf '%s\n' '--- postfreeze receipt seal recomputed ---'
POST=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10-postfreeze-receipts
/usr/bin/python3 - "$POST" <<'PY'
import hashlib,json,sys
from pathlib import Path
root=Path(sys.argv[1]); canonical=lambda x: json.dumps(x,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False).encode(); sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest(); seal=json.loads((root/'SEAL.json').read_text()); actual=[{'path':p.relative_to(root).as_posix(),'sha256':sha(p),'size':p.stat().st_size} for p in sorted(root.iterdir()) if p.is_file() and p.name!='SEAL.json']; print(json.dumps({'seal_self_hash_ok':seal.get('document_sha256')==hashlib.sha256(canonical({k:v for k,v in seal.items() if k!='document_sha256'})).hexdigest(),'inventory_exact':actual==seal.get('files'),'file_count':len(actual),'symlink_count':sum(p.is_symlink() for p in root.iterdir())},sort_keys=True))
PY


{"reason": "missing dependency: audioop-lts", "status": "TASK26_FROZEN_CANDIDATE_FAIL"}
exit=1


def verify_task26_contract(
    root: Path,
    *,
    candidate: str | None = None,
    native: Mapping[str, object] | None = None,
    cleanup: Mapping[str, object] | None = None,
) -> dict[str, object]:
    """Derive every Task26 branch verdict from raw, hash-bound API outcomes."""
    evidence_root = root / "task26-evidence"
    try:
        private(evidence_root, directory=True)
        chain_path = evidence_root / "receipts.jsonl"
        private(chain_path)
        receipts = lines(chain_path, "Task26 receipt")
    except OSError as exc:
        raise ValueError("Task26 evidence contract is unavailable") from exc
    if len(receipts) != len(TASK26_CLAUSES):
        raise ValueError("Task26 evidence contract is incomplete")
    expected_files = {"receipts.jsonl"} | {
        f"{index:02d}-{clause}.json"
        for index, clause in enumerate(TASK26_CLAUSES, 1)
    }
    if {path.name for path in evidence_root.iterdir()} != expected_files:
        raise ValueError("Task26 evidence inventory is not exact")

    previous = ZERO
    invocation_id: str | None = None
    artifacts: dict[str, dict[str, Any]] = {}
    for sequence, (clause, receipt) in enumerate(
        zip(TASK26_CLAUSES, receipts, strict=True), 1
    ):
        if set(receipt) != {
            "schema", "sequence", "clause", "invocation_id",
            "candidate_digest", "previous_sha256", "artifact",
            "artifact_sha256", "receipt_sha256",
        }:
            raise ValueError("Task26 receipt schema is invalid")
        body = {key: value for key, value in receipt.items() if key != "receipt_sha256"}
        computed = hashlib.sha256(canonical(body)).hexdigest()
        current_invocation = receipt.get("invocation_id")
        if (
            receipt.get("schema") != "task26-native-receipt-v1"
            or receipt.get("sequence") != sequence
            or receipt.get("clause") != clause
            or receipt.get("previous_sha256") != previous
            or receipt.get("receipt_sha256") != computed
            or not isinstance(current_invocation, str)
            or len(current_invocation) != 32
            or any(character not in "0123456789abcdef" for character in current_invocation)
            or (invocation_id is not None and current_invocation != invocation_id)
            or (candidate is not None and receipt.get("candidate_digest") != candidate)
        ):
            raise ValueError("Task26 receipt chain or invocation binding is invalid")
        invocation_id = current_invocation
        artifact_name = f"{sequence:02d}-{clause}.json"
        if receipt.get("artifact") != artifact_name:
            raise ValueError("Task26 artifact binding is invalid")
        artifact_path = evidence_root / artifact_name
        private(artifact_path)
        if sha(artifact_path) != receipt.get("artifact_sha256"):
            raise ValueError("Task26 artifact hash binding is invalid")
        artifact = read_json(artifact_path, "Task26 artifact")
        if (
            set(artifact) != {"schema", "invocation_id", "candidate_digest", "clause", "payload"}
            or artifact.get("schema") != "task26-native-artifact-v1"
            or artifact.get("invocation_id") != invocation_id
            or artifact.get("candidate_digest") != receipt.get("candidate_digest")
            or artifact.get("clause") != clause
        ):
            raise ValueError("Task26 native artifact envelope is invalid")
        artifacts[clause] = obj(artifact.get("payload"), f"Task26 {clause} payload")
        previous = computed

    from checkin_cli.nutrition_onboarding import QUESTION_FIELDS
    from checkin_cli.nutrition_onboarding_clarification_policy import compile_clarification_policy
    from checkin_cli.nutrition_onboarding_reconciliation import build_reconciliation
    from gateway.platforms.telegram_nutrition_onboarding_copy import parse_answer

    onboarding = artifacts["onboarding_22_clear"]
    observations = onboarding.get("observations")
    if (
        onboarding.get("question_fields") != list(QUESTION_FIELDS)
        or not isinstance(observations, list)
        or len(observations) != 22
        or len(TASK26_ANSWERS) != 22
    ):
        raise ValueError("Task26 22-answer native evidence is incomplete")
    canonical_answers: dict[str, object] = {}
    for index, (field, raw, raw_observation) in enumerate(
        zip(QUESTION_FIELDS, TASK26_ANSWERS, observations, strict=True)
    ):
        observation = obj(raw_observation, "Task26 answer observation")
        parsed = parse_answer(field, raw)
        if observation != {
            "index": index,
            "field": field,
            "raw": raw,
            "canonical": parsed,
            "before_count": index,
            "after_count": index + 1,
            "handled": True,
            "reask_count": 0,
        }:
            raise ValueError("Task26 clear answer was re-asked or miscanonicalized")
        canonical_answers[field] = parsed
    if onboarding.get("production_answers") != canonical_answers:
        raise ValueError("Task26 production answers differ from raw canonical results")

    ambiguity = artifacts["deterministic_ambiguity_revision"]
    ambiguous_answers = obj(ambiguity.get("ambiguous_answers"), "ambiguous answers")
    revised_answers = obj(ambiguity.get("revised_answers"), "revised answers")
    try:
        reference_date = date.fromisoformat(str(ambiguity.get("reference_date")))
    except ValueError as exc:
        raise ValueError("Task26 ambiguity reference date is invalid") from exc
    first = compile_clarification_policy(ambiguous_answers, reference_date=reference_date)
    second = compile_clarification_policy(ambiguous_answers, reference_date=reference_date)
    revised = compile_clarification_policy(revised_answers, reference_date=reference_date)
    first_record = build_reconciliation(
        answers=ambiguous_answers,
        answers_digest=first.answers_digest,
        advisory={"status": "unavailable"},
        reference_date=reference_date,
    )
    binding = obj(ambiguity.get("revision_binding"), "revision binding")
    native_branch = obj(ambiguity.get("native_branch"), "native ambiguity branch")
    workflow_relative = native_branch.get("workflow_path")
    if (
        not isinstance(workflow_relative, str)
        or Path(workflow_relative).is_absolute()
        or ".." in Path(workflow_relative).parts
    ):
        raise ValueError("Task26 native ambiguity workflow path is invalid")
    workflow_path = root / workflow_relative
    private(workflow_path)
    workflow = read_json(workflow_path, "native ambiguity workflow")
    changed_fields = [
        field for field in QUESTION_FIELDS
        if ambiguous_answers.get(field) != revised_answers.get(field)
    ]
    if (
        ambiguity.get("first_result") != first.model_dump(mode="json")
        or ambiguity.get("second_result") != second.model_dump(mode="json")
        or first != second
        or len(first.issues) != 1
        or first.issues[0].field != "schedule_constraints"
        or binding != {
            "issue_id": first.issues[0].issue_id,
            "field": "schedule_constraints",
            "field_index": QUESTION_FIELDS.index("schedule_constraints"),
            "answers_digest": first.answers_digest,
            "reconciliation_digest": first.result_digest,
        }
        or binding["field_index"] == 0
        or changed_fields != ["schedule_constraints"]
        or ambiguity.get("revised_result") != revised.model_dump(mode="json")
        or revised.issues
        or native_branch.get("workflow_sha256") != sha(workflow_path)
        or native_branch.get("field_zero_rejection") != "reconciliation revision binding is stale"
        or obj(native_branch.get("status"), "native revised status").get("state") != "customer_attestation"
        or native_branch.get("initial_reconciliation") != first_record
        or native_branch.get("revised_reconciliation") != workflow.get("reconciliation")
        or obj(native_branch.get("revised_reconciliation"), "native revised reconciliation").get("state") != "resolved"
        or native_branch.get("answers") != revised_answers
        or workflow.get("answers") != revised_answers
    ):
        raise ValueError("Task26 deterministic ambiguity or revision binding is invalid")

    preview = artifacts["preview_isolation"]
    if (
        preview.get("preview_phase") != "confirming"
        or preview.get("preview_clarifications") != []
        or preview.get("production_answer_count") != 22
        or preview.get("production_state") != "customer_attestation"
        or (native is not None and preview.get("production_session_id") != native.get("session_id"))
    ):
        raise ValueError("Task26 preview evidence was used as production acceptance")

    projection = artifacts["approved_card_projection_gate"]
    if (
        projection.get("projection_fault_seen") is not True
        or projection.get("projection_error") != "source-golden-approved-card-projection-fault"
        or projection.get("delivery_rows_after_failure") != {}
        or not str(projection.get("capability_error", "")).startswith(
            "DraftGenerationTransitionError: delivery capability target is unavailable"
        )
    ):
        raise ValueError("Task26 projection failure did not prevent capability issuance")

    unknown = artifacts["unknown_delivery_no_retry"]
    expected_unknown = {
        "accepted": True,
        "status": "unknown_provider_outcome",
        "transport_required": False,
    }
    unknown_ledger = obj(unknown.get("delivery_ledger"), "unknown delivery ledger")
    unknown_rows = list(unknown_ledger.values())
    if (
        unknown.get("first") != expected_unknown
        or unknown.get("second") != expected_unknown
        or unknown.get("transport_calls_before_send") != 0
        or len(unknown_rows) != 1
        or not isinstance(unknown_rows[0], dict)
        or unknown_rows[0].get("status") != "unknown_provider_outcome"
        or obj(unknown_rows[0].get("delivery_capability"), "unknown capability").get("status") != "consumed"
    ):
        raise ValueError("Task26 unknown delivery outcome was retryable")

    successful = artifacts["successful_lifecycle"]
    delivery_path = root / "data/owner-actions/draft-deliveries.json"
    if (
        successful.get("attestation_state") != "owner_review"
        or successful.get("owner_review_state") != "ready"
        or successful.get("activation_state") != "ACTIVE"
        or successful.get("checkin_finalized") is not True
        or successful.get("approval_status") != "approved"
        or successful.get("delivery_status") != "sent_audited"
        or successful.get("surface_schema") != "telegram-customer-surface-receipt-v2"
        or successful.get("transport_calls") != 1
        or successful.get("duplicate_rejected") is not True
        or successful.get("delivery_ledger_sha256") != sha(delivery_path)
    ):
        raise ValueError("Task26 successful lifecycle native binding is invalid")

    terminal = artifacts["cleanup_resume_terminal"]
    journal = root / "data/customer-cleanup/client_001.journal.jsonl"
    if (
        terminal.get("fault_phase") != "copied_verified"
        or terminal.get("fault_seen") is not True
        or terminal.get("terminal_phase") != "committed"
        or terminal.get("terminal") is not True
        or any(terminal.get(key) != 0 for key in ("active_count", "pending_count", "unknown_count", "orphan_count"))
        or terminal.get("journal_sha256") != sha(journal)
        or (cleanup is not None and terminal.get("operation_id") != cleanup.get("operation_id"))
    ):
        raise ValueError("Task26 cleanup did not resume forward to one terminal receipt")
    return {"clause_count": len(TASK26_CLAUSES), "chain_head": previous, "invocation_id": invocation_id}

def verify_native(root: Path, artifacts: dict[str, Path], customer: str, candidate: str) -> dict[str, Any]:
    if (root / "lifecycle-events.jsonl").exists():
        raise ValueError("self-authored lifecycle/PASS declarations are forbidden")
    registry = read_json(root / "customers/registry.json", "registry")
    matches = [row for row in registry.get("customers", []) if isinstance(row, dict) and row.get("customer_key") == customer]
    if len(matches) != 1 or matches[0].get("enabled") is not False or obj(matches[0].get("ai_processing_consent"), "consent").get("granted") is not False:
        raise ValueError("terminal registry authority is not withdrawn")
    activation = read_json(root / "data/customer-activation-journal.json", "activation journal")
    if activation.get("state") != "committed" or activation.get("customer_id") != customer:
        raise ValueError("activation commit is unavailable")

    bootstrap_path = root / "data/onboarding/telegram-customer-bootstrap-v1/ledger.json"
    session_id = verify_bootstrap_active_lineage(bootstrap_path, customer)

    ready = read_json(required(artifacts, "nutrition-onboarding/ready.json"), "onboarding ready")
    baseline = read_json(required(artifacts, "nutrition-onboarding/baseline-v1.json"), "onboarding baseline")
    readiness = read_json(required(artifacts, "nutrition-onboarding/readiness-current.json"), "readiness pointer")
    receipt = read_json(required(artifacts, "nutrition-onboarding/readiness-receipt-v1.json"), "readiness receipt")
    if ready.get("state") != "ready" or ready.get("customer_key") != customer or receipt.get("delivery_enabled") is not False or receipt.get("activation_enabled") is not False:
        raise ValueError("native readiness state is invalid")
    if (
        baseline.get("customer_key") != customer
        or baseline.get("equation_sex_basis") != "male"
        or baseline.get("height_cm") != 180.0
        or baseline.get("weight_kg") != 80.0
        or baseline.get("activity_category") != "moderate"
        or baseline.get("goal_type") != "maintain"
        or baseline.get("target_weight_kg") is not None
        or baseline.get("target_date") is not None
        or baseline.get("meal_count") != 3
        or baseline.get("schedule_constraints") != TASK26_ANSWERS[-1]
        or any(
            baseline.get(field) != []
            for field in (
                "allergies", "intolerances", "religious_ethical_exclusions",
                "disliked_foods", "dietary_preferences", "conditions", "medications",
            )
        )
        or baseline.get("pregnancy_breastfeeding") is not False
        or not isinstance(baseline.get("customer_attested_at_kst"), str)
        or not isinstance(baseline.get("owner_review_receipt"), str)
        or len(str(baseline.get("owner_review_receipt"))) != 64
    ):
        raise ValueError("native onboarding baseline does not prove the canonical answers and reviews")
    for document, label in ((baseline, "baseline"), (readiness, "readiness"), (receipt, "readiness receipt")):
        claimed = document.get("digest")
        if claimed != hashlib.sha256(canonical({key: value for key, value in document.items() if key != "digest"})).hexdigest():
            raise ValueError(f"{label} digest is invalid")

    checkin_id, draft_id = verify_canonical_journey_events(
        required(artifacts, "wizard/events.jsonl"), customer
    )
    generations = read_json(required(artifacts, "projections/data/owner-actions/draft-generations.json"), "generation projection")
    if generations.get("schema_version") != "customer-cleanup-draft-generations-projection-v1" or generations.get("customer_key") != customer:
        raise ValueError("generation projection schema is invalid")
    history = verify_generation_lineage(
        generations.get("histories"), customer, checkin_id, draft_id
    )

    deliveries_path = root / "data/owner-actions/draft-deliveries.json"
    private(deliveries_path)
    deliveries = read_json(deliveries_path, "delivery ledger")
    if len(deliveries) != 1:
        raise ValueError("delivery cardinality is invalid")
    delivery = next(iter(deliveries.values()))
    capability = obj(delivery.get("delivery_capability"), "delivery capability")
    bindings = obj(capability.get("bindings"), "delivery capability bindings")
    if delivery.get("draft_id") != draft_id or delivery.get("customer_key") != customer or delivery.get("status") != "sent_audited" or capability.get("status") != "consumed" or bindings.get("candidate_digest") != candidate:
        raise ValueError("delivery capability lineage is invalid")

    raw_calls = lines(root / "raw-customer-transport-calls.jsonl", "raw customer call")
    if len(raw_calls) != 1 or raw_calls[0].get("provider_message_id") != delivery.get("message_id") or raw_calls[0].get("text_sha256") != hashlib.sha256(str(delivery.get("text", "")).encode()).hexdigest():
        raise ValueError("raw transport cardinality or receipt binding is invalid")
    surface_path = root / "data/owner-actions/customer-surface-receipts-v2/receipts.jsonl"
    private(surface_path)
    surfaces = lines(surface_path, "surface receipt")
    surface = surfaces[0] if len(surfaces) == 1 else {}
    if (
        surface.get("schema") != "telegram-customer-surface-receipt-v2"
        or surface.get("draft_id") != draft_id
        or surface.get("provider_message_id") != delivery.get("message_id")
        or surface.get("customer_key") != customer
        or surface.get("approved_generation") != delivery.get("generation")
        or surface.get("approved_generation_record_digest")
        != delivery.get("generation_record_digest")
        or surface.get("terminal_generation") != history[-1].get("generation")
        or surface.get("terminal_generation_record_digest")
        != history[-1].get("record_digest")
    ):
        raise ValueError("customer surface receipt descendant binding is invalid")

    service_path = root / "data/owner-actions/customer-service-state.json"
    verify_customer_quiescence(service_path, customer)
    outbox_path = root / "data/onboarding/telegram-publication-outbox-v1/ledger.json"
    private(outbox_path)
    outbox = read_json(outbox_path, "publication outbox")
    records = outbox.get("records")
    if not isinstance(records, list) or not records or any(row.get("session_id") != session_id or row.get("state") != "COMMITTED" for row in records):
        raise ValueError("publication receipt lineage is invalid")
    return {"customer_key": customer, "session_id": session_id, "draft_id": draft_id, "publication_count": len(records), "generation_count": len(history)}

def frozen_terminal_inventory(
    root: Path, customer: str, cleanup: Mapping[str, object]
) -> dict[str, object]:
    """Derive terminal state without asking production code to open write locks."""
    categories = {field: 0 for field in TERMINAL_CATEGORY_FIELDS}
    categories["owner_action"] = 1 if cleanup.get("projection_record_count") else 0
    activation_count = 0
    for relative in (
        "data/customer-activation-journal.json",
        "data/customer-activation-audit.jsonl",
    ):
        path = root / relative
        if not path.exists():
            continue
        values = lines(path, "activation authority") if path.suffix == ".jsonl" else [read_json(path, "activation authority")]
        activation_count += sum(
            1 for row in values
            if row.get("customer_id") == customer or row.get("customer_key") == customer
        )
    categories["activation"] = activation_count
    return {
        "customer_key": customer,
        "disabled": True,
        "nonconsenting": True,
        "categories": dict(sorted(categories.items())),
        "active_count": 0,
        "pending_count": 0,
        "unknown_count": 0,
        "orphan_count": 0,
        "archive_verified": True,
        "journal_committed": True,
        "terminal": True,
    }

def verify(
    root: Path, *, runtime_override: dict[str, object] | None = None
) -> dict[str, object]:
    root = root.absolute()
    private(root, directory=True)
    if (root / "lifecycle-events.jsonl").exists():
        raise ValueError("self-authored lifecycle/PASS declarations are forbidden")
    source_candidate, source = verify_provenance(
        root, offline_recorded_source=runtime_override is not None
    )
    source_document = read_json(root / "source-provenance.json", "source provenance")
    input_doc = read_json(root / "driver-input.json", "driver input")
    runtime_mode = input_doc.get("runtime_mode", "source")
    if runtime_mode == "installed":
        candidate, authority_root = verify_installed_provenance(
            root, source_document, runtime_override=runtime_override
        )
    elif runtime_mode == "source":
        candidate, authority_root = source_candidate, source
        source_text = str(source)
        if source_text not in sys.path:
            sys.path.insert(0, source_text)
    else:
        raise ValueError("driver runtime mode is invalid")
    observer = verify_observer(root, candidate)
    customer = input_doc.get("customer_key")
    if input_doc.get("candidate_digest") != candidate or not isinstance(customer, str):
        raise ValueError("driver input binding is invalid")
    artifacts, cleanup = verify_cleanup(root, customer)
    if stat.S_IMODE(root.stat().st_mode) == 0o500:
        terminal_inventory = frozen_terminal_inventory(root, customer, cleanup)
    else:
        from checkin_cli.customer_cleanup import post_cleanup_authority_inventory

        terminal = post_cleanup_authority_inventory(root, customer)
        terminal_inventory = serialize_terminal_inventory(terminal)
        if not terminal.terminal or any(
            value != 0
            for value in (
                terminal.active_count,
                terminal.pending_count,
                terminal.unknown_count,
                terminal.orphan_count,
            )
        ):
            raise ValueError("post-cleanup authority inventory is not terminal")
    cleanup["terminal_inventory"] = terminal_inventory
    native = verify_native(root, artifacts, customer, candidate)
    task26_contract = verify_task26_contract(
        root, candidate=candidate, native=native, cleanup=cleanup
    )
    from gateway.platforms.task26_candidate_authority import verify_candidate_authority

    candidate_authority = verify_candidate_authority(root, candidate)
    chain_head = hashlib.sha256(canonical({
        "candidate": candidate,
        "observer": observer["head"],
        "manifest": cleanup["manifest_sha256"],
        "native": native,
        "task26_contract_head": task26_contract["chain_head"],
        "authority_registry_head": candidate_authority["registry_head_sha256"],
        "authority_ledger_head": candidate_authority["ledger_head_sha256"],
    })).hexdigest()
    status = "ACTUAL_INSTALLED_GOLDEN_PATH_PASS" if runtime_mode == "installed" else "ACTUAL_SOURCE_GOLDEN_PATH_PASS"
    return {"status": status, "runtime_mode": runtime_mode, "candidate_digest": candidate, "chain_head": chain_head, "source": str(source), "package_authority": str(authority_root), "observer_receipt_count": observer["receipt_count"], "observer_backend": observer["backend"], "observer_directory_resource_count": observer["directory_resource_count"], "observer_inotify_watch_count": observer["inotify_watch_count"], "task26_contract": task26_contract, "candidate_authority": candidate_authority, **cleanup, **native}

def verify_envelope(*_args: object, **_kwargs: object) -> tuple[dict[str, object], dict[str, str]]:

[36 more lines in file. Use offset=1131 to continue.]


def _wheel_identity(path: Path) -> dict[str, object]:
    _private(path)
    try:
        with zipfile.ZipFile(path) as archive:
            names = archive.namelist()
            if (
                len(names) != len(set(names))
                or any(name.startswith("/") or ".." in Path(name).parts for name in names)
            ):
                raise ValueError("wheel members are invalid")
            metadata_names = [
                name for name in names if name.endswith(".dist-info/METADATA")
            ]
            if len(metadata_names) != 1:
                raise ValueError("wheel METADATA cardinality is invalid")
            message = BytesParser(policy=compat32).parsebytes(
                archive.read(metadata_names[0])
            )
    except zipfile.BadZipFile as exc:
        raise ValueError("dependency wheel is invalid") from exc
    project = str(message.get("Name", "")).strip()
    version_text = str(message.get("Version", "")).strip()
    if not project or not version_text:
        raise ValueError("wheel project/version is unavailable")
    try:
        version = str(Version(version_text))
    except InvalidVersion as exc:
        raise ValueError("wheel version is invalid") from exc
    requirements = sorted(str(value) for value in (message.get_all("Requires-Dist") or []))
    return {
        "project": _normal_project(project),
        "version": version,
        "requires_dist": requirements,
        "sha256": sha256_file(path),
        "size": path.stat().st_size,
        "mode": stat.S_IMODE(path.stat().st_mode),
    }

def _wheelhouse_files(
    root: Path,
) -> tuple[list[Path], list[dict[str, object]]]:
    _private(root, directory=True)
    wheels: list[Path] = []
    directories: list[dict[str, object]] = []
    pending = [root]
    while pending:
        directory = pending.pop()
        _private(directory, directory=True)
        for entry in sorted(os.scandir(directory), key=lambda item: item.name):
            path = Path(entry.path)
            info = path.lstat()
            if stat.S_ISLNK(info.st_mode):
                raise ValueError("wheelhouse symlink is forbidden")
            if stat.S_ISDIR(info.st_mode):
                _private(path, directory=True)
                directories.append(
                    {
                        "relative_path": path.relative_to(root).as_posix(),
                        "mode": stat.S_IMODE(info.st_mode),
                    }
                )
                pending.append(path)
            elif stat.S_ISREG(info.st_mode) and path.suffix == ".whl":
                _private(path)
                wheels.append(path)
            else:
                raise ValueError("wheelhouse contains an unbound non-wheel entry")
    return (
        sorted(wheels, key=lambda path: path.relative_to(root).as_posix()),
        sorted(directories, key=lambda row: str(row["relative_path"])),
    )

def _validate_dependency_closure(
    wheels: Sequence[tuple[Path, Mapping[str, object]]],
) -> None:
    projects: dict[str, tuple[Path, Mapping[str, object]]] = {}
    identities: set[tuple[str, str]] = set()
    for path, identity in wheels:
        project = str(identity.get("project", ""))
        version = str(identity.get("version", ""))
        key = (project, version)
        if key in identities or project in projects:
            raise ValueError("duplicate project/version in explicit wheel set")
        identities.add(key)
        projects[project] = (path, identity)
    for _path, identity in wheels:
        requirements = identity.get("requires_dist")
        if not isinstance(requirements, list):
            raise ValueError("wheel dependency declarations are invalid")
        for raw in requirements:
            try:
                requirement = Requirement(str(raw))
            except InvalidRequirement as exc:
                raise ValueError("wheel dependency declaration is invalid") from exc
            if requirement.url is not None:
                raise ValueError("direct URL dependencies are forbidden")
            if requirement.marker is not None and not requirement.marker.evaluate():
                continue
            dependency = projects.get(_normal_project(requirement.name))
            if dependency is None:
                raise ValueError(f"missing dependency: {requirement.name}")
            selected_version = str(dependency[1].get("version", ""))
            if requirement.specifier and not requirement.specifier.contains(
                selected_version, prereleases=True
            ):
                raise ValueError(f"dependency version mismatch: {requirement.name}")

def build_wheelhouse_inventory(
    wheelhouse: Path | None,
    *,
    required_wheels: Sequence[Path],
) -> dict[str, object]:
    """Build an exact recursive inventory and prove the explicit dependency closure."""
    root_wheels = [(path, _wheel_identity(path)) for path in required_wheels]
    if wheelhouse is None:
        dependency_wheels: list[tuple[Path, Mapping[str, object]]] = []
        entries: list[dict[str, object]] = []
    else:
        paths, directories = _wheelhouse_files(wheelhouse)
        dependency_wheels = [(path, _wheel_identity(path)) for path in paths]
        entries = [
            {
                "relative_path": path.relative_to(wheelhouse).as_posix(),
                **identity,
            }
            for path, identity in dependency_wheels
        ]
    if wheelhouse is None:
        root_mode: int | None = None
        directories = []
    else:
        root_mode = stat.S_IMODE(wheelhouse.stat().st_mode)
    _validate_dependency_closure([*root_wheels, *dependency_wheels])
    payload = {
        "root_mode": root_mode,
        "directories": directories,
        "entries": entries,
    }
    return {
        "schema": "task26-sealed-wheelhouse-inventory-v1",
        **payload,
        "inventory_sha256": hashlib.sha256(canonical(payload)).hexdigest(),
    }

def verify_wheelhouse_inventory(
    wheelhouse: Path | None,
    expected: object,
    *,
    required_wheels: Sequence[Path],
) -> dict[str, object]:
    document = _object(expected, "sealed wheelhouse inventory")
    if set(document) != {
        "schema",
        "root_mode",
        "directories",
        "entries",
        "inventory_sha256",
    } or document.get(
        "schema"
    ) != "task26-sealed-wheelhouse-inventory-v1":
        raise ValueError("sealed wheelhouse inventory schema is invalid")
    entries = document.get("entries")
    directories = document.get("directories")
    payload = {
        "root_mode": document.get("root_mode"),
        "directories": directories,
        "entries": entries,
    }
    if (
        not isinstance(entries, list)
        or not isinstance(directories, list)
        or document.get("inventory_sha256")
        != hashlib.sha256(canonical(payload)).hexdigest()
    ):
        raise ValueError("sealed wheelhouse inventory digest is invalid")
    actual = build_wheelhouse_inventory(
        wheelhouse, required_wheels=required_wheels
    )
    if actual != document:
        raise ValueError("wheelhouse inventory differs from sealed expectation")
    return actual

def _bound_wheel_paths(
    wheelhouse: Path | None, inventory: Mapping[str, object]
) -> list[Path]:
    entries = inventory.get("entries")
    if not isinstance(entries, list):
        raise ValueError("sealed wheelhouse entries are invalid")
    if wheelhouse is None:
        if entries:
            raise ValueError("sealed wheelhouse is unavailable")
        return []
    paths: list[Path] = []
    for raw in entries:
        row = _object(raw, "sealed wheelhouse row")
        relative = row.get("relative_path")
        if (
            not isinstance(relative, str)
            or Path(relative).is_absolute()
            or ".." in Path(relative).parts
        ):
            raise ValueError("sealed wheelhouse path is invalid")
        paths.append(wheelhouse / relative)
    return paths

def _validate_portable_origin_contract(runtime_portable: object) -> None:
    runtime = _object(runtime_portable, "portable installed runtime")
    proof = _object(runtime.get("origin_proof"), "portable origin proof")
    execution = _object(proof.get("execution"), "portable origin execution")
    modules = proof.get("modules")
    if (
        runtime.get("schema") != "installed-golden-runtime-portable-v1"
        or proof.get("schema") != "task26-installed-origin-proof-v1"
        or execution

[584 more lines in file. Use offset=339 to continue.]


def _clean_environment() -> dict[str, str]:
    environment = {
        key: value
        for key, value in os.environ.items()
        if not key.startswith("PYTHON") and not key.startswith("PIP")
    }
    environment.update(
        {
            "PYTHONNOUSERSITE": "1",
            "PIP_CONFIG_FILE": os.devnull,
            "PIP_NO_INDEX": "1",
            "PIP_DISABLE_PIP_VERSION_CHECK": "1",
        }
    )
    return environment

def _run_python(
    command: Sequence[str],
    *,
    controlled_cwd: Path,
    environment: Mapping[str, str],
) -> subprocess.CompletedProcess[str]:
    _private(controlled_cwd, directory=True)
    if any(controlled_cwd.iterdir()):
        raise ValueError("controlled Python cwd is not empty")
    completed = subprocess.run(
        list(command),
        check=True,
        cwd=controlled_cwd,
        env=dict(environment),
        capture_output=True,
        text=True,
    )
    if any(controlled_cwd.iterdir()):
        raise ValueError("Python subprocess wrote to controlled cwd")
    return completed

def _verify_bound_wheel_hashes(
    expected: Mapping[str, object], hermes_wheel: Path, profile_wheel: Path
) -> None:
    for label, path in (
        ("hermes_wheel", hermes_wheel),
        ("profile_wheel", profile_wheel),
    ):
        binding = _object(expected.get(label), label)
        if binding != {"filename": path.name, "sha256": sha256_file(path)}:
            raise ValueError(f"sealed {label} digest differs")

def rehydrate_and_verify(
    bundle: Path,
    expected_path: Path,
    *,
    hermes_wheel: Path,
    profile_wheel: Path,
    wheelhouse: Path | None = None,
    temp_parent: Path | None = None,
) -> dict[str, object]:
    """Create an isolated offline runtime, rerun verification, and scrub it."""
    expected = verify_expected_state(
        bundle,
        expected_path,
        hermes_wheel=hermes_wheel,
        profile_wheel=profile_wheel,
    )
    inventory = verify_wheelhouse_inventory(
        wheelhouse,
        expected.get("wheelhouse"),
        required_wheels=(profile_wheel, hermes_wheel),
    )
    temporary = Path(tempfile.mkdtemp(prefix="task26-rehydrate-", dir=temp_parent))
    temporary.chmod(0o700)
    controlled_cwd = temporary / "controlled-cwd"
    controlled_cwd.mkdir(mode=0o700)
    environment = _clean_environment()
    try:
        venv = temporary / "venv"
        _run_python(
            [sys.executable, "-I", "-m", "venv", str(venv)],
            controlled_cwd=controlled_cwd,
            environment=environment,
        )
        venv.chmod(0o700)
        python = venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
        # Recompute immediately before install, then pass only these exact paths.
        inventory = verify_wheelhouse_inventory(
            wheelhouse,
            inventory,
            required_wheels=(profile_wheel, hermes_wheel),
        )
        _verify_bound_wheel_hashes(expected, hermes_wheel, profile_wheel)
        dependency_paths = _bound_wheel_paths(wheelhouse, inventory)
        install = [
            str(python),
            "-I",
            "-m",
            "pip",
            "install",
            "--no-index",
            "--no-deps",
            "--no-compile",
            *(str(path) for path in dependency_paths),
            str(profile_wheel),
            str(hermes_wheel),
        ]
        _run_python(
            install, controlled_cwd=controlled_cwd, environment=environment
        )
        site_packages_text = _run_python(
            [
                str(python),
                "-I",
                "-c",
                "import sysconfig; print(sysconfig.get_paths()['purelib'])",
            ],
            controlled_cwd=controlled_cwd,
            environment=environment,
        ).stdout.strip()
        site_packages = Path(site_packages_text)
        runtime_path = temporary / "runtime.json"
        helper = bundle / str(
            _object(expected["provenance_helper"], "provenance helper")[
                "relative_path"
            ]
        )
        probe = (
            "import hashlib,importlib.util,json,os,pathlib,sys;"
            "p=pathlib.Path(sys.argv[1]);"
            "s=importlib.util.spec_from_file_location('sealed_provenance',p);"
            "m=importlib.util.module_from_spec(s);s.loader.exec_module(m);"
            "r=m.collect_installed_runtime(venv=pathlib.Path(sys.argv[2]),"
            "site_packages=pathlib.Path(sys.argv[3]),"
            "profile_wheel=pathlib.Path(sys.argv[4]),"
            "hermes_wheel=pathlib.Path(sys.argv[5]));"
            "import checkin_cli,gateway;"
            "o={'schema':'task26-rehydrated-origin-probe-v1',"
            "'isolated':sys.flags.isolated,'pythonpath_present':'PYTHONPATH' in os.environ,"
            "'cwd':os.getcwd(),'modules':{'gateway':gateway.__file__,"
            "'checkin_cli':checkin_cli.__file__}};"
            "print(json.dumps({'runtime':r,'origin_probe':o},sort_keys=True,separators=(',',':')))"
        )
        probe_output = _run_python(
            [
                str(python),
                "-I",
                "-c",
                probe,
                str(helper),
                str(venv),
                str(site_packages),
                str(profile_wheel),
                str(hermes_wheel),
            ],
            controlled_cwd=controlled_cwd,
            environment=environment,
        ).stdout
        probe_document = _object(
            json.loads(probe_output), "rehydrated probe document"
        )
        runtime_document = _object(
            probe_document.get("runtime"), "rehydrated runtime"
        )
        origin_proof = verify_runtime_origin_proof(
            runtime_document,
            site_packages,
            probe_document.get("origin_probe"),
            controlled_cwd=controlled_cwd,
        )
        runtime_document["origin_proof"] = origin_proof
        if _portable_runtime(runtime_document) != expected.get("runtime_portable"):
            raise ValueError("rehydrated runtime differs from sealed portable bytes")
        runtime_path.write_bytes(canonical(runtime_document) + b"\n")
        runtime_path.chmod(0o600)
        verifier = bundle / str(
            _object(expected["verifier"], "verifier")["relative_path"]
        )
        completed = _run_python(
            [
                str(python),
                "-I",
                str(verifier),
                str(bundle),
                "--rehydrated-runtime",
                str(runtime_path),
            ],
            controlled_cwd=controlled_cwd,
            environment=environment,
        )
        result = _object(json.loads(completed.stdout), "rehydrated verifier result")
        authority = _object(
            result.get("candidate_authority"), "rehydrated authority"
        )
        expected_authority = _object(
            expected.get("authority"), "expected authority"
        )
        if (
            result.get("status") != expected.get("expected_status")
            or result.get("candidate_digest") != expected.get("candidate_digest")
            or authority.get("registry_head_sha256")
            != expected_authority.get("registry_head_sha256")
            or authority.get("ledger_head_sha256")
            != expected_authority.get("ledger_head_sha256")
            or hashlib.sha256(
                canonical(_portable_verifier_result(result))
            ).hexdigest()
            != expected.get("expected_result_sha256")
        ):
            raise ValueError(
                "rehydrated verifier result differs from sealed expected state"
            )
        result["rehydration_origin_proof"] = origin_proof
        return result
    finally:
        # Verify immutable inputs again after every success or failure path.
        try:
            verify_wheelhouse_inventory(
                wheelhouse,
                inventory,
                required_wheels=(profile_wheel, hermes_wheel),
            )
            _verify_bound_wheel_hashes(expected, hermes_wheel, profile_wheel)
        finally:
            if temporary.exists():
                for path in temporary.rglob("*"):
                    try:
                        if path.is_symlink():
                            continue
                        path.chmod(0o700 if path.is_dir() else 0o600)
                    except OSError:
                        pass
                shutil.rmtree(temporary, ignore_errors=False)

def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("bundle", type=Path)
    parser.add_argument("expected_state", type=Path)
    parser.add_argument("--hermes-wheel", type=Path, required=True)
    parser.add_argument("--profile-wheel", type=Path, required=True)
    parser.add_argument("--wheelhouse", type=Path)
    parser.add_argument("--temp-parent", type=Path)

[31 more lines in file. Use offset=892 to continue.]