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
fix(daemon): report authoritative agent counts (#556)
Gustavo Ye993d979a391e
diff --git a/src/daemon/src/cli/daemonList.test.ts b/src/daemon/src/cli/daemonList.test.tsindex e77bd23a2..583a39acb 100644--- a/src/daemon/src/cli/daemonList.test.ts+++ b/src/daemon/src/cli/daemonList.test.ts@@ -162,6 +162,37 @@ describe("daemonList — C0 per-daemon subdir layout + multi-daemon isolation",expect(row!.running).toBe(4); // only the working ones → renders "4/6"});+ it("prefers authoritative machine counts over conflicting historical FSM rows", () => {+ const id = "cm_summary_wins";+ writeDaemon(id, process.pid, 6, Date.now(), 5);+ const statusPath = path.join(baseDir, "daemons", id, "status.json");+ const snapshot = JSON.parse(fs.readFileSync(statusPath, "utf8"));+ fs.writeFileSync(statusPath, JSON.stringify({+ ...snapshot,+ agentSummary: { total: 4, running: 2 },+ }));++ const row = daemonList({ baseDir }).find((item) => item.id === id);+ expect(row).toMatchObject({ agents: 4, running: 2 });+ expect(renderDaemonList([row!])).toContain("2/4");+ });++ it("renders unknown instead of a false zero before the bot roster is loaded", () => {+ const id = "cm_summary_unknown";+ writeDaemon(id, process.pid, 3, Date.now(), 3);+ const statusPath = path.join(baseDir, "daemons", id, "status.json");+ const snapshot = JSON.parse(fs.readFileSync(statusPath, "utf8"));+ fs.writeFileSync(statusPath, JSON.stringify({+ ...snapshot,+ agentSummary: { total: null, running: 0 },+ }));++ const row = daemonList({ baseDir }).find((item) => item.id === id);+ expect(row).toMatchObject({ agents: null, running: 0 });+ expect(renderDaemonList([row!])).toContain("—");+ expect(renderDaemonList([row!])).not.toContain("0/0");+ });+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.diff --git a/src/daemon/src/cli/daemonStart.test.ts b/src/daemon/src/cli/daemonStart.test.tsindex a75addb83..65111e4bf 100644--- a/src/daemon/src/cli/daemonStart.test.ts+++ b/src/daemon/src/cli/daemonStart.test.ts@@ -59,13 +59,14 @@ describe("daemonStatus — reads snapshot + always flags freshness (batch E2)",// Per-key layout (C0): status lives at daemons/<id>/status.json.const ID = "cm_status_test_123";const daemonSubdir = () => path.join(baseDir, "daemons", ID);- const writeSnap = (writtenAt: number) => {+ const writeSnap = (writtenAt: number, agentSummary?: { total: number | null; running: number }) => {const dir = daemonSubdir();fs.mkdirSync(dir, { recursive: true });fs.writeFileSync(path.join(dir, "status.json"),JSON.stringify({writtenAt,+ ...(agentSummary ? { agentSummary } : {}),agents: [{ agentId: "a1", status: "running", derivedActivity: "idle", turnActive: false, inbox: 0, sinceProgressMs: 10, stoppingSince: null },],@@ -81,15 +82,23 @@ describe("daemonStatus — reads snapshot + always flags freshness (batch E2)",});it("recent snapshot → 'fresh' with the agent projection + age", () => {- writeSnap(1000);+ writeSnap(1000, { total: 4, running: 2 });const r = daemonStatus({ id: ID, baseDir, now: () => 3000 }); // 2s oldexpect(r.found).toBe(true);expect(r.freshness).toBe("fresh");expect(r.ageMs).toBe(2000);+ expect(r.agentSummary).toEqual({ total: 4, running: 2 });expect(r.agents[0]?.agentId).toBe("a1");expect(r.agents[0]?.derivedActivity).toBe("idle");});+ it("keeps an unknown authoritative total distinct from zero", () => {+ writeSnap(1000, { total: null, running: 0 });+ const r = daemonStatus({ id: ID, baseDir, now: () => 1000 });++ expect(r.agentSummary).toEqual({ total: null, running: 0 });+ });+it("recent snapshot resolvable WITHOUT an id when only one daemon exists (auto-pick)", () => {writeSnap(1000);const r = daemonStatus({ baseDir, now: () => 3000 });diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.tsindex 3c356f74a..6d6208f22 100644--- a/src/daemon/src/cli/daemonStart.ts+++ b/src/daemon/src/cli/daemonStart.ts@@ -507,10 +507,9 @@ export interface DaemonInfo {* (`daemons/<id>/status.json`, per-daemon since C0). NULL when no snapshot yet* (or a dead daemon). Per-row accurate even with multiple daemons sharing a* baseDir (pre-C0 the global single file made every row show the last- * writer's count). `running` = agents with derivedActivity "running" (actually- * working a turn); `agents` = total registered — the render shows- * `running/agents` so an operator sees "how many are busy" not just "how many- * exist" (C2, the AGENTS-count-imprecision fix).+ * writer's count). Current daemons publish `running` from the process+ * manager's owned sessions and `agents` from the machine-scoped bound-bot+ * roster; older snapshots retain the FSM-row fallback for compatibility.*/agents: number | null;running: number | null;@@ -555,8 +554,14 @@ export function daemonList(opts: DaemonListOpts): DaemonInfo[] {if (alive && statusPath) {const s = daemonStatusFromFile(statusPath, now);if (s.found) {- agents = s.agents.length;- running = s.agents.filter((a) => a.derivedActivity === "running").length;+ if (s.agentSummary) {+ agents = s.agentSummary.total;+ running = s.agentSummary.running;+ } else {+ // Compatibility with snapshots written by older daemons.+ agents = s.agents.length;+ running = s.agents.filter((a) => a.derivedActivity === "running").length;+ }lastActiveMs = daemonLastActiveMs(s, now);}}@@ -607,6 +612,8 @@ export interface DaemonStatusResult {freshness: "fresh" | "stale" | "missing";/** The snapshot's own writtenAt (ms epoch), or null. */writtenAt: number | null;+ /** Authoritative list counts when written by a current daemon. */+ agentSummary: DaemonStatusSnapshot["agentSummary"] | null;agents: DaemonStatusSnapshot["agents"];/*** Set when no `id` was given AND more than one daemon exists — the caller must@@ -620,7 +627,24 @@ export interface DaemonStatusResult {/** Older than this ⇒ "stale" (a few status-write intervals of slack). */const STATUS_STALE_MS = 20_000;-const MISSING_STATUS: DaemonStatusResult = { found: false, ageMs: null, freshness: "missing", writtenAt: null, agents: [] };+const MISSING_STATUS: DaemonStatusResult = {+ found: false,+ ageMs: null,+ freshness: "missing",+ writtenAt: null,+ agentSummary: null,+ agents: [],+};++function validAgentSummary(value: unknown): DaemonStatusSnapshot["agentSummary"] | null {+ if (!value || typeof value !== "object") return null;+ const summary = value as { total?: unknown; running?: unknown };+ const validTotal = summary.total === null+ || (Number.isInteger(summary.total) && (summary.total as number) >= 0);+ const validRunning = Number.isInteger(summary.running) && (summary.running as number) >= 0;+ if (!validTotal || !validRunning) return null;+ return { total: summary.total as number | null, running: summary.running as number };+}/** Read+parse ONE status.json at a known path. Never throws (best-effort). */function daemonStatusFromFile(statusPath: string, nowMs: number): DaemonStatusResult {@@ -633,6 +657,7 @@ function daemonStatusFromFile(statusPath: string, nowMs: number): DaemonStatusReageMs,freshness: ageMs <= STATUS_STALE_MS ? "fresh" : "stale",writtenAt: snap.writtenAt,+ agentSummary: validAgentSummary(snap.agentSummary),agents: Array.isArray(snap.agents) ? snap.agents : [],};} catch {diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 9e3e6299a..c5832d928 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -84,9 +84,10 @@ function relTime(ms: number | null, nowMs: number): string {/*** Render `daemon list` as a human table (C2/C3). Columns: ID (pass to `daemon- * stop <id>`), AGENTS (`running/total` — how many are actually working a turn- * vs total registered, C2), LAST ACTIVE, PID, STATE. Data is per-daemon since- * C0 (each row reads its own daemon's status.json), so no multi-daemon caveat.+ * stop <id>`), AGENTS (`running/total` — how many manager-owned sessions are+ * live vs total bots bound to the machine), LAST ACTIVE, PID, STATE. Data is+ * per-daemon since C0 (each row reads its own daemon's status.json), so no+ * multi-daemon caveat.* NO machine key / hash prefix (credential stays out of human view, red line 2).*/export function renderDaemonList(daemons: DaemonInfo[], nowMs: number = Date.now()): string {@@ -94,7 +95,7 @@ export function renderDaemonList(daemons: DaemonInfo[], nowMs: number = Date.nowconst header = ["ID", "AGENTS", "LAST ACTIVE", "PID", "STATE"];const rows = daemons.map((d) => [d.id,- // `running/total`: e.g. "2/8" = 2 working, 8 registered. "—" if no snapshot.+ // `running/total`: e.g. "2/8" = 2 live, 8 bound. "—" if no snapshot.d.agents == null ? "—" : `${d.running ?? 0}/${d.agents}`,relTime(d.lastActiveMs, nowMs),String(d.pid),diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 8cbc2e526..de73ca6f4 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -757,6 +757,215 @@ for await (const line of createInterface({ input: process.stdin })) {}});+ it("writes machine-bound bot totals after warmup and keeps bot pushes in sync", async () => {+ vi.useFakeTimers();+ const sockets: FakeSocket[] = [];+ const root = mkdtempSync(join(tmpdir(), "daemon-status-summary-"));+ startupSweepDirs.push(root);+ const statusFilePath = join(root, "status.json");+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL) => {+ if (String(url).includes("/api/community/daemon/bots")) {+ return Response.json({+ bots: [+ { id: "bot_1", name: "One", discriminator: "0001" },+ { id: "bot_2", name: "Two", discriminator: "0002" },+ ],+ });+ }+ return Response.json({});+ }));++ const daemon = await createDaemon({+ machineKey: "cmk_status_summary",+ serverUrl: "http://localhost:9999",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as never,+ runtimeReport: [],+ driverFor: () => fakeDriver,+ capabilities: [],+ statusFilePath,+ workingDirectoryBase: root,+ tickIntervalMs: 1_000_000,+ });++ try {+ expect(JSON.parse(readFileSync(statusFilePath, "utf8")).agentSummary).toEqual({+ total: null,+ running: 0,+ });++ sockets[0].emit("open");+ await vi.advanceTimersByTimeAsync(5_000);+ expect(JSON.parse(readFileSync(statusFilePath, "utf8")).agentSummary).toEqual({+ total: 2,+ running: 0,+ });++ sockets[0].emit("message", JSON.stringify({+ type: "bot:added",+ botId: "bot_3",+ name: "Three",+ discriminator: "0003",+ }));+ await vi.advanceTimersByTimeAsync(5_000);+ expect(JSON.parse(readFileSync(statusFilePath, "utf8")).agentSummary.total).toBe(3);++ sockets[0].emit("message", JSON.stringify({ type: "bot:removed", botId: "bot_2" }));+ await vi.advanceTimersByTimeAsync(5_000);+ expect(JSON.parse(readFileSync(statusFilePath, "utf8")).agentSummary.total).toBe(2);+ } finally {+ await daemon.stop();+ vi.useRealTimers();+ }+ });++ it("counts manager-owned sessions across bot removal and physical exit", async () => {+ vi.useFakeTimers();+ const sockets: FakeSocket[] = [];+ const sessions: DaemonFakeSession[] = [];+ const root = mkdtempSync(join(tmpdir(), "daemon-status-running-"));+ startupSweepDirs.push(root);+ mkdirSync(join(root, "bot_1"));+ mkdirSync(join(root, "bot_2"));+ const statusFilePath = join(root, "status.json");+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url.includes("/api/community/daemon/bots")) {+ return Response.json({+ bots: [+ { id: "bot_1", name: "One", discriminator: "0001" },+ { id: "bot_2", name: "Two", discriminator: "0002" },+ ],+ });+ }+ if (url.includes("/api/community/daemon/enroll-agent")) {+ return Response.json({ runnerKey: "runner_test" });+ }+ return Response.json({ attempted: 0 });+ }));++ const daemon = await createDaemon({+ machineKey: "cmk_status_running",+ serverUrl: "http://localhost:9999",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as never,+ runtimeReport: [{ id: "codex" }],+ driverFor: () => fullFakeDriver("codex"),+ sessionFactory: () => {+ const session = daemonFakeSession();+ sessions.push(session);+ return session;+ },+ capabilities: [],+ statusFilePath,+ workingDirectoryBase: root,+ tickIntervalMs: 1_000_000,+ });+ const summary = () => JSON.parse(readFileSync(statusFilePath, "utf8")).agentSummary;+ const wake = (agentId: string, latestSeq: number) => sockets[0].emit("message", JSON.stringify({+ type: "agent:wake",+ agentId,+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: `launch_${latestSeq}`,+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq },+ }));++ try {+ sockets[0].emit("open");+ await vi.advanceTimersByTimeAsync(5_000);+ expect(summary()).toEqual({ total: 2, running: 0 });++ wake("bot_1", 1);+ await vi.advanceTimersByTimeAsync(1);+ expect(sessions).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(5_000);+ expect(summary()).toEqual({ total: 2, running: 1 });++ sockets[0].emit("message", JSON.stringify({ type: "bot:removed", botId: "bot_1" }));+ await vi.advanceTimersByTimeAsync(1);+ await vi.advanceTimersByTimeAsync(5_000);+ expect(summary()).toEqual({ total: 1, running: 0 });++ wake("bot_2", 2);+ await vi.advanceTimersByTimeAsync(1);+ expect(sessions).toHaveLength(2);+ await vi.advanceTimersByTimeAsync(5_000);+ expect(summary()).toEqual({ total: 1, running: 1 });++ await sessions[1]!.fire("exit");+ await vi.advanceTimersByTimeAsync(1);+ await vi.advanceTimersByTimeAsync(5_000);+ expect(summary()).toEqual({ total: 1, running: 0 });+ } finally {+ await daemon.stop();+ vi.useRealTimers();+ }+ });++ it("marks a deferred roster fetch authoritative after warmup exhaustion", async () => {+ vi.useFakeTimers();+ const sockets: FakeSocket[] = [];+ const sessions: DaemonFakeSession[] = [];+ const root = mkdtempSync(join(tmpdir(), "daemon-status-deferred-roster-"));+ startupSweepDirs.push(root);+ mkdirSync(join(root, "bot_1"));+ const statusFilePath = join(root, "status.json");+ let allowRoster = false;+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url.includes("/api/community/daemon/bots")) {+ return allowRoster+ ? Response.json({ bots: [{ id: "bot_1", name: "One", discriminator: "0001" }] })+ : Response.json({ error: "unavailable" }, { status: 503 });+ }+ if (url.includes("/api/community/daemon/enroll-agent")) {+ return Response.json({ runnerKey: "runner_test" });+ }+ return Response.json({ attempted: 0 });+ }));++ const daemon = await createDaemon({+ machineKey: "cmk_status_deferred_roster",+ serverUrl: "http://localhost:9999",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as never,+ runtimeReport: [{ id: "codex" }],+ driverFor: () => fullFakeDriver("codex"),+ sessionFactory: () => {+ const session = daemonFakeSession();+ sessions.push(session);+ return session;+ },+ capabilities: [],+ statusFilePath,+ workingDirectoryBase: root,+ tickIntervalMs: 1_000_000,+ });+ const summary = () => JSON.parse(readFileSync(statusFilePath, "utf8")).agentSummary;++ try {+ sockets[0].emit("open");+ await vi.advanceTimersByTimeAsync(35_000);+ expect(summary()).toEqual({ total: null, running: 0 });++ allowRoster = true;+ sockets[0].emit("message", JSON.stringify({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "launch_deferred",+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },+ }));+ await vi.advanceTimersByTimeAsync(1);+ expect(sessions).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(5_000);+ expect(summary()).toEqual({ total: 1, running: 1 });+ } finally {+ await daemon.stop();+ vi.useRealTimers();+ }+ });+it("consumes diagnostics before Router and invokes the injected handler once", async () => {const sockets: FakeSocket[] = [];const routerEntry = spyOnRouterCommandEntry();diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 9bc98fb2b..ebd531a4a 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -575,6 +575,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDastring,{ name: string; discriminator: string; description?: string; ownerName?: string; ownerDiscriminator?: string }>();+ let botCacheReady = false;async function listMyBotsHttp(): Promise<Array<{@@ -604,6 +605,20 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDareturn json.bots ?? [];}+ function replaceBotCache(bots: Awaited<ReturnType<typeof listMyBotsHttp>>): void {+ botsById.clear();+ for (const b of bots) {+ botsById.set(b.id, {+ name: b.name,+ discriminator: b.discriminator,+ description: b.description,+ ownerName: b.ownerName,+ ownerDiscriminator: b.ownerDiscriminator,+ });+ }+ botCacheReady = true;+ }+async function coldStartWarmup(): Promise<void> {const start = Date.now();let attempt = 0;@@ -611,16 +626,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDatry {const bots = await listMyBotsHttp();// Server snapshot wins — reconcile the cache.- botsById.clear();- for (const b of bots) {- botsById.set(b.id, {- name: b.name,- discriminator: b.discriminator,- description: b.description,- ownerName: b.ownerName,- ownerDiscriminator: b.ownerDiscriminator,- });- }+ replaceBotCache(bots);log.info("cold-start bot-cache warmup succeeded", { bots: bots.length, attempt });return;} catch {@@ -927,7 +933,14 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaconst statusPath = opts.statusFilePath;const writeStatus = () => {const nowMs = Date.now();- writeStatusFile(statusPath, { writtenAt: nowMs, agents: manager.statusProjection(nowMs) });+ writeStatusFile(statusPath, {+ writtenAt: nowMs,+ agentSummary: {+ total: botCacheReady ? botsById.size : null,+ running: manager.runningAgentCount(),+ },+ agents: manager.statusProjection(nowMs),+ });};writeStatus(); // one immediately so `daemon status` works right after bootstatusTimer = setInterval(writeStatus, STATUS_WRITE_INTERVAL_MS);@@ -958,15 +971,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// the fetch once before erroring out.try {const bots = await listMyBotsHttp();- for (const b of bots) {- botsById.set(b.id, {- name: b.name,- discriminator: b.discriminator,- description: b.description,- ownerName: b.ownerName,- ownerDiscriminator: b.ownerDiscriminator,- });- }+ replaceBotCache(bots);} catch {// Fall through — still treat as unknown below.}diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 07b4df220..a4d6ffe27 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -652,6 +652,10 @@ export class AgentProcessManager {snapshot(): ManagerState {return this.state;}+ /** Number of physical agent sessions currently owned by this manager. */+ runningAgentCount(): number {+ return this.sessions.size;+ }auditContext(agentId: string): { sessionId: string | null; launchId: string | null } {return {sessionId: this.liveSessions.get(agentId) ?? null,diff --git a/src/daemon/src/util/statusFile.test.ts b/src/daemon/src/util/statusFile.test.tsindex 2882228b2..7b5c66a40 100644--- a/src/daemon/src/util/statusFile.test.ts+++ b/src/daemon/src/util/statusFile.test.ts@@ -15,6 +15,7 @@ describe("writeStatusFile (batch E2 — atomic daemon status snapshot)", () => {const snap: DaemonStatusSnapshot = {writtenAt: 1000,+ agentSummary: { total: 3, running: 1 },agents: [{ agentId: "a1", status: "running", derivedActivity: "idle", turnActive: false, inbox: 0, sinceProgressMs: 42, stoppingSince: null },],diff --git a/src/daemon/src/util/statusFile.ts b/src/daemon/src/util/statusFile.tsindex c266956c0..6a1ef0089 100644--- a/src/daemon/src/util/statusFile.ts+++ b/src/daemon/src/util/statusFile.ts@@ -23,6 +23,19 @@ import { writeFileSync, renameSync } from "node:fs";export interface DaemonStatusSnapshot {/** ms epoch when this snapshot was written — the reader flags its age. */writtenAt: number;+ /**+ * Authoritative machine-level counts for `daemon list`.+ *+ * `total` is null until the daemon has loaded its machine-scoped bot roster;+ * reporting zero before that point would turn an unknown into a lie.+ * `running` comes from the process manager's owned physical sessions.+ *+ * Optional for compatibility with snapshots written by older daemons.+ */+ agentSummary?: {+ total: number | null;+ running: number;+ };agents: Array<{agentId: string;status: string;