diff --git a/packages/core/src/__tests__/command-center-live.test.ts b/packages/core/src/__tests__/command-center-live.test.ts new file mode 100644 index 0000000000..2cb71fc074 --- /dev/null +++ b/packages/core/src/__tests__/command-center-live.test.ts @@ -0,0 +1,150 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync } from "node:fs"; +import { rm } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; + +import { Database } from "../db.js"; +import { composeLiveSnapshot } from "../command-center-live.js"; + +function insertSession( + db: Database, + opts: { + id: string; + taskId?: string | null; + agentState: string; + terminationReason?: string | null; + worktreePath?: string | null; + purpose?: string; + }, +): void { + db.prepare( + `INSERT INTO cli_sessions + (id, taskId, purpose, projectId, adapterId, agentState, terminationReason, worktreePath, createdAt, updatedAt) + VALUES (?, ?, ?, 'proj-1', 'claude-local', ?, ?, ?, ?, ?)`, + ).run( + opts.id, + opts.taskId ?? null, + opts.purpose ?? "execute", + opts.agentState, + opts.terminationReason ?? null, + opts.worktreePath ?? null, + "2026-03-01T00:00:00.000Z", + "2026-03-01T00:00:00.000Z", + ); +} + +function insertAgent(db: Database, id: string): void { + db.prepare( + `INSERT INTO agents (id, name, role, state, createdAt, updatedAt) + VALUES (?, ?, 'executor', 'idle', ?, ?)`, + ).run(id, id, "2026-03-01T00:00:00.000Z", "2026-03-01T00:00:00.000Z"); +} + +function insertRun( + db: Database, + opts: { id: string; agentId: string; status: string; taskId?: string }, +): void { + db.prepare( + `INSERT INTO agentRuns (id, agentId, data, startedAt, endedAt, status) + VALUES (?, ?, ?, ?, ?, ?)`, + ).run( + opts.id, + opts.agentId, + JSON.stringify(opts.taskId ? { taskId: opts.taskId } : {}), + "2026-03-01T00:00:00.000Z", + opts.status === "active" ? null : "2026-03-01T01:00:00.000Z", + opts.status, + ); +} + +function insertTask(db: Database, id: string, column: string): void { + db.prepare( + `INSERT INTO tasks (id, description, "column", createdAt, updatedAt) + VALUES (?, 'desc', ?, ?, ?)`, + ).run(id, column, "2026-03-01T00:00:00.000Z", "2026-03-01T00:00:00.000Z"); +} + +describe("command-center-live", () => { + let tmpDir: string; + let db: Database; + + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), "kb-cc-live-")); + db = new Database(join(tmpDir, ".fusion")); + db.init(); + }); + + afterEach(async () => { + db.close(); + await rm(tmpDir, { recursive: true, force: true }); + }); + + it("composes an empty snapshot with zeroed counts (not nulls)", () => { + const snap = composeLiveSnapshot(db, Date.parse("2026-03-01T12:00:00.000Z")); + expect(snap.capturedAt).toBe("2026-03-01T12:00:00.000Z"); + expect(snap.activeSessions).toBe(0); + expect(snap.activeRuns).toBe(0); + expect(snap.activeNodes).toBe(0); + expect(snap.sessions).toEqual([]); + expect(snap.runs).toEqual([]); + expect(snap.columns).toEqual([]); + }); + + it("counts active sessions and active nodes, excluding terminal/terminated", () => { + insertSession(db, { id: "s1", agentState: "busy", worktreePath: "/wt/node-a" }); + insertSession(db, { id: "s2", agentState: "ready", worktreePath: "/wt/node-b" }); + // same worktree as s1 → one distinct node + insertSession(db, { id: "s3", agentState: "waitingOnInput", worktreePath: "/wt/node-a" }); + // terminal state → excluded + insertSession(db, { id: "s4", agentState: "done", worktreePath: "/wt/node-c" }); + // terminated → excluded even though state is non-terminal + insertSession(db, { + id: "s5", + agentState: "busy", + terminationReason: "userExited", + worktreePath: "/wt/node-d", + }); + + const snap = composeLiveSnapshot(db); + expect(snap.activeSessions).toBe(3); // s1, s2, s3 + expect(snap.activeNodes).toBe(2); // /wt/node-a, /wt/node-b + expect(snap.sessions.map((s) => s.id).sort()).toEqual(["s1", "s2", "s3"]); + }); + + it("counts active runs only and extracts taskId from run data", () => { + insertAgent(db, "agent-1"); + insertRun(db, { id: "r1", agentId: "agent-1", status: "active", taskId: "FN-1" }); + insertRun(db, { id: "r2", agentId: "agent-1", status: "completed", taskId: "FN-2" }); + insertRun(db, { id: "r3", agentId: "agent-1", status: "active" }); + + const snap = composeLiveSnapshot(db); + expect(snap.activeRuns).toBe(2); + expect(snap.runs.map((r) => r.id).sort()).toEqual(["r1", "r3"]); + const r1 = snap.runs.find((r) => r.id === "r1"); + expect(r1?.taskId).toBe("FN-1"); + const r3 = snap.runs.find((r) => r.id === "r3"); + expect(r3?.taskId).toBeNull(); + }); + + it("produces current per-column task counts", () => { + insertTask(db, "FN-1", "todo"); + insertTask(db, "FN-2", "todo"); + insertTask(db, "FN-3", "in-progress"); + insertTask(db, "FN-4", "done"); + + const snap = composeLiveSnapshot(db); + const byColumn = Object.fromEntries(snap.columns.map((c) => [c.column, c.count])); + expect(byColumn).toEqual({ todo: 2, "in-progress": 1, done: 1 }); + }); + + it("is a pure read — does not mutate the database", () => { + insertTask(db, "FN-1", "todo"); + composeLiveSnapshot(db); + composeLiveSnapshot(db); + const count = ( + db.prepare(`SELECT COUNT(*) AS count FROM tasks`).get() as { count: number } + ).count; + expect(count).toBe(1); + }); +}); diff --git a/packages/core/src/command-center-live.ts b/packages/core/src/command-center-live.ts new file mode 100644 index 0000000000..8aa0f71b5d --- /dev/null +++ b/packages/core/src/command-center-live.ts @@ -0,0 +1,185 @@ +import type { Database } from "./db.js"; + +/** + * Live Mission-Control snapshot composer (U6a). + * + * Builds an instantaneous, point-in-time view of orchestration activity from the + * existing tables — `agentRuns` / `agentHeartbeats` (active heartbeat runs), + * `cli_sessions` (live CLI/chat sessions), and `tasks` (current per-column + * counts). It is a **pure read** over a {@link Database} handle: no clock, no + * network, no engine dependency, so the engine, CLI, and the dashboard route + * (U9) can all reuse it. The dashboard's `/api/command-center/live` endpoint is a + * thin adapter over this function (KTD2). + * + * "Live" here means *current state*, not a date range: it counts what is active + * right now (active runs, live sessions) and the present board distribution. The + * snapshot carries a `capturedAt` ISO timestamp so callers can label staleness. + * + * Active definitions: + * - **Active session** — a `cli_sessions` row whose `agentState` is not a + * terminal state (`done`/`dead`) and whose `terminationReason` is still null. + * - **Active run** — an `agentRuns` row with `status = 'active'` (matching the + * {@link import("./types.js").AgentHeartbeatRun} status union). + * - **Active node** — a distinct, non-null node id observed across active + * sessions (no `nodeId` column exists on `agentRuns`, so nodes are sourced + * from `cli_sessions`). + */ + +/** A single active CLI/chat session in the live snapshot. */ +export interface LiveSession { + id: string; + /** Bound task id, or null for an unbound (e.g. chat) session. */ + taskId: string | null; + purpose: string; + adapterId: string; + agentState: string; + /** Worktree/node path the session runs in, or null. */ + worktreePath: string | null; + updatedAt: string; +} + +/** A single active heartbeat run in the live snapshot. */ +export interface LiveRun { + id: string; + agentId: string; + taskId: string | null; + startedAt: string; +} + +/** Current task count for one board column. */ +export interface ColumnCount { + column: string; + count: number; +} + +/** The composed live Mission-Control snapshot. */ +export interface LiveSnapshot { + /** ISO-8601 timestamp this snapshot was composed. */ + capturedAt: string; + /** Number of active (non-terminal, non-terminated) CLI/chat sessions. */ + activeSessions: number; + /** Number of active heartbeat runs (`agentRuns.status = 'active'`). */ + activeRuns: number; + /** Distinct non-null nodes with at least one active session. */ + activeNodes: number; + /** The active sessions, most-recently-updated first. */ + sessions: LiveSession[]; + /** The active heartbeat runs, most-recently-started first. */ + runs: LiveRun[]; + /** Current per-column task counts (the SDLC funnel's live snapshot). */ + columns: ColumnCount[]; +} + +/** Terminal CLI agent states — a session in one of these is not "active". */ +const TERMINAL_SESSION_STATES = ["done", "dead"] as const; + +interface SessionRow { + id: string; + taskId: string | null; + purpose: string; + adapterId: string; + agentState: string; + worktreePath: string | null; + updatedAt: string; +} + +interface ColumnRow { + column: string; + count: number; +} + +interface CountRow { + count: number; +} + +/** + * Compose a live Mission-Control snapshot from the current database state. + * + * Pure and synchronous: takes a {@link Database} handle and returns plain data. + * `capturedAt` defaults to `new Date().toISOString()`; pass `now` (epoch ms) to + * make the timestamp deterministic in tests — no other value reads the clock. + */ +export function composeLiveSnapshot(db: Database, now?: number): LiveSnapshot { + const capturedAt = new Date(now ?? Date.now()).toISOString(); + + const terminalPlaceholders = TERMINAL_SESSION_STATES.map(() => "?").join(", "); + + // Active sessions: not in a terminal state and not terminated. + const sessionRows = db + .prepare( + `SELECT id, taskId, purpose, adapterId, agentState, worktreePath, updatedAt + FROM cli_sessions + WHERE agentState NOT IN (${terminalPlaceholders}) + AND terminationReason IS NULL + ORDER BY updatedAt DESC`, + ) + .all(...TERMINAL_SESSION_STATES) as SessionRow[]; + const sessions: LiveSession[] = sessionRows.map((r) => ({ + id: r.id, + taskId: r.taskId ?? null, + purpose: r.purpose, + adapterId: r.adapterId, + agentState: r.agentState, + worktreePath: r.worktreePath ?? null, + updatedAt: r.updatedAt, + })); + + // Active nodes: distinct non-null worktree paths across active sessions. + // (cli_sessions has no nodeId column; worktreePath is the per-node locator.) + const activeNodes = new Set( + sessions + .map((s) => s.worktreePath) + .filter((p): p is string => typeof p === "string" && p.length > 0), + ).size; + + // Active heartbeat runs. + const runRows = db + .prepare( + `SELECT id, agentId, startedAt, data + FROM agentRuns + WHERE status = 'active' + ORDER BY startedAt DESC`, + ) + .all() as Array<{ id: string; agentId: string; startedAt: string; data: string }>; + const runs: LiveRun[] = runRows.map((r) => { + let taskId: string | null = null; + try { + const data = JSON.parse(r.data) as { taskId?: string }; + if (typeof data.taskId === "string") taskId = data.taskId; + } catch { + // Malformed run data → leave taskId null rather than throw. + } + return { id: r.id, agentId: r.agentId, taskId, startedAt: r.startedAt }; + }); + + const activeRuns = ( + db + .prepare(`SELECT COUNT(*) AS count FROM agentRuns WHERE status = 'active'`) + .get() as CountRow + ).count; + + // Current per-column task counts. `column` is a reserved word in the schema, + // so it is quoted. + const columnRows = db + .prepare( + `SELECT "column" AS column, COUNT(*) AS count + FROM tasks + GROUP BY "column" + ORDER BY count DESC`, + ) + .all() as ColumnRow[]; + const columns: ColumnCount[] = columnRows.map((r) => ({ + column: r.column, + count: r.count, + })); + + return { + capturedAt, + activeSessions: sessions.length, + activeRuns, + activeNodes, + sessions, + runs, + columns, + }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index cd14f04927..329086268c 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -572,6 +572,13 @@ export type { LanguageCount, LocSummary, } from "./productivity-analytics.js"; +export { composeLiveSnapshot } from "./command-center-live.js"; +export type { + LiveSnapshot, + LiveSession, + LiveRun, + ColumnCount, +} from "./command-center-live.js"; export { STALLED_REVIEW_REENQUEUE_THRESHOLD, STALLED_REVIEW_INVALID_TRANSITION_THRESHOLD, diff --git a/packages/dashboard/src/__tests__/register-command-center-routes.auth.test.ts b/packages/dashboard/src/__tests__/register-command-center-routes.auth.test.ts new file mode 100644 index 0000000000..9dfd73fec6 --- /dev/null +++ b/packages/dashboard/src/__tests__/register-command-center-routes.auth.test.ts @@ -0,0 +1,92 @@ +// @vitest-environment node + +/** + * Auth integration for the Command Center endpoints: every endpoint, including + * `/live`, must be rejected with 401 when unauthenticated and accepted with a + * valid bearer token. Mirrors `auth-middleware-integration.test.ts` but exercises + * the U9 routes specifically (the registrar adds no auth of its own — it inherits + * the server-level middleware, which is exactly what this asserts). + */ + +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { EventEmitter } from "node:events"; +import type { Task, TaskStore } from "@fusion/core"; +import { request } from "../test-request.js"; +import { createServer } from "../server.js"; + +vi.mock("@fusion/core", async (importOriginal) => { + const { createCoreMock } = await import("../test/mockCoreEngine.js"); + return createCoreMock(() => importOriginal(), {}); +}); + +class MockStore extends EventEmitter { + getRootDir(): string { + return "/tmp/fn-cc-auth-test"; + } + + getFusionDir(): string { + return "/tmp/fn-cc-auth-test/.fusion"; + } + + getDatabase() { + return { + exec: vi.fn(), + prepare: vi.fn().mockReturnValue({ + run: vi.fn().mockReturnValue({ changes: 0 }), + get: vi.fn().mockReturnValue({ count: 0 }), + all: vi.fn().mockReturnValue([]), + }), + }; + } + + getDatabaseHealth() { + return { + healthy: true, + corruptionDetected: false, + corruptionErrors: [], + isRunning: false, + lastCheckedAt: null, + }; + } + + async listTasks(): Promise { + return []; + } +} + +const TOKEN = "fn_cc_test1234567890abcdef"; +const ENDPOINTS = [ + "/api/command-center/tokens", + "/api/command-center/tools", + "/api/command-center/activity", + "/api/command-center/productivity", + "/api/command-center/live", +]; + +describe("Command Center routes — auth", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("rejects unauthenticated requests to every endpoint (incl. /live) with 401", async () => { + const app = createServer(new MockStore() as unknown as TaskStore, { + daemon: { token: TOKEN }, + }); + for (const path of ENDPOINTS) { + const res = await request(app, "GET", path); + expect(res.status, `${path} should be 401 unauthenticated`).toBe(401); + } + }); + + it("accepts every endpoint (incl. /live) with a valid bearer token", async () => { + const app = createServer(new MockStore() as unknown as TaskStore, { + daemon: { token: TOKEN }, + }); + for (const path of ENDPOINTS) { + const res = await request(app, "GET", path, undefined, { + Authorization: `Bearer ${TOKEN}`, + }); + expect(res.status, `${path} should be 200 with token`).toBe(200); + } + }); +}); diff --git a/packages/dashboard/src/__tests__/register-command-center-routes.test.ts b/packages/dashboard/src/__tests__/register-command-center-routes.test.ts new file mode 100644 index 0000000000..21def3601b --- /dev/null +++ b/packages/dashboard/src/__tests__/register-command-center-routes.test.ts @@ -0,0 +1,279 @@ +// @vitest-environment node + +import express, { type NextFunction, type Request, type Response } from "express"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { mkdtempSync } from "node:fs"; +import { rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { EventEmitter } from "node:events"; + +import { Database, emitUsageEvent } from "@fusion/core"; +import type { TaskStore } from "@fusion/core"; +import { request } from "../test-request.js"; +import { ApiError } from "../api-error.js"; +import { + registerCommandCenterRoutes, + resolveRange, + resolveGroupBy, + DEFAULT_WINDOW_DAYS, +} from "../routes/register-command-center-routes.js"; +import type { ApiRoutesContext } from "../routes/types.js"; + +/** Seed a temp DB with a token-bearing task and a tool-call usage event. */ +function seedDb(db: Database, opts: { taskId: string; model: string; tokens: number }): void { + db.prepare( + `INSERT INTO tasks + (id, description, "column", modelProvider, modelId, + tokenUsageInputTokens, tokenUsageOutputTokens, tokenUsageTotalTokens, + tokenUsageLastUsedAt, createdAt, updatedAt) + VALUES (?, 'desc', 'todo', 'anthropic', ?, ?, ?, ?, ?, ?, ?)`, + ).run( + opts.taskId, + opts.model, + opts.tokens, + opts.tokens, + opts.tokens * 2, + "2026-03-01T00:00:00.000Z", + "2026-03-01T00:00:00.000Z", + "2026-03-01T00:00:00.000Z", + ); + emitUsageEvent(db, { + kind: "tool_call", + taskId: opts.taskId, + agentId: "agent-1", + nodeId: "node-1", + category: "edit", + ts: "2026-03-01T00:00:00.000Z", + }); +} + +/** + * Build an express app with the registrar mounted, backed by per-project real + * DBs. The `getScopedStore` resolves the DB by the `projectId` query param, + * proving project scoping at the route boundary. + */ +function buildApp(stores: Record, fallback: TaskStore) { + const app = express(); + app.use(express.json()); + + const router = express.Router(); + const ctx = { + router, + getScopedStore: async (req: Request): Promise => { + const projectId = + typeof req.query.projectId === "string" ? req.query.projectId : undefined; + return projectId && stores[projectId] ? stores[projectId] : fallback; + }, + rethrowAsApiError: (error: unknown, fallbackMessage?: string): never => { + if (error instanceof ApiError) throw error; + throw new ApiError(500, fallbackMessage ?? "Internal error"); + }, + } as unknown as ApiRoutesContext; + + registerCommandCenterRoutes(ctx); + app.use("/api", router); + + // Minimal ApiError → HTTP status mapper (mirrors server.ts behaviour). + app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => { + if (err instanceof ApiError) { + res.status(err.statusCode).json({ error: err.message }); + return; + } + res.status(500).json({ error: "Internal error" }); + }); + + return app; +} + +/** A minimal TaskStore exposing only getDatabase(), which is all the routes use. */ +function storeFor(db: Database): TaskStore { + const store = new EventEmitter() as unknown as TaskStore & { getDatabase(): Database }; + store.getDatabase = () => db; + return store; +} + +describe("register-command-center-routes", () => { + let tmpDir: string; + let dbA: Database; + let dbB: Database; + let app: ReturnType; + + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), "kb-cc-routes-")); + dbA = new Database(join(tmpDir, "a", ".fusion")); + dbA.init(); + dbB = new Database(join(tmpDir, "b", ".fusion")); + dbB.init(); + + // Project A: a known task + tool call. Project B: a *different* marker task. + seedDb(dbA, { taskId: "FN-A1", model: "claude-sonnet-4-5", tokens: 100 }); + seedDb(dbB, { taskId: "FN-B1", model: "claude-opus-4-5", tokens: 999 }); + + const storeA = storeFor(dbA); + const storeB = storeFor(dbB); + app = buildApp({ "proj-a": storeA, "proj-b": storeB }, storeA); + }); + + afterEach(() => { + dbA.close(); + dbB.close(); + rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("returns the token aggregator shape for a fixture DB", async () => { + const res = await request( + app, + "GET", + "/api/command-center/tokens?from=2026-02-01T00:00:00.000Z&to=2026-04-01T00:00:00.000Z&groupBy=model&projectId=proj-a", + ); + expect(res.status).toBe(200); + const body = res.body as Record; + expect(body).toHaveProperty("totals"); + expect(body).toHaveProperty("cost"); + expect(body).toHaveProperty("groups"); + expect(body.groupBy).toBe("model"); + expect((body.totals as { totalTokens: number }).totalTokens).toBe(200); + }); + + it("returns the tools / activity / productivity aggregator shapes", async () => { + const range = "from=2026-02-01T00:00:00.000Z&to=2026-04-01T00:00:00.000Z"; + const tools = await request(app, "GET", `/api/command-center/tools?${range}&projectId=proj-a`); + expect(tools.status).toBe(200); + expect(tools.body).toHaveProperty("autonomyRatio"); + expect((tools.body as { toolCalls: number }).toolCalls).toBe(1); + + const activity = await request(app, "GET", `/api/command-center/activity?${range}&projectId=proj-a`); + expect(activity.status).toBe(200); + expect(activity.body).toHaveProperty("stickiness"); + expect(activity.body).toHaveProperty("mttr"); + + const prod = await request(app, "GET", `/api/command-center/productivity?${range}&projectId=proj-a`); + expect(prod.status).toBe(200); + expect(prod.body).toHaveProperty("loc"); + expect(prod.body).toHaveProperty("byLanguage"); + }); + + it("returns the live snapshot shape", async () => { + const res = await request(app, "GET", "/api/command-center/live?projectId=proj-a"); + expect(res.status).toBe(200); + const body = res.body as Record; + expect(body).toHaveProperty("capturedAt"); + expect(body).toHaveProperty("activeSessions"); + expect(body).toHaveProperty("columns"); + // Project A seeded one 'todo' task. + expect(body.columns).toContainEqual({ column: "todo", count: 1 }); + }); + + it("invalid range params fall back to the default window, not a 500", async () => { + const res = await request( + app, + "GET", + "/api/command-center/tokens?from=not-a-date&to=also-bad&projectId=proj-a", + ); + expect(res.status).toBe(200); + const body = res.body as Record; + // Defaulted window is recent (last 7d), so the 2026-03 fixture is out of + // range → zeroed totals, but never a 500. + expect(body).toHaveProperty("totals"); + }); + + it("missing range params default rather than 500", async () => { + const res = await request(app, "GET", "/api/command-center/tokens?projectId=proj-a"); + expect(res.status).toBe(200); + expect(res.body).toHaveProperty("totals"); + }); + + it("project scoping — project-A request cannot read project-B data (JSON)", async () => { + const a = await request( + app, + "GET", + "/api/command-center/tokens?from=2026-02-01T00:00:00.000Z&to=2026-04-01T00:00:00.000Z&projectId=proj-a", + ); + const b = await request( + app, + "GET", + "/api/command-center/tokens?from=2026-02-01T00:00:00.000Z&to=2026-04-01T00:00:00.000Z&projectId=proj-b", + ); + // A's task had 100 input tokens (total 200); B's had 999 (total 1998). + expect((a.body as { totals: { totalTokens: number } }).totals.totalTokens).toBe(200); + expect((b.body as { totals: { totalTokens: number } }).totals.totalTokens).toBe(1998); + }); + + it("project scoping — /live is scoped per project", async () => { + // Add a distinguishing 'in-review' task only to project B. + dbB.prepare( + `INSERT INTO tasks (id, description, "column", createdAt, updatedAt) + VALUES ('FN-B2', 'd', 'in-review', '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z')`, + ).run(); + + const a = await request(app, "GET", "/api/command-center/live?projectId=proj-a"); + const b = await request(app, "GET", "/api/command-center/live?projectId=proj-b"); + const aColumns = (a.body as { columns: { column: string }[] }).columns.map((c) => c.column); + const bColumns = (b.body as { columns: { column: string }[] }).columns.map((c) => c.column); + expect(aColumns).not.toContain("in-review"); + expect(bColumns).toContain("in-review"); + }); +}); + +describe("resolveRange / resolveGroupBy (param parsing)", () => { + const NOW = Date.parse("2026-06-15T00:00:00.000Z"); + + it("uses valid, ordered ISO bounds as-is", () => { + const r = resolveRange( + { from: "2026-06-01T00:00:00.000Z", to: "2026-06-10T00:00:00.000Z" }, + NOW, + ); + expect(r.defaulted).toBe(false); + expect(r.from).toBe("2026-06-01T00:00:00.000Z"); + expect(r.to).toBe("2026-06-10T00:00:00.000Z"); + }); + + it("defaults to the last-7d window for missing params", () => { + const r = resolveRange({}, NOW); + expect(r.defaulted).toBe(true); + expect(r.to).toBe(new Date(NOW).toISOString()); + expect(r.from).toBe( + new Date(NOW - DEFAULT_WINDOW_DAYS * 24 * 60 * 60 * 1000).toISOString(), + ); + }); + + it("defaults when from > to (inverted range)", () => { + const r = resolveRange( + { from: "2026-06-10T00:00:00.000Z", to: "2026-06-01T00:00:00.000Z" }, + NOW, + ); + expect(r.defaulted).toBe(true); + }); + + it("defaults when a bound is unparseable", () => { + const r = resolveRange({ from: "garbage", to: "2026-06-10T00:00:00.000Z" }, NOW); + expect(r.defaulted).toBe(true); + }); + + it("accepts known groupBy values and ignores unknown ones", () => { + expect(resolveGroupBy({ groupBy: "model" })).toBe("model"); + expect(resolveGroupBy({ groupBy: "provider" })).toBe("provider"); + expect(resolveGroupBy({ groupBy: "bogus" })).toBeUndefined(); + expect(resolveGroupBy({})).toBeUndefined(); + }); +}); + +describe("vite /api proxy negative-lookahead (proxy verification)", () => { + // The exact key from packages/dashboard/vite.config.ts's server.proxy. Real + // /api endpoints must proxy to the backend; app source modules ending in a + // .ts/.tsx (?import) suffix must stay on the Vite dev server. + const PROXY_RE = new RegExp("^/api(?!/.*\\.[jt]sx?(?:\\?|$))(/|$)"); + + it("proxies the real command-center endpoints to the backend", () => { + expect(PROXY_RE.test("/api/command-center/tokens")).toBe(true); + expect(PROXY_RE.test("/api/command-center/live")).toBe(true); + expect(PROXY_RE.test("/api/command-center/activity?from=x&to=y")).toBe(true); + }); + + it("leaves .ts?import source module paths on Vite (not proxied)", () => { + expect(PROXY_RE.test("/api/command-center/foo.ts?import")).toBe(false); + expect(PROXY_RE.test("/api/command-center/Component.tsx?import")).toBe(false); + expect(PROXY_RE.test("/api/something.ts")).toBe(false); + }); +}); diff --git a/packages/dashboard/src/routes.ts b/packages/dashboard/src/routes.ts index 7ccbae277b..3b8a903a0e 100644 --- a/packages/dashboard/src/routes.ts +++ b/packages/dashboard/src/routes.ts @@ -168,6 +168,7 @@ import { registerProxyRoutes } from "./routes/register-proxy-routes.js"; import { registerModelRoutes } from "./routes/register-model-routes.js"; import { registerCustomProviderRoutes } from "./routes/register-custom-provider-routes.js"; import { registerUsageRoutes } from "./routes/register-usage-routes.js"; +import { registerCommandCenterRoutes } from "./routes/register-command-center-routes.js"; import { registerSignalRoutes } from "./routes/register-signal-routes.js"; import { registerAuthRoutes } from "./routes/register-auth-routes.js"; import { registerRuntimeProviderRoutes } from "./routes/register-runtime-provider-routes.js"; @@ -1990,6 +1991,9 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout }); registerUsageRoutes(routeContext); + // U9 — Command Center analytics + live snapshot endpoints. Thin adapters over + // the core aggregators; inherit standard auth + getScopedStore project scoping. + registerCommandCenterRoutes(routeContext); // U11 — inbound external signal webhooks (Sentry/Datadog/PagerDuty/generic). // Each route HMAC-verifies against a per-provider secret; never an // unauthenticated task-creation endpoint. diff --git a/packages/dashboard/src/routes/register-command-center-routes.ts b/packages/dashboard/src/routes/register-command-center-routes.ts new file mode 100644 index 0000000000..ee96649972 --- /dev/null +++ b/packages/dashboard/src/routes/register-command-center-routes.ts @@ -0,0 +1,195 @@ +import { + aggregateTokenAnalytics, + aggregateToolAnalytics, + aggregateActivityAnalytics, + aggregateProductivityAnalytics, + composeLiveSnapshot, + type TokenGroupBy, +} from "@fusion/core"; +import type { Request } from "express"; +import { ApiError } from "../api-error.js"; +import type { ApiRouteRegistrar } from "./types.js"; + +/** + * Command Center analytics API (U9). + * + * Thin HTTP adapters over the Phase-A core aggregators + * (`{token,tool,activity,productivity}-analytics.ts`) and the U6a live-snapshot + * composer (`command-center-live.ts`). All metric math lives in `@fusion/core` + * (KTD2); these handlers only parse the request, resolve the **project-scoped** + * store, and serialize the aggregator output. + * + * Security: + * - Every route inherits the dashboard's standard session/auth middleware via + * the {@link ApiRouteRegistrar} contract — exactly like `register-usage-routes.ts`. + * No analytics endpoint, including `/live`, is unauthenticated; an + * unauthenticated request is rejected with 401 by the server-level auth + * middleware before reaching these handlers. + * - Every endpoint (JSON and `/live`) resolves the database through + * `getScopedStore(req)` before aggregating, so a project-A caller can never + * read project-B data. + * + * Robustness: + * - Missing or invalid `from`/`to`/`groupBy` query params fall back to a + * documented default window (the last {@link DEFAULT_WINDOW_DAYS} days) and a + * no-grouping default — never a 500. See {@link resolveRange}. + */ + +/** Documented default analytics window when range params are absent/invalid. */ +export const DEFAULT_WINDOW_DAYS = 7; + +const VALID_GROUP_BY: ReadonlySet = new Set([ + "model", + "provider", + "node", + "agent", +]); + +/** A resolved, always-valid `[from, to]` ISO range. */ +export interface ResolvedRange { + from: string; + to: string; + /** True when the caller's params were missing/invalid and the default applied. */ + defaulted: boolean; +} + +function isValidIso(value: string): boolean { + const t = Date.parse(value); + return Number.isFinite(t); +} + +/** + * Resolve `from`/`to` query params into an always-valid ISO range. + * + * Both bounds must be present, parseable, and ordered (`from <= to`); otherwise + * the documented default window (last {@link DEFAULT_WINDOW_DAYS} days ending + * now) is used and `defaulted` is true. `now` is injectable for tests. + */ +export function resolveRange( + query: Request["query"], + now: number = Date.now(), +): ResolvedRange { + const rawFrom = typeof query.from === "string" ? query.from : undefined; + const rawTo = typeof query.to === "string" ? query.to : undefined; + + if ( + rawFrom !== undefined && + rawTo !== undefined && + isValidIso(rawFrom) && + isValidIso(rawTo) && + Date.parse(rawFrom) <= Date.parse(rawTo) + ) { + return { from: rawFrom, to: rawTo, defaulted: false }; + } + + const to = new Date(now).toISOString(); + const from = new Date(now - DEFAULT_WINDOW_DAYS * 24 * 60 * 60 * 1000).toISOString(); + return { from, to, defaulted: true }; +} + +/** Resolve the `groupBy` query param, ignoring unknown values. */ +export function resolveGroupBy(query: Request["query"]): TokenGroupBy | undefined { + const raw = typeof query.groupBy === "string" ? query.groupBy : undefined; + return raw !== undefined && VALID_GROUP_BY.has(raw) ? (raw as TokenGroupBy) : undefined; +} + +export const registerCommandCenterRoutes: ApiRouteRegistrar = (ctx) => { + const { router, getScopedStore, rethrowAsApiError } = ctx; + + /** + * GET /api/command-center/tokens + * Token consumption + derived USD cost (U2 + U3) over a date range. + * Query: from, to (ISO-8601), groupBy (model|provider|node|agent). + */ + router.get("/command-center/tokens", async (req, res) => { + try { + const store = await getScopedStore(req); + const range = resolveRange(req.query); + const groupBy = resolveGroupBy(req.query); + const result = aggregateTokenAnalytics(store.getDatabase(), { + from: range.from, + to: range.to, + groupBy, + now: Date.now(), + }); + res.json(result); + } catch (err: unknown) { + if (err instanceof ApiError) throw err; + rethrowAsApiError(err, "Failed to aggregate token analytics"); + } + }); + + /** + * GET /api/command-center/tools + * Tool-usage counts + autonomy ratio (U2) over a date range. + */ + router.get("/command-center/tools", async (req, res) => { + try { + const store = await getScopedStore(req); + const range = resolveRange(req.query); + const result = aggregateToolAnalytics(store.getDatabase(), { + from: range.from, + to: range.to, + }); + res.json(result); + } catch (err: unknown) { + if (err instanceof ApiError) throw err; + rethrowAsApiError(err, "Failed to aggregate tool analytics"); + } + }); + + /** + * GET /api/command-center/activity + * Sessions/messages/active-nodes/stickiness (U2) over a date range. + */ + router.get("/command-center/activity", async (req, res) => { + try { + const store = await getScopedStore(req); + const range = resolveRange(req.query); + const result = aggregateActivityAnalytics(store.getDatabase(), { + from: range.from, + to: range.to, + }); + res.json(result); + } catch (err: unknown) { + if (err instanceof ApiError) throw err; + rethrowAsApiError(err, "Failed to aggregate activity analytics"); + } + }); + + /** + * GET /api/command-center/productivity + * Files/commits/PRs/LOC (U2) over a date range. + */ + router.get("/command-center/productivity", async (req, res) => { + try { + const store = await getScopedStore(req); + const range = resolveRange(req.query); + const result = aggregateProductivityAnalytics(store.getDatabase(), { + from: range.from, + to: range.to, + }); + res.json(result); + } catch (err: unknown) { + if (err instanceof ApiError) throw err; + rethrowAsApiError(err, "Failed to aggregate productivity analytics"); + } + }); + + /** + * GET /api/command-center/live + * Live Mission-Control snapshot (U6a): active sessions/runs/nodes + current + * per-column task counts. No date range — current state only. Scoped + authed + * like every other endpoint. + */ + router.get("/command-center/live", async (req, res) => { + try { + const store = await getScopedStore(req); + const result = composeLiveSnapshot(store.getDatabase()); + res.json(result); + } catch (err: unknown) { + if (err instanceof ApiError) throw err; + rethrowAsApiError(err, "Failed to compose live snapshot"); + } + }); +};