diff --git a/pkgs/mcpx/internal/daemon/call_frames_test.go b/pkgs/mcpx/internal/daemon/call_frames_test.go index 3ba6d73013..2011ef6147 100644 --- a/pkgs/mcpx/internal/daemon/call_frames_test.go +++ b/pkgs/mcpx/internal/daemon/call_frames_test.go @@ -6,12 +6,15 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "testing" "time" "github.com/developing-today/code/pkgs/mcpx/internal/config" "github.com/developing-today/code/pkgs/mcpx/internal/execsvc" + "github.com/developing-today/code/pkgs/mcpx/internal/logging" ) // collectFrames registers a sink for run on s and returns the frames it @@ -24,12 +27,79 @@ func collectFrames(s *Server, run string) *[]execsvc.Frame { return frames } +func TestReportCallFrameWritesPayloadFreeLedgerWithoutRun(t *testing.T) { + dir := t.TempDir() + ledger, err := logging.NewFileSink(logging.FileOptions{Dir: dir}) + if err != nil { + t.Fatal(err) + } + defer ledger.Close() + s := &Server{callLedger: ledger} + start := time.Now().Add(-25 * time.Millisecond) + s.reportCallFrame(context.Background(), "srv", "tool", "session-7", map[string]any{"secret": "do-not-write"}, start, + json.RawMessage(`{"isError":true,"content":[{"text":"private error"}]}`), nil) + s.reportCallFrame(context.Background(), "srv", "ok", "", map[string]any{}, time.Now(), json.RawMessage(`{"ok":true}`), nil) + + data, err := os.ReadFile(filepath.Join(dir, "mcpx-"+time.Now().Format("2006-01-02")+".jsonl")) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(string(data)), "\n") + if len(lines) != 2 { + t.Fatalf("ledger has %d records, want exactly 2: %s", len(lines), data) + } + var failed, succeeded map[string]any + if err := json.Unmarshal([]byte(lines[0]), &failed); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(lines[1]), &succeeded); err != nil { + t.Fatal(err) + } + if failed["server"] != "srv" || failed["tool"] != "tool" || failed["outcome"] != "error" || failed["msg"] != "tool_call" || failed["caller_session"] != "session-7" { + t.Fatalf("error ledger row = %v", failed) + } + if _, ok := failed["duration_ms"]; !ok || failed["ts"] == nil { + t.Fatalf("error ledger row lacks timestamp or duration: %v", failed) + } + if succeeded["server"] != "srv" || succeeded["tool"] != "ok" || succeeded["outcome"] != "success" { + t.Fatalf("success ledger row = %v", succeeded) + } + if strings.Contains(string(data), "secret") || strings.Contains(string(data), "private error") { + t.Fatalf("ledger leaked call payload: %s", data) + } +} + +func TestPruneCallLedgerKeepsEightCalendarDays(t *testing.T) { + dir := t.TempDir() + now := time.Date(2026, time.November, 18, 12, 0, 0, 0, time.UTC) + for _, name := range []string{ + "mcpx-2026-11-10.jsonl", + "mcpx-2026-11-11.jsonl", + "mcpx-2026-11-11-120000.jsonl", + "other-2026-11-01.jsonl", + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte("{}\n"), 0o600); err != nil { + t.Fatal(err) + } + } + + pruneCallLedger(dir, now) + if _, err := os.Stat(filepath.Join(dir, "mcpx-2026-11-10.jsonl")); !os.IsNotExist(err) { + t.Fatalf("expired daily ledger file was not removed: %v", err) + } + for _, name := range []string{"mcpx-2026-11-11.jsonl", "mcpx-2026-11-11-120000.jsonl", "other-2026-11-01.jsonl"} { + if _, err := os.Stat(filepath.Join(dir, name)); err != nil { + t.Fatalf("kept ledger/unrelated file %s missing: %v", name, err) + } + } +} + func TestReportCallFrameMarksIsErrorResultsFailed(t *testing.T) { s := &Server{reg: &Registry{}} frames := collectFrames(s, "run-1") ctx := withRun(context.Background(), "run-1") - s.reportCallFrame(ctx, "srv", "tool", map[string]any{}, time.Now(), + s.reportCallFrame(ctx, "srv", "tool", "", map[string]any{}, time.Now(), json.RawMessage(`{"content":[{"type":"text","text":"no"}],"isError":true}`), nil) if len(*frames) != 1 { t.Fatalf("frames = %v, want 1", *frames) @@ -39,7 +109,7 @@ func TestReportCallFrameMarksIsErrorResultsFailed(t *testing.T) { t.Fatalf("isError result must be a failed call frame, got %+v", c) } - s.reportCallFrame(ctx, "srv", "tool", map[string]any{}, time.Now(), + s.reportCallFrame(ctx, "srv", "tool", "", map[string]any{}, time.Now(), json.RawMessage(`{"content":[],"isError":false}`), nil) if len(*frames) != 2 || !(*frames)[1].Call.OK { t.Fatalf("a clean result must stay ok, got %+v", *frames) @@ -58,7 +128,7 @@ func TestReportCallFrameResolvesExactServerBeforeNamespace(t *testing.T) { frames := collectFrames(s, "run-2") ctx := withRun(context.Background(), "run-2") - s.reportCallFrame(ctx, "b", "x", map[string]any{}, time.Now(), nil, nil) + s.reportCallFrame(ctx, "b", "x", "", map[string]any{}, time.Now(), nil, nil) if len(*frames) != 1 { t.Fatalf("frames = %v, want 1", *frames) } @@ -73,7 +143,7 @@ func TestReportCallFrameResolvesExactServerBeforeNamespace(t *testing.T) { }} s2 := &Server{reg: reg2} frames2 := collectFrames(s2, "run-3") - s2.reportCallFrame(withRun(context.Background(), "run-3"), "ns", "x", + s2.reportCallFrame(withRun(context.Background(), "run-3"), "ns", "x", "", map[string]any{}, time.Now(), nil, nil) if len(*frames2) != 1 { t.Fatalf("frames = %v, want 1", *frames2) diff --git a/pkgs/mcpx/internal/daemon/call_ledger.go b/pkgs/mcpx/internal/daemon/call_ledger.go new file mode 100644 index 0000000000..c50411678b --- /dev/null +++ b/pkgs/mcpx/internal/daemon/call_ledger.go @@ -0,0 +1,37 @@ +package daemon + +import ( + "os" + "path/filepath" + "strings" + "time" +) + +// pruneCallLedger keeps eight calendar days of daily JSONL files. FileSink +// separately caps each active file and retains eight size/line/age rotations; +// together these bounds prevent old daily files from accumulating forever. +func pruneCallLedger(dir string, now time.Time) { + entries, err := os.ReadDir(dir) + if err != nil { + return + } + today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) + cutoff := today.AddDate(0, 0, -7) + for _, entry := range entries { + name := entry.Name() + if !strings.HasPrefix(name, "mcpx-") || !strings.HasSuffix(name, ".jsonl") { + continue + } + stem := strings.TrimSuffix(strings.TrimPrefix(name, "mcpx-"), ".jsonl") + if len(stem) < len("2006-01-02") { + continue + } + day, err := time.Parse("2006-01-02", stem[:len("2006-01-02")]) + if err != nil || (len(stem) > len("2006-01-02") && stem[len("2006-01-02")] != '-') { + continue + } + if day.Before(cutoff) { + _ = os.Remove(filepath.Join(dir, name)) + } + } +} diff --git a/pkgs/mcpx/internal/daemon/input_required.go b/pkgs/mcpx/internal/daemon/input_required.go index 22c4947c72..5009e60a5a 100644 --- a/pkgs/mcpx/internal/daemon/input_required.go +++ b/pkgs/mcpx/internal/daemon/input_required.go @@ -151,7 +151,7 @@ func (s *Server) handleCallReporting(w http.ResponseWriter, r *http.Request, req // report the completed call here: an exec run whose calls // ask questions is still a run whose calls belong in its // stream. - s.reportCallFrame(callCtx, req.Server, req.Tool, args, start, res, err) + s.reportCallFrame(callCtx, req.Server, req.Tool, cc.SessionID, args, start, res, err) done <- outcome{res, err} if err != nil { return nil, &tasks.Fault{Code: failureStatus(err), Message: err.Error()} diff --git a/pkgs/mcpx/internal/daemon/routes_proto.go b/pkgs/mcpx/internal/daemon/routes_proto.go index 80bc914125..d8bb8ad570 100644 --- a/pkgs/mcpx/internal/daemon/routes_proto.go +++ b/pkgs/mcpx/internal/daemon/routes_proto.go @@ -1058,7 +1058,7 @@ func (s *Server) handleCallPath(w http.ResponseWriter, r *http.Request) { } else { res, err = s.reg.Call(callCtx, r.PathValue("server"), r.PathValue("tool"), cc, args) } - s.reportCallFrame(callCtx, r.PathValue("server"), r.PathValue("tool"), args, start, res, err) + s.reportCallFrame(callCtx, r.PathValue("server"), r.PathValue("tool"), cc.SessionID, args, start, res, err) if err != nil { writeJSON(w, failureStatus(err), map[string]any{"ok": false, "error": err.Error()}) return diff --git a/pkgs/mcpx/internal/daemon/server.go b/pkgs/mcpx/internal/daemon/server.go index b666b73cc1..88e26212dd 100644 --- a/pkgs/mcpx/internal/daemon/server.go +++ b/pkgs/mcpx/internal/daemon/server.go @@ -144,8 +144,13 @@ type Server struct { // sink is the durable log POST /v1/log appends to. Nil when the log // could not be opened, which the daemon survives and the route reports. - sink *logging.FileSink - lastReq atomic.Int64 + sink *logging.FileSink + // callLedger is the dedicated, payload-free execution ledger. It is + // separate from the mixed diagnostic log so analytics can read it safely. + callLedger *logging.FileSink + callLedgerDir string + lastLedgerPrune atomic.Int64 + lastReq atomic.Int64 // cfgMu guards cfg, contentHash and stamp. The daemon re-reads its // configuration from a request goroutine now, so what used to be @@ -241,24 +246,43 @@ func NewServer(opts Options) (*Server, error) { if err := ValidateBearerToken(opts.Settings); err != nil { return nil, err } + // This dedicated, payload-free JSONL surface has an explicit rotation + // contract independent of general logging defaults: 16 MiB, 200k records, + // or 24 hours per file, retaining eight rotated files. FileSink names the + // active file mcpx-YYYY-MM-DD.jsonl and rotated files with a time suffix. + callLedger, ledgerErr := logging.NewFileSink(logging.FileOptions{ + Dir: filepath.Join(opts.Paths.State, "call-ledger"), + MaxBytes: 16 * 1024 * 1024, + MaxLines: 200_000, + MaxAge: 24 * time.Hour, + Keep: 8, + }) + if ledgerErr == nil { + pruneCallLedger(filepath.Join(opts.Paths.State, "call-ledger"), time.Now()) + } + if ledgerErr != nil { + opts.Logger.Printf("call ledger unavailable: %v", ledgerErr) + } // logging.trace, which is MCPX_TRACE. It was read here by name, so a // configuration file or `mcpx daemon --logging-trace` could not turn it on. if opts.Settings.Bool("logging.trace") { pool.Trace = func(f string, a ...any) { opts.Logger.Printf(f, a...) } } srv := &Server{ - set: opts.Settings, - reg: reg, - paths: opts.Paths, - cfg: opts.Config, - logger: opts.Logger, - version: opts.Version, - idleExit: opts.IdleExit, - sink: opts.Sink, - augment: opts.Augment, - Events: events.New(opts.Settings.Int("events.history")), - httpErr: make(chan error, 4), - handedOff: make(chan struct{}), + set: opts.Settings, + reg: reg, + paths: opts.Paths, + cfg: opts.Config, + logger: opts.Logger, + version: opts.Version, + idleExit: opts.IdleExit, + sink: opts.Sink, + callLedger: callLedger, + callLedgerDir: filepath.Join(opts.Paths.State, "call-ledger"), + augment: opts.Augment, + Events: events.New(opts.Settings.Int("events.history")), + httpErr: make(chan error, 4), + handedOff: make(chan struct{}), } // The broker is optional: a daemon whose state directory cannot hold a // database still serves tools, and answers every server question with @@ -761,6 +785,9 @@ func (s *Server) shutdown() error { if s.tokenStore != nil { _ = s.tokenStore.Close() } + if s.callLedger != nil { + _ = s.callLedger.Close() + } _ = os.Remove(s.paths.Socket) s.paths.RemoveInfo() s.logger.Printf("stopped") @@ -1253,7 +1280,7 @@ func (s *Server) handleCall(w http.ResponseWriter, r *http.Request) { res, err = s.reg.Call(ctx, req.Server, req.Tool, cc, args) } dur := time.Since(start).Truncate(time.Millisecond) - s.reportCallFrame(ctx, req.Server, req.Tool, args, start, res, err) + s.reportCallFrame(ctx, req.Server, req.Tool, cc.SessionID, args, start, res, err) toolKey := req.Server + ":" + req.Tool var inBytes, outBytes []byte @@ -1405,7 +1432,7 @@ func (s *Server) handleBatch(w http.ResponseWriter, r *http.Request) { // Batch items bypass the single-call handlers, so report each // completed one here: a script's batch(...) calls belong in // its exec stream like any other call. - s.reportCallFrame(ctx, server, tool, args, start, res, err) + s.reportCallFrame(ctx, server, tool, cc.SessionID, args, start, res, err) if err != nil { return map[string]any{ @@ -1914,18 +1941,41 @@ func (s *Server) callRegistry() *execsvc.CallRegistry { // reportCallFrame tells the exec stream that is running this call, if // any, that the call happened: a call frame with the tool's resolved // destructiveHint. A call with no run id, or a run this daemon is not -// executing, has no stream to join and is not reported. -func (s *Server) reportCallFrame(ctx context.Context, server, tool string, args any, start time.Time, res json.RawMessage, callErr error) { +// executing, has no stream to join but still belongs in the call ledger. +func (s *Server) reportCallFrame(ctx context.Context, server, tool, callerSession string, args any, start time.Time, res json.RawMessage, callErr error) { run := runFrom(ctx) - if run == "" { - return - } // A tool that ran and returned isError failed, even though the // transport call itself succeeded: the frame must say so, the way // the path-per-tool handler already does with resultFailed. if callErr == nil && resultFailed(res) { callErr = errors.New("tool returned an error result (isError)") } + if s.callLedger != nil { + attrs := map[string]any{ + "server": server, + "tool": tool, + "outcome": "success", + "duration_ms": time.Since(start).Milliseconds(), + } + if callErr != nil { + attrs["outcome"] = "error" + } + if run != "" { + attrs["caller_run"] = run + } + if callerSession != "" { + attrs["caller_session"] = callerSession + } + s.callLedger.Write(logging.Record{Time: time.Now(), Msg: "tool_call", Attrs: attrs}, nil) + now := time.Now() + last := s.lastLedgerPrune.Load() + if now.Unix()-last >= 3600 && s.lastLedgerPrune.CompareAndSwap(last, now.Unix()) { + pruneCallLedger(s.callLedgerDir, now) + } + } + if run == "" { + return + } var dh *bool if picked := s.pickTool(server, tool); picked != nil { d := destructiveHint(picked.Annotations) diff --git a/pm-stack/aggregator/src/analytics-store.ts b/pm-stack/aggregator/src/analytics-store.ts index 98e299e24d..e885cd1c8c 100644 --- a/pm-stack/aggregator/src/analytics-store.ts +++ b/pm-stack/aggregator/src/analytics-store.ts @@ -7,10 +7,10 @@ // opencode.db) — one row per model call with provider, model, // variant (effort), token columns (input / output / reasoning / // cache read / cache write), recorded cost, and outcome. -// - Sessions, sub-sessions, turns, tool calls, skill use, mcpx: -// session_v2 + session_message in the same database (tool parts -// carry the tool name; `skill` parts carry the skill name in -// their input; mcpx tools are named mcpx_*). +// - Sessions, sub-sessions, turns, tool calls, skill use, and the +// in-session mcpx subset: session_v2 + session_message in the +// OpenCode database. Direct daemon calls come from mcpx's separate, +// payload-free rotated call ledger (PM_AGG_MCPX_CALL_LEDGER_DIR). // - Fleet binary use per subcommand: INFERRED — counted by // scanning shell tool-call inputs for `fleet `. // There is no fleet invocation ledger; the UI labels this @@ -24,7 +24,7 @@ // unavailable state — the page never breaks over analytics. import { Database } from "bun:sqlite"; -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import type { QuotaPool, QuotaView, SnapshotRecord, UsageView } from "./model.ts"; @@ -122,6 +122,8 @@ export interface ActivityCounts { topSkills: { name: string; count: number }[]; /** Direct mcpx tool calls (mcpx_discover / mcpx_exec / mcpx_project). */ mcpx: { name: string; count: number }[]; + /** Calls observed by the mcpx daemon's payload-free execution ledger. */ + mcpxDaemon: { calls: number; errors: number; topTools: { name: string; count: number }[] }; /** The `execute` code-gateway tool (mcpx-style namespace calls go * through it; counted separately, not folded into mcpx). */ executeGateway: number; @@ -624,13 +626,57 @@ function dayRange(now: number, daysBack: number): Set { const ACTIVITY_TTL_MS = 600_000; const ACTIVITY_SLICE_MS = 12 * HOUR_MS; -let activityCache: { at: number; data: ActivityCounts } | null = null; +let activityCache: { at: number; ledgerDir: string; data: ActivityCounts } | null = null; let activityComputing = false; /** Build the chunked activity computation: a list of single-query * steps (run one per macrotask by startActivityCompute) plus the * assembler that folds the accumulated slices into ActivityCounts. */ -function activityComputePlan(db: Database, now: number): { steps: Array<() => void>; assemble: () => ActivityCounts } { +export function readMcpxCallLedger(dir: string, now: number): ActivityCounts["mcpxDaemon"] { + const cutoff = now - 7 * DAY_MS; + const counts = new Map(); + let calls = 0; + let errors = 0; + let budget = 32 * 1024 * 1024; + let names: string[]; + try { + names = readdirSync(dir).filter((name) => /^mcpx-\d{4}-\d{2}-\d{2}(?:-.*)?\.jsonl$/.test(name)).sort().slice(-32); + } catch { + return { calls, errors, topTools: [] }; + } + for (const name of names) { + const path = join(dir, name); + try { + const size = statSync(path).size; + if (size > budget) continue; + budget -= size; + for (const line of readFileSync(path, "utf8").split("\n")) { + if (!line) continue; + try { + const row = JSON.parse(line) as { ts?: unknown; server?: unknown; tool?: unknown; outcome?: unknown }; + const at = typeof row.ts === "string" ? Date.parse(row.ts) : NaN; + if (!Number.isFinite(at) || at < cutoff || at > now + 60_000) continue; + if (typeof row.server !== "string" || typeof row.tool !== "string") continue; + calls++; + if (row.outcome === "error") errors++; + const label = `${row.server}.${row.tool}`; + counts.set(label, (counts.get(label) ?? 0) + 1); + } catch { + // A torn final append or an older record is simply absent. + } + } + } catch { + // Rotation or permission changes during the scan are fail-soft. + } + } + return { + calls, + errors, + topTools: [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 12).map(([name, count]) => ({ name, count })), + }; +} + +function activityComputePlan(db: Database, now: number, ledgerDir: string): { steps: Array<() => void>; assemble: () => ActivityCounts } { const since = now - 7 * DAY_MS; const until = now + 1; const toolCounts = new Map(); @@ -639,6 +685,7 @@ function activityComputePlan(db: Database, now: number): { steps: Array<() => vo let fleetTotal = 0; let sessionRow: { total: number; roots: number; subs: number } = { total: 0, roots: 0, subs: 0 }; let turnCount = 0; + let mcpxDaemon: ActivityCounts["mcpxDaemon"] = { calls: 0, errors: 0, topTools: [] }; const steps: Array<() => void> = []; for (const [from, to] of chunkBounds(since, until, ACTIVITY_SLICE_MS)) { steps.push(() => { @@ -700,6 +747,9 @@ function activityComputePlan(db: Database, now: number): { steps: Array<() => vo ) .get(since) as { total: number; roots: number; subs: number }; }); + steps.push(() => { + mcpxDaemon = readMcpxCallLedger(ledgerDir, now); + }); steps.push(() => { const row = db .query(`SELECT COUNT(*) AS c FROM session_message WHERE type = 'user' AND time_created >= ?`) @@ -730,6 +780,7 @@ function activityComputePlan(db: Database, now: number): { steps: Array<() => vo mcpx: ["mcpx_discover", "mcpx_exec", "mcpx_project"] .filter((n) => byName.has(n)) .map((n) => ({ name: n, count: byName.get(n) as number })), + mcpxDaemon, executeGateway: byName.get("execute") ?? 0, fleetInferred: [...fleet.entries()] .sort((a, b) => b[1] - a[1]) @@ -741,14 +792,14 @@ function activityComputePlan(db: Database, now: number): { steps: Array<() => vo return { steps, assemble }; } -function startActivityCompute(db: Database): void { +function startActivityCompute(db: Database, ledgerDir: string): void { activityComputing = true; - const { steps, assemble } = activityComputePlan(db, Date.now()); + const { steps, assemble } = activityComputePlan(db, Date.now(), ledgerDir); let idx = 0; const step = (): void => { if (idx >= steps.length) { try { - activityCache = { at: Date.now(), data: assemble() }; + activityCache = { at: Date.now(), ledgerDir, data: assemble() }; } catch { // fail-soft: leave the cache as-is; a later call retries } finally { @@ -768,10 +819,10 @@ function startActivityCompute(db: Database): void { setTimeout(step, 0); } -function loadActivity(db: Database, now: number): ActivityCounts | null { - if (activityCache && now - activityCache.at < ACTIVITY_TTL_MS) return activityCache.data; - if (!activityComputing) startActivityCompute(db); - return activityCache?.data ?? null; +function loadActivity(db: Database, now: number, ledgerDir: string): ActivityCounts | null { + if (activityCache && activityCache.ledgerDir === ledgerDir && now - activityCache.at < ACTIVITY_TTL_MS) return activityCache.data; + if (!activityComputing) startActivityCompute(db, ledgerDir); + return activityCache?.ledgerDir === ledgerDir ? activityCache.data : null; } // --------------------------------------------------------------------------- @@ -891,6 +942,7 @@ export function buildQuotaAnalytics(args: { usage: UsageView; quotaCurrentPath: string; opencodeDbPath?: string; + mcpxCallLedgerDir?: string; now?: number; }): QuotaAnalytics { const now = args.now ?? Date.now(); @@ -1077,7 +1129,7 @@ export function buildQuotaAnalytics(args: { } satisfies PoolAnalytics; }); - base.activity7d = loadActivity(db, now); + base.activity7d = loadActivity(db, now, args.mcpxCallLedgerDir ?? join(homedir(), ".local", "state", "mcpx", "call-ledger")); return base; } catch { // Schema drift or a locked DB must never break /quota: the diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index d6308eceea..60aa3735ac 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -139,6 +139,8 @@ export interface Config { * 2026-10-29, which left attention single-legged on the collector * feed until the 2026-11-10 fixture incident. */ opencodeServerStateFile: string; + /** Read-only directory containing mcpx daemon's rotated call ledger. */ + mcpxCallLedgerDir: string; kaneo: { baseUrl: string; /** Kaneo's client URL — the Origin its auth accepts (better-auth). */ @@ -291,6 +293,10 @@ export function loadConfig(env: Record = process.env env.PM_AGG_OPENCODE_SERVER_STATE, join(homedir(), ".local", "state", "opencode", "service-prod.json"), ), + mcpxCallLedgerDir: s( + env.PM_AGG_MCPX_CALL_LEDGER_DIR, + join(homedir(), ".local", "state", "mcpx", "call-ledger"), + ), kaneo: { baseUrl: s(env.KANEO_URL, "http://127.0.0.1:5173"), // Kaneo's auth accepts only its configured client URL as Origin. diff --git a/pm-stack/aggregator/src/quota-analytics-view.ts b/pm-stack/aggregator/src/quota-analytics-view.ts index 964553ce6d..62848b9c09 100644 --- a/pm-stack/aggregator/src/quota-analytics-view.ts +++ b/pm-stack/aggregator/src/quota-analytics-view.ts @@ -341,7 +341,9 @@ export function analyticsSectionHtml(a: QuotaAnalytics, display: (n: string) => ? `
sessions (7d): ${fmtN(act.sessions)} · root ${fmtN(act.rootSessions)} · sub-sessions ${fmtN(act.subSessions)} · user turns ${fmtN(act.turns)}
` + `
tool calls (7d): ${fmtN(act.toolCallsTotal)} · ${act.topTools.map((t) => `${esc(t.name)} ${fmtN(t.count)}`).join(" · ")}
` + `
skill use (7d): ${fmtN(act.skillTotal)}${act.topSkills.length ? ` · ${act.topSkills.map((s) => `${esc(s.name)} ${fmtN(s.count)}`).join(" · ")}` : ""}
` + - `
mcpx (7d): ${act.mcpx.length ? act.mcpx.map((m) => `${esc(m.name)} ${fmtN(m.count)}`).join(" · ") : "no direct mcpx tool calls"} · execute gateway (code-tool calls): ${fmtN(act.executeGateway)}
` + + `
mcpx daemon-recorded calls (7d): ${fmtN(act.mcpxDaemon.calls)} · errors ${fmtN(act.mcpxDaemon.errors)}` + + `${act.mcpxDaemon.topTools.length ? ` · ${act.mcpxDaemon.topTools.map((m) => `${esc(m.name)} ${fmtN(m.count)}`).join(" · ")}` : ""}
` + + `
mcpx calls seen in OpenCode transcripts (7d, subset): ${act.mcpx.length ? act.mcpx.map((m) => `${esc(m.name)} ${fmtN(m.count)}`).join(" · ") : "none"} · execute gateway (code-tool calls): ${fmtN(act.executeGateway)}
` + `
fleet binary (7d, inferred from shell inputs — no invocation ledger exists): ${fmtN(act.fleetInferredTotal)}${act.fleetInferred.length ? ` · ${act.fleetInferred.map((f) => `fleet ${esc(f.subcommand)} ${fmtN(f.count)}`).join(" · ")}` : ""}
` : `
activity scan (sessions, tools, skills, mcpx, fleet) is still computing — reload in about a minute.
`; const dowNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index f2562924d7..d1a14fe195 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -2851,7 +2851,7 @@ async function handler(req: Request): Promise { source.usage().catch(() => emptyUsageView()), ]); try { - return json(buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile })); + return json(buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile, mcpxCallLedgerDir: cfg.mcpxCallLedgerDir })); } catch { return json({ error: "analytics unavailable" }, 503); } @@ -2869,7 +2869,7 @@ async function handler(req: Request): Promise { // quota page down with it (the builder itself also degrades). let analytics: QuotaAnalytics | null = null; try { - analytics = buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile }); + analytics = buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile, mcpxCallLedgerDir: cfg.mcpxCallLedgerDir }); } catch { analytics = null; } diff --git a/pm-stack/aggregator/test/config.test.ts b/pm-stack/aggregator/test/config.test.ts index 5749d8064f..77f8a3dd56 100644 --- a/pm-stack/aggregator/test/config.test.ts +++ b/pm-stack/aggregator/test/config.test.ts @@ -9,6 +9,15 @@ describe("loadConfig projector hot-list credentials", () => { }); }); +describe("loadConfig mcpx call ledger", () => { + test("uses the state-directory default and accepts an explicit directory", () => { + const home = process.env.HOME ?? "/home/test"; + expect(loadConfig({ PM_AGG_DEV: "1" }).mcpxCallLedgerDir).toBe(`${home}/.local/state/mcpx/call-ledger`); + expect(loadConfig({ PM_AGG_DEV: "1", PM_AGG_MCPX_CALL_LEDGER_DIR: "/var/lib/mcpx/ledger" }).mcpxCallLedgerDir) + .toBe("/var/lib/mcpx/ledger"); + }); +}); + describe("loadConfig PM_AGG_PORT", () => { test("keeps the existing default for unset and empty values", () => { expect(loadConfig({ PM_AGG_DEV: "1" }).port).toBe(4870); diff --git a/pm-stack/aggregator/test/mcpx-call-ledger-9374.test.ts b/pm-stack/aggregator/test/mcpx-call-ledger-9374.test.ts new file mode 100644 index 0000000000..384a17c795 --- /dev/null +++ b/pm-stack/aggregator/test/mcpx-call-ledger-9374.test.ts @@ -0,0 +1,40 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "bun:test"; +import { readMcpxCallLedger } from "../src/analytics-store.ts"; + +const dirs: string[] = []; +function ledgerDir(): string { + const dir = mkdtempSync(join(tmpdir(), "mcpx-call-ledger-")); + dirs.push(dir); + return dir; +} +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +describe("mcpx daemon call ledger (#9374)", () => { + test("counts only valid records in the last seven days and groups tools", () => { + const dir = ledgerDir(); + const now = Date.parse("2026-11-18T12:00:00.000Z"); + const day = "2026-11-18"; + writeFileSync(join(dir, `mcpx-${day}.jsonl`), [ + JSON.stringify({ ts: "2026-11-18T11:00:00.000Z", server: "github", tool: "issues", outcome: "success" }), + JSON.stringify({ ts: "2026-11-18T11:30:00.000Z", server: "github", tool: "issues", outcome: "error" }), + JSON.stringify({ ts: "2026-11-01T11:00:00.000Z", server: "old", tool: "ignored", outcome: "success" }), + "{torn", + ].join("\n")); + expect(readMcpxCallLedger(dir, now)).toEqual({ + calls: 2, + errors: 1, + topTools: [{ name: "github.issues", count: 2 }], + }); + }); + + test("missing ledger directory degrades to zero recorded calls", () => { + const dir = ledgerDir(); + rmSync(dir, { recursive: true, force: true }); + expect(readMcpxCallLedger(dir, Date.now())).toEqual({ calls: 0, errors: 0, topTools: [] }); + }); +}); diff --git a/pm-stack/aggregator/test/quota-horizon-9553.test.ts b/pm-stack/aggregator/test/quota-horizon-9553.test.ts index c6b7cbdfe9..c4a9a2b12a 100644 --- a/pm-stack/aggregator/test/quota-horizon-9553.test.ts +++ b/pm-stack/aggregator/test/quota-horizon-9553.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from "bun:test"; import { analyticsSectionHtml, resetHorizonEvents } from "../src/quota-analytics-view.ts"; import { fmtCentral } from "../src/render.ts"; import { formatResetCompact } from "../src/notifications.ts"; -import type { QuotaAnalytics } from "../src/analytics-store.ts"; +import type { ActivityCounts, QuotaAnalytics } from "../src/analytics-store.ts"; import { emptyBurn } from "../src/analytics-store.ts"; // Sat 2026-11-14 18:00Z = 12:00 PM CST. @@ -74,6 +74,30 @@ function analytics(): QuotaAnalytics { } describe("reset horizon (#9553)", () => { + test("labels daemon-recorded mcpx calls separately from the transcript subset", () => { + const a = analytics(); + a.activity7d = { + rangeLabel: "7d", + sessions: 0, + rootSessions: 0, + subSessions: 0, + turns: 0, + toolCallsTotal: 0, + topTools: [], + skillTotal: 0, + topSkills: [], + mcpx: [{ name: "mcpx_exec", count: 2 }], + mcpxDaemon: { calls: 5, errors: 1, topTools: [{ name: "srv.tool", count: 5 }] }, + executeGateway: 0, + fleetInferred: [], + fleetInferredTotal: 0, + } satisfies ActivityCounts; + const html = analyticsSectionHtml(a, (n) => n); + expect(html).toContain("mcpx daemon-recorded calls (7d)"); + expect(html).toContain("mcpx calls seen in OpenCode transcripts (7d, subset)"); + expect(html).toContain("srv.tool 5"); + }); + test("weekly window steps -3d..+35d from the recorded reset", () => { const ev = resetHorizonEvents(analytics()).filter((e) => e.window === "weekly"); expect(ev.map((e) => new Date(e.at).toISOString())).toEqual([