diff --git a/pkgs/fleet/crates/fleet/src/invocation_ledger.rs b/pkgs/fleet/crates/fleet/src/invocation_ledger.rs new file mode 100644 index 0000000000..82d78fe3e1 --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/invocation_ledger.rs @@ -0,0 +1,140 @@ +//! Best-effort local record of fleet CLI invocations for quota analytics. + +use fleet_config::Config; +use serde_json::json; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub const SCHEMA: &str = "fleet-invocation/v1"; +const FILE: &str = "invocations.jsonl"; +const MAX_BYTES: u64 = 4 * 1024 * 1024; +const KEEP: usize = 4; + +pub fn path() -> PathBuf { + std::env::var_os("FLEET_INVOCATION_LEDGER") + .map(PathBuf::from) + .unwrap_or_else(|| Config::state_dir().join(FILE)) +} + +pub fn record( + invoked_as: &str, + args: &[String], + code: i32, + duration_ms: u128, +) -> serde_json::Value { + let host = std::env::var("HOSTNAME").ok().filter(|s| !s.is_empty()); + let caller = [ + "FLEET_CALLER", + "OPENCODE_SESSION_ID", + "MCPX_SESSION_ID", + "FLEET_SESSION_ID", + "SYSTEMD_UNIT", + "CRON_JOB", + ] + .iter() + .find_map(|key| std::env::var(key).ok().filter(|s| !s.is_empty())); + // Only the leading positional words are recorded: the first flag + // ends them, so a flag's value (a token, a title, a path) never + // reaches the ledger. + let words: Vec<&str> = args + .iter() + .map(String::as_str) + .take_while(|arg| !arg.starts_with('-')) + .take(3) + .collect(); + let (command, subcommand, sub_subcommand) = match invoked_as { + "fleet" | "fleet-serve" | "fleet-connect" => ( + words.first().copied(), + words.get(1).copied(), + words.get(2).copied(), + ), + "repo-queue" => (Some("queue"), words.first().copied(), words.get(1).copied()), + other => (Some(other), words.get(1).copied(), words.get(2).copied()), + }; + json!({ + "schema": SCHEMA, + "at_unix_ms": SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0), + "invoked_as": invoked_as, + "command": command, + "subcommand": subcommand, + "sub_subcommand": sub_subcommand, + "exit_code": code, + "duration_ms": duration_ms, + "host": host, + "caller": caller, + }) +} + +pub fn append(path: &Path, value: &serde_json::Value) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + if path + .metadata() + .map(|m| m.len() >= MAX_BYTES) + .unwrap_or(false) + { + for i in (1..KEEP).rev() { + let from = rotated(path, i); + let to = rotated(path, i + 1); + if from.exists() { + let _ = std::fs::remove_file(&to); + if let Err(error) = std::fs::rename(from, to) { + if error.kind() != std::io::ErrorKind::NotFound { + return Err(error); + } + } + } + } + let _ = std::fs::remove_file(rotated(path, 1)); + std::fs::rename(path, rotated(path, 1))?; + } + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path)?; + writeln!(file, "{value}") +} + +fn rotated(path: &Path, index: usize) -> PathBuf { + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".{index}")); + path.with_file_name(name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn appends_versioned_records_and_rotates() { + let dir = std::env::temp_dir().join(format!("fleet-ledger-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join(FILE); + append( + &path, + &record("fleet", &["queue".into(), "list".into()], 0, 4), + ) + .unwrap(); + assert_eq!( + serde_json::from_str::(&std::fs::read_to_string(&path).unwrap()) + .unwrap()["schema"], + SCHEMA + ); + let flagged = record( + "fleet", + &["queue".into(), "--token".into(), "secret-value".into()], + 0, + 1, + ); + assert_eq!(flagged["command"], "queue"); + assert!(flagged["subcommand"].is_null()); + assert!(!flagged.to_string().contains("secret-value")); + std::fs::write(&path, vec![b'x'; MAX_BYTES as usize]).unwrap(); + append(&path, &record("fleet", &[], 2, 1)).unwrap(); + assert!(rotated(&path, 1).exists()); + assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 1); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 2d441f1477..d772e47fdb 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -51,6 +51,7 @@ mod gh; #[cfg(feature = "gh")] mod gh_cache; mod gh_closure; +mod invocation_ledger; #[allow(dead_code)] // the derivation runs in build.rs (which includes this module by path); the binary itself consumes only the baked FLEET_DERIVED_VERSION value, plus these unit tests @@ -1391,6 +1392,7 @@ fn restore_default_sigpipe() { fn restore_default_sigpipe() {} fn main() { + let started = std::time::Instant::now(); restore_default_sigpipe(); let argv: Vec = std::env::args().collect(); let invoked_as = argv @@ -1407,40 +1409,46 @@ fn main() { // Config decides the disable table; a malformed config is a loud // error on every path (a silently ignored disable would defeat // the §7 incident lever). - let config = match fleet_config::Config::load() { - Ok(c) => c, + let code = match fleet_config::Config::load() { + Ok(config) => { + if invoked_as == "fleet" { + let surface = Surface::new(None, config); + run_root(&surface, &args, &invoked_as) + } else if let Some(variant) = Variant::from_invocation_name(&invoked_as) { + // Refinement A: the hyphenated name narrows (never widens). + let surface = Surface::new(Some(variant), config); + run_root(&surface, &args, &invoked_as) + } else if let Some(route) = alias_route(&invoked_as) { + let surface = Surface::new(None, config); + let d = domain(route.domain).expect("registry aliases route to real domains"); + let mut routed: Vec = Vec::new(); + if let Some(implied) = route.implied_arg { + routed.push(implied.to_string()); + } + routed.extend(args.iter().cloned()); + run_domain(&surface, d, &routed, &invoked_as) + } else if is_known_invocation_name(&invoked_as) { + unreachable!("known names are handled above"); + } else { + eprintln!( + "fleet: invoked under unknown name '{invoked_as}'; expected 'fleet', a variant \ + name ('fleet-serve', 'fleet-connect'), or a known alias (repo-queue, queue-broker, \ + secrets-broker, laptop-agent, laptop-agent-broker, atlas-search)" + ); + EXIT_USAGE + } + } Err(e) => { eprintln!("{e}"); - std::process::exit(EXIT_USAGE); - } - }; - - let code = if invoked_as == "fleet" { - let surface = Surface::new(None, config); - run_root(&surface, &args, &invoked_as) - } else if let Some(variant) = Variant::from_invocation_name(&invoked_as) { - // Refinement A: the hyphenated name narrows (never widens). - let surface = Surface::new(Some(variant), config); - run_root(&surface, &args, &invoked_as) - } else if let Some(route) = alias_route(&invoked_as) { - let surface = Surface::new(None, config); - let d = domain(route.domain).expect("registry aliases route to real domains"); - let mut routed: Vec = Vec::new(); - if let Some(implied) = route.implied_arg { - routed.push(implied.to_string()); + EXIT_USAGE } - routed.extend(args); - run_domain(&surface, d, &routed, &invoked_as) - } else if is_known_invocation_name(&invoked_as) { - unreachable!("known names are handled above"); - } else { - eprintln!( - "fleet: invoked under unknown name '{invoked_as}'; expected 'fleet', a variant \ - name ('fleet-serve', 'fleet-connect'), or a known alias (repo-queue, queue-broker, \ - secrets-broker, laptop-agent, laptop-agent-broker, atlas-search)" - ); - EXIT_USAGE }; + // Telemetry is local, payload-free and best-effort: failure to write + // the ledger must never alter the command's result. + let _ = invocation_ledger::append( + &invocation_ledger::path(), + &invocation_ledger::record(&invoked_as, &args, code, started.elapsed().as_millis()), + ); std::process::exit(code); } diff --git a/pkgs/fleet/crates/fleet/tests/invocation_ledger.rs b/pkgs/fleet/crates/fleet/tests/invocation_ledger.rs new file mode 100644 index 0000000000..3a2f380542 --- /dev/null +++ b/pkgs/fleet/crates/fleet/tests/invocation_ledger.rs @@ -0,0 +1,44 @@ +use std::fs; +use std::process::Command; + +fn run_case(name: &str, args: &[&str], config: Option<&str>) -> (i32, serde_json::Value) { + let dir = + std::env::temp_dir().join(format!("fleet-entry-ledger-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let ledger = dir.join("invocations.jsonl"); + let mut command = Command::new(env!("CARGO_BIN_EXE_fleet")); + command.args(args).env("FLEET_INVOCATION_LEDGER", &ledger); + if let Some(config) = config { + let config_path = dir.join("config.toml"); + fs::write(&config_path, config).unwrap(); + command.env("FLEET_CONFIG", config_path); + } + let output = command.output().unwrap(); + let text = fs::read_to_string(&ledger).unwrap(); + let rows: Vec = text + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + let _ = fs::remove_dir_all(dir); + assert_eq!(rows.len(), 1, "one record for {name}"); + ( + output.status.code().unwrap_or(1), + rows.into_iter().next().unwrap(), + ) +} + +#[test] +fn entry_path_records_success_usage_error_and_config_failure_once() { + let (code, row) = run_case("success", &["version"], None); + assert_eq!(code, 0); + assert_eq!(row["exit_code"], 0); + + let (code, row) = run_case("usage", &["--not-a-fleet-command"], None); + assert_eq!(code, 2); + assert_eq!(row["exit_code"], 2); + + let (code, row) = run_case("config-error", &["version"], Some("not = [valid toml")); + assert_eq!(code, 2); + assert_eq!(row["exit_code"], 2); +} diff --git a/pm-stack/aggregator/src/analytics-store.ts b/pm-stack/aggregator/src/analytics-store.ts index e885cd1c8c..055c6fe337 100644 --- a/pm-stack/aggregator/src/analytics-store.ts +++ b/pm-stack/aggregator/src/analytics-store.ts @@ -130,6 +130,10 @@ export interface ActivityCounts { /** INFERRED fleet binary use from shell tool-call inputs. */ fleetInferred: { subcommand: string; count: number }[]; fleetInferredTotal: number; + /** Source selected for fleet CLI counts. */ + fleetSource: "recorded" | "inferred"; + fleetRecorded: { subcommand: string; count: number }[]; + fleetRecordedTotal: number; } export interface QuotaAnalytics { @@ -676,7 +680,54 @@ export function readMcpxCallLedger(dir: string, now: number): ActivityCounts["mc }; } -function activityComputePlan(db: Database, now: number, ledgerDir: string): { steps: Array<() => void>; assemble: () => ActivityCounts } { +export function readFleetInvocationLedger(file: string, now: number): { + readable: boolean; + total: number; + byCommand: { subcommand: string; count: number }[]; +} { + const texts: string[] = []; + for (const candidate of [file, ...[1, 2, 3, 4].map((index) => `${file}.${index}`)]) { + try { + texts.push(readFileSync(candidate, "utf8")); + } catch { + // Rotated segments are optional; one readable segment is enough to + // establish that the ledger is available rather than inferred. + } + } + if (texts.length === 0) return { readable: false, total: 0, byCommand: [] }; + const cutoff = now - 7 * DAY_MS; + const counts = new Map(); + let total = 0; + for (const line of texts.join("\n").split("\n")) { + if (!line) continue; + try { + const row = JSON.parse(line) as { + schema?: unknown; + at_unix_ms?: unknown; + command?: unknown; + subcommand?: unknown; + sub_subcommand?: unknown; + exit_code?: unknown; + }; + if (row.schema !== "fleet-invocation/v1" || typeof row.at_unix_ms !== "number" || + row.at_unix_ms < cutoff || row.at_unix_ms > now + 60_000 || typeof row.exit_code !== "number") continue; + const command = [row.command, row.subcommand, row.sub_subcommand] + .filter((part): part is string => typeof part === "string" && part.length > 0) + .join(" ") || "(root)"; + total++; + counts.set(command, (counts.get(command) ?? 0) + 1); + } catch { + // Ignore torn or malformed JSONL lines. + } + } + return { + readable: true, + total, + byCommand: [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 12).map(([subcommand, count]) => ({ subcommand, count })), + }; +} + +function activityComputePlan(db: Database, now: number, ledgerDir: string, fleetLedgerFile: string): { steps: Array<() => void>; assemble: () => ActivityCounts } { const since = now - 7 * DAY_MS; const until = now + 1; const toolCounts = new Map(); @@ -686,6 +737,7 @@ function activityComputePlan(db: Database, now: number, ledgerDir: string): { st 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 fleetLedger = readFleetInvocationLedger(fleetLedgerFile, now); const steps: Array<() => void> = []; for (const [from, to] of chunkBounds(since, until, ACTIVITY_SLICE_MS)) { steps.push(() => { @@ -787,19 +839,22 @@ function activityComputePlan(db: Database, now: number, ledgerDir: string): { st .slice(0, 12) .map(([subcommand, count]) => ({ subcommand, count })), fleetInferredTotal: fleetTotal, + fleetSource: fleetLedger.readable ? "recorded" : "inferred", + fleetRecorded: fleetLedger.byCommand, + fleetRecordedTotal: fleetLedger.total, }; }; return { steps, assemble }; } -function startActivityCompute(db: Database, ledgerDir: string): void { +function startActivityCompute(db: Database, ledgerDir: string, fleetLedgerFile: string): void { activityComputing = true; - const { steps, assemble } = activityComputePlan(db, Date.now(), ledgerDir); + const { steps, assemble } = activityComputePlan(db, Date.now(), ledgerDir, fleetLedgerFile); let idx = 0; const step = (): void => { if (idx >= steps.length) { try { - activityCache = { at: Date.now(), ledgerDir, data: assemble() }; + activityCache = { at: Date.now(), ledgerDir: `${ledgerDir}|${fleetLedgerFile}`, data: assemble() }; } catch { // fail-soft: leave the cache as-is; a later call retries } finally { @@ -819,10 +874,11 @@ function startActivityCompute(db: Database, ledgerDir: string): void { setTimeout(step, 0); } -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; +function loadActivity(db: Database, now: number, ledgerDir: string, fleetLedgerFile: string): ActivityCounts | null { + const cacheKey = `${ledgerDir}|${fleetLedgerFile}`; + if (activityCache && activityCache.ledgerDir === cacheKey && now - activityCache.at < ACTIVITY_TTL_MS) return activityCache.data; + if (!activityComputing) startActivityCompute(db, ledgerDir, fleetLedgerFile); + return activityCache?.ledgerDir === cacheKey ? activityCache.data : null; } // --------------------------------------------------------------------------- @@ -943,6 +999,7 @@ export function buildQuotaAnalytics(args: { quotaCurrentPath: string; opencodeDbPath?: string; mcpxCallLedgerDir?: string; + fleetInvocationLedgerFile?: string; now?: number; }): QuotaAnalytics { const now = args.now ?? Date.now(); @@ -1129,7 +1186,12 @@ export function buildQuotaAnalytics(args: { } satisfies PoolAnalytics; }); - base.activity7d = loadActivity(db, now, args.mcpxCallLedgerDir ?? join(homedir(), ".local", "state", "mcpx", "call-ledger")); + base.activity7d = loadActivity( + db, + now, + args.mcpxCallLedgerDir ?? join(homedir(), ".local", "state", "mcpx", "call-ledger"), + args.fleetInvocationLedgerFile ?? join(homedir(), ".local", "state", "fleet", "invocations.jsonl"), + ); 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 8ebf3823ee..174792f494 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -147,6 +147,8 @@ export interface Config { opencodeServerStateFile: string; /** Read-only directory containing mcpx daemon's rotated call ledger. */ mcpxCallLedgerDir: string; + /** Read-only fleet CLI invocation JSONL ledger. */ + fleetInvocationLedgerFile: string; kaneo: { baseUrl: string; /** Kaneo's client URL — the Origin its auth accepts (better-auth). */ @@ -308,6 +310,10 @@ export function loadConfig(env: Record = process.env env.PM_AGG_MCPX_CALL_LEDGER_DIR, join(homedir(), ".local", "state", "mcpx", "call-ledger"), ), + fleetInvocationLedgerFile: s( + env.PM_AGG_FLEET_INVOCATION_LEDGER_FILE, + join(env.XDG_STATE_HOME?.trim() || join(homedir(), ".local", "state"), "fleet", "invocations.jsonl"), + ), 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 62848b9c09..7d785d3dd0 100644 --- a/pm-stack/aggregator/src/quota-analytics-view.ts +++ b/pm-stack/aggregator/src/quota-analytics-view.ts @@ -344,7 +344,9 @@ export function analyticsSectionHtml(a: QuotaAnalytics, display: (n: string) => `
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(" · ")}` : ""}
` + (act.fleetSource === "recorded" + ? `
fleet binary (7d, recorded): ${fmtN(act.fleetRecordedTotal)}${act.fleetRecorded.length ? ` · ${act.fleetRecorded.map((f) => `fleet ${esc(f.subcommand)} ${fmtN(f.count)}`).join(" · ")}` : ""}
` + : `
fleet binary (7d, inferred from shell inputs — pre-ledger fallback): ${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"]; return ( diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 57325dde72..b75290dde1 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -2873,7 +2873,7 @@ async function handler(req: Request): Promise { source.usage().catch(() => emptyUsageView()), ]); try { - return json(buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile, mcpxCallLedgerDir: cfg.mcpxCallLedgerDir })); + return json(buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile, mcpxCallLedgerDir: cfg.mcpxCallLedgerDir, fleetInvocationLedgerFile: cfg.fleetInvocationLedgerFile })); } catch { return json({ error: "analytics unavailable" }, 503); } @@ -2891,7 +2891,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, mcpxCallLedgerDir: cfg.mcpxCallLedgerDir }); + analytics = buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile, mcpxCallLedgerDir: cfg.mcpxCallLedgerDir, fleetInvocationLedgerFile: cfg.fleetInvocationLedgerFile }); } catch { analytics = null; } diff --git a/pm-stack/aggregator/test/fleet-invocation-ledger-9373.test.ts b/pm-stack/aggregator/test/fleet-invocation-ledger-9373.test.ts new file mode 100644 index 0000000000..ddbf1e5d35 --- /dev/null +++ b/pm-stack/aggregator/test/fleet-invocation-ledger-9373.test.ts @@ -0,0 +1,53 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readFleetInvocationLedger } from "../src/analytics-store.ts"; + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +describe("fleet invocation ledger (#9373)", () => { + test("counts valid versioned records in the seven-day window", () => { + const dir = mkdtempSync(join(tmpdir(), "fleet-ledger-")); + dirs.push(dir); + const file = join(dir, "invocations.jsonl"); + const now = Date.parse("2026-11-18T12:00:00Z"); + writeFileSync(file, [ + JSON.stringify({ schema: "fleet-invocation/v1", at_unix_ms: now - 1_000, command: "queue", exit_code: 0 }), + JSON.stringify({ schema: "fleet-invocation/v1", at_unix_ms: now - 2_000, command: "queue", exit_code: 2 }), + JSON.stringify({ schema: "fleet-invocation/v1", at_unix_ms: now - 8 * 86_400_000, command: "secrets", exit_code: 0 }), + "{torn", + ].join("\n")); + expect(readFleetInvocationLedger(file, now)).toEqual({ + readable: true, + total: 2, + byCommand: [{ subcommand: "queue", count: 2 }], + }); + }); + + test("distinguishes a readable empty ledger from a missing ledger", () => { + const dir = mkdtempSync(join(tmpdir(), "fleet-ledger-")); + dirs.push(dir); + const file = join(dir, "empty.jsonl"); + writeFileSync(file, ""); + expect(readFleetInvocationLedger(file, Date.now())).toEqual({ readable: true, total: 0, byCommand: [] }); + expect(readFleetInvocationLedger(join(dir, "missing.jsonl"), Date.now())).toEqual({ readable: false, total: 0, byCommand: [] }); + }); + + test("includes recent records from rotated segments", () => { + const dir = mkdtempSync(join(tmpdir(), "fleet-ledger-")); + dirs.push(dir); + const file = join(dir, "invocations.jsonl"); + const now = Date.parse("2026-11-18T12:00:00Z"); + writeFileSync(file, JSON.stringify({ schema: "fleet-invocation/v1", at_unix_ms: now - 1_000, command: "queue", exit_code: 0 })); + writeFileSync(`${file}.1`, JSON.stringify({ schema: "fleet-invocation/v1", at_unix_ms: now - 2_000, command: "fleet", subcommand: "status", exit_code: 0 })); + expect(readFleetInvocationLedger(file, now)).toEqual({ + readable: true, + total: 2, + byCommand: [{ subcommand: "queue", count: 1 }, { subcommand: "fleet status", count: 1 }], + }); + }); +}); diff --git a/pm-stack/aggregator/test/quota-horizon-9553.test.ts b/pm-stack/aggregator/test/quota-horizon-9553.test.ts index c4a9a2b12a..40fbb75840 100644 --- a/pm-stack/aggregator/test/quota-horizon-9553.test.ts +++ b/pm-stack/aggregator/test/quota-horizon-9553.test.ts @@ -91,6 +91,9 @@ describe("reset horizon (#9553)", () => { executeGateway: 0, fleetInferred: [], fleetInferredTotal: 0, + fleetSource: "inferred", + fleetRecorded: [], + fleetRecordedTotal: 0, } satisfies ActivityCounts; const html = analyticsSectionHtml(a, (n) => n); expect(html).toContain("mcpx daemon-recorded calls (7d)"); @@ -98,6 +101,20 @@ describe("reset horizon (#9553)", () => { expect(html).toContain("srv.tool 5"); }); + test("labels fleet invocation-ledger counts as recorded", () => { + const a = analytics(); + a.activity7d = { + rangeLabel: "7d", sessions: 0, rootSessions: 0, subSessions: 0, turns: 0, + toolCallsTotal: 0, topTools: [], skillTotal: 0, topSkills: [], mcpx: [], + mcpxDaemon: { calls: 0, errors: 0, topTools: [] }, executeGateway: 0, + fleetInferred: [{ subcommand: "queue", count: 99 }], fleetInferredTotal: 99, + fleetSource: "recorded", fleetRecorded: [{ subcommand: "queue", count: 2 }], fleetRecordedTotal: 2, + } satisfies ActivityCounts; + const html = analyticsSectionHtml(a, (n) => n); + expect(html).toContain("fleet binary (7d, recorded): 2"); + expect(html).not.toContain("inferred from shell inputs"); + }); + 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([