@linxiraos/pi-stats 1.5.1 → 1.5.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +28 -3
  2. package/THIRD-PARTY-NOTICES.txt +22 -11
  3. package/dist/client/favicon.ico +0 -0
  4. package/dist/client/index.css +1 -1
  5. package/dist/client/index.js +90 -89
  6. package/dist/types/aggregator.d.ts +5 -0
  7. package/dist/types/client/api.d.ts +7 -1
  8. package/dist/types/client/app/nav.d.ts +1 -1
  9. package/dist/types/client/data/formatters.d.ts +2 -2
  10. package/dist/types/client/data/range.d.ts +5 -4
  11. package/dist/types/client/data/series.d.ts +14 -2
  12. package/dist/types/client/i18n/messages/costs.d.ts +4 -4
  13. package/dist/types/client/i18n/messages/en.d.ts +86 -6
  14. package/dist/types/client/i18n/messages/gain.d.ts +2 -2
  15. package/dist/types/client/i18n/messages/nav.d.ts +2 -0
  16. package/dist/types/client/i18n/messages/tracking.d.ts +89 -0
  17. package/dist/types/client/i18n/messages/zh-CN.d.ts +1 -1
  18. package/dist/types/client/routes/TrackingRoute.d.ts +10 -0
  19. package/dist/types/client/routes/index.d.ts +1 -0
  20. package/dist/types/db.d.ts +20 -0
  21. package/dist/types/index.d.ts +1 -1
  22. package/dist/types/parser.d.ts +7 -1
  23. package/dist/types/rollup.d.ts +4 -0
  24. package/dist/types/shared-types.d.ts +88 -0
  25. package/dist/types/spotlight-aggregator.d.ts +24 -5
  26. package/dist/types/spotlight-ingest.d.ts +48 -9
  27. package/dist/types/spotlight-worker.d.ts +27 -0
  28. package/dist/types/trace.d.ts +7 -1
  29. package/dist/types/tracking.d.ts +29 -0
  30. package/dist/types/types.d.ts +5 -5
  31. package/package.json +4 -4
  32. package/src/aggregator.ts +16 -0
  33. package/src/client/App.tsx +3 -0
  34. package/src/client/api.ts +11 -0
  35. package/src/client/app/nav.ts +3 -0
  36. package/src/client/data/formatters.ts +7 -7
  37. package/src/client/data/range.ts +22 -9
  38. package/src/client/data/series.ts +33 -14
  39. package/src/client/favicon.ico +0 -0
  40. package/src/client/i18n/messages/costs.ts +4 -4
  41. package/src/client/i18n/messages/en.ts +2 -0
  42. package/src/client/i18n/messages/gain.ts +2 -2
  43. package/src/client/i18n/messages/nav.ts +2 -0
  44. package/src/client/i18n/messages/tracking.ts +91 -0
  45. package/src/client/i18n/messages/zh-CN.ts +2 -0
  46. package/src/client/routes/CostsRoute.tsx +4 -4
  47. package/src/client/routes/GainRoute.tsx +5 -4
  48. package/src/client/routes/ProvidersRoute.tsx +4 -4
  49. package/src/client/routes/TrackingRoute.tsx +262 -0
  50. package/src/client/routes/index.ts +1 -0
  51. package/src/client/routes/tracking.css +94 -0
  52. package/src/client/spotlight/Overhead.tsx +46 -1
  53. package/src/db.ts +105 -21
  54. package/src/gain-aggregator.ts +3 -6
  55. package/src/index.ts +5 -1
  56. package/src/parser.ts +75 -10
  57. package/src/rollup.ts +67 -14
  58. package/src/server.ts +57 -16
  59. package/src/shared-types.ts +98 -0
  60. package/src/spotlight-aggregator.ts +207 -45
  61. package/src/spotlight-ingest.ts +141 -37
  62. package/src/spotlight-measures.ts +117 -85
  63. package/src/spotlight-worker.ts +45 -0
  64. package/src/trace.ts +56 -20
  65. package/src/tracking.ts +394 -0
  66. package/src/types.ts +5 -5
