@linxiraos/pi-stats 1.5.1 → 1.5.10
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.
- package/CHANGELOG.md +22 -3
- package/THIRD-PARTY-NOTICES.txt +22 -11
- package/dist/client/favicon.ico +0 -0
- package/dist/client/index.css +1 -1
- package/dist/client/index.js +95 -94
- package/dist/types/aggregator.d.ts +5 -0
- package/dist/types/client/api.d.ts +7 -1
- package/dist/types/client/app/nav.d.ts +1 -1
- package/dist/types/client/data/formatters.d.ts +2 -2
- package/dist/types/client/data/range.d.ts +5 -4
- package/dist/types/client/data/series.d.ts +14 -2
- package/dist/types/client/i18n/messages/costs.d.ts +4 -4
- package/dist/types/client/i18n/messages/en.d.ts +86 -6
- package/dist/types/client/i18n/messages/gain.d.ts +2 -2
- package/dist/types/client/i18n/messages/nav.d.ts +2 -0
- package/dist/types/client/i18n/messages/tracking.d.ts +89 -0
- package/dist/types/client/i18n/messages/zh-CN.d.ts +1 -1
- package/dist/types/client/routes/TrackingRoute.d.ts +10 -0
- package/dist/types/client/routes/index.d.ts +1 -0
- package/dist/types/db.d.ts +20 -0
- package/dist/types/index.d.ts +1 -1
- package/dist/types/parser.d.ts +7 -1
- package/dist/types/rollup.d.ts +4 -0
- package/dist/types/shared-types.d.ts +88 -0
- package/dist/types/spotlight-aggregator.d.ts +24 -5
- package/dist/types/spotlight-ingest.d.ts +48 -9
- package/dist/types/spotlight-worker.d.ts +27 -0
- package/dist/types/trace.d.ts +7 -1
- package/dist/types/tracking.d.ts +29 -0
- package/dist/types/types.d.ts +5 -5
- package/package.json +4 -4
- package/src/aggregator.ts +16 -0
- package/src/client/App.tsx +3 -0
- package/src/client/api.ts +11 -0
- package/src/client/app/nav.ts +3 -0
- package/src/client/data/formatters.ts +7 -7
- package/src/client/data/range.ts +22 -9
- package/src/client/data/series.ts +33 -14
- package/src/client/favicon.ico +0 -0
- package/src/client/i18n/messages/costs.ts +4 -4
- package/src/client/i18n/messages/en.ts +2 -0
- package/src/client/i18n/messages/gain.ts +2 -2
- package/src/client/i18n/messages/nav.ts +2 -0
- package/src/client/i18n/messages/tracking.ts +91 -0
- package/src/client/i18n/messages/zh-CN.ts +2 -0
- package/src/client/routes/CostsRoute.tsx +4 -4
- package/src/client/routes/GainRoute.tsx +5 -4
- package/src/client/routes/ProvidersRoute.tsx +4 -4
- package/src/client/routes/TrackingRoute.tsx +262 -0
- package/src/client/routes/index.ts +1 -0
- package/src/client/routes/tracking.css +94 -0
- package/src/client/spotlight/Overhead.tsx +46 -1
- package/src/db.ts +105 -21
- package/src/gain-aggregator.ts +3 -6
- package/src/index.ts +5 -1
- package/src/parser.ts +75 -10
- package/src/rollup.ts +67 -14
- package/src/server.ts +57 -16
- package/src/shared-types.ts +98 -0
- package/src/spotlight-aggregator.ts +207 -45
- package/src/spotlight-ingest.ts +141 -37
- package/src/spotlight-measures.ts +117 -85
- package/src/spotlight-worker.ts +45 -0
- package/src/trace.ts +56 -20
- package/src/tracking.ts +394 -0
- package/src/types.ts +5 -5
package/src/trace.ts
CHANGED
|
@@ -35,7 +35,7 @@ export class TracePathError extends Error {}
|
|
|
35
35
|
* span assembly changes so browsers don't revalidate stale cached bodies
|
|
36
36
|
* against an unchanged transcript mtime.
|
|
37
37
|
*/
|
|
38
|
-
export const TRACE_ETAG_VERSION =
|
|
38
|
+
export const TRACE_ETAG_VERSION = 6;
|
|
39
39
|
|
|
40
40
|
const MAX_TRACK_DEPTH = 6;
|
|
41
41
|
const LABEL_MAX = 80;
|
|
@@ -43,6 +43,9 @@ const DETAIL_MAX = 160;
|
|
|
43
43
|
const TITLE_SCAN_BYTES = 4096;
|
|
44
44
|
const LIST_FOLD_LIMIT = 300;
|
|
45
45
|
|
|
46
|
+
/** Async job statuses after which no async-result delivery follows a `wait` or cancel handover. */
|
|
47
|
+
const SETTLED_JOB_STATUSES: Record<string, true> = { completed: true, failed: true, cancelled: true };
|
|
48
|
+
|
|
46
49
|
// ---------------------------------------------------------------------------
|
|
47
50
|
// Structural entry views (journal shapes mirrored without importing coding-agent)
|
|
48
51
|
|
|
@@ -58,6 +61,8 @@ interface EntryView {
|
|
|
58
61
|
timestamp?: string;
|
|
59
62
|
customType?: string;
|
|
60
63
|
data?: Record<string, unknown>;
|
|
64
|
+
// custom_message
|
|
65
|
+
details?: Record<string, unknown>;
|
|
61
66
|
message?: MessageView;
|
|
62
67
|
// session header
|
|
63
68
|
cwd?: string;
|
|
@@ -82,7 +87,6 @@ interface MessageView {
|
|
|
82
87
|
toolName?: string;
|
|
83
88
|
isError?: boolean;
|
|
84
89
|
details?: Record<string, unknown>;
|
|
85
|
-
customType?: string;
|
|
86
90
|
timestamp?: number;
|
|
87
91
|
completedAt?: number;
|
|
88
92
|
duration?: number;
|
|
@@ -273,6 +277,14 @@ function argsPreview(args: unknown): string | undefined {
|
|
|
273
277
|
}
|
|
274
278
|
}
|
|
275
279
|
|
|
280
|
+
/** End the open background job with `jobId` at `at`, never before it opened; a later job may reuse the id. */
|
|
281
|
+
function closeBackgroundJob(active: Map<string, PendingBackgroundJob>, jobId: string, at: number): void {
|
|
282
|
+
const job = active.get(jobId);
|
|
283
|
+
if (!job) return;
|
|
284
|
+
job.end = Math.max(job.start, at);
|
|
285
|
+
active.delete(jobId);
|
|
286
|
+
}
|
|
287
|
+
|
|
276
288
|
/**
|
|
277
289
|
* Scan one transcript into a track: model/tool/turn/background spans plus
|
|
278
290
|
* markers, and the cross-track facts (task results, request counts).
|
|
@@ -355,6 +367,18 @@ function scanTranscript(
|
|
|
355
367
|
continue;
|
|
356
368
|
}
|
|
357
369
|
|
|
370
|
+
if (entry.type === "custom_message") {
|
|
371
|
+
// Async-result deliveries persist as `custom_message` entries carrying `details.jobs[].jobId`.
|
|
372
|
+
if (entry.customType === "async-result" && envelopeTs !== undefined && Array.isArray(entry.details?.jobs)) {
|
|
373
|
+
for (const job of entry.details.jobs) {
|
|
374
|
+
if (job && typeof job === "object" && "jobId" in job && typeof job.jobId === "string") {
|
|
375
|
+
closeBackgroundJob(activeBackgroundJobs, job.jobId, envelopeTs);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
|
|
358
382
|
if (entry.type === "compaction" && envelopeTs !== undefined) {
|
|
359
383
|
markers.push({
|
|
360
384
|
time: envelopeTs,
|
|
@@ -490,6 +514,34 @@ function scanTranscript(
|
|
|
490
514
|
backgroundJobs.push(job);
|
|
491
515
|
activeBackgroundJobs.set(job.jobId, job);
|
|
492
516
|
}
|
|
517
|
+
// A `wait` (`details.jobs`) or proc:// cancel (`details.proc.jobs`) that reports a settled
|
|
518
|
+
// job replaces its async-result delivery, so the job closes when it settled, or at this result.
|
|
519
|
+
const proc = details?.proc;
|
|
520
|
+
const reportedJobs =
|
|
521
|
+
details?.op === "wait"
|
|
522
|
+
? details.jobs
|
|
523
|
+
: proc && typeof proc === "object" && "op" in proc && proc.op === "cancel" && "jobs" in proc
|
|
524
|
+
? proc.jobs
|
|
525
|
+
: undefined;
|
|
526
|
+
if (Array.isArray(reportedJobs)) {
|
|
527
|
+
for (const job of reportedJobs) {
|
|
528
|
+
if (
|
|
529
|
+
job &&
|
|
530
|
+
typeof job === "object" &&
|
|
531
|
+
"id" in job &&
|
|
532
|
+
typeof job.id === "string" &&
|
|
533
|
+
"status" in job &&
|
|
534
|
+
typeof job.status === "string" &&
|
|
535
|
+
SETTLED_JOB_STATUSES[job.status] === true
|
|
536
|
+
) {
|
|
537
|
+
const settledAt =
|
|
538
|
+
"settledAtMs" in job && typeof job.settledAtMs === "number" && Number.isFinite(job.settledAtMs)
|
|
539
|
+
? Math.min(job.settledAtMs, end)
|
|
540
|
+
: end;
|
|
541
|
+
closeBackgroundJob(activeBackgroundJobs, job.id, settledAt);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
493
545
|
if (msg.toolName === "task" && Array.isArray(details?.results)) {
|
|
494
546
|
for (const result of details.results) {
|
|
495
547
|
if (!result || typeof result !== "object" || !("id" in result) || typeof result.id !== "string")
|
|
@@ -508,22 +560,6 @@ function scanTranscript(
|
|
|
508
560
|
continue;
|
|
509
561
|
}
|
|
510
562
|
|
|
511
|
-
if (msg.role === "custom" && msg.customType === "async-result") {
|
|
512
|
-
const closeAt =
|
|
513
|
-
typeof msg.timestamp === "number" && Number.isFinite(msg.timestamp) ? msg.timestamp : envelopeTs;
|
|
514
|
-
const jobs = msg.details?.jobs;
|
|
515
|
-
if (closeAt !== undefined && Array.isArray(jobs)) {
|
|
516
|
-
for (const job of jobs) {
|
|
517
|
-
if (!job || typeof job !== "object" || !("jobId" in job) || typeof job.jobId !== "string") continue;
|
|
518
|
-
const targetJob = activeBackgroundJobs.get(job.jobId);
|
|
519
|
-
if (!targetJob || targetJob.end !== undefined) continue;
|
|
520
|
-
targetJob.end = closeAt;
|
|
521
|
-
activeBackgroundJobs.delete(job.jobId);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
continue;
|
|
525
|
-
}
|
|
526
|
-
|
|
527
563
|
if (msg.role === "user" && msg.synthetic !== true) {
|
|
528
564
|
const time = typeof msg.timestamp === "number" && Number.isFinite(msg.timestamp) ? msg.timestamp : envelopeTs;
|
|
529
565
|
if (time === undefined) continue;
|
|
@@ -1103,7 +1139,7 @@ export async function getTraceEntry(fileParam: string, entryId: string): Promise
|
|
|
1103
1139
|
// ---------------------------------------------------------------------------
|
|
1104
1140
|
// Session list
|
|
1105
1141
|
|
|
1106
|
-
interface SessionMetadata {
|
|
1142
|
+
export interface SessionMetadata {
|
|
1107
1143
|
title: string | null;
|
|
1108
1144
|
cwd: string | null;
|
|
1109
1145
|
}
|
|
@@ -1137,7 +1173,7 @@ async function readSessionMetadataHead(file: string): Promise<string> {
|
|
|
1137
1173
|
}
|
|
1138
1174
|
|
|
1139
1175
|
/** Read list metadata from the fixed title slot and session header. */
|
|
1140
|
-
async function readSessionMetadata(file: string): Promise<SessionMetadata> {
|
|
1176
|
+
export async function readSessionMetadata(file: string): Promise<SessionMetadata> {
|
|
1141
1177
|
let mtimeMs: number;
|
|
1142
1178
|
try {
|
|
1143
1179
|
mtimeMs = (await fs.stat(file)).mtimeMs;
|
package/src/tracking.ts
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only project tracking snapshots for the stats dashboard.
|
|
3
|
+
*
|
|
4
|
+
* The tracking documents under `<project>/.zeta/tracking/` are written by the
|
|
5
|
+
* coding agent's `tracking_update` tool; this module only reads them. It does
|
|
6
|
+
* not import the agent package (types or implementation) and never creates,
|
|
7
|
+
* repairs, or rewrites a tracking file.
|
|
8
|
+
*
|
|
9
|
+
* Reads are bounded per file and per directory, and every missing, truncated,
|
|
10
|
+
* malformed or unreadable input is reported as such instead of being smoothed
|
|
11
|
+
* into a plausible-looking status.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import * as fs from "node:fs";
|
|
15
|
+
import * as path from "node:path";
|
|
16
|
+
import { getProjectTrackingDir } from "@linxiraos/pi-utils";
|
|
17
|
+
import { peekFileTail } from "@linxiraos/pi-utils/peek-file";
|
|
18
|
+
import type {
|
|
19
|
+
TrackingActionRow,
|
|
20
|
+
TrackingActionsSnapshot,
|
|
21
|
+
TrackingSessionSnapshot,
|
|
22
|
+
TrackingSnapshot,
|
|
23
|
+
TrackingSnapshotState,
|
|
24
|
+
TrackingStatusSnapshot,
|
|
25
|
+
TrackingStatusValue,
|
|
26
|
+
TrackingTextSnapshot,
|
|
27
|
+
} from "./shared-types";
|
|
28
|
+
|
|
29
|
+
const STATUS_FILE = "status.json";
|
|
30
|
+
const INDEX_FILE = "INDEX.md";
|
|
31
|
+
const SESSIONS_DIR = "sessions";
|
|
32
|
+
/** Pre-rotation single log; still read when present, then the rotated family. */
|
|
33
|
+
const LEGACY_ACTIONS_FILE = "actions.jsonl";
|
|
34
|
+
/** `actions.<local day>.jsonl.log[.<roll-over index>]` (see the agent's rotating sink). */
|
|
35
|
+
const ACTION_LOG_FILE_RE = /^actions\.(\d{4}-\d{2}-\d{2})\.jsonl\.log(?:\.(\d+))?$/;
|
|
36
|
+
|
|
37
|
+
/** Upper bounds for one snapshot; larger files are read partially and say so. */
|
|
38
|
+
export const TRACKING_READ_LIMITS = {
|
|
39
|
+
statusBytes: 256 * 1024,
|
|
40
|
+
indexBytes: 512 * 1024,
|
|
41
|
+
sessionBytes: 256 * 1024,
|
|
42
|
+
sessionFiles: 50,
|
|
43
|
+
actionBytes: 1024 * 1024,
|
|
44
|
+
} as const;
|
|
45
|
+
|
|
46
|
+
interface HeadRead {
|
|
47
|
+
text: string | null;
|
|
48
|
+
size: number;
|
|
49
|
+
mtimeMs: number;
|
|
50
|
+
truncated: boolean;
|
|
51
|
+
error: NodeJS.ErrnoException | null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Read at most `maxBytes` from the start of a regular file (never a symlink). */
|
|
55
|
+
function readHead(filePath: string, maxBytes: number): HeadRead {
|
|
56
|
+
try {
|
|
57
|
+
const stat = fs.lstatSync(filePath);
|
|
58
|
+
if (!stat.isFile()) {
|
|
59
|
+
const error = new Error(`${filePath} is not a regular file`) as NodeJS.ErrnoException;
|
|
60
|
+
error.code = "EINVAL";
|
|
61
|
+
return { text: null, size: 0, mtimeMs: 0, truncated: false, error };
|
|
62
|
+
}
|
|
63
|
+
const length = Math.min(stat.size, maxBytes);
|
|
64
|
+
const buffer = Buffer.alloc(length);
|
|
65
|
+
if (length > 0) {
|
|
66
|
+
const fd = fs.openSync(filePath, "r");
|
|
67
|
+
try {
|
|
68
|
+
fs.readSync(fd, buffer, 0, length, 0);
|
|
69
|
+
} finally {
|
|
70
|
+
fs.closeSync(fd);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
text: buffer.toString("utf8"),
|
|
75
|
+
size: stat.size,
|
|
76
|
+
mtimeMs: stat.mtimeMs,
|
|
77
|
+
truncated: stat.size > maxBytes,
|
|
78
|
+
error: null,
|
|
79
|
+
};
|
|
80
|
+
} catch (error) {
|
|
81
|
+
return { text: null, size: 0, mtimeMs: 0, truncated: false, error: error as NodeJS.ErrnoException };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function readState(read: HeadRead, truncatedState: TrackingSnapshotState = "partial"): TrackingSnapshotState {
|
|
86
|
+
if (read.error) return read.error.code === "ENOENT" ? "missing" : "error";
|
|
87
|
+
return read.truncated ? truncatedState : "present";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function readError(read: HeadRead): string | null {
|
|
91
|
+
return read.error ? read.error.message : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function textSnapshot(read: HeadRead): TrackingTextSnapshot {
|
|
95
|
+
return {
|
|
96
|
+
state: readState(read),
|
|
97
|
+
content: read.error ? null : read.text,
|
|
98
|
+
truncated: read.truncated,
|
|
99
|
+
error: readError(read),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function stringArray(value: unknown): string[] {
|
|
104
|
+
return Array.isArray(value) ? value.map(String) : [];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Validate the shape the agent writes. A top-level non-object or invalid JSON
|
|
109
|
+
* is corrupt; wrong field types fall back to empty values, matching the tool's
|
|
110
|
+
* own defaults instead of blanking the rest of the file.
|
|
111
|
+
*/
|
|
112
|
+
function parseStatus(text: string): { value: TrackingStatusValue | null; error: string | null } {
|
|
113
|
+
let raw: unknown;
|
|
114
|
+
try {
|
|
115
|
+
raw = JSON.parse(text);
|
|
116
|
+
} catch (error) {
|
|
117
|
+
return { value: null, error: error instanceof Error ? error.message : String(error) };
|
|
118
|
+
}
|
|
119
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
120
|
+
return { value: null, error: "status.json must be a JSON object" };
|
|
121
|
+
}
|
|
122
|
+
const record = raw as Record<string, unknown>;
|
|
123
|
+
const phaseRows: unknown = record.phases;
|
|
124
|
+
const phases = Array.isArray(phaseRows)
|
|
125
|
+
? phaseRows.flatMap(row => {
|
|
126
|
+
if (!row || typeof row !== "object") return [];
|
|
127
|
+
if (!("name" in row) || !("status" in row)) return [];
|
|
128
|
+
if (typeof row.name !== "string" || typeof row.status !== "string") return [];
|
|
129
|
+
return [{ name: row.name, status: row.status }];
|
|
130
|
+
})
|
|
131
|
+
: undefined;
|
|
132
|
+
return {
|
|
133
|
+
value: {
|
|
134
|
+
phase: String(record.phase ?? ""),
|
|
135
|
+
progress: String(record.progress ?? ""),
|
|
136
|
+
blockers: stringArray(record.blockers),
|
|
137
|
+
decisions: stringArray(record.decisions),
|
|
138
|
+
lastUpdated: String(record.lastUpdated ?? ""),
|
|
139
|
+
...(typeof record.stage === "string" && record.stage !== "" ? { stage: record.stage } : {}),
|
|
140
|
+
...(phases && phases.length > 0 ? { phases } : {}),
|
|
141
|
+
...(typeof record.lastSessionId === "string" || record.lastSessionId === null
|
|
142
|
+
? { lastSessionId: record.lastSessionId }
|
|
143
|
+
: {}),
|
|
144
|
+
},
|
|
145
|
+
error: null,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function readStatus(trackingDir: string): { snapshot: TrackingStatusSnapshot; mtimeMs: number } {
|
|
150
|
+
const read = readHead(path.join(trackingDir, STATUS_FILE), TRACKING_READ_LIMITS.statusBytes);
|
|
151
|
+
if (read.error) {
|
|
152
|
+
return {
|
|
153
|
+
snapshot: { state: readState(read), value: null, truncated: false, error: readError(read) },
|
|
154
|
+
mtimeMs: read.mtimeMs,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const parsed = parseStatus(read.text ?? "");
|
|
158
|
+
if (!parsed.value) {
|
|
159
|
+
return {
|
|
160
|
+
snapshot: {
|
|
161
|
+
state: read.truncated ? "partial" : "corrupt",
|
|
162
|
+
value: null,
|
|
163
|
+
truncated: read.truncated,
|
|
164
|
+
error: parsed.error,
|
|
165
|
+
},
|
|
166
|
+
mtimeMs: read.mtimeMs,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
return {
|
|
170
|
+
snapshot: {
|
|
171
|
+
state: read.truncated ? "partial" : "present",
|
|
172
|
+
value: parsed.value,
|
|
173
|
+
truncated: read.truncated,
|
|
174
|
+
error: null,
|
|
175
|
+
},
|
|
176
|
+
mtimeMs: read.mtimeMs,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function readIndex(trackingDir: string): { snapshot: TrackingTextSnapshot; mtimeMs: number } {
|
|
181
|
+
const read = readHead(path.join(trackingDir, INDEX_FILE), TRACKING_READ_LIMITS.indexBytes);
|
|
182
|
+
return { snapshot: textSnapshot(read), mtimeMs: read.mtimeMs };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Oldest first: legacy `actions.jsonl`, then rotated day/index names. */
|
|
186
|
+
function actionLogFiles(trackingDir: string): string[] {
|
|
187
|
+
let names: string[];
|
|
188
|
+
try {
|
|
189
|
+
names = fs.readdirSync(trackingDir);
|
|
190
|
+
} catch {
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
const ranked: { filePath: string; day: string; index: number }[] = [];
|
|
194
|
+
for (const name of names) {
|
|
195
|
+
if (name === LEGACY_ACTIONS_FILE) {
|
|
196
|
+
ranked.push({ filePath: path.join(trackingDir, name), day: "", index: 0 });
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const match = ACTION_LOG_FILE_RE.exec(name);
|
|
200
|
+
if (!match) continue;
|
|
201
|
+
ranked.push({ filePath: path.join(trackingDir, name), day: match[1]!, index: match[2] ? Number(match[2]) : 0 });
|
|
202
|
+
}
|
|
203
|
+
ranked.sort((a, b) => (a.day === b.day ? a.index - b.index : a.day < b.day ? -1 : 1));
|
|
204
|
+
return ranked.map(row => row.filePath);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Bounded tail read of every action-log generation, oldest first. */
|
|
208
|
+
async function readActions(trackingDir: string): Promise<TrackingActionsSnapshot> {
|
|
209
|
+
const files = actionLogFiles(trackingDir);
|
|
210
|
+
if (files.length === 0) return { state: "missing", rows: [], truncated: false, invalidRows: 0, error: null };
|
|
211
|
+
|
|
212
|
+
const segments: string[] = [];
|
|
213
|
+
const errors: string[] = [];
|
|
214
|
+
let remaining = TRACKING_READ_LIMITS.actionBytes;
|
|
215
|
+
let truncated = false;
|
|
216
|
+
for (let i = files.length - 1; i >= 0; i--) {
|
|
217
|
+
const filePath = files[i]!;
|
|
218
|
+
try {
|
|
219
|
+
const stat = fs.lstatSync(filePath);
|
|
220
|
+
if (!stat.isFile()) {
|
|
221
|
+
errors.push(`${path.basename(filePath)} is not a regular file`);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (remaining <= 0) {
|
|
225
|
+
truncated = true;
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
if (stat.size <= 0) continue;
|
|
229
|
+
const window = Math.min(remaining, stat.size);
|
|
230
|
+
if (window < stat.size) truncated = true;
|
|
231
|
+
const text = await peekFileTail(filePath, window, bytes => new TextDecoder().decode(bytes));
|
|
232
|
+
remaining -= window;
|
|
233
|
+
// A window starting mid-file begins in a truncated fragment.
|
|
234
|
+
const firstNewline = window < stat.size ? text.indexOf("\n") : -1;
|
|
235
|
+
if (firstNewline === -1 && window < stat.size) continue;
|
|
236
|
+
segments.unshift(firstNewline === -1 ? text : text.slice(firstNewline + 1));
|
|
237
|
+
} catch (error) {
|
|
238
|
+
errors.push(`${path.basename(filePath)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const rows: TrackingActionRow[] = [];
|
|
243
|
+
let invalidRows = 0;
|
|
244
|
+
for (const line of segments
|
|
245
|
+
.join("")
|
|
246
|
+
.split("\n")
|
|
247
|
+
.map(value => value.trim())
|
|
248
|
+
.filter(Boolean)) {
|
|
249
|
+
try {
|
|
250
|
+
const parsed = JSON.parse(line) as Partial<TrackingActionRow> | null;
|
|
251
|
+
if (!parsed || typeof parsed !== "object" || typeof parsed.action !== "string") {
|
|
252
|
+
invalidRows++;
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
rows.push({
|
|
256
|
+
timestamp: String(parsed.timestamp ?? ""),
|
|
257
|
+
action: parsed.action,
|
|
258
|
+
...(parsed.detail !== undefined ? { detail: String(parsed.detail) } : {}),
|
|
259
|
+
});
|
|
260
|
+
} catch {
|
|
261
|
+
invalidRows++;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
let state: TrackingSnapshotState;
|
|
266
|
+
if (errors.length > 0) state = rows.length > 0 ? "partial" : "error";
|
|
267
|
+
else if (invalidRows > 0) state = rows.length > 0 ? "partial" : "corrupt";
|
|
268
|
+
else state = "present";
|
|
269
|
+
return {
|
|
270
|
+
state,
|
|
271
|
+
rows,
|
|
272
|
+
truncated,
|
|
273
|
+
invalidRows,
|
|
274
|
+
error: errors.length > 0 ? errors.join("; ") : null,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Newest sessions first, up to the read limit; each file is bounded. */
|
|
279
|
+
function readSessions(trackingDir: string): {
|
|
280
|
+
state: TrackingSnapshotState;
|
|
281
|
+
sessions: TrackingSessionSnapshot[];
|
|
282
|
+
mtimeMs: number;
|
|
283
|
+
error: string | null;
|
|
284
|
+
} {
|
|
285
|
+
const dir = path.join(trackingDir, SESSIONS_DIR);
|
|
286
|
+
let entries: fs.Dirent[];
|
|
287
|
+
try {
|
|
288
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
289
|
+
} catch (error) {
|
|
290
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
291
|
+
return {
|
|
292
|
+
state: code === "ENOENT" ? "missing" : "error",
|
|
293
|
+
sessions: [],
|
|
294
|
+
mtimeMs: 0,
|
|
295
|
+
error: code === "ENOENT" ? null : error instanceof Error ? error.message : String(error),
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const files: { filePath: string; name: string; mtimeMs: number }[] = [];
|
|
300
|
+
const errors: string[] = [];
|
|
301
|
+
for (const entry of entries) {
|
|
302
|
+
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
|
|
303
|
+
const filePath = path.join(dir, entry.name);
|
|
304
|
+
try {
|
|
305
|
+
const stat = fs.lstatSync(filePath);
|
|
306
|
+
if (!stat.isFile()) continue;
|
|
307
|
+
files.push({ filePath, name: entry.name, mtimeMs: stat.mtimeMs });
|
|
308
|
+
} catch (error) {
|
|
309
|
+
errors.push(`${entry.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
313
|
+
const kept = files.slice(0, TRACKING_READ_LIMITS.sessionFiles);
|
|
314
|
+
const sessions = kept.map(file => {
|
|
315
|
+
const read = readHead(file.filePath, TRACKING_READ_LIMITS.sessionBytes);
|
|
316
|
+
return { name: file.name, ...textSnapshot(read) };
|
|
317
|
+
});
|
|
318
|
+
const newest = files.length > 0 ? files[0]!.mtimeMs : 0;
|
|
319
|
+
const state: TrackingSnapshotState =
|
|
320
|
+
errors.length > 0 || sessions.some(session => session.state === "partial" || session.state === "error")
|
|
321
|
+
? "partial"
|
|
322
|
+
: "present";
|
|
323
|
+
return { state, sessions, mtimeMs: newest, error: errors.length > 0 ? errors.join("; ") : null };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Exact registry label. The label is an opaque database key, never a path, so
|
|
328
|
+
* the caller cannot smuggle traversal into it; the server resolves the label to
|
|
329
|
+
* a session-header cwd before calling {@link readTrackingSnapshot}.
|
|
330
|
+
*/
|
|
331
|
+
export function isTrackableProject(project: string, known: readonly string[]): boolean {
|
|
332
|
+
return known.includes(project);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Read one project's tracking documents without writing anything. */
|
|
336
|
+
export async function readTrackingSnapshot(cwd: string, project = cwd): Promise<TrackingSnapshot> {
|
|
337
|
+
if (!path.isAbsolute(cwd)) throw new Error("tracking cwd must be an absolute path");
|
|
338
|
+
const trackingDir = getProjectTrackingDir(cwd);
|
|
339
|
+
const missing = (): TrackingSnapshot => ({
|
|
340
|
+
project,
|
|
341
|
+
trackingDir,
|
|
342
|
+
exists: false,
|
|
343
|
+
updatedAt: null,
|
|
344
|
+
status: { state: "missing", value: null, truncated: false, error: null },
|
|
345
|
+
index: { state: "missing", content: null, truncated: false, error: null },
|
|
346
|
+
actions: { state: "missing", rows: [], truncated: false, invalidRows: 0, error: null },
|
|
347
|
+
sessions: [],
|
|
348
|
+
sessionsState: "missing",
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
let dirStat: fs.Stats;
|
|
352
|
+
try {
|
|
353
|
+
dirStat = fs.lstatSync(trackingDir);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
356
|
+
if (code === "ENOENT") return missing();
|
|
357
|
+
return {
|
|
358
|
+
...missing(),
|
|
359
|
+
status: { state: "error", value: null, truncated: false, error: String((error as Error).message) },
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
if (!dirStat.isDirectory()) return missing();
|
|
363
|
+
|
|
364
|
+
const status = readStatus(trackingDir);
|
|
365
|
+
const index = readIndex(trackingDir);
|
|
366
|
+
const actions = await readActions(trackingDir);
|
|
367
|
+
const sessions = readSessions(trackingDir);
|
|
368
|
+
const newest = Math.max(status.mtimeMs, index.mtimeMs, newestActionMtime(trackingDir), sessions.mtimeMs);
|
|
369
|
+
return {
|
|
370
|
+
project,
|
|
371
|
+
trackingDir,
|
|
372
|
+
exists: true,
|
|
373
|
+
updatedAt: newest > 0 ? new Date(newest).toISOString() : null,
|
|
374
|
+
status: status.snapshot,
|
|
375
|
+
index: index.snapshot,
|
|
376
|
+
actions,
|
|
377
|
+
sessions: sessions.sessions,
|
|
378
|
+
sessionsState: sessions.state,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Newest mtime among the action-log generations (even when every row is malformed). */
|
|
383
|
+
function newestActionMtime(trackingDir: string): number {
|
|
384
|
+
let newest = 0;
|
|
385
|
+
for (const filePath of actionLogFiles(trackingDir)) {
|
|
386
|
+
try {
|
|
387
|
+
const stat = fs.lstatSync(filePath);
|
|
388
|
+
if (stat.isFile() && stat.mtimeMs > newest) newest = stat.mtimeMs;
|
|
389
|
+
} catch {
|
|
390
|
+
// ignore a file that disappeared mid-read
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return newest;
|
|
394
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -241,11 +241,11 @@ export interface AssistantTextStats {
|
|
|
241
241
|
}
|
|
242
242
|
|
|
243
243
|
/**
|
|
244
|
-
* Pair emitted by the parser
|
|
245
|
-
*
|
|
246
|
-
*
|
|
247
|
-
* applies the link to the persisted `user_messages` row so it
|
|
248
|
-
* up in the "unknown" model bucket.
|
|
244
|
+
* Pair emitted by the parser for each assistant message that answers a user
|
|
245
|
+
* message: the first assistant message descending from it through non-message
|
|
246
|
+
* entries, whether the user message was parsed in this pass or an earlier one.
|
|
247
|
+
* The aggregator applies the link to the persisted `user_messages` row so it
|
|
248
|
+
* stops showing up in the "unknown" model bucket.
|
|
249
249
|
*/
|
|
250
250
|
export interface UserMessageLink {
|
|
251
251
|
sessionFile: string;
|