Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(daemon): trace daemon-owned turn spans

Guse7abf0fb0535
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index ea5de1e26..81f3df5ee 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -25,12 +25,12 @@
import { homedir } from "os";
import { appendFileSync, mkdirSync } from "node:fs";
import { createRotatingFileSink } from "../util/rotatingFileSink.js";
-import { createTraceSampler } from "../util/traceSampler.js";
+import { createTraceSampler, DEFAULT_TRACE_FILE_MAX_BYTES } from "../util/traceSampler.js";
import { writeStatusFile } from "../util/statusFile.js";
import { WsControlChannel } from "../server/wsControlChannel.js";
import { CredentialBroker, startCredentialProxy } from "../credentials/index.js";
import { AgentProcessManager, AgentRouter, createTypingScopeTracker } from "../manager/index.js";
-import type { TypingScopeTracker } from "../manager/index.js";
+import type { ManagerTraceRecord, TypingScopeTracker } from "../manager/index.js";
import { UnknownBotError, BotEnrollFailedError, UnknownRuntimeError } from "../manager/agentRouter.js";
import { createTimelineRecorder, sweepTimelineHistory } from "../timeline/index.js";
import { resolveAlookCliPathWithFallback } from "../discovery.js";
@@ -44,17 +44,7 @@ import { formatHandle } from "@alook/shared/lib/discriminator";
// Cold-start warmup backoff schedule (ms).
const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;
const WARMUP_CEILING_MS = 30_000;
-/**
- * Per-file cap for the DEFAULT-ON bounded FSM trace (batch E1). The rotating
- * sink keeps the active file + one rotated generation, so total on-disk ≈
- * 2×this ≈ 16MB. RAW row rate at N≈8 agents is ~74% unchanged-state tick noise
- * → only ~2h of history unsampled; the T4 heartbeat sampler (createTraceSampler)
- * folds that noise so TRANSITION rows survive ≥12h @ N=8 in the same budget.
- * (≥12h is @ N=8 — write rate scales with agent count, so a much larger fleet
- * warrants revisiting this cap.) The `ALOOK_FSM_TRACE` override is unbounded and
- * unsampled (full-fidelity deep dives).
- */
-const FSM_TRACE_MAX_BYTES = 8 * 1024 * 1024;
+/** Per-file cap for opt-in raw runtime stdout trace (independent of FSM trace). */
const RUNTIME_RAW_TRACE_MAX_BYTES = 8 * 1024 * 1024;
export const RUNTIME_RAW_TRACE_AGENT_IDS_ENV = "ALOOK_RUNTIME_RAW_TRACE_AGENT_IDS";
/** How often the daemon rewrites the `daemon status` snapshot file (batch E2). */
@@ -757,7 +747,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
const overridePath = process.env.ALOOK_FSM_TRACE;
if (overridePath) {
return {
- onFsmTransition: (rec: Record<string, unknown>) => {
+ onFsmTransition: (rec: ManagerTraceRecord) => {
try {
appendFileSync(overridePath, JSON.stringify(rec) + "\n");
} catch {
@@ -774,17 +764,18 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
}
const sink = createRotatingFileSink(
`${opts.fsmTraceDir}/fsm-trace.jsonl`,
- FSM_TRACE_MAX_BYTES,
+ DEFAULT_TRACE_FILE_MAX_BYTES,
);
// Heartbeat sampler between the manager and the sink (batch T4): folds
// redundant unchanged-state ticks + progress/runtime_signal noise so the
- // bounded file retains transition rows ≥12h (@ N=8) instead of ~2h.
+ // bounded two-generation file retains ~16.73h at the executable N=8
+ // operational envelope.
// Transitions and watchdog-fired (effects-carrying) frames are never
// dropped. The ALOOK_FSM_TRACE override above is unbounded → unsampled,
// for full-fidelity deep dives.
const sampler = createTraceSampler((rec) => sink.write(JSON.stringify(rec)));
return {
- onFsmTransition: (rec: Record<string, unknown>) => sampler.offer(rec),
+ onFsmTransition: (rec: ManagerTraceRecord) => sampler.offer(rec),
};
}
return {};
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index 53803288a..c6941b1bc 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -14,6 +14,7 @@ import {
} from "./managerRuntime.js";
import { SdkRuntimeSession, type SdkSessionHandle } from "../runtime/sdkRuntimeSession.js";
import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
+import type { RuntimeConfig } from "../runtimeConfig.js";
import type { Logger } from "../logger.js";
/** Stub logger — records calls per level for assertions. */
@@ -2041,7 +2042,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
// distinguishable from a clean nap/idle (red line 7). B1 only RECORDS it —
// onTurnEnd behavior is unchanged (verified in the "clean" case below).
- it("a mid-turn error then turn_end stamps endReason=errored + terminationCause=runtime_error + errorDetail (red line 6/7)", () => {
+ it("a mid-turn error then turn_end stamps fixed metadata but drops free-text errorDetail", () => {
const recs: Record<string, unknown>[] = [];
const { mgr, session } = makeWithTrace((r) => recs.push(r));
mgr.deliver("a1", { seq: 1, text: "hi" });
@@ -2055,7 +2056,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
expect(turnEnd).toBeTruthy();
expect(turnEnd!.endReason).toBe("errored");
expect(turnEnd!.terminationCause).toBe("runtime_error");
- expect(turnEnd!.errorDetail).toBe("boom: model overloaded");
+ expect(turnEnd!.errorDetail).toBeUndefined();
});
it("a CLEAN turn_end (no preceding error/kill) carries no endReason/terminationCause/errorDetail (byte-for-byte the old row)", () => {
@@ -2616,3 +2617,654 @@ describe("T1 — abnormal-exit user audit stays gated (no nap-noise on deliberat
}
});
});
+
+type B1TraceRow = Record<string, unknown>;
+
+const B1_RUNTIME_CONFIG: RuntimeConfig = {
+ version: 1,
+ runtime: "codex",
+ model: { kind: "named", name: "test-model" },
+ mode: { kind: "default" },
+};
+
+function b1PersistentDriver(): Driver {
+ return {
+ ...fakeDriver("codex"),
+ lifecycle: {
+ kind: "persistent",
+ start: "immediate",
+ exit: "natural",
+ inFlightWake: "queue",
+ stdin: "direct",
+ } as never,
+ } as Driver;
+}
+
+function b1GatedDriver(): Driver {
+ return {
+ ...fakeDriver("codex"),
+ lifecycle: {
+ kind: "persistent",
+ start: "immediate",
+ exit: "natural",
+ inFlightWake: "queue",
+ stdin: "gated",
+ } as never,
+ } as Driver;
+}
+
+function b1Session(order: string[], name = "s"): FakeSession {
+ const session = fakeSession();
+ session.start = vi.fn(async (input: { text: string; sessionId?: string }) => {
+ order.push(`${name}:start:${input.text}`);
+ });
+ session.send = vi.fn((input: { text: string; mode: "busy" | "idle" }) => {
+ order.push(`${name}:send:${input.mode}:${input.text}`);
+ });
+ session.stop = vi.fn((opts?: { reason?: string }) => {
+ order.push(`${name}:stop:${opts?.reason ?? ""}`);
+ });
+ return session;
+}
+
+function b1Manager(opts: {
+ trace?: (row: B1TraceRow) => void;
+ sessions?: FakeSession[];
+ driver?: Driver;
+ launchId?: string | null;
+ now?: () => number;
+ handshakeTimeoutMs?: number;
+ tickIntervalMs?: number;
+ staleThresholdMs?: number;
+ stoppingStuckThresholdMs?: number;
+ onRuntimeSpawnFailed?: (runtimeId: string, reason: string) => void;
+} = {}) {
+ const sessions = opts.sessions ?? [b1Session([])];
+ let index = 0;
+ const mgr = new AgentProcessManager({
+ driverFor: () => opts.driver ?? b1PersistentDriver(),
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: () => sessions[index++]!,
+ onFsmTransition: opts.trace as never,
+ now: opts.now,
+ ...(opts.handshakeTimeoutMs !== undefined ? { handshakeTimeoutMs: opts.handshakeTimeoutMs } : {}),
+ ...(opts.tickIntervalMs !== undefined ? { tickIntervalMs: opts.tickIntervalMs } : {}),
+ ...(opts.staleThresholdMs !== undefined ? { staleThresholdMs: opts.staleThresholdMs } : {}),
+ ...(opts.stoppingStuckThresholdMs !== undefined
+ ? { stoppingStuckThresholdMs: opts.stoppingStuckThresholdMs }
+ : {}),
+ onRuntimeSpawnFailed: opts.onRuntimeSpawnFailed,
+ });
+ if (opts.launchId === null) mgr.register("a1");
+ else mgr.register("a1", { launchId: opts.launchId ?? "launch-a" });
+ return { mgr, sessions };
+}
+
+function b1SpanRows(rows: B1TraceRow[], event?: "turn_begin" | "turn_end" | "turn_abort"): B1TraceRow[] {
+ return rows.filter((row) => row.recordKind === "turn_span" && (event === undefined || row.event === event));
+}
+
+function b1CallProjection(session: FakeSession): Record<"start" | "send" | "stop", unknown[][]> {
+ const callsOf = (fn: unknown): unknown[][] =>
+ (fn as { mock: { calls: unknown[][] } }).mock.calls.map((args) => [...args]);
+ return {
+ start: callsOf(session.start),
+ send: callsOf(session.send),
+ stop: callsOf(session.stop),
+ };
+}
+
+function b1FsmEffectProjection(rows: B1TraceRow[]): Array<{
+ agentId: unknown;
+ event: unknown;
+ effects: unknown;
+}> {
+ return rows
+ // Pre-B1 rows are unstamped; B1 stamps them `fsm`. In either shape, every
+ // non-span trace row belongs to the FSM projection under comparison.
+ .filter((row) => row.recordKind !== "turn_span")
+ .map((row) => ({ agentId: row.agentId, event: row.event, effects: row.effects }));
+}
+
+describe("B1 red gate — daemon-owned turn span lifecycle", () => {
+ it("opens at the start/send last mile, reuses busy, increments persistent turn ordinal, and closes before the next begin", async () => {
+ const order: string[] = [];
+ const rows: B1TraceRow[] = [];
+ const session = b1Session(order);
+ const { mgr } = b1Manager({
+ sessions: [session],
+ trace: (row) => {
+ rows.push(row);
+ if (row.recordKind === "turn_span") order.push(`trace:${String(row.event)}:${String(row.turnOrdinal)}`);
+ },
+ });
+
+ mgr.deliver("a1", { seq: 1, text: "first" });
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "session-a" });
+ mgr.deliver("a1", { seq: 2, text: "busy" });
+ session.fire("runtime_event", { kind: "turn_end" });
+ mgr.deliver("a1", { seq: 3, text: "idle-second" });
+ session.fire("runtime_event", { kind: "turn_end" });
+
+ const begins = b1SpanRows(rows, "turn_begin");
+ const ends = b1SpanRows(rows, "turn_end");
+ expect(begins).toHaveLength(2);
+ expect(ends).toHaveLength(2);
+ expect(begins.map((row) => row.traceTurnId)).toEqual(["launch-a:1", "launch-a:2"]);
+ expect(begins.map((row) => row.turnOrdinal)).toEqual([1, 2]);
+ expect(rows.filter((row) => row.event === "runtime_signal" && row.traceTurnId === "launch-a:1").length).toBeGreaterThan(0);
+ expect(order.indexOf("trace:turn_begin:1")).toBeLessThan(order.indexOf("s:start:first"));
+ expect(order.indexOf("trace:turn_end:1")).toBeLessThan(order.indexOf("trace:turn_begin:2"));
+ expect(order.filter((entry) => entry.includes("send:busy:busy"))).toHaveLength(1);
+ });
+
+ it("closes the old per-turn span inside dispatch before a queued spawn effect opens the replacement", async () => {
+ const order: string[] = [];
+ const rows: B1TraceRow[] = [];
+ const first = b1Session(order, "a");
+ const second = b1Session(order, "b");
+ const { mgr } = b1Manager({
+ sessions: [first, second],
+ driver: fakeDriver("codex"),
+ trace: (row) => {
+ rows.push(row);
+ if (row.recordKind === "turn_span") order.push(`trace:${String(row.event)}:${String(row.daemonTurnOrdinal)}`);
+ },
+ });
+
+ mgr.deliver("a1", { seq: 1, text: "first" });
+ await Promise.resolve();
+ mgr.deliver("a1", { seq: 2, text: "queued" });
+ first.fire("runtime_event", { kind: "turn_end" });
+ first.fire("exit", { code: 0, reason: "runtime_exit" });
+ await Promise.resolve();
+
+ const begins = b1SpanRows(rows, "turn_begin");
+ const ends = b1SpanRows(rows, "turn_end");
+ expect(begins).toHaveLength(2);
+ expect(ends).toHaveLength(1);
+ expect(order.indexOf(`trace:turn_end:${String(ends[0]!.daemonTurnOrdinal)}`)).toBeLessThan(
+ order.indexOf(`trace:turn_begin:${String(begins[1]!.daemonTurnOrdinal)}`),
+ );
+ expect(order.filter((entry) => entry.startsWith("b:start:"))).toHaveLength(1);
+ });
+
+ it("uses the process nonce fallback only when launchId is absent", () => {
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({ sessions: [session], launchId: null, trace: (row) => rows.push(row) });
+ mgr.deliver("a1", { seq: 1, text: "no launch" });
+
+ const begin = b1SpanRows(rows, "turn_begin")[0];
+ expect(begin).toBeTruthy();
+ expect(begin!.launchIdSnapshot).toBeNull();
+ expect(begin!.traceTurnId).toMatch(/^[0-9a-f-]+:1$/);
+ expect(begin!.daemonTurnOrdinal).toBe(1);
+ expect(begin!.spawnOrdinal).toBe(1);
+ });
+
+ it("records clean, runtime-error, and unknown turn-end outcomes with fixed semantics", async () => {
+ const cleanRows: B1TraceRow[] = [];
+ const cleanSession = b1Session([]);
+ const { mgr: cleanManager } = b1Manager({
+ sessions: [cleanSession],
+ trace: (row) => cleanRows.push(row),
+ });
+ cleanManager.deliver("a1", { seq: 1, text: "clean" });
+ await Promise.resolve();
+ cleanSession.fire("runtime_event", { kind: "session_init", sessionId: "clean-session" });
+ cleanSession.fire("runtime_event", { kind: "turn_end" });
+
+ const cleanEnd = b1SpanRows(cleanRows, "turn_end")[0];
+ expect(cleanEnd).toBeTruthy();
+ expect(cleanEnd!.outcome).toBe("clean");
+ expect(cleanEnd!.terminationCause).toBeUndefined();
+
+ const errorRows: B1TraceRow[] = [];
+ const errorSession = b1Session([]);
+ const { mgr: errorManager } = b1Manager({
+ sessions: [errorSession],
+ trace: (row) => errorRows.push(row),
+ });
+ errorManager.deliver("a1", { seq: 1, text: "error" });
+ await Promise.resolve();
+ errorSession.fire("runtime_event", { kind: "session_init", sessionId: "error-session" });
+ errorSession.fire("runtime_event", { kind: "error", message: "HOSTILE_RUNTIME_DETAIL_220b" });
+ errorSession.fire("runtime_event", { kind: "turn_end" });
+
+ const errorEnd = b1SpanRows(errorRows, "turn_end")[0];
+ expect(errorEnd).toBeTruthy();
+ expect(errorEnd!.outcome).toBe("errored");
+ expect(errorEnd!.terminationCause).toBe("runtime_error");
+
+ const unknownRows: B1TraceRow[] = [];
+ const unknownSession = b1Session([]);
+ const { mgr: unknownManager } = b1Manager({
+ sessions: [unknownSession],
+ trace: (row) => unknownRows.push(row),
+ });
+ unknownManager.deliver("a1", { seq: 1, text: "unknown" });
+ await Promise.resolve();
+ (unknownManager as unknown as { dispatch(event: unknown): void }).dispatch({
+ type: "turn_end",
+ agentId: "a1",
+ nowMs: 1,
+ endReason: "errored",
+ terminationCause: "HOSTILE_UNKNOWN_CAUSE_832a",
+ });
+
+ const unknownEnd = b1SpanRows(unknownRows, "turn_end")[0];
+ expect(unknownEnd).toBeTruthy();
+ expect(unknownEnd!.outcome).toBe("errored");
+ expect(unknownEnd!.terminationCause).toBe("other");
+ expect(JSON.stringify(unknownRows)).not.toContain("HOSTILE_UNKNOWN_CAUSE_832a");
+ });
+
+ it("annotates active tick/progress/runtime_signal rows and clears every later row after close", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 1_000;
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({
+ sessions: [session],
+ trace: (row) => rows.push(row),
+ now: () => now,
+ tickIntervalMs: 5,
+ });
+ mgr.start();
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ now = 1_005;
+ await vi.advanceTimersByTimeAsync(5);
+
+ const begin = b1SpanRows(rows, "turn_begin")[0];
+ expect(begin).toBeTruthy();
+ const activeId = begin!.traceTurnId;
+ for (const event of ["progress", "runtime_signal", "tick"]) {
+ expect(rows.some((row) => row.event === event && row.traceTurnId === activeId)).toBe(true);
+ }
+
+ session.fire("runtime_event", { kind: "turn_end" });
+ const close = b1SpanRows(rows, "turn_end")[0];
+ expect(close!.traceTurnId).toBe(activeId);
+ rows.length = 0;
+
+ now = 1_010;
+ await vi.advanceTimersByTimeAsync(5);
+ session.fire("runtime_event", { kind: "internal_progress" });
+ session.fire("exit", { code: 0, reason: "runtime_exit" });
+ expect(rows.some((row) => ["tick", "runtime_signal", "exit"].includes(String(row.event)))).toBe(true);
+ expect(rows.every((row) => row.traceTurnId === undefined)).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("B1 red gate — strict read-only trace sink", () => {
+ async function scenario(trace?: (row: B1TraceRow) => void) {
+ const calls: string[] = [];
+ const session = b1Session(calls);
+ const { mgr } = b1Manager({ sessions: [session], trace, now: () => 1_700_000_000_000 });
+ mgr.deliver("a1", { seq: 1, text: "one" });
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ session.fire("runtime_event", { kind: "turn_end" });
+ mgr.deliver("a1", { seq: 2, text: "two" });
+ await mgr.stop("a1");
+ return { state: mgr.snapshot(), calls, runtimeCalls: b1CallProjection(session) };
+ }
+
+ it("absent, collecting, and throwing sinks preserve identical state and runtime calls", async () => {
+ const absent = await scenario();
+ const collected: B1TraceRow[] = [];
+ const collecting = await scenario((row) => collected.push(row));
+ const throwAfterRecording: B1TraceRow[] = [];
+ let throwing: Awaited<ReturnType<typeof scenario>> | undefined;
+ let thrown: unknown;
+ try {
+ throwing = await scenario((row) => {
+ throwAfterRecording.push(row);
+ throw new Error("trace sink exploded");
+ });
+ } catch (error) {
+ thrown = error;
+ }
+
+ const collectingEffects = b1FsmEffectProjection(collected);
+ const throwingEffects = b1FsmEffectProjection(throwAfterRecording);
+ expect(collectingEffects.length).toBeGreaterThan(0);
+ expect(throwingEffects).toEqual(collectingEffects);
+ expect(thrown).toBeUndefined();
+ expect(collecting).toEqual(absent);
+ expect(throwing).toEqual(absent);
+ expect(absent.runtimeCalls.start).toHaveLength(1);
+ expect(absent.runtimeCalls.send).toHaveLength(1);
+ expect(absent.runtimeCalls.stop).toHaveLength(1);
+ expect(b1SpanRows(collected, "turn_begin").length).toBeGreaterThan(0);
+ });
+});
+
+describe("B1 red gate — exact-once terminal matrix", () => {
+ const requestedCases: Array<{
+ name: string;
+ cause: string;
+ run: (mgr: AgentProcessManager) => Promise<void>;
+ }> = [
+ { name: "requested stop", cause: "requested_stop", run: (mgr) => mgr.stop("a1") },
+ { name: "shutdown", cause: "shutdown", run: (mgr) => mgr.stopAll() },
+ {
+ name: "reset",
+ cause: "reset",
+ run: (mgr) => mgr.resetSession("a1", { runtimeConfig: B1_RUNTIME_CONFIG, launchId: "launch-b", rewakePrompt: "reset" }),
+ },
+ {
+ name: "nap",
+ cause: "nap",
+ run: (mgr) => mgr.resetSession("a1", { runtimeConfig: B1_RUNTIME_CONFIG, launchId: "launch-b", rewakePrompt: "nap", barrierType: "nap" }),
+ },
+ {
+ name: "model switch",
+ cause: "model_switch",
+ run: (mgr) => mgr.switchModel("a1", { runtimeConfig: B1_RUNTIME_CONFIG, launchId: "launch-b", rewakePrompt: "switch" }),
+ },
+ ];
+
+ for (const terminal of requestedCases) {
+ it(`${terminal.name} aborts the active span once before the existing stop path`, async () => {
+ const rows: B1TraceRow[] = [];
+ const order: string[] = [];
+ const session = b1Session(order);
+ const { mgr } = b1Manager({
+ sessions: [session],
+ trace: (row) => {
+ rows.push(row);
+ if (row.recordKind === "turn_span" && row.event === "turn_abort") {
+ order.push(`trace:turn_abort:${String(row.abortCause)}`);
+ }
+ },
+ });
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ await Promise.resolve();
+ await terminal.run(mgr);
+
+ const aborts = b1SpanRows(rows, "turn_abort");
+ expect(aborts).toHaveLength(1);
+ expect(aborts[0]!.abortCause).toBe(terminal.cause);
+ const abortIndex = order.indexOf(`trace:turn_abort:${terminal.cause}`);
+ const stopIndex = order.findIndex((entry) => entry.startsWith("s:stop:"));
+ expect(abortIndex).toBeGreaterThan(-1);
+ expect(stopIndex).toBeGreaterThan(-1);
+ expect(abortIndex).toBeLessThan(stopIndex);
+ });
+ }
+
+ it("physical exit aborts once and its duplicate late exit cannot close again", () => {
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ session.fire("exit", { signal: "SIGKILL", reason: "runtime_exit" });
+ session.fire("exit", { signal: "SIGKILL", reason: "runtime_exit" });
+
+ const aborts = b1SpanRows(rows, "turn_abort");
+ expect(aborts).toHaveLength(1);
+ expect(aborts[0]!.abortCause).toBe("physical_exit");
+ });
+
+ it("start synchronous throw aborts once and rethrows the exact error", () => {
+ const rows: B1TraceRow[] = [];
+ const error = new Error("unique-start-sync-secret");
+ const session = b1Session([]);
+ session.start = vi.fn(() => {
+ throw error;
+ });
+ const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
+
+ expect(() => mgr.deliver("a1", { seq: 1, text: "active" })).toThrow(error);
+ const aborts = b1SpanRows(rows, "turn_abort");
+ expect(aborts).toHaveLength(1);
+ expect(aborts[0]!.abortCause).toBe("start_threw");
+ });
+
+ it("start promise rejection closes in the existing rejection branch exactly once", async () => {
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ session.start = vi.fn(() => Promise.reject(new Error("unique-start-reject-secret")));
+ const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const aborts = b1SpanRows(rows, "turn_abort");
+ expect(aborts).toHaveLength(1);
+ expect(aborts[0]!.abortCause).toBe("start_rejected");
+ });
+
+ for (const mode of ["idle", "busy"] as const) {
+ it(`${mode} send synchronous throw aborts once and rethrows without another send`, async () => {
+ const rows: B1TraceRow[] = [];
+ const error = new Error(`unique-send-${mode}-secret`);
+ const session = b1Session([]);
+ const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
+ mgr.deliver("a1", { seq: 1, text: "first" });
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ if (mode === "idle") session.fire("runtime_event", { kind: "turn_end" });
+ session.send = vi.fn(() => {
+ throw error;
+ });
+
+ expect(() => mgr.deliver("a1", { seq: 2, text: "throw" })).toThrow(error);
+ expect(session.send).toHaveBeenCalledTimes(1);
+ const aborts = b1SpanRows(rows, "turn_abort");
+ expect(aborts.length).toBeGreaterThan(0);
+ expect(aborts.at(-1)!.abortCause).toBe("send_threw");
+ expect(aborts.filter((row) => row.abortCause === "send_threw")).toHaveLength(1);
+ });
+ }
+
+ it("handshake timeout aborts once before its synthetic exit", async () => {
+ vi.useFakeTimers();
+ try {
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({
+ sessions: [session],
+ trace: (row) => rows.push(row),
+ handshakeTimeoutMs: 100,
+ });
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(101);
+
+ const aborts = b1SpanRows(rows, "turn_abort");
+ expect(aborts).toHaveLength(1);
+ expect(aborts[0]!.abortCause).toBe("handshake_timeout");
+ const exit = rows.find((row) => row.recordKind === "fsm" && row.event === "exit");
+ expect(exit!.traceTurnId).toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("terminate_stalled then force_exit emits one abort total", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 0;
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ session.stop = vi.fn();
+ const { mgr } = b1Manager({
+ sessions: [session],
+ driver: fakeDriver("codex"),
+ trace: (row) => rows.push(row),
+ now: () => now,
+ tickIntervalMs: 5,
+ staleThresholdMs: 50,
+ stoppingStuckThresholdMs: 50,
+ });
+ mgr.start();
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ now = 100;
+ await vi.advanceTimersByTimeAsync(10);
+ now = 200;
+ await vi.advanceTimersByTimeAsync(60);
+
+ const aborts = b1SpanRows(rows, "turn_abort");
+ expect(aborts).toHaveLength(1);
+ expect(aborts[0]!.abortCause).toBe("terminate_stalled");
+ expect(rows.some((row) => Array.isArray(row.effects) && (row.effects as string[]).includes("force_exit"))).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("B1 red gate — stale owner isolation", () => {
+ it("old launch callbacks and a late deferred start rejection never borrow or close the replacement span", async () => {
+ const rows: B1TraceRow[] = [];
+ const first = fakeSession();
+ const second = b1Session([], "b");
+ const { mgr } = b1Manager({ sessions: [first, second], trace: (row) => rows.push(row), launchId: "launch-a" });
+ mgr.deliver("a1", { seq: 1, text: "first" });
+ await mgr.resetSession("a1", { runtimeConfig: B1_RUNTIME_CONFIG, launchId: "launch-b", rewakePrompt: "reborn" });
+ first.fire("exit", { signal: "SIGTERM", reason: "requested" });
+ await Promise.resolve();
+
+ const begins = b1SpanRows(rows, "turn_begin");
+ expect(begins).toHaveLength(2);
+ const replacementId = begins[1]!.traceTurnId;
+ rows.length = 0;
+ first.fire("runtime_event", { kind: "text", text: "late old output" });
+ first.fire("runtime_event", { kind: "turn_end" });
+ first.startRejector!(new Error("HOSTILE_LATE_START_REJECTION_19cf"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const staleRows = [...rows];
+ expect(
+ staleRows.every((row) => row.traceTurnId !== replacementId),
+ JSON.stringify(staleRows),
+ ).toBe(true);
+ expect(
+ b1SpanRows(rows).filter(
+ (row) => row.traceTurnId === replacementId && (row.event === "turn_end" || row.event === "turn_abort"),
+ ),
+ ).toHaveLength(0);
+ expect(JSON.stringify(rows)).not.toContain("HOSTILE_LATE_START_REJECTION_19cf");
+
+ second.fire("runtime_event", { kind: "turn_end" });
+ const replacementCloses = b1SpanRows(rows).filter((row) => row.traceTurnId === replacementId && (row.event === "turn_end" || row.event === "turn_abort"));
+ expect(replacementCloses).toHaveLength(1);
+ });
+});
+
+describe("B1 red gate — privacy normalization and coherent time", () => {
+ it("drops hostile prompt/error detail, normalizes unknown spawn reason, and preserves the audit callback input", () => {
+ const rows: B1TraceRow[] = [];
+ const onRuntimeSpawnFailed = vi.fn();
+ const session = b1Session([]);
+ const { mgr } = b1Manager({
+ sessions: [session],
+ trace: (row) => rows.push(row),
+ onRuntimeSpawnFailed,
+ });
+ const prompt = "UNIQUE_PROMPT_SECRET_8f26";
+ const hostileCode = "UNIQUE_RAW_REASON_SECRET_71ac";
+ mgr.deliver("a1", { seq: 1, text: prompt });
+ session.fire("error", { code: hostileCode, message: "UNIQUE_DETAIL_SECRET_5d44" });
+ session.fire("exit");
+
+ const serialized = JSON.stringify(rows);
+ expect(serialized).not.toContain(prompt);
+ expect(serialized).not.toContain(hostileCode);
+ expect(serialized).not.toContain("UNIQUE_DETAIL_SECRET_5d44");
+ expect(serialized).not.toContain("errorDetail");
+ const exit = rows.find((row) => row.event === "exit");
+ expect(exit!.spawnFailureReason).toBe("other");
+ expect(onRuntimeSpawnFailed).toHaveBeenCalledWith("codex", hostileCode);
+ });
+
+ it("drops send/response/thinking/tool and gated-hold detail at every producer boundary", async () => {
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({
+ sessions: [session],
+ driver: b1GatedDriver(),
+ trace: (row) => rows.push(row),
+ });
+ const secrets = {
+ prompt: "HOSTILE_INITIAL_PROMPT_ea31",
+ send: "HOSTILE_SEND_TEXT_581b",
+ response: "HOSTILE_RESPONSE_TEXT_98ac",
+ thinking: "HOSTILE_THINKING_TEXT_1d7f",
+ tool: "HOSTILE_TOOL_PAYLOAD_6c23",
+ recentEvent: "HOSTILE_RECENT_EVENT_47bd",
+ };
+
+ mgr.deliver("a1", { seq: 1, text: secrets.prompt });
+ await Promise.resolve();
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ session.fire("runtime_event", { kind: "text", text: secrets.response });
+ session.fire("runtime_event", { kind: "thinking", text: secrets.thinking });
+ session.fire("runtime_event", {
+ kind: "tool_call",
+ name: "Read",
+ input: { file_path: secrets.tool, nested: { raw: secrets.tool } },
+ });
+ session.fire("runtime_event", { kind: secrets.recentEvent, text: secrets.response });
+ mgr.deliver("a1", { seq: 2, text: secrets.send });
+
+ expect(rows.some((row) => Array.isArray(row.effects) && (row.effects as string[]).includes("gated_hold"))).toBe(true);
+ const serialized = JSON.stringify(rows);
+ for (const secret of Object.values(secrets)) expect(serialized).not.toContain(secret);
+ expect(serialized).not.toContain("mid_turn_wake");
+ expect(serialized).not.toContain("recentEvents");
+ });
+
+ it("normalizes unknown termination semantics without leaking the raw token", async () => {
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({ sessions: [session], trace: (row) => rows.push(row) });
+ mgr.deliver("a1", { seq: 1, text: "active" });
+ await Promise.resolve();
+ (mgr as unknown as { dispatch(event: unknown): void }).dispatch({
+ type: "exit",
+ agentId: "a1",
+ terminationSemantics: "HOSTILE_TERMINATION_SEMANTIC_03cc",
+ });
+
+ const exit = rows.find((row) => row.recordKind === "fsm" && row.event === "exit");
+ expect(exit).toBeTruthy();
+ expect(exit!.terminationSemantics).toBe("other");
+ expect(JSON.stringify(rows)).not.toContain("HOSTILE_TERMINATION_SEMANTIC_03cc");
+ });
+
+ it("derives every row timeIso from that row's single nowMs sample", () => {
+ let tick = 0;
+ const rows: B1TraceRow[] = [];
+ const session = b1Session([]);
+ const { mgr } = b1Manager({
+ sessions: [session],
+ trace: (row) => rows.push(row),
+ now: () => Date.UTC(2026, 0, 1) + tick++,
+ });
+ mgr.deliver("a1", { seq: 1, text: "time" });
+ session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
+ session.fire("runtime_event", { kind: "turn_end" });
+
+ expect(rows.length).toBeGreaterThan(0);
+ for (const row of rows) {
+ expect(row.timeIso).toBe(new Date(row.nowMs as number).toISOString());
+ }
+ });
+});
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index 32db35a81..138c65a4e 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -33,6 +33,7 @@ import { SdkManagedSession } from "../runtime/sdkManagedSession.js";
import { DEFAULT_CLI_CONFIG } from "../drivers/cliTransport.js";
import { createLogger, type Logger } from "../logger.js";
import { nowLocalISO } from "../util/localTime.js";
+import { randomUUID } from "node:crypto";
/**
* Derived activity state reported up the control plane — NOT a raw passthrough
@@ -51,6 +52,155 @@ export interface ManagedSession {
readonly currentSessionId: string | null;
}
+type TraceTerminationCause = "runtime_error" | "killed_stalled" | "other";
+type TraceSpawnFailureReason = "ENOENT" | "handshake_timeout" | "pre_handshake_exit" | "spawn_threw" | "other";
+type TraceTerminationSemantics = "killed_stalled" | "idle_stop" | "force_exit" | "other";
+type TraceAbortCause =
+ | "start_threw"
+ | "start_rejected"
+ | "send_threw"
+ | "spawn_failure"
+ | "handshake_timeout"
+ | "reset"
+ | "nap"
+ | "model_switch"
+ | "requested_stop"
+ | "shutdown"
+ | "physical_exit"
+ | "terminate_stalled"
+ | "force_exit"
+ | "other";
+
+interface ActiveTurnSpan {
+ traceTurnId: string;
+ daemonTurnOrdinal: number;
+ spawnOrdinal: number;
+ turnOrdinal: number;
+ launchIdSnapshot: string | null;
+}
+
+interface ActiveSpawnState {
+ agentId: string;
+ session: ManagedSession;
+ hasEstablished: boolean;
+ hasReportedSpawnFailure: boolean;
+ suppressExitLog: boolean;
+ handshakeTimer: ReturnType<typeof setTimeout> | null;
+ torndown: boolean;
+ superseded: boolean;
+ pid: number | null;
+ spawnFailureReason: string | null;
+ terminationSemantics: string | null;
+ spawnOrdinal: number;
+ launchIdSnapshot: string | null;
+ nextTurnOrdinal: number;
+ activeSpan: ActiveTurnSpan | null;
+}
+
+interface TraceRecordBase {
+ agentId: string;
+ effects: string[];
+ nowMs: number;
+ timeIso: string;
+}
+
+interface TraceSpanMetadata {
+ traceTurnId: string;
+ daemonTurnOrdinal: number;
+ spawnOrdinal: number;
+ turnOrdinal: number;
+ launchIdSnapshot: string | null;
+}
+
+interface FsmTraceRecord extends TraceRecordBase, Partial<TraceSpanMetadata> {
+ recordKind: "fsm";
+ event: ManagerEvent["type"];
+ status: AgentStatus;
+ turnActive: boolean;
+ inbox: number;
+ lastDeliverAt: number | null;
+ lastProgressAt: number;
+ idleSince: number | null;
+ resetting: boolean;
+ resettingSince: number | null;
+ stoppingSince: number | null;
+ apmPhase: AgentState["apm"]["phase"];
+ sinceProgressMs: number;
+ sinceDeliverMs: number | null;
+ sinceStoppingMs: number | null;
+ endReason?: "errored";
+ terminationCause?: TraceTerminationCause;
+ exitCode?: number | null;
+ exitSignal?: string | null;
+ abnormal?: boolean;
+ spawnFailureReason?: TraceSpawnFailureReason;
+ terminationSemantics?: TraceTerminationSemantics;
+}
+
+type TurnSpanTraceRecord = TraceRecordBase &
+ TraceSpanMetadata &
+ (
+ | { recordKind: "turn_span"; event: "turn_begin" }
+ | {
+ recordKind: "turn_span";
+ event: "turn_end";
+ outcome: "clean" | "errored";
+ terminationCause?: TraceTerminationCause;
+ }
+ | { recordKind: "turn_span"; event: "turn_abort"; abortCause: TraceAbortCause }
+ );
+
+/** Metadata-only local trace row with an explicit privacy allowlist. */
+export type ManagerTraceRecord = FsmTraceRecord | TurnSpanTraceRecord;
+
+function normalizeTerminationCause(value: unknown): TraceTerminationCause {
+ return value === "runtime_error" || value === "killed_stalled" ? value : "other";
+}
+
+function normalizeAbortCause(value: unknown): TraceAbortCause {
+ switch (value) {
+ case "start_threw":
+ case "start_rejected":
+ case "send_threw":
+ case "spawn_failure":
+ case "handshake_timeout":
+ case "reset":
+ case "nap":
+ case "model_switch":
+ case "requested_stop":
+ case "shutdown":
+ case "physical_exit":
+ case "terminate_stalled":
+ case "force_exit":
+ return value;
+ default:
+ return "other";
+ }
+}
+
+function normalizeSpawnFailureReason(value: unknown): TraceSpawnFailureReason {
+ switch (value) {
+ case "ENOENT":
+ case "handshake_timeout":
+ case "pre_handshake_exit":
+ case "spawn_threw":
+ return value;
+ default:
+ return "other";
+ }
+}
+
+function normalizeTerminationSemantics(value: unknown): TraceTerminationSemantics {
+ switch (value) {
+ case "killed_stalled":
+ case "idle_stop":
+ case "force_exit":
+ return value;
+ default:
+ return "other";
+ }
+}
+
/**
* How the host builds a session for an agent launch. Given the agent id, the
* driver, and the launch context (prompt + resume id filled in), return a
@@ -164,70 +314,13 @@ export interface ManagerRuntimeOpts {
*/
onRuntimeRawLine?: (agentId: string, line: string) => void;
/**
- * Pure-observability FSM transition trace. Called once per `dispatch` reduce
- * (for events carrying an agentId) with the post-reduce key fields + the
- * effect kinds produced. Wired in `createDaemon` to append to a file when
- * `ALOOK_FSM_TRACE` is set — lets a wedge that produces no other log be
- * reconstructed from its FSM history. No behavior change; omit ⇒ no-op.
+ * Pure-observability FSM and turn-lifecycle trace. Each agent-scoped
+ * `dispatch` emits the post-reduce key fields + effect kinds; trace-only
+ * turn_begin/end/abort rows add lifecycle boundaries without entering the
+ * reducer. Wired in `createDaemon` when `ALOOK_FSM_TRACE` is set. No behavior
+ * change; omit ⇒ no-op.
*/
- onFsmTransition?: (rec: {
- agentId: string;
- event: string;
- status: string;
- turnActive: boolean;
- inbox: number;
- lastDeliverAt: number | null;
- lastProgressAt: number;
- idleSince: number | null;
- resetting: boolean;
- resettingSince: number | null;
- stoppingSince: number | null;
- apmPhase: string;
- effects: string[];
- nowMs: number;
- /** `nowMs - lastProgressAt` — stalled/suspectedDeaf "no progress for how long". */
- sinceProgressMs: number;
- /** `nowMs - lastDeliverAt` (null if never delivered) — suspectedDeaf's half. */
- sinceDeliverMs: number | null;
- /** `nowMs - stoppingSince` (null unless in `stopping`) — stopping-stuck backstop clock. */
- sinceStoppingMs: number | null;
- /**
- * Present only on a `turn_end` that ended NON-cleanly. `endReason:"errored"`
- * is the binary crashed-vs-clean judgement; `terminationCause` is the cause
- * (`runtime_error` = mid-turn runtime error; `killed_stalled` = stall
- * watchdog kill) for B2 policy branching; `errorDetail` is free-text. Absent
- * on a clean turn_end and every non-turn_end event — makes a non-clean turn
- * externally distinguishable from a clean nap/idle in the trace (B1 red line
- * 7). See plans/daemon-runtime-error-rewake.md.
- */
- endReason?: "errored";
- terminationCause?: "runtime_error" | "killed_stalled";
- errorDetail?: string;
- /**
- * Present only on an `exit` event: the RAW PHYSICAL termination fact (T1,
- * plans/daemon-trace-completeness-charter.md). `exitCode`/`exitSignal` = how
- * the OS reported the death; `abnormal` = not a deliberate stop AND died on
- * non-zero code or a signal. Makes a hard exit (segfault/OOM/external
- * SIGKILL — no turn_end) distinguishable from a clean exit in the trace.
- * Physical fact only; FSM semantics of the exit are a T3 layer on top.
- */
- exitCode?: number | null;
- exitSignal?: string | null;
- abnormal?: boolean;
- /**
- * Present on an `exit` that followed a LAUNCH failure: the reason string
- * (same value as the web audit — ENOENT/handshake_timeout/pre_handshake_exit/
- * spawn_threw/Node code). T2: makes a failed-to-start distinguishable from a
- * 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;
+ onFsmTransition?: (rec: ManagerTraceRecord) => void;
/**
* Optional context-timeline recorder. When provided, the manager logs each
* spawn as a "running" row, fills in the session id on session_init, and closes
@@ -592,64 +685,15 @@ export class AgentProcessManager {
*/
private readonly thinkingBuffers = new Map<string, string>();
/**
- * agentId → the current spawn's per-session end-tracking flags, shared
+ * agentId → the current spawn's per-session end-tracking and trace ownership,
+ * shared
* between `doSpawn`'s closure (turn_end / exit) and `applyEffect` (stop /
* terminate_stalled) — see `logSessionEnded`'s `suppressExitLog` handling.
*/
- private readonly activeSpawnState = new Map<
- string,
- {
- hasEstablished: boolean;
- hasReportedSpawnFailure: boolean;
- suppressExitLog: boolean;
- /** Handshake watchdog timer; cleared on first `runtime_event` or on exit. */
- handshakeTimer: ReturnType<typeof setTimeout> | null;
- /**
- * Set once this spawn's teardown has run (delete from maps + dispatch
- * `exit`). Guards against a SECOND teardown: the handshake watchdog tears
- * down eagerly, then the killed process emits its own late `exit` — that
- * late event must be a no-op, not a duplicate FSM `exit` that could clobber
- * 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;
- /**
- * OS pid of this spawn's child process, recorded once `session.start()`
- * resolves (the process exists by then; `activeSpawnState` is created at
- * :1226 BEFORE start(), when there is no pid yet). Null for SDK in-process
- * sessions (no OS pid). Read ONLY by `force_exit`'s no-session-handle
- * branch: when the stopping-stuck backstop fires but `this.sessions` no
- * longer holds the session (batch G / Hypothesis A — the map entry was
- * gone while the OS process lived on), the pid recorded here is the only
- * way to actually kill the orphan instead of merely warning. Never a
- * behavioral decision input; purely the kill-target of last resort. See
- * 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;
- }
- >();
+ private readonly activeSpawnState = new Map<string, ActiveSpawnState>();
+ private readonly traceProcessNonce = randomUUID();
+ private nextSpawnOrdinal = 1;
+ private nextDaemonTurnOrdinal = 1;
/**
* agentId → why the current turn ended NON-cleanly, buffered until the
* trailing `turn_end` reads+clears it. Two symmetric marker points feed it
@@ -658,7 +702,8 @@ export class AgentProcessManager {
* misread as a crash):
* - `runtime_error`: a runtime `error` event mid-turn, set ONLY in the
* `!sessionSuperseded` branch (an intentional reset/nap death-rattle never
- * marks). Carries the free-text `detail` for lossless fsm-trace.
+ * marks). Free-text `detail` stays on the existing policy/audit path and
+ * is never serialized to the local trace.
* - `killed_stalled`: the `terminate_stalled` effect (the stall watchdog
* SIGKILLing a wedged turn — Blair's actual case). By construction, no
* dependence on whether the runtime emits a trailing error rattle.
@@ -859,6 +904,7 @@ export class AgentProcessManager {
rewakePrompt: opts.rewakePrompt,
forgetSession: true,
barrierType: opts.barrierType ?? "reset_session",
+ abortCause: opts.barrierType === "nap" ? "nap" : "reset",
opName: "reset",
});
}
@@ -895,12 +941,14 @@ export class AgentProcessManager {
rewakePrompt: string;
forgetSession: boolean;
barrierType?: "reset_session" | "nap";
+ abortCause: "reset" | "nap" | "model_switch";
/** Human label for logs so a restart failure reads as reset vs model switch. */
opName: string;
},
): Promise<void> {
this.register(agentId, { runtimeConfig: opts.runtimeConfig, launchId: opts.launchId });
if (opts.forgetSession) this.forgetSession(agentId, opts.barrierType ?? "reset_session");
+ this.abortCurrentTurn(agentId, opts.abortCause);
this.markResetting(agentId);
const status = this.state.agents[agentId]?.status;
if (status === "idle") {
@@ -964,6 +1012,7 @@ export class AgentProcessManager {
launchId: opts.launchId,
rewakePrompt: opts.rewakePrompt,
forgetSession: false,
+ abortCause: "model_switch",
opName: "model switch",
});
}
@@ -978,6 +1027,7 @@ export class AgentProcessManager {
async stop(agentId: string): Promise<void> {
const session = this.sessions.get(agentId);
if (!session) return;
+ this.abortCurrentTurn(agentId, "requested_stop");
await Promise.resolve(session.stop({ reason: "requested", forceAfterMs: SESSION_STOP_GRACE_MS }));
this.sessions.delete(agentId);
}
@@ -987,11 +1037,11 @@ export class AgentProcessManager {
clearInterval(this.tickTimer);
this.tickTimer = null;
}
- await Promise.all(
- [...this.sessions.values()].map((s) =>
- Promise.resolve(s.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS })),
- ),
- );
+ const entries = [...this.sessions.entries()];
+ for (const [agentId] of entries) this.abortCurrentTurn(agentId, "shutdown");
+ await Promise.all(entries.map(([, session]) =>
+ Promise.resolve(session.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS })),
+ ));
this.sessions.clear();
}
@@ -1079,10 +1129,97 @@ export class AgentProcessManager {
/* Core dispatch: reduce → apply effects */
/* --------------------------------------------------------------- */
- private dispatch(event: ManagerEvent): ManagerEffect[] {
+ private emitTrace(rec: ManagerTraceRecord): void {
+ if (!this.opts.onFsmTransition) return;
+ try {
+ this.opts.onFsmTransition(rec);
+ } catch {
+ // Trace is strictly read-only. A broken sink cannot change reducer or
+ // runtime-call behavior, nor can it leave a lifecycle span half-closed.
+ }
+ }
+
+ private traceOwnerFor(agentId: string, captured?: ActiveSpawnState): ActiveSpawnState | undefined {
+ if (captured) return captured.agentId === agentId ? captured : undefined;
+ const owner = this.activeSpawnState.get(agentId);
+ return owner && this.sessions.get(agentId) === owner.session ? owner : undefined;
+ }
+
+ private openTurn(owner: ActiveSpawnState): ActiveTurnSpan {
+ if (owner.activeSpan) return owner.activeSpan;
+ const daemonTurnOrdinal = this.nextDaemonTurnOrdinal++;
+ const span: ActiveTurnSpan = {
+ traceTurnId: `${owner.launchIdSnapshot ?? this.traceProcessNonce}:${daemonTurnOrdinal}`,
+ daemonTurnOrdinal,
+ spawnOrdinal: owner.spawnOrdinal,
+ turnOrdinal: owner.nextTurnOrdinal++,
+ launchIdSnapshot: owner.launchIdSnapshot,
+ };
+ owner.activeSpan = span;
+ const nowMs = this.now();
+ this.emitTrace({
+ recordKind: "turn_span",
+ agentId: owner.agentId,
+ event: "turn_begin",
+ ...span,
+ effects: [],
+ nowMs,
+ timeIso: new Date(nowMs).toISOString(),
+ });
+ return span;
+ }
+
+ private closeTurn(
+ owner: ActiveSpawnState,
+ expectedSpan: ActiveTurnSpan | null,
+ close:
+ | { event: "turn_end"; outcome: "clean" | "errored"; terminationCause?: TraceTerminationCause }
+ | { event: "turn_abort"; abortCause: TraceAbortCause },
+ ): boolean {
+ if (!expectedSpan || owner.activeSpan !== expectedSpan) return false;
+ // Clear before invoking the sink: throw/re-entry can never close twice.
+ owner.activeSpan = null;
+ const nowMs = this.now();
+ const base = {
+ recordKind: "turn_span" as const,
+ agentId: owner.agentId,
+ ...expectedSpan,
+ effects: [],
+ nowMs,
+ timeIso: new Date(nowMs).toISOString(),
+ };
+ if (close.event === "turn_end") {
+ this.emitTrace({
+ ...base,
+ event: "turn_end",
+ outcome: close.outcome,
+ ...(close.terminationCause ? { terminationCause: close.terminationCause } : {}),
+ });
+ } else {
+ this.emitTrace({
+ ...base,
+ event: "turn_abort",
+ abortCause: normalizeAbortCause(close.abortCause),
+ });
+ }
+ return true;
+ }
+
+ private abortCurrentTurn(agentId: string, cause: TraceAbortCause): void {
+ const owner = this.traceOwnerFor(agentId);
+ if (owner) this.closeTurn(owner, owner.activeSpan, { event: "turn_abort", abortCause: cause });
+ }
+
+ private dispatch(event: ManagerEvent, capturedOwner?: ActiveSpawnState): ManagerEffect[] {
const before = this.deriveActivitySnapshot(this.state);
const { state, effects } = reduceManager(this.state, event);
this.state = state;
+ const eventAgentId = (event as { agentId?: string }).agentId;
+ const closingOwner =
+ event.type === "turn_end" && eventAgentId
+ ? this.traceOwnerFor(eventAgentId, capturedOwner)
+ : undefined;
+ const closingSpan = closingOwner?.activeSpan ?? null;
// FSM transition trace (plans/daemon-fsm-desync.md): pure observability, no
// behavior change. Emits one record per reduce so a wedge that leaves no
// other log (the gated_hold/send branches are the only ones that log today,
@@ -1090,14 +1227,16 @@ export class AgentProcessManager {
// — the missing capability behind every "no log when it breaks" incident.
// Guarded so it's a no-op unless a sink is wired (createDaemon opts).
if (this.opts.onFsmTransition) {
- const nowMs = this.now();
const emit = (agentId: string): void => {
const a = this.state.agents[agentId];
if (!a) return;
+ const nowMs = this.now();
+ const activeSpan = this.traceOwnerFor(agentId, capturedOwner)?.activeSpan ?? null;
// Effects this dispatch produced FOR THIS agent (effects carry agentId,
// so a tick that terminates one wedged agent attributes correctly).
const myEffects = effects.filter((e) => (e as { agentId?: string }).agentId === agentId).map((e) => e.type);
- this.opts.onFsmTransition!({
+ this.emitTrace({
+ recordKind: "fsm",
agentId,
event: event.type,
status: a.status,
@@ -1112,6 +1251,8 @@ export class AgentProcessManager {
apmPhase: a.apm.phase,
effects: myEffects,
nowMs,
+ timeIso: new Date(nowMs).toISOString(),
+ ...(activeSpan ? activeSpan : {}),
// Derived watchdog inputs — the ONLY way to judge, per wedge, WHY no
// watchdog fired: `sinceProgressMs` is `stalled`/`suspectedDeaf`'s
// "no progress for how long" (if it keeps getting reset small on a
@@ -1131,9 +1272,9 @@ export class AgentProcessManager {
...(event.type === "turn_end" && (event as { endReason?: "errored" }).endReason === "errored"
? {
endReason: "errored" as const,
- terminationCause: (event as { terminationCause?: "runtime_error" | "killed_stalled" })
- .terminationCause,
- errorDetail: (event as { errorDetail?: string }).errorDetail,
+ terminationCause: normalizeTerminationCause(
+ (event as { terminationCause?: unknown }).terminationCause,
+ ),
}
: {}),
// Raw physical exit fact, carried on the `exit` event (not agent
@@ -1147,21 +1288,28 @@ export class AgentProcessManager {
// Launch-failure reason (T2). Included only when present so a
// normal exit row stays free of the key.
...((event as { spawnFailureReason?: string | null }).spawnFailureReason != null
- ? { spawnFailureReason: (event as { spawnFailureReason?: string | null }).spawnFailureReason }
+ ? {
+ spawnFailureReason: normalizeSpawnFailureReason(
+ (event as { spawnFailureReason?: unknown }).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 }
+ ? {
+ terminationSemantics: normalizeTerminationSemantics(
+ (event as { terminationSemantics?: unknown }).terminationSemantics,
+ ),
+ }
: {}),
}
: {}),
});
};
- const agentId = (event as { agentId?: string }).agentId;
- if (agentId) {
+ if (eventAgentId) {
// Agent-scoped event (wake / spawned / turn_end / …).
- emit(agentId);
+ emit(eventAgentId);
} else if (event.type === "tick") {
// A tick carries no agentId but the reducer evaluates EVERY agent's
// watchdogs — fan out so each agent's per-tick watchdog inputs + any
@@ -1170,6 +1318,25 @@ export class AgentProcessManager {
for (const id of Object.keys(this.state.agents)) emit(id);
}
}
+ // Trace-only lifecycle close: never enters the reducer. It occurs after the
+ // FSM row (which still carries the active id) and before any queued effect
+ // can open the next turn.
+ if (closingOwner && closingSpan) {
+ const errored = (event as { endReason?: unknown }).endReason === "errored";
+ this.closeTurn(
+ closingOwner,
+ closingSpan,
+ errored
+ ? {
+ event: "turn_end",
+ outcome: "errored",
+ terminationCause: normalizeTerminationCause(
+ (event as { terminationCause?: unknown }).terminationCause,
+ ),
+ }
+ : { event: "turn_end", outcome: "clean" },
+ );
+ }
for (const effect of effects) this.applyEffect(effect);
if (this.opts.onAgentActivity) {
const after = this.deriveActivitySnapshot(this.state);
@@ -1235,18 +1402,46 @@ export class AgentProcessManager {
// Stamp at the moment the text hits `session.send`, not earlier —
// between effect creation and this call the event loop can drain other
// dispatches, and we want the timestamp to match the agent's arrival.
- session?.send({ text: this.stampNow(this.withFooter(effect.text)), mode: effect.mode });
+ const input = { text: this.stampNow(this.withFooter(effect.text)), mode: effect.mode };
+ if (session) {
+ const owner = this.activeSpawnState.get(effect.agentId);
+ const exactOwner = owner?.session === session ? owner : undefined;
+ const associatedSpan = exactOwner
+ ? effect.mode === "idle"
+ ? this.openTurn(exactOwner)
+ : exactOwner.activeSpan
+ : null;
+ try {
+ // Deliberately do not inspect/await the return value: ManagedSession
+ // send is observationally synchronous under the existing contract.
+ session.send(input);
+ } catch (error) {
+ if (exactOwner) {
+ this.closeTurn(exactOwner, associatedSpan, {
+ event: "turn_abort",
+ abortCause: "send_threw",
+ });
+ }
+ throw error;
+ }
+ }
this.log.info("steering message sent to running agent", { agentId: effect.agentId, mode: effect.mode });
break;
}
case "stop":
case "terminate_stalled": {
const session = this.sessions.get(effect.agentId);
+ const spawnState = this.activeSpawnState.get(effect.agentId);
+ if (effect.type === "terminate_stalled" && spawnState) {
+ this.closeTurn(spawnState, spawnState.activeSpan, {
+ event: "turn_abort",
+ abortCause: "terminate_stalled",
+ });
+ }
void Promise.resolve(session?.stop({ reason: effect.type, forceAfterMs: SESSION_STOP_GRACE_MS }));
// The stop we just issued will make the underlying process emit its
// own `exit` shortly after — suppress that follow-up log so a single
// termination doesn't produce two contradictory "session ended" lines.
- const spawnState = this.activeSpawnState.get(effect.agentId);
if (spawnState) spawnState.suppressExitLog = true;
// `terminate_stalled` is the stall watchdog SIGKILLing a wedged turn —
// an INVOLUNTARY kill (Blair's case). Mark it by cause so the trailing
@@ -1295,6 +1490,12 @@ export class AgentProcessManager {
// lost the entry) has a durable data point at each real occurrence.
const session = this.sessions.get(effect.agentId);
const state = this.activeSpawnState.get(effect.agentId);
+ if (state) {
+ this.closeTurn(state, state.activeSpan, {
+ event: "turn_abort",
+ abortCause: "force_exit",
+ });
+ }
if (session) {
void Promise.resolve(session.stop({ reason: effect.reason, forceAfterMs: SESSION_STOP_GRACE_MS })).catch(() => {});
} else if (state?.pid != null) {
@@ -1449,7 +1650,23 @@ 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, terminationSemantics: null as string | null };
+ const state: ActiveSpawnState = {
+ agentId,
+ session,
+ hasEstablished: false,
+ hasReportedSpawnFailure: false,
+ suppressExitLog: false,
+ handshakeTimer: null,
+ torndown: false,
+ superseded: false,
+ pid: null,
+ spawnFailureReason: null,
+ terminationSemantics: null,
+ spawnOrdinal: this.nextSpawnOrdinal++,
+ launchIdSnapshot: typeof ctx.launchId === "string" && ctx.launchId.length > 0 ? ctx.launchId : null,
+ nextTurnOrdinal: 1,
+ activeSpan: null,
+ };
this.activeSpawnState.set(agentId, state);
const clearHandshakeTimer = () => {
if (state.handshakeTimer) {
@@ -1463,6 +1680,10 @@ export class AgentProcessManager {
) => {
if (state.hasEstablished || state.hasReportedSpawnFailure) return;
state.hasReportedSpawnFailure = true;
+ this.closeTurn(state, state.activeSpan, {
+ event: "turn_abort",
+ abortCause: opts?.scope === "handshake_timeout" ? "handshake_timeout" : "spawn_failure",
+ });
// Record the launch-failure reason on THIS spawn's state so the exit
// dispatch that follows can carry it into the fsm-trace (T2 — same reason
// string the web audit below gets, so trace and audit "say the same word":
@@ -1503,7 +1724,7 @@ export class AgentProcessManager {
// 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);
+ this.onRuntimeEvent(agentId, e, driver.id, state);
});
// Only ChildProcessRuntimeSession emits `stderr`; SdkManagedSession
// doesn't, so this is harmless when the session is an SDK adapter.
@@ -1539,6 +1760,10 @@ export class AgentProcessManager {
// per-spawn flag instead.
if (state.torndown) return;
state.torndown = true;
+ this.closeTurn(state, state.activeSpan, {
+ event: "turn_abort",
+ abortCause: "physical_exit",
+ });
const info = args[0] as { code?: number | null; signal?: string | null; reason?: string } | undefined;
// A session that exits without ever emitting `runtime_event` is
// treated as a pre-handshake failure too — covers runtimes whose
@@ -1590,7 +1815,10 @@ 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, terminationSemantics: state.terminationSemantics });
+ this.dispatch(
+ { type: "exit", agentId, exitCode, exitSignal, abnormal, spawnFailureReason: state.spawnFailureReason, terminationSemantics: state.terminationSemantics },
+ state,
+ );
});
// Stamp the wake-prompt timestamp AT the last mile — right before the
@@ -1600,7 +1828,15 @@ export class AgentProcessManager {
// difference matters on cold starts where system-prompt assembly + child
// wiring above adds tens/hundreds of ms.
const stampedPrompt = this.stampNow(prompt);
- void Promise.resolve(session.start({ text: stampedPrompt, sessionId: ctx.config.sessionId }))
+ const startedSpan = this.openTurn(state);
+ let startResult: Promise<unknown>;
+ try {
+ startResult = Promise.resolve(session.start({ text: stampedPrompt, sessionId: ctx.config.sessionId }));
+ } catch (error) {
+ this.closeTurn(state, startedSpan, { event: "turn_abort", abortCause: "start_threw" });
+ throw error;
+ }
+ void startResult
.then(() => {
// A concurrent stop()/terminate_stalled can race this in-flight
// start() and finish first — its `exit` handler above already
@@ -1615,7 +1851,7 @@ export class AgentProcessManager {
// the session handle is later gone (batch F). A child-process session
// exposes `.pid`; an SDK in-process session has none → stays null.
state.pid = (session as { pid?: number }).pid ?? null;
- this.dispatch({ type: "spawned", agentId, nowMs: this.now() });
+ this.dispatch({ type: "spawned", agentId, nowMs: this.now() }, state);
// Arm the handshake watchdog. The FSM just went `running`+`turnActive`
// optimistically (managerPolicy's `spawned`), but the process hasn't
// proven itself — a bad model can make the CLI HANG with no exit, no
@@ -1628,6 +1864,10 @@ export class AgentProcessManager {
state.handshakeTimer = null;
if (state.hasEstablished || state.hasReportedSpawnFailure) return;
if (this.sessions.get(agentId) !== session) return;
+ this.closeTurn(state, state.activeSpan, {
+ event: "turn_abort",
+ abortCause: "handshake_timeout",
+ });
reportSpawnFailure("handshake_timeout", {
scope: "handshake_timeout",
message: `No response ${Math.round(this.opts.handshakeTimeoutMs / 1000)}s after launch — the runtime may be misconfigured (e.g. an invalid model).`,
@@ -1644,20 +1884,24 @@ export class AgentProcessManager {
// T2: carry the launch-failure reason (just set by reportSpawnFailure)
// into the FSM/trace — a handshake_timeout exit is otherwise a bare
// exit in the trace, indistinguishable from a clean one.
- this.dispatch({ type: "exit", agentId, spawnFailureReason: state.spawnFailureReason });
+ this.dispatch({ type: "exit", agentId, spawnFailureReason: state.spawnFailureReason }, state);
}, this.opts.handshakeTimeoutMs);
})
.catch((err: unknown) => {
// Synchronous throws inside driver.spawn() (e.g. child_process.spawn
// throwing ENOENT before returning a subprocess) reach us here.
// Same guard: whichever path saw the failure first names the reason.
+ this.closeTurn(state, startedSpan, {
+ event: "turn_abort",
+ abortCause: "start_rejected",
+ });
const code =
(err as { code?: string } | undefined)?.code ??
"spawn_threw";
reportSpawnFailure(String(code));
if (this.sessions.get(agentId) === session) this.sessions.delete(agentId);
// T2: carry the launch-failure reason into the FSM/trace (same as above).
- this.dispatch({ type: "exit", agentId, spawnFailureReason: state.spawnFailureReason });
+ this.dispatch({ type: "exit", agentId, spawnFailureReason: state.spawnFailureReason }, state);
});
}
@@ -1726,9 +1970,20 @@ export class AgentProcessManager {
}
}
- private onRuntimeEvent(agentId: string, e: unknown, runtimeId: string, sessionSuperseded: boolean): void {
+ private onRuntimeEvent(
+ agentId: string,
+ e: unknown,
+ runtimeId: string,
+ ownerOrSuperseded: ActiveSpawnState | boolean,
+ ): void {
const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string; input?: unknown; message?: string };
if (!ev?.kind) return;
+ // Boolean is retained for the legacy direct unit seam; real subscribers
+ // always pass their captured per-spawn owner.
+ const owner = typeof ownerOrSuperseded === "boolean" ? undefined : ownerOrSuperseded;
+ const sessionSuperseded = typeof ownerOrSuperseded === "boolean"
+ ? ownerOrSuperseded
+ : ownerOrSuperseded.superseded;
// A runtime-parsed `error` event (rate limit, auth failure, bad-model API
// error, provider outage) is otherwise web-silent — the parser sees it,
// the FSM shrugs, and the owner learns nothing. Emit an `error` audit row
@@ -1826,7 +2081,7 @@ export class AgentProcessManager {
}
}
if (ev.kind === "session_init" && ev.sessionId) {
- this.dispatch({ type: "session", agentId, sessionId: ev.sessionId });
+ this.dispatch({ type: "session", agentId, sessionId: ev.sessionId }, owner);
this.liveSessions.set(agentId, ev.sessionId);
this.opts.timeline?.setSession(agentId, ev.sessionId);
this.opts.onAgentSession?.({
@@ -1848,19 +2103,21 @@ export class AgentProcessManager {
// progress: a runtime that errors then goes quiet must still trip the
// stall watchdog rather than reset its progress clock on the way down.
if (ev.kind !== "internal_progress" && ev.kind !== "error") {
- this.dispatch({ type: "progress", agentId, nowMs: this.now() });
+ this.dispatch({ type: "progress", agentId, nowMs: this.now() }, owner);
}
// Forward every parsed event's kind for gated-steering phase tracking
// (tool/compaction/review boundaries). No-ops in the reducer for kinds
// it doesn't care about, aside from the diagnostics ring buffer.
- this.dispatch({ type: "runtime_signal", agentId, kind: ev.kind, nowMs: this.now() });
+ this.dispatch({ type: "runtime_signal", agentId, kind: ev.kind, nowMs: this.now() }, owner);
if (ev.kind === "turn_end") {
this.logSessionEnded(agentId, "turn_end");
// Read+clear the non-clean-end marker set this turn by a preceding runtime
// `error` OR a `terminate_stalled` kill (B1). Present ⇒ the turn is ending
// NON-cleanly; carry the binary judgement (`endReason:"errored"`) + the
// cause (`terminationCause`, for B2 policy branching) + free-text detail
- // into the FSM so onTurnEnd + fsm-trace can tell it from a clean end.
+ // into the existing policy/audit path so onTurnEnd can tell it from a
+ // clean end. The local trace projection serializes only the fixed cause;
+ // it never serializes the free-text detail.
const marker = this.nonCleanEndMarker.get(agentId);
this.nonCleanEndMarker.delete(agentId);
this.dispatch(
@@ -1874,6 +2131,7 @@ export class AgentProcessManager {
errorDetail: marker.detail,
}
: { type: "turn_end", agentId, nowMs: this.now() },
+ owner,
);
}
}
diff --git a/src/daemon/src/util/traceSampler.test.ts b/src/daemon/src/util/traceSampler.test.ts
index 4abb4839a..d4fe08432 100644
--- a/src/daemon/src/util/traceSampler.test.ts
+++ b/src/daemon/src/util/traceSampler.test.ts
@@ -1,12 +1,13 @@
import { describe, it, expect } from "vitest";
import { createTraceSampler, DEFAULT_TRACE_SAMPLE_MS } from "./traceSampler.js";
+import * as traceSamplerModule from "./traceSampler.js";
/*
* T4 (plans/daemon-trace-completeness-charter.md) — heartbeat sampler.
* Two acceptance conditions (Claudette 架构#421):
* ① retention: folding the unchanged-tick / progress / runtime_signal noise
- * lifts transition-row retention ≥12h @ N=8 in the fixed byte budget —
- * here proven as a reproducible fold-ratio → hours calculation.
+ * bounds each agent's sampleable streams; the B1 fleet-budget test below
+ * combines that rate with N=8, transition, and turn-span traffic.
* ② reconstruction: after sampling, a wedge is STILL reconstructable from the
* retained rows alone — which phase, how long, through to kill; the
* watchdog-fired (effects) frame with the peak sinceProgressMs survives.
@@ -37,6 +38,47 @@ function tick(agentId: string, nowMs: number, over: Partial<Rec> = {}): Rec {
};
}
+function operationalRow(
+ agentId: string,
+ event: string,
+ nowMs: number,
+ over: Partial<Rec> = {},
+): Rec {
+ return {
+ recordKind: "fsm",
+ agentId,
+ event,
+ status: "running",
+ turnActive: true,
+ inbox: 0,
+ lastDeliverAt: nowMs,
+ lastProgressAt: nowMs,
+ idleSince: null,
+ resetting: false,
+ resettingSince: null,
+ stoppingSince: null,
+ apmPhase: "idle",
+ effects: [],
+ nowMs,
+ timeIso: new Date(nowMs).toISOString(),
+ sinceProgressMs: 0,
+ sinceDeliverMs: 0,
+ sinceStoppingMs: null,
+ ...over,
+ };
+}
+
+function operationalSpanFields(agentIndex: number, turn: number): Rec {
+ const daemonTurnOrdinal = agentIndex * 60 + turn + 1;
+ return {
+ traceTurnId: `launch-${agentIndex}:${daemonTurnOrdinal}`,
+ daemonTurnOrdinal,
+ spawnOrdinal: agentIndex + 1,
+ turnOrdinal: turn + 1,
+ launchIdSnapshot: `launch-${agentIndex}`,
+ };
+}
+
describe("traceSampler — sacrosanct rows never dropped", () => {
it("all non-tick events pass through untouched", () => {
const { s, out } = collect();
@@ -125,12 +167,11 @@ describe("traceSampler — ② reconstruction: a wedge is reconstructable from r
});
});
-describe("traceSampler — ① retention: fold ratio yields ≥12h @ N=8 (reproducible calc)", () => {
- it("folding unchanged ticks + progress + runtime_signal drops enough to clear the 12h anchor", () => {
- // Measured live baseline @ N=8 (架构#414): avg row 362B, 16MB budget (8MB×2).
- // Raw write rate by stream (MB/h): tick 4.93 (73% unchanged), runtime_signal
- // 0.88, progress 0.65, transitions <0.3. Simulate one agent's steady-state
- // over a window and measure the emitted fraction of the sampleable streams.
+describe("traceSampler — ① per-agent fold-rate evidence", () => {
+ it("bounds one unchanged tick stream to at most 120 rows/hour at the 30s default", () => {
+ // Simulate one agent's steady-state over a window and measure the emitted
+ // fraction. The B1 budget test multiplies this per-agent ceiling across
+ // all three sampleable streams and all eight agents.
const { s, out } = collect(30_000);
const WINDOW_MS = 3600_000; // 1h
const TICK_EVERY = 2000; // ~every 2s (matches observed)
@@ -144,12 +185,7 @@ describe("traceSampler — ① retention: fold ratio yields ≥12h @ N=8 (reprod
emittedSampleable = out.filter((r) => r.event === "tick").length;
// With a 30s throttle over 1h, at most ~1h/30s = 120 emitted (+edges/tail).
expect(emittedSampleable).toBeLessThanOrEqual(125);
- // Reproducible retention calc (documented, not verbal):
- // post-fold tick rate ≈ 120 rows/h; +progress(edge only)+runtime_signal
- // (phase edges) + transitions ≈ well under the 1.33 MB/h ceiling that 16MB
- // / 12h implies. 120 rows/h × 362B ≈ 0.041 MB/h for ticks alone → the tick
- // stream (the 4.93 MB/h bulk) collapses ~40×, so total lands under
- // 1.33 MB/h and transition retention ≥ 16MB / (total MB/h) ≥ 12h @ N=8.
+ // One stream for one agent: 120 rows/h × 362B ≈ 0.041 MiB/h.
const tickMBph = (emittedSampleable * 362) / 1024 / 1024;
expect(tickMBph).toBeLessThan(0.1); // was 4.93 MB/h raw
});
@@ -172,3 +208,165 @@ describe("traceSampler — constants", () => {
expect(DEFAULT_TRACE_SAMPLE_MS).toBe(30_000);
});
});
+
+describe("B1 red gate — turn-span sacred rows", () => {
+ it("preserves begin/end/abort fields and flushes a pending tick tail before each boundary", () => {
+ const { s, out } = collect(30_000);
+ s.offer(tick("a", 0));
+ s.offer(tick("a", 5_000, { sinceProgressMs: 5_000 }));
+ const begin = {
+ recordKind: "turn_span",
+ agentId: "a",
+ event: "turn_begin",
+ traceTurnId: "launch-a:1",
+ daemonTurnOrdinal: 1,
+ spawnOrdinal: 1,
+ turnOrdinal: 1,
+ nowMs: 6_000,
+ timeIso: "2026-01-01T00:00:06.000Z",
+ effects: [],
+ };
+ const end = { ...begin, event: "turn_end", nowMs: 7_000, timeIso: "2026-01-01T00:00:07.000Z" };
+ const abort = { ...begin, event: "turn_abort", nowMs: 8_000, timeIso: "2026-01-01T00:00:08.000Z", abortCause: "physical_exit" };
+ s.offer(begin);
+ s.offer(tick("a", 6_500, { sinceProgressMs: 6_500 }));
+ s.offer(end);
+ s.offer(tick("a", 7_500, { sinceProgressMs: 7_500 }));
+ s.offer(abort);
+
+ expect(out).toContainEqual(begin);
+ expect(out).toContainEqual(end);
+ expect(out).toContainEqual(abort);
+ expect(out.findIndex((row) => row.event === "tick" && row.nowMs === 5_000)).toBeLessThan(
+ out.findIndex((row) => row.event === "turn_begin"),
+ );
+ expect(out.findIndex((row) => row.event === "tick" && row.nowMs === 6_500)).toBeLessThan(
+ out.findIndex((row) => row.event === "turn_end"),
+ );
+ expect(out.findIndex((row) => row.event === "tick" && row.nowMs === 7_500)).toBeLessThan(
+ out.findIndex((row) => row.event === "turn_abort"),
+ );
+ });
+
+ it("keeps a measured one-hour N=8 operational envelope for at least 12h", () => {
+ const productionPerFileCap = Reflect.get(traceSamplerModule, "DEFAULT_TRACE_FILE_MAX_BYTES") as unknown;
+ const AGENTS = 8;
+ const TURNS_PER_AGENT_HOUR = 60;
+ const CLEAN_TURNS_PER_AGENT_HOUR = 54;
+ const FAILED_TURNS_PER_AGENT_HOUR = 6;
+ const TICK_EVERY_MS = 2_000;
+ const ACTIVE_MS_PER_TURN = 20_000;
+ // Seven named phases make six phase-change edges per turn. These edges
+ // bypass the 30s runtime_signal throttle and therefore belong in the
+ // operational upper envelope rather than the steady-stream estimate.
+ const PHASES = ["idle", "tool_wait", "idle", "compacting", "idle", "review", "idle"];
+ const BASE_EPOCH_MS = Date.UTC(2026, 0, 1);
+ const survivors: Rec[] = [];
+ const sampler = createTraceSampler(
+ (row) => survivors.push(row),
+ DEFAULT_TRACE_SAMPLE_MS,
+ );
+
+ expect(CLEAN_TURNS_PER_AGENT_HOUR + FAILED_TURNS_PER_AGENT_HOUR).toBe(
+ TURNS_PER_AGENT_HOUR,
+ );
+
+ for (let agentIndex = 0; agentIndex < AGENTS; agentIndex += 1) {
+ const agentId = `agent-${agentIndex}`;
+ for (let turn = 0; turn < TURNS_PER_AGENT_HOUR; turn += 1) {
+ const turnBaseMs = BASE_EPOCH_MS + turn * 60_000;
+ const spanFields = operationalSpanFields(agentIndex, turn);
+ sampler.offer(operationalRow(agentId, "wake", turnBaseMs, { turnActive: false }));
+ sampler.offer(operationalRow(agentId, "turn_begin", turnBaseMs + 1, {
+ recordKind: "turn_span",
+ ...spanFields,
+ }));
+
+ for (let offsetMs = 0; offsetMs < ACTIVE_MS_PER_TURN; offsetMs += TICK_EVERY_MS) {
+ const phaseIndex = Math.min(
+ Math.floor(offsetMs / TICK_EVERY_MS),
+ PHASES.length - 1,
+ );
+ sampler.offer(operationalRow(agentId, "progress", turnBaseMs + offsetMs + 100, {
+ apmPhase: PHASES[phaseIndex],
+ ...spanFields,
+ }));
+ sampler.offer(operationalRow(agentId, "runtime_signal", turnBaseMs + offsetMs + 200, {
+ apmPhase: PHASES[phaseIndex],
+ ...spanFields,
+ }));
+ sampler.offer(operationalRow(agentId, "tick", turnBaseMs + offsetMs + 300, {
+ turnActive: true,
+ apmPhase: PHASES[phaseIndex],
+ ...spanFields,
+ }));
+ }
+
+ const failed = turn % 10 === 9;
+ sampler.offer(operationalRow(
+ agentId,
+ failed ? "exit" : "turn_end",
+ turnBaseMs + ACTIVE_MS_PER_TURN + 1,
+ { turnActive: false, ...spanFields },
+ ));
+ sampler.offer(operationalRow(
+ agentId,
+ failed ? "turn_abort" : "turn_end",
+ turnBaseMs + ACTIVE_MS_PER_TURN + 2,
+ {
+ recordKind: "turn_span",
+ turnActive: false,
+ ...spanFields,
+ ...(failed ? { abortCause: "physical_exit" } : { outcome: "clean" }),
+ },
+ ));
+ for (
+ let offsetMs = ACTIVE_MS_PER_TURN;
+ offsetMs < 60_000;
+ offsetMs += TICK_EVERY_MS
+ ) {
+ sampler.offer(operationalRow(agentId, "tick", turnBaseMs + offsetMs + 300, {
+ turnActive: false,
+ apmPhase: PHASES.at(-1),
+ }));
+ }
+ }
+ // Flush the final pending idle-tick tail at the one-hour boundary.
+ sampler.offer(operationalRow(agentId, "wake", BASE_EPOCH_MS + 3_600_000, {
+ turnActive: false,
+ }));
+ }
+
+ const count = (event: string, recordKind?: string): number => survivors.filter(
+ (row) => row.event === event && (recordKind === undefined || row.recordKind === recordKind),
+ ).length;
+ const serializedBytesPerHour = survivors.reduce(
+ (total, row) => total + Buffer.byteLength(`${JSON.stringify(row)}\n`, "utf8"),
+ 0,
+ );
+ for (let agentIndex = 0; agentIndex < AGENTS; agentIndex += 1) {
+ const agentRows = survivors.filter((row) => row.agentId === `agent-${agentIndex}`);
+ for (let index = 1; index < agentRows.length; index += 1) {
+ expect(agentRows[index]!.nowMs).toBeGreaterThanOrEqual(agentRows[index - 1]!.nowMs);
+ }
+ }
+
+ expect(DEFAULT_TRACE_SAMPLE_MS).toBe(30_000);
+ expect(PHASES.length - 1).toBe(6);
+ expect(count("runtime_signal")).toBe(AGENTS * TURNS_PER_AGENT_HOUR * PHASES.length);
+ expect(count("progress")).toBe(AGENTS * TURNS_PER_AGENT_HOUR);
+ // Five retained ticks per turn mechanically includes state-change edges,
+ // throttle survivors, and the pending tail flushed by the next boundary.
+ expect(count("tick")).toBe(AGENTS * TURNS_PER_AGENT_HOUR * 5);
+ expect(count("turn_begin", "turn_span")).toBe(AGENTS * TURNS_PER_AGENT_HOUR);
+ expect(count("turn_end", "turn_span")).toBe(AGENTS * CLEAN_TURNS_PER_AGENT_HOUR);
+ expect(count("turn_abort", "turn_span")).toBe(AGENTS * FAILED_TURNS_PER_AGENT_HOUR);
+ expect(survivors).toHaveLength(8_168);
+ expect(serializedBytesPerHour).toBe(4_010_728);
+
+ expect(productionPerFileCap).toBe(32 * 1024 * 1024);
+ if (typeof productionPerFileCap !== "number") return;
+ const retainedHours = (productionPerFileCap * 2) / serializedBytesPerHour;
+ expect(retainedHours).toBeGreaterThanOrEqual(12);
+ });
+});
diff --git a/src/daemon/src/util/traceSampler.ts b/src/daemon/src/util/traceSampler.ts
index 5cd0aa626..ea4369eb5 100644
--- a/src/daemon/src/util/traceSampler.ts
+++ b/src/daemon/src/util/traceSampler.ts
@@ -3,16 +3,13 @@
* useful HISTORY WINDOW instead of being flushed by routine noise
* (plans/daemon-trace-completeness-charter.md T4).
*
- * WHY: the default trace is size-capped (8MB×2, rotatingFileSink). Measured at
- * N≈8 agents, ~74% of all rows are UNCHANGED-STATE `tick` heartbeats (~every
- * 2s/agent) that carry no new information — they flush the information-rich
- * transition rows (exit/turn_end/reset/spawn-fail/kill) out of the window in
- * ~2h. An incident is often investigated hours later (the Blair stall-kill was
- * looked at ~3h after), so the meaningful rows must survive far longer. This
- * sampler folds the redundant heartbeats while keeping every transition and the
- * forensic anchors, lifting transition-row retention to ≥12h @ N=8 at the same
- * byte budget (see charter T4; ≥12h is @ N=8 — write rate scales with agent
- * count, so a much larger fleet needs the byte budget revisited).
+ * WHY: the default trace is capped at 32 MiB per generation (64 MiB for active
+ * + `.1`, rotatingFileSink). At the executable N=8 operational envelope, the
+ * sampler retains 8,168 rows / 4,010,728 serialized JSONL bytes per hour
+ * (3.825 MiB/h), so the two generations preserve approximately 16.73 hours.
+ * Unchanged-state heartbeats carry no new information and would otherwise flush
+ * information-rich transitions far sooner; write rate still scales with agent
+ * count, so a much larger fleet needs the byte budget revisited.
*
* INVARIANT (Cecilia 架构#423 ③): a row is sampleable IFF its information can be
* fully reconstructed from the retained neighbors; otherwise it is sacrosanct.
@@ -43,8 +40,20 @@
* `progress` stream is fully folded.
*/
-/** A trace record as produced by the manager's onFsmTransition callback. */
-type TraceRec = Record<string, unknown>;
+/** Sampler-visible subset of the manager's explicitly allowlisted trace rows. */
+interface TraceRec {
+ recordKind: "fsm" | "turn_span";
+ agentId: string;
+ event: string;
+ effects: string[];
+ nowMs: number;
+ status?: unknown;
+ turnActive?: unknown;
+ inbox?: unknown;
+ resetting?: unknown;
+ stoppingSince?: unknown;
+ apmPhase?: unknown;
+}
export interface TraceSampler {
/** Offer one record; the sampler emits it (and any tail-flush) or folds it. */
@@ -53,9 +62,12 @@ export interface TraceSampler {
/** Streams that are throttled rather than always-emitted. */
const SAMPLEABLE_EVENTS = new Set(["tick", "progress", "runtime_signal"]);
+const SACRED_TURN_SPAN_EVENTS = new Set(["turn_begin", "turn_end", "turn_abort"]);
/** Default heartbeat throttle: at most one folded-stream row per agent per this. */
export const DEFAULT_TRACE_SAMPLE_MS = 30_000;
+/** Cap for each generation of the default-on local FSM trace (active and `.1`). */
+export const DEFAULT_TRACE_FILE_MAX_BYTES = 32 * 1024 * 1024;
interface AgentSamplerState {
/** Last emitted tick's reconstruct-key (state fingerprint); null before first. */
@@ -142,6 +154,15 @@ export function createTraceSampler(
const s = stateFor(agentId);
const event = rec.event;
+ // Lifecycle rows are explicitly sacred rather than relying on their
+ // current absence from SAMPLEABLE_EVENTS. This survives future sampler
+ // expansion and preserves the pending tick tail before the boundary.
+ if (rec.recordKind === "turn_span" && SACRED_TURN_SPAN_EVENTS.has(String(event))) {
+ flushPending(s);
+ emit(rec);
+ return;
+ }
+
// Sacrosanct: any non-sampleable event, or ANY row carrying effects (the
// watchdog-fired frame). Flush the pending tail first so run order + the
// last unchanged tick are preserved ahead of the terminating frame.