Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

daemon: T3 — recovery-transition semantics into fsm-trace (trace-completeness charter)

Gus00658526376d
diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.ts
index df5e15387..0f0229f9a 100644
--- a/src/daemon/src/manager/managerPolicy.ts
+++ b/src/daemon/src/manager/managerPolicy.ts
@@ -215,6 +215,20 @@ export type ManagerEvent =
* only; `onExit` must not branch on it.
*/
spawnFailureReason?: string | null;
+ /**
+ * The FSM-level SEMANTIC of this exit, LAYERED on the physical fact above
+ * (T3, plans/daemon-trace-completeness-charter.md): `killed_stalled` (stall
+ * watchdog SIGKILL — same word as B1's turn_end-path `terminationCause`,
+ * one concept one token), `idle_stop` (voluntary idle-timeout hibernation),
+ * `force_exit` (stopping-stuck black-hole escape). Distinguishes a
+ * stall-kill-via-exit from a clean idle-stop (physically identical:
+ * reason=requested, signal set, abnormal=false) and labels the synthetic
+ * force_exit. FORENSICS ONLY: DELIBERATELY SEPARATE from `terminationCause`
+ * (which is turn_end-only and read by B2's rewake gate) so NO policy ever
+ * reads this — it can never leak into a rewake decision. Never overwrites
+ * the physical exit fields.
+ */
+ terminationSemantics?: string | null;
}
| { type: "tick"; nowMs: number }
/**
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index d5da219cc..edc6ab694 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -2284,6 +2284,148 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(cleanExit).toBeTruthy();
expect(cleanExit!.spawnFailureReason).toBeUndefined(); // no stale reason from spawn #1
});
+
+ // ---- T3: recovery-transition semantics into trace ----
+ // A stall-kill that exits WITHOUT a turn_end is physically identical to a
+ // clean idle-timeout stop (reason=requested, signal set, abnormal=false); a
+ // force_exit synthetic exit is bare. T3 layers a `terminationSemantics` label
+ // (killed_stalled / idle_stop / force_exit) ON TOP of the physical fact —
+ // never overwriting it, and read by NO policy (kept out of B2's gate).
+
+ it("T3 — terminate_stalled then its real exit records terminationSemantics=killed_stalled", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 0;
+ const recs: Record<string, unknown>[] = [];
+ const session = fakeSession();
+ const mgr = new AgentProcessManager({
+ driverFor: () => fakeDriver("codex"),
+ baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
+ sessionFactory: () => session,
+ now: () => now,
+ tickIntervalMs: 5,
+ staleThresholdMs: 100,
+ onFsmTransition: ((r: Record<string, unknown>) => recs.push(r)) as never,
+ });
+ mgr.start();
+ mgr.register("a1");
+ mgr.deliver("a1", { seq: 1, text: "hi" });
+ session.startResolver?.();
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ now = 200; // past staleThreshold → terminate_stalled (sets the semantic marker)
+ await vi.advanceTimersByTimeAsync(10);
+ // The killed process's real exit (via the exit listener, where state lives).
+ recs.length = 0;
+ session.fire("exit", { signal: "SIGKILL", reason: "requested" });
+
+ const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
+ expect(exitRec).toBeTruthy();
+ expect(exitRec!.terminationSemantics).toBe("killed_stalled");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("T3 — a VOLUNTARY idle-timeout stop's real exit records idle_stop, NOT killed_stalled (mis-label guard, Claudette #407)", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 0;
+ const recs: Record<string, unknown>[] = [];
+ const persistentDriver = {
+ ...fakeDriver("codex"),
+ lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,
+ } as Driver;
+ const session = fakeSession();
+ const mgr = new AgentProcessManager({
+ driverFor: () => persistentDriver,
+ baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
+ sessionFactory: () => session,
+ now: () => now,
+ tickIntervalMs: 5,
+ idleTimeoutMs: 50,
+ stoppingStuckThresholdMs: 1_000_000, // don't force_exit during the test
+ onFsmTransition: ((r: Record<string, unknown>) => recs.push(r)) as never,
+ });
+ mgr.start();
+ mgr.register("a1");
+ mgr.deliver("a1", { seq: 1, text: "hi" });
+ session.startResolver?.();
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ session.fire("runtime_event", { kind: "turn_end" }); // clean end → idle
+ now = 100; // past idleTimeout → voluntary stop (sets idle_stop, NOT killed_stalled)
+ await vi.advanceTimersByTimeAsync(10);
+ recs.length = 0;
+ session.fire("exit", { signal: "SIGTERM", reason: "requested" });
+
+ const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
+ expect(exitRec).toBeTruthy();
+ expect(exitRec!.terminationSemantics).toBe("idle_stop");
+ expect(exitRec!.terminationSemantics).not.toBe("killed_stalled");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("T3 — force_exit's synthetic exit records terminationSemantics=force_exit and does NOT pollute the physical fields (Claudette #407)", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 0;
+ const recs: Record<string, unknown>[] = [];
+ const persistentDriver = {
+ ...fakeDriver("codex"),
+ lifecycle: { kind: "persistent", start: "immediate", exit: "natural", inFlightWake: "queue" } as never,
+ } as Driver;
+ const session = fakeSession();
+ session.stop = vi.fn(); // swallow the stop so no real exit fires — force wedge
+ const mgr = new AgentProcessManager({
+ driverFor: () => persistentDriver,
+ baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),
+ sessionFactory: () => session,
+ now: () => now,
+ tickIntervalMs: 5,
+ idleTimeoutMs: 50,
+ stoppingStuckThresholdMs: 100,
+ onFsmTransition: ((r: Record<string, unknown>) => recs.push(r)) as never,
+ });
+ mgr.start();
+ mgr.register("a1");
+ mgr.deliver("a1", { seq: 1, text: "hi" });
+ session.startResolver?.();
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ session.fire("runtime_event", { kind: "turn_end" });
+ now = 100; // idle-timeout → stopping (stop swallowed, no exit)
+ await vi.advanceTimersByTimeAsync(10);
+ recs.length = 0;
+ now = 300; // stopping-stuck past threshold → force_exit synthetic exit
+ await vi.advanceTimersByTimeAsync(10);
+
+ const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
+ expect(exitRec).toBeTruthy();
+ expect(exitRec!.terminationSemantics).toBe("force_exit");
+ // Physical layer NOT polluted by the semantic label (synthetic exit has no
+ // real code/signal): abnormal false, code/signal null.
+ expect(exitRec!.abnormal).toBe(false);
+ expect(exitRec!.exitCode).toBeNull();
+ expect(exitRec!.exitSignal).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("T3 — a plain runtime exit (no recovery) carries NO terminationSemantics", () => {
+ const recs: Record<string, unknown>[] = [];
+ const { mgr, session } = makeWithTrace((r) => recs.push(r));
+ mgr.deliver("a1", { seq: 1, text: "hi" });
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ session.fire("exit", { code: 0, reason: "runtime_exit" });
+
+ const exitRec = recs.find((r) => r.event === "exit" && r.agentId === "a1");
+ expect(exitRec).toBeTruthy();
+ expect(exitRec!.terminationSemantics).toBeUndefined();
+ });
});
describe("T1 — abnormal-exit user audit stays gated (no nap-noise on deliberate kill)", () => {
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index ce747b0eb..a629d4700 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -215,6 +215,12 @@ export interface ManagerRuntimeOpts {
* clean exit in the trace. Absent on a normal exit.
*/
spawnFailureReason?: string | null;
+ /**
+ * FSM semantic of an `exit` (T3): killed_stalled / idle_stop / force_exit.
+ * Layered on the physical fact; forensics-only, no policy reads it. Absent on
+ * a plain runtime exit.
+ */
+ terminationSemantics?: string | null;
}) => void;
/**
* Optional context-timeline recorder. When provided, the manager logs each
@@ -612,6 +618,20 @@ export class AgentProcessManager {
* plans/daemon-fsm-desync.md batch F.
*/
pid: number | null;
+ /**
+ * Launch-failure reason (T2) recorded by reportSpawnFailure, read by the
+ * trailing exit dispatch → trace. Same value as the web audit. Null unless
+ * this spawn failed to establish. See daemon-trace-completeness-charter T2.
+ */
+ spawnFailureReason: string | null;
+ /**
+ * Recovery-transition SEMANTIC (T3): killed_stalled / idle_stop, set in the
+ * stop/terminate_stalled applyEffect branch (split by effect.type), read by
+ * the exit listener's dispatch → trace. force_exit sets its own semantic
+ * INLINE (state already deleted by then). Null on a plain runtime exit.
+ * Forensics-only, layered on the physical exit fact. See charter T3.
+ */
+ terminationSemantics: string | null;
}
>();
/**
@@ -1111,6 +1131,11 @@ export class AgentProcessManager {
...((event as { spawnFailureReason?: string | null }).spawnFailureReason != null
? { spawnFailureReason: (event as { spawnFailureReason?: string | null }).spawnFailureReason }
: {}),
+ // Recovery semantic (T3). Included only when present — a plain
+ // runtime exit has none.
+ ...((event as { terminationSemantics?: string | null }).terminationSemantics != null
+ ? { terminationSemantics: (event as { terminationSemantics?: string | null }).terminationSemantics }
+ : {}),
}
: {}),
});
@@ -1213,6 +1238,21 @@ export class AgentProcessManager {
if (effect.type === "terminate_stalled") {
this.nonCleanEndMarker.set(effect.agentId, { cause: "killed_stalled" });
}
+ // T3: record the recovery SEMANTIC of this stop on the per-spawn state so
+ // the trailing exit (via the exit listener, where state is still alive)
+ // carries it into the trace. Split by effect.type — the two share this
+ // branch but mean opposite things: `terminate_stalled` = stall watchdog
+ // SIGKILL (killed_stalled, same word as B1's turn_end-path cause — one
+ // concept, one token); voluntary `stop` = idle-timeout hibernation
+ // (idle_stop). Conflating them would re-create the "stall-kill
+ // impersonates idle" bug in the trace. Purely additive semantic layer
+ // over the physical exit fact (exitSignal/etc), never overwriting it —
+ // and NOTHING reads it for policy (kept out of B2's rewake gate, which
+ // reads terminationCause on turn_end only). See
+ // plans/daemon-trace-completeness-charter.md T3.
+ if (spawnState) {
+ spawnState.terminationSemantics = effect.type === "terminate_stalled" ? "killed_stalled" : "idle_stop";
+ }
this.logSessionEnded(effect.agentId, effect.type === "stop" ? "stopped" : "terminate_stalled");
this.opts.onAgentLocallyStopped?.({ agentId: effect.agentId, reason: effect.type });
break;
@@ -1266,7 +1306,12 @@ export class AgentProcessManager {
// (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 });
+ // T3: `terminationSemantics` is set INLINE here, not via the state
+ // marker — activeSpawnState was already deleted at (2) above, so the
+ // marker is unreadable by the time this synthetic exit dispatches.
+ // Labels this as the stopping-stuck black-hole escape (force_exit),
+ // otherwise the synthetic exit is a bare, unexplained exit in trace.
+ this.dispatch({ type: "exit", agentId: effect.agentId, terminationSemantics: "force_exit" });
break;
}
case "gated_hold":
@@ -1372,7 +1417,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, superseded: false, pid: null as number | null, spawnFailureReason: null as string | null };
+ const state = { hasEstablished: false, hasReportedSpawnFailure: false, suppressExitLog: false, handshakeTimer: null as ReturnType<typeof setTimeout> | null, torndown: false, superseded: false, pid: null as number | null, spawnFailureReason: null as string | null, terminationSemantics: null as string | null };
this.activeSpawnState.set(agentId, state);
const clearHandshakeTimer = () => {
if (state.handshakeTimer) {
@@ -1513,7 +1558,7 @@ export class AgentProcessManager {
// from a stale/superseded spawn must NOT drop a fresh session's marker.
this.nonCleanEndMarker.delete(agentId);
}
- this.dispatch({ type: "exit", agentId, exitCode, exitSignal, abnormal, spawnFailureReason: state.spawnFailureReason });
+ this.dispatch({ type: "exit", agentId, exitCode, exitSignal, abnormal, spawnFailureReason: state.spawnFailureReason, terminationSemantics: state.terminationSemantics });
});
// Stamp the wake-prompt timestamp AT the last mile — right before the