Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(daemon): default-on bounded FSM transition trace (batch E1)

Gusaf8dea9246e6
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index ba69b1fff..4b25f7ffb 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -409,6 +409,10 @@ export async function daemonStart(opts: DaemonStartOpts): Promise<void> {
capabilities: CAPABILITIES,
agentCliPath,
workingDirectoryBase: baseDir,
+ // Default-on bounded FSM trace lives under <baseDir>/logs (batch E1). This
+ // is what makes "the last wedge's FSM history" always available without
+ // pre-setting ALOOK_FSM_TRACE. The env var, if set, overrides this.
+ fsmTraceDir: path.join(baseDir, "logs"),
hostname: os.hostname(),
platform: process.platform,
arch: process.arch,
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index e8522e641..ce6622b7d 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -26,7 +26,8 @@
* — the `driverFor` is INJECTED by the caller.
*/
import { homedir } from "os";
-import { appendFileSync } from "node:fs";
+import { appendFileSync, mkdirSync } from "node:fs";
+import { createRotatingFileSink } from "../util/rotatingFileSink.js";
import { WsControlChannel } from "../server/wsControlChannel.js";
import { CredentialBroker, startCredentialProxy } from "../credentials/index.js";
import { AgentProcessManager, AgentRouter, createTypingScopeTracker } from "../manager/index.js";
@@ -44,6 +45,13 @@ 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 — about 4h of history at the observed ~14 rows/min/agent rate,
+ * enough to hold the last wedge. The `ALOOK_FSM_TRACE` override is unbounded.
+ */
+const FSM_TRACE_MAX_BYTES = 8 * 1024 * 1024;
/**
* Derive the audit-log `cli_invocation` subcommand from a proxy request
@@ -129,6 +137,14 @@ export interface CreateDaemonOptions {
capabilities: string[];
/** Working directory base for agent launch contexts. */
workingDirectoryBase?: string;
+ /**
+ * Directory for the DEFAULT-ON bounded FSM transition trace
+ * (`<fsmTraceDir>/fsm-trace.jsonl`, size-capped/rotating — batch E1). When
+ * omitted the default trace is off (test stubs). `ALOOK_FSM_TRACE=<path>`
+ * overrides BOTH: it takes precedence and uses an unbounded single-file
+ * append (deep-investigation mode). See plans/daemon-fsm-desync.md batch E.
+ */
+ fsmTraceDir?: string;
/**
* Absolute path to the host's agent CLI entrypoint. Real deployments point this
* at the shim/binary the agent subprocess invokes (via a symlink in PATH).
@@ -587,21 +603,44 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
// `ready` frame's `runningAgents` reflects what's actually live and the
// server's reconciler safety net can flip stale pills to idle.
onAgentLocallyStopped: (info) => router?.markLocallyStopped(info.agentId),
- // FSM transition trace → file, ONLY when ALOOK_FSM_TRACE is set (opt-in,
- // zero cost otherwise). One JSON line per reduce so a wedge that logs
- // nothing else is reconstructable from its FSM history. See
- // plans/daemon-fsm-desync.md — the "no log when it breaks" fix.
- ...(process.env.ALOOK_FSM_TRACE
- ? {
+ // FSM transition trace → file. One JSON line per reduce so a wedge that
+ // logs nothing else is reconstructable from its FSM history (the "no log
+ // when it breaks" fix, plans/daemon-fsm-desync.md). Two modes:
+ // - DEFAULT ON (batch E1): a bounded, size-capped/rotating sink at
+ // `<fsmTraceDir>/fsm-trace.jsonl` — so we're never blind to the last
+ // wedge without pre-setting an env, and it can't fill the disk.
+ // - `ALOOK_FSM_TRACE=<path>` OVERRIDE: unbounded single-file append at
+ // that path (deep-investigation mode; takes precedence over the
+ // default). Content is FSM metadata only (no PII) — safe to default on.
+ ...(() => {
+ const overridePath = process.env.ALOOK_FSM_TRACE;
+ if (overridePath) {
+ return {
onFsmTransition: (rec: Record<string, unknown>) => {
try {
- appendFileSync(process.env.ALOOK_FSM_TRACE as string, JSON.stringify(rec) + "\n");
+ appendFileSync(overridePath, JSON.stringify(rec) + "\n");
} catch {
/* never let tracing break the daemon */
}
},
+ };
+ }
+ if (opts.fsmTraceDir) {
+ try {
+ mkdirSync(opts.fsmTraceDir, { recursive: true });
+ } catch {
+ /* best-effort: if the dir can't be made, sink writes just no-op */
}
- : {}),
+ const sink = createRotatingFileSink(
+ `${opts.fsmTraceDir}/fsm-trace.jsonl`,
+ FSM_TRACE_MAX_BYTES,
+ );
+ return {
+ onFsmTransition: (rec: Record<string, unknown>) => sink.write(JSON.stringify(rec)),
+ };
+ }
+ return {};
+ })(),
// Only the "pi" runtime declares `Driver.createSession` today (in-process
// SDK, no child process) — this is only ever consulted for that case.
sdkDriverDepsFor: (ctx) => createPiSdkDriverDeps(ctx),
diff --git a/src/daemon/src/util/rotatingFileSink.test.ts b/src/daemon/src/util/rotatingFileSink.test.ts
new file mode 100644
index 000000000..75671b854
--- /dev/null
+++ b/src/daemon/src/util/rotatingFileSink.test.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import { mkdtempSync, rmSync, existsSync, statSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createRotatingFileSink } from "./rotatingFileSink";
+
+describe("createRotatingFileSink (batch E1 — bounded default trace backing)", () => {
+ let dir: string;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "fsm-sink-"));
+ });
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it("caps total on-disk bytes across many writes (~2×maxBytes, active + one rotated)", () => {
+ const path = join(dir, "trace.jsonl");
+ const maxBytes = 1000;
+ const sink = createRotatingFileSink(path, maxBytes);
+ // Write far more than the cap: 500 lines × ~100 bytes = ~50KB, cap is 1KB.
+ const line = "x".repeat(99); // ~100 bytes with newline
+ for (let i = 0; i < 500; i++) sink.write(line);
+
+ const active = existsSync(path) ? statSync(path).size : 0;
+ const rotated = existsSync(`${path}.1`) ? statSync(`${path}.1`).size : 0;
+ // Total bounded by ~2×maxBytes + one line's slack (a write can push the
+ // active file slightly past maxBytes before the NEXT write rotates it).
+ expect(active + rotated).toBeLessThanOrEqual(2 * maxBytes + 200);
+ // And it kept SOMETHING (didn't just delete everything).
+ expect(active + rotated).toBeGreaterThan(0);
+ });
+
+ it("retains the most-recent lines after rotation (last wedge stays readable)", () => {
+ const path = join(dir, "trace.jsonl");
+ const sink = createRotatingFileSink(path, 500);
+ for (let i = 0; i < 200; i++) sink.write(`line-${i}`);
+ // The active file's last line should be the most recent write.
+ const activeContent = readFileSync(path, "utf8").trim().split("\n");
+ expect(activeContent[activeContent.length - 1]).toBe("line-199");
+ });
+
+ it("maxBytes <= 0 disables rotation (unbounded single file)", () => {
+ const path = join(dir, "trace.jsonl");
+ const sink = createRotatingFileSink(path, 0);
+ for (let i = 0; i < 200; i++) sink.write("x".repeat(99));
+ expect(existsSync(`${path}.1`)).toBe(false); // never rotated
+ expect(statSync(path).size).toBeGreaterThan(10_000); // all of it in one file
+ });
+
+ it("never throws when the target directory does not exist (best-effort)", () => {
+ const sink = createRotatingFileSink(join(dir, "nope", "trace.jsonl"), 1000);
+ expect(() => sink.write("line")).not.toThrow();
+ });
+});
diff --git a/src/daemon/src/util/rotatingFileSink.ts b/src/daemon/src/util/rotatingFileSink.ts
new file mode 100644
index 000000000..e16aef29f
--- /dev/null
+++ b/src/daemon/src/util/rotatingFileSink.ts
@@ -0,0 +1,72 @@
+/**
+ * A tiny size-capped, rotating append sink — the bounded backing for the
+ * default-on FSM transition trace (plans/daemon-fsm-desync.md batch E1).
+ *
+ * WHY net-new: the daemon has no rotation utility (recon-confirmed), and the
+ * raw `appendFileSync` sink the trace shipped with (createDaemon.ts) is
+ * UNBOUNDED — ~15MB/4h, only grows. That's fine for an opt-in deep-dive
+ * (`ALOOK_FSM_TRACE`), but the whole point of E1 is to make the trace DEFAULT
+ * ON so we're never blind to a wedge again — and a default that silently fills
+ * the disk is a bug, not a feature. This sink caps total on-disk bytes.
+ *
+ * DESIGN — a 2-file ring (active + `.1`):
+ * - append lines to `<path>`;
+ * - when `<path>` would exceed `maxBytes`, rotate: `rename(<path> → <path>.1)`
+ * (overwriting any previous `.1`), then start a fresh empty `<path>`.
+ * - so on-disk total is bounded by ~2×maxBytes, and we always retain at least
+ * the last `maxBytes` of history (usually ~2×) — enough to hold the last
+ * wedge's FSM trail.
+ *
+ * Everything is best-effort: a sink must NEVER break the daemon, so every fs
+ * call is wrapped and failures are swallowed (same contract as the old inline
+ * try/catch). Synchronous fs (appendFileSync/statSync/renameSync) mirrors the
+ * existing sink — the write is off the FSM hot path (it runs in the
+ * onFsmTransition callback, after the reduce), and keeping it sync avoids
+ * interleaving/ordering hazards a per-line async write would add.
+ */
+import { appendFileSync, statSync, renameSync, existsSync } from "node:fs";
+
+export interface RotatingFileSink {
+ /** Append one already-serialized line (a trailing newline is added). */
+ write(line: string): void;
+}
+
+/**
+ * @param path active file path; rotated file is `${path}.1`.
+ * @param maxBytes rotate once the active file reaches/exceeds this. Total
+ * on-disk ≈ 2×maxBytes. Must be > 0; non-positive disables
+ * rotation (unbounded) — callers that want a cap must pass > 0.
+ */
+export function createRotatingFileSink(path: string, maxBytes: number): RotatingFileSink {
+ const rotate = (): void => {
+ try {
+ // Overwrite any prior `.1` — we only keep one generation back.
+ renameSync(path, `${path}.1`);
+ } catch {
+ /* rename can fail (path gone, races) — swallow; next write recreates. */
+ }
+ };
+
+ const currentSize = (): number => {
+ try {
+ return existsSync(path) ? statSync(path).size : 0;
+ } catch {
+ return 0;
+ }
+ };
+
+ return {
+ write(line: string): void {
+ try {
+ // Rotate BEFORE the write that would breach the cap, so the active file
+ // never grows unbounded between checks. (A single line can still exceed
+ // maxBytes; that's fine — it lands in a freshly-rotated active file and
+ // the next write rotates again. Bound holds within one line's slack.)
+ if (maxBytes > 0 && currentSize() >= maxBytes) rotate();
+ appendFileSync(path, line + "\n");
+ } catch {
+ /* never let tracing break the daemon */
+ }
+ },
+ };
+}