pi-evals 0.0.0-stage → 0.2.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 +21 -0
- package/LICENSE +21 -0
- package/README.md +116 -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 +165 -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 +31 -0
- package/dist/report/concepts.js +37 -0
- package/dist/report/findings.js +73 -0
- package/dist/report/format.js +16 -0
- package/dist/report/sections.js +61 -0
- package/dist/report/style.js +77 -0
- package/dist/report/timeline.js +91 -0
- package/dist/report/week.js +36 -0
- package/dist/schema.js +65 -0
- package/dist/skills.js +41 -0
- package/dist/store.js +51 -0
- package/docs/design.md +106 -0
- package/docs/learn.zh-TW.md +33 -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 +160 -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 +63 -0
- package/src/report/concepts.ts +94 -0
- package/src/report/findings.ts +84 -0
- package/src/report/format.ts +24 -0
- package/src/report/sections.ts +188 -0
- package/src/report/style.ts +77 -0
- package/src/report/timeline.ts +143 -0
- package/src/report/week.ts +55 -0
- package/src/schema.ts +84 -0
- package/src/skills.ts +46 -0
- package/src/store.ts +49 -0
package/src/build.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the index from back-fill summaries and live records: per-day, per-project aggregates (days.json),
|
|
3
|
+
* per-session detector results for the labels join (session-evals.json), the change timeline, and a status file.
|
|
4
|
+
* Live records fill what session files lack; for a session both sources saw, back-fill counts win and live adds
|
|
5
|
+
* monitor lifecycles and ask-user answer sources.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { addLabel, bucketOf, bump, type DayAgg, emptyDay, mergeDay, rowOf, type SessionRow, type SessionSummary } from "./aggregate.ts";
|
|
10
|
+
import { buildChanges, type Change, versionAt, writeChanges } from "./changes.ts";
|
|
11
|
+
import type { Checkpoint } from "./extract/run.ts";
|
|
12
|
+
import { dayOf, type Layout, type Settings } from "./paths.ts";
|
|
13
|
+
import { type EvalRecord, NAMES } from "./schema.ts";
|
|
14
|
+
import { liveFiles, readRecords } from "./store.ts";
|
|
15
|
+
|
|
16
|
+
export interface DaysIndex {
|
|
17
|
+
v: 1;
|
|
18
|
+
built: string;
|
|
19
|
+
lastExtract?: string;
|
|
20
|
+
/** day → project → aggregates */
|
|
21
|
+
days: Record<string, Record<string, DayAgg>>;
|
|
22
|
+
/** tool → owner package (newest live snapshot), with version when known. */
|
|
23
|
+
owners: Record<string, { owner: string; version?: string }>;
|
|
24
|
+
/** Skills pi offered in the newest sessions (union of catalogs seen in the last 7 days of data, and live snapshots). */
|
|
25
|
+
offeredSkills: string[];
|
|
26
|
+
sessions: { backfill: number; live: number; both: number; subagent: number; linked: number };
|
|
27
|
+
/** First and last session start in the index, and the last extract: the range the data covers. */
|
|
28
|
+
range: { start: string; end: string };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const ANCHORLOOP_PACKAGES = ["pi-anchorloop", "pi-aaaav", "aaaav"];
|
|
32
|
+
|
|
33
|
+
function atomicWrite(file: string, text: string) {
|
|
34
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
35
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
36
|
+
writeFileSync(tmp, text);
|
|
37
|
+
renameSync(tmp, file);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Live records grouped by session id. */
|
|
41
|
+
function liveSessions(layout: Layout): { bySession: Map<string, EvalRecord[]>; snapshots: EvalRecord[] } {
|
|
42
|
+
const bySession = new Map<string, EvalRecord[]>();
|
|
43
|
+
const snapshots: EvalRecord[] = [];
|
|
44
|
+
for (const file of liveFiles(layout.events)) {
|
|
45
|
+
for (const rec of readRecords(file)) {
|
|
46
|
+
const id = String(rec.attrs?.["session.id"] ?? "");
|
|
47
|
+
if (!id) continue;
|
|
48
|
+
if (rec.name === NAMES.tools) snapshots.push(rec);
|
|
49
|
+
const list = bySession.get(id);
|
|
50
|
+
if (list) list.push(rec);
|
|
51
|
+
else bySession.set(id, [rec]);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return { bySession, snapshots };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const dayAgg = (days: Record<string, DayAgg>, ts: string) => (days[dayOf(ts)] ??= emptyDay());
|
|
58
|
+
|
|
59
|
+
/** Aggregates from live records alone, for a session no session file covers (e.g. `--no-session`). */
|
|
60
|
+
export function liveSummary(records: EvalRecord[]): { project: string; start: string; days: Record<string, DayAgg> } {
|
|
61
|
+
const days: Record<string, DayAgg> = {};
|
|
62
|
+
const start = records.reduce((min, r) => (r.ts < min ? r.ts : min), records[0]?.ts ?? new Date(0).toISOString());
|
|
63
|
+
const project = String(records[0]?.attrs["pi.project"] ?? "unknown");
|
|
64
|
+
const loaded = new Set<string>();
|
|
65
|
+
for (const r of records) {
|
|
66
|
+
const a = r.attrs;
|
|
67
|
+
if (r.name === NAMES.tool) {
|
|
68
|
+
const day = dayAgg(days, r.end_ts ?? r.ts);
|
|
69
|
+
const name = String(a["gen_ai.tool.name"]);
|
|
70
|
+
const t = (day.tools[name] ??= { calls: 0, errors: 0, durSum: 0, durN: 0 });
|
|
71
|
+
t.calls += 1;
|
|
72
|
+
if (a["error.type"]) t.errors += 1;
|
|
73
|
+
if (typeof r.duration_ms === "number") {
|
|
74
|
+
t.durSum += r.duration_ms;
|
|
75
|
+
t.durN += 1;
|
|
76
|
+
}
|
|
77
|
+
if (a["pi.ask_user.source"] !== undefined) addAsk(day, r);
|
|
78
|
+
if (name === "subagent" && a["gen_ai.agent.name"]) bump(day.subagents, `${a["gen_ai.agent.name"]}|${a["gen_ai.request.model"]}`);
|
|
79
|
+
} else if (r.name === NAMES.skill) {
|
|
80
|
+
const day = dayAgg(days, r.ts);
|
|
81
|
+
const skill = String(a["gen_ai.skill.name"]);
|
|
82
|
+
bump(day.skills, skill);
|
|
83
|
+
bump(day.skillTriggers, String(a["pi.skill.trigger"]));
|
|
84
|
+
loaded.add(skill);
|
|
85
|
+
} else if (r.name === NAMES.prompt) dayAgg(days, r.ts).prompts += 1;
|
|
86
|
+
else if (r.name === NAMES.monitor) addMonitor(dayAgg(days, r.end_ts ?? r.ts), r);
|
|
87
|
+
}
|
|
88
|
+
const first = dayAgg(days, start);
|
|
89
|
+
first.sessions += 1;
|
|
90
|
+
if (records.some((r) => r.name === NAMES.session && r.attrs["pi.session.kind"] === "subagent")) first.subagentSessions += 1;
|
|
91
|
+
for (const skill of loaded) bump(first.skillSessions, skill);
|
|
92
|
+
return { project, start, days };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function addAsk(day: DayAgg, r: EvalRecord) {
|
|
96
|
+
const a = r.attrs;
|
|
97
|
+
day.ask.calls += 1;
|
|
98
|
+
if (a["pi.ask_user.cancelled"] === true) day.ask.cancelled += 1;
|
|
99
|
+
if (a["error.type"]) day.ask.errors += 1;
|
|
100
|
+
bump(day.ask.sources, String(a["pi.ask_user.source"]));
|
|
101
|
+
if (typeof r.duration_ms === "number" && !a["error.type"]) {
|
|
102
|
+
day.ask.durSum += r.duration_ms;
|
|
103
|
+
day.ask.durN += 1;
|
|
104
|
+
day.ask.buckets[bucketOf(r.duration_ms)] += 1;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function addMonitor(day: DayAgg, r: EvalRecord) {
|
|
109
|
+
day.monitors.finished += 1;
|
|
110
|
+
bump(day.monitors.statuses, String(r.attrs["pi.monitor.status"] ?? "unknown"));
|
|
111
|
+
if (typeof r.duration_ms === "number") {
|
|
112
|
+
day.monitors.durSum += r.duration_ms;
|
|
113
|
+
day.monitors.durN += 1;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Back-fill days of one session with live-only facts laid over: monitor lifecycles and ask-user answer sources. */
|
|
118
|
+
export function overlayLive(days: Record<string, DayAgg>, records: EvalRecord[]): Record<string, DayAgg> {
|
|
119
|
+
const out: Record<string, DayAgg> = structuredClone(days);
|
|
120
|
+
const monitors = records.filter((r) => r.name === NAMES.monitor);
|
|
121
|
+
if (monitors.length) {
|
|
122
|
+
for (const day of Object.values(out)) day.monitors = { started: day.monitors.started, finished: 0, statuses: {}, durSum: 0, durN: 0 };
|
|
123
|
+
for (const r of monitors) addMonitor(dayAgg(out, r.end_ts ?? r.ts), r);
|
|
124
|
+
}
|
|
125
|
+
for (const r of records) {
|
|
126
|
+
const source = r.attrs["pi.ask_user.source"];
|
|
127
|
+
if (r.name !== NAMES.tool || typeof source !== "string") continue;
|
|
128
|
+
const day = dayAgg(out, r.end_ts ?? r.ts);
|
|
129
|
+
if ((day.ask.sources.unknown ?? 0) > 0) {
|
|
130
|
+
day.ask.sources.unknown -= 1;
|
|
131
|
+
bump(day.ask.sources, source);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** child logical id → parent session id and the role and model it was launched with. */
|
|
138
|
+
export function subagentLinks(summaries: SessionSummary[], ledgerDir: string): Map<string, { parent: string; role: string; model: string }> {
|
|
139
|
+
const links = new Map<string, { parent: string; role: string; model: string }>();
|
|
140
|
+
if (existsSync(ledgerDir)) {
|
|
141
|
+
for (const name of readdirSync(ledgerDir).filter((n) => n.endsWith(".json"))) {
|
|
142
|
+
try {
|
|
143
|
+
const rows = JSON.parse(readFileSync(join(ledgerDir, name), "utf8")) as { id?: string; agent?: string; model?: string }[];
|
|
144
|
+
if (!Array.isArray(rows)) continue;
|
|
145
|
+
for (const row of rows) if (row?.id) links.set(row.id, { parent: name.slice(0, -5), role: row.agent ?? "unknown", model: row.model ?? "unknown" });
|
|
146
|
+
} catch {}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
for (const s of summaries) for (const child of s.spawned) links.set(child.id, { parent: s.sessionId, role: child.role, model: child.model });
|
|
150
|
+
return links;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function buildIndex(options: { layout: Layout; settings: Settings; checkpoint: Checkpoint; agentDir: string; now?: () => Date }): {
|
|
154
|
+
index: DaysIndex;
|
|
155
|
+
changes: Change[];
|
|
156
|
+
errors: string[];
|
|
157
|
+
} {
|
|
158
|
+
const { layout, checkpoint } = options;
|
|
159
|
+
const { bySession, snapshots } = liveSessions(layout);
|
|
160
|
+
const errors: string[] = [];
|
|
161
|
+
const changes = buildChanges(options.settings.changeRepos, snapshots, layout.marks, errors);
|
|
162
|
+
writeChanges(layout.changes, changes);
|
|
163
|
+
|
|
164
|
+
const summaries = Object.values(checkpoint.files).map((f) => f.summary);
|
|
165
|
+
const links = subagentLinks(summaries, join(options.agentDir, "dispatch-ledger"));
|
|
166
|
+
const cube: DaysIndex["days"] = {};
|
|
167
|
+
const add = (project: string, days: Record<string, DayAgg>) => {
|
|
168
|
+
for (const [day, agg] of Object.entries(days)) {
|
|
169
|
+
const byProject = (cube[day] ??= {});
|
|
170
|
+
byProject[project] = mergeDay(byProject[project] ?? emptyDay(), agg);
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
const versionFor = (start: string) => versionAt(changes, ANCHORLOOP_PACKAGES, start) ?? "unknown";
|
|
174
|
+
const rows: SessionRow[] = [];
|
|
175
|
+
const sessionEvals: Record<string, Record<string, string>> = {};
|
|
176
|
+
const seen = new Set<string>();
|
|
177
|
+
let both = 0;
|
|
178
|
+
let linked = 0;
|
|
179
|
+
let subagent = 0;
|
|
180
|
+
for (const s of summaries) {
|
|
181
|
+
if (!s.sessionId || seen.has(s.sessionId)) continue;
|
|
182
|
+
seen.add(s.sessionId);
|
|
183
|
+
const live = bySession.get(s.sessionId);
|
|
184
|
+
const days = live ? overlayLive(s.days, live) : structuredClone(s.days);
|
|
185
|
+
if (live) both += 1;
|
|
186
|
+
const startDay = dayOf(s.start || 0);
|
|
187
|
+
const first = (days[startDay] ??= emptyDay());
|
|
188
|
+
if (s.kind === "subagent") {
|
|
189
|
+
subagent += 1;
|
|
190
|
+
const link = s.logicalId ? links.get(s.logicalId) : undefined;
|
|
191
|
+
if (link || s.parentId) linked += 1;
|
|
192
|
+
bump(first.subagentCost, link?.role ?? (s.parentId ? "role-unknown" : "unlinked"), s.cost);
|
|
193
|
+
}
|
|
194
|
+
const version = versionFor(s.start);
|
|
195
|
+
const labels: Record<string, string> = {};
|
|
196
|
+
for (const [name, result] of Object.entries(s.evals)) {
|
|
197
|
+
if (!result || result.explanation === "out_of_scope_pre_3.0") continue;
|
|
198
|
+
addLabel(first.detectorVersions, `${name}|${version}`, result.label);
|
|
199
|
+
labels[name] = result.label;
|
|
200
|
+
}
|
|
201
|
+
if (Object.keys(labels).length) sessionEvals[s.sessionId] = labels;
|
|
202
|
+
add(s.project, days);
|
|
203
|
+
rows.push(rowOf(s.start, s.project, s.kind === "subagent", s.cost, days, s.evals));
|
|
204
|
+
}
|
|
205
|
+
let liveOnly = 0;
|
|
206
|
+
for (const [id, records] of bySession) {
|
|
207
|
+
if (seen.has(id)) continue;
|
|
208
|
+
liveOnly += 1;
|
|
209
|
+
const summary = liveSummary(records);
|
|
210
|
+
add(summary.project, summary.days);
|
|
211
|
+
rows.push(rowOf(summary.start, summary.project, records.some((r) => r.name === NAMES.session && r.attrs["pi.session.kind"] === "subagent"), 0, summary.days));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const owners: DaysIndex["owners"] = {};
|
|
215
|
+
for (const rec of [...snapshots].sort((a, b) => a.ts.localeCompare(b.ts))) {
|
|
216
|
+
const tools = rec.attrs["pi.tools"];
|
|
217
|
+
if (!Array.isArray(tools)) continue;
|
|
218
|
+
for (const entry of tools) {
|
|
219
|
+
const eq = entry.indexOf("=");
|
|
220
|
+
const owner = entry.slice(eq + 1);
|
|
221
|
+
const at = owner.lastIndexOf("@");
|
|
222
|
+
owners[entry.slice(0, eq)] = at > 0 ? { owner: owner.slice(0, at), version: owner.slice(at + 1) } : { owner };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const allDays = Object.keys(cube).sort();
|
|
227
|
+
const lastDay = allDays.at(-1) ?? "";
|
|
228
|
+
rows.sort((a, b) => a.s.localeCompare(b.s));
|
|
229
|
+
const cutoff = lastDay ? dayOf(Date.parse(lastDay) - 7 * 86_400_000) : "";
|
|
230
|
+
const offered = new Set<string>();
|
|
231
|
+
for (const cat of Object.values(checkpoint.catalogs)) if (cat.last.slice(0, 10) >= cutoff) for (const n of cat.names) offered.add(n);
|
|
232
|
+
for (const rec of bySession.values()) for (const r of rec) if (r.name === NAMES.skills && Array.isArray(r.attrs["pi.skills"])) for (const n of r.attrs["pi.skills"]) offered.add(n);
|
|
233
|
+
|
|
234
|
+
const index: DaysIndex = {
|
|
235
|
+
v: 1,
|
|
236
|
+
built: (options.now?.() ?? new Date()).toISOString(),
|
|
237
|
+
lastExtract: checkpoint.lastExtract,
|
|
238
|
+
days: cube,
|
|
239
|
+
owners,
|
|
240
|
+
offeredSkills: [...offered].sort(),
|
|
241
|
+
sessions: { backfill: seen.size, live: liveOnly, both, subagent, linked },
|
|
242
|
+
range: { start: rows[0]?.s ?? "", end: checkpoint.lastExtract ?? rows.at(-1)?.s ?? "" },
|
|
243
|
+
};
|
|
244
|
+
atomicWrite(layout.days, JSON.stringify(index));
|
|
245
|
+
atomicWrite(layout.sessionRows, JSON.stringify(rows));
|
|
246
|
+
atomicWrite(layout.sessionEvals, JSON.stringify(sessionEvals));
|
|
247
|
+
return { index, changes, errors };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function loadRows(layout: Layout): SessionRow[] {
|
|
251
|
+
return existsSync(layout.sessionRows) ? (JSON.parse(readFileSync(layout.sessionRows, "utf8")) as SessionRow[]) : [];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function loadIndex(layout: Layout): DaysIndex | undefined {
|
|
255
|
+
if (!existsSync(layout.days)) return undefined;
|
|
256
|
+
return JSON.parse(readFileSync(layout.days, "utf8")) as DaysIndex;
|
|
257
|
+
}
|
package/src/changes.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The change timeline: architecture changes the boss makes, from git history (read-only `git log`), version
|
|
3
|
+
* changes seen in live tool-owner snapshots, and manual marks (`/evals mark`).
|
|
4
|
+
*/
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { basename, dirname } from "node:path";
|
|
8
|
+
import type { EvalRecord } from "./schema.ts";
|
|
9
|
+
|
|
10
|
+
export type ChangeKind = "pin" | "model-routing" | "rule" | "skill" | "agent-role" | "manual";
|
|
11
|
+
|
|
12
|
+
export interface Change {
|
|
13
|
+
at: string;
|
|
14
|
+
kind: ChangeKind;
|
|
15
|
+
subject: string;
|
|
16
|
+
package?: string;
|
|
17
|
+
from?: string;
|
|
18
|
+
to?: string;
|
|
19
|
+
sha?: string;
|
|
20
|
+
repo?: string;
|
|
21
|
+
source: "git" | "live" | "mark";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const PIN_FILE = "scripts/pi_root/pins.py";
|
|
25
|
+
|
|
26
|
+
/** Which kind of architecture change a repository path is, if any. */
|
|
27
|
+
export function classifyPath(path: string): Exclude<ChangeKind, "pin" | "manual"> | "pin" | undefined {
|
|
28
|
+
if (path === PIN_FILE) return "pin";
|
|
29
|
+
if (/(^|\/)herdr-agents-models[^/]*\.json$/.test(path) || /^pi\/models\.json$/.test(path)) return "model-routing";
|
|
30
|
+
if (/^rules\//.test(path) || /^pi\/AGENTS[^/]*\.md(\.in)?$/.test(path)) return "rule";
|
|
31
|
+
if (/^agents\//.test(path)) return "agent-role";
|
|
32
|
+
if (/^skills\//.test(path) || path === "overlay.json") return "skill";
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const SPEC = /npm:((?:@[\w.-]+\/)?[\w.-]+)@([\w.+-]+)|git:github\.com\/[\w.-]+\/([\w.-]+)@([0-9a-f]{7,40})/g;
|
|
37
|
+
|
|
38
|
+
/** Package versions named on one side of a diff. */
|
|
39
|
+
function specs(lines: string[]): Map<string, string> {
|
|
40
|
+
const out = new Map<string, string>();
|
|
41
|
+
for (const line of lines) {
|
|
42
|
+
for (const m of line.matchAll(SPEC)) {
|
|
43
|
+
if (m[1]) out.set(m[1], m[2]);
|
|
44
|
+
else if (m[3]) out.set(m[3], m[4].slice(0, 7));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Pin changes in one commit's `-U0` diff of pins.py. */
|
|
51
|
+
export function pinChanges(diff: string): { package: string; from?: string; to?: string }[] {
|
|
52
|
+
const removed = specs(diff.split("\n").filter((l) => l.startsWith("-") && !l.startsWith("---")));
|
|
53
|
+
const added = specs(diff.split("\n").filter((l) => l.startsWith("+") && !l.startsWith("+++")));
|
|
54
|
+
const out: { package: string; from?: string; to?: string }[] = [];
|
|
55
|
+
for (const [name, to] of added) if (removed.get(name) !== to) out.push({ package: name, from: removed.get(name), to });
|
|
56
|
+
for (const [name, from] of removed) if (!added.has(name)) out.push({ package: name, from });
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function git(repo: string, args: string[]): string {
|
|
61
|
+
const res = spawnSync("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 256 << 20 });
|
|
62
|
+
if (res.status !== 0) throw new Error(`git ${args[0]} in ${repo} failed: ${res.stderr.trim()}`);
|
|
63
|
+
return res.stdout;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Changes from one repository's history. A missing repository yields none. */
|
|
67
|
+
export function gitChanges(repo: string): Change[] {
|
|
68
|
+
if (!existsSync(repo)) return [];
|
|
69
|
+
const name = basename(repo);
|
|
70
|
+
const out: Change[] = [];
|
|
71
|
+
const log = git(repo, ["log", "--format=%x1e%H%x1f%cI%x1f%s", "--name-only", "--no-merges"]);
|
|
72
|
+
for (const block of log.split("\x1e").slice(1)) {
|
|
73
|
+
const [head, ...files] = block.split("\n");
|
|
74
|
+
const [sha, at, subject] = head.split("\x1f");
|
|
75
|
+
const kinds = new Set(files.map((f) => f.trim()).filter(Boolean).map(classifyPath).filter((k) => k && k !== "pin"));
|
|
76
|
+
for (const kind of kinds) out.push({ at: new Date(at).toISOString(), kind: kind as ChangeKind, subject, sha: sha.slice(0, 12), repo: name, source: "git" });
|
|
77
|
+
}
|
|
78
|
+
if (existsSync(`${repo}/${PIN_FILE}`) || git(repo, ["log", "-1", "--format=%H", "--", PIN_FILE]).trim()) {
|
|
79
|
+
const pins = git(repo, ["log", "-p", "-U0", "--no-merges", "--format=%x1e%H%x1f%cI%x1f%s", "--", PIN_FILE]);
|
|
80
|
+
for (const block of pins.split("\x1e").slice(1)) {
|
|
81
|
+
const nl = block.indexOf("\n");
|
|
82
|
+
const [sha, at, subject] = block.slice(0, nl).split("\x1f");
|
|
83
|
+
for (const change of pinChanges(block.slice(nl + 1))) {
|
|
84
|
+
out.push({ at: new Date(at).toISOString(), kind: "pin", subject, ...change, sha: sha.slice(0, 12), repo: name, source: "git" });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Version changes between consecutive live tool-owner snapshots, per package. */
|
|
92
|
+
export function liveChanges(snapshots: EvalRecord[]): Change[] {
|
|
93
|
+
const last = new Map<string, string>();
|
|
94
|
+
const out: Change[] = [];
|
|
95
|
+
for (const rec of [...snapshots].sort((a, b) => a.ts.localeCompare(b.ts))) {
|
|
96
|
+
const tools = rec.attrs["pi.tools"];
|
|
97
|
+
if (!Array.isArray(tools)) continue;
|
|
98
|
+
const versions = new Map<string, string>();
|
|
99
|
+
for (const entry of tools) {
|
|
100
|
+
const owner = entry.slice(entry.indexOf("=") + 1);
|
|
101
|
+
const at = owner.lastIndexOf("@");
|
|
102
|
+
if (at > 0) versions.set(owner.slice(0, at), owner.slice(at + 1));
|
|
103
|
+
}
|
|
104
|
+
for (const [pkg, version] of versions) {
|
|
105
|
+
const before = last.get(pkg);
|
|
106
|
+
if (before && before !== version) out.push({ at: rec.ts, kind: "pin", subject: `${pkg} ${before} → ${version} (seen live)`, package: pkg, from: before, to: version, source: "live" });
|
|
107
|
+
last.set(pkg, version);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function readMarks(file: string): Change[] {
|
|
114
|
+
if (!existsSync(file)) return [];
|
|
115
|
+
return readFileSync(file, "utf8")
|
|
116
|
+
.split("\n")
|
|
117
|
+
.filter(Boolean)
|
|
118
|
+
.flatMap((line) => {
|
|
119
|
+
try {
|
|
120
|
+
const m = JSON.parse(line) as { at: string; text: string };
|
|
121
|
+
return [{ at: m.at, kind: "manual" as const, subject: m.text, source: "mark" as const }];
|
|
122
|
+
} catch {
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function addMark(file: string, text: string, at = new Date()): Change {
|
|
129
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
130
|
+
appendFileSync(file, `${JSON.stringify({ at: at.toISOString(), text })}\n`);
|
|
131
|
+
return { at: at.toISOString(), kind: "manual", subject: text, source: "mark" };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* All changes, oldest first; a live version change already pinned in git within three days before is dropped.
|
|
136
|
+
* A repository whose history cannot be read is reported through `errors` and skipped.
|
|
137
|
+
*/
|
|
138
|
+
export function buildChanges(repos: string[], snapshots: EvalRecord[], marksFile: string, errors: string[] = []): Change[] {
|
|
139
|
+
const fromGit = repos.flatMap((repo) => {
|
|
140
|
+
try {
|
|
141
|
+
return gitChanges(repo);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
errors.push(error instanceof Error ? error.message : String(error));
|
|
144
|
+
return [];
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
const live = liveChanges(snapshots).filter(
|
|
148
|
+
(c) => !fromGit.some((g) => g.kind === "pin" && g.package === c.package && g.to === c.to && Date.parse(c.at) - Date.parse(g.at) < 3 * 86_400_000 && Date.parse(c.at) >= Date.parse(g.at)),
|
|
149
|
+
);
|
|
150
|
+
return [...fromGit, ...live, ...readMarks(marksFile)].sort((a, b) => a.at.localeCompare(b.at));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function writeChanges(file: string, changes: Change[]): void {
|
|
154
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
155
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
156
|
+
writeFileSync(tmp, changes.map((c) => `${JSON.stringify(c)}\n`).join(""));
|
|
157
|
+
renameSync(tmp, file);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function readChanges(file: string): Change[] {
|
|
161
|
+
if (!existsSync(file)) return [];
|
|
162
|
+
return readFileSync(file, "utf8")
|
|
163
|
+
.split("\n")
|
|
164
|
+
.filter(Boolean)
|
|
165
|
+
.map((line) => JSON.parse(line) as Change);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The version of a package in effect at an ISO time: the newest pin change at or before it (changes oldest first). */
|
|
169
|
+
export function versionAt(changes: Change[], pkg: string | string[], at: string): string | undefined {
|
|
170
|
+
const names = Array.isArray(pkg) ? pkg : [pkg];
|
|
171
|
+
let version: string | undefined;
|
|
172
|
+
for (const c of changes) {
|
|
173
|
+
if (c.kind !== "pin" || !c.package || !names.includes(c.package)) continue;
|
|
174
|
+
if (c.at > at) break;
|
|
175
|
+
version = c.to ?? version;
|
|
176
|
+
}
|
|
177
|
+
return version;
|
|
178
|
+
}
|
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
|
+
}
|