Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(daemon): escape the stopping black-hole via a stopping-stuck backstop (batch L3)
Guse4026efb0233
diff --git a/src/daemon/src/manager/managerPolicy.test.ts b/src/daemon/src/manager/managerPolicy.test.tsindex 58e8f7af0..cc80b27f6 100644--- a/src/daemon/src/manager/managerPolicy.test.ts+++ b/src/daemon/src/manager/managerPolicy.test.ts@@ -527,6 +527,98 @@ describe("reduceManager — tick: reset-stuck reconcile (batch D)", () => {});});+// Batch L3 (plans/daemon-fsm-desync.md): the stopping-wedge black hole. A+// stop/terminate set status=stopping expecting an `exit` that never arrived+// (no-op stop / kill didn't take). No other predicate keys on `stopping`, and+// onWake only queues there → permanent wedge (observed live: Olivia 2026-07-31,+// stuck 12min+, inbox climbing, process still alive). This branch forces it out+// via `force_exit` (runtime handler kills any tracked proc + synthetic exit).+describe("reduceManager — tick: stopping-stuck escalation (batch L3)", () => {+ // Drive an agent into `stopping` via idle-timeout, then WITHHOLD the exit —+ // exactly the wedge. staleThreshold huge so nothing else fires; idleTimeout+ // small to enter stopping; stoppingStuck = the arg under test (4th).+ function toStoppingStuck(stoppingStuckMs = 100) {+ let s = createInitialManagerState(1_000_000, 50, 1_000_000, stoppingStuckMs);+ s = register(s, "a", PERSISTENT_GATED);+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;+ s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 0 }).state; // idleSince=0+ // Idle-timeout tick (past idleTimeout=50) → status=stopping, stoppingSince stamped.+ s = reduceManager(s, { type: "tick", nowMs: 100 }).state;+ return s;+ }++ it("stamps stoppingSince and issues stop when entering stopping", () => {+ let s = createInitialManagerState(1_000_000, 50, 1_000_000, 100);+ s = register(s, "a", PERSISTENT_GATED);+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;+ s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 0 }).state;+ const r = reduceManager(s, { type: "tick", nowMs: 100 });+ expect(r.effects).toEqual([{ type: "stop", agentId: "a", reason: "idle_timeout" }]);+ expect(r.state.agents.a.status).toBe("stopping");+ expect(r.state.agents.a.stoppingSince).toBe(100);+ });++ it("force_exits an agent wedged in stopping past the threshold (the black-hole escape)", () => {+ const s = toStoppingStuck();+ expect(s.agents.a.status).toBe("stopping");+ expect(s.agents.a.stoppingSince).toBe(100);+ // No exit ever came. nowMs - stoppingSince = 250 - 100 = 150 >= 100 → escape.+ const r = reduceManager(s, { type: "tick", nowMs: 250 });+ expect(r.effects).toEqual([{ type: "force_exit", agentId: "a", reason: "stopping_stuck" }]);+ // Still stopping this tick (the effect drives the transition out via onExit).+ expect(r.state.agents.a.status).toBe("stopping");+ });++ it("does NOT force_exit before the stopping-stuck threshold elapses", () => {+ const s = toStoppingStuck();+ // nowMs - stoppingSince = 150 - 100 = 50 < 100 → not yet.+ expect(reduceManager(s, { type: "tick", nowMs: 150 }).effects).toEqual([]);+ });++ it("clears stoppingSince on the synthetic exit (onExit) so it can't re-fire for the same episode", () => {+ let s = toStoppingStuck();+ s = reduceManager(s, { type: "tick", nowMs: 250 }).state; // force_exit emitted+ // The synthetic exit lands: onExit → settle idle (empty inbox) → stoppingSince cleared.+ s = reduceManager(s, { type: "exit", agentId: "a" }).state;+ expect(s.agents.a.stoppingSince).toBeNull();+ expect(s.agents.a.status).toBe("idle");+ // No more force_exit — the episode is over.+ expect(reduceManager(s, { type: "tick", nowMs: 10_000 }).effects).toEqual([]);+ });++ it("re-escalates if a respawn wedges in stopping AGAIN (fresh stoppingSince restarts the clock)", () => {+ let s = toStoppingStuck();+ // A wake queued during stopping so onExit respawns rather than settling idle.+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 200 }).state;+ s = reduceManager(s, { type: "tick", nowMs: 250 }).state; // force_exit+ s = reduceManager(s, { type: "exit", agentId: "a" }).state; // onExit → respawn (inbox>0) → starting+ expect(s.agents.a.status).toBe("starting");+ expect(s.agents.a.stoppingSince).toBeNull(); // cleared by onExit+ // The respawn never reaches running and gets stopped again (simulate another+ // idle-timeout path isn't reachable in starting; instead drive it via a+ // fresh stopping through the reset-stuck-like route is out of scope here).+ // Minimal: confirm a NEW stopping stamps a fresh clock.+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 300 }).state; // running+ s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 300 }).state; // idle+ s = reduceManager(s, { type: "tick", nowMs: 400 }).state; // idle-timeout → stopping again+ expect(s.agents.a.status).toBe("stopping");+ expect(s.agents.a.stoppingSince).toBe(400); // fresh clock, not the old 100+ const r = reduceManager(s, { type: "tick", nowMs: 550 }); // 550-400=150>=100+ expect(r.effects).toEqual([{ type: "force_exit", agentId: "a", reason: "stopping_stuck" }]);+ });++ it("does NOT force_exit a healthy running agent (stoppingSince null)", () => {+ let s = createInitialManagerState(1_000_000, 1_000_000, 1_000_000, 100);+ s = register(s, "a", PERSISTENT_GATED);+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;+ expect(s.agents.a.stoppingSince).toBeNull();+ expect(reduceManager(s, { type: "tick", nowMs: 10_000 }).effects).toEqual([]);+ });+});+describe("reduceManager — reset_session", () => {it("nulls sessionId on a known agent without changing status/turnActive", () => {let s = createInitialManagerState();diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.tsindex 702cbba1a..cc2ceb0a1 100644--- a/src/daemon/src/manager/managerPolicy.ts+++ b/src/daemon/src/manager/managerPolicy.ts@@ -73,6 +73,21 @@ export interface AgentState {lastDeliverAt: number | null;/** ms timestamp since which the agent has been idle (running, no turn, empty inbox); null if not idle. */idleSince: number | null;+ /**+ * ms timestamp at which the agent entered `stopping`; null whenever it is not+ * `stopping`. A `stop`/`terminate_stalled` effect expects the process to emit+ * `exit` shortly after, which drives `onExit` → respawn/idle. If that `exit`+ * never arrives (the stop was a no-op because the session handle was already+ * gone, or the kill didn't take), the agent is wedged in `stopping` FOREVER:+ * no onTick predicate keys on `stopping` (stalled/suspectedDeaf/idle need+ * `running`, resetStuck needs `resetting` and even guards `!== "stopping"`),+ * and `onWake` only queues in `stopping`. This clock is the ONLY escape: a+ * tick that finds `stopping` older than `stoppingStuckThresholdMs` forces the+ * agent out (see `onTick`'s stopping-stuck branch). SET at every transition+ * into `stopping`; CLEARED by `enterStable` (→ running/idle) and `onExit`.+ * See plans/daemon-fsm-desync.md batch L3 (stopping-wedge black hole).+ */+ stoppingSince: number | null;/*** True during an owner-triggered reset window. Gates every inbound wake to* inbox-only (no `spawn`, no `send`, no `gated_hold`) EXCEPT when the@@ -132,6 +147,12 @@ export interface ManagerState {* `DEFAULT_RESET_STUCK_THRESHOLD_MS`.*/resetStuckThresholdMs: number;+ /**+ * Stopping-stuck escalation threshold: `status === "stopping"` for longer than+ * this (from `stoppingSince`) ⇒ the process's `exit` never arrived, so force+ * the agent out of the black hole. See `DEFAULT_STOPPING_STUCK_THRESHOLD_MS`.+ */+ stoppingStuckThresholdMs: number;}/* ------------------------------------------------------------------ */@@ -180,6 +201,17 @@ export type ManagerEffect =| { type: "send"; agentId: string; text: string; mode: "busy" | "idle" }| { type: "stop"; agentId: string; reason: string }| { type: "terminate_stalled"; agentId: string }+ /**+ * Stopping-stuck escalation (batch L3): the agent has sat in `stopping` past+ * `stoppingStuckThresholdMs` — the `exit` a prior stop/terminate expected never+ * arrived, so the agent is wedged in the one state no other watchdog can reach.+ * The runtime handler force-kills any still-tracked process (best effort; warns+ * if none is available — a possible orphan) and dispatches a SYNTHETIC `exit`+ * so the FSM traverses the normal `onExit` → respawn/idle recovery. Universal+ * backstop: covers both a no-op stop (session handle already gone) and a stop+ * that ran but produced no exit. See plans/daemon-fsm-desync.md batch L3.+ */+ | { type: "force_exit"; agentId: string; reason: string }/*** Pure observability: a gated agent has a non-empty inbox but nothing was* actually sent — either a mid-turn wake was held, or a boundary flush@@ -201,6 +233,16 @@ export const DEFAULT_IDLE_TIMEOUT_MS = 300_000;* See plans/daemon-fsm-desync.md batch D.*/export const DEFAULT_RESET_STUCK_THRESHOLD_MS = 120_000;+/**+ * Stopping-stuck escalation threshold (ms): how long an agent may sit in+ * `stopping` — waiting for a `stop`/`terminate_stalled`'s expected `exit` — before+ * the tick concludes the exit will never come and forces the agent out (force-kill+ * the orphaned process if any + a synthetic `exit` to drive onExit→respawn). MUST+ * be comfortably larger than `SESSION_STOP_GRACE_MS` (the legitimate SIGTERM→SIGKILL+ * grace, 2s) so it never races an in-flight stop that's about to succeed — this is+ * a black-hole safety net, not a fast path. See plans/daemon-fsm-desync.md batch L3.+ */+export const DEFAULT_STOPPING_STUCK_THRESHOLD_MS = 30_000;export interface ReduceResult {state: ManagerState;@@ -211,8 +253,9 @@ export function createInitialManagerState(staleThresholdMs = DEFAULT_STALE_THRESHOLD_MS,idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,resetStuckThresholdMs = DEFAULT_RESET_STUCK_THRESHOLD_MS,+ stoppingStuckThresholdMs = DEFAULT_STOPPING_STUCK_THRESHOLD_MS,): ManagerState {- return { agents: {}, staleThresholdMs, idleTimeoutMs, resetStuckThresholdMs };+ return { agents: {}, staleThresholdMs, idleTimeoutMs, resetStuckThresholdMs, stoppingStuckThresholdMs };}/* ------------------------------------------------------------------ */@@ -500,6 +543,12 @@ function onExit(state: ManagerState, agentId: string): ReduceResult {if (!existing) return { state, effects: [] };const agent = clone(existing);agent.turnActive = false;+ // The process is gone, so `stopping` no longer applies — clear the+ // stopping-stuck clock here (covers BOTH onExit branches: the respawn path+ // sets status="starting" directly, not via enterStable, so it wouldn't be+ // cleared otherwise; the settle-idle path goes through enterStable which also+ // clears it, harmless to do twice).+ agent.stoppingSince = null;// Fresh process ⇒ fresh gated-steering horizon. Symmetric with `onTurnEnd`;// prevents a dead process's `compacting` / outstanding-tool-use flags from// silently carrying into the next spawn and re-blocking `onWake`.@@ -575,7 +624,7 @@ function onTick(state: ManagerState, nowMs: number): ReduceResult {a.lastDeliverAt > a.lastProgressAt &&nowMs - a.lastDeliverAt >= state.staleThresholdMs;if (stalled || suspectedDeaf) {- agents[id] = { ...a, status: "stopping", idleSince: null };+ agents[id] = { ...a, status: "stopping", idleSince: null, stoppingSince: nowMs };effects.push({ type: "terminate_stalled", agentId: id });continue;}@@ -613,11 +662,40 @@ function onTick(state: ManagerState, nowMs: number): ReduceResult {a.resettingSince !== null &&nowMs - a.resettingSince >= state.resetStuckThresholdMs;if (resetStuck) {- agents[id] = { ...a, status: "stopping", idleSince: null };+ agents[id] = { ...a, status: "stopping", idleSince: null, stoppingSince: nowMs };effects.push({ type: "terminate_stalled", agentId: id });continue;}+ // Stopping-stuck escalation (plans/daemon-fsm-desync.md batch L3): the black+ // hole. A `stop`/`terminate_stalled` set status=`stopping` expecting the+ // process to emit `exit` (→ onExit → respawn/idle). If that `exit` never+ // comes — the stop was a no-op (session handle already gone), or the kill+ // didn't take — the agent is wedged in `stopping` PERMANENTLY: no predicate+ // above keys on `stopping` (stalled/suspectedDeaf/idle need `running`;+ // resetStuck needs `resetting` AND guards `!== "stopping"`), and `onWake`+ // only queues in `stopping` (inbox grows unboundedly, never delivered —+ // observed live: Olivia 2026-07-31 stuck 12min, inbox climbing, process+ // still alive). This is the ONE escape. Force the agent out via `force_exit`+ // (runtime handler best-effort-kills any tracked process, then dispatches a+ // SYNTHETIC `exit` so the FSM runs the normal onExit recovery). Threshold ≫+ // SESSION_STOP_GRACE_MS so it never races a legitimate in-flight stop.+ // Storm-free: `force_exit` → onExit → enterStable clears `stoppingSince`, so+ // it can't re-fire for the same stopping episode; if the respawn wedges in+ // `stopping` again, a fresh `stoppingSince` restarts the clock and it re-+ // escalates — converging until a respawn sticks.+ const stoppingStuck =+ a.status === "stopping" &&+ a.stoppingSince !== null &&+ nowMs - a.stoppingSince >= state.stoppingStuckThresholdMs;+ if (stoppingStuck) {+ // Leave stoppingSince set until the synthetic exit's onExit clears it —+ // status stays `stopping` this tick, so the `!== "stopping"` shape holds+ // and nothing else touches it; the effect drives the transition out.+ effects.push({ type: "force_exit", agentId: id, reason: "stopping_stuck" });+ continue;+ }+// Idle hibernation: a persistent keep-alive process that has sat idle (turn// ended, inbox empty) past the timeout is stopped to free resources. Its// sessionId is preserved, so the next wake resumes it.@@ -629,7 +707,7 @@ function onTick(state: ManagerState, nowMs: number): ReduceResult {state.idleTimeoutMs > 0 &&Number.isFinite(state.idleTimeoutMs);if (idleEligible && a.idleSince !== null && nowMs - a.idleSince >= state.idleTimeoutMs) {- agents[id] = { ...a, status: "stopping", idleSince: null };+ agents[id] = { ...a, status: "stopping", idleSince: null, stoppingSince: nowMs };effects.push({ type: "stop", agentId: id, reason: "idle_timeout" });}}@@ -651,6 +729,7 @@ function freshAgent(agentId: string, caps: AgentRuntimeCaps): AgentState {lastProgressAt: 0,lastDeliverAt: null,idleSince: null,+ stoppingSince: null,resetting: false,resettingSince: null,apm: createInitialApmGatedSteeringState(),@@ -681,6 +760,8 @@ function enterStable(agent: AgentState, status: "running" | "idle"): void {agent.status = status;agent.resetting = false;agent.resettingSince = null;+ // Left `stopping` (reached a stable state) ⇒ the stopping-stuck clock is moot.+ agent.stoppingSince = null;}/** Coalesce all queued messages into one prompt, deduplicating identical lines. */diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex 04bd376c1..d555c185e 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -522,6 +522,55 @@ describe("AgentProcessManager — session race conditions", () => {vi.useRealTimers();}});++ it("force_exits an agent wedged in `stopping` when its stop produced no exit (batch L3 black-hole escape)", async () => {+ vi.useFakeTimers();+ try {+ let currentTime = 0;+ const stopSpy = vi.fn();+ const persistentDriver = {+ ...fakeDriver("codex"),+ lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,+ } as Driver;+ const session = fakeSession();+ session.stop = stopSpy; // spy: was the process asked to die?+ // A live session handle is present → force_exit takes the kill path+ // (session.stop), not the orphan-warn path.+ const mgr = new AgentProcessManager({+ driverFor: () => persistentDriver,+ baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),+ sessionFactory: () => session,+ now: () => currentTime,+ tickIntervalMs: 5,+ idleTimeoutMs: 50,+ stoppingStuckThresholdMs: 100,+ });+ mgr.register("a1");+ mgr.deliver("a1", { seq: 1, text: "hello" });+ session.startResolver?.();+ await Promise.resolve();+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });+ session.fire("runtime_event", { kind: "turn_end" });+ mgr.start();++ // Idle-timeout tick → status=stopping, issues a stop. Crucially we DO NOT+ // fire the session's `exit` — the wedge: stop was requested, exit never came.+ currentTime = 100;+ await vi.advanceTimersByTimeAsync(10);+ const stopCallsAfterIdle = stopSpy.mock.calls.length; // idle-timeout stop++ // Now sit in `stopping` past the stopping-stuck threshold with NO exit.+ currentTime = 300; // 300 - 100(stoppingSince) = 200 >= 100+ await vi.advanceTimersByTimeAsync(10);++ // force_exit fired: the handler force-killed (a 2nd stop) AND dispatched a+ // synthetic exit that drove the FSM out of `stopping`.+ expect(stopSpy.mock.calls.length).toBeGreaterThan(stopCallsAfterIdle);+ expect(mgr.snapshot().agents["a1"]?.status).not.toBe("stopping");+ } finally {+ vi.useRealTimers();+ }+ });});describe("AgentProcessManager — onAgentActivity (derived activity reporting)", () => {diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex b8e38bcf1..fa914d810 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -13,6 +13,7 @@import {reduceManager,createInitialManagerState,+ DEFAULT_STOPPING_STUCK_THRESHOLD_MS,type ManagerState,type ManagerEvent,type ManagerEffect,@@ -91,6 +92,8 @@ export interface ManagerRuntimeOpts {idleTimeoutMs?: number;/** Reset-stuck reconcile threshold (ms): `resetting` stuck this long ⇒ escalate. */resetStuckThresholdMs?: number;+ /** Stopping-stuck escalation threshold (ms): `stopping` this long (no exit came) ⇒ force_exit. */+ stoppingStuckThresholdMs?: number;/*** Handshake watchdog (ms): a spawned session that never emits its first* `runtime_event` (the handshake) within this window is treated as a@@ -610,13 +613,19 @@ export class AgentProcessManager {staleThresholdMs: 120_000,idleTimeoutMs: 300_000,resetStuckThresholdMs: 120_000,+ stoppingStuckThresholdMs: DEFAULT_STOPPING_STUCK_THRESHOLD_MS,handshakeTimeoutMs: 60_000,stampWakePromptTime: false,...opts,};this.now = opts.now ?? (() => Date.now());this.log = opts.logger ?? createLogger({ header: "@alook/daemon:manager" });- this.state = createInitialManagerState(this.opts.staleThresholdMs, this.opts.idleTimeoutMs, this.opts.resetStuckThresholdMs);+ this.state = createInitialManagerState(+ this.opts.staleThresholdMs,+ this.opts.idleTimeoutMs,+ this.opts.resetStuckThresholdMs,+ this.opts.stoppingStuckThresholdMs,+ );}/**@@ -1067,6 +1076,49 @@ export class AgentProcessManager {this.opts.onAgentLocallyStopped?.({ agentId: effect.agentId, reason: effect.type });break;}+ case "force_exit": {+ // Stopping-stuck black-hole escape (plans/daemon-fsm-desync.md batch L3):+ // the agent sat in `stopping` past the threshold because the `exit` a+ // prior stop/terminate expected never came. Force the FSM out.+ //+ // (1) Best-effort kill any still-tracked process so we don't leak an+ // orphan. The session handle is the ONLY process reference we have+ // (activeSpawnState carries no pid), so if it's already gone — the+ // very no-op case that caused this wedge (the handle was cleared+ // before the original stop ran) — we genuinely CANNOT kill the+ // process here; the synthetic exit below still frees the FSM, but+ // the old process is orphaned. Warn so that orphan is VISIBLE+ // (Claudette's gate requirement) rather than a silent leak — an+ // orphan beats a permanent wedge. Actually reaping the orphan needs+ // an independent pid record (activeSpawnState.pid); that's a+ // followup, so this branch honestly only warns, it does not pretend+ // to kill what it can't reach.+ const session = this.sessions.get(effect.agentId);+ const state = this.activeSpawnState.get(effect.agentId);+ if (session) {+ void Promise.resolve(session.stop({ reason: effect.reason, forceAfterMs: SESSION_STOP_GRACE_MS })).catch(() => {});+ } else {+ this.log.warn("force_exit: no session handle to kill before synthetic exit — possible orphan process (reap is a followup, needs an independent pid record)", {+ agentId: effect.agentId,+ reason: effect.reason,+ });+ }+ // (2) Tear down tracking + mark torndown so the killed process's eventual+ // late `exit` (if the kill does land) is a no-op, not a second+ // teardown that could clobber a session a fresh wake spawned in+ // between — same guard the handshake-timeout path uses.+ if (state) state.torndown = true;+ this.logSessionEnded(effect.agentId, "terminate_stalled");+ if (this.sessions.get(effect.agentId) === session) this.sessions.delete(effect.agentId);+ this.liveSessions.delete(effect.agentId);+ if (this.activeSpawnState.get(effect.agentId) === state) this.activeSpawnState.delete(effect.agentId);+ this.opts.onAgentLocallyStopped?.({ agentId: effect.agentId, reason: "terminate_stalled" });+ // (3) Synthetic `exit` → the normal onExit recovery (drain-respawn or+ // settle idle; enterStable clears stoppingSince). Universal backstop:+ // works whether or not we could kill the process.+ this.dispatch({ type: "exit", agentId: effect.agentId });+ break;+ }case "gated_hold":// Pure observability — no behavioral effect. Emitted whenever a// gated agent has a non-empty inbox but nothing was actually sent.