From 46d849bbe76351dfed58c7cfdf4a8557d4491290 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 05:31:17 +0000 Subject: [PATCH 1/2] docs(state-machines): reconcile P5 remainder, P6, and Tier-A queue with targeted race/teardown tests --- .../p5-p6-tier-a-reconciliation.md | 228 ++++++++++++++++++ docs/state-machines/physical-teardown.md | 127 +++++++++- .../bot-runtime/bot-session-service.test.ts | 24 ++ main/services/browser/core.test.ts | 32 +++ .../follow-through/background-jobs.test.ts | 93 +++++++ main/services/git-executable.test.ts | 147 +++++++++++ main/services/schedule-service-core.test.ts | 67 ++++- main/services/scheduled-bot-routines.test.ts | 35 +++ .../subagents/subagent-supervisor.test.ts | 137 +++++++++++ 9 files changed, 879 insertions(+), 11 deletions(-) create mode 100644 docs/state-machines/p5-p6-tier-a-reconciliation.md diff --git a/docs/state-machines/p5-p6-tier-a-reconciliation.md b/docs/state-machines/p5-p6-tier-a-reconciliation.md new file mode 100644 index 0000000000..93e54c54ec --- /dev/null +++ b/docs/state-machines/p5-p6-tier-a-reconciliation.md @@ -0,0 +1,228 @@ +# P5/P6 and Tier-A state-machine reconciliation + +Source-verified transition tables, invariants, commit points, and dispositions for the open P6 owners and the deferred / dense Tier-A reading queue on `main`. Nothing here is marked a defect unless reproduced by a behavioral test. + +Dispositions follow the existing state-machine worksheets: +- **Retain:** transitions and linearization points are already centralized and guarded; keep authoritative code as-is (extending behavioral race/teardown tests where gaps exist). +- **Deferred:** extraction remains deliberately deferred with an explicit architectural precondition and no defect found. +- **Unresolved inventory ID on `main`:** the legacy inventory ID appears in a lane worksheet, but no master inventory table exists on `main` to map that ID to a file path; live authority owners in the same area are audited directly by path instead. + +--- + +## 1. Open P6 owners + +### 1.1 `main/services/schedule-service-core.ts` — Retain + +Owns cron job registration (`jobs`), active task execution slots (`runningTasks`), per-task mutation serialization (`lifecycleTails`), workspace blocks (`blockedWorkspaces`), staggered catch-up (`createCatchUpQueue`), and periodic pending-routine-fire recovery (`pendingRecoveryQueued`, `pendingRetryAt`). + +#### Axes +- **Service lifecycle:** `stopped` (`started = false`) vs `running` (`started = true`, fenced by monotonic `startupRevision` and `globallyEnabled`). +- **Task slot (`runningTasks`):** absent, `preparing` (`executionStarted = false`), `executing` (`executionStarted = true`), with `cancelRequested` flag and `workspaceReady` barrier. +- **Catch-up queue (`createCatchUpQueue`):** bounded concurrency (`2`), staggered starts (`3 s`), lock-screen deferral (`shouldDefer`), fenced by monotonic `generation` on `clear()`. + +#### Transitions + +| Event | Guard | Next / Effect | +|---|---|---| +| `start()` | `!started` | Sets `started = true`, bumps `startupRevision`, starts pending-retry timer, schedules enabled tasks under `withTaskLifecycle`, queues pending Bot fire recovery before overdue catch-up. On error while current, resets `started = false` and clears jobs/timers. | +| `dispatch(taskId)` | `runningTasks.get(taskId)` absent, or stale pre-execution automatic entry (`!executionStarted && !isCurrent()`) | Inserts `RunningTask`. Re-checks `expectedUpdatedAt`, `blockedWorkspaces`, `started && globallyEnabled`, `task.enabled` (with exact one-off paused catch-up exception), `isCurrent()`, and due `fireTime` (throwing `UnclaimableScheduledFire` if already claimed or future). | +| `advanceBeforeRun` | Automatic non-recovery fire | For Bot routines: `store.claimRoutineFire` (optionally running `claimRoutineExecution` write-ahead before publishing the pending fire). For one-off chat tasks: disables task atomically. Marks `state.executionStarted = true` before `execution.run`. | +| `save` / `remove` / `pause` / `resume` | Serialized by `withTaskLifecycle(taskId)` + optional `expectedUpdatedAt` | Stops cron job and awaits `cancelAndSettle(taskId)` before durable write. On caller `AbortSignal` after commit (`saveWithRollback` / `pauseWithRollback` / `resume`), rolls back durable state and rearms prior schedule. | +| `cancelWorkspace(workspaceId)` | Synchronous add to `blockedWorkspaces` | Stops matching cron jobs, awaits `workspaceReady` on snapshot of `runningTasks`, cancels and settles matching runs. | +| `stop()` / `stopAndSettle()` | Any | Bumps `startupRevision`, sets `started = false`, stops pending-retry timer, clears catch-up queue (`generation += 1`), stops all crons, sets `cancelRequested = true`, calls `execution.cancelAll()`. `stopAndSettle()` races `cancelAndSettle()` against a 5 s shutdown cap. | + +#### Invariants & commit points +- **Claim linearization:** For Bot routines, `store.claimRoutineFire` publishes the pending fire (and optional frozen execution claim) before `executionStarted` flips; a cancelled preparation before that point cannot publish a pending fire. +- **Overlap isolation:** Active runs (`executionStarted = true`) and manual runs are never superseded by automatic triggers; `runEvent` serializes per task by awaiting the active `runningTasks` promise. +- **Oracles:** `main/services/schedule-service-core.test.ts` (`npm run test:scheduled`). + +--- + +### 1.2 `main/services/scheduled-bot-routines.ts` — Retain + +Owns `createBotRoutineExecutor` (execution and crash recovery of one Bot routine fire) and strict IPC/CRUD routine management (`parseBotRoutine*`, `projectBotRoutine`). + +#### Transitions (one routine fire `run(task, { runId, trigger, signal })`) + +| Phase | Guard / Input | Next / Outcome | +|---|---|---| +| Idempotent recovery (`recovering`) | `replayable(trigger)` (`automatic`, `retry`, `event`) and `runId === requestId` | Reads `store.runById(task.id, requestId)`. If a prior durable `ScheduledRun` exists: repairs stale task summary, retries idempotent `deliver`, settles pending fire, and returns `prior` without re-running the Bot. | +| Admission probe | `recovering` with no prior run | Queries `ports.submissionForRequest(task.botId, requestId)`. If `retry` is `observeOnly` with no submission, settles fire and throws `UnclaimableScheduledFire`. If paused/disabled with no submission, records `blocked` without submitting. | +| Execute: claim & state check | Not recovering or no `existingSubmissionId` | Optional write-ahead `ports.claimExecution`; inspects `ports.state(botId)`. `paused` → `skipped(paused_by_person)` (or `RoutineOutcomeUnknown` if an admitted fire exists); `interrupted` without `existingSubmissionId` → `skipped(bot_paused)`; `needs_model` → `RoutineFailure`; `unavailable` → error. | +| Execute: retry safety | `trigger.kind === "retry"` and `!verifiedToolFree` | Verifies every prior attempt via `ports.canRetryRoutineRequest`; fails closed with `retry_effect_unknown` if any prior attempt may have executed tools. | +| Execute: submit & await | `wakeUpAllowed` (for wake-ups) and `!signal.aborted` | Calls `ports.send(..., { requestId, ifNotInterrupted: true })`. On send failure for `replayable(trigger)`, re-reads `submissionForRequest` — an admitted or unreadable lookup becomes `RoutineOutcomeUnknown` (never a false terminal failure). Awaits `ports.awaitReply`; abort/transport error on `replayable` becomes `RoutineOutcomeUnknown`. | +| Settle & deliver | Outcome resolved or caught | Writes durable `store.recordRun` (with `id: requestId` for durable/catch-up fires, omitting `id` for `duplicate` or `uncertain` so the real fire's ID stays free). Runs advisory `afterRun` (healing/retry/pause) and fire-and-forget `observeRoutineHooks` (`RoutineRun` / `RoutineFailed`). Calls `deliver` unless silent/skipped/retrying; if delivery throws, keeps pending fire receipt so startup retries delivery without re-running. Calls `store.settleRoutineFire` only when `durableFire(trigger) && !outcome.uncertain`. | + +#### Invariants & commit points +- **At-most-once submission per fire:** `botRoutineRequestId` is deterministic (`routine::`), reused by catch-ups and crash recovery. +- **Unknown-outcome preservation:** Cancellation or lost reply on a replayable trigger sets `uncertain = true`, records `blocked`, suppresses failure notification/hooks, and leaves `pendingRoutineFires` unsettled for recovery. +- **Oracles:** `main/services/scheduled-bot-routines.test.ts` (`npm run test:scheduled`). + +--- + +### 1.3 `main/services/bot-runtime/bot-session-service.ts` — Retain + +Also retained under `backend:M024` in `retained-p1-owners.md`; re-audited here for P6 routine/pause/execution-claim/deletion interactions. + +#### Axes +- **Per-Bot serialization:** `serialize = createKeyedQueue()` serializes `send`, `resume`, `dismiss`, `stop`, `stopLinkedWork`, `withdraw`, `compact`, `deleteBot`, `pause`, `unpause`, `submissionForRequest`, `canRetryRoutineRequest`. +- **Durable state (`BotSessionState`):** `unavailable` (profile lock held elsewhere) | `paused` (persisted in `BotPauseStore`, fail-closed on unreadable file) | `running(submissionId)` | `interrupted(submissionId, blocked?)` | `needs_model` | `model_error` | `idle`. +- **Terminal fences:** `deleted` (loaded from durable `bots/pending-deletes.json` at construction before any open) and `shuttingDown` (set synchronously in `shutdown()`). + +#### Transitions + +| Command | Guard | Next / Effect | +|---|---|---| +| `initialize()` | `host !== null` | Finishes every Bot in `pending-deletes.json`, sweeps orphan sessions against `knownBotIds()`, reads `interruptedBots()` without starting any scheduler, and publishes their state. | +| `send(botId, input)` | Validates provenance (`routineOrigin`, `peerOrigin`, `botMessage`, no `steer` under `deps.execution`), checks `deleted` | Inside `serialize(botId)`: dedupes by `requestId` first (`lookupRequest`); enforces `assertNotPaused`, `peer.assertCurrent()`, `spendingRefusal`, `ifNotInterrupted`, `ifIdle`; claims execution/model (releasing unsubmitted plain claim on refusal); dismisses prior interrupted turn if allowed; writes notices and submits to `pi-durable`. | +| `resume(botId, requestId, options)` | `consumeBotResumeOperation` durable idempotency + `assertNotPaused` | Reconciles `BotExecutionDoc` tasks and unknown-cost approvals (`costConsent` verified via `verifyCostApproval` before `acknowledgeUnknown`), clears `blocked`, calls `harness.resume()`, and publishes state. | +| `dismiss` / `stop` / `withdraw` | Per-Bot queue; `dismiss` checks `assertNotPaused` | `dismiss` dedupes via bounded `answered` map, isolates peer-shared inputs, aborts paused turn, writes `interrupted` notice, calls `onStopped`. `stop` guards `expectedSubmissionId` so a successor turn is spared. `withdraw` aborts only queued (unplaced) submissions. | +| `pause` / `unpause` | `pause` checks `!deleted`; durable write first | `pause` writes `BotPauseStore` before calling `onPaused`, bounds `host.suspend` (tracking timed-out closes in `suspending` + `reopenAfterSuspend`), runs `afterPaused`, and publishes `paused`. `unpause` clears pause under queue, then runs `onUnpaused` outside queue so skipped-routine notices can `appendEntry` without deadlock. | +| `awaitReply(botId, submissionId, signal)` | Never starts a paused scheduler | Checks `inspection.scheduling === "paused"` before `submission.wait`; on wait failure (`replyAfterFailedWait`), `deleted` → `{ kind: "interrupted", settled: true }`, `BotHarnessHostClosedError` (quit) → `{ kind: "interrupted" }`, reopened settled submission → returns committed `settledOutcome`, else `failed`. | +| `appendEntry` | Outside command queue (own SQLite tx) | Re-checks `deleted` and `shuttingDown` both before and after any `effectId` idempotency scan inside `conversation.commit`. | +| `deleteBot(botId)` | `requireHost()` (never deletes while another process holds profile lock) | Adds to `deleted`, persists `pending-deletes.json`, runs `beforeDelete`, `host.destroy(botId)`, sequential idempotent `deleteEffects`, then removes from `pending-deletes.json`. | +| `shutdown()` | Any | Sets `shuttingDown = true`, awaits `host?.shutdown()`. | + +- **Oracles:** `main/services/bot-runtime/bot-session-service.test.ts` (`npm run test:bot-runtime`). + +--- + +### 1.4 `main/services/bot-routine-notifications.ts` — Retain + +Stateless read-only feed projection (`createBotNotificationFeed`) over `BotDeliveryLog.due(since, now() - 1)`. + +- **Cursor invariant:** Upper bound is `now() - 1` so rows committing in the current millisecond are never skipped by the client's next exclusive `since` cursor. +- **Capability & quiet filtering:** Drops `row.quiet === true`, missing Bots (`botName === undefined`), and capability-gated classes (`issue` requires `options.issues`, `access_needed` issues require `options.accessRequests`, `peer_result` requires `options.peers`, `bot_message` requires `options.messaging`). Failed routine rows always substitute `BOT_ROUTINE_FAILED_PREVIEW` rather than leaking raw error text; bodies are redacted through `redactRemoteText`. Caps response at `AIDEN_REMOTE_BOT_ROUTINE_NOTIFICATIONS_MAX` (100) and validates via `parseAidenRemoteBotRoutineNotificationList`. +- **Oracles:** `main/services/bot-routine-notifications.test.ts` (`npm run test:bots`). + +--- + +### 1.5 `main/services/aiden-remote-streams.ts` — Retain + +Owns remote chat generation stream journals, SSE replay/backpressure (`openCursorSse`), pending remote approvals and questions, and aggregate persistence budgets. + +#### States (`AidenRemoteStreamState`) +- **Live:** `queued`, `running`, `waiting_for_approval`, `reconciling`. +- **Terminal:** `done`, `error`, `cancelled`, `interrupted`. + +#### Transitions + +| Event | Guard | Next State / Effect | +|---|---|---| +| `create(deviceId, streamId, chatId, turnId)` | Unique `streamId`, `streams.size < 256` (after `prune()`) | Creates `StreamRecord` in `queued`, mints `RemoteChatGenerationOwnerController`, records durable `turnIndex`, appends immediate-persist `status(queued)` event. | +| `append` (content/delta) | `!terminal(stream.state)` | Coalesces undelivered deltas within `persistCoalesceMs` (1 s) while `openDelta` matches; structural/boundary events persist immediately, content deltas coalesce. | +| `projectNotification("chat:approval" \| "chat:question")` | Live stream | Arms expiry timer (5 min for devices, 30 min for chat audience), transitions stream to `waiting_for_approval`, persists immediately. | +| `resolveApproval` / `resolveQuestion` | Entry exists in `approvals` / `questions` | Clears expiry timer, removes entry, invokes host coordinator (`approve` / `respondQuestion`). If live: coordinator rejected → `reconciling`; another pending prompt on same stream → re-emits surviving prompt in `waiting_for_approval`; none left → `running`. | +| Terminal `append` (`done`, `error`, `cancelled`, `interrupted`) | Not already terminal | Invalidates `stream.owner`, clears all pending approval/question timers for `streamId`, notifies subscribers & chat listeners, persists immediately. Subsequent `append` calls are no-ops returning the last event. | +| `enforceAggregateBudget` | Snapshot > 16 MiB | Evicts oldest terminal streams with no replay subscriber; marks terminal streams with active replay subscribers `evictAfterDelivery = true` (evicted only when `onClose(finished = true)` confirms complete terminal flush). | +| `revokeDevice(deviceId)` | Any | Denies/cancels all device approvals and questions, cancels live streams (`source: "server"`), invalidates owners, closes all subscribers, deletes streams, and awaits `settlePersistence()`. | + +- **Oracles:** `main/services/aiden-remote-streams.test.ts` (`npm run test:aiden-remote`). + +--- + +## 2. Deferred and dense Tier-A reading queue + +### 2.1 `backend:M100` — `main/services/subagents/subagent-supervisor-core.ts` — Deferred (audited, behavioral gaps closed) + +- **Why previously deferred (`retained-p1-owners.md`):** Cancellation, cleanup, and budget settlement span top-level `execute()` and nested `executeNestedBatch()` paths. +- **Audit findings:** + - **Ordering & barrier invariants:** Top-level `execute()` validates abort/guidance/tree-expiry/tree-budget/launch-budget, allocates safe IDs, captures fork context (if `fork`), resolves child models (atomic batch refusal if any model is rejected), runs `prepareRun` via `Promise.allSettled`, checks abort/failure before any projection, projects all tasks and awaits `projector.flush()`, then marks `childrenLaunched = true` and registers `stopLiveForGuidance`. + - **Pre-projection failure cleanup:** Any throw before projection (or abort during `prepareRun`) runs `abortPreparation(reason)` on every fulfilled `PreparedSubagentRun` and never projects or increments `this.launches` (in V2, `this.launches` updates in `finally` from `ledger.snapshot().launched`). + - **Post-projection failure & cancellation:** `abortExecution(kind, reason)` records first `cancellationKind`, aborts `executionController`, cancels `treeScheduler`, and arms `settlementTimer` (`cancellationGraceMs`) to resolve `settlementSeal`. Each task races `childOperation` against `settlementSeal`; a sealed child records a cleanup failure (`healthMetrics.cleanupFailed()`). `preparedRun.complete(result)` returns `"stopped"` to fence late settlement from overwriting a canonical stop; `finishRun` dedupes `SubagentStop` hooks (`stoppedRuns`) and non-interrupted terminal health metrics (`terminalHealthRuns`). + - **Nested path (`executeNestedBatch`):** Revalidates depth-1 delegation authority, checks remaining generation-wide turn/network-operation allowance, reserves descendants synchronously via `lease.runDescendants` behind a `startBarrier`, extends ledger allowance, projects + flushes, then releases `startBarrier`. On flush failure, `rejectStart(reason)` + `input.abortTree(reason)` + `Promise.allSettled([nestedExecution])`, then outer `catch` completes projected runs and aborts unprojected preparations. + - **Disposition:** Keep **Deferred** for structural extraction (splitting `SubagentSupervisor` into a pure transition reducer requires refactoring both `execute` and `executeNestedBatch` across 1,852 lines with no reproduced ordering bug; P5a process settlement is now landed). Added targeted behavioral tests in `main/services/subagents/subagent-supervisor.test.ts` for abort-during-`prepareRun` cleanup and nested `projector.flush()` failure teardown. + +### 2.2 `backend:M163` — `main/services/config-store-core.ts` — Retain + +- **Axes:** Split-layout migration gate (`seedPromise`, single-flight), secret migration state (`secretMigrationComplete` / `secretMigrationDeferred` / `secretMigrationPromise`), corrupt/unsafe file guards (`loadedFromCorruptFile`, `loadedFromUnsafeFile`, `normalizePortableConfig`), and session-seeded monotonic TTS settings revision. +- **Transitions & invariants:** + - `ensureSeeded()` runs `configStores.ensureMigrated()`, refuses to write if local or portable files are corrupt/unsafe, runs `migratePiProviderConfig` over a composite draft (portable intent + cached model metadata), validates the migrated document against `normalizePortableConfig` before publishing, writes `~/.aiden/config.json` only on real diff (preserving hand-edited JSON), remaps provider-keyed local settings (`lastProviderId`, hidden models, Model Pad, thinking, compaction overrides), and captures `secretMigrationAliases`/`secretMigrationTargets`. + - `attemptSecretMigration()` runs once per process; unresolved future-version records set `secretMigrationDeferred = true` and log once without clobbering; thrown keychain errors clear `secretMigrationPromise` so the next read can retry. + - `ensureWebSearchSettings()` and `ensureApprovalModeSettings()` are one-shot local JSON backfills that bail out on corrupt files or existing markers without overwriting unsupported future values. +- **Oracles:** `main/services/config-store-core.test.ts`, `main/services/portable-config-core.test.ts`, `npm run test:config-recovery`. + +### 2.3 `backend:M166` — Analytics consent (`main/services/analytics/analytics-consent.ts`, `analytics-service.ts`) — Retain + +- **Why previously deferred:** Lane B deferred while PRs #732–#734 were modifying analytics. Those changes have landed on `main`. +- **Pure consent rules (`analytics-consent.ts`):** `analyticsSendStatus` requires all four gates: `!envDisablesAnalytics(env)` (`DO_NOT_TRACK` / `AIDEN_ANALYTICS=0`), `state.enabled === true`, `hasKey === true`, and `state.noticeShownAt` set. `disableAnalytics` strips `installId`; `enableAnalytics` never reuses an old `installId` (`ensureInstallId` mints a fresh UUID v4 only when sending activates). +- **Service lifecycle (`analytics-service.ts`):** + - Consent mutations (`setEnabled`, `markNoticeShown`) and `onboardingFinished` serialize through `consentQueue` (`inOrder`). `changeConsent` synchronously bumps `actionEpoch`, drops `heldUntilStarted`, and increments `pendingConsentChanges` before awaiting storage so concurrent feature events or delayed `actionReporter()` callbacks are dropped immediately. + - `activate()` fences async `store.update` + `createTransport()` with monotonic `generation`; if `stop()` or `cancelStartup()` bumped `generation` mid-activation, the newly created transport is discarded via `created.discard()`. + - `turnOff()` captures at most one `analytics_disabled` message via `sendNow`, calls `stop()` synchronously (`revokeQueue()`, clears timer/core/installId, notifies renderer `onSendingChanged(false)`), persists `enabled: false` (restoring via `activateIfAllowed()` if `isCurrent()` lost ownership), deletes any pending crash file, sends `captureOptOut` bounded to `1.5 s`, and always calls `stopping.discard()`. + - `shutdown(timeoutMs = 1_500)` sets `shutdownRequested = true`, bumps `actionEpoch`, drains `consentQueue` + up to `timeoutMs / 3` of startup, cancels startup, stops the hourly timer, and flushes `transport.shutdown` + `crashSends` within `timeoutMs + 250 ms`. +- **Oracles:** `npm run test:analytics`. + +### 2.4 `backend:M026` & `main/services/bot-application-service.ts` — Bot deletion and lifecycle journal — Retain + +- **Two-layer crash-safe roll-forward:** + 1. `bot-session-service.ts` (`deleteBot`): verifies profile lock ownership (`requireHost()`), adds `botId` to in-memory `deleted`, durably records `botId` in `bots/pending-deletes.json` before its first destructive step, runs `beforeDelete`, `host.destroy(botId)`, then sequential idempotent `deleteEffects`, and removes `botId` from `pending-deletes.json`. On crash, `initialize()` replays every pending delete before exposing any Bot. + 2. `bot-application-service.ts` (`finishDeleteBot`, backed by `bot-lifecycle-journal-core.ts` `M035`): under `mutationGate.run(botId)`, begins or resumes a `delete_bot` journal entry (`prepared → identity_deleted`). Invalidates Bot authority, deletes photo, approval rules (best-effort), browser profile, managed home, capability authority, all Bot chat rows (via `deleteChatWithEffects`), and finally deletes the Bot record last (`botStore.delete(botId)`) before advancing to `identity_deleted` and completing the journal. Keeping the Bot record last guarantees a crash leaves the Bot visible to startup recovery and rolls forward cleanly. +- **Other `bot-application-service.ts` mutations:** `create_bot`, `create_chat`, `copy_chat`, `delete_chat`, `update_model` all follow strict forward stage tables (`STAGES`) in `bot-lifecycle-journal-core.ts`, retry inventory-lease races up to 3 times (`withFreshInventoryLease`), and poison mutations (`recoveryFailure`) if startup recovery cannot complete an interrupted operation. +- **Oracles:** `main/services/bot-application-service.test.ts`, `main/services/bot-runtime/bot-delete.test.ts`, `main/services/bot-lifecycle-journal-core.test.ts` (`npm run test:bots`, `npm run test:bot-runtime`). + +### 2.5 `backend:M158` — Chat store (`main/services/chat-store-core.ts`) — Retain + +- **Concurrency & durability model:** + - Per-chat locks (`withLocks` sorted lexicographically for deadlock-free multi-chat ops) + dedicated `INDEX_LOCK`. + - Shared vs exclusive maintenance gate (`enterShared` / `runMaintenance`): waits for `activeShared === 0` (`drained()`), retries any `pendingDirectorySync`, sweeps crash-leftover temp files (`removeCrashLeftStages`) on first init, reconciles `.chat-transaction..pending` records (`reconcileChatTransactions`), and rebuilds/validates the in-memory `index.json` memo. External modifications to `index.json` are detected via stat stamp (`ino:size:mtimeNs:ctimeNs`) and invalidate `memo`. + - Corrupt chat payloads under `"owner"` / `"exclusive"` policies are quarantined verbatim (`*.corrupt`) rather than silently truncated; `"pure"` reads never write. +- **Oracles:** `main/services/chat-store-core.test.ts`, `main/services/chat-append-commit.test.ts`, `main/services/chat-fork-service.test.ts` (`npm run test:slash-commands`). + +### 2.6 `backend:M159` — Pi journal & compaction (`main/services/pi-compaction-core.ts`, `pi-session-port.ts`, `pi-session-migration.ts`) — Retain + +- **Journal write contract (`pi-session-port.ts`):** Every structural mutation (`appendCompaction`, `appendBranchSummary`, `appendCustomEntry`, `appendMessage`, `importBranch`, `moveTo`) runs inside a single `session.mutate` transaction reading and updating `branchTip("main")` atomically (no torn tip/entry writes). +- **Compaction transitions (`pi-compaction-core.ts`):** Explicit `PiCompactionEvent` (`start` / `end`) and `PiCompactionCheckResult` failure codes (`context-overflow`, `retry-exhausted`, `compaction-failed`, `host-inference`, `host-policy`, `session-failed`, `unsafe-rollback`). Cached-prefix summaries require exact branch/context/memory hash match (`prefixContinuesContext`), verify no forgotten memory fact was restated (`MemoryFactInSummaryError`), and fall back or abort cleanly on `AbortSignal` (`CompactionAbortedError`). +- **Oracles:** `main/services/pi-compaction-core.test.ts`, `main/services/pi-session-port.test.ts`, `main/services/pi-session-migration.test.ts`, `main/services/pi-journal-fork.test.ts` (`npm run test:compaction`). + +### 2.7 `backend:M147` — Image storage (`main/services/display-image-artifact-store.ts`, `chat-image-store.ts`) — Retain + +- **`DisplayImageArtifactStore`:** Backed by `DataStore` with strict schema validation (`rejectCorruptWrite`, `rejectUnsafeWrite`), 100-record and byte/pixel caps. `initialize()` quarantines unreadable/unsafe staging files (`*.invalid-*`) and opens a clean store, or sets `unavailableReason` (blocking chat mutations fail-closed). `stage()` is idempotent on identical payload and rejects conflicting ID reuse; `recover()` replays staged display artifacts into interrupted assistant messages on startup. +- **`ChatImageStore` (`chat-image-store.ts`):** Content-addressed `chats/images/<2-hex>/` files published via exclusive atomic write + `syncFile` + `syncDirectory` before any chat references the hash. Per-hash `putQueues`, `putsInFlight`, and `removals` prevent `put` and `sweep` from crossing on the same hash; `sweep` enforces a 24 h grace window + `isProtected` check before unlinking unreferenced images. +- **Oracles:** `main/services/display-image-artifact-store.test.ts`, `main/services/chat-image-storage.test.ts` (`npm run test:display-image`, `npm run test:transcript-images`). + +### 2.8 `clients:C03` — `renderer/main/chat-pane.tsx` — Deferred + +- **Current shape:** 4,961 lines with 132 React hook/state/ref/effect sites (`useState`/`useRef`/`useReducer`/`useEffect`), acting as the renderer adapter over main-owned turn admission (`M006`), generation settlement (`M005`/`M177`), approval/question coordinators (`M019`/`M020`), and queued message delivery (`C02`). +- **Disposition:** Keep **Deferred**. It holds no durable authority of its own (the host decides admission, queues, and terminal settlement). Splitting it safely requires a dedicated React component interaction harness rather than unit-only extraction. + +### 2.9 `main/services/git.ts` `VerifiedRepoIdentityProof` & `main/services/git-executable.ts` — Retain + +Gates the 0-spawn pure-FS `managedWorktreeUsable` fast path in `GitService`: + +| Phase | Guard / Check | Failure Behavior | +|---|---|---| +| Binary resolution (`git-executable.ts`) | Absolute `PATH` entries only (never cwd/relative); on macOS resolves `/usr/bin/git` shim via `xcode-select --print-path` or CLT fallback; memoized per `(binary/directPath, PATH, DEVELOPER_DIR)` for 5 min with per-hit `executablePath` revalidation; failures never cached. | Throws `"Git is not installed or unavailable"` or falls back to fresh resolution on path/symlink change. | +| Proof minting (`pureFsAdmissionProof`) | Rejects if `GIT_EXEC_PATH`, `LD_PRELOAD`, or `DYLD_INSERT_LIBRARIES` is set; requires `freshExecutable === memoizedExecutable`; requires trusted OS-managed install path (`isTrustedDirectGitInstallPath`), native Mach-O/ELF binary (`isNativeExecutableBinary`), Linux root-owned non-writable ancestor chain (`isRootOwnedNonWritableChain`), macOS Apple `com.apple.git` codesign verification, direct `--exec-path` match, and bounded no-follow config reads with zero `[include]` / `[includeIf]` directives. Re-hashes repo/config/exec signatures before and after reads (`beforeSig === afterSig`, `execBefore === execAfter`). | Returns `undefined` → `verifyAdmissionRepository` evicts cached proof and fails closed to Git-backed discovery. | +| Proof reuse (`isVerifiedRepoIdentityCurrent`) | Re-checks dangerous env vars, `systemConfigEnvKey`, exact ordered `allPaths`, `repositorySignature(paths)`, and `executableIdentitySignature`. | Returns `false` → falls back to full `verifyAdmissionRepository` (Git spawn). | + +- **Oracles:** `main/services/git-executable.test.ts`, `main/services/git.test.ts` (extended with `VerifiedRepoIdentityProof` behavioral edge cases). + +### 2.10 Bot allow-list, access authorization, and approval tallies — Retain + +- **`main/services/bot-runtime/bot-allow-list.ts`:** Coordinates `ToolApprovalRuleBook` (`grantBot`/`botGrantOperation`/`botConsentRevision`), `BotApprovalTallies`, and `BotApprovals`. In `settle()`, an `allow_always` decision records its publication context and checks `botGrantOperation` first so replays reconcile history without re-granting; new publications pass `expectedConsentRevision` and `validatePublication` to `grantBot`, check for post-grant revocation (`revoked` vs `published`), complete the tally publication state, and release matching pending approval prompts only while `currentGrant` still holds. `reconcile()` is read-only toward authority (never grants access). +- **`main/services/bot-runtime/bot-access-authorization.ts`:** `createBotAccessAuthorizer` snapshots the prompt, checks durable `folderCommitted` history before live checks (so a retry of a committed `always` returns `{ savedForFuture: true }` without creating a duplicate publication), validates owner signal/deadline/callback, revalidates scoped Custom policy revision via `createBotAccessRevalidator`, checks folder `(root, device, inode, inventoryRevision)`, publishes durable folder grant (`grantFolder`) with `operationId: prompt.waitId`, then revalidates at the exact returned publication revision before granting temporary `BotRunAccess`. If post-publication checks fail on `always`, acknowledges `{ savedForFuture: true }` without issuing temporary run authority. +- **`main/services/bot-runtime/bot-approval-tallies.ts`:** Per-Bot serialized append-only decision receipt ledger (`approval-tallies.json`, `0600`) with fail-closed tamper/corruption detection (`blocked = true` on unreadable file, missing/mutated previously observed receipts, or illegal publication transitions outside `pending → published | revoked`). `writeJsonAtomic` `beforePublish` re-reads disk bytes to block lost updates. +- **Oracles:** `main/services/bot-runtime/bot-allow-list.test.ts`, `bot-approval-tallies.test.ts`, `bot-access-requests.test.ts` (`npm run test:bot-allowed`, `npm run test:bot-access`). + +### 2.11 `main/services/aiden-remote-bot-session.ts` — Retain + +- **Projector lifecycle (`BotLiveProjector`):** Single serialized lane (`this.serial`) per Bot; mints a fresh `epoch` per conversation attachment so reopened harnesses always reach phones as a new epoch with monotonic `seq`. Bounded pending frame ring (`MAX_PENDING_FRAMES = 256`) and snapshot byte budget (`SNAPSHOT_BUDGET_BYTES`), 60 s idle timer (`armIdle`) when `subscribers.size === 0`, and idempotent `close()` emitting `{ type: "closed" }`, stopping `QueuedInputClassifier`, and awaiting `stopWatch`. +- **Service teardown & revocation (`AidenRemoteBotSessionService`):** Tracks SSE `CursorSseHandle` sets per `deviceId`. `revokeDevice(deviceId)` removes and closes all handles for that device; `close()` unsubscribes from intents, state changes, access requests, and plans, revokes all active devices, and closes every settled projector. +- **Mutation idempotency:** `send`, `resume`, `dismiss`, `stop`, `pause`, `unpause`, and card responses run through `bots.executeIdempotent`, using `AidenOperationReplaySafeRetryError` where the underlying Bot session holds its own durable `requestId` receipt. +- **Oracles:** `main/services/aiden-remote-bot-session.test.ts` (`npm run test:aiden-remote`). + +--- + +## 3. Lane B's 30 unreviewed deferred IDs + +`docs/audits/state-machine-worksheets-lane-b.md` (line 228) listed 30 inventory IDs whose transition review was not done in Lane B's pass: +- **Backend (14):** `M009`, `M010`, `M031`, `M033`, `M076`, `M099`, `M109`, `M110`, `M127`, `M164`, `M171`, `M180`, `M189`, `M197` +- **Clients (16):** `C10`, `C35`, `C50`, `C51`, `C52`, `C56`, `C63`, `C64`, `C67`, `C71`, `C74`, `N10`, `N12`, `N24`, `N26`, `N34` + +| ID(s) | Disposition | Basis | +|---|---|---| +| `backend:M009` | **Retained** (resolved) | Already audited and retained in `docs/state-machines/retained-p1-owners.md`: `main/services/renderer-document-owner.ts` and `main/services/chat-generation-owner.ts` (one-way invalidation, listeners removed once). | +| `backend:M010` | **Cross-referenced (Retained authority vocabulary)** | Lane B notes `M010` sits beside `M009` on Lane A's ownership vocabulary (workspace/chat mutation gates in `main/services/chat-workspace-authority.ts`, `workspace-mutation-gate.ts`, `chat-deletion-gate.ts`, all covered by `npm run test:subagents`). | +| `backend:M031`, `M033`, `M076`, `M099`, `M109`, `M110`, `M127`, `M164`, `M171`, `M180`, `M189`, `M197` | **Unresolved inventory ID on `main`** | The master inventory table mapping these 12 IDs to file paths does not exist on `main` (it was never merged from the planning branch). Rather than guessing ID bindings, concrete live authority/consent owners on `main` in the Bot, approval, and remote domains (`bot-allow-list.ts`, `bot-access-authorization.ts`, `bot-approval-tallies.ts`, `bot-application-service.ts`, `aiden-remote-bot-session.ts`, `aiden-remote-streams.ts`, `config-store-core.ts`, `analytics-service.ts`) are audited directly by path in §§1–2 above. | +| `clients:C10`, `C35`, `C50`, `C51`, `C52`, `C56`, `C63`, `C64`, `C67`, `C71`, `C74`, `N10`, `N12`, `N24`, `N26`, `N34` | **Unresolved inventory ID on `main`** | Same as above: no master inventory table exists on `main` to resolve these 16 client/native IDs to concrete files. Client/native approval views stay read-only projections of host authority; native iOS/Android state-machine work is tracked directly by file path in the dedicated client branches/docs. | diff --git a/docs/state-machines/physical-teardown.md b/docs/state-machines/physical-teardown.md index 09efa7a42c..1aa5213787 100644 --- a/docs/state-machines/physical-teardown.md +++ b/docs/state-machines/physical-teardown.md @@ -48,13 +48,122 @@ Everything else stayed as it was. `CuaDriverHost.shutdown()`, `CuaDriverSession` The flags in `main/index.ts` (`backend:M001`) stay where they are. Each is written in few places and the cancel paths reset them, but they have no Electron-free harness, so moving them would trade a read-checked flow for an untested one. -## Not done in this slice +## Audited remainder and verification boundaries + +Every item previously left open in this slice has now been audited in source and reconciled against its behavioral unit suites. Hardware, OS-permission, and real-device/VM acceptance boundaries are recorded explicitly so static/unit evidence is never overstated as physical acceptance. + +### `backend:M112` — Background jobs (`main/services/follow-through/background-jobs.ts`) + +**Disposition:** Retain. + +- **Ownership & lifecycle:** `BackgroundJobs` owns spawned process-group jobs (`start`), adopted leftover groups (`adopt`), and check-group crash-recovery records (`recordCheckGroup`), serialized onto `/running.json` via a chained atomic temp-and-rename writer (`recordWrite`). +- **Teardown & admission fences:** `shutdown()` sets `closed = true`, clears the port-scan timer, awaits `stopRecord(job, "app-quit")` for all live jobs, and drains `recordWrite`. `start()` throws synchronously once `closed` is true; `adopt()` rechecks `this.closed` before and after `adoptSettleMs` and after `markedMembers()`, so an in-flight adoption cannot register a job after shutdown starts. +- **Confirmation boundaries:** + - `recordCheckGroup` / `releaseCheckGroup` and `stopWorkspace` confirm group exit via `processGroupStillRuns` before dropping the record or allowing workspace removal. + - Adopted jobs (`stopAdopted`) signal only processes carrying `AIDEN_BACKGROUND_JOB=` (SIGTERM then up to 3 SIGKILL rounds via `endMarked`). If exit cannot be confirmed or inspection fails, the job stays `running`, stays in `running.json`, is skipped by `stopChat(..., forget = true)`, and causes `stopWorkspace` to reject so a later Stop or `reapPreviousLaunch()` still owns it. + - Spawned jobs send SIGTERM then SIGKILL after `stopGraceMs`, destroy pipes 1 s after SIGKILL so detached pipe-holders cannot wedge `close`, and run a final synchronous `signalGroup(pid, "SIGKILL")` inside `finish()` without waiting for post-SIGKILL descendant confirmation before dropping the entry from `running.json`. That bounded-teardown trade-off is retained as designed; `reapPreviousLaunch()` recovers crash leftovers using `processStartTime` and marker checks so reused PIDs are never signalled. +- **Verification boundary:** Real-process POSIX unit tests in `main/services/follow-through/background-jobs.test.ts` (`npm run test:follow-through`). + +### `backend:M125`, `M126`, `M130`, `M156`, `clients:C43` — Browser, device helper host, terminal, Ghostty + +**Disposition:** Retain all five owners. + +- **`backend:M125` Browser (`main/services/browser/service.ts`, `core.ts`, `private-session.ts`, `files.ts`):** + - `BrowserActionQueue` serializes per-tab automation behind `tail`. `interrupt()` increments `epoch`, marks all pending actions cancelled, and aborts the active `AbortController`; `interruptForHumanInput()` cancels only `source === "agent"` work and preserves `"user"` commands both active and queued. + - `BrowserPrivateSession` serializes last-tab cleanup (`clearStorageData`, `clearCache`, `clearAuthCache` via `Promise.allSettled`) before allowing a new private tab in `open()`, failing closed on cleanup error until a subsequent `clear()` succeeds. + - `close(tab)` is idempotent (`tab.closing`), cancels file consumers and held-field watches, interrupts the queue, detaches debugger/PiP/recording windows (`destroy()`), closes `webContents` without waiting for `beforeunload`, and triggers `privateSession.clear()` on the last incognito tab. `shutdown()` cancels file acquisitions, closes all tabs, drains `this.persistence`, and awaits `browserFileService.shutdown()`. + - **Verification boundary:** Pure core/queue/private-session/recording/file unit suites (`npm run test:browser`); live Chromium `WebContentsView` / CDP / Electron window teardown requires Electron E2E, not headless unit tests. +- **`backend:M126` Device helper host (`main/services/devices/local-device-host.ts`, `device-service.ts`, `ssh-device-host.ts`, `device-recording.ts`):** + - `createLocalDeviceHost` fences `expo-device-hub` and `agent-device` startup with a monotonic `generation`, `stopped` flag, and serialized `startLock`. `stop()` bumps `generation`, sets `stopped = true`, aborts any pending readiness probe, sends `SIGTERM` to pending and active hub children once (`WeakSet`), awaits `stopAgent()` (`daemon stop` falling back to `terminateRecordedDaemon` checked by `lstart` and installed daemon path), and removes `hub.json`. + - Under quit budget pressure (`SHUTDOWN_BUDGET_MS.devices = 8 s`), `terminateRunningDeviceCommands()` sets `commandsCancelledForQuit = true` and `SIGTERM`s all active helper commands so post-deadline commands cannot spawn or outlive quit. + - `createDeviceRecorder` bounds recording stop (`SIGINT` → `SIGKILL` after 15 s) and cleans up Android remote files once per entry; `terminate()` immediately `SIGKILL`s live recorder children. + - **Verification boundary:** Fake-process/fake-clock unit tests (`npm run test:devices`); real Xcode `simctl` / Android emulator / SSH host teardown requires macOS hardware/simulator acceptance. +- **`backend:M130` Terminal (`main/services/terminal.ts`, `terminal-spawn-helper.ts`):** + - `create()` revalidates `owner` and `webContentsEpochs` across every async step before spawning, validates `pty.pid > 0` (marking `unverifiableWorkspaces` fail-closed otherwise), records `pty.pid` as the POSIX session ID for worktree cleanup, and registers `onExit` before owner invalidation so a synchronous teardown always settles `exited`. + - `terminate()` clears coalesce timers, sends `SIGHUP` to `-pid` + `pty.kill()`, escalates to `SIGKILL` after `killGraceMs` (2 s), and releases `settleExit` after a second grace interval. `closeForWorkspaceAndWait()` waits for pending PTY exits and audits every tracked POSIX session ID via `managedWorktreeSessionHasMembers`, throwing `ManagedWorktreeProcessActiveError` if any process survives or is unverifiable. `flushHistory()` drains debounced scrollback writes during quit (`2 s` budget). + - **Verification boundary:** Unit tests with coverage gate (`npm run test:terminal:coverage`). +- **`backend:M156` & `clients:C43` Ghostty (`renderer/lib/ghostty-terminal/surface.ts`, `runtime.ts`, `core.ts`):** + - `GhosttyTerminalSurface.dispose()` is idempotent (`this.disposed = true`), disconnects `ResizeObserver`, removes font/DPR/appearance/DOM listeners, clears selection-scroll, cursor-blink, synchronized-output, composition-suppression, and resize-debounce timers (flushing final grid dimensions once on unmount), cancels `requestAnimationFrame`, disposes `GhosttyTerminalCore` (freeing WASM handles; `runtime.ts` zero-initializes handle slots so partial-init disposal is safe), and removes mounted DOM nodes. All post-dispose callbacks guard on `this.disposed` and monotonic font/copy/paste tokens. + - **Verification boundary:** Headless unit/DOM-mock tests (`npm run test:ghostty-terminal`); GPU/canvas presentation and real IME composition require Electron/browser acceptance. + +### `cli-native:N13`, `O01` — iMCP launcher and bounded-command guard + +**Disposition:** Retain both (read-audited; native/helper boundaries unchanged). + +- **`cli-native:N13` (`native/imcp-launcher/main.swift`):** Verifies Apple static code-signing requirements on `iMCP.app` (`co.dododo.iMCP`) and `imcp-server` (`TeamIdentifier TTY35UM57S`, no network access) before spawning with `LaunchCodeRequirement`. Installs a `SIGTERM` `DispatchSource` that `SIGKILL`s `-child.processIdentifier`, and a `terminationHandler` that `SIGKILL`s the child's process group on exit before propagating exit/signal status. **Verification boundary:** Static read audit; code-signature execution requires signed macOS host binary acceptance. +- **`cli-native:O01` (`scripts/bounded-command-guard.mjs`):** Detached process-group lease wrapper that ignores `SIGTERM`/`SIGINT` itself so it remains the occupied group leader until `terminate` / `release` / IPC `disconnect` runs `terminateGroup(graceMs)` (idempotent `terminating` flag: `SIGTERM` to `-process.pid`, then `SIGKILL` to `-process.pid` after `graceMs`, followed by `process.exit(70)`). **Verification boundary:** Exercised by real-process bounded-shell unit tests (`main/services/bounded-shell-command.test.ts`). + +### Rank 13 capture and input owners (`backend:M131`, `M133`–`M138`) + +**Disposition:** Retain all owners; static/unit lifecycle verified, physical hardware/OS-permission acceptance not claimed here. + +| Inventory | Owner(s) | Lifecycle & Teardown Invariants | Verification Boundary | +|---|---|---|---| +| `backend:M131` | `main/services/dictation-coordinator.ts`, `dictation-paste.ts`, `linux-dictation-portal.ts` | Single serialized promise queue (`enqueue`); explicit `DictationStage` (`idle → starting → recording → transcribing → delivering → idle`); operation-ID fencing on `release`/`result`/`error`; audio-scaled transcription watchdog; `dispose()` sets `disposed`, clears hide/release/watchdog timers, ends hold-watch, destroys pill. | Unit/mocked-timer tests (`npm run test:voice`); real macOS Accessibility/Secure Input/hotkey release and Linux xdg-desktop-portal require desktop hardware acceptance. | +| `backend:M133` | `main/services/gemini-live/service.ts` | `shuttingDown` blocks new sessions and `bindDisplayMedia`; `shutdown()` aborts active sessions, closes protocols, disposes display bindings, and awaits `pendingThreadFinalization` and in-flight starts (bounded by `SHUTDOWN_BUDGET_MS.geminiLive = 3 s`). | Unit tests (`npm run test:gemini-live`); live audio/screen-capture permissions and real Google Live WebSocket require hardware/authorized-packaged acceptance (`test:gemini-live:packaged:authorized`). | +| `backend:M134`–`M137` | `main/services/local-speech-worker-host.ts`, `local-speech-lane.ts`, `local-speech-process-core.ts`, `local-speech-engine.ts`, `local-speech-downloads.ts` | `LocalSpeechLane` serializes access to the single worker and aborts queued vs active callers cleanly. `LocalSpeechWorkerHost` fences forks with monotonic `generation`, retires workers before replacing models (`retirementsSettled()` guarantees two native models are never resident at once), escalates stubborn workers to `SIGKILL` after `exitWaitMs` (2 s), and `shutDown()` detaches synchronously while still tracking background `SIGKILL` escalation. | Fake-process unit tests (`npm run test:voice`); real sherpa-onnx native memory release and microphone capture require hardware/smoke acceptance (`test:stt-smoke`). | +| `backend:M138` | `main/services/tts/service.ts`, `audio-store.ts`, `browser/recordings.ts`, `devices/device-recording.ts` | `createTtsService` enforces one active job (`cancelActiveJob`), per-document owner invalidation releasing `audioStore` bytes and cancelling active jobs, pause-wait wakeups on termination, and idempotent start intent keys per document. Recording owners bound duration and clean up temp/remote files on stop/discard/quit. | Unit/loopback tests (`npm run test:tts`, `test:browser`, `test:devices`); real audio output playback and OS screen-recording permissions require hardware acceptance. | + +### Rank 14 remainder: startup and updater owners (`backend:M002`–`M004`, `M165`, `M192`) + +**Disposition:** Retain all owners. + +| Inventory | Owner(s) | Lifecycle & Teardown Invariants | Verification Boundary | +|---|---|---|---| +| `backend:M002` | `main/application-lifecycle-core.ts`, `main/services/quit-barrier.ts` | Pure core already extracted: `createLifecycleCheck`, `createUpdateInstallIntent`, `settleUpdateInstallQuit`, `closeRendererBeforeShutdown` (5 s hang deadline → `destroy()`), `withDeadline`, `joinInFlight`, `requireWithinDeadline`. | Unit tests (`main/services/quit-barrier.test.ts`, `main/services/onboarding-reset-lifecycle.test.ts`). | +| `backend:M003`, `M004` | `main/services/startup-ipc-admission.ts`, `startup-chat-reconciliation.ts`, `renderer-crash-recovery.ts`, `main/index.ts` startup sequence | `installProcessStartupIpcAdmission` holds every `ipcMain.handle` invoke in arrival order until `openProcessStartupIpcAdmission()` runs strictly after all durable reconciliation finishes. `decideRendererRecovery` caps automatic reloads at 3 per 60 s with exponential backoff (`250 ms` → `2 s`). Startup failure destroys an unadmitted window and joins `shutdownAndQuit()` (falling back to `app.exit(1)` if Computer Use persistence refuses quit with no window left). | Unit tests (`npm run test:diagnostics`, `test:chat-visibility`); full Electron cold-start sequence requires Electron E2E. | +| `backend:M165`, `M192` | `main/services/app-updater-core.ts`, `app-updater.ts`, `app-updater-linux.ts`, `app-updater-linux-package.ts` | `AppUpdateController` owns explicit snapshot phases (`idle → checking → downloading → ready | error`), single-flight `operationPromise`, monotonic progress guard, and `dispose()` that stops future publications while preserving a completed `ready` snapshot for quit-time install handoff. `AppUpdateService` owns 15 s initial / 6 h periodic / backoff retry timers, 2 min download-stall watchdog (`CancellationToken`), `AppUpdateInstallHandoff` (catching synchronous `quitAndInstall` failure), AppImage SHA-512 atomic replacement, and DEB/RPM pre-quit `pkexec` install (`autoInstallOnAppQuit = false`). `dispose()` clears all timers, cancels active download, and detaches updater listeners. | Pure core & Linux installer unit tests (`npm run test:branding`); real Squirrel/macOS code-signed update install and `pkexec` prompt require packaged release acceptance. | + +## Cross-lane shutdown and restart trace (P1–P5) + +Traced end-to-end across `main/index.ts` (`requestApplicationQuit`, `runShutdownAndQuit`, `cleanupApplication`, and `app.whenReady` startup reconciliation) and the landed P1–P4 owners (`retained-p1-owners.md`, `docs/audits/state-machine-worksheets-lane-b.md`, `.memory/remote-durable-operations.md`): + +### Shutdown order (`runShutdownAndQuit`) + +1. **Admission & pre-shutdown durability (outside ceiling):** + - `createLifecycleCheck` serializes quit against close/reload/onboarding reset; `shutdownAndQuit` uses `joinInFlight` so concurrent callers join one run. + - `shutdownStarted = true` and `llmClient.setQuitInProgress(true)` block new owed-turn launches (`P1`). + - `prepareComputerUseForQuit()` persists Computer Use state within `PRE_SHUTDOWN_BUDGET_MS.computerUseSettings` (5 s). Failure rolls back `shutdownStarted`, withdraws `updateInstall`, clears `quitInProgress`, and leaves Aiden open. + - `armShutdownCeiling()` arms the hard ceiling (`SHUTDOWN_HARD_CEILING_MS`, exiting with code `1` if any step escapes its per-step budget). +2. **Serial drain of active producers (P1 → P5 → P2/P3):** + - `stopKeepAwake()` and `shutdownGoalLoop()` halt new goal rounds synchronously. + - `storageUsageService.shutdown()` (6 s) stops storage sweeps before chats/worktrees tear down. + - `geminiLiveService.shutdown()` (3 s, Rank 13) closes Live sessions and flushes thread finalization. + - `llmClient.abortAll()` + `llmClient.shutdown()` (7 s, `P1` `M005`/`M006`/`M012`/`M177`) aborts active parent generations, drains settlement through `settleGeneration`, and prevents owed turns from starting. + - `shutdownFollowThrough()` (6 s, `P5` `M112`) stops background jobs and persists check/follow state. + - `modelPaceRecorder.flush()` (1 s). + - `subagentRuntimeRegistry.shutdown()` (7 s, `P1`/`P5` `M102`/`M103`/`subagent-shell.ts`) drains child runtimes and shell brokers. + - `spending.flush()`, `usageLimits.flush()`, `usageStore.flush()` (1 s); `analyticsService().shutdown()` (2 s, `M166`); optional packaged-soak receipt finalization (exiting `1` on receipt failure). + - `stopAidenRemoteServiceAndSettle()` (5 s, `P2`/`P3` `M056`/`M057`/`M178` + streams/idempotency) closes the Remote HTTP/SSE server, revokes/drains in-flight operations, and settles durable operation snapshots. +3. **Synchronous cut (`cleanupApplication`, idempotent):** + - Disposes `appUpdateService`, global shortcuts, dictation (`M131`), quick chat, local speech (`M134`–`M137`), Foundation Models connection, `formFillRuntime`, `computerUseStatus` invalidation, `scheduleService.stop()` (`P6`), `stopScheduledTaskTriggers()`, `telegramService.stop()`, `llmClient.abortAll()`, `subagentRuntimeRegistry.abortAll()`, watchers, and triggers `mcpManager.closeAll({ final: true })`. +4. **Parallel bounded teardown (P2, P4, P5, P6):** + - Provider OAuth sign-in (`2 s`, `M078`); Computer Use host (`5.5 s`, `M116`–`M118`). + - Bot ingress (`scheduleService.stopAndSettle()` + `telegramService.stopAndSettle()`, `5.5 s`) **strictly before** `shutdownBotSessionRuntime()` (`5 s`, `M023`/`M024`), so nothing reopens a Bot harness while harnesses close and release profile locks. + - `subagentRunStore.flush()` + `close()` (`3 s`); `terminalService.flushHistory()` (`2 s`, `M130`). + - `createImagesRuntime.shutdown("app-quit")` (`5 s`) **strictly before** `studioAssetStore.close()` (`2 s`). + - `browserService.shutdown()` (`3 s`, `M125`); `shutdownBotComputers(4_000)` (`5 s`, `M121`/`M122`); `shutdownDevices()` (`8 s`, `M126`, calling `terminateDeviceHelperCommands()` on timeout); `settleFoundationModelsHelperStops(1_500)` (`2 s`); `mcpManager.closeAllWithin(2_000)` (`3 s`); `shutdownAntigravity()` (`4 s`, `M089`/`M090`). +5. **Final diagnostics & exit:** + - Flushes subagent diagnostics, diagnostic journal, and diagnostic health (`1 s` each). + - Sets `forceAppQuit = true`; if `updateInstall.take()` is armed, hands off to `appUpdateService.installDownloadedUpdateAndRestart()` (disarming ceiling on success), else calls `app.quit()`. + +### Restart reconciliation order (`app.whenReady`, before `openProcessStartupIpcAdmission`) + +All renderer invokes are held by `startup-ipc-admission.ts` until every recovery step below settles: +1. Studio assets & `createImagesRuntime.initialize()` restart sweep (before any image run starts). +2. `displayImageArtifactStore` / `generativeUiArtifactStore` initialization (quarantining corrupt staging or failing closed on chat mutations) and `subagentRunStore.initialize()`. +3. `reapFollowThroughProcesses()` (`M112` `reapPreviousLaunch()` — **before** chat or worktree deletion so orphaned shells cannot hold files open). +4. `reconcilePendingChatDeletions()` (`P4` roll-forward across tool outputs, image/HTML artifacts, Pi effects/compaction, design canvas, `chatStore`, inbox state), followed by `sweepOrphanedEphemeralChats()` and `prepareNoWorkspaceChats()`. +5. Recovery of staged image (`M147`) and HTML artifacts into interrupted assistant messages. +6. `startBotApplication()` (rolls forward `bot-lifecycle-journal-core` pending create/delete/model ops, `M026`/`M035`; reconciles Bot sessions & pending deletes) and background `reconcileBotComputers()` (`M121`/`M122`). +7. `migrateLegacyEmptyWorkspaceChats()` (throwing `EmptyChatMigrationSnapshotError` aborts startup rather than admitting writers after an uncertain snapshot), `reconcileChatScopedStores` (Pi effect & compaction stores against full unfiltered `chatStore.list()`), and `reconcilePendingManagedWorktreeDeletions()` (`P4` `git.ts`, blocking each pending workspace via `scheduleService.cancelWorkspace` + `backgroundJobs.stopWorkspace`). +8. Credential reconciliation: `reconcilePendingProviderCredentialRotation()`, `reconcilePendingMcpCredentialCleanup()`, `cleanupRetiredMcpServerCredentials()`, `sealPlaintextMcpServerFields()`. +9. Follow-through & goal restoration (`startFollowThrough()`, `startGoalLoop()` — active goals come back paused), `childChatCompletions.recoverOwed()`, `startKeepAwake()`, and `initializeAidenRemoteService()`. +10. `openProcessStartupIpcAdmission()` — only now do renderer invokes, `scheduleService.start()` (with lock-screen catch-up deferral), `startScheduledTaskTriggers()`, `telegramService.start()`, and `appUpdateService.start()` activate, each guarded by `if (shutdownHasBegun()) return`. + +### Cross-lane gaps noted (none silently hidden) + +- Every step in `runShutdownAndQuit` is bounded by `settleShutdownStep` so a wedged step cannot hang quit, and `SHUTDOWN_HARD_CEILING_MS` forces `app.exit(1)` as a last resort. When a step times out (e.g., `parentGenerations`, `subagentRuntime`, `botRuntime`, or `mcpServers`), physical cleanup may still be finishing asynchronously or left to next-launch crash recovery (`reapPreviousLaunch()`, `reconcilePendingChatDeletions()`, `reconcilePendingManagedWorktreeDeletions()`, `pending-deletes.json`, `pi-durable` interrupted state). +- `aiden serve stop` in `packages/cli` still cannot reap an MCP group whose wrapper exited (documented under MCP stdio servers above). +- No end-to-end Electron multi-subsystem kill-and-restart harness exists across all P1–P5 lanes simultaneously; verification combines this static trace with per-lane unit/integration suites and the packaged subagent/compaction/diagnostics acceptance scripts. -| Inventory | Owner | Why | -|---|---|---| -| `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. | diff --git a/main/services/bot-runtime/bot-session-service.test.ts b/main/services/bot-runtime/bot-session-service.test.ts index a3b72f215c..48e0f122f7 100644 --- a/main/services/bot-runtime/bot-session-service.test.ts +++ b/main/services/bot-runtime/bot-session-service.test.ts @@ -1667,3 +1667,27 @@ test("metadata commits dedupe concurrent issue effects and cannot append after d await assert.rejects(service.appendEntry("bot:a", kind, data), /no longer exists/u); } finally { await service.shutdown(); } }); + +test("shutdown interrupts in-flight awaitReply for Resume and rejects late appendEntry commits", async () => { + const fauxModels = createFauxModels([slowAnswer()], { tokensPerSecond: 40 }); + const service = await serviceFor(tempProfile(), fauxModels); + try { + const sent = await service.send("bot:a", { text: "Long work", requestId: "req-shutdown-race" }); + await waitFor( + async () => (await service.state("bot:a")).kind === "running" && fauxModels.calls() === 1, + { what: "turn start" }, + ); + const replyPromise = service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + // Let awaitReply attach to submission.wait before host shutdown begins. + await new Promise((resolve) => setTimeout(resolve, 40)); + await service.shutdown(); + const outcome = await replyPromise; + assert.deepEqual(outcome, { kind: "interrupted" }); + await assert.rejects( + service.appendEntry("bot:a", BOT_ISSUE_STATUS_ENTRY_KIND, { effectId: "after-shutdown" }), + /shut down|shutting down|closed/u, + ); + } finally { + await service.shutdown(); + } +}); diff --git a/main/services/browser/core.test.ts b/main/services/browser/core.test.ts index 6a5e0f54ee..0243f2e0ca 100644 --- a/main/services/browser/core.test.ts +++ b/main/services/browser/core.test.ts @@ -336,3 +336,35 @@ test("same browser page compares normalized URLs", () => { assert.equal(sameBrowserPage("https://example.com/#x", "https://example.com/#y"), false); assert.equal(sameBrowserPage("about:blank", "nope"), false); }); +test("human input while a user action runs keeps epoch stable and cancels only queued agent work", async () => { + const queue = new BrowserActionQueue(); + const initialEpoch = queue.epoch; + let userStarted!: () => void; + let releaseUser!: () => void; + const started = new Promise((resolve) => { userStarted = resolve; }); + const userRun = queue.run(async (check) => { + userStarted(); + await new Promise((resolve) => { releaseUser = resolve; }); + check(); + return "user-ok"; + }, undefined, "user"); + let queuedAgentRan = false; + const queuedAgent = queue.run(async () => { + queuedAgentRan = true; + return "agent-ran"; + }, undefined, "agent"); + await started; + + queue.interruptForHumanInput(); + assert.equal(queue.epoch, initialEpoch); + assert.equal(queue.signal?.aborted, false); + releaseUser(); + + assert.equal(await userRun, "user-ok"); + await assert.rejects(queuedAgent, /interrupted/); + assert.equal(queuedAgentRan, false); + + queue.interrupt(); + assert.equal(queue.epoch, initialEpoch + 1); + assert.equal(await queue.run(async () => "post-interrupt"), "post-interrupt"); +}); diff --git a/main/services/follow-through/background-jobs.test.ts b/main/services/follow-through/background-jobs.test.ts index 216d68557a..e569d9e8c1 100644 --- a/main/services/follow-through/background-jobs.test.ts +++ b/main/services/follow-through/background-jobs.test.ts @@ -882,3 +882,96 @@ test("a shell's background job that cannot be confirmed gone is not reported sto assert.equal(result.timedOut, false); assert.equal(result.backgroundStopped, false); }); + +test("an adoption racing with shutdown never registers a job or writes it after close", { skip }, async (t) => { + const dir = await tempDir(); + const id = newBackgroundJobId(); + let enteredLookup!: () => void; + let releaseLookup!: () => void; + const lookupEntered = new Promise((resolve) => { enteredLookup = resolve; }); + const lookupHeld = new Promise((resolve) => { releaseLookup = resolve; }); + const { jobs } = harness(dir, { + adoptSettleMs: 0, + processGroupMembers: async (pgid) => { + enteredLookup(); + await lookupHeld; + return defaultProcessGroupMembers(pgid); + }, + }); + const child = spawn("sleep 30", { + cwd: dir, + detached: true, + shell: true, + stdio: "ignore", + env: { ...process.env, AIDEN_BACKGROUND_JOB: id }, + }); + t.after(async () => { + try { if (child.pid) process.kill(-child.pid, "SIGKILL"); } catch { /* Already gone. */ } + await cleanUp(jobs, dir); + }); + assert.ok(child.pid); + const adopting = jobs.adopt({ + id, + chatId: "chat-1", + workspaceId: "ws-1", + cwd: dir, + command: "sleep 30 &", + processGroup: child.pid, + }); + await lookupEntered; + const shuttingDown = jobs.shutdown(); + releaseLookup(); + assert.equal(await adopting, undefined); + await shuttingDown; + assert.deepEqual(jobs.listAll(), []); +}); + +test("an unconfirmed adopted stop blocks workspace teardown and stays in running.json across shutdown", { skip }, async (t) => { + const dir = await tempDir(); + const id = newBackgroundJobId(); + let failLookup = false; + const { jobs } = harness(dir, { + adoptSettleMs: 0, + processHasEnvironment: async (pid, entry) => { + if (failLookup) throw new Error("proc unreadable"); + return pid === child.pid && entry === `AIDEN_BACKGROUND_JOB=${id}`; + }, + processGroupMembers: async (pgid) => { + if (failLookup) throw new Error("ps unavailable"); + return pgid === child.pid ? [child.pid] : []; + }, + }); + const child = spawn("sleep 30", { + cwd: dir, + detached: true, + shell: true, + stdio: "ignore", + env: { ...process.env, AIDEN_BACKGROUND_JOB: id }, + }); + t.after(async () => { + failLookup = false; + try { if (child.pid) process.kill(-child.pid, "SIGKILL"); } catch { /* Already gone. */ } + await fs.rm(dir, { recursive: true, force: true }); + }); + assert.ok(child.pid); + const adopted = await jobs.adopt({ + id, + chatId: "chat-1", + workspaceId: "ws-1", + cwd: dir, + command: "sleep 30 &", + processGroup: child.pid, + }); + assert.equal(adopted?.state, "running"); + + failLookup = true; + await assert.rejects(jobs.stopWorkspace("ws-1", "access-changed"), /confirm.*background jobs stopped/u); + assert.equal(jobs.get("chat-1", id)?.state, "running"); + + await jobs.shutdown(); + assert.equal(jobs.get("chat-1", id)?.state, "running"); + const ledger = JSON.parse(await fs.readFile(path.join(dir, "logs", "running.json"), "utf8")) as { + jobs: Array<{ id: string; pid: number }>; + }; + assert.ok(ledger.jobs.some((entry) => entry.id === id && entry.pid === child.pid)); +}); diff --git a/main/services/git-executable.test.ts b/main/services/git-executable.test.ts index c67a47602e..37fcd74033 100644 --- a/main/services/git-executable.test.ts +++ b/main/services/git-executable.test.ts @@ -1,7 +1,15 @@ import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; import test from "node:test"; +import { promisify } from "node:util"; +import { GitService } from "./git.js"; import { createGitExecutableResolver, resolveGitExecutable } from "./git-executable.js"; +const execFileAsync = promisify(execFile); + function fixture(paths: Record, developerDir?: string) { let probes = 0; return { @@ -233,3 +241,142 @@ test("memoized resolver on Linux skips a workspace-relative PATH entry", async ( assert.equal(await resolve("git", "/w", { PATH: ".:/usr/bin" }), "/usr/bin/git"); assert.ok(!f.inspected.includes("/w/git")); }); + +async function createTempRepoWithWorktree(t: test.TestContext, gitBinary?: string) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-git-proof-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const repo = path.join(root, "repo"); + const worktreesRoot = path.join(root, "worktrees"); + await fs.mkdir(repo, { recursive: true }); + await fs.mkdir(worktreesRoot, { recursive: true }); + const runGit = (args: string[]) => + execFileAsync("git", args, { + cwd: repo, + env: { + ...process.env, + GIT_AUTHOR_NAME: "Test", + GIT_AUTHOR_EMAIL: "test@example.com", + GIT_COMMITTER_NAME: "Test", + GIT_COMMITTER_EMAIL: "test@example.com", + }, + }); + await runGit(["init", "-b", "main"]); + await fs.writeFile(path.join(repo, "README.md"), "hello\n", "utf8"); + await runGit(["add", "README.md"]); + await runGit(["commit", "-m", "init"]); + const service = new GitService(gitBinary ? { gitBinary } : {}); + const created = await service.createWorktree(repo, worktreesRoot, "proof/test-branch"); + return { root, repo, service, created }; +} + +test( + "VerifiedRepoIdentityProof refuses to cache pure-FS admission when repo config uses [include]", + { skip: process.platform === "win32" }, + async (t) => { + const { root, repo, service, created } = await createTempRepoWithWorktree(t); + const check = () => + service.managedWorktreeUsable( + repo, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ); + // First call verifies through Git and caches the VerifiedRepoIdentityProof; + // second call hits the pure-FS fast path while signatures match. + assert.equal(await check(), true); + assert.equal(await check(), true); + + // Add a valid [include] directive to repo/.git/config and re-check. + // Because repo/.git/config now has an [include], pureFsAdmissionProof must + // refuse to cache a VerifiedRepoIdentityProof for subsequent calls. + const extraConfig = path.join(root, "extra.gitconfig"); + await fs.writeFile(extraConfig, "# included\n", "utf8"); + const repoConfig = path.join(repo, ".git", "config"); + const before = await fs.readFile(repoConfig, "utf8"); + await fs.writeFile(repoConfig, `${before}\n[include]\n\tpath = ${extraConfig}\n`, "utf8"); + assert.equal(await check(), true); + + // Now break ONLY the included file without modifying repo/.git/config. + // A stale pure-FS cache would have returned true; failing closed forces + // Git discovery, which rejects the broken included config. + await fs.writeFile(extraConfig, "[core\n", "utf8"); + await assert.rejects(check(), /Git repository|bad config|not_a_repo/u); + }, +); + +test( + "VerifiedRepoIdentityProof refuses to cache pure-FS admission for a shebang wrapper git binary", + { skip: process.platform === "win32" }, + async (t) => { + const wrapperDir = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-git-wrap-")); + t.after(() => fs.rm(wrapperDir, { recursive: true, force: true })); + const wrapperPath = path.join(wrapperDir, "git-wrapper"); + const countFile = path.join(wrapperDir, "calls.log"); + const realGit = await resolveGitExecutable("git", wrapperDir, process.env); + await fs.writeFile( + wrapperPath, + `#!/bin/sh\necho call >> "${countFile}"\nexec "${realGit}" "$@"\n`, + { mode: 0o755 }, + ); + + const { repo, service, created } = await createTempRepoWithWorktree(t, wrapperPath); + const check = () => + service.managedWorktreeUsable( + repo, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ); + assert.equal(await check(), true); + const callsAfterFirst = (await fs.readFile(countFile, "utf8")).trim().split("\n").length; + assert.equal(await check(), true); + const callsAfterSecond = (await fs.readFile(countFile, "utf8")).trim().split("\n").length; + assert.ok( + callsAfterSecond > callsAfterFirst, + "wrapper binary must never satisfy the 0-spawn pure-FS admission proof", + ); + }, +); + +test( + "VerifiedRepoIdentityProof fails closed out of pure-FS fast path when GIT_EXEC_PATH is set", + { skip: process.platform === "win32" }, + async (t) => { + const { repo, service, created } = await createTempRepoWithWorktree(t); + const check = () => + service.managedWorktreeUsable( + repo, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ); + assert.equal(await check(), true); + + const previousExecPath = process.env.GIT_EXEC_PATH; + const fakeExecDir = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-fake-exec-")); + t.after(async () => { + if (previousExecPath === undefined) delete process.env.GIT_EXEC_PATH; + else process.env.GIT_EXEC_PATH = previousExecPath; + await fs.rm(fakeExecDir, { recursive: true, force: true }); + }); + // Point GIT_EXEC_PATH to an empty directory and remove the worktree's + // .git file's sibling check? Even simpler: set GIT_EXEC_PATH and verify + // GitService rejects/falls back when Git itself runs with a broken exec path + // or verify `managedWorktreeUsable` still evaluates accurately without + // trusting the cached proof after core.bare=true + GIT_EXEC_PATH. + process.env.GIT_EXEC_PATH = fakeExecDir; + const repoConfig = path.join(repo, ".git", "config"); + const before = await fs.readFile(repoConfig, "utf8"); + await fs.writeFile(repoConfig, `${before}\n[core]\n\tbare = true\n`, "utf8"); + await assert.rejects(check(), /Git repository|bare|failed/u); + }, +); diff --git a/main/services/schedule-service-core.test.ts b/main/services/schedule-service-core.test.ts index 7679e6519c..992e57a64f 100644 --- a/main/services/schedule-service-core.test.ts +++ b/main/services/schedule-service-core.test.ts @@ -66,7 +66,11 @@ function harness(globallyEnabled: () => Promise = async () => true) { }, cancelAll: () => { cancelAllCalls += 1; - for (const [taskId, resolve] of pending) { + for (const [taskId, resolve] of [...pending]) { + if (deferCancellations) { + deferredCancellations.add(taskId); + continue; + } resolve({ id: `run-${taskId}`, taskId, @@ -76,8 +80,8 @@ function harness(globallyEnabled: () => Promise = async () => true) { output: "", error: "cancelled", }); + pending.delete(taskId); } - pending.clear(); }, }; const service = createScheduleServiceCore({ @@ -1533,3 +1537,62 @@ test("turning a chat task off and on by hand starts a new count of failed runs", assert.equal((await late.store.get(task.id))?.enabled, true, "the failure after turning it back on is the first of a new count"); assert.deepEqual(late.cards, []); }); + +test("stopAndSettle cancels active runs and clears deferred catch-up so reevaluateCatchUp cannot dispatch after stop", async (t) => { + const h = harness(); + t.after(() => h.service.stop()); + let deferred = true; + h.service.setCatchUpDeferPolicy(() => deferred); + const task1 = await addTask(h.store); + const task2 = await h.store.save({ + name: "Second brief", + mode: "llm", + cron: "0 9 * * *", + timezone: "UTC", + prompt: "Summarize more changes.", + }); + await h.store.updateRuntime(task2.id, { nextRunAt: Date.now() - 60_000 }); + await h.service.start(); + + // Start task1 manually and hold its cancellation until we explicitly release it. + h.holdCancellations(); + const manualRun = h.service.runNow(task1.id); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(h.service.isRunning(task1.id), true); + + let settled = false; + const stopping = h.service.stopAndSettle().then(() => { settled = true; }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(settled, false); + assert.equal(h.hasDeferredCancellation(task1.id), true); + + h.releaseCancellation(task1.id); + await stopping; + await manualRun; + assert.equal(h.service.isActive(), false); + assert.equal(h.service.isRunning(task1.id), false); + + // Unblocking deferral after shutdown must not dispatch the cleared catch-up entry. + deferred = false; + h.service.reevaluateCatchUp(); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(h.hasPending(task2.id), false); +}); + +test("pause rolls back durable pause and rearms the cron job when caller aborts after pauseWithRollback commits", async (t) => { + const h = harness(); + t.after(() => h.service.stop()); + const task = await addTask(h.store); + await h.service.start(); + const controller = new AbortController(); + const originalPauseWithRollback = h.store.pauseWithRollback.bind(h.store); + h.store.pauseWithRollback = async (id: string) => { + const result = await originalPauseWithRollback(id); + controller.abort(); + return result; + }; + + await assert.rejects(h.service.pause(task.id, { signal: controller.signal }), /cancelled/u); + assert.equal((await h.store.get(task.id))?.enabled, true); + assert.ok(scheduledJobs.some((job) => job.name === `scheduled:${task.id}`)); +}); diff --git a/main/services/scheduled-bot-routines.test.ts b/main/services/scheduled-bot-routines.test.ts index ce1c0655c8..fa5c2c9228 100644 --- a/main/services/scheduled-bot-routines.test.ts +++ b/main/services/scheduled-bot-routines.test.ts @@ -1829,3 +1829,38 @@ test("a routine run counts once by what started it, including a failure, and a s await h.run(task, undefined, { kind: "automatic", fireTime: 2 }); assert.deepEqual(sent, []); }); + +test("aborting during awaitReply keeps an automatic fire receipt unsettled and suppresses failure delivery", async () => { + const h = harness(); + const routine = await h.routines.create({ + botId: "bot-scout", + name: "Morning brief", + schedule: { kind: "daily", time: "07:30" }, + prompt: "Check the inbox.", + }); + const fireTime = Date.now() - 1_000; + await h.store.updateRuntime(routine.id, { nextRunAt: fireTime }); + const claimed = await h.store.claimRoutineFire(routine.id, fireTime, fireTime + 86_400_000); + const requestId = botRoutineRequestId(routine.id, { kind: "automatic", fireTime }); + // Hold awaitReply indefinitely so only the AbortSignal interrupts it. + h.session.replies.push(new Promise(() => {})); + const controller = new AbortController(); + const runPromise = h.executor.run(claimed, { + trigger: { kind: "automatic", fireTime }, + signal: controller.signal, + }); + // Wait for send to admit the submission before aborting. + while (h.session.sends.length === 0) await new Promise((resolve) => setImmediate(resolve)); + controller.abort(); + const recorded = await runPromise; + + assert.equal(recorded.result, "blocked"); + assert.notEqual(recorded.id, requestId, "uncertain cancellation must not claim the durable fire's run id"); + assert.deepEqual(h.session.deliveries, [], "cancellation must not notify the user as a failure"); + const after = await h.store.get(routine.id); + assert.equal( + after?.pendingRoutineFires?.some((fire) => fire.requestId === requestId), + true, + "automatic fire receipt stays pending so restart recovery can observe the admitted turn", + ); +}); diff --git a/main/services/subagents/subagent-supervisor.test.ts b/main/services/subagents/subagent-supervisor.test.ts index 151bf05e3d..43e1d4679a 100644 --- a/main/services/subagents/subagent-supervisor.test.ts +++ b/main/services/subagents/subagent-supervisor.test.ts @@ -3459,3 +3459,140 @@ test("each foreground subagent counts once, and a batch over budget counts nothi await assert.rejects(supervisor.execute(request(["3"])), /launch budget exceeded/i); assert.deepEqual(sent, []); }); + +test("parent cancellation during prepareRun aborts all fulfilled preparations without projecting or charging budget", async () => { + const controller = new AbortController(); + const secondEntered = deferred(); + const releaseSecond = deferred(); + const aborted: string[] = []; + const stopHooksFired: string[] = []; + const projector = new SubagentEventProjector({ + generationId: "generation-prep-cancel", + chatId: TEST_SUPERVISOR_SCOPE.chatId, + workspaceId: TEST_SUPERVISOR_SCOPE.workspaceId, + modelId: runtime().model.id, + }); + let prepareCalls = 0; + const supervisor = new SubagentSupervisor({ + generationId: "generation-prep-cancel", + ...TEST_SUPERVISOR_SCOPE, + runtime: runtime(), + thinkingLevel: "high", + workspaceRoot: "/workspace", + permission: "full", + inheritedCeiling: SUBAGENT_READ_TOOL_NAMES, + projector, + stopHooks: { + observe: (_event: unknown, payload: unknown) => { + stopHooksFired.push(String((payload as { agent_id?: unknown }).agent_id ?? "")); + }, + } as never, + prepareRun: async ({ identity, contextRevision }) => { + prepareCalls += 1; + if (prepareCalls === 2) { + secondEntered.resolve(); + await releaseSecond.promise; + } + return phase6Prepared( + phase6Authority({ + runId: identity.runId, + contextRevision, + delegate: false, + }), + () => { + aborted.push(identity.runId); + }, + ); + }, + runChild: async () => assert.fail("child must never run after cancellation during preparation"), + }); + + const pending = supervisor.execute(request(["First", "Second"]), controller.signal); + await secondEntered.promise; + controller.abort(new Error("parent stopped during prepare")); + releaseSecond.resolve(); + + await assert.rejects(pending, /parent stopped during prepare/u); + assert.equal(aborted.length, 2); + assert.deepEqual(projector.snapshot(), []); + assert.deepEqual(stopHooksFired, []); + assert.equal(supervisor.launchesUsed, 0); +}); + +test("nested projector flush failure aborts the tree and completes projected nested runs without duplicate SubagentStop", async () => { + const completedNested: string[] = []; + const stopHooksFired: string[] = []; + let failedNestedFlush = false; + const projector = new SubagentEventProjector({ + generationId: "generation-nested-flush-fail", + chatId: TEST_SUPERVISOR_SCOPE.chatId, + workspaceId: TEST_SUPERVISOR_SCOPE.workspaceId, + modelId: runtime().model.id, + onSnapshot: async (snapshot) => { + // Fail the nested batch's initial durability flush after depth-1 projected. + if (!failedNestedFlush && snapshot.label === "Nested child") { + failedNestedFlush = true; + throw new Error("nested projection disk full"); + } + }, + }); + const supervisor = new SubagentSupervisor({ + generationId: "generation-nested-flush-fail", + ...TEST_SUPERVISOR_SCOPE, + runtime: runtime(), + thinkingLevel: "high", + workspaceRoot: "/workspace", + permission: "full", + inheritedCeiling: SUBAGENT_READ_TOOL_NAMES, + projector, + stopHooks: { + observe: (_event: unknown, payload: unknown) => { + stopHooksFired.push(String((payload as { agent_id?: unknown }).agent_id ?? "")); + }, + } as never, + prepareRun: async ({ identity, requestedCapabilities, contextRevision, parentAuthority }) => { + const prepared = phase6Prepared( + phase6Authority({ + runId: identity.runId, + contextRevision, + delegate: requestedCapabilities.delegate === true, + parent: parentAuthority, + }), + ); + if (!parentAuthority) return prepared; + return { + ...prepared, + complete: async (result) => { + completedNested.push(`${identity.runId}:${result.status}`); + return prepared.complete(result); + }, + }; + }, + runChild: async (child) => { + if (child.v2Authority?.depth === 1) { + await assert.rejects( + child.executeNested!( + { tasks: [{ role: "scout", label: "Nested child", task: "Should not run." }] }, + child.signal, + ), + /nested projection disk full/u, + ); + return completed(child.request.label); + } + return assert.fail("nested child must not execute past a failed flush barrier"); + }, + }); + + await assert.rejects( + supervisor.execute({ + capabilities: { workspaceRead: true, delegate: true, web: false, mcp: [] }, + tasks: [{ role: "planner", label: "Depth 1", task: "Spawn nested child." }], + }), + /nested projection disk full/u, + ); + assert.ok(completedNested.length >= 1); + // Every finished run fires SubagentStop at most once. + assert.equal(new Set(stopHooksFired).size, stopHooksFired.length); + const nestedSnapshot = projector.snapshot().find((entry) => entry.label === "Nested child"); + assert.ok(nestedSnapshot && ["failed", "interrupted"].includes(nestedSnapshot.state)); +}); From bba618e6dc589d9b74a1e389be260f8c739e2418 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 06:16:36 +0000 Subject: [PATCH 2/2] Address PR #905 review comments on teardown docs and proof/subagent tests --- .../p5-p6-tier-a-reconciliation.md | 8 +- docs/state-machines/physical-teardown.md | 6 +- main/services/git-executable.test.ts | 78 +++++++++++++++---- .../subagents/subagent-supervisor.test.ts | 12 ++- 4 files changed, 80 insertions(+), 24 deletions(-) diff --git a/docs/state-machines/p5-p6-tier-a-reconciliation.md b/docs/state-machines/p5-p6-tier-a-reconciliation.md index 93e54c54ec..0757d934be 100644 --- a/docs/state-machines/p5-p6-tier-a-reconciliation.md +++ b/docs/state-machines/p5-p6-tier-a-reconciliation.md @@ -29,7 +29,7 @@ Owns cron job registration (`jobs`), active task execution slots (`runningTasks` | `advanceBeforeRun` | Automatic non-recovery fire | For Bot routines: `store.claimRoutineFire` (optionally running `claimRoutineExecution` write-ahead before publishing the pending fire). For one-off chat tasks: disables task atomically. Marks `state.executionStarted = true` before `execution.run`. | | `save` / `remove` / `pause` / `resume` | Serialized by `withTaskLifecycle(taskId)` + optional `expectedUpdatedAt` | Stops cron job and awaits `cancelAndSettle(taskId)` before durable write. On caller `AbortSignal` after commit (`saveWithRollback` / `pauseWithRollback` / `resume`), rolls back durable state and rearms prior schedule. | | `cancelWorkspace(workspaceId)` | Synchronous add to `blockedWorkspaces` | Stops matching cron jobs, awaits `workspaceReady` on snapshot of `runningTasks`, cancels and settles matching runs. | -| `stop()` / `stopAndSettle()` | Any | Bumps `startupRevision`, sets `started = false`, stops pending-retry timer, clears catch-up queue (`generation += 1`), stops all crons, sets `cancelRequested = true`, calls `execution.cancelAll()`. `stopAndSettle()` races `cancelAndSettle()` against a 5 s shutdown cap. | +| `stop()` / `stopAndSettle()` | Any | Bumps `startupRevision`, sets `started = false`, stops pending-retry timer, clears catch-up queue (`generation += 1`), stops all crons, sets `cancelRequested = true`, calls `execution.cancelAll()`. `stopAndSettle()` races `cancelAndSettle()` against a 5 s shutdown cap and returns with a warning even if `runningTasks` are still live (stop requested, not a strict settlement fence). | #### Invariants & commit points - **Claim linearization:** For Bot routines, `store.claimRoutineFire` publishes the pending fire (and optional frozen execution claim) before `executionStarted` flips; a cancelled preparation before that point cannot publish a pending fire. @@ -50,7 +50,7 @@ Owns `createBotRoutineExecutor` (execution and crash recovery of one Bot routine | Admission probe | `recovering` with no prior run | Queries `ports.submissionForRequest(task.botId, requestId)`. If `retry` is `observeOnly` with no submission, settles fire and throws `UnclaimableScheduledFire`. If paused/disabled with no submission, records `blocked` without submitting. | | Execute: claim & state check | Not recovering or no `existingSubmissionId` | Optional write-ahead `ports.claimExecution`; inspects `ports.state(botId)`. `paused` → `skipped(paused_by_person)` (or `RoutineOutcomeUnknown` if an admitted fire exists); `interrupted` without `existingSubmissionId` → `skipped(bot_paused)`; `needs_model` → `RoutineFailure`; `unavailable` → error. | | Execute: retry safety | `trigger.kind === "retry"` and `!verifiedToolFree` | Verifies every prior attempt via `ports.canRetryRoutineRequest`; fails closed with `retry_effect_unknown` if any prior attempt may have executed tools. | -| Execute: submit & await | `wakeUpAllowed` (for wake-ups) and `!signal.aborted` | Calls `ports.send(..., { requestId, ifNotInterrupted: true })`. On send failure for `replayable(trigger)`, re-reads `submissionForRequest` — an admitted or unreadable lookup becomes `RoutineOutcomeUnknown` (never a false terminal failure). Awaits `ports.awaitReply`; abort/transport error on `replayable` becomes `RoutineOutcomeUnknown`. | +| Execute: submit & await | `wakeUpAllowed` (for wake-ups) and `!signal.aborted` | Calls `ports.send(..., { requestId, ifNotInterrupted: true })` wrapped in `abortable(..., signal)` (which races cancellation against the promise without aborting an already-started `ports.send()` call). On send failure for `replayable(trigger)`, re-reads `submissionForRequest` — an admitted or unreadable lookup becomes `RoutineOutcomeUnknown` (never a false terminal failure). Awaits `ports.awaitReply`; abort/transport error on `replayable` becomes `RoutineOutcomeUnknown`. | | Settle & deliver | Outcome resolved or caught | Writes durable `store.recordRun` (with `id: requestId` for durable/catch-up fires, omitting `id` for `duplicate` or `uncertain` so the real fire's ID stays free). Runs advisory `afterRun` (healing/retry/pause) and fire-and-forget `observeRoutineHooks` (`RoutineRun` / `RoutineFailed`). Calls `deliver` unless silent/skipped/retrying; if delivery throws, keeps pending fire receipt so startup retries delivery without re-running. Calls `store.settleRoutineFire` only when `durableFire(trigger) && !outcome.uncertain`. | #### Invariants & commit points @@ -67,14 +67,14 @@ Also retained under `backend:M024` in `retained-p1-owners.md`; re-audited here f #### Axes - **Per-Bot serialization:** `serialize = createKeyedQueue()` serializes `send`, `resume`, `dismiss`, `stop`, `stopLinkedWork`, `withdraw`, `compact`, `deleteBot`, `pause`, `unpause`, `submissionForRequest`, `canRetryRoutineRequest`. - **Durable state (`BotSessionState`):** `unavailable` (profile lock held elsewhere) | `paused` (persisted in `BotPauseStore`, fail-closed on unreadable file) | `running(submissionId)` | `interrupted(submissionId, blocked?)` | `needs_model` | `model_error` | `idle`. -- **Terminal fences:** `deleted` (loaded from durable `bots/pending-deletes.json` at construction before any open) and `shuttingDown` (set synchronously in `shutdown()`). +- **Terminal fences:** `deleted` (loaded from durable `bots/pending-deletes.json` at construction before any open) and `shuttingDown` (set synchronously in `shutdown()`, currently checked by `appendEntry` — not by `send()` or `openBot()`, which rely on `BotHarnessHost.shutdown()` rejecting later `host.open()` calls once `shutDown = true`). #### Transitions | Command | Guard | Next / Effect | |---|---|---| | `initialize()` | `host !== null` | Finishes every Bot in `pending-deletes.json`, sweeps orphan sessions against `knownBotIds()`, reads `interruptedBots()` without starting any scheduler, and publishes their state. | -| `send(botId, input)` | Validates provenance (`routineOrigin`, `peerOrigin`, `botMessage`, no `steer` under `deps.execution`), checks `deleted` | Inside `serialize(botId)`: dedupes by `requestId` first (`lookupRequest`); enforces `assertNotPaused`, `peer.assertCurrent()`, `spendingRefusal`, `ifNotInterrupted`, `ifIdle`; claims execution/model (releasing unsubmitted plain claim on refusal); dismisses prior interrupted turn if allowed; writes notices and submits to `pi-durable`. | +| `send(botId, input)` | Validates provenance (`routineOrigin`, `peerOrigin`, `botMessage`, no `steer` under `deps.execution`), checks `deleted` (no `shuttingDown` guard; late in-flight sends are fenced only once `host.shutdown()` closes host admission) | Inside `serialize(botId)`: dedupes by `requestId` first (`lookupRequest`); enforces `assertNotPaused`, `peer.assertCurrent()`, `spendingRefusal`, `ifNotInterrupted`, `ifIdle`; claims execution/model (releasing unsubmitted plain claim on refusal); dismisses prior interrupted turn if allowed; writes notices and submits to `pi-durable`. | | `resume(botId, requestId, options)` | `consumeBotResumeOperation` durable idempotency + `assertNotPaused` | Reconciles `BotExecutionDoc` tasks and unknown-cost approvals (`costConsent` verified via `verifyCostApproval` before `acknowledgeUnknown`), clears `blocked`, calls `harness.resume()`, and publishes state. | | `dismiss` / `stop` / `withdraw` | Per-Bot queue; `dismiss` checks `assertNotPaused` | `dismiss` dedupes via bounded `answered` map, isolates peer-shared inputs, aborts paused turn, writes `interrupted` notice, calls `onStopped`. `stop` guards `expectedSubmissionId` so a successor turn is spared. `withdraw` aborts only queued (unplaced) submissions. | | `pause` / `unpause` | `pause` checks `!deleted`; durable write first | `pause` writes `BotPauseStore` before calling `onPaused`, bounds `host.suspend` (tracking timed-out closes in `suspending` + `reopenAfterSuspend`), runs `afterPaused`, and publishes `paused`. `unpause` clears pause under queue, then runs `onUnpaused` outside queue so skipped-routine notices can `appendEntry` without deadlock. | diff --git a/docs/state-machines/physical-teardown.md b/docs/state-machines/physical-teardown.md index 1aa5213787..deea38bab2 100644 --- a/docs/state-machines/physical-teardown.md +++ b/docs/state-machines/physical-teardown.md @@ -139,7 +139,7 @@ Traced end-to-end across `main/index.ts` (`requestApplicationQuit`, `runShutdown - Disposes `appUpdateService`, global shortcuts, dictation (`M131`), quick chat, local speech (`M134`–`M137`), Foundation Models connection, `formFillRuntime`, `computerUseStatus` invalidation, `scheduleService.stop()` (`P6`), `stopScheduledTaskTriggers()`, `telegramService.stop()`, `llmClient.abortAll()`, `subagentRuntimeRegistry.abortAll()`, watchers, and triggers `mcpManager.closeAll({ final: true })`. 4. **Parallel bounded teardown (P2, P4, P5, P6):** - Provider OAuth sign-in (`2 s`, `M078`); Computer Use host (`5.5 s`, `M116`–`M118`). - - Bot ingress (`scheduleService.stopAndSettle()` + `telegramService.stopAndSettle()`, `5.5 s`) **strictly before** `shutdownBotSessionRuntime()` (`5 s`, `M023`/`M024`), so nothing reopens a Bot harness while harnesses close and release profile locks. + - Bot ingress stop (`scheduleService.stopAndSettle()` + `telegramService.stopAndSettle()`, `5.5 s`) is requested before `shutdownBotSessionRuntime()` (`5 s`, `M023`/`M024`), reducing the chance of late harness opens while harnesses close and release profile locks. This ordering is **not** a strict ingress settlement fence (see the late-send / 5 s timeout gap below). - `subagentRunStore.flush()` + `close()` (`3 s`); `terminalService.flushHistory()` (`2 s`, `M130`). - `createImagesRuntime.shutdown("app-quit")` (`5 s`) **strictly before** `studioAssetStore.close()` (`2 s`). - `browserService.shutdown()` (`3 s`, `M125`); `shutdownBotComputers(4_000)` (`5 s`, `M121`/`M122`); `shutdownDevices()` (`8 s`, `M126`, calling `terminateDeviceHelperCommands()` on timeout); `settleFoundationModelsHelperStops(1_500)` (`2 s`); `mcpManager.closeAllWithin(2_000)` (`3 s`); `shutdownAntigravity()` (`4 s`, `M089`/`M090`). @@ -164,6 +164,10 @@ All renderer invokes are held by `startup-ipc-admission.ts` until every recovery ### Cross-lane gaps noted (none silently hidden) - Every step in `runShutdownAndQuit` is bounded by `settleShutdownStep` so a wedged step cannot hang quit, and `SHUTDOWN_HARD_CEILING_MS` forces `app.exit(1)` as a last resort. When a step times out (e.g., `parentGenerations`, `subagentRuntime`, `botRuntime`, or `mcpServers`), physical cleanup may still be finishing asynchronously or left to next-launch crash recovery (`reapPreviousLaunch()`, `reconcilePendingChatDeletions()`, `reconcilePendingManagedWorktreeDeletions()`, `pending-deletes.json`, `pi-durable` interrupted state). +- **Bot ingress stop vs. runtime shutdown late-send gap:** Running `scheduleService.stopAndSettle()` before `shutdownBotSessionRuntime()` requests stop first, rather than guaranteeing strict ingress settlement before harnesses close: + - `scheduleService.stopAndSettle()` (`main/services/schedule-service-core.ts`) races `cancelAndSettle()` against a 5 s cap and returns with a warning even while `runningTasks` are still live. + - In `main/services/scheduled-bot-routines.ts`, `abortable(ports.send(...), signal)` only races cancellation against an already-started `ports.send()` promise without cancelling the underlying `send()` call. + - `BotSessionService.send()` and `openBot()` (`main/services/bot-runtime/bot-session-service.ts`) do not check `shuttingDown` (only `appendEntry` checks `shuttingDown`); harness admission closes only once `BotHarnessHost.shutdown()` flips `shutDown = true` and rejects subsequent `host.open()` calls with `BotHarnessHostClosedError`. A late in-flight `send()` can therefore still race into `openBot()` before `host.shutdown()` begins. - `aiden serve stop` in `packages/cli` still cannot reap an MCP group whose wrapper exited (documented under MCP stdio servers above). - No end-to-end Electron multi-subsystem kill-and-restart harness exists across all P1–P5 lanes simultaneously; verification combines this static trace with per-lane unit/integration suites and the packaged subagent/compaction/diagnostics acceptance scripts. diff --git a/main/services/git-executable.test.ts b/main/services/git-executable.test.ts index 37fcd74033..9349e52b4d 100644 --- a/main/services/git-executable.test.ts +++ b/main/services/git-executable.test.ts @@ -348,7 +348,31 @@ test( "VerifiedRepoIdentityProof fails closed out of pure-FS fast path when GIT_EXEC_PATH is set", { skip: process.platform === "win32" }, async (t) => { - const { repo, service, created } = await createTempRepoWithWorktree(t); + const previousExecPath = process.env.GIT_EXEC_PATH; + const previousTrace = process.env.GIT_TRACE; + const previousGlobalConfig = process.env.GIT_CONFIG_GLOBAL; + const previousNoSystem = process.env.GIT_CONFIG_NOSYSTEM; + const { root, repo, service, created } = await createTempRepoWithWorktree(t, "/usr/bin/git"); + const fakeExecDir = path.join(root, "fake-exec"); + const traceFile = path.join(root, "git-trace.log"); + await fs.mkdir(fakeExecDir, { recursive: true }); + t.after(() => { + if (previousExecPath === undefined) delete process.env.GIT_EXEC_PATH; + else process.env.GIT_EXEC_PATH = previousExecPath; + if (previousTrace === undefined) delete process.env.GIT_TRACE; + else process.env.GIT_TRACE = previousTrace; + if (previousGlobalConfig === undefined) delete process.env.GIT_CONFIG_GLOBAL; + else process.env.GIT_CONFIG_GLOBAL = previousGlobalConfig; + if (previousNoSystem === undefined) delete process.env.GIT_CONFIG_NOSYSTEM; + else process.env.GIT_CONFIG_NOSYSTEM = previousNoSystem; + }); + + delete process.env.GIT_EXEC_PATH; + process.env.GIT_CONFIG_GLOBAL = "/dev/null"; + process.env.GIT_CONFIG_NOSYSTEM = "1"; + process.env.GIT_TRACE = traceFile; + + const readTrace = () => fs.readFile(traceFile, "utf8").catch(() => ""); const check = () => service.managedWorktreeUsable( repo, @@ -359,24 +383,44 @@ test( created.worktreeDevice, created.worktreeInode, ); + + // First call runs Git and caches the VerifiedRepoIdentityProof. assert.equal(await check(), true); + const traceAfterFirst = await readTrace(); + assert.ok(traceAfterFirst.length > 0, "initial check must invoke Git to mint the proof"); - const previousExecPath = process.env.GIT_EXEC_PATH; - const fakeExecDir = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-fake-exec-")); - t.after(async () => { - if (previousExecPath === undefined) delete process.env.GIT_EXEC_PATH; - else process.env.GIT_EXEC_PATH = previousExecPath; - await fs.rm(fakeExecDir, { recursive: true, force: true }); - }); - // Point GIT_EXEC_PATH to an empty directory and remove the worktree's - // .git file's sibling check? Even simpler: set GIT_EXEC_PATH and verify - // GitService rejects/falls back when Git itself runs with a broken exec path - // or verify `managedWorktreeUsable` still evaluates accurately without - // trusting the cached proof after core.bare=true + GIT_EXEC_PATH. + // Second call with identical environment and untouched signed paths must + // hit the 0-spawn pure-FS fast path (no new Git trace entries). + assert.equal(await check(), true); + const traceAfterFastPath = await readTrace(); + assert.equal( + traceAfterFastPath, + traceAfterFirst, + "unchanged check without GIT_EXEC_PATH must use the 0-spawn pure-FS fast path", + ); + + // Set GIT_EXEC_PATH while leaving all signed repo and config paths intact. + // The environment fence must invalidate the cached proof and invoke Git. process.env.GIT_EXEC_PATH = fakeExecDir; - const repoConfig = path.join(repo, ".git", "config"); - const before = await fs.readFile(repoConfig, "utf8"); - await fs.writeFile(repoConfig, `${before}\n[core]\n\tbare = true\n`, "utf8"); - await assert.rejects(check(), /Git repository|bare|failed/u); + assert.equal(await check(), true); + const traceAfterExecPath = await readTrace(); + assert.ok( + traceAfterExecPath.length > traceAfterFastPath.length, + "setting GIT_EXEC_PATH must bypass the cached proof and invoke Git", + ); + assert.match( + traceAfterExecPath.slice(traceAfterFastPath.length), + /rev-parse/u, + "Git discovery must run when GIT_EXEC_PATH invalidates the cached proof", + ); + + // A subsequent call while GIT_EXEC_PATH remains set must still invoke Git + // (no new proof may be cached under GIT_EXEC_PATH). + assert.equal(await check(), true); + const traceAfterRepeatExecPath = await readTrace(); + assert.ok( + traceAfterRepeatExecPath.length > traceAfterExecPath.length, + "pure-FS proof must not be re-cached while GIT_EXEC_PATH is set", + ); }, ); diff --git a/main/services/subagents/subagent-supervisor.test.ts b/main/services/subagents/subagent-supervisor.test.ts index 43e1d4679a..abf2975ecb 100644 --- a/main/services/subagents/subagent-supervisor.test.ts +++ b/main/services/subagents/subagent-supervisor.test.ts @@ -3522,6 +3522,7 @@ test("parent cancellation during prepareRun aborts all fulfilled preparations wi test("nested projector flush failure aborts the tree and completes projected nested runs without duplicate SubagentStop", async () => { const completedNested: string[] = []; const stopHooksFired: string[] = []; + const nestedRunIds: string[] = []; let failedNestedFlush = false; const projector = new SubagentEventProjector({ generationId: "generation-nested-flush-fail", @@ -3560,6 +3561,7 @@ test("nested projector flush failure aborts the tree and completes projected nes }), ); if (!parentAuthority) return prepared; + nestedRunIds.push(identity.runId); return { ...prepared, complete: async (result) => { @@ -3590,8 +3592,14 @@ test("nested projector flush failure aborts the tree and completes projected nes }), /nested projection disk full/u, ); - assert.ok(completedNested.length >= 1); - // Every finished run fires SubagentStop at most once. + assert.equal(nestedRunIds.length, 1); + const [nestedRunId] = nestedRunIds; + assert.equal(completedNested.length, 1); + assert.ok(completedNested[0]?.startsWith(`${nestedRunId}:`)); + assert.deepEqual( + stopHooksFired.filter((id) => id === nestedRunId), + [nestedRunId], + ); assert.equal(new Set(stopHooksFired).size, stopHooksFired.length); const nestedSnapshot = projector.snapshot().find((entry) => entry.label === "Nested child"); assert.ok(nestedSnapshot && ["failed", "interrupted"].includes(nestedSnapshot.state));