Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(daemon): atomically close the reset window + surface a reborn session's errors

Claudette054c11b49dae
diff --git a/src/daemon/src/manager/managerPolicy.test.ts b/src/daemon/src/manager/managerPolicy.test.ts
index d84e8d36c..07be8126d 100644
--- a/src/daemon/src/manager/managerPolicy.test.ts
+++ b/src/daemon/src/manager/managerPolicy.test.ts
@@ -469,12 +469,14 @@ describe("reduceManager — reset_session", () => {
});
describe("reduceManager — begin_reset / rewake_after_reset", () => {
- it("begin_reset sets resetting=true and emits no effects", () => {
+ it("begin_reset sets resetting=true, stamps resettingSince, and emits no effects", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_GATED);
- const r = reduceManager(s, { type: "begin_reset", agentId: "a" });
+ const r = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 42 });
expect(r.effects).toEqual([]);
expect(r.state.agents.a.resetting).toBe(true);
+ // Window start stamped so batch D can detect a reset that never converged.
+ expect(r.state.agents.a.resettingSince).toBe(42);
});
it("rewake_after_reset appends to inbox and emits no effects", () => {
@@ -487,7 +489,7 @@ describe("reduceManager — begin_reset / rewake_after_reset", () => {
it("both events are no-ops on an unknown agent", () => {
const s = createInitialManagerState();
- expect(reduceManager(s, { type: "begin_reset", agentId: "ghost" }).state.agents.ghost).toBeUndefined();
+ expect(reduceManager(s, { type: "begin_reset", agentId: "ghost", nowMs: 1 }).state.agents.ghost).toBeUndefined();
expect(
reduceManager(s, { type: "rewake_after_reset", agentId: "ghost", message: { text: "x" } }).state.agents.ghost,
).toBeUndefined();
@@ -502,7 +504,7 @@ describe("reduceManager — onWake `resetting` gate", () => {
s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
// Set resetting via the FSM event (bypassing onSpawned's auto-clear
// which fires before this event).
- s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
expect(s.agents.a.resetting).toBe(true);
expect(s.agents.a.status).toBe("running");
@@ -516,7 +518,7 @@ describe("reduceManager — onWake `resetting` gate", () => {
s = register(s, "a", PERSISTENT_GATED);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
- s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "unread" }, nowMs: 3 });
expect(r.effects).toEqual([]);
@@ -528,7 +530,7 @@ describe("reduceManager — onWake `resetting` gate", () => {
s = register(s, "a", PERSISTENT_DIRECT);
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
// status=starting now
- s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "unread" }, nowMs: 2 });
expect(r.effects).toEqual([]);
@@ -538,7 +540,7 @@ describe("reduceManager — onWake `resetting` gate", () => {
it("idle + resetting=true: wake IS EXEMPTED — still spawns (idle branch of reset orchestrator relies on this)", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_DIRECT);
- s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
expect(s.agents.a.resetting).toBe(true);
expect(s.agents.a.status).toBe("idle");
@@ -556,22 +558,52 @@ describe("reduceManager — onExit / onSpawned clear resetting", () => {
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
// Begin reset: mark + enqueue rewake
- s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
s = reduceManager(s, { type: "rewake_after_reset", agentId: "a", message: { text: "REWAKE" } }).state;
// Real unread arrives during reset window — gate queues to inbox.
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "unread" }, nowMs: 3 }).state;
expect(s.agents.a.inbox.map((m) => m.text)).toEqual(["REWAKE", "unread"]);
- // Kill lands → exit
+ // Kill lands → exit → drains rewake+unread into ONE respawn.
const r = reduceManager(s, { type: "exit", agentId: "a" });
expect(r.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "REWAKE\nunread", resumeSessionId: null }]);
- expect(r.state.agents.a.resetting).toBe(false);
+ // Batch C semantic change (intentional): the reset window stays OPEN across
+ // the respawn's transient `starting` state — it closes only when the fresh
+ // process reaches `running` via `spawned`/`enterStable`, i.e. when context
+ // is actually re-established, not merely when the old process died.
+ expect(r.state.agents.a.status).toBe("starting");
+ expect(r.state.agents.a.resetting).toBe(true);
+ // ...and closes on the respawn's `spawned`.
+ const r2 = reduceManager(r.state, { type: "spawned", agentId: "a", nowMs: 5 });
+ expect(r2.state.agents.a.status).toBe("running");
+ expect(r2.state.agents.a.resetting).toBe(false);
+ expect(r2.state.agents.a.resettingSince).toBeNull();
+ });
+
+ it("respawn that itself wedges keeps resetting true + resettingSince aging → batch D's reconcile can catch the stuck-in-starting orphan", () => {
+ let s = createInitialManagerState();
+ s = register(s, "a", PERSISTENT_DIRECT);
+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;
+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 3 }).state;
+ s = reduceManager(s, { type: "rewake_after_reset", agentId: "a", message: { text: "REWAKE" } }).state;
+ // Kill → exit → respawn emitted, status goes to the transient `starting`.
+ const r = reduceManager(s, { type: "exit", agentId: "a" });
+ expect(r.effects[0]).toMatchObject({ type: "spawn", agentId: "a" });
+ // The respawn never lands a `spawned` (new process wedged). The reset window
+ // stays open with its ORIGINAL start time — the signal batch D reads to
+ // detect a reset that never converged. Under the old "clear at onExit"
+ // behavior this was `resetting=false, status=starting`, invisible to every
+ // running-gated recovery predicate.
+ expect(r.state.agents.a.status).toBe("starting");
+ expect(r.state.agents.a.resetting).toBe(true);
+ expect(r.state.agents.a.resettingSince).toBe(3);
});
it("onSpawned clears resetting (idle-branch reset spawn)", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_DIRECT);
- s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
// Idle-branch deliver emits spawn (idle exempt).
s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "REWAKE" }, nowMs: 1 }).state;
expect(s.agents.a.resetting).toBe(true);
@@ -582,7 +614,7 @@ describe("reduceManager — onExit / onSpawned clear resetting", () => {
it("spawn-failure path (exit fires with empty inbox) still clears resetting → no permanent reset-lock", () => {
let s = createInitialManagerState();
s = register(s, "a", PERSISTENT_DIRECT);
- s = reduceManager(s, { type: "begin_reset", agentId: "a" }).state;
+ s = reduceManager(s, { type: "begin_reset", agentId: "a", nowMs: 1 }).state;
// Simulate driver.start() rejecting: `doSpawn` dispatches an immediate
// exit; by then drainInboxToPrompt already emptied the inbox into the
// (failed) spawn's prompt.
diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.ts
index f291983d6..bf542c24d 100644
--- a/src/daemon/src/manager/managerPolicy.ts
+++ b/src/daemon/src/manager/managerPolicy.ts
@@ -78,11 +78,23 @@ export interface AgentState {
* inbox-only (no `spawn`, no `send`, no `gated_hold`) EXCEPT when the
* agent is currently `idle` — the orchestrator's idle branch relies on
* `deliver` still emitting a spawn to kick a fresh session; if the gate
- * blocked idle too, the reset would silently reset-lock the agent. Cleared
- * by `onExit` (kill-and-respawn path) and `onSpawned` (idle-branch spawn
- * path). See plans/bot-reset-session-v2.md.
+ * blocked idle too, the reset would silently reset-lock the agent. SET at
+ * `begin_reset`; CLEARED exclusively by `enterStable` (the single owner of
+ * every transition into a stable `running`/`idle` state — see its doc). See
+ * plans/bot-reset-session-v2.md and plans/daemon-fsm-desync.md batch C.
*/
resetting: boolean;
+ /**
+ * ms timestamp at which the current reset window began (`begin_reset`); null
+ * when not resetting. Owned by this (recovery) layer alongside `resetting`
+ * itself — SET at `begin_reset`, cleared by `enterStable`. Batch D's
+ * reconcile READS it to detect a reset that never converged (`resetting`
+ * still true, `resettingSince` older than the stale window ⇒ the clearing
+ * event never arrived), then escalates through `enterStable` — state
+ * ownership here, detection ownership there. See plans/daemon-fsm-desync.md
+ * batch C/D.
+ */
+ resettingSince: number | null;
/**
* Coarse gated-steering phase (tool/compaction/review boundaries). Only
* meaningfully consulted when `caps.busyDeliveryMode === "gated"`; kept on
@@ -140,7 +152,7 @@ export type ManagerEvent =
* effects — the orchestrator dispatches `deliver` (idle branch) or
* `enqueueRewake` immediately after, and `stop()` follows on live branch.
*/
- | { type: "begin_reset"; agentId: string }
+ | { type: "begin_reset"; agentId: string; nowMs: number }
/**
* Enqueue a synthetic rewake message into the agent's inbox WITHOUT
* emitting any effect. Used by the reset orchestrator's live/starting/
@@ -199,7 +211,11 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceR
case "spawned":
return mutate(state, event.agentId, (a) => {
- a.status = "running";
+ // Single owner of the stable-state transition: `enterStable` sets
+ // status="running" AND clears the reset window (resetting/
+ // resettingSince) atomically — covering the idle-branch reset path
+ // (deliver → spawn directly, no `exit` fires) without a separate clear.
+ enterStable(a, "running");
a.turnActive = true;
a.lastProgressAt = event.nowMs;
// Fresh process ⇒ no outstanding unanswered delivery yet. Clearing keeps
@@ -209,10 +225,6 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceR
// so the fresh-lifecycle invariant doesn't rely on that coincidence.
a.lastDeliverAt = null;
a.idleSince = null;
- // Belt for the idle-branch reset path where `deliver` triggered a
- // spawn directly (no `exit` fires there). The kill-and-respawn path
- // clears `resetting` in `onExit`; here we cover the parallel path.
- if (a.resetting) a.resetting = false;
});
case "session":
@@ -234,6 +246,10 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceR
if (!state.agents[event.agentId]) return { state, effects: [] };
return mutate(state, event.agentId, (a) => {
a.resetting = true;
+ // Stamp the window's start so batch D's reconcile can detect a reset
+ // that never converged (still resetting, `resettingSince` older than
+ // the stale window ⇒ the clearing event never arrived).
+ a.resettingSince = event.nowMs;
});
case "rewake_after_reset":
@@ -466,13 +482,6 @@ function onExit(state: ManagerState, agentId: string): ReduceResult {
if (!existing) return { state, effects: [] };
const agent = clone(existing);
agent.turnActive = false;
- // Clear `resetting` unconditionally at the top — covers both the normal
- // path (kill → exit → drain → spawn, resetting cleared before the spawn)
- // AND the spawn-failure path (`doSpawn` dispatches an immediate `exit`
- // with `inbox.length === 0`, taking the idle branch below). Without the
- // top-level clear, the failure path would leave `resetting: true` and
- // silently reset-lock the agent for every subsequent wake.
- if (agent.resetting) agent.resetting = false;
// 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`.
@@ -481,7 +490,15 @@ function onExit(state: ManagerState, agentId: string): ReduceResult {
// deliver marker so the suspected-deaf detector starts clean for the respawn.
agent.lastDeliverAt = null;
- // Per-turn: if more messages queued, immediately respawn for the next batch.
+ // Per-turn / reset-respawn: if messages are queued (drained rewake + unreads),
+ // respawn for the next batch. `status = "starting"` is TRANSIENT — the reset
+ // window (`resetting`) deliberately stays OPEN across it and closes only when
+ // the fresh process reaches `running` via `spawned` → `enterStable`. This is
+ // the batch-C semantic: a reset ends at "context re-established", not at "old
+ // process died". If the respawn itself wedges (new process never emits
+ // `spawned`), `resetting` stays true with an aging `resettingSince`, so
+ // batch D's reconcile catches the stuck-in-`starting` orphan — which the old
+ // "clear at onExit" behavior left invisible to every running-gated detector.
if (agent.inbox.length > 0) {
agent.status = "starting";
const prompt = drainInboxToPrompt(agent);
@@ -489,7 +506,11 @@ function onExit(state: ManagerState, agentId: string): ReduceResult {
{ type: "spawn", agentId, prompt, resumeSessionId: agent.sessionId },
]);
}
- agent.status = "idle";
+ // No respawn (incl. the spawn-failure path: `doSpawn` dispatched an immediate
+ // `exit` after draining the inbox into the failed spawn's prompt) ⇒ the agent
+ // settles idle. `enterStable` closes the reset window here — the single owner
+ // of clearing `resetting`, so a failed reset can never leave it stuck.
+ enterStable(agent, "idle");
return commit(state, agent, []);
}
@@ -575,10 +596,37 @@ function freshAgent(agentId: string, caps: AgentRuntimeCaps): AgentState {
lastDeliverAt: null,
idleSince: null,
resetting: false,
+ resettingSince: null,
apm: createInitialApmGatedSteeringState(),
};
}
+/**
+ * Move an agent into a STABLE lifecycle state (`running` or `idle`) — the
+ * SINGLE owner of clearing the reset window. Every transition into a stable
+ * state MUST go through here, never a bare `agent.status = "running"/"idle"`
+ * assignment: that is what makes "the reset window ends exactly when the agent
+ * reaches a stable state" a structural invariant instead of two hand-maintained
+ * clear sites (`onSpawned` and `onExit`) that a deaf/hung process can both miss.
+ *
+ * Batch C (plans/daemon-fsm-desync.md): the old design cleared `resetting` in
+ * `onSpawned` (idle-branch) and `onExit` (kill-branch) — both event-driven, so
+ * an event that never arrives (SDK start wedged → no `spawned`; process won't
+ * emit `exit`) left `resetting` stuck true forever, reset-locking every future
+ * wake. Folding the clear into the stable-state transition means: whatever path
+ * reaches `running`/`idle`, the window closes atomically with it. Batch D's
+ * reconcile, on detecting a reset that never converged (`resettingSince` stale),
+ * escalates through this same helper — recovery reuses the primitive.
+ *
+ * `starting`/`stopping` are TRANSIENT (still mid-reset) and deliberately do NOT
+ * go through here — they don't clear the window.
+ */
+function enterStable(agent: AgentState, status: "running" | "idle"): void {
+ agent.status = status;
+ agent.resetting = false;
+ agent.resettingSince = null;
+}
+
/** Coalesce all queued messages into one prompt, deduplicating identical lines. */
function drainInboxToPrompt(agent: AgentState): string {
const seen = new Set<string>();
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index 64ccf55cb..188f84ca1 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -1102,13 +1102,16 @@ describe("AgentProcessManager — error audit emission", () => {
expect(payload.message).toContain("429");
});
- it("does NOT emit a `runtime_error` row for an error event during an intentional kill (resetting=true)", () => {
+ it("does NOT emit a `runtime_error` row for the death rattle of a session an intentional kill superseded", () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
// Establish, then enter the reset/nap kill window before the dying
- // process fires its interrupted-turn "death rattle" error.
+ // process fires its interrupted-turn "death rattle" error. `markResetting`
+ // marks THIS live session's per-session state `superseded`, so the gate
+ // suppresses its rattle by session identity (not the agent-level reset
+ // flag) — the reborn session, a fresh state, would still surface its own.
session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
mgr.markResetting("a1");
session.fire("runtime_event", { kind: "error", message: "turn interrupted" });
@@ -1119,6 +1122,50 @@ describe("AgentProcessManager — error audit emission", () => {
expect(errCalls).toHaveLength(0);
});
+ it("DOES emit a `runtime_error` for a REBORN (non-superseded) session's error even while the agent's reset window is still open — batch C reader-C fix", () => {
+ // Batch C keeps `resetting` open across the respawn until the reborn
+ // process reaches `running`, so the reborn session is live while the reset
+ // window is still open. Gating the audit on the agent-level reset window
+ // would swallow the reborn session's OWN genuine error. The gate instead
+ // keys on per-session identity: only a SUPERSEDED (outgoing/killed)
+ // session's rattle is suppressed. A reborn session gets a fresh state
+ // (`superseded=false`), so its real error must SURFACE.
+ //
+ // The fake harness reuses one session object; we assert the gate's
+ // behavior directly by driving `onRuntimeEvent` with the reborn session's
+ // (non-superseded) identity — mirroring what the real per-session
+ // subscriber closure passes.
+ const onBotAuditEvent = vi.fn();
+ const { mgr } = makeManager({ onBotAuditEvent });
+
+ // Reborn session identity → superseded=false (the subscriber passes its own
+ // session state's flag). A genuine startup error must be audited.
+ (mgr as unknown as {
+ onRuntimeEvent: (a: string, e: unknown, r: string, superseded: boolean) => void;
+ }).onRuntimeEvent("a1", { kind: "error", message: "reborn hit a rate limit" }, "codex", false);
+
+ const errCalls = onBotAuditEvent.mock.calls.filter(
+ ([, ev]) => (ev as { kind?: string })?.kind === "error",
+ );
+ expect(errCalls).toHaveLength(1);
+ expect((errCalls[0]![1] as { payload: { message: string } }).payload.message).toContain("rate limit");
+ });
+
+ it("does NOT emit for a SUPERSEDED session's death rattle (the outgoing session an intentional kill interrupted) — batch C reader-C fix", () => {
+ const onBotAuditEvent = vi.fn();
+ const { mgr } = makeManager({ onBotAuditEvent });
+ // Superseded session identity → its interrupted-turn error is teardown
+ // noise, suppressed regardless of the agent's status.
+ (mgr as unknown as {
+ onRuntimeEvent: (a: string, e: unknown, r: string, superseded: boolean) => void;
+ }).onRuntimeEvent("a1", { kind: "error", message: "turn interrupted" }, "codex", true);
+
+ const errCalls = onBotAuditEvent.mock.calls.filter(
+ ([, ev]) => (ev as { kind?: string })?.kind === "error",
+ );
+ expect(errCalls).toHaveLength(0);
+ });
+
it("scrubs secrets out of an error message before it becomes an audit row", () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index cf6b0f25b..5265602d7 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -525,6 +525,15 @@ export class AgentProcessManager {
* a session a fresh wake spawned in between.
*/
torndown: boolean;
+ /**
+ * Set when this session has been SUPERSEDED by an intentional kill
+ * (reset / nap / model_switch) — `markResetting` flips it before the
+ * kill. The error-audit gate uses it to suppress this outgoing session's
+ * interrupted-turn death rattle while still surfacing a reborn session's
+ * genuine error (the reborn gets a fresh entry with `superseded=false`).
+ * Per-session identity, not agent-level status. See batch C reader-C fix.
+ */
+ superseded: boolean;
}
>();
private readonly opts: Required<
@@ -648,7 +657,15 @@ export class AgentProcessManager {
* explicit "end reset" event.
*/
markResetting(agentId: string): void {
- this.dispatch({ type: "begin_reset", agentId });
+ this.dispatch({ type: "begin_reset", agentId, nowMs: this.now() });
+ // Mark the CURRENTLY-live session (if any) superseded, so its death rattle
+ // — the interrupted-turn error the dying process emits before `exit` — is
+ // suppressed by the error-audit gate, while the reborn session (a fresh
+ // `activeSpawnState` entry with `superseded=false`) still surfaces its own
+ // genuine errors. Per-session identity, set at kill-initiation. If there's
+ // no live session yet (reset of an idle agent), there's nothing to rattle.
+ const live = this.activeSpawnState.get(agentId);
+ if (live) live.superseded = true;
}
/**
@@ -1071,7 +1088,7 @@ export class AgentProcessManager {
// `terminate_stalled` from `applyEffect`) so the process's eventual
// `exit` event doesn't ALSO log a redundant/contradictory
// "session ended" line for the same termination.
- const state = { hasEstablished: false, hasReportedSpawnFailure: false, suppressExitLog: false, handshakeTimer: null as ReturnType<typeof setTimeout> | null, torndown: false };
+ const state = { hasEstablished: false, hasReportedSpawnFailure: false, suppressExitLog: false, handshakeTimer: null as ReturnType<typeof setTimeout> | null, torndown: false, superseded: false };
this.activeSpawnState.set(agentId, state);
const clearHandshakeTimer = () => {
if (state.handshakeTimer) {
@@ -1112,7 +1129,12 @@ export class AgentProcessManager {
if ((e as { kind?: string })?.kind === "turn_end" && driver.lifecycle.kind === "per_turn") {
state.suppressExitLog = true;
}
- this.onRuntimeEvent(agentId, e, driver.id);
+ // Pass THIS session's own state so the error-audit gate can tell a
+ // superseded (being-killed) session's death rattle from a live session's
+ // genuine error — per-session identity, not agent-level status. A reborn
+ // session gets a fresh `state` with `superseded=false`, so its startup
+ // error surfaces even while the agent's reset window is still open.
+ this.onRuntimeEvent(agentId, e, driver.id, state.superseded);
});
// Only ChildProcessRuntimeSession emits `stderr`; SdkManagedSession
// doesn't, so this is harmless when the session is an SDK adapter.
@@ -1305,7 +1327,7 @@ export class AgentProcessManager {
}
}
- private onRuntimeEvent(agentId: string, e: unknown, runtimeId: string): void {
+ private onRuntimeEvent(agentId: string, e: unknown, runtimeId: string, sessionSuperseded: boolean): void {
const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string; input?: unknown; message?: string };
if (!ev?.kind) return;
// A runtime-parsed `error` event (rate limit, auth failure, bad-model API
@@ -1315,14 +1337,23 @@ export class AgentProcessManager {
// here (this fires from the `runtime_event` subscriber), so the scope is
// `runtime`, not `spawn`.
//
- // EXCEPT during an intentional kill (reset / nap / model_switch): the
- // dying process, interrupted mid-turn, emits a final error `result`
- // ("death rattle") that is teardown noise, not a fault. `agent.resetting`
- // is true across the whole kill→respawn window (set at `begin_reset`
- // before `stop()`, cleared at `onExit`/`spawned`), and the reborn session
- // isn't spawned until AFTER the flag clears — so gating on it drops only
- // the intentional-kill noise, never a live session's genuine error.
- if (ev.kind === "error" && !this.state.agents[agentId]?.resetting) {
+ // EXCEPT for the death rattle of a SUPERSEDED session: an intentional kill
+ // (reset / nap / model_switch) interrupts the dying process mid-turn and it
+ // emits a final error `result` that is teardown noise, not a fault.
+ //
+ // This gates on PER-SESSION identity (`sessionSuperseded`), not the
+ // agent-level `resetting` flag. Batch C keeps `resetting` true across the
+ // respawn until the reborn process reaches `running`, so the reborn session
+ // is LIVE while `resetting` is still set — gating the audit on `resetting`
+ // would swallow the reborn session's own genuine startup error (the exact
+ // "healthy signal silenced" bug this plan attacks). And status can't
+ // separate them either: an old process killed while still `starting` and a
+ // reborn erroring while `starting` share the same status. Only session
+ // IDENTITY distinguishes them: `restartAgent` marks the OUTGOING session's
+ // state `superseded` before killing it, so its rattle is suppressed; the
+ // reborn session has a fresh state (`superseded=false`), so its real error
+ // surfaces. See plans/daemon-fsm-desync.md batch C (reader-C fix).
+ if (ev.kind === "error" && !sessionSuperseded) {
this.emitErrorAudit(agentId, "runtime", "runtime_error", ev.message ?? "Runtime error");
}
// Bot audit hook — thinking + non-Bash tool_call, no correlation.