From 5333aa1b846510cd8821340899fb3619235c96d5 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 05:43:59 +0000 Subject: [PATCH 1/6] docs,cli,services: land Phase 0 D1 inventory index, Phase 3B desktop worksheets/fixes, and CLI serve-stop MCP survivor fix --- ...cit-state-machine-inventory-2026-11-04.tsv | 373 ++++++++++++++++++ ...-state-machine-risk-ranking-2026-11-04.tsv | 373 ++++++++++++++++++ docs/plans/README.md | 1 + ...-state-machines-refresh-plan-2026-11-23.md | 99 +++++ docs/state-machines/README.md | 49 +++ .../new-desktop-owners-2026-11.md | 104 +++++ docs/state-machines/serve-daemon.md | 12 +- main/services/aiden-mcp-server.test.ts | 101 +++++ main/services/bot-messages/lifecycle.test.ts | 39 ++ main/services/bot-plans/lifecycle.test.ts | 54 +++ .../gemini-live/app-control/provider.test.ts | 69 ++++ .../gemini-live/app-control/provider.ts | 14 +- main/services/hooks/hook-dispatcher.test.ts | 52 +++ main/services/hooks/hook-dispatcher.ts | 7 +- packages/cli/src/serve-lifecycle.ts | 120 +++++- packages/cli/tests/serve-lifetime.test.mjs | 93 +++++ 16 files changed, 1536 insertions(+), 24 deletions(-) create mode 100644 docs/audits/implicit-state-machine-inventory-2026-11-04.tsv create mode 100644 docs/audits/implicit-state-machine-risk-ranking-2026-11-04.tsv create mode 100644 docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md create mode 100644 docs/state-machines/README.md create mode 100644 docs/state-machines/new-desktop-owners-2026-11.md diff --git a/docs/audits/implicit-state-machine-inventory-2026-11-04.tsv b/docs/audits/implicit-state-machine-inventory-2026-11-04.tsv new file mode 100644 index 0000000000..39d591bced --- /dev/null +++ b/docs/audits/implicit-state-machine-inventory-2026-11-04.tsv @@ -0,0 +1,373 @@ +id scope review_label machine state_events_invariants source_links report +backend:M001 backend M001 I Application quit: forceAppQuit × cleanupStarted × shutdownStarted × installUpdateOnQuit, pending image quit coverage and soak receipts Close, before-quit, cancellation, install-update and teardown settlement advance separate flags. Cleanup once; a cancelled quit must reopen admission, actual shutdown must not. main/index.ts:241; main/index.ts:386; main/index.ts:543; main/index.ts:711; main/index.ts:1838; main/index.ts:2208 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M002 backend M002 I Lifecycle question/action gate: in-flight check plus queued continuation Serialize lifecycle checks and defer actions until the result; failure must release gate and not execute stale close. main/application-lifecycle-core.ts:45 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M003 backend M003 I Startup IPC and renderer readiness: opened/admitted bit, renderer generation, shared wait IPC opens only once startup is ready; replacement documents invalidate prior readiness; concurrent windows share readiness wait. main/services/startup-ipc-admission.ts:24; main/services/renderer-readiness-core.ts:8; main/index.ts:1894; main/index.ts:2292 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M004 backend M004 I Pill-window creation: absent / loading promise / live window / destroyed Concurrent create shares one promise; destruction and failed loading must clear correct owner. main/windows/pill-window.ts:20 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M005 backend M005 I Generation lifecycle: initializing map → active map → removed, crossed with cancelRequested, rendererDetached, inputClosed, quitInProgress, prompt attendance and computer-use activation Start, stream events, cancel, document loss, guidance, delete, quit; cancellation is not settlement, detach does not necessarily cancel work. Admission and cleanup cross several services. main/services/llm-client.ts:600; main/services/llm-client.ts:626; main/services/llm-client.ts:901; main/services/llm-client.ts:5221; main/services/llm-client.ts:5353; main/services/llm-client.ts:5466 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M006 backend M006 I Chat append-to-generation lease: authorityActive × asyncSettled × append/skill slot/byte reservations; owner reconciliation fence Reserve → append → settle → synchronous handoff → release. Expiry revokes authority but retains resource accounting until admitted IO settles; indeterminate append fences owner. main/services/chat-turn-admission.ts:35; main/services/chat-turn-admission.ts:80; main/services/chat-turn-admission.ts:197; main/services/chat-turn-admission.ts:315 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M007 backend M007 I First-send commit: committed × workSettled plus turn lease/worktree receipt Commit/handoff/failure/owner invalidation must distinguish durable append from safe retry; late IO retains ownership. main/services/chat-first-message-commit.ts:76; main/services/chat-generation-start.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M008 backend M008 I Mid-run input admission: per-stream serialized append and Pi steer/follow-up receipt Recheck generation identity, deletion, ownership, inputClosed and cancellation after awaits; committed user input must not be replayed as fresh input on a late failure. main/services/chat-run-input-admission.ts:73; main/services/chat-run-input-admission.ts:94 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M009 backend M009 I Generation/document ownership leases: active/invalidated identity plus listeners Reload/destroy invalidates authority; stale same-WebContents documents must not cancel, answer or mutate replacement document work. main/services/chat-generation-owner.ts:56; main/services/renderer-document-owner.ts:131 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M010 backend M010 I Chat/workspace mutation gates: changing/deleting sets plus active admissions Move/delete/copy/export blocks new turns, aborts matching work and awaits settlement, then releases; admission busy differs from draining-child busy. main/services/chat-deletion-gate.ts:7; main/services/chat-workspace-mutation-gate.ts:6; main/services/workspace-mutation-gate.ts:2; main/services/workspace-operation-registry.ts:25 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M011 backend M011 I Chat deletion saga: reconciliationRequired × chatRemoved × rollForwardPublished × deletionIsPending Journal/delete/side-effect cleanup/recovery must roll forward after durable deletion; failure before publication differs from uncertain publication. main/services/chat-application-service.ts:166; main/services/chat-application-service.ts:340 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M012 backend M012 I Pi runtime harness: running/managedRunning, managedQueueOpen, pendingAbort, appCancelRequested, shutdownInterrupted, disposed, durable operation and tool maps Prompt/steer/follow-up/abort/compaction/end/close. Managed queue closure, persistence completion and model completion are different transitions. main/services/pi-agent-runtime-harness.ts:866; main/services/pi-agent-runtime-harness.ts:916; main/services/pi-agent-runtime-harness.ts:2806; main/services/pi-agent-runtime-harness.ts:2814; main/services/pi-agent-runtime-harness.ts:2911; main/services/pi-agent-runtime-harness.ts:2944 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M013 backend M013 H Generation timeline and step lifecycle: running → completed/failed/cancelled; steps pending/awaiting_approval/running/blocked/terminal Tool start/result, approvals, cancellation, parent finish settle remaining unfinished steps; avoid resurrecting a terminal step via late callbacks. main/services/generation-timeline.ts:387; main/services/generation-timeline.ts:458; main/services/generation-timeline.ts:596; main/services/generation-timeline.ts:735; main/services/generation-timeline.ts:742 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M014 backend M014 I Delta coalescing: per-stream pending buffers/timers Delta enqueue → scheduled flush → terminal flush/removal. Terminal event must follow retained deltas and stale timer must not affect replacement stream. main/services/generation-delta-coalescer.ts:61 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M015 backend M015 H Host-run registry: working/needs_approval/needs_input/done/failed/cancelled; prompt IDs, pending terminal outcome, source ownership Generation/Bot events, approval/question changes, ownership loss, expiry; pending prompts override busy display and terminal outcomes must settle exactly once. main/services/host-run-registry.ts:250; main/services/host-run-registry.ts:292; main/services/host-run-registry.ts:560 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M016 backend M016 H Local run observation: idle/streaming/ended/gone plus holder/target subscriptions Subscribe/replay/live terminal/unsubscribe/source disappearance; cursor/event ordering and last-holder detach matter. main/services/local-run-observers.ts:74; main/services/local-run-observers.ts:108; main/services/local-run-observers.ts:252 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M017 backend M017 I Chat activity/attention/read state: stream counts, detached prompts, revisions and markers Start/end stream, prompt answer/expiry, detach, mark read; read status and active work must not accidentally clear outstanding attention. main/services/chat-activity-core.ts:22; main/services/chat-pending-attention.ts:37; main/services/chat-progress-events.ts:5; main/services/chat-read-markers.ts:64 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M018 backend M018 H Chat triage/snooze: started, stored snoozes, timer/retry and waking classification Snooze/wake, person writes, needs-input/approval/failure, expiration; publish-before-arm and restart expiration. main/services/chat-triage.ts:116; main/services/chat-triage.ts:248; main/services/chat-triage.ts:325; main/services/chat-triage.ts:347 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M019 backend M019 I Tool approval coordinator: pending × published × settled, closed-stream cancelled/detached tombstones Request/publish/decision/abort/detach/shutdown; exactly one answer, no late prompt after closed stream. main/services/tool-approval.ts:76; main/services/tool-approval.ts:126 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M020 backend M020 I Question coordinator: pending/expired/detached maps, timer × published × settled Ask, valid answer, countdown expiry, abort/detach/shutdown; timeout and answer race must choose one winner. main/services/ask-user-question-coordinator.ts:34; main/services/ask-user-question-coordinator.ts:95 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M021 backend M021 H Ephemeral side-question conversation: per-chat thread fingerprint, active operation/controller and terminal event Start/cancel/clear/delete/shutdown; independent of main turn but bound to owner document and current model. main/services/rpiv-btw/service-core.ts:89; main/services/rpiv-btw/service-core.ts:101; main/services/rpiv-btw/service-core.ts:277; main/services/rpiv-btw/service-core.ts:289; main/services/rpiv-btw/operation-registry.ts:10 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M022 backend M022 H Fork-summary job: pending → ready/failed plus running controller registry Fork starts job; retry/cancel/delete/restart reconcile pending with no live owner to interrupted failure. main/services/fork-summary-service.ts:94; main/services/fork-summary-service.ts:129; main/services/fork-summary-service.ts:161; main/services/fork-summary-service.ts:168; main/services/chat-fork-service.ts:95 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M023 backend M023 I Harness host: per-Bot open/closing/deleted sets, serialized lifecycle tails, admitted operations, shutDown flag, idle timer Open/touch/idle-close/suspend/destroy/shutdown; no reopen while close owns lock, no orphan deletion while live profile lease is held. main/services/bot-runtime/harness-host.ts:198; main/services/bot-runtime/harness-host.ts:215; main/services/bot-runtime/harness-host.ts:297; main/services/bot-runtime/harness-host.ts:323; main/services/bot-runtime/harness-host.ts:364; main/services/bot-runtime/harness-host.ts:451; main/services/bot-runtime/harness-host.ts:514 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M024 backend M024 H Bot session state: idle/running/interrupted/needs_model/model_error/unavailable/paused projected from harness plus pause store, deleted/suspending/blocked sets Send, Resume, Dismiss, Stop, pause/unpause, model changes and restart; displaying paused does not mean harness shutdown finished. main/services/bot-runtime/bot-session-service.ts:69; main/services/bot-runtime/bot-session-service.ts:378; main/services/bot-runtime/bot-session-service.ts:494; main/services/bot-runtime/bot-session-service.ts:776; main/services/bot-runtime/bot-session-service.ts:947 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M025 backend M025 I Durable pause overlay: absent/persisted pause, suspend pending/timed out/reopened; interrupted turn optional Persist pause before aborting work; passive entry commits must not resume scheduler. Unpause clears overlay without implicitly resuming interrupted turn. main/services/bot-pause-store.ts:1; main/services/bot-runtime/bot-session-service.ts:472; main/services/bot-runtime/bot-session-service.ts:487; main/services/bot-runtime/bot-session-service.ts:947; main/services/bot-runtime/bot-session-main.ts:147 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M026 backend M026 I Bot deletion/restart recovery: deleted fence plus durable pending-delete file and ordered cleanup effects Mark before destructive work, destroy harness, delete owned records, remove pending marker; restart must finish deletion, never reopen a half-deleted Bot. main/services/bot-runtime/bot-session-service.ts:402; main/services/bot-runtime/bot-session-service.ts:414; main/services/bot-runtime/bot-session-service.ts:843 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M027 backend M027 I Bot request/reply dedupe: requestId→submission, bounded resume/dismiss answers, hidden submissions, blocked readmission Duplicate send/resume/dismiss replays outcome; awaitReply must inspect paused scheduling without wait() accidentally starting it. main/services/bot-runtime/bot-session-service.ts:397; main/services/bot-runtime/bot-session-service.ts:441; main/services/bot-runtime/bot-session-service.ts:590; main/services/bot-runtime/bot-session-service.ts:776; main/services/bot-runtime/bot-session-service.ts:858 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M028 backend M028 I Bot approval wait registry Absent → waiting → allow/deny/withdrawn; abort and duplicate wait IDs clean up identity-matched entries, durable task memo permits same-ID re-ask after Resume. main/services/bot-runtime/bot-approvals.ts:47 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M029 backend M029 I Bot question wait registry Waiting → first valid answer or abort/replacement; invalid answers leave wait live; Bot ID and exact prompt identity gate settlement. main/services/bot-runtime/bot-questions.ts:74 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M030 backend M030 I Bot handoff registry and result idempotency Waiting → done/skipped/withdrawn; notes allowed only for appropriate card kinds; settled rule row is once per producing assistant call, not globally per reusable toolCallId. main/services/bot-runtime/bot-handoffs.ts:74; main/services/bot-runtime/bot-handoffs.ts:156 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M031 backend M031 I Handoff browser/computer holds and notifications Open card acquires tab/control hold, person answers or aborts releases; browser tab recreation, take-over state, and announced wait-ID dedupe have separate lifetimes. main/services/bot-runtime/bot-browser-handoff.ts:87; main/services/bot-runtime/bot-computer-handoff.ts:66; main/services/bot-runtime/bot-handoff-notifications.ts:50 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M032 backend M032 H Desktop live Bot projection: feed opening/live/ended, run starts, queued classifiers, subscriber replay/buffer and stopping/resuming overlays Watch frames/state notifications/cards/idle teardown/reopen; serial feed queue and run identity prevent old snapshots masking current work. main/services/bot-runtime/live-projection.ts:844; main/services/bot-runtime/live-projection.ts:1043; main/services/bot-runtime/live-projection.ts:1239; main/services/bot-runtime/live-projection.ts:1280; main/services/bot-runtime/live-projection.ts:1385 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M033 backend M033 I Bot model/tool registry snapshot and authority freshness Session opens registry, prepare/refresh installs tool set and memory snapshot, lazy runtime map per Bot; turn ingress changes routine/attended policy. main/services/bot-runtime/bot-models.ts:73; main/services/bot-runtime/bot-extension.ts:379; main/services/bot-runtime/bot-tool-assembly.ts:185 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M034 backend M034 I Bot starter/idempotent self-introduction Creation-key reservation → Bot creation/access → stable intro request → introduced; repeated preset starts must not duplicate Bot or intro. main/services/bot-runtime/bot-starter.ts:63; main/services/bot-application-service.ts:289 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M035 backend M035 H Bot lifecycle journal saga Pending operation/stage → completed; Bot/chat create/copy/delete/model-update and replay lookups serialize durable stages and expected identities. main/services/bot-lifecycle-journal-core.ts:10; main/services/bot-lifecycle-journal-core.ts:22; main/services/bot-lifecycle-journal-core.ts:423; main/services/bot-lifecycle-journal-core.ts:465; main/services/bot-application-service.ts:289 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M036 backend M036 I Bot capability leases and inventory generation fences Active leases → invalidated/aborted/released by policy epoch, identity or inventory fingerprint changes; readmission validates immediately before effect. main/services/bot-capability-lease.ts:62; main/services/bot-runtime-inventory-lease.ts:39; main/services/bot-runtime-authority.ts:526 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M037 backend M037 H Capability checkpoint/anchor publication pending → committed state head and pending → consumed bootstrap marker, initialized/poisoned flags; anchored persistence disagreement fails closed. main/services/bot-capability-state-checkpoint.ts:27; main/services/bot-capability-state-checkpoint.ts:307; main/services/bot-capability-state-checkpoint.ts:374; main/services/bot-capability-state-checkpoint.ts:516; main/services/bot-capability-authority-item.ts:133 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M038 backend M038 I Bot watchdog/stall latch running + no progress + not waiting on person → acting → handled/snoozed; attended vs routine outcomes differ; resume resets timing. main/services/bot-runtime/bot-run-watchdog.ts:42; main/services/bot-runtime/bot-run-watchdog.ts:48; main/services/bot-runtime/bot-run-watchdog.ts:82; main/services/bot-runtime/bot-run-watchdog.ts:102 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M039 backend M039 H Bot issue workflow Open issue → action claim → resolved/released/resettled; dedupe key prevents repeat delivery, action claim prevents simultaneous remedies. main/services/bot-issues/service.ts:139; main/services/bot-issues/service.ts:175; main/services/bot-issues/service.ts:194; main/services/bot-issues/service.ts:216; main/services/bot-issues/service.ts:232 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M040 backend M040 I Bot background memory review: scheduled → running → reviewed/failed/aborted/revoked/skipped; closed flag, per-Bot abort, admission lease and watermark Idle/turn threshold gates review; cancellation rechecked before passive marker commit; revoked authority may leave partial accepted writes. main/services/bot-memory/review.ts:562; main/services/bot-memory/review.ts:577; main/services/bot-memory/review.ts:588; main/services/bot-memory/review.ts:654 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M041 backend M041 I Bot memory snapshot freshness and forgotten fence load/cache → stale → reload; delete marks forgotten against late writes. Session memory snapshots intentionally outlive some edits until session refresh. main/services/bot-memory/service.ts:61; main/services/bot-memory/store.ts:202; main/services/bot-memory/store.ts:221 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M042 backend M042 H Bot routine proposal lifecycle pending → accepted/dismissed, revision/superseded and shown state; accept creates or updates routine, stale proposal decisions and dismiss cooldown are guarded. main/services/bot-routine-proposals.ts:209; main/services/bot-routine-proposals.ts:335; main/services/bot-routine-proposals.ts:367; main/services/bot-routine-proposals.ts:453; main/services/bot-routine-proposals.ts:677 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M043 backend M043 H Skill proposal lifecycle pending → added/dismissed with bounded pending/history, content/source fingerprints; accepting a changed file must not grant stale proposed content. main/services/bot-skills/proposals.ts:59; main/services/bot-skills/proposals.ts:74; main/services/bot-skills/proposals.ts:98 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M044 backend M044 H Lesson lifecycle proposed/active → retired/dismissed; per-scope capacity and supersession on acceptance, routine deletion retires/removes dependent lesson. main/services/bot-lessons/store.ts:39; main/services/bot-lessons/store.ts:55; main/services/bot-lessons/store.ts:74; main/services/bot-lessons/store.ts:91; main/services/bot-lessons/store.ts:115 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M045 backend M045 H Commitment reminder lifecycle waiting → proposed → accepted/dismissed/expired; clock pump and proposal settlement are separate transition owners; open-ended proposals remain pending. main/services/bot-commitments/store.ts:99; main/services/bot-commitments/store.ts:141; main/services/bot-commitments/proposer.ts:43; main/services/bot-commitments/proposer.ts:92 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M046 backend M046 H Delivery funnel new → deferred/suppressed/sent, per-channel delivery flags and dedupe/digest records; quiet hours/day cap/flush timer govern transitions. main/services/bot-delivery/funnel.ts:63; main/services/bot-delivery/funnel.ts:77; main/services/bot-delivery/funnel.ts:111; main/services/bot-delivery/funnel.ts:150; main/services/bot-delivery/funnel.ts:219; main/services/bot-delivery/gate.ts:80 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M047 backend M047 I Schedule scheduler: started × globallyEnabled, task timers/running-task map/cancelRequested/pendingScanRunning and catch-up queue Start/stop/rearm/fire/cancel/manual/retry/catch-up; a timer firing under an old task revision must not dispatch stale work. main/services/schedule-service-core.ts:181; main/services/schedule-service-core.ts:189; main/services/schedule-service-core.ts:576; main/services/schedule-service-core.ts:589; main/services/schedule-service-core.ts:696; main/services/schedule-service-core.ts:897 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M048 backend M048 H Durable routine fire and execution: pending fire → submitted/observing → completed/failed/interrupted/skipped; stable request ID, prior submission, retry evidence, pause and silent reply Existing submission cannot be repeated merely because observation failed; tool-free evidence gates retry; pause is skip not catch-up authorization. main/services/scheduled-bot-routines.ts:269; main/services/scheduled-bot-routines.ts:286; main/services/scheduled-bot-routines.ts:314; main/services/scheduled-bot-routines.ts:393; main/services/scheduled-bot-routines.ts:442; main/services/scheduled-bot-routines.ts:511; main/services/schedule-store-core.ts:938 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M049 backend M049 H Routine recovery/circuit breaker: retryable failure streak → backoff retry / needs-person issue / paused routine; successful run or explicit resume clears state Retry budget and no-effect evidence, not just error text, permit fresh execution. main/services/bot-routine-recovery.ts:48; main/services/bot-routine-recovery.ts:64; main/services/bot-routine-recovery.ts:131 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M050 backend M050 I Catch-up and one-shot wake-up lifecycle: last Bot state map detects leaving interrupted/paused; pending one-shot task → spent/cancelled/replaced, per-Bot queue No automatic catch-up while still paused; wake-up generation identity prevents obsolete reminders. main/services/scheduled-bot-routines.ts:857; main/services/scheduled-bot-routines.ts:1066; main/services/scheduled-bot-routines.ts:1090; main/services/bot-wake-ups/wake-ups.ts:135 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M051 backend M051 H Event routine dispatcher: event unseen → duplicate/held/queued/running/settled; daily counters, cooldown, held timer, running list, disposal epoch Durable dedupe before dispatch, bounded concurrent work; held release must verify current routine and pause. main/services/bot-routine-events/dispatcher.ts:31; main/services/bot-routine-events/dispatcher.ts:58; main/services/bot-routine-events/dispatcher.ts:95; main/services/bot-routine-events/dispatcher.ts:120 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M052 backend M052 H Watched source lifecycle: no baseline → baseline/no_change/changed/error, failure streak/paused/recovered, timer and inFlight set Rechecks latest enabled routine after IO; baseline must not emit as a change; repeated errors stop/recover watch appropriately. main/services/bot-routine-events/watch.ts:150; main/services/bot-routine-events/watch.ts:182; main/services/bot-routine-events/watch.ts:212; main/services/bot-routine-events/watch.ts:267; main/services/bot-routine-events/store.ts:47 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M053 backend M053 I Folder watcher/debounce/self-write suppression: active watches, event windows, running turns with held paths, echo fingerprints and rearm generation File event → batch/hold → post-run release; prevent own-write echo loops while preserving real external edits. main/services/bot-routine-events/folder-watch.ts:57; main/services/bot-routine-events/folder-watch.ts:68; main/services/bot-routine-events/folder-watch.ts:97; main/services/bot-routine-events/folder-watch.ts:127; main/services/bot-routine-events/own-writes.ts:25 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M054 backend M054 I Remote service: enabled/mode/setupInFlight, listener readiness/failure, socket sets, TLS refresh, operation tail and tailnet route ownership Enable/disable/switch mode/pair/TLS update/connect/disconnect/quit serialize mutations; listener readiness differs from network route readiness. main/services/aiden-remote-service.ts:386; main/services/aiden-remote-service.ts:540; main/services/aiden-remote-service.ts:959; main/services/aiden-remote-service.ts:980; main/services/aiden-remote-service.ts:1034; main/services/aiden-remote-service.ts:1178; main/services/aiden-remote-service.ts:1281 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M055 backend M055 H Tailscale ownership/takeover workflow: unavailable/free/conflicting/owned assessment, takeover review tokens and exact route mutation/recheck Only owned or explicitly reviewed routes may be changed; command failure requires inspecting actual Serve state. main/services/aiden-remote-tailscale.ts:481; main/services/aiden-remote-tailscale.ts:609; main/services/aiden-remote-tailscale.ts:673; main/services/aiden-remote-tailscale.ts:729; main/services/aiden-remote-tailscale-route.ts:263 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M056 backend M056 H Pairing window: absent/awaiting_scan/finishing/failed/expired, secret/manual key material, exchange admission and source attempts Begin/close/expire/exchange; one admitted exchange, bounded attempts, erasure of abandoned key material. main/services/aiden-remote-pairing.ts:76; main/services/aiden-remote-pairing.ts:230; main/services/aiden-remote-pairing.ts:245; main/services/aiden-remote-pairing.ts:361; main/services/aiden-remote-pairing.ts:383; main/services/aiden-remote-pairing.ts:442 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M057 backend M057 H Nearby pairing requests: pending/approving/approved/denied/expired/cancelled × revealed/delivered/withdrawn/issued credential; poll waiters and retirements Approve/deny/cancel/host-window change/poll/retire/close; approval can require compensating revocation after cancellation or uncollected grant. main/services/aiden-remote-pairing-requests.ts:297; main/services/aiden-remote-pairing-requests.ts:436; main/services/aiden-remote-pairing-requests.ts:532; main/services/aiden-remote-pairing-requests.ts:567; main/services/aiden-remote-pairing-requests.ts:687; main/services/aiden-remote-pairing-requests.ts:702 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M058 backend M058 H Durable idempotency ledger: in_flight → fulfilled/rejected; unknown-outcome stays in_flight; persisted clock high-water and capacity Execute/replay/reconcile/prune/restart; uncertainty must never reopen effect execution, stale clock cannot resurrect expired keys. main/services/aiden-remote-operation-contract.ts:455; main/services/aiden-remote-operation-contract.ts:490; main/services/aiden-remote-operation-contract.ts:790 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M059 backend M059 I Durable operation ownership registry: unowned → owned by operation → complete/reconciled; restoration and bounded capacity Expected revision + owner proof guard finish; not equivalent to transient request completion. main/services/aiden-remote-operation-contract.ts:863 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M060 backend M060 H Remote generation stream registry: queued/running/waiting_for_approval/reconciling/done/error/cancelled/interrupted; approvals/questions/replay/cursors, persistence dirty/running/timer Start/events/admission/decision/detach/restart/retention; durable stream and generation settlement may diverge temporarily. main/services/aiden-remote-streams.ts:538; main/services/aiden-remote-streams.ts:963; main/services/aiden-remote-streams.ts:1089; main/services/aiden-remote-streams.ts:1114; main/services/aiden-remote-streams.ts:1484; main/services/aiden-remote-streams.ts:1761 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M061 backend M061 I SSE pump/backpressure: closed × blocked × ending × pumping, drain deadline and cursor Wake/write(false)/drain/terminal/close; no duplicate pump, bounded blocked transport and terminal flush before close. main/services/aiden-remote-sse.ts:58 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M062 backend M062 I Chat-progress stream refresh: closed/running/dirty/scheduled/revalidating, versions and audience cursors Snapshot/update/coalesce/revalidate/close; lost dirty update or authorization change must not leak stale private data. main/services/aiden-remote-chat-progress.ts:84; main/services/aiden-remote-chat-progress.ts:456; main/services/aiden-remote-chat-progress.ts:568 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M063 backend M063 I Host-feed projection: dirty × refreshChain × closed, pending run changes, audience subscriptions, timer Change/refresh/heartbeat/audience expiry/close; serialized refresh and per-audience event identity. main/services/aiden-remote-host-feed.ts:185; main/services/aiden-remote-host-feed.ts:356 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M064 backend M064 H Remote Bot live projector: per-Bot projector promise, state, watch lane, idle timer, stopping/stopRequested/resuming/resumeRequested/placedFailing Subscribe/frame/pause/resume/cards/unwatch/close; compatibility projection changes paused→unavailable for older audience. main/services/aiden-remote-bot-session.ts:791; main/services/aiden-remote-bot-session.ts:804; main/services/aiden-remote-bot-session.ts:883; main/services/aiden-remote-bot-session.ts:1060; main/services/aiden-remote-bot-session.ts:1243; main/services/aiden-remote-bot-session.ts:1586 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M065 backend M065 I Attachment upload/reservation lifecycle: upload active, records staged/claimed/consumed/reclaimed, deleting-chat fence Begin/upload/stage/reserve/consume/delete/revoke device/expiry; reservation rollback must preserve retryable attachments, deletion invalidates admitted uploads. main/services/aiden-remote-attachments.ts:231; main/services/aiden-remote-attachments.ts:244; main/services/aiden-remote-attachments.ts:266; main/services/aiden-remote-attachments.ts:374; main/services/aiden-remote-attachments.ts:393; main/services/aiden-remote-attachments.ts:489 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M066 backend M066 I Opaque file handle/listing leases: issued handles, listing membership, reclaimable set, counts and root identity List/use/renew/reclaim/revoke; bound device/root/inode and listing capacity prevent stale handles becoming authority. main/services/aiden-remote-opaque-handles.ts:64; main/services/aiden-remote-opaque-handles.ts:316; main/services/aiden-remote-files.ts:153 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M067 backend M067 I Remote workspace operation owner and schedule/script claims: active owner→invalidated and claim acquisition→consumption; workspace/device revoke blocks late effects Owner invalidation plus expected operation revision gate async writes and script run. main/services/aiden-remote-workspace-owners.ts:4; main/services/aiden-remote-schedules.ts:193 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M068 backend M068 I Remote TTS intents/sessions: live/cancelled/retained intent × session idle/active × revoked device/closed Start/cancel/owner deletion/capacity eviction; accepted or uncertain work remains fenced even after cache eviction. main/services/aiden-remote-tts.ts:32; main/services/aiden-remote-tts.ts:57; main/services/aiden-remote-tts.ts:160 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M069 backend M069 H Peer host registry: stored/enabled/current route/verified/negotiated/repinning plus active requests/streams, epochs, pairings and closed Pair/connect/repin/route discovery/enable/remove/close; credential identity and TLS pin bind every admitted request. main/services/peer-host-registry.ts:237; main/services/peer-host-registry.ts:607; main/services/peer-host-registry.ts:1026; main/services/peer-host-registry.ts:1131 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M070 backend M070 H Peer connection supervisor: disabled/connecting/connected/backoff/blocked with generation and timers Wake/network failure/auth failure/repair/route changes; stale generation callbacks cannot revive removed/disabled host. main/services/peer-host-manager.ts:205; main/services/peer-host-manager.ts:547; main/services/peer-host-manager.ts:585; main/services/peer-host-manager.ts:606; main/services/peer-host-manager.ts:682 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M071 backend M071 H Peer feed and run stream supervisor: feed off/unsupported/syncing/live; run streaming/idle/ended/gone/waiting plus cursor, holders, dropped/announced flags SSE loss/reconnect/reset/source end/last unsubscribe; feed health and peer transport connection are separate machines. main/services/peer-host-manager.ts:757; main/services/peer-host-manager.ts:779; main/services/peer-host-manager.ts:926; main/services/peer-run-subscriptions.ts:112; main/services/peer-run-subscriptions.ts:261 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M072 backend M072 H Peer Bot session stream supervisor: waiting/streaming/gone states, stopped flag, refcount holders, retry wake and cursor Subscribe/unsubscribe/dropHost/connection failure/resync; compatibility negotiation before applying Bot events. main/services/peer-bot-sessions.ts:74; main/services/peer-bot-sessions.ts:138; main/services/peer-bot-sessions.ts:151; main/services/peer-bot-sessions.ts:175 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M073 backend M073 I Peer discovery/pairing client: bounded session, queued probes, abort/deadline, polling pending→decision Discovery expires/cancels; pairing polling only accepts bound host identity and final envelope, abort can require remote cancellation. main/services/peer-discovery.ts:274; main/services/peer-discovery.ts:329; main/services/peer-pairing-client.ts:141; main/services/peer-pairing-client.ts:210; main/services/peer-pairing-client.ts:241 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M074 backend M074 I Telegram poll/dispatch/turn supervisor: started × activeTurn × dispatchPending × processingUpdates, poll abort and dispatch cancellation; offset/queue/typing activity Start/stop/new updates/claim/dispatch/retry/profile mutation; no overlapping polling owners or turn dispatch after profile invalidation. main/services/telegram/telegram-service-core.ts:265; main/services/telegram/telegram-service-core.ts:376; main/services/telegram/telegram-service-core.ts:1923; main/services/telegram/telegram-service-core.ts:2080; main/services/telegram/telegram-ownership.ts:60 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M075 backend M075 H Telegram durable Bot reply outbox: awaiting/interrupted/pending/sending/sent/failed/dismissed, redelivered flag Submit/watch reply/pause/unpause/restart/deliver; crash in sending is ambiguous and only bounded redelivery is allowed. main/services/telegram/bot-reply-outbox.ts:198; main/services/telegram/bot-reply-outbox.ts:275; main/services/telegram/bot-reply-outbox.ts:328; main/services/telegram/bot-reply-outbox.ts:399; main/services/telegram/bot-reply-outbox.ts:446 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M076 backend M076 I Telegram profile/config binding mutation: per-profile tails + incarnation, active profile service map, binding committed/pending anchor Remove/recreate/rotate binding/activate profile; old operations must not mutate replacement profile or commit mismatched anchor. main/services/telegram/telegram-profile-mutation-fence.ts:15; main/services/telegram/telegram-service.ts:895; main/services/telegram/telegram-bot-binding-store.ts:417 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M077 backend M077 I Telegram activity/thinking coalescer: dirty × pending × finished + timer Event/thinking tick/finish; late timer must not send after terminal delivery. main/services/telegram/telegram-activity.ts:34 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M078 backend M078 H Provider auth flow: no active session/authenticating/committing, pending prompt, timedOut/suppressNotifications, logoutInProgress/disposed Start/respond/cancel/owner loss/timeout/commit/logout/shutdown; committing is point of no return, cancellation may not claim credentials were not committed. main/services/provider-auth-flow-core.ts:476; main/services/provider-auth-flow-core.ts:557; main/services/provider-auth-flow-core.ts:603; main/services/provider-auth-flow-core.ts:672; main/services/provider-auth-flow-core.ts:695; main/services/provider-auth-flow-core.ts:922 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M079 backend M079 I Codex credential health and refresh: localNeedsAttention × remoteNeedsAttention × observed credential, generation abort controller and refresh flight Credential changes/rejected refresh/expiry/logout; stale failures cannot poison replacement credential generation. main/services/codex-provider.ts:251; main/services/codex-provider.ts:345; main/services/codex-provider.ts:358; main/services/codex-provider.ts:474 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M080 backend M080 I Generation-bound MCP connections: missing/pending/connected plus generation/cancelled/closedAfterConnect/closed Connect/disconnect/config change/transport close/timeout/shutdown; identity checks prevent late old connection caching, second close after late connect is required. main/services/generation-bound-connection-cache.ts:115; main/services/generation-bound-connection-cache.ts:151; main/services/generation-bound-connection-cache.ts:297 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M081 backend M081 I MCP service inventory/connection lifecycle: closed flag, connection cache, disconnecting set, inventory memo and generation Discover/prewarm/config changes/close; tool inventory ownership must match active connection and configuration generation. main/services/mcp.ts:319; main/services/mcp.ts:401; main/services/mcp.ts:414; main/services/mcp.ts:733 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M082 backend M082 I MCP OAuth operation ownership: interactive operations/generations/suspension counts Start/cancel/config-write/suspend/release; stale OAuth result cannot publish after configuration mutation. main/services/mcp-oauth-operation.ts:26; main/services/mcp-config-lease.ts:32 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M083 backend M083 I MCP OAuth exchange/token session: exchangingCode × flowReadTokens, observed tokens/session binding, commitAttempted/redirected, cache generation Redirect/auth-code/refresh/save/revoke; compare token identity and generation before write, distinguish rejected grant from stale observer. main/services/mcp-oauth-provider-core.ts:172; main/services/mcp-oauth-provider-core.ts:234; main/services/mcp-oauth-provider-core.ts:689; main/services/mcp-oauth-session-cache.ts:38 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M084 backend M084 I OAuth loopback receiver: closed × listening × answered + deadline Listen/callback/invalid request/timeout/abort; one valid answer and shutdown of listener on every terminal path. main/services/mcp-oauth-loopback.ts:100 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M085 backend M085 I MCP admission and cleanup gates: admission unknown/empty/pending; exclusive tail and cleanup in-flight Mark mutation pending → reconcile → empty; startup uncertainty must not admit credential-dependent tools prematurely. main/services/mcp-admission-queue.ts:17; main/services/mcp-admission-queue.ts:57; main/services/mcp-admission-queue.ts:83; main/services/mcp-credential-cleanup.ts:158 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M086 backend M086 I MCP discovery backoff/prewarm and failure diagnostics: generation-bound negative cache, active/idle/in-flight times, running prewarm, degraded-server windows Discover/fail/retry/config change/idle eviction/recovery/close; stale failures not carried into new generation. main/services/mcp-tool-discovery-core.ts:295; main/services/mcp-tool-discovery-core.ts:334; main/services/mcp-tool-discovery-core.ts:371; main/services/mcp-tool-discovery-core.ts:418; main/services/mcp-failure-diagnostics.ts:461 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M087 backend M087 I MCP stdio child teardown: live process ownership, groupReaped, exit-hook installation Spawn/close/exit/shutdown; process-group cleanup is separate from protocol close. main/services/mcp-stdio-transport.ts:31; main/services/mcp-stdio-transport.ts:107 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M088 backend M088 H ACP pinned runtime installation: unsupported/not_installed/installing/installed/update_available/failed, phase downloading/verifying/extracting/validating/activating, removing/lease count Explicit install/cancel/remove/validation/activation; atomic active-pointer publication after validation; no removal while leased. main/services/acp/installer.ts:35; main/services/acp/installer.ts:69; main/services/acp/installer.ts:169; main/services/acp/installer.ts:190; main/services/acp/installer.ts:249 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M089 backend M089 I ACP runtime session pool: bindings promises/live set/starting reservations/inflight operations × disposed/admissionClosed Prompt reuse/create/makeRoom/drop/abort/close; reserve starting capacity before await, validate host/session fingerprint before reuse. main/services/acp/runtime.ts:164; main/services/acp/runtime.ts:639; main/services/acp/runtime.ts:658; main/services/acp/runtime.ts:1039; main/services/acp/runtime.ts:1058 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M090 backend M090 I ACP launcher/process/connection: live and starting sets, closed; process settled/closing; connection exitError and exit waiters Launch/cancel/exit/close/shutdown fanout; shutdown waits launches, one exit notification rejects pending RPCs, pid ledger tracks surviving groups. main/services/acp/launcher.ts:56; main/services/acp/process.ts:77; main/services/acp/connection.ts:56; main/services/acp/pid-ledger.ts:140 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M091 backend M091 I Antigravity service/provider discovery: loaded/stopping promise and discoveryDue Explicit install/sign-in/catalog refresh/shutdown; catalog discovery one-shot after auth, launcher closes permanently only once quit committed. main/services/antigravity/service.ts:52; main/services/acp/provider.ts:58 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M092 backend M092 I ACP event adapter/tool activity: started × terminal and tracked tool call/diff retention Session update/start/result/end; terminal once, late tool updates cannot keep stale diffs forever. main/services/acp/pi-events.ts:37; main/services/acp/activity.ts:167; main/services/acp/activity.ts:261 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M093 backend M093 I Foundation Models helper connection/status: disposing flag, helper launch/request settlement/deadlines, status in-flight cache Status/generate/timeout/dispose; helper executable identity guards process termination, retryable preparation differs from permanent failure. main/services/foundation-models-connection.ts:25; main/services/foundation-models-connection.ts:116; main/services/foundation-models-connection-core.ts:286 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M094 backend M094 I Manual catalog refresh jobs: single-flight models.dev refresh; remote-catalog active task+signal; provider image catalog fetches; serialized AA/OpenRouter cache publication Explicit foreground refresh/cancel/key change; cached ordinary reads must not cause network refresh and stale jobs must not publish under changed credentials. main/services/models-dev-cache-core.ts:165; main/services/pi-remote-catalog.ts:274; main/services/image-generation/runtime.ts:342; main/services/artificial-analysis-runtime-core.ts:121; main/services/openrouter-benchmark-runtime-core.ts:164 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M095 backend M095 I Gemini context cache and warming: cache entries/loading/expiry/workspace ownership/cleanup set, warm run/disposed Create/reuse/update/expire/delete/shutdown; stale warming result must not recreate revoked cache entry. main/services/gemini-context-cache.ts:250; main/services/gemini-context-cache.ts:289; main/services/gemini-context-cache.ts:383; main/services/pi-cache-warming.ts:102; main/services/pi-cache-warming.ts:187 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M096 backend M096 H Provider usage-limit queue/circuit breaker: entry status, tester reservation, waiter/flight/line maps, draining and retry-now cooldown Rate/billing responses, deadline wake, probe/retry/cancel and successful requests; one tester per recovering provider and bounded retained waiters. main/services/usage-limit-core.ts:676; main/services/usage-limit-core.ts:778; main/services/usage-limit-core.ts:1001; main/services/usage-limit-service.ts:38 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M097 backend M097 I Spending/usage-accounting lifecycle: open request accounting, reserved/billed usage, loading/saving timers and limit adjustments Begin/record/end/allow-more/restart; account once despite cancellation or provider result races; persistence and UI limit state can lag. main/services/usage-accounting.ts:128; main/services/spending-service.ts:63; main/services/spending-service.ts:230; main/services/usage-store-core.ts:440 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M098 backend M098 I Web-search credential pool cooldown: per-key cooldown record and rotating cursors Claim/request quota failure/success/reset; no immediate retry of quota-blocked key, identity changes invalidate stale cooldown. main/services/web-search-key-pool-core.ts:146; main/services/web-search-key-pool-core.ts:315 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M099 backend M099 H Auth reuse grant validity: not-consented/invalid/ready/revoked/expired/identity-drift/model-unavailable projected from persisted binding and current credential Connect/refresh/revoke/key/model changes; reusable grant is not inference authorization after identity drift. main/services/web-search-auth-reuse.ts:398; main/services/web-search-auth-reuse.ts:522 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M100 backend M100 I Subagent supervisor/tree: treeExpired × treeBudgetExhausted, live batch stop hooks, children launched, deadline/settlement timers Spawn/delegate/result/timeout/budget/stop; parent settlement and proof child processes are gone are separate facts. main/services/subagents/subagent-supervisor-core.ts:382; main/services/subagents/subagent-supervisor-core.ts:1072; main/services/subagents/subagent-supervisor-core.ts:1089; main/services/subagents/subagent-supervisor-core.ts:1106 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M101 backend M101 H Nested concurrency scheduler: queued/running/waiting/settled plus tree active/waiting/terminal and capacity counters Parent delegates/releases slot, child runs, parent resumes, cancel/terminal; no slot leak or deadlock while parent waits for child. main/services/subagents/subagent-nesting-core.ts:725; main/services/subagents/subagent-nesting-core.ts:746; main/services/subagents/subagent-nesting-core.ts:865; main/services/subagents/subagent-nesting-core.ts:951; main/services/subagents/subagent-nesting-core.ts:1020; main/services/subagents/subagent-nesting-core.ts:1098 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M102 backend M102 I Child runtime registry/quarantine: children registry × shuttingDown × quarantined deployments Register/start/cancel/settle/abort by chat/generation/workspace/shutdown; quarantined process cleanup must block unsafe reuse. main/services/subagents/child-agent-runtime.ts:150; main/services/subagents/child-agent-runtime.ts:481 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M103 backend M103 I Isolated inference process: terminal × exited × workerMessageObserved × auth failure, stopping promise, cleanupHealthy and active controllers Worker messages/exit/error/abort/hard kill/retry; result terminal does not prove process gone; failed proof stays pending/fail-closed. main/services/subagents/subagent-inference-process-core.ts:94; main/services/subagents/subagent-inference-process-core.ts:133; main/services/subagents/subagent-inference-process-core.ts:149; main/services/subagents/subagent-inference-process-core.ts:240 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M104 backend M104 H Subagent public event projection/persistence: queued→starting→running→terminal with retained milestone/context maps and persistence tail Spawn/event/result/filter/persist; projection cannot publish success before durable boundary and must reconcile late events. main/services/subagents/subagent-event-projector.ts:240; main/services/subagents/subagent-event-projector.ts:292; main/services/subagents/subagent-event-projector.ts:569 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M105 backend M105 H Subagent control/steering/retry registry: live/terminal record, bounded pending steering/waiters/retry identity allocation Wait/steer/stop/retry/terminal/evict; owner and revision proofs, first terminal wins, retry creates fresh lineage. main/services/subagents/subagent-control-v2.ts:235; main/services/subagents/subagent-control-v2.ts:375; main/services/subagents/subagent-control-v2.ts:518; main/services/subagents/subagent-control-v2.ts:554; main/services/subagents/subagent-control-v2.ts:595; main/services/subagents/subagent-control-main.ts:78 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M106 backend M106 I Background subagent coordinator: active map + queued start/child binding/abort controller/settled bit Durable accept → execute → terminal; deletion/revocation/shutdown stop child and persist terminal evidence. main/services/subagents/background-subagent-coordinator-v2.ts:100; main/services/subagents/background-subagent-coordinator-v2.ts:265; main/services/subagents/background-subagent-coordinator-v2.ts:350 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M107 backend M107 H Subagent approval/run grant: pending/granted/denied; pending promise and call-owner/approval ledger with expiry Request/grant/deny/consume/expire/cancel; bound authority digest, argument digest and one-use call ownership. main/services/subagents/approval-v2.ts:8; main/services/subagents/approval-v2.ts:351; main/services/subagents/approval-v2.ts:472; main/services/subagents/subagent-mcp-mutation-approval.ts:198 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M108 backend M108 H Durable subagent effect/approval store: approval prepared/authorized/consumed/cancelled; effect prepared/dispatch_started/terminal/unknown; manifest revision CAS Persist prepare → dispatch marker → finish, restart reconciliation; no fresh retry after ambiguous external dispatch. main/services/subagents/subagent-effect-v2.ts:11; main/services/subagents/subagent-run-store-v2-core.ts:598 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M109 backend M109 I Subagent network budget and retained request capabilities: scoped counters/leases → exhausted/released; owned request capabilities expire/revoke Reserve before effect, refund/release exactly once; permission is bounded by lineage and current authority. main/services/subagents/network-budget-v2.ts:20; main/services/subagents/request-capabilities-v2.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M110 backend M110 H Durable parent effect/operation store: operation running→terminal; effect prepared→dispatch_started→completed/remote_error/unknown/interrupted or cancelled_before_dispatch Begin/prepare/dispatch/finish/recovery; terminal receipt and digest must agree, abandoned prepared effects differ from dispatched unknown effects. main/services/pi-runtime-effect-store.ts:185; main/services/pi-runtime-effect-store.ts:297; main/services/pi-runtime-effect-store.ts:430; main/services/pi-runtime-effect-store.ts:443; main/services/pi-runtime-effect-store.ts:475; main/services/pi-runtime-effect-store.ts:507 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M111 backend M111 H Advisor attempt workflow: prepared → dispatch_started → completed/failed/cancelled; restart prepared→cancelled, dispatched→unknown Reserve/admit/dispatch/result/timeout/restart; cannot retry unknown effect as if no request left host. main/services/advisor-attempt-store.ts:198; main/services/advisor-attempt-store.ts:234; main/services/advisor-attempt-store.ts:264; main/services/advisor-attempt-store.ts:271; main/services/advisor-runtime.ts:537; main/services/advisor-runtime.ts:601 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M112 backend M112 H Background shell jobs: running→exited/failed/stopped with stop promise, adopted group and pid identity, port scan and durable running record Launch/adopt/exit/stop/chat delete/quit/restart cleanup; process-group proof, not only leader exit, controls completion. main/services/follow-through/background-jobs.ts:280; main/services/follow-through/background-jobs.ts:339; main/services/follow-through/background-jobs.ts:734; main/services/follow-through/background-jobs.ts:765; main/services/follow-through/background-jobs.ts:790; main/services/follow-through/background-jobs.ts:889; main/services/follow-through/background-jobs.ts:981 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M113 backend M113 H Done-when check loop: waiting/running/passed/gave-up, running controllers and runWhenFree set Turn ends/check starts/result/abort/busy/restart; bounded checks, waiting run restored after interrupted check, no concurrent check and agent turn. main/services/follow-through/done-when.ts:88; main/services/follow-through/done-when.ts:100; main/services/follow-through/done-when.ts:190; main/services/follow-through/done-when.ts:240 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M114 backend M114 H Pull-request follow loop: following/ended plus checks history, nextCheck, notices count, paused chats/tick/closed Poll/observation/auth failure/check change/merge/stop/chat delete; retry bounds and notice dedupe distinct from PR's own static status. main/services/follow-through/pull-request-follows.ts:52; main/services/follow-through/pull-request-follows.ts:162; main/services/follow-through/pull-request-follows.ts:188; main/services/follow-through/pull-request-follow.ts:241; main/services/follow-through/pull-request-follow.ts:431 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M115 backend M115 I Agent notice delivery/wake admission: per-chat chain, saved message, wake budget and turn busy Save notice then steer/queue/wake; avoid duplicate wake or losing persisted notice when current run ends during admission. main/services/follow-through/notice-delivery.ts:63; main/services/follow-through/notice-delivery.ts:99; main/services/follow-through/notice-delivery.ts:129; main/services/follow-through/follow-through-main.ts:120 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M116 backend M116 H Computer-use controller: new/starting/ready/poisoned/closed, startup/close promises, closeFailed, driver calls and lifecycle abort Lazy first action/start error/timeout/driver loss/close; poisoned controller cannot silently reuse possibly unsafe state. main/services/computer-use/controller.ts:838; main/services/computer-use/controller.ts:1048; main/services/computer-use/controller.ts:1196; main/services/computer-use/controller.ts:2035 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M117 backend M117 H CUA session/transport: new/connecting/ready/broken/closed and started/didNotifyClose/closePromise Connect/list tools/call/error/timeout/close; serialized calls, exactly-once closure notification, drain failure breaks session. main/services/computer-use/session.ts:204; main/services/computer-use/session.ts:381; main/services/computer-use/session.ts:421; main/services/computer-use/session.ts:636; main/services/computer-use/session.ts:661 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M118 backend M118 I CUA host launch/cleanup: sessions/runtimes/pendingLaunches, shutdown controller, pending cleanup directories/retry counts Launch/readiness/cancel/close/shutdown/retry cleanup; don't lose runtime ownership when session creation fails mid-launch. main/services/computer-use/host.ts:148; main/services/computer-use/host.ts:206; main/services/computer-use/host.ts:218; main/services/computer-use/host.ts:419; main/services/computer-use/host.ts:485 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M119 backend M119 I Computer-use access/settings generation: grant revision, request epoch, disableRequired/closed/shutdown, activated stream bit Explicit access decision/enable/disable/model removal/revoke; close gate before snapshotting activated work and await actual settlement. main/services/computer-use/access-gate.ts:44; main/services/computer-use/access-gate.ts:119; main/services/computer-use/settings-core.ts:14; main/services/computer-use/generation-gate.ts:3; main/services/computer-use/generation-gate.ts:58 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M120 backend M120 I Computer-use status probe: cached expiry, in-flight probe controllers, revision and closed Probe/permissions/settings/revoke/shutdown; stale probe must not overwrite newer disabled state. main/services/computer-use/status-core.ts:265; main/services/computer-use/status-core.ts:297; main/services/computer-use/status-core.ts:422 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M121 backend M121 H Bot VM lifecycle and slot scheduler: stopped/waiting_for_slot/starting/running/stopping/stale × start/stopping promises × leases/idle timer; baseHoldsSlot/shuttingDown Acquire/release/start readiness/idle stop/pause/base setup/quit; slot not released until VM state confirmed; failed stop may return to running. main/services/bot-computers/host.ts:227; main/services/bot-computers/host.ts:265; main/services/bot-computers/host.ts:513; main/services/bot-computers/host.ts:626; main/services/bot-computers/host.ts:683; main/services/bot-computers/host.ts:731; main/services/bot-computers/host.ts:1543 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M122 backend M122 H Bot base setup/update: setupTask/setupAbort, progress downloading/verifying/provisioning, current/staging base and stale clones Explicit setup/update/cancel/failure/recovery; validate pinned image before base activation and keep operation off startup paths. main/services/bot-computers/host.ts:227; main/services/bot-computers/host.ts:1197; main/services/bot-computers/host.ts:1672; main/services/bot-computers/restore-image-download.ts:89; main/services/bot-computers/provision.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M123 backend M123 I Bot computer ownership takeover: controller bot/person × actions × waiters and unattended remaining wait budget Take over aborts in-flight Bot actions, Give back releases waits, forget invalidates; no Bot screen read while person holds control. main/services/bot-computers/control.ts:64; main/services/bot-computers/control.ts:80; main/services/bot-computers/control.ts:110; main/services/bot-computers/control.ts:126 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M124 backend M124 I Bot screen/session/viewer lifecycle: connection-keyed opening/screen lease, connecting/closed/pictured, viewer hub holders and button/key/touch state Open/change VM connection/close/takeover/disconnect; old screen must not act on restarted VM; release pressed inputs on teardown. main/services/bot-computers/sessions.ts:80; main/services/bot-computers/rfb-screen.ts:100; main/services/bot-computers/viewer-hub.ts:232; main/services/bot-computers/viewer-hub.ts:485; main/services/bot-computers/viewer-main.ts:69 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M125 backend M125 I Browser tab/workspace lifecycle: workspace/tab/session/popup-owner maps, loaded/deletingProfiles/workspaceAccess, navigation/crash generation Open/navigate/crash/reload/close/profile deletion/access change; tab existence does not imply active agent authority. main/services/browser/service.ts:286; main/services/browser/service.ts:757; main/services/browser/service.ts:1239 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M126 backend M126 I Browser per-workspace action queue/cancellation: serial tail plus AbortController Tool action admitted→running→settled, stop cancels current work and queue freshness guards stale actions. main/services/browser/core.ts:311; main/services/browser-tools.ts:199; main/services/browser/service.ts:2630; main/services/browser/service.ts:2945 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M127 backend M127 I Browser file capability leases: leases/opening/epochs/consumers/closing/retiredOrigins/retiredTokens/stopped Acquire/use/revoke origin/navigation/close/shutdown; root identity validation and draining reads precede resource cleanup. main/services/browser/files.ts:259; main/services/browser/files.ts:763; main/services/browser/files.ts:782; main/services/browser/files.ts:873 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M128 backend M128 I Browser PiP capture/recording/annotation selection: painting/pending/disposed, recording media + byte/error state, active picker Start/frame/stop/tab close/abort; capture stop and final recording blob completion are distinct, cancellation must remove interceptors. main/services/browser/pip-feed.ts:43; main/services/browser/service.ts:1913; main/services/browser/service.ts:2029; main/services/browser/service.ts:2192; main/services/browser/service.ts:2241 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M129 backend M129 H Device hub service: needs-consent/stopped/installing/starting/ready/error/unavailable plus loaded/starting/proxy/saving/granting/removing promises; peer/SSH entries Consent/install/connect/update/stop/revoke/peer loss; invalidate dependent proxy/recording/streams before removing toolchain. main/services/devices/device-service.ts:437; main/services/devices/device-service.ts:554; main/services/devices/device-service.ts:649; main/services/devices/device-service.ts:1166; main/services/devices/device-service.ts:1235; main/services/devices/device-service.ts:1317 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M130 backend M130 I Local/SSH device helper host: start lock, stopped/activated, stop promise, process readiness and reconnect callbacks Explicit start/cancel/exit/health failure/reconnect/stop; helper identity and ownership verified before terminating process groups. main/services/devices/local-device-host.ts:337; main/services/devices/local-device-host.ts:629; main/services/devices/ssh-device-host.ts:268; main/services/devices/ssh-device-host.ts:614 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M131 backend M131 H Device recording: recording/stopping/ready/failed × stopping/settling promises, kill/sweep timers Start/stop/process exit/collect/timeout/delete; only one recording per device, stop request not equal to file collected. main/services/devices/device-recording.ts:146; main/services/devices/device-recording.ts:184; main/services/devices/device-recording.ts:209; main/services/devices/device-recording.ts:261; main/services/devices/device-recording.ts:329 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M132 backend M132 I Device/SSE simulator audience lifecycle: per-target live sockets and subscriptions, audience mapping and websocket inMessage/violated Subscribe/upgrade/frame/consent revoke/close; retained socket must be closed when sharing or audience authorization changes. main/services/aiden-remote-simulators.ts:84; main/services/aiden-remote-simulators.ts:268 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M133 backend M133 H Dictation coordinator: operation identity, recording/stopping/delivering/error/cancelled; pillReady/holdToTalk/holdWatchActive/pendingRelease and hide/release/watchdog timers Press/release/toggle/warm-up/pill ready/transcript/result/error/cancel/dispose; stale operation result cannot paste after replacement/cancel. main/services/dictation-coordinator.ts:117; main/services/dictation-coordinator.ts:349; main/services/dictation-coordinator.ts:459; main/services/dictation-coordinator.ts:516; main/services/dictation-coordinator.ts:551; main/services/dictation-coordinator.ts:660 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M134 backend M134 I Dictation physical-key/portal/shortcut lifecycle: bound × pressed, stopped/settled, recordingSuspended and registered/unavailable maps Register/unregister/press/release/lost key event/settings changes; release watchdog handles missing keyup, shortcut transaction may rollback. main/services/linux-dictation-portal.ts:39; main/services/dictation-key-state.ts:30; main/services/shortcut.ts:36; main/services/shortcut.ts:336; main/services/shortcut-transaction-core.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M135 backend M135 H Local speech model download/load: downloading/failed with download/verify/extract phase; unload/loading/ready/failed engine state Download/cancel/remove/atomic replacement/load/release; loaded model identity changes emit unload before new load. main/services/local-speech-downloads.ts:261; main/services/local-speech-downloads.ts:337; main/services/local-speech-downloads.ts:355; main/services/local-speech-model-state.ts:34 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M136 backend M136 I Local speech worker/serialized lane/idle unload: launching/live/retiring worker generation, pending RPCs/closed, active lease count/loaded/idle timer Acquire/request/cancel/worker exit/model change/release/idle timeout/shutdown; terminate old process before admitting new incompatible work. main/services/local-speech-worker-host.ts:98; main/services/local-speech-worker-host.ts:159; main/services/local-speech-worker-host.ts:224; main/services/local-speech-process-core.ts:88; main/services/local-speech-lane.ts:41; main/services/local-speech-idle-unload.ts:22 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M137 backend M137 I Live transcription preview: decoding/stopped plus speech/pause segmentation and stable/provisional text; owner→session map Push audio/detect pause/decode/revise/end phrase/stop/owner invalidation; late decode cannot publish for ended session. main/services/local-speech-live-core.ts:89; main/services/local-speech-live-core.ts:200; main/services/local-speech-live-core.ts:219; main/services/local-speech-live-core.ts:310; main/services/gemini-live-transcription.ts:66; main/services/gemini-live-transcription.ts:252; main/services/gemini-live-transcription-core.ts:21 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M138 backend M138 H TTS generation/playback: preparing/generating/buffering/playing/paused/completed/cancelled/failed × paused × segments-ready × current owner/retained job Start/synthesis segment/audio fetch/pause/resume/cancel/revoke/shutdown; completed generation is not playback completion, stale owner must lose audio access. main/services/tts/service.ts:138; main/services/tts/service.ts:283; main/services/tts/service.ts:452; main/services/tts/service.ts:509; main/services/tts/service.ts:542; main/services/tts/service.ts:824; main/services/tts/audio-store.ts:37 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M139 backend M139 H Gemini live protocol: idle/connecting/open/resuming/closing/disconnected/failed/closed; seeded/resumptionInFlight, toolCalls issued/completed/cancelled and attempt controller Socket open/setup/audio/server turn/tool call/goAway/resume/error/close; exactly-once tools across resumption, bounded reconnect and setup timeouts. main/services/gemini-live/protocol.ts:526; main/services/gemini-live/protocol.ts:539; main/services/gemini-live/protocol.ts:727; main/services/gemini-live/protocol.ts:1366; main/services/gemini-live/protocol.ts:1513; main/services/gemini-live/protocol.ts:1691 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M140 backend M140 H Live-session ownership/thread finalization: per-owner sessions with connecting/resuming/closed, display bindings, shuttingDown, pending thread finalization/start waiters Start/protocol callbacks/display grant replacement/stop/shutdown/recovery; do not finalize transcript before in-flight start and final content are settled. main/services/gemini-live/service.ts:242; main/services/gemini-live/service.ts:384; main/services/gemini-live/service.ts:666; main/services/gemini-live/service.ts:722; main/services/gemini-live/service.ts:816; main/services/aiden-live-thread-store.ts:29 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M141 backend M141 I Live computer-use bridge/socket ownership: calls queued/running/complete/cancelled, closed/currentCapture; SDK socket finished/localCloseRequested Queue/execute/tool cancellation/close; one current screen capture and no SDK-owned socket surviving local close. main/services/gemini-live/computer-use-bridge.ts:111; main/services/gemini-live/computer-use-bridge.ts:188; main/services/gemini-live/owned-sdk-connector.ts:136 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M142 backend M142 H Form-fill batch consent: pending/authorized/consumed/revoked/expired and plan digest/token index Prepare/authorize/revalidate/consume/revoke/timeout; token consumed before effect, changed plan cannot reuse consent. main/services/form-fill/batch-core.ts:130; main/services/form-fill/batch-core.ts:184; main/services/form-fill/batch-core.ts:218; main/services/form-fill/batch-core.ts:264; main/services/form-fill/service.ts:168 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M143 backend M143 H Form-fill artifacts/runtime/helper: not-downloaded/downloading/preparing/ready/error/unsupported; preparation/stopping promises, lifecycle controller, helper pending/poisoned Download/cancel/remove/load/execute/helper error/dispose; removal waits work, uncorrelatable protocol failure poisons all pending requests. main/services/form-fill/artifacts-core.ts:200; main/services/form-fill/artifacts-core.ts:292; main/services/form-fill/artifacts-core.ts:353; main/services/form-fill/artifacts-core.ts:399; main/services/form-fill/runtime.ts:29; main/services/form-fill/helper-client.ts:98 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M144 backend M144 I Image workflow runtime/coordinator: opening/enabled; active/starting/deleting/version maps/closed Run start/stop/delete/config disable/shutdown; deleted or superseded workflow cannot receive late result publication. main/services/create-images/runtime.ts:80; main/services/create-images/run-coordinator.ts:98 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M145 backend M145 H Image run/attempt scheduler: run running→finished/interrupted; attempts queued/running/succeeded/failed/skipped/cancelled/interrupted; graph dependencies and request limit Claim request before provider dispatch, settle downstream on failure, restart interrupts live attempts; persisted claim and actual dispatch boundary differ. main/services/create-images/run-ledger.ts:268; main/services/create-images/run-ledger.ts:304; main/services/create-images/run-ledger.ts:528; main/services/create-images/scheduler-core.ts:394; main/services/create-images/run-executor.ts:270 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M146 backend M146 H External image job polling: submitted/queued/processing/completed/failed/cancelled and abort/deadline fal/Replicate submit→poll→download or error/cancel; local cancellation can race external completion and billable dispatch. main/services/image-generation/fal-images.ts:153; main/services/image-generation/replicate-images.ts:236; main/services/create-images/image-port.ts:133 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M147 backend M147 I Image consent/export/workflow storage: consent entries one-use/expiry, export pending/inFlight/sweep, workflow serialized writes/unreadable fences Grant/consume/revoke; export/cache expiry; staged document publication/recovery; late file creation must not survive revoked owner unexpectedly. main/services/create-images/consent-core.ts:18; main/services/create-images/image-export.ts:201; main/services/create-images/workflow-store.ts:113 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M148 backend M148 H Design run/revision lifecycle: running→complete/partial/interrupted, draft→published/missing; run recorded × accepted and pending settlements Start/render/finish/cancel/recover/missing files; publish complete only with revisions, partial requires retained output, effect acknowledgement follows durable render. main/services/design/store-core.ts:285; main/services/design/store-core.ts:381; main/services/design/store-core.ts:531; main/services/design/store-core.ts:572; main/services/design/store-core.ts:617; main/services/design/run-service.ts:90; main/services/design/run-service.ts:149; main/services/design/run-service.ts:260 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M149 backend M149 H Design project lifecycle: active/deleting/unreadable plus staging/reservations/per-project gate Create/publish/delete/restart/repair; durable deleting marker drives roll-forward, capacity reservations held through admitted writes. main/services/design/store.ts:118; main/services/design/store.ts:160; main/services/design/store.ts:524; main/services/design/store.ts:557; main/services/design/store.ts:601; main/services/design/store.ts:690 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M150 backend M150 I Generated HTML/Aiden UI draft lifecycle: call maps, sent partial/finished/cancelled, preview closed and artifact publication Tool argument deltas→draft preview→final artifact/cancel; terminal must remove ephemeral preview without losing committed artifact. main/services/generative-ui-draft.ts:21; main/services/generative-ui-draft.ts:101; main/services/aiden-ui-draft.ts:36; main/services/generative-ui-preview-store.ts:75; main/services/generative-ui-artifact-store.ts:189 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M151 backend M151 I Workspace artifact refresh/action: live refresh with joiners, generation, abort/cancel and save eligibility Refresh/join/leave/invalidate/action/close; one request may outlive caller but stale generation must not persist snapshot. main/services/workspace-artifacts/runner.ts:112; main/services/workspace-artifacts/runner.ts:125; main/services/workspace-artifacts/runner.ts:201; main/services/workspace-artifacts/runner.ts:227; main/services/workspace-artifacts/runner.ts:259 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M152 backend M152 H Managed first-message worktree: pending/failed/ready plus preparing/fetching/creating progress, persistent request key and writes chain Prepare/retry/reconcile existing checkout/commit; retry must adopt only matching identity rather than create duplicate branch. main/services/first-message-worktree.ts:39; main/services/first-message-worktree.ts:99; main/services/first-message-worktree.ts:285; main/services/first-message-worktree.ts:299; main/services/first-message-worktree.ts:328; main/services/workspace-worktree-application-service.ts:407 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M153 backend M153 H Managed worktree deletion: prepared→quarantined→checkout_cleanup_started→checkout_complete→admin_cleanup_started→filesystem_complete/needs_review; path moved flags and journal Authorize/quarantine/delete/recover/metadata finalization; uncertain filesystem identity routes to review, never infer safe deletion from absence alone. main/services/git.ts:5028; main/services/git.ts:5088; main/services/git.ts:5208; main/services/git.ts:5480; main/services/git.ts:5586; main/services/managed-worktree-remover.ts:310 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M154 backend M154 H Managed worktree snapshot/restore: creating/ready/restoring/expired; restore checkout_planned→checkout_created→snapshot_applied→complete Snapshot/delete/restore/restart/expire; planned checkout adoption verifies identity and publication journal retains crash position. main/services/managed-worktree-snapshot.ts:67; main/services/managed-worktree-restore.ts:171; main/services/managed-worktree-restore.ts:219; main/services/managed-worktree-restore.ts:265; main/services/managed-worktree-restore.ts:281; main/services/managed-worktree-restore.ts:295 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M155 backend M155 I Git operation concurrency/transactions: read flights/cache/mutation epochs/per-common-dir mutation tails; index transaction/head guard/ref-update attempted/confirmed Read/mutate/cancel/commit/push/reconcile; stale cached read invalidated after mutation, external push uncertainty cannot be reported as unexecuted. main/services/git.ts:1023; main/services/git.ts:1515; main/services/git.ts:2242; main/services/git.ts:2322; main/services/git.ts:2467; main/services/git.ts:2621; main/services/git.ts:3367 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M156 backend M156 I Terminal session/process ownership: session map, pending workspace exits, unverifiable workspaces, webContents epochs and exited flag Spawn/write/resize/owner loss/exit/workspace remove/quit; process-tree settlement needed before destructive worktree operation. main/services/terminal.ts:245; main/services/terminal.ts:418; main/services/terminal.ts:493; main/services/terminal.ts:640 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M157 backend M157 I Generic data store publication/recovery: unloaded/loading/loaded × corrupt/unsafe × mutation queue; receipt not-published/uncertain/published; live held files Read/reload/mutate/stage/fsync/rename/recover; uncertain publication cannot safely rollback in-memory authority as if no write occurred. main/services/data-store.ts:85; main/services/data-store.ts:112; main/services/data-store.ts:329; main/services/data-store.ts:448; main/services/data-store.ts:501; main/services/data-store.ts:604 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M158 backend M158 I Chat store migration/maintenance: initialized × reconcileNeeded × exclusive, maintenance promise and image-sweep timer/running Load/migrate/reconcile/write/cleanup; one maintenance owner and no normal reads through unreconciled data. main/services/chat-store-core.ts:182; main/services/chat-store-core.ts:258; main/services/chat-store-core.ts:873 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M159 backend M159 H Pi session compaction/journal recovery: begin/commit transaction markers, open transactions, sessions/opening/quarantined maps, compaction abort and overflowRecoveryAttempted Compact/cancel/crash/reopen/quarantine/seed; incomplete transactions hidden/recovered, at most one overflow recovery per coordinator attempt. main/services/pi-compaction-session-store.ts:53; main/services/pi-compaction-session-store.ts:533; main/services/pi-compaction-session-store.ts:604; main/services/pi-compaction-session-store.ts:857; main/services/pi-compaction-core.ts:249; main/services/context-lifecycle-service.ts:88 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M160 backend M160 H Durable job SQL lifecycle and worker lease: admitting/queued/running/pause_requested/cancel_requested/waiting_approval/waiting_input/paused/interrupted/needs_attention/failed/succeeded/cancelled × intent/continuation/lease/revision/dispatched Enqueue/claim/admit/dispatch/checkpoint/settle/recover/retry/stop; beforeEffect checks live lease, outcome evidence governs settlement. Foundation service explicitly says Pi runtime adapter not wired here. main/services/durable-jobs/store.ts:362; main/services/durable-jobs/store.ts:471; main/services/durable-jobs/store.ts:490; main/services/durable-jobs/store.ts:534; main/services/durable-jobs/store.ts:636; main/services/durable-jobs/service.ts:73; main/services/durable-jobs/worker.ts:9 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M161 backend M161 I Studio asset store/open/recovery/delivery grants: opening/failed, thumbnail loads/failures, blob write queue; per-document expiring delivery grants Open/recover/import/GC/thumbnail failure/document invalidation; references and grants must be invalidated before orphan collection. main/services/studio-assets/store.ts:202; main/services/studio-assets/store.ts:243; main/services/studio-assets/store.ts:316; main/services/studio-assets/store.ts:604; main/services/studio-assets/delivery-core.ts:55 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M162 backend M162 H Memory fact lifecycle: active→superseded via replacement/expiry/delete; database opening/migration Fact insertion and supersession scoped transactionally, expiry cannot leave stale active always-on facts. main/services/memory-store.ts:205; main/services/memory-store.ts:376; main/services/memory-store.ts:685; main/services/memory-store.ts:691 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M163 backend M163 I Configuration/credential migration/watch: seedPromise, secretMigrationComplete/deferred/promise, portable migration, pending reconciliation/tail/timer Load/unlock/import/watch event/reconcile/cancel; defer on locked store without falsely marking migration complete. main/services/config-store-core.ts:319; main/services/portable-config-core.ts:1348; main/services/portable-config-watch-core.ts:43; main/services/portable-config-watch-core.ts:89; main/services/portable-config-watch-core.ts:174 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M164 backend M164 I Proof/receipt stores with deletion fencing: queued writes, deletedChats and pendingChats, initialized/reconciled records Verify/record/delete/restart; late checks cannot republish evidence for deleted chat. main/services/pi-verification-store.ts:81; main/services/workflow-evidence-store.ts:132; main/services/chat-pull-request-store.ts:123 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M165 backend M165 H App updater: idle/checking/downloading/ready/error, in-flight operation, manual pending, started/disposed and retry/stall timers Manual/periodic check/download/progress/stall/retry/install/quit; install only ready version and stop all scheduled work on disposal. main/services/app-updater-core.ts:55; main/services/app-updater-core.ts:157; main/services/app-updater-core.ts:182; main/services/app-updater-core.ts:198; main/services/app-updater.ts:124; main/services/app-updater.ts:172; main/services/app-updater.ts:323 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M166 backend M166 I Analytics consent/client lifecycle: activation promise/generation, client/revocation/stopped/openedSent, consent queue Notice shown/toggle/environment gate/start/shutdown; revoke pending activation before it creates client, disabled event once then drop queue/install ID. main/services/analytics/analytics-service.ts:119; main/services/analytics/analytics-service.ts:192; main/services/analytics/analytics-service.ts:248; main/services/analytics/analytics-service.ts:260; main/services/analytics/analytics-client.ts:33 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M167 backend M167 I Diagnostic/usage/support flushers: dirty × running/counting/scheduled × stopped/persistenceFailed, queue and retry Mutate/debounce/flush/close/retry; changes arriving during write require follow-up flush, terminal shutdown bounded. main/services/diagnostic-health.ts:50; main/services/diagnostic-journal.ts:64; main/services/model-pace-core.ts:347; main/services/inbox-dock-badge.ts:243 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M168 backend M168 I File/watch cache refreshers: entry generations, scheduled refresh, pending invalidation/disposed FS change/add/remove/refresh/close; old async discovery cannot overwrite newer owner snapshot. main/services/git-repo-watcher.ts:67; main/services/git-repo-watcher.ts:163; main/services/bot-skill-content-watcher.ts:18; main/services/skills-discovery.ts:492; main/services/skill-registry.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M169 backend M169 I Single-flight/coalescing operation gates: absent/pending/fulfilled/rejected/superseded, current-token identity Replace/retry/wait/clear; waiters follow replacement while obsolete failure remains observable only to its caller. Shared pattern also used by model/catalog/path discovery. main/services/superseding-task-core.ts:19; main/services/git-executable.ts:123; main/services/models-catalog-core.ts:86 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M170 backend M170 I Bounded child process/request settlement: settled × aborted/timedOut/outputLimitExceeded, termination promise, drain timer and identity-backed process ownership Spawn/data/drain/exit/error/deadline/abort/kill; one response, continued cleanup after timeout, process exit proof independent of returned error. main/shared/process-group.ts:76; main/shared/process-group.ts:132; main/services/bounded-shell-command.ts:90; main/services/bounded-shell-command.ts:204; main/services/git-clone-runner.ts:120; main/services/bot-computers/bounded-process.ts:71 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M171 backend M171 I Foreground picker/export/single-operation admission: pickerActive/chatExportActive/pending/preparingShare IPC request claims synchronously, dialog cancel/success/error releases; owner invalidation must prevent response applying to new document. main/handlers/attachments.ts:52; main/handlers/chats.ts:158; main/handlers/bot-computers.ts:72; main/handlers/acp-harnesses.ts:45; main/services/profile-share.ts:29 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M172 backend M172 H App-control side-effect receipts: pending operation→outcome_unknown/applied/already_set, serialized authority revision Read/revalidate/change/verify/persist; transport or publication error must preserve unknown result instead of allowing blind retry. main/services/app-controls-core.ts:230; main/services/app-controls-core.ts:321; main/services/app-controls-core.ts:339; main/services/app-controls-core.ts:358; main/services/app-controls-core.ts:370 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M173 backend M173 I Cut-off continuation and failed-attempt rewind continuingCutOffReply × currentAssistantTurnContinuesCutOff × currentAssistantTurnHadVisibleText/HadReasoningDelta, turn start offsets and failed-turn start. Message start captures continuation mode; deltas choose separator; retry retaining partial continues it, retry replacing partial rewinds only failed attempt and emits reset. main/services/llm-client.ts:3014; main/services/llm-client.ts:4312; main/services/llm-client.ts:4359; main/services/llm-client.ts:4416; main/services/llm-client.ts:4920; main/services/llm-client.ts:4956 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M174 backend M174 I Journal availability/fault latch piJournalHealthy × piJournalStopNoted × piJournalless × piUpgradeCompactionEnabled. Initial session eligibility chooses durable or in-memory path; journal failure poisons durability and emits stop notice once. Journal-free mode must not enter durable quarantine/recovery path. main/services/llm-client.ts:3032; main/services/llm-client.ts:3053; main/services/llm-client.ts:3769; main/services/llm-client.ts:4599; main/services/llm-client.ts:4692 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M175 backend M175 I Visible-assistant publication / durable reconciliation saga Visible-turn lease, pending durability settlement, abandoned-assistant and quarantine-without-lease flags. Final save may commit, fail, rollback or defer reconciliation; detached settlement quarantines chat until recovery; visible and durable histories must agree before next turn. main/services/llm-client.ts:4594; main/services/llm-client.ts:4608; main/services/llm-client.ts:4648; main/services/llm-client.ts:4704; main/services/llm-client.ts:4962 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M176 backend M176 I Accepted but undelivered guidance return Collected-once bit plus immediate/late queued messages and captured owner. Stop/terminal/projection failure collects pending steer text; late settlement returns only messages whose visible save did not land. Avoid both loss and duplicate restoration after cancel. main/services/llm-client.ts:4831; main/services/llm-client.ts:4833; main/services/llm-client.ts:4841 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M177 backend M177 I Terminal response persistence and usage settlement Runtime outcome/cancelRequested, unreported-usage cancellation claim, replyNotSaved and final persistenceFailed projection. A model-completed reply can still have local-save failure; cancellation usage must be recorded once and terminal event exposes persistence failure. main/services/llm-client.ts:4966; main/services/llm-client.ts:4990; main/services/llm-client.ts:5060; main/services/llm-client.ts:5085 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M178 backend M178 I Remote device authorization/revocation barrier: blocked device set, active authorization counts, waiters and pending revocation promises Acquire authorization → release; revoke blocks new acquisitions, drains existing authorizations, persists revoke; failed write can release temporary block but cannot pretend persisted revoke. main/services/aiden-remote-state.ts:608; main/services/aiden-remote-state.ts:996; main/services/aiden-remote-state.ts:1027; main/services/aiden-remote-state.ts:1037 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M179 backend M179 I Renderer-acknowledged app navigation: pending request with owner/document and five-second deadline Open emits navigation only to a usable local owner; opened/blocked acknowledgement, abort, document invalidation or deadline settle request; same-document proof gates acknowledgement. main/services/aiden-app-navigation.ts:14; main/services/aiden-app-navigation.ts:39; main/services/aiden-app-navigation.ts:64 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M180 backend M180 I Attachment ingestion reservations: records + per-document/global count/byte budgets × cancelled Acquire synchronously reserves budgets; cancel revokes authority without freeing retained representation; release returns counters exactly once. Separate from remote uploaded-attachment consumption. main/services/attachments.ts:151; main/services/attachments.ts:177; main/services/attachments.ts:211 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M181 backend M181 I Per-attempt MCP OAuth nonce/issuer consumption: discovered metadata, started/consumed, required issuer and scope Discovery→authorization URL→single callback→code exchange; same nonce, exact issuer/count and one result required, no callback replay after consume. main/services/mcp-oauth-session.ts:418; main/services/mcp-oauth-session.ts:447; main/services/mcp-oauth-session.ts:478 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M182 backend M182 I Privileged computer-use one-shot grant: prepared fingerprint/target revision → authorized map entry → consumed/deleted Authorize checks action/target unchanged; consume deletes before validation/effect, so stale or reused grant cannot be retried; clear ends generation grants. main/services/computer-use/safety.ts:821; main/services/computer-use/safety.ts:829; main/services/computer-use/safety.ts:842; main/services/computer-use/safety.ts:864 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M183 backend M183 I GitHub rate governor and GraphQL reservations: scope pausedUntil/generation/strikes, reading/reset window/reserved budget/last operation cost Rate response increments generation/backoff; success clears only matching generation. Reserve before dispatch and settle response against monotonic reset/remaining evidence, preserve background reserve. main/services/github/github-rate-limit.ts:23; main/services/github/github-rate-limit.ts:42; main/services/github/github-rate-limit.ts:57; main/services/github/github-graphql-budget.ts:83; main/services/github/github-graphql-budget.ts:97; main/services/github/github-graphql-budget.ts:112 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M184 backend M184 I GitHub request batching/cache/credential lookup: queued→inflight→cached/failed plus flushScheduled, active document slots/waiters Read batches by host and operation, split failed multi-entry batch, release document slot once; caller abort need not cancel shared work. Credential cache and inflight lookup have separate freshness. main/services/github/github-pull-request-reader.ts:81; main/services/github/github-pull-request-reader.ts:102; main/services/github/github-pull-request-reader.ts:128; main/services/github/github-pull-request-reader.ts:140; main/services/github/github-pull-request-reader.ts:184; main/services/github/github-credentials.ts:216 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M185 backend M185 I Visual snapshot job queue: pending jobs, current abort, running promise, cancelled-chat tombstones/disposed Enqueue/drain/capture timeout/cancel chat/dispose; no snapshot publication after chat cancellation, bounded capture and follow-up drain. main/services/visual-snapshot-core.ts:136; main/services/visual-snapshot-core.ts:167; main/services/visual-snapshot-core.ts:196; main/services/visual-snapshot-main.ts:84 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M186 backend M186 I Local inference model-loading monitor: stopped × announcedLoading + polling timer Probe unloaded emits loading once; loaded emits ready only if loading was announced; unknown stops without faking loading; stream activity/abort stops poll. main/services/local-runtime-status.ts:186; main/services/local-runtime-status.ts:195; main/services/local-runtime-status.ts:205 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M187 backend M187 I Subagent workspace-write transaction: authorized calls/reserved tool IDs/lifecycles × shuttingDown, retained/commitConfirmed/cleanupPreserved Prepare approval and helper transaction, consume one-shot authorization, commit/finalize, preserve recovery on uncertain commit; release workspace admission only after helper cleanup. main/services/subagents/subagent-workspace-write.ts:457; main/services/subagents/subagent-workspace-write.ts:463; main/services/subagents/subagent-workspace-write.ts:707; main/services/subagents/subagent-file-mutator-io.ts:161 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M188 backend M188 I Subagent shell dispatch transaction: pending approval, active abort controllers, shuttingDown × dispatchStarted × terminal Revalidate command/root/authority, consume consent, durable dispatch marker, run, proof of cleanup then finish; unconfirmed cleanup becomes unknown once, pre-dispatch refusal cancels. main/services/subagents/subagent-shell.ts:302; main/services/subagents/subagent-shell.ts:522; main/services/subagents/subagent-shell.ts:557; main/services/subagents/subagent-shell.ts:572; main/services/subagents/subagent-shell-runner-io.ts:230 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M189 backend M189 I Routine health preflight scheduler: timers, checked fire keys, per-Bot running chains, disposed/rearms generation Rearm after schedule/sleep changes; stale read cannot arm old timers; one check per fire and per-Bot serial checks; late/past fire not checked. main/services/bot-health/preflight.ts:106; main/services/bot-health/preflight.ts:120; main/services/bot-health/preflight.ts:141 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M190 backend M190 I Remembered tool approval scope: no grant/chat grant/persisted always grant, per-chat map and bounded eviction Grant/match/revoke/clear chat; exact call/workspace binding, temporary chat authority distinct from persisted always authority. main/services/tool-approval-rules.ts:185; main/services/tool-approval-rules.ts:202; main/services/tool-approval-rules.ts:218; main/services/tool-approval-rules.ts:255 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M191 backend M191 I Remote Git snapshot authority: issued bounded snapshot token with expiry and expected repository/workspace identity Inspect issues token; mutation validates current snapshot/revision; expiry/prune removes authority. Durable idempotency ledger separately owns effect replay. main/services/aiden-remote-git.ts:207; main/services/aiden-remote-git.ts:227; main/services/aiden-remote-git.ts:234; main/services/aiden-remote-git.ts:280 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M192 backend M192 I Registration-once infrastructure: unregistered→registered/installed/requested Platform handlers, custom schemes, attachment/visual/asset protocols and discovery lazily register once; failed registration must not incorrectly latch success. main/platform.ts:122; main/services/custom-schemes-core.ts:44; main/services/chat-attachment-protocol.ts:6; main/services/generative-ui-protocol.ts:15; main/services/studio-assets/protocol.ts:4; main/services/browser-discovery.ts:10 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M193 backend M193 H Main-owned onboarding evidence: incomplete/deferred/completed × lastSatisfiedStep × selected provider evidence Read/migrate/reconcile/progress/finish/reset; profile precedes provider, completion needs ready evidence, lost readiness can reopen incomplete; current document gates publication. main/services/onboarding-state.ts:63; main/services/onboarding-state.ts:105; main/services/onboarding-state.ts:157; main/services/onboarding-state-core.ts:1; main/services/onboarding-reset-core.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M194 backend M194 H Subagent V1→V2 activation journal: missing/prepared/committed with source generation/content digest Read source→write prepared→reread source→CAS committed; changed source prevents activation; content digest handles filesystem identity changes after reboot. main/services/subagents/subagent-run-store-v2-migration.ts:30; main/services/subagents/subagent-run-store-v2-migration.ts:344; main/services/subagents/subagent-run-store-v2-migration.ts:387; main/services/subagents/subagent-run-store-v2-migration.ts:400; main/services/subagents/subagent-run-store-v2-migration.ts:413 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M195 backend M195 I Routine reflection worker: per-routine running set, last-reflected watermark, budget/admission lease and proposal output Enough settled runs→reserve→admit→model→watermark→propose/retire/no_entry/failed; evidence from multiple matching configurations and repeated authority checks gate accepted lessons. main/services/bot-learning/routine-reflection.ts:105; main/services/bot-learning/routine-reflection.ts:121; main/services/bot-learning/routine-reflection.ts:151; main/services/bot-learning/learning-main.ts:173 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M196 backend M196 I Bot learning daily accounting: day-scoped persisted request/output counts and returned settlement capability Reserve increments request before dispatch; settle charges observed output or worst-case cap for unknown usage; day rollover resets counters. Shared across review/reflection/tidy. main/services/bot-learning/budget.ts:22; main/services/bot-learning/budget.ts:40; main/services/bot-learning/budget.ts:50 docs/audits/implicit-state-machines-backend-2026-11-04.md +backend:M197 backend M197 I Device proxy grant/socket lifetime: expiring token grants, open sockets, per-host socket ownership and listening port Issue/access/prune/host disconnect/close; token authorizes only local proxy and is stripped upstream, host revoke must destroy retained connections. main/services/devices/device-hub-proxy.ts:362; main/services/devices/device-hub-proxy.ts:369; main/services/devices/device-hub-proxy.ts:374; main/services/devices/device-hub-proxy.ts:384 docs/audits/implicit-state-machines-backend-2026-11-04.md +clients:C01 clients C01 V Queue delivery and edit holds Queue contents × paused × sendingId × editingId × compaction hold × fork-summary hold. Add/edit/reorder/pause/resume/claim/settle; only one claimed send, editing blocks normal delivery, failed send retains message and pauses. Compaction failure pauses existing drafts; successful/unneeded/busy compaction releases hold. Explicit Steer has different guards. Retention/remount cleanup at renderer/lib/chat-message-queue.ts:225 is a second lifetime machine. renderer/lib/chat-message-queue.ts:19; renderer/lib/chat-message-queue.ts:130; renderer/lib/chat-message-queue.ts:156; renderer/lib/chat-message-queue.ts:178; renderer/lib/chat-message-queue.ts:206; renderer/lib/chat-message-queue.ts:225 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C02 clients C02 S Queued admission / steering Claimed → admitted/sent, deferred, or failed; waits for run admission with bounded retry, returns unsent guidance to draft. Queue state and host admission are separate authorities; stale chat/input owners must not consume another draft. renderer/lib/chat-message-queue.ts:255; renderer/lib/chat-message-queue.ts:318; renderer/lib/chat-message-queue.ts:386; renderer/lib/use-chat-message-queue.ts:24 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C03 clients C03 S Desktop generation orchestration Starting/live/stopping/retry-wait/reveal-draining/persisted plus approval/question/tool/model-loading flags. Start callbacks, deltas, terminal events, Stop, route change, resume/retry, delayed reveal. generationIntent/chatVisit/ref ownership fence async results; local render state alone cannot fence same-tick actions. renderer/main/chat-pane.tsx:769; renderer/main/chat-pane.tsx:809; renderer/main/chat-pane.tsx:849; renderer/main/chat-pane.tsx:1485; renderer/main/chat-pane.tsx:1935 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C04 clients C04 V Generation IPC subscription Subscribed before invocation → projecting → done callback settling → disposed; reset clears partial/reasoning; error disposes immediately. Stream ID filters every event. Lifecycle-detached versus explicit user-stop flags in IPC distinguish UI teardown from cancellation of main-owned work. renderer/lib/generation-stream.ts:98; renderer/lib/generation-stream.ts:116; renderer/lib/generation-stream.ts:167; renderer/lib/ipc.ts:2133 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C05 clients C05 V Detached lifecycle registry and fallback settlement Owned/attached → detached/projected → terminal-read pending → reconciled/released, with fallback registries/in-flight sets and bounded exponential retry. Capture stream IDs before reads so a stale reconciliation cannot clear replacement work; retain live output until saved transcript is ready. renderer/lib/chat-terminal-sync.ts:34; renderer/lib/chat-terminal-sync.ts:225; renderer/lib/chat-terminal-sync.ts:386; renderer/lib/chat-terminal-sync.ts:674; renderer/lib/chat-terminal-sync.ts:742 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C06 clients C06 V Observed local foreign run Following → terminal awaiting persisted reply → handed off; orthogonal releasing/reading/readRequested/readOwed. Coalesces reads, retries missing saved reply, release timer is generation-fenced, retain revokes pending release. Hotspot is terminal-before-disk publication. renderer/lib/hosts/observed-local-run.ts:90; renderer/lib/hosts/observed-local-run.ts:151; renderer/lib/hosts/observed-local-run.ts:195; renderer/lib/hosts/observed-local-run.ts:229 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C07 clients C07 V Remote run projection Explicit pure transition functions track idle/running/done/error/cancelled plus run identity, seq, incomplete, handedOff, prompts, textStreaming. Event gaps trigger refetch; handoff determines live versus persisted transcript. This is an explicit reducer-like island; external subscription/read lifecycle remains implicit. renderer/lib/hosts/remote-stream-translator.ts:28; renderer/lib/hosts/remote-stream-translator.ts:192; renderer/lib/hosts/remote-stream-translator.ts:359; renderer/lib/hosts/remote-stream-translator.ts:382; renderer/lib/hosts/remote-stream-translator.ts:387; renderer/lib/hosts/remote-stream-translator.ts:422 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C08 clients C08 S Remote chat reader Not-started/started/disposed × serialized refresh queue × frame pending × transcript/run/status snapshots. Adapter events enqueue updates and transcript reconciliation; dispose invalidates publication and cancels frames. Separate control/read classes are coordinated by hooks and view. renderer/lib/hosts/remote-chat-session.ts:67; renderer/lib/hosts/remote-chat-session.ts:111; renderer/lib/hosts/remote-chat-session.ts:165; renderer/lib/hosts/remote-chat-session.ts:178; renderer/lib/hosts/remote-chat-session.ts:187; renderer/lib/hosts/remote-chat-session.ts:245 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C09 clients C09 V Durable chat mutation intent ledger Unhydrated/hydrating/ready; pending intents → known/forgotten or unresolved → retrying/dismissed; secondary unknown outcomes queue behind the first. Persist before mutation; same request/key plus pairing ownership and retry window required for retry. Fork uncertainty has its own slot. renderer/lib/hosts/chat-intent-ledger.ts:81; renderer/lib/hosts/chat-intent-ledger.ts:140; renderer/lib/hosts/chat-intent-ledger.ts:155; renderer/lib/hosts/chat-intent-ledger.ts:172 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C10 clients C10 S Remote chat mutation controls Busy intent set, unresolved mutation, elsewhere notice, hydrated availability, attached lifetime. Send/cancel/approval/question/run-input/rename/remove → receipt/refusal/unknown. Guards combine adapter capability, host availability, ledger readiness and uncertainty; uncertain mutation must not silently mint a new key. renderer/lib/hosts/chat-session-control.ts:52; renderer/lib/hosts/chat-session-control.ts:160; renderer/lib/hosts/chat-session-control.ts:524 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C11 clients C11 V Remote queued-turn fence No fence → pending receipt (runId=null) → accepted run fence → released by same-run terminal/feed state or 120s stall. Refused send restores previous fence by object identity. A generic idle row is not evidence that the accepted run ended. renderer/lib/hosts/remote-queue-fence.ts:12; renderer/lib/hosts/remote-queue-fence.ts:39; renderer/lib/hosts/remote-queue-fence.ts:63; renderer/main/remote-chat-view.tsx:445 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C12 clients C12 S Remote first-chat transaction Per-host selected target/draft/create intent/send intent; create and first turn can independently have unknown outcomes. Folder/workspace selection, create/send/retry/dismiss, host switch; host-keyed memory and ledger preserve recovery through navigation. renderer/lib/hosts/remote-new-chat.ts:133; renderer/lib/hosts/remote-new-chat.ts:201; renderer/main/remote-new-chat-view.tsx:61 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C13 clients C13 S Peer-host transport/sidebar follower Connecting/available/unavailable host generation × feed snapshot/deltas/buffering/resync × disposed observers. Capability checks and generation/sequence fences; frame-coalesced feed updates must retain changes during initial read/subscription. renderer/lib/hosts/remote-host-adapter.ts:252; renderer/lib/hosts/remote-host-adapter.ts:763; renderer/lib/hosts/peer-host-feed-state.ts:133; renderer/lib/hosts/use-peer-host-sidebar.ts:115 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C14 clients C14 V Local Bot live subscription sharing No consumers → one shared subscription → fresh/stale/failed view → retry/resubscribe → microtask release. Remembered snapshot is display-only until authoritative snapshot; epoch/seq gap triggers resubscribe; ref-counted lifecycle prevents multiple components replacing each other's main subscription. renderer/lib/use-bot-live.ts:76; renderer/lib/use-bot-live.ts:92; renderer/lib/use-bot-live.ts:140; renderer/lib/use-bot-live.ts:157; renderer/shared/bot-live.ts:363 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C15 clients C15 V Paired-host Bot live follower started/stopped × subscribing/subscribed × read in-flight × buffered deltas × resyncPending × gone/failed. Snapshot supersedes pending read by reading counter; gaps/epoch changes refetch; resync during read coalesces another read. renderer/lib/hosts/remote-bot-session-follower.ts:31; renderer/lib/hosts/remote-bot-session-follower.ts:58; renderer/lib/hosts/remote-bot-session-follower.ts:109; renderer/lib/hosts/remote-bot-session-follower.ts:149 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C16 clients C16 S Local and paired Bot sends/echo recovery Pending send/morph/echo, unsettled same-key send, hidden interrupted/failed turn, retry request maps, operation counters, retained answered prompts/handoffs. Receipt, live echo, timer, retry/remove/navigation reconcile them; identical-looking send text is not sufficient identity. renderer/main/bots/bot-chat-pane.tsx:959; renderer/main/bots/bot-chat-pane.tsx:970; renderer/main/bots/bot-chat-pane.tsx:975; renderer/main/bots/bot-chat-pane.tsx:1224; renderer/main/remote-bot-chat-view.tsx:96; renderer/main/remote-bot-chat-view.tsx:133; renderer/main/remote-bot-chat-view.tsx:138 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C17 clients C17 S Workspace composer transaction Draft × text/attachment revisions × IME composing × attaching/sending × permission confirmation × slash action/session command/compaction busy. Refs synchronously claim work; callbacks compare revisions before removing submitted input. Manual compaction keeps draft editable while queue owns delivery hold. renderer/components/composer.tsx:469; renderer/components/composer.tsx:590; renderer/components/composer.tsx:601; renderer/components/composer.tsx:625; renderer/components/composer.tsx:1897 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C18 clients C18 S Draft submission/recovery mailbox Persisted draft/submitted backup, staged text, memory-only attachments, guidance/unsent return mailboxes. Mark submission before clearing, accept settles, refusal/late guidance merges back, subscriber handoff consumes pending data. Separate from rendered textarea. renderer/lib/composer-draft-store.ts:34; renderer/lib/composer-draft-store.ts:43; renderer/lib/composer-draft-store.ts:51; renderer/lib/composer-draft-store.ts:119; renderer/lib/composer-draft-store.ts:140; renderer/lib/composer-draft-store.ts:198 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C19 clients C19 S Attachment admission and new-worktree send Attachment operation generation/busy; worktree settled/released/answered flags; draft not-created/created/moved-to-chat with cancellation ownership. One current operation may append attachments or transfer draft; releasing UI cannot assume host work was cancelled. renderer/lib/composer-attachment-operation.ts:8; renderer/lib/draft-worktree-send.ts:169; renderer/lib/no-workspace-send.ts:59; renderer/lib/chat-draft.ts:306 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C20 clients C20 S Prompt response/expiry/late answer Pending → responding → answered/denied/withdrawn/expired; late-answer saved/sending; deciding refs fence duplicate actions. Stream/prompt/wait ID determines ownership; timer expiry and server settlement race. Per-wait recovery-owner maps at renderer/main/chat-pane.tsx:3421 add retry lifetime. renderer/main/chat-pane.tsx:797; renderer/main/chat-pane.tsx:807; renderer/main/chat-pane.tsx:2543; renderer/main/chat-pane.tsx:3402; renderer/components/ask-user-question-composer.tsx:14; renderer/components/computer-use-access-approval.tsx:37; renderer/main/chat-pane.tsx:3421 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C21 clients C21 S Failure/restart/interrupt recovery Failed/interrupted → retry/resume/dismiss pending → recovered/failed; owner-token records prevent one stale result clearing a newer action. Actual generation and displayed failure card may outlive one another. renderer/main/chat-pane.tsx:3311; renderer/main/chat-pane.tsx:3373; renderer/main/remote-chat-view.tsx:528; renderer/main/bots/bot-chat-pane.tsx:965 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C22 clients C22 S Fork and summary workflow Fork configuration → creating → navigation; summary pending/ready/failed/cancelled/continue-without-summary. Same intent key for uncertain fork; summary-held queue blocks next message until disposition. renderer/main/chat-pane.tsx:1339; renderer/main/remote-chat-view.tsx:591; renderer/components/fork-message-button.tsx:32; renderer/components/fork-summary-card.tsx:25 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C23 clients C23 S Inbox read/triage optimistic overlays Unread/read-through marker, triage/snooze/archive overlay, pending reads, undo batch, stale sidebar cache. Read result merges by owner/revision; undo must reverse only its batch, not newer server activity. renderer/lib/use-inbox-triage.ts:181; renderer/lib/use-mark-chat-read.ts:39; renderer/lib/use-chat-activity.ts:38; renderer/lib/use-sidebar-view.ts:20 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C24 clients C24 S Context-pressure/deadline feed Scoped chat live/history/draft reads × debounce and request generations; expiry handled/returned maps; paused-until deadline wait. Navigation invalidates old responses; return/expiry actions dedupe by identity. renderer/lib/context-pressure-feed.ts:34; renderer/lib/use-expired-cache-return.ts:23; renderer/lib/expired-cache-return.ts:83; renderer/lib/use-usage-limit-wait.ts:25 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C25 clients C25 V Shared monotonic subagent and todo fences Subagent queued→starting→active→terminal; revisions enrich only matching immutable identity, no terminal resurrection or timestamp/counter rollback. Todo read fence tracks active chat+revision against delayed snapshot. These are explicit guard helpers used by distributed owners. renderer/shared/subagent-runs.ts:816; renderer/shared/subagent-runs.ts:832; renderer/shared/todo.ts:31 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C26 clients C26 S Subagent selection/detail/stop/announcement Selected run/detail-request version, loading/error, pending stop, live/detail speech debounce, per-batch collapse latch and visit generation. Selection/navigation/revision updates cannot announce or act on old owner; accessibility timing has its own pending state. renderer/components/environment-panel.tsx:370; renderer/components/environment-panel.tsx:399; renderer/lib/subagent-panel-state.ts:288; renderer/components/subagent-composer-pill.tsx:120 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C27 clients C27 S Composer dictation controller Permission/setup/start → recording/live preview → stop-tail/transcribing → done/error/cancelled, plus explicit recorded-retry consent and pending-stop-during-start. generation gate prevents late setup/transcription writes; composer and floating pill are distinct orchestration owners. renderer/lib/use-voice-recorder.ts:44; renderer/lib/use-voice-recorder.ts:59; renderer/pill/pill-app.tsx:87 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C28 clients C28 V Dictation admission/deadline/VAD Gate idle/starting/current/cancelled generations; deadline active/expired; silence detector unheard/heard/hangover/fired; retry consent absent/waiting/approved/denied. Cancellation invalidates operation; timer terminal only once; consent is a separate authority. renderer/lib/dictation-operation-gate.ts:6; renderer/lib/dictation-operation-gate.ts:66; renderer/lib/dictation-vad.ts:17; renderer/lib/gemini-recorded-retry.ts:8 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C29 clients C29 V PCM recording, ordered send, live finish PCM carry/partial-chunk buffers; queue pending/in-flight/backpressured; audioStopped/settled/finishPromise/failure; recorder accumulating→flush-wait→finished. Stop waits bounded worklet flush; one finalization promise; queue cannot reorder audio. renderer/lib/live-pcm-capture.ts:14; renderer/lib/live-pcm-capture.ts:134; renderer/lib/pcm-recorder.ts:33 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C30 clients C30 V Local speech preview Start pending with buffered chunks → session ready → batched send → ended, with sending flag. Overflow/error disables preview, late-start success is stopped if already ended; final transcription stays independent. renderer/lib/local-live-preview.ts:16 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C31 clients C31 V Slow-model notice Hidden idle → loading grace timer → shown → disposed; ready/failed cancels timer, unrelated unloaded event does not reset active load. Hook maps state by model identity. renderer/lib/slow-model-load.ts:14; renderer/lib/use-slow-model-load.ts:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C32 clients C32 S Live assistant session Availability/setup/start/session/reconnect-required/stop; operation/media/availability generations; microphone permission/enabled/active; screen chooser/binding/pump; computer-use enabled/acting/busy. Late permission/media resolution must release resources without reviving cancelled session. renderer/components/assistant/use-assistant-live.ts:481; renderer/components/assistant/use-assistant-live.ts:518; renderer/components/assistant/use-assistant-live.ts:1145; renderer/components/assistant/use-assistant-live.ts:1244; renderer/components/assistant/use-assistant-live.ts:1305 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C33 clients C33 S Live assistant approvals and output media Pending/answered voice approvals and receipt retention; caption IDs; audible-session/received-audio ownership; screen share start/active/stopped; PCM player active and packet buffers. Session identity must fence audio and approval result callbacks. renderer/components/assistant/use-assistant-live-approvals.ts:14; renderer/components/assistant/use-assistant-live.ts:507; renderer/components/assistant/use-assistant-live.ts:948; renderer/components/assistant/use-assistant-live.ts:996; renderer/lib/gemini-live-media-core.ts:93 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C34 clients C34 S Read Aloud controller and player Job source/pending/current × generating/playing/paused/finished/error × scheduled segments and pumping/finished epochs. Start supersedes previous, pause/resume affects context, stop disposes sources; old fetch/decode/end callback cannot advance new playback. renderer/lib/tts-client.ts:42; renderer/lib/tts-client.ts:314; renderer/lib/tts-client.ts:321; renderer/lib/tts-client.ts:340; renderer/lib/tts-client.ts:360; renderer/lib/tts-player.ts:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C35 clients C35 S Device grant/view lifecycle idle/grant acquisition/connecting/streaming/error × inputConnected × renewal attempts × pressed keys. Selection/visibility/retry/grant-expiry/unmount start or stop client; release held keys and reject stale grant responses. renderer/lib/use-device-stream.ts:61; renderer/lib/use-device-stream.ts:85 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C36 clients C36 S Device video transport/decoder/fallback Stopped/connecting/streaming/error × waiting keyframe/configuring/first frame × AVC/WebSocket versus MJPEG × separate input socket renewal. First-frame/stall/prime timers, decoder failure, socket close, grant renewal, explicit stop; drop non-keyframe data after reset and avoid old sockets controlling replacement client. renderer/lib/device-stream.ts:530; renderer/lib/device-stream.ts:558; renderer/lib/device-stream.ts:621; renderer/lib/device-stream.ts:748; renderer/lib/device-stream.ts:812; renderer/lib/device-stream.ts:1063; renderer/lib/device-stream.ts:1160 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C37 clients C37 S Device input gesture transactions Pointer/touch down/move/up/cancel; wheel gesture open/idle timeout; Duo command pending/receipt/timeout; controls visible×busy; mini-player drag/click distinction. Always finish contacts/keys on cancellation; command acknowledgments match request IDs. renderer/lib/device-multitouch.ts:126; renderer/lib/device-duo-control.ts:83; renderer/lib/device-controls.ts:43; renderer/components/device-mini-player.tsx:107 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C38 clients C38 V Fold posture read/write controller Watching/paused/disposed × reading/writing/pending/retry timer × optimistic angle/reported fold. Writes suspend reads; result or timeout restores/reconciles angle; identity/abort guards ignore stale read. renderer/lib/device-fold.ts:137 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C39 clients C39 S Device tools/record/erase/clipboard/install Idle/confirmation/pending/success/error, recording starting/recording/stopping/artifact receipt, clipboard bounded retry. Device identity and disposal matter; side-effect controls are distinct from passive device status DTOs. renderer/components/device-record-control.tsx:19; renderer/components/device-erase-control.tsx:26; renderer/components/device-clipboard-controls.tsx:20; renderer/lib/device-clipboard.ts:52; renderer/components/device-tools-panel.tsx:357 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C40 clients C40 S 3D device viewer resource/gesture lifecycle Model loading/ready/disposed; frame loop active/inactive; pointer drag/rotation/fold targets and animation progress; texture/frame ownership. Cleanup must stop frames/listeners/materials and stale async model loads. renderer/lib/device-3d/viewer-runtime.ts:50; renderer/lib/device-3d/duo-viewer.ts:61; renderer/lib/device-3d/trackpad.ts:29; renderer/lib/device-3d/interaction.ts:10 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C41 clients C41 S Browser panel/navigation/annotation Browser/tab selection and loading/error/controls; annotation draft/edit/preview/delivery/cancel; serialized preview tail + revision, debounce timer. Latest edit owns preview; old queued work must not repaint cancelled editor. renderer/components/browser-panel.tsx:26; renderer/lib/browser-ui-state.ts:9; renderer/components/browser-annotation-editor.tsx:10; renderer/lib/browser-annotation-preview-queue.ts:3 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C42 clients C42 S Floating/docked environment and Bot workbench Active tab, visited surfaces, float/dock/quick-view layout, mounted/present/exiting, pending focus/return focus, drag preview. Explicit environment reducer is surrounded by effects/timers; hidden and unmounted are intentionally different states. renderer/components/environment-panel.tsx:321; renderer/components/environment-panel.tsx:1308; renderer/components/environment-panel.tsx:1640; renderer/components/environment-panel.tsx:1686; renderer/main/bots/bot-workbench.tsx:81; renderer/main/bots/bot-panel-context.tsx:106 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C43 clients C43 S Ghostty terminal lifecycle and input Runtime loading/shared reference ownership; terminal created/attached/detached/exited/disposed; resize/frame scheduling; IME/key/mouse/selection/paste state; workspace session collection and split layout. UI hide does not necessarily end PTY. renderer/lib/ghostty-terminal/surface.ts:63; renderer/lib/ghostty-terminal/runtime.ts:3; renderer/lib/ghostty-terminal/core.ts:157; renderer/components/terminal-drawer.tsx:143 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C44 clients C44 V Image workflow editor + autosave Explicit undo/redo session reducer; implicit dirty/saving/conflict/deleted/error × pending document/in-flight promise/timer/disposed. Debounce/flush/save receipt/error; serialize saves, retain failed latest edit, conflict/deletion block further writes. renderer/images/workflow-session-core.ts:91; renderer/images/workflow-session-core.ts:110; renderer/images/workflow-session-core.ts:154 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C45 clients C45 S Workflow loading/run consent loading/ready/error; asset/model resolution request sequences; prepare plan→consent→busy run snapshot→settled; selected/stale nodes and reload confirmation. Save revision must precede execution; stale preparation cannot authorize changed graph. renderer/images/use-workflow-controller.ts:35; renderer/images/use-image-run.ts:14; renderer/images/workflow-editor.tsx:49 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C46 clients C46 S Image gallery/viewer actions Loading/pagination/error/request sequence × filter/focus/selected image × zoom/pan/fullscreen/action pending. Navigation restores originating focus; revoke temporary URLs and ignore outdated pages. renderer/images/use-gallery.ts:21; renderer/images/image-library.tsx:45; renderer/images/viewer/image-viewer.tsx:44; renderer/images/viewer/use-image-actions.ts:10 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C47 clients C47 S Visual document / HTML iframe handshake loading/mounted/themed/ready/error; document identity, last prompt, announced height; native visual local state/events. Origin/document ownership validates bridge events; reload invalidates old readiness. renderer/visual-viewer/main.tsx:109; renderer/components/html-artifact-frame.tsx:44; renderer/components/aiden-ui/aiden-ui-block.tsx:29 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C48 clients C48 S Interactive generated UI local state Visual initial/current state, selection/input event updates, expression evaluation budget, render fallback. User events update local visual state, not host conversation authority; expression traversal is a bounded synchronous evaluator rather than a long-lived job. renderer/components/aiden-ui/aiden-ui-block.tsx:29; renderer/components/aiden-ui/chart.tsx:17; renderer/shared/aiden-ui/expression.ts:20 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C49 clients C49 S Onboarding progression State loading/error/ready × current step × provider skipped/saving/discovering/ready × Bots step/completion. Next/back/provider-auth/save/feature-capability changes; saving ref plus load generation fence transitions; completion must persist before closing. renderer/components/onboarding-flow.tsx:169; renderer/components/onboarding-flow.tsx:274; renderer/components/onboarding-flow.tsx:291; renderer/components/onboarding-flow.tsx:403; renderer/lib/onboarding-state.ts:9 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C50 clients C50 S Provider/Codex auth sessions Created/started/cancelRequested/disposed and backend auth phase; subscription precedes start, flow ID filters callbacks, terminal updates refresh credentials even if view detached, cancel may be refused as finishing. Both are distinct wrappers sharing a lifecycle shape. renderer/lib/provider-auth-session.ts:57; renderer/lib/provider-auth-session.ts:118; renderer/lib/provider-auth-session.ts:141; renderer/lib/codex-auth-session.ts:87; renderer/lib/codex-auth-session.ts:156; renderer/lib/codex-auth-session.ts:179 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C51 clients C51 S Provider setup/edit/discovery/key sharing Draft/validate/save/discover/auth/error plus confirmation and model visibility. Explicit foreground action authorizes fetching; view selection/request identity fences stale response. renderer/components/settings/providers-settings.tsx:57; renderer/components/settings/provider-editor.tsx:41; renderer/components/settings/builtin-provider-editor.tsx:28; renderer/components/settings/codex-provider-settings.tsx:32; renderer/components/settings/provider-connector-key-sharing.tsx:12; renderer/components/settings/provider-model-visibility.tsx:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C52 clients C52 S MCP/connectors/runtime installation Configure/connect/auth/install/check/retry/remove and disclosure substeps. Existing status unions render backend state; local pending state gates actions and must not cause startup installs/downloads. renderer/components/settings/mcp-settings.tsx:78; renderer/components/settings/mcp-preset-setup.tsx:32; renderer/components/settings/mcp-mac-app-setup.tsx:24; renderer/components/settings/harness-runtime-section.tsx:23; renderer/components/settings/connections-settings.tsx:15; renderer/lib/mcp-preset-state.ts:3 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C53 clients C53 S Remote pairing/access/device add Method entry→request/QR/manual waiting→approved/denied/expired/cancelled/finishing; enable/access mode and per-request pending decisions. Countdown/refresh/cancel/late approval and unmount must preserve exact pairing ownership. renderer/components/settings/remote-access-settings.tsx:74; renderer/components/settings/peer-add-device-sheet.tsx:51; renderer/components/settings/peer-hosts-settings.tsx:32; renderer/components/remote-pairing-request-sheet.tsx:11; renderer/lib/remote-pairing-lifecycle.ts:15 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C54 clients C54 S Voice/model download settings Not downloaded/downloading/ready/error/current selection, explicit download/cancel/delete/load; settings draft/saving/testing audio. Polling observes status rather than authorizing network work. renderer/components/settings/local-voice-settings.tsx:36; renderer/components/settings/model-manager-view.tsx:16; renderer/components/settings/voice-settings.tsx:57; renderer/components/settings/tts-settings.tsx:51; renderer/components/settings/live-audio-settings.tsx:7; renderer/components/settings/gemini-live-settings.tsx:22 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C55 clients C55 S Manual model/benchmark/image catalogs Key draft/connect/fetch in-flight/ready/stale/error/disconnect; selected provider/model IDs and per-provider requests. Explicit fetch required; display cache cannot become runtime authorization or model inventory authority. renderer/components/settings/model-pad/model-pad-settings.tsx:75; renderer/components/settings/model-pad/model-pad-data-rows.tsx:42; renderer/components/settings/image-generation-settings.tsx:61 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C56 clients C56 S Bot creation/profile/access/instructions Create steps/model/provider connection/busy/error; edit draft/baseline/save/discard; photo upload; Full/Custom access draft. Save rollback belongs to captured entity/revision; creating Bot and initial message are separate operations. renderer/main/bots/bot-create-flow.tsx:195; renderer/main/bots/bot-profile.tsx:67; renderer/main/bots/bot-advanced.tsx:501; renderer/main/bots/bot-instructions-editor.tsx:25 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C57 clients C57 S Bot pause/delete/computer setup Idle/confirmation/action pending/error; host pause/unpause and VM setup/start/stop phase projections. UI does not own host lifecycle; host receipt, not optimistic label, proves pause/setup. renderer/main/bots/bot-paused-card.tsx:48; renderer/main/bots/bot-delete-dialog.tsx:42; renderer/main/bots/bot-computer-section.tsx:23; renderer/components/settings/bot-computers-settings.tsx:36; renderer/components/settings/bot-computer-base-screen.tsx:22 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C58 clients C58 S Bot memory/rules/lessons/skills/issue cards Edit/save/error, pending-removal map+hidden IDs+undo window, proposal pending/accepted/dismissed, issue action pending/settled. Capture entry identity/revision; undo timer and navigation can outlive initiating row. renderer/main/bots/bot-memory-page.tsx:286; renderer/main/bots/use-bot-rules.ts:26; renderer/components/bots/lesson-cards.tsx:11; renderer/components/bots/skill-proposal-card.tsx:10; renderer/components/bots/bot-issue-card.tsx:35 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C59 clients C59 S Bot routines/events/proposals Edit session/new/existing, save/delete, link creation, proposal decide, Run now idle/pending/started/error. Editor-session identity separates reopened drafts; run state is per mount and host pause is authoritative. renderer/main/bots/bot-routines.tsx:37; renderer/main/bots/bot-routine-editor.tsx:124; renderer/main/bots/bot-event-routines.tsx:137; renderer/components/bots/routine-proposal-card.tsx:28; renderer/components/bots/routines-skipped-card.tsx:17 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C60 clients C60 S Bot activity wording/preferences/status speech Optimistic value + saved baseline + serialized queue/pending count; timed preview frames; announcement armed/debounce; starter pending selection. Serialize settings edits; delayed failure cannot roll back newer value. renderer/main/bots/bot-chat-activity-page.tsx:244; renderer/main/bots/bot-status-line.tsx:37; renderer/main/bots/bot-starter-carousel.tsx:30 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C61 clients C61 S Workspace file editor and artifact reader Index/document loading/ready/error × selected file × dirty/saving/conflict/reload prompt; request IDs and workspace identity. Results from old workspace or document cannot replace current editor. renderer/components/files-panel.tsx:70; renderer/lib/use-workspace-artifacts.ts:25; renderer/main/bots/bot-panel-files.tsx:45; renderer/components/artifacts-panel.tsx:67 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C62 clients C62 S Git commit/push/branch/clone workflows Preparing/validating/running/cancelling/success/error; confirmation and dirty/worktree gates; tool activity debounces refetch. UI cancellation versus process settlement and captured repository ownership are hotspots. renderer/components/git-commit-dialog.tsx:18; renderer/components/git-push-dialog.tsx:35; renderer/components/git-branch-picker.tsx:58; renderer/main/peer-project-clone-dialog.tsx:22; renderer/lib/git-query-sync.ts:51 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C63 clients C63 S Scheduled task editor/list and ancillary settings mutations Edit/validate/save/delete/run/cancel/refresh and pending row IDs; diagnostics collect/export; Telegram link/poll/disconnect; keys validate/remove; memory edit/undo. Independent per-owner mutations, with busy/error states and late-response ownership. renderer/components/scheduled-task-editor.tsx:47; renderer/components/scheduled-tasks-view.tsx:104; renderer/components/settings/scheduled-tasks-settings.tsx:31; renderer/components/settings/diagnostics-settings.tsx:12; renderer/components/settings/telegram-settings.tsx:44; renderer/components/settings/web-search-key-pool.tsx:20; renderer/components/settings/memory-facts-section.tsx:24 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C64 clients C64 S Link routing consent / command routing Preferences unknown/loading→ready, queued links, pending consent/menu, surfaces/blockers; command handler stack+palette mode/open/query/selection. Resolve prefs before routing; owner unregister removes handlers; Escape/choice drains the right pending action. renderer/lib/link-opener.tsx:129; renderer/lib/command-system.tsx:76; renderer/components/command-palette.tsx:120 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C65 clients C65 S Transcript follow/reveal/microinteraction families Follow locked/unlocked/near bottom, paced reveal backlog/draining/reset, explicit reasoning-disclosure reducer, present/exiting/unmounted, idle/copied/error with reset timer, pointer hold→menu versus click. Generation/version guards and reduced-motion routes matter; visual state is still temporal behavior. renderer/components/message-list.tsx:209; renderer/components/streaming-markdown-reveal.tsx:25; renderer/components/reasoning-block.tsx:37; renderer/components/event-presence.tsx:14; renderer/components/copy-button.tsx:22; renderer/components/busy-send-button.tsx:48; renderer/lib/use-collapsible-body.ts:9 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C66 clients C66 S Cross-cutting selection/focus/resize and resource feeds Selected workspace and hidden-ID reconciliation; debounced intake; shared subscribed/released poller/clock; photo pending/active/cached/evicted with epochs and budget; log subscription ended. Reference ownership and generation fences distinguish them from passive preferences. renderer/lib/workspace-context.tsx:30; renderer/lib/use-workspace-path-intake.ts:34; renderer/lib/use-device-service-state.ts:35; renderer/lib/second-clock.ts:11; renderer/lib/bot-canonical-photo-cache.ts:45; renderer/lib/device-event-log.ts:219 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N01 clients N01 S Connection/activation ownership needsPairing/connecting/connected/offline × mutation busy × connection generation × activation generation. Start/pair/switch/reconnect/remove/revocation; request context binds installation+device+activation so A→B→A cannot revive old A work. Credential/client cache and data purge have distinct ownership. iOS transition bodies read; Android coordinator state and event sites inspected. ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:113; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:191; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:365; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:391; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:760; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:1097; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenRemoteCoordinator.kt:317 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N02 clients N02 S Pairing and nearby discovery QR camera permission/scanning/recognized; manual endpoint/code/check/exchange; discovery browsing/resolving/stopped; cancellation/failure/success. Pair/exchange claim must prevent duplicate scans, issued credential must be cleaned up on failed activation. ios/AidenOnTheGo/Features/Remote/AidenPairingView.swift:113; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenPairingScreen.kt:98; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenNearbyDesktops.kt:11; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenQRCodeScanner.kt:73 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N03 clients N03 S Native shell/navigation/deep-link lifecycle Selected installation/product area/root/detail stack × loading route/queued navigation/transition leaving key/back-in-progress. External navigation waits for correct pairing/target and capabilities; cancelled navigation may still return HTTP result. Adaptive one/two-pane transitions preserve identity. ios/AidenOnTheGo/ContentView.swift:4; ios/AidenOnTheGo/Features/Remote/AidenProductShellView.swift:26; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:1333; android/app/src/main/java/sbtbiswas/AidenOnTheGo/MainActivity.kt:53; android/app/src/main/java/sbtbiswas/AidenOnTheGo/navigation/AidenNavigationHost.kt:71; android/app/src/main/java/sbtbiswas/AidenOnTheGo/navigation/AidenNavigationHost.kt:413; android/app/src/main/java/sbtbiswas/AidenOnTheGo/navigation/AidenNavigationStack.kt:7; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenProductNavigationStore.kt:41 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N04 clients N04 V Foreground/resume gate Foreground/active/background plus needsRefresh latch. Background suspends observers and arms refresh, inactive bounce does not; active either resumes or refreshes. Explicit tiny reducer on iOS; view lifecycle drives several separate subscriptions. ios/AidenOnTheGo/Features/Remote/AidenSceneRefreshGate.swift:12; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2027; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2045; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2678; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:803; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:814; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:834 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N05 clients N05 S Workspace/home list loading and pagination Initial/cache/loading/ready/error and pagination idle/loading/failed/exhausted; request token/content context/local overlay generations. Detail/receipt/local triage edits cannot be overwritten by older list; later authoritative list can remove older omitted rows. ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:168; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:174; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:181; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:198; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:876; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:920; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceHomeViewModel.kt:41 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N06 clients N06 S Native workspace/chat metadata mutations Create/rename/remove in-flight, retained rename overlay, coherent revision refresh required for next mutation, managed-worktree delete uncertain key. Mutation receipt and next GET are independent; never replay with arbitrary fresh key when outcome is unknown. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:987; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:998; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1076; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:481; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:558; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:613; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceHomeViewModel.kt:41; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenRemoteCoordinator.kt:38 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N07 clients N07 S Native chat cache response admission Request-reserved write clock, admitted detail/list/summaries, receipt overlays, deletion lifetime/tombstone, purge generation, active-stream record. Read/save/remove/purge events; reserve before HTTP/IO, reject stale completion and stale disk fallback, preserve newer receipt/detail ownership. Disk success is not the only current presentation authority. ios/AidenOnTheGo/Persistence/AidenChatCache.swift:4; ios/AidenOnTheGo/Persistence/AidenChatCache.swift:214; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenChatCache.kt:95 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N08 clients N08 V Draft session / durable pending send Session generation current/invalidated, pending debounce/written sequence, stored text plus unresolved send attempt. Begin session/save/consume/failure restore/remove/purge; purge invalidates writers before deleting so delayed failed-send restoration cannot resurrect removed data. ios/AidenOnTheGo/Persistence/AidenChatDraftStore.swift:6; ios/AidenOnTheGo/Persistence/AidenChatDraftStore.swift:163; ios/AidenOnTheGo/Persistence/AidenChatDraftStore.swift:188; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenChatDraftStore.kt:133; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenDebouncedDraftWriter.kt:23 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N09 clients N09 S Native send/start/rate-limit recovery Idle/starting/pending-send unknown/refused-busy/rate-limit waiting/active stream × optimistic message/draft. Durable request+key freezes before network; accepted receipt advances, definite rejection restores draft, ambiguous response keeps key. Rate-limit retry timer must stay within captured ownership and not retry a fresh mutation indiscriminately. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1335; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1369; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1393; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3110; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:240; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:248; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1553; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1606; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenChat.kt:2156 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N10 clients N10 S Native owned run reconnect/replay Stored active stream + last sequence → restoring/streaming/network-wait/reconnecting/terminal reconciliation; retry count/network availability independent of stream status. Restore stream before foreign-run attach; TCP/SSE loss does not create another turn. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1273; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1325; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4522; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4582; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4599; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4719; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:274; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1540; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2014; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenNetworkAvailability.kt:88; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenNetworkAvailability.kt:110 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N11 clients N11 S Native terminal output/persistence handoff Live output→ended-but-unsettled→transcript accepted→live cleared. Terminal reconciliation task, ended reply, transcript generation and identity checks; publish saved transcript and clear live in same UI turn to avoid duplicate/gap. Pending reveal backlog has its own drain policy. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1517; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1871; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5123; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5193; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5414; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:300; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3440; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3498; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3723; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3754 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N12 clients N12 S Foreign-run discovery / attach / settle Absent/lookup/live/ended-before-attach/reconciling/accounted × local start/restore × pending roster signal × foreground probe/backoff. New roster turn triggers attach, own run skipped, announced missing run gets bounded retry, probes only without roster capability; coalesced signal must survive lookup already in flight. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1293; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10842; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10865; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10912; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10997; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2770; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2816; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2848; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2878; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3071 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N13 clients N13 S Task/agent progress observer idle/connecting/live/reconnecting/denied × task epoch/revision × agent epoch/revision × selected historical roster request. Snapshot/deltas/403/foreground/background; denied access clears only relevant state, monotonic versions reject stale frames, historical selection cannot overwrite current roster. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2678; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2767; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2876; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2909; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2988; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:233; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:848; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1091; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1100 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N14 clients N14 S Native approval and question recovery None/pending/responding/withdrawn/terminal; snapshot generation/in-flight owner; same-key response attempts. Delayed snapshot must not resurrect answered or superseded prompt; server expiry and user response race. Answer authority differs for owned and foreign runs. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1546; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4350; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4433; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4931; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5007; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:133; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:153; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2226; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2276; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenApprovalActions.kt:37 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N15 clients N15 S Native run-input guidance and Stop Run input mode/last attempt/in-flight/receipt; draft consumed/restored; Stop pending/terminal. One cancellation per stream/intent; unknown input response retains key; same draft baseline/remainder decides restoration without destroying new typing. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3891; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3905; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3967; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4323; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4340; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:138; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:148; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2353; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2373; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2747 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N16 clients N16 S Native worktree-on-first-send and fork Setup task/not started/cancelled/created; retained worktree request; fork pending/uncertain/navigated, summary pending/failed/ready/skipped. Setup cancellation and send receipt may race; fork copy preserves attachment/intent identity; summary gates sending. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1473; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1936; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2354; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2473; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2544; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:200; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:474; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:500; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:631 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N17 clients N17 S Native attachment preparation/upload/cleanup Preparing batch→uploading(progress)→staged→consumed/deleted; cancellation/deferred access revocation/owned cleanup tasks. Capacity and generation guards; cancelled upload can still return a reference needing cleanup, removal/revocation prevents reattachment. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1447; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3411; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3525; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3637; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3654; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:159; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:175; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1858 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N18 clients N18 S Native message history/title/visual refresh Initial/settled window/loading older/exhausted; title and visual refresh pending/backoff/done. Transcript generation and request context preserve live/optimistic entries when older pages or delayed title arrive. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1464; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5232; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5293; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5373; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:211; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:305; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:309; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3528; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3631 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N19 clients N19 S Native composer catalogs and model selection Default/explicit choice; suggestion catalog not-loaded/loading/loaded/retry-pending per skills/agents/files; active token/menu/focus. Explicit model choice survives refresh; capabilities gate reads, new query/owner invalidates suggestions. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1252; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3037; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4119; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4205; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:333; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2544; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2660; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/shared/AidenModelPicker.kt:108 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N20 clients N20 S Native transcript follow/reveal Following/dragging/away/jump-settling, generation-fenced queued scroll and bottom arrival; reveal buffered/held-word-fragment/draining/final. User drag revokes auto-follow; bottom latch re-arms only at threshold; rewrite resets reveal, tool/terminal boundaries flush according to owner policy. iOS pacing differs from Android. ios/AidenOnTheGo/Features/Chat/AidenChatScrollPolicy.swift:213; ios/AidenOnTheGo/Features/Chat/AidenChatScrollObserver.swift:48; ios/AidenOnTheGo/Features/Chat/AidenStreamingRevealGate.swift:24; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1779; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenTranscriptFollow.kt:46; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenStreamingRevealGate.kt:21; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenStreamingRichText.kt:36 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N21 clients N21 V Bot session feed sequence/reconnect Loaded/unloaded/stream-down/reopening/released; epoch+seq; snapshot replaces, duplicate ignored, gap/wrong epoch refetches, closed reconnects. Feed does not wait for outbox requests. Explicit event application coexists with implicit feed task lifetime/backoff. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1164; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1489; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1561; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:566; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:639; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:668 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N22 clients N22 V Bot durable outbox delivery sending/sent(submission)/failed/expired × request frozen/keepsKey/deferred/attempt count/echoed/claimed entry/queued/unheld/taken-before-visit/attachmentsGone. FIFO sends never overtake deferred head. Ambiguous failure preserves key and bounded retry; definite refusal permits new request; one transcript entry settles one message; expired uploads require reattach. iOS full delivery branches read; Android state and corresponding methods verified. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:449; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1751; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1896; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1912; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2030; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2547; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOutbox.kt:163; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:992; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1109; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1233; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1254; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1351 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N23 clients N23 V Bot outbox ownership/restore/purge/disk write Cache adopted owner, disk restoring/restored, coalesced writes, pairing known/revoked, stuck files, purge generation/released. Restore must finish before writes and must not reintroduce revoked data; one view owns shared outbox. Pending-create recovery has a separate disk slot. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:536; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:602; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:637; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:706; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:809; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1843; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2070; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:578; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:726; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1362; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOutbox.kt:183 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N24 clients N24 S Bot actions and per-field rollback Action in-flight set, retained key/payload per question/approval/handoff/issue/proposal, stop/resume intent none/requested/acknowledged. Rollback only if field-write counter unchanged; late failed action cannot erase newer authoritative SSE frame. Resume and unpause are different operations. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1247; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1254; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1291; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2095; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2134; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2278; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2625; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2666; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:584; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:588; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1384; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1465; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1501; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1596 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N25 clients N25 S Bot images/attachments/partial reveal Staged/uploading/cancelled/cleanup plus bounded shared image cache; revealedPartial trails partial on iOS, snapshot/rewrite/entry clears immediately. iOS attachment references and user text freeze together in its outbox request. Android source here exposes shared-image presentation but its send transport still takes text/mode, so iOS attachment delivery parity is not claimed. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1188; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1224; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1640; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2418; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2496; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2771; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:701; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionScreen.kt:240 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N26 clients N26 S Bot create/profile/access optimistic saves Create draft/pending/uncertain/recoverable; editing authoritative baseline/optimistic draft/saving/conflict/failed; pause/delete pending. Revision/context guards; current Bot detail is independent from list cache and uncertain creation key. ios/AidenOnTheGo/Features/Bots/AidenBotCreateView.swift:86; ios/AidenOnTheGo/Features/Bots/AidenBotProfileView.swift:28; ios/AidenOnTheGo/Features/Bots/AidenBotAdvancedView.swift:4; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotsViewModel.kt:26; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotEditorScreen.kt:48; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotProfileScreen.kt:74; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOptimisticSaves.kt:28 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N27 clients N27 S Generated/canonical avatar lifecycle idle/loading/normalizing/ready/uploading/reverting/failed × candidate bytes/generation/authoritative avatar revision. Picker→accept→normalize→explicit upload; cancellation, failed mutation/re-read, revert and stale canonical download compete. Candidate preview is not persisted canonical photo. ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:29; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:301; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:422; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:540; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:628; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:821; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:859; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt:51; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt:155; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotCanonicalAvatarView.kt:62 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N28 clients N28 S Bot memory/routines/chat-activity edits Load/edit/save/delete/undo/erase; per-entry pending; serialized optimistic wording changes with latest pending value. Bot/installation/revision identity guards async responses; don't collapse independent fields into global “saving.” ios/AidenOnTheGo/Features/Bots/AidenBotMemoryView.swift:5; ios/AidenOnTheGo/Features/Bots/AidenBotRoutinesView.swift:4; ios/AidenOnTheGo/Features/Bots/AidenBotAdvancedView.swift:4; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotMemoryController.kt:23; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutines.kt:45; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotChatActivityModel.kt:252; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotChatActivityScreen.kt:163 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N29 clients N29 V Native dictation/audio resource lifecycle idle/requestingPermission(or preparing)/listening/transcribing × native/Mac provider × audio tap/session active × accepts draft updates/session generation. Stop-keeping finalizes recognition, send/cancel invalidates session; late permission/recognition result cannot change new draft. iOS native finalization timeout is independent of Mac transcription task. ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:11; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:77; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:110; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:207; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:330; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:461; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/ComposerVoiceInputController.kt:49; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/ComposerVoiceInputController.kt:62; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/ComposerVoiceInputController.kt:89; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/ComposerVoiceInputController.kt:112 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N30 clients N30 S Native Read Aloud Idle/loading remote source/job/segments/playing/paused/stopped/error, generation/current-source/job revision. Fetch/poll/audio-ended/interruption/stop; stop invalidates pending work and cancels remote job as supported. Verify source revision before playing newly fetched segments. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10713; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10723; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10735; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenReadAloudPlayback.kt:26 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N31 clients N31 S Simulator list/view model idle/starting/connecting/streaming/open-on-Mac/shut-down/failed plus screen/input enabled, app foreground and selected device. User open/start/retry/leave and device state changes; old grant/boot result cannot revive dismissed viewer. ios/AidenOnTheGo/Features/Simulators/AidenSimulatorViewerModel.swift:208; ios/AidenOnTheGo/Features/Simulators/AidenSimulatorViewerModel.swift:368; ios/AidenOnTheGo/Features/Simulators/AidenSimulatorViewerModel.swift:409; ios/AidenOnTheGo/Features/Simulators/AidenSimulatorViewerModel.swift:482; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/simulators/AidenSimulatorsViewModel.kt:135; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/simulators/AidenSimulatorsViewModel.kt:344; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/simulators/AidenSimulatorsViewModel.kt:391; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/simulators/AidenSimulatorViewerState.kt:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N32 clients N32 S Native simulator frame/input transport Frame stream running/generation/first-frame/decode pending; latest-frame mailbox, input socket opening/open/renewable/retried/closed; stream/decode/retry jobs. Drop superseded frames, finite renewal, cancel all resources on stop. MJPEG parser is separate N41. ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:85; ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:169; ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:195; ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:277; ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:370; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:395; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:404; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:449; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:607 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N33 clients N33 S Native remote visuals/WebView loading/document/ready/failed/outdated; document ID/page-ready/pending prompt/link/retry; cache stamp/owner/generation. Bridge events only for current trusted document; external link prompt and chat prompt submission require separate user intent. ios/AidenOnTheGo/Features/Remote/AidenVisualViewer.swift:25; ios/AidenOnTheGo/Features/Remote/AidenVisualViewer.swift:310; ios/AidenOnTheGo/Features/Remote/AidenVisualDocument.swift:8; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenVisualViewerModel.kt:17; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenVisualViewerScreen.kt:93; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenVisualDocumentCache.kt:39 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N34 clients N34 S Native workspace environment/files/git/providers Read/loading/cache/error × selected tab/file/folder/page × mutation pending/confirmation. Opaque capabilities and request contexts scope folder/file navigation; stale selection response cannot replace current owner. ios/AidenOnTheGo/Features/Remote/AidenWorkspaceEnvironmentView.swift:134; ios/AidenOnTheGo/Features/Remote/AidenProvidersView.swift:5; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:4834; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:4920; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceEnvironmentScreen.kt:65; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenGitScreen.kt:55; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenProviderSettings.kt:55 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N35 clients N35 S Native schedules, usage, spending, jobs Loading/cached/live/error; schedule edit/run/cancel/delete; per-job stopping IDs; temporary spend override pending/expired. Explicit action invokes mutation, status poll only observes; scoped owner invalidates late results. ios/AidenOnTheGo/Features/Remote/AidenScheduledTasksView.swift:107; ios/AidenOnTheGo/Features/Remote/AidenSpendingNotice.swift:6; ios/AidenOnTheGo/Features/Remote/AidenBackgroundJobs.swift:7; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/scheduled/AidenScheduledTasksScreen.kt:69; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenSpending.kt:98; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenBackgroundJobs.kt:134; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenUsageSheet.kt:59 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N36 clients N36 S Native app-control panel receipts/cache Snapshot loading/current, confirmation, pending operation, applied/already-set/outcome-unknown retry. Snapshot generation/read serial rejects stale reads; retry operation preserves expected revision and semantic action. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4069; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4080; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:11505; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenAppControls.kt:49; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/NativeAppControlPanel.kt:29 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N37 clients N37 S Live Activities / notifications / alert throttling No activity/active/update-throttled/ended with latest pending value; alert seen/deduped/throttled per run; foreground/quiet suppression. Terminal update must not be overwritten by queued older active update; task cancellation flush/drop semantics matter. ios/AidenOnTheGo/LiveActivities/AidenRemoteLiveActivityManager.swift:7; ios/AidenOnTheGo/LiveActivities/AidenLatestValueThrottle.swift:11; ios/AidenOnTheGo/Features/Remote/AidenScheduledRunNotifier.swift:9; android/app/src/main/java/sbtbiswas/AidenOnTheGo/notifications/AidenRemoteLiveNotificationManager.kt:19; android/app/src/main/java/sbtbiswas/AidenOnTheGo/notifications/AidenNotificationThrottle.kt:16 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N38 clients N38 V Android external-new-chat consent pending target→approved target→active consumed target; new link/reject/accept/consume/reset. Approval is target-scoped, not a global bypass; duplicate external intent and app recreation must not auto-create chat. android/app/src/main/java/sbtbiswas/AidenOnTheGo/notifications/AidenNewChatLinkConsent.kt:23; android/app/src/main/java/sbtbiswas/AidenOnTheGo/MainActivity.kt:53 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N39 clients N39 S Native gesture/sheet/focus microinteraction families Picker expanded/camera/photo/file import/permission denied; photo load/failure/retry/save/share; deck drag axis/selection; context-menu open and focus return; tool/activity expansion and delayed reveal. Transient state can retain resource work after visual dismissal; owner identity and accessibility reduced-motion routes must remain consistent. ios/AidenOnTheGo/Features/Chat/AidenAttachmentPicker.swift:6; ios/AidenOnTheGo/Features/Chat/AidenAttachmentCamera.swift:6; ios/AidenOnTheGo/Features/Chat/AidenTranscriptPolish.swift:7; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:7492; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:7755; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:7926; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenMessageImageAttachments.kt:198; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenMessageImageAttachments.kt:340; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenMessageImageAttachments.kt:611; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenComposerView.kt:69; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenMessageContextMenu.kt:26 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N40 clients N40 S Other native persistence/cache ownership Active scope and admitted snapshots, request/write stamps, retained/revoked installations, local archived-workspace acknowledgement, preference migrations. Store/remove/purge/scope-switch invalidate old reads; simple scalar preference values are not counted separately. ios/AidenOnTheGo/Persistence/AidenBotCache.swift:123; ios/AidenOnTheGo/Persistence/AidenModelPreferenceStore.swift:12; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenBotCache.kt:20; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenReadSnapshotCache.kt:35; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenSettingsCache.kt:62; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenWorkspaceArchiveStore.kt:21; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenInstallationStore.kt:30 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N41 clients N41 S ios/AidenOnTheGo/Networking/AidenSSEParser.swift:3, ios/AidenOnTheGo/Networking/AidenMJPEGMultipartParser.swift:8; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSSEParser.kt:108, android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRunEvents.kt:299, android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:53; renderer renderer/lib/device-stream.ts:349 SSE event ID/name/data/frame byte count across lines; MJPEG boundary/header/body/length across chunks; AVCC incomplete length/payload buffer. Data feed advances state; boundary/blank line emits frame; byte caps/invalid fields fail; reset/cancel drops partial frame. Android MJPEG explicit enum still has distributed incremental-buffer ownership. ios/AidenOnTheGo/Networking/AidenSSEParser.swift:3; ios/AidenOnTheGo/Networking/AidenMJPEGMultipartParser.swift:8; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSSEParser.kt:108; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRunEvents.kt:299; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:53; renderer/lib/device-stream.ts:349 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N42 clients N42 S ios/AidenOnTheGo/Models/AidenChat.swift:3808 foreign-run projection and ios/AidenOnTheGo/Features/Chat/AidenStreamingRevealGate.swift:104; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenForeignRun.kt:19, android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenForeignRun.kt:66; renderer renderer/lib/streaming-reveal.ts:411 Foreign-run event projection, cumulative text tail/byte counters, markdown sealed prefix/tail; snapshot versus append/rewrite changes interpretation. Explicit pure reducers/projections exist here and should not be mistaken for independent host execution engines. ios/AidenOnTheGo/Models/AidenChat.swift:3808; ios/AidenOnTheGo/Features/Chat/AidenStreamingRevealGate.swift:104; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenForeignRun.kt:19; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenForeignRun.kt:66; renderer/lib/streaming-reveal.ts:411 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N43 clients N43 S Renderer renderer/shared/workspace-artifacts.ts:319, renderer/shared/workspace-artifacts.ts:369, renderer/shared/subagent-safe-text.ts:264, renderer/shared/subagent-safe-text.ts:943, renderer/shared/aiden-ui/expression.ts:20; android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRawJsonDuplicateKeyScanner.kt:4; native Markdown splitter/cache files Synchronous scanner automata: shell quoting/redirect context, escape decoding/bounded text, expression token cursor/depth/budget, JSON offset/object-key count, code fence/block/tail recognition. These are genuine local parsing state but not async orchestration; no finding is implied by their use. renderer/shared/workspace-artifacts.ts:319; renderer/shared/workspace-artifacts.ts:369; renderer/shared/subagent-safe-text.ts:264; renderer/shared/subagent-safe-text.ts:943; renderer/shared/aiden-ui/expression.ts:20; android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRawJsonDuplicateKeyScanner.kt:4 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C67 clients C67 V Single-use annotation/image delivery registry Registered eligible composer(s) → captured recipient → delivered/rejected/invalidated. Annotation capture requires exactly one eligible receiver; receipt can succeed only once and only while exact receiver remains registered. Image registry follows mounted receiver ownership. renderer/lib/browser-annotation-delivery.ts:18; renderer/lib/composer-attach.ts:14 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C68 clients C68 S App-root detached settlement and navigation acknowledgement Bootstrap subscription/read, detached owners active/draining/settled, route action opened/blocked. Subscribe before bootstrap snapshot; query cancellation and deleted-chat fences protect delayed reconciliation; onboarding/navigation guard denies route with explicit acknowledgement. renderer/main/root-view.tsx:523; renderer/main/root-view.tsx:547; renderer/main/chat-layout.tsx:143 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C69 clients C69 V Desktop native app-control cards Hidden/visible→snapshot loading; confirmation→applying→known receipt/unknown outcome/error→refresh. Owner epoch and synchronous applying ref; retry retains exact operation ID and expected revision; checking unknown outcome must not repeat mutation. renderer/components/app-controls-panel.tsx:125 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C70 clients C70 S App update notice / reset / restart affordance Snapshot received, dismissed-key, entering/present/exiting banner; retrying/restarting with fallback timer; reset confirmation/resetting/error. Backend update status is explicit DTO; UI suppression and action lifetime is implicit. renderer/components/chat-sidebar.tsx:239; renderer/components/settings/about-settings.tsx:70; renderer/lib/use-app-update-snapshot.ts:7 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C71 clients C71 S Debounced appearance and preference/action editors Cached/hydrated/dirty/debounced/in-flight saved settings; shortcut idle/recording/conflict-replacement/saving; permission requesting/recheck; computer-use enable review; profile editing/sharing pending. Baseline, request revision and mount guard prevent stale preference writes; explicit refresh reducer exists for computer-use. renderer/components/settings/appearance-settings.tsx:284; renderer/components/settings/shortcut-settings.tsx:176; renderer/components/settings/dictation-shortcut-settings.tsx:48; renderer/components/settings/computer-use-settings.tsx:145; renderer/main/profile-view.tsx:40 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C72 clients C72 S Hover/focus/search/disclosure interaction families Hover/focus/timer→open; pinned click versus dismissed-while-focused; delayed close; find query/debounce/matches/current index/return focus; compact sidebar focus-intent; pointer/focus/window-active suppress transitions. Focus/hover temporal state is not reducible to one open boolean. renderer/components/ui-info-hint.tsx:32; renderer/components/rich-link.tsx:162; renderer/components/chat-find-bar.tsx:56; renderer/components/ui.tsx:450; renderer/components/sidebar/inbox-view.tsx:148; renderer/lib/use-held-modifier-reveal.ts:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C73 clients C73 S Pull-request linking/review and follow-through cards Link draft/query/linking/attached/error; create PR title/base/body/pending, refresh/unlink/resolve; job/PR follow display and due timer; wakeup cancelled/elapsed. User mutation pending is separate from host following state; elapsed deadline rerender does not itself authorize work. renderer/components/chat-pull-requests.tsx:178; renderer/components/chat-pull-requests.tsx:454; renderer/components/chat-pull-requests.tsx:632; renderer/components/follow-through-chips.tsx:89; renderer/components/bots/wake-up-chip.tsx:22 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C74 clients C74 S Capability refresh, diagnostics throttle, and status feeds Capability loading/polling/current/disposed; diagnostics installed/policy-resolved/per-key suppressed-count/window timer; analytics confirmed versus optimistic request generation; spend override pending/deadline refresh. Latest owner/request controls publication; passive status DTO is not counted separately. renderer/lib/app-capabilities.tsx:90; renderer/lib/dev-log.ts:26; renderer/components/usage-data.tsx:34; renderer/lib/use-spending-status.ts:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C75 clients C75 V Recording playback / preview resources Idle/loading/ready/missing plus reveal-failed; object URL exists/revoked, mounted guard; image preview loading/failed retry/selected dialog. Async result after unmount must not allocate retained URL; native recording counterparts belong to same family via N39. renderer/components/browser-recording-card.tsx:28; renderer/components/transcript-image.tsx:8; renderer/components/message-attachments.tsx:80 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:C76 clients C76 S Model picker / Model Pad interaction Open/closed pad/list/search, preview versus confirmed model, dragging/frame-queued point, focus held/restored, delayed close, awaited recent models. Pointer gesture cannot accidentally commit stale model; dropdown removal restores focus to owner. renderer/components/model-picker.tsx:478; renderer/components/model-picker-pad.tsx:166; renderer/components/settings/model-pad/model-pad-add-popover.tsx:104; renderer/components/settings/model-pad/model-pad-arrange-menu.tsx:211 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N44 clients N44 S Native pairing installation persistence Unpaired/retained/active/removed installation, secure credential saved versus metadata, validated server capabilities, cached navigation catalog. Save/select/remove must keep active ID valid and purge corresponding credential/data; App Intents cache updates navigate only, not mutate. ios/AidenOnTheGo/Models/AidenInstallation.swift:206; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenInstallationStore.kt:30; ios/AidenOnTheGo/AppIntents/AidenAppIntents.swift:177 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N45 clients N45 V Native optimistic Inbox triage/undo Optimistic row → success/rollback/conflict; undo window fresh/stale and exact write revision; read-view stamp. Rollback preserves newer reads; host switch suppresses stale notice; Android swipe conflict may retry fresh revision once but Undo never retries. iOS counterpart state sites inspected, Android handlers read. android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenInboxTriage.kt:70; ios/AidenOnTheGo/Features/Remote/AidenInboxViews.swift:8; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:207 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N46 clients N46 V Android frame-coalesced live transcript buffer Accumulating text/reasoning, unpublished/published prefix, frame job scheduled/none. Append coalesces, flush cancels frame and publishes, reset clears both buffers, publishCurrent forces replay. Flush before timeline-offset or terminal event keeps text and timeline consistent. android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenLiveTranscriptBuffer.kt:17 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N47 clients N47 V Native network recovery/transport-local memory Availability/waiter continuation pending/resumed/cancelled; recovery probe/backoff/offline parked/refunded attempt/healthy reset; server-requested deadline survives network flap. Client-scoped ETag cache/gzip-supported capability; run identity unbound→bound rejects cross-run frames. Simulator retry budget refills only after stable interval. iOS bodies read; Android corresponding owners inspected. ios/AidenOnTheGo/Networking/AidenNetworkPath.swift:20; ios/AidenOnTheGo/Networking/AidenNetworkPath.swift:125; ios/AidenOnTheGo/Networking/AidenNetworkPath.swift:156; ios/AidenOnTheGo/Networking/AidenRemoteClient.swift:1130; ios/AidenOnTheGo/Networking/AidenRemoteClient.swift:4261; ios/AidenOnTheGo/Networking/AidenSimulatorContract.swift:434; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenNetworkAvailability.kt:88; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRemoteClient.kt:105 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N48 clients N48 V Haptic delivery and reduced-motion animation ownership Scoped activation, bounded semantic dedupe history, sequence pulse, app-active/audio-capture suppression; mark mounted/running/reduced-motion/low-power, pointer pressed. Haptic dedupe precedes emission guard; inactive scope cannot deliver later pulse. Animation timer/resource owners are independent of immutable shape specifications. ios/AidenOnTheGo/Config/AidenAppearance.swift:43; ios/AidenOnTheGo/Features/Shared/ActivityMarks/AidenActivityMarkView.swift:58; android/app/src/main/java/sbtbiswas/AidenOnTheGo/ui/theme/AidenMotion.kt:142 docs/audits/implicit-state-machines-clients-2026-11-04.md +clients:N49 clients N49 V Native settings optimistic baseline and rebind Bound installation/generation × cached/current × saving memory/speech × unconfirmed baseline × action counters × refresh/poll jobs. Rebind cancels work and restores confirmed baseline; any overlapping status read is rejected by action counter, including reads begun during mutation. iOS settings read/write state inspected as corresponding family, not claimed identical implementation. android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenSettingsStore.kt:131; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenSettingsStore.kt:156; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenSettingsStore.kt:191; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenSettingsStore.kt:244; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:4301; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:4474 docs/audits/implicit-state-machines-clients-2026-11-04.md +cli-native:C01 cli-native C01 Daemon ownership and startup absent/stale lease → start lease held → spawning → owner/socket ready; timeout → terminating start, readiness polling, competing owner, spawn failure, deadline The start lease serializes starts; readiness belongs to the spawned PID, and failed startup tears down its tree. packages/cli/src/serve-lifecycle.ts:200; packages/cli/src/serve-lifecycle.ts:287 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C02 cli-native C02 Daemon shutdown and stale recovery live verified owner → TERM → waiting → KILL → gone/artifacts cleared; foreign or unverifiable owner blocks action stop, lease change, PID exit/reuse, grace deadline Owner token/start time and process identity govern cleanup; detached group and recorded MCP groups have separate teardown. packages/cli/src/serve-lifecycle.ts:354 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C03 cli-native C03 Serve admission and resource lifetime lease held → services starting → socket serving → ingress closed → services draining → socket/lease released start, ready, signal, initialization error, finally Chat admission closes synchronously before asynchronous ingress shutdown; cleanup results are settled together. packages/cli/src/serve.ts:30; packages/cli/src/serve.ts:41 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C04 cli-native C04 Local daemon command framing connecting → request sent → partial response → newline frame → resolved/rejected/closed connect/data/end/error/timeout One response promise, byte ceiling, UTF-8 chunk decoding and missing-response rejection. A stream protocol machine, not a product mode. packages/cli/src/daemon-control.ts:5; packages/cli/src/serve.ts:54 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C05 cli-native C05 OS service install/replacement rollback inspected → previous daemon stopped → installed → ready → network configured; failure restores/removes service install, readiness timeout, manager failure, network failure, uninstall Service identity rechecked before mutation; service readiness and network reachability are independent outcomes. packages/cli/src/service.ts:167; packages/cli/src/service.ts:516 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C06 cli-native C06 Startup pairing presentation address preparation → pairing window → QR shown → polling → paired/failed/expired/superseded/cancelled foreground pair, status, deadline, signal Only the matching session is reported/cancelled; cancelling service-install pairing leaves the daemon running. packages/cli/src/serve-command.ts:86; packages/cli/src/service.ts:614 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C07 cli-native C07 Tailscale health wait unchecked → probing → ready or retry → timed out/cancelled bounded HTTPS response, socket error, abort, retry timer Pinned CA supplied where required; response byte bound and single-settlement guard; route preparation precedes code display. packages/cli/src/reachability.ts:296; packages/cli/src/reachability.ts:337; packages/cli/src/reachability.ts:366 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C08 cli-native C08 Linux Bonjour publisher stopped → spawning → advertising → exited → retry scheduled; superseded generation start, child spawn/error/exit, retry timer, stop Generation and child identity fence late exit/retry callbacks. macOS delegates to the shared publisher. packages/cli/src/remote.ts:57 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C09 cli-native C09 Daemon turn admission and handoff idle → reserved → active → cancellation requested → settled; closed/deleting block entry beginChatTurn, start/handoff, cancelChat, lease release, stop Three distinct busy representations (reserved, admission, active); idle waiters must observe both reservation and execution settlement. packages/cli/src/daemon-chats.ts:69; packages/cli/src/daemon-chats.ts:82; packages/cli/src/daemon-chats.ts:128 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C10 cli-native C10 Daemon generation execution and persistence resource preparation → session bound → prompting/streaming/tools → final persisted or partial persisted → disposed provider/tool events, acceptance, owner invalidation, timeout, cancel, persistence error persisted flag prevents duplicate assistant append; terminal notification and cleanup occur at different boundaries. packages/cli/src/daemon-chats.ts:147; packages/cli/src/daemon-chats.ts:297 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C11 cli-native C11 Daemon tool approval absent → attention pending → allowed/denied/expired/cancelled → authority rechecked tool call, owner/host answer, timer, turn abort Owner-scoped resolution, unchanged arguments, current workspace authority and idempotent pending-map removal. packages/cli/src/daemon-chats.ts:73; packages/cli/src/daemon-chats.ts:235 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C12 cli-native C12 CLI Bot pause orchestration unpaused → durable pause written → foreground work stopped and drained; unpause clears fence pause/unpause, start/preflight, shutdown Paused state is a durable authority fence, not just a UI indicator; shared Bot services own underlying capability transitions. packages/cli/src/bots.ts:104; packages/cli/src/bots.ts:112 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C13 cli-native C13 CLI durable Bot migration legacy/no marker → preparing → backup completed → enabled, restart required explicit migration, cancel/drain legacy chats, backup failure, retry/restart Preparing blocks new legacy generation; only a complete backup publishes enabled. Marker persists across crashes. packages/cli/src/bot-durable-migration.ts:8; packages/cli/src/bot-durable-migration.ts:16; packages/cli/src/bots.ts:254 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C14 cli-native C14 CLI remote chat deletion recovery persisted deletion tombstone → private history cleanup → tombstone removed startup replay, chat delete, cleanup failure An unfinished deletion is replayed before normal serving. Shared chat application, stream journal, read-marker and triage machines are reused, not new independent implementations. packages/cli/src/remote-chats.ts:23 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C15 cli-native C15 Schedule consent publication snapshot captured → consent receipt active → first write verified → follow-on writes → invalidated/cancelled model mutation, durable write, expiry, changed workspace/provider/task, receipt removal AsyncLocalStorage tracks active/firstWrite/cancellation; failed verification disables consent and aborts publication for rollback. packages/cli/src/schedule-tool-approval.ts:27; packages/cli/src/schedule-tool-approval.ts:44; packages/cli/src/schedules.ts:27 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C16 cli-native C16 CLI scheduled execution inactive → active controller → script/inference/Bot execution → result recorded → inactive scheduler run/cancel/cancelAll, tool call, authority change Provider/workspace/MCP authority is checked before and during unattended execution; shared scheduler owns timing/revision transitions. packages/cli/src/schedules.ts:53; packages/cli/src/scheduled-inference.ts:54 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C17 cli-native C17 Scheduled inference response metering per-message empty → per-block streaming → block end → terminal signature accounting → next message delta/end/message_start/message_end State is streamed/signature maps plus cumulative budget; avoids double counting partial snapshots and enforces abort on resource budgets. Algorithmic streaming machine. packages/cli/src/scheduled-inference.ts:21 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C18 cli-native C18 CLI child inference and cleanup forked → started → running/tool pending → done received → child closed; failure → TERM → KILL → tools drained IPC events, budgets, cancellation, error, close done, failure, activeTools and toolAbort jointly determine successful settlement; done alone is insufficient without clean child close/final answer. packages/cli/src/subagent-process.ts:13; packages/cli/src/subagent-process.ts:27; packages/cli/src/subagent-process.ts:80 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C19 cli-native C19 CLI worker RPC not started → started/session preparing → prompting ↔ parent tool RPC pending → finished/disconnected start/tool-result/cancel/disconnect started gates duplicate start; per-ID pending map owns tool reply; finished changes disconnect handling. packages/cli/src/subagent-worker.ts:11 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C20 cli-native C20 CLI MCP connection and inventory incarnation absent → connecting → client ready → stale/superseded/terminal failure → absent; pool closed terminal connection, credential/config change, inventory invalidation, close Entry identity fences awaits; concurrent callers share pending connection; close retires attempts and resolved clients; tools revalidate schema/effects. packages/cli/src/mcp.ts:399; packages/cli/src/mcp.ts:427; packages/cli/src/mcp.ts:488 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C21 cli-native C21 Terminal provider auth interaction coordinator started → URL/device-code or prompt waiting → response → signed-in/cancelled/error → teardown auth notifications, readline answer, SIGINT Secret echo suppression and AbortController are coupled to prompt and terminal events; shared coordinator owns actual provider auth. packages/cli/src/auth.ts:51 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C22 cli-native C22 CLI speech worker/model lifetime no worker → worker available → model/language held → transcribing → retire/recreate or crash retry transcribe, model switch, hang/exit/crash, stop Worker and client identity fence late exits; model recorded before request because failure may still retain native recognizer. packages/cli/src/speech.ts:23; packages/cli/src/speech.ts:72 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C23 cli-native C23 Avatar decoder admission and worker below concurrency limit → active slot → worker request → decoded/error/timeout → terminated/slot released decode, message, exit, error, timer Bounded concurrent work and finally cleanup; relies on shared avatar service for upload lifecycle. packages/cli/src/bot-avatars.ts:7 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C24 cli-native C24 Cross-process lease and JSON publication guard acquired → stale owner removed → owner published → held → released; queued mutation → lease → publication acquire/release/update, failure, currentness check released makes release idempotent; failed publication releases guard; serialized tails plus filesystem lease guard updates. packages/cli/src/state.ts:48; packages/cli/src/state.ts:98; native/lease-flock/main.c:6 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C25 cli-native C25 Credential writer queue and contention queued → lease retry/backoff → held → mutation → released; expired/superseded prior writer settlement, lock contention, deadline, isCurrent Per-file queue plus cross-process lease; identity check prevents old completion deleting a newer queue tail. packages/cli/src/credentials.ts:34 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C26 cli-native C26 Todo branch restore fencing unavailable → restoring(epoch) → ready or unavailable after error; superseded/shutdown session_start/session_tree/session_shutdown A late restore cannot overwrite a newer branch; unreadable checkpoints never become empty tasks. Shared todo reducer is explicit. packages/cli/src/extensions/todo.ts:18 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C27 cli-native C27 Advisor per-turn availability runtime absent → lazy runtime ready; currentTurn absent ↔ enabled reviewer tool before_agent_start, model/scope selection, tool call Current turn captures matching tool/prompt; shared advisor runtime owns consultation attempt lifecycle. packages/cli/src/extensions/advisor.ts:65; packages/cli/src/extensions/advisor.ts:107 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C28 cli-native C28 CLI Bot inventory authority invalidation current fingerprint/lease revision → invalidated → new admission required auth/model/MCP/web config watcher, approved-root fingerprint change or read failure Root fingerprint distinguishes unrelated remote-state writes; invalidated admissions must not authorize further tools. packages/cli/src/bots.ts:181 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C29 cli-native C29 CLI MCP configuration migration/reconciliation legacy recognized → lease → validated backup → destination published → source inode claimed → retained recovery; conflict → reconciliation required startup/store construction, concurrent file change, claim/sync failure Publish destination before retiring source; never discard claimed inode or overwrite a newer source; retries recognize existing identical backup. packages/cli/src/mcp-config-migration.ts:35 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C30 cli-native C30 CLI Azure identity migration legacy per-file identity → file lock/credential lease → reconciled current identity → atomic publication; divergent identities block migration pre-runtime migration, credential conflict, repeated startup Repeatable per-file migration; model endpoint and credential identity must remain aligned; this is a persisted migration transaction. packages/cli/src/azure-config-migration.ts:39 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C31 cli-native C31 CLI provider credential migration/writer queued → writer lease → absent-store initialization or legacy staging → encrypted replacement → operation → released credential read/list/modify/delete, legacy format, invalid entry, migration failure Validate all legacy entries before replacement; queue identity and writer lease prevent overlapping publication; stage removed in finally. packages/cli/src/provider-credentials.ts:9 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:C32 cli-native C32 CLI usage attempt accounting unaccounted → serialized writer/lease → usage plus attempt hash published → accounted; replay suppressed record usage, repeated advisor attempt, writer failure Dedupe receipt and aggregate usage are published together; bounded retained attempt window is separate from in-process promise tail. packages/cli/src/usage-ledger.ts:13; packages/cli/src/usage-ledger.ts:31 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N01 cli-native N01 Native CUA broker/bridge handshake lease listener → authenticated bridge lease → matching control peer → supervision armed → driver constrained → acknowledged → ready relay → teardown socket peers, handshake frames, deadline, EOF/signal Same audit token on both sockets; no ready relay before both supervision acknowledgements. native/computer-use-broker/src/runtime.rs:423; native/computer-use-broker/src/runtime.rs:641 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N02 cli-native N02 CUA containment guard dormant → ready → awaiting authenticated arm → liveness monitoring → TERM grace → KILL arm byte, deadline, death pipe, lease EOF/payload/error Guard occupies the process group; any lease payload revokes liveness, avoiding delayed numeric-PGID reuse. native/computer-use-broker/src/guard.rs:100; native/computer-use-broker/src/guard.rs:157; native/computer-use-broker/src/guard.rs:234 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N03 cli-native N03 CUA driver launch supervision fallback/watchdog ready → entering launch → returned PID → stopped/identified/contained → launcher joined → resumed or supervision failed private byte protocol, spawn return, timeout, audit-token/identity checks Explicit wire phase bytes with transitions distributed through launcher/watchdog processes; separate from broker ready state. native/computer-use-broker/src/supervisor.rs:9; native/computer-use-broker/src/driver.rs:1 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N04 cli-native N04 CUA JSON-RPC pending tool-list filter request unseen → allowed list request pending → response matched/filtered → removed client/driver frames, duplicate or unsupported request Pending request-ID set and bounded line framing determine what may traverse privileged relay. Protocol machine. native/computer-use-broker/src/runtime.rs:365; native/computer-use-broker/src/jsonrpc.rs:1; native/computer-use-broker/src/lines.rs:1 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N05 cli-native N05 Native subagent shell execution validated → spawned/contained → polling and capture → exited/signalled/cancelled/timed-out/overflow → cleanup confirmed or unconfirmed stdin lifetime, output, waitpid, deadline, process-group cleanup Child exit and descendant cleanup are separate facts; cleanup failure overrides otherwise successful outcome. native/subagent-shell-runner/main.c:228; native/subagent-shell-runner/main.c:388 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N06 cli-native N06 Native file mutation transaction idle → inspected → prepared → committed with recovery → finalized/preserved; precommit cancel; indeterminate durability inspect/prepare/prepare-inspected/commit/finalize/preserve/cancel/close active/prepared/committed/recovery_unlinked/commit_parent_synced encode product state; identity, digest and request ID guard transitions. native/subagent-file-mutator/main.c:44; native/subagent-file-mutator/main.c:1242; native/subagent-file-mutator/main.c:1619 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N07 cli-native N07 Native managed-worktree removal and resume quarantined → isolated → manifest persisted → authorization barrier → deleting → manifest finalizing/deleting → removed or recoverable residue fresh/resume/remove, continue/resume digest, identity change, partial failure Directory identity and durable manifest bind deletion; pre-existing isolated children require explicit matching resume authority. native/worktree-remover/main.c:1104; native/worktree-remover/main.c:1570; native/worktree-remover/main.c:720 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N08 cli-native N08 Native editor/save publication source opened/verified → content staged → exchange/publication → recovery cleanup or preserved error edit/create/save, source identity/hash mismatch, write/fsync failure Editor publication checks source identity/digest; create/save use confined paths and their own publication rules. Recovery and durability handling differ by operation. Transaction machine, not a UI editor state. native/worktree-file-io/main.c:337; native/worktree-file-io/main.c:495; native/worktree-file-io/main.c:560 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N09 cli-native N09 Native subagent run-store protocol and CAS publication ready → read/write(expected digest)/cleanup/sync → response → ready; close/EOF terminal command frames, destination changed, partial write/sync error Expected hash and owned temporary recovery files guard publication; state is partly on disk. native/subagent-run-store/main.c:757 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N10 cli-native N10 Native inbox file receipt identity checked → exclusively created → declared bytes receiving → EOF verified → file+directory synced → acknowledged short/extra input, write failure, fsync, stdout failure Incomplete file cleanup precedes failure; no success receipt until exact byte count and durability checks. native/bot-inbox-writer/main.c:115 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N11 cli-native N11 Linux shortcut portal session and hold creating → binding → bound; inactive ↔ active; finishing terminal D-Bus Response/Activated/Deactivated/ShortcutsChanged/Closed/owner change, stdin EOF waiting_create/bound/active/finishing plus sender/session IDs; only matched activation toggles hold. native/global-shortcuts-portal/main.c:19; native/global-shortcuts-portal/main.c:136 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N12 cli-native N12 Native form-fill model service scorer absent → loaded → repeated score; shutdown clears scorer and marks shutdownRequested load/compile/score/shutdown, cancellation/error Scoring requires a loaded scorer; outer helper loop consumes shutdownRequested. Compile is an operation, not necessarily a loaded-model transition. native/cua-s1-forms/Sources/AidenCuaS1FormsCore/Service.swift:5; native/cua-s1-forms/Sources/AidenCuaS1FormsHelper/main.swift:1 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N13 cli-native N13 Signed iMCP child supervision verified → launched → running → TERM/exit → group KILL → launcher exit signature checks, child run/error, termination source/handler Launch constraint binds executable identity; child exit also kills descendants retaining pipes. native/imcp-launcher/main.swift:40 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N14 cli-native N14 Linux managed-payload staging transaction validated inventory/approval → private staging → copied+verified → published → parent synced; prepublish discard or published-uncertain stage, validation/copy failure, publish, fsync failure published flag forbids deleting a generation already published; receipt explicitly does not grant runtime admission. Ancillary staging tool. native/linux-managed-payload/src/stage.rs:194 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N15 cli-native N15 Audio-worklet chunk framing partial samples retained → complete 20ms frame → emitted PCM → residual samples retained audio process blocks Sample-count buffer carries state across callbacks; this is an algorithmic streaming machine, not connection/session lifecycle. public/gemini-live-pcm-worklet.js:39 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:N16 cli-native N16 Foundation Models helper file handshake process marker published → request read/deleted → cancellation marker checked → service invoked → atomic response → process marker removed launch, preflight cancellation, parse/model failure, response encode/write, process return Availability enum is external state; the helper owns the file/request/process receipt lifecycle. Cancellation after invocation is enforced by its parent process supervisor, not an internal polling loop. native/apple-foundation-models/Sources/AidenFoundationModelsHelper/main.swift:25 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:O01 cli-native O01 Bounded-command occupied group guard running → result reported/waiting release → terminating → TERM grace → KILL terminate/release IPC, parent disconnect, command error/close terminating makes teardown idempotent; result does not release descendant containment. Runtime support script. scripts/bounded-command-guard.mjs:15 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +cli-native:O02 cli-native O02 Distribution transaction unprepared → prepared → built → verified → promoted; failure → discard or aggregate failure prepare/build/verify/promote/discard Only prepared staging is discarded; packaging is operational tooling, not a live application lifecycle. scripts/run-macos-distribution.mjs:218 docs/audits/implicit-state-machines-cli-native-2026-11-04.md diff --git a/docs/audits/implicit-state-machine-risk-ranking-2026-11-04.tsv b/docs/audits/implicit-state-machine-risk-ranking-2026-11-04.tsv new file mode 100644 index 0000000000..c91199eef5 --- /dev/null +++ b/docs/audits/implicit-state-machine-risk-ranking-2026-11-04.tsv @@ -0,0 +1,373 @@ +risk_rank risk_tier risk_group planned_phase inventory_id machine consequence authority temporal_complexity recovery group_rationale state_events_invariants source_links inventory_report +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M009 I Generation/document ownership leases: active/invalidated identity plus listeners 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Reload/destroy invalidates authority; stale same-WebContents documents must not cancel, answer or mutate replacement document work. main/services/chat-generation-owner.ts:56; main/services/renderer-document-owner.ts:131 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M010 I Chat/workspace mutation gates: changing/deleting sets plus active admissions 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Move/delete/copy/export blocks new turns, aborts matching work and awaits settlement, then releases; admission busy differs from draining-child busy. main/services/chat-deletion-gate.ts:7; main/services/chat-workspace-mutation-gate.ts:6; main/services/workspace-mutation-gate.ts:2; main/services/workspace-operation-registry.ts:25 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M019 I Tool approval coordinator: pending × published × settled, closed-stream cancelled/detached tombstones 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Request/publish/decision/abort/detach/shutdown; exactly one answer, no late prompt after closed stream. main/services/tool-approval.ts:76; main/services/tool-approval.ts:126 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M020 I Question coordinator: pending/expired/detached maps, timer × published × settled 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Ask, valid answer, countdown expiry, abort/detach/shutdown; timeout and answer race must choose one winner. main/services/ask-user-question-coordinator.ts:34; main/services/ask-user-question-coordinator.ts:95 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M028 I Bot approval wait registry 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Absent → waiting → allow/deny/withdrawn; abort and duplicate wait IDs clean up identity-matched entries, durable task memo permits same-ID re-ask after Resume. main/services/bot-runtime/bot-approvals.ts:47 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M029 I Bot question wait registry 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Waiting → first valid answer or abort/replacement; invalid answers leave wait live; Bot ID and exact prompt identity gate settlement. main/services/bot-runtime/bot-questions.ts:74 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M031 I Handoff browser/computer holds and notifications 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Open card acquires tab/control hold, person answers or aborts releases; browser tab recreation, take-over state, and announced wait-ID dedupe have separate lifetimes. main/services/bot-runtime/bot-browser-handoff.ts:87; main/services/bot-runtime/bot-computer-handoff.ts:66; main/services/bot-runtime/bot-handoff-notifications.ts:50 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M033 I Bot model/tool registry snapshot and authority freshness 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Session opens registry, prepare/refresh installs tool set and memory snapshot, lazy runtime map per Bot; turn ingress changes routine/attended policy. main/services/bot-runtime/bot-models.ts:73; main/services/bot-runtime/bot-extension.ts:379; main/services/bot-runtime/bot-tool-assembly.ts:185 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M036 I Bot capability leases and inventory generation fences 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Active leases → invalidated/aborted/released by policy epoch, identity or inventory fingerprint changes; readmission validates immediately before effect. main/services/bot-capability-lease.ts:62; main/services/bot-runtime-inventory-lease.ts:39; main/services/bot-runtime-authority.ts:526 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M037 H Capability checkpoint/anchor publication 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. pending → committed state head and pending → consumed bootstrap marker, initialized/poisoned flags; anchored persistence disagreement fails closed. main/services/bot-capability-state-checkpoint.ts:27; main/services/bot-capability-state-checkpoint.ts:307; main/services/bot-capability-state-checkpoint.ts:374; main/services/bot-capability-state-checkpoint.ts:516; main/services/bot-capability-authority-item.ts:133 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M056 H Pairing window: absent/awaiting_scan/finishing/failed/expired, secret/manual key material, exchange admission and source attempts 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Begin/close/expire/exchange; one admitted exchange, bounded attempts, erasure of abandoned key material. main/services/aiden-remote-pairing.ts:76; main/services/aiden-remote-pairing.ts:230; main/services/aiden-remote-pairing.ts:245; main/services/aiden-remote-pairing.ts:361; main/services/aiden-remote-pairing.ts:383; main/services/aiden-remote-pairing.ts:442 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M057 H Nearby pairing requests: pending/approving/approved/denied/expired/cancelled × revealed/delivered/withdrawn/issued credential; poll waiters and retirements 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Approve/deny/cancel/host-window change/poll/retire/close; approval can require compensating revocation after cancellation or uncollected grant. main/services/aiden-remote-pairing-requests.ts:297; main/services/aiden-remote-pairing-requests.ts:436; main/services/aiden-remote-pairing-requests.ts:532; main/services/aiden-remote-pairing-requests.ts:567; main/services/aiden-remote-pairing-requests.ts:687; main/services/aiden-remote-pairing-requests.ts:702 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M065 I Attachment upload/reservation lifecycle: upload active, records staged/claimed/consumed/reclaimed, deleting-chat fence 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Begin/upload/stage/reserve/consume/delete/revoke device/expiry; reservation rollback must preserve retryable attachments, deletion invalidates admitted uploads. main/services/aiden-remote-attachments.ts:231; main/services/aiden-remote-attachments.ts:244; main/services/aiden-remote-attachments.ts:266; main/services/aiden-remote-attachments.ts:374; main/services/aiden-remote-attachments.ts:393; main/services/aiden-remote-attachments.ts:489 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M066 I Opaque file handle/listing leases: issued handles, listing membership, reclaimable set, counts and root identity 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. List/use/renew/reclaim/revoke; bound device/root/inode and listing capacity prevent stale handles becoming authority. main/services/aiden-remote-opaque-handles.ts:64; main/services/aiden-remote-opaque-handles.ts:316; main/services/aiden-remote-files.ts:153 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M067 I Remote workspace operation owner and schedule/script claims: active owner→invalidated and claim acquisition→consumption; workspace/device revoke blocks late effects 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Owner invalidation plus expected operation revision gate async writes and script run. main/services/aiden-remote-workspace-owners.ts:4; main/services/aiden-remote-schedules.ts:193 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M076 I Telegram profile/config binding mutation: per-profile tails + incarnation, active profile service map, binding committed/pending anchor 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Remove/recreate/rotate binding/activate profile; old operations must not mutate replacement profile or commit mismatched anchor. main/services/telegram/telegram-profile-mutation-fence.ts:15; main/services/telegram/telegram-service.ts:895; main/services/telegram/telegram-bot-binding-store.ts:417 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M099 H Auth reuse grant validity: not-consented/invalid/ready/revoked/expired/identity-drift/model-unavailable projected from persisted binding and current credential 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Connect/refresh/revoke/key/model changes; reusable grant is not inference authorization after identity drift. main/services/web-search-auth-reuse.ts:398; main/services/web-search-auth-reuse.ts:522 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M107 H Subagent approval/run grant: pending/granted/denied; pending promise and call-owner/approval ledger with expiry 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Request/grant/deny/consume/expire/cancel; bound authority digest, argument digest and one-use call ownership. main/services/subagents/approval-v2.ts:8; main/services/subagents/approval-v2.ts:351; main/services/subagents/approval-v2.ts:472; main/services/subagents/subagent-mcp-mutation-approval.ts:198 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M109 I Subagent network budget and retained request capabilities: scoped counters/leases → exhausted/released; owned request capabilities expire/revoke 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Reserve before effect, refund/release exactly once; permission is bounded by lineage and current authority. main/services/subagents/network-budget-v2.ts:20; main/services/subagents/request-capabilities-v2.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M110 H Durable parent effect/operation store: operation running→terminal; effect prepared→dispatch_started→completed/remote_error/unknown/interrupted or cancelled_before_dispatch 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Begin/prepare/dispatch/finish/recovery; terminal receipt and digest must agree, abandoned prepared effects differ from dispatched unknown effects. main/services/pi-runtime-effect-store.ts:185; main/services/pi-runtime-effect-store.ts:297; main/services/pi-runtime-effect-store.ts:430; main/services/pi-runtime-effect-store.ts:443; main/services/pi-runtime-effect-store.ts:475; main/services/pi-runtime-effect-store.ts:507 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M119 I Computer-use access/settings generation: grant revision, request epoch, disableRequired/closed/shutdown, activated stream bit 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Explicit access decision/enable/disable/model removal/revoke; close gate before snapshotting activated work and await actual settlement. main/services/computer-use/access-gate.ts:44; main/services/computer-use/access-gate.ts:119; main/services/computer-use/settings-core.ts:14; main/services/computer-use/generation-gate.ts:3; main/services/computer-use/generation-gate.ts:58 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M123 I Bot computer ownership takeover: controller bot/person × actions × waiters and unattended remaining wait budget 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Take over aborts in-flight Bot actions, Give back releases waits, forget invalidates; no Bot screen read while person holds control. main/services/bot-computers/control.ts:64; main/services/bot-computers/control.ts:80; main/services/bot-computers/control.ts:110; main/services/bot-computers/control.ts:126 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M127 I Browser file capability leases: leases/opening/epochs/consumers/closing/retiredOrigins/retiredTokens/stopped 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Acquire/use/revoke origin/navigation/close/shutdown; root identity validation and draining reads precede resource cleanup. main/services/browser/files.ts:259; main/services/browser/files.ts:763; main/services/browser/files.ts:782; main/services/browser/files.ts:873 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M142 H Form-fill batch consent: pending/authorized/consumed/revoked/expired and plan digest/token index 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Prepare/authorize/revalidate/consume/revoke/timeout; token consumed before effect, changed plan cannot reuse consent. main/services/form-fill/batch-core.ts:130; main/services/form-fill/batch-core.ts:184; main/services/form-fill/batch-core.ts:218; main/services/form-fill/batch-core.ts:264; main/services/form-fill/service.ts:168 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M164 I Proof/receipt stores with deletion fencing: queued writes, deletedChats and pendingChats, initialized/reconciled records 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Verify/record/delete/restart; late checks cannot republish evidence for deleted chat. main/services/pi-verification-store.ts:81; main/services/workflow-evidence-store.ts:132; main/services/chat-pull-request-store.ts:123 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M166 I Analytics consent/client lifecycle: activation promise/generation, client/revocation/stopped/openedSent, consent queue 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Notice shown/toggle/environment gate/start/shutdown; revoke pending activation before it creates client, disabled event once then drop queue/install ID. main/services/analytics/analytics-service.ts:119; main/services/analytics/analytics-service.ts:192; main/services/analytics/analytics-service.ts:248; main/services/analytics/analytics-service.ts:260; main/services/analytics/analytics-client.ts:33 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M171 I Foreground picker/export/single-operation admission: pickerActive/chatExportActive/pending/preparingShare 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. IPC request claims synchronously, dialog cancel/success/error releases; owner invalidation must prevent response applying to new document. main/handlers/attachments.ts:52; main/handlers/chats.ts:158; main/handlers/bot-computers.ts:72; main/handlers/acp-harnesses.ts:45; main/services/profile-share.ts:29 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M180 I Attachment ingestion reservations: records + per-document/global count/byte budgets × cancelled 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Acquire synchronously reserves budgets; cancel revokes authority without freeing retained representation; release returns counters exactly once. Separate from remote uploaded-attachment consumption. main/services/attachments.ts:151; main/services/attachments.ts:177; main/services/attachments.ts:211 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M181 I Per-attempt MCP OAuth nonce/issuer consumption: discovered metadata, started/consumed, required issuer and scope 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Discovery→authorization URL→single callback→code exchange; same nonce, exact issuer/count and one result required, no callback replay after consume. main/services/mcp-oauth-session.ts:418; main/services/mcp-oauth-session.ts:447; main/services/mcp-oauth-session.ts:478 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M182 I Privileged computer-use one-shot grant: prepared fingerprint/target revision → authorized map entry → consumed/deleted 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Authorize checks action/target unchanged; consume deletes before validation/effect, so stale or reused grant cannot be retried; clear ends generation grants. main/services/computer-use/safety.ts:821; main/services/computer-use/safety.ts:829; main/services/computer-use/safety.ts:842; main/services/computer-use/safety.ts:864 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M189 I Routine health preflight scheduler: timers, checked fire keys, per-Bot running chains, disposed/rearms generation 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Rearm after schedule/sleep changes; stale read cannot arm old timers; one check per fire and per-Bot serial checks; late/past fire not checked. main/services/bot-health/preflight.ts:106; main/services/bot-health/preflight.ts:120; main/services/bot-health/preflight.ts:141 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M190 I Remembered tool approval scope: no grant/chat grant/persisted always grant, per-chat map and bounded eviction 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Grant/match/revoke/clear chat; exact call/workspace binding, temporary chat authority distinct from persisted always authority. main/services/tool-approval-rules.ts:185; main/services/tool-approval-rules.ts:202; main/services/tool-approval-rules.ts:218; main/services/tool-approval-rules.ts:255 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M191 I Remote Git snapshot authority: issued bounded snapshot token with expiry and expected repository/workspace identity 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Inspect issues token; mutation validates current snapshot/revision; expiry/prune removes authority. Durable idempotency ledger separately owns effect replay. main/services/aiden-remote-git.ts:207; main/services/aiden-remote-git.ts:227; main/services/aiden-remote-git.ts:234; main/services/aiden-remote-git.ts:280 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 backend:M197 I Device proxy grant/socket lifetime: expiring token grants, open sockets, per-host socket ownership and listening port 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Issue/access/prune/host disconnect/close; token authorizes only local proxy and is stripped upstream, host revoke must destroy retained connections. main/services/devices/device-hub-proxy.ts:362; main/services/devices/device-hub-proxy.ts:369; main/services/devices/device-hub-proxy.ts:374; main/services/devices/device-hub-proxy.ts:384 docs/audits/implicit-state-machines-backend-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 cli-native:C11 Daemon tool approval 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. absent → attention pending → allowed/denied/expired/cancelled → authority rechecked tool call, owner/host answer, timer, turn abort Owner-scoped resolution, unchanged arguments, current workspace authority and idempotent pending-map removal. packages/cli/src/daemon-chats.ts:73; packages/cli/src/daemon-chats.ts:235 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 cli-native:C15 Schedule consent publication 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. snapshot captured → consent receipt active → first write verified → follow-on writes → invalidated/cancelled model mutation, durable write, expiry, changed workspace/provider/task, receipt removal AsyncLocalStorage tracks active/firstWrite/cancellation; failed verification disables consent and aborts publication for rollback. packages/cli/src/schedule-tool-approval.ts:27; packages/cli/src/schedule-tool-approval.ts:44; packages/cli/src/schedules.ts:27 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 cli-native:N10 Native inbox file receipt 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. identity checked → exclusively created → declared bytes receiving → EOF verified → file+directory synced → acknowledged short/extra input, write failure, fsync, stdout failure Incomplete file cleanup precedes failure; no success receipt until exact byte count and durability checks. native/bot-inbox-writer/main.c:115 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 cli-native:N12 Native form-fill model service 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. scorer absent → loaded → repeated score; shutdown clears scorer and marks shutdownRequested load/compile/score/shutdown, cancellation/error Scoring requires a loaded scorer; outer helper loop consumes shutdownRequested. Compile is an operation, not necessarily a loaded-model transition. native/cua-s1-forms/Sources/AidenCuaS1FormsCore/Service.swift:5; native/cua-s1-forms/Sources/AidenCuaS1FormsHelper/main.swift:1 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C10 Remote chat mutation controls 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Busy intent set, unresolved mutation, elsewhere notice, hydrated availability, attached lifetime. Send/cancel/approval/question/run-input/rename/remove → receipt/refusal/unknown. Guards combine adapter capability, host availability, ledger readiness and uncertainty; uncertain mutation must not silently mint a new key. renderer/lib/hosts/chat-session-control.ts:52; renderer/lib/hosts/chat-session-control.ts:160; renderer/lib/hosts/chat-session-control.ts:524 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C20 Prompt response/expiry/late answer 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Pending → responding → answered/denied/withdrawn/expired; late-answer saved/sending; deciding refs fence duplicate actions. Stream/prompt/wait ID determines ownership; timer expiry and server settlement race. Per-wait recovery-owner maps at renderer/main/chat-pane.tsx:3421 add retry lifetime. renderer/main/chat-pane.tsx:797; renderer/main/chat-pane.tsx:807; renderer/main/chat-pane.tsx:2543; renderer/main/chat-pane.tsx:3402; renderer/components/ask-user-question-composer.tsx:14; renderer/components/computer-use-access-approval.tsx:37; renderer/main/chat-pane.tsx:3421 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C33 Live assistant approvals and output media 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Pending/answered voice approvals and receipt retention; caption IDs; audible-session/received-audio ownership; screen share start/active/stopped; PCM player active and packet buffers. Session identity must fence audio and approval result callbacks. renderer/components/assistant/use-assistant-live-approvals.ts:14; renderer/components/assistant/use-assistant-live.ts:507; renderer/components/assistant/use-assistant-live.ts:948; renderer/components/assistant/use-assistant-live.ts:996; renderer/lib/gemini-live-media-core.ts:93 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C35 Device grant/view lifecycle 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. idle/grant acquisition/connecting/streaming/error × inputConnected × renewal attempts × pressed keys. Selection/visibility/retry/grant-expiry/unmount start or stop client; release held keys and reject stale grant responses. renderer/lib/use-device-stream.ts:61; renderer/lib/use-device-stream.ts:85 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C53 Remote pairing/access/device add 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Method entry→request/QR/manual waiting→approved/denied/expired/cancelled/finishing; enable/access mode and per-request pending decisions. Countdown/refresh/cancel/late approval and unmount must preserve exact pairing ownership. renderer/components/settings/remote-access-settings.tsx:74; renderer/components/settings/peer-add-device-sheet.tsx:51; renderer/components/settings/peer-hosts-settings.tsx:32; renderer/components/remote-pairing-request-sheet.tsx:11; renderer/lib/remote-pairing-lifecycle.ts:15 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C56 Bot creation/profile/access/instructions 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Create steps/model/provider connection/busy/error; edit draft/baseline/save/discard; photo upload; Full/Custom access draft. Save rollback belongs to captured entity/revision; creating Bot and initial message are separate operations. renderer/main/bots/bot-create-flow.tsx:195; renderer/main/bots/bot-profile.tsx:67; renderer/main/bots/bot-advanced.tsx:501; renderer/main/bots/bot-instructions-editor.tsx:25 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C63 Scheduled task editor/list and ancillary settings mutations 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Edit/validate/save/delete/run/cancel/refresh and pending row IDs; diagnostics collect/export; Telegram link/poll/disconnect; keys validate/remove; memory edit/undo. Independent per-owner mutations, with busy/error states and late-response ownership. renderer/components/scheduled-task-editor.tsx:47; renderer/components/scheduled-tasks-view.tsx:104; renderer/components/settings/scheduled-tasks-settings.tsx:31; renderer/components/settings/diagnostics-settings.tsx:12; renderer/components/settings/telegram-settings.tsx:44; renderer/components/settings/web-search-key-pool.tsx:20; renderer/components/settings/memory-facts-section.tsx:24 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C64 Link routing consent / command routing 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Preferences unknown/loading→ready, queued links, pending consent/menu, surfaces/blockers; command handler stack+palette mode/open/query/selection. Resolve prefs before routing; owner unregister removes handlers; Escape/choice drains the right pending action. renderer/lib/link-opener.tsx:129; renderer/lib/command-system.tsx:76; renderer/components/command-palette.tsx:120 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C67 Single-use annotation/image delivery registry 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Registered eligible composer(s) → captured recipient → delivered/rejected/invalidated. Annotation capture requires exactly one eligible receiver; receipt can succeed only once and only while exact receiver remains registered. Image registry follows mounted receiver ownership. renderer/lib/browser-annotation-delivery.ts:18; renderer/lib/composer-attach.ts:14 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C71 Debounced appearance and preference/action editors 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Cached/hydrated/dirty/debounced/in-flight saved settings; shortcut idle/recording/conflict-replacement/saving; permission requesting/recheck; computer-use enable review; profile editing/sharing pending. Baseline, request revision and mount guard prevent stale preference writes; explicit refresh reducer exists for computer-use. renderer/components/settings/appearance-settings.tsx:284; renderer/components/settings/shortcut-settings.tsx:176; renderer/components/settings/dictation-shortcut-settings.tsx:48; renderer/components/settings/computer-use-settings.tsx:145; renderer/main/profile-view.tsx:40 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:C74 Capability refresh, diagnostics throttle, and status feeds 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Capability loading/polling/current/disposed; diagnostics installed/policy-resolved/per-key suppressed-count/window timer; analytics confirmed versus optimistic request generation; spend override pending/deadline refresh. Latest owner/request controls publication; passive status DTO is not counted separately. renderer/lib/app-capabilities.tsx:90; renderer/lib/dev-log.ts:26; renderer/components/usage-data.tsx:34; renderer/lib/use-spending-status.ts:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:N02 Pairing and nearby discovery 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. QR camera permission/scanning/recognized; manual endpoint/code/check/exchange; discovery browsing/resolving/stopped; cancellation/failure/success. Pair/exchange claim must prevent duplicate scans, issued credential must be cleaned up on failed activation. ios/AidenOnTheGo/Features/Remote/AidenPairingView.swift:113; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenPairingScreen.kt:98; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenNearbyDesktops.kt:11; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenQRCodeScanner.kt:73 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:N14 Native approval and question recovery 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. None/pending/responding/withdrawn/terminal; snapshot generation/in-flight owner; same-key response attempts. Delayed snapshot must not resurrect answered or superseded prompt; server expiry and user response race. Answer authority differs for owned and foreign runs. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1546; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4350; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4433; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4931; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5007; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:133; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:153; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2226; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2276; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenApprovalActions.kt:37 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:N24 Bot actions and per-field rollback 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Action in-flight set, retained key/payload per question/approval/handoff/issue/proposal, stop/resume intent none/requested/acknowledged. Rollback only if field-write counter unchanged; late failed action cannot erase newer authoritative SSE frame. Resume and unpause are different operations. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1247; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1254; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1291; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2095; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2134; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2278; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2625; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2666; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:584; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:588; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1384; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1465; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1501; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1596 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:N26 Bot create/profile/access optimistic saves 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Create draft/pending/uncertain/recoverable; editing authoritative baseline/optimistic draft/saving/conflict/failed; pause/delete pending. Revision/context guards; current Bot detail is independent from list cache and uncertain creation key. ios/AidenOnTheGo/Features/Bots/AidenBotCreateView.swift:86; ios/AidenOnTheGo/Features/Bots/AidenBotProfileView.swift:28; ios/AidenOnTheGo/Features/Bots/AidenBotAdvancedView.swift:4; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotsViewModel.kt:26; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotEditorScreen.kt:48; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotProfileScreen.kt:74; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOptimisticSaves.kt:28 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:N34 Native workspace environment/files/git/providers 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. Read/loading/cache/error × selected tab/file/folder/page × mutation pending/confirmation. Opaque capabilities and request contexts scope folder/file navigation; stale selection response cannot replace current owner. ios/AidenOnTheGo/Features/Remote/AidenWorkspaceEnvironmentView.swift:134; ios/AidenOnTheGo/Features/Remote/AidenProvidersView.swift:5; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:4834; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:4920; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceEnvironmentScreen.kt:65; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenGitScreen.kt:55; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenProviderSettings.kt:55 docs/audits/implicit-state-machines-clients-2026-11-04.md +1 T1 Authorization, consent, revocation and capability ownership P2 clients:N38 Android external-new-chat consent 4 4 4 3 A stale or misbound approval can authorize effects for the wrong run, document, device or policy generation. pending target→approved target→active consumed target; new link/reject/accept/consume/reset. Approval is target-scoped, not a global bypass; duplicate external intent and app recreation must not auto-create chat. android/app/src/main/java/sbtbiswas/AidenOnTheGo/notifications/AidenNewChatLinkConsent.kt:23; android/app/src/main/java/sbtbiswas/AidenOnTheGo/MainActivity.kt:53 docs/audits/implicit-state-machines-clients-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M011 I Chat deletion saga: reconciliationRequired × chatRemoved × rollForwardPublished × deletionIsPending 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Journal/delete/side-effect cleanup/recovery must roll forward after durable deletion; failure before publication differs from uncertain publication. main/services/chat-application-service.ts:166; main/services/chat-application-service.ts:340 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M026 I Bot deletion/restart recovery: deleted fence plus durable pending-delete file and ordered cleanup effects 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Mark before destructive work, destroy harness, delete owned records, remove pending marker; restart must finish deletion, never reopen a half-deleted Bot. main/services/bot-runtime/bot-session-service.ts:402; main/services/bot-runtime/bot-session-service.ts:414; main/services/bot-runtime/bot-session-service.ts:843 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M147 I Image consent/export/workflow storage: consent entries one-use/expiry, export pending/inFlight/sweep, workflow serialized writes/unreadable fences 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Grant/consume/revoke; export/cache expiry; staged document publication/recovery; late file creation must not survive revoked owner unexpectedly. main/services/create-images/consent-core.ts:18; main/services/create-images/image-export.ts:201; main/services/create-images/workflow-store.ts:113 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M152 H Managed first-message worktree: pending/failed/ready plus preparing/fetching/creating progress, persistent request key and writes chain 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Prepare/retry/reconcile existing checkout/commit; retry must adopt only matching identity rather than create duplicate branch. main/services/first-message-worktree.ts:39; main/services/first-message-worktree.ts:99; main/services/first-message-worktree.ts:285; main/services/first-message-worktree.ts:299; main/services/first-message-worktree.ts:328; main/services/workspace-worktree-application-service.ts:407 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M153 H Managed worktree deletion: prepared→quarantined→checkout_cleanup_started→checkout_complete→admin_cleanup_started→filesystem_complete/needs_review; path moved flags and journal 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Authorize/quarantine/delete/recover/metadata finalization; uncertain filesystem identity routes to review, never infer safe deletion from absence alone. main/services/git.ts:5028; main/services/git.ts:5088; main/services/git.ts:5208; main/services/git.ts:5480; main/services/git.ts:5586; main/services/managed-worktree-remover.ts:310 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M154 H Managed worktree snapshot/restore: creating/ready/restoring/expired; restore checkout_planned→checkout_created→snapshot_applied→complete 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Snapshot/delete/restore/restart/expire; planned checkout adoption verifies identity and publication journal retains crash position. main/services/managed-worktree-snapshot.ts:67; main/services/managed-worktree-restore.ts:171; main/services/managed-worktree-restore.ts:219; main/services/managed-worktree-restore.ts:265; main/services/managed-worktree-restore.ts:281; main/services/managed-worktree-restore.ts:295 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M155 I Git operation concurrency/transactions: read flights/cache/mutation epochs/per-common-dir mutation tails; index transaction/head guard/ref-update attempted/confirmed 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Read/mutate/cancel/commit/push/reconcile; stale cached read invalidated after mutation, external push uncertainty cannot be reported as unexecuted. main/services/git.ts:1023; main/services/git.ts:1515; main/services/git.ts:2242; main/services/git.ts:2322; main/services/git.ts:2467; main/services/git.ts:2621; main/services/git.ts:3367 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M157 I Generic data store publication/recovery: unloaded/loading/loaded × corrupt/unsafe × mutation queue; receipt not-published/uncertain/published; live held files 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Read/reload/mutate/stage/fsync/rename/recover; uncertain publication cannot safely rollback in-memory authority as if no write occurred. main/services/data-store.ts:85; main/services/data-store.ts:112; main/services/data-store.ts:329; main/services/data-store.ts:448; main/services/data-store.ts:501; main/services/data-store.ts:604 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M158 I Chat store migration/maintenance: initialized × reconcileNeeded × exclusive, maintenance promise and image-sweep timer/running 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Load/migrate/reconcile/write/cleanup; one maintenance owner and no normal reads through unreconciled data. main/services/chat-store-core.ts:182; main/services/chat-store-core.ts:258; main/services/chat-store-core.ts:873 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M187 I Subagent workspace-write transaction: authorized calls/reserved tool IDs/lifecycles × shuttingDown, retained/commitConfirmed/cleanupPreserved 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Prepare approval and helper transaction, consume one-shot authorization, commit/finalize, preserve recovery on uncertain commit; release workspace admission only after helper cleanup. main/services/subagents/subagent-workspace-write.ts:457; main/services/subagents/subagent-workspace-write.ts:463; main/services/subagents/subagent-workspace-write.ts:707; main/services/subagents/subagent-file-mutator-io.ts:161 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 backend:M188 I Subagent shell dispatch transaction: pending approval, active abort controllers, shuttingDown × dispatchStarted × terminal 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Revalidate command/root/authority, consume consent, durable dispatch marker, run, proof of cleanup then finish; unconfirmed cleanup becomes unknown once, pre-dispatch refusal cancels. main/services/subagents/subagent-shell.ts:302; main/services/subagents/subagent-shell.ts:522; main/services/subagents/subagent-shell.ts:557; main/services/subagents/subagent-shell.ts:572; main/services/subagents/subagent-shell-runner-io.ts:230 docs/audits/implicit-state-machines-backend-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 cli-native:C14 CLI remote chat deletion recovery 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. persisted deletion tombstone → private history cleanup → tombstone removed startup replay, chat delete, cleanup failure An unfinished deletion is replayed before normal serving. Shared chat application, stream journal, read-marker and triage machines are reused, not new independent implementations. packages/cli/src/remote-chats.ts:23 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 cli-native:C24 Cross-process lease and JSON publication 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. guard acquired → stale owner removed → owner published → held → released; queued mutation → lease → publication acquire/release/update, failure, currentness check released makes release idempotent; failed publication releases guard; serialized tails plus filesystem lease guard updates. packages/cli/src/state.ts:48; packages/cli/src/state.ts:98; native/lease-flock/main.c:6 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 cli-native:N06 Native file mutation transaction 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. idle → inspected → prepared → committed with recovery → finalized/preserved; precommit cancel; indeterminate durability inspect/prepare/prepare-inspected/commit/finalize/preserve/cancel/close active/prepared/committed/recovery_unlinked/commit_parent_synced encode product state; identity, digest and request ID guard transitions. native/subagent-file-mutator/main.c:44; native/subagent-file-mutator/main.c:1242; native/subagent-file-mutator/main.c:1619 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 cli-native:N07 Native managed-worktree removal and resume 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. quarantined → isolated → manifest persisted → authorization barrier → deleting → manifest finalizing/deleting → removed or recoverable residue fresh/resume/remove, continue/resume digest, identity change, partial failure Directory identity and durable manifest bind deletion; pre-existing isolated children require explicit matching resume authority. native/worktree-remover/main.c:1104; native/worktree-remover/main.c:1570; native/worktree-remover/main.c:720 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 cli-native:N08 Native editor/save publication 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. source opened/verified → content staged → exchange/publication → recovery cleanup or preserved error edit/create/save, source identity/hash mismatch, write/fsync failure Editor publication checks source identity/digest; create/save use confined paths and their own publication rules. Recovery and durability handling differ by operation. Transaction machine, not a UI editor state. native/worktree-file-io/main.c:337; native/worktree-file-io/main.c:495; native/worktree-file-io/main.c:560 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +2 T1 Irreversible file, worktree and deletion transactions P4 clients:C62 Git commit/push/branch/clone workflows 4 3 4 4 Publication, durability and cleanup are different commit boundaries; incorrect rollback or retry can lose or corrupt data. Preparing/validating/running/cancelling/success/error; confirmation and dirty/worktree gates; tool activity debounces refetch. UI cancellation versus process settlement and captured repository ownership are hotspots. renderer/components/git-commit-dialog.tsx:18; renderer/components/git-push-dialog.tsx:35; renderer/components/git-branch-picker.tsx:58; renderer/main/peer-project-clone-dialog.tsx:22; renderer/lib/git-query-sync.ts:51 docs/audits/implicit-state-machines-clients-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M007 I First-send commit: committed × workSettled plus turn lease/worktree receipt 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Commit/handoff/failure/owner invalidation must distinguish durable append from safe retry; late IO retains ownership. main/services/chat-first-message-commit.ts:76; main/services/chat-generation-start.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M027 I Bot request/reply dedupe: requestId→submission, bounded resume/dismiss answers, hidden submissions, blocked readmission 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Duplicate send/resume/dismiss replays outcome; awaitReply must inspect paused scheduling without wait() accidentally starting it. main/services/bot-runtime/bot-session-service.ts:397; main/services/bot-runtime/bot-session-service.ts:441; main/services/bot-runtime/bot-session-service.ts:590; main/services/bot-runtime/bot-session-service.ts:776; main/services/bot-runtime/bot-session-service.ts:858 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M030 I Bot handoff registry and result idempotency 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Waiting → done/skipped/withdrawn; notes allowed only for appropriate card kinds; settled rule row is once per producing assistant call, not globally per reusable toolCallId. main/services/bot-runtime/bot-handoffs.ts:74; main/services/bot-runtime/bot-handoffs.ts:156 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M034 I Bot starter/idempotent self-introduction 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Creation-key reservation → Bot creation/access → stable intro request → introduced; repeated preset starts must not duplicate Bot or intro. main/services/bot-runtime/bot-starter.ts:63; main/services/bot-application-service.ts:289 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M046 H Delivery funnel 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. new → deferred/suppressed/sent, per-channel delivery flags and dedupe/digest records; quiet hours/day cap/flush timer govern transitions. main/services/bot-delivery/funnel.ts:63; main/services/bot-delivery/funnel.ts:77; main/services/bot-delivery/funnel.ts:111; main/services/bot-delivery/funnel.ts:150; main/services/bot-delivery/funnel.ts:219; main/services/bot-delivery/gate.ts:80 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M058 H Durable idempotency ledger: in_flight → fulfilled/rejected; unknown-outcome stays in_flight; persisted clock high-water and capacity 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Execute/replay/reconcile/prune/restart; uncertainty must never reopen effect execution, stale clock cannot resurrect expired keys. main/services/aiden-remote-operation-contract.ts:455; main/services/aiden-remote-operation-contract.ts:490; main/services/aiden-remote-operation-contract.ts:790 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M059 I Durable operation ownership registry: unowned → owned by operation → complete/reconciled; restoration and bounded capacity 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Expected revision + owner proof guard finish; not equivalent to transient request completion. main/services/aiden-remote-operation-contract.ts:863 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M075 H Telegram durable Bot reply outbox: awaiting/interrupted/pending/sending/sent/failed/dismissed, redelivered flag 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Submit/watch reply/pause/unpause/restart/deliver; crash in sending is ambiguous and only bounded redelivery is allowed. main/services/telegram/bot-reply-outbox.ts:198; main/services/telegram/bot-reply-outbox.ts:275; main/services/telegram/bot-reply-outbox.ts:328; main/services/telegram/bot-reply-outbox.ts:399; main/services/telegram/bot-reply-outbox.ts:446 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M108 H Durable subagent effect/approval store: approval prepared/authorized/consumed/cancelled; effect prepared/dispatch_started/terminal/unknown; manifest revision CAS 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Persist prepare → dispatch marker → finish, restart reconciliation; no fresh retry after ambiguous external dispatch. main/services/subagents/subagent-effect-v2.ts:11; main/services/subagents/subagent-run-store-v2-core.ts:598 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 backend:M172 H App-control side-effect receipts: pending operation→outcome_unknown/applied/already_set, serialized authority revision 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Read/revalidate/change/verify/persist; transport or publication error must preserve unknown result instead of allowing blind retry. main/services/app-controls-core.ts:230; main/services/app-controls-core.ts:321; main/services/app-controls-core.ts:339; main/services/app-controls-core.ts:358; main/services/app-controls-core.ts:370 docs/audits/implicit-state-machines-backend-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 clients:C12 Remote first-chat transaction 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Per-host selected target/draft/create intent/send intent; create and first turn can independently have unknown outcomes. Folder/workspace selection, create/send/retry/dismiss, host switch; host-keyed memory and ledger preserve recovery through navigation. renderer/lib/hosts/remote-new-chat.ts:133; renderer/lib/hosts/remote-new-chat.ts:201; renderer/main/remote-new-chat-view.tsx:61 docs/audits/implicit-state-machines-clients-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 clients:C16 Local and paired Bot sends/echo recovery 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Pending send/morph/echo, unsettled same-key send, hidden interrupted/failed turn, retry request maps, operation counters, retained answered prompts/handoffs. Receipt, live echo, timer, retry/remove/navigation reconcile them; identical-looking send text is not sufficient identity. renderer/main/bots/bot-chat-pane.tsx:959; renderer/main/bots/bot-chat-pane.tsx:970; renderer/main/bots/bot-chat-pane.tsx:975; renderer/main/bots/bot-chat-pane.tsx:1224; renderer/main/remote-bot-chat-view.tsx:96; renderer/main/remote-bot-chat-view.tsx:133; renderer/main/remote-bot-chat-view.tsx:138 docs/audits/implicit-state-machines-clients-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 clients:C69 Desktop native app-control cards 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Hidden/visible→snapshot loading; confirmation→applying→known receipt/unknown outcome/error→refresh. Owner epoch and synchronous applying ref; retry retains exact operation ID and expected revision; checking unknown outcome must not repeat mutation. renderer/components/app-controls-panel.tsx:125 docs/audits/implicit-state-machines-clients-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 clients:N06 Native workspace/chat metadata mutations 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Create/rename/remove in-flight, retained rename overlay, coherent revision refresh required for next mutation, managed-worktree delete uncertain key. Mutation receipt and next GET are independent; never replay with arbitrary fresh key when outcome is unknown. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:987; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:998; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1076; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:481; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:558; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:613; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceHomeViewModel.kt:41; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenRemoteCoordinator.kt:38 docs/audits/implicit-state-machines-clients-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 clients:N22 Bot durable outbox delivery 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. sending/sent(submission)/failed/expired × request frozen/keepsKey/deferred/attempt count/echoed/claimed entry/queued/unheld/taken-before-visit/attachmentsGone. FIFO sends never overtake deferred head. Ambiguous failure preserves key and bounded retry; definite refusal permits new request; one transcript entry settles one message; expired uploads require reattach. iOS full delivery branches read; Android state and corresponding methods verified. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:449; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1751; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1896; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1912; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2030; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2547; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOutbox.kt:163; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:992; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1109; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1233; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1254; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1351 docs/audits/implicit-state-machines-clients-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 clients:N23 Bot outbox ownership/restore/purge/disk write 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Cache adopted owner, disk restoring/restored, coalesced writes, pairing known/revoked, stuck files, purge generation/released. Restore must finish before writes and must not reintroduce revoked data; one view owns shared outbox. Pending-create recovery has a separate disk slot. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:536; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:602; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:637; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:706; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:809; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1843; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2070; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:578; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:726; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:1362; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOutbox.kt:183 docs/audits/implicit-state-machines-clients-2026-11-04.md +3 T2 Unknown remote outcomes, idempotency and durable outboxes P3 clients:N36 Native app-control panel receipts/cache 4 3 4 4 A lost response can hide an accepted mutation; a fresh retry can duplicate execution across restart or re-pairing. Snapshot loading/current, confirmation, pending operation, applied/already-set/outcome-unknown retry. Snapshot generation/read serial rejects stale reads; retry operation preserves expected revision and semantic action. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4069; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4080; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:11505; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenAppControls.kt:49; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/NativeAppControlPanel.kt:29 docs/audits/implicit-state-machines-clients-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M005 I Generation lifecycle: initializing map → active map → removed, crossed with cancelRequested, rendererDetached, inputClosed, quitInProgress, prompt attendance and computer-use activation 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Start, stream events, cancel, document loss, guidance, delete, quit; cancellation is not settlement, detach does not necessarily cancel work. Admission and cleanup cross several services. main/services/llm-client.ts:600; main/services/llm-client.ts:626; main/services/llm-client.ts:901; main/services/llm-client.ts:5221; main/services/llm-client.ts:5353; main/services/llm-client.ts:5466 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M006 I Chat append-to-generation lease: authorityActive × asyncSettled × append/skill slot/byte reservations; owner reconciliation fence 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Reserve → append → settle → synchronous handoff → release. Expiry revokes authority but retains resource accounting until admitted IO settles; indeterminate append fences owner. main/services/chat-turn-admission.ts:35; main/services/chat-turn-admission.ts:80; main/services/chat-turn-admission.ts:197; main/services/chat-turn-admission.ts:315 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M008 I Mid-run input admission: per-stream serialized append and Pi steer/follow-up receipt 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Recheck generation identity, deletion, ownership, inputClosed and cancellation after awaits; committed user input must not be replayed as fresh input on a late failure. main/services/chat-run-input-admission.ts:73; main/services/chat-run-input-admission.ts:94 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M012 I Pi runtime harness: running/managedRunning, managedQueueOpen, pendingAbort, appCancelRequested, shutdownInterrupted, disposed, durable operation and tool maps 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Prompt/steer/follow-up/abort/compaction/end/close. Managed queue closure, persistence completion and model completion are different transitions. main/services/pi-agent-runtime-harness.ts:866; main/services/pi-agent-runtime-harness.ts:916; main/services/pi-agent-runtime-harness.ts:2806; main/services/pi-agent-runtime-harness.ts:2814; main/services/pi-agent-runtime-harness.ts:2911; main/services/pi-agent-runtime-harness.ts:2944 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M015 H Host-run registry: working/needs_approval/needs_input/done/failed/cancelled; prompt IDs, pending terminal outcome, source ownership 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Generation/Bot events, approval/question changes, ownership loss, expiry; pending prompts override busy display and terminal outcomes must settle exactly once. main/services/host-run-registry.ts:250; main/services/host-run-registry.ts:292; main/services/host-run-registry.ts:560 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M021 H Ephemeral side-question conversation: per-chat thread fingerprint, active operation/controller and terminal event 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Start/cancel/clear/delete/shutdown; independent of main turn but bound to owner document and current model. main/services/rpiv-btw/service-core.ts:89; main/services/rpiv-btw/service-core.ts:101; main/services/rpiv-btw/service-core.ts:277; main/services/rpiv-btw/service-core.ts:289; main/services/rpiv-btw/operation-registry.ts:10 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M023 I Harness host: per-Bot open/closing/deleted sets, serialized lifecycle tails, admitted operations, shutDown flag, idle timer 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Open/touch/idle-close/suspend/destroy/shutdown; no reopen while close owns lock, no orphan deletion while live profile lease is held. main/services/bot-runtime/harness-host.ts:198; main/services/bot-runtime/harness-host.ts:215; main/services/bot-runtime/harness-host.ts:297; main/services/bot-runtime/harness-host.ts:323; main/services/bot-runtime/harness-host.ts:364; main/services/bot-runtime/harness-host.ts:451; main/services/bot-runtime/harness-host.ts:514 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M024 H Bot session state: idle/running/interrupted/needs_model/model_error/unavailable/paused projected from harness plus pause store, deleted/suspending/blocked sets 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Send, Resume, Dismiss, Stop, pause/unpause, model changes and restart; displaying paused does not mean harness shutdown finished. main/services/bot-runtime/bot-session-service.ts:69; main/services/bot-runtime/bot-session-service.ts:378; main/services/bot-runtime/bot-session-service.ts:494; main/services/bot-runtime/bot-session-service.ts:776; main/services/bot-runtime/bot-session-service.ts:947 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M035 H Bot lifecycle journal saga 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Pending operation/stage → completed; Bot/chat create/copy/delete/model-update and replay lookups serialize durable stages and expected identities. main/services/bot-lifecycle-journal-core.ts:10; main/services/bot-lifecycle-journal-core.ts:22; main/services/bot-lifecycle-journal-core.ts:423; main/services/bot-lifecycle-journal-core.ts:465; main/services/bot-application-service.ts:289 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M100 I Subagent supervisor/tree: treeExpired × treeBudgetExhausted, live batch stop hooks, children launched, deadline/settlement timers 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Spawn/delegate/result/timeout/budget/stop; parent settlement and proof child processes are gone are separate facts. main/services/subagents/subagent-supervisor-core.ts:382; main/services/subagents/subagent-supervisor-core.ts:1072; main/services/subagents/subagent-supervisor-core.ts:1089; main/services/subagents/subagent-supervisor-core.ts:1106 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M101 H Nested concurrency scheduler: queued/running/waiting/settled plus tree active/waiting/terminal and capacity counters 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Parent delegates/releases slot, child runs, parent resumes, cancel/terminal; no slot leak or deadlock while parent waits for child. main/services/subagents/subagent-nesting-core.ts:725; main/services/subagents/subagent-nesting-core.ts:746; main/services/subagents/subagent-nesting-core.ts:865; main/services/subagents/subagent-nesting-core.ts:951; main/services/subagents/subagent-nesting-core.ts:1020; main/services/subagents/subagent-nesting-core.ts:1098 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M105 H Subagent control/steering/retry registry: live/terminal record, bounded pending steering/waiters/retry identity allocation 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Wait/steer/stop/retry/terminal/evict; owner and revision proofs, first terminal wins, retry creates fresh lineage. main/services/subagents/subagent-control-v2.ts:235; main/services/subagents/subagent-control-v2.ts:375; main/services/subagents/subagent-control-v2.ts:518; main/services/subagents/subagent-control-v2.ts:554; main/services/subagents/subagent-control-v2.ts:595; main/services/subagents/subagent-control-main.ts:78 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M106 I Background subagent coordinator: active map + queued start/child binding/abort controller/settled bit 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Durable accept → execute → terminal; deletion/revocation/shutdown stop child and persist terminal evidence. main/services/subagents/background-subagent-coordinator-v2.ts:100; main/services/subagents/background-subagent-coordinator-v2.ts:265; main/services/subagents/background-subagent-coordinator-v2.ts:350 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 backend:M178 I Remote device authorization/revocation barrier: blocked device set, active authorization counts, waiters and pending revocation promises 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Acquire authorization → release; revoke blocks new acquisitions, drains existing authorizations, persists revoke; failed write can release temporary block but cannot pretend persisted revoke. main/services/aiden-remote-state.ts:608; main/services/aiden-remote-state.ts:996; main/services/aiden-remote-state.ts:1027; main/services/aiden-remote-state.ts:1037 docs/audits/implicit-state-machines-backend-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 cli-native:C09 Daemon turn admission and handoff 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. idle → reserved → active → cancellation requested → settled; closed/deleting block entry beginChatTurn, start/handoff, cancelChat, lease release, stop Three distinct busy representations (reserved, admission, active); idle waiters must observe both reservation and execution settlement. packages/cli/src/daemon-chats.ts:69; packages/cli/src/daemon-chats.ts:82; packages/cli/src/daemon-chats.ts:128 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 cli-native:C10 Daemon generation execution and persistence 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. resource preparation → session bound → prompting/streaming/tools → final persisted or partial persisted → disposed provider/tool events, acceptance, owner invalidation, timeout, cancel, persistence error persisted flag prevents duplicate assistant append; terminal notification and cleanup occur at different boundaries. packages/cli/src/daemon-chats.ts:147; packages/cli/src/daemon-chats.ts:297 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 clients:C02 Queued admission / steering 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Claimed → admitted/sent, deferred, or failed; waits for run admission with bounded retry, returns unsent guidance to draft. Queue state and host admission are separate authorities; stale chat/input owners must not consume another draft. renderer/lib/chat-message-queue.ts:255; renderer/lib/chat-message-queue.ts:318; renderer/lib/chat-message-queue.ts:386; renderer/lib/use-chat-message-queue.ts:24 docs/audits/implicit-state-machines-clients-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 clients:C03 Desktop generation orchestration 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Starting/live/stopping/retry-wait/reveal-draining/persisted plus approval/question/tool/model-loading flags. Start callbacks, deltas, terminal events, Stop, route change, resume/retry, delayed reveal. generationIntent/chatVisit/ref ownership fence async results; local render state alone cannot fence same-tick actions. renderer/main/chat-pane.tsx:769; renderer/main/chat-pane.tsx:809; renderer/main/chat-pane.tsx:849; renderer/main/chat-pane.tsx:1485; renderer/main/chat-pane.tsx:1935 docs/audits/implicit-state-machines-clients-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 clients:C04 Generation IPC subscription 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Subscribed before invocation → projecting → done callback settling → disposed; reset clears partial/reasoning; error disposes immediately. Stream ID filters every event. Lifecycle-detached versus explicit user-stop flags in IPC distinguish UI teardown from cancellation of main-owned work. renderer/lib/generation-stream.ts:98; renderer/lib/generation-stream.ts:116; renderer/lib/generation-stream.ts:167; renderer/lib/ipc.ts:2133 docs/audits/implicit-state-machines-clients-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 clients:C05 Detached lifecycle registry and fallback settlement 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Owned/attached → detached/projected → terminal-read pending → reconciled/released, with fallback registries/in-flight sets and bounded exponential retry. Capture stream IDs before reads so a stale reconciliation cannot clear replacement work; retain live output until saved transcript is ready. renderer/lib/chat-terminal-sync.ts:34; renderer/lib/chat-terminal-sync.ts:225; renderer/lib/chat-terminal-sync.ts:386; renderer/lib/chat-terminal-sync.ts:674; renderer/lib/chat-terminal-sync.ts:742 docs/audits/implicit-state-machines-clients-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 clients:C11 Remote queued-turn fence 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. No fence → pending receipt (runId=null) → accepted run fence → released by same-run terminal/feed state or 120s stall. Refused send restores previous fence by object identity. A generic idle row is not evidence that the accepted run ended. renderer/lib/hosts/remote-queue-fence.ts:12; renderer/lib/hosts/remote-queue-fence.ts:39; renderer/lib/hosts/remote-queue-fence.ts:63; renderer/main/remote-chat-view.tsx:445 docs/audits/implicit-state-machines-clients-2026-11-04.md +4 T2 Generation admission, ownership, handoff and cancellation P1 clients:N15 Native run-input guidance and Stop 4 3 4 3 Premature release or stale ownership can permit overlapping execution, wrong-chat effects or unbounded retained work. Run input mode/last attempt/in-flight/receipt; draft consumed/restored; Stop pending/terminal. One cancellation per stream/intent; unknown input response retains key; same draft baseline/remainder decides restoration without destroying new typing. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3891; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3905; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3967; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4323; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4340; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:138; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:148; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2353; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2373; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2747 docs/audits/implicit-state-machines-clients-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M087 I MCP stdio child teardown: live process ownership, groupReaped, exit-hook installation 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Spawn/close/exit/shutdown; process-group cleanup is separate from protocol close. main/services/mcp-stdio-transport.ts:31; main/services/mcp-stdio-transport.ts:107 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M089 I ACP runtime session pool: bindings promises/live set/starting reservations/inflight operations × disposed/admissionClosed 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Prompt reuse/create/makeRoom/drop/abort/close; reserve starting capacity before await, validate host/session fingerprint before reuse. main/services/acp/runtime.ts:164; main/services/acp/runtime.ts:639; main/services/acp/runtime.ts:658; main/services/acp/runtime.ts:1039; main/services/acp/runtime.ts:1058 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M090 I ACP launcher/process/connection: live and starting sets, closed; process settled/closing; connection exitError and exit waiters 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Launch/cancel/exit/close/shutdown fanout; shutdown waits launches, one exit notification rejects pending RPCs, pid ledger tracks surviving groups. main/services/acp/launcher.ts:56; main/services/acp/process.ts:77; main/services/acp/connection.ts:56; main/services/acp/pid-ledger.ts:140 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M102 I Child runtime registry/quarantine: children registry × shuttingDown × quarantined deployments 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Register/start/cancel/settle/abort by chat/generation/workspace/shutdown; quarantined process cleanup must block unsafe reuse. main/services/subagents/child-agent-runtime.ts:150; main/services/subagents/child-agent-runtime.ts:481 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M103 I Isolated inference process: terminal × exited × workerMessageObserved × auth failure, stopping promise, cleanupHealthy and active controllers 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Worker messages/exit/error/abort/hard kill/retry; result terminal does not prove process gone; failed proof stays pending/fail-closed. main/services/subagents/subagent-inference-process-core.ts:94; main/services/subagents/subagent-inference-process-core.ts:133; main/services/subagents/subagent-inference-process-core.ts:149; main/services/subagents/subagent-inference-process-core.ts:240 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M112 H Background shell jobs: running→exited/failed/stopped with stop promise, adopted group and pid identity, port scan and durable running record 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Launch/adopt/exit/stop/chat delete/quit/restart cleanup; process-group proof, not only leader exit, controls completion. main/services/follow-through/background-jobs.ts:280; main/services/follow-through/background-jobs.ts:339; main/services/follow-through/background-jobs.ts:734; main/services/follow-through/background-jobs.ts:765; main/services/follow-through/background-jobs.ts:790; main/services/follow-through/background-jobs.ts:889; main/services/follow-through/background-jobs.ts:981 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M116 H Computer-use controller: new/starting/ready/poisoned/closed, startup/close promises, closeFailed, driver calls and lifecycle abort 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Lazy first action/start error/timeout/driver loss/close; poisoned controller cannot silently reuse possibly unsafe state. main/services/computer-use/controller.ts:838; main/services/computer-use/controller.ts:1048; main/services/computer-use/controller.ts:1196; main/services/computer-use/controller.ts:2035 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M117 H CUA session/transport: new/connecting/ready/broken/closed and started/didNotifyClose/closePromise 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Connect/list tools/call/error/timeout/close; serialized calls, exactly-once closure notification, drain failure breaks session. main/services/computer-use/session.ts:204; main/services/computer-use/session.ts:381; main/services/computer-use/session.ts:421; main/services/computer-use/session.ts:636; main/services/computer-use/session.ts:661 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M118 I CUA host launch/cleanup: sessions/runtimes/pendingLaunches, shutdown controller, pending cleanup directories/retry counts 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Launch/readiness/cancel/close/shutdown/retry cleanup; don't lose runtime ownership when session creation fails mid-launch. main/services/computer-use/host.ts:148; main/services/computer-use/host.ts:206; main/services/computer-use/host.ts:218; main/services/computer-use/host.ts:419; main/services/computer-use/host.ts:485 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M121 H Bot VM lifecycle and slot scheduler: stopped/waiting_for_slot/starting/running/stopping/stale × start/stopping promises × leases/idle timer; baseHoldsSlot/shuttingDown 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Acquire/release/start readiness/idle stop/pause/base setup/quit; slot not released until VM state confirmed; failed stop may return to running. main/services/bot-computers/host.ts:227; main/services/bot-computers/host.ts:265; main/services/bot-computers/host.ts:513; main/services/bot-computers/host.ts:626; main/services/bot-computers/host.ts:683; main/services/bot-computers/host.ts:731; main/services/bot-computers/host.ts:1543 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M122 H Bot base setup/update: setupTask/setupAbort, progress downloading/verifying/provisioning, current/staging base and stale clones 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Explicit setup/update/cancel/failure/recovery; validate pinned image before base activation and keep operation off startup paths. main/services/bot-computers/host.ts:227; main/services/bot-computers/host.ts:1197; main/services/bot-computers/host.ts:1672; main/services/bot-computers/restore-image-download.ts:89; main/services/bot-computers/provision.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M125 I Browser tab/workspace lifecycle: workspace/tab/session/popup-owner maps, loaded/deletingProfiles/workspaceAccess, navigation/crash generation 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Open/navigate/crash/reload/close/profile deletion/access change; tab existence does not imply active agent authority. main/services/browser/service.ts:286; main/services/browser/service.ts:757; main/services/browser/service.ts:1239 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M126 I Browser per-workspace action queue/cancellation: serial tail plus AbortController 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Tool action admitted→running→settled, stop cancels current work and queue freshness guards stale actions. main/services/browser/core.ts:311; main/services/browser-tools.ts:199; main/services/browser/service.ts:2630; main/services/browser/service.ts:2945 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M130 I Local/SSH device helper host: start lock, stopped/activated, stop promise, process readiness and reconnect callbacks 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Explicit start/cancel/exit/health failure/reconnect/stop; helper identity and ownership verified before terminating process groups. main/services/devices/local-device-host.ts:337; main/services/devices/local-device-host.ts:629; main/services/devices/ssh-device-host.ts:268; main/services/devices/ssh-device-host.ts:614 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M156 I Terminal session/process ownership: session map, pending workspace exits, unverifiable workspaces, webContents epochs and exited flag 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Spawn/write/resize/owner loss/exit/workspace remove/quit; process-tree settlement needed before destructive worktree operation. main/services/terminal.ts:245; main/services/terminal.ts:418; main/services/terminal.ts:493; main/services/terminal.ts:640 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 backend:M170 I Bounded child process/request settlement: settled × aborted/timedOut/outputLimitExceeded, termination promise, drain timer and identity-backed process ownership 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Spawn/data/drain/exit/error/deadline/abort/kill; one response, continued cleanup after timeout, process exit proof independent of returned error. main/shared/process-group.ts:76; main/shared/process-group.ts:132; main/services/bounded-shell-command.ts:90; main/services/bounded-shell-command.ts:204; main/services/git-clone-runner.ts:120; main/services/bot-computers/bounded-process.ts:71 docs/audits/implicit-state-machines-backend-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:C18 CLI child inference and cleanup 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. forked → started → running/tool pending → done received → child closed; failure → TERM → KILL → tools drained IPC events, budgets, cancellation, error, close done, failure, activeTools and toolAbort jointly determine successful settlement; done alone is insufficient without clean child close/final answer. packages/cli/src/subagent-process.ts:13; packages/cli/src/subagent-process.ts:27; packages/cli/src/subagent-process.ts:80 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:C19 CLI worker RPC 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. not started → started/session preparing → prompting ↔ parent tool RPC pending → finished/disconnected start/tool-result/cancel/disconnect started gates duplicate start; per-ID pending map owns tool reply; finished changes disconnect handling. packages/cli/src/subagent-worker.ts:11 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:N01 Native CUA broker/bridge handshake 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. lease listener → authenticated bridge lease → matching control peer → supervision armed → driver constrained → acknowledged → ready relay → teardown socket peers, handshake frames, deadline, EOF/signal Same audit token on both sockets; no ready relay before both supervision acknowledgements. native/computer-use-broker/src/runtime.rs:423; native/computer-use-broker/src/runtime.rs:641 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:N02 CUA containment guard 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. dormant → ready → awaiting authenticated arm → liveness monitoring → TERM grace → KILL arm byte, deadline, death pipe, lease EOF/payload/error Guard occupies the process group; any lease payload revokes liveness, avoiding delayed numeric-PGID reuse. native/computer-use-broker/src/guard.rs:100; native/computer-use-broker/src/guard.rs:157; native/computer-use-broker/src/guard.rs:234 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:N03 CUA driver launch supervision 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. fallback/watchdog ready → entering launch → returned PID → stopped/identified/contained → launcher joined → resumed or supervision failed private byte protocol, spawn return, timeout, audit-token/identity checks Explicit wire phase bytes with transitions distributed through launcher/watchdog processes; separate from broker ready state. native/computer-use-broker/src/supervisor.rs:9; native/computer-use-broker/src/driver.rs:1 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:N04 CUA JSON-RPC pending tool-list filter 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. request unseen → allowed list request pending → response matched/filtered → removed client/driver frames, duplicate or unsupported request Pending request-ID set and bounded line framing determine what may traverse privileged relay. Protocol machine. native/computer-use-broker/src/runtime.rs:365; native/computer-use-broker/src/jsonrpc.rs:1; native/computer-use-broker/src/lines.rs:1 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:N05 Native subagent shell execution 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. validated → spawned/contained → polling and capture → exited/signalled/cancelled/timed-out/overflow → cleanup confirmed or unconfirmed stdin lifetime, output, waitpid, deadline, process-group cleanup Child exit and descendant cleanup are separate facts; cleanup failure overrides otherwise successful outcome. native/subagent-shell-runner/main.c:228; native/subagent-shell-runner/main.c:388 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:N13 Signed iMCP child supervision 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. verified → launched → running → TERM/exit → group KILL → launcher exit signature checks, child run/error, termination source/handler Launch constraint binds executable identity; child exit also kills descendants retaining pipes. native/imcp-launcher/main.swift:40 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 cli-native:O01 Bounded-command occupied group guard 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. running → result reported/waiting release → terminating → TERM grace → KILL terminate/release IPC, parent disconnect, command error/close terminating makes teardown idempotent; result does not release descendant containment. Runtime support script. scripts/bounded-command-guard.mjs:15 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +5 T2 Child process, VM and native supervision lifetimes P5 clients:C43 Ghostty terminal lifecycle and input 4 3 4 4 Logical cancellation without confirmed physical teardown leaves tools, descendants, leases or computers active. Runtime loading/shared reference ownership; terminal created/attached/detached/exited/disposed; resize/frame scheduling; IME/key/mouse/selection/paste state; workspace session collection and split layout. UI hide does not necessarily end PTY. renderer/lib/ghostty-terminal/surface.ts:63; renderer/lib/ghostty-terminal/runtime.ts:3; renderer/lib/ghostty-terminal/core.ts:157; renderer/components/terminal-drawer.tsx:143 docs/audits/implicit-state-machines-clients-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 backend:M078 H Provider auth flow: no active session/authenticating/committing, pending prompt, timedOut/suppressNotifications, logoutInProgress/disposed 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Start/respond/cancel/owner loss/timeout/commit/logout/shutdown; committing is point of no return, cancellation may not claim credentials were not committed. main/services/provider-auth-flow-core.ts:476; main/services/provider-auth-flow-core.ts:557; main/services/provider-auth-flow-core.ts:603; main/services/provider-auth-flow-core.ts:672; main/services/provider-auth-flow-core.ts:695; main/services/provider-auth-flow-core.ts:922 docs/audits/implicit-state-machines-backend-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 backend:M082 I MCP OAuth operation ownership: interactive operations/generations/suspension counts 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Start/cancel/config-write/suspend/release; stale OAuth result cannot publish after configuration mutation. main/services/mcp-oauth-operation.ts:26; main/services/mcp-config-lease.ts:32 docs/audits/implicit-state-machines-backend-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 backend:M083 I MCP OAuth exchange/token session: exchangingCode × flowReadTokens, observed tokens/session binding, commitAttempted/redirected, cache generation 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Redirect/auth-code/refresh/save/revoke; compare token identity and generation before write, distinguish rejected grant from stale observer. main/services/mcp-oauth-provider-core.ts:172; main/services/mcp-oauth-provider-core.ts:234; main/services/mcp-oauth-provider-core.ts:689; main/services/mcp-oauth-session-cache.ts:38 docs/audits/implicit-state-machines-backend-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 backend:M084 I OAuth loopback receiver: closed × listening × answered + deadline 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Listen/callback/invalid request/timeout/abort; one valid answer and shutdown of listener on every terminal path. main/services/mcp-oauth-loopback.ts:100 docs/audits/implicit-state-machines-backend-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 backend:M085 I MCP admission and cleanup gates: admission unknown/empty/pending; exclusive tail and cleanup in-flight 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Mark mutation pending → reconcile → empty; startup uncertainty must not admit credential-dependent tools prematurely. main/services/mcp-admission-queue.ts:17; main/services/mcp-admission-queue.ts:57; main/services/mcp-admission-queue.ts:83; main/services/mcp-credential-cleanup.ts:158 docs/audits/implicit-state-machines-backend-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 backend:M163 I Configuration/credential migration/watch: seedPromise, secretMigrationComplete/deferred/promise, portable migration, pending reconciliation/tail/timer 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Load/unlock/import/watch event/reconcile/cancel; defer on locked store without falsely marking migration complete. main/services/config-store-core.ts:319; main/services/portable-config-core.ts:1348; main/services/portable-config-watch-core.ts:43; main/services/portable-config-watch-core.ts:89; main/services/portable-config-watch-core.ts:174 docs/audits/implicit-state-machines-backend-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 cli-native:C21 Terminal provider auth interaction 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. coordinator started → URL/device-code or prompt waiting → response → signed-in/cancelled/error → teardown auth notifications, readline answer, SIGINT Secret echo suppression and AbortController are coupled to prompt and terminal events; shared coordinator owns actual provider auth. packages/cli/src/auth.ts:51 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 cli-native:C25 Credential writer queue and contention 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. queued → lease retry/backoff → held → mutation → released; expired/superseded prior writer settlement, lock contention, deadline, isCurrent Per-file queue plus cross-process lease; identity check prevents old completion deleting a newer queue tail. packages/cli/src/credentials.ts:34 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 cli-native:C30 CLI Azure identity migration 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. legacy per-file identity → file lock/credential lease → reconciled current identity → atomic publication; divergent identities block migration pre-runtime migration, credential conflict, repeated startup Repeatable per-file migration; model endpoint and credential identity must remain aligned; this is a persisted migration transaction. packages/cli/src/azure-config-migration.ts:39 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 cli-native:C31 CLI provider credential migration/writer 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. queued → writer lease → absent-store initialization or legacy staging → encrypted replacement → operation → released credential read/list/modify/delete, legacy format, invalid entry, migration failure Validate all legacy entries before replacement; queue identity and writer lease prevent overlapping publication; stage removed in finally. packages/cli/src/provider-credentials.ts:9 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 clients:C50 Provider/Codex auth sessions 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Created/started/cancelRequested/disposed and backend auth phase; subscription precedes start, flow ID filters callbacks, terminal updates refresh credentials even if view detached, cancel may be refused as finishing. Both are distinct wrappers sharing a lifecycle shape. renderer/lib/provider-auth-session.ts:57; renderer/lib/provider-auth-session.ts:118; renderer/lib/provider-auth-session.ts:141; renderer/lib/codex-auth-session.ts:87; renderer/lib/codex-auth-session.ts:156; renderer/lib/codex-auth-session.ts:179 docs/audits/implicit-state-machines-clients-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 clients:C51 Provider setup/edit/discovery/key sharing 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Draft/validate/save/discover/auth/error plus confirmation and model visibility. Explicit foreground action authorizes fetching; view selection/request identity fences stale response. renderer/components/settings/providers-settings.tsx:57; renderer/components/settings/provider-editor.tsx:41; renderer/components/settings/builtin-provider-editor.tsx:28; renderer/components/settings/codex-provider-settings.tsx:32; renderer/components/settings/provider-connector-key-sharing.tsx:12; renderer/components/settings/provider-model-visibility.tsx:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +6 T2 Authentication, credential commit and identity migration P2 clients:C52 MCP/connectors/runtime installation 4 4 4 3 Late callbacks, logout or interrupted migrations can restore obsolete credentials or misreport committed authentication. Configure/connect/auth/install/check/retry/remove and disclosure substeps. Existing status unions render backend state; local pending state gates actions and must not cause startup installs/downloads. renderer/components/settings/mcp-settings.tsx:78; renderer/components/settings/mcp-preset-setup.tsx:32; renderer/components/settings/mcp-mac-app-setup.tsx:24; renderer/components/settings/harness-runtime-section.tsx:23; renderer/components/settings/connections-settings.tsx:15; renderer/lib/mcp-preset-state.ts:3 docs/audits/implicit-state-machines-clients-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M025 I Durable pause overlay: absent/persisted pause, suspend pending/timed out/reopened; interrupted turn optional 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Persist pause before aborting work; passive entry commits must not resume scheduler. Unpause clears overlay without implicitly resuming interrupted turn. main/services/bot-pause-store.ts:1; main/services/bot-runtime/bot-session-service.ts:472; main/services/bot-runtime/bot-session-service.ts:487; main/services/bot-runtime/bot-session-service.ts:947; main/services/bot-runtime/bot-session-main.ts:147 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M038 I Bot watchdog/stall latch 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. running + no progress + not waiting on person → acting → handled/snoozed; attended vs routine outcomes differ; resume resets timing. main/services/bot-runtime/bot-run-watchdog.ts:42; main/services/bot-runtime/bot-run-watchdog.ts:48; main/services/bot-runtime/bot-run-watchdog.ts:82; main/services/bot-runtime/bot-run-watchdog.ts:102 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M042 H Bot routine proposal lifecycle 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. pending → accepted/dismissed, revision/superseded and shown state; accept creates or updates routine, stale proposal decisions and dismiss cooldown are guarded. main/services/bot-routine-proposals.ts:209; main/services/bot-routine-proposals.ts:335; main/services/bot-routine-proposals.ts:367; main/services/bot-routine-proposals.ts:453; main/services/bot-routine-proposals.ts:677 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M045 H Commitment reminder lifecycle 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. waiting → proposed → accepted/dismissed/expired; clock pump and proposal settlement are separate transition owners; open-ended proposals remain pending. main/services/bot-commitments/store.ts:99; main/services/bot-commitments/store.ts:141; main/services/bot-commitments/proposer.ts:43; main/services/bot-commitments/proposer.ts:92 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M047 I Schedule scheduler: started × globallyEnabled, task timers/running-task map/cancelRequested/pendingScanRunning and catch-up queue 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Start/stop/rearm/fire/cancel/manual/retry/catch-up; a timer firing under an old task revision must not dispatch stale work. main/services/schedule-service-core.ts:181; main/services/schedule-service-core.ts:189; main/services/schedule-service-core.ts:576; main/services/schedule-service-core.ts:589; main/services/schedule-service-core.ts:696; main/services/schedule-service-core.ts:897 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M048 H Durable routine fire and execution: pending fire → submitted/observing → completed/failed/interrupted/skipped; stable request ID, prior submission, retry evidence, pause and silent reply 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Existing submission cannot be repeated merely because observation failed; tool-free evidence gates retry; pause is skip not catch-up authorization. main/services/scheduled-bot-routines.ts:269; main/services/scheduled-bot-routines.ts:286; main/services/scheduled-bot-routines.ts:314; main/services/scheduled-bot-routines.ts:393; main/services/scheduled-bot-routines.ts:442; main/services/scheduled-bot-routines.ts:511; main/services/schedule-store-core.ts:938 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M049 H Routine recovery/circuit breaker: retryable failure streak → backoff retry / needs-person issue / paused routine; successful run or explicit resume clears state 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Retry budget and no-effect evidence, not just error text, permit fresh execution. main/services/bot-routine-recovery.ts:48; main/services/bot-routine-recovery.ts:64; main/services/bot-routine-recovery.ts:131 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M050 I Catch-up and one-shot wake-up lifecycle: last Bot state map detects leaving interrupted/paused; pending one-shot task → spent/cancelled/replaced, per-Bot queue 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. No automatic catch-up while still paused; wake-up generation identity prevents obsolete reminders. main/services/scheduled-bot-routines.ts:857; main/services/scheduled-bot-routines.ts:1066; main/services/scheduled-bot-routines.ts:1090; main/services/bot-wake-ups/wake-ups.ts:135 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M051 H Event routine dispatcher: event unseen → duplicate/held/queued/running/settled; daily counters, cooldown, held timer, running list, disposal epoch 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Durable dedupe before dispatch, bounded concurrent work; held release must verify current routine and pause. main/services/bot-routine-events/dispatcher.ts:31; main/services/bot-routine-events/dispatcher.ts:58; main/services/bot-routine-events/dispatcher.ts:95; main/services/bot-routine-events/dispatcher.ts:120 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M052 H Watched source lifecycle: no baseline → baseline/no_change/changed/error, failure streak/paused/recovered, timer and inFlight set 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Rechecks latest enabled routine after IO; baseline must not emit as a change; repeated errors stop/recover watch appropriately. main/services/bot-routine-events/watch.ts:150; main/services/bot-routine-events/watch.ts:182; main/services/bot-routine-events/watch.ts:212; main/services/bot-routine-events/watch.ts:267; main/services/bot-routine-events/store.ts:47 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M053 I Folder watcher/debounce/self-write suppression: active watches, event windows, running turns with held paths, echo fingerprints and rearm generation 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. File event → batch/hold → post-run release; prevent own-write echo loops while preserving real external edits. main/services/bot-routine-events/folder-watch.ts:57; main/services/bot-routine-events/folder-watch.ts:68; main/services/bot-routine-events/folder-watch.ts:97; main/services/bot-routine-events/folder-watch.ts:127; main/services/bot-routine-events/own-writes.ts:25 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M113 H Done-when check loop: waiting/running/passed/gave-up, running controllers and runWhenFree set 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Turn ends/check starts/result/abort/busy/restart; bounded checks, waiting run restored after interrupted check, no concurrent check and agent turn. main/services/follow-through/done-when.ts:88; main/services/follow-through/done-when.ts:100; main/services/follow-through/done-when.ts:190; main/services/follow-through/done-when.ts:240 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M114 H Pull-request follow loop: following/ended plus checks history, nextCheck, notices count, paused chats/tick/closed 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Poll/observation/auth failure/check change/merge/stop/chat delete; retry bounds and notice dedupe distinct from PR's own static status. main/services/follow-through/pull-request-follows.ts:52; main/services/follow-through/pull-request-follows.ts:162; main/services/follow-through/pull-request-follows.ts:188; main/services/follow-through/pull-request-follow.ts:241; main/services/follow-through/pull-request-follow.ts:431 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M160 H Durable job SQL lifecycle and worker lease: admitting/queued/running/pause_requested/cancel_requested/waiting_approval/waiting_input/paused/interrupted/needs_attention/failed/succeeded/cancelled × intent/continuation/lease/revision/dispatched 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Enqueue/claim/admit/dispatch/checkpoint/settle/recover/retry/stop; beforeEffect checks live lease, outcome evidence governs settlement. Foundation service explicitly says Pi runtime adapter not wired here. main/services/durable-jobs/store.ts:362; main/services/durable-jobs/store.ts:471; main/services/durable-jobs/store.ts:490; main/services/durable-jobs/store.ts:534; main/services/durable-jobs/store.ts:636; main/services/durable-jobs/service.ts:73; main/services/durable-jobs/worker.ts:9 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M195 I Routine reflection worker: per-routine running set, last-reflected watermark, budget/admission lease and proposal output 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Enough settled runs→reserve→admit→model→watermark→propose/retire/no_entry/failed; evidence from multiple matching configurations and repeated authority checks gate accepted lessons. main/services/bot-learning/routine-reflection.ts:105; main/services/bot-learning/routine-reflection.ts:121; main/services/bot-learning/routine-reflection.ts:151; main/services/bot-learning/learning-main.ts:173 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 backend:M196 I Bot learning daily accounting: day-scoped persisted request/output counts and returned settlement capability 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Reserve increments request before dispatch; settle charges observed output or worst-case cap for unknown usage; day rollover resets counters. Shared across review/reflection/tidy. main/services/bot-learning/budget.ts:22; main/services/bot-learning/budget.ts:40; main/services/bot-learning/budget.ts:50 docs/audits/implicit-state-machines-backend-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 cli-native:C12 CLI Bot pause orchestration 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. unpaused → durable pause written → foreground work stopped and drained; unpause clears fence pause/unpause, start/preflight, shutdown Paused state is a durable authority fence, not just a UI indicator; shared Bot services own underlying capability transitions. packages/cli/src/bots.ts:104; packages/cli/src/bots.ts:112 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 cli-native:C16 CLI scheduled execution 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. inactive → active controller → script/inference/Bot execution → result recorded → inactive scheduler run/cancel/cancelAll, tool call, authority change Provider/workspace/MCP authority is checked before and during unattended execution; shared scheduler owns timing/revision transitions. packages/cli/src/schedules.ts:53; packages/cli/src/scheduled-inference.ts:54 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 cli-native:C26 Todo branch restore fencing 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. unavailable → restoring(epoch) → ready or unavailable after error; superseded/shutdown session_start/session_tree/session_shutdown A late restore cannot overwrite a newer branch; unreadable checkpoints never become empty tasks. Shared todo reducer is explicit. packages/cli/src/extensions/todo.ts:18 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 cli-native:N09 Native subagent run-store protocol and CAS publication 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. ready → read/write(expected digest)/cleanup/sync → response → ready; close/EOF terminal command frames, destination changed, partial write/sync error Expected hash and owned temporary recovery files guard publication; state is partly on disk. native/subagent-run-store/main.c:757 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 clients:C57 Bot pause/delete/computer setup 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Idle/confirmation/action pending/error; host pause/unpause and VM setup/start/stop phase projections. UI does not own host lifecycle; host receipt, not optimistic label, proves pause/setup. renderer/main/bots/bot-paused-card.tsx:48; renderer/main/bots/bot-delete-dialog.tsx:42; renderer/main/bots/bot-computer-section.tsx:23; renderer/components/settings/bot-computers-settings.tsx:36; renderer/components/settings/bot-computer-base-screen.tsx:22 docs/audits/implicit-state-machines-clients-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 clients:C59 Bot routines/events/proposals 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Edit session/new/existing, save/delete, link creation, proposal decide, Run now idle/pending/started/error. Editor-session identity separates reopened drafts; run state is per mount and host pause is authoritative. renderer/main/bots/bot-routines.tsx:37; renderer/main/bots/bot-routine-editor.tsx:124; renderer/main/bots/bot-event-routines.tsx:137; renderer/components/bots/routine-proposal-card.tsx:28; renderer/components/bots/routines-skipped-card.tsx:17 docs/audits/implicit-state-machines-clients-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 clients:C73 Pull-request linking/review and follow-through cards 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Link draft/query/linking/attached/error; create PR title/base/body/pending, refresh/unlink/resolve; job/PR follow display and due timer; wakeup cancelled/elapsed. User mutation pending is separate from host following state; elapsed deadline rerender does not itself authorize work. renderer/components/chat-pull-requests.tsx:178; renderer/components/chat-pull-requests.tsx:454; renderer/components/chat-pull-requests.tsx:632; renderer/components/follow-through-chips.tsx:89; renderer/components/bots/wake-up-chip.tsx:22 docs/audits/implicit-state-machines-clients-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 clients:N28 Bot memory/routines/chat-activity edits 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Load/edit/save/delete/undo/erase; per-entry pending; serialized optimistic wording changes with latest pending value. Bot/installation/revision identity guards async responses; don't collapse independent fields into global “saving.” ios/AidenOnTheGo/Features/Bots/AidenBotMemoryView.swift:5; ios/AidenOnTheGo/Features/Bots/AidenBotRoutinesView.swift:4; ios/AidenOnTheGo/Features/Bots/AidenBotAdvancedView.swift:4; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotMemoryController.kt:23; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutines.kt:45; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotChatActivityModel.kt:252; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotChatActivityScreen.kt:163 docs/audits/implicit-state-machines-clients-2026-11-04.md +7 T2 Unattended Bot execution, pause, routine claims and recovery P6 clients:N35 Native schedules, usage, spending, jobs 4 3 4 4 Restart, clocks, stale claims or recovery policy can duplicate unattended work or revive paused/deleted Bots. Loading/cached/live/error; schedule edit/run/cancel/delete; per-job stopping IDs; temporary spend override pending/expired. Explicit action invokes mutation, status poll only observes; scoped owner invalidates late results. ios/AidenOnTheGo/Features/Remote/AidenScheduledTasksView.swift:107; ios/AidenOnTheGo/Features/Remote/AidenSpendingNotice.swift:6; ios/AidenOnTheGo/Features/Remote/AidenBackgroundJobs.swift:7; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/scheduled/AidenScheduledTasksScreen.kt:69; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenSpending.kt:98; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenBackgroundJobs.kt:134; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenUsageSheet.kt:59 docs/audits/implicit-state-machines-clients-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M013 H Generation timeline and step lifecycle: running → completed/failed/cancelled; steps pending/awaiting_approval/running/blocked/terminal 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. Tool start/result, approvals, cancellation, parent finish settle remaining unfinished steps; avoid resurrecting a terminal step via late callbacks. main/services/generation-timeline.ts:387; main/services/generation-timeline.ts:458; main/services/generation-timeline.ts:596; main/services/generation-timeline.ts:735; main/services/generation-timeline.ts:742 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M022 H Fork-summary job: pending → ready/failed plus running controller registry 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. Fork starts job; retry/cancel/delete/restart reconcile pending with no live owner to interrupted failure. main/services/fork-summary-service.ts:94; main/services/fork-summary-service.ts:129; main/services/fork-summary-service.ts:161; main/services/fork-summary-service.ts:168; main/services/chat-fork-service.ts:95 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M159 H Pi session compaction/journal recovery: begin/commit transaction markers, open transactions, sessions/opening/quarantined maps, compaction abort and overflowRecoveryAttempted 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. Compact/cancel/crash/reopen/quarantine/seed; incomplete transactions hidden/recovered, at most one overflow recovery per coordinator attempt. main/services/pi-compaction-session-store.ts:53; main/services/pi-compaction-session-store.ts:533; main/services/pi-compaction-session-store.ts:604; main/services/pi-compaction-session-store.ts:857; main/services/pi-compaction-core.ts:249; main/services/context-lifecycle-service.ts:88 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M173 I Cut-off continuation and failed-attempt rewind 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. continuingCutOffReply × currentAssistantTurnContinuesCutOff × currentAssistantTurnHadVisibleText/HadReasoningDelta, turn start offsets and failed-turn start. Message start captures continuation mode; deltas choose separator; retry retaining partial continues it, retry replacing partial rewinds only failed attempt and emits reset. main/services/llm-client.ts:3014; main/services/llm-client.ts:4312; main/services/llm-client.ts:4359; main/services/llm-client.ts:4416; main/services/llm-client.ts:4920; main/services/llm-client.ts:4956 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M174 I Journal availability/fault latch 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. piJournalHealthy × piJournalStopNoted × piJournalless × piUpgradeCompactionEnabled. Initial session eligibility chooses durable or in-memory path; journal failure poisons durability and emits stop notice once. Journal-free mode must not enter durable quarantine/recovery path. main/services/llm-client.ts:3032; main/services/llm-client.ts:3053; main/services/llm-client.ts:3769; main/services/llm-client.ts:4599; main/services/llm-client.ts:4692 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M175 I Visible-assistant publication / durable reconciliation saga 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. Visible-turn lease, pending durability settlement, abandoned-assistant and quarantine-without-lease flags. Final save may commit, fail, rollback or defer reconciliation; detached settlement quarantines chat until recovery; visible and durable histories must agree before next turn. main/services/llm-client.ts:4594; main/services/llm-client.ts:4608; main/services/llm-client.ts:4648; main/services/llm-client.ts:4704; main/services/llm-client.ts:4962 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M176 I Accepted but undelivered guidance return 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. Collected-once bit plus immediate/late queued messages and captured owner. Stop/terminal/projection failure collects pending steer text; late settlement returns only messages whose visible save did not land. Avoid both loss and duplicate restoration after cancel. main/services/llm-client.ts:4831; main/services/llm-client.ts:4833; main/services/llm-client.ts:4841 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M177 I Terminal response persistence and usage settlement 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. Runtime outcome/cancelRequested, unreported-usage cancellation claim, replyNotSaved and final persistenceFailed projection. A model-completed reply can still have local-save failure; cancellation usage must be recorded once and terminal event exposes persistence failure. main/services/llm-client.ts:4966; main/services/llm-client.ts:4990; main/services/llm-client.ts:5060; main/services/llm-client.ts:5085 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 backend:M194 H Subagent V1→V2 activation journal: missing/prepared/committed with source generation/content digest 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. Read source→write prepared→reread source→CAS committed; changed source prevents activation; content digest handles filesystem identity changes after reboot. main/services/subagents/subagent-run-store-v2-migration.ts:30; main/services/subagents/subagent-run-store-v2-migration.ts:344; main/services/subagents/subagent-run-store-v2-migration.ts:387; main/services/subagents/subagent-run-store-v2-migration.ts:400; main/services/subagents/subagent-run-store-v2-migration.ts:413 docs/audits/implicit-state-machines-backend-2026-11-04.md +8 T2 Transcript, run journal and terminal persistence reconciliation P1/P4 clients:N11 Native terminal output/persistence handoff 4 2 4 4 Visible completion can diverge from durable history; partial writes must not become missing or duplicate turns. Live output→ended-but-unsettled→transcript accepted→live cleared. Terminal reconciliation task, ended reply, transcript generation and identity checks; publish saved transcript and clear live in same UI turn to avoid duplicate/gap. Pending reveal backlog has its own drain policy. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1517; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1871; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5123; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5193; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5414; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:300; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3440; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3498; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3723; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3754 docs/audits/implicit-state-machines-clients-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 backend:M097 I Spending/usage-accounting lifecycle: open request accounting, reserved/billed usage, loading/saving timers and limit adjustments 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Begin/record/end/allow-more/restart; account once despite cancellation or provider result races; persistence and UI limit state can lag. main/services/usage-accounting.ts:128; main/services/spending-service.ts:63; main/services/spending-service.ts:230; main/services/usage-store-core.ts:440 docs/audits/implicit-state-machines-backend-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 backend:M144 I Image workflow runtime/coordinator: opening/enabled; active/starting/deleting/version maps/closed 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Run start/stop/delete/config disable/shutdown; deleted or superseded workflow cannot receive late result publication. main/services/create-images/runtime.ts:80; main/services/create-images/run-coordinator.ts:98 docs/audits/implicit-state-machines-backend-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 backend:M145 H Image run/attempt scheduler: run running→finished/interrupted; attempts queued/running/succeeded/failed/skipped/cancelled/interrupted; graph dependencies and request limit 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Claim request before provider dispatch, settle downstream on failure, restart interrupts live attempts; persisted claim and actual dispatch boundary differ. main/services/create-images/run-ledger.ts:268; main/services/create-images/run-ledger.ts:304; main/services/create-images/run-ledger.ts:528; main/services/create-images/scheduler-core.ts:394; main/services/create-images/run-executor.ts:270 docs/audits/implicit-state-machines-backend-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 backend:M146 H External image job polling: submitted/queued/processing/completed/failed/cancelled and abort/deadline 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. fal/Replicate submit→poll→download or error/cancel; local cancellation can race external completion and billable dispatch. main/services/image-generation/fal-images.ts:153; main/services/image-generation/replicate-images.ts:236; main/services/create-images/image-port.ts:133 docs/audits/implicit-state-machines-backend-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 backend:M148 H Design run/revision lifecycle: running→complete/partial/interrupted, draft→published/missing; run recorded × accepted and pending settlements 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Start/render/finish/cancel/recover/missing files; publish complete only with revisions, partial requires retained output, effect acknowledgement follows durable render. main/services/design/store-core.ts:285; main/services/design/store-core.ts:381; main/services/design/store-core.ts:531; main/services/design/store-core.ts:572; main/services/design/store-core.ts:617; main/services/design/run-service.ts:90; main/services/design/run-service.ts:149; main/services/design/run-service.ts:260 docs/audits/implicit-state-machines-backend-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 backend:M149 H Design project lifecycle: active/deleting/unreadable plus staging/reservations/per-project gate 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Create/publish/delete/restart/repair; durable deleting marker drives roll-forward, capacity reservations held through admitted writes. main/services/design/store.ts:118; main/services/design/store.ts:160; main/services/design/store.ts:524; main/services/design/store.ts:557; main/services/design/store.ts:601; main/services/design/store.ts:690 docs/audits/implicit-state-machines-backend-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 backend:M150 I Generated HTML/Aiden UI draft lifecycle: call maps, sent partial/finished/cancelled, preview closed and artifact publication 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Tool argument deltas→draft preview→final artifact/cancel; terminal must remove ephemeral preview without losing committed artifact. main/services/generative-ui-draft.ts:21; main/services/generative-ui-draft.ts:101; main/services/aiden-ui-draft.ts:36; main/services/generative-ui-preview-store.ts:75; main/services/generative-ui-artifact-store.ts:189 docs/audits/implicit-state-machines-backend-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 backend:M151 I Workspace artifact refresh/action: live refresh with joiners, generation, abort/cancel and save eligibility 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Refresh/join/leave/invalidate/action/close; one request may outlive caller but stale generation must not persist snapshot. main/services/workspace-artifacts/runner.ts:112; main/services/workspace-artifacts/runner.ts:125; main/services/workspace-artifacts/runner.ts:201; main/services/workspace-artifacts/runner.ts:227; main/services/workspace-artifacts/runner.ts:259 docs/audits/implicit-state-machines-backend-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 cli-native:C32 CLI usage attempt accounting 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. unaccounted → serialized writer/lease → usage plus attempt hash published → accounted; replay suppressed record usage, repeated advisor attempt, writer failure Dedupe receipt and aggregate usage are published together; bounded retained attempt window is separate from in-process promise tail. packages/cli/src/usage-ledger.ts:13; packages/cli/src/usage-ledger.ts:31 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 clients:C45 Workflow loading/run consent 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. loading/ready/error; asset/model resolution request sequences; prepare plan→consent→busy run snapshot→settled; selected/stale nodes and reload confirmation. Save revision must precede execution; stale preparation cannot authorize changed graph. renderer/images/use-workflow-controller.ts:35; renderer/images/use-image-run.ts:14; renderer/images/workflow-editor.tsx:49 docs/audits/implicit-state-machines-clients-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 clients:C48 Interactive generated UI local state 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Visual initial/current state, selection/input event updates, expression evaluation budget, render fallback. User events update local visual state, not host conversation authority; expression traversal is a bounded synchronous evaluator rather than a long-lived job. renderer/components/aiden-ui/aiden-ui-block.tsx:29; renderer/components/aiden-ui/chart.tsx:17; renderer/shared/aiden-ui/expression.ts:20 docs/audits/implicit-state-machines-clients-2026-11-04.md +9 T2 External generation, publication and spend accounting P6 clients:C76 Model picker / Model Pad interaction 3 3 4 3 Retries or cancellation around external work can create duplicate paid jobs, publications or misleading accounting. Open/closed pad/list/search, preview versus confirmed model, dragging/frame-queued point, focus held/restored, delayed close, awaited recent models. Pointer gesture cannot accidentally commit stale model; dropdown removal restores focus to owner. renderer/components/model-picker.tsx:478; renderer/components/model-picker-pad.tsx:166; renderer/components/settings/model-pad/model-pad-add-popover.tsx:104; renderer/components/settings/model-pad/model-pad-arrange-menu.tsx:211 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 backend:M179 I Renderer-acknowledged app navigation: pending request with owner/document and five-second deadline 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Open emits navigation only to a usable local owner; opened/blocked acknowledgement, abort, document invalidation or deadline settle request; same-document proof gates acknowledgement. main/services/aiden-app-navigation.ts:14; main/services/aiden-app-navigation.ts:39; main/services/aiden-app-navigation.ts:64 docs/audits/implicit-state-machines-backend-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:C01 Queue delivery and edit holds 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Queue contents × paused × sendingId × editingId × compaction hold × fork-summary hold. Add/edit/reorder/pause/resume/claim/settle; only one claimed send, editing blocks normal delivery, failed send retains message and pauses. Compaction failure pauses existing drafts; successful/unneeded/busy compaction releases hold. Explicit Steer has different guards. Retention/remount cleanup at renderer/lib/chat-message-queue.ts:225 is a second lifetime machine. renderer/lib/chat-message-queue.ts:19; renderer/lib/chat-message-queue.ts:130; renderer/lib/chat-message-queue.ts:156; renderer/lib/chat-message-queue.ts:178; renderer/lib/chat-message-queue.ts:206; renderer/lib/chat-message-queue.ts:225 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:C06 Observed local foreign run 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Following → terminal awaiting persisted reply → handed off; orthogonal releasing/reading/readRequested/readOwed. Coalesces reads, retries missing saved reply, release timer is generation-fenced, retain revokes pending release. Hotspot is terminal-before-disk publication. renderer/lib/hosts/observed-local-run.ts:90; renderer/lib/hosts/observed-local-run.ts:151; renderer/lib/hosts/observed-local-run.ts:195; renderer/lib/hosts/observed-local-run.ts:229 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:C08 Remote chat reader 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Not-started/started/disposed × serialized refresh queue × frame pending × transcript/run/status snapshots. Adapter events enqueue updates and transcript reconciliation; dispose invalidates publication and cancels frames. Separate control/read classes are coordinated by hooks and view. renderer/lib/hosts/remote-chat-session.ts:67; renderer/lib/hosts/remote-chat-session.ts:111; renderer/lib/hosts/remote-chat-session.ts:165; renderer/lib/hosts/remote-chat-session.ts:178; renderer/lib/hosts/remote-chat-session.ts:187; renderer/lib/hosts/remote-chat-session.ts:245 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:C09 Durable chat mutation intent ledger 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Unhydrated/hydrating/ready; pending intents → known/forgotten or unresolved → retrying/dismissed; secondary unknown outcomes queue behind the first. Persist before mutation; same request/key plus pairing ownership and retry window required for retry. Fork uncertainty has its own slot. renderer/lib/hosts/chat-intent-ledger.ts:81; renderer/lib/hosts/chat-intent-ledger.ts:140; renderer/lib/hosts/chat-intent-ledger.ts:155; renderer/lib/hosts/chat-intent-ledger.ts:172 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:C18 Draft submission/recovery mailbox 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Persisted draft/submitted backup, staged text, memory-only attachments, guidance/unsent return mailboxes. Mark submission before clearing, accept settles, refusal/late guidance merges back, subscriber handoff consumes pending data. Separate from rendered textarea. renderer/lib/composer-draft-store.ts:34; renderer/lib/composer-draft-store.ts:43; renderer/lib/composer-draft-store.ts:51; renderer/lib/composer-draft-store.ts:119; renderer/lib/composer-draft-store.ts:140; renderer/lib/composer-draft-store.ts:198 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:C19 Attachment admission and new-worktree send 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Attachment operation generation/busy; worktree settled/released/answered flags; draft not-created/created/moved-to-chat with cancellation ownership. One current operation may append attachments or transfer draft; releasing UI cannot assume host work was cancelled. renderer/lib/composer-attachment-operation.ts:8; renderer/lib/draft-worktree-send.ts:169; renderer/lib/no-workspace-send.ts:59; renderer/lib/chat-draft.ts:306 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:C22 Fork and summary workflow 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Fork configuration → creating → navigation; summary pending/ready/failed/cancelled/continue-without-summary. Same intent key for uncertain fork; summary-held queue blocks next message until disposition. renderer/main/chat-pane.tsx:1339; renderer/main/remote-chat-view.tsx:591; renderer/components/fork-message-button.tsx:32; renderer/components/fork-summary-card.tsx:25 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N04 Foreground/resume gate 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Foreground/active/background plus needsRefresh latch. Background suspends observers and arms refresh, inactive bounce does not; active either resumes or refreshes. Explicit tiny reducer on iOS; view lifecycle drives several separate subscriptions. ios/AidenOnTheGo/Features/Remote/AidenSceneRefreshGate.swift:12; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2027; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2045; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2678; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:803; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:814; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:834 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N08 Draft session / durable pending send 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Session generation current/invalidated, pending debounce/written sequence, stored text plus unresolved send attempt. Begin session/save/consume/failure restore/remove/purge; purge invalidates writers before deleting so delayed failed-send restoration cannot resurrect removed data. ios/AidenOnTheGo/Persistence/AidenChatDraftStore.swift:6; ios/AidenOnTheGo/Persistence/AidenChatDraftStore.swift:163; ios/AidenOnTheGo/Persistence/AidenChatDraftStore.swift:188; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenChatDraftStore.kt:133; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenDebouncedDraftWriter.kt:23 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N09 Native send/start/rate-limit recovery 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Idle/starting/pending-send unknown/refused-busy/rate-limit waiting/active stream × optimistic message/draft. Durable request+key freezes before network; accepted receipt advances, definite rejection restores draft, ambiguous response keeps key. Rate-limit retry timer must stay within captured ownership and not retry a fresh mutation indiscriminately. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1335; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1369; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1393; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3110; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:240; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:248; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1553; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1606; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenChat.kt:2156 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N10 Native owned run reconnect/replay 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Stored active stream + last sequence → restoring/streaming/network-wait/reconnecting/terminal reconciliation; retry count/network availability independent of stream status. Restore stream before foreign-run attach; TCP/SSE loss does not create another turn. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1273; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1325; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4522; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4582; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4599; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4719; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:274; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1540; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2014; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenNetworkAvailability.kt:88; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenNetworkAvailability.kt:110 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N12 Foreign-run discovery / attach / settle 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Absent/lookup/live/ended-before-attach/reconciling/accounted × local start/restore × pending roster signal × foreground probe/backoff. New roster turn triggers attach, own run skipped, announced missing run gets bounded retry, probes only without roster capability; coalesced signal must survive lookup already in flight. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1293; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10842; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10865; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10912; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10997; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2770; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2816; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2848; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2878; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3071 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N16 Native worktree-on-first-send and fork 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Setup task/not started/cancelled/created; retained worktree request; fork pending/uncertain/navigated, summary pending/failed/ready/skipped. Setup cancellation and send receipt may race; fork copy preserves attachment/intent identity; summary gates sending. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1473; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1936; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2354; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2473; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2544; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:200; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:474; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:500; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:631 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N17 Native attachment preparation/upload/cleanup 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Preparing batch→uploading(progress)→staged→consumed/deleted; cancellation/deferred access revocation/owned cleanup tasks. Capacity and generation guards; cancelled upload can still return a reference needing cleanup, removal/revocation prevents reattachment. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1447; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3411; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3525; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3637; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3654; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:159; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:175; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1858 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N25 Bot images/attachments/partial reveal 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Staged/uploading/cancelled/cleanup plus bounded shared image cache; revealedPartial trails partial on iOS, snapshot/rewrite/entry clears immediately. iOS attachment references and user text freeze together in its outbox request. Android source here exposes shared-image presentation but its send transport still takes text/mode, so iOS attachment delivery parity is not claimed. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1188; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1224; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1640; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2418; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2496; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:2771; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:701; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionScreen.kt:240 docs/audits/implicit-state-machines-clients-2026-11-04.md +10 T2 Client send queues, mutation intents, replay and settlement P3 clients:N46 Android frame-coalesced live transcript buffer 3 2 4 3 Navigation, reconnect and late events can resend work, lose drafts or release the wrong queue entry. Accumulating text/reasoning, unpublished/published prefix, frame job scheduled/none. Append coalesces, flush cancels frame and publishes, reset clears both buffers, publishCurrent forces replay. Flush before timeline-offset or terminal event keeps text and timeline consistent. android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenLiveTranscriptBuffer.kt:17 docs/audits/implicit-state-machines-clients-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M054 I Remote service: enabled/mode/setupInFlight, listener readiness/failure, socket sets, TLS refresh, operation tail and tailnet route ownership 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Enable/disable/switch mode/pair/TLS update/connect/disconnect/quit serialize mutations; listener readiness differs from network route readiness. main/services/aiden-remote-service.ts:386; main/services/aiden-remote-service.ts:540; main/services/aiden-remote-service.ts:959; main/services/aiden-remote-service.ts:980; main/services/aiden-remote-service.ts:1034; main/services/aiden-remote-service.ts:1178; main/services/aiden-remote-service.ts:1281 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M055 H Tailscale ownership/takeover workflow: unavailable/free/conflicting/owned assessment, takeover review tokens and exact route mutation/recheck 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Only owned or explicitly reviewed routes may be changed; command failure requires inspecting actual Serve state. main/services/aiden-remote-tailscale.ts:481; main/services/aiden-remote-tailscale.ts:609; main/services/aiden-remote-tailscale.ts:673; main/services/aiden-remote-tailscale.ts:729; main/services/aiden-remote-tailscale-route.ts:263 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M060 H Remote generation stream registry: queued/running/waiting_for_approval/reconciling/done/error/cancelled/interrupted; approvals/questions/replay/cursors, persistence dirty/running/timer 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Start/events/admission/decision/detach/restart/retention; durable stream and generation settlement may diverge temporarily. main/services/aiden-remote-streams.ts:538; main/services/aiden-remote-streams.ts:963; main/services/aiden-remote-streams.ts:1089; main/services/aiden-remote-streams.ts:1114; main/services/aiden-remote-streams.ts:1484; main/services/aiden-remote-streams.ts:1761 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M061 I SSE pump/backpressure: closed × blocked × ending × pumping, drain deadline and cursor 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Wake/write(false)/drain/terminal/close; no duplicate pump, bounded blocked transport and terminal flush before close. main/services/aiden-remote-sse.ts:58 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M069 H Peer host registry: stored/enabled/current route/verified/negotiated/repinning plus active requests/streams, epochs, pairings and closed 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Pair/connect/repin/route discovery/enable/remove/close; credential identity and TLS pin bind every admitted request. main/services/peer-host-registry.ts:237; main/services/peer-host-registry.ts:607; main/services/peer-host-registry.ts:1026; main/services/peer-host-registry.ts:1131 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M070 H Peer connection supervisor: disabled/connecting/connected/backoff/blocked with generation and timers 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Wake/network failure/auth failure/repair/route changes; stale generation callbacks cannot revive removed/disabled host. main/services/peer-host-manager.ts:205; main/services/peer-host-manager.ts:547; main/services/peer-host-manager.ts:585; main/services/peer-host-manager.ts:606; main/services/peer-host-manager.ts:682 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M071 H Peer feed and run stream supervisor: feed off/unsupported/syncing/live; run streaming/idle/ended/gone/waiting plus cursor, holders, dropped/announced flags 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. SSE loss/reconnect/reset/source end/last unsubscribe; feed health and peer transport connection are separate machines. main/services/peer-host-manager.ts:757; main/services/peer-host-manager.ts:779; main/services/peer-host-manager.ts:926; main/services/peer-run-subscriptions.ts:112; main/services/peer-run-subscriptions.ts:261 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M072 H Peer Bot session stream supervisor: waiting/streaming/gone states, stopped flag, refcount holders, retry wake and cursor 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Subscribe/unsubscribe/dropHost/connection failure/resync; compatibility negotiation before applying Bot events. main/services/peer-bot-sessions.ts:74; main/services/peer-bot-sessions.ts:138; main/services/peer-bot-sessions.ts:151; main/services/peer-bot-sessions.ts:175 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M073 I Peer discovery/pairing client: bounded session, queued probes, abort/deadline, polling pending→decision 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Discovery expires/cancels; pairing polling only accepts bound host identity and final envelope, abort can require remote cancellation. main/services/peer-discovery.ts:274; main/services/peer-discovery.ts:329; main/services/peer-pairing-client.ts:141; main/services/peer-pairing-client.ts:210; main/services/peer-pairing-client.ts:241 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M074 I Telegram poll/dispatch/turn supervisor: started × activeTurn × dispatchPending × processingUpdates, poll abort and dispatch cancellation; offset/queue/typing activity 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Start/stop/new updates/claim/dispatch/retry/profile mutation; no overlapping polling owners or turn dispatch after profile invalidation. main/services/telegram/telegram-service-core.ts:265; main/services/telegram/telegram-service-core.ts:376; main/services/telegram/telegram-service-core.ts:1923; main/services/telegram/telegram-service-core.ts:2080; main/services/telegram/telegram-ownership.ts:60 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M080 I Generation-bound MCP connections: missing/pending/connected plus generation/cancelled/closedAfterConnect/closed 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Connect/disconnect/config change/transport close/timeout/shutdown; identity checks prevent late old connection caching, second close after late connect is required. main/services/generation-bound-connection-cache.ts:115; main/services/generation-bound-connection-cache.ts:151; main/services/generation-bound-connection-cache.ts:297 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M081 I MCP service inventory/connection lifecycle: closed flag, connection cache, disconnecting set, inventory memo and generation 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Discover/prewarm/config changes/close; tool inventory ownership must match active connection and configuration generation. main/services/mcp.ts:319; main/services/mcp.ts:401; main/services/mcp.ts:414; main/services/mcp.ts:733 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M088 H ACP pinned runtime installation: unsupported/not_installed/installing/installed/update_available/failed, phase downloading/verifying/extracting/validating/activating, removing/lease count 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Explicit install/cancel/remove/validation/activation; atomic active-pointer publication after validation; no removal while leased. main/services/acp/installer.ts:35; main/services/acp/installer.ts:69; main/services/acp/installer.ts:169; main/services/acp/installer.ts:190; main/services/acp/installer.ts:249 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M091 I Antigravity service/provider discovery: loaded/stopping promise and discoveryDue 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Explicit install/sign-in/catalog refresh/shutdown; catalog discovery one-shot after auth, launcher closes permanently only once quit committed. main/services/antigravity/service.ts:52; main/services/acp/provider.ts:58 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 backend:M139 H Gemini live protocol: idle/connecting/open/resuming/closing/disconnected/failed/closed; seeded/resumptionInFlight, toolCalls issued/completed/cancelled and attempt controller 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Socket open/setup/audio/server turn/tool call/goAway/resume/error/close; exactly-once tools across resumption, bounded reconnect and setup timeouts. main/services/gemini-live/protocol.ts:526; main/services/gemini-live/protocol.ts:539; main/services/gemini-live/protocol.ts:727; main/services/gemini-live/protocol.ts:1366; main/services/gemini-live/protocol.ts:1513; main/services/gemini-live/protocol.ts:1691 docs/audits/implicit-state-machines-backend-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 cli-native:C08 Linux Bonjour publisher 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. stopped → spawning → advertising → exited → retry scheduled; superseded generation start, child spawn/error/exit, retry timer, stop Generation and child identity fence late exit/retry callbacks. macOS delegates to the shared publisher. packages/cli/src/remote.ts:57 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 cli-native:C20 CLI MCP connection and inventory incarnation 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. absent → connecting → client ready → stale/superseded/terminal failure → absent; pool closed terminal connection, credential/config change, inventory invalidation, close Entry identity fences awaits; concurrent callers share pending connection; close retires attempts and resolved clients; tools revalidate schema/effects. packages/cli/src/mcp.ts:399; packages/cli/src/mcp.ts:427; packages/cli/src/mcp.ts:488 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 clients:C13 Peer-host transport/sidebar follower 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Connecting/available/unavailable host generation × feed snapshot/deltas/buffering/resync × disposed observers. Capability checks and generation/sequence fences; frame-coalesced feed updates must retain changes during initial read/subscription. renderer/lib/hosts/remote-host-adapter.ts:252; renderer/lib/hosts/remote-host-adapter.ts:763; renderer/lib/hosts/peer-host-feed-state.ts:133; renderer/lib/hosts/use-peer-host-sidebar.ts:115 docs/audits/implicit-state-machines-clients-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 clients:C14 Local Bot live subscription sharing 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. No consumers → one shared subscription → fresh/stale/failed view → retry/resubscribe → microtask release. Remembered snapshot is display-only until authoritative snapshot; epoch/seq gap triggers resubscribe; ref-counted lifecycle prevents multiple components replacing each other's main subscription. renderer/lib/use-bot-live.ts:76; renderer/lib/use-bot-live.ts:92; renderer/lib/use-bot-live.ts:140; renderer/lib/use-bot-live.ts:157; renderer/shared/bot-live.ts:363 docs/audits/implicit-state-machines-clients-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 clients:C15 Paired-host Bot live follower 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. started/stopped × subscribing/subscribed × read in-flight × buffered deltas × resyncPending × gone/failed. Snapshot supersedes pending read by reading counter; gaps/epoch changes refetch; resync during read coalesces another read. renderer/lib/hosts/remote-bot-session-follower.ts:31; renderer/lib/hosts/remote-bot-session-follower.ts:58; renderer/lib/hosts/remote-bot-session-follower.ts:109; renderer/lib/hosts/remote-bot-session-follower.ts:149 docs/audits/implicit-state-machines-clients-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 clients:C68 App-root detached settlement and navigation acknowledgement 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Bootstrap subscription/read, detached owners active/draining/settled, route action opened/blocked. Subscribe before bootstrap snapshot; query cancellation and deleted-chat fences protect delayed reconciliation; onboarding/navigation guard denies route with explicit acknowledgement. renderer/main/root-view.tsx:523; renderer/main/root-view.tsx:547; renderer/main/chat-layout.tsx:143 docs/audits/implicit-state-machines-clients-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 clients:N01 Connection/activation ownership 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. needsPairing/connecting/connected/offline × mutation busy × connection generation × activation generation. Start/pair/switch/reconnect/remove/revocation; request context binds installation+device+activation so A→B→A cannot revive old A work. Credential/client cache and data purge have distinct ownership. iOS transition bodies read; Android coordinator state and event sites inspected. ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:113; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:191; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:365; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:391; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:760; ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift:1097; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/remote/AidenRemoteCoordinator.kt:317 docs/audits/implicit-state-machines-clients-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 clients:N03 Native shell/navigation/deep-link lifecycle 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Selected installation/product area/root/detail stack × loading route/queued navigation/transition leaving key/back-in-progress. External navigation waits for correct pairing/target and capabilities; cancelled navigation may still return HTTP result. Adaptive one/two-pane transitions preserve identity. ios/AidenOnTheGo/ContentView.swift:4; ios/AidenOnTheGo/Features/Remote/AidenProductShellView.swift:26; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:1333; android/app/src/main/java/sbtbiswas/AidenOnTheGo/MainActivity.kt:53; android/app/src/main/java/sbtbiswas/AidenOnTheGo/navigation/AidenNavigationHost.kt:71; android/app/src/main/java/sbtbiswas/AidenOnTheGo/navigation/AidenNavigationHost.kt:413; android/app/src/main/java/sbtbiswas/AidenOnTheGo/navigation/AidenNavigationStack.kt:7; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenProductNavigationStore.kt:41 docs/audits/implicit-state-machines-clients-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 clients:N21 Bot session feed sequence/reconnect 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Loaded/unloaded/stream-down/reopening/released; epoch+seq; snapshot replaces, duplicate ignored, gap/wrong epoch refetches, closed reconnects. Feed does not wait for outbox requests. Explicit event application coexists with implicit feed task lifetime/backoff. ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1164; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1489; ios/AidenOnTheGo/Features/Bots/AidenBotSessionModel.swift:1561; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:566; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:639; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt:668 docs/audits/implicit-state-machines-clients-2026-11-04.md +11 T2 Connection incarnation, streams and transport replacement P6 clients:N47 Native network recovery/transport-local memory 3 3 4 3 Stale connections or callbacks can attach old-peer data to the current session or retain obsolete resources. Availability/waiter continuation pending/resumed/cancelled; recovery probe/backoff/offline parked/refunded attempt/healthy reset; server-requested deadline survives network flap. Client-scoped ETag cache/gzip-supported capability; run identity unbound→bound rejects cross-run frames. Simulator retry budget refills only after stable interval. iOS bodies read; Android corresponding owners inspected. ios/AidenOnTheGo/Networking/AidenNetworkPath.swift:20; ios/AidenOnTheGo/Networking/AidenNetworkPath.swift:125; ios/AidenOnTheGo/Networking/AidenNetworkPath.swift:156; ios/AidenOnTheGo/Networking/AidenRemoteClient.swift:1130; ios/AidenOnTheGo/Networking/AidenRemoteClient.swift:4261; ios/AidenOnTheGo/Networking/AidenSimulatorContract.swift:434; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenNetworkAvailability.kt:88; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRemoteClient.kt:105 docs/audits/implicit-state-machines-clients-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred backend:M040 I Bot background memory review: scheduled → running → reviewed/failed/aborted/revoked/skipped; closed flag, per-Bot abort, admission lease and watermark 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. Idle/turn threshold gates review; cancellation rechecked before passive marker commit; revoked authority may leave partial accepted writes. main/services/bot-memory/review.ts:562; main/services/bot-memory/review.ts:577; main/services/bot-memory/review.ts:588; main/services/bot-memory/review.ts:654 docs/audits/implicit-state-machines-backend-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred backend:M041 I Bot memory snapshot freshness and forgotten fence 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. load/cache → stale → reload; delete marks forgotten against late writes. Session memory snapshots intentionally outlive some edits until session refresh. main/services/bot-memory/service.ts:61; main/services/bot-memory/store.ts:202; main/services/bot-memory/store.ts:221 docs/audits/implicit-state-machines-backend-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred backend:M043 H Skill proposal lifecycle 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. pending → added/dismissed with bounded pending/history, content/source fingerprints; accepting a changed file must not grant stale proposed content. main/services/bot-skills/proposals.ts:59; main/services/bot-skills/proposals.ts:74; main/services/bot-skills/proposals.ts:98 docs/audits/implicit-state-machines-backend-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred backend:M044 H Lesson lifecycle 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. proposed/active → retired/dismissed; per-scope capacity and supersession on acceptance, routine deletion retires/removes dependent lesson. main/services/bot-lessons/store.ts:39; main/services/bot-lessons/store.ts:55; main/services/bot-lessons/store.ts:74; main/services/bot-lessons/store.ts:91; main/services/bot-lessons/store.ts:115 docs/audits/implicit-state-machines-backend-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred backend:M161 I Studio asset store/open/recovery/delivery grants: opening/failed, thumbnail loads/failures, blob write queue; per-document expiring delivery grants 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. Open/recover/import/GC/thumbnail failure/document invalidation; references and grants must be invalidated before orphan collection. main/services/studio-assets/store.ts:202; main/services/studio-assets/store.ts:243; main/services/studio-assets/store.ts:316; main/services/studio-assets/store.ts:604; main/services/studio-assets/delivery-core.ts:55 docs/audits/implicit-state-machines-backend-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred backend:M162 H Memory fact lifecycle: active→superseded via replacement/expiry/delete; database opening/migration 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. Fact insertion and supersession scoped transactionally, expiry cannot leave stale active always-on facts. main/services/memory-store.ts:205; main/services/memory-store.ts:376; main/services/memory-store.ts:685; main/services/memory-store.ts:691 docs/audits/implicit-state-machines-backend-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred cli-native:C13 CLI durable Bot migration 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. legacy/no marker → preparing → backup completed → enabled, restart required explicit migration, cancel/drain legacy chats, backup failure, retry/restart Preparing blocks new legacy generation; only a complete backup publishes enabled. Marker persists across crashes. packages/cli/src/bot-durable-migration.ts:8; packages/cli/src/bot-durable-migration.ts:16; packages/cli/src/bots.ts:254 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred cli-native:C29 CLI MCP configuration migration/reconciliation 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. legacy recognized → lease → validated backup → destination published → source inode claimed → retained recovery; conflict → reconciliation required startup/store construction, concurrent file change, claim/sync failure Publish destination before retiring source; never discard claimed inode or overwrite a newer source; retries recognize existing identical backup. packages/cli/src/mcp-config-migration.ts:35 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred clients:C44 Image workflow editor + autosave 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. Explicit undo/redo session reducer; implicit dirty/saving/conflict/deleted/error × pending document/in-flight promise/timer/disposed. Debounce/flush/save receipt/error; serialize saves, retain failed latest edit, conflict/deletion block further writes. renderer/images/workflow-session-core.ts:91; renderer/images/workflow-session-core.ts:110; renderer/images/workflow-session-core.ts:154 docs/audits/implicit-state-machines-clients-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred clients:C61 Workspace file editor and artifact reader 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. Index/document loading/ready/error × selected file × dirty/saving/conflict/reload prompt; request IDs and workspace identity. Results from old workspace or document cannot replace current editor. renderer/components/files-panel.tsx:70; renderer/lib/use-workspace-artifacts.ts:25; renderer/main/bots/bot-panel-files.tsx:45; renderer/components/artifacts-panel.tsx:67 docs/audits/implicit-state-machines-clients-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred clients:N07 Native chat cache response admission 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. Request-reserved write clock, admitted detail/list/summaries, receipt overlays, deletion lifetime/tombstone, purge generation, active-stream record. Read/save/remove/purge events; reserve before HTTP/IO, reject stale completion and stale disk fallback, preserve newer receipt/detail ownership. Disk success is not the only current presentation authority. ios/AidenOnTheGo/Persistence/AidenChatCache.swift:4; ios/AidenOnTheGo/Persistence/AidenChatCache.swift:214; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenChatCache.kt:95 docs/audits/implicit-state-machines-clients-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred clients:N40 Other native persistence/cache ownership 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. Active scope and admitted snapshots, request/write stamps, retained/revoked installations, local archived-workspace acknowledgement, preference migrations. Store/remove/purge/scope-switch invalidate old reads; simple scalar preference values are not counted separately. ios/AidenOnTheGo/Persistence/AidenBotCache.swift:123; ios/AidenOnTheGo/Persistence/AidenModelPreferenceStore.swift:12; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenBotCache.kt:20; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenReadSnapshotCache.kt:35; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenSettingsCache.kt:62; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenWorkspaceArchiveStore.kt:21; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenInstallationStore.kt:30 docs/audits/implicit-state-machines-clients-2026-11-04.md +12 T2 Durable local state, migrations, edits and autosave P4 targeted; remainder deferred clients:N44 Native pairing installation persistence 3 2 3 4 Interrupted or competing writes can lose local configuration, edits, caches or durable receipts. Unpaired/retained/active/removed installation, secure credential saved versus metadata, validated server capabilities, cached navigation catalog. Save/select/remove must keep active ID valid and purge corresponding credential/data; App Intents cache updates navigate only, not mutate. ios/AidenOnTheGo/Models/AidenInstallation.swift:206; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenInstallationStore.kt:30; ios/AidenOnTheGo/AppIntents/AidenAppIntents.swift:177 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M068 I Remote TTS intents/sessions: live/cancelled/retained intent × session idle/active × revoked device/closed 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Start/cancel/owner deletion/capacity eviction; accepted or uncertain work remains fenced even after cache eviction. main/services/aiden-remote-tts.ts:32; main/services/aiden-remote-tts.ts:57; main/services/aiden-remote-tts.ts:160 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M124 I Bot screen/session/viewer lifecycle: connection-keyed opening/screen lease, connecting/closed/pictured, viewer hub holders and button/key/touch state 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Open/change VM connection/close/takeover/disconnect; old screen must not act on restarted VM; release pressed inputs on teardown. main/services/bot-computers/sessions.ts:80; main/services/bot-computers/rfb-screen.ts:100; main/services/bot-computers/viewer-hub.ts:232; main/services/bot-computers/viewer-hub.ts:485; main/services/bot-computers/viewer-main.ts:69 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M128 I Browser PiP capture/recording/annotation selection: painting/pending/disposed, recording media + byte/error state, active picker 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Start/frame/stop/tab close/abort; capture stop and final recording blob completion are distinct, cancellation must remove interceptors. main/services/browser/pip-feed.ts:43; main/services/browser/service.ts:1913; main/services/browser/service.ts:2029; main/services/browser/service.ts:2192; main/services/browser/service.ts:2241 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M129 H Device hub service: needs-consent/stopped/installing/starting/ready/error/unavailable plus loaded/starting/proxy/saving/granting/removing promises; peer/SSH entries 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Consent/install/connect/update/stop/revoke/peer loss; invalidate dependent proxy/recording/streams before removing toolchain. main/services/devices/device-service.ts:437; main/services/devices/device-service.ts:554; main/services/devices/device-service.ts:649; main/services/devices/device-service.ts:1166; main/services/devices/device-service.ts:1235; main/services/devices/device-service.ts:1317 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M131 H Device recording: recording/stopping/ready/failed × stopping/settling promises, kill/sweep timers 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Start/stop/process exit/collect/timeout/delete; only one recording per device, stop request not equal to file collected. main/services/devices/device-recording.ts:146; main/services/devices/device-recording.ts:184; main/services/devices/device-recording.ts:209; main/services/devices/device-recording.ts:261; main/services/devices/device-recording.ts:329 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M132 I Device/SSE simulator audience lifecycle: per-target live sockets and subscriptions, audience mapping and websocket inMessage/violated 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Subscribe/upgrade/frame/consent revoke/close; retained socket must be closed when sharing or audience authorization changes. main/services/aiden-remote-simulators.ts:84; main/services/aiden-remote-simulators.ts:268 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M133 H Dictation coordinator: operation identity, recording/stopping/delivering/error/cancelled; pillReady/holdToTalk/holdWatchActive/pendingRelease and hide/release/watchdog timers 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Press/release/toggle/warm-up/pill ready/transcript/result/error/cancel/dispose; stale operation result cannot paste after replacement/cancel. main/services/dictation-coordinator.ts:117; main/services/dictation-coordinator.ts:349; main/services/dictation-coordinator.ts:459; main/services/dictation-coordinator.ts:516; main/services/dictation-coordinator.ts:551; main/services/dictation-coordinator.ts:660 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M134 I Dictation physical-key/portal/shortcut lifecycle: bound × pressed, stopped/settled, recordingSuspended and registered/unavailable maps 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Register/unregister/press/release/lost key event/settings changes; release watchdog handles missing keyup, shortcut transaction may rollback. main/services/linux-dictation-portal.ts:39; main/services/dictation-key-state.ts:30; main/services/shortcut.ts:36; main/services/shortcut.ts:336; main/services/shortcut-transaction-core.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M135 H Local speech model download/load: downloading/failed with download/verify/extract phase; unload/loading/ready/failed engine state 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Download/cancel/remove/atomic replacement/load/release; loaded model identity changes emit unload before new load. main/services/local-speech-downloads.ts:261; main/services/local-speech-downloads.ts:337; main/services/local-speech-downloads.ts:355; main/services/local-speech-model-state.ts:34 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M136 I Local speech worker/serialized lane/idle unload: launching/live/retiring worker generation, pending RPCs/closed, active lease count/loaded/idle timer 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Acquire/request/cancel/worker exit/model change/release/idle timeout/shutdown; terminate old process before admitting new incompatible work. main/services/local-speech-worker-host.ts:98; main/services/local-speech-worker-host.ts:159; main/services/local-speech-worker-host.ts:224; main/services/local-speech-process-core.ts:88; main/services/local-speech-lane.ts:41; main/services/local-speech-idle-unload.ts:22 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M137 I Live transcription preview: decoding/stopped plus speech/pause segmentation and stable/provisional text; owner→session map 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Push audio/detect pause/decode/revise/end phrase/stop/owner invalidation; late decode cannot publish for ended session. main/services/local-speech-live-core.ts:89; main/services/local-speech-live-core.ts:200; main/services/local-speech-live-core.ts:219; main/services/local-speech-live-core.ts:310; main/services/gemini-live-transcription.ts:66; main/services/gemini-live-transcription.ts:252; main/services/gemini-live-transcription-core.ts:21 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M138 H TTS generation/playback: preparing/generating/buffering/playing/paused/completed/cancelled/failed × paused × segments-ready × current owner/retained job 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Start/synthesis segment/audio fetch/pause/resume/cancel/revoke/shutdown; completed generation is not playback completion, stale owner must lose audio access. main/services/tts/service.ts:138; main/services/tts/service.ts:283; main/services/tts/service.ts:452; main/services/tts/service.ts:509; main/services/tts/service.ts:542; main/services/tts/service.ts:824; main/services/tts/audio-store.ts:37 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M140 H Live-session ownership/thread finalization: per-owner sessions with connecting/resuming/closed, display bindings, shuttingDown, pending thread finalization/start waiters 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Start/protocol callbacks/display grant replacement/stop/shutdown/recovery; do not finalize transcript before in-flight start and final content are settled. main/services/gemini-live/service.ts:242; main/services/gemini-live/service.ts:384; main/services/gemini-live/service.ts:666; main/services/gemini-live/service.ts:722; main/services/gemini-live/service.ts:816; main/services/aiden-live-thread-store.ts:29 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M141 I Live computer-use bridge/socket ownership: calls queued/running/complete/cancelled, closed/currentCapture; SDK socket finished/localCloseRequested 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Queue/execute/tool cancellation/close; one current screen capture and no SDK-owned socket surviving local close. main/services/gemini-live/computer-use-bridge.ts:111; main/services/gemini-live/computer-use-bridge.ts:188; main/services/gemini-live/owned-sdk-connector.ts:136 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred backend:M143 H Form-fill artifacts/runtime/helper: not-downloaded/downloading/preparing/ready/error/unsupported; preparation/stopping promises, lifecycle controller, helper pending/poisoned 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Download/cancel/remove/load/execute/helper error/dispose; removal waits work, uncorrelatable protocol failure poisons all pending requests. main/services/form-fill/artifacts-core.ts:200; main/services/form-fill/artifacts-core.ts:292; main/services/form-fill/artifacts-core.ts:353; main/services/form-fill/artifacts-core.ts:399; main/services/form-fill/runtime.ts:29; main/services/form-fill/helper-client.ts:98 docs/audits/implicit-state-machines-backend-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred cli-native:C22 CLI speech worker/model lifetime 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. no worker → worker available → model/language held → transcribing → retire/recreate or crash retry transcribe, model switch, hang/exit/crash, stop Worker and client identity fence late exits; model recorded before request because failure may still retain native recognizer. packages/cli/src/speech.ts:23; packages/cli/src/speech.ts:72 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred cli-native:N11 Linux shortcut portal session and hold 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. creating → binding → bound; inactive ↔ active; finishing terminal D-Bus Response/Activated/Deactivated/ShortcutsChanged/Closed/owner change, stdin EOF waiting_create/bound/active/finishing plus sender/session IDs; only matched activation toggles hold. native/global-shortcuts-portal/main.c:19; native/global-shortcuts-portal/main.c:136 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred cli-native:N15 Audio-worklet chunk framing 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. partial samples retained → complete 20ms frame → emitted PCM → residual samples retained audio process blocks Sample-count buffer carries state across callbacks; this is an algorithmic streaming machine, not connection/session lifecycle. public/gemini-live-pcm-worklet.js:39 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred cli-native:N16 Foundation Models helper file handshake 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. process marker published → request read/deleted → cancellation marker checked → service invoked → atomic response → process marker removed launch, preflight cancellation, parse/model failure, response encode/write, process return Availability enum is external state; the helper owns the file/request/process receipt lifecycle. Cancellation after invocation is enforced by its parent process supervisor, not an internal polling loop. native/apple-foundation-models/Sources/AidenFoundationModelsHelper/main.swift:25 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C27 Composer dictation controller 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Permission/setup/start → recording/live preview → stop-tail/transcribing → done/error/cancelled, plus explicit recorded-retry consent and pending-stop-during-start. generation gate prevents late setup/transcription writes; composer and floating pill are distinct orchestration owners. renderer/lib/use-voice-recorder.ts:44; renderer/lib/use-voice-recorder.ts:59; renderer/pill/pill-app.tsx:87 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C28 Dictation admission/deadline/VAD 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Gate idle/starting/current/cancelled generations; deadline active/expired; silence detector unheard/heard/hangover/fired; retry consent absent/waiting/approved/denied. Cancellation invalidates operation; timer terminal only once; consent is a separate authority. renderer/lib/dictation-operation-gate.ts:6; renderer/lib/dictation-operation-gate.ts:66; renderer/lib/dictation-vad.ts:17; renderer/lib/gemini-recorded-retry.ts:8 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C29 PCM recording, ordered send, live finish 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. PCM carry/partial-chunk buffers; queue pending/in-flight/backpressured; audioStopped/settled/finishPromise/failure; recorder accumulating→flush-wait→finished. Stop waits bounded worklet flush; one finalization promise; queue cannot reorder audio. renderer/lib/live-pcm-capture.ts:14; renderer/lib/live-pcm-capture.ts:134; renderer/lib/pcm-recorder.ts:33 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C30 Local speech preview 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Start pending with buffered chunks → session ready → batched send → ended, with sending flag. Overflow/error disables preview, late-start success is stopped if already ended; final transcription stays independent. renderer/lib/local-live-preview.ts:16 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C32 Live assistant session 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Availability/setup/start/session/reconnect-required/stop; operation/media/availability generations; microphone permission/enabled/active; screen chooser/binding/pump; computer-use enabled/acting/busy. Late permission/media resolution must release resources without reviving cancelled session. renderer/components/assistant/use-assistant-live.ts:481; renderer/components/assistant/use-assistant-live.ts:518; renderer/components/assistant/use-assistant-live.ts:1145; renderer/components/assistant/use-assistant-live.ts:1244; renderer/components/assistant/use-assistant-live.ts:1305 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C34 Read Aloud controller and player 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Job source/pending/current × generating/playing/paused/finished/error × scheduled segments and pumping/finished epochs. Start supersedes previous, pause/resume affects context, stop disposes sources; old fetch/decode/end callback cannot advance new playback. renderer/lib/tts-client.ts:42; renderer/lib/tts-client.ts:314; renderer/lib/tts-client.ts:321; renderer/lib/tts-client.ts:340; renderer/lib/tts-client.ts:360; renderer/lib/tts-player.ts:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C36 Device video transport/decoder/fallback 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Stopped/connecting/streaming/error × waiting keyframe/configuring/first frame × AVC/WebSocket versus MJPEG × separate input socket renewal. First-frame/stall/prime timers, decoder failure, socket close, grant renewal, explicit stop; drop non-keyframe data after reset and avoid old sockets controlling replacement client. renderer/lib/device-stream.ts:530; renderer/lib/device-stream.ts:558; renderer/lib/device-stream.ts:621; renderer/lib/device-stream.ts:748; renderer/lib/device-stream.ts:812; renderer/lib/device-stream.ts:1063; renderer/lib/device-stream.ts:1160 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C37 Device input gesture transactions 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Pointer/touch down/move/up/cancel; wheel gesture open/idle timeout; Duo command pending/receipt/timeout; controls visible×busy; mini-player drag/click distinction. Always finish contacts/keys on cancellation; command acknowledgments match request IDs. renderer/lib/device-multitouch.ts:126; renderer/lib/device-duo-control.ts:83; renderer/lib/device-controls.ts:43; renderer/components/device-mini-player.tsx:107 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C38 Fold posture read/write controller 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Watching/paused/disposed × reading/writing/pending/retry timer × optimistic angle/reported fold. Writes suspend reads; result or timeout restores/reconciles angle; identity/abort guards ignore stale read. renderer/lib/device-fold.ts:137 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C39 Device tools/record/erase/clipboard/install 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Idle/confirmation/pending/success/error, recording starting/recording/stopping/artifact receipt, clipboard bounded retry. Device identity and disposal matter; side-effect controls are distinct from passive device status DTOs. renderer/components/device-record-control.tsx:19; renderer/components/device-erase-control.tsx:26; renderer/components/device-clipboard-controls.tsx:20; renderer/lib/device-clipboard.ts:52; renderer/components/device-tools-panel.tsx:357 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C41 Browser panel/navigation/annotation 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Browser/tab selection and loading/error/controls; annotation draft/edit/preview/delivery/cancel; serialized preview tail + revision, debounce timer. Latest edit owns preview; old queued work must not repaint cancelled editor. renderer/components/browser-panel.tsx:26; renderer/lib/browser-ui-state.ts:9; renderer/components/browser-annotation-editor.tsx:10; renderer/lib/browser-annotation-preview-queue.ts:3 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:C75 Recording playback / preview resources 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Idle/loading/ready/missing plus reveal-failed; object URL exists/revoked, mounted guard; image preview loading/failed retry/selected dialog. Async result after unmount must not allocate retained URL; native recording counterparts belong to same family via N39. renderer/components/browser-recording-card.tsx:28; renderer/components/transcript-image.tsx:8; renderer/components/message-attachments.tsx:80 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:N29 Native dictation/audio resource lifecycle 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. idle/requestingPermission(or preparing)/listening/transcribing × native/Mac provider × audio tap/session active × accepts draft updates/session generation. Stop-keeping finalizes recognition, send/cancel invalidates session; late permission/recognition result cannot change new draft. iOS native finalization timeout is independent of Mac transcription task. ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:11; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:77; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:110; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:207; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:330; ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift:461; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/ComposerVoiceInputController.kt:49; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/ComposerVoiceInputController.kt:62; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/ComposerVoiceInputController.kt:89; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/ComposerVoiceInputController.kt:112 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:N30 Native Read Aloud 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Idle/loading remote source/job/segments/playing/paused/stopped/error, generation/current-source/job revision. Fetch/poll/audio-ended/interruption/stop; stop invalidates pending work and cancels remote job as supported. Verify source revision before playing newly fetched segments. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10713; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10723; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:10735; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenReadAloudPlayback.kt:26 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:N31 Simulator list/view model 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. idle/starting/connecting/streaming/open-on-Mac/shut-down/failed plus screen/input enabled, app foreground and selected device. User open/start/retry/leave and device state changes; old grant/boot result cannot revive dismissed viewer. ios/AidenOnTheGo/Features/Simulators/AidenSimulatorViewerModel.swift:208; ios/AidenOnTheGo/Features/Simulators/AidenSimulatorViewerModel.swift:368; ios/AidenOnTheGo/Features/Simulators/AidenSimulatorViewerModel.swift:409; ios/AidenOnTheGo/Features/Simulators/AidenSimulatorViewerModel.swift:482; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/simulators/AidenSimulatorsViewModel.kt:135; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/simulators/AidenSimulatorsViewModel.kt:344; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/simulators/AidenSimulatorsViewModel.kt:391; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/simulators/AidenSimulatorViewerState.kt:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:N32 Native simulator frame/input transport 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. Frame stream running/generation/first-frame/decode pending; latest-frame mailbox, input socket opening/open/renewable/retried/closed; stream/decode/retry jobs. Drop superseded frames, finite renewal, cancel all resources on stop. MJPEG parser is separate N41. ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:85; ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:169; ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:195; ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:277; ios/AidenOnTheGo/Networking/AidenSimulatorStream.swift:370; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:395; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:404; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:449; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:607 docs/audits/implicit-state-machines-clients-2026-11-04.md +13 T2 Audio, video, input, recording and device sessions P5 targeted; remainder deferred clients:N33 Native remote visuals/WebView 3 3 4 2 Capture/input/playback must respect permission and foreground ownership while buffers and workers drain. loading/document/ready/failed/outdated; document ID/page-ready/pending prompt/link/retry; cache stamp/owner/generation. Bridge events only for current trusted document; external link prompt and chat prompt submission require separate user intent. ios/AidenOnTheGo/Features/Remote/AidenVisualViewer.swift:25; ios/AidenOnTheGo/Features/Remote/AidenVisualViewer.swift:310; ios/AidenOnTheGo/Features/Remote/AidenVisualDocument.swift:8; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenVisualViewerModel.kt:17; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenVisualViewerScreen.kt:93; android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenVisualDocumentCache.kt:39 docs/audits/implicit-state-machines-clients-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred backend:M001 I Application quit: forceAppQuit × cleanupStarted × shutdownStarted × installUpdateOnQuit, pending image quit coverage and soak receipts 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. Close, before-quit, cancellation, install-update and teardown settlement advance separate flags. Cleanup once; a cancelled quit must reopen admission, actual shutdown must not. main/index.ts:241; main/index.ts:386; main/index.ts:543; main/index.ts:711; main/index.ts:1838; main/index.ts:2208 docs/audits/implicit-state-machines-backend-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred backend:M002 I Lifecycle question/action gate: in-flight check plus queued continuation 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. Serialize lifecycle checks and defer actions until the result; failure must release gate and not execute stale close. main/application-lifecycle-core.ts:45 docs/audits/implicit-state-machines-backend-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred backend:M003 I Startup IPC and renderer readiness: opened/admitted bit, renderer generation, shared wait 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. IPC opens only once startup is ready; replacement documents invalidate prior readiness; concurrent windows share readiness wait. main/services/startup-ipc-admission.ts:24; main/services/renderer-readiness-core.ts:8; main/index.ts:1894; main/index.ts:2292 docs/audits/implicit-state-machines-backend-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred backend:M004 I Pill-window creation: absent / loading promise / live window / destroyed 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. Concurrent create shares one promise; destruction and failed loading must clear correct owner. main/windows/pill-window.ts:20 docs/audits/implicit-state-machines-backend-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred backend:M165 H App updater: idle/checking/downloading/ready/error, in-flight operation, manual pending, started/disposed and retry/stall timers 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. Manual/periodic check/download/progress/stall/retry/install/quit; install only ready version and stop all scheduled work on disposal. main/services/app-updater-core.ts:55; main/services/app-updater-core.ts:157; main/services/app-updater-core.ts:182; main/services/app-updater-core.ts:198; main/services/app-updater.ts:124; main/services/app-updater.ts:172; main/services/app-updater.ts:323 docs/audits/implicit-state-machines-backend-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred backend:M192 I Registration-once infrastructure: unregistered→registered/installed/requested 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. Platform handlers, custom schemes, attachment/visual/asset protocols and discovery lazily register once; failed registration must not incorrectly latch success. main/platform.ts:122; main/services/custom-schemes-core.ts:44; main/services/chat-attachment-protocol.ts:6; main/services/generative-ui-protocol.ts:15; main/services/studio-assets/protocol.ts:4; main/services/browser-discovery.ts:10 docs/audits/implicit-state-machines-backend-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred cli-native:C01 Daemon ownership and startup 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. absent/stale lease → start lease held → spawning → owner/socket ready; timeout → terminating start, readiness polling, competing owner, spawn failure, deadline The start lease serializes starts; readiness belongs to the spawned PID, and failed startup tears down its tree. packages/cli/src/serve-lifecycle.ts:200; packages/cli/src/serve-lifecycle.ts:287 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred cli-native:C02 Daemon shutdown and stale recovery 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. live verified owner → TERM → waiting → KILL → gone/artifacts cleared; foreign or unverifiable owner blocks action stop, lease change, PID exit/reuse, grace deadline Owner token/start time and process identity govern cleanup; detached group and recorded MCP groups have separate teardown. packages/cli/src/serve-lifecycle.ts:354 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred cli-native:C03 Serve admission and resource lifetime 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. lease held → services starting → socket serving → ingress closed → services draining → socket/lease released start, ready, signal, initialization error, finally Chat admission closes synchronously before asynchronous ingress shutdown; cleanup results are settled together. packages/cli/src/serve.ts:30; packages/cli/src/serve.ts:41 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred cli-native:C05 OS service install/replacement rollback 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. inspected → previous daemon stopped → installed → ready → network configured; failure restores/removes service install, readiness timeout, manager failure, network failure, uninstall Service identity rechecked before mutation; service readiness and network reachability are independent outcomes. packages/cli/src/service.ts:167; packages/cli/src/service.ts:516 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred cli-native:C07 Tailscale health wait 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. unchecked → probing → ready or retry → timed out/cancelled bounded HTTPS response, socket error, abort, retry timer Pinned CA supplied where required; response byte bound and single-settlement guard; route preparation precedes code display. packages/cli/src/reachability.ts:296; packages/cli/src/reachability.ts:337; packages/cli/src/reachability.ts:366 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred cli-native:N14 Linux managed-payload staging transaction 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. validated inventory/approval → private staging → copied+verified → published → parent synced; prepublish discard or published-uncertain stage, validation/copy failure, publish, fsync failure published flag forbids deleting a generation already published; receipt explicitly does not grant runtime admission. Ancillary staging tool. native/linux-managed-payload/src/stage.rs:194 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred cli-native:O02 Distribution transaction 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. unprepared → prepared → built → verified → promoted; failure → discard or aggregate failure prepare/build/verify/promote/discard Only prepared staging is discarded; packaging is operational tooling, not a live application lifecycle. scripts/run-macos-distribution.mjs:218 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +14 T2 Startup, shutdown, update and installation coordination P5 targeted; remainder deferred clients:C70 App update notice / reset / restart affordance 3 2 4 3 Partial startup, cancelled quit or update can leave admission closed, work orphaned or installation incomplete. Snapshot received, dismissed-key, entering/present/exiting banner; retrying/restarting with fallback timer; reset confirmation/resetting/error. Backend update status is explicit DTO; UI suppression and action lifetime is implicit. renderer/components/chat-sidebar.tsx:239; renderer/components/settings/about-settings.tsx:70; renderer/lib/use-app-update-snapshot.ts:7 docs/audits/implicit-state-machines-clients-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 backend:M086 I MCP discovery backoff/prewarm and failure diagnostics: generation-bound negative cache, active/idle/in-flight times, running prewarm, degraded-server windows 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Discover/fail/retry/config change/idle eviction/recovery/close; stale failures not carried into new generation. main/services/mcp-tool-discovery-core.ts:295; main/services/mcp-tool-discovery-core.ts:334; main/services/mcp-tool-discovery-core.ts:371; main/services/mcp-tool-discovery-core.ts:418; main/services/mcp-failure-diagnostics.ts:461 docs/audits/implicit-state-machines-backend-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 backend:M096 H Provider usage-limit queue/circuit breaker: entry status, tester reservation, waiter/flight/line maps, draining and retry-now cooldown 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Rate/billing responses, deadline wake, probe/retry/cancel and successful requests; one tester per recovering provider and bounded retained waiters. main/services/usage-limit-core.ts:676; main/services/usage-limit-core.ts:778; main/services/usage-limit-core.ts:1001; main/services/usage-limit-service.ts:38 docs/audits/implicit-state-machines-backend-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 backend:M098 I Web-search credential pool cooldown: per-key cooldown record and rotating cursors 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Claim/request quota failure/success/reset; no immediate retry of quota-blocked key, identity changes invalidate stale cooldown. main/services/web-search-key-pool-core.ts:146; main/services/web-search-key-pool-core.ts:315 docs/audits/implicit-state-machines-backend-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 backend:M111 H Advisor attempt workflow: prepared → dispatch_started → completed/failed/cancelled; restart prepared→cancelled, dispatched→unknown 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Reserve/admit/dispatch/result/timeout/restart; cannot retry unknown effect as if no request left host. main/services/advisor-attempt-store.ts:198; main/services/advisor-attempt-store.ts:234; main/services/advisor-attempt-store.ts:264; main/services/advisor-attempt-store.ts:271; main/services/advisor-runtime.ts:537; main/services/advisor-runtime.ts:601 docs/audits/implicit-state-machines-backend-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 backend:M167 I Diagnostic/usage/support flushers: dirty × running/counting/scheduled × stopped/persistenceFailed, queue and retry 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Mutate/debounce/flush/close/retry; changes arriving during write require follow-up flush, terminal shutdown bounded. main/services/diagnostic-health.ts:50; main/services/diagnostic-journal.ts:64; main/services/model-pace-core.ts:347; main/services/inbox-dock-badge.ts:243 docs/audits/implicit-state-machines-backend-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 backend:M169 I Single-flight/coalescing operation gates: absent/pending/fulfilled/rejected/superseded, current-token identity 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Replace/retry/wait/clear; waiters follow replacement while obsolete failure remains observable only to its caller. Shared pattern also used by model/catalog/path discovery. main/services/superseding-task-core.ts:19; main/services/git-executable.ts:123; main/services/models-catalog-core.ts:86 docs/audits/implicit-state-machines-backend-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 backend:M183 I GitHub rate governor and GraphQL reservations: scope pausedUntil/generation/strikes, reading/reset window/reserved budget/last operation cost 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Rate response increments generation/backoff; success clears only matching generation. Reserve before dispatch and settle response against monotonic reset/remaining evidence, preserve background reserve. main/services/github/github-rate-limit.ts:23; main/services/github/github-rate-limit.ts:42; main/services/github/github-rate-limit.ts:57; main/services/github/github-graphql-budget.ts:83; main/services/github/github-graphql-budget.ts:97; main/services/github/github-graphql-budget.ts:112 docs/audits/implicit-state-machines-backend-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 backend:M184 I GitHub request batching/cache/credential lookup: queued→inflight→cached/failed plus flushScheduled, active document slots/waiters 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Read batches by host and operation, split failed multi-entry batch, release document slot once; caller abort need not cancel shared work. Credential cache and inflight lookup have separate freshness. main/services/github/github-pull-request-reader.ts:81; main/services/github/github-pull-request-reader.ts:102; main/services/github/github-pull-request-reader.ts:128; main/services/github/github-pull-request-reader.ts:140; main/services/github/github-pull-request-reader.ts:184; main/services/github/github-credentials.ts:216 docs/audits/implicit-state-machines-backend-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 cli-native:C17 Scheduled inference response metering 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. per-message empty → per-block streaming → block end → terminal signature accounting → next message delta/end/message_start/message_end State is streamed/signature maps plus cumulative budget; avoids double counting partial snapshots and enforces abort on resource budgets. Algorithmic streaming machine. packages/cli/src/scheduled-inference.ts:21 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 cli-native:C23 Avatar decoder admission and worker 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. below concurrency limit → active slot → worker request → decoded/error/timeout → terminated/slot released decode, message, exit, error, timer Bounded concurrent work and finally cleanup; relies on shared avatar service for upload lifecycle. packages/cli/src/bot-avatars.ts:7 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +15 T3 Budgets, bounded queues, backoff and single-flight work Deferred after P6 clients:C24 Context-pressure/deadline feed 2 2 3 2 Incorrect release or retry creates starvation, excess load or stuck work; authority-bearing variants are ranked higher. Scoped chat live/history/draft reads × debounce and request generations; expiry handled/returned maps; paused-until deadline wait. Navigation invalidates old responses; return/expiry actions dedupe by identity. renderer/lib/context-pressure-feed.ts:34; renderer/lib/use-expired-cache-return.ts:23; renderer/lib/expired-cache-return.ts:83; renderer/lib/use-usage-limit-wait.ts:25 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M014 I Delta coalescing: per-stream pending buffers/timers 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Delta enqueue → scheduled flush → terminal flush/removal. Terminal event must follow retained deltas and stale timer must not affect replacement stream. main/services/generation-delta-coalescer.ts:61 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M016 H Local run observation: idle/streaming/ended/gone plus holder/target subscriptions 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Subscribe/replay/live terminal/unsubscribe/source disappearance; cursor/event ordering and last-holder detach matter. main/services/local-run-observers.ts:74; main/services/local-run-observers.ts:108; main/services/local-run-observers.ts:252 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M017 I Chat activity/attention/read state: stream counts, detached prompts, revisions and markers 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Start/end stream, prompt answer/expiry, detach, mark read; read status and active work must not accidentally clear outstanding attention. main/services/chat-activity-core.ts:22; main/services/chat-pending-attention.ts:37; main/services/chat-progress-events.ts:5; main/services/chat-read-markers.ts:64 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M018 H Chat triage/snooze: started, stored snoozes, timer/retry and waking classification 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Snooze/wake, person writes, needs-input/approval/failure, expiration; publish-before-arm and restart expiration. main/services/chat-triage.ts:116; main/services/chat-triage.ts:248; main/services/chat-triage.ts:325; main/services/chat-triage.ts:347 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M032 H Desktop live Bot projection: feed opening/live/ended, run starts, queued classifiers, subscriber replay/buffer and stopping/resuming overlays 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Watch frames/state notifications/cards/idle teardown/reopen; serial feed queue and run identity prevent old snapshots masking current work. main/services/bot-runtime/live-projection.ts:844; main/services/bot-runtime/live-projection.ts:1043; main/services/bot-runtime/live-projection.ts:1239; main/services/bot-runtime/live-projection.ts:1280; main/services/bot-runtime/live-projection.ts:1385 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M039 H Bot issue workflow 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Open issue → action claim → resolved/released/resettled; dedupe key prevents repeat delivery, action claim prevents simultaneous remedies. main/services/bot-issues/service.ts:139; main/services/bot-issues/service.ts:175; main/services/bot-issues/service.ts:194; main/services/bot-issues/service.ts:216; main/services/bot-issues/service.ts:232 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M062 I Chat-progress stream refresh: closed/running/dirty/scheduled/revalidating, versions and audience cursors 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Snapshot/update/coalesce/revalidate/close; lost dirty update or authorization change must not leak stale private data. main/services/aiden-remote-chat-progress.ts:84; main/services/aiden-remote-chat-progress.ts:456; main/services/aiden-remote-chat-progress.ts:568 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M063 I Host-feed projection: dirty × refreshChain × closed, pending run changes, audience subscriptions, timer 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Change/refresh/heartbeat/audience expiry/close; serialized refresh and per-audience event identity. main/services/aiden-remote-host-feed.ts:185; main/services/aiden-remote-host-feed.ts:356 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M064 H Remote Bot live projector: per-Bot projector promise, state, watch lane, idle timer, stopping/stopRequested/resuming/resumeRequested/placedFailing 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Subscribe/frame/pause/resume/cards/unwatch/close; compatibility projection changes paused→unavailable for older audience. main/services/aiden-remote-bot-session.ts:791; main/services/aiden-remote-bot-session.ts:804; main/services/aiden-remote-bot-session.ts:883; main/services/aiden-remote-bot-session.ts:1060; main/services/aiden-remote-bot-session.ts:1243; main/services/aiden-remote-bot-session.ts:1586 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M077 I Telegram activity/thinking coalescer: dirty × pending × finished + timer 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Event/thinking tick/finish; late timer must not send after terminal delivery. main/services/telegram/telegram-activity.ts:34 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M092 I ACP event adapter/tool activity: started × terminal and tracked tool call/diff retention 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Session update/start/result/end; terminal once, late tool updates cannot keep stale diffs forever. main/services/acp/pi-events.ts:37; main/services/acp/activity.ts:167; main/services/acp/activity.ts:261 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M104 H Subagent public event projection/persistence: queued→starting→running→terminal with retained milestone/context maps and persistence tail 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Spawn/event/result/filter/persist; projection cannot publish success before durable boundary and must reconcile late events. main/services/subagents/subagent-event-projector.ts:240; main/services/subagents/subagent-event-projector.ts:292; main/services/subagents/subagent-event-projector.ts:569 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred backend:M115 I Agent notice delivery/wake admission: per-chat chain, saved message, wake budget and turn busy 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Save notice then steer/queue/wake; avoid duplicate wake or losing persisted notice when current run ends during admission. main/services/follow-through/notice-delivery.ts:63; main/services/follow-through/notice-delivery.ts:99; main/services/follow-through/notice-delivery.ts:129; main/services/follow-through/follow-through-main.ts:120 docs/audits/implicit-state-machines-backend-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:C07 Remote run projection 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Explicit pure transition functions track idle/running/done/error/cancelled plus run identity, seq, incomplete, handedOff, prompts, textStreaming. Event gaps trigger refetch; handoff determines live versus persisted transcript. This is an explicit reducer-like island; external subscription/read lifecycle remains implicit. renderer/lib/hosts/remote-stream-translator.ts:28; renderer/lib/hosts/remote-stream-translator.ts:192; renderer/lib/hosts/remote-stream-translator.ts:359; renderer/lib/hosts/remote-stream-translator.ts:382; renderer/lib/hosts/remote-stream-translator.ts:387; renderer/lib/hosts/remote-stream-translator.ts:422 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:C21 Failure/restart/interrupt recovery 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Failed/interrupted → retry/resume/dismiss pending → recovered/failed; owner-token records prevent one stale result clearing a newer action. Actual generation and displayed failure card may outlive one another. renderer/main/chat-pane.tsx:3311; renderer/main/chat-pane.tsx:3373; renderer/main/remote-chat-view.tsx:528; renderer/main/bots/bot-chat-pane.tsx:965 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:C23 Inbox read/triage optimistic overlays 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Unread/read-through marker, triage/snooze/archive overlay, pending reads, undo batch, stale sidebar cache. Read result merges by owner/revision; undo must reverse only its batch, not newer server activity. renderer/lib/use-inbox-triage.ts:181; renderer/lib/use-mark-chat-read.ts:39; renderer/lib/use-chat-activity.ts:38; renderer/lib/use-sidebar-view.ts:20 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:C25 Shared monotonic subagent and todo fences 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Subagent queued→starting→active→terminal; revisions enrich only matching immutable identity, no terminal resurrection or timestamp/counter rollback. Todo read fence tracks active chat+revision against delayed snapshot. These are explicit guard helpers used by distributed owners. renderer/shared/subagent-runs.ts:816; renderer/shared/subagent-runs.ts:832; renderer/shared/todo.ts:31 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:C26 Subagent selection/detail/stop/announcement 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Selected run/detail-request version, loading/error, pending stop, live/detail speech debounce, per-batch collapse latch and visit generation. Selection/navigation/revision updates cannot announce or act on old owner; accessibility timing has its own pending state. renderer/components/environment-panel.tsx:370; renderer/components/environment-panel.tsx:399; renderer/lib/subagent-panel-state.ts:288; renderer/components/subagent-composer-pill.tsx:120 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:C31 Slow-model notice 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Hidden idle → loading grace timer → shown → disposed; ready/failed cancels timer, unrelated unloaded event does not reset active load. Hook maps state by model identity. renderer/lib/slow-model-load.ts:14; renderer/lib/use-slow-model-load.ts:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:C58 Bot memory/rules/lessons/skills/issue cards 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Edit/save/error, pending-removal map+hidden IDs+undo window, proposal pending/accepted/dismissed, issue action pending/settled. Capture entry identity/revision; undo timer and navigation can outlive initiating row. renderer/main/bots/bot-memory-page.tsx:286; renderer/main/bots/use-bot-rules.ts:26; renderer/components/bots/lesson-cards.tsx:11; renderer/components/bots/skill-proposal-card.tsx:10; renderer/components/bots/bot-issue-card.tsx:35 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:C60 Bot activity wording/preferences/status speech 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Optimistic value + saved baseline + serialized queue/pending count; timed preview frames; announcement armed/debounce; starter pending selection. Serialize settings edits; delayed failure cannot roll back newer value. renderer/main/bots/bot-chat-activity-page.tsx:244; renderer/main/bots/bot-status-line.tsx:37; renderer/main/bots/bot-starter-carousel.tsx:30 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:N13 Task/agent progress observer 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. idle/connecting/live/reconnecting/denied × task epoch/revision × agent epoch/revision × selected historical roster request. Snapshot/deltas/403/foreground/background; denied access clears only relevant state, monotonic versions reject stale frames, historical selection cannot overwrite current roster. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2678; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2767; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2876; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2909; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:2988; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:233; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:848; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1091; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:1100 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:N18 Native message history/title/visual refresh 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Initial/settled window/loading older/exhausted; title and visual refresh pending/backoff/done. Transcript generation and request context preserve live/optimistic entries when older pages or delayed title arrive. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1464; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5232; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5293; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:5373; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:211; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:305; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:309; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3528; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:3631 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:N37 Live Activities / notifications / alert throttling 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. No activity/active/update-throttled/ended with latest pending value; alert seen/deduped/throttled per run; foreground/quiet suppression. Terminal update must not be overwritten by queued older active update; task cancellation flush/drop semantics matter. ios/AidenOnTheGo/LiveActivities/AidenRemoteLiveActivityManager.swift:7; ios/AidenOnTheGo/LiveActivities/AidenLatestValueThrottle.swift:11; ios/AidenOnTheGo/Features/Remote/AidenScheduledRunNotifier.swift:9; android/app/src/main/java/sbtbiswas/AidenOnTheGo/notifications/AidenRemoteLiveNotificationManager.kt:19; android/app/src/main/java/sbtbiswas/AidenOnTheGo/notifications/AidenNotificationThrottle.kt:16 docs/audits/implicit-state-machines-clients-2026-11-04.md +16 T3 Run projections, attention, notices and monotonic views P3/P6 boundary tests; extraction deferred clients:N42 ios/AidenOnTheGo/Models/AidenChat.swift:3808 foreign-run projection and ios/AidenOnTheGo/Features/Chat/AidenStreamingRevealGate.swift:104; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenForeignRun.kt:19, android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenForeignRun.kt:66; renderer renderer/lib/streaming-reveal.ts:411 2 1 3 2 Out-of-order projection can misstate progress or hide attention; it must never become execution authority. Foreign-run event projection, cumulative text tail/byte counters, markdown sealed prefix/tail; snapshot versus append/rewrite changes interpretation. Explicit pure reducers/projections exist here and should not be mistaken for independent host execution engines. ios/AidenOnTheGo/Models/AidenChat.swift:3808; ios/AidenOnTheGo/Features/Chat/AidenStreamingRevealGate.swift:104; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenForeignRun.kt:19; android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenForeignRun.kt:66; renderer/lib/streaming-reveal.ts:411 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 backend:M193 H Main-owned onboarding evidence: incomplete/deferred/completed × lastSatisfiedStep × selected provider evidence 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. Read/migrate/reconcile/progress/finish/reset; profile precedes provider, completion needs ready evidence, lost readiness can reopen incomplete; current document gates publication. main/services/onboarding-state.ts:63; main/services/onboarding-state.ts:105; main/services/onboarding-state.ts:157; main/services/onboarding-state-core.ts:1; main/services/onboarding-reset-core.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 cli-native:C06 Startup pairing presentation 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. address preparation → pairing window → QR shown → polling → paired/failed/expired/superseded/cancelled foreground pair, status, deadline, signal Only the matching session is reported/cancelled; cancelling service-install pairing leaves the daemon running. packages/cli/src/serve-command.ts:86; packages/cli/src/service.ts:614 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:C17 Workspace composer transaction 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. Draft × text/attachment revisions × IME composing × attaching/sending × permission confirmation × slash action/session command/compaction busy. Refs synchronously claim work; callbacks compare revisions before removing submitted input. Manual compaction keeps draft editable while queue owns delivery hold. renderer/components/composer.tsx:469; renderer/components/composer.tsx:590; renderer/components/composer.tsx:601; renderer/components/composer.tsx:625; renderer/components/composer.tsx:1897 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:C46 Image gallery/viewer actions 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. Loading/pagination/error/request sequence × filter/focus/selected image × zoom/pan/fullscreen/action pending. Navigation restores originating focus; revoke temporary URLs and ignore outdated pages. renderer/images/use-gallery.ts:21; renderer/images/image-library.tsx:45; renderer/images/viewer/image-viewer.tsx:44; renderer/images/viewer/use-image-actions.ts:10 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:C49 Onboarding progression 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. State loading/error/ready × current step × provider skipped/saving/discovering/ready × Bots step/completion. Next/back/provider-auth/save/feature-capability changes; saving ref plus load generation fence transitions; completion must persist before closing. renderer/components/onboarding-flow.tsx:169; renderer/components/onboarding-flow.tsx:274; renderer/components/onboarding-flow.tsx:291; renderer/components/onboarding-flow.tsx:403; renderer/lib/onboarding-state.ts:9 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:C54 Voice/model download settings 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. Not downloaded/downloading/ready/error/current selection, explicit download/cancel/delete/load; settings draft/saving/testing audio. Polling observes status rather than authorizing network work. renderer/components/settings/local-voice-settings.tsx:36; renderer/components/settings/model-manager-view.tsx:16; renderer/components/settings/voice-settings.tsx:57; renderer/components/settings/tts-settings.tsx:51; renderer/components/settings/live-audio-settings.tsx:7; renderer/components/settings/gemini-live-settings.tsx:22 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:C55 Manual model/benchmark/image catalogs 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. Key draft/connect/fetch in-flight/ready/stale/error/disconnect; selected provider/model IDs and per-provider requests. Explicit fetch required; display cache cannot become runtime authorization or model inventory authority. renderer/components/settings/model-pad/model-pad-settings.tsx:75; renderer/components/settings/model-pad/model-pad-data-rows.tsx:42; renderer/components/settings/image-generation-settings.tsx:61 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:N19 Native composer catalogs and model selection 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. Default/explicit choice; suggestion catalog not-loaded/loading/loaded/retry-pending per skills/agents/files; active token/menu/focus. Explicit model choice survives refresh; capabilities gate reads, new query/owner invalidates suggestions. ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1252; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:3037; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4119; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4205; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:333; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2544; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt:2660; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/shared/AidenModelPicker.kt:108 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:N27 Generated/canonical avatar lifecycle 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. idle/loading/normalizing/ready/uploading/reverting/failed × candidate bytes/generation/authoritative avatar revision. Picker→accept→normalize→explicit upload; cancellation, failed mutation/re-read, revert and stale canonical download compete. Candidate preview is not persisted canonical photo. ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:29; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:301; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:422; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:540; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:628; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:821; ios/AidenOnTheGo/Features/Bots/AidenBotGeneratedAvatarLifecycle.swift:859; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt:51; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt:155; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotCanonicalAvatarView.kt:62 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:N45 Native optimistic Inbox triage/undo 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. Optimistic row → success/rollback/conflict; undo window fresh/stale and exact write revision; read-view stamp. Rollback preserves newer reads; host switch suppresses stale notice; Android swipe conflict may retry fresh revision once but Undo never retries. iOS counterpart state sites inspected, Android handlers read. android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenInboxTriage.kt:70; ios/AidenOnTheGo/Features/Remote/AidenInboxViews.swift:8; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:207 docs/audits/implicit-state-machines-clients-2026-11-04.md +17 T3 User-driven editors, setup and optimistic workflow UI Deferred after P6 clients:N49 Native settings optimistic baseline and rebind 2 2 3 2 Late saves, cancellation or rollback can target stale entities or mislead the user about a completed action. Bound installation/generation × cached/current × saving memory/speech × unconfirmed baseline × action counters × refresh/poll jobs. Rebind cancels work and restores confirmed baseline; any overlapping status read is rejected by action counter, including reads begun during mutation. iOS settings read/write state inspected as corresponding family, not claimed identical implementation. android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenSettingsStore.kt:131; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenSettingsStore.kt:156; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenSettingsStore.kt:191; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/settings/AidenSettingsStore.kt:244; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:4301; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:4474 docs/audits/implicit-state-machines-clients-2026-11-04.md +18 T3 Protocol framing, decoding and local parser states Deferred; validate at owner phase cli-native:C04 Local daemon command framing 2 2 3 2 Framing/sequence errors can desynchronize a stream; native privilege-boundary parsers are ranked with supervision/authority. connecting → request sent → partial response → newline frame → resolved/rejected/closed connect/data/end/error/timeout One response promise, byte ceiling, UTF-8 chunk decoding and missing-response rejection. A stream protocol machine, not a product mode. packages/cli/src/daemon-control.ts:5; packages/cli/src/serve.ts:54 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +18 T3 Protocol framing, decoding and local parser states Deferred; validate at owner phase clients:C47 Visual document / HTML iframe handshake 2 2 3 2 Framing/sequence errors can desynchronize a stream; native privilege-boundary parsers are ranked with supervision/authority. loading/mounted/themed/ready/error; document identity, last prompt, announced height; native visual local state/events. Origin/document ownership validates bridge events; reload invalidates old readiness. renderer/visual-viewer/main.tsx:109; renderer/components/html-artifact-frame.tsx:44; renderer/components/aiden-ui/aiden-ui-block.tsx:29 docs/audits/implicit-state-machines-clients-2026-11-04.md +18 T3 Protocol framing, decoding and local parser states Deferred; validate at owner phase clients:N41 ios/AidenOnTheGo/Networking/AidenSSEParser.swift:3, ios/AidenOnTheGo/Networking/AidenMJPEGMultipartParser.swift:8; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSSEParser.kt:108, android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRunEvents.kt:299, android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:53; renderer renderer/lib/device-stream.ts:349 2 2 3 2 Framing/sequence errors can desynchronize a stream; native privilege-boundary parsers are ranked with supervision/authority. SSE event ID/name/data/frame byte count across lines; MJPEG boundary/header/body/length across chunks; AVCC incomplete length/payload buffer. Data feed advances state; boundary/blank line emits frame; byte caps/invalid fields fail; reset/cancel drops partial frame. Android MJPEG explicit enum still has distributed incremental-buffer ownership. ios/AidenOnTheGo/Networking/AidenSSEParser.swift:3; ios/AidenOnTheGo/Networking/AidenMJPEGMultipartParser.swift:8; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSSEParser.kt:108; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRunEvents.kt:299; android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenSimulatorStream.kt:53; renderer/lib/device-stream.ts:349 docs/audits/implicit-state-machines-clients-2026-11-04.md +18 T3 Protocol framing, decoding and local parser states Deferred; validate at owner phase clients:N43 Renderer renderer/shared/workspace-artifacts.ts:319, renderer/shared/workspace-artifacts.ts:369, renderer/shared/subagent-safe-text.ts:264, renderer/shared/subagent-safe-text.ts:943, renderer/shared/aiden-ui/expression.ts:20; android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRawJsonDuplicateKeyScanner.kt:4; native Markdown splitter/cache files 2 2 3 2 Framing/sequence errors can desynchronize a stream; native privilege-boundary parsers are ranked with supervision/authority. Synchronous scanner automata: shell quoting/redirect context, escape decoding/bounded text, expression token cursor/depth/budget, JSON offset/object-key count, code fence/block/tail recognition. These are genuine local parsing state but not async orchestration; no finding is implied by their use. renderer/shared/workspace-artifacts.ts:319; renderer/shared/workspace-artifacts.ts:369; renderer/shared/subagent-safe-text.ts:264; renderer/shared/subagent-safe-text.ts:943; renderer/shared/aiden-ui/expression.ts:20; android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRawJsonDuplicateKeyScanner.kt:4 docs/audits/implicit-state-machines-clients-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 backend:M079 I Codex credential health and refresh: localNeedsAttention × remoteNeedsAttention × observed credential, generation abort controller and refresh flight 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Credential changes/rejected refresh/expiry/logout; stale failures cannot poison replacement credential generation. main/services/codex-provider.ts:251; main/services/codex-provider.ts:345; main/services/codex-provider.ts:358; main/services/codex-provider.ts:474 docs/audits/implicit-state-machines-backend-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 backend:M093 I Foundation Models helper connection/status: disposing flag, helper launch/request settlement/deadlines, status in-flight cache 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Status/generate/timeout/dispose; helper executable identity guards process termination, retryable preparation differs from permanent failure. main/services/foundation-models-connection.ts:25; main/services/foundation-models-connection.ts:116; main/services/foundation-models-connection-core.ts:286 docs/audits/implicit-state-machines-backend-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 backend:M094 I Manual catalog refresh jobs: single-flight models.dev refresh; remote-catalog active task+signal; provider image catalog fetches; serialized AA/OpenRouter cache publication 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Explicit foreground refresh/cancel/key change; cached ordinary reads must not cause network refresh and stale jobs must not publish under changed credentials. main/services/models-dev-cache-core.ts:165; main/services/pi-remote-catalog.ts:274; main/services/image-generation/runtime.ts:342; main/services/artificial-analysis-runtime-core.ts:121; main/services/openrouter-benchmark-runtime-core.ts:164 docs/audits/implicit-state-machines-backend-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 backend:M095 I Gemini context cache and warming: cache entries/loading/expiry/workspace ownership/cleanup set, warm run/disposed 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Create/reuse/update/expire/delete/shutdown; stale warming result must not recreate revoked cache entry. main/services/gemini-context-cache.ts:250; main/services/gemini-context-cache.ts:289; main/services/gemini-context-cache.ts:383; main/services/pi-cache-warming.ts:102; main/services/pi-cache-warming.ts:187 docs/audits/implicit-state-machines-backend-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 backend:M120 I Computer-use status probe: cached expiry, in-flight probe controllers, revision and closed 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Probe/permissions/settings/revoke/shutdown; stale probe must not overwrite newer disabled state. main/services/computer-use/status-core.ts:265; main/services/computer-use/status-core.ts:297; main/services/computer-use/status-core.ts:422 docs/audits/implicit-state-machines-backend-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 backend:M168 I File/watch cache refreshers: entry generations, scheduled refresh, pending invalidation/disposed 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. FS change/add/remove/refresh/close; old async discovery cannot overwrite newer owner snapshot. main/services/git-repo-watcher.ts:67; main/services/git-repo-watcher.ts:163; main/services/bot-skill-content-watcher.ts:18; main/services/skills-discovery.ts:492; main/services/skill-registry.ts:1 docs/audits/implicit-state-machines-backend-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 backend:M185 I Visual snapshot job queue: pending jobs, current abort, running promise, cancelled-chat tombstones/disposed 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Enqueue/drain/capture timeout/cancel chat/dispose; no snapshot publication after chat cancellation, bounded capture and follow-up drain. main/services/visual-snapshot-core.ts:136; main/services/visual-snapshot-core.ts:167; main/services/visual-snapshot-core.ts:196; main/services/visual-snapshot-main.ts:84 docs/audits/implicit-state-machines-backend-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 backend:M186 I Local inference model-loading monitor: stopped × announcedLoading + polling timer 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Probe unloaded emits loading once; loaded emits ready only if loading was announced; unknown stops without faking loading; stream activity/abort stops poll. main/services/local-runtime-status.ts:186; main/services/local-runtime-status.ts:195; main/services/local-runtime-status.ts:205 docs/audits/implicit-state-machines-backend-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 cli-native:C27 Advisor per-turn availability 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. runtime absent → lazy runtime ready; currentTurn absent ↔ enabled reviewer tool before_agent_start, model/scope selection, tool call Current turn captures matching tool/prompt; shared advisor runtime owns consultation attempt lifecycle. packages/cli/src/extensions/advisor.ts:65; packages/cli/src/extensions/advisor.ts:107 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 cli-native:C28 CLI Bot inventory authority invalidation 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. current fingerprint/lease revision → invalidated → new admission required auth/model/MCP/web config watcher, approved-root fingerprint change or read failure Root fingerprint distinguishes unrelated remote-state writes; invalidated admissions must not authorize further tools. packages/cli/src/bots.ts:181 docs/audits/implicit-state-machines-cli-native-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 clients:C66 Cross-cutting selection/focus/resize and resource feeds 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Selected workspace and hidden-ID reconciliation; debounced intake; shared subscribed/released poller/clock; photo pending/active/cached/evicted with epochs and budget; log subscription ended. Reference ownership and generation fences distinguish them from passive preferences. renderer/lib/workspace-context.tsx:30; renderer/lib/use-workspace-path-intake.ts:34; renderer/lib/use-device-service-state.ts:35; renderer/lib/second-clock.ts:11; renderer/lib/bot-canonical-photo-cache.ts:45; renderer/lib/device-event-log.ts:219 docs/audits/implicit-state-machines-clients-2026-11-04.md +19 T3 Catalogs, caches, discovery and background observation Deferred after P6 clients:N05 Workspace/home list loading and pagination 2 1 3 2 Invalidation or late fetches can show stale choices or retain resources; manual-only network rules remain invariant. Initial/cache/loading/ready/error and pagination idle/loading/failed/exhausted; request token/content context/local overlay generations. Detail/receipt/local triage edits cannot be overwritten by older list; later authoritative list can remove older omitted rows. ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:168; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:174; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:181; ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift:198; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:876; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:920; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceHomeViewModel.kt:41 docs/audits/implicit-state-machines-clients-2026-11-04.md +20 T4 Ephemeral presentation, gestures and selection Defer unless defect or coupling emerges clients:C40 3D device viewer resource/gesture lifecycle 1 1 2 1 Failures are usually local, recoverable presentation errors; a new reducer needs a concrete complexity benefit. Model loading/ready/disposed; frame loop active/inactive; pointer drag/rotation/fold targets and animation progress; texture/frame ownership. Cleanup must stop frames/listeners/materials and stale async model loads. renderer/lib/device-3d/viewer-runtime.ts:50; renderer/lib/device-3d/duo-viewer.ts:61; renderer/lib/device-3d/trackpad.ts:29; renderer/lib/device-3d/interaction.ts:10 docs/audits/implicit-state-machines-clients-2026-11-04.md +20 T4 Ephemeral presentation, gestures and selection Defer unless defect or coupling emerges clients:C42 Floating/docked environment and Bot workbench 1 1 2 1 Failures are usually local, recoverable presentation errors; a new reducer needs a concrete complexity benefit. Active tab, visited surfaces, float/dock/quick-view layout, mounted/present/exiting, pending focus/return focus, drag preview. Explicit environment reducer is surrounded by effects/timers; hidden and unmounted are intentionally different states. renderer/components/environment-panel.tsx:321; renderer/components/environment-panel.tsx:1308; renderer/components/environment-panel.tsx:1640; renderer/components/environment-panel.tsx:1686; renderer/main/bots/bot-workbench.tsx:81; renderer/main/bots/bot-panel-context.tsx:106 docs/audits/implicit-state-machines-clients-2026-11-04.md +20 T4 Ephemeral presentation, gestures and selection Defer unless defect or coupling emerges clients:C65 Transcript follow/reveal/microinteraction families 1 1 2 1 Failures are usually local, recoverable presentation errors; a new reducer needs a concrete complexity benefit. Follow locked/unlocked/near bottom, paced reveal backlog/draining/reset, explicit reasoning-disclosure reducer, present/exiting/unmounted, idle/copied/error with reset timer, pointer hold→menu versus click. Generation/version guards and reduced-motion routes matter; visual state is still temporal behavior. renderer/components/message-list.tsx:209; renderer/components/streaming-markdown-reveal.tsx:25; renderer/components/reasoning-block.tsx:37; renderer/components/event-presence.tsx:14; renderer/components/copy-button.tsx:22; renderer/components/busy-send-button.tsx:48; renderer/lib/use-collapsible-body.ts:9 docs/audits/implicit-state-machines-clients-2026-11-04.md +20 T4 Ephemeral presentation, gestures and selection Defer unless defect or coupling emerges clients:C72 Hover/focus/search/disclosure interaction families 1 1 2 1 Failures are usually local, recoverable presentation errors; a new reducer needs a concrete complexity benefit. Hover/focus/timer→open; pinned click versus dismissed-while-focused; delayed close; find query/debounce/matches/current index/return focus; compact sidebar focus-intent; pointer/focus/window-active suppress transitions. Focus/hover temporal state is not reducible to one open boolean. renderer/components/ui-info-hint.tsx:32; renderer/components/rich-link.tsx:162; renderer/components/chat-find-bar.tsx:56; renderer/components/ui.tsx:450; renderer/components/sidebar/inbox-view.tsx:148; renderer/lib/use-held-modifier-reveal.ts:13 docs/audits/implicit-state-machines-clients-2026-11-04.md +20 T4 Ephemeral presentation, gestures and selection Defer unless defect or coupling emerges clients:N20 Native transcript follow/reveal 1 1 2 1 Failures are usually local, recoverable presentation errors; a new reducer needs a concrete complexity benefit. Following/dragging/away/jump-settling, generation-fenced queued scroll and bottom arrival; reveal buffered/held-word-fragment/draining/final. User drag revokes auto-follow; bottom latch re-arms only at threshold; rewrite resets reveal, tool/terminal boundaries flush according to owner policy. iOS pacing differs from Android. ios/AidenOnTheGo/Features/Chat/AidenChatScrollPolicy.swift:213; ios/AidenOnTheGo/Features/Chat/AidenChatScrollObserver.swift:48; ios/AidenOnTheGo/Features/Chat/AidenStreamingRevealGate.swift:24; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1779; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenTranscriptFollow.kt:46; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenStreamingRevealGate.kt:21; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenStreamingRichText.kt:36 docs/audits/implicit-state-machines-clients-2026-11-04.md +20 T4 Ephemeral presentation, gestures and selection Defer unless defect or coupling emerges clients:N39 Native gesture/sheet/focus microinteraction families 1 1 2 1 Failures are usually local, recoverable presentation errors; a new reducer needs a concrete complexity benefit. Picker expanded/camera/photo/file import/permission denied; photo load/failure/retry/save/share; deck drag axis/selection; context-menu open and focus return; tool/activity expansion and delayed reveal. Transient state can retain resource work after visual dismissal; owner identity and accessibility reduced-motion routes must remain consistent. ios/AidenOnTheGo/Features/Chat/AidenAttachmentPicker.swift:6; ios/AidenOnTheGo/Features/Chat/AidenAttachmentCamera.swift:6; ios/AidenOnTheGo/Features/Chat/AidenTranscriptPolish.swift:7; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:7492; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:7755; ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:7926; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenMessageImageAttachments.kt:198; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenMessageImageAttachments.kt:340; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenMessageImageAttachments.kt:611; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenComposerView.kt:69; android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenMessageContextMenu.kt:26 docs/audits/implicit-state-machines-clients-2026-11-04.md +20 T4 Ephemeral presentation, gestures and selection Defer unless defect or coupling emerges clients:N48 Haptic delivery and reduced-motion animation ownership 1 1 2 1 Failures are usually local, recoverable presentation errors; a new reducer needs a concrete complexity benefit. Scoped activation, bounded semantic dedupe history, sequence pulse, app-active/audio-capture suppression; mark mounted/running/reduced-motion/low-power, pointer pressed. Haptic dedupe precedes emission guard; inactive scope cannot deliver later pulse. Animation timer/resource owners are independent of immutable shape specifications. ios/AidenOnTheGo/Config/AidenAppearance.swift:43; ios/AidenOnTheGo/Features/Shared/ActivityMarks/AidenActivityMarkView.swift:58; android/app/src/main/java/sbtbiswas/AidenOnTheGo/ui/theme/AidenMotion.kt:142 docs/audits/implicit-state-machines-clients-2026-11-04.md diff --git a/docs/plans/README.md b/docs/plans/README.md index 8e6fc0dec7..6f63cf2bd0 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -8,6 +8,7 @@ Research addition 2026-10-03 against `main` at `3f86d41af` (0.52.0): [all-PR inv ## Active and partial +- [Explicit state machines: 2026-11-23 refresh and audit remediation](explicit-state-machines-refresh-plan-2026-11-23.md) — Active (2026-11-24), grounded on `0.69.0` (`b2b5c3517`). Reconciles the 2026-11-04 372-entry inventory (`docs/audits/implicit-state-machine-{inventory,risk-ranking}-2026-11-04.tsv`) and post-Nov-4 owners in [`docs/state-machines/README.md`](../state-machines/README.md). Executed in the 2026-11-24 remediation wave: Phase 0 (canonical index, P3/P4 `remote-durable-operations.md`, `retained-p1-owners.md`/`physical-teardown.md` corrections, `backend:M028` `bot-approvals.ts` closed with 3 ordering fixes), Phase 1 (4 subagent progression copies unified into `renderer/shared/subagent-runs.ts`; two-tier iOS & Android `AidenRemoteFailureClassification` + `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json` fixing the live `409 idempotency_in_flight` key-drop defect; `bot-execution-and-peers.md`), Phase 2 (shared iOS/Android `AidenDurablePendingMutation` engine + direct unit tests), Phase 3 (Proactive Aiden `proactive-aiden.md` + 2 `goal-loop.ts` race fixes; Phase 3B `new-desktop-owners-2026-11.md` + `use-design-canvas.ts`, `gemini-live/app-control/provider.ts`, and `hook-dispatcher.ts` race/teardown fixes), and Phase 4 (4A–4C iOS extractions for `AidenHostConnectionLifecycle`, `AidenForeignRunObserver`, `AidenPendingSendCoordinator`, `AidenChatMutationSubMachines`, and `ComposerVoiceInputReducer`; 4D–4E `aiden serve stop` orphaned MCP survivor fix in `packages/cli/src/serve-lifecycle.ts`, `cli-native` P5/P6 review in `serve-daemon.md`, P5/P6/Tier-A reconciliation in `physical-teardown.md` and `p5-p6-tier-a-reconciliation.md`). Remaining open: macOS `xcodebuild` Simulator CI, Android `:app:lintDebug`, and physical-hardware acceptance. - [Proactive Aiden: chats that check back, keep going, run tasks and run other chats](proactive-aiden-plan.md) — Built on one integration branch, in review (2026-11-22). Phase 1 (keep awake, check-backs, tasks that post into the chat they were made in, worktrees keeping approval settings), phase 2 (`/goal` keep-going loop with a reviewer, goal bar, 30-minute round approvals, read-only helpers, `/until` as a goal, browser and Computer Use in on-screen rounds, and Aiden suggesting a goal), phase 4 (shared event core, watch, link and connector triggers, Aiden proposing triggers, the failure pause and 12-hour missed-run rule: [guide](../scheduled-task-triggers.md)) and phase 5 (`child_chats`: chats that start, send to, wait on, read and stop other chats, in the same workspace or new worktrees, with structured results: [guide](../chats-that-run-chats.md)) are built and switched on. Phase 3 (background helpers) is blocked on the subagent panel plan and the in-flight [subagent upgrade](subagent-desktop-serve-upgrade-plan.md); phase 6 (phones, `aiden serve`, experiments) is later. - [Worktree creation performance (Tier 1 & Tier 2)](worktree-creation-performance.md) — Implemented, in review (2026-11-21) on `worktree_performance_optimization`. All four phases shipped and audited by two adversarial reviewers per phase. Measured head-to-head on `aiden-macos` (6,497 tracked files, APFS, 5-run medians): explicit create drops from 1,417 ms / 127 git spawns to 744 ms / 8 git spawns (−47.5%, 1.90× faster); worktree-on-send local backend drops from 1,915 ms / 144 git spawns to 711 ms / 12 git spawns (−62.9%, 2.69× faster); post-create `git.info` drops from 172.8 ms (6 spawns) to 0.77 ms (0 spawns, −99.6%); per-op `managedWorktreeUsable` admission drops from 15.3 ms (4 spawns) to 0.58 ms (0 spawns, −96.2%); `.worktreeinclude` (31 files) drops from 100 ms to 40 ms (−60.0%) and stops crashing on large `node_modules` trees (44 ms with 5,000 ignored files vs `output_limit` crash). Renderer changes add inline `workspace` return + cache seeding, `workspaces:changed` creation narrowing, StrictMode-safe one-shot promotion `useChat` freshness, frame-1 draft worktree send inside `MessageList` with zero-remount bubble handoff, `EnvironmentArtifactsContext` isolation, and frame-0 `⌥↵` base seeding. - [iPhone Duo: list and conversation side by side](ios-iphone-duo-plan.md) — In review (PR) (2026-11-22), iOS only, no Remote revision. At regular width the Inbox, Bots and Workspaces tabs are list and detail; compact width keeps one stack; the fold keeps drafts, reading place, Search and list positions; bars are ready for the Duo's vertical rail (Xcode 27.1). Also ships the owner's quieter card lists, the iOS ink Aiden accent and underlined links. Phase 4 polish (remaining poses, the swipe-row item) is listed as remaining work in the plan. diff --git a/docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md b/docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md new file mode 100644 index 0000000000..9e82827303 --- /dev/null +++ b/docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md @@ -0,0 +1,99 @@ +# Explicit State Machines: 2026-11-23 Refresh & Audit Remediation Plan + +Status: **Active — Phases 0, 1, 2, 3, and 4 (4A–4E) implemented in the 2026-11-24 remediation wave; macOS `xcodebuild` Simulator CI, Android `:app:lintDebug`, and physical-hardware acceptance remain open.** +Baseline: `main` HEAD `b2b5c3517` (`0.69.0` release area; `main/`, `renderer/`, and all `ios/` Swift code are byte-identical to `4dec8df04`, with `4dec8df04..b2b5c3517` touching only 7 release/doc files: `package.json`, `package-lock.json`, `docs/plans/README.md`, `docs/release-notes/v0.69.0.md`, and `ios/{APP_STORE_METADATA,ASC_CLI,TESTFLIGHT}.md`). + +> **Governing principle** (carried forward from the November 4 migration plan on `origin/feature/explicit-state-machines-plan` at `82c5b3849`): +> Prioritize authority/revocation, irreversible transactions, ambiguous remote outcomes, generation ownership, and native teardown. Migrate one authority or effect boundary per PR. Keep existing authoritative cores; do **not** introduce a generic state-machine framework, replace harmless UI booleans, or change wire formats/persistence schemas unless an explicit bug fix requires it. + +--- + +## 1. Verified Baseline & Audit Corrections (`b2b5c3517`) + +Three independent verification passes against `b2b5c3517` established the exact codebase baseline and corrected several drifts from the initial 2026-11-23 refresh notes: + +### 1.1 Snapshot, Size & Prior-Lane Status +- **Codebase footprint (non-test production `.ts`/`.tsx`/`.swift`, excluding `.d.ts`)**: + - `main/`: **1,583 files / 424,835 lines** (`1,560` excluding 23 test-support/fixture/fake helpers). + - `renderer/`: **1,045 files / 237,840 lines**. + - `ios/AidenOnTheGo/` + `ios/AidenLiveActivityWidget/`: **177 `.swift` files / 98,398 lines** (`176` excluding `Demo/AidenPreviewFixtureView.swift`). + - Combined desktop + iOS production total: **2,805 files / 761,073 lines** (versus 2,654 scan rows in `82c5b3849` on 2026-11-04). +- **Delta `9c85bb79b..4dec8df04`**: **167 commits**; **55 added, 0 deleted, 138 modified** non-test production `.ts`/`.tsx`/`.swift` files across desktop + iOS; **58** of the 707 unique paths in `82c5b3849:docs/audits/implicit-state-machine-inventory-2026-11-04.tsv` changed repo-wide (**56** in `main/` + `renderer/` + `ios/`). +- **Prior November migration lanes already landed on `main`**: + - **P0/P1 (Lane A)**: PRs `#735, #736, #741–#745, #755` landed; worksheets in `docs/state-machines/{chat-turn-admission,generation-run,retained-p1-owners}.md`. + - **P2 (Lane B)**: PRs `#737–#740` landed; worksheet in `docs/audits/state-machine-worksheets-lane-b.md`. + - **P3 (`#746–#750`) & P4 (`#751–#754`) (Lane C)**: all landed on `main`, including `aiden-remote-durable-operation.ts`, Telegram outbox transitions, phone Bot outbox fixture (`protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json`), native subagent file mutator `enum TransactionPhase`, worktree removal journal, and `ChatDeletionSettlement`. Formally documented in `docs/state-machines/remote-durable-operations.md`. + - **P5 (Lane A)**: PRs `#756, #757, #766, #767, #769` (plus `#768`) landed; worksheet in `docs/state-machines/physical-teardown.md`. + - **Lane D (`aiden serve`)**: PRs `#758–#765` landed; worksheet in `docs/state-machines/serve-daemon.md`. + - **P6 (Lane B)**: P6a (`bot-pause-store`, `bot-pause-steps`, `bot-routine-recovery`) reviewed and retained (`lane-b.md#L232-242`); remaining P6 owners reconciled in Phase 4E (`docs/state-machines/p5-p6-tier-a-reconciliation.md` and `docs/state-machines/serve-daemon.md`). + +### 1.2 Verified Corrections Incorporated +1. **`Run input transitions` table location**: Lives in `docs/state-machines/retained-p1-owners.md#L52-65` (not `chat-turn-admission.md`); updated for PR #879's `outsideInput()` (`chat-run-input-admission.ts#L303-305`) and `await generation.leadChatInput()` (`#L306-312`). +2. **Webhook slot-release semantics (`main/services/scheduled-task-link-trigger.ts`)**: Known-token disabled `404` (`#L269`) intentionally keeps its 60/min slot (`#L258`), and `429` (`#L261`) rejects before taking a slot (separate `unknown` bucket at 120/min `#L179, #L248-253`). The status codes that call `refuse(taskId, admission)` to release their 60/min slot are **`400`**, **`401`**, **`413`**, and **`415`**. +3. **iOS & Android failure-ambiguity classifiers — 12 iOS sites across two endpoint contracts + verified live `409 idempotency_in_flight` bug**: + - Host `aiden-remote-router.ts#L3770` and `aiden-remote-durable-operation.ts#L126` throw `409 idempotency_in_flight` when an outcome is unknown after effect commit. Both iOS (`AidenBotOpenWorkModel`, `AidenBotWatchModel`, `AidenBotRoutineModelsModel`, `aidenBotSessionFailureIsAmbiguous`, `aidenBotEditorCreateFailureIsAmbiguous`, etc.) and Android (`AidenBotOpenWorkController.kt#L174`) previously treated `409` as definite and dropped pending idempotency keys. + - Meanwhile, endpoints backed by `executeAidenDurableOperation`'s 24h cached-rejection ledger (`AidenNewWorktreeRetry`, `AidenChatForkAttempt`, scheduled tasks, git mutations, coordinator mutations) require a distinct tier (`cachedRejectionLedger`) so structured non-in-flight refusals spend the key rather than replaying a cached rejection, while `CancellationError`/`URLError`/`.invalidResponse`/`409 idempotency_in_flight` retain it. +4. **iOS `storageBlocked` pattern — 6 classes across 5 files (plus 5 parallel Android controllers)**: `AidenBotPeersModel.swift` defines two classes (`AidenBotPeersModel` and `AidenBotPeerExchangeModel`), alongside `AidenBotResumeModel.swift`, `AidenBotWatchModel.swift`, `AidenBotRoutineModelsModel.swift`, and `AidenBotOpenWorkModel.swift`. +5. **Symbol, count & path corrections**: + - `AidenPendingGitMutation` has **5** cases (`commit`, `checkout`, `createBranch`, `push`, `createWorktree`), not 17. + - `AidenBotCreateOperations+Machine.swift` is paired-computer (`+Machine`) targeting, not a state machine. + - Densest desktop owners (`wc -l`): `git.ts` 8,921; `llm-client.ts` 7,499; `aiden-remote-router.ts` 5,659; `chat-pane.tsx` 4,961; `pi-agent-runtime-harness.ts` 3,392; `browser/service.ts` 3,241; `aiden-remote-bot-session.ts` 3,157; `telegram-service-core.ts` 2,629; `bot-application-service.ts` 2,282; `ghostty-terminal/surface.ts` 2,212; `subagent-supervisor-core.ts` 1,852; `config-store-core.ts` 1,506; `schedule-service-core.ts` 1,137; `bot-capability-store.ts` 762. + - `physical-teardown.md` ranges explicitly name `M003`, `M134–M137`, `M002` (pure core), and `cli-native:N13, O01`. + - `bot-peers/service.ts` (332 lines) has **5** stop receipt states (`requested | uncertain | stopped | not_running | blocked`, `renderer/shared/bot-peers.ts#L60`); `bot-execution.ts` is 390 lines (`#L181-191` no synthetic zero charge); `VerifiedRepoIdentityProof` is `git.ts#L1026-1036` (`isVerifiedRepoIdentityCurrent` `#L1943`); `AidenChatFeature.swift` split across 12 commits (`6182b2e30..a9185707a`) into `ios/AidenOnTheGo/Features/Chat/*`. + - Path fixes: `main/services/design-canvas/` (not `main/services/design/`); `main/services/bot-runtime/bot-{allow-list,access-authorization,approval-tallies}.ts`. + +--- + +## 2. Recorded Decisions (D1–D7) + +| ID | Decision | Resolution Applied | +|---|---|---| +| **D1** | Phase 0 inventory home | **Option A:** Import `docs/audits/implicit-state-machine-{inventory,risk-ranking}-2026-11-04.tsv` verbatim from `82c5b3849` + create canonical [`docs/state-machines/README.md`](../state-machines/README.md) reconciling all 372 IDs and post-Nov-4 owners + `docs/state-machines/remote-durable-operations.md`. | +| **D2** | Phase 1A subagent progression API | **Option A:** Single `subagentRunStateProgresses(current, next, { allowStopped?: boolean })` (plus `subagentRunSnapshotProgresses`, `sameSubagentRunSnapshotIdentity`, `isSubagentRunStateTerminal`) in `renderer/shared/subagent-runs.ts`, preserving `allowStopped: false` in `subagent-control-v2.ts`. | +| **D3** | Phase 1B failure-ambiguity policy | **Option A:** Two-tier endpoint contract (`beforeEffectRefusal` vs `cachedRejectionLedger`) in `AidenRemoteFailureClassification.{swift,kt}`, backed by shared fixture `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json` (no Remote protocol revision bump). | +| **D4** | Phase 1C `bot-execution.ts` & `bot-peers/service.ts` | **Option A:** Land transition worksheets (`docs/state-machines/bot-execution-and-peers.md`) first; keep security-critical receipt code untouched unless a test reproduces a defect. | +| **D5** | Phase 2A Android parity scope | **Option B (executed):** Unified classifiers + extracted `AidenDurablePendingMutation` on both iOS and Android alongside fixing two `STORAGE`-masking defects in Android `OpenWork` and `Peers`. | +| **D6** | Phase 4B `AidenChatViewModel` first slice | **Option A (planned):** Start with `AidenForeignRunObserver` (`AidenChatViewModel+ForeignRuns.swift`), then `AidenPendingSendCoordinator`, then `AidenChatMutationSubMachines`. | +| **D7** | Phase 4D/4E backlog depth | **Option A (risk-gated):** Fix `aiden serve stop` MCP survivor gap, execute cross-lane P1–P4 shutdown trace, reconcile P5/P6/Tier-A owners via transition worksheets + targeted race/teardown tests, fixing only reproduced defects. | + +--- + +## 3. Phase Status & Deliverables + +| Phase | Scope | Status (2026-11-24) | Primary Artifacts / Verification | +|---|---|---|---| +| **Phase 0** (`0A`, `0B`) | Import Nov-4 TSVs, canonical `docs/state-machines/README.md`, `remote-durable-operations.md`, `retained-p1-owners.md` / `physical-teardown.md` / `lane-b.md` corrections, close `backend:M028` (`bot-approvals.ts` 3 ordering fixes + behavioral tests) | **Implemented** | `docs/state-machines/{README,remote-durable-operations,retained-p1-owners,physical-teardown}.md`, `docs/audits/implicit-state-machine-*-2026-11-04.tsv`, `main/services/bot-runtime/bot-approvals.{ts,test.ts}` | +| **Phase 1** (`1A`, `1B`, `1C`) | Unify 4 subagent progression copies (`renderer/shared/subagent-runs.ts`); two-tier `AidenRemoteFailureClassification` on iOS (12 sites) & Android + `mutation-failure-ambiguity.json` fixture fixing `409 idempotency_in_flight`; `bot-execution-and-peers.md` | **Implemented** (iOS `xcodebuild` simulator check pending macOS host) | `renderer/shared/subagent-runs.ts`, `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json`, `AidenRemoteFailureClassification.{swift,kt}`, `docs/state-machines/bot-execution-and-peers.md` | +| **Phase 2** (`2A`, `2B`) | Shared `AidenDurablePendingMutation` across 5 iOS Bot files (6 classes) & Android parity + direct unit tests (`AidenDurablePendingMutationTests`, `AidenBotResumeModelTests`, `AidenScheduledTasksModel`, `ComposerVoiceInputController`) | **Implemented** (iOS `xcodebuild` simulator check pending macOS host) | `ios/AidenOnTheGo/Features/Bots/AidenDurablePendingMutation.swift`, `android/.../AidenDurablePendingMutation.kt`, mobile test suites | +| **Phase 3** (`3A`, `3B`) | Proactive Aiden (`proactive-aiden.md`, 2 `goal-loop.ts` race fixes); Phase 3B desktop owners (`new-desktop-owners-2026-11.md`, `use-design-canvas.ts` sync races, `provider.ts` close-during-`enabled()` fixes, `hook-dispatcher.ts` idempotency eviction-identity fix, `aiden-mcp-tools`/`bot-plans`/`bot-messages` teardown tests) | **Implemented** | `docs/state-machines/{proactive-aiden,new-desktop-owners-2026-11}.md`, `main/services/goal/goal-loop.ts`, `main/services/gemini-live/app-control/provider.ts`, `main/services/hooks/hook-dispatcher.ts`, `renderer/design/use-design-canvas.ts` | +| **Phase 4A–4C** (iOS dense owners) | Explicit `AidenHostConnectionLifecycle` (`AidenHostConnection.swift`), incremental `AidenChatViewModel` extractions (`AidenForeignRunObserver`, `AidenPendingSendCoordinator`, `AidenChatMutationSubMachines`), explicit `ComposerVoiceInputReducer` + simulator tests | **Implemented** (macOS `xcodebuild` Simulator CI & physical-device mic acceptance pending) | `ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnectionLifecycle.swift`, `ios/AidenOnTheGo/Features/Chat/{AidenForeignRunObserver,AidenPendingSendCoordinator,AidenChatMutationSubMachines,ComposerVoiceInputController}.swift` | +| **Phase 4D–4E** (P5, P6, CLI, Tier-A) | Fix `aiden serve stop` orphaned MCP survivor (`packages/cli/src/serve-lifecycle.ts` `selectDaemonMcpGroups`), review `cli-native:N13, O01, C12, C16, C28, C32` (`serve-daemon.md`), audit P5 unaudited remainder + cross-lane P1–P4 shutdown trace (`physical-teardown.md`), reconcile P6 & Tier-A queue (`p5-p6-tier-a-reconciliation.md`) + targeted teardown tests | **Implemented** (hardware/macOS acceptance separate) | `packages/cli/src/serve-lifecycle.ts`, `packages/cli/tests/serve-lifetime.test.mjs`, `docs/state-machines/{serve-daemon,physical-teardown,p5-p6-tier-a-reconciliation}.md` | + +--- + +## 4. Remaining Open Execution Slices (Phases 4A–4C) + +### PR 4A: Explicit `AidenHostConnection` Lifecycle (`ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnection.swift`) +- Consolidate the 8 coupled axes (`connectionState`, `generation`, `hostGeneration`, `connectionGeneration`, `isRevoked`, `isPurgePending`, `connectInFlight`, `settledState`) into an explicit pure transition type separating terminal custody (`active` vs `revoked(purgePending: Bool)`) from connection attempt state (`idle` / `connecting` / `connected` / `offline`), keeping all `@Observable` properties derived and `AidenHostRegistry` / `AidenHostConnectScheduler` untouched. +- Check Android's host connection coordinator for revocation-vs-reconnect parity. + +### PR 4B (Series of 3 Small PRs): Incremental `AidenChatViewModel` Extraction +- **PR 4B-1:** Extract `AidenForeignRunObserver` from `AidenChatViewModel+ForeignRuns.swift` (`probeForForeignRuns`, `isCurrentForeignRun`, `foreignRunGeneration`). +- **PR 4B-2:** Extract `AidenPendingSendCoordinator` (`pendingSend`, `canRetrySend`, `scheduleRateLimitedSendRetry`) over `AidenChatDraftStore`. +- **PR 4B-3:** Extract `AidenChatMutationSubMachines` (worktree setup cancel-after-finish guard, fork/continue attempts, approval/question snapshot generation fences). + +### PR 4C: Explicit `ComposerVoiceInputController` Reducer (`ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift`) +- Consolidate the 12 `state` write sites and audio/task ownership flags (`activatedAudioSessionForRecording`, `audioTapInstalled`, `macTranscriptionTask`, `nativeFinalizationTask`, `suppressNextRecognitionError`, `sessionFence`) into one explicit transition function over `(State, Backend, ResourceOwnership)` guaranteeing tap/audio-session/task cleanup on every exit to `.idle`. + +--- + +## 5. Verification & Rollback Contract + +- **Desktop & CLI:** `npm run type-check`, affected registered test scripts in `package.json`, and `npm --prefix packages/cli run build && npm --prefix packages/cli test` whenever touching shared `main/services/` or `renderer/shared/`. +- **Native prerequisites in fresh checkouts:** `npm run build:worktree-remover && npm run build:worktree-file-io && npm run build:subagent-file-mutator && npm run build:subagent-shell-runner && npm run build:vcc && npm run build:lease-flock`. +- **Mobile & hardware gates:** + - iOS (macOS host required): `xcodebuild test -project ios/AidenOnTheGo.xcodeproj -scheme AidenOnTheGo -destination 'platform=iOS Simulator,id=' -only-testing:AidenOnTheGoTests` (simulator evidence does not replace physical-device microphone/Keychain acceptance). + - Android: `cd android && ./gradlew :app:testDebugUnitTest :app:lintDebug :app:assembleDebug :app:compileDebugAndroidTestKotlin`. + - Electron E2E: `npm run test:e2e:space -- ` on macOS or CI's `xvfb-run --auto-servernum` sequence on Linux. +- **Test quality invariant:** Behavioral and transition-matrix tests only; never add `readFileSync`/source-grep tests against production `.ts`/`.tsx`/`.css` files. +- **Compatibility & rollback:** Public IPC/service signatures, wire schemas, on-disk stores, and manual-only network guarantees remain unchanged across all phases so every PR can revert cleanly without stranding durable recovery state. diff --git a/docs/state-machines/README.md b/docs/state-machines/README.md new file mode 100644 index 0000000000..eaf3a8bff2 --- /dev/null +++ b/docs/state-machines/README.md @@ -0,0 +1,49 @@ +# Explicit State Machines: Canonical Index + +This directory is the canonical home for Aiden's state-machine transition worksheets, dispositions, and audit reconciliations. It resolves every ID from the 2026-11-04 baseline inventory (`372` rows) alongside post-Nov-4 owners introduced through `0.69.0` (`b2b5c3517`). + +## Baseline Inventory & Plan + +- **Baseline inventory (2026-11-04, `372` entries: `197` `backend`, `125` `clients`, `50` `cli-native`):** [`docs/audits/implicit-state-machine-inventory-2026-11-04.tsv`](../audits/implicit-state-machine-inventory-2026-11-04.tsv) (imported unchanged from `82c5b3849` on `origin/feature/explicit-state-machines-plan`). +- **Risk ranking (2026-11-04, `372` entries: `72` `T1`, `230` `T2`, `63` `T3`, `7` `T4`):** [`docs/audits/implicit-state-machine-risk-ranking-2026-11-04.tsv`](../audits/implicit-state-machine-risk-ranking-2026-11-04.tsv) (imported unchanged from `82c5b3849`). +- **Refresh & remediation plan (2026-11-23):** [`docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md`](../plans/explicit-state-machines-refresh-plan-2026-11-23.md). + +## Worksheet Map + +| Document | Scope / Lanes | Key IDs & Owners Covered | Status | +|---|---|---|---| +| [`chat-turn-admission.md`](chat-turn-admission.md) | Lane A (P0/P1a, PR #735) | `backend:M005` (`chat-turn-admission.ts` -> `chat-turn-admission-lifecycle.ts`) | Converted | +| [`generation-run.md`](generation-run.md) | Lane A (P1b, PR #736) | `backend:M006` (`generation-settlement.ts` -> `generation-settlement-lifecycle.ts`) | Converted | +| [`retained-p1-owners.md`](retained-p1-owners.md) | Lane A (P1, PRs `#741–#745, #755`, refreshed 2026-11-24) | `backend:M007–M009, M012` (partial: `pi-managed-run-state.ts`), `M013, M015, M021–M024, M035, M100, M101, M105, M106, M159, M173–M176, M178, M194`; `clients:C02–C05, C11, N15`; Run input transitions updated for PR #879 | Reconciled | +| [`docs/audits/state-machine-worksheets-lane-b.md`](../audits/state-machine-worksheets-lane-b.md) | Lane B (P2 PRs `#737–#740`, P6a, refreshed 2026-11-24) | Converted: `backend:M019, M020, M107`. Retained: `backend:M028` (**closed 2026-11-24** with 3 ordering fixes), `M029, M036, M037, M056, M057, M065–M067, M078, M082–M085, M119, M123, M142, M181, M182, M190, M191`; `clients:C20, C33, C53, N02, N14, N38`; P6a (`bot-pause-store`, `bot-pause-steps`, `bot-routine-recovery`). Deferred list reconciled in `p5-p6-tier-a-reconciliation.md`. | Reconciled (`M028` closed) | +| [`remote-durable-operations.md`](remote-durable-operations.md) | Lane C (P3 `#746–#750` & P4 `#751–#754`, landed on `main`) | `aiden-remote-durable-operation.ts`, `advanceAidenOperation`, Telegram `BOT_REPLY_ROW_TRANSITIONS`, `protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json`, `native/subagent-file-mutator/main.c` (`TransactionPhase`), `managedWorktreeRemovalPhaseAllowed`, `ChatDeletionSettlement`; deferred P4 IDs `M026, M147, M158, M159` | Landed & documented | +| [`physical-teardown.md`](physical-teardown.md) | Lane A (P5 `#756, #757, #766–#769`, completed in Phase 4D) | `main/shared/process-group.ts`, `subagents/subagent-shell.ts`, `CuaDriverHost` (`M116–M118`), `AidenStdioTransport`, `bot-computers/host.ts` (`M121, M122`), `acp/` (`M089, M090`), `subagents/child-agent-runtime.ts` (`M102, M103`), `application-lifecycle-core.ts` (`M002`), `main/index.ts` (`M001`), plus Phase 4D dispositions for `M112, M125, M126, M130, M131, M133–M138, M156, M165, M192, C43` and cross-lane P1–P4 shutdown trace | Reconciled | +| [`serve-daemon.md`](serve-daemon.md) | Lane D (`aiden serve` `#758–#765` + Phase 4D/4E CLI) | `cli-native:C01–C32, N13, O01` (`C01–C04, C09–C11, C14` converted/extracted; `C15` removed; `C12, C16, C28, C32, N13, O01` reviewed & retained; `aiden serve stop` orphaned MCP survivor defect fixed in `serve-lifecycle.ts`; `C05, C18, C19` deferred/blocked on external branches) | Reconciled | +| [`bot-execution-and-peers.md`](bot-execution-and-peers.md) | Post-Nov-4 Bot runtime (Phase 1C) | `main/services/bot-runtime/bot-execution.ts` (390 lines; receipt verification & fail-closed unknown cost `#L181-191`) and `main/services/bot-peers/service.ts` (332 lines; keyed serial queue, 5 stop receipt states `renderer/shared/bot-peers.ts#L60`, `BotPeerPublication.assertCurrent`, per-pair `AbortController` leases) | Documented | +| [`proactive-aiden.md`](proactive-aiden.md) | Post-Nov-4 Proactive Aiden (PR #879, Phase 3A) | `chat-orchestration/{child-chats,links,links-main,completion-delivery,run-core}.ts`, `goal/{goal-core,goal-loop}.ts`, `keep-awake/keep-awake-core.ts`, `scheduled-task-link-trigger.ts`, `follow-through/{notice-delivery,done-when}.ts`, `bot-routine-events/{dispatcher,watch}.ts`, `schedule-service-core.ts` | Documented | +| [`new-desktop-owners-2026-11.md`](new-desktop-owners-2026-11.md) | Post-Nov-4 high-consequence desktop owners (Phase 3B) | `aiden-mcp-tools.ts`, `bot-plans/*`, `bot-messages/*`, `gemini-live/app-control/provider.ts` (close-during-`enabled()` fixes) + `renderer/lib/live-*`, `hooks/*` (idempotency eviction-identity fix), `approval-rules/*`, `bot-settings-changes/*`, `desktop-stream-handoff.ts`, `quick-chat-window.ts` / `floating-chat-app.tsx` | Documented | +| [`p5-p6-tier-a-reconciliation.md`](p5-p6-tier-a-reconciliation.md) | Phase 4D/4E reconciliation | Open P6 owners (`scheduled-bot-routines.ts`, `bot-session-service.ts`, `bot-routine-notifications.ts`, `schedule-service-core.ts`, `aiden-remote-streams.ts`), Tier-A deferred owners (`M100, M163, M166, M026, M158, M159, M147, C03`, Lane B's 30 unreviewed deferred IDs), and new/dense security owners (`git.ts` `VerifiedRepoIdentityProof`, `bot-allow-list`/`access-authorization`/`approval-tallies`, `aiden-remote-bot-session.ts`, `bot-application-service.ts`) | Documented | + +## Reconciling the 372 Nov-4 Inventory IDs + +All 372 IDs in [`implicit-state-machine-inventory-2026-11-04.tsv`](../audits/implicit-state-machine-inventory-2026-11-04.tsv) resolve to one of four dispositions across the worksheets above: + +1. **`backend:M001–M197` (197 entries)**: + - **P0/P1 (`M005–M009, M012–M015, M021–M024, M035, M100, M101, M105, M106, M159, M173–M178, M194`)**: Converted (`M005, M006`, partial `M012`) or retained in `chat-turn-admission.md`, `generation-run.md`, and `retained-p1-owners.md`; `M100` and `M159` reconciled in `p5-p6-tier-a-reconciliation.md`. + - **P2 (`M019, M020, M028, M029, M036, M037, M056, M057, M065–M067, M078, M082–M085, M107, M119, M123, M142, M163, M166, M181, M182, M190, M191`, plus Lane B's deferred list)**: Converted (`M019, M020, M107`) or retained (including `M028` closed 2026-11-24) in `docs/audits/state-machine-worksheets-lane-b.md`; `M163, M166` and the 14 deferred backend IDs reconciled in `p5-p6-tier-a-reconciliation.md`. + - **P3/P4 (durable remote, outbox, deletions, file transactions)**: Landed in PRs `#746–#754` and documented in `remote-durable-operations.md`; deferred `M026, M147, M158, M159` reconciled in `p5-p6-tier-a-reconciliation.md`. + - **P5 (teardown, startup/updater, capture/dictation/TTS)**: Landed in PRs `#756, #757, #766–#769` and completed in `physical-teardown.md` (with hardware-bound Rank 13 acceptance noted explicitly). + - **P6 & deferred-after-P6 (`M*` remaining)**: P6a retained in `state-machine-worksheets-lane-b.md`; remaining P6 schedule/session/notification/stream owners reconciled in `p5-p6-tier-a-reconciliation.md`; lower-tier T3/T4 entries (`Deferred after P6`, `Defer unless defect or coupling emerges`) remain retained-by-default unless a defect or multi-writer coupling emerges. +2. **`clients:C01–C76` & `clients:N01–N49` (125 entries)**: + - Renderer P1/P2/P5 entries (`C02–C05, C11, C20, C33, C43, C53`) live in `retained-p1-owners.md`, `state-machine-worksheets-lane-b.md`, `physical-teardown.md`, and `p5-p6-tier-a-reconciliation.md`. + - Native iOS/Android entries (`N01–N49`): `N15` (`AidenChatFeature.swift`, split across `6182b2e30..a9185707a` into `ios/AidenOnTheGo/Features/Chat/*`) is tracked in `retained-p1-owners.md` and the refresh plan Phase 4B; failure-ambiguity classification and durable pending-mutation controllers on iOS and Android are unified under `AidenRemoteFailureClassification` and `AidenDurablePendingMutation` (Phase 1B/2A) with shared fixture `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json`. +3. **`cli-native:C01–C32, N01–N16, O01–O02` (50 entries)**: + - `C01–C32`, `N13`, `O01` are reconciled in [`serve-daemon.md`](serve-daemon.md) (`C15` removed; `C05, C18, C19` remain deferred/blocked on external branches). + - `N01–N04` (Computer Use broker/guard/supervisor/filter) are documented as out-of-bounds/retained in `physical-teardown.md`; `N05–N12, N14–N16, O02` cover native C/Rust/Swift helpers (subagent file mutator `TransactionPhase` and worktree remover covered in `remote-durable-operations.md`; subagent shell runner in `physical-teardown.md`; remaining build/packaging helpers deferred unless a defect emerges). + +## Cross-Cutting Contract Fixtures & Shared Unifications (2026-11-24) + +- **Subagent state progression (Phase 1A):** Unified across all 4 prior copies into `renderer/shared/subagent-runs.ts` (`subagentRunStateProgresses` with `{ allowStopped }`, `subagentRunSnapshotProgresses`, `sameSubagentRunSnapshotIdentity`, `isSubagentRunStateTerminal`). +- **Cross-platform remote failure-ambiguity contract (Phase 1B):** Two-tier policy (`beforeEffectRefusal` vs `cachedRejectionLedger`, fixing the live `409 idempotency_in_flight` pending-key drop bug) implemented in `ios/AidenOnTheGo/Networking/AidenRemoteFailureClassification.swift` and `android/.../protocol/AidenRemoteFailureClassification.kt`, backed by `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json` (no Remote protocol revision bump). +- **Shared iOS durable pending-mutation engine (Phase 2A):** `ios/AidenOnTheGo/Features/Bots/AidenDurablePendingMutation.swift` replaces the 6× duplicated `storageBlocked` / 23h-replay state machines across 5 iOS Bot control files, with parallel Android unit-test and classifier parity. +- **Design Mode canvas sync (Phase 3B):** `renderer/design/use-design-canvas.ts` (`createCanvasSync` close-with-unsent-edits, late revision announcements, backoff cancellation) covered alongside `renderer/design/` tests. diff --git a/docs/state-machines/new-desktop-owners-2026-11.md b/docs/state-machines/new-desktop-owners-2026-11.md new file mode 100644 index 0000000000..ba925dca83 --- /dev/null +++ b/docs/state-machines/new-desktop-owners-2026-11.md @@ -0,0 +1,104 @@ +# Post-Nov-4 High-Consequence Desktop Owners (Phase 3B Worksheets) + +Reviewed against `main` baseline `b2b5c3517` (2026-11-24). Covers the high-consequence desktop state-machine owners that arrived after the 2026-11-04 inventory (`82c5b3849`) outside PR #879 Proactive Aiden (covered in `docs/state-machines/proactive-aiden.md`) and `bot-execution.ts` / `bot-peers/service.ts` (covered in `docs/state-machines/bot-execution-and-peers.md`). Design canvas sync (`renderer/design/use-design-canvas.ts`) is audited alongside Design Mode in its dedicated slice. + +Dispositions follow Lanes A–D: **Retained** (existing owner already centralizes transitions; no wrapper extracted), **Retained, with fixes** (reproduced defects fixed in place with behavioral tests), or **Converted** (explicit transition core extracted). + +--- + +## 1. `main/services/aiden-mcp-tools.ts` (542 lines) — Retained + +Owner: `AidenMcpToolRunner`, backing external MCP clients (Claude Code, Codex, etc.) over `/mcp`. + +### Axes & Invariants +- **Authorization & drain fence:** Every `call()` (`#L163-192`) checks tool existence, capability (`server:read`, `chat:read`, `chat:write`), TypeBox schema, then calls `dependencies.acquireAuthorization(app.id, tool.level === "write")` (`#L179`) with a `finally { release(); }` guard (`#L189-191`) so revocation waits for in-flight writes and never leaks a drain hold on unexpected throws. Unexpected non-`ToolRefusal`/non-`AidenRemoteServiceError` errors return a fixed generic `toolError` without leaking internal exception messages. +- **Admission & request dedupe:** Write turns (`aiden_chat_start`, `aiden_chat_send`) run through `turnRequest()` -> `ChatRunCore.request()` (`#L464-484`) with per-app (`pendingRequests: 8`) and host-wide (`hostPendingRequests: 32`, including disconnected/revoked apps' unsettled work) caps (`DEFAULT_AIDEN_MCP_LIMITS` `#L63-69`). Rate limiting (`turnsPerMinute: 10`, sliding 60s window in `turnTimes`) and concurrency (`concurrentRuns: 2`, via `core.liveRuns`) run in `admitTurn()` (`#L487-505`) only when the request was not already durably recorded (`hasRecordedRequest`). +- **Wait & revocation:** `aiden_chat_wait` delegates to `ChatRunCore.wait()` (`#L377-387`), returning `closed` on `revokeApp()` (`#L195-198`, which calls `core.forget(appId)` and deletes `turnTimes`), `aborted` on request signal abort, or a snapshot (`running`, `waiting_for_approval`, `waiting_for_input`, `done`, `failed`). `aiden_chat_stop` checks `CHAT_RUN_TERMINAL_STATES` first (`#L451`) and returns `{ stopped: false, state }` without calling `streams.cancel` for already-finished runs. +- **Visibility isolation:** `requireOrdinaryChat` (`#L519-528`) hides Bot, assistant, and design-project chats behind the same error as unknown IDs; no tool can answer approvals or questions. + +**Tests:** `main/services/aiden-mcp-server.test.ts` (extended with `AidenMcpToolRunner` unexpected-error authorization release/redaction, terminal `aiden_chat_stop`, and aborted `aiden_chat_wait` watcher-detach behavioral coverage). + +--- + +## 2. `main/services/bot-plans/*` (`plans.ts` 472, `authority.ts` 211, `lifecycle.ts` 33, `store.ts` 74) — Retained + +Owners: `createBotPlans` (`plans.ts`), `createBotPlanAuthority` (`authority.ts`), `createBotPlanLifecycle` (`lifecycle.ts`). + +### Transitions & Linearization Points +| Phase / Event | Owner | Guard / Fence | Next / Effect | +|---|---|---|---| +| `request` | `plans.ts#L232-259` | Per-Bot `serial`; rejects unreadable store or replay identity mismatch; joins identical waiting `planId` or ends older waiting card | `waiting` map (1 visible card per Bot) or idempotent replay of saved plan/receipt | +| `respond("approve" \| "not_now" \| "stop")` | `plans.ts#L289-336` | `transition(botId, endsAuthority)` increments `terminating` fence; `approve` stages `next` and validates `options.revalidate` + `fence` inside `writeJsonAtomic.beforePublish` before settling | `active` with single `expiresAt` timer (`schedule`), prior active plans marked `finished`, `fresh` one-shot grant slot recorded | +| `grantFreshAccess` | `plans.ts#L260-288` | Consumes one-shot `fresh` entry, revalidates, checks `terminating`/`deleted`/`aborted`/expiry before and after `apply()` | Ends plan fail-closed if revoked or throw occurs | +| `cover` -> `admit` | `plans.ts#L337-413` | `cover` mints `WeakSet`-tracked `BotPlanPermit` and records `counted[executionId]`; `admit` persists `admittedAt` under `finalFence` then revalidates one final time before synchronously invoking `start()` | Invocation (not completion) is linearized against `Stop`; restart never infers prior external effect | +| `markStep` / `endRuns` / `forgetBot` | `plans.ts#L414-470` | `terminating` fence + `rememberEnd` synchronously calls `options.revokeAccess` and records in-memory `terminal` fail-closed overlay even if disk save fails; `forgetBot` sets `deleted` synchronously before serial cleanup | Terminal `finished` / `stopped` / `expired` with immutable compact `BotPlanReceipt` | +| Session lifecycle hooks | `lifecycle.ts#L5-33` | Synchronous `running` `Set` so session queues never await plan serial; only observed runs ending `idle`/`needs_model`/`model_error` (or explicit `settled`/`stopped`) fire `endRuns`; `paused`/`interrupted` preserve recovery; sync and async `endRuns` errors route to `onError` | Fires `endRuns(botId, "finished" \| "stopped")` once | + +- `authority.ts` (`createBotPlanAuthority`) pins every proposal to `botPlanBindingRevision(authority, effectiveRules)` and validates fixed locations, folder device/inode identity, and `finalFence` synchronously after the last awaited read. + +**Tests:** `main/services/bot-plans/{lifecycle,plans,authority,validate}.test.ts` (extended `lifecycle.test.ts` with synchronous `endRuns` throw clearing `running` and `forgetBot` settling an in-flight waiting plan request). + +--- + +## 3. `main/services/bot-messages/*` (`courier.ts` 1,084, `ledger.ts` 551, `lifecycle.ts` 42) — Retained + +Owners: `createBotMessageLifecycle` (`lifecycle.ts`), `createBotMessageCourier` (`courier.ts`), `createBotMessageLedger` (`ledger.ts`). + +### Transitions & Shutdown Fence +| Event | Prior | Guard | Next / Effect | +|---|---|---|---| +| `post` | `closed === true` | None | Immediately returns `{ status: "refused", code: "unavailable", message: "Bot messaging is shut down." }` without constructing courier | +| `announceWaiting` | `closed === true` | `!ids.some(isBotMessageRequestId)` -> returns `undefined`; if any Bot-message request ID is present -> throws `"Bot messaging is shut down."` (fail closed so a Bot-message approval cannot proceed unannounced) | Fails closed for Bot-message waits; no-op for ordinary turns | +| `forgetBot` | `closed === true` | Calls `requireCurrent()` | Throws synchronously `"Bot messaging is shut down."` without instantiating courier | +| `dispose` | Any | Sets `closed = true` synchronously, awaits `current?.dispose()` (which sets `disposed = true`, unsubscribes listeners, cancels all `timers`/`scheduled`, aborts `workers`/`receiptWatches`/`waits`, awaits `Promise.allSettled` of all in-flight promises, then cancels any re-armed timers) | Shut down; late tools cannot lazily recreate courier | +| `start` | `closed === true` | Explicit runtime initialization only | Resets `current = undefined`, `closed = false`, constructs fresh courier, catches startup errors via `deps.report` | + +- Inside `courier.ts`, durable deliveries live in `ledger.ts` (`delivered` -> `answered` / `expired` / `failed`) with replay-hash dedupe (`botMessageReplayHash`), hop/chain-loop/rate-limit enforcement (`post` `#L798-922`), per-delivery serialized workers (`workers` + `dirty` re-queue), deadline timers that deny pending approvals with `"expiry"`, and `forgetBot` denying matching pending approvals before/after ledger removal (`#L1022-1058`). + +**Tests:** `main/services/bot-messages/{lifecycle,courier,ledger,real-courier,tool,framing,roster}.test.ts` (extended `lifecycle.test.ts` with pre-start `dispose()` fencing `post` and `forgetBot` without lazy courier construction). + +--- + +## 4. `main/services/gemini-live/app-control/provider.ts` (915 lines) & `renderer/lib/live-*` — Retained, with fixes + +### `AidenAppControlProvider` (`main/services/gemini-live/app-control/provider.ts`) +- **State axes:** `closed` + `lifetime` (`AbortController`), `busy` + `current` (active `use_aiden`/`open_in_aiden`), `confirming` + `pendingConfirm` (guarded control OK wait), `watch` + `idleTimer` (renderer outline/take-over watcher), `refs` + `signatures` (element numbers invalidated on `onNavigate` `#L361`, new `handleLook`, mid-session disable, or `close()`), `calls` (session cap 120). +- **Key semantics:** + - `interrupt()` (`#L386-389`): aborts `current` and `endActing()`, intentionally keeping `pendingConfirm` alive so barge-in does not discard a pending user confirmation. + - `onNavigate` (`#L361-364`): clears `refs` and aborts `pendingConfirm` with `CONFIRM_PAGE_CHANGED`. + - `enabled()` turning `false` mid-session (`#L406-421`): synchronously aborts `current` and `pendingConfirm`, stops acting, and clears `refs`. + - `close()` (`#L391-404`): sets `closed = true`, aborts `current` and `lifetime` (which aborts `pendingConfirm`), ends acting, detaches navigation listener, clears `refs`, and closes the CDP port. +- **Defects reproduced & fixed (2026-11-24):** + 1. `handle()` (`#L367-373`) and `confirmThenAct()` (`#L835-846`) did not recheck `this.closed` after `await this.enabled()`, allowing a `close()` that landed while `enabled()` was pending to execute page actions or port calls on a closed provider and arm a dangling `idleTimer`. Fixed by rechecking `this.closed` right after `await this.enabled()` in both methods, guarding `this.refs` assignment in `look()` (`#L594-597`), and guarding `scheduleIdle()` in `finishAction()` (`#L688`). Reproduced in `main/services/gemini-live/app-control/provider.test.ts`. + +### Renderer Live Boundary (`renderer/lib/live-*.ts`) — Retained +| File (lines) | Owner | Key State & Invariants | +|---|---|---| +| `live-session-bus.ts` (277) | `LiveSessionBus` | Monotonic `voiceInputFence()`/`beginVoiceInput()`, `setSession()` aborts & clears all `inFlight` tool requests on session switch; `cancelToolRequest` immediately answers uncommitted requests as `cancelled` while committed requests still report their true outcome once (`reported` flag) and run `afterReport`/`afterSettled` hooks. | +| `live-app-control.ts` (279) | `LiveAppControlController` | Per-utterance action budget (`actions`, reset on `onVoiceInput`), trusted-only `userInput` take-over (`isTrusted`), one-shot `confirm` settlement (voice armed only after `awaitDelivery: true` + `voiceInputFence`), and `reset()`/`dispose()` clearing timers, watches, and confirmations. | +| `live-chat-approvals.ts` (593) | `LiveChatApprovalsStore`, `LiveChatVoiceApprovals` | Owner-symbol-fenced snapshot store; voice arming requires `awaitDelivery: true` -> `LIVE_APPROVAL_ARM_DELAY_MS` (2.5s) -> `voiceInputFence()` -> `LIVE_SPEECH_FENCE_GUARD_MS` before accepting allow-once/deny phrases; `answering`/`answered` prevent duplicate answers; sensitive/harness/remote prompts stay tap-only. | +| `live-chat-tools.ts` (333) | `LiveChatRequestGate`, `createLiveChatToolHandlers` | Serialized `tail` queue per window; `LiveChatRequestGate` advances `fence` whenever `untrusted_chat_content` or a delivered note reaches Live and blocks mutating tools until fresh speech starts strictly after `fence`; `tail` waits on `afterSettled` before the next tool runs. | + +**Tests:** `npm run test:gemini-live` (`provider.test.ts` extended with close-during-`enabled()` and barge-in-vs-close `pendingConfirm` tests). + +--- + +## 5. `main/services/hooks/*` (`hook-service.ts` 1,061, `hook-dispatcher.ts` 452, `hook-script-files.ts` 516) — Retained, with one fix + +- **`hook-service.ts`**: Serializes all store mutations (`approveProposal`, `saveHook`, `approveDigest`, `setEnabled`, `deleteHook`) through one `serialized` queue; enforces digest-pinned approval (covering in-workspace script hashes from `hook-script-files.ts` and `targetDigest` CAS for update/delete proposals); fails closed on unreadable profile stores (denies tool calls and refuses Settings overwrites); `setPaused(true)` stops all background `async` hooks via `dispatcher.stopBackgroundHooks()` (`#L1002-1008`). +- **`hook-dispatcher.ts`**: Enforces `AsyncLocalStorage` re-entrancy guard (`isInsideHookRun`), fail-closed `PreToolUse` on load error or unmatched guard refusal (marked `uncacheable`), bounded foreground concurrency (`4`) and background `async` queue (`4` running / `32` queued) with `stopBackgroundHooks()` and `whenBackgroundIdle()`, and 3-failure auto-disable (exempting fail-closed `PreToolUse` hooks). + - **Defect reproduced & fixed (2026-11-24):** `outcomes.delete(key)` in `dispatch()` (`#L415-418`) deleted unconditionally when an aborted/uncacheable/throwing dispatch settled; if `clearIdempotencyCache()` ran while the first dispatch was in flight and a replacement dispatch with the same `idempotencyKey` completed before the stale first dispatch aborted, the stale cleanup evicted the fresh cached outcome. Fixed with `BoundedMap.deleteIf(key, pending)`. Reproduced in `main/services/hooks/hook-dispatcher.test.ts`. +- **`hook-script-files.ts`**: Pure lexical/filesystem scanner (no command execution) with bounded words (`128`), files (`16`), and file size (`256 MiB`); fails closed (`overLimit`) on unclosed quotes or exceeded caps. + +**Tests:** `npm run test:hooks` (`hook-dispatcher.test.ts` extended with aborted idempotent dispatch + evicted in-flight replacement protection). + +--- + +## 6. Brief Disposition Checks (Retained) + +| Owner (lines) | Disposition | Key Invariants & Existing Coverage | +|---|---|---| +| `main/services/approval-rules/{store,rules-page,file-store}.ts` (225 / 433 / 55) | **Retained** | `ApprovalRuleBook` serializes mutations through `store.update`, validates round-trip target parsing and byte/count caps before saving, throws `ApprovalRulesUnreadableError` (fail-closed) when `readable()` is false, and refuses overwrites until `setAside()` or clean `refresh()`. Covered by `main/services/approval-rules/rules.test.ts` & `main/handlers/approval-rules.test.ts` (`npm run test:approval-gate`). | +| `main/services/bot-settings-changes/{service,tool,ports}.ts` (307 / 107 / 188) | **Retained** | Per-Bot `createKeyedSerial()`, `applied` (owner-only, untainted, non-widening) vs `held` (capped at 5 pending), revision-checked compare-and-swap `ports.write(botId, patch, revision)` throwing `BotSettingsConflictError` so intervening edits are preserved (`undo_refused` on stale undo), and atomic persistence to `settings-changes.json`. Covered by `main/services/bot-settings-changes/{service,ports,tool}.test.ts` (`npm run test:bot-runtime`). | +| `main/services/desktop-stream-handoff.ts` (403) | **Retained** | `DesktopLiveStreamAccumulator` (bounded 2 MiB/stream, 64 streams) and `DesktopHandoffTicketStore` (one-shot `claimDraft`/`claimChat`, 30s TTL, max 16 tickets, `deferDetachIfPending` holding source detach until claim/expiry/abandon, `abandonChat` running deferred detaches immediately, `clear` cancelling timers). Covered by `main/services/desktop-stream-handoff.test.ts` (`npm run test:aiden-service-boundary`). | +| `main/windows/quick-chat-window.ts` (347) & `renderer/quick-chat/floating-chat-app.tsx` (1,141) | **Retained** | Main window singleton shares `loading` promise, tracks `loadingWindow` so `destroyQuickChat()` tears down mid-load windows, gates conversation access via `authorizedQuickChatIds` + `rendererDocumentOwner`, and delegates mode/bounds/blur logic to pure `quick-chat-window-core.ts`. Renderer view holds UI state fenced by `generationIntentRef` and `popoverOpenGenRef` with no host authority of its own. Covered by `main/windows/quick-chat-window-core.test.ts`, `main/handlers/quick-chat.test.ts`, and `renderer/quick-chat/floating-chat-app.test.tsx` (`npm run test:aiden-service-boundary`). | diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index 387d16789c..73a89e0c2d 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -126,6 +126,8 @@ Evidence of exit is `pidAlive`, never the signal. **Defect fixed:** the periodic `foreign` check ran only every tenth poll, so a PID that stopped being ours just before the deadline fell through to `did not stop ... try kill -9 `, sending the person to kill an unrelated process. Reproduced in `tests/serve-lifetime.test.mjs` with a process that `exec`s into something else. +**Defect fixed (2026-11-24, Phase 4D):** `aiden serve stop` could not force-stop an orphaned MCP grandchild survivor whose wrapper (`npx`, `uvx`, or launcher script) had already exited and been reaped, because `daemonMcpGroups()` in `packages/cli/src/serve-lifecycle.ts` required a direct child (`ppid === pid`). `recordServeMcpGroups()` now binds `mcp-groups.json` to the daemon's lease token when present, and `selectDaemonMcpGroups()` selects (1) any recorded group with a member descended from `daemonPid`, and (2) any leaderless recorded group (`pid === group` absent) with live non-zombie members owned by the daemon's UID (POSIX forbids reusing PID `group` while any member remains in that group, and `AidenStdioTransport` drops empty groups), while refusing any group whose leader PID is held outside the daemon's tree (recycled PID), any group matching `daemonPid` or `daemonPgid`, zombie-only groups, or foreign-UID groups. Verified by both pure selection tests and a real-process orphaned-grandchild stop test in `packages/cli/tests/serve-lifetime.test.mjs`. + ## C04: local daemon command framing Owners: `remoteDaemonCommand` (`daemon-control.ts`) and the socket handler in `serve.ts`. One request per connection, framed by a newline, 64 KiB request ceiling, 8 MiB response ceiling, UTF-8 decoded across chunks. The client settles once for result, error, closed without a frame, oversized reply and transport error. It is a stream parser, not a product mode. Retained as it was, with no state model: that would add nothing to a one-shot parser. @@ -164,9 +166,9 @@ Removed on 2026-11-18. The consent receipts (`approvedMutation` in `createCliSch | C06 pairing presentation | Startup only | Retained: presentation, and #733 changes `serve-command.ts`. | | C07 Tailscale health wait | Startup only | Retained: single settlement and a byte bound, covered by `tests/reachability.test.mjs`. | | C08 Linux Bonjour | Yes, Linux | Retained: generation and child identity already fence late callbacks. Not exercised against real avahi here. | -| C12 Bot pause | Yes | Deferred to P6: the shared pause store and durable runtime own it. It reuses `stopChatWork`, which now waits on C09 settlement. | +| C12 Bot pause | Yes | Retained (2026-11-24 Phase 4E review): `packages/cli/src/bots.ts#L110-129` writes durable pause first (through `durable.runtime.pause` or `bot-pause-store`, which fails closed on unreadable files), then drains active chats via `stopChatWork` (C09 settlement). `assertNotPaused` checks the same store before turns. | | C13 durable Bot migration | Admin command | Retained: `preparing` and `enabled` are already an explicit durable marker. | -| C16 scheduled execution | Yes | Deferred to P6: the shared scheduler owns timing and revisions; drain already awaits `stopAndSettle`. | +| C16 scheduled execution | Yes | Retained (2026-11-24 Phase 4E review): `packages/cli/src/schedules.ts#L27-80` delegates timing, 12h late skip, 3-failure auto-pause, and `stopAndSettle()` drain to `createScheduleServiceCore`, tracks per-task `active` `AbortController`s with `finally` removal, and rechecks workspace full-access + provider fingerprint before launch and on every `tool_call`. `packages/cli/src/scheduled-inference.ts#L59-116` combines external + watchdog/budget signals (64 tools, 24 turns, 2 MiB reply, 5m inactivity / 6h wall) and cleans up watchdog, listeners, session, MCP pool, and usage in `finally`. | | C17 inference metering | Yes | Retained: an algorithmic streaming counter, deferred after P6 by the plan. | | C18, C19 child inference and worker RPC | Yes, through Bot subagents | Blocked: the subagent upgrade branch rewrites `subagent-process.ts` and `subagent-worker.ts`. Revisit after it lands. | | C20 MCP connection incarnation | Yes | Retained: entry identity fences every await, covered by the MCP pool cases in `tests/parity.test.mjs`. | @@ -177,6 +179,8 @@ Removed on 2026-11-18. The consent receipts (`approvedMutation` in `createCliSch | C25, C30, C31 credentials | Reads only | Retained: per-file queue plus lease; migrations are explicit transactions outside the daemon's turn path. | | C26 todo restore | Yes, inside sessions | Retained: `restoreEpoch` fences late restores, covered by the todo cases in `tests/parity.test.mjs`. | | C27 advisor availability | Yes, inside sessions | Retained: the shared advisor runtime owns attempts, deferred after P6 by the plan. | -| C28 Bot inventory invalidation | Yes | Deferred to P6 with the shared Bot authority owners. | +| C28 Bot inventory invalidation | Yes | Retained (2026-11-24 Phase 4E review): `packages/cli/src/bots.ts#L156-200` invalidates the shared `BotRuntimeInventoryLeaseRegistry` (`M036`) on `auth.json`/`models.json`/`aiden-mcp.json`/`web-search.json` changes and on `remote.json` `approvedRoots` fingerprint changes or parse errors; `mcpScopeCache` and 3s catalog reuse fence on `inventoryLeases.revision()`, and tools wrap `protectAdmittedBotTool` after `revalidateBeforeEffect()` (`#L261-262`). | | C29 MCP config migration | Store construction | Retained: an explicit publish-then-retire transaction. | -| C32 usage accounting | Yes | Deferred to P6: receipt and aggregate already publish together. | +| C32 usage accounting | Yes | Retained (2026-11-24 Phase 4E review): `packages/cli/src/usage-ledger.ts` (48 lines) serializes per-`agentDir` via promise tail + `acquireLease("usage-writer")` and atomically writes aggregate usage + SHA-256 `${source}\0${attemptId}` dedupe hashes (bounded to `MAX_ADVISOR_ATTEMPTS * 8`) in one `atomicJson` publication. | +| N13 signed iMCP child supervision | macOS native launcher | Retained (2026-11-24 Phase 4D static review; signed macOS hardware acceptance separate): `native/imcp-launcher/main.swift` (64 lines) strictly validates both bundle (`co.dododo.iMCP`) and executable (`imcp-server`) via `SecStaticCodeCheckValidity` before launching with `LaunchCodeRequirement`; `SIGTERM` DispatchSource sends `kill(-child.processIdentifier, SIGKILL)` while running, and `terminationHandler` unconditionally kills the child's process group before exiting so pipe-holding descendants cannot survive. | +| O01 bounded-command occupied group guard | Runtime support script | Retained (2026-11-24 Phase 4D static review): `scripts/bounded-command-guard.mjs` (66 lines) uses a single-boolean `terminating` idempotency guard (`#L15, #L24`), ignores `SIGTERM`/`SIGINT` on the detached leader until `terminateGroup(graceMs)` sends group `SIGTERM` -> `SIGKILL` + `process.exit(70)`, escalates on parent `disconnect` (`terminateGroup(0)`), and runs `terminateGroup(graceMs)` on `release` so ignored-stdio descendants cannot outlive a successful command. | diff --git a/main/services/aiden-mcp-server.test.ts b/main/services/aiden-mcp-server.test.ts index 272df17fec..1cd38048da 100644 --- a/main/services/aiden-mcp-server.test.ts +++ b/main/services/aiden-mcp-server.test.ts @@ -1131,3 +1131,104 @@ test("assistant and design-project chats answer every chat tool exactly as an un await fixture.close(); } }); + +test("AidenMcpToolRunner releases write authorization on unexpected errors, stops finished runs cleanly, and ends aborted waits", async () => { + let releases = 0; + const acquired: Array<{ appId: string; tracksMutationDrain: boolean }> = []; + const app = { + id: "app-1", + name: "Codex", + capabilities: new Set(["server:read", "chat:read", "chat:write"] as const), + }; + let statusState: "running" | "done" = "running"; + let watchDetached = false; + const runner = new AidenMcpToolRunner({ + appVersion: "0.69.0", + hostName: async () => "Studio Mac", + acquireAuthorization: (appId, tracksMutationDrain) => { + acquired.push({ appId, tracksMutationDrain }); + return () => { + releases += 1; + }; + }, + services: async () => ({ + workspaces: { + list: async () => ({ workspaces: WORKSPACES }), + }, + chats: { + listSummaries: async () => ({ summaries: [] }), + messagesWindow: async () => ({ + chatId: "chat-1", + workspaceId: "ws-1", + title: "Test", + revision: "rev-1", + createdAt: "2026-11-24T00:00:00.000Z", + updatedAt: "2026-11-24T00:00:00.000Z", + messages: [], + hasOlder: false, + }), + classify: async () => ({ botId: undefined, workspaceId: "ws-1" } as never), + isListedChat: async () => true, + hasRecordedRequest: () => false, + runMutation: async (_appId, _chatId, _c, fn) => fn(), + create: async () => { + throw new Error("raw internal secret path /tmp/private"); + }, + startTurn: async () => ({ + turnId: "t1", + streamId: "run-1", + status: "accepted" as const, + message: { id: "m1", role: "user" as const, text: "Hello", createdAt: "2026-11-24T00:00:00.000Z" }, + }), + }, + streams: { + status: () => ({ state: statusState, chatId: "chat-1", streamId: "run-1" } as never), + pendingApproval: () => null, + pendingQuestion: () => null, + cancel: async () => ({ ok: true } as never), + watch: () => { + return () => { + watchDetached = true; + }; + }, + }, + }), + }); + + // 1. Unexpected throw inside write handler releases authorization and redacts raw error message. + const failedStart = await runner.call( + app, + "aiden_chat_start", + { clientRequestId: "req-boom-0001", workspaceId: "workspace-1", text: "Hello" }, + new AbortController().signal, + ); + assert.equal(failedStart.isError, true); + assert.equal(refusal(failedStart), "Aiden could not complete this request."); + assert.equal(releases, 1); + assert.deepEqual(acquired[0], { appId: "app-1", tracksMutationDrain: true }); + + // 2. Stopping an already-finished run reports stopped: false without invoking cancel(). + statusState = "done"; + const stoppedFinished = structured( + await runner.call(app, "aiden_chat_stop", { chatId: "chat-1", runId: "run-1" }, new AbortController().signal), + ); + assert.deepEqual(stoppedFinished, { chatId: "chat-1", runId: "run-1", stopped: false, state: "done" }); + assert.equal(releases, 2); + + // 3. Aborting the request signal during aiden_chat_wait ends the wait cleanly, detaches the watcher, and releases authorization. + statusState = "running"; + const waitAbort = new AbortController(); + const waiting = runner.call( + app, + "aiden_chat_wait", + { chatId: "chat-1", runId: "run-1", timeoutSeconds: 10 }, + waitAbort.signal, + ); + await new Promise((resolve) => setTimeout(resolve, 10)); + waitAbort.abort(); + const waitResult = await waiting; + assert.equal(waitResult.isError, true); + assert.equal(refusal(waitResult), "The wait ended because the request closed."); + assert.equal(watchDetached, true); + assert.equal(releases, 3); +}); diff --git a/main/services/bot-messages/lifecycle.test.ts b/main/services/bot-messages/lifecycle.test.ts index 320b1efb77..10bdf50581 100644 --- a/main/services/bot-messages/lifecycle.test.ts +++ b/main/services/bot-messages/lifecycle.test.ts @@ -107,3 +107,42 @@ test("corrupt messaging storage is reported without rejecting Bot startup or alt assert.equal(await readFile(file, "utf8"), "broken"); await service.dispose(); }); + +test("disposing before start fences post and forgetBot without instantiating the courier until start()", async () => { + let factories = 0; + let forgotten: string[] = []; + const service = createBotMessageLifecycle({ + report: () => assert.fail("unexpected startup failure"), + create: (): BotMessageCourier => { + factories += 1; + return { + start: async () => {}, + post: async () => ({ status: "sent", deliveryId: "d1", to: { id: "B", name: "B" } }), + dispose: async () => {}, + forgetBot: async (id) => { + forgotten.push(id); + }, + announceWaiting: async () => undefined, + }; + }, + }); + + await service.dispose(); + assert.equal(factories, 0); + const refused = await service.post({ + fromBotId: "A", + target: "B", + message: "hello", + deliveryId: "d1", + runRequestIds: [undefined], + }); + assert.equal(refused.status, "refused"); + assert.throws(() => service.forgetBot("A"), /shut down/u); + assert.equal(factories, 0, "closed lifecycle must never construct the courier lazily"); + + await service.start(); + await service.forgetBot("A"); + assert.equal(factories, 1); + assert.deepEqual(forgotten, ["A"]); + await service.dispose(); +}); diff --git a/main/services/bot-plans/lifecycle.test.ts b/main/services/bot-plans/lifecycle.test.ts index d70afc9942..ad34676928 100644 --- a/main/services/bot-plans/lifecycle.test.ts +++ b/main/services/bot-plans/lifecycle.test.ts @@ -87,3 +87,57 @@ for (const terminal of ["needs_model", "model_error"] as const) { assert.deepEqual(ended, ["b:finished"]); }); } + +test("synchronous endRuns throws are reported and still clear observed running state", () => { + const boom = new Error("sync failure"); + const reports: Array<[string, unknown]> = []; + let calls = 0; + const lifecycle = createBotPlanLifecycle({ + plans: { + endRuns: () => { + calls += 1; + throw boom; + }, + }, + onError: (botId, error) => reports.push([botId, error]), + }); + lifecycle.stateChanged("b", { kind: "running" }); + lifecycle.stateChanged("b", { kind: "idle" }); + lifecycle.stateChanged("b", { kind: "idle" }); + assert.equal(calls, 1, "cleared running entry must not re-fire endRuns on repeated idle"); + assert.deepEqual(reports, [["b", boom]]); +}); + +test("forgetBot settles a waiting plan request as ended and clears the visible pending card", async () => { + const profileDir = await mkdtemp(path.join(tmpdir(), "plan-forget-waiting-")); + const plans = createBotPlans({ + profileDir, + knownBot: async () => true, + revalidate: async () => {}, + revokeAccess: () => {}, + }); + try { + const proposal = { + title: "Delete race", + why: "Check forgetBot while waiting", + steps: ["Run check"], + items: [{ id: "i1", kind: "shell" as const }], + authorization: { policyRevision: "policy-1", bindingRevision: "binding-1", proposalFingerprint: "", rules: [] }, + }; + proposal.authorization.proposalFingerprint = botPlanProposalFingerprint(proposal); + const pending = plans.request({ + botId: "b", + planId: "p-forget", + toolCallId: "plan-call", + requestIds: ["person-1"], + proposal, + signal: undefined, + }); + assert.equal((await plans.current("b"))?.status, "pending"); + await plans.forgetBot("b"); + assert.deepEqual(await pending, { status: "ended" }); + assert.equal(await plans.current("b"), null); + } finally { + await rm(profileDir, { recursive: true, force: true }); + } +}); diff --git a/main/services/gemini-live/app-control/provider.test.ts b/main/services/gemini-live/app-control/provider.test.ts index 4f0a409fc1..8846dfd006 100644 --- a/main/services/gemini-live/app-control/provider.test.ts +++ b/main/services/gemini-live/app-control/provider.test.ts @@ -840,3 +840,72 @@ test("the tools are offered only while Let Live move through Aiden is on", async ); provider?.close?.(); }); + +test("closing the provider while enabled() is pending stops handle() and confirmThenAct() before acting", async () => { + const h = harness(``); + try { + let goClicks = 0; + let outClicks = 0; + h.document.getElementById("go")!.addEventListener("click", () => (goClicks += 1)); + h.document.getElementById("out")!.addEventListener("click", () => (outClicks += 1)); + const goRef = await h.ref("Go"); + const outRef = await h.ref("Sign out"); + + // 1. Start a guarded confirmation, tap Confirm, then close while the post-OK enabled() check is pending. + assert.equal((await h.call("use_aiden", { element: outRef, action: "press" })).status, "waiting_for_user"); + await h.noteMatching(PROMPT); + let releaseConfirmCheck!: () => void; + h.switchedOn.hold = new Promise((resolve) => (releaseConfirmCheck = resolve)); + const shown = h.activity.get(); + if (shown?.kind === "confirm") shown.confirm(); + await h.settle(); + const notesBeforeClose = h.notes.length; + + // 2. Also start an ordinary use_aiden call whose enabled() check is held. + let releaseHandleCheck!: () => void; + h.switchedOn.hold = new Promise((resolve) => (releaseHandleCheck = resolve)); + const pendingHandle = h.call("use_aiden", { element: goRef, action: "press" }); + await h.settle(); + + // Close the provider while both enabled() awaits are still open, then release both as enabled=true. + h.provider.close(); + releaseConfirmCheck(); + releaseHandleCheck(); + const response = await pendingHandle; + await h.settle(); + + assert.equal(code(response), "window_unavailable"); + assert.equal(goClicks, 0, "handle() must not act after close() during enabled()"); + assert.equal(outClicks, 0, "confirmThenAct() must not act after close() during enabled()"); + assert.equal(h.notes.length, notesBeforeClose, "no follow-up note after close()"); + } finally { + h.dispose(); + } +}); + +test("barge-in interrupt keeps a pending confirmation waiting, while close() cancels it cleanly", async () => { + const h = harness(``); + try { + let outClicks = 0; + h.document.getElementById("out")!.addEventListener("click", () => (outClicks += 1)); + const outRef = await h.ref("Sign out"); + assert.equal((await h.call("use_aiden", { element: outRef, action: "press" })).status, "waiting_for_user"); + await h.noteMatching(PROMPT); + + // Barge-in must not drop the pending OK prompt. + h.provider.interrupt(); + await h.settle(); + assert.equal(h.activity.get()?.kind, "confirm"); + assert.equal(code(await h.call("open_in_aiden", { place: "providers" })), "waiting_for_user"); + + // Closing the provider drops the pending OK with no action and no follow-up note. + const notesBeforeClose = h.notes.length; + h.provider.close(); + await h.settle(); + assert.equal(h.activity.get(), null); + assert.equal(outClicks, 0); + assert.equal(h.notes.length, notesBeforeClose); + } finally { + h.dispose(); + } +}); diff --git a/main/services/gemini-live/app-control/provider.ts b/main/services/gemini-live/app-control/provider.ts index 3f8e84c648..e7ecfec749 100644 --- a/main/services/gemini-live/app-control/provider.ts +++ b/main/services/gemini-live/app-control/provider.ts @@ -368,6 +368,8 @@ export class AidenAppControlProvider implements LiveToolProvider { if (this.closed) return AIDEN_APP_CONTROL_ERRORS.unreadable; // The switch can be turned off mid-session: from then on nothing runs. if (!(await this.enabled())) return AIDEN_APP_CONTROL_ERRORS.turnedOff; + // The session may have closed while the switch check was awaited. + if (this.closed) return AIDEN_APP_CONTROL_ERRORS.unreadable; this.calls += 1; if (this.calls > (this.options.sessionCalls ?? DEFAULT_SESSION_CALLS)) return AIDEN_APP_CONTROL_ERRORS.budget; switch (call.name) { @@ -589,8 +591,10 @@ export class AidenAppControlProvider implements LiveToolProvider { limits, previous: markNew ? this.signatures : undefined, }); - this.refs = new Map(screen.elements.map((element) => [element.ref, element])); - this.signatures = screen.signatures; + if (!this.closed) { + this.refs = new Map(screen.elements.map((element) => [element.ref, element])); + this.signatures = screen.signatures; + } return screen; } finally { this.release(LOOK_OBJECT_GROUP); @@ -682,7 +686,7 @@ export class AidenAppControlProvider implements LiveToolProvider { private finishAction(abort: AbortController): void { if (this.current === abort) this.current = null; this.busy = false; - if (!abort.signal.aborted) this.scheduleIdle(); + if (!abort.signal.aborted && !this.closed) this.scheduleIdle(); } /** @@ -837,6 +841,10 @@ export class AidenAppControlProvider implements LiveToolProvider { await this.note(`Let Live move through Aiden was turned off, so ${quoted(element.name, element.role)} was not used.`); return; } + if (this.closed) { + this.confirming = false; + return; + } const abort = this.beginAction(this.lifetime.signal); this.confirming = false; let message: string; diff --git a/main/services/hooks/hook-dispatcher.test.ts b/main/services/hooks/hook-dispatcher.test.ts index 983a0ce01e..bd63cc5558 100644 --- a/main/services/hooks/hook-dispatcher.test.ts +++ b/main/services/hooks/hook-dispatcher.test.ts @@ -148,3 +148,55 @@ test("the turn's own signal stops waited hooks but not background ones", async ( await dispatcher.whenBackgroundIdle(); assert.equal(dispatcher.lastRun("bg")?.result, "ok"); }); + +test("an aborted idempotent dispatch does not poison replay, and an evicted in-flight abort cannot delete a newer cached entry", async () => { + let runs = 0; + const releases: Array<(result: HookRawRun) => void> = []; + const dispatcher = createHookDispatcher({ + source: source(() => [hook("guard", {}, "PreToolUse")]), + run: (_definition, _payload, runContext) => + new Promise((resolve) => { + runs += 1; + releases.push(resolve); + runContext.signal?.addEventListener("abort", () => resolve(raw({ aborted: true, exitCode: null })), { once: true }); + }), + }); + + // 1. First dispatch starts with key "k1", then cache is cleared while it is still running. + const firstSignal = new AbortController(); + const first = dispatcher.dispatch("PreToolUse", preTool, context({ idempotencyKey: "k1", signal: firstSignal.signal })); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(runs, 1); + + dispatcher.clearIdempotencyCache(); + + // 2. Second dispatch with the same key starts and completes cleanly. + const second = dispatcher.dispatch("PreToolUse", preTool, context({ idempotencyKey: "k1" })); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(runs, 2); + releases[1]!(raw({ stdout: JSON.stringify({ systemMessage: "fresh" }) })); + const secondOutcome = await second; + assert.deepEqual(secondOutcome.ranHooks, ["guard"]); + + // 3. Now the stale evicted first dispatch aborts; it must NOT delete the second dispatch's cached outcome. + firstSignal.abort(); + await first; + + const third = await dispatcher.dispatch("PreToolUse", preTool, context({ idempotencyKey: "k1" })); + assert.deepEqual(third, secondOutcome); + assert.equal(runs, 2, "replay after evicted first abort must hit the second cached result"); + + // 4. An ordinary aborted dispatch (without replacement) evicts itself so a later retry runs fresh. + const abortOnly = new AbortController(); + const fourth = dispatcher.dispatch("PreToolUse", preTool, context({ idempotencyKey: "k2", signal: abortOnly.signal })); + await new Promise((resolve) => setImmediate(resolve)); + abortOnly.abort(); + await fourth; + + const fifth = dispatcher.dispatch("PreToolUse", preTool, context({ idempotencyKey: "k2" })); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(runs, 4); + releases[3]!(raw()); + const fifthOutcome = await fifth; + assert.deepEqual(fifthOutcome.ranHooks, ["guard"]); +}); diff --git a/main/services/hooks/hook-dispatcher.ts b/main/services/hooks/hook-dispatcher.ts index c6253456d1..4b7fe8314d 100644 --- a/main/services/hooks/hook-dispatcher.ts +++ b/main/services/hooks/hook-dispatcher.ts @@ -180,6 +180,9 @@ class BoundedMap { delete(key: K): void { this.map.delete(key); } + deleteIf(key: K, expected: V): void { + if (this.map.get(key) === expected) this.map.delete(key); + } clear(): void { this.map.clear(); } @@ -412,10 +415,10 @@ export function createHookDispatcher(options: HookDispatcherOptions): AidenHookD try { const outcome = await pending; // An abandoned run, or hooks that could not load, must be able to run again on replay. - if (context.signal?.aborted || uncacheable.has(outcome)) outcomes.delete(key); + if (context.signal?.aborted || uncacheable.has(outcome)) outcomes.deleteIf(key, pending); return outcome; } catch (error) { - outcomes.delete(key); + outcomes.deleteIf(key, pending); throw error; } }, diff --git a/packages/cli/src/serve-lifecycle.ts b/packages/cli/src/serve-lifecycle.ts index b891104a16..25e92571cb 100644 --- a/packages/cli/src/serve-lifecycle.ts +++ b/packages/cli/src/serve-lifecycle.ts @@ -48,6 +48,14 @@ function processGroupId(pid: number): number | undefined { } catch { return undefined; } } +export interface ObservedProcess { + pid: number; + ppid: number; + pgid: number; + uid?: number; + zombie?: boolean; +} + /** * Publishes the serving process's live stdio MCP process groups beside its lease * owner. Each server leads its own group, outside the daemon's, and a SIGKILL @@ -59,31 +67,113 @@ export function recordServeMcpGroups(agentDir: string): () => void { return watchMcpProcessGroups((groups) => { // Never recreate a lease directory that was already released. if (!existsSync(lock)) return; - try { atomicJson(join(lock, MCP_GROUPS), { pid: process.pid, groups }); } catch { /* best effort */ } + const owner = serveOwner(agentDir); + const token = owner?.pid === process.pid && typeof owner.token === "string" ? owner.token : undefined; + try { atomicJson(join(lock, MCP_GROUPS), { pid: process.pid, ...(token ? { token } : {}), groups }); } catch { /* best effort */ } }); } /** - * The recorded MCP groups of daemon `pid` that still have a member the daemon - * spawned, read before the daemon dies and its children are reparented. A group - * id with no such member may have been reused, so it is never signalled. + * Selects which recorded MCP process groups belong to `daemonPid` and may be + * force-stopped when the daemon is SIGKILLed: + * - A group whose leader PID is currently held by a process outside the + * daemon's tree was recycled and is never signalled. + * - A group with a live or zombie member descended from `daemonPid` is owned. + * - A leaderless group (`pid === group` already exited and was reaped, e.g. an + * `npx`/`uvx` wrapper whose grandchild server outlived it) with live members + * owned by the daemon's UID is owned: POSIX prevents PID `group` reuse while + * any member stays in that group, and `AidenStdioTransport` drops empty groups. */ -function daemonMcpGroups(agentDir: string, pid: number): number[] { - let recorded: { pid?: unknown; groups?: unknown } | undefined; - try { recorded = readJson<{ pid?: unknown; groups?: unknown } | undefined>(join(agentDir, SERVE_LOCK, MCP_GROUPS), undefined); } catch { return []; } - if (recorded?.pid !== pid || !Array.isArray(recorded.groups)) return []; - const wanted = new Set(recorded.groups.filter((group): group is number => validPid(group) && group !== pid)); - if (!wanted.size) return []; +export function selectDaemonMcpGroups( + daemonPid: number, + recordedGroups: readonly number[], + processes: readonly ObservedProcess[], + options: { daemonPgid?: number; daemonUid?: number } = {}, +): number[] { + const byPid = new Map(); + const byPgid = new Map(); + for (const proc of processes) { + byPid.set(proc.pid, proc); + let members = byPgid.get(proc.pgid); + if (!members) { + members = []; + byPgid.set(proc.pgid, members); + } + members.push(proc); + } + const daemonProc = byPid.get(daemonPid); + const daemonPgid = options.daemonPgid ?? daemonProc?.pgid; + const daemonUid = daemonProc?.uid ?? options.daemonUid; + const isDescendantOfDaemon = (proc: ObservedProcess): boolean => { + const visited = new Set([proc.pid]); + let parentPid = proc.ppid; + while (validPid(parentPid)) { + if (parentPid === daemonPid) return true; + if (visited.has(parentPid)) return false; + visited.add(parentPid); + const parent = byPid.get(parentPid); + if (!parent) return false; + parentPid = parent.ppid; + } + return false; + }; const owned = new Set(); + for (const group of recordedGroups) { + if (!validPid(group) || group === daemonPid || group === daemonPgid) continue; + const members = byPgid.get(group); + if (!members || members.length === 0) continue; + const leader = byPid.get(group); + if (leader && !isDescendantOfDaemon(leader)) continue; + if (members.some((member) => isDescendantOfDaemon(member))) { + owned.add(group); + continue; + } + const liveMembers = members.filter((member) => !member.zombie); + if (liveMembers.length === 0) continue; + if (daemonUid !== undefined && liveMembers.some((member) => member.uid !== daemonUid)) continue; + owned.add(group); + } + return [...owned]; +} + +/** + * The recorded MCP groups of daemon `pid` that still belong to it, read before + * the daemon dies and its live children are reparented. Covers both direct + * children and orphaned grandchild servers whose wrapper exited. + */ +function daemonMcpGroups(agentDir: string, pid: number, owner?: ServeOwner): number[] { + let recorded: { pid?: unknown; token?: unknown; groups?: unknown } | undefined; + try { recorded = readJson<{ pid?: unknown; token?: unknown; groups?: unknown } | undefined>(join(agentDir, SERVE_LOCK, MCP_GROUPS), undefined); } catch { return []; } + if (recorded?.pid !== pid || !Array.isArray(recorded.groups)) return []; + if (typeof recorded.token === "string" && typeof owner?.token === "string" && recorded.token !== owner.token) return []; + const wanted = recorded.groups.filter((group): group is number => validPid(group) && group !== pid); + if (!wanted.length) return []; try { - const out = spawnSync("ps", ["-A", "-o", "pid=,ppid=,pgid="], { encoding: "utf8" }); + const out = spawnSync("ps", ["-A", "-o", "pid=,ppid=,pgid=,uid=,stat="], { encoding: "utf8" }); if (out.status !== 0) return []; + const processes: ObservedProcess[] = []; for (const line of out.stdout.split("\n")) { - const [, ppid, pgid] = line.trim().split(/\s+/u).map(Number); - if (ppid === pid && pgid !== undefined && wanted.has(pgid)) owned.add(pgid); + const trimmed = line.trim(); + if (!trimmed) continue; + const parts = trimmed.split(/\s+/u); + const procPid = Number(parts[0]); + const ppid = Number(parts[1]); + const pgid = Number(parts[2]); + const uid = Number(parts[3]); + const stat = parts[4] ?? ""; + if (!validPid(procPid) || !Number.isSafeInteger(ppid) || !validPid(pgid)) continue; + processes.push({ + pid: procPid, + ppid, + pgid, + ...(Number.isSafeInteger(uid) ? { uid } : {}), + zombie: stat.startsWith("Z"), + }); } + return selectDaemonMcpGroups(pid, wanted, processes, { + daemonUid: typeof process.getuid === "function" ? process.getuid() : undefined, + }); } catch { return []; } - return [...owned]; } function serveOwner(agentDir: string): ServeOwner | undefined { @@ -412,7 +502,7 @@ export async function stopDaemon(agentDir: string, timeoutMs = 15_000): Promise< // shares its group with the shell job (`aiden serve | tee`), so only the // serve process itself is killed. Either way its stdio MCP servers each lead // a group of their own, which the daemon recorded, and are killed as well. - const mcpGroups = daemonMcpGroups(agentDir, pid); + const mcpGroups = daemonMcpGroups(agentDir, pid, owner); const ownGroup = owner.detached === true && processGroupId(pid) === pid; try { process.kill(ownGroup ? -pid : pid, "SIGKILL"); } catch { /* already gone */ } for (const group of mcpGroups) { try { process.kill(-group, "SIGKILL"); } catch { /* already gone */ } } diff --git a/packages/cli/tests/serve-lifetime.test.mjs b/packages/cli/tests/serve-lifetime.test.mjs index d8ad722979..975dfddf2e 100644 --- a/packages/cli/tests/serve-lifetime.test.mjs +++ b/packages/cli/tests/serve-lifetime.test.mjs @@ -397,3 +397,96 @@ test("the command client settles once for every way a daemon can answer", posix, const missing = sandbox(t); await assert.rejects(api.remoteDaemonCommand(missing.agentDir, "serve", ["status"]), (error) => error.code === "ENOENT" && /not running/u.test(error.message)); }); + +test("selectDaemonMcpGroups includes orphaned wrapper survivors and refuses recycled, foreign-uid, or daemon-group entries", () => { + const daemonPid = 500; + const processes = [ + { pid: daemonPid, ppid: 400, pgid: 400, uid: 1000, zombie: false }, + // Direct child wrapper still alive. + { pid: 601, ppid: daemonPid, pgid: 601, uid: 1000, zombie: false }, + // Orphaned grandchild whose wrapper (602) exited and was reaped; reparented to init (1). + { pid: 612, ppid: 1, pgid: 602, uid: 1000, zombie: false }, + // Recycled leader PID (603) now owned by an unrelated parent (777) with a child in group 603. + { pid: 603, ppid: 777, pgid: 603, uid: 1000, zombie: false }, + { pid: 613, ppid: 603, pgid: 603, uid: 1000, zombie: false }, + // Leaderless group with only a zombie left. + { pid: 614, ppid: 1, pgid: 604, uid: 1000, zombie: true }, + // Leaderless group whose live member belongs to another user. + { pid: 615, ppid: 1, pgid: 605, uid: 2000, zombie: false }, + // Unrelated process sharing the foreground daemon's shell process group (400). + { pid: 401, ppid: 400, pgid: 400, uid: 1000, zombie: false }, + ]; + assert.deepEqual( + api.selectDaemonMcpGroups(daemonPid, [601, 602, 603, 604, 605, 400, daemonPid, 699], processes), + [601, 602], + ); +}); + +test("serve stop force-stops an orphaned MCP grandchild survivor after its wrapper exited", posix, async (t) => { + const box = sandbox(t); + const pkg = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + const wrapper = join(box.agentDir, "mcp-wrapper.mjs"); + const stuck = join(box.agentDir, "stuck-serve-orphan-mcp.mjs"); + const pidsFile = join(box.agentDir, "pids.json"); + const grandchildFile = join(box.agentDir, "grandchild.json"); + mkdirSync(box.lock, { mode: 0o700, recursive: true }); + // Wrapper spawns a stubborn grandchild in the same process group, then exits immediately. + writeFileSync(wrapper, `import { spawn } from "node:child_process"; import { renameSync, writeFileSync } from "node:fs"; +const child = spawn(process.execPath, ["-e", "process.on('SIGTERM', () => {}); process.stdin.resume(); process.stdin.on('end', () => {}); setInterval(() => {}, 1e9);"], { stdio: ["ignore", "inherit", "inherit"] }); +writeFileSync(${JSON.stringify(grandchildFile + ".tmp")}, JSON.stringify({ wrapper: process.pid, grandchild: child.pid })); +renameSync(${JSON.stringify(grandchildFile + ".tmp")}, ${JSON.stringify(grandchildFile)}); +process.exit(0);`); + writeFileSync(stuck, `import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import * as api from ${JSON.stringify(join(pkg, "dist/parity-test-api.js"))}; +process.on("SIGTERM", () => {}); +api.recordServeMcpGroups(${JSON.stringify(box.agentDir)}); +const transport = api.createMcpStdioTransport({ command: process.execPath, args: [${JSON.stringify(wrapper)}], stderr: "pipe" }); +await transport.start(); +const deadline = Date.now() + 10_000; +while (!existsSync(${JSON.stringify(grandchildFile)}) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 25)); +const info = JSON.parse(readFileSync(${JSON.stringify(grandchildFile)}, "utf8")); +writeFileSync(${JSON.stringify(pidsFile + ".tmp")}, JSON.stringify({ ...info, group: transport.pid })); +renameSync(${JSON.stringify(pidsFile + ".tmp")}, ${JSON.stringify(pidsFile)}); +setInterval(() => {}, 1e9);`); + const daemon = spawn(process.execPath, [stuck, "serve"], { stdio: "ignore", detached: true }); + let started; + t.after(() => { + for (const pid of [daemon.pid, started?.group, started?.grandchild]) { + if (pid) { + try { process.kill(-pid, "SIGKILL"); } catch { /* already gone */ } + try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ } + } + } + }); + const ready = Date.now() + 10_000; + while (!existsSync(pidsFile) && Date.now() < ready) await new Promise((r) => setTimeout(r, 25)); + assert.equal(existsSync(pidsFile), true, "stuck daemon failed to start wrapper fixture"); + started = JSON.parse(readFileSync(pidsFile, "utf8")); + // Wait for the wrapper leader to finish exiting and be reaped by the daemon, + // leaving only the orphaned grandchild alive in the recorded MCP group. + const isRunning = (pid) => { + if (!api.pidAlive(pid)) return false; + const state = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" }); + return state.status === 0 && state.stdout.trim() !== "" && !state.stdout.trim().startsWith("Z"); + }; + const waitExit = Date.now() + 5_000; + while (api.pidAlive(started.wrapper) && Date.now() < waitExit) await new Promise((r) => setTimeout(r, 25)); + assert.equal(api.pidAlive(started.wrapper), false, "wrapper leader should have exited and been reaped"); + assert.equal(isRunning(started.grandchild), true, "grandchild survivor should still be running"); + api.atomicJson(join(box.lock, "owner.json"), { + detached: true, + pid: daemon.pid, + argv: [process.execPath, stuck, "serve"], + startedAt: Date.now(), + token: "orphan-test", + }); + writeFileSync(box.socket, ""); + assert.deepEqual(await api.stopDaemon(box.agentDir, 1_000), { stopped: true, pid: daemon.pid, forced: true }); + const stopDeadline = Date.now() + 5_000; + while ((isRunning(daemon.pid) || isRunning(started.grandchild)) && Date.now() < stopDeadline) { + await new Promise((r) => setTimeout(r, 25)); + } + assert.equal(isRunning(daemon.pid), false, "daemon must be stopped"); + assert.equal(isRunning(started.grandchild), false, "orphaned MCP grandchild survivor must be stopped"); + assert.equal(existsSync(box.lock), false); +}); From 8cea0941e70b68a56d4bd40b2a9f88b0ef7f2176 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 06:27:35 +0000 Subject: [PATCH 2/6] cli,mcp,docs: require process-incarnation proof for leaderless MCP groups and reconcile Phase 4A-4C plan status --- ...-state-machines-refresh-plan-2026-11-23.md | 26 +-- docs/state-machines/serve-daemon.md | 2 +- main/services/mcp-stdio-transport.test.ts | 46 +++- main/services/mcp-stdio-transport.ts | 181 ++++++++++++++-- main/shared/process-group.ts | 161 +++++++++++++- packages/cli/src/serve-lifecycle.ts | 197 +++++++++++++----- packages/cli/tests/serve-lifetime.test.mjs | 151 ++++++++++++-- 7 files changed, 660 insertions(+), 104 deletions(-) diff --git a/docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md b/docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md index 9e82827303..4585fd79d7 100644 --- a/docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md +++ b/docs/plans/explicit-state-machines-refresh-plan-2026-11-23.md @@ -53,7 +53,7 @@ Three independent verification passes against `b2b5c3517` established the exact | **D3** | Phase 1B failure-ambiguity policy | **Option A:** Two-tier endpoint contract (`beforeEffectRefusal` vs `cachedRejectionLedger`) in `AidenRemoteFailureClassification.{swift,kt}`, backed by shared fixture `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json` (no Remote protocol revision bump). | | **D4** | Phase 1C `bot-execution.ts` & `bot-peers/service.ts` | **Option A:** Land transition worksheets (`docs/state-machines/bot-execution-and-peers.md`) first; keep security-critical receipt code untouched unless a test reproduces a defect. | | **D5** | Phase 2A Android parity scope | **Option B (executed):** Unified classifiers + extracted `AidenDurablePendingMutation` on both iOS and Android alongside fixing two `STORAGE`-masking defects in Android `OpenWork` and `Peers`. | -| **D6** | Phase 4B `AidenChatViewModel` first slice | **Option A (planned):** Start with `AidenForeignRunObserver` (`AidenChatViewModel+ForeignRuns.swift`), then `AidenPendingSendCoordinator`, then `AidenChatMutationSubMachines`. | +| **D6** | Phase 4B `AidenChatViewModel` first slice | **Option A (executed):** Extracted `AidenForeignRunObserver` (`AidenChatViewModel+ForeignRuns.swift`), `AidenPendingSendCoordinator`, and `AidenChatMutationSubMachines` in stacked PR #906 (`feat/sm-ios-dense-owners`). | | **D7** | Phase 4D/4E backlog depth | **Option A (risk-gated):** Fix `aiden serve stop` MCP survivor gap, execute cross-lane P1–P4 shutdown trace, reconcile P5/P6/Tier-A owners via transition worksheets + targeted race/teardown tests, fixing only reproduced defects. | --- @@ -66,24 +66,26 @@ Three independent verification passes against `b2b5c3517` established the exact | **Phase 1** (`1A`, `1B`, `1C`) | Unify 4 subagent progression copies (`renderer/shared/subagent-runs.ts`); two-tier `AidenRemoteFailureClassification` on iOS (12 sites) & Android + `mutation-failure-ambiguity.json` fixture fixing `409 idempotency_in_flight`; `bot-execution-and-peers.md` | **Implemented** (iOS `xcodebuild` simulator check pending macOS host) | `renderer/shared/subagent-runs.ts`, `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json`, `AidenRemoteFailureClassification.{swift,kt}`, `docs/state-machines/bot-execution-and-peers.md` | | **Phase 2** (`2A`, `2B`) | Shared `AidenDurablePendingMutation` across 5 iOS Bot files (6 classes) & Android parity + direct unit tests (`AidenDurablePendingMutationTests`, `AidenBotResumeModelTests`, `AidenScheduledTasksModel`, `ComposerVoiceInputController`) | **Implemented** (iOS `xcodebuild` simulator check pending macOS host) | `ios/AidenOnTheGo/Features/Bots/AidenDurablePendingMutation.swift`, `android/.../AidenDurablePendingMutation.kt`, mobile test suites | | **Phase 3** (`3A`, `3B`) | Proactive Aiden (`proactive-aiden.md`, 2 `goal-loop.ts` race fixes); Phase 3B desktop owners (`new-desktop-owners-2026-11.md`, `use-design-canvas.ts` sync races, `provider.ts` close-during-`enabled()` fixes, `hook-dispatcher.ts` idempotency eviction-identity fix, `aiden-mcp-tools`/`bot-plans`/`bot-messages` teardown tests) | **Implemented** | `docs/state-machines/{proactive-aiden,new-desktop-owners-2026-11}.md`, `main/services/goal/goal-loop.ts`, `main/services/gemini-live/app-control/provider.ts`, `main/services/hooks/hook-dispatcher.ts`, `renderer/design/use-design-canvas.ts` | -| **Phase 4A–4C** (iOS dense owners) | Explicit `AidenHostConnectionLifecycle` (`AidenHostConnection.swift`), incremental `AidenChatViewModel` extractions (`AidenForeignRunObserver`, `AidenPendingSendCoordinator`, `AidenChatMutationSubMachines`), explicit `ComposerVoiceInputReducer` + simulator tests | **Implemented** (macOS `xcodebuild` Simulator CI & physical-device mic acceptance pending) | `ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnectionLifecycle.swift`, `ios/AidenOnTheGo/Features/Chat/{AidenForeignRunObserver,AidenPendingSendCoordinator,AidenChatMutationSubMachines,ComposerVoiceInputController}.swift` | +| **Phase 4A–4C** (iOS dense owners) | Explicit `AidenHostConnectionLifecycle` (`AidenHostConnection.swift`), incremental `AidenChatViewModel` extractions (`AidenForeignRunObserver`, `AidenPendingSendCoordinator`, `AidenChatMutationSubMachines`), explicit `ComposerVoiceInputReducer` + simulator tests | **Implemented** in stacked PR #906 (`feat/sm-ios-dense-owners`; macOS `xcodebuild` Simulator CI & physical-device mic acceptance pending) | `ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnectionLifecycle.swift`, `ios/AidenOnTheGo/Features/Chat/{AidenForeignRunObserver,AidenPendingSendCoordinator,AidenChatMutationSubMachines,ComposerVoiceInputController}.swift` | | **Phase 4D–4E** (P5, P6, CLI, Tier-A) | Fix `aiden serve stop` orphaned MCP survivor (`packages/cli/src/serve-lifecycle.ts` `selectDaemonMcpGroups`), review `cli-native:N13, O01, C12, C16, C28, C32` (`serve-daemon.md`), audit P5 unaudited remainder + cross-lane P1–P4 shutdown trace (`physical-teardown.md`), reconcile P6 & Tier-A queue (`p5-p6-tier-a-reconciliation.md`) + targeted teardown tests | **Implemented** (hardware/macOS acceptance separate) | `packages/cli/src/serve-lifecycle.ts`, `packages/cli/tests/serve-lifetime.test.mjs`, `docs/state-machines/{serve-daemon,physical-teardown,p5-p6-tier-a-reconciliation}.md` | --- -## 4. Remaining Open Execution Slices (Phases 4A–4C) +## 4. Phase 4A–4C Implementation Record (Stacked PR #906 / `feat/sm-ios-dense-owners`) -### PR 4A: Explicit `AidenHostConnection` Lifecycle (`ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnection.swift`) -- Consolidate the 8 coupled axes (`connectionState`, `generation`, `hostGeneration`, `connectionGeneration`, `isRevoked`, `isPurgePending`, `connectInFlight`, `settledState`) into an explicit pure transition type separating terminal custody (`active` vs `revoked(purgePending: Bool)`) from connection attempt state (`idle` / `connecting` / `connected` / `offline`), keeping all `@Observable` properties derived and `AidenHostRegistry` / `AidenHostConnectScheduler` untouched. -- Check Android's host connection coordinator for revocation-vs-reconnect parity. +All three iOS dense-owner slices (4A–4C) are implemented in stacked PR #906 (`feat/sm-ios-dense-owners`); only macOS `xcodebuild` Simulator CI, Android `:app:lintDebug`, and physical-device/hardware acceptance remain open before closing the wave: -### PR 4B (Series of 3 Small PRs): Incremental `AidenChatViewModel` Extraction -- **PR 4B-1:** Extract `AidenForeignRunObserver` from `AidenChatViewModel+ForeignRuns.swift` (`probeForForeignRuns`, `isCurrentForeignRun`, `foreignRunGeneration`). -- **PR 4B-2:** Extract `AidenPendingSendCoordinator` (`pendingSend`, `canRetrySend`, `scheduleRateLimitedSendRetry`) over `AidenChatDraftStore`. -- **PR 4B-3:** Extract `AidenChatMutationSubMachines` (worktree setup cancel-after-finish guard, fork/continue attempts, approval/question snapshot generation fences). +### Phase 4A: Explicit `AidenHostConnection` Lifecycle (`ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnectionLifecycle.swift`) +- Consolidated the 8 coupled axes (`connectionState`, `generation`, `hostGeneration`, `connectionGeneration`, `isRevoked`, `isPurgePending`, `connectInFlight`, `settledState`) into an explicit pure transition type separating terminal custody (`active` vs `revoked(purgePending: Bool)`) from connection attempt state (`idle` / `connecting` / `connected` / `offline`), keeping all `@Observable` properties derived and `AidenHostRegistry` / `AidenHostConnectScheduler` untouched. +- Verified Android host connection coordinator revocation-vs-reconnect parity. -### PR 4C: Explicit `ComposerVoiceInputController` Reducer (`ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift`) -- Consolidate the 12 `state` write sites and audio/task ownership flags (`activatedAudioSessionForRecording`, `audioTapInstalled`, `macTranscriptionTask`, `nativeFinalizationTask`, `suppressNextRecognitionError`, `sessionFence`) into one explicit transition function over `(State, Backend, ResourceOwnership)` guaranteeing tap/audio-session/task cleanup on every exit to `.idle`. +### Phase 4B: Incremental `AidenChatViewModel` Extractions (`ios/AidenOnTheGo/Features/Chat/`) +- **4B-1:** Extracted `AidenForeignRunObserver` from `AidenChatViewModel+ForeignRuns.swift` (`probeForForeignRuns`, `isCurrentForeignRun`, `foreignRunGeneration`). +- **4B-2:** Extracted `AidenPendingSendCoordinator` (`pendingSend`, `canRetrySend`, `scheduleRateLimitedSendRetry`) over `AidenChatDraftStore`. +- **4B-3:** Extracted `AidenChatMutationSubMachines` (worktree setup cancel-after-finish guard, fork/continue attempts, approval/question snapshot generation fences). + +### Phase 4C: Explicit `ComposerVoiceInputController` Reducer (`ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift`) +- Consolidated the 12 `state` write sites and audio/task ownership flags (`activatedAudioSessionForRecording`, `audioTapInstalled`, `macTranscriptionTask`, `nativeFinalizationTask`, `suppressNextRecognitionError`, `sessionFence`) into one explicit `ComposerVoiceInputReducer` transition function over `(State, Backend, ResourceOwnership)` guaranteeing tap/audio-session/task cleanup on every exit to `.idle`. --- diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index 73a89e0c2d..765f700b3b 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -126,7 +126,7 @@ Evidence of exit is `pidAlive`, never the signal. **Defect fixed:** the periodic `foreign` check ran only every tenth poll, so a PID that stopped being ours just before the deadline fell through to `did not stop ... try kill -9 `, sending the person to kill an unrelated process. Reproduced in `tests/serve-lifetime.test.mjs` with a process that `exec`s into something else. -**Defect fixed (2026-11-24, Phase 4D):** `aiden serve stop` could not force-stop an orphaned MCP grandchild survivor whose wrapper (`npx`, `uvx`, or launcher script) had already exited and been reaped, because `daemonMcpGroups()` in `packages/cli/src/serve-lifecycle.ts` required a direct child (`ppid === pid`). `recordServeMcpGroups()` now binds `mcp-groups.json` to the daemon's lease token when present, and `selectDaemonMcpGroups()` selects (1) any recorded group with a member descended from `daemonPid`, and (2) any leaderless recorded group (`pid === group` absent) with live non-zombie members owned by the daemon's UID (POSIX forbids reusing PID `group` while any member remains in that group, and `AidenStdioTransport` drops empty groups), while refusing any group whose leader PID is held outside the daemon's tree (recycled PID), any group matching `daemonPid` or `daemonPgid`, zombie-only groups, or foreign-UID groups. Verified by both pure selection tests and a real-process orphaned-grandchild stop test in `packages/cli/tests/serve-lifetime.test.mjs`. +**Defect fixed (2026-11-24, Phase 4D):** `aiden serve stop` could not force-stop an orphaned MCP grandchild survivor whose wrapper (`npx`, `uvx`, or launcher script) had already exited and been reaped, because `daemonMcpGroups()` in `packages/cli/src/serve-lifecycle.ts` required a direct child (`ppid === pid`). `AidenStdioTransport` (`main/services/mcp-stdio-transport.ts`) now captures the leader's kernel start identifier (`proc:` on Linux, UTC `lstart:` on macOS) and, when the leader exits, snapshots surviving same-UID group members `{ pid, startId }`, and `recordServeMcpGroups()` publishes those incarnation records (`groupRecords`) bound to the daemon's lease token when present. `selectDaemonMcpGroups()` selects (1) any recorded group with a member descended from `daemonPid` (provided any live leader matches its recorded `leaderStartId`), and (2) any leaderless recorded group (`pid === group` absent) ONLY when a live non-zombie same-UID member matches—or descends from a group member matching—a recorded survivor `{ pid, startId }`. Same-UID membership alone is never accepted, so a stale PGID reused by an unrelated same-UID wrapper that exits fails closed alongside recycled leaders, `daemonPid`/`daemonPgid`, zombie-only groups, and foreign-UID groups. `AidenStdioTransport`'s survivor poll (`forgetWhenGone`) uses the same incarnation proof so a reused PGID is dropped immediately rather than kept live. Verified by pure selection tests and real-process orphaned-grandchild + stale-PGID-reuse stop tests in `packages/cli/tests/serve-lifetime.test.mjs`. ## C04: local daemon command framing diff --git a/main/services/mcp-stdio-transport.test.ts b/main/services/mcp-stdio-transport.test.ts index 117659fc44..055d43e7d0 100644 --- a/main/services/mcp-stdio-transport.test.ts +++ b/main/services/mcp-stdio-transport.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { McpClient } from "@earendil-works/pi-mcp"; -import { createMcpStdioTransport, watchMcpProcessGroups } from "./mcp-stdio-transport.js"; +import { createMcpStdioTransport, watchMcpProcessGroupRecords, watchMcpProcessGroups, type McpProcessGroupRecord } from "./mcp-stdio-transport.js"; /** * A wrapper-shaped server (like `npx`/`uvx`): it starts a long-lived @@ -153,6 +153,50 @@ test("a closed transport means the whole group is gone, even a descendant that i assert.equal(listedWhileAlive, true, "a running group left the list a force-stop owner reads"); }); +test("watchMcpProcessGroupRecords captures surviving grandchild incarnation when a wrapper exits while pipes stay open", { + skip: process.platform === "win32" ? "POSIX process groups" : false, + timeout: 15_000, +}, async (t) => { + const directory = await mkdtemp(join(tmpdir(), "aiden-mcp-stdio-")); + t.after(() => rm(directory, { recursive: true, force: true })); + const reportFile = join(directory, "report.json"); + const wrapper = ` +const { spawn } = require("node:child_process"); +const { writeFileSync } = require("node:fs"); +const grandchild = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: ["ignore", "inherit", "inherit"] }); +writeFileSync(${JSON.stringify(reportFile)}, JSON.stringify({ wrapper: process.pid, grandchild: grandchild.pid })); +process.exit(0); +`; + let latest: readonly McpProcessGroupRecord[] = []; + const stopWatching = watchMcpProcessGroupRecords((records) => { latest = records; }); + t.after(stopWatching); + const transport = createMcpStdioTransport({ + command: process.execPath, + args: ["-e", wrapper], + closeGraceMs: 300, + stderr: "pipe", + }); + t.after(() => transport.close().catch(() => undefined)); + await transport.start(); + for (let attempt = 0; attempt < 200 && !existsSync(reportFile); attempt += 1) await delay(20); + const report = JSON.parse(await readFile(reportFile, "utf8")) as { wrapper: number; grandchild: number }; + t.after(() => { try { process.kill(report.grandchild, "SIGKILL"); } catch { /* already gone */ } }); + for (let attempt = 0; attempt < 200; attempt += 1) { + const record = latest.find((entry) => entry.pgid === report.wrapper); + if (record?.survivors.some((survivor) => survivor.pid === report.grandchild && survivor.startId.length > 0)) break; + await delay(20); + } + const captured = latest.find((entry) => entry.pgid === report.wrapper); + assert.ok(captured, "wrapper group record should still be tracked while grandchild holds pipes"); + assert.ok( + captured.survivors.some((survivor) => survivor.pid === report.grandchild && survivor.startId.length > 0), + `expected grandchild ${report.grandchild} with startId in ${JSON.stringify(captured)}`, + ); + await transport.close(); + for (let attempt = 0; attempt < 150 && alive(report.grandchild); attempt += 1) await delay(20); + assert.equal(alive(report.grandchild), false, "transport.close() must reap the surviving grandchild"); +}); + test("a group that survives close leaves the list once it is gone, so its ID is never signalled again", { skip: process.platform === "win32" ? "POSIX process groups" : false, timeout: 15_000, diff --git a/main/services/mcp-stdio-transport.ts b/main/services/mcp-stdio-transport.ts index 40fbc0dc0c..8b9052fdbd 100644 --- a/main/services/mcp-stdio-transport.ts +++ b/main/services/mcp-stdio-transport.ts @@ -7,9 +7,31 @@ // a process outside the group holds the server's stdout. import type { ChildProcess } from "node:child_process"; import process from "node:process"; -import { groupStoppedWithin, processGroupExists, processGroupStillRuns } from "../shared/process-group.js"; +import { + captureProcessGroupSurvivors, + groupStoppedWithin, + listObservedProcesses, + processGroupExists, + processGroupStillRuns, + readProcessStartId, + type ObservedProcessEntry, + type ProcessIncarnationSurvivor, +} from "../shared/process-group.js"; import { StdioTransport, type McpTransport, type StdioTransportOptions } from "@earendil-works/pi-mcp"; +export interface McpProcessGroupRecord { + pgid: number; + leaderStartId?: string; + survivors: readonly ProcessIncarnationSurvivor[]; +} + +interface TrackedMcpGroupRecord { + pgid: number; + leaderStartId?: string; + leaderExited: boolean; + survivors: ProcessIncarnationSurvivor[]; +} + export interface McpStdioTransportOptions { groupStillRuns?: (pid: number) => Promise; command: string; @@ -32,13 +54,26 @@ const DEFAULT_CLOSE_GRACE_MS = 2_000; const SURVIVOR_POLL_MS = 1_000; // SIGKILL is asynchronous and can be denied, so sending it proves nothing. const KILL_CONFIRM_MS = 2_000; -const liveGroups = new Set(); +const liveGroups = new Map(); const groupListeners = new Set<(groups: readonly number[]) => void>(); +const groupRecordListeners = new Set<(records: readonly McpProcessGroupRecord[]) => void>(); let exitHookInstalled = false; +function snapshotGroupRecords(): McpProcessGroupRecord[] { + return [...liveGroups.values()].map((record) => ({ + pgid: record.pgid, + ...(record.leaderStartId ? { leaderStartId: record.leaderStartId } : {}), + survivors: record.survivors.map((survivor) => ({ pid: survivor.pid, startId: survivor.startId })), + })); +} + function groupsChanged(): void { - const groups = [...liveGroups]; + const groups = [...liveGroups.keys()]; for (const listener of groupListeners) listener(groups); + if (groupRecordListeners.size > 0) { + const records = snapshotGroupRecords(); + for (const listener of groupRecordListeners) listener(records); + } } /** @@ -48,10 +83,42 @@ function groupsChanged(): void { */ export function watchMcpProcessGroups(listener: (groups: readonly number[]) => void): () => void { groupListeners.add(listener); - listener([...liveGroups]); + listener([...liveGroups.keys()]); return () => { groupListeners.delete(listener); }; } +/** + * Reports live stdio MCP process groups together with kernel start-ID + * incarnation proof (leader start ID and any survivors captured when a wrapper + * leader exited), so a force-stop caller never signals a reused PGID. + */ +export function watchMcpProcessGroupRecords( + listener: (records: readonly McpProcessGroupRecord[]) => void, +): () => void { + groupRecordListeners.add(listener); + listener(snapshotGroupRecords()); + return () => { groupRecordListeners.delete(listener); }; +} + +function isDescendantOfAny( + proc: ObservedProcessEntry, + roots: ReadonlySet, + byPid: ReadonlyMap, +): boolean { + if (roots.has(proc.pid)) return true; + const visited = new Set([proc.pid]); + let parentPid = proc.ppid; + while (Number.isSafeInteger(parentPid) && parentPid > 0) { + if (roots.has(parentPid)) return true; + if (visited.has(parentPid)) return false; + visited.add(parentPid); + const parent = byPid.get(parentPid); + if (!parent) return false; + parentPid = parent.ppid; + } + return false; +} + /** The environment every stdio server may see, matching the MCP SDK's default set. */ const DEFAULT_INHERITED_ENV_VARS = process.platform === "win32" ? ["APPDATA", "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "PATH", "PROCESSOR_ARCHITECTURE", "SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "USERNAME", "USERPROFILE", "PROGRAMFILES"] @@ -85,7 +152,10 @@ function installExitHook(): void { if (exitHookInstalled) return; exitHookInstalled = true; process.once("exit", () => { - for (const pid of liveGroups) signalGroup(pid, "SIGTERM"); + for (const [pid, record] of liveGroups) { + if (record.leaderExited && record.survivors.length === 0) continue; + signalGroup(pid, "SIGTERM"); + } }); } @@ -109,6 +179,9 @@ const OVERSIZED_MESSAGE = /^MCP stdio message exceeds \d+ bytes$/u; */ class AidenStdioTransport extends StdioTransport { private groupPid?: number; + private groupRecord?: TrackedMcpGroupRecord; + private readonly customGroupProbe: boolean; + private readonly groupStillRuns: (pid: number) => Promise; /** The process group's teardown, which runs exactly once. */ private reaping?: Promise; @@ -116,9 +189,11 @@ class AidenStdioTransport extends StdioTransport { options: StdioTransportOptions, private readonly graceMs: number, private readonly processGroups: boolean, - private readonly groupStillRuns: (pid: number) => Promise = processGroupStillRuns, + groupStillRuns?: (pid: number) => Promise, ) { super(options); + this.customGroupProbe = groupStillRuns !== undefined; + this.groupStillRuns = groupStillRuns ?? processGroupStillRuns; // Every pipe is closed, so nothing left in the group can reach Aiden. A // wrapper that exited on its own may still have left its server there. this.onClose(() => void this.reapGroup()); @@ -136,7 +211,29 @@ class AidenStdioTransport extends StdioTransport { if (pid === undefined || !this.processGroups) return; this.groupPid = pid; installExitHook(); - liveGroups.add(pid); + const leaderStartId = readProcessStartId(pid); + const record: TrackedMcpGroupRecord = { + pgid: pid, + ...(leaderStartId ? { leaderStartId } : {}), + leaderExited: false, + survivors: [], + }; + this.groupRecord = record; + liveGroups.set(pid, record); + const child = (this as unknown as { child?: ChildProcess }).child; + const captureLeaderExit = (): void => { + if (liveGroups.get(pid) !== record || record.leaderExited) return; + record.leaderExited = true; + const survivors = captureProcessGroupSurvivors(pid, record.leaderStartId); + if (survivors.length > 0) { + record.survivors = survivors; + groupsChanged(); + } + }; + if (child) { + if (child.exitCode !== null || child.signalCode !== null) captureLeaderExit(); + else child.once("exit", captureLeaderExit); + } groupsChanged(); } @@ -162,33 +259,77 @@ class AidenStdioTransport extends StdioTransport { await this.reapGroup(); } + private async incarnationStillRuns(pid: number, record: TrackedMcpGroupRecord): Promise { + if (this.customGroupProbe) return this.groupStillRuns(pid); + if (!processGroupExists(pid)) return false; + const processes = listObservedProcesses({ exactStartIdForPgids: new Set([pid]) }); + if (!processes) return this.groupStillRuns(pid); + const members = processes.filter((proc) => proc.pgid === pid); + if (members.length === 0) return false; + const leader = processes.find((proc) => proc.pid === pid); + if (!record.leaderExited) { + if (leader && record.leaderStartId && leader.startId && leader.startId !== record.leaderStartId) { + return false; + } + return members.some((proc) => !proc.zombie); + } + // Leader already exited and was reaped: a live leader PID now means PGID reuse. + if (leader || record.survivors.length === 0) return false; + const currentUid = typeof process.getuid === "function" ? process.getuid() : undefined; + const byPid = new Map(); + for (const proc of processes) byPid.set(proc.pid, proc); + const verifiedPids = new Set(); + for (const member of members) { + if (currentUid !== undefined && member.uid !== currentUid) continue; + if (!member.startId) continue; + if (record.survivors.some((survivor) => survivor.pid === member.pid && survivor.startId === member.startId)) { + verifiedPids.add(member.pid); + } + } + if (verifiedPids.size === 0) return false; + return members.some( + (member) => !member.zombie && (currentUid === undefined || member.uid === currentUid) && isDescendantOfAny(member, verifiedPids, byPid), + ); + } + + private removeRecord(pid: number, record: TrackedMcpGroupRecord): void { + if (liveGroups.get(pid) === record && liveGroups.delete(pid)) groupsChanged(); + } + /** * Terminate whatever remains of the group: SIGTERM, then SIGKILL after the - * grace. A group is forgotten only once nothing in it runs, so whoever - * force-stops this process can still find one that survived. + * grace. A group is forgotten only once our incarnation no longer runs, so + * whoever force-stops this process can still find one that survived without + * ever chasing a reused PGID. */ private reapGroup(): Promise { const pid = this.groupPid; - if (pid === undefined) return Promise.resolve(); + const record = this.groupRecord; + if (pid === undefined || record === undefined) return Promise.resolve(); this.reaping ??= (async () => { signalGroup(pid, "SIGTERM"); - const probe = { exists: () => processGroupExists(pid), stillRuns: () => this.groupStillRuns(pid) }; + const probe = { + exists: () => processGroupExists(pid), + stillRuns: () => this.incarnationStillRuns(pid, record), + }; if (!(await groupStoppedWithin(probe, this.graceMs))) { - signalGroup(pid, "SIGKILL"); - await groupStoppedWithin(probe, KILL_CONFIRM_MS); + if (await this.incarnationStillRuns(pid, record)) { + signalGroup(pid, "SIGKILL"); + await groupStoppedWithin(probe, KILL_CONFIRM_MS); + } } - if (await this.groupStillRuns(pid)) this.forgetWhenGone(pid); - else if (liveGroups.delete(pid)) groupsChanged(); + if (await this.incarnationStillRuns(pid, record)) this.forgetWhenGone(pid, record); + else this.removeRecord(pid, record); })(); return this.reaping; } - /** A listed ID gets signalled later, so a dead group must not stay listed for reuse to hit. */ - private forgetWhenGone(pid: number): void { + /** A listed ID gets signalled later, so a dead or reused group must not stay listed. */ + private forgetWhenGone(pid: number, record: TrackedMcpGroupRecord): void { const timer = setTimeout(() => { - void this.groupStillRuns(pid).then((runs) => { - if (runs) this.forgetWhenGone(pid); - else if (liveGroups.delete(pid)) groupsChanged(); + void this.incarnationStillRuns(pid, record).then((runs) => { + if (runs) this.forgetWhenGone(pid, record); + else this.removeRecord(pid, record); }); }, SURVIVOR_POLL_MS); timer.unref?.(); diff --git a/main/shared/process-group.ts b/main/shared/process-group.ts index 6a8f8ebdbf..f70c738e00 100644 --- a/main/shared/process-group.ts +++ b/main/shared/process-group.ts @@ -3,7 +3,8 @@ // leader, also stops the shell's background jobs, Git's helpers and a script's // children. Windows has no process groups; there only the child is signalled. -import { execFile, type ChildProcess } from "node:child_process"; +import { execFile, spawnSync, type ChildProcess } from "node:child_process"; +import { readFileSync } from "node:fs"; import { StringDecoder } from "node:string_decoder"; const POLL_MS = 25; @@ -11,6 +12,164 @@ const POLL_MS = 25; const STOP_POLL_MS = 100; // SIGKILL is asynchronous and can be denied, so sending it proves nothing. const KILL_CONFIRM_MS = 2_000; +// Small tolerance for 1-second `ps lstart` granularity / NTP clock jitter. +const LSTART_TOLERANCE_MS = 2_000; + +export interface ProcessIncarnationSurvivor { + pid: number; + startId: string; +} + +export interface ObservedProcessEntry { + pid: number; + ppid: number; + pgid: number; + uid?: number; + zombie: boolean; + startId?: string; +} + +function deterministicPsEnv(): NodeJS.ProcessEnv { + return { ...process.env, LC_ALL: "C", TZ: "UTC" }; +} + +function readLinuxProcStartId(pid: number): string | undefined { + if (process.platform !== "linux") return undefined; + try { + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + const closeParen = stat.lastIndexOf(")"); + if (closeParen < 0) return undefined; + // Field 3 (state) is index 0 after `) `; field 22 (starttime in clock ticks since boot) is index 19. + const fields = stat.slice(closeParen + 2).trim().split(" "); + const starttime = fields[19]; + return starttime && /^\d+$/u.test(starttime) ? `proc:${starttime}` : undefined; + } catch { + return undefined; + } +} + +/** + * Kernel-recorded process start identifier for `pid`: monotonic boot-tick + * `starttime` on Linux (`/proc//stat`), or UTC `ps lstart` on other POSIX + * systems (macOS). Works even for Hardened Runtime / SIP binaries where + * environment inspection is denied. + */ +export function readProcessStartId(pid: number): string | undefined { + if (process.platform === "win32" || !Number.isSafeInteger(pid) || pid <= 0) return undefined; + const linuxStartId = readLinuxProcStartId(pid); + if (linuxStartId) return linuxStartId; + try { + const out = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { + encoding: "utf8", + env: deterministicPsEnv(), + timeout: 2_000, + }); + if (out.status !== 0) return undefined; + const trimmed = out.stdout.trim().replace(/\s+/gu, " "); + return trimmed ? `lstart:${trimmed}` : undefined; + } catch { + return undefined; + } +} + +/** Whether `candidateStartId` is at least as recent as `leaderStartId`. */ +export function startIdNotOlderThan( + candidateStartId: string | undefined, + leaderStartId: string | undefined, +): boolean { + if (!candidateStartId || !leaderStartId) return true; + if (candidateStartId.startsWith("proc:") && leaderStartId.startsWith("proc:")) { + try { + return BigInt(candidateStartId.slice(5)) >= BigInt(leaderStartId.slice(5)); + } catch { + return true; + } + } + if (candidateStartId.startsWith("lstart:") && leaderStartId.startsWith("lstart:")) { + const candidateMs = Date.parse(`${candidateStartId.slice(7)} UTC`); + const leaderMs = Date.parse(`${leaderStartId.slice(7)} UTC`); + if (Number.isFinite(candidateMs) && Number.isFinite(leaderMs)) { + return candidateMs >= leaderMs - LSTART_TOLERANCE_MS; + } + } + return true; +} + +/** + * Lists live and zombie POSIX processes with their start identifiers. On Linux, + * processes in `exactStartIdForPgids` use monotonic `/proc//stat` ticks so + * they match `readProcessStartId()` even across same-second spawns or clock shifts. + */ +export function listObservedProcesses( + options: { exactStartIdForPgids?: ReadonlySet } = {}, +): ObservedProcessEntry[] | undefined { + if (process.platform === "win32") return undefined; + try { + const out = spawnSync("ps", ["-A", "-o", "pid=,ppid=,pgid=,uid=,stat=,lstart="], { + encoding: "utf8", + env: deterministicPsEnv(), + timeout: 2_000, + maxBuffer: 4 * 1024 * 1024, + }); + if (out.status !== 0) return undefined; + const processes: ObservedProcessEntry[] = []; + for (const line of out.stdout.split("\n")) { + const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u); + if (!match) continue; + const procPid = Number(match[1]); + const ppid = Number(match[2]); + const pgid = Number(match[3]); + const uid = Number(match[4]); + const stat = match[5] ?? ""; + const lstart = (match[6] ?? "").trim().replace(/\s+/gu, " "); + if (!Number.isSafeInteger(procPid) || procPid <= 0 || !Number.isSafeInteger(ppid) || !Number.isSafeInteger(pgid) || pgid <= 0) { + continue; + } + const lstartId = lstart ? `lstart:${lstart}` : undefined; + const startId = options.exactStartIdForPgids?.has(pgid) + ? (readLinuxProcStartId(procPid) ?? lstartId) + : lstartId; + processes.push({ + pid: procPid, + ppid, + pgid, + ...(Number.isSafeInteger(uid) ? { uid } : {}), + zombie: stat.startsWith("Z"), + ...(startId ? { startId } : {}), + }); + } + return processes; + } catch { + return undefined; + } +} + +/** + * Snapshots surviving non-zombie members of `pgid` right after our group leader + * exited and was reaped. If `pid === pgid` already exists in the process table, + * the PID was already reused and nothing is captured. + */ +export function captureProcessGroupSurvivors( + pgid: number, + leaderStartId?: string, +): ProcessIncarnationSurvivor[] { + if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 0 || !processGroupExists(pgid)) { + return []; + } + const processes = listObservedProcesses({ exactStartIdForPgids: new Set([pgid]) }); + if (!processes) return []; + // Our leader was just reaped, so any process holding `pid === pgid` now is a reused PID. + if (processes.some((proc) => proc.pid === pgid)) return []; + const currentUid = typeof process.getuid === "function" ? process.getuid() : undefined; + const survivors: ProcessIncarnationSurvivor[] = []; + for (const proc of processes) { + if (proc.pgid !== pgid || proc.pid === pgid || proc.zombie) continue; + if (currentUid !== undefined && proc.uid !== currentUid) continue; + if (!proc.startId || !startIdNotOlderThan(proc.startId, leaderStartId)) continue; + survivors.push({ pid: proc.pid, startId: proc.startId }); + } + return survivors; +} /** Whether any process is still in the group led by `pid`. Always false on Windows. */ export function processGroupExists(pid: number | undefined): boolean { diff --git a/packages/cli/src/serve-lifecycle.ts b/packages/cli/src/serve-lifecycle.ts index 25e92571cb..648713a4a4 100644 --- a/packages/cli/src/serve-lifecycle.ts +++ b/packages/cli/src/serve-lifecycle.ts @@ -18,7 +18,8 @@ import { join, relative, resolve } from "node:path"; import { daemonSocket } from "./daemon-control.ts"; import { acquireLease, atomicJson, cliLeaseHelperPath, leaseGuardPath, readJson } from "./state.ts"; import { tryAcquireProcessLifetimeLock } from "../../../main/services/process-lifetime-lock.ts"; -import { watchMcpProcessGroups } from "../../../main/services/mcp-stdio-transport.js"; +import { watchMcpProcessGroupRecords } from "../../../main/services/mcp-stdio-transport.js"; +import { listObservedProcesses } from "../../../main/shared/process-group.js"; import { decideServeStopDeadline, decideServeStopStart, type ServeOwnerObservation, type ServeProcessClass } from "./serve-ownership.ts"; const SERVE_LOCK = "serve.lock"; @@ -54,39 +55,83 @@ export interface ObservedProcess { pgid: number; uid?: number; zombie?: boolean; + startId?: string; +} + +export interface RecordedMcpGroupSurvivor { + pid: number; + startId: string; +} + +export interface RecordedMcpGroup { + pgid: number; + leaderStartId?: string; + survivors?: readonly RecordedMcpGroupSurvivor[]; } /** * Publishes the serving process's live stdio MCP process groups beside its lease - * owner. Each server leads its own group, outside the daemon's, and a SIGKILL - * skips the daemon's own cleanup, so a forced `serve stop` ends them from here. - * Stop recording before releasing the lease. + * owner, including kernel start-ID incarnation proof for any survivors captured + * when a wrapper leader exited. Each server leads its own group, outside the + * daemon's, and a SIGKILL skips the daemon's own cleanup, so a forced `serve stop` + * ends them from here. Stop recording before releasing the lease. */ export function recordServeMcpGroups(agentDir: string): () => void { const lock = join(agentDir, SERVE_LOCK); - return watchMcpProcessGroups((groups) => { + return watchMcpProcessGroupRecords((records) => { // Never recreate a lease directory that was already released. if (!existsSync(lock)) return; const owner = serveOwner(agentDir); const token = owner?.pid === process.pid && typeof owner.token === "string" ? owner.token : undefined; - try { atomicJson(join(lock, MCP_GROUPS), { pid: process.pid, ...(token ? { token } : {}), groups }); } catch { /* best effort */ } + const groups = records.map((record) => record.pgid); + try { + atomicJson(join(lock, MCP_GROUPS), { + pid: process.pid, + ...(token ? { token } : {}), + groups, + groupRecords: records, + }); + } catch { /* best effort */ } }); } +function isDescendantOfAny( + proc: ObservedProcess, + roots: ReadonlySet, + byPid: ReadonlyMap, +): boolean { + if (roots.has(proc.pid)) return true; + const visited = new Set([proc.pid]); + let parentPid = proc.ppid; + while (validPid(parentPid)) { + if (roots.has(parentPid)) return true; + if (visited.has(parentPid)) return false; + visited.add(parentPid); + const parent = byPid.get(parentPid); + if (!parent) return false; + parentPid = parent.ppid; + } + return false; +} + /** * Selects which recorded MCP process groups belong to `daemonPid` and may be * force-stopped when the daemon is SIGKILLed: * - A group whose leader PID is currently held by a process outside the - * daemon's tree was recycled and is never signalled. + * daemon's tree (or whose kernel start ID mismatches the recorded leader + * incarnation) was recycled and is never signalled. * - A group with a live or zombie member descended from `daemonPid` is owned. * - A leaderless group (`pid === group` already exited and was reaped, e.g. an - * `npx`/`uvx` wrapper whose grandchild server outlived it) with live members - * owned by the daemon's UID is owned: POSIX prevents PID `group` reuse while - * any member stays in that group, and `AidenStdioTransport` drops empty groups. + * `npx`/`uvx` wrapper whose grandchild server outlived it) is owned ONLY when + * it carries recorded process-incarnation proof (`survivors` with `{ pid, startId }`) + * that matches a current same-UID member of the group (and a live non-zombie + * member is or descends from that verified survivor). Same-UID membership alone + * is never sufficient, so a stale PGID reused by an unrelated same-UID wrapper + * that exits fails closed. */ export function selectDaemonMcpGroups( daemonPid: number, - recordedGroups: readonly number[], + recordedGroups: readonly (number | RecordedMcpGroup)[], processes: readonly ObservedProcess[], options: { daemonPgid?: number; daemonUid?: number } = {}, ): number[] { @@ -104,26 +149,24 @@ export function selectDaemonMcpGroups( const daemonProc = byPid.get(daemonPid); const daemonPgid = options.daemonPgid ?? daemonProc?.pgid; const daemonUid = daemonProc?.uid ?? options.daemonUid; + const daemonRoots = new Set([daemonPid]); const isDescendantOfDaemon = (proc: ObservedProcess): boolean => { - const visited = new Set([proc.pid]); - let parentPid = proc.ppid; - while (validPid(parentPid)) { - if (parentPid === daemonPid) return true; - if (visited.has(parentPid)) return false; - visited.add(parentPid); - const parent = byPid.get(parentPid); - if (!parent) return false; - parentPid = parent.ppid; - } - return false; + if (proc.pid === daemonPid) return false; + return isDescendantOfAny(proc, daemonRoots, byPid); }; const owned = new Set(); - for (const group of recordedGroups) { + for (const entry of recordedGroups) { + const group = typeof entry === "number" ? entry : entry.pgid; + const leaderStartId = typeof entry === "number" ? undefined : entry.leaderStartId; + const recordedSurvivors = typeof entry === "number" ? [] : (entry.survivors ?? []); if (!validPid(group) || group === daemonPid || group === daemonPgid) continue; const members = byPgid.get(group); if (!members || members.length === 0) continue; const leader = byPid.get(group); - if (leader && !isDescendantOfDaemon(leader)) continue; + if (leader) { + if (!isDescendantOfDaemon(leader)) continue; + if (leaderStartId && leader.startId && leader.startId !== leaderStartId) continue; + } if (members.some((member) => isDescendantOfDaemon(member))) { owned.add(group); continue; @@ -131,49 +174,91 @@ export function selectDaemonMcpGroups( const liveMembers = members.filter((member) => !member.zombie); if (liveMembers.length === 0) continue; if (daemonUid !== undefined && liveMembers.some((member) => member.uid !== daemonUid)) continue; - owned.add(group); + // Fail closed for leaderless groups unless a member proves the recorded incarnation. + const validSurvivors = recordedSurvivors.filter( + (survivor) => + validPid(survivor.pid) && + survivor.pid !== group && + survivor.pid !== daemonPid && + typeof survivor.startId === "string" && + survivor.startId.length > 0, + ); + if (validSurvivors.length === 0) continue; + const verifiedSurvivorPids = new Set(); + for (const member of members) { + if (daemonUid !== undefined && member.uid !== daemonUid) continue; + if (typeof member.startId !== "string" || member.startId.length === 0) continue; + if (validSurvivors.some((survivor) => survivor.pid === member.pid && survivor.startId === member.startId)) { + verifiedSurvivorPids.add(member.pid); + } + } + if (verifiedSurvivorPids.size === 0) continue; + if (liveMembers.some((member) => isDescendantOfAny(member, verifiedSurvivorPids, byPid))) { + owned.add(group); + } } return [...owned]; } +function parseRecordedMcpGroups( + recorded: { groups?: unknown; groupRecords?: unknown }, + daemonPid: number, +): RecordedMcpGroup[] { + if (Array.isArray(recorded.groupRecords)) { + const parsed: RecordedMcpGroup[] = []; + for (const item of recorded.groupRecords) { + if (!item || typeof item !== "object") continue; + const raw = item as { pgid?: unknown; leaderStartId?: unknown; survivors?: unknown }; + if (!validPid(raw.pgid as number | undefined) || raw.pgid === daemonPid) continue; + const leaderStartId = typeof raw.leaderStartId === "string" && raw.leaderStartId.length > 0 + ? raw.leaderStartId + : undefined; + const survivors: RecordedMcpGroupSurvivor[] = []; + if (Array.isArray(raw.survivors)) { + for (const survivor of raw.survivors) { + if (!survivor || typeof survivor !== "object") continue; + const s = survivor as { pid?: unknown; startId?: unknown }; + if (validPid(s.pid as number | undefined) && typeof s.startId === "string" && s.startId.length > 0) { + survivors.push({ pid: s.pid, startId: s.startId }); + } + } + } + parsed.push({ + pgid: raw.pgid, + ...(leaderStartId ? { leaderStartId } : {}), + survivors, + }); + } + return parsed; + } + if (!Array.isArray(recorded.groups)) return []; + return recorded.groups + .filter((group): group is number => validPid(group) && group !== daemonPid) + .map((pgid) => ({ pgid, survivors: [] })); +} + /** * The recorded MCP groups of daemon `pid` that still belong to it, read before * the daemon dies and its live children are reparented. Covers both direct - * children and orphaned grandchild servers whose wrapper exited. + * children and incarnation-verified orphaned grandchild servers whose wrapper exited. */ function daemonMcpGroups(agentDir: string, pid: number, owner?: ServeOwner): number[] { - let recorded: { pid?: unknown; token?: unknown; groups?: unknown } | undefined; - try { recorded = readJson<{ pid?: unknown; token?: unknown; groups?: unknown } | undefined>(join(agentDir, SERVE_LOCK, MCP_GROUPS), undefined); } catch { return []; } - if (recorded?.pid !== pid || !Array.isArray(recorded.groups)) return []; - if (typeof recorded.token === "string" && typeof owner?.token === "string" && recorded.token !== owner.token) return []; - const wanted = recorded.groups.filter((group): group is number => validPid(group) && group !== pid); - if (!wanted.length) return []; + let recorded: { pid?: unknown; token?: unknown; groups?: unknown; groupRecords?: unknown } | undefined; try { - const out = spawnSync("ps", ["-A", "-o", "pid=,ppid=,pgid=,uid=,stat="], { encoding: "utf8" }); - if (out.status !== 0) return []; - const processes: ObservedProcess[] = []; - for (const line of out.stdout.split("\n")) { - const trimmed = line.trim(); - if (!trimmed) continue; - const parts = trimmed.split(/\s+/u); - const procPid = Number(parts[0]); - const ppid = Number(parts[1]); - const pgid = Number(parts[2]); - const uid = Number(parts[3]); - const stat = parts[4] ?? ""; - if (!validPid(procPid) || !Number.isSafeInteger(ppid) || !validPid(pgid)) continue; - processes.push({ - pid: procPid, - ppid, - pgid, - ...(Number.isSafeInteger(uid) ? { uid } : {}), - zombie: stat.startsWith("Z"), - }); - } - return selectDaemonMcpGroups(pid, wanted, processes, { - daemonUid: typeof process.getuid === "function" ? process.getuid() : undefined, - }); + recorded = readJson<{ pid?: unknown; token?: unknown; groups?: unknown; groupRecords?: unknown } | undefined>( + join(agentDir, SERVE_LOCK, MCP_GROUPS), + undefined, + ); } catch { return []; } + if (recorded?.pid !== pid || (!Array.isArray(recorded.groups) && !Array.isArray(recorded.groupRecords))) return []; + if (typeof recorded.token === "string" && typeof owner?.token === "string" && recorded.token !== owner.token) return []; + const wanted = parseRecordedMcpGroups(recorded, pid); + if (!wanted.length) return []; + const processes = listObservedProcesses({ exactStartIdForPgids: new Set(wanted.map((entry) => entry.pgid)) }); + if (!processes) return []; + return selectDaemonMcpGroups(pid, wanted, processes, { + daemonUid: typeof process.getuid === "function" ? process.getuid() : undefined, + }); } function serveOwner(agentDir: string): ServeOwner | undefined { diff --git a/packages/cli/tests/serve-lifetime.test.mjs b/packages/cli/tests/serve-lifetime.test.mjs index 975dfddf2e..94c69a5013 100644 --- a/packages/cli/tests/serve-lifetime.test.mjs +++ b/packages/cli/tests/serve-lifetime.test.mjs @@ -398,27 +398,59 @@ test("the command client settles once for every way a daemon can answer", posix, await assert.rejects(api.remoteDaemonCommand(missing.agentDir, "serve", ["status"]), (error) => error.code === "ENOENT" && /not running/u.test(error.message)); }); -test("selectDaemonMcpGroups includes orphaned wrapper survivors and refuses recycled, foreign-uid, or daemon-group entries", () => { +test("selectDaemonMcpGroups requires incarnation proof for leaderless groups and refuses stale PGID reuse", () => { const daemonPid = 500; const processes = [ - { pid: daemonPid, ppid: 400, pgid: 400, uid: 1000, zombie: false }, + { pid: daemonPid, ppid: 400, pgid: 400, uid: 1000, zombie: false, startId: "proc:50" }, // Direct child wrapper still alive. - { pid: 601, ppid: daemonPid, pgid: 601, uid: 1000, zombie: false }, - // Orphaned grandchild whose wrapper (602) exited and was reaped; reparented to init (1). - { pid: 612, ppid: 1, pgid: 602, uid: 1000, zombie: false }, + { pid: 601, ppid: daemonPid, pgid: 601, uid: 1000, zombie: false, startId: "proc:100" }, + // Orphaned grandchild whose wrapper (602) exited and was reaped; matches recorded survivor incarnation. + { pid: 612, ppid: 1, pgid: 602, uid: 1000, zombie: false, startId: "proc:110" }, + // Orphaned survivor (622) turned zombie while its child (623) still runs in group 620. + { pid: 622, ppid: 1, pgid: 620, uid: 1000, zombie: true, startId: "proc:115" }, + { pid: 623, ppid: 622, pgid: 620, uid: 1000, zombie: false, startId: "proc:116" }, // Recycled leader PID (603) now owned by an unrelated parent (777) with a child in group 603. - { pid: 603, ppid: 777, pgid: 603, uid: 1000, zombie: false }, - { pid: 613, ppid: 603, pgid: 603, uid: 1000, zombie: false }, - // Leaderless group with only a zombie left. - { pid: 614, ppid: 1, pgid: 604, uid: 1000, zombie: true }, + { pid: 603, ppid: 777, pgid: 603, uid: 1000, zombie: false, startId: "proc:120" }, + { pid: 613, ppid: 603, pgid: 603, uid: 1000, zombie: false, startId: "proc:121" }, + // Leaderless group with only a zombie left (even with matching startId). + { pid: 614, ppid: 1, pgid: 604, uid: 1000, zombie: true, startId: "proc:130" }, // Leaderless group whose live member belongs to another user. - { pid: 615, ppid: 1, pgid: 605, uid: 2000, zombie: false }, + { pid: 615, ppid: 1, pgid: 605, uid: 2000, zombie: false, startId: "proc:140" }, + // Stale bare PGID (606) with no survivor incarnation proof, reused by an unrelated same-UID wrapper that exited. + { pid: 616, ppid: 1, pgid: 606, uid: 1000, zombie: false, startId: "proc:200" }, + // Stale PGID (607) whose original survivor (617) exited; unrelated same-UID wrapper reused PGID 607 and left 717. + { pid: 717, ppid: 1, pgid: 607, uid: 1000, zombie: false, startId: "proc:210" }, + // Stale PGID (608) where both PGID 608 and survivor PID 618 were reused with a newer startId. + { pid: 618, ppid: 1, pgid: 608, uid: 1000, zombie: false, startId: "proc:220" }, + // Leaderless group (609) whose live member has no observable startId (must fail closed). + { pid: 619, ppid: 1, pgid: 609, uid: 1000, zombie: false }, + // Direct child whose leaderStartId mismatches the recorded leader incarnation. + { pid: 610, ppid: daemonPid, pgid: 610, uid: 1000, zombie: false, startId: "proc:230" }, // Unrelated process sharing the foreground daemon's shell process group (400). - { pid: 401, ppid: 400, pgid: 400, uid: 1000, zombie: false }, + { pid: 401, ppid: 400, pgid: 400, uid: 1000, zombie: false, startId: "proc:40" }, ]; assert.deepEqual( - api.selectDaemonMcpGroups(daemonPid, [601, 602, 603, 604, 605, 400, daemonPid, 699], processes), - [601, 602], + api.selectDaemonMcpGroups( + daemonPid, + [ + { pgid: 601, leaderStartId: "proc:100", survivors: [] }, + { pgid: 602, leaderStartId: "proc:105", survivors: [{ pid: 612, startId: "proc:110" }] }, + { pgid: 620, leaderStartId: "proc:114", survivors: [{ pid: 622, startId: "proc:115" }] }, + { pgid: 603, leaderStartId: "proc:90", survivors: [{ pid: 613, startId: "proc:91" }] }, + { pgid: 604, leaderStartId: "proc:129", survivors: [{ pid: 614, startId: "proc:130" }] }, + { pgid: 605, leaderStartId: "proc:139", survivors: [{ pid: 615, startId: "proc:140" }] }, + 606, + { pgid: 607, leaderStartId: "proc:95", survivors: [{ pid: 617, startId: "proc:100" }] }, + { pgid: 608, leaderStartId: "proc:96", survivors: [{ pid: 618, startId: "proc:100" }] }, + { pgid: 609, leaderStartId: "proc:97", survivors: [{ pid: 619, startId: "proc:100" }] }, + { pgid: 610, leaderStartId: "proc:98", survivors: [] }, + 400, + daemonPid, + 699, + ], + processes, + ), + [601, 602, 620], ); }); @@ -490,3 +522,96 @@ setInterval(() => {}, 1e9);`); assert.equal(isRunning(started.grandchild), false, "orphaned MCP grandchild survivor must be stopped"); assert.equal(existsSync(box.lock), false); }); + +test("serve stop fails closed and spares unrelated same-UID leaderless groups matching a stale mcp-groups record", posix, async (t) => { + const box = sandbox(t); + const unrelatedWrapper = join(box.agentDir, "unrelated-wrapper.mjs"); + const stuckDaemon = join(box.agentDir, "stuck-serve-stale-pgid.mjs"); + mkdirSync(box.lock, { mode: 0o700, recursive: true }); + writeFileSync(unrelatedWrapper, `import { spawn } from "node:child_process"; import { renameSync, writeFileSync } from "node:fs"; +const outFile = process.argv[2]; +const child = spawn(process.execPath, ["-e", "process.on('SIGTERM', () => {}); setInterval(() => {}, 1e9);"], { stdio: "ignore" }); +writeFileSync(outFile + ".tmp", JSON.stringify({ wrapper: process.pid, child: child.pid })); +renameSync(outFile + ".tmp", outFile); +process.exit(0);`); + writeFileSync(stuckDaemon, `process.on("SIGTERM", () => {}); setInterval(() => {}, 1e9);`); + + const spawnUnrelatedLeaderlessGroup = async (label) => { + const outFile = join(box.agentDir, `${label}.json`); + const wrapper = spawn(process.execPath, [unrelatedWrapper, outFile], { stdio: "ignore", detached: true }); + const exited = new Promise((resolveExit) => wrapper.once("exit", resolveExit)); + const deadline = Date.now() + 10_000; + while (!existsSync(outFile) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 25)); + assert.equal(existsSync(outFile), true, `unrelated wrapper ${label} did not report child`); + await exited; + return JSON.parse(readFileSync(outFile, "utf8")); + }; + + const isRunning = (pid) => { + if (!api.pidAlive(pid)) return false; + const state = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" }); + return state.status === 0 && state.stdout.trim() !== "" && !state.stdout.trim().startsWith("Z"); + }; + + const groupA = await spawnUnrelatedLeaderlessGroup("stale-incarnation"); + const groupB = await spawnUnrelatedLeaderlessGroup("stale-unproven"); + const daemon = spawn(process.execPath, [stuckDaemon, "serve"], { stdio: "ignore", detached: true }); + t.after(() => { + for (const pid of [daemon.pid, groupA.wrapper, groupA.child, groupB.wrapper, groupB.child]) { + if (pid) { + try { process.kill(-pid, "SIGKILL"); } catch { /* already gone */ } + try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ } + } + } + }); + + const waitReaped = Date.now() + 5_000; + while ((api.pidAlive(groupA.wrapper) || api.pidAlive(groupB.wrapper)) && Date.now() < waitReaped) { + await new Promise((r) => setTimeout(r, 25)); + } + assert.equal(api.pidAlive(groupA.wrapper), false, "unrelated wrapper A should have exited and been reaped"); + assert.equal(api.pidAlive(groupB.wrapper), false, "unrelated wrapper B should have exited and been reaped"); + assert.equal(isRunning(groupA.child), true, "unrelated leaderless child A should be running"); + assert.equal(isRunning(groupB.child), true, "unrelated leaderless child B should be running"); + + const token = "stale-pgid-reuse-test"; + api.atomicJson(join(box.lock, "owner.json"), { + detached: true, + pid: daemon.pid, + argv: [process.execPath, stuckDaemon, "serve"], + startedAt: Date.now(), + token, + }); + // Simulate a stale mcp-groups.json left behind after earlier groups emptied and + // their PGIDs were reused by unrelated same-UID wrappers that exited: + // - groupA has a mismatched survivor startId (even with the same child PID), + // - groupB has no survivor incarnation proof at all. + api.atomicJson(join(box.lock, "mcp-groups.json"), { + pid: daemon.pid, + token, + groups: [groupA.wrapper, groupB.wrapper], + groupRecords: [ + { + pgid: groupA.wrapper, + leaderStartId: "proc:1", + survivors: [{ pid: groupA.child, startId: "proc:1" }], + }, + { + pgid: groupB.wrapper, + leaderStartId: "proc:2", + survivors: [], + }, + ], + }); + writeFileSync(box.socket, ""); + + assert.deepEqual(await api.stopDaemon(box.agentDir, 1_000), { stopped: true, pid: daemon.pid, forced: true }); + const stopDeadline = Date.now() + 5_000; + while (isRunning(daemon.pid) && Date.now() < stopDeadline) { + await new Promise((r) => setTimeout(r, 25)); + } + assert.equal(isRunning(daemon.pid), false, "daemon must be stopped"); + assert.equal(isRunning(groupA.child), true, "unrelated same-UID leaderless group with stale startId must be spared"); + assert.equal(isRunning(groupB.child), true, "unrelated same-UID leaderless group without survivor proof must be spared"); + assert.equal(existsSync(box.lock), false); +}); From db7581c12654d7e2b6175f57bbadaa7c5250214a Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 06:47:10 +0000 Subject: [PATCH 3/6] cli: narrow unknown PID values through validPid type guard --- packages/cli/src/serve-lifecycle.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/serve-lifecycle.ts b/packages/cli/src/serve-lifecycle.ts index 648713a4a4..a87ccf1e73 100644 --- a/packages/cli/src/serve-lifecycle.ts +++ b/packages/cli/src/serve-lifecycle.ts @@ -209,7 +209,7 @@ function parseRecordedMcpGroups( for (const item of recorded.groupRecords) { if (!item || typeof item !== "object") continue; const raw = item as { pgid?: unknown; leaderStartId?: unknown; survivors?: unknown }; - if (!validPid(raw.pgid as number | undefined) || raw.pgid === daemonPid) continue; + if (!validPid(raw.pgid) || raw.pgid === daemonPid) continue; const leaderStartId = typeof raw.leaderStartId === "string" && raw.leaderStartId.length > 0 ? raw.leaderStartId : undefined; @@ -218,7 +218,7 @@ function parseRecordedMcpGroups( for (const survivor of raw.survivors) { if (!survivor || typeof survivor !== "object") continue; const s = survivor as { pid?: unknown; startId?: unknown }; - if (validPid(s.pid as number | undefined) && typeof s.startId === "string" && s.startId.length > 0) { + if (validPid(s.pid) && typeof s.startId === "string" && s.startId.length > 0) { survivors.push({ pid: s.pid, startId: s.startId }); } } @@ -270,8 +270,8 @@ function serveOwner(agentDir: string): ServeOwner | undefined { } } -function validPid(pid: number | undefined): pid is number { - return Number.isSafeInteger(pid) && (pid as number) > 0; +function validPid(pid: unknown): pid is number { + return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0; } /** True when the PID refers to a live process (EPERM still means alive). */ From 6e6da4efc31b8a60152ad5d75c91326e424df67e Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 07:04:17 +0000 Subject: [PATCH 4/6] test(cli): wait for stuck daemon SIGTERM readiness and survivor record before stopDaemon --- packages/cli/tests/serve-lifetime.test.mjs | 29 +++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/packages/cli/tests/serve-lifetime.test.mjs b/packages/cli/tests/serve-lifetime.test.mjs index 94c69a5013..6535ce79ca 100644 --- a/packages/cli/tests/serve-lifetime.test.mjs +++ b/packages/cli/tests/serve-lifetime.test.mjs @@ -505,6 +505,21 @@ setInterval(() => {}, 1e9);`); while (api.pidAlive(started.wrapper) && Date.now() < waitExit) await new Promise((r) => setTimeout(r, 25)); assert.equal(api.pidAlive(started.wrapper), false, "wrapper leader should have exited and been reaped"); assert.equal(isRunning(started.grandchild), true, "grandchild survivor should still be running"); + const mcpGroupsFile = join(box.lock, "mcp-groups.json"); + const hasRecordedSurvivor = () => { + if (!existsSync(mcpGroupsFile)) return false; + try { + const recorded = JSON.parse(readFileSync(mcpGroupsFile, "utf8")); + return Array.isArray(recorded.groupRecords) && recorded.groupRecords.some( + (record) => record?.pgid === started.group + && Array.isArray(record.survivors) + && record.survivors.some((survivor) => survivor?.pid === started.grandchild), + ); + } catch { return false; } + }; + const waitRecorded = Date.now() + 5_000; + while (!hasRecordedSurvivor() && Date.now() < waitRecorded) await new Promise((r) => setTimeout(r, 25)); + assert.equal(hasRecordedSurvivor(), true, "daemon should record orphaned MCP grandchild survivor before force-stop"); api.atomicJson(join(box.lock, "owner.json"), { detached: true, pid: daemon.pid, @@ -527,6 +542,7 @@ test("serve stop fails closed and spares unrelated same-UID leaderless groups ma const box = sandbox(t); const unrelatedWrapper = join(box.agentDir, "unrelated-wrapper.mjs"); const stuckDaemon = join(box.agentDir, "stuck-serve-stale-pgid.mjs"); + const daemonReadyFile = join(box.agentDir, "stuck-daemon.ready"); mkdirSync(box.lock, { mode: 0o700, recursive: true }); writeFileSync(unrelatedWrapper, `import { spawn } from "node:child_process"; import { renameSync, writeFileSync } from "node:fs"; const outFile = process.argv[2]; @@ -534,7 +550,11 @@ const child = spawn(process.execPath, ["-e", "process.on('SIGTERM', () => {}); s writeFileSync(outFile + ".tmp", JSON.stringify({ wrapper: process.pid, child: child.pid })); renameSync(outFile + ".tmp", outFile); process.exit(0);`); - writeFileSync(stuckDaemon, `process.on("SIGTERM", () => {}); setInterval(() => {}, 1e9);`); + writeFileSync(stuckDaemon, `import { renameSync, writeFileSync } from "node:fs"; +process.on("SIGTERM", () => {}); +writeFileSync(${JSON.stringify(daemonReadyFile + ".tmp")}, "ready"); +renameSync(${JSON.stringify(daemonReadyFile + ".tmp")}, ${JSON.stringify(daemonReadyFile)}); +setInterval(() => {}, 1e9);`); const spawnUnrelatedLeaderlessGroup = async (label) => { const outFile = join(box.agentDir, `${label}.json`); @@ -565,6 +585,13 @@ process.exit(0);`); } }); + const daemonReadyDeadline = Date.now() + 10_000; + while (!existsSync(daemonReadyFile) && Date.now() < daemonReadyDeadline) { + await new Promise((r) => setTimeout(r, 25)); + } + assert.equal(existsSync(daemonReadyFile), true, "stuck daemon failed to install SIGTERM handler in time"); + assert.equal(isRunning(daemon.pid), true, "stuck daemon should be running"); + const waitReaped = Date.now() + 5_000; while ((api.pidAlive(groupA.wrapper) || api.pidAlive(groupB.wrapper)) && Date.now() < waitReaped) { await new Promise((r) => setTimeout(r, 25)); From 36e344c8f2d73d26e44c2fd4c1f9a329320077b0 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 07:51:11 +0000 Subject: [PATCH 5/6] mcp,cli: require pre-exit or transport-pipe ownership proof for post-exit survivor capture --- docs/state-machines/serve-daemon.md | 2 +- main/services/mcp-stdio-transport.test.ts | 33 ++ main/services/mcp-stdio-transport.ts | 109 +++- main/shared/process-group.test.ts | 364 ++++++++++++ main/shared/process-group.ts | 661 +++++++++++++++++++++- 5 files changed, 1139 insertions(+), 30 deletions(-) diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index 765f700b3b..ef906cf567 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -126,7 +126,7 @@ Evidence of exit is `pidAlive`, never the signal. **Defect fixed:** the periodic `foreign` check ran only every tenth poll, so a PID that stopped being ours just before the deadline fell through to `did not stop ... try kill -9 `, sending the person to kill an unrelated process. Reproduced in `tests/serve-lifetime.test.mjs` with a process that `exec`s into something else. -**Defect fixed (2026-11-24, Phase 4D):** `aiden serve stop` could not force-stop an orphaned MCP grandchild survivor whose wrapper (`npx`, `uvx`, or launcher script) had already exited and been reaped, because `daemonMcpGroups()` in `packages/cli/src/serve-lifecycle.ts` required a direct child (`ppid === pid`). `AidenStdioTransport` (`main/services/mcp-stdio-transport.ts`) now captures the leader's kernel start identifier (`proc:` on Linux, UTC `lstart:` on macOS) and, when the leader exits, snapshots surviving same-UID group members `{ pid, startId }`, and `recordServeMcpGroups()` publishes those incarnation records (`groupRecords`) bound to the daemon's lease token when present. `selectDaemonMcpGroups()` selects (1) any recorded group with a member descended from `daemonPid` (provided any live leader matches its recorded `leaderStartId`), and (2) any leaderless recorded group (`pid === group` absent) ONLY when a live non-zombie same-UID member matches—or descends from a group member matching—a recorded survivor `{ pid, startId }`. Same-UID membership alone is never accepted, so a stale PGID reused by an unrelated same-UID wrapper that exits fails closed alongside recycled leaders, `daemonPid`/`daemonPgid`, zombie-only groups, and foreign-UID groups. `AidenStdioTransport`'s survivor poll (`forgetWhenGone`) uses the same incarnation proof so a reused PGID is dropped immediately rather than kept live. Verified by pure selection tests and real-process orphaned-grandchild + stale-PGID-reuse stop tests in `packages/cli/tests/serve-lifetime.test.mjs`. +**Defect fixed (2026-11-24, Phase 4D):** `aiden serve stop` could not force-stop an orphaned MCP grandchild survivor whose wrapper (`npx`, `uvx`, or launcher script) had already exited and been reaped, because `daemonMcpGroups()` in `packages/cli/src/serve-lifecycle.ts` required a direct child (`ppid === pid`). `AidenStdioTransport` (`main/services/mcp-stdio-transport.ts`) now captures the leader's kernel start identifier (`proc:` on Linux, UTC `lstart:` on macOS), observes pre-exit group members alongside the verified live leader, and when the leader exits only captures a surviving same-UID group member `{ pid, startId }` via `captureProcessGroupSurvivors()` if it (or its same-UID ancestor in `pgid`) is proven by pre-exit live-leader observation, by holding a peer endpoint of this transport's own still-open anonymous stdio pipe/socketpair (with post-check `startId` re-verification), or by live ancestry from the daemon — failing closed (`[]`) and immediately dropping the group record otherwise so a foreign same-UID leaderless group reusing the PGID after exit can never be captured. `recordServeMcpGroups()` publishes those incarnation records (`groupRecords`) bound to the daemon's lease token when present. `selectDaemonMcpGroups()` selects (1) any recorded group with a member descended from `daemonPid` (provided any live leader matches its recorded `leaderStartId`), and (2) any leaderless recorded group (`pid === group` absent) ONLY when a live non-zombie same-UID member matches—or descends from a group member matching—a recorded survivor `{ pid, startId }`. Same-UID membership alone is never accepted, so a stale PGID reused by an unrelated same-UID wrapper that exits fails closed alongside recycled leaders, `daemonPid`/`daemonPgid`, zombie-only groups, and foreign-UID groups. `AidenStdioTransport`'s survivor poll (`forgetWhenGone`) and `reapGroup()` use the same incarnation proof so a dead or reused PGID is dropped immediately rather than signalled or kept live. Verified by pure selection, pipe-endpoint parser, and real-process survivor-proof tests in `main/shared/process-group.test.ts`, `main/services/mcp-stdio-transport.test.ts`, and `packages/cli/tests/serve-lifetime.test.mjs`. ## C04: local daemon command framing diff --git a/main/services/mcp-stdio-transport.test.ts b/main/services/mcp-stdio-transport.test.ts index 055d43e7d0..36944e63f7 100644 --- a/main/services/mcp-stdio-transport.test.ts +++ b/main/services/mcp-stdio-transport.test.ts @@ -197,6 +197,39 @@ process.exit(0); assert.equal(alive(report.grandchild), false, "transport.close() must reap the surviving grandchild"); }); +test("watchMcpProcessGroupRecords drops a wrapper PGID immediately when the leader exits with no proven survivors", { + skip: process.platform === "win32" ? "POSIX process groups" : false, + timeout: 15_000, +}, async (t) => { + let latest: readonly McpProcessGroupRecord[] = []; + const stopWatching = watchMcpProcessGroupRecords((records) => { latest = records; }); + t.after(stopWatching); + const transport = createMcpStdioTransport({ + command: process.execPath, + args: ["-e", "setTimeout(() => process.exit(0), 50);"], + closeGraceMs: 300, + stderr: "pipe", + }); + t.after(() => transport.close().catch(() => undefined)); + await transport.start(); + const groupPid = (transport as { pid?: number }).pid; + assert.ok(groupPid && groupPid > 0, "expected spawned transport PID"); + assert.equal( + latest.some((entry) => entry.pgid === groupPid), + true, + `live wrapper group ${groupPid} should be tracked before exit`, + ); + for (let attempt = 0; attempt < 200; attempt += 1) { + if (!latest.some((entry) => entry.pgid === groupPid)) break; + await delay(20); + } + assert.equal( + latest.some((entry) => entry.pgid === groupPid), + false, + `dead wrapper group ${groupPid} with no survivors must be removed immediately`, + ); +}); + test("a group that survives close leaves the list once it is gone, so its ID is never signalled again", { skip: process.platform === "win32" ? "POSIX process groups" : false, timeout: 15_000, diff --git a/main/services/mcp-stdio-transport.ts b/main/services/mcp-stdio-transport.ts index 8b9052fdbd..22c8f89f3e 100644 --- a/main/services/mcp-stdio-transport.ts +++ b/main/services/mcp-stdio-transport.ts @@ -11,6 +11,7 @@ import { captureProcessGroupSurvivors, groupStoppedWithin, listObservedProcesses, + observePreExitProcessGroupMembers, processGroupExists, processGroupStillRuns, readProcessStartId, @@ -29,6 +30,7 @@ interface TrackedMcpGroupRecord { pgid: number; leaderStartId?: string; leaderExited: boolean; + preExitMembers: ProcessIncarnationSurvivor[]; survivors: ProcessIncarnationSurvivor[]; } @@ -172,6 +174,50 @@ function settlesWithin(operation: Promise, ms: number): Promise= 0 ? fd : undefined; +} + +function openTransportStdioFds(child: ChildProcess | undefined): number[] { + if (!child) return []; + const fds: number[] = []; + for (const stream of [child.stdin, child.stdout, child.stderr]) { + const fd = streamOpenFd(stream); + if (fd !== undefined && !fds.includes(fd)) fds.push(fd); + } + return fds; +} + +function isTransportStdioFdOpen(child: ChildProcess | undefined, fd: number): boolean { + if (!child) return false; + for (const stream of [child.stdin, child.stdout, child.stderr]) { + if (streamOpenFd(stream) === fd) return true; + } + return false; +} + +function mergePreExitMembers( + record: TrackedMcpGroupRecord, + observed: readonly ProcessIncarnationSurvivor[], +): void { + const seen = new Set(record.preExitMembers.map((entry) => `${entry.pid}:${entry.startId}`)); + for (const entry of observed) { + const key = `${entry.pid}:${entry.startId}`; + if (seen.has(key)) continue; + seen.add(key); + record.preExitMembers.push({ pid: entry.pid, startId: entry.startId }); + } +} + /** * Pi's stdio transport with Aiden's lifecycle guarantees: close never waits * forever, an oversized message ends the connection, and on POSIX the @@ -180,6 +226,7 @@ const OVERSIZED_MESSAGE = /^MCP stdio message exceeds \d+ bytes$/u; class AidenStdioTransport extends StdioTransport { private groupPid?: number; private groupRecord?: TrackedMcpGroupRecord; + private trackedChild?: ChildProcess; private readonly customGroupProbe: boolean; private readonly groupStillRuns: (pid: number) => Promise; /** The process group's teardown, which runs exactly once. */ @@ -205,36 +252,62 @@ class AidenStdioTransport extends StdioTransport { }); } + private observePreExitMembers(): void { + const pid = this.groupPid; + const record = this.groupRecord; + const child = this.trackedChild; + if (pid === undefined || record === undefined || record.leaderExited || !record.leaderStartId) return; + if (liveGroups.get(pid) !== record) return; + if (child && (child.exitCode !== null || child.signalCode !== null)) return; + const observed = observePreExitProcessGroupMembers(pid, record.leaderStartId); + if (observed.length > 0) mergePreExitMembers(record, observed); + } + override async start(): Promise { await super.start(); const pid = this.pid; if (pid === undefined || !this.processGroups) return; this.groupPid = pid; installExitHook(); + const child = (this as unknown as { child?: ChildProcess }).child; + this.trackedChild = child; const leaderStartId = readProcessStartId(pid); const record: TrackedMcpGroupRecord = { pgid: pid, ...(leaderStartId ? { leaderStartId } : {}), leaderExited: false, + preExitMembers: [], survivors: [], }; this.groupRecord = record; liveGroups.set(pid, record); - const child = (this as unknown as { child?: ChildProcess }).child; const captureLeaderExit = (): void => { if (liveGroups.get(pid) !== record || record.leaderExited) return; record.leaderExited = true; - const survivors = captureProcessGroupSurvivors(pid, record.leaderStartId); + const transportFds = openTransportStdioFds(child); + const survivors = captureProcessGroupSurvivors(pid, { + leaderStartId: record.leaderStartId, + preExitMembers: record.preExitMembers, + transportFds, + isTransportFdStillOpen: (fd) => isTransportStdioFdOpen(child, fd), + }); if (survivors.length > 0) { record.survivors = survivors; groupsChanged(); + } else if (!this.customGroupProbe) { + this.removeRecord(pid, record); } }; if (child) { - if (child.exitCode !== null || child.signalCode !== null) captureLeaderExit(); - else child.once("exit", captureLeaderExit); + if (child.exitCode !== null || child.signalCode !== null) { + captureLeaderExit(); + } else { + this.observePreExitMembers(); + child.stdout?.prependOnceListener("data", () => this.observePreExitMembers()); + child.once("exit", captureLeaderExit); + } } - groupsChanged(); + if (liveGroups.get(pid) === record) groupsChanged(); } /** @@ -243,6 +316,8 @@ class AidenStdioTransport extends StdioTransport { * so after twice the grace the pipes are destroyed and the server killed. */ override async close(): Promise { + // Capture any non-pipe descendants while our verified leader is still live. + this.observePreExitMembers(); const closing = super.close(); if (!(await settlesWithin(closing, 2 * this.graceMs))) { // Pi keeps the child private; only its pipes and process are touched. @@ -250,8 +325,12 @@ class AidenStdioTransport extends StdioTransport { child?.stdin?.destroy(); child?.stdout?.destroy(); child?.stderr?.destroy(); - if (this.groupPid !== undefined) signalGroup(this.groupPid, "SIGKILL"); - else child?.kill("SIGKILL"); + const record = this.groupRecord; + if (this.groupPid !== undefined && !(record?.leaderExited && record.survivors.length === 0 && !this.customGroupProbe)) { + signalGroup(this.groupPid, "SIGKILL"); + } else if (!record?.leaderExited) { + child?.kill("SIGKILL"); + } await settlesWithin(closing, this.graceMs); } // A wrapper that already exited while its server holds the pipes never @@ -268,10 +347,16 @@ class AidenStdioTransport extends StdioTransport { if (members.length === 0) return false; const leader = processes.find((proc) => proc.pid === pid); if (!record.leaderExited) { - if (leader && record.leaderStartId && leader.startId && leader.startId !== record.leaderStartId) { - return false; + if (leader) { + if (record.leaderStartId && leader.startId && leader.startId !== record.leaderStartId) { + return false; + } + return members.some((proc) => !proc.zombie); } - return members.some((proc) => !proc.zombie); + const byPid = new Map(); + for (const proc of processes) byPid.set(proc.pid, proc); + const selfRoots = new Set([process.pid]); + return members.some((proc) => !proc.zombie && isDescendantOfAny(proc, selfRoots, byPid)); } // Leader already exited and was reaped: a live leader PID now means PGID reuse. if (leader || record.survivors.length === 0) return false; @@ -307,6 +392,10 @@ class AidenStdioTransport extends StdioTransport { const record = this.groupRecord; if (pid === undefined || record === undefined) return Promise.resolve(); this.reaping ??= (async () => { + if (!this.customGroupProbe && !(await this.incarnationStillRuns(pid, record))) { + this.removeRecord(pid, record); + return; + } signalGroup(pid, "SIGTERM"); const probe = { exists: () => processGroupExists(pid), diff --git a/main/shared/process-group.test.ts b/main/shared/process-group.test.ts index a98eebc6c8..e1fe9c86eb 100644 --- a/main/shared/process-group.test.ts +++ b/main/shared/process-group.test.ts @@ -7,8 +7,15 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { + captureProcessGroupSurvivors, createProcessGroupTerminator, decodeCappedUtf8, + observePreExitProcessGroupMembers, + parseDarwinLsofSharedPipePids, + parseLinuxLsofUnixPeerInodes, + parseSsUnixPeerInodes, + readProcessStartId, + selectVerifiedProcessGroupSurvivors, waitForChildExit, } from "./process-group.js"; import { processGroupRunning, processRunning } from "./process-liveness-test-support.js"; @@ -156,3 +163,360 @@ test("capped output drops a cut trailing character instead of showing U+FFFD", ( assert.equal(decodeCappedUtf8(full, true), "héllo €"); assert.equal(decodeCappedUtf8(full, false), "héllo €"); }); + +test("selectVerifiedProcessGroupSurvivors fails closed for unproven leaderless groups even when startId >= leaderStartId", () => { + const processes = [ + { pid: 900, ppid: 1, pgid: 800, uid: 1000, zombie: false, startId: "proc:200" }, + { pid: 901, ppid: 900, pgid: 800, uid: 1000, zombie: false, startId: "proc:201" }, + ]; + assert.deepEqual( + selectVerifiedProcessGroupSurvivors({ + pgid: 800, + processes, + leaderStartId: "proc:100", + parentPid: 500, + currentUid: 1000, + }), + [], + "a foreign same-UID leaderless group with newer startId must fail closed without incarnation proof", + ); + // Stale pre-exit proof with matching PID but different startId must also fail closed. + assert.deepEqual( + selectVerifiedProcessGroupSurvivors({ + pgid: 800, + processes, + leaderStartId: "proc:100", + parentPid: 500, + currentUid: 1000, + preExitMembers: [{ pid: 900, startId: "proc:105" }], + }), + [], + ); +}); + +test("selectVerifiedProcessGroupSurvivors accepts pre-exit, pipe-verified, and unreaped-tree members and rejects reused leaders", () => { + const leaderlessProcesses = [ + // Proven via pre-exit observation (now zombie) with a live in-group child. + { pid: 910, ppid: 1, pgid: 810, uid: 1000, zombie: true, startId: "proc:110" }, + { pid: 911, ppid: 910, pgid: 810, uid: 1000, zombie: false, startId: "proc:111" }, + // Proven via inherited transport pipe, with a live in-group child and a foreign-UID child. + { pid: 920, ppid: 1, pgid: 810, uid: 1000, zombie: false, startId: "proc:120" }, + { pid: 921, ppid: 920, pgid: 810, uid: 1000, zombie: false, startId: "proc:121" }, + { pid: 922, ppid: 920, pgid: 810, uid: 2000, zombie: false, startId: "proc:122" }, + // Unrelated same-UID member in the same PGID with no proof. + { pid: 930, ppid: 1, pgid: 810, uid: 1000, zombie: false, startId: "proc:130" }, + ]; + assert.deepEqual( + selectVerifiedProcessGroupSurvivors({ + pgid: 810, + processes: leaderlessProcesses, + leaderStartId: "proc:100", + parentPid: 500, + currentUid: 1000, + preExitMembers: [{ pid: 910, startId: "proc:110" }], + pipeVerifiedPids: new Set([920]), + }), + [ + { pid: 911, startId: "proc:111" }, + { pid: 920, startId: "proc:120" }, + { pid: 921, startId: "proc:121" }, + ], + ); + + // If a foreign leader already reused PID === pgid, nothing may be captured even with proof inputs. + assert.deepEqual( + selectVerifiedProcessGroupSurvivors({ + pgid: 810, + processes: [ + { pid: 810, ppid: 777, pgid: 810, uid: 1000, zombie: false, startId: "proc:150" }, + ...leaderlessProcesses, + ], + leaderStartId: "proc:100", + parentPid: 500, + currentUid: 1000, + preExitMembers: [{ pid: 910, startId: "proc:110" }], + pipeVerifiedPids: new Set([920]), + }), + [], + ); + + // If our own leader is still unreaped (matching ppid + leaderStartId), live descendants of parentPid are verified. + assert.deepEqual( + selectVerifiedProcessGroupSurvivors({ + pgid: 820, + processes: [ + { pid: 500, ppid: 400, pgid: 500, uid: 1000, zombie: false, startId: "proc:50" }, + { pid: 820, ppid: 500, pgid: 820, uid: 1000, zombie: true, startId: "proc:100" }, + { pid: 821, ppid: 820, pgid: 820, uid: 1000, zombie: false, startId: "proc:101" }, + ], + leaderStartId: "proc:100", + parentPid: 500, + currentUid: 1000, + }), + [{ pid: 821, startId: "proc:101" }], + ); +}); + +test("Linux ss and lsof socketpair parsers match only anonymous connected peer inodes", () => { + const ssStdout = [ + "u_str ESTAB 0 0 * 75167340 * 75167341", + "u_str ESTAB 0 0 * 75167342 * 75167343", + "u_str ESTAB 0 0 /run/dbus/system_bus_socket 75167344 * 75167345", + "u_str ESTAB 0 0 * 75167346 /var/run/named.sock 75167347", + "u_str LISTEN 0 0 * 75167348 * 75167349", + "u_str ESTAB 0 0 * 75167350 * 0", + ].join("\n"); + const ssPeers = parseSsUnixPeerInodes( + ssStdout, + new Set(["75167340", "75167344", "75167346", "75167348", "75167350"]), + ); + assert.deepEqual([...ssPeers.entries()], [["75167340", "75167341"]]); + + const lsofStdout = [ + "p1000", + "f25", + "tunix", + "i75167340", + "ntype=STREAM ->INO=75167341 2000,node,1u", + "f27", + "tunix", + "i75167344", + "n/run/dbus/system_bus_socket type=STREAM ->INO=75167345", + "f29", + "tunix", + "i75167350", + "ntype=STREAM ->INO=75167351 2000,node,2u", + "p9999", + "f25", + "tunix", + "i75167360", + "ntype=STREAM ->INO=75167361", + ].join("\n"); + const lsofPeers = parseLinuxLsofUnixPeerInodes( + lsofStdout, + 1000, + new Set([25, 27]), + new Set(["75167340", "75167344", "75167350", "75167360"]), + ); + assert.deepEqual([...lsofPeers.entries()], [["75167340", "75167341"]]); +}); + +test("Darwin lsof parser verifies anonymous PIPE and unix socketpairs and rejects named or zero-address entries", () => { + const darwinLsof = [ + "p1000", + // Anonymous PIPE held on transport FD 25 + "f25", + "tPIPE", + "d0x1111aaaa", + "n->0x2222bbbb", + // Anonymous unix socketpair held on transport FD 27 + "f27", + "tunix", + "d0x3333cccc", + "n->0x4444dddd", + // Named unix socket on FD 29 (must never verify) + "f29", + "tunix", + "d0x5555eeee", + "n/var/run/syslog ->0x6666ffff", + // All-zero device address on FD 31 (must never verify) + "f31", + "tunix", + "d0x0000000000000000", + "n->0x7777aaaa", + // Non-transport FD 40 (must not verify) + "f40", + "tPIPE", + "d0x8888bbbb", + "n->0x9999cccc", + // Candidate 2001: matching PIPE peer of FD 25 + "p2001", + "f1", + "tPIPE", + "d0x2222bbbb", + "n->0x1111aaaa", + // Candidate 2002: matching unix socketpair peer of FD 27 + "p2002", + "f2", + "tunix", + "d0x4444dddd", + "n->0x3333cccc", + // Candidate 2003: matches named socket FD 29 only (rejected) + "p2003", + "f3", + "tunix", + "d0x6666ffff", + "n/var/run/syslog ->0x5555eeee", + // Candidate 2004: matches non-transport FD 40 only (rejected) + "p2004", + "f1", + "tPIPE", + "d0x9999cccc", + "n->0x8888bbbb", + // Candidate 2005: wrong type (`unix` vs parent `PIPE`) (rejected) + "p2005", + "f1", + "tunix", + "d0x2222bbbb", + "n->0x1111aaaa", + // Candidate 2006: unrelated pipe (rejected) + "p2006", + "f1", + "tPIPE", + "d0xdeadbeef", + "n->0xfeedface", + ].join("\n"); + const matched = parseDarwinLsofSharedPipePids( + darwinLsof, + 1000, + new Set([25, 27, 29, 31]), + new Set([2001, 2002, 2003, 2004, 2005, 2006]), + ); + assert.deepEqual([...matched].sort((a, b) => a - b), [2001, 2002]); +}); + +test("captureProcessGroupSurvivors fails closed without proof and verifies pipe-inheriting survivors while rejecting unrelated leaderless groups", { skip: !posix }, async (t) => { + const dir = await mkdtemp(path.join(os.tmpdir(), "aiden-survivor-proof-")); + t.after(() => rm(dir, { recursive: true, force: true })); + + // 1. Spawn a wrapper whose grandchild inherits our stdout/stderr pipes, then wrapper exits. + const ownedWrapper = spawn( + process.execPath, + [ + "-e", + `const { spawn } = require("node:child_process"); +const g = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { stdio: ["ignore", "inherit", "inherit"] }); +process.stdout.write(String(g.pid) + "\\n"); +process.exit(0);`, + ], + { detached: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + const ownedGroup = ownedWrapper.pid!; + const ownedLeaderStartId = readProcessStartId(ownedGroup); + const ownedExited = once(ownedWrapper, "exit"); + const ownedGrandchild = Number(await firstLine(ownedWrapper)); + t.after(() => { + for (const pid of [ownedGroup, ownedGrandchild]) { + try { process.kill(-pid, "SIGKILL"); } catch { /* gone */ } + try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } + } + ownedWrapper.stdin?.destroy(); + ownedWrapper.stdout?.destroy(); + ownedWrapper.stderr?.destroy(); + }); + await ownedExited; + assert.equal(await eventually(() => !processRunning(ownedGroup)), true, "owned wrapper should be reaped"); + assert.equal(processRunning(ownedGrandchild), true, "owned grandchild should still run"); + + // 2. Spawn an unrelated same-UID leaderless group with stdio ignored (no shared transport pipe). + const foreignFile = path.join(dir, "foreign.pid"); + const foreignWrapper = spawn( + process.execPath, + [ + "-e", + `const { spawn } = require("node:child_process"); +const { writeFileSync } = require("node:fs"); +const g = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { stdio: "ignore" }); +writeFileSync(${JSON.stringify(foreignFile)}, String(g.pid)); +process.exit(0);`, + ], + { detached: true, stdio: "ignore" }, + ); + const foreignGroup = foreignWrapper.pid!; + const foreignExited = once(foreignWrapper, "exit"); + await foreignExited; + assert.equal(await eventually(() => existsSync(foreignFile)), true); + const foreignGrandchild = Number( + (await import("node:fs")).readFileSync(foreignFile, "utf8").trim(), + ); + t.after(() => { + for (const pid of [foreignGroup, foreignGrandchild]) { + try { process.kill(-pid, "SIGKILL"); } catch { /* gone */ } + try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } + } + }); + assert.equal(await eventually(() => !processRunning(foreignGroup)), true, "foreign wrapper should be reaped"); + assert.equal(processRunning(foreignGrandchild), true, "foreign leaderless child should still run"); + + // Without pre-exit observation or transport FDs, BOTH leaderless groups MUST fail closed. + assert.deepEqual( + captureProcessGroupSurvivors(ownedGroup, { leaderStartId: ownedLeaderStartId }), + [], + "leaderless capture without pre-exit or transport-pipe proof must fail closed", + ); + assert.deepEqual( + captureProcessGroupSurvivors(foreignGroup, { leaderStartId: ownedLeaderStartId }), + [], + "foreign same-UID leaderless group with newer startId must fail closed", + ); + + // Extract our open transport FDs from `ownedWrapper`. + const ownedFds = [ownedWrapper.stdin, ownedWrapper.stdout, ownedWrapper.stderr] + .map((stream) => (stream && !stream.destroyed ? (stream as unknown as { _handle?: { fd?: number } })._handle?.fd : undefined)) + .filter((fd): fd is number => typeof fd === "number" && Number.isSafeInteger(fd) && fd >= 0); + assert.ok(ownedFds.length > 0, "expected at least one open stdio pipe FD held by owned grandchild"); + + // With our transport's open pipe FDs, the pipe-inheriting grandchild IS captured... + const capturedOwned = captureProcessGroupSurvivors(ownedGroup, { + leaderStartId: ownedLeaderStartId, + transportFds: ownedFds, + }); + assert.equal(capturedOwned.length, 1); + assert.equal(capturedOwned[0]!.pid, ownedGrandchild); + assert.ok(capturedOwned[0]!.startId.length > 0); + + // ...while the unrelated same-UID leaderless group (holding no pipe from ownedWrapper) is REJECTED! + assert.deepEqual( + captureProcessGroupSurvivors(foreignGroup, { + leaderStartId: ownedLeaderStartId, + transportFds: ownedFds, + }), + [], + "unrelated same-UID leaderless group without inherited transport pipe must be rejected", + ); +}); + +test("observePreExitProcessGroupMembers proves a stdio-ignored descendant before leader exit", { skip: !posix }, async (t) => { + const dir = await mkdtemp(path.join(os.tmpdir(), "aiden-preexit-proof-")); + t.after(() => rm(dir, { recursive: true, force: true })); + const child = spawn( + process.execPath, + [ + "-e", + `const { spawn } = require("node:child_process"); +const g = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { stdio: "ignore" }); +process.stdout.write(String(g.pid) + "\\n"); +process.stdin.resume(); +process.stdin.on("end", () => process.exit(0));`, + ], + { detached: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + const pgid = child.pid!; + const leaderStartId = readProcessStartId(pgid); + const grandchild = Number(await firstLine(child)); + t.after(() => { + for (const pid of [pgid, grandchild]) { + try { process.kill(-pid, "SIGKILL"); } catch { /* gone */ } + try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } + } + }); + const preExitMembers = observePreExitProcessGroupMembers(pgid, leaderStartId); + assert.ok( + preExitMembers.some((member) => member.pid === grandchild && member.startId.length > 0), + `expected pre-exit observation of grandchild ${grandchild}, got ${JSON.stringify(preExitMembers)}`, + ); + + // Now let the leader exit and be reaped; grandchild has stdio: "ignore" (no shared pipes). + const exited = once(child, "exit"); + child.stdin!.end(); + await exited; + assert.equal(await eventually(() => !processRunning(pgid)), true); + assert.equal(processRunning(grandchild), true); + + // Without pre-exit proof, capture fails closed. + assert.deepEqual(captureProcessGroupSurvivors(pgid, { leaderStartId }), []); + // With pre-exit proof captured alongside the verified live leader, grandchild IS captured. + const captured = captureProcessGroupSurvivors(pgid, { leaderStartId, preExitMembers }); + assert.equal(captured.length, 1); + assert.equal(captured[0]!.pid, grandchild); +}); diff --git a/main/shared/process-group.ts b/main/shared/process-group.ts index f70c738e00..13f3bc9199 100644 --- a/main/shared/process-group.ts +++ b/main/shared/process-group.ts @@ -4,7 +4,7 @@ // children. Windows has no process groups; there only the child is signalled. import { execFile, spawnSync, type ChildProcess } from "node:child_process"; -import { readFileSync } from "node:fs"; +import { readdirSync, readFileSync, readlinkSync } from "node:fs"; import { StringDecoder } from "node:string_decoder"; const POLL_MS = 25; @@ -33,21 +33,50 @@ function deterministicPsEnv(): NodeJS.ProcessEnv { return { ...process.env, LC_ALL: "C", TZ: "UTC" }; } -function readLinuxProcStartId(pid: number): string | undefined { - if (process.platform !== "linux") return undefined; +interface LinuxProcStat { + zombie: boolean; + ppid: number; + pgid: number; + startId: string; +} + +function readLinuxProcStat(pid: number): LinuxProcStat | undefined { + if (process.platform !== "linux" || !Number.isSafeInteger(pid) || pid <= 0) return undefined; try { const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); const closeParen = stat.lastIndexOf(")"); if (closeParen < 0) return undefined; - // Field 3 (state) is index 0 after `) `; field 22 (starttime in clock ticks since boot) is index 19. + // Field 3 (state) is index 0 after `) `; field 4 (ppid) is 1; field 5 (pgrp) is 2; field 22 (starttime) is 19. const fields = stat.slice(closeParen + 2).trim().split(" "); + const state = fields[0]; + const ppid = Number(fields[1]); + const pgid = Number(fields[2]); const starttime = fields[19]; - return starttime && /^\d+$/u.test(starttime) ? `proc:${starttime}` : undefined; + if ( + !state || + !Number.isSafeInteger(ppid) || + !Number.isSafeInteger(pgid) || + pgid <= 0 || + !starttime || + !/^\d+$/u.test(starttime) + ) { + return undefined; + } + return { + zombie: state === "Z", + ppid, + pgid, + startId: `proc:${starttime}`, + }; } catch { return undefined; } } +function readLinuxProcStartId(pid: number): string | undefined { + return readLinuxProcStat(pid)?.startId; +} + /** * Kernel-recorded process start identifier for `pid`: monotonic boot-tick * `starttime` on Linux (`/proc//stat`), or UTC `ps lstart` on other POSIX @@ -126,9 +155,12 @@ export function listObservedProcesses( continue; } const lstartId = lstart ? `lstart:${lstart}` : undefined; - const startId = options.exactStartIdForPgids?.has(pgid) - ? (readLinuxProcStartId(procPid) ?? lstartId) - : lstartId; + let startId = lstartId; + if (options.exactStartIdForPgids?.has(pgid) && process.platform === "linux") { + const procStat = readLinuxProcStat(procPid); + // If `/proc//stat` now belongs to a different group, the `ps` row is stale (PID reused). + startId = procStat && procStat.pgid === pgid ? procStat.startId : undefined; + } processes.push({ pid: procPid, ppid, @@ -144,31 +176,622 @@ export function listObservedProcesses( } } +export interface VerifyProcessGroupSurvivorsInput { + pgid: number; + processes: readonly ObservedProcessEntry[]; + leaderStartId?: string; + parentPid?: number; + currentUid?: number; + preExitMembers?: readonly ProcessIncarnationSurvivor[]; + pipeVerifiedPids?: ReadonlySet; +} + +export interface CaptureProcessGroupSurvivorsOptions { + leaderStartId?: string; + parentPid?: number; + preExitMembers?: readonly ProcessIncarnationSurvivor[]; + transportFds?: readonly number[]; + isTransportFdStillOpen?: (fd: number) => boolean; +} + +function isDescendantOfPid( + proc: ObservedProcessEntry, + ancestorPid: number, + byPid: ReadonlyMap, +): boolean { + if (proc.pid === ancestorPid) return false; + const visited = new Set([proc.pid]); + let parentPid = proc.ppid; + while (Number.isSafeInteger(parentPid) && parentPid > 0) { + if (parentPid === ancestorPid) return true; + if (visited.has(parentPid)) return false; + visited.add(parentPid); + const parent = byPid.get(parentPid); + if (!parent) return false; + parentPid = parent.ppid; + } + return false; +} + +function isDescendantInGroup( + member: ObservedProcessEntry, + verifiedRoots: ReadonlySet, + groupByPid: ReadonlyMap, +): boolean { + if (verifiedRoots.has(member.pid)) return true; + const visited = new Set([member.pid]); + let parentPid = member.ppid; + while (Number.isSafeInteger(parentPid) && parentPid > 0) { + if (verifiedRoots.has(parentPid)) return true; + if (visited.has(parentPid)) return false; + visited.add(parentPid); + const parent = groupByPid.get(parentPid); + if (!parent) return false; + parentPid = parent.ppid; + } + return false; +} + /** - * Snapshots surviving non-zombie members of `pgid` right after our group leader - * exited and was reaped. If `pid === pgid` already exists in the process table, - * the PID was already reused and nothing is captured. + * Parses `ss -xH` output on Linux and maps each anonymous local Unix + * socketpair inode in `localInodes` to its connected peer socket inode. + * Named sockets (non-`*` local or peer address) are ignored. */ -export function captureProcessGroupSurvivors( +export function parseSsUnixPeerInodes( + stdout: string, + localInodes: ReadonlySet, +): Map { + const peers = new Map(); + if (localInodes.size === 0) return peers; + for (const line of stdout.split("\n")) { + const cols = line.trim().split(/\s+/u); + if (cols.length < 8) continue; + if (cols[0] !== "u_str" && cols[0] !== "u_seq" && cols[0] !== "u_dgr") continue; + if (cols[1] !== "ESTAB") continue; + if (cols[4] !== "*" || cols[6] !== "*") continue; + const localInode = cols[5] ?? ""; + const peerInode = cols[7] ?? ""; + if (!localInodes.has(localInode)) continue; + if (!/^\d+$/u.test(peerInode) || peerInode === "0" || peerInode === localInode) continue; + peers.set(localInode, peerInode); + } + return peers; +} + +/** + * Fallback Linux parser for `lsof +E -nP -a -p -F pftin` when `ss` is + * unavailable. Maps each anonymous Unix socketpair inode held on one of + * `transportFds` to its connected peer inode (`->INO=`). + */ +export function parseLinuxLsofUnixPeerInodes( + stdout: string, + selfPid: number, + transportFds: ReadonlySet, + localInodes: ReadonlySet, +): Map { + const peers = new Map(); + if (transportFds.size === 0 || localInodes.size === 0) return peers; + let currentPid: number | undefined; + let currentFd: number | undefined; + let currentType: string | undefined; + let currentInode: string | undefined; + let currentName: string | undefined; + const flush = (): void => { + if ( + currentPid === selfPid && + currentFd !== undefined && + transportFds.has(currentFd) && + currentType === "unix" && + currentInode !== undefined && + localInodes.has(currentInode) && + currentName !== undefined + ) { + const match = currentName.trim().match(/^type=(?:STREAM|SEQPACKET|DGRAM)\s+->INO=(\d+)(?:\s|$)/u); + const peerInode = match?.[1]; + if (peerInode && peerInode !== "0" && peerInode !== currentInode) { + peers.set(currentInode, peerInode); + } + } + currentFd = undefined; + currentType = undefined; + currentInode = undefined; + currentName = undefined; + }; + for (const rawLine of stdout.split("\n")) { + const line = rawLine.replace(/\r$/u, ""); + if (line.length === 0) continue; + const tag = line[0]; + const value = line.slice(1); + if (tag === "p") { + flush(); + const parsed = Number(value); + currentPid = Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined; + } else if (tag === "f") { + flush(); + const match = value.match(/^(\d+)[rwu]?$/u); + currentFd = match ? Number(match[1]) : undefined; + } else if (tag === "t") { + currentType = value; + } else if (tag === "i") { + currentInode = /^\d+$/u.test(value) ? value : undefined; + } else if (tag === "n") { + currentName = value; + } + } + flush(); + return peers; +} + +function normalizeKernelHexAddr(raw: string): string | undefined { + const trimmed = raw.trim().toLowerCase(); + if (!/^0x[0-9a-f]+$/u.test(trimmed) || /^0x0+$/u.test(trimmed)) return undefined; + return trimmed; +} + +interface DarwinLsofEndpoint { + pid: number; + fd: number; + type: "PIPE" | "unix"; + localAddr: string; + peerAddr?: string; +} + +function parseDarwinLsofSharedPipeMatches( + stdout: string, + selfPid: number, + transportFds: ReadonlySet, + candidatePids: ReadonlySet, +): Map> { + const verified = new Map>(); + if (transportFds.size === 0 || candidatePids.size === 0) return verified; + const parentEndpoints: DarwinLsofEndpoint[] = []; + const candidateEndpoints: DarwinLsofEndpoint[] = []; + let currentPid: number | undefined; + let currentFd: number | undefined; + let currentType: "PIPE" | "unix" | undefined; + let devCharAddr: string | undefined; + let devNumAddr: string | undefined; + let peerAddr: string | undefined; + let hasNamedPath = false; + const flush = (): void => { + const localAddr = devCharAddr ?? devNumAddr; + if ( + currentPid !== undefined && + currentFd !== undefined && + currentType !== undefined && + localAddr !== undefined && + !hasNamedPath + ) { + const endpoint: DarwinLsofEndpoint = { + pid: currentPid, + fd: currentFd, + type: currentType, + localAddr, + ...(peerAddr ? { peerAddr } : {}), + }; + if (currentPid === selfPid && transportFds.has(currentFd)) { + parentEndpoints.push(endpoint); + } else if (candidatePids.has(currentPid)) { + candidateEndpoints.push(endpoint); + } + } + currentFd = undefined; + currentType = undefined; + devCharAddr = undefined; + devNumAddr = undefined; + peerAddr = undefined; + hasNamedPath = false; + }; + for (const rawLine of stdout.split("\n")) { + const line = rawLine.replace(/\r$/u, ""); + if (line.length === 0) continue; + const tag = line[0]; + const value = line.slice(1); + if (tag === "p") { + flush(); + const parsed = Number(value); + currentPid = Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined; + } else if (tag === "f") { + flush(); + const match = value.match(/^(\d+)[rwu]?$/u); + currentFd = match ? Number(match[1]) : undefined; + } else if (tag === "t") { + currentType = value === "PIPE" || value === "unix" ? value : undefined; + } else if (tag === "d") { + devCharAddr = normalizeKernelHexAddr(value); + } else if (tag === "D") { + devNumAddr = normalizeKernelHexAddr(value); + } else if (tag === "n") { + const trimmed = value.trim(); + if (trimmed.length === 0) continue; + const match = trimmed.match(/^->(0x[0-9a-f]+)(?:\s+\([^)]*\))?$/iu); + if (match) { + peerAddr = normalizeKernelHexAddr(match[1]!); + } else { + hasNamedPath = true; + } + } + } + flush(); + if (parentEndpoints.length === 0 || candidateEndpoints.length === 0) return verified; + for (const cand of candidateEndpoints) { + for (const parent of parentEndpoints) { + if (parent.type !== cand.type) continue; + const matched = + parent.peerAddr !== undefined && cand.peerAddr !== undefined + ? parent.peerAddr === cand.localAddr && cand.peerAddr === parent.localAddr + : (parent.peerAddr !== undefined && parent.peerAddr === cand.localAddr) || + (cand.peerAddr !== undefined && cand.peerAddr === parent.localAddr); + if (matched) { + let fds = verified.get(cand.pid); + if (!fds) { + fds = new Set(); + verified.set(cand.pid, fds); + } + fds.add(parent.fd); + } + } + } + return verified; +} + +/** + * Parses macOS/Darwin `lsof -nP -p , -F pftdDn` output and + * returns the candidate PIDs proven to hold the peer endpoint of an anonymous + * `PIPE` or `unix` socketpair held open by `selfPid` on `transportFds`. + * Named Unix sockets, all-zero addresses, and unconnected endpoints are rejected. + */ +export function parseDarwinLsofSharedPipePids( + stdout: string, + selfPid: number, + transportFds: ReadonlySet, + candidatePids: ReadonlySet, +): Set { + return new Set(parseDarwinLsofSharedPipeMatches(stdout, selfPid, transportFds, candidatePids).keys()); +} + +function findTransportPipeVerifiedPids( + candidates: readonly ObservedProcessEntry[], + pgid: number, + transportFds: readonly number[], + isTransportFdStillOpen?: (fd: number) => boolean, + selfPid: number = process.pid, +): Set { + const verified = new Set(); + const validFds = [...new Set(transportFds.filter((fd) => Number.isSafeInteger(fd) && fd >= 0))]; + if (candidates.length === 0 || validFds.length === 0) return verified; + + if (process.platform === "linux") { + const fdTargetByFd = new Map(); + const expectedTargetToSourceFd = new Map(); + const localSocketInodeToFd = new Map(); + for (const fd of validFds) { + if (isTransportFdStillOpen && !isTransportFdStillOpen(fd)) continue; + let target: string; + try { + target = readlinkSync(`/proc/self/fd/${fd}`); + } catch { + continue; + } + fdTargetByFd.set(fd, target); + if (/^pipe:\[\d+\]$/u.test(target)) { + expectedTargetToSourceFd.set(target, fd); + } else { + const sockMatch = target.match(/^socket:\[(\d+)\]$/u); + if (sockMatch?.[1]) { + localSocketInodeToFd.set(sockMatch[1], fd); + } + } + } + if (localSocketInodeToFd.size > 0) { + const localInodes = new Set(localSocketInodeToFd.keys()); + let peerMap: Map | undefined; + try { + const ssOut = spawnSync("ss", ["-xH"], { + encoding: "utf8", + timeout: 2_000, + maxBuffer: 4 * 1024 * 1024, + }); + if (!ssOut.error && ssOut.status === 0 && ssOut.stdout) { + peerMap = parseSsUnixPeerInodes(ssOut.stdout, localInodes); + } + } catch { + // Fall through to `lsof +E` fallback. + } + if (!peerMap) { + try { + const lsofOut = spawnSync("lsof", ["+E", "-nP", "-a", "-p", String(selfPid), "-F", "pftin"], { + encoding: "utf8", + timeout: 2_000, + maxBuffer: 4 * 1024 * 1024, + }); + if (!lsofOut.error && lsofOut.stdout) { + peerMap = parseLinuxLsofUnixPeerInodes( + lsofOut.stdout, + selfPid, + new Set(localSocketInodeToFd.values()), + localInodes, + ); + } + } catch { + // Fail closed when neither `ss` nor `lsof` can resolve socketpair peers. + } + } + if (peerMap) { + for (const [localInode, peerInode] of peerMap) { + const sourceFd = localSocketInodeToFd.get(localInode); + if (sourceFd !== undefined) { + expectedTargetToSourceFd.set(`socket:[${peerInode}]`, sourceFd); + } + } + } + } + if (expectedTargetToSourceFd.size === 0) return verified; + + for (const cand of candidates) { + if (!cand.startId) continue; + let entries: string[]; + try { + entries = readdirSync(`/proc/${cand.pid}/fd`); + } catch { + continue; + } + let matchedSourceFd: number | undefined; + for (const entry of entries) { + try { + const link = readlinkSync(`/proc/${cand.pid}/fd/${entry}`); + const sourceFd = expectedTargetToSourceFd.get(link); + if (sourceFd !== undefined) { + matchedSourceFd = sourceFd; + break; + } + } catch { + // FD closed mid-scan; keep checking remaining FDs. + } + } + if (matchedSourceFd === undefined) continue; + // Re-verify both ends after FD inspection to close PID-reuse / FD-reuse TOCTOU. + if (isTransportFdStillOpen && !isTransportFdStillOpen(matchedSourceFd)) continue; + try { + if (readlinkSync(`/proc/self/fd/${matchedSourceFd}`) !== fdTargetByFd.get(matchedSourceFd)) continue; + } catch { + continue; + } + const postStat = readLinuxProcStat(cand.pid); + if (postStat && postStat.pgid === pgid && postStat.startId === cand.startId) { + verified.add(cand.pid); + } + } + return verified; + } + + if (process.platform === "darwin") { + const openFds = validFds.filter((fd) => !isTransportFdStillOpen || isTransportFdStillOpen(fd)); + if (openFds.length === 0) return verified; + const candidateByPid = new Map(); + for (const cand of candidates) { + if (cand.startId) candidateByPid.set(cand.pid, cand); + } + if (candidateByPid.size === 0) return verified; + try { + const pids = [selfPid, ...candidateByPid.keys()].join(","); + const out = spawnSync("lsof", ["-nP", "-p", pids, "-F", "pftdDn"], { + encoding: "utf8", + timeout: 2_000, + maxBuffer: 4 * 1024 * 1024, + }); + if (out.error || !out.stdout) return verified; + const matched = parseDarwinLsofSharedPipeMatches( + out.stdout, + selfPid, + new Set(openFds), + new Set(candidateByPid.keys()), + ); + for (const [pid, matchedFds] of matched) { + const cand = candidateByPid.get(pid); + if (!cand?.startId) continue; + if (![...matchedFds].some((fd) => !isTransportFdStillOpen || isTransportFdStillOpen(fd))) continue; + if (readProcessStartId(cand.pid) === cand.startId) { + verified.add(cand.pid); + } + } + } catch { + // Fail closed if `lsof` is absent or errors. + } + return verified; + } + + return verified; +} + +/** + * Pure incarnation-proof selector for post-exit survivor capture. + * + * A non-zombie same-UID member of `pgid` is captured ONLY when `pgid` has not + * been reused by a foreign leader AND the member (or its same-UID ancestor in + * `pgid`) is proven to belong to this incarnation by at least one of: + * 1. Exact `{ pid, startId }` match in `preExitMembers` observed alongside our + * verified live leader; + * 2. Membership in `pipeVerifiedPids` (proven to hold our transport's own + * open anonymous stdio pipe/socketpair endpoint); + * 3. Live ancestry from `parentPid` (e.g. leader not yet reaped). + * + * Never accepts a leaderless candidate solely on `!live(pgid)` + `startId >= leaderStartId`. + */ +export function selectVerifiedProcessGroupSurvivors( + input: VerifyProcessGroupSurvivorsInput, +): ProcessIncarnationSurvivor[] { + const { pgid, processes, leaderStartId, parentPid, currentUid, preExitMembers, pipeVerifiedPids } = input; + if (!Number.isSafeInteger(pgid) || pgid <= 0) return []; + const byPid = new Map(); + const members: ObservedProcessEntry[] = []; + for (const proc of processes) { + byPid.set(proc.pid, proc); + if (proc.pgid === pgid) members.push(proc); + } + if (members.length === 0) return []; + const leader = byPid.get(pgid); + if (leader) { + const isOwnUnreapedLeader = + parentPid !== undefined && + leader.ppid === parentPid && + Boolean(leaderStartId) && + leader.startId === leaderStartId; + if (!isOwnUnreapedLeader) return []; + } + const sameUidMembers: ObservedProcessEntry[] = []; + const sameUidByPid = new Map(); + for (const proc of members) { + if (proc.pid === pgid) continue; + if (currentUid !== undefined && proc.uid !== currentUid) continue; + if (!proc.startId || !startIdNotOlderThan(proc.startId, leaderStartId)) continue; + sameUidMembers.push(proc); + sameUidByPid.set(proc.pid, proc); + } + if (sameUidMembers.length === 0) return []; + + const preExitKeys = new Set(); + if (preExitMembers) { + for (const entry of preExitMembers) { + if (Number.isSafeInteger(entry.pid) && entry.pid > 0 && entry.pid !== pgid && entry.startId.length > 0) { + preExitKeys.add(`${entry.pid}:${entry.startId}`); + } + } + } + const verifiedRoots = new Set(); + for (const member of sameUidMembers) { + if (preExitKeys.has(`${member.pid}:${member.startId}`)) { + verifiedRoots.add(member.pid); + continue; + } + if (!member.zombie && pipeVerifiedPids?.has(member.pid)) { + verifiedRoots.add(member.pid); + continue; + } + if (parentPid !== undefined && isDescendantOfPid(member, parentPid, byPid)) { + verifiedRoots.add(member.pid); + } + } + if (verifiedRoots.size === 0) return []; + + const survivors: ProcessIncarnationSurvivor[] = []; + for (const member of sameUidMembers) { + if (member.zombie) continue; + if (isDescendantInGroup(member, verifiedRoots, sameUidByPid)) { + survivors.push({ pid: member.pid, startId: member.startId! }); + } + } + return survivors; +} + +/** + * Observes non-zombie same-UID members of `pgid` while our verified live group + * leader (`pid === pgid`, `ppid === parentPid`, `startId === leaderStartId`, + * non-zombie) is still present in the same process snapshot. + */ +export function observePreExitProcessGroupMembers( pgid: number, - leaderStartId?: string, + leaderStartId: string | undefined, + options: { parentPid?: number } = {}, ): ProcessIncarnationSurvivor[] { - if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 0 || !processGroupExists(pgid)) { + if ( + process.platform === "win32" || + !Number.isSafeInteger(pgid) || + pgid <= 0 || + !leaderStartId || + !processGroupExists(pgid) + ) { return []; } + const parentPid = options.parentPid ?? process.pid; const processes = listObservedProcesses({ exactStartIdForPgids: new Set([pgid]) }); if (!processes) return []; - // Our leader was just reaped, so any process holding `pid === pgid` now is a reused PID. - if (processes.some((proc) => proc.pid === pgid)) return []; + const leader = processes.find((proc) => proc.pid === pgid); + if (!leader || leader.zombie || leader.pgid !== pgid || leader.ppid !== parentPid || leader.startId !== leaderStartId) { + return []; + } const currentUid = typeof process.getuid === "function" ? process.getuid() : undefined; - const survivors: ProcessIncarnationSurvivor[] = []; + const observed: ProcessIncarnationSurvivor[] = []; for (const proc of processes) { if (proc.pgid !== pgid || proc.pid === pgid || proc.zombie) continue; if (currentUid !== undefined && proc.uid !== currentUid) continue; if (!proc.startId || !startIdNotOlderThan(proc.startId, leaderStartId)) continue; - survivors.push({ pid: proc.pid, startId: proc.startId }); + observed.push({ pid: proc.pid, startId: proc.startId }); } - return survivors; + return observed; +} + +/** + * Snapshots surviving non-zombie members of `pgid` right after our group leader + * exited. Fails closed (returns `[]`) unless a candidate (or its same-UID + * ancestor in `pgid`) is proven to belong to this incarnation via pre-exit + * live-leader observation, an open inherited transport stdio pipe/socketpair, + * or live ancestry from `parentPid`. + */ +export function captureProcessGroupSurvivors( + pgid: number, + options: CaptureProcessGroupSurvivorsOptions = {}, +): ProcessIncarnationSurvivor[] { + if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 0 || !processGroupExists(pgid)) { + return []; + } + const processes = listObservedProcesses({ exactStartIdForPgids: new Set([pgid]) }); + if (!processes) return []; + const parentPid = options.parentPid ?? process.pid; + const currentUid = typeof process.getuid === "function" ? process.getuid() : undefined; + const leader = processes.find((proc) => proc.pid === pgid); + if (leader) { + const isOwnUnreapedLeader = + leader.ppid === parentPid && + Boolean(options.leaderStartId) && + leader.startId === options.leaderStartId; + if (!isOwnUnreapedLeader) return []; + } + const eligibleCandidates = processes.filter( + (proc) => + proc.pgid === pgid && + proc.pid !== pgid && + !proc.zombie && + (currentUid === undefined || proc.uid === currentUid) && + Boolean(proc.startId) && + startIdNotOlderThan(proc.startId, options.leaderStartId), + ); + if (eligibleCandidates.length === 0) return []; + + // Only invoke pipe/socketpair inspection when there are transport FDs and at least one + // candidate is not already verified by pre-exit observation or parentPid ancestry. + let pipeVerifiedPids: Set | undefined; + if (parentPid === process.pid && options.transportFds && options.transportFds.length > 0) { + const alreadyVerified = selectVerifiedProcessGroupSurvivors({ + pgid, + processes, + leaderStartId: options.leaderStartId, + parentPid, + currentUid, + preExitMembers: options.preExitMembers, + }); + const alreadyVerifiedPids = new Set(alreadyVerified.map((s) => s.pid)); + const unverifiedCandidates = eligibleCandidates.filter((cand) => !alreadyVerifiedPids.has(cand.pid)); + if (unverifiedCandidates.length > 0) { + pipeVerifiedPids = findTransportPipeVerifiedPids( + unverifiedCandidates, + pgid, + options.transportFds, + options.isTransportFdStillOpen, + parentPid, + ); + } + } + + return selectVerifiedProcessGroupSurvivors({ + pgid, + processes, + leaderStartId: options.leaderStartId, + parentPid, + currentUid, + preExitMembers: options.preExitMembers, + pipeVerifiedPids, + }); } /** Whether any process is still in the group led by `pid`. Always false on Windows. */ From e04b525f187d39993658eb6147e3a9d3805733a9 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 08:13:50 +0000 Subject: [PATCH 6/6] mcp,cli: accept buffered Darwin lsof pipes and install iproute2 in CLI Docker image --- main/shared/process-group.test.ts | 85 +++++++++++++++++++++++++++++++ main/shared/process-group.ts | 18 +++++-- packages/cli/Dockerfile | 6 ++- 3 files changed, 102 insertions(+), 7 deletions(-) diff --git a/main/shared/process-group.test.ts b/main/shared/process-group.test.ts index e1fe9c86eb..da8d93537f 100644 --- a/main/shared/process-group.test.ts +++ b/main/shared/process-group.test.ts @@ -375,6 +375,91 @@ test("Darwin lsof parser verifies anonymous PIPE and unix socketpairs and reject assert.deepEqual([...matched].sort((a, b) => a - b), [2001, 2002]); }); +test("Darwin lsof parser accepts buffered anonymous pipes with cnt=N while rejecting named, zero, malformed, and unconnected endpoints", () => { + const darwinLsof = [ + "p1000", + // Buffered anonymous PIPE on transport FD 25 (unread bytes on parent end) + "f25", + "tPIPE", + "d0x1111aaaa", + "n->0x2222bbbb, cnt=42", + // Anonymous PIPE on transport FD 26 with trailing annotation; candidate end is buffered + "f26", + "tPIPE", + "d0x1111cccc", + "n->0x2222dddd (pipe)", + // Parent PIPE on FD 27 paired against malformed/zero/named candidates below + "f27", + "tPIPE", + "d0x3333aaaa", + "n->0x4444bbbb", + // Unconnected parent PIPE on FD 28 (no peer) + "f28", + "tPIPE", + "d0x5555aaaa", + // Candidate 3001: peer of buffered FD 25 (unbuffered write end) + "p3001", + "f1", + "tPIPE", + "d0x2222bbbb", + "n->0x1111aaaa", + // Candidate 3002: peer of FD 26 with buffered cnt=N and optional annotation + "p3002", + "f2", + "tPIPE", + "d0x2222dddd", + "n->0x1111cccc, cnt=128 (pipe)", + // Candidate 3003: named path target on matching local address (rejected) + "p3003", + "f1", + "tPIPE", + "d0x4444bbbb", + "n->/tmp/mcp.sock", + // Candidate 3004: explicit zero peer address on matching local address (rejected) + "p3004", + "f1", + "tPIPE", + "d0x4444bbbb", + "n->0x00000000, cnt=5", + // Candidate 3005: malformed cnt suffix on matching local address (rejected) + "p3005", + "f1", + "tPIPE", + "d0x4444bbbb", + "n->0x3333aaaa, cnt=abc", + // Candidate 3006: unknown extra suffix on matching local address (rejected) + "p3006", + "f1", + "tPIPE", + "d0x4444bbbb", + "n->0x3333aaaa, extra=1", + // Candidate 3007: unconnected buffered pipe (bare `, cnt=42`) (rejected) + "p3007", + "f1", + "tPIPE", + "d0x4444bbbb", + "n, cnt=42", + // Candidate 3008: unconnected unix socket `->(none)` (rejected) + "p3008", + "f1", + "tunix", + "d0x4444bbbb", + "n->(none)", + // Candidate 3009: unconnected pipe with no `n` line matching unconnected FD 28 (rejected) + "p3009", + "f1", + "tPIPE", + "d0x5555aaaa", + ].join("\n"); + const matched = parseDarwinLsofSharedPipePids( + darwinLsof, + 1000, + new Set([25, 26, 27, 28]), + new Set([3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009]), + ); + assert.deepEqual([...matched].sort((a, b) => a - b), [3001, 3002]); +}); + test("captureProcessGroupSurvivors fails closed without proof and verifies pipe-inheriting survivors while rejecting unrelated leaderless groups", { skip: !posix }, async (t) => { const dir = await mkdtemp(path.join(os.tmpdir(), "aiden-survivor-proof-")); t.after(() => rm(dir, { recursive: true, force: true })); diff --git a/main/shared/process-group.ts b/main/shared/process-group.ts index 13f3bc9199..e1e838aa8d 100644 --- a/main/shared/process-group.ts +++ b/main/shared/process-group.ts @@ -404,9 +404,15 @@ function parseDarwinLsofSharedPipeMatches( } else if (tag === "n") { const trimmed = value.trim(); if (trimmed.length === 0) continue; - const match = trimmed.match(/^->(0x[0-9a-f]+)(?:\s+\([^)]*\))?$/iu); - if (match) { - peerAddr = normalizeKernelHexAddr(match[1]!); + // Darwin `lsof` appends `, cnt=` to non-empty anonymous pipes + // (`process_pipe_common` in dialects/darwin/dfile.c) and may include a + // trailing ` (...)` annotation. Reject named paths, all-zero peer + // addresses, malformed suffixes, and unconnected entries (`->(none)` or + // bare `, cnt=N`). + const match = trimmed.match(/^->(0x[0-9a-f]+)(?:,\s*cnt=\d+)?(?:\s+\([^)]*\))?$/iu); + const parsedPeerAddr = match ? normalizeKernelHexAddr(match[1]!) : undefined; + if (parsedPeerAddr) { + peerAddr = parsedPeerAddr; } else { hasNamedPath = true; } @@ -438,8 +444,10 @@ function parseDarwinLsofSharedPipeMatches( /** * Parses macOS/Darwin `lsof -nP -p , -F pftdDn` output and * returns the candidate PIDs proven to hold the peer endpoint of an anonymous - * `PIPE` or `unix` socketpair held open by `selfPid` on `transportFds`. - * Named Unix sockets, all-zero addresses, and unconnected endpoints are rejected. + * `PIPE` or `unix` socketpair held open by `selfPid` on `transportFds` + * (including buffered pipes reported as `->0x, cnt=`). + * Named Unix sockets, all-zero addresses, malformed suffixes, and unconnected + * endpoints are rejected. */ export function parseDarwinLsofSharedPipePids( stdout: string, diff --git a/packages/cli/Dockerfile b/packages/cli/Dockerfile index e8d301c63b..be675b4974 100644 --- a/packages/cli/Dockerfile +++ b/packages/cli/Dockerfile @@ -1,7 +1,8 @@ FROM mirror.gcr.io/library/node:22-bookworm AS build ENV ELECTRON_SKIP_BINARY_DOWNLOAD=1 PI_TELEMETRY=0 PI_OFFLINE=1 WORKDIR /build -RUN apt-get update -qq && apt-get install -y --no-install-recommends libssl-dev ca-certificates openssl && rm -rf /var/lib/apt/lists/* +# iproute2 (`ss`) verifies inherited Linux AF_UNIX stdio socketpairs for MCP orphan cleanup. +RUN apt-get update -qq && apt-get install -y --no-install-recommends libssl-dev ca-certificates openssl iproute2 && rm -rf /var/lib/apt/lists/* COPY package.json package-lock.json ./ RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts COPY packages/cli/package.json packages/cli/package-lock.json ./packages/cli/ @@ -30,7 +31,8 @@ COPY packages/cli/package.json packages/cli/package-lock.json ./ RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev FROM mirror.gcr.io/library/node:22-bookworm-slim -RUN apt-get update -qq && apt-get install -y --no-install-recommends git openssl ca-certificates libssl3 avahi-utils bzip2 && rm -rf /var/lib/apt/lists/* +# iproute2 (`ss`) verifies inherited Linux AF_UNIX stdio socketpairs for MCP orphan cleanup. +RUN apt-get update -qq && apt-get install -y --no-install-recommends git openssl ca-certificates libssl3 avahi-utils bzip2 iproute2 && rm -rf /var/lib/apt/lists/* COPY --from=runtime-deps --chown=node:node /deps/node_modules /opt/aiden/node_modules COPY --from=build --chown=node:node /build/packages/cli/package.json /opt/aiden/package.json COPY --from=build --chown=node:node /build/packages/cli/dist/app /opt/aiden/dist/app