Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .memory/explicit-state-machines-lane-b.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
20 changes: 17 additions & 3 deletions docs/audits/state-machine-worksheets-lane-b.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
81 changes: 81 additions & 0 deletions docs/state-machines/bot-execution-and-peers.md
Original file line number Diff line number Diff line change
@@ -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.<sha256>` 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.
8 changes: 4 additions & 4 deletions docs/state-machines/physical-teardown.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`). |
Loading
Loading