package/src/rollup.ts CHANGED
@@ -597,10 +597,34 @@ function normalizeCutoff(cutoff: number | null | undefined): number | null {
597
597
  return cutoff === undefined || cutoff === null || cutoff <= 0 ? null : cutoff;
598
598
  }
599
599
 
600
+ /**
601
+ * Series bucket for a fact row. Day buckets are the local calendar date
602
+ * (`YYYY-MM-DD` in the server's timezone, the viewer's when both run on one
603
+ * machine; the client tolerates a mismatch by floor-matching, see
604
+ * `client/data/series.ts`), so a day matches the date the user sees. Rolled
605
+ * hours are attributed by their start, so half-hour UTC offsets shift a day
606
+ * boundary by up to 30 minutes, as in {@link getProviderHourlyBurn}. Shorter
607
+ * buckets stay epoch-aligned.
608
+ */
600
609
  function seriesBucket(bucketMs: number): string {
610
+ if (bucketMs === DAY_MS) return "date(f.bucket / 1000, 'unixepoch', 'localtime')";
611
+ return epochBucket(bucketMs);
612
+ }
613
+
614
+ /** Epoch-aligned bucket start (ms) for a fact row, at any bucket size. */
615
+ function epochBucket(bucketMs: number): string {
601
616
  return `(f.bucket / ${bucketMs}) * ${bucketMs}`;
602
617
  }
603
618
 
619
+ /**
620
+ * Epoch ms for a {@link seriesBucket} value. A local date resolves the way the
621
+ * client's day axis does (an offset-less date-time parses as local time), so
622
+ * both agree even on a day whose midnight a DST change skips.
623
+ */
624
+ function seriesTimestamp(bucket: number | string): number {
625
+ return typeof bucket === "string" ? Date.parse(`${bucket}T00:00:00`) : bucket;
626
+ }
627
+
604
628
  // ---------------------------------------------------------------------------
605
629
  // Aggregates
606
630
  // ---------------------------------------------------------------------------
@@ -697,6 +721,25 @@ export function getStatsByFolder(cutoff: number | null = null, limit = Number.MA
697
721
  ).map(row => ({ folder: row.folder, ...toAggregatedStats(row) }));
698
722
  }
699
723
 
724
+ /** Distinct project folders the stats registry knows, most recently active first. */
725
+ export function getProjectFolders(limit = Number.MAX_SAFE_INTEGER): string[] {
726
+ return queryMessages<{ folder: string }>(
727
+ { cutoff: null },
728
+ "f.folder AS folder, MAX(f.last_ts) AS last_ts",
729
+ `GROUP BY f.folder ORDER BY last_ts DESC LIMIT ${Math.max(0, Math.floor(limit))}`,
730
+ ).map(row => row.folder);
731
+ }
732
+
733
+ /** Newest session file registered for a project folder, used to resolve its real cwd. */
734
+ export function getProjectSessionFile(folder: string): string | null {
735
+ const database = currentDb();
736
+ if (!database) return null;
737
+ const row = database
738
+ .query("SELECT session_file FROM messages WHERE folder = ? ORDER BY timestamp DESC LIMIT 1")
739
+ .get(folder) as { session_file: string } | null;
740
+ return row?.session_file ?? null;
741
+ }
742
+
700
743
  /** Token usage per agent type (main, subagent, advisor). */
