Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
daemon: C0 — per-key daemon file layout, fix multi-daemon file clobber
Gus0e824a3c74d1
diff --git a/src/daemon/src/cli/daemonList.test.ts b/src/daemon/src/cli/daemonList.test.tsindex 7b707e97e..029bab00c 100644--- a/src/daemon/src/cli/daemonList.test.ts+++ b/src/daemon/src/cli/daemonList.test.ts@@ -22,15 +22,15 @@ describe("daemonList — C3 fields", () => {fs.rmSync(baseDir, { recursive: true, force: true });});- it("returns id (pidfile name) + pid + alive, and NEVER the machine key", () => {- const daemonsDir = path.join(baseDir, "daemons");- fs.mkdirSync(daemonsDir, { recursive: true });- // A live daemon: use our own pid (definitely alive).- fs.writeFileSync(path.join(daemonsDir, "abc123def456.pid"), JSON.stringify({ pid: process.pid, key: "cmk_super_secret_key" }));+ it("returns id (subdir name) + pid + alive, and NEVER the machine key", () => {+ // Per-key subdir (C0): daemons/<id>/daemon.pid.+ const dir = path.join(baseDir, "daemons", "abc123def456");+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, "daemon.pid"), JSON.stringify({ pid: process.pid, key: "cmk_super_secret_key" }));const list = daemonList({ baseDir });expect(list).toHaveLength(1);- expect(list[0]!.id).toBe("abc123def456"); // the pidfile name = the stop id+ expect(list[0]!.id).toBe("abc123def456"); // the subdir name = the stop idexpect(list[0]!.pid).toBe(process.pid);expect(list[0]!.alive).toBe(true);// The credential must not appear anywhere in the returned shape.@@ -38,13 +38,14 @@ describe("daemonList — C3 fields", () => {expect(JSON.stringify(list[0])).not.toContain("secret");});- it("prunes a dead pidfile and reports nothing alive for it", () => {- const daemonsDir = path.join(baseDir, "daemons");- fs.mkdirSync(daemonsDir, { recursive: true });+ it("prunes a dead daemon's pidfile and reports nothing alive for it", () => {+ const dir = path.join(baseDir, "daemons", "deadone00000");+ fs.mkdirSync(dir, { recursive: true });// pid 1 is init — process.kill(1, 0) from a normal user throws EPERM, which// isProcessAlive treats as... alive. Use a pid that's almost certainly dead.const deadPid = 2 ** 22; // very unlikely to be a live pid- fs.writeFileSync(path.join(daemonsDir, "deadone00000.pid"), JSON.stringify({ pid: deadPid, key: "cmk_x" }));+ const pidfile = path.join(dir, "daemon.pid");+ fs.writeFileSync(pidfile, JSON.stringify({ pid: deadPid, key: "cmk_x" }));const list = daemonList({ baseDir });const dead = list.find((d) => d.id === "deadone00000");@@ -53,7 +54,7 @@ describe("daemonList — C3 fields", () => {expect(dead.agents).toBeNull(); // no live agents attributed to a dead daemon}// pidfile pruned on read- expect(fs.existsSync(path.join(daemonsDir, "deadone00000.pid"))).toBe(false);+ expect(fs.existsSync(pidfile)).toBe(false);});it("empty when no daemons dir", () => {@@ -103,3 +104,59 @@ describe("renderDaemonList — human table (C2)", () => {expect(out).toContain("—");});});++describe("daemonList — C0 per-daemon subdir layout + multi-daemon isolation", () => {+ let baseDir: string;+ beforeEach(() => { baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-c0-")); });+ afterEach(() => { fs.rmSync(baseDir, { recursive: true, force: true }); });++ const writeDaemon = (id: string, pid: number, agents: number, writtenAt: number) => {+ const dir = path.join(baseDir, "daemons", id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, "daemon.pid"), JSON.stringify({ pid, key: `cmk_${id}` }));+ fs.writeFileSync(+ path.join(dir, "status.json"),+ JSON.stringify({+ writtenAt,+ agents: Array.from({ length: agents }, (_, i) => ({+ agentId: `${id}-a${i}`, status: "running", derivedActivity: "running", turnActive: true, inbox: 0, sinceProgressMs: 1, stoppingSince: null,+ })),+ }),+ );+ };++ it("discovers a subdir daemon and reads ITS OWN status (id = subdir name)", () => {+ writeDaemon("111111111111", process.pid, 3, Date.now());+ const list = daemonList({ baseDir });+ const row = list.find((d) => d.id === "111111111111");+ expect(row).toBeTruthy();+ expect(row!.alive).toBe(true);+ expect(row!.agents).toBe(3); // this daemon's own count, from its own status.json+ });++ it("TWO daemons each show their OWN agent count — not the last writer's (the multi-daemon bug fix)", () => {+ // The pre-C0 bug: a single global status.json meant both rows showed the+ // last writer's count. Per-key subdir status → each row is its own.+ writeDaemon("aaaaaaaaaaaa", process.pid, 3, Date.now());+ writeDaemon("bbbbbbbbbbbb", process.pid, 7, Date.now());+ const list = daemonList({ baseDir });+ const a = list.find((d) => d.id === "aaaaaaaaaaaa");+ const b = list.find((d) => d.id === "bbbbbbbbbbbb");+ expect(a!.agents).toBe(3);+ expect(b!.agents).toBe(7); // distinct — NOT both showing one value+ });++ it("only subdir daemons are listed — a stray flat file is NOT discovered (legacy compat dropped, Gus #466)", () => {+ // No migration compat: a bare `<id>.pid` file (pre-C0 shape) is ignored;+ // only per-key subdirs are daemons. Keeps discovery single-path, no legacy+ // debt. (Cutover: old flat residue must be cleaned manually before restart.)+ const dir = path.join(baseDir, "daemons");+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, "straystray00.pid"), JSON.stringify({ pid: process.pid, key: "cmk_stray" }));+ writeDaemon("newnewnewnew", process.pid, 2, Date.now());++ const list = daemonList({ baseDir });+ expect(list.find((d) => d.id === "straystray00")).toBeUndefined(); // flat file ignored+ expect(list.find((d) => d.id === "newnewnewnew")?.agents).toBe(2); // only subdir daemons+ });+});diff --git a/src/daemon/src/cli/daemonStart.test.ts b/src/daemon/src/cli/daemonStart.test.tsindex 48b374442..7a16b6e7d 100644--- a/src/daemon/src/cli/daemonStart.test.ts+++ b/src/daemon/src/cli/daemonStart.test.ts@@ -45,9 +45,14 @@ describe("daemonStatus — reads snapshot + always flags freshness (batch E2)",fs.rmSync(baseDir, { recursive: true, force: true });});+ // Per-key layout (C0): status lives at daemons/<id>/status.json.+ const ID = "d0d0d0d0d0d0";+ const daemonSubdir = () => path.join(baseDir, "daemons", ID);const writeSnap = (writtenAt: number) => {+ const dir = daemonSubdir();+ fs.mkdirSync(dir, { recursive: true });fs.writeFileSync(- path.join(baseDir, "status.json"),+ path.join(dir, "status.json"),JSON.stringify({writtenAt,agents: [@@ -58,7 +63,7 @@ describe("daemonStatus — reads snapshot + always flags freshness (batch E2)",};it("missing file → freshness 'missing', found false, no throw", () => {- const r = daemonStatus({ baseDir, now: () => 1000 });+ const r = daemonStatus({ id: ID, baseDir, now: () => 1000 });expect(r.found).toBe(false);expect(r.freshness).toBe("missing");expect(r.agents).toEqual([]);@@ -66,7 +71,7 @@ describe("daemonStatus — reads snapshot + always flags freshness (batch E2)",it("recent snapshot → 'fresh' with the agent projection + age", () => {writeSnap(1000);- const r = daemonStatus({ baseDir, now: () => 3000 }); // 2s old+ const r = daemonStatus({ id: ID, baseDir, now: () => 3000 }); // 2s oldexpect(r.found).toBe(true);expect(r.freshness).toBe("fresh");expect(r.ageMs).toBe(2000);@@ -74,18 +79,40 @@ describe("daemonStatus — reads snapshot + always flags freshness (batch E2)",expect(r.agents[0]?.derivedActivity).toBe("idle");});+ it("recent snapshot resolvable WITHOUT an id when only one daemon exists (auto-pick)", () => {+ writeSnap(1000);+ const r = daemonStatus({ baseDir, now: () => 3000 });+ expect(r.found).toBe(true);+ expect(r.agents[0]?.agentId).toBe("a1");+ });+it("old snapshot → 'stale' (never mistaken for live truth)", () => {writeSnap(1000);- const r = daemonStatus({ baseDir, now: () => 1000 + 60_000 }); // 60s old+ const r = daemonStatus({ id: ID, baseDir, now: () => 1000 + 60_000 }); // 60s oldexpect(r.freshness).toBe("stale");expect(r.ageMs).toBe(60_000);expect(r.found).toBe(true); // still returns the last-known frame});it("corrupt/half-written file → treated as missing, no throw", () => {- fs.writeFileSync(path.join(baseDir, "status.json"), "{ not valid json");- const r = daemonStatus({ baseDir, now: () => 1000 });+ const dir = daemonSubdir();+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, "status.json"), "{ not valid json");+ const r = daemonStatus({ id: ID, baseDir, now: () => 1000 });expect(r.found).toBe(false);expect(r.freshness).toBe("missing");});++ it("multiple daemons + no id → ambiguous (per-daemon status can't guess which)", () => {+ // Two daemons each with their own status.json subdir.+ for (const id of ["aaaaaaaaaaaa", "bbbbbbbbbbbb"]) {+ const dir = path.join(baseDir, "daemons", id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, "status.json"), JSON.stringify({ writtenAt: 1000, agents: [] }));+ }+ const r = daemonStatus({ baseDir, now: () => 1000 });+ expect(r.found).toBe(false);+ expect(r.ambiguous).toBe(true);+ expect(r.availableIds?.sort()).toEqual(["aaaaaaaaaaaa", "bbbbbbbbbbbb"]);+ });});diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.tsindex 1ec064df4..4a8c93cce 100644--- a/src/daemon/src/cli/daemonStart.ts+++ b/src/daemon/src/cli/daemonStart.ts@@ -54,8 +54,31 @@ function daemonsDir(baseDir: string): string {return path.join(baseDir, "daemons");}+/**+ * Per-daemon subdirectory (batch C0): each daemon's own on-disk files+ * (daemon.pid + status.json + fsm-trace.jsonl + daemon.log) live under+ * `daemons/<keyHash>/`, so multiple daemons sharing a baseDir never clobber a+ * shared file. `<keyHash>` is the daemon's addressing id (what `daemon list`+ * shows and `daemon stop <id>` takes). Mirrors the pre-C0 per-key pidfile+ * naming — this just collects the per-daemon set into one directory.+ */+function daemonDir(baseDir: string, machineKey: string): string {+ return path.join(daemonsDir(baseDir), keyHash(machineKey));+}+function daemonDirById(baseDir: string, id: string): string {+ return path.join(daemonsDir(baseDir), id);+}+function pidfilePath(baseDir: string, machineKey: string): string {- return path.join(daemonsDir(baseDir), `${keyHash(machineKey)}.pid`);+ return path.join(daemonDir(baseDir, machineKey), "daemon.pid");+}++/** Per-daemon status snapshot (C0): `daemons/<keyHash>/status.json`. */+function statusFilePathForKey(baseDir: string, machineKey: string): string {+ return path.join(daemonDir(baseDir, machineKey), "status.json");+}+function statusFilePathById(baseDir: string, id: string): string {+ return path.join(daemonDirById(baseDir, id), "status.json");}function isProcessAlive(pid: number): boolean {@@ -120,12 +143,11 @@ export interface DaemonInfo {pid: number;alive: boolean;/**- * Agent count + last-activity ms-epoch from status.json (the daemon's- * periodic snapshot). NULL when no snapshot yet. CAVEAT (red line 5):- * status.json is per-baseDir/GLOBAL, not per-daemon — so these two are- * accurate at the common one-daemon-per-machine case; with multiple daemons- * sharing a baseDir they reflect the last writer, not this row. The CLI- * renderer surfaces that caveat.+ * Agent count + last-activity ms-epoch from THIS daemon's own status.json+ * (`daemons/<id>/status.json`, per-daemon since C0). NULL when no snapshot yet+ * (or a dead daemon). Now accurate per-row even with multiple daemons sharing+ * a baseDir — the pre-C0 global single file made every row show the last+ * writer's count; the per-key subdir fixes that.*/agents: number | null;lastActiveMs: number | null;@@ -136,31 +158,37 @@ export function daemonList(opts: DaemonListOpts): DaemonInfo[] {const dir = daemonsDir(baseDir);if (!fs.existsSync(dir)) return [];- // status.json is per-baseDir (global). Read once; attach to each row with the- // documented caveat that it's the last writer, exact only at 1 daemon/baseDir.- const status = daemonStatus({ baseDir });- const agents = status.found ? status.agents.length : null;- const lastActiveMs = status.writtenAt;-- const files = fs.readdirSync(dir).filter((f) => f.endsWith(".pid"));const results: DaemonInfo[] = [];+ const now = Date.now();- for (const file of files) {- const filePath = path.join(dir, file);- const data = readPidFile(filePath);- if (!data) continue;+ const pushRow = (id: string, pidfile: string, statusPath: string | null): void => {+ const data = readPidFile(pidfile);+ if (!data) return;const alive = isProcessAlive(data.pid);- // Clean up stale pidfilesif (!alive) {- try { fs.unlinkSync(filePath); } catch { /* ok */ }+ // Prune the stale pidfile (subdir daemon.pid or legacy flat).+ try { fs.unlinkSync(pidfile); } catch { /* ok */ }+ }+ // Per-daemon status: read THIS daemon's own snapshot (C0), not a global one.+ let agents: number | null = null;+ let lastActiveMs: number | null = null;+ if (alive && statusPath) {+ const s = daemonStatusFromFile(statusPath, now);+ if (s.found) {+ agents = s.agents.length;+ lastActiveMs = s.writtenAt;+ }+ }+ results.push({ id, pid: data.pid, alive, agents, lastActiveMs });+ };++ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ // Per-key subdir layout (C0): daemons/<id>/daemon.pid + status.json. Each+ // daemon has its own directory; id = the directory name.+ if (entry.isDirectory()) {+ const id = entry.name;+ pushRow(id, path.join(dir, id, "daemon.pid"), path.join(dir, id, "status.json"));}- results.push({- id: file.replace(".pid", ""),- pid: data.pid,- alive,- agents: alive ? agents : null,- lastActiveMs: alive ? lastActiveMs : null,- });}return results;@@ -172,6 +200,13 @@ export function daemonList(opts: DaemonListOpts): DaemonInfo[] {export interface DaemonStatusOpts {baseDir?: string;+ /**+ * Which daemon's status to read (the id from `daemon list`). Since C0 status+ * is per-daemon (`daemons/<id>/status.json`). If omitted and exactly ONE+ * daemon exists, that one is used; if omitted with multiple daemons it's+ * ambiguous → `ambiguous:true` (the CLI then tells the user to pass an id).+ */+ id?: string;/** Injectable clock for tests; defaults to Date.now. */now?: () => number;}@@ -192,21 +227,26 @@ export interface DaemonStatusResult {/** The snapshot's own writtenAt (ms epoch), or null. */writtenAt: number | null;agents: DaemonStatusSnapshot["agents"];+ /**+ * Set when no `id` was given AND more than one daemon exists — the caller must+ * disambiguate. `found` is false in that case (no single snapshot to return).+ */+ ambiguous?: boolean;+ /** The ids available to pass, when ambiguous. */+ availableIds?: string[];}/** Older than this ⇒ "stale" (a few status-write intervals of slack). */const STATUS_STALE_MS = 20_000;-export function daemonStatus(opts: DaemonStatusOpts): DaemonStatusResult {- const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;- const now = opts.now ?? (() => Date.now());- const statusPath = path.join(baseDir, "status.json");- if (!fs.existsSync(statusPath)) {- return { found: false, ageMs: null, freshness: "missing", writtenAt: null, agents: [] };- }+const MISSING_STATUS: DaemonStatusResult = { found: false, ageMs: null, freshness: "missing", writtenAt: null, agents: [] };++/** Read+parse ONE status.json at a known path. Never throws (best-effort). */+function daemonStatusFromFile(statusPath: string, nowMs: number): DaemonStatusResult {+ if (!fs.existsSync(statusPath)) return MISSING_STATUS;try {const snap = JSON.parse(fs.readFileSync(statusPath, "utf8")) as DaemonStatusSnapshot;- const ageMs = now() - snap.writtenAt;+ const ageMs = nowMs - snap.writtenAt;return {found: true,ageMs,@@ -217,19 +257,48 @@ export function daemonStatus(opts: DaemonStatusOpts): DaemonStatusResult {} catch {// File present but unreadable/half-written/corrupt → treat as missing// rather than crash (a `daemon status` must never throw on a bad file).- return { found: false, ageMs: null, freshness: "missing", writtenAt: null, agents: [] };+ return MISSING_STATUS;}}+/** The subdir ids of daemons that have a per-key status file (C0). */+function daemonIdsWithStatus(baseDir: string): string[] {+ const dir = daemonsDir(baseDir);+ if (!fs.existsSync(dir)) return [];+ const ids: string[] = [];+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ if (entry.isDirectory() && fs.existsSync(path.join(dir, entry.name, "status.json"))) {+ ids.push(entry.name);+ }+ }+ return ids;+}++export function daemonStatus(opts: DaemonStatusOpts): DaemonStatusResult {+ const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;+ const nowMs = (opts.now ?? (() => Date.now()))();+ // Explicit id → that daemon's per-key status.+ if (opts.id) {+ return daemonStatusFromFile(statusFilePathById(baseDir, opts.id), nowMs);+ }+ // No id: auto-pick the sole daemon; ambiguous if more than one.+ const ids = daemonIdsWithStatus(baseDir);+ if (ids.length === 1) {+ return daemonStatusFromFile(statusFilePathById(baseDir, ids[0]!), nowMs);+ }+ if (ids.length > 1) {+ return { ...MISSING_STATUS, ambiguous: true, availableIds: ids };+ }+ return MISSING_STATUS;+}+/* ------------------------------------------------------------------ *//* daemon stop *//* ------------------------------------------------------------------ */export interface DaemonStopOpts {- /** Stop by the id shown in `daemon list` (= the pidfile's keyHash name). */- id?: string;- /** Legacy/programmatic: stop by full machine key (hashed to the pidfile). */- machineKey?: string;+ /** The id shown in `daemon list` (= the daemon's subdir name / keyHash). */+ id: string;baseDir?: string;}@@ -238,9 +307,7 @@ export interface DaemonStopOpts {* agent children, close channel/proxy, remove pidfile) → escalate to SIGKILL* only if it overruns the grace window. This kill/teardown semantic is* UNCHANGED by stop-by-id (plans/daemon-cli-humanize-charter.md red line 3) —- * only HOW the daemon is addressed changed (id vs machine key resolve to the- * same pidfile). `notFoundHint` tailors the "nothing here" message to how the- * caller addressed it.+ * only HOW the daemon is addressed changed (its list id, not a machine key).*/async function stopByPidfile(pf: string, notFoundHint: string): Promise<void> {const data = readPidFile(pf);@@ -274,21 +341,13 @@ async function stopByPidfile(pf: string, notFoundHint: string): Promise<void> {export async function daemonStop(opts: DaemonStopOpts): Promise<void> {const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;- // Prefer the id (what `daemon list` shows and a human passes) — it IS the- // pidfile's keyHash name, so it resolves directly with no machine key. A- // machine key is still accepted for programmatic/legacy callers (hashed to- // the same pidfile). The credential never has to enter the human's stop- // command (red line 2): `daemon stop <id>`, not `--machine-key <secret>`.- if (opts.id) {- const pf = path.join(daemonsDir(baseDir), `${opts.id}.pid`);- await stopByPidfile(pf, `no daemon with id '${opts.id}' (pidfile not found — check \`alook daemon list\`)`);- return;- }- if (opts.machineKey) {- await stopByPidfile(pidfilePath(baseDir, opts.machineKey), "no daemon running for this machine key (pidfile not found)");- return;- }- log.error("daemon stop: an id (from `alook daemon list`) is required");+ // Stop by the id `daemon list` shows — it IS the daemon's subdir name, so it+ // resolves the pidfile directly. The machine key (a credential) never enters+ // the human's stop command (red line 2): `daemon stop <id>`.+ await stopByPidfile(+ path.join(daemonDirById(baseDir, opts.id), "daemon.pid"),+ `no daemon with id '${opts.id}' (pidfile not found — check \`alook daemon list\`)`,+ );}/* ------------------------------------------------------------------ */@@ -514,12 +573,14 @@ 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"),- // Periodic `daemon status` snapshot (batch E2) → <baseDir>/status.json.- statusFilePath: path.join(baseDir, "status.json"),+ // Default-on bounded FSM trace + periodic status snapshot both live in THIS+ // daemon's per-key subdir `daemons/<keyHash>/` (batch C0), NOT a shared+ // <baseDir> path — so multiple daemons on one baseDir never interleave their+ // traces or clobber each other's status.json, and each daemon's trace gets+ // its OWN rotation budget (restoring T4's ≥12h-per-daemon retention). The+ // ALOOK_FSM_TRACE env override (createDaemon) still wins for deep dives.+ fsmTraceDir: daemonDir(baseDir, opts.machineKey),+ statusFilePath: statusFilePathForKey(baseDir, opts.machineKey),hostname: os.hostname(),platform: process.platform,arch: process.arch,diff --git a/src/daemon/src/cli/daemonStop.test.ts b/src/daemon/src/cli/daemonStop.test.tsindex 0ccabfa30..41771f7f7 100644--- a/src/daemon/src/cli/daemonStop.test.ts+++ b/src/daemon/src/cli/daemonStop.test.ts@@ -35,18 +35,14 @@ describe("daemonStop — event-loop friendly (no spin loop)", () => {// where the event lags behind the OS process actually being gone).const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));- const machineKey = "cmk_test_key";+ const id = "abc123def456";const daemonsDir = path.join(baseDir, "daemons");- fs.mkdirSync(daemonsDir, { recursive: true });- // pidfile name is <sha256(machineKey).slice(0,12)>.pid — we don't care- // about the exact hash here; just create one that daemonStop will find- // by re-computing the same hash.- const crypto = await import("crypto");- const hash = crypto.createHash("sha256").update(machineKey).digest("hex").slice(0, 12);- pidfile = path.join(daemonsDir, `${hash}.pid`);- fs.writeFileSync(pidfile, JSON.stringify({ pid: child.pid, key: machineKey }));+ // Per-key subdir layout (C0): pidfile is daemons/<id>/daemon.pid.+ fs.mkdirSync(path.join(daemonsDir, id), { recursive: true });+ pidfile = path.join(daemonsDir, id, "daemon.pid");+ fs.writeFileSync(pidfile, JSON.stringify({ pid: child.pid, key: "cmk_test_key" }));- const stopPromise = daemonStop({ machineKey, baseDir });+ const stopPromise = daemonStop({ id, baseDir });expect(stopPromise).toBeInstanceOf(Promise);await stopPromise;@@ -63,10 +59,11 @@ describe("daemonStop — event-loop friendly (no spin loop)", () => {const machineKey = "cmk_secret_should_not_be_needed";const daemonsDir = path.join(baseDir, "daemons");- fs.mkdirSync(daemonsDir, { recursive: true });const crypto = await import("crypto");const id = crypto.createHash("sha256").update(machineKey).digest("hex").slice(0, 12);- pidfile = path.join(daemonsDir, `${id}.pid`);+ // Per-key subdir (C0): daemons/<id>/daemon.pid — id is the subdir name.+ fs.mkdirSync(path.join(daemonsDir, id), { recursive: true });+ pidfile = path.join(daemonsDir, id, "daemon.pid");fs.writeFileSync(pidfile, JSON.stringify({ pid: child.pid, key: machineKey }));// Stop using ONLY the id (what `daemon list` shows) — the credentialdiff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex db1fe0a09..995a05740 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -810,17 +810,15 @@ function buildProgram(): Command {daemon.command("stop")- .argument("[id]", "daemon id from `alook daemon list` (the ID column)")+ .argument("<id>", "daemon id from `alook daemon list` (the ID column)").description("stop a daemon by its id (from `alook daemon list`)")- .option("--machine-key <key>", "legacy: identify the daemon by full machine key instead of id").option("--base-dir <path>", "data directory (or ALOOK_DATA_DIR env)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })- .action(async function (this: Command, id: string | undefined) {+ .action(async function (this: Command, id: string) {const localOpts = this.opts();await daemonStop({id,- machineKey: localOpts.machineKey as string | undefined,baseDir: localOpts.baseDir as string | undefined,});});@@ -842,13 +840,23 @@ function buildProgram(): Command {daemon.command("status")- .description("dump each agent's current FSM state from the daemon's status snapshot")+ .argument("[id]", "daemon id from `alook daemon list` (omit if only one daemon)")+ .description("dump each agent's current FSM state from a daemon's status snapshot").option("--base-dir <path>", "data directory (or ALOOK_DATA_DIR env)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })- .action(function (this: Command) {+ .action(function (this: Command, id: string | undefined) {const localOpts = this.opts();- const status = daemonStatus({ baseDir: localOpts.baseDir as string | undefined });+ const status = daemonStatus({ id, baseDir: localOpts.baseDir as string | undefined });+ // Multiple daemons + no id → ambiguous: tell the reader which id to pass+ // (status is per-daemon since C0, so it can't guess which one).+ if (status.ambiguous) {+ printEnvelope({+ error: "multiple daemons on this machine — pass an id: `alook daemon status <id>`",+ hint: `available ids: ${(status.availableIds ?? []).join(", ")} (see \`alook daemon list\`)`,+ });+ return;+ }// ALWAYS surface freshness — a stale snapshot must never read as live// truth (the "state unsynced" blind spot this feature kills). The reader// gets the raw fields + an explicit freshness verdict + snapshot age.diff --git a/src/daemon/src/util/statusFile.ts b/src/daemon/src/util/statusFile.tsindex 19d2f083a..c266956c0 100644--- a/src/daemon/src/util/statusFile.ts+++ b/src/daemon/src/util/statusFile.ts@@ -4,8 +4,10 @@* The FSM daemon has NO IPC — `daemon stop`/`list`/`status` are separate CLI* processes, and `manager.snapshot()` lives only inside the running daemon. So* to answer "what is each agent's FSM state right now" out-of-band, the running- * daemon periodically writes a slim projection to `<baseDir>/status.json` and- * the `daemon status` CLI reads that file (Cecilia's ruling (a): snapshot-file,+ * daemon periodically writes a slim projection to its per-key status file+ * (`daemons/<keyHash>/status.json` since batch C0 — was a single global+ * `<baseDir>/status.json`, which multiple daemons clobbered) and the+ * `daemon status` CLI reads that file (Cecilia's ruling (a): snapshot-file,* not a control listener — zero new network/attack surface, crash-safe: if the* daemon dies the last frame is still readable). See plans/daemon-fsm-desync.md.*