From 1565b134997c2c915253c9d9813fa4f2a44206b8 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 01:20:22 +0000 Subject: [PATCH 1/2] docs(state-machines): reconcile state-machine docs and close backend:M028 --- .memory/explicit-state-machines-lane-b.md | 6 +- .../audits/state-machine-worksheets-lane-b.md | 20 +- .../state-machines/bot-execution-and-peers.md | 81 ++++++++ docs/state-machines/physical-teardown.md | 8 +- docs/state-machines/proactive-aiden.md | 158 +++++++++++++++ .../remote-durable-operations.md | 135 +++++++++++++ docs/state-machines/retained-p1-owners.md | 14 +- .../bot-runtime/bot-approvals.test.ts | 183 ++++++++++++++++++ main/services/bot-runtime/bot-approvals.ts | 41 +++- 9 files changed, 623 insertions(+), 23 deletions(-) create mode 100644 docs/state-machines/bot-execution-and-peers.md create mode 100644 docs/state-machines/proactive-aiden.md create mode 100644 docs/state-machines/remote-durable-operations.md diff --git a/.memory/explicit-state-machines-lane-b.md b/.memory/explicit-state-machines-lane-b.md index 57169859f3..ed1e84fcc1 100644 --- a/.memory/explicit-state-machines-lane-b.md +++ b/.memory/explicit-state-machines-lane-b.md @@ -7,11 +7,11 @@ Lane B of the explicit state-machine migration: P0 baselines and P2 (authority, - Subagent ledger `consume` is the real fence for child writes and shell. Brokers read authority before awaited checks, so any new revocation path must pair `revokeAuthority` with `approvals.cancelRun`. - `tsx --test` of the write and shell suites needs `npm run build:subagent-file-mutator` and `npm run build:subagent-shell-runner` in a fresh worktree. Without them 7 tests fail and 3 are cancelled. That is not a code failure. - Pre-existing local failures, identical on base `bc663001f`: `agent-compatibility.test.ts` "forked initial context respects zero recent model budget" (`compaction-failed`), and four `scripts/aiden-remote-lan-transport-spike.test.mjs` tests because OpenSSL 4.1 rejects `x509 -days 0`. Both stop their `&&` chains, so run the later stages of `test:subagents` and `test:aiden-remote` by hand. -- M028 still needs its transition review now that #730 and #727 are on `main`. The publish-throw leftover noted during #730 is closed: `request`'s `finally` clears `waiting` and withdraws as `unavailable`. +- M028 (`bot-approvals.ts`) transition review is closed (retained, three fixes) with behavioral tests in `main/services/bot-runtime/bot-approvals.test.ts`: synchronous cleanup + `unavailable` withdrawal on publish throw (including re-entrant replacement), unique per-attempt payload key (`attemptId`) + `finally` drain so aborted/replaced `always` answers cannot leak onto reused `waitId`s, and late `decide` abort guard/rollback. -## Status (2026-11-04) +## Status (2026-11-24) -- P2 stack open: #737, #738, #739, #740. Later commits merge forward, never rebase. +- P2 stack (#737, #738, #739, #740) and P3/P4 (#746–#754) have landed on `main`; `backend:M028` is now closed in `docs/audits/state-machine-worksheets-lane-b.md`. Later commits merge forward, never rebase. - Same-id approval replacement was first recorded as unreachable. Pullfrog reproduced it and it was fixed, so a reachability argument alone does not close a finding on code this lane added. - P3, P4 and P5 PRs opened on 2026-11-05 (#746 to #757, #766, #767, #769), so that dependency has cleared. Recheck overlap before each P6 owner, because file lists move. - P6a reviewed and retained: `bot-pause-store`, `bot-pause-steps`, `bot-routine-recovery`. diff --git a/docs/audits/state-machine-worksheets-lane-b.md b/docs/audits/state-machine-worksheets-lane-b.md index dbf281ab67..c082d793ca 100644 --- a/docs/audits/state-machine-worksheets-lane-b.md +++ b/docs/audits/state-machine-worksheets-lane-b.md @@ -112,11 +112,25 @@ Fixed defects, reproduced by test: `bot-questions.ts` keeps one wait per `waitId`, and its `settle` is gated on prompt identity, so a stale abort cannot end the replacement wait. Baselines are in `bot-questions.test.ts`. -### `backend:M028` Bot approval wait registry — deferred +### `backend:M028` Bot approval wait registry — retained, three fixes -#730 and #727 have landed, and the transition review of the rewritten `bot-approvals.ts` is still to do. +`bot-approvals.ts` wraps `ToolApprovalCoordinator` with per-`waitId` deduplication (`requests`), live prompt publication (`waiting`), and allow-list release (`releaseFromAllowList`). -The item recorded here while #730 was open is closed: its publish callback still sets `waiting` before calling `options.publish`, but the `finally` in `request` removes that entry and withdraws the prompt as `unavailable` when a publish throws. Read in code, not reproduced by a test. +| Event | Prior state | Guard | Next state | Effect | +|---|---|---|---|---| +| `request` (durable hit) | none | `assertCurrent` passes before and after `lookupDecision`, `id` and `authorizationFingerprint` match | unchanged (never published) | Returns cloned saved `BotApprovalDecision` | +| `request` (identical join) | `requests` has live entry | Same `(waitId, botId, authorizationFingerprint)` and `!controller.signal.aborted` | unchanged | Joins existing `result` promise without republishing | +| `request` (new or replacement) | none or mismatched entry | `assertCurrent` and `signal` live | `requests` and `waiting` hold new attempt | Aborts mismatched prior waiter with `The approval was replaced.` (withdrawing it as `cancelled`), then publishes new prompt | +| `options.publish` throws, unsettled | `publishing` | `!controller.signal.aborted && !source` | removed from `requests` and `waiting` (restoring any enclosing `waiting` entry) | Clears callbacks, withdraws prompt once as `unavailable`, notifies `onChange`, rejects waiter with `unavailable` | +| `decide` | `waiting` has entry | `!controller.signal.aborted`, unclaimed (or `expiry` + `deny`) | removed by coordinator `withdraw` | Records `source`/`decisionSource` (rolled back if coordinator refuses) and resolves waiter with `allow`, `allow_always` (only if offered), or `deny` | +| `releaseFromAllowList` | `waiting` has entry | Unclaimed, matching rule key, `assertCurrent` passes before and after `prepareAllowListRelease`, still same `waiting` entry and not aborted | removed by coordinator `withdraw` | Resolves waiter with replacement `allow_list` decision; `finally` clears `claimed` if still waiting | +| abort / Bot pause | live entry | Signal aborts | removed from `requests` and `waiting` | Withdraws as `cancelled`, rejects waiter; late `decide` and `releaseFromAllowList` return `false` | + +Fixed defects, reproduced by test in `main/services/bot-runtime/bot-approvals.test.ts`: + +- **Stale `Always` scope leak across `waitId` reuse:** `coordinator.request` keyed `decisionPayloads` by `captured.waitId`, and an abort or replacement between `decide(..., "allow", "always")` and `complete()` resuming threw before `takeDecisionPayload` ran. A subsequent wait reusing the same `(botId, waitId)` with a plain one-shot `allow` (even without `always` offered) read the leaked `{ scope: "always" }` and resolved to `allow_always`. Each attempt now keys its payload by a private monotonic `attemptId` and drains it in `finally`. +- **Synchronous stale window and re-entrant replacement on publish throw:** `options.publish` throwing left `requests` and `waiting` populated until `complete()`'s microtask `finally` ran (allowing synchronous `pending()`, `releaseFromAllowList`, or retry joins to observe the failed entry), and a re-entrant same-id replacement whose `publish` threw overwrote the enclosing prompt in `waiting` so the enclosing prompt's withdrawal received the replacement's prompt. Unsettled publish throws now clean up `requests` and `waiting` synchronously (restoring any enclosing `waiting` entry) and withdraw once as `unavailable`. +- **Late `decide` metadata mutation:** `decide` now refuses already-aborted waits and rolls back `claimed`/`source`/`decisionSource` if `coordinator.decideAsHost` returns `false`. ## P2b: Remote pairing and single-use capabilities diff --git a/docs/state-machines/bot-execution-and-peers.md b/docs/state-machines/bot-execution-and-peers.md new file mode 100644 index 0000000000..99528cf164 --- /dev/null +++ b/docs/state-machines/bot-execution-and-peers.md @@ -0,0 +1,81 @@ +# Bot execution and Bot peers + +Phase contracts for `main/services/bot-runtime/bot-execution.ts` (390 lines) and `main/services/bot-peers/service.ts` (332 lines). + +## Bot execution (`main/services/bot-runtime/bot-execution.ts`) + +Owner: `main/services/bot-runtime/bot-execution.ts` (`createBotExecutionRegistry`, `withBotExecutionAdmission`, `createBotBackgroundExecutionModels`, `reconcileBotExecutionResponses`). Behavioral oracle: `main/services/bot-runtime/bot-execution.test.ts`. + +### Durable documents + +- `BotExecutionDoc` (`aiden.execution-binding`, task-scoped): binds `claimId`, `requestId`, `sourceInputs`, `dispatchGeneration`, `dispatchIds` (max 256), `operations` (`{ key, requestFingerprint }`, max 256), `costConsent`, `costDecision`, and `blocked` (`spending_unknown` | `unavailable`). +- `BotCostReceiptScopeDoc` (conversation-scoped): holds a UUIDv4 `nonce` (`responseScopeId`) initialized before any provider receipt reconciliation or publication. + +### Wrapped task phases (`GenerationTask`, `ToolTask`, `CompactionTask`) + +Every phase handler (and `abort`) runs inside `invoke`: + +| Step | Guard / invariant | Failure behavior | +|---|---|---| +| 1. Bind & verify sources | Reads `BotExecutionDoc` (or `LiveDoc.run.inputs` for `GenerationTask`). `resolveSources` loads 1–64 placed submissions, verifies all share one `claimId`, checks exact `peerOrigin` provenance when `selected.peer` is set (and rejects ambient peer metadata otherwise), and idempotently records `submissionId`. Commits `BotExecutionDoc`. | Throws immediately (no model resolution or dispatch). | +| 2. Offline response reconciliation | Initializes/validates `BotCostReceiptScopeDoc.nonce` (`responseScopeId`). Calls `reconcileBotExecutionResponses`: reconciles response costs, then verifies each `aiden.execution.response.` memo (`version: 2`) via `port.verifyResponse(facts)` before calling `port.recordKnownResponse`. Does not require live credentials. | Calls `block(error)`. | +| 3. Resolve runtime & typed fallback | Runs `port.resolve(botId, claim, runtime.signal)` inside `claimScope`. Fallback (`selectFallback`) is permitted **only** on `BotRoutineModelUnavailableError` when `phase` is `"prepare"` or `"select"`, `claim.fallback` exists, `!claim.startedAt`, and `claim.actual === "primary"`. | On `abort`, rethrows so the outer `abort` handler settles locally with `getModel: () => undefined` and calls `port.dismissed`. Otherwise calls `block(error)`. | +| 4. Checkpoint & model lock | If `checkpoint.model` is present, its `provider`, `modelId`, and `thinkingLevel` must match the resolved claim. `executionModels` enforces `exact(model)` on every call so prepared work cannot retarget. | Releases runtime and throws. | +| 5. Execute inside `BotExecutionScope` | Revalidates runtime, prepares optional `registrySnapshot` (skipped on `abort`), checks image-input capability during `GenerationTask:prepare` (blocks with `BotExecutionImageError` unless `inspect_image` companion is offered), runs original handler, and calls `port.dismissed` on `abort` or `settledTerminal`. | Releases helper runtimes and main runtime in `finally`. | + +`block(error)` commits `BotExecutionDoc.blocked` (`spending_unknown` when `error instanceof SpendingDispatchError && error.code === "uncertain"`, else `unavailable`), notifies `options.onBlocked`, and waits for `runtime.signal` to abort before throwing. + +### Provider receipt verification and deferred terminal guard (`#L129-260`) + +- **Request identity & replay (`saved`):** Records `{ key: operationKey, requestFingerprint }` in `BotExecutionDoc.operations` (refusing mismatched request bodies or >256 rows). Checks `runtime.memo(memoKey)`; if present, both `matching(receipt)` and `port.verifyResponse(facts)` must succeed (SQLite memos are untrusted hints). For fresh (non-`previousDispatch`) calls with no exact memo, scans prior generations' verified accountable memos (excluding `deferred`/`pending`) in descending `generation` order and replays the first verified accountable response without re-dispatching. +- **Seal before memo (`remember`):** On a fresh observation (`observed = true`), computes `responseFacts` and calls `execution.sealResponse(facts, amount)` (omitting `amount` for `pending`/`deferred` or unverified cost) before `runtime.memo(memoKey, envelope)` and re-verifying `matching(saved) && verified(memoKey, saved)`. +- **No synthetic zero charge on unverified deferred error/abort (`#L181-191`):** When `previousDispatch` is set (`fetchDeferred`), `stored.stopReason` is `"error"` or `"aborted"`, and `!botExecutionAccountableResponse(stored)`, `remember` checks whether `BotExecutionDoc.costDecision` holds a verified person cost approval (`decision.dispatchId === dispatchId`, matching `BotCostReceiptScopeDoc.nonce`, `toGeneration === fromGeneration + 1`, `dispatchGeneration >= fromGeneration`, and `verifyCostApproval(...)`) or `execution.isDispatchSettled(dispatchId)` is true. If so, it triggers `settledDeferredTerminal()` (which disables retry and compaction on `scoped.settings` and calls `port.dismissed` after the phase ends) and returns `stored` **without calling `execution.afterDispatch`**: the outcome stays an error/abort, no synthetic zero charge is written, and the deferred job is not polled again. +- **Deferred polling (`fetchDeferred` / `cancelDeferred`):** Authenticates the originating `dispatchId` via the in-memory `deferred` map or a verified persisted memo (`originatingDispatch`), calls `reserve()` (protected response slot without opening a second `beforeDispatch` budget reservation), and seals/verifies the poll result. +- **Child task provenance (`scoped.commit`):** Automatically stamps `BotExecutionDoc.sourceInputs` onto newly created `GenerationTask` children from `LiveDoc.run.inputs`, and propagates `claimId`, `requestId`, and `sourceInputs` onto `ToolTask` and `CompactionTask` children. +- **Background execution (`createBotBackgroundExecutionModels`):** Separate model proxy for detached reviews; fixes the admitted model, runs `revalidate → beforeDispatch → revalidate → started → afterDispatch` per sequential `dispatchId`, and rejects `fetchDeferred`/`cancelDeferred`. + +## Bot peers (`main/services/bot-peers/service.ts`) + +Owner: `main/services/bot-peers/service.ts` (`createBotPeerService`) and `renderer/shared/bot-peers.ts` (wire types and parsers). Behavioral oracle: `main/services/bot-peers/service.test.ts`. + +### Serialization and state persistence + +All state writes run through one keyed serial queue (`serial = createKeyedSerial()`, key `"state"`). Each mutation loads JSON (`<= 2 MiB`), validates every invariant (`validateState`), checks prospective serialized capacity (`publicationBytes`) before reserving external link slots, and writes via `options.persistence.write(previousBytes, nextBytes, assertCurrent, isCurrent)` with a fresh `state.revision`. + +### Exchange, delivery, and stop states + +- **Exchange states (`BotPeerExchangeState`):** `waiting`, `queued`, `running`, `interrupted`, `stopping`, `completed`, `failed`, `cancelled`, `expired`, `uncertain`. +- **Delivery / return states (`Delivery.state`):** `reserved → waiting → queued → delivered` (projected as `not_applicable` for `status`/`fyi` returns). +- **Stop receipt states (`BotPeerStopState`, `renderer/shared/bot-peers.ts#L60`):** five states — `requested`, `uncertain`, `stopped`, `not_running`, `blocked` — with optional `reason` (`mixed_inputs`, `host_unavailable`, `stale_source`). `pendingStop(exchange)` is true while `lastStop.state` is `requested` or `uncertain`. + +| Stop path | Prior condition | `lastStop.state` | Exchange transition | +|---|---|---|---| +| `stop()` on terminal, `fyi`, or `status` | Valid revision and new `mutationId` | `not_running` | Unchanged; receipt stored for idempotent replay. | +| `stop()` on active `request`/`question` | Valid revision, no pending stop | `requested` | Cascades `state = "stopping"` across up to 3 hops of unresulted descendants, then invokes `stopProgress()`. | +| `stopProgress()` sees `mixed_inputs` | Target shares a live run with other inputs | `blocked` (`mixed_inputs`) | `state = "uncertain"`, `blockedReason` set. | +| `stopProgress()` sees `uncertain` or active descendants | Stop unconfirmed or child return undelivered | `uncertain` (`host_unavailable`) | `state = "uncertain"`, `blockedReason` set. | +| `stopProgress()` sees retired recipient | `!recipientPublication` | `not_running` | `markResult(..., { outcome: "failed" })`. | +| `stopProgress()` confirms stop or unadmitted delivery | `stopped \|\| !row.delivery.submissionId` | `stopped` | `markResult` with `expired` (if past `expiresAt`) or `cancelled`. | +| `stopProgress()` sees nothing running | Not stopped, delivery existed | `not_running` | Runs `completeBranch()`; if still unresulted, marks `failed`. | + +`stopProgress()` returns early without mutating while `deliveryInFlight.has(id)` so an in-flight admission settles first. + +### Passive publication fence (`BotPeerPublication.assertCurrent`) + +`publication(expected, valid)` builds a host-only `BotPeerPublication` (`{ botId, incarnation, assertCurrent }`) used by `rowPublication`, `rootPublication`, and `finalPublication`. `assertCurrent()`: +1. Reloads state and verifies `valid(state)` (record exists, not retired, incarnation matches), +2. Checks live `owner(botId).incarnation === frozen.incarnation`, +3. Reloads state a second time and re-verifies `valid(state)` to close any retirement race during the owner check. + +Every runtime row, receipt read, link activation, evidence read, and final publication rechecks `assertCurrent()`. `PublicationProof` records (`state.publications`, max 512) preserve passive final-delivery authority across `prune()` until `settleFinalPublication` records `settledAt` (re-openable via `retainFinalPublication`). + +### Execution leases (`AbortController`) + +`executionLease(binding)` verifies `bindingCurrent(binding)` and creates an `AbortController` indexed in `leases` (`${pairId}:${exchangeId}`) with WeakMaps recording every ancestor `pairId`, `pairGeneration`, `botId`, `rootId`, and `branchId` (up to 4 hops). + +- `revalidate()` checks `controller.signal.throwIfAborted()` both before and after `bindingCurrent(binding)`. +- Leases abort synchronously on pair revocation (`revokeLeases`, and `abortStaleLeases` on failed revoke or reconcile), Bot pause/removal (`abortBotLeases`, `forgetBot`), and initiating task/branch stop (`stopSource`). + +### Single-flight reconciliation (`reconcile`) + +`reconcile()` deduplicates concurrent callers via a shared `pumping` promise and loops up to 4 rounds until `state.revision` stops changing: aborts stale leases, cleans up links, publishes sender/recipient rows, closes stale unresulted exchanges (`closeStale`), advances `stopProgress` or `deliver` + `completeBranch`, delivers terminal returns (`deliver(..., true)`), and runs `finalize(rootId)` once every activating exchange in a root has a terminal result, delivered return, and no pending stop. diff --git a/docs/state-machines/physical-teardown.md b/docs/state-machines/physical-teardown.md index 09efa7a42c..3666471dfb 100644 --- a/docs/state-machines/physical-teardown.md +++ b/docs/state-machines/physical-teardown.md @@ -54,7 +54,7 @@ The flags in `main/index.ts` (`backend:M001`) stay where they are. Each is writt |---|---|---| | `backend:M112` | `follow-through/background-jobs.ts` | Not audited beyond `recordCheckGroup`. | | `backend:M125`, `M126`, `M130`, `M156`, `clients:C43` | Browser, device helper host, terminal, Ghostty | Not audited. | -| `cli-native:N13`, `O01` | iMCP launcher, bounded-command guard | Not audited. | -| Rank 13 capture and input owners, including `M131`, `M133`–`M138` | Recording, dictation, speech, TTS | Not audited. Permission and device behavior needs real hardware evidence, which this slice did not gather. | -| Rank 14 remainder: `M002`–`M004`, `M165`, `M192` | Startup and updater owners | `M002` already has a pure core. The others were not audited. | -| Shutdown and restart trace across P1 to P4 | All lanes | Needs the P2, P3 and P4 work on one branch, which has not merged. | +| `cli-native:N13`, `O01` | iMCP launcher (`native/imcp-launcher`), bounded-command guard (`scripts/bounded-command-guard.mjs`) | Not audited. Cross-referenced with `cli-native:N01`–`N04` above (out of bounds for this slice). | +| Rank 13 capture and input owners: `backend:M131`, `M133`, `M134`–`M137`, `M138` | Recording, dictation, speech, TTS | Not audited (`M134`–`M137` included). Permission and device behavior needs real hardware evidence, which this slice did not gather. | +| Rank 14 remainder: `backend:M002` (pure core), `M003`, `M004`, `M165`, `M192` | Startup and updater owners | `M002` already has a pure core; `M003`, `M004`, `M165`, and `M192` were not audited. | +| Shutdown and restart trace across P1 to P4 | All lanes | Not yet run end-to-end across the landed P1–P4 owners (`retained-p1-owners.md`, `state-machine-worksheets-lane-b.md`, `remote-durable-operations.md`). | diff --git a/docs/state-machines/proactive-aiden.md b/docs/state-machines/proactive-aiden.md new file mode 100644 index 0000000000..cf973d31ea --- /dev/null +++ b/docs/state-machines/proactive-aiden.md @@ -0,0 +1,158 @@ +# Proactive Aiden state machines + +State-machine reference for the owners introduced or extended by Proactive Aiden (PR `#879`). + +## Chat orchestration (`main/services/chat-orchestration/`) + +### `ChatLinkStore` (`links.ts`, `links-main.ts`) + +Persists one `ChatLink` per started child chat in `chat-orchestration.json` (mode `0600`, max 8 MiB, max 5,000 links, newest 64 retain `resultSchema` and `result`, last 16 `delivered` run IDs). + +- **Restore & persist:** `restore()` loads once (shared promise); damaged links are dropped and a damaged document reads empty. Writes serialize through `writes` with single-slot coalescing (`queued`); a failed save is logged while memory stays current. +- **Authority & trust invariants:** + - Depth 1 only (`childChatId !== leadChatId`, first link wins, started chats never receive `child_chats`). + - `startedChatTurnCeiling` narrows the link's stored `ceiling` (or `LOST_LINK_CEILING` — `Ask`, no Mac grants — when only `startedBy` survives after a link loss or `deleteChat`) against the lead's current workspace policy on every turn. + - `personTookOver(link)` holds once `tookOverAt > (leadSentAt ?? 0)` (`markPersonTookOver` in `links-main.ts`). + - `startedChatRunTrust(link)`: if `leadTainted === true`, child runs start `tainted: true`, and `judgeTrusted` is `false` until `personTookOver(link)` is true. + - `childTainted` is sticky (`markChildTainted` writes once) and marks lead notices with `outside: true`. + - `deleteChat(chatId)` removes both the chat's own link and links of chats it started. + +### `ChatRunCore` (`run-core.ts`) + +Shared run follower and request deduper for any caller driving Remote chat/stream services: + +- **Snapshot states (`ChatRunSnapshot`):** `running`, `waiting_for_input`, `waiting_for_approval`, `done` (`completed` | `stopped`), `failed` (`interrupted` | `error`). Terminal stream states (`CHAT_RUN_TERMINAL_STATES`): `done`, `error`, `cancelled`, `interrupted`. +- **Bounded wait (`wait`):** Returns immediately if already non-`running` or aborted; otherwise watches stream changes and re-probes once after attaching (`look()`) to close the attach race. Resolves `{ kind: "snapshot" | "closed" | "aborted" }`. Timeout returns the current snapshot without stopping the run. +- **Request dedupe (`request`):** Keyed by `owner + "\0" + requestId`. In-flight requests are joined and never evicted; settled successes are cached up to `REQUEST_CACHE_LIMIT` (128); failures delete their entry so callers may retry. +- **Revocation (`forget(owner)`):** Aborts every active wait (`closed`), drops tracked runs, and clears cached requests for `owner`. + +### `ChildChats` (`child-chats.ts`) + +Drives started chats through `chats` and `streams` under audience `chat:`: + +- **`start`:** Validates every `resultSchema` up front (`compileResultSchema`). Derives deterministic keys (`childChatKey(leadChatId, callKey, index)`). If `create` fails after creating the chat or worktree and before `links.add` persists, it removes the chat and discards the new worktree. Replays find the existing link by key and reuse `link.runId`. +- **`send`:** Refuses if `personTookOver(link)`. Propagates `leadTainted` before sending. If `link.runId` is live, submits mid-flight input (`queue` when requested or when `link.resultSchema` is set, else `steer`); falls back to `startTurn` only on `run_not_active`. +- **`wait` / `stop` / `stopAll`:** `wait` blocks until `any` or `all` runs reach `done`/`failed` (approval/question waits do not end a turn), then calls `markTold` so completion notices do not repeat them. `stop` refuses if `personTookOver(link)`, cancels via `streams.cancel`, and marks the run told only after the stop succeeds. `stopAll` skips chats taken over by the person. +- **`follow`:** In-memory stream watcher (deduped in `followed`) that notifies `onChanged` on approval/question transitions and fires `onRunEnded` once a stream hits a terminal state (`childRunEnd`: `done`, `stopped`, `failed`, `interrupted`). + +### `ChildChatCompletions` (`completion-delivery.ts`) + +Coalesces child run endings into `chat` notices for the lead: + +- **`runEnded`:** Ignores already-`delivered` runs; persists `link.owed = { runId, end, at }` and arms a `CHILD_COMPLETION_GROUP_MS` (10 s) per-lead timer. +- **Quiet lead:** `quietLead(leadChatId)` (person pressed Stop in the lead) forces `wake: false` on flushed notices until `resumeLead(leadChatId)` (person sends again). +- **Settlement (`settle`):** Clears `link.owed` and appends to `link.delivered` on any non-`dropped` outcome; clears `link.owed` without marking delivered only when `outcome.gone === true`. Transient drops leave `link.owed` intact. +- **Startup recovery (`recoverOwed`):** Posts remaining `link.owed` entries per lead with `wake: false` (or merges them into an already-pending group), re-checking `stillOwed` before each post in case `wait` already consumed them. + +## Keep-going goals (`main/services/goal/`) + +### Pure state machine (`goal-core.ts`) + +Statuses: `active`, `paused`, `needs-you`, `done`. Every mutation increments `revision`; system writes use `compareAndSetGoal(current, { id, revision }, update)` so a person's Pause, Clear, or replacement always wins over an in-flight review or check. + +- **Limits:** `GOAL_MAX_ROUNDS` (50) for reviewed goals, `GOAL_CHECK_MAX_ROUNDS` (5) for command (`check`) goals, `GOAL_MAX_STALLS` (3 consecutive repeated `continue` reasons or quiet rounds with 0 tool calls and `< GOAL_SUBSTANTIAL_TEXT_CHARS`), `GOAL_MAX_UNUSABLE_REVIEWS` (2), `GOAL_WAIT_LIMIT_MS` (30 minutes for `wait`/helper/prompt expiry). +- **Transitions:** + - `restoreGoal`: any `active` goal from another `boot` ID comes back `paused` (`cause: "restart"`). + - `goalAfterSettle`: checks `active`, matching `boot`, `!stopped`, `!lastRunFailed`, `rounds <= maxRounds`, and `helperRunning` (sets `waitingSince` and returns `skip`, or pauses `wait-limit` after 30 min), then routes to `check` or `review`. + - `applyGoalVerdict`: unusable answer increments `unusableReviews` (`retry-review` once, then pauses `reviewer`); `done` → `done`, `blocked` → `needs-you`, `paused` → `paused (asked)`, `wait` → keeps `active` with `waitingSince` (pauses `wait-limit` at 30 min), `continue` → checks stall/round limits then increments `rounds`. + - `applyGoalCheck`: `passed` → `done`; else increments `rounds` up to `maxRounds` (`round-limit`). + - `goalNoticeRound`: counts a waking notice as a round for reviewed goals (pausing `round-limit` at cap) and spends no check for command goals. `goalRoundNotStarted` rolls back an unstarted round count. + - `resumeGoal`: moves non-active goal back to `active` at `rounds: 1`, `stalls: 0`, `unusableReviews: 0`, current `boot`. + - `windowWanted` is preserved only on `blocked` and `stalled` stops and cleared on new rounds or `windowRoundStarted`. + +### Loop coordinator (`goal-loop.ts`) + +`GoalLoop` coordinates one `reviews` look, one `relooks` idle-wait, and one `watchdogs` 30-minute timer per chat: + +- After `runSettled`, drops any in-flight look (restoring an uncounted round via `dropLook`), waits `GOAL_SETTLE_DELAY_MS` (1.5 s), backs off to `relookWhenIdle` if busy, then runs pre-checks, review/check, CAS write, and `startRound` guarded by `isCurrent()`. +- `noticeRound` drops any stale look, counts the round, and starts the notice round; if it fails to start, rolls back the round count and schedules `relookAfterNotice`. +- `promptExpired` → `needs-you (unanswered)`; `windowClosed` → `paused (chat-closed)`; `accessChanged` → `paused (access-changed)`; `shutdown` sets `stopped = true` and aborts all reviews, relooks, and watchdogs. + +## Keep-awake controller (`main/services/keep-awake/keep-awake-core.ts`) + +Pure controller over injected `KeepAwakeInput`s, `KeepAwakeBlocker`, `KeepAwakeClock`, and `idleSeconds()`: + +| Condition | Blocker state | Timers | +|---|---|---| +| `!enabled` or `disposed` | Released immediately | Grace and idle poll cleared (`dispose` also clears `recheckTimer`). | +| `reasons.length > 0`, idle cap reached (`>= 4 h`) and no exempt reason | Released (`pausedWhileIdle: true`) | Idle poll (`60 s`) keeps running to re-acquire when the person returns. | +| `reasons.length > 0`, active or exempt (`check-back`, `wake-up`) | Acquired (`holding: true`, `pausedWhileIdle: false`) | Grace cleared; idle poll (`60 s`) active. | +| `reasons.length === 0` while holding | Kept during `KEEP_AWAKE_GRACE_MS` (`60 s`), then released | Idle poll stopped; grace timer armed once. | + +`recheckAt` across inputs schedules one bounded `recheckTimer` clamped to `[1 s, 1 h]`. Status changes publish only when serialized `KeepAwakeStatus` changes. + +## Scheduled task link trigger (`main/services/scheduled-task-link-trigger.ts`) + +Two-stage webhook gate (`admit` before body read, `tooLarge` on body abort, `deliver` after read) with **two separate per-task rate buckets** plus one global unknown-token bucket: + +1. **Global unknown-token bucket:** `UNKNOWN_LINK_CALLS_PER_MINUTE` (120/min). An unknown token returns `404` until exhausted, then `429`, without touching any real link's quota. +2. **Per-task admission bucket (`recent`):** `callsPerMinute` (60/min), reserved in `admit` with a unique admission ID **before** reading the task (so a disabled known token still consumes its link's 60/min and returns `404` without releasing its slot). +3. **Per-task refusal bucket (`refused`):** `REFUSED_LINK_CALLS_PER_MINUTE` (30/min), completely separate from `recent`. + +| Response | Slot behavior (`recent`) | Refusal bucket (`refused`) & logging | +|---|---|---| +| `429` | Pre-slot refusal (no slot taken) | Not charged to `refused`. | +| `404` (known disabled/non-webhook token) | **Retained** in `recent` (not released) | Not logged. | +| `415` (wrong content type) | **Released** via `refuse(taskId, admission)` (or fast-rejected pre-slot if `refused >= 30/min`) | Charged to `refused`; not logged. | +| `413` (body > 256 KB, via `tooLarge` or `deliver`) | **Released** via `refuse(taskId, admission)` | Charged to `refused`. | +| `401` (bad/missing HMAC-SHA256 signature) | **Released** via `refuse(taskId, admission)` | Charged to `refused`; logs coalesced `bad_signature` only for first 30/min. | +| `400` (invalid JSON or depth > `MAX_JSON_DEPTH` 32) | **Released** via `refuse(taskId, admission)` | Charged to `refused`; logs coalesced `invalid` only for first 30/min. | +| `202` (filtered, duplicate, daily_limit, held, queued) | Kept in `recent` | Always answers `202` with empty body so callers learn nothing about the task. | + +Batching helpers (`mergeLinkBatches`, `linkEventText`) hold up to 20 calls (`SCHEDULED_TASK_LINK_LIMITS.batch`), dropping oldest calls and trimming the longest entries to stay within `maxChars`. + +## Follow-through delivery and checks (`main/services/follow-through/`) + +### `NoticeDelivery` (`notice-delivery.ts`) + +Serializes delivery per `chatId` via `chains` (`post` and `inOrder`). `hasPending(chatId)` is true while chained unless the chat is in `waitingOnRun`. + +1. Probes `queueIntoRun(post)` (up to `MAX_ATTEMPTS = 4`): + - `queued` → returns `{ kind: "queued" }`. + - `saved` (run ended right after persist) → `wakeSaved`: tries `startGoalRound` (attended, no wake budget), else `startTurn` within `MAX_WAKES_PER_CHAT_PER_HOUR` (6/h rolling window), else returns `{ kind: "recorded" }`. + - `rejected` → `waitForIdle` and retry. + - `busy` (foreign-owned run holds the chat, identified by `holder`): if `holder` already matched `outlasted.get(chatId)`, skips straight to `record()`. Otherwise waits once on `waitForRunToSettle` and retries; if still busy, waits on `waitForRunToEnd` (1 day bound), records `outlasted` if unsettled, then records without waking (calling `onError` if dropped and `!gone`). +2. When `no-run`: if `wake`, tries `startGoalRound` first, then `startTurn` (if `wakesLeft > 0`), else `record()` (up to 4 attempts of `append` / fallback `queueIntoRun` / `waitForIdle`, returning `dropped` with `gone: true` when the chat is gone). + +### `GoalCheckRunner` (`done-when.ts`) + +Runs at most one command check per `chatId` (10-minute timeout, 3,000-char fenced tail): + +- Starting a new check for a chat aborts and awaits the previous check (`previous.settled`) before registering the new `RunningCheck`. +- `stopChat(chatId)`, `interruptWorkspace(workspaceId)`, and `shutdown()` (sets `closed = true`) abort matching controllers and await `settled`. +- `goalCheckResult` returns `{ kind: "stopped" }` on abort or `CheckInterruptedError`, else `{ kind: "finished", passed: exitCode === 0 && !timedOut, summary, details }`. +- `migrateDoneWhenRecords` migrates legacy `waiting`/`running` `/until` records into `paused` (`cause: "restart"`) command goals while retaining unreadable chats in `kept`. + +## Event routine dispatcher and watches (`main/services/bot-routine-events/`) + +### `createEventRoutineDispatcher` (`dispatcher.ts`) + +Shared owner-keyed event core for Bot routines and chat trigger tasks: + +- **Admission (`emit`):** Under per-owner `store.mutate`, rejects paused/disabled/stale `watchRevision`, deduplicates against `seenEventIds`, `held`, and `running`, enforces daily cap (`perDay`, default 24), and enforces minimum gap (`minGapMs`, default 5 min) or full `running` slots (`BOT_EVENT_RUNNING_MAX`) by holding the event (replacing or merging via `mergeHeld`) and arming `heldTimers`. When immediately admitted, snapshots original task/condition (`prepare`) and writes a durable `running` receipt (`claimPending: true` if `claimRoutineExecution` is wired) **before** calling `claimAndStart`. +- **Two-phase claim & run (`claimAndStart` → `start`):** `claimAndStart` completes `claimRoutineExecution` and clears `claimPending` durably before `start` runs. `start` re-reads the store, checks `sameSource` and `watchRevision`, acquires `authorizeRun` for watches, re-reads after authorization, and invokes `dependencies.run`. Only `settled !== false` removes the `running` receipt; throws or `settled: false` leave it for `rearm()`. +- **Requeue & drop notices (`requeue`, `reconcileRequeue`, `showDrops`):** Atomically drops `settles` from `running`, optionally refunds the daily count, and either merges back into `held` (respecting `notBefore`) or records a durable `dropNotices` entry past `maxRetries`. A failed `requeue` write triggers exponential-backoff `reconcileRequeue` (`5 s` → `5 min`); `showDrops` tracks `shownParts` so no notice part is shown twice across retries up to `BOT_EVENT_DROP_NOTICE_TRIES`. +- **Lifecycle fence:** `dispose()` bumps `generation` and cancels all `heldTimers` and `recoveryTimers`; in-flight work from an earlier generation never starts a run even after `resume()`. `idle()` drains all tracked `pending` promises. + +### `createEventWatches` (`watch.ts`) + +Periodic watch runner keyed by owner: + +- **Single-flight per watch:** `inFlight` prevents overlapping checks of the same routine; `rearm()` is serialized (`rearming` chain) and aborts in-flight checks whose `updatedAt` moved or whose routine was disabled/removed. +- **Durable transition before dispatch:** `performCheckNow` records `baseline`, `no_change`, `error` (3 consecutive failures or `check.pause === true` disable the watch and notify `paused`), or `changed`. On `changed` (hash diff, semantic connector change, or non-empty `reportsOutput`), it saves the new hash/baseline **and** `watch.pending` (`eventId`, `payload`, `revision`, `nextAttemptAt`) in one `store.mutate` before calling `deliverPending`. +- **Pending delivery (`deliverPending`):** Re-authorizes via `authorizeDispatch` (pausing on error), emits to `dispatcher.emit` with `watchRevision` and `isCurrent`, and clears `watch.pending` only on durable dispatcher acceptance (`queued`, `held`, `duplicate`, `daily_limit`). Otherwise reschedules `nextAttemptAt` 60 s later. +- **Lifecycle:** `dispose()` increments `generation`, aborts all `inFlight` checks, and cancels all timers. + +## Schedule service core (`main/services/schedule-service-core.ts`) + +Owner: `main/services/schedule-service-core.ts` (`createScheduleServiceCore`, `createCatchUpQueue`). + +- **Per-task serialization (`withTaskLifecycle`):** Serializes `start` scheduling, `save`, `remove`, `pause`, `resume`, `rescheduleAll`, and `resumeWorkspace` per `taskId`. Mutations stop the cron job and `cancelAndSettle(taskId)` before persisting, and roll back + re-arm on `signal.aborted` or store error. +- **Single-slot execution (`runningTasks`):** One active `RunningTask` per `taskId`. A new dispatch skips (`already-running`) unless the prior entry is obsolete automatic preparation (`automatic && !executionStarted && !isCurrent()`), which is superseded. `runEvent` loops and awaits the running task's promise so trigger events for one task run sequentially. +- **Startup & catch-up (`createCatchUpQueue`, `startupRevision`):** `start()`, `stop()`, and `setGlobalEnabled()` bump `startupRevision` so stale startup reads and cron callbacks fail `isCurrent()`. Missed runs queue through `createCatchUpQueue` (`CATCH_UP_CONCURRENCY = 2`, `CATCH_UP_STAGGER_MS = 3 s`, optional `shouldDefer` policy, `clear()` bumps queue generation). +- **Chat task guards (PR `#879`):** + - Automatic fires > `CHAT_TASK_LATE_LIMIT_MS` (12 h) late (with no newer occurrence inside 12 h) advance the schedule and record `result: "skipped", reason: "too_late"` without executing. + - `CHAT_TASK_FAILURES_TO_PAUSE` (3) consecutive unattended failures (`error` or non-cancelled `blocked`, ignoring `skipped`, cancelled, and manual failures) disable the chat task (`failurePausedAt`) and invoke `pausedAfterFailures`. + - Trigger tasks (`task.trigger`) do not arm a `Cron` job; `runEvent` rejects with `ScheduledTaskIneligible` (`missing` | `paused` | `no_trigger`) when ineligible. +- **Bot routine recovery (`pendingRoutineFires`):** `queuePendingRecovery` and the periodic `scanPendingRoutines` timer (60 s, exponential backoff up to 15 min) replay pending fires and delayed retries (marking superseded retries `observeOnly: true` so the executor only checks receipts). +- **Workspace fencing & shutdown:** `cancelWorkspace` adds `workspaceId` to `blockedWorkspaces`, stops matching jobs, awaits `workspaceReady`, and settles running tasks. `stopAndSettle()` cancels all tasks and bounds shutdown wait to 5 seconds. diff --git a/docs/state-machines/remote-durable-operations.md b/docs/state-machines/remote-durable-operations.md new file mode 100644 index 0000000000..14e34b5130 --- /dev/null +++ b/docs/state-machines/remote-durable-operations.md @@ -0,0 +1,135 @@ +# Remote durable operations and named state machines + +Formal record of the P3 (`#746`–`#750`) and P4 (`#751`–`#754`) state-machine work landed on `main` (summarized during rollout in `.memory/remote-durable-operations.md`). No serialized snapshot format, existing API fixture, or Aiden Remote protocol revision changed; `protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json` is a new contract fixture recording existing phone outbox behavior. + +## Idempotency ledger (`aiden-remote-durable-operation.ts`) + +Owner: `main/services/aiden-remote-durable-operation.ts` (persist adapter), `main/services/aiden-remote-operation-state.ts` (pure phase reducer), and `main/services/aiden-remote-operation-contract.ts` (ledger, error classes, snapshot bounds). Behavioral oracles: `main/services/aiden-remote-durable-operation.test.ts` and `main/services/aiden-remote-operation-contract.test.ts`. + +`executeAidenDurableOperation` is the only persist adapter for Remote mutations. Six services use it: `aiden-remote-bots.ts`, `aiden-remote-chats.ts`, `aiden-remote-git.ts`, `aiden-remote-schedules.ts`, `aiden-remote-streams.ts`, and `aiden-remote-workspaces.ts`. Do not add inline admission or outcome writes elsewhere. + +### Phases and transitions (`advanceAidenOperation`) + +| Phase | Wire state | `expiresAt` | Meaning | +|---|---|---|---| +| `executing` | `in_flight` | `null` | Live owner in this process. | +| `unknown` | `in_flight` | `null` | No live owner; outcome is unconfirmed and never expires into a retry. | +| `fulfilled` | `fulfilled` | timestamp | Terminal success, replayable until expiry. | +| `rejected` | `rejected` | timestamp | Terminal contract rejection, replayable until expiry. | + +| Event | Prior phase | Next phase | Notes | +|---|---|---|---| +| `action_fulfilled` | `executing` | `fulfilled` | Unaccepted in other phases (late events are no-ops). | +| `action_rejected` | `executing` | `rejected` | Stores `errorCode`. | +| `outcome_lost` | `executing` | `unknown` | Action threw `AidenOperationUnknownOutcomeError` or result could not fit snapshot bounds. | +| `outcome_unrecorded` | `fulfilled`, `rejected` | `unknown` | Durable outcome write failed; disk still holds `in_flight`. | +| `reconciled_fulfilled` | `unknown` | `fulfilled` | Authoritative reconciliation only. | +| `reconciled_rejected` | `unknown` | `rejected` | Authoritative reconciliation only. | + +Because both `executing` and `unknown` serialize as `in_flight` with `expiresAt: null`, a process restart turns any in-flight admission into `unknown` without changing the stored format. + +### Two durable edges and commit points + +1. **Admission write (`in_flight`) before the action runs:** `settleDurably` persists `ledger.snapshot()` before calling `admit()`. If that write fails, the action never runs, the entry is dropped via `AidenOperationNotExecutedError`, and the caller gets `500 internal_error` (`notPreparedMessage`); the key remains reusable. +2. **Outcome write after the action settles:** `settleDurably` persists `ledger.snapshot()` again. If that write fails, `ownership.unrecorded()` transitions the live entry to `unknown` and throws `409 idempotency_in_flight` (`outcomeUnrecordedMessage`). The key never re-runs—even past the normal TTL—until reconciled. +3. **Single-writer joins and replays:** Only the call with `ownership` persists. Concurrent joins and replays wait on the owner's `unfinishedOperations` promise so they answer with the owner's durable result rather than an unpersisted in-memory result. +4. **Pre-effect and receipt-backed retries:** Both `AidenOperationNotExecutedError` (nothing committed) and `AidenOperationReplaySafeRetryError` (the underlying action keeps its own durable exact receipt, used by `main/services/aiden-remote-bot-session.ts`) delete the ledger entry and rethrow `cause`. If saving that deletion fails, the caller still receives `409 idempotency_in_flight` and disk retains the admission. +5. **Peer hosts:** On the desktop peer client (`main/handlers/peer-host-live.ts`, `renderer/lib/hosts/remote-host-adapter.ts`), a host's `409 idempotency_in_flight` (or lost/ambiguous answer) maps to `outcome_unknown`, keeping the send unresolved under its idempotency key rather than retrying blindly. + +## Telegram Bot reply outbox (`BOT_REPLY_ROW_TRANSITIONS`) + +Owner: `main/services/telegram/bot-reply-outbox.ts`. + +Every outbox row moves exclusively through `advanceBotReplyRow` and the `BOT_REPLY_ROW_TRANSITIONS` table; direct `row.state =` writes outside that helper are a bug. An in-memory `delivering` guard serializes delivery attempts per `requestId`. + +States: `awaiting`, `pending`, `sending`, `sent`, `interrupted`, `dismissed`, `failed`. + +| Event | Valid prior states | Next state | Meaning | +|---|---|---|---| +| `answered` | `awaiting`, `interrupted` | `pending` | Bot answer saved to the row. | +| `turn_interrupted` | `awaiting`, `interrupted` | `interrupted` | Turn paused/interrupted; Resume may still answer. | +| `turn_dismissed` | `awaiting`, `interrupted` | `dismissed` | Person stopped or dismissed the turn (terminal). | +| `send_started` | `pending` | `sending` | First send attempt started; outcome is unknown until confirmed. | +| `redelivery_started` | `sending` | `sending` | Single duplicate-labelled retry (`(may be a duplicate)`). | +| `send_confirmed` | `sending` | `sent` | Telegram delivery confirmed (terminal). | +| `send_abandoned` | `pending`, `sending` | `failed` | Retries exhausted or target gone (terminal). | + +Events that do not match the row's current state return `undefined` and leave the row untouched, preventing a stale lock copy from repeating a finished send. + +## Phone Bot outbox failure steps + +Shared fixture: `protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json` (`maxConnectionAttempts: 3`). Implementations: `aidenBotOutboxFailureStep` in `ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift` and `android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt`. + +### Failure classification + +- **Ambiguous (`ambiguous: true`):** `500 internal_error`, `503 internal_error`, `408 internal_error`, `429 rate_limited`, `409 idempotency_in_flight`. +- **Definite refusal (`ambiguous: false`):** `409 idempotency_conflict`, `409 internal_error` (replayed settled rejection), `400 invalid_request`. + +### Next step (`aidenBotOutboxFailureStep`) + +| Condition | Step | +|---|---| +| Definite refusal with lost uploads (iOS only) | `refused_attachments_gone` | +| Any other definite refusal (with or without echo) | `refused` | +| Ambiguous, `attempts < 2` | `retry_later` | +| Ambiguous, `attempts >= 2`, untagged echo present (`echoed && !echoNamesSubmission`) | `settled_by_echo` | +| Ambiguous, `attempts >= 2`, no echo or echo belongs to another submission | `out_of_tries` | + +## Subagent file mutation transaction (`TransactionPhase`) + +Owners: `native/subagent-file-mutator/main.c` (`enum TransactionPhase`) and `main/services/subagents/subagent-file-mutation-transaction.ts` (`commitSubagentFileMutation`). Behavioral oracle: `main/services/subagents/subagent-file-mutation-transaction.test.ts`. + +### Native phases (`enum TransactionPhase`) + +`PHASE_IDLE` → `PHASE_INSPECTED` → `PHASE_PREPARED` → `PHASE_COMMITTED` (plus `PHASE_IDLE` → `PHASE_PREPARED` without prior inspect, and `PHASE_INSPECTED | PHASE_PREPARED` → `PHASE_IDLE` on cancel or pre-publish refusal). + +- **Point of no return:** `PHASE_COMMITTED` begins at namespace publication (the atomic rename), before parent `fsync` or recovery-file cleanup. `recovery_unlinked` and `commit_parent_synced` track durability independently. An indeterminate commit stays `PHASE_COMMITTED` so the recovery file is never treated as disposable. +- Changing `native/subagent-file-mutator/main.c` requires refreshing prebuilt binaries for all three targets. + +### TypeScript settlement (`commitSubagentFileMutation`) + +| Outcome | Meaning | +|---|---| +| `not_committed` | Commit threw while helper state was neither `committed` nor `indeterminate`; original file intact. | +| `unknown` | Commit threw while helper state was `committed` or `indeterminate`; recovery preserved if possible. | +| `committed` | Published and recovery file unlinked (or no recovery file needed). | +| `recovery_kept` | Published; `finalize` failed, `preserve` succeeded. | +| `cleanup_unknown` | Published; both `finalize` and `preserve` failed. | + +## Managed worktree removal journal + +Owner: `main/services/managed-worktree-removal-core.ts` (`managedWorktreeRemovalPhaseAllowed`, `removeManagedWorkspace`). Behavioral oracle: `main/services/managed-worktree-removal-core.test.ts`. + +Ordered phases: + +```text +prepared → quarantined → checkout_cleanup_started → checkout_complete → admin_cleanup_started → filesystem_complete +``` + +`managedWorktreeRemovalPhaseAllowed(from, to)` permits only: +1. One step forward in `REMOVAL_PHASE_ORDER`, +2. A same-phase write (`from === to`) to record a manifest digest, or +3. A transition to `needs_review` from any phase. + +Nothing leaves `needs_review`: once preserved for human inspection, no recovery path may walk it back into deletion. All 19 journal writers in `git.ts` were traced against this rule. `removeManagedWorkspace` invokes `onDestructiveBoundary()` whenever `deleteWorktree()` succeeds or throws without `destructiveMutationAttempted === false`, ensuring callers never restore workspace-scoped background work after Git deregistration or quarantine mutation begins. + +## Chat deletion settlement + +Owner: `main/services/chat-application-service.ts` (`ChatDeletionSettlement`, `chatDeletionSettlement`). + +| Settlement | Condition | Meaning | +|---|---|---| +| `completed` | `admissionReleased && chatRemoved` | Chat removed and no tombstone remains. | +| `rolled_back` | `admissionReleased && !chatRemoved` | Delete rolled back before tombstone commitment; chat stays usable. | +| `roll_forward_pending` | `!admissionReleased` | A durable tombstone may remain (or its status could not be read); fences stay closed for startup roll-forward. | + +## Deferred P4 owners + +The following owners were not changed in this pass and remain deferred: + +| Inventory | Owner | Status | +|---|---|---| +| `backend:M026` | Bot deletion | Deferred; unchanged. | +| `backend:M158` | Chat store | Deferred; unchanged. | +| `backend:M159` | Pi session compaction journal | Deferred; unchanged. | +| `backend:M147` | Image storage | Deferred; unchanged. | diff --git a/docs/state-machines/retained-p1-owners.md b/docs/state-machines/retained-p1-owners.md index d8ec182f69..7d398bcc9b 100644 --- a/docs/state-machines/retained-p1-owners.md +++ b/docs/state-machines/retained-p1-owners.md @@ -43,11 +43,11 @@ The P1b work changed no IPC, so these needed no adapter change. | Inventory | Owner | Disposition | Why | |---|---|---|---| | `clients:C02` | `renderer/lib/chat-message-queue.ts` | Retain | `claim`, `settle` and `deliverQueuedMessage` are the only route for delivering a queued message, and `chat-message-queue.test.ts` covers stale chats, drafts and unknown appends. | -| `clients:C03` | `renderer/main/chat-pane.tsx` | Deferred | The orchestration is spread through a 4,166-line view. Moving it needs a UI test harness first, and it holds no authority of its own: the host decides. | +| `clients:C03` | `renderer/main/chat-pane.tsx` | Deferred | The orchestration is spread through a 4,961-line view. Moving it needs a UI test harness first, and it holds no authority of its own: the host decides. | | `clients:C04` | `renderer/lib/generation-stream.ts` | Retain, one fix | One subscription per stream. The first terminal event now blocks any later terminal event, because listeners stay on while an async `onDone` settles. Disposal runs even if a terminal handler throws. | | `clients:C05` | `renderer/lib/chat-terminal-sync.ts` | Retain | Identity-keyed registries with bounded retries, covered by `chat-terminal-sync.test.ts`. Not re-audited beyond the entry points. | | `clients:C11` | `renderer/lib/hosts/remote-queue-fence.ts` | Retain | `remoteQueueFenceHolds` is pure and tested. Two overlapping `sendFencedTurn` calls can replace each other's fence. The 120 s stall bounds how long a fence can hold, but not the ordering. Whether two can overlap in practice was not established. | -| `clients:N15` | iOS `AidenChatFeature.swift` | Unchanged, not audited | No shared contract changed, so nothing here needed native work. That says nothing about how its ownership is structured. | +| `clients:N15` | iOS `Features/Chat/{AidenChatViewModel,AidenChatDetailView,AidenChatViewModel+ForeignRuns,AidenChatViewModel+Fork}.swift` and `Models/AidenChat.swift` (split from `AidenChatFeature.swift` across `6182b2e30..a9185707a`) | Unchanged, not audited | No shared contract changed, so nothing here needed native work. That says nothing about how its ownership is structured. | ## Run input transitions @@ -56,10 +56,12 @@ The P1b work changed no IPC, so these needed no adapter change. | Identify | Stream is live, chat and owner match, input open | `run_not_active` | Kept | | Stop check | No Stop, chat not being deleted | `cancelled` | Kept | | Queue probe | Queue would accept | The probe's reason | Kept | -| Persist | Still the live run and not stopped, checked inside the store write | `cancelled` or `run_not_active` | Kept | -| Recheck | Still the live run, not stopped | Same reasons, with `committed: true` | Consumed | -| Queue | Receipt accepted | The receipt's reason, with `committed: true` | Consumed | +| Hook screen | Optional `inputHooks.screen` for non-notice input; rechecks live stream, Stop/delete, and queue capacity | `run_not_active`, `cancelled`, or probe reason | Kept | +| Persist | Still the live run and not stopped, checked inside the store write; stamps `fromLeadChat` for non-notice lead inputs and `hookBlockedReason` when refused | `cancelled` or `run_not_active` (or `invalid` with `committed: true` if hook-blocked) | Kept (consumed if hook-blocked) | +| Post-persist hooks | Non-notice, non-`fromLeadChat` inputs notify `onPersonWrote(chatId)` (non-fatal, ends Inbox snooze); inputs carrying outside content call `generation.outsideInput()`; `fromLeadChat` inputs `await generation.leadChatInput()` (non-fatal, propagates lead taint before queueing) | Never refuses (message is already committed) | Consumed | +| Recheck | Still the live run (if ended, falls through to `owedTurn` registration when held and not stopped), not stopped | `cancelled`, `run_not_active`, or `follow-up` owed turn, with `committed: true` | Consumed | +| Queue | Receipt accepted (if `not-active`, tries `owedTurn`); attaches `hookContext` and runs `stopSubagentsForGuidance` on `steer` | The receipt's reason, with `committed: true` | Consumed | A persist whose outcome is unknown throws `AidenOperationUnknownOutcomeError`, as does a queue call that throws. Once the message is saved it stays saved: a late refusal reports `committed: true` and never replays the input. -The one fix: both the persist and recheck steps now treat a chat deletion that began during the save as a stop. Before, only the first check saw it, so input could reach a run whose chat was being deleted. +The one fix: both the persist and recheck steps now treat a chat deletion that began during the save as a stop. Before, only the first check saw it, so input could reach a run whose chat was being deleted. PR #879 added the post-persist `onPersonWrote`, `outsideInput()`, and awaited `leadChatInput()` steps between persistence and recheck/queueing, with `fromLeadChat` excluding lead-chat inputs from `onPersonWrote` while propagating taint before the model sees the message. diff --git a/main/services/bot-runtime/bot-approvals.test.ts b/main/services/bot-runtime/bot-approvals.test.ts index f438bf82a2..fd2e965fcc 100644 --- a/main/services/bot-runtime/bot-approvals.test.ts +++ b/main/services/bot-runtime/bot-approvals.test.ts @@ -196,3 +196,186 @@ for (const prepared of [false, true]) { assert.equal(await releasing, false); }); } + +test("bridge: publish throw after waiting registration withdraws once as unavailable and leaves no synchronous window", async () => { + const withdrawn: Array<[string, string]> = []; + const changes: string[] = []; + let prepared = 0; + let shouldThrow = true; + const bridge = createBotApprovals({ + publish() { + if (shouldThrow) throw new Error("window gone"); + }, + withdraw(prompt, outcome) { + withdrawn.push([prompt.waitId, outcome]); + }, + }); + bridge.onChange((botId) => changes.push(botId)); + const pending = bridge.request({ + ...rememberedRequest(), + prepareAllowListRelease: async () => { + prepared++; + return { id: "auto", authorizationFingerprint: "auto-fp", answer: "allow", source: "allow_list" }; + }, + }); + // Before awaiting rejection, waiting/requests must already be cleared. + assert.deepEqual(bridge.pending(), []); + assert.equal(bridge.decide("w1", "allow"), false); + assert.equal(await bridge.releaseFromAllowList("w1", grant), false); + assert.equal(prepared, 0); + await assert.rejects(pending, /unavailable/u); + assert.deepEqual(withdrawn, [["w1", "unavailable"]]); + assert.deepEqual(changes, ["bot-1"]); + + // A subsequent retry with the same key starts cleanly rather than joining the failed attempt. + shouldThrow = false; + const retry = bridge.request(request()); + assert.equal(bridge.pending().length, 1); + assert.equal(bridge.decide("w1", "allow"), true); + assert.equal((await retry).answer, "allow"); + assert.deepEqual(withdrawn, [["w1", "unavailable"], ["w1", "allowed"]]); +}); + +test("bridge: re-entrant replacement that fails to publish still withdraws the shown original with its own prompt", async () => { + const withdrawn: Array<[string | undefined, string]> = []; + let replacement: Promise | undefined; + const bridge = createBotApprovals({ + publish(prompt) { + if (prompt.authorizationFingerprint === "fp-second") throw new Error("surface gone"); + replacement = bridge.request({ ...request(), authorizationFingerprint: "fp-second" }); + }, + withdraw(prompt, outcome) { + withdrawn.push([prompt.authorizationFingerprint, outcome]); + }, + }); + const first = bridge.request({ ...request(), authorizationFingerprint: "fp-first" }); + await assert.rejects(first, /The approval was replaced\./u); + await assert.rejects(replacement!, /unavailable/u); + assert.deepEqual(bridge.pending(), []); + assert.deepEqual(withdrawn, [["fp-second", "unavailable"], ["fp-first", "cancelled"]]); +}); + +test("bridge: identical waitId, botId, and fingerprint join one card; different fingerprint or botId replaces it", async () => { + const published: Array<[string, string | undefined]> = []; + const withdrawn: Array<[string, string | undefined, string]> = []; + const bridge = createBotApprovals({ + publish(prompt) { + published.push([prompt.botId, prompt.authorizationFingerprint]); + }, + withdraw(prompt, outcome) { + withdrawn.push([prompt.botId, prompt.authorizationFingerprint, outcome]); + }, + }); + const first = bridge.request(request("w1")); + const joined = bridge.request(request("w1")); + assert.deepEqual(published, [["bot-1", "fp-w1"]]); + assert.equal(bridge.pending().length, 1); + assert.equal(bridge.decide("w1", "allow"), true); + assert.deepEqual(await Promise.all([first, joined]), [ + { id: "w1", authorizationFingerprint: "fp-w1", answer: "allow", source: "person" }, + { id: "w1", authorizationFingerprint: "fp-w1", answer: "allow", source: "person" }, + ]); + + const original = bridge.request(request("w2")); + const diffFp = bridge.request({ ...request("w2"), authorizationFingerprint: "fp-w2-v2" }); + await assert.rejects(original, /The approval was replaced\./u); + assert.equal(bridge.pending().length, 1); + assert.equal(bridge.pending()[0]?.authorizationFingerprint, "fp-w2-v2"); + + const diffBot = bridge.request({ ...request("w2"), botId: "bot-2", authorizationFingerprint: "fp-w2-v2" }); + await assert.rejects(diffFp, /The approval was replaced\./u); + assert.equal(bridge.pending("bot-1").length, 0); + assert.equal(bridge.pending("bot-2").length, 1); + assert.equal(bridge.decide("w2", "deny"), true); + assert.deepEqual(await diffBot, { id: "w2", authorizationFingerprint: "fp-w2-v2", answer: "deny", source: "person" }); + assert.deepEqual(withdrawn, [ + ["bot-1", "fp-w1", "allowed"], + ["bot-1", "fp-w2", "cancelled"], + ["bot-1", "fp-w2-v2", "cancelled"], + ["bot-2", "fp-w2-v2", "denied"], + ]); +}); + +test("bridge: late answers after abort, replacement, or Bot pause are rejected and cannot leak an Always scope", async () => { + const withdrawn: Array<[string | undefined, string, string | undefined]> = []; + let paused = false; + const bridge = createBotApprovals({ + publish() {}, + withdraw(prompt, outcome) { + withdrawn.push([prompt.authorizationFingerprint, outcome, prompt.decisionSource]); + }, + }); + + // Abort after an Always answer before settlement bookkeeping finishes must not leak scope onto a reused waitId. + const firstAbort = new AbortController(); + const first = bridge.request({ + ...request("w-leak"), + authorizationFingerprint: "fp-1", + always: { key: "k", count: 3 }, + signal: firstAbort.signal, + }); + assert.equal(bridge.decide("w-leak", "allow", "always"), true); + firstAbort.abort(new Error("bot paused")); + await assert.rejects(first, /bot paused/u); + assert.equal(bridge.decide("w-leak", "allow"), false); + + const reused = bridge.request({ ...request("w-leak"), authorizationFingerprint: "fp-2" }); + assert.equal(bridge.decide("w-leak", "allow"), true); + assert.deepEqual(await reused, { + id: "w-leak", + authorizationFingerprint: "fp-2", + answer: "allow", + source: "person", + }); + + // Replacement after a synchronous Always answer also must not leak scope onto the replacement. + const replaced = bridge.request({ + ...request("w-rep"), + authorizationFingerprint: "fp-a", + always: { key: "k", count: 3 }, + }); + assert.equal(bridge.decide("w-rep", "allow", "always"), true); + const replacement = bridge.request({ ...request("w-rep"), authorizationFingerprint: "fp-b" }); + await assert.rejects(replaced, /The approval was replaced\./u); + assert.equal(bridge.decide("w-rep", "allow"), true); + assert.deepEqual(await replacement, { + id: "w-rep", + authorizationFingerprint: "fp-b", + answer: "allow", + source: "person", + }); + assert.equal(bridge.decide("w-rep", "deny"), false); + + // Bot pause aborts the wait signal and fails assertCurrent; late decide and allow-list release both fail. + const pauseAbort = new AbortController(); + const waitingWhilePaused = bridge.request({ + ...rememberedRequest("w-pause"), + signal: pauseAbort.signal, + assertCurrent: async () => { + if (paused) throw new Error("Bot is paused."); + }, + prepareAllowListRelease: async () => ({ + id: "auto", + authorizationFingerprint: "auto-fp", + answer: "allow", + source: "allow_list", + }), + }); + await waitFor(() => bridge.pending().some((prompt) => prompt.waitId === "w-pause")); + paused = true; + pauseAbort.abort(new Error("Bot paused")); + assert.equal(bridge.decide("w-pause", "allow"), false); + assert.equal(await bridge.releaseFromAllowList("w-pause", grant), false); + await assert.rejects(waitingWhilePaused, /Bot paused/u); + await assert.rejects( + bridge.request({ + ...rememberedRequest("w-pause"), + assertCurrent: async () => { + if (paused) throw new Error("Bot is paused."); + }, + }), + /Bot is paused\./u, + ); + assert.deepEqual(bridge.pending(), []); + assert.deepEqual(withdrawn[withdrawn.length - 1], ["fp-w-pause", "cancelled", undefined]); +}); diff --git a/main/services/bot-runtime/bot-approvals.ts b/main/services/bot-runtime/bot-approvals.ts index 926647a824..9416eb01f9 100644 --- a/main/services/bot-runtime/bot-approvals.ts +++ b/main/services/bot-runtime/bot-approvals.ts @@ -62,6 +62,7 @@ function clearCallbacks(state: Waiting) { export function createBotApprovals(options: BotApprovalsOptions): BotApprovals { const requests = new Map(), waiting = new Map(); const listeners = new Set<(botId: string) => void>(); + let attemptSequence = 0; const changed = (botId: string) => { for (const listener of listeners) listener(botId); }; const coordinator = new ToolApprovalCoordinator(prompt => { const state = requests.get(prompt.approvalId); @@ -73,8 +74,25 @@ export function createBotApprovals(options: BotApprovalsOptions): BotApprovals { ...(request.owner ? { owner: structuredClone(request.owner) } : {}), ...(request.always ? { always: { ...request.always } } : {}), ...(request.autoWouldJudge ? { autoWouldJudge: true as const } : {}), ...(request.allowList ? { allowList: structuredClone(request.allowList) } : {}) }; + const previousWaiting = waiting.get(request.waitId); state.prompt = published; waiting.set(request.waitId, state); - options.publish(published); changed(request.botId); + try { + options.publish(published); + } catch (error) { + if (!state.controller.signal.aborted && !state.source) { + if (requests.get(request.waitId) === state) requests.delete(request.waitId); + if (waiting.get(request.waitId) === state) { + if (previousWaiting && previousWaiting !== state) waiting.set(request.waitId, previousWaiting); + else waiting.delete(request.waitId); + clearCallbacks(state); + try { options.withdraw?.(published, "unavailable"); } + catch { /* Presentation failure cannot retain an authorization capability. */ } + changed(request.botId); + } + } + throw error; + } + changed(request.botId); }, (id, outcome) => { const state = waiting.get(id); waiting.delete(id); if (state?.prompt) { @@ -110,20 +128,22 @@ export function createBotApprovals(options: BotApprovalsOptions): BotApprovals { if (input.signal?.aborted) abort(); requests.set(captured.waitId, state); const complete = async (): Promise => { + const streamId = `${STREAM_PREFIX}${captured.botId}`; + const attemptId = `${captured.waitId}:${++attemptSequence}`; try { - const streamId = `${STREAM_PREFIX}${captured.botId}`; const outcome = await coordinator.request({ streamId, approvalId: captured.waitId, - // Payloads are keyed by this private attempt ID, not a reused provider call ID. - toolCallId: captured.waitId, + // Payloads are keyed by this unique attempt ID, so a cancelled or + // replaced wait cannot leak its scope onto a later attempt. + toolCallId: attemptId, toolName: captured.toolName, summary: captured.summary, ...(captured.always ? { scopes: ["once", "always"] as const } : {}), }, state.controller.signal); state.controller.signal.throwIfAborted(); assertActive(captured); - const payload = coordinator.takeDecisionPayload(streamId, captured.waitId); + const payload = coordinator.takeDecisionPayload(streamId, attemptId); if (state.replacement) return state.replacement; if ((outcome !== "allowed" && outcome !== "denied") || !state.source) { throw new Error("The approval was withdrawn or unavailable."); @@ -136,6 +156,7 @@ export function createBotApprovals(options: BotApprovalsOptions): BotApprovals { }; } finally { clearCallbacks(state); + coordinator.takeDecisionPayload(streamId, attemptId); input.signal?.removeEventListener("abort", abort); if (requests.get(captured.waitId) === state) requests.delete(captured.waitId); if (waiting.get(captured.waitId) === state) { @@ -156,10 +177,16 @@ export function createBotApprovals(options: BotApprovalsOptions): BotApprovals { decide(id, decision, scope, source = "person") { const state = waiting.get(id); // Expiry grants nothing and must be able to withdraw a release held across an await. - if (!state || (state.claimed && !(source === "expiry" && decision === "deny"))) return false; + if (!state || state.controller.signal.aborted || (state.claimed && !(source === "expiry" && decision === "deny"))) return false; + const previousClaimed = state.claimed, previousSource = state.source, previousPromptSource = state.prompt?.decisionSource; state.claimed = true; state.source = source; if (state.prompt) state.prompt.decisionSource = source; - return coordinator.decideAsHost(id, decision === "allow", scope ? { scope } : undefined, source === "person"); + const settled = coordinator.decideAsHost(id, decision === "allow", scope ? { scope } : undefined, source === "person"); + if (!settled) { + state.claimed = previousClaimed; state.source = previousSource; + if (state.prompt) state.prompt.decisionSource = previousPromptSource; + } + return settled; }, async releaseFromAllowList(id, input) { const state = waiting.get(id), grant = structuredClone(input); From 63936f9becd86b81cd4177db2d4e611f274b1810 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 05:47:47 +0000 Subject: [PATCH 2/2] docs(state-machines): clarify ChildChats.wait exit paths and markTold scope --- docs/state-machines/proactive-aiden.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/state-machines/proactive-aiden.md b/docs/state-machines/proactive-aiden.md index cf973d31ea..754ca18b54 100644 --- a/docs/state-machines/proactive-aiden.md +++ b/docs/state-machines/proactive-aiden.md @@ -32,7 +32,7 @@ Drives started chats through `chats` and `streams` under audience `chat: