7382:         action = self.prepare_delivery(
7383:             draft_id,
7384:             owner,
7385:             expected_generation=expected_generation,
7386:             expected_record_digest=expected_record_digest,
7387:             expected_checkin_revision=expected_checkin_revision,
7388:             expected_draft_revision=expected_draft_revision,
7389:         )
7390:         if not action.accepted or action.selection is None or action.text is None:
7391:             return action
7392:         if action.status in {
7393:             "approved",
7394:             "pending",
7395:             "unknown_provider_outcome",
7396:         } or not action.message_id:
7397:             return DraftAction(
7398:                 False,
7399:                 draft_id=draft_id,
7400:                 text=action.text,
7401:                 status=action.status,
7402:                 selection=action.selection,
7403:                 error="delivery_receipt_pending",
7404:             )
7405:         with self._delivery_lock():
7406:             if not self._ensure_live_registry():
7407:                 return DraftAction(
7408:                     False,
7409:                     draft_id=draft_id,
7410:                     text=action.text,
7411:                     status=action.status,
7412:                     selection=action.selection,
7413:                     message_id=action.message_id,
7414:                     error="customer_registry_unavailable",
7415:                 )
7416:             try:
7417:                 return self._mark_sent_audited_locked(action, draft_id, owner)
7418:             except (DraftLedgerError, OSError, ValueError) as exc:
7419:                 return DraftAction(
7420:                     False,
7421:                     draft_id=draft_id,
7422:                     text=action.text,
7423:                     status="delivered",
7424:                     selection=action.selection,
7425:                     message_id=action.message_id,
7426:                     error=(
7427:                         "draft_ledger_corrupt"
7428:                         if isinstance(exc, DraftLedgerError)
7429:                         else f"draft_ledger_write_failed:{type(exc).__name__}"
7430:                     ),
7431:                 )
7432:
7433:     def _mark_sent_audited_locked(
7434:         self,
7435:         action: DraftAction,
7436:         draft_id: str,
7437:         owner: IncomingAddress,
7438:     ) -> DraftAction:
7439:         if not self._ensure_live_registry():
7440:             return DraftAction(False, draft_id=draft_id, error="customer_registry_unavailable")
7441:         selection = action.selection
7442:         text = action.text
7443:         if selection is None or text is None:
7444:             return DraftAction(False, draft_id=draft_id, error="draft_delivery_state_invalid")
=== gateway/platforms/nutrition_coaching.py:7383-7470 ===
7383:             draft_id,
7384:             owner,
7385:             expected_generation=expected_generation,
7386:             expected_record_digest=expected_record_digest,
7387:             expected_checkin_revision=expected_checkin_revision,
7388:             expected_draft_revision=expected_draft_revision,
7389:         )
7390:         if not action.accepted or action.selection is None or action.text is None:
7391:             return action
7392:         if action.status in {
7393:             "approved",
7394:             "pending",
7395:             "unknown_provider_outcome",
7396:         } or not action.message_id:
7397:             return DraftAction(
7398:                 False,
7399:                 draft_id=draft_id,
7400:                 text=action.text,
7401:                 status=action.status,
7402:                 selection=action.selection,
7403:                 error="delivery_receipt_pending",
7404:             )
7405:         with self._delivery_lock():
7406:             if not self._ensure_live_registry():
7407:                 return DraftAction(
7408:                     False,
7409:                     draft_id=draft_id,
7410:                     text=action.text,
7411:                     status=action.status,
7412:                     selection=action.selection,
7413:                     message_id=action.message_id,
7414:                     error="customer_registry_unavailable",
7415:                 )
7416:             try:
7417:                 return self._mark_sent_audited_locked(action, draft_id, owner)
7418:             except (DraftLedgerError, OSError, ValueError) as exc:
7419:                 return DraftAction(
7420:                     False,
7421:                     draft_id=draft_id,
7422:                     text=action.text,
7423:                     status="delivered",
7424:                     selection=action.selection,
7425:                     message_id=action.message_id,
7426:                     error=(
7427:                         "draft_ledger_corrupt"
7428:                         if isinstance(exc, DraftLedgerError)
7429:                         else f"draft_ledger_write_failed:{type(exc).__name__}"
7430:                     ),
7431:                 )
7432:
7433:     def _mark_sent_audited_locked(
7434:         self,
7435:         action: DraftAction,
7436:         draft_id: str,
7437:         owner: IncomingAddress,
7438:     ) -> DraftAction:
7439:         if not self._ensure_live_registry():
7440:             return DraftAction(False, draft_id=draft_id, error="customer_registry_unavailable")
7441:         selection = action.selection
7442:         text = action.text
7443:         if selection is None or text is None:
7444:             return DraftAction(False, draft_id=draft_id, error="draft_delivery_state_invalid")
7445:         drafts = self._read_drafts()
7446:         draft_record = drafts.get(draft_id)
7447:         record_gate = self._record_eligibility_error(draft_record, owner)
7448:         if record_gate is not None:
7449:             return DraftAction(False, draft_id=draft_id, error=record_gate)
7450:         selection_gate = self._selection_eligibility_error(selection)
7451:         if selection_gate is not None:
7452:             return DraftAction(False, draft_id=draft_id, error=selection_gate)
7453:         if isinstance(draft_record, dict):
7454:             approval_error = self._approved_record_error(draft_id, selection, draft_record)
7455:             if approval_error is not None and not (
7456:                 approval_error == "draft_approval_evidence_missing"
7457:                 and action.status in {"delivered", "sent_audited"}
7458:             ):
7459:                 return DraftAction(False, draft_id=draft_id, error=approval_error)
7460:         deliveries = self._read_deliveries()
7461:         key = self._delivery_key(draft_id, text)
7462:         record = deliveries.get(key)
7463:         if record is None or not record.get("message_id"):
7464:             return DraftAction(False, draft_id=draft_id, error="delivery_receipt_missing")
7465:         generation_plan: dict[str, tuple[DraftGenerationRecord, ...]] | None = None
7466:         current_generation: DraftGenerationRecord | None = None
7467:         try:
7468:             generation_history = self._read_draft_generations().get(draft_id)
7469:             if generation_history is not None:
7470:                 current_generation = generation_history[-1]
=== gateway/platforms/nutrition_coaching.py:7525-7612 ===
7525:                     draft_id=draft_id,
7526:                     text=action.text,
7527:                     status="delivered",
7528:                     selection=action.selection,
7529:                     message_id=str(record["message_id"]),
7530:                     error="draft_event_unavailable",
7531:                 )
7532:         next_deliveries = dict(deliveries)
7533:         audited = dict(record)
7534:         audited["status"] = "sent_audited"
7535:         next_deliveries[key] = audited
7536:         # Persist the receipt ledger before the mutable drafts convenience index.
7537:         self._write_json_private(self._delivery_ledger_path(), next_deliveries)
7538:         if isinstance(draft_record, dict):
7539:             draft_record["status"] = "sent"
7540:             drafts[draft_id] = draft_record
7541:             self._write_json_private(self._drafts_path, drafts)
7542:         if generation_plan is not None:
7543:             self._write_draft_generations(generation_plan)
7544:         return self._action_with_generation(
7545:             replace(
7546:                 action,
7547:                 status="sent_audited",
7548:                 message_id=str(record["message_id"]),
7549:                 transport_required=False,
7550:             ),
7551:             (
7552:                 generation_plan[draft_id][-1]
7553:                 if generation_plan is not None
7554:                 else current_generation
7555:             ),
7556:         )
7557:
7558:     def reconcile_delivery(
7559:         self,
7560:         draft_id: str,
7561:         owner: IncomingAddress,
7562:         evidence: DeliveryReconciliationEvidence | None = None,
7563:         *,
7564:         expected_generation: int | None = None,
7565:         expected_record_digest: str | None = None,
7566:         expected_checkin_revision: str | None = None,
7567:         expected_draft_revision: str | None = None,
7568:     ) -> DraftAction:
7569:         """Resolve unknown outcomes only from exact, bounded provider evidence."""
7570:         action = self.prepare_delivery(
7571:             draft_id,
7572:             owner,
7573:             expected_generation=expected_generation,
7574:             expected_record_digest=expected_record_digest,
7575:             expected_checkin_revision=expected_checkin_revision,
7576:             expected_draft_revision=expected_draft_revision,
7577:         )
7578:         if not action.accepted:
7579:             return action
7580:         if action.status == "sent_audited":
7581:             return action
7582:         if action.status == "pending":
7583:             return DraftAction(
7584:                 False,
7585:                 draft_id=draft_id,
7586:                 text=action.text,
7587:                 status="pending",
7588:                 selection=action.selection,
7589:                 error="delivery_reconciliation_required",
7590:             )
7591:         if action.status == "unknown_provider_outcome":
7592:             if action.text is None or type(evidence) is not DeliveryReconciliationEvidence:
7593:                 return DraftAction(
7594:                     False,
7595:                     draft_id=draft_id,
7596:                     text=action.text,
7597:                     status=action.status,
7598:                     selection=action.selection,
7599:                     error="delivery_reconciliation_required",
7600:                 )
7601:             with self._delivery_lock():
7602:                 try:
7603:                     deliveries = self._read_deliveries()
7604:                     key = self._delivery_key(draft_id, action.text)
7605:                     record = deliveries.get(key)
7606:                 except DraftLedgerError:
7607:                     return DraftAction(
7608:                         False,
7609:                         draft_id=draft_id,
7610:                         error="draft_ledger_corrupt",
7611:                     )
7612:                 message_id = evidence.provider_message_id
=== gateway/platforms/nutrition_coaching.py:7579-7666 ===
7579:             return action
7580:         if action.status == "sent_audited":
7581:             return action
7582:         if action.status == "pending":
7583:             return DraftAction(
7584:                 False,
7585:                 draft_id=draft_id,
7586:                 text=action.text,
7587:                 status="pending",
7588:                 selection=action.selection,
7589:                 error="delivery_reconciliation_required",
7590:             )
7591:         if action.status == "unknown_provider_outcome":
7592:             if action.text is None or type(evidence) is not DeliveryReconciliationEvidence:
7593:                 return DraftAction(
7594:                     False,
7595:                     draft_id=draft_id,
7596:                     text=action.text,
7597:                     status=action.status,
7598:                     selection=action.selection,
7599:                     error="delivery_reconciliation_required",
7600:                 )
7601:             with self._delivery_lock():
7602:                 try:
7603:                     deliveries = self._read_deliveries()
7604:                     key = self._delivery_key(draft_id, action.text)
7605:                     record = deliveries.get(key)
7606:                 except DraftLedgerError:
7607:                     return DraftAction(
7608:                         False,
7609:                         draft_id=draft_id,
7610:                         error="draft_ledger_corrupt",
7611:                     )
7612:                 message_id = evidence.provider_message_id
7613:                 receipt = (
7614:                     message_id.strip()
7615:                     if isinstance(message_id, str) and message_id.strip()
7616:                     else None
7617:                 )
7618:                 if (
7619:                     not isinstance(record, dict)
7620:                     or record.get("status") != "unknown_provider_outcome"
7621:                     or evidence.outcome not in {"sent", "not_sent"}
7622:                     or evidence.idempotency_key != record.get("idempotency_key")
7623:                     or evidence.provider_chat_id != record.get("provider_chat_id")
7624:                     or evidence.provider_topic_id != record.get("provider_topic_id")
7625:                     or evidence.canonical_payload_digest
7626:                     != record.get("canonical_payload_digest")
7627:                     or evidence.outcome == "sent"
7628:                     and (receipt is None or len(receipt) > 128)
7629:                     or evidence.outcome == "not_sent" and message_id is not None
7630:                 ):
7631:                     return DraftAction(
7632:                         False,
7633:                         draft_id=draft_id,
7634:                         text=action.text,
7635:                         status=action.status,
7636:                         selection=action.selection,
7637:                         error="delivery_reconciliation_evidence_invalid",
7638:                     )
7639:                 if evidence.outcome == "not_sent":
7640:                     capability = record.get("delivery_capability")
7641:                     if isinstance(capability, dict):
7642:                         return DraftAction(
7643:                             False,
7644:                             draft_id=draft_id,
7645:                             text=action.text,
7646:                             status=action.status,
7647:                             selection=action.selection,
7648:                             error="delivery_capability_consumed",
7649:                         )
7650:                     retryable = dict(record)
7651:                     retryable["status"] = "pending"
7652:                     next_deliveries = dict(deliveries)
7653:                     next_deliveries[key] = retryable
7654:                     try:
7655:                         self._write_json_private(
7656:                             self._delivery_ledger_path(),
7657:                             next_deliveries,
7658:                         )
7659:                     except (OSError, ValueError):
7660:                         return DraftAction(
7661:                             False,
7662:                             draft_id=draft_id,
7663:                             error="delivery_reconciliation_write_failed",
7664:                         )
7665:                     return replace(
7666:                         action,
=== gateway/platforms/nutrition_coaching.py:7608-7695 ===
7608:                         False,
7609:                         draft_id=draft_id,
7610:                         error="draft_ledger_corrupt",
7611:                     )
7612:                 message_id = evidence.provider_message_id
7613:                 receipt = (
7614:                     message_id.strip()
7615:                     if isinstance(message_id, str) and message_id.strip()
7616:                     else None
7617:                 )
7618:                 if (
7619:                     not isinstance(record, dict)
7620:                     or record.get("status") != "unknown_provider_outcome"
7621:                     or evidence.outcome not in {"sent", "not_sent"}
7622:                     or evidence.idempotency_key != record.get("idempotency_key")
7623:                     or evidence.provider_chat_id != record.get("provider_chat_id")
7624:                     or evidence.provider_topic_id != record.get("provider_topic_id")
7625:                     or evidence.canonical_payload_digest
7626:                     != record.get("canonical_payload_digest")
7627:                     or evidence.outcome == "sent"
7628:                     and (receipt is None or len(receipt) > 128)
7629:                     or evidence.outcome == "not_sent" and message_id is not None
7630:                 ):
7631:                     return DraftAction(
7632:                         False,
7633:                         draft_id=draft_id,
7634:                         text=action.text,
7635:                         status=action.status,
7636:                         selection=action.selection,
7637:                         error="delivery_reconciliation_evidence_invalid",
7638:                     )
7639:                 if evidence.outcome == "not_sent":
7640:                     capability = record.get("delivery_capability")
7641:                     if isinstance(capability, dict):
7642:                         return DraftAction(
7643:                             False,
7644:                             draft_id=draft_id,
7645:                             text=action.text,
7646:                             status=action.status,
7647:                             selection=action.selection,
7648:                             error="delivery_capability_consumed",
7649:                         )
7650:                     retryable = dict(record)
7651:                     retryable["status"] = "pending"
7652:                     next_deliveries = dict(deliveries)
7653:                     next_deliveries[key] = retryable
7654:                     try:
7655:                         self._write_json_private(
7656:                             self._delivery_ledger_path(),
7657:                             next_deliveries,
7658:                         )
7659:                     except (OSError, ValueError):
7660:                         return DraftAction(
7661:                             False,
7662:                             draft_id=draft_id,
7663:                             error="delivery_reconciliation_write_failed",
7664:                         )
7665:                     return replace(
7666:                         action,
7667:                         status="pending",
7668:                         transport_required=True,
7669:                     )
7670:             if receipt is None:
7671:                 return DraftAction(
7672:                     False,
7673:                     draft_id=draft_id,
7674:                     error="delivery_reconciliation_evidence_invalid",
7675:                 )
7676:             recorded = self.record_delivery_transport_receipt(
7677:                 draft_id,
7678:                 owner,
7679:                 receipt,
7680:                 expected_generation=action.generation,
7681:                 expected_record_digest=action.generation_record_digest,
7682:                 expected_checkin_revision=action.generation_checkin_revision,
7683:                 expected_draft_revision=action.generation_draft_revision,
7684:             )
7685:             if not recorded.accepted:
7686:                 return recorded
7687:             action = recorded
7688:         if action.status == "sent" and action.message_id is not None:
7689:             action = self.mark_delivered(
7690:                 draft_id,
7691:                 owner,
7692:                 action.message_id,
7693:                 expected_generation=action.generation,
7694:                 expected_record_digest=action.generation_record_digest,
7695:                 expected_checkin_revision=action.generation_checkin_revision,
=== gateway/platforms/nutrition_coaching.py:7644-7731 ===
7644:                             draft_id=draft_id,
7645:                             text=action.text,
7646:                             status=action.status,
7647:                             selection=action.selection,
7648:                             error="delivery_capability_consumed",
7649:                         )
7650:                     retryable = dict(record)
7651:                     retryable["status"] = "pending"
7652:                     next_deliveries = dict(deliveries)
7653:                     next_deliveries[key] = retryable
7654:                     try:
7655:                         self._write_json_private(
7656:                             self._delivery_ledger_path(),
7657:                             next_deliveries,
7658:                         )
7659:                     except (OSError, ValueError):
7660:                         return DraftAction(
7661:                             False,
7662:                             draft_id=draft_id,
7663:                             error="delivery_reconciliation_write_failed",
7664:                         )
7665:                     return replace(
7666:                         action,
7667:                         status="pending",
7668:                         transport_required=True,
7669:                     )
7670:             if receipt is None:
7671:                 return DraftAction(
7672:                     False,
7673:                     draft_id=draft_id,
7674:                     error="delivery_reconciliation_evidence_invalid",
7675:                 )
7676:             recorded = self.record_delivery_transport_receipt(
7677:                 draft_id,
7678:                 owner,
7679:                 receipt,
7680:                 expected_generation=action.generation,
7681:                 expected_record_digest=action.generation_record_digest,
7682:                 expected_checkin_revision=action.generation_checkin_revision,
7683:                 expected_draft_revision=action.generation_draft_revision,
7684:             )
7685:             if not recorded.accepted:
7686:                 return recorded
7687:             action = recorded
7688:         if action.status == "sent" and action.message_id is not None:
7689:             action = self.mark_delivered(
7690:                 draft_id,
7691:                 owner,
7692:                 action.message_id,
7693:                 expected_generation=action.generation,
7694:                 expected_record_digest=action.generation_record_digest,
7695:                 expected_checkin_revision=action.generation_checkin_revision,
7696:                 expected_draft_revision=action.generation_draft_revision,
7697:             )
7698:             if not action.accepted:
7699:                 return action
7700:         if action.status != "delivered":
7701:             return DraftAction(
7702:                 False,
7703:                 draft_id=draft_id,
7704:                 error="delivery_receipt_pending",
7705:             )
7706:         return self.mark_sent_audited(
7707:             draft_id,
7708:             owner,
7709:             expected_generation=action.generation,
7710:             expected_record_digest=action.generation_record_digest,
7711:             expected_checkin_revision=action.generation_checkin_revision,
7712:             expected_draft_revision=action.generation_draft_revision,
7713:         )
7714:
7715:     def reconcile_draft_delivery(
7716:         self,
7717:         draft_id: str,
7718:         owner: IncomingAddress,
7719:         evidence: DeliveryReconciliationEvidence | None = None,
7720:     ) -> DraftAction:
7721:         """Compatibility alias for :meth:`reconcile_delivery`."""
7722:         return self.reconcile_delivery(draft_id, owner, evidence)
7723:
7724:     def mark_draft_sent(
7725:         self,
7726:         draft_id: str,
7727:         owner: IncomingAddress,
7728:         message_id: str | int | None = None,
7729:     ) -> DraftAction:
7730:         """Record a transport receipt and canonical sent audit."""
7731:         if not self._ensure_live_registry():
=== gateway/platforms/nutrition_coaching.py:8046-8133 ===
8046:                     else {name: value for name, value in values.items() if name in params}
8047:                 )
8048:             )
8049:             appended = resolved.bridge.append_event(event)
8050:             if appended is None:
8051:                 return None
8052:             event_id = getattr(appended, "event_id", None) or getattr(event, "event_id", None)
8053:             return str(event_id) if event_id else None
8054:         except Exception:
8055:             return None
8056:
8057:     def _read_deliveries(self) -> dict[str, dict[str, object]]:
8058:         path = self._delivery_ledger_path()
8059:         if not path.exists():
8060:             return {}
8061:         try:
8062:             payload = json.loads(path.read_text(encoding="utf-8"))
8063:         except (OSError, ValueError) as exc:
8064:             raise DraftLedgerError(
8065:                 f"{path.name} is unreadable; repair or restore it before retrying ({type(exc).__name__})"
8066:             ) from exc
8067:         if not isinstance(payload, dict):
8068:             raise DraftLedgerError(f"{path.name} root must be an object")
8069:         deliveries: dict[str, dict[str, object]] = {}
8070:         required = {
8071:             "draft_id",
8072:             "customer_key",
8073:             "session_id",
8074:             "text",
8075:             "revision",
8076:             "approved_revision",
8077:             "approved_event_id",
8078:             "checkin_revision",
8079:             "idempotency_key",
8080:             "canonical_payload_digest",
8081:             "provider_chat_id",
8082:             "provider_topic_id",
8083:             "status",
8084:         }
8085:         allowed_states = {
8086:             "awaiting_capability",
8087:             "pending",
8088:             "unknown_provider_outcome",
8089:             "sent",
8090:             "sent_audited",
8091:         }
8092:         for key, value in payload.items():
8093:             if not isinstance(key, str) or not isinstance(value, dict):
8094:                 raise DraftLedgerError(f"{path.name} contains a malformed record")
8095:             optional = {
8096:                 "message_id", "approved_card", "delivery_capability",
8097:                 "generation", "generation_record_digest", "provider_user_id",
8098:             }
8099:             if not required.issubset(value) or set(value) - required - optional:
8100:                 raise DraftLedgerError(f"{path.name} record {key!r} is malformed")
8101:             if not all(isinstance(value[item], str) for item in required):
8102:                 raise DraftLedgerError(f"{path.name} record {key!r} is malformed")
8103:             if any(not value[item] for item in required):
8104:                 raise DraftLedgerError(f"{path.name} record {key!r} is malformed")
8105:             if (
8106:                 not 1 <= len(value["text"]) <= 8_000
8107:                 or telegram_utf16_length(value["text"]) > TELEGRAM_SINGLE_MESSAGE_LIMIT_UTF16
8108:             ):
8109:                 raise DraftLedgerError(f"{path.name} record {key!r} has invalid text")
8110:             if value["status"] not in allowed_states:
8111:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid status")
8112:             if value["revision"] != self._draft_revision(value["text"]):
8113:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid revision")
8114:             if key != self._delivery_key(value["draft_id"], value["text"]):
8115:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid identity")
8116:             approved_revision = value.get("approved_revision")
8117:             if approved_revision is not None and approved_revision != value["revision"]:
8118:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid approved revision")
8119:             if (
8120:                 value["canonical_payload_digest"] != value["revision"]
8121:                 or _DRAFT_GENERATION_DIGEST.fullmatch(value["checkin_revision"])
8122:                 is None
8123:                 or value["idempotency_key"]
8124:                 != self._delivery_idempotency_key(
8125:                     value["customer_key"],
8126:                     value["checkin_revision"],
8127:                     value["approved_revision"],
8128:                 )
8129:                 or not 1 <= len(value["provider_chat_id"]) <= 128
8130:                 or not 1 <= len(value["provider_topic_id"]) <= 128
8131:             ):
8132:                 raise DraftLedgerError(f"{path.name} record {key!r} has invalid delivery pins")
8133:             message_id = value.get("message_id")
=== gateway/platforms/nutrition_coaching.py:8076-8163 ===
8076:             "approved_revision",
8077:             "approved_event_id",
8078:             "checkin_revision",
8079:             "idempotency_key",
8080:             "canonical_payload_digest",
8081:             "provider_chat_id",
8082:             "provider_topic_id",
8083:             "status",
8084:         }
8085:         allowed_states = {
8086:             "awaiting_capability",
8087:             "pending",
8088:             "unknown_provider_outcome",
8089:             "sent",
8090:             "sent_audited",
8091:         }
8092:         for key, value in payload.items():
8093:             if not isinstance(key, str) or not isinstance(value, dict):
8094:                 raise DraftLedgerError(f"{path.name} contains a malformed record")
8095:             optional = {
8096:                 "message_id", "approved_card", "delivery_capability",
8097:                 "generation", "generation_record_digest", "provider_user_id",
8098:             }
8099:             if not required.issubset(value) or set(value) - required - optional:
8100:                 raise DraftLedgerError(f"{path.name} record {key!r} is malformed")
8101:             if not all(isinstance(value[item], str) for item in required):
8102:                 raise DraftLedgerError(f"{path.name} record {key!r} is malformed")
8103:             if any(not value[item] for item in required):
8104:                 raise DraftLedgerError(f"{path.name} record {key!r} is malformed")
8105:             if (
8106:                 not 1 <= len(value["text"]) <= 8_000
8107:                 or telegram_utf16_length(value["text"]) > TELEGRAM_SINGLE_MESSAGE_LIMIT_UTF16
8108:             ):
8109:                 raise DraftLedgerError(f"{path.name} record {key!r} has invalid text")
8110:             if value["status"] not in allowed_states:
8111:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid status")
8112:             if value["revision"] != self._draft_revision(value["text"]):
8113:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid revision")
8114:             if key != self._delivery_key(value["draft_id"], value["text"]):
8115:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid identity")
8116:             approved_revision = value.get("approved_revision")
8117:             if approved_revision is not None and approved_revision != value["revision"]:
8118:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid approved revision")
8119:             if (
8120:                 value["canonical_payload_digest"] != value["revision"]
8121:                 or _DRAFT_GENERATION_DIGEST.fullmatch(value["checkin_revision"])
8122:                 is None
8123:                 or value["idempotency_key"]
8124:                 != self._delivery_idempotency_key(
8125:                     value["customer_key"],
8126:                     value["checkin_revision"],
8127:                     value["approved_revision"],
8128:                 )
8129:                 or not 1 <= len(value["provider_chat_id"]) <= 128
8130:                 or not 1 <= len(value["provider_topic_id"]) <= 128
8131:             ):
8132:                 raise DraftLedgerError(f"{path.name} record {key!r} has invalid delivery pins")
8133:             message_id = value.get("message_id")
8134:             if message_id is not None and (not isinstance(message_id, str) or not 0 < len(message_id) <= 128):
8135:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid message id")
8136:             if value["status"] in {"pending", "unknown_provider_outcome"} and message_id is not None:
8137:                 raise DraftLedgerError(f"{path.name} record {key!r} has an early receipt")
8138:             if value["status"] in {"sent", "sent_audited"} and not message_id:
8139:                 raise DraftLedgerError(f"{path.name} record {key!r} is missing its receipt")
8140:             card = value.get("approved_card")
8141:             capability = value.get("delivery_capability")
8142:             if card is not None and (
8143:                 not isinstance(card, dict)
8144:                 or set(card) != {"route", "message_id", "nonce", "payload_digest"}
8145:                 or not isinstance(card.get("route"), dict)
8146:                 or set(card["route"]) != {"user_id", "chat_id", "topic_id"}
8147:                 or not all(isinstance(item, str) and item for item in card["route"].values())
8148:                 or not isinstance(card.get("message_id"), str)
8149:                 or re.fullmatch(r"[a-f0-9]{8}", str(card.get("nonce", ""))) is None
8150:                 or _DRAFT_GENERATION_DIGEST.fullmatch(str(card.get("payload_digest", ""))) is None
8151:             ):
8152:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid approved card")
8153:             if capability is not None and (
8154:                 not isinstance(capability, dict)
8155:                 or capability.get("schema") != "draft-delivery-capability-v1"
8156:                 or capability.get("status") not in {"issued", "consumed"}
8157:                 or not isinstance(capability.get("bindings"), dict)
8158:             ):
8159:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid capability")
8160:             if value["status"] == "awaiting_capability" and (card is None or capability is not None):
8161:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid capability state")
8162:             deliveries[key] = value
8163:         return deliveries
=== gateway/platforms/nutrition_coaching.py:8124-8211 ===
8124:                 != self._delivery_idempotency_key(
8125:                     value["customer_key"],
8126:                     value["checkin_revision"],
8127:                     value["approved_revision"],
8128:                 )
8129:                 or not 1 <= len(value["provider_chat_id"]) <= 128
8130:                 or not 1 <= len(value["provider_topic_id"]) <= 128
8131:             ):
8132:                 raise DraftLedgerError(f"{path.name} record {key!r} has invalid delivery pins")
8133:             message_id = value.get("message_id")
8134:             if message_id is not None and (not isinstance(message_id, str) or not 0 < len(message_id) <= 128):
8135:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid message id")
8136:             if value["status"] in {"pending", "unknown_provider_outcome"} and message_id is not None:
8137:                 raise DraftLedgerError(f"{path.name} record {key!r} has an early receipt")
8138:             if value["status"] in {"sent", "sent_audited"} and not message_id:
8139:                 raise DraftLedgerError(f"{path.name} record {key!r} is missing its receipt")
8140:             card = value.get("approved_card")
8141:             capability = value.get("delivery_capability")
8142:             if card is not None and (
8143:                 not isinstance(card, dict)
8144:                 or set(card) != {"route", "message_id", "nonce", "payload_digest"}
8145:                 or not isinstance(card.get("route"), dict)
8146:                 or set(card["route"]) != {"user_id", "chat_id", "topic_id"}
8147:                 or not all(isinstance(item, str) and item for item in card["route"].values())
8148:                 or not isinstance(card.get("message_id"), str)
8149:                 or re.fullmatch(r"[a-f0-9]{8}", str(card.get("nonce", ""))) is None
8150:                 or _DRAFT_GENERATION_DIGEST.fullmatch(str(card.get("payload_digest", ""))) is None
8151:             ):
8152:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid approved card")
8153:             if capability is not None and (
8154:                 not isinstance(capability, dict)
8155:                 or capability.get("schema") != "draft-delivery-capability-v1"
8156:                 or capability.get("status") not in {"issued", "consumed"}
8157:                 or not isinstance(capability.get("bindings"), dict)
8158:             ):
8159:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid capability")
8160:             if value["status"] == "awaiting_capability" and (card is None or capability is not None):
8161:                 raise DraftLedgerError(f"{path.name} record {key!r} has an invalid capability state")
8162:             deliveries[key] = value
8163:         return deliveries
8164:
8165:     def _read_draft_generation_cards(self) -> dict[str, dict[str, object]]:
8166:         path = self._generation_card_ledger_path()
8167:         if not path.exists():
8168:             return {}
8169:         try:
8170:             payload = json.loads(path.read_text(encoding="utf-8"))
8171:         except (OSError, ValueError) as exc:
8172:             raise DraftLedgerError(
8173:                 f"{path.name} is unreadable; repair or restore it before retrying ({type(exc).__name__})"
8174:             ) from exc
8175:         if not isinstance(payload, dict):
8176:             raise DraftLedgerError(f"{path.name} root must be an object")
8177:         required = {
8178:             "token",
8179:             "generation",
8180:             "record_digest",
8181:             "checkin_revision",
8182:             "draft_revision",
8183:             "destination",
8184:             "not_sent_destinations",
8185:             "not_sent_receipts",
8186:             "payload_digest",
8187:             "state",
8188:             "claim_id",
8189:             "message_id",
8190:         }
8191:         cards: dict[str, dict[str, object]] = {}
8192:         for card_id, value in payload.items():
8193:             if (
8194:                 not isinstance(card_id, str)
8195:                 or not isinstance(value, dict)
8196:                 or set(value) != required
8197:                 or not isinstance(value["token"], str)
8198:                 or _DRAFT_GENERATION_IDENTIFIER.fullmatch(value["token"]) is None
8199:                 or type(value["generation"]) is not int
8200:                 or value["generation"] < 1
8201:                 or not isinstance(value["record_digest"], str)
8202:                 or _DRAFT_GENERATION_DIGEST.fullmatch(value["record_digest"]) is None
8203:                 or not isinstance(value["checkin_revision"], str)
8204:                 or _DRAFT_GENERATION_DIGEST.fullmatch(value["checkin_revision"])
8205:                 is None
8206:                 or (
8207:                     value["draft_revision"] is not None
8208:                     and (
8209:                         not isinstance(value["draft_revision"], str)
8210:                         or _DRAFT_GENERATION_DIGEST.fullmatch(
8211:                             value["draft_revision"]
=== gateway/platforms/nutrition_coaching.py:8295-8382 ===
8295:                     or _DRAFT_GENERATION_IDENTIFIER.fullmatch(message_id) is None
8296:                 )
8297:             ):
8298:                 raise DraftLedgerError(f"{path.name} contains an invalid receipt")
8299:             if value["state"] == "claimed" and claim_id is None:
8300:                 raise DraftLedgerError(f"{path.name} contains an invalid claim")
8301:             if value["state"] == "published" and (claim_id is not None or message_id is None):
8302:                 raise DraftLedgerError(f"{path.name} contains an invalid receipt")
8303:             if value["state"] == "not_sent" and (
8304:                 claim_id is not None or message_id is not None
8305:             ):
8306:                 raise DraftLedgerError(f"{path.name} contains an invalid failure")
8307:             if value["state"] == "unknown_provider_outcome" and claim_id is not None:
8308:                 raise DraftLedgerError(f"{path.name} contains an invalid failure")
8309:             cards[card_id] = value
8310:         return cards
8311:
8312:     def _read_drafts(self) -> dict[str, dict[str, object]]:
8313:         if not self._drafts_path.exists():
8314:             return {}
8315:         try:
8316:             payload = json.loads(self._drafts_path.read_text(encoding="utf-8"))
8317:         except (OSError, ValueError) as exc:
8318:             raise DraftLedgerError(
8319:                 f"drafts.json is unreadable; repair or restore it before retrying ({type(exc).__name__})"
8320:             ) from exc
8321:         if not isinstance(payload, dict):
8322:             raise DraftLedgerError("drafts.json root must be an object")
8323:         records: dict[str, dict[str, object]] = {}
8324:         for key, value in payload.items():
8325:             if not isinstance(key, str) or not isinstance(value, dict):
8326:                 raise DraftLedgerError("drafts.json contains a malformed record")
8327:             required = {"customer_key", "session_id", "text", "status"}
8328:             if not required.issubset(value) or not all(isinstance(value[item], str) for item in required):
8329:                 raise DraftLedgerError(f"drafts.json record {key!r} is malformed")
8330:             if value["status"] not in {
8331:                 "created",
8332:                 "edited",
8333:                 "approved",
8334:                 "held",
8335:                 "superseded",
8336:                 "sent",
8337:             }:
8338:                 raise DraftLedgerError(f"drafts.json record {key!r} has an invalid status")
8339:             if (
8340:                 not 1 <= len(value["text"]) <= 8_000
8341:                 or telegram_utf16_length(value["text"]) > TELEGRAM_SINGLE_MESSAGE_LIMIT_UTF16
8342:             ):
8343:                 raise DraftLedgerError(f"drafts.json record {key!r} has invalid text")
8344:             if "approved_revision" in value and not isinstance(value["approved_revision"], str):
8345:                 raise DraftLedgerError(f"drafts.json record {key!r} has a malformed approved revision")
8346:             if "approved_event_id" in value and not isinstance(value["approved_event_id"], str):
8347:                 raise DraftLedgerError(f"drafts.json record {key!r} has a malformed approved event id")
8348:             if "coach_review" in value:
8349:                 review = coach_review_from_dict(value["coach_review"])
8350:                 if review is None:
8351:                     raise DraftLedgerError(
8352:                         f"drafts.json record {key!r} has a malformed coach review"
8353:                     )
8354:                 binding = value.get("revision_binding_digest")
8355:                 if binding != review.revision_binding_digest:
8356:                     raise DraftLedgerError(
8357:                         f"drafts.json record {key!r} has a mismatched coach review"
8358:                     )
8359:                 if value.get("coach_review_state") not in {
8360:                     "validated_model",
8361:                     "operator_edited",
8362:                     "operator_approved",
8363:                     "held",
8364:                 }:
8365:                     raise DraftLedgerError(
8366:                         f"drafts.json record {key!r} has an invalid coach review state"
8367:                     )
8368:                 artifacts = coach_artifacts_from_dict(
8369:                     value.get("coach_artifacts"),
8370:                     revision_binding_digest=review.revision_binding_digest,
8371:                     accepted_polish_output=value["text"],
8372:                 )
8373:                 if artifacts is None:
8374:                     raise DraftLedgerError(
8375:                         f"drafts.json record {key!r} has malformed coach artifacts"
8376:                     )
8377:             records[key] = value
8378:         return records
8379:
8380:     def _read_draft_generations(
8381:         self,
8382:     ) -> dict[str, tuple[DraftGenerationRecord, ...]]:
=== gateway/platforms/nutrition_coaching.py:13484-13571 ===
13484:     def set_delivery_enabled(self, enabled: bool) -> None:
13485:         """Update the explicit production delivery gate."""
13486:         if type(enabled) is not bool:
13487:             raise AdaptiveWorkflowError("adaptive delivery gate is invalid")
13488:         self.delivery_enabled = enabled
13489:     def set_persisted_delivery(
13490:         self,
13491:         enabled: bool,
13492:         *,
13493:         operator_id: object,
13494:         topic_id: object = OPERATOR_REVIEW_TOPIC_ID,
13495:     ) -> Mapping[str, object]:
13496:         """Persist an owner-approved delivery capability transition."""
13497:         self._require_non_diagnostic_delivery_runtime()
13498:         if enabled is True and self.delivery_enabled is False:
13499:             raise AdaptiveWorkflowError("global adaptive delivery is disabled")
13500:         if type(enabled) is not bool:
13501:             raise AdaptiveWorkflowError("adaptive delivery gate is invalid")
13502:         self._topic(topic_id)
13503:         actor = self._require_operator_owner(
13504:             operator_id,
13505:             required_action="delivery_enable" if enabled else "delivery_revoke",
13506:         )
13507:         owner_snapshot = self._live_owner_key()
13508:         owner_version = self._live_owner_version()
13509:         locked = getattr(self.store, "locked", None)
13510:         if not callable(locked):
13511:             raise AdaptiveWorkflowError("adaptive lifecycle lock is unavailable")
13512:         with self._authority_lock(), self._lifecycle_lock:
13513:             self._ensure_live_adaptive_journals()
13514:             with locked():
13515:                 _customer, data_root, _spec = self._live_customer()
13516:                 self._validate_production_journals()
13517:                 epoch_path, prior = self._feature_epoch(data_root)
13518:                 risk_policy = self._risk_policy_evidence() if enabled else None
13519:                 if prior.get("delivery") is enabled:
13520:                     if enabled:
13521:                         latest_enable = self._latest_committed_delivery_enable_locked()
13522:                         if latest_enable is None or any(
13523:                             latest_enable.get(key) != risk_policy[key]
13524:                             for key in (
13525:                                 "risk_policy_version",
13526:                                 "risk_policy_digest",
13527:                                 "risk_policy_document_digest",
13528:                             )
13529:                         ):
13530:                             raise AdaptiveWorkflowError(
13531:                                 "adaptive delivery enable requires explicit owner reapproval"
13532:                             )
13533:                     return prior
13534:                 customer_keys = self._enabled_customer_keys()
13535:                 updated = dict(prior)
13536:                 updated["epoch"] = int(prior["epoch"]) + 1
13537:                 updated["delivery"] = enabled
13538:                 updated = self._with_feature_config_digest(updated)
13539:                 self._assert_owner_snapshot(operator_id, owner_snapshot, owner_version)
13540:                 self._append_config_epoch_locked(
13541:                     int(updated["epoch"]),
13542:                     str(updated["config_digest"]),
13543:                     customer_keys,
13544:                     state="prepared",
13545:                     approved_by=self._live_owner_key(),
13546:                     risk_policy=risk_policy,
13547:                     delivery=enabled,
13548:                 )
13549:                 try:
13550:                     self._assert_owner_snapshot(operator_id, owner_snapshot, owner_version)
13551:                     self._write_feature_epoch(epoch_path, updated)
13552:                     self._assert_owner_snapshot(operator_id, owner_snapshot, owner_version)
13553:                     self._append_config_epoch_locked(
13554:                         int(updated["epoch"]),
13555:                         str(updated["config_digest"]),
13556:                         customer_keys,
13557:                         state="committed",
13558:                         approved_by=self._live_owner_key(),
13559:                         risk_policy=risk_policy,
13560:                         delivery=enabled,
13561:                     )
13562:                 except (OSError, TypeError, ValueError) as exc:
13563:                     try:
13564:                         self._write_feature_epoch(epoch_path, prior)
13565:                         self._append_config_epoch_locked(
13566:                             int(updated["epoch"]),
13567:                             str(updated["config_digest"]),
13568:                             customer_keys,
13569:                             state="abandoned",
13570:                             approved_by=self._live_owner_key(),
13571:                             risk_policy=risk_policy,

[Showing lines 2163-3115 of 3115 (50.0KB limit). Full output: /tmp/pi-bash-e2679f695fc313f3.log]


**Reevaluating toolchain availability command**

**Analyzing verifier limitations and security tests**

**Locating Python 3.12 for test execution**

**Implementing basic file search**

bash

printf '%s\n' '--- candidate interpreter paths ---'; ls -l /home/cube/miniconda3/bin/python /home/cube/miniconda3/bin/python3.12 /usr/bin/python3 2>&1; printf '%s\n' '--- versions ---'; /home/cube/miniconda3/bin/python3.12 -I -c 'import sys; print(sys.executable); print(sys.version)' 2>&1; /usr/bin/python3 -I -c 'import sys; print(sys.executable); print(sys.version)' 2>&1; printf '%s\n' '--- original runtime exists ---'; ls -ld /home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10 /home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv /home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/bin 2>&1

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10; printf '%s\n' '--- test artifacts packaged? ---'; for whl in "$ROOT"/artifacts/*.whl; do echo ===$(basename "$whl")===; unzip -l "$whl" | grep -Ei '(^|/)(test|tests)[_/].*|test_.*\.py$|security.*test|attack.*test' || true; done; printf '%s\n' '--- test name references in preserved evidence ---'; rg -n --hidden --glob '!.git' 'test_duplicate_and_concurrent|direct_url|wheelhouse.*symlink|shadow_import|unknown_provider_outcome' "$ROOT" | head -300

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

W=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10/artifacts/physique_checkin_cli-0.1.0-py3-none-any.whl
python3 - "$W" <<'PY'
import zipfile,sys
z=zipfile.ZipFile(sys.argv[1])
for name in ['checkin_cli/nutrition_onboarding_clarification_policy.py','checkin_cli/nutrition_onboarding_authority.py','checkin_cli/customer_cleanup_fs.py','checkin_cli/customer_cleanup_inventory.py']:
 print('===',name,'===')
 print(z.read(name).decode())
PY

ROOT=.omo/evidence/task26/task26-isolated-bound-wheelhouse-installed-st_01a01574-v10
printf '%s\n' '--- sensitive values, location and redacted matched key only ---'
/usr/bin/python3 - "$ROOT/installed-golden-bundle" <<'PY'
from pathlib import Path
import re,sys
root=Path(sys.argv[1]); rx=re.compile(r'(?i)(api[_-]?key|authorization|bearer\s+|password|secret|token)')
for p in sorted(root.rglob('*')):
 if not p.is_file(): continue
 try: text=p.read_text()
 except (UnicodeDecodeError,OSError): continue
 matches=[m.group(1).lower() for m in rx.finditer(text)]
 if matches: print(p.relative_to(root), len(matches), sorted(set(matches)))
PY
printf '%s\n' '--- final cleanup evidence ---'
jq -c . "$ROOT/installed-golden-bundle/task26-evidence/07-cleanup_resume_terminal.json"
printf '%s\n' '--- stored customer archive/private data modes ---'
find "$ROOT/installed-golden-bundle/data/customer-cleanup" -printf '%m %y %p -> %l\n' | sort | head -250


--- candidate interpreter paths ---
lrwxrwxrwx 1 cube cube       10 Apr  9  2025 /home/cube/miniconda3/bin/python -> python3.12
-rwxr-xr-x 1 cube cube 30753048 Apr  9  2025 /home/cube/miniconda3/bin/python3.12
lrwxrwxrwx 1 root root       10 Aug 22  2025 /usr/bin/python3 -> python3.13
--- versions ---
/home/cube/miniconda3/bin/python3.12
3.12.9 | packaged by Anaconda, Inc. | (main, Feb  6 2025, 18:56:27) [GCC 11.2.0]
/usr/bin/python3
3.13.7 (main, Mar  3 2026, 12:19:54) [GCC 15.2.0]
--- original runtime exists ---
ls: cannot access '/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10': No such file or directory
ls: cannot access '/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv': No such file or directory
ls: cannot access '/home/cube/.cache/task26-isolated-bound-runtime-st_01a01574-v10/venv/bin': No such file or directory

Command exited with code 2