{"task_id":"st_01a00ed3","status":"completed","residency_state":"evicted","parent_session_id":"01a00387-aaf8-7f2f-89e3-e24c1af24859","root_session_id":"01a00387-aaf8-7f2f-89e3-e24c1af24859","depth":1,"execution_mode":"in-process","model":"openai-codex/gpt-5.6-sol","notify_on_terminal":true,"created_at":"2026-08-17T08:24:35.411Z","updated_at":"2026-08-19T04:53:40.232Z","notification":{"run_epoch":0,"notified_epoch":0},"name":"strict-one-use-delivery-design","task_summary":"Design one-use delivery capability","description":"Design one-use delivery capability","category":"architect","requested_model":{"provider":"openai-codex","model_id":"gpt-5.6-sol","display":"openai-codex/gpt-5.6-sol","source":"category","variant":"xhigh","reasoning_effort":"xhigh"},"fallback_models":[{"provider":"clinepass","model_id":"cline-pass/glm-5.2","display":"clinepass/cline-pass/glm-5.2","source":"category","variant":"xhigh","reasoning_effort":"medium"},{"provider":"openai-codex","model_id":"gpt-5.6-terra","display":"openai-codex/gpt-5.6-terra","source":"category","variant":"xhigh","reasoning_effort":"xhigh"}],"resolved_model":{"provider":"openai-codex","model_id":"gpt-5.6-sol","display":"GPT-5.6 Sol","source":"category","variant":"xhigh","reasoning_effort":"xhigh"},"spawn_spec":{"version":1,"cwd":"/home/cube/projects/richard/traning coach","prompt":"Read-only architecture deliverable for strict rerun: design the smallest production change replacing the global `adaptive_nutrition.delivery_enabled` window for approved draft delivery with a durable one-use capability. Ground in actual current source/tests and preserve fail-closed exactly-once behavior. Capability must bind candidate/wheel/config authorization, customer key/route, draft/revision/checkin, owner actor/chat/topic, card nonce/render message, and expire/consume atomically before or in the same transaction as transport; handle success, failure, timeout, unknown-provider outcomes without reopening or duplicate sends. Keep global config false; no automatic/adaptive sends. Identify exact files/functions/schemas/CLI/operator authorization path/tests and migration semantics. One goal: decision-complete implementation design with file:line evidence and security invariants. No edits/live actions.\n\n<Category_Context>\nYou are a big-picture system design consultant, NOT an implementer.\n\n<Method>\n1. Survey the WHOLE architecture end to end before proposing anything: module boundaries, data flow, ownership, and the blast radius of the area in question.\n2. Produce at least TWO viable designs and state the trade-offs of each in concrete terms (coupling, testability, migration cost, failure modes).\n3. Recommend ONE of them with the reasoning that decided it, the boundaries it assumes, and the risks it carries.\n4. Demand the SIMPLEST architecture that handles the actual requirements. Reject enterprise patterns that do not pay for themselves.\n</Method>\n\n<Advisory_Mode>\nWhen the caller marks the task advisory-only, produce NO file edits: return the analysis, options, recommendation, and risks as structured text.\n</Advisory_Mode>\n</Category_Context>"},"host_pid":1761519,"final_response":"I read this as a read-only production design request - I’ll recommend the smallest capability-based change and map it to exact code, schemas, operations, migration, tests, and invariants.\n\n## Recommendation\n\nUse a **dedicated strict-draft delivery capability embedded in the existing draft-delivery ledger**.\n\nDo not reuse `AdaptiveOperatorCapability`, do not introduce a general token service, and do not create another transport path. Add one typed operation that:\n\n1. Issues a short-lived grant for one already-approved, currently rendered review card.\n2. On the exact owner callback, durably changes:\n   - capability `issued -> consumed`; and\n   - delivery `authorized -> unknown_provider_outcome`\n   in the **same locked JSON replacement**.\n3. Returns an opaque dispatch claim only after all generation, route, card, deployment, consent, safety, and expiry checks pass.\n4. Allows exactly one provider invocation from that returned claim.\n5. Uses the existing receipt, delivered, sent-audit, and reconciliation machinery afterward.\n\nKeep `adaptive_nutrition.delivery_enabled: false`. A true global flag must no longer authorize this Telegram send path.\n\nStrictly speaking, a remote provider cannot offer provable exactly-once delivery across unknown outcomes. The enforceable production guarantee is:\n\n> one durable capability consumption, at most one provider invocation, and no automatic retry after an unknown outcome.\n\nThat is the fail-closed behavior the existing outbox already implements.\n\n---\n\n## Why this is the smallest safe design\n\n### Design A — capability inside `draft-deliveries.json` — recommended\n\nAdd an `authorized` delivery state and a nested capability grant to the existing row.\n\nAdvantages:\n\n- Capability consumption and dispatch claim are one atomic `os.replace` under the existing cross-process `flock`.\n- Reuses current idempotency key, payload digest, provider route, receipt, audit, and reconciliation code.\n- No cross-ledger transaction protocol.\n- Legacy rows can remain readable without receiving authority.\n- A torn generation-ledger write can lose availability but cannot cause a send: no provider call occurs unless the whole claim method returns successfully.\n\nCost:\n\n- The delivery row schema grows.\n- Existing tests that treat `delivery_enabled=True` as authorization must be rewritten.\n\n### Design B — separate append-only capability journal\n\nFor example, `strict-draft-delivery-capabilities.jsonl`, linked to the delivery row by capability ID.\n\nAdvantages:\n\n- Cleaner audit history.\n- Capability events remain append-only.\n\nDisadvantages:\n\n- Consuming the capability and reserving dispatch requires writes to two files.\n- Consume-first can strand an unused capability; reserve-first creates an ambiguous pending reservation.\n- Crash-safe atomicity would require a two-phase recovery protocol or SQLite transaction.\n- Substantially more schema, recovery, and migration code for no delivery benefit.\n\nThis is not the smallest production-safe choice.\n\n### Design C — reuse `AdaptiveOperatorCapability` — reject\n\nThe existing type already has expiry, owner, review route, message provenance, and durable sessions at `gateway/platforms/nutrition_coaching.py:8920-9004` and validation at `13244-13384`.\n\nIt is nevertheless the wrong authority:\n\n- It is scoped to adaptive proposal actions, not approved draft generations.\n- It binds proposal digest/revision rather than draft/check-in/generation records.\n- It couples this exception to adaptive delivery enablement.\n- It does not bind the conventional delivery ledger identity.\n- Reusing it would make it easier, not harder, for the capability to leak into adaptive sends.\n\n---\n\n## Proposed durable model\n\n### Deployment authorization receipt\n\nAdd `dualcoach-strict-rerun-launch-authorization-v1`, written only by an explicit successful human `launch --start-service`.\n\nRequired immutable fields:\n\n```text\nschema\npurpose = \"strict_rerun_one_approved_draft\"\nauthorization_id\nissued_at_utc\narm_receipt_sha256\ncandidate_digest\ncandidate_manifest_sha256\nwheel_sha256\nprovider_receipt_sha256\nprovider_config_sha256\nprofile_config_sha256\nprofile_authorization_digest\nrepository_status_sha256\ncontroller_module_sha256\nauthorization_digest\n```\n\nThe digest covers every preceding field in canonical JSON.\n\nThis is needed because the current launch returns an in-memory status but does not create durable proof that the human-authorized candidate was launched. Current launch validation is at `dualcoach_tasks21_25_controller.py:586-646`.\n\n### Delivery capability grant\n\nNested in the delivery row:\n\n```json\n{\n  \"schema\": \"strict-draft-delivery-capability-v1\",\n  \"purpose\": \"strict_rerun_one_approved_draft\",\n  \"capability_id\": \"<256-bit random identifier>\",\n  \"state\": \"issued\",\n  \"issued_at_utc\": \"...\",\n  \"expires_at_utc\": \"...\",\n  \"consumed_at_utc\": null,\n\n  \"deployment_authorization_digest\": \"...\",\n  \"candidate_digest\": \"...\",\n  \"candidate_manifest_sha256\": \"...\",\n  \"wheel_sha256\": \"...\",\n  \"provider_config_sha256\": \"...\",\n  \"profile_authorization_digest\": \"...\",\n\n  \"customer_key\": \"...\",\n  \"customer_route\": {\n    \"user_id\": \"...\",\n    \"chat_id\": \"...\",\n    \"topic_id\": \"...\"\n  },\n\n  \"draft_id\": \"...\",\n  \"approved_generation\": 4,\n  \"approved_generation_record_digest\": \"...\",\n  \"checkin_event_id\": \"...\",\n  \"checkin_revision\": \"...\",\n  \"session_id\": \"...\",\n  \"approved_draft_revision\": \"...\",\n  \"approved_event_id\": \"...\",\n  \"canonical_payload_digest\": \"...\",\n\n  \"canonical_owner_route\": {\n    \"user_id\": \"...\",\n    \"chat_id\": \"...\",\n    \"topic_id\": \"...\"\n  },\n  \"owner_authority_digest\": \"...\",\n\n  \"review_card_route\": {\n    \"user_id\": \"...\",\n    \"chat_id\": \"...\",\n    \"topic_id\": \"...\"\n  },\n  \"review_card_message_id\": \"...\",\n  \"review_card_nonce\": \"...\",\n  \"review_card_payload_digest\": \"...\",\n\n  \"grant_digest\": \"...\"\n}\n```\n\nUse a fixed short TTL, preferably ten minutes. Do not accept an arbitrary CLI TTL in the first version.\n\n### State transitions\n\n```text\nNo row\n  -> authorized + capability issued        CLI issuance; no provider effect\n\nauthorized/issued\n  -> unknown_provider_outcome/consumed     exact callback dispatch claim\n\nunknown_provider_outcome/consumed\n  -> sent/consumed                          durable provider receipt\n\nsent/consumed\n  -> delivered/consumed\n  -> sent_audited/consumed\n```\n\nExpiry and revocation are terminal authorization states. A negative provider reconciliation must not revive a consumed capability. Another attempt requires a new approved child revision and a new capability.\n\n---\n\n## Exact source changes\n\n### 1. `gateway/platforms/nutrition_coaching.py`\n\nRelevant existing boundaries:\n\n- Coordinator and delivery paths: `2126-2174`\n- Existing atomic pre-transport consume: `2587-2692`\n- Durable card publication: `3846-4145`\n- Generation/card-pinned delivery reservation: `6331-6643`\n- Receipt and audit lifecycle: `6645-7056`\n- Bounded reconciliation: `7058-7186`\n- Strict delivery-row parser: `7547-7629`\n\nAdd:\n\n- `StrictDraftDeliveryCapability`\n- `StrictDeliveryCardContext`\n- `StrictDeliveryDispatchClaim`\n- Capability parser/digest validation.\n- Injectable UTC clock for deterministic expiry tests.\n- `issue_strict_delivery_capability(...)`\n- `claim_strict_delivery_dispatch(...)`\n\n`claim_strict_delivery_dispatch` must:\n\n1. Acquire `_delivery_lock`.\n2. Reload registry, draft, generation, card, delivery, and launch authority.\n3. Require global adaptive delivery to still be false.\n4. Verify all capability fields against live canonical values.\n5. Require current generation to be the exact approved generation named by the grant.\n6. Require the actual callback route, message ID, and nonce.\n7. Persist capability consumption and `unknown_provider_outcome` together.\n8. Persist the generation transition.\n9. Return a dispatch claim only if all writes completed.\n\nChange public `prepare_delivery` and `validate_delivery_transport` so neither can create a new transport-eligible reservation without this capability. They may still support post-transport receipt/audit reconciliation.\n\nAdd a hard adaptive master check: production `set_persisted_delivery(True)` and `deliver_latest_once()` must reject while the configured global gate is false. The current adaptive composite flow can otherwise enable persisted delivery at `nutrition_coaching.py:11926-11935`, despite starting with the global value false.\n\n### 2. `gateway/platforms/telegram.py`\n\nCurrent evidence:\n\n- Render identity is the Telegram message ID: `6505-6516`\n- Nonce binds draft and generation CAS values: `6518-6559`\n- Callback data includes nonce and message identity: `6797-6838`\n- Callback verifies both before mutation: `6870-6913`\n- Current global authorization check: `7110-7116`\n- Existing dispatch calls reservation, validation, then provider: `7117-7208`\n\nChange the send branch to:\n\n```text\nparse and authenticate exact card\n-> claim_strict_delivery_dispatch(...)\n-> if and only if an opaque claim is returned, call Telegram once\n-> existing receipt/delivered/audit sequence\n```\n\nDelete the meaning of:\n\n```python\ndelivery_enabled is True -> send permitted\n```\n\nInstead:\n\n- `delivery_enabled=True` without a capability must still fail.\n- `delivery_enabled=False` with the exact valid capability may perform this one manual send.\n\nAlso persist the newly approved rendering after `query.edit_message_text` succeeds. The current card ledger records publication message IDs, but approval edits the same Telegram message without updating that ledger to the approved generation. Capability issuance must require a card row containing the current approved generation, current rendered payload digest, route, and message ID.\n\nIf that projection cannot be recorded, approval remains valid but capability issuance fails closed.\n\n### 3. `gateway/platforms/dualcoach_tasks21_25_controller.py`\n\nCurrent evidence:\n\n- Candidate and arm schemas: `27-28`\n- Global false and initial profile snapshot validation: `227-274`\n- Candidate/source binding: `357-384`\n- Arm receipt creation: `417-482`\n- Installed wheel validation: `508-581`\n- Human launch: `586-646`\n- CLI parser: `654-674`\n\nAdd:\n\n- Durable launch-authorization schema and receipt.\n- Validation of the provider receipt's existing `config_sha256`.\n- Required `wheel.sha256` extraction from the candidate manifest.\n- Self-digest validation for launch authorization.\n- `issue-delivery-capability` subcommand.\n\nProposed operator command:\n\n```text\ndualcoach_tasks21_25_controller issue-delivery-capability\n  --launch-authorization <private receipt>\n  --draft-id <draft id>\n  --review-message-id <Telegram message id>\n  --json\n```\n\nDo not accept customer route, owner route, text, revision, digest, or destination from the command line. Derive all of them from the launch receipt, committed registry, generation ledger, approval event, delivery/card ledgers, and current config.\n\nThe command must not call Telegram or the provider. JSON output should contain only:\n\n```text\nstatus\ncapability_id\nexpires_at_utc\ndraft binding digest\nreview-card message id\n```\n\nDo not print customer text or raw routes.\n\n### 4. `gateway/platforms/dualcoach_admin.py`\n\nNo new provider operation is needed.\n\nIt already emits:\n\n- Candidate digest: `274-286`\n- Redacted config digest: `303-313`\n- Receipt candidate/config fields: `669-715`\n- Unchanged-profile evidence: `715-719`\n\nThe controller must begin validating and carrying these existing values into launch authorization.\n\n### 5. `gateway/platforms/nutrition_coaching_config.py`\n\nNo new delivery boolean.\n\nKeep:\n\n- `AdaptiveNutritionConfig.delivery_enabled`: `124`\n- Default false parsing: `169`\n\nThe strict capability is an exception for one manual approved-draft dispatch, not a second global enable switch.\n\n### 6. Profile operator console\n\nCurrent production console can reach the same transport lifecycle through:\n\n- `CoordinatorLifecycleAdapter.send`: `operator_console.py:118-181`\n- Production factory wiring `send_draft=adapter.send`: `795-838`\n\nThat is a bypass unless it can supply the exact Telegram review-card context.\n\nSmallest change: production console remains available for evidence/edit/approve, but configure `send_draft=None`. A production `/send` then returns operation unavailable and cannot claim a capability. The exact Telegram card becomes the sole strict-rerun consumer.\n\nDo not add a text box for capability IDs or raw destinations.\n\n### 7. `scripts/reproducible-wheel-build`\n\nNo source change required. It already fixes ZIP time and offline build inputs.\n\nUse the wheel digest from its sealed output as a launch/capability binding. Existing reproducibility coverage is at `tests/test_reproducible_wheel_build.py:17`.\n\n---\n\n## Operator procedure\n\n1. Build and seal the candidate wheel.\n2. Arm and explicitly launch the candidate.\n3. Preserve the generated private launch-authorization receipt.\n4. Generate and approve the draft in Telegram.\n5. Confirm the approved card is durably bound to its exact message ID.\n6. Run `issue-delivery-capability` for that draft/message.\n7. Press **Send** on that same card before expiry.\n8. Never retry after an unknown outcome.\n9. Reconcile only from exact provider evidence.\n\nNo CLI command itself sends a message.\n\n---\n\n## Failure behavior\n\n| Boundary | Durable state | Provider calls | Retry |\n|---|---|---:|---|\n| Issuance validation fails | no capability | 0 | correct inputs may be retried |\n| Capability expired/tampered | issued but unusable, or terminal expired | 0 | requires new approved revision |\n| Claim persistence fails before consumption | issued/authorized | 0 | safe before expiry |\n| Consumption persists, then crash | consumed/unknown | 0 | no resend |\n| Provider rejects or times out | consumed/unknown | at most 1 | no resend |\n| Provider succeeds, receipt write fails | consumed/unknown | 1 | evidence-only reconciliation |\n| Receipt persists, audit fails | sent/delivered | 1 | audit-only retry |\n| Success | sent_audited | 1 | duplicate is idempotent |\n| Concurrent callbacks | one consumed winner | at most 1 | losers rejected |\n\n---\n\n## Migration\n\nUse an additive, fail-closed migration:\n\n- Existing delivery rows without a capability remain readable for receipt/audit reconciliation.\n- A legacy `pending` row is never transport-authorized.\n- Do not auto-mint capabilities for existing drafts or rows.\n- Existing approved cards whose current approved rendering was not recorded must be re-rendered through the typed card recovery path.\n- Existing arm receipts remain historical evidence but cannot issue a capability without a new launch-authorization receipt.\n- No startup rewrite of delivery/card ledgers.\n- No legacy global `delivery_enabled=True` grant survives.\n\nIf an existing delivery row already exists for the same draft/revision, capability issuance should reject rather than guess whether a prior provider attempt occurred.\n\n---\n\n## Required tests\n\n### `tests/gateway/test_nutrition_coaching.py`\n\nAdd coverage for:\n\n- Exact issuance bindings.\n- Tampering with every deployment, route, owner, draft, check-in, card, and expiry field.\n- Expiry immediately before and at the boundary.\n- Legacy rows confer no authority.\n- Concurrent claim has exactly one winner.\n- Capability consumption and unknown state appear in one persisted document.\n- Crash before and after consumption.\n- Negative reconciliation cannot reopen a consumed capability.\n- Corrupt capability fails the whole delivery read closed.\n- Global true without capability cannot send.\n- Global false with capability can claim once.\n- Adaptive `delivery_enable` and `deliver_latest_once` remain blocked.\n\nExisting crash-matrix tests are at `6174`, `6231`, `6263`, `6332`, and `6402`.\n\n### `tests/gateway/test_task7_generation_hardening.py`\n\nConvert the real callback tests to global false plus an issued capability:\n\n- Receipt projection restart: `720`\n- Crash after provider before receipt: `967`\n\nAdd crash after durable capability consumption but before provider invocation: zero calls before restart and zero after restart.\n\n### `tests/gateway/test_telegram_physique_checkin.py`\n\nExtend:\n\n- Approval-only/no-delivery test: `1886`\n- Exact destination/text revalidation: `1943`\n\nAdd:\n\n- Wrong message ID.\n- Wrong nonce.\n- Wrong review route.\n- Stale approved generation.\n- Card projection write failure.\n- Capability expiry.\n- Duplicate tap.\n- `delivery_enabled=True` cannot replace a capability.\n\n### `tests/gateway/test_dualcoach_tasks21_25_controller.py`\n\nExtend current arm/launch tests at `208` and `333`:\n\n- Private launch receipt permissions.\n- Candidate, manifest, wheel, provider config, and profile authorization bindings.\n- Receipt self-digest tampering.\n- Installed wheel drift.\n- Wrong profile.\n- Issuance emits no Telegram/provider action.\n- CLI rejects raw or mismatched card identity.\n\n### Profile `tests/test_operator_console.py`\n\nAssert production `/send` is unavailable and customer transport remains uncalled, while evidence/edit/approve continue to work.\n\n---\n\n## Security invariants\n\n1. **No ambient authority:** neither `delivery_enabled=True` nor an approved draft alone authorizes transport.\n2. **Global remains false:** strict dispatch is valid only while the global adaptive gate is false.\n3. **One purpose:** the capability can invoke only the strict approved-draft dispatch method.\n4. **Exact deployment:** candidate, manifest, wheel, provider config, profile authorization, and human launch receipt are immutable bindings.\n5. **Exact customer:** customer key and full user/chat/topic route must match the live committed registry.\n6. **Exact draft:** draft ID, approved generation, generation-record digest, check-in event/revision, approval event, and payload revision must all match.\n7. **Exact operator:** actual review ingress and canonical owner are separately authenticated and bound.\n8. **Exact card:** nonce, Telegram message ID, rendered payload digest, and review route must match the durable current approved card.\n9. **Short lifetime:** claim is rejected before issuance time and at or after expiry.\n10. **Consume before effect:** the capability is durably consumed before the provider call.\n11. **One winner:** capability consumption and dispatch unknown-state reservation are one locked atomic replacement.\n12. **Unknown is terminal:** timeout, missing receipt, exception, or crash after consumption never causes automatic resend.\n13. **Receipt repair is not delivery:** reconciliation with a receipt performs zero provider calls.\n14. **No legacy grant:** missing capability data means no transport authority.\n15. **No adaptive leakage:** the strict type is not accepted as an `AdaptiveOperatorCapability`.\n16. **No automatic consumer:** scheduler, startup recovery, operator console, and adaptive flows cannot consume the capability.\n17. **Corruption fails closed:** malformed launch, capability, delivery, card, generation, or registry state prevents transport.\n\nNo files were edited, no tests were run, and no service, Telegram, provider, or migration action was performed.","run_stats":{"runtime_ms":716494,"turns":28,"tool_calls":130,"output_tokens":33604,"total_tokens":3570352,"generation_ms":676446,"tokens_per_second":50,"cost_usd":4.69506,"cache_hit_rate_last":0.9927220614269255,"cache_hit_rate_run":0.8794519711328034}}