701
744
  export function getStatsByAgentType(cutoff: number | null = null): AgentTypeStats[] {
702
745
  return queryMessages<{
@@ -726,13 +769,13 @@ export function getStatsByAgentType(cutoff: number | null = null): AgentTypeStat
726
769
 
727
770
  /** Requests, errors, tokens and cost per bucket. */
728
771
  export function getTimeSeries({ cutoff, bucketMs }: RangeWindow): TimeSeriesPoint[] {
729
- return queryMessages<{ bucket: number; requests: number; errors: number; tokens: number; cost: number }>(
772
+ return queryMessages<{ bucket: number | string; requests: number; errors: number; tokens: number; cost: number }>(
730
773
  { cutoff, bucketMs },
731
774
  `${seriesBucket(bucketMs)} AS bucket, SUM(f.requests) AS requests, SUM(f.failed) AS errors,
732
775
  SUM(f.total_tokens) AS tokens, TOTAL(f.cost_total) AS cost`,
733
776
  "GROUP BY 1 ORDER BY 1",
734
777
  ).map(row => ({
735
- timestamp: row.bucket,
778
+ timestamp: seriesTimestamp(row.bucket),
736
779
  requests: row.requests,
737
780
  errors: row.errors,
738
781
  tokens: row.tokens,
@@ -742,17 +785,22 @@ export function getTimeSeries({ cutoff, bucketMs }: RangeWindow): TimeSeriesPoin
742
785
 
743
786
  /** Requests per bucket per (model, provider). */
744
787
  export function getModelTimeSeries({ cutoff, bucketMs }: RangeWindow): ModelTimeSeriesPoint[] {
745
- return queryMessages<{ bucket: number; model: string; provider: string; requests: number }>(
788
+ return queryMessages<{ bucket: number | string; model: string; provider: string; requests: number }>(
746
789
  { cutoff, bucketMs },
747
790
  `${seriesBucket(bucketMs)} AS bucket, f.model AS model, f.provider AS provider, SUM(f.requests) AS requests`,
748
791
  "GROUP BY 1, f.model, f.provider ORDER BY 1",
749
- ).map(row => ({ timestamp: row.bucket, model: row.model, provider: row.provider, requests: row.requests }));
792
+ ).map(row => ({
793
+ timestamp: seriesTimestamp(row.bucket),
794
+ model: row.model,
795
+ provider: row.provider,
796
+ requests: row.requests,
797
+ }));
750
798
  }
751
799
 
752
800
  /** Average TTFT and output tokens/s per bucket per (model, provider). */
753
801
  export function getModelPerformanceSeries({ cutoff, bucketMs }: RangeWindow): ModelPerformancePoint[] {
754
802
  return queryMessages<{
755
- bucket: number;
803
+ bucket: number | string;
756
804
  model: string;
757
805
  provider: string;
758
806
  requests: number;
@@ -765,7 +813,7 @@ export function getModelPerformanceSeries({ cutoff, bucketMs }: RangeWindow): Mo
765
813
  TOTAL(f.tps_sum) / NULLIF(SUM(f.tps_n), 0) AS avg_tps`,
766
814
  "GROUP BY 1, f.model, f.provider ORDER BY 1",
767
815
  ).map(row => ({
768
- timestamp: row.bucket,
816
+ timestamp: seriesTimestamp(row.bucket),
769
817
  model: row.model,
770
818
  provider: row.provider,
771
819
  requests: row.requests,
@@ -777,7 +825,7 @@ export function getModelPerformanceSeries({ cutoff, bucketMs }: RangeWindow): Mo
777
825
  /** Daily cost per (model, provider) with the per-component split. */
778
826
  export function getCostTimeSeries(cutoff: number | null = null): CostTimeSeriesPoint[] {
779
827
  return queryMessages<{
780
- bucket: number;
828
+ bucket: string;
781
829
  model: string;
782
830
  provider: string;
783
831
  cost: number;
@@ -795,7 +843,7 @@ export function getCostTimeSeries(cutoff: number | null = null): CostTimeSeriesP
795
843
  SUM(f.requests) AS requests`,
796
844
  "GROUP BY 1, f.model, f.provider ORDER BY 1",
797
845
  ).map(row => ({
798
- timestamp: row.bucket,
846
+ timestamp: seriesTimestamp(row.bucket),
799
847
  model: row.model,
800
848
  provider: row.provider,
801
849
  cost: row.cost,
@@ -931,7 +979,7 @@ export function getModelHourlyActivity(cutoff: number | null = null): ModelHourl
931
979
  /** Tokens/cost per bucket per provider. */
932
980
  export function getProviderTimeSeries({ cutoff, bucketMs }: RangeWindow): ProviderTimeSeriesPoint[] {
933
981
  return queryMessages<{
934
- bucket: number;
982
+ bucket: number | string;
935
983
  provider: string;
936
984
  total_tokens: number;
937
985
  cost: number;
@@ -944,7 +992,7 @@ export function getProviderTimeSeries({ cutoff, bucketMs }: RangeWindow): Provid
944
992
  TOTAL(f.cost_total) AS cost, SUM(f.unpriced) AS unpriced, SUM(f.requests) AS requests`,
945
993
  "GROUP BY 1, f.provider ORDER BY 1",
946
994
  ).map(row => ({
947
- timestamp: row.bucket,
995
+ timestamp: seriesTimestamp(row.bucket),
948
996
  provider: row.provider,
949
997
  totalTokens: row.total_tokens,
950
998
  cost: row.cost,
@@ -1067,11 +1115,16 @@ export function getToolStatsByModel(cutoff: number | null = null): ToolModelStat
1067
1115
 
1068
1116
  /** Calls and errors per bucket per tool. */
1069
1117
  export function getToolTimeSeries({ cutoff, bucketMs }: RangeWindow): ToolTimeSeriesPoint[] {
1070
- return queryTools<{ bucket: number; tool_name: string; calls: number; errors: number }>(
1118
+ return queryTools<{ bucket: number | string; tool_name: string; calls: number; errors: number }>(
1071
1119
  { cutoff, bucketMs },
1072
1120
  `${seriesBucket(bucketMs)} AS bucket, f.tool_name AS tool_name, SUM(f.calls) AS calls, SUM(f.errors) AS errors`,
1073
1121
  "GROUP BY 1, f.tool_name ORDER BY 1",
1074
- ).map(row => ({ timestamp: row.bucket, tool: row.tool_name, calls: row.calls, errors: row.errors }));
1122
+ ).map(row => ({
1123
+ timestamp: seriesTimestamp(row.bucket),
1124
+ tool: row.tool_name,
1125
+ calls: row.calls,
1126
+ errors: row.errors,
1127
+ }));
1075
1128
  }
1076
1129
 
1077
1130
  // ---------------------------------------------------------------------------
@@ -1144,14 +1197,14 @@ export function getContextFactSeries(database: Database, { cutoff, bucketMs }: R
1144
1197
  type Row = { bucket: number; agent_type: AgentType; n: number | null };
1145
1198
  const toolRows = database
1146
1199
  .query(
1147
- `SELECT ${seriesBucket(bucketMs)} AS bucket, f.agent_type AS agent_type, SUM(f.result_chars) AS n
1200
+ `SELECT ${epochBucket(bucketMs)} AS bucket, f.agent_type AS agent_type, SUM(f.result_chars) AS n
1148
1201
  FROM (${tools.sql}) f GROUP BY 1, 2`,
1149
1202
  )
1150
1203
  .all(...tools.params) as Row[];
1151
1204
  for (const row of toolRows) point(row.bucket, row.agent_type).resultChars += row.n ?? 0;
1152
1205
  const messageRows = database
1153
1206
  .query(
1154
- `SELECT ${seriesBucket(bucketMs)} AS bucket, f.agent_type AS agent_type, SUM(f.output_tokens) AS n
1207
+ `SELECT ${epochBucket(bucketMs)} AS bucket, f.agent_type AS agent_type, SUM(f.output_tokens) AS n
1155
1208
  FROM (${messages.sql}) f GROUP BY 1, 2`,
1156
1209
  )
1157
1210
  .all(...messages.params) as Row[];
package/src/server.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  import type { Dirent } from "node:fs";
2
2
  import * as fs from "node:fs/promises";
3
- import * as path from "node:path";
3
+ import * as nodePath from "node:path";
4
4
  import { isEnoent, logger, ZETA_STATS_PORT } from "@linxiraos/pi-utils";
5
5
  import { $, type Server } from "bun";
6
6
  import {
7
7
  getCostDashboardStats,
8
8
  getDashboardStats,
9
9
  getFolderStats,
10
+ getKnownProjectFolders,
10
11
  getModelDashboardStats,
11
12
  getOverviewStats,
12
13
  getProviderDashboardStats,
@@ -39,11 +40,13 @@ import {
39
40
  STATS_DASHBOARD_HOSTNAME_HEADER,
40
41
  STATS_DASHBOARD_SECURITY_VERSION,
41
42
  } from "./port-conflict";
42
- import { getStatsByModel, getTimeSeries } from "./rollup";
43
- import { getSpotlightDashboardStats, getSpotlightSessionContext } from "./spotlight-aggregator";
43
+ import { getProjectSessionFile, getStatsByModel, getTimeSeries } from "./rollup";
44
+ import { buildSpotlightDashboardJson, getSpotlightSessionContext } from "./spotlight-aggregator";
45
+ import { isTrackableProject, readTrackingSnapshot } from "./tracking";
44
46
  import {
45
47
  buildSessionTrace,
46
48
  getTraceEntry,
49
+ readSessionMetadata,
47
50
  listSessionSummaries,
48
51
  TRACE_ETAG_VERSION,
49
52
  type TraceFingerprint,
@@ -52,8 +55,8 @@ import {
52
55
  TracePathError,
53
56
  } from "./trace";
54
57
 
55
- const CLIENT_DIR = path.join(import.meta.dir, "client");
56
- const STATIC_DIR = path.join(import.meta.dir, "..", "dist", "client");
58
+ const CLIENT_DIR = nodePath.join(import.meta.dir, "client");
59
+ const STATIC_DIR = nodePath.join(import.meta.dir, "..", "dist", "client");
57
60
  const IS_BUN_COMPILED =
58
61
  Boolean(process.env.PI_COMPILED || Bun.env.PI_COMPILED) ||
59
62
  import.meta.url.includes("$bunfs") ||
@@ -109,7 +112,7 @@ async function getLatestMtime(dir: string): Promise<number> {
109
112
 
110
113
  const promises = [];
111
114
  for (const entry of entries) {
112
- const fullPath = path.join(dir, entry.name);
115
+ const fullPath = nodePath.join(dir, entry.name);
113
116
  if (entry.isDirectory()) {
114
117
  promises.push(getLatestMtime(fullPath));
115
118
  } else if (entry.isFile()) {
@@ -130,8 +133,8 @@ async function getLatestMtime(dir: string): Promise<number> {
130
133
 
131
134
  const ensureClientBuild = async () => {
132
135
  if (USE_EMBEDDED_CLIENT) return;
133
- const indexPath = path.join(STATIC_DIR, "index.html");
134
- const cssPath = path.join(STATIC_DIR, "index.css");
136
+ const indexPath = nodePath.join(STATIC_DIR, "index.html");
137
+ const cssPath = nodePath.join(STATIC_DIR, "index.css");
135
138
  const sourceMtime = await getLatestMtime(CLIENT_DIR);
136
139
  let shouldBuild = true;
137
140
  try {
@@ -153,7 +156,7 @@ const ensureClientBuild = async () => {
153
156
  await fs.rm(STATIC_DIR, { recursive: true, force: true });
154
157
 
155
158
  logger.debug("Building stats client");
156
- const packageRoot = path.join(import.meta.dir, "..");
159
+ const packageRoot = nodePath.join(import.meta.dir, "..");
157
160
  const buildResult = await $`bun run build.ts`.cwd(packageRoot).quiet().nothrow();
158
161
  if (buildResult.exitCode !== 0) {
159
162
  const output = buildResult.text().trim();
@@ -175,12 +178,19 @@ let closeHandler: (() => void) | undefined;
175
178
  /** Longest a Spotlight build serves later requests of its data version: its time range moves with the clock. */
176
179
  const SPOTLIGHT_VIEW_TTL_MS = 60_000;
177
180
 
178
- /** Spotlight payloads (JSON) of one live data version by `range\0agent`, with when each build started. */
181
+ /** Spotlight payloads (JSON) of one live data version by `range\0agent`, with when each was requested. */
179
182
  let spotlightViews: { version: number; views: Map<string, { at: number; json: Promise<string> }> } | null = null;
180
183
 
184
+ /** Aborted when the last dashboard of this process stops, ending the Spotlight builds still running for it. */
185
+ let spotlightBuilds = new AbortController();
186
+
187
+ /** Settles when the last queued Spotlight build does: builds run one at a time, as they did on the server's thread. */
188
+ let spotlightQueue: Promise<unknown> = Promise.resolve();
189
+
181
190
  /**
182
191
  * The Spotlight dashboard as JSON, built once per data version and view. Every open page refetches on each version
183
- * bump and a build takes seconds on the thread that also ingests, so pages showing the same view share one build.
192
+ * bump and a build takes seconds of a worker's CPU and memory, so pages showing the same view share one build and
193
+ * different views wait their turn.
184
194
  */
185
195
  function spotlightView(range: string | null, agent: string | null): Promise<string> {
186
196
  const version = statsLive().status().version;
@@ -189,7 +199,9 @@ function spotlightView(range: string | null, agent: string | null): Promise<stri
189
199
  const key = `${range ?? ""}\0${agent ?? ""}`;
190
200
  const cached = views.get(key);
191
201
  if (cached && Date.now() - cached.at < SPOTLIGHT_VIEW_TTL_MS) return cached.json;
192
- const json = getSpotlightDashboardStats(range, agent).then(stats => JSON.stringify(stats));
202
+ const { signal } = spotlightBuilds;
203
+ const json = spotlightQueue.then(() => buildSpotlightDashboardJson(range, agent, signal));
204
+ spotlightQueue = json.catch(() => {});
193
205
  const entry = { at: Date.now(), json };
194
206
  views.set(key, entry);
195
207
  // A failed build is not reused.
@@ -219,6 +231,29 @@ export async function handleApi(req: Request): Promise<Response> {
219
231
  // Stats reads are DB-only; ingest runs in the background (see `live.ts`).
220
232
  const range = url.searchParams.get("range");
221
233
 
234
+ // Read-only project tracking snapshot. The project must be an exact label
235
+ // from the stats registry: there is no arbitrary `cwd`/path input to escape.
236
+ if (path === "/api/tracking/projects") {
237
+ if (req.method !== "GET") return Response.json({ error: "GET required" }, { status: 405 });
238
+ return Response.json({ projects: await getKnownProjectFolders() });
239
+ }
240
+
241
+ if (path === "/api/tracking") {
242
+ if (req.method !== "GET") return Response.json({ error: "GET required" }, { status: 405 });
243
+ const project = url.searchParams.get("project")?.trim();
244
+ if (!project) return Response.json({ error: "project required" }, { status: 400 });
245
+ const known = await getKnownProjectFolders();
246
+ if (!isTrackableProject(project, known)) return Response.json({ error: "unknown project" }, { status: 404 });
247
+ // Registry labels are encoded session-folder names, not paths; the newest
248
+ // session header carries the real cwd. Never derive a path from the label.
249
+ const sessionFile = getProjectSessionFile(project);
250
+ const cwd = sessionFile ? (await readSessionMetadata(sessionFile)).cwd : null;
251
+ if (!cwd || !nodePath.isAbsolute(cwd)) {
252
+ return Response.json({ error: "project path unavailable" }, { status: 409 });
253
+ }
254
+ return Response.json(await readTrackingSnapshot(cwd, project));
255
+ }
256
+
222
257
  if (path === "/api/status") {
223
258
  return Response.json(statsLive().status());
224
259
  }
@@ -418,7 +453,7 @@ async function handleStatic(requestPath: string): Promise<Response> {
418
453
  }
419
454
 
420
455
  const filePath = requestPath === "/" ? "/index.html" : requestPath;
421
- const fullPath = path.join(STATIC_DIR, filePath);
456
+ const fullPath = nodePath.join(STATIC_DIR, filePath);
422
457
 
423
458
  const file = Bun.file(fullPath);
424
459
  if (await file.exists()) {
@@ -426,7 +461,7 @@ async function handleStatic(requestPath: string): Promise<Response> {
426
461
  }
427
462
 
428
463
  // SPA fallback
429
- const index = Bun.file(path.join(STATIC_DIR, "index.html"));
464
+ const index = Bun.file(nodePath.join(STATIC_DIR, "index.html"));
430
465
  if (await index.exists()) {
431
466
  return shellResponse(await index.text());
432
467
  }
@@ -477,6 +512,8 @@ function createDashboardServer(port: number, hostname: string): Server<undefined
477
512
  server.timeout(req, 0);
478
513
  return liveEventStream(dashboardHeaders, req.signal);
479
514
  }
515
+ // A Spotlight build runs on a worker and can outlast the idle timeout, which counts a pending handler.
516
+ if (path === "/api/stats/spotlight") server.timeout(req, 0);
480
517
 
481
518
  try {
482
519
  let response: Response;
@@ -622,8 +659,12 @@ export async function startServer(
622
659
  server.stop(true);
623
660
  if (stopped) return;
624
661
  stopped = true;
625
- // The last dashboard in this process takes background ingest down with it.
626
- if (--liveServers === 0) statsLive().stop();
662
+ // The last dashboard in this process takes background ingest and Spotlight builds down with it.
663
+ if (--liveServers === 0) {
664
+ statsLive().stop();
665
+ spotlightBuilds.abort(new Error("Stats dashboard stopped"));
666
+ spotlightBuilds = new AbortController();
667
+ }
627
668
  },
628
669
  };
629
670
  for (const key of keys) activeServers.set(key, handle);
@@ -694,6 +694,18 @@ export interface SpotlightGapCount {
694
694
  holdout: number;
695
695
  }
696
696
 
697
+ /**
698
+ * Failed results by why their Spotlight calls failed: `no_credential` (no Stencil sign-in), `timeout`, `transport`,
699
+ * `rate_limited`, `bad_reply`, `http_<status>`, or `unrecorded` for results journaled before pi recorded causes.
700
+ */
701
+ export interface SpotlightFailureCause {
702
+ cause: string;
703
+ /** Results with a call that failed this way (a result with calls failing two ways counts under both). */
704
+ results: number;
705
+ /** Of the results that called Spotlight. */
706
+ share: number;
707
+ }
708
+
697
709
  /** What shaping costs in time and reliability (all evaluated results, held-out ones included). */
698
710
  export interface SpotlightOverhead {
699
711
  results: number;
@@ -705,6 +717,8 @@ export interface SpotlightOverhead {
705
717
  spotlightMsP90: number | null;
706
718
  /** Results whose Spotlight calls failed or timed out (shaped by the no-score fallback). */
707
719
  failureRate: number | null;
720
+ /** The failed results by cause, most first. */
721
+ failureCauses: SpotlightFailureCause[];
708
722
  /** Wall time tool calls spent shaping results whose Spotlight calls failed (mostly the 5 s timeout per call). */
709
723
  failedWaitMs: number;
710
724
  spotlightUsd: number;
@@ -1241,3 +1255,87 @@ export interface SessionTrace {
1241
1255
  tracks: TraceTrack[];
1242
1256
  summary: TraceSummary;
1243
1257
  }
1258
+
1259
+ // ---------------------------------------------------------------------------
1260
+ // Project tracking snapshot (`/api/tracking`)
1261
+ // ---------------------------------------------------------------------------
1262
+
1263
+ /**
1264
+ * What a tracking read actually found for one file or file family. The
1265
+ * dashboard renders these states instead of guessing: a missing status file is
1266
+ * not a zero-progress project.
1267
+ */
1268
+ export type TrackingSnapshotState = "present" | "missing" | "partial" | "corrupt" | "error";
1269
+
1270
+ /** Parsed `status.json`; every field is optional in the file, so defaults are explicit. */
1271
+ export interface TrackingStatusValue {
1272
+ phase: string;
1273
+ progress: string;
1274
+ blockers: string[];
1275
+ decisions: string[];
1276
+ lastUpdated: string;
1277
+ /** Current todo phase name (Tracking v2 sync_todo). */
1278
+ stage?: string;
1279
+ /** Ordered todo-phase mirror (Tracking v2 sync_todo). */
1280
+ phases?: { name: string; status: string }[];
1281
+ /** Session that last wrote tracking state. */
1282
+ lastSessionId?: string | null;
1283
+ }
1284
+
1285
+ export interface TrackingStatusSnapshot {
1286
+ state: TrackingSnapshotState;
1287
+ /** Null unless `state` is `present` or `partial` and the JSON parsed. */
1288
+ value: TrackingStatusValue | null;
1289
+ truncated: boolean;
1290
+ error: string | null;
1291
+ }
1292
+
1293
+ export interface TrackingTextSnapshot {
1294
+ state: TrackingSnapshotState;
1295
+ content: string | null;
1296
+ truncated: boolean;
1297
+ error: string | null;
1298
+ }
1299
+
1300
+ export interface TrackingActionRow {
1301
+ timestamp: string;
1302
+ action: string;
1303
+ detail?: string;
1304
+ }
1305
+
1306
+ export interface TrackingActionsSnapshot {
1307
+ state: TrackingSnapshotState;
1308
+ /** Oldest first, as written. */
1309
+ rows: TrackingActionRow[];
1310
+ truncated: boolean;
1311
+ /** JSONL rows that did not parse; they are skipped, never invented. */
1312
+ invalidRows: number;
1313
+ error: string | null;
1314
+ }
1315
+
1316
+ export interface TrackingSessionSnapshot {
1317
+ name: string;
1318
+ state: TrackingSnapshotState;
1319
+ content: string | null;
1320
+ truncated: boolean;
1321
+ error: string | null;
1322
+ }
1323
+
1324
+ /** Read-only snapshot of `<project>/.zeta/tracking/`; independent of any agent package type. */
1325
+ export interface TrackingSnapshot {
1326
+ /** Exact project folder from the stats registry, never a caller-supplied path. */
1327
+ project: string;
1328
+ /** Resolved tracking directory the reads targeted. */
1329
+ trackingDir: string;
1330
+ /** Whether the tracking directory itself exists. */
1331
+ exists: boolean;
1332
+ /** Newest mtime among the files read, ISO; null when nothing exists. */
1333
+ updatedAt: string | null;
1334
+ status: TrackingStatusSnapshot;
1335
+ index: TrackingTextSnapshot;
1336
+ actions: TrackingActionsSnapshot;
1337
+ /** Newest first, at most the read limit. */
1338
+ sessions: TrackingSessionSnapshot[];
1339
+ /** State of the `sessions/` directory itself. */
1340
+ sessionsState: TrackingSnapshotState;
1341
+ }