pi-evals 0.0.0-stage → 0.1.0
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 +14 -0
- package/LICENSE +21 -0
- package/README.md +106 -2
- package/dist/aggregate.js +113 -0
- package/dist/build.js +260 -0
- package/dist/changes.js +170 -0
- package/dist/cli.js +86 -0
- package/dist/coverage.js +34 -0
- package/dist/detectors.js +154 -0
- package/dist/extract/file.js +42 -0
- package/dist/extract/run.js +149 -0
- package/dist/extract/session.js +430 -0
- package/dist/extract/worker.js +12 -0
- package/dist/index.js +160 -0
- package/dist/meta.js +233 -0
- package/dist/model.js +317 -0
- package/dist/observer.js +240 -0
- package/dist/ops.js +93 -0
- package/dist/owners.js +97 -0
- package/dist/paths.js +76 -0
- package/dist/project.js +43 -0
- package/dist/query.js +92 -0
- package/dist/render.js +172 -0
- package/dist/schema.js +65 -0
- package/dist/skills.js +41 -0
- package/dist/store.js +51 -0
- package/docs/design.md +95 -0
- package/docs/schema.md +68 -0
- package/package.json +56 -4
- package/src/aggregate.ts +204 -0
- package/src/build.ts +257 -0
- package/src/changes.ts +178 -0
- package/src/cli.ts +89 -0
- package/src/coverage.ts +44 -0
- package/src/detectors.ts +182 -0
- package/src/extract/file.ts +46 -0
- package/src/extract/run.ts +198 -0
- package/src/extract/session.ts +430 -0
- package/src/extract/worker.ts +12 -0
- package/src/index.ts +155 -0
- package/src/meta.ts +259 -0
- package/src/model.ts +346 -0
- package/src/observer.ts +255 -0
- package/src/ops.ts +110 -0
- package/src/owners.ts +92 -0
- package/src/paths.ts +108 -0
- package/src/project.ts +43 -0
- package/src/query.ts +85 -0
- package/src/render.ts +189 -0
- package/src/schema.ts +84 -0
- package/src/skills.ts +46 -0
- package/src/store.ts +49 -0
package/src/cli.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Thin CLI over the same operations as `/evals`. */
|
|
3
|
+
import { context, mark, runExtract, runReport, statusText } from "./ops.ts";
|
|
4
|
+
import { query, type View, VIEWS } from "./query.ts";
|
|
5
|
+
|
|
6
|
+
const USAGE = `usage:
|
|
7
|
+
pi-evals extract [--root <dir>]... [--workers <n>] [--json]
|
|
8
|
+
pi-evals report [--out <dir>] [--since YYYY-MM-DD] [--project <key>] [--lang zh|en]
|
|
9
|
+
pi-evals status
|
|
10
|
+
pi-evals query <${VIEWS.join("|")}> [--since YYYY-MM-DD] [--project <key>]
|
|
11
|
+
pi-evals mark <note>`;
|
|
12
|
+
|
|
13
|
+
function flag(args: string[], name: string): string | undefined {
|
|
14
|
+
const i = args.indexOf(name);
|
|
15
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function flags(args: string[], name: string): string[] {
|
|
19
|
+
return args.flatMap((a, i) => (a === name && args[i + 1] ? [args[i + 1]] : []));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function main(argv: string[]): Promise<number> {
|
|
23
|
+
const [cmd, ...args] = argv;
|
|
24
|
+
const settingsError = context().settings.error;
|
|
25
|
+
if (settingsError) process.stderr.write(`pi-evals settings: ${settingsError}\n`);
|
|
26
|
+
if (cmd === "extract") {
|
|
27
|
+
const json = args.includes("--json");
|
|
28
|
+
const workers = flag(args, "--workers");
|
|
29
|
+
let lastPrint = 0;
|
|
30
|
+
const status = await runExtract({
|
|
31
|
+
extraRoots: flags(args, "--root"),
|
|
32
|
+
workers: workers === undefined ? undefined : Number(workers),
|
|
33
|
+
onProgress: (done, total, bytes) => {
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
if (now - lastPrint < 500 && done !== total) return;
|
|
36
|
+
lastPrint = now;
|
|
37
|
+
if (json) process.stdout.write(`${JSON.stringify({ progress: { done, total, bytes } })}\n`);
|
|
38
|
+
else process.stderr.write(`\rextract ${done}/${total} files, ${(bytes / 1e9).toFixed(2)} GB `);
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
if (json) process.stdout.write(`${JSON.stringify({ result: status })}\n`);
|
|
42
|
+
else {
|
|
43
|
+
process.stderr.write("\n");
|
|
44
|
+
const s = status.stats;
|
|
45
|
+
console.log(`read ${s.changed} of ${s.files} files (${(s.bytes / 1e9).toFixed(2)} GB) in ${(s.ms / 1000).toFixed(1)} s, ${s.mbPerSec} MB/s; ${s.records} records; ${s.failed} failed`);
|
|
46
|
+
console.log(`sessions ${status.sessions.backfill} indexed (subagent ${status.sessions.subagent}, linked ${status.sessions.linked}), live-only ${status.sessions.live}; changes ${status.changes}`);
|
|
47
|
+
}
|
|
48
|
+
return status.stats.failed ? 2 : 0;
|
|
49
|
+
}
|
|
50
|
+
if (cmd === "report") {
|
|
51
|
+
const lang = flag(args, "--lang") === "en" ? "en" : "zh";
|
|
52
|
+
const out = runReport({ outDir: flag(args, "--out"), filter: { since: flag(args, "--since"), project: flag(args, "--project") }, lang });
|
|
53
|
+
if (!out) {
|
|
54
|
+
console.error("nothing extracted yet: run pi-evals extract");
|
|
55
|
+
return 1;
|
|
56
|
+
}
|
|
57
|
+
console.log(out.html);
|
|
58
|
+
console.log(out.json);
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
if (cmd === "status") {
|
|
62
|
+
console.log(statusText());
|
|
63
|
+
return 0;
|
|
64
|
+
}
|
|
65
|
+
if (cmd === "query") {
|
|
66
|
+
const view = args[0] as View;
|
|
67
|
+
if (!VIEWS.includes(view)) {
|
|
68
|
+
console.error(USAGE);
|
|
69
|
+
return 1;
|
|
70
|
+
}
|
|
71
|
+
console.log(query(view, { since: flag(args, "--since"), project: flag(args, "--project") }));
|
|
72
|
+
return 0;
|
|
73
|
+
}
|
|
74
|
+
if (cmd === "mark" && args.length) {
|
|
75
|
+
const change = mark(args.join(" "));
|
|
76
|
+
console.log(`marked ${change.at}`);
|
|
77
|
+
return 0;
|
|
78
|
+
}
|
|
79
|
+
console.error(USAGE);
|
|
80
|
+
return cmd === "help" || cmd === "--help" ? 0 : 1;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
main(process.argv.slice(2)).then(
|
|
84
|
+
(code) => process.exit(code),
|
|
85
|
+
(error) => {
|
|
86
|
+
console.error(error instanceof Error ? error.stack : error);
|
|
87
|
+
process.exit(1);
|
|
88
|
+
},
|
|
89
|
+
);
|
package/src/coverage.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** The cleanup gate: how many session files older than the cut are fully indexed, by count and bytes. */
|
|
2
|
+
import type { Checkpoint } from "./extract/run.ts";
|
|
3
|
+
import { listSessionFiles } from "./extract/run.ts";
|
|
4
|
+
|
|
5
|
+
export interface Coverage {
|
|
6
|
+
cutDays: number;
|
|
7
|
+
cutoff: string;
|
|
8
|
+
old: { files: number; bytes: number };
|
|
9
|
+
indexed: { files: number; bytes: number };
|
|
10
|
+
notIndexed: { files: number; bytes: number };
|
|
11
|
+
all: { files: number; bytes: number; indexedFiles: number };
|
|
12
|
+
/** Session files the index still holds whose source file is gone. */
|
|
13
|
+
retainedGone: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function coverage(roots: string[], checkpoint: Checkpoint, cutDays: number, now = Date.now()): Coverage {
|
|
17
|
+
const cutoff = now - cutDays * 86_400_000;
|
|
18
|
+
const files = listSessionFiles(roots);
|
|
19
|
+
const result: Coverage = {
|
|
20
|
+
cutDays,
|
|
21
|
+
cutoff: new Date(cutoff).toISOString(),
|
|
22
|
+
old: { files: 0, bytes: 0 },
|
|
23
|
+
indexed: { files: 0, bytes: 0 },
|
|
24
|
+
notIndexed: { files: 0, bytes: 0 },
|
|
25
|
+
all: { files: files.length, bytes: 0, indexedFiles: 0 },
|
|
26
|
+
retainedGone: 0,
|
|
27
|
+
};
|
|
28
|
+
const present = new Set<string>();
|
|
29
|
+
for (const f of files) {
|
|
30
|
+
present.add(f.path);
|
|
31
|
+
result.all.bytes += f.size;
|
|
32
|
+
const known = checkpoint.files[f.path];
|
|
33
|
+
const fresh = !!known && known.size === f.size && known.mtimeMs === f.mtimeMs;
|
|
34
|
+
if (fresh) result.all.indexedFiles += 1;
|
|
35
|
+
if (f.mtimeMs >= cutoff) continue;
|
|
36
|
+
result.old.files += 1;
|
|
37
|
+
result.old.bytes += f.size;
|
|
38
|
+
const side = fresh ? result.indexed : result.notIndexed;
|
|
39
|
+
side.files += 1;
|
|
40
|
+
side.bytes += f.size;
|
|
41
|
+
}
|
|
42
|
+
for (const path of Object.keys(checkpoint.files)) if (!present.has(path)) result.retainedGone += 1;
|
|
43
|
+
return result;
|
|
44
|
+
}
|
package/src/detectors.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process detectors over one session, fed entries in file order. Each yields a session-scoped
|
|
3
|
+
* `gen_ai.evaluation.result` (annotator CODE). Commands and text are held in memory only while the
|
|
4
|
+
* session is read; results carry fixed reason codes, never text.
|
|
5
|
+
*
|
|
6
|
+
* Anchor and change reading is ported from pi-anchorloop's close guard (`pi/close-guard.ts` `read()`,
|
|
7
|
+
* MIT, Copyright (c) 2026 Wei Hung, anchorloop 3.3.0 at 7614445): the last `Anchor:` line or todo anchor,
|
|
8
|
+
* backticked commands (a todo's bare value is one command), a change is a successful `write` or `edit`,
|
|
9
|
+
* a bash run passes on exit code 0 (else on `isError` false), and a run matches an anchor command when it contains it.
|
|
10
|
+
* Like the guard, an edit made through bash is not seen as a change. Unlike the guard, an Anchor stated only in the
|
|
11
|
+
* first user message (a subagent's brief) is reported as `anchor_only_in_brief`, still a fail: the rule asks the
|
|
12
|
+
* agent to state it.
|
|
13
|
+
*/
|
|
14
|
+
import type { Label } from "./schema.ts";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* anchorloop 3.0.0 (one anchor rule and the close guard) reached this setup when weihung-basic-agent pinned it
|
|
18
|
+
* (commit 9f72366, 2026-11-23T10:51:07Z). Sessions that started earlier are out of scope.
|
|
19
|
+
*/
|
|
20
|
+
export const ERA_START = "2026-11-23T10:51:07.000Z";
|
|
21
|
+
export const DETECTORS = ["anchor_before_first_edit", "check_after_last_edit", "todo_evidence", "close_guard_quiet"] as const;
|
|
22
|
+
export type DetectorName = (typeof DETECTORS)[number];
|
|
23
|
+
export interface DetectorResult {
|
|
24
|
+
name: DetectorName;
|
|
25
|
+
label: Label;
|
|
26
|
+
/** Share in [0, 1] where the detector measures a share (todo_evidence). */
|
|
27
|
+
value?: number;
|
|
28
|
+
/** A fixed reason code. */
|
|
29
|
+
explanation: string;
|
|
30
|
+
}
|
|
31
|
+
export type NoticeKind = "no_anchor" | "no_passing_run" | "evidence_handoff" | "other";
|
|
32
|
+
|
|
33
|
+
const NOTICE_TYPE = "anchorloop-close-guard";
|
|
34
|
+
const MAX_RUNS = 5000;
|
|
35
|
+
|
|
36
|
+
export function noticeKind(text: unknown): NoticeKind {
|
|
37
|
+
if (typeof text !== "string") return "other";
|
|
38
|
+
if (/no `Anchor: <check>` line was stated/.test(text)) return "no_anchor";
|
|
39
|
+
if (/no passing run of /.test(text)) return "no_passing_run";
|
|
40
|
+
if (/use todo update on #\d+ to append/.test(text)) return "evidence_handoff";
|
|
41
|
+
return "other";
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const squeeze = (text: string) => text.replace(/[ \t]+/g, " ").trim();
|
|
45
|
+
|
|
46
|
+
function commandsOf(text: string, bare: boolean): string[] {
|
|
47
|
+
const ticked = [...text.matchAll(/`([^`\n]+)`/g)].map((m) => squeeze(m[1])).filter(Boolean);
|
|
48
|
+
return ticked.length || !bare ? ticked : [squeeze(text)].filter(Boolean);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function anchorLine(text: string): string | undefined {
|
|
52
|
+
const lines = [...text.matchAll(/^[ \t>*_-]*(?:reality )?anchor[*_]*:[*_]*\s*(.+)$/gim)];
|
|
53
|
+
return lines.at(-1)?.[1];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
type Part = { type?: string; text?: string; id?: string; name?: string; arguments?: Record<string, unknown> };
|
|
57
|
+
interface Task { status?: string; evidence?: unknown }
|
|
58
|
+
type Entry = {
|
|
59
|
+
type?: string;
|
|
60
|
+
customType?: string;
|
|
61
|
+
content?: unknown;
|
|
62
|
+
data?: { v?: number; tasks?: Task[] };
|
|
63
|
+
message?: { role?: string; content?: unknown; toolCallId?: string; isError?: boolean; structuredContent?: { exit_code?: unknown } };
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export class ProcessTracker {
|
|
67
|
+
private seq = 0;
|
|
68
|
+
private calls = new Map<string, { name: string; command?: string }>();
|
|
69
|
+
private runs: { seq: number; command: string; ok: boolean }[] = [];
|
|
70
|
+
private anchor: string[] | undefined;
|
|
71
|
+
private anchoredBeforeChange = false;
|
|
72
|
+
private firstChange = -1;
|
|
73
|
+
private lastChange = -1;
|
|
74
|
+
private tasks: Task[] | undefined;
|
|
75
|
+
private sawUser = false;
|
|
76
|
+
private briefAnchor = false;
|
|
77
|
+
private notices = new Map<NoticeKind, number>();
|
|
78
|
+
|
|
79
|
+
/** Notice kinds seen so far, for `anchorloop.close_guard.notice` records. */
|
|
80
|
+
feed(raw: unknown): NoticeKind | undefined {
|
|
81
|
+
const entry = raw as Entry;
|
|
82
|
+
const seq = ++this.seq;
|
|
83
|
+
if (entry?.type === "custom" && entry.customType === "todo/v1" && entry.data?.v === 1 && Array.isArray(entry.data.tasks)) {
|
|
84
|
+
this.tasks = entry.data.tasks;
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
if (entry?.type === "custom_message" && entry.customType === NOTICE_TYPE) {
|
|
88
|
+
const kind = noticeKind(entry.content);
|
|
89
|
+
this.notices.set(kind, (this.notices.get(kind) ?? 0) + 1);
|
|
90
|
+
return kind;
|
|
91
|
+
}
|
|
92
|
+
const message = entry?.message;
|
|
93
|
+
if (entry?.type !== "message" || !message) return undefined;
|
|
94
|
+
if (message.role === "user" && !this.sawUser) {
|
|
95
|
+
this.sawUser = true;
|
|
96
|
+
const text = Array.isArray(message.content) ? (message.content as Part[]).map((p) => (p?.type === "text" ? (p.text ?? "") : "")).join("\n") : String(message.content ?? "");
|
|
97
|
+
this.briefAnchor = anchorLine(text) !== undefined;
|
|
98
|
+
} else if (message.role === "assistant" && Array.isArray(message.content)) {
|
|
99
|
+
for (const part of message.content as Part[]) {
|
|
100
|
+
if (part?.type === "text" && typeof part.text === "string") {
|
|
101
|
+
const line = anchorLine(part.text);
|
|
102
|
+
if (line !== undefined) this.setAnchor(commandsOf(line, false));
|
|
103
|
+
} else if (part?.type === "toolCall" && typeof part.id === "string") {
|
|
104
|
+
const command = part.name === "bash" && typeof part.arguments?.command === "string" ? squeeze(part.arguments.command) : undefined;
|
|
105
|
+
this.calls.set(part.id, { name: String(part.name), command });
|
|
106
|
+
if (part.name === "todo" && part.arguments) {
|
|
107
|
+
const batch = Array.isArray(part.arguments.tasks) ? part.arguments.tasks : [];
|
|
108
|
+
for (const item of [part.arguments, ...batch] as Record<string, unknown>[]) {
|
|
109
|
+
const meta = item?.metadata as Record<string, unknown> | undefined;
|
|
110
|
+
const value = [item?.anchor, meta?.anchor].find((v) => typeof v === "string" && v.trim()) as string | undefined;
|
|
111
|
+
if (value) this.setAnchor(commandsOf(value, true));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
} else if (message.role === "toolResult" && typeof message.toolCallId === "string") {
|
|
117
|
+
const call = this.calls.get(message.toolCallId);
|
|
118
|
+
if (!call) return undefined;
|
|
119
|
+
this.calls.delete(message.toolCallId);
|
|
120
|
+
const code = message.structuredContent?.exit_code;
|
|
121
|
+
const ok = typeof code === "number" ? code === 0 : message.isError !== true;
|
|
122
|
+
if ((call.name === "write" || call.name === "edit") && ok) {
|
|
123
|
+
if (this.firstChange < 0) {
|
|
124
|
+
this.firstChange = seq;
|
|
125
|
+
this.anchoredBeforeChange = this.anchor !== undefined;
|
|
126
|
+
}
|
|
127
|
+
this.lastChange = seq;
|
|
128
|
+
} else if (call.name === "bash" && call.command) {
|
|
129
|
+
this.runs.push({ seq, command: call.command, ok });
|
|
130
|
+
if (this.runs.length > MAX_RUNS) this.runs.splice(0, this.runs.length - MAX_RUNS);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private setAnchor(commands: string[]) {
|
|
137
|
+
this.anchor = commands;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
results(inScope: boolean): DetectorResult[] {
|
|
141
|
+
if (!inScope) return DETECTORS_ALL.map((name) => ({ name, label: "na", explanation: "out_of_scope_pre_3.0" }));
|
|
142
|
+
return [this.anchorFirst(), this.checkAfter(), this.todoEvidence(), this.quiet()];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private anchorFirst(): DetectorResult {
|
|
146
|
+
const name = "anchor_before_first_edit";
|
|
147
|
+
if (this.firstChange < 0) return { name, label: "na", explanation: "no_edit" };
|
|
148
|
+
if (this.anchoredBeforeChange) return { name, label: "pass", explanation: "anchor_first" };
|
|
149
|
+
return { name, label: "fail", explanation: this.briefAnchor ? "anchor_only_in_brief" : "change_before_anchor" };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private checkAfter(): DetectorResult {
|
|
153
|
+
const name = "check_after_last_edit";
|
|
154
|
+
if (this.lastChange < 0) return { name, label: "na", explanation: "no_edit" };
|
|
155
|
+
if (!this.anchor) return { name, label: "na", explanation: "no_anchor" };
|
|
156
|
+
if (!this.anchor.length) return { name, label: "na", explanation: "anchor_without_command" };
|
|
157
|
+
const green = this.anchor.every((command) => {
|
|
158
|
+
const last = this.runs.findLast((run) => run.command.includes(command));
|
|
159
|
+
return !!last && last.seq > this.lastChange && last.ok;
|
|
160
|
+
});
|
|
161
|
+
return green ? { name, label: "pass", explanation: "anchor_green" } : { name, label: "fail", explanation: "no_passing_run_after_change" };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private todoEvidence(): DetectorResult {
|
|
165
|
+
const name = "todo_evidence";
|
|
166
|
+
const done = (this.tasks ?? []).filter((t) => t?.status === "completed");
|
|
167
|
+
if (!done.length) return { name, label: "na", explanation: "no_completed_task" };
|
|
168
|
+
const withEvidence = done.filter((t) => Array.isArray(t.evidence) && t.evidence.length > 0).length;
|
|
169
|
+
const value = withEvidence / done.length;
|
|
170
|
+
return { name, label: value === 1 ? "pass" : "fail", value, explanation: value === 1 ? "all_evidenced" : "completed_without_evidence" };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private quiet(): DetectorResult {
|
|
174
|
+
const name = "close_guard_quiet";
|
|
175
|
+
if (this.firstChange < 0) return { name, label: "na", explanation: "no_edit" };
|
|
176
|
+
// An evidence hand-off asks the agent to record a run that passed; it is not a missing or failing check.
|
|
177
|
+
const top = [...this.notices].filter(([kind]) => kind !== "evidence_handoff").sort((a, b) => b[1] - a[1])[0];
|
|
178
|
+
return top ? { name, label: "fail", explanation: top[0] } : { name, label: "pass", explanation: "no_notice" };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const DETECTORS_ALL: DetectorName[] = [...DETECTORS];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Extracting one session file: stream its lines, write its records next to the index, return its summary. */
|
|
2
|
+
import { createReadStream, mkdirSync, openSync, renameSync, writeSync, closeSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline";
|
|
5
|
+
import type { SessionSummary } from "../aggregate.ts";
|
|
6
|
+
import type { EvalRecord } from "../schema.ts";
|
|
7
|
+
import { SessionReader } from "./session.ts";
|
|
8
|
+
|
|
9
|
+
export interface FileResult {
|
|
10
|
+
summary: SessionSummary;
|
|
11
|
+
catalog?: string[];
|
|
12
|
+
records: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Reads `path` (never writes it) and writes its records to `out` atomically. */
|
|
16
|
+
export async function extractFile(path: string, out: string, home: string): Promise<FileResult> {
|
|
17
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
18
|
+
const tmp = `${out}.${process.pid}.tmp`;
|
|
19
|
+
const fd = openSync(tmp, "w");
|
|
20
|
+
let buffer: string[] = [];
|
|
21
|
+
let count = 0;
|
|
22
|
+
const flush = () => {
|
|
23
|
+
if (buffer.length) writeSync(fd, buffer.join(""));
|
|
24
|
+
buffer = [];
|
|
25
|
+
};
|
|
26
|
+
const emit = (r: EvalRecord) => {
|
|
27
|
+
buffer.push(`${JSON.stringify(r)}\n`);
|
|
28
|
+
count += 1;
|
|
29
|
+
if (buffer.length >= 500) flush();
|
|
30
|
+
};
|
|
31
|
+
try {
|
|
32
|
+
const reader = new SessionReader(path, home, emit);
|
|
33
|
+
const lines = createInterface({ input: createReadStream(path, { highWaterMark: 1 << 20 }), crlfDelay: Number.POSITIVE_INFINITY });
|
|
34
|
+
for await (const line of lines) reader.feedLine(line);
|
|
35
|
+
const { summary, catalog } = reader.finish();
|
|
36
|
+
flush();
|
|
37
|
+
closeSync(fd);
|
|
38
|
+
renameSync(tmp, out);
|
|
39
|
+
return { summary, catalog, records: count };
|
|
40
|
+
} catch (error) {
|
|
41
|
+
try {
|
|
42
|
+
closeSync(fd);
|
|
43
|
+
} catch {}
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/** Incremental back-fill over session roots: only files whose size or mtime changed are read again. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { availableParallelism } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { Worker } from "node:worker_threads";
|
|
7
|
+
import type { SessionSummary } from "../aggregate.ts";
|
|
8
|
+
import type { Layout } from "../paths.ts";
|
|
9
|
+
import { fileKey } from "../schema.ts";
|
|
10
|
+
import { extractFile, type FileResult } from "./file.ts";
|
|
11
|
+
|
|
12
|
+
export interface FileEntry {
|
|
13
|
+
size: number;
|
|
14
|
+
mtimeMs: number;
|
|
15
|
+
key: string;
|
|
16
|
+
month: string;
|
|
17
|
+
summary: SessionSummary;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Bump when extraction changes what it derives; a checkpoint from another version re-reads every file. */
|
|
21
|
+
export const EXTRACTOR_VERSION = 2;
|
|
22
|
+
|
|
23
|
+
export interface Checkpoint {
|
|
24
|
+
v: 1;
|
|
25
|
+
extractor?: number;
|
|
26
|
+
files: Record<string, FileEntry>;
|
|
27
|
+
/** Skill catalogs by hash, with the newest session start that offered each. */
|
|
28
|
+
catalogs: Record<string, { names: string[]; last: string }>;
|
|
29
|
+
lastExtract?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ExtractStats {
|
|
33
|
+
files: number;
|
|
34
|
+
changed: number;
|
|
35
|
+
failed: number;
|
|
36
|
+
bytes: number;
|
|
37
|
+
records: number;
|
|
38
|
+
ms: number;
|
|
39
|
+
errors: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type Progress = (done: number, total: number, bytes: number) => void;
|
|
43
|
+
|
|
44
|
+
export function loadCheckpoint(file: string): Checkpoint {
|
|
45
|
+
if (!existsSync(file)) return { v: 1, extractor: EXTRACTOR_VERSION, files: {}, catalogs: {} };
|
|
46
|
+
const raw = JSON.parse(readFileSync(file, "utf8")) as Checkpoint;
|
|
47
|
+
if (raw.v !== 1) throw new Error(`pi-evals: unknown checkpoint version ${raw.v} in ${file}`);
|
|
48
|
+
return raw;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function saveCheckpoint(file: string, checkpoint: Checkpoint): void {
|
|
52
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
53
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
54
|
+
writeFileSync(tmp, JSON.stringify(checkpoint));
|
|
55
|
+
renameSync(tmp, file);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Every `*.jsonl` under the roots (any depth), with size and mtime. Sidecars and missing roots are skipped. */
|
|
59
|
+
export function listSessionFiles(roots: string[]): { path: string; size: number; mtimeMs: number }[] {
|
|
60
|
+
const out: { path: string; size: number; mtimeMs: number }[] = [];
|
|
61
|
+
const walk = (dir: string) => {
|
|
62
|
+
let entries: import("node:fs").Dirent[];
|
|
63
|
+
try {
|
|
64
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
65
|
+
} catch {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
for (const entry of entries) {
|
|
69
|
+
const path = join(dir, entry.name);
|
|
70
|
+
if (entry.isDirectory()) walk(path);
|
|
71
|
+
else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
72
|
+
try {
|
|
73
|
+
const st = statSync(path);
|
|
74
|
+
out.push({ path, size: st.size, mtimeMs: Math.floor(st.mtimeMs) });
|
|
75
|
+
} catch {}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
for (const root of roots) walk(root);
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const monthOf = (path: string) => path.match(/(\d{4}-\d{2})-\d{2}T/)?.[1] ?? "unknown";
|
|
84
|
+
|
|
85
|
+
const workerUrl = () => new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url);
|
|
86
|
+
|
|
87
|
+
/** Runs `jobs` on a pool of worker threads, or in this thread when `workers` is 0. */
|
|
88
|
+
async function runPool(
|
|
89
|
+
jobs: { path: string; out: string }[],
|
|
90
|
+
home: string,
|
|
91
|
+
workers: number,
|
|
92
|
+
onDone: (job: { path: string; out: string }, result: FileResult | undefined, error?: string) => void,
|
|
93
|
+
signal?: AbortSignal,
|
|
94
|
+
): Promise<void> {
|
|
95
|
+
if (workers <= 0) {
|
|
96
|
+
for (const job of jobs) {
|
|
97
|
+
if (signal?.aborted) return;
|
|
98
|
+
try {
|
|
99
|
+
onDone(job, await extractFile(job.path, job.out, home));
|
|
100
|
+
} catch (error) {
|
|
101
|
+
onDone(job, undefined, error instanceof Error ? error.message : String(error));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
let next = 0;
|
|
107
|
+
const pool = Array.from({ length: Math.min(workers, jobs.length) }, () => new Worker(workerUrl()));
|
|
108
|
+
try {
|
|
109
|
+
await Promise.all(
|
|
110
|
+
pool.map(
|
|
111
|
+
(worker) =>
|
|
112
|
+
new Promise<void>((resolve, reject) => {
|
|
113
|
+
const pump = () => {
|
|
114
|
+
if (signal?.aborted || next >= jobs.length) return resolve();
|
|
115
|
+
const id = next++;
|
|
116
|
+
worker.once("message", (msg: { id: number; result?: FileResult; error?: string }) => {
|
|
117
|
+
onDone(jobs[id], msg.result, msg.error);
|
|
118
|
+
pump();
|
|
119
|
+
});
|
|
120
|
+
worker.postMessage({ id, ...jobs[id], home });
|
|
121
|
+
};
|
|
122
|
+
worker.once("error", reject);
|
|
123
|
+
pump();
|
|
124
|
+
}),
|
|
125
|
+
),
|
|
126
|
+
);
|
|
127
|
+
} finally {
|
|
128
|
+
await Promise.all(pool.map((w) => w.terminate()));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function extract(options: {
|
|
133
|
+
roots: string[];
|
|
134
|
+
layout: Layout;
|
|
135
|
+
home: string;
|
|
136
|
+
workers?: number;
|
|
137
|
+
onProgress?: Progress;
|
|
138
|
+
signal?: AbortSignal;
|
|
139
|
+
now?: () => Date;
|
|
140
|
+
}): Promise<{ stats: ExtractStats; checkpoint: Checkpoint }> {
|
|
141
|
+
const started = Date.now();
|
|
142
|
+
const checkpoint = loadCheckpoint(options.layout.checkpoint);
|
|
143
|
+
const files = listSessionFiles(options.roots);
|
|
144
|
+
const rereadAll = checkpoint.extractor !== EXTRACTOR_VERSION;
|
|
145
|
+
checkpoint.extractor = EXTRACTOR_VERSION;
|
|
146
|
+
const changed = files.filter((f) => {
|
|
147
|
+
const known = checkpoint.files[f.path];
|
|
148
|
+
if (rereadAll) return true;
|
|
149
|
+
return !known || known.size !== f.size || known.mtimeMs !== f.mtimeMs;
|
|
150
|
+
});
|
|
151
|
+
const stats: ExtractStats = { files: files.length, changed: changed.length, failed: 0, bytes: 0, records: 0, ms: 0, errors: [] };
|
|
152
|
+
const byPath = new Map(changed.map((f) => [f.path, f]));
|
|
153
|
+
const jobs = changed
|
|
154
|
+
.sort((a, b) => a.size - b.size)
|
|
155
|
+
.map((f) => {
|
|
156
|
+
const key = fileKey(f.path);
|
|
157
|
+
const month = monthOf(f.path);
|
|
158
|
+
return { path: f.path, out: join(options.layout.records, month, `${key}.jsonl`) };
|
|
159
|
+
});
|
|
160
|
+
let done = 0;
|
|
161
|
+
let sinceSave = 0;
|
|
162
|
+
const workers = options.workers ?? Math.max(1, Math.min(8, availableParallelism() - 1));
|
|
163
|
+
options.onProgress?.(0, jobs.length, 0);
|
|
164
|
+
await runPool(
|
|
165
|
+
jobs,
|
|
166
|
+
options.home,
|
|
167
|
+
jobs.length < 4 ? 0 : workers,
|
|
168
|
+
(job, result, error) => {
|
|
169
|
+
const file = byPath.get(job.path);
|
|
170
|
+
done += 1;
|
|
171
|
+
if (file) stats.bytes += file.size;
|
|
172
|
+
if (!result || !file) {
|
|
173
|
+
stats.failed += 1;
|
|
174
|
+
if (stats.errors.length < 20) stats.errors.push(`${job.path}: ${error ?? "no result"}`);
|
|
175
|
+
} else {
|
|
176
|
+
stats.records += result.records;
|
|
177
|
+
const key = fileKey(file.path);
|
|
178
|
+
checkpoint.files[file.path] = { size: file.size, mtimeMs: file.mtimeMs, key, month: monthOf(file.path), summary: result.summary };
|
|
179
|
+
if (result.catalog?.length) {
|
|
180
|
+
const hash = createHash("sha1").update(result.catalog.join("\n")).digest("hex").slice(0, 16);
|
|
181
|
+
result.summary.catalog = hash;
|
|
182
|
+
const seen = checkpoint.catalogs[hash];
|
|
183
|
+
if (!seen || seen.last < result.summary.start) checkpoint.catalogs[hash] = { names: result.catalog, last: result.summary.start };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (++sinceSave >= 1000) {
|
|
187
|
+
sinceSave = 0;
|
|
188
|
+
saveCheckpoint(options.layout.checkpoint, checkpoint);
|
|
189
|
+
}
|
|
190
|
+
options.onProgress?.(done, jobs.length, stats.bytes);
|
|
191
|
+
},
|
|
192
|
+
options.signal,
|
|
193
|
+
);
|
|
194
|
+
checkpoint.lastExtract = (options.now?.() ?? new Date()).toISOString();
|
|
195
|
+
saveCheckpoint(options.layout.checkpoint, checkpoint);
|
|
196
|
+
stats.ms = Date.now() - started;
|
|
197
|
+
return { stats, checkpoint };
|
|
198
|
+
}
|