pi-evals 0.1.0 → 0.3.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 +13 -0
- package/README.md +29 -9
- package/dist/build.js +4 -3
- package/dist/cli.js +2 -2
- package/dist/coverage.js +8 -1
- package/dist/findings.js +50 -0
- package/dist/index.js +22 -10
- package/dist/model.js +21 -10
- package/dist/ops.js +52 -22
- package/dist/query.js +32 -13
- package/dist/ranges.js +14 -0
- package/dist/render.js +38 -170
- package/dist/report/concepts.js +37 -0
- package/dist/report/findings.js +84 -0
- package/dist/report/format.js +16 -0
- package/dist/report/sections.js +61 -0
- package/dist/report/strip.js +42 -0
- package/dist/report/style.js +85 -0
- package/dist/report/timeline.js +82 -0
- package/dist/report/week.js +44 -0
- package/dist/trends.js +58 -0
- package/docs/design.md +26 -0
- package/docs/learn.zh-TW.md +33 -0
- package/package.json +6 -3
- package/scripts/change-impact.mjs +18 -0
- package/scripts/package-errors.mjs +10 -0
- package/scripts/query-lib.mjs +36 -0
- package/scripts/skill-days.mjs +9 -0
- package/skills/analyzing-evals/SKILL.md +21 -0
- package/src/aggregate.ts +3 -0
- package/src/build.ts +4 -3
- package/src/cli.ts +2 -2
- package/src/coverage.ts +8 -1
- package/src/findings.ts +49 -0
- package/src/index.ts +22 -12
- package/src/model.ts +22 -10
- package/src/ops.ts +49 -22
- package/src/query.ts +29 -13
- package/src/ranges.ts +15 -0
- package/src/render.ts +70 -187
- package/src/report/concepts.ts +94 -0
- package/src/report/findings.ts +102 -0
- package/src/report/format.ts +24 -0
- package/src/report/sections.ts +186 -0
- package/src/report/strip.ts +40 -0
- package/src/report/style.ts +85 -0
- package/src/report/timeline.ts +127 -0
- package/src/report/week.ts +59 -0
- package/src/trends.ts +61 -0
package/src/index.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { existsSync } from "node:fs";
|
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
8
8
|
import { Type } from "typebox";
|
|
9
|
+
import { scriptsDir } from "./findings.ts";
|
|
9
10
|
import { observe } from "./observer.ts";
|
|
10
11
|
import { context, mark, reportPath, runReport, statusText } from "./ops.ts";
|
|
11
12
|
import { query, type View, VIEWS } from "./query.ts";
|
|
@@ -22,12 +23,13 @@ export function cliPath(): { cmd: string; args: string[] } | undefined {
|
|
|
22
23
|
return found ? { cmd: process.execPath, args: [found] } : undefined;
|
|
23
24
|
}
|
|
24
25
|
|
|
25
|
-
const SUBCOMMANDS = ["status", "extract", "report", "mark"];
|
|
26
|
+
const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark"];
|
|
26
27
|
|
|
27
|
-
function parseFlags(args: string[])
|
|
28
|
-
const out: { since?: string; project?: string; rest: string[] } = { rest: [] };
|
|
28
|
+
function parseFlags(args: string[]) {
|
|
29
|
+
const out: { since?: string; days?: number; project?: string; rest: string[] } = { rest: [] };
|
|
29
30
|
for (let i = 0; i < args.length; i++) {
|
|
30
31
|
if (args[i] === "--since") out.since = args[++i];
|
|
32
|
+
else if (args[i] === "--days") out.days = Number(args[++i]);
|
|
31
33
|
else if (args[i] === "--project") out.project = args[++i];
|
|
32
34
|
else out.rest.push(args[i]);
|
|
33
35
|
}
|
|
@@ -50,14 +52,14 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
|
|
|
50
52
|
});
|
|
51
53
|
let running: Promise<void> | undefined;
|
|
52
54
|
|
|
53
|
-
const extractInChild = (ctx: ExtensionCommandContext): Promise<void> => {
|
|
55
|
+
const extractInChild = (ctx: ExtensionCommandContext, workers: number): Promise<void> => {
|
|
54
56
|
const cli = cliPath();
|
|
55
57
|
if (!cli) {
|
|
56
58
|
ctx.ui.notify("pi-evals: cannot find its CLI (dist/cli.js); run npm run build in the package.", "error");
|
|
57
59
|
return Promise.resolve();
|
|
58
60
|
}
|
|
59
61
|
return new Promise<void>((resolve) => {
|
|
60
|
-
const child = spawnFn(cli.cmd, [...cli.args, "extract", "--json"], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
|
|
62
|
+
const child = spawnFn(cli.cmd, [...cli.args, "extract", "--json", "--workers", String(workers)], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
|
|
61
63
|
let buffer = "";
|
|
62
64
|
let last = "";
|
|
63
65
|
let errText = "";
|
|
@@ -94,7 +96,7 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
|
|
|
94
96
|
};
|
|
95
97
|
|
|
96
98
|
pi.registerCommand("evals", {
|
|
97
|
-
description: "Usage and process records: /evals [status|extract|report|mark <note>]",
|
|
99
|
+
description: "Usage and process records: /evals [status|findings|extract|report|mark <note>]",
|
|
98
100
|
getArgumentCompletions: (prefix: string) => {
|
|
99
101
|
const items = SUBCOMMANDS.filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
|
|
100
102
|
return items.length ? items : null;
|
|
@@ -104,18 +106,26 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
|
|
|
104
106
|
const sub = words[0] ?? "status";
|
|
105
107
|
if (sub === "status") {
|
|
106
108
|
ctx.ui.notify(statusText(env), "info");
|
|
109
|
+
} else if (sub === "findings") {
|
|
110
|
+
const flags = parseFlags(words.slice(1));
|
|
111
|
+
ctx.ui.notify(query("findings", { env, ...flags }), "info");
|
|
107
112
|
} else if (sub === "extract") {
|
|
108
113
|
if (running) {
|
|
109
114
|
ctx.ui.notify("pi-evals: an extract is already running.", "warning");
|
|
110
115
|
return;
|
|
111
116
|
}
|
|
117
|
+
const workers = words.length === 1 ? 2 : words.length === 3 && words[1] === "--workers" && /^\d+$/.test(words[2]) ? Number(words[2]) : NaN;
|
|
118
|
+
if (!Number.isSafeInteger(workers)) {
|
|
119
|
+
ctx.ui.notify("Usage: /evals extract [--workers <non-negative integer>]", "warning");
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
112
122
|
ctx.ui.notify("pi-evals: extract started in the background; progress shows in the footer.", "info");
|
|
113
|
-
running = extractInChild(ctx).finally(() => {
|
|
123
|
+
running = extractInChild(ctx, workers).finally(() => {
|
|
114
124
|
running = undefined;
|
|
115
125
|
});
|
|
116
126
|
} else if (sub === "report") {
|
|
117
127
|
const flags = parseFlags(words.slice(1));
|
|
118
|
-
const out = runReport({ env, filter:
|
|
128
|
+
const out = runReport({ env, filter: flags });
|
|
119
129
|
ctx.ui.notify(out ? `pi-evals report: ${out.html}\nmodel: ${out.json}` : "pi-evals: nothing extracted yet; run /evals extract first.", out ? "info" : "warning");
|
|
120
130
|
} else if (sub === "mark") {
|
|
121
131
|
const text = words.slice(1).join(" ").trim();
|
|
@@ -134,11 +144,11 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
|
|
|
134
144
|
pi.registerTool({
|
|
135
145
|
name: "evals_query",
|
|
136
146
|
label: "Evals Query",
|
|
137
|
-
description: "
|
|
138
|
-
promptSnippet: "
|
|
147
|
+
description: "Start with findings for agent activity and changes; use one detail view for counts, cost or coverage.",
|
|
148
|
+
promptSnippet: "Analyze agent activity: query findings first, then one detail view",
|
|
139
149
|
parameters: Type.Object({
|
|
140
150
|
view: Type.Unsafe<View>({ type: "string", enum: [...VIEWS], description: "Which summary" }),
|
|
141
|
-
since: Type.Optional(Type.String({ description: "YYYY-MM-DD; default
|
|
151
|
+
since: Type.Optional(Type.String({ description: "YYYY-MM-DD; default last 30 UTC dates through extraction" })),
|
|
142
152
|
project: Type.Optional(Type.String({ description: "Project key, e.g. a repo name" })),
|
|
143
153
|
}),
|
|
144
154
|
async execute(_id, params) {
|
|
@@ -146,7 +156,7 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
|
|
|
146
156
|
if (!VIEWS.includes(view)) throw new Error(`Unknown view "${view}". Views: ${VIEWS.join(", ")}.`);
|
|
147
157
|
if (params.since && !/^\d{4}-\d{2}-\d{2}$/.test(params.since)) throw new Error("since must be YYYY-MM-DD.");
|
|
148
158
|
const text = query(view, { since: params.since, project: params.project, env });
|
|
149
|
-
return { content: [{ type: "text", text }], details: { view, report: reportPath(env) } };
|
|
159
|
+
return { content: [{ type: "text", text }], details: { view, scriptsDir, report: reportPath(env) } };
|
|
150
160
|
},
|
|
151
161
|
});
|
|
152
162
|
};
|
package/src/model.ts
CHANGED
|
@@ -10,7 +10,8 @@ import type { Coverage } from "./coverage.ts";
|
|
|
10
10
|
import { DETECTORS, ERA_START } from "./detectors.ts";
|
|
11
11
|
import { CHANGE_KIND_META, DETECTOR_META, METRICS, NOTICE_META } from "./meta.ts";
|
|
12
12
|
import { staticOwner } from "./owners.ts";
|
|
13
|
-
import {
|
|
13
|
+
import { weeklyRises } from "./trends.ts";
|
|
14
|
+
import { traceId } from "./schema.ts";
|
|
14
15
|
|
|
15
16
|
export const SMALL_SAMPLE = 20;
|
|
16
17
|
/** Data older than this (hours) is reported as stale. */
|
|
@@ -174,7 +175,7 @@ interface LabelRow {
|
|
|
174
175
|
label: string;
|
|
175
176
|
}
|
|
176
177
|
|
|
177
|
-
function labelsJoin(labelsFile: string, evalsFile: string) {
|
|
178
|
+
function labelsJoin(labelsFile: string, evalsFile: string, sessionIds?: Set<string>) {
|
|
178
179
|
if (!existsSync(labelsFile)) return { present: false, n: 0, agreement: [] as { detector: string; n: number; agree: number; rate: Rate }[] };
|
|
179
180
|
const codeLabels = existsSync(evalsFile) ? (JSON.parse(readFileSync(evalsFile, "utf8")) as Record<string, Record<string, string>>) : {};
|
|
180
181
|
const rows: LabelRow[] = readFileSync(labelsFile, "utf8")
|
|
@@ -188,7 +189,10 @@ function labelsJoin(labelsFile: string, evalsFile: string) {
|
|
|
188
189
|
}
|
|
189
190
|
});
|
|
190
191
|
const by = new Map<string, { n: number; agree: number }>();
|
|
192
|
+
let n = 0;
|
|
191
193
|
for (const row of rows) {
|
|
194
|
+
if (sessionIds && !sessionIds.has(traceId(row.session_id, "labels"))) continue;
|
|
195
|
+
n++;
|
|
192
196
|
const code = codeLabels[row.session_id]?.[row.evaluation_name];
|
|
193
197
|
if (!code || code === "na") continue;
|
|
194
198
|
const t = by.get(row.evaluation_name) ?? { n: 0, agree: 0 };
|
|
@@ -196,13 +200,15 @@ function labelsJoin(labelsFile: string, evalsFile: string) {
|
|
|
196
200
|
if (code === row.label) t.agree += 1;
|
|
197
201
|
by.set(row.evaluation_name, t);
|
|
198
202
|
}
|
|
199
|
-
return { present: true, n
|
|
203
|
+
return { present: true, n, agreement: [...by].map(([detector, t]) => ({ detector, n: t.n, agree: t.agree, rate: rate(t.agree, t.n) })) };
|
|
200
204
|
}
|
|
201
205
|
|
|
202
206
|
export function buildModel(options: {
|
|
203
207
|
index: DaysIndex;
|
|
204
208
|
rows: SessionRow[];
|
|
205
209
|
changes: Change[];
|
|
210
|
+
/** Already computed for the same index, project and comparison settings. */
|
|
211
|
+
comparisons?: (Change & { impact: ReturnType<typeof impactFromRows> | null })[];
|
|
206
212
|
filter: Filter;
|
|
207
213
|
windowDays: number;
|
|
208
214
|
labelsFile: string;
|
|
@@ -233,6 +239,11 @@ export function buildModel(options: {
|
|
|
233
239
|
const byProject = [...projectSkills.values()].sort((a, b) => b.loads - a.loads);
|
|
234
240
|
const projectRows = filter.project ? options.rows.filter((r) => r.p === filter.project) : options.rows;
|
|
235
241
|
const owner = (tool: string) => ownerFor(index, tool);
|
|
242
|
+
const inRange = (at: string) => (!filter.since || at.slice(0, 10) >= filter.since) && (!filter.until || at.slice(0, 10) <= filter.until);
|
|
243
|
+
const selected = projectRows.filter(r => inRange(r.s)), children = selected.filter(r => r.k);
|
|
244
|
+
const scoped = Boolean(filter.since || filter.until || filter.project);
|
|
245
|
+
const hasSessionIds = selected.every(r => r.id !== undefined);
|
|
246
|
+
const labelIds = scoped && existsSync(options.labelsFile) ? new Set(selected.flatMap(r => r.id ? [r.id] : [])) : undefined;
|
|
236
247
|
const calls = Object.values(total.tools).reduce((s, t) => s + t.calls, 0);
|
|
237
248
|
const errors = Object.values(total.tools).reduce((s, t) => s + t.errors, 0);
|
|
238
249
|
const tokens = total.usage.input + total.usage.output + total.usage.cacheRead + total.usage.cacheWrite;
|
|
@@ -246,11 +257,12 @@ export function buildModel(options: {
|
|
|
246
257
|
versions.set(name, list);
|
|
247
258
|
}
|
|
248
259
|
const sortedChanges = [...options.changes].sort((a, b) => a.at.localeCompare(b.at));
|
|
249
|
-
const
|
|
260
|
+
const earliest = [days[0], sortedChanges.find(c => inRange(c.at))?.at.slice(0, 10)].filter(Boolean).sort()[0];
|
|
250
261
|
return {
|
|
251
262
|
v: 1 as const,
|
|
252
263
|
generated: now.toISOString(),
|
|
253
|
-
|
|
264
|
+
weekly: weeklyRises(index, filter.since ?? earliest, filter.project),
|
|
265
|
+
window: { since: filter.since ?? earliest ?? null, until: filter.until ?? days.at(-1) ?? null, days: days.length, project: filter.project ?? null },
|
|
254
266
|
freshness: { lastExtract: lastExtract ?? null, built: index.built, stale: ageHours > STALE_HOURS, ageHours: Number.isFinite(ageHours) ? round(ageHours, 1) : null },
|
|
255
267
|
meta: { metrics: METRICS, detectors: DETECTOR_META, notices: NOTICE_META, changeKinds: CHANGE_KIND_META },
|
|
256
268
|
totals: {
|
|
@@ -308,8 +320,8 @@ export function buildModel(options: {
|
|
|
308
320
|
costByRole: Object.entries(total.subagentCost)
|
|
309
321
|
.map(([role, cost]) => ({ role, cost: round(cost, 2) }))
|
|
310
322
|
.sort((a, b) => b.cost - a.cost),
|
|
311
|
-
linked: index.sessions.linked,
|
|
312
|
-
subagentTotal: index.sessions.subagent,
|
|
323
|
+
linked: scoped ? (children.every(r => r.linked !== undefined) ? children.filter(r => r.linked).length : null) : index.sessions.linked,
|
|
324
|
+
subagentTotal: scoped ? children.length : index.sessions.subagent,
|
|
313
325
|
},
|
|
314
326
|
process: {
|
|
315
327
|
eraStart: ERA_START,
|
|
@@ -335,10 +347,10 @@ export function buildModel(options: {
|
|
|
335
347
|
.slice(0, 25)
|
|
336
348
|
.map(({ name, cost, sessions }) => ({ skill: name, cost, sessions })),
|
|
337
349
|
},
|
|
338
|
-
changes: sortedChanges
|
|
339
|
-
.filter((c) => (
|
|
350
|
+
changes: options.comparisons?.filter(c => inRange(c.at)) ?? sortedChanges
|
|
351
|
+
.filter((c) => inRange(c.at))
|
|
340
352
|
.map((c) => ({ ...c, impact: index.range.start && c.at > index.range.start ? impactFromRows(projectRows, c, sortedChanges, options.windowDays, index.range, owner) : null })),
|
|
341
|
-
labels: labelsJoin(options.labelsFile, options.sessionEvalsFile),
|
|
353
|
+
labels: { ...labelsJoin(options.labelsFile, options.sessionEvalsFile, labelIds), needsIndex: !!labelIds && !hasSessionIds },
|
|
342
354
|
coverage: options.coverage ?? null,
|
|
343
355
|
};
|
|
344
356
|
}
|
package/src/ops.ts
CHANGED
|
@@ -5,7 +5,8 @@ import { buildIndex, loadIndex, loadRows } from "./build.ts";
|
|
|
5
5
|
import { addMark, readChanges } from "./changes.ts";
|
|
6
6
|
import { coverage } from "./coverage.ts";
|
|
7
7
|
import { extract, loadCheckpoint, type Progress } from "./extract/run.ts";
|
|
8
|
-
import {
|
|
8
|
+
import { PRESETS, type Preset, rangeFilter, suffix } from "./ranges.ts";
|
|
9
|
+
import { buildModel, type Filter, type ReportModel } from "./model.ts";
|
|
9
10
|
import { agentDir, home, layout, loadSettings, stateDir } from "./paths.ts";
|
|
10
11
|
import { renderHtml, type Lang } from "./render.ts";
|
|
11
12
|
|
|
@@ -52,34 +53,60 @@ export function coverageNow(env?: Env, cutDays?: number) {
|
|
|
52
53
|
return coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), cutDays ?? ctx.settings.coverageDays);
|
|
53
54
|
}
|
|
54
55
|
|
|
56
|
+
type RangeInput = Filter & { days?: number };
|
|
57
|
+
function coverageReader(ctx: ReturnType<typeof context>, now: Date) {
|
|
58
|
+
const activity = new Map<string, { files: number; indexed: number }>();
|
|
59
|
+
const cov = coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), ctx.settings.coverageDays, now.getTime(), activity);
|
|
60
|
+
return (filter: Filter) => {
|
|
61
|
+
const inRange = { files: 0, indexed: 0 };
|
|
62
|
+
for (const [day, a] of activity) if ((!filter.since || day >= filter.since) && (!filter.until || day <= filter.until)) {
|
|
63
|
+
inRange.files += a.files; inRange.indexed += a.indexed;
|
|
64
|
+
}
|
|
65
|
+
return { ...cov, inRange };
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export function coverageInRange(input: RangeInput, env?: Env) {
|
|
69
|
+
const ctx = context(env), now = new Date(), last = loadIndex(ctx.layout)?.lastExtract;
|
|
70
|
+
const filter = rangeFilter(input, last ?? now.toISOString());
|
|
71
|
+
return { filter, last, coverage: coverageReader(ctx, now)(filter) };
|
|
72
|
+
}
|
|
73
|
+
function snapshot(env?: Env, withCoverage = true) {
|
|
74
|
+
const ctx = context(env), index = loadIndex(ctx.layout);
|
|
75
|
+
if (!index) return;
|
|
76
|
+
const rows = loadRows(ctx.layout), changes = readChanges(ctx.layout.changes), now = new Date();
|
|
77
|
+
const cov = withCoverage ? coverageReader(ctx, now) : undefined;
|
|
78
|
+
return { index, build(input: RangeInput, preset: Preset, comparisons?: ReportModel["changes"]) {
|
|
79
|
+
const filter = rangeFilter(input, index.lastExtract ?? now.toISOString(), preset);
|
|
80
|
+
return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays,
|
|
81
|
+
labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter) });
|
|
82
|
+
} };
|
|
83
|
+
}
|
|
84
|
+
export function indexedModel(filter: RangeInput, env?: Env, withCoverage = true) {
|
|
85
|
+
const data = snapshot(env, withCoverage);
|
|
86
|
+
return data && { report: data.build(filter, 30), index: data.index };
|
|
87
|
+
}
|
|
88
|
+
|
|
55
89
|
export function model(filter: Filter, env?: Env, withCoverage = true) {
|
|
56
|
-
|
|
57
|
-
const index = loadIndex(ctx.layout);
|
|
58
|
-
if (!index) return undefined;
|
|
59
|
-
return buildModel({
|
|
60
|
-
index,
|
|
61
|
-
rows: loadRows(ctx.layout),
|
|
62
|
-
changes: readChanges(ctx.layout.changes),
|
|
63
|
-
filter,
|
|
64
|
-
windowDays: ctx.settings.impactWindowDays,
|
|
65
|
-
labelsFile: ctx.layout.labels,
|
|
66
|
-
sessionEvalsFile: ctx.layout.sessionEvals,
|
|
67
|
-
coverage: withCoverage ? coverageNow(env) : undefined,
|
|
68
|
-
});
|
|
90
|
+
return indexedModel(filter, env, withCoverage)?.report;
|
|
69
91
|
}
|
|
70
92
|
|
|
71
93
|
/** Builds the report; returns the HTML path, or undefined when nothing was extracted yet. */
|
|
72
|
-
export function runReport(options: { env?: Env; filter?:
|
|
94
|
+
export function runReport(options: { env?: Env; filter?: RangeInput; outDir?: string; lang?: Lang } = {}): { html: string; json: string } | undefined {
|
|
73
95
|
const ctx = context(options.env);
|
|
74
|
-
const
|
|
75
|
-
if (!
|
|
96
|
+
const data = snapshot(options.env), filter = options.filter ?? {};
|
|
97
|
+
if (!data) return;
|
|
76
98
|
const dir = resolve(options.outDir ?? ctx.layout.reports);
|
|
77
99
|
mkdirSync(dir, { recursive: true });
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
100
|
+
const write = (m: ReportModel, range: Preset | "custom") => {
|
|
101
|
+
const html = join(dir, `report${suffix(range)}.html`), json = join(dir, `model${suffix(range)}.json`);
|
|
102
|
+
writeFileSync(json, JSON.stringify(m, null, 1));
|
|
103
|
+
writeFileSync(html, renderHtml(m, options.lang ?? "zh", range));
|
|
104
|
+
return { html, json };
|
|
105
|
+
};
|
|
106
|
+
if (filter.since || filter.until || filter.days !== undefined) return write(data.build(filter, 30), "custom");
|
|
107
|
+
const all = data.build(filter, "all");
|
|
108
|
+
for (const p of PRESETS) if (p !== 30) write(p === "all" ? all : data.build(filter, p, all.changes), p);
|
|
109
|
+
return write(data.build(filter, 30, all.changes), 30);
|
|
83
110
|
}
|
|
84
111
|
|
|
85
112
|
export function reportPath(env?: Env): string {
|
package/src/query.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/** `evals_query`: bounded plain-text summaries of the index for an agent (names and numbers only, under 2 KB). */
|
|
2
|
-
import {
|
|
2
|
+
import { coverageInRange, indexedModel, reportPath } from "./ops.ts";
|
|
3
|
+
import { findings } from "./findings.ts";
|
|
4
|
+
import { select } from "./report/findings.ts";
|
|
3
5
|
import type { Rate } from "./model.ts";
|
|
4
6
|
|
|
5
|
-
export const VIEWS = ["skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"] as const;
|
|
7
|
+
export const VIEWS = ["findings", "skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"] as const;
|
|
6
8
|
export type View = (typeof VIEWS)[number];
|
|
7
9
|
export const MAX_BYTES = 1900;
|
|
8
10
|
|
|
@@ -12,25 +14,34 @@ const sec = (v: number | null) => (v === null ? "n/a" : `${(v / 1000).toFixed(1)
|
|
|
12
14
|
/** Cuts text to the byte limit at a line boundary. */
|
|
13
15
|
export function bound(text: string, limit = MAX_BYTES): string {
|
|
14
16
|
if (Buffer.byteLength(text) <= limit) return text;
|
|
15
|
-
const lines = text.split("\n");
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
const lines = text.split("\n"), tail = lines.at(-1) ?? "";
|
|
18
|
+
const suffix = tail.startsWith("report: ") && Buffer.byteLength(tail) < limit / 2 ? `\n…\n${tail}` : "\n…";
|
|
19
|
+
const kept: string[] = [];
|
|
20
|
+
for (const line of lines) {
|
|
21
|
+
if (Buffer.byteLength([...kept, line].join("\n") + suffix) > limit) break;
|
|
22
|
+
kept.push(line);
|
|
23
|
+
}
|
|
24
|
+
return kept.join("\n") + suffix;
|
|
18
25
|
}
|
|
19
26
|
|
|
20
|
-
export function query(view: View, options: { since?: string; project?: string; env?: Record<string, string | undefined> } = {}): string {
|
|
27
|
+
export function query(view: View, options: { since?: string; days?: number; project?: string; env?: Record<string, string | undefined> } = {}): string {
|
|
21
28
|
if (view === "coverage") {
|
|
22
|
-
const c =
|
|
29
|
+
const { coverage: c, filter, last } = coverageInRange(options, options.env);
|
|
23
30
|
return bound(
|
|
24
31
|
[
|
|
32
|
+
`${filter.since}..${filter.until} UTC; last extract ${last ?? "never"}; live cleanup check across all dates and projects`,
|
|
25
33
|
`coverage, sessions inactive > ${c.cutDays} days (before ${c.cutoff.slice(0, 10)}):`,
|
|
26
34
|
`indexed ${c.indexed.files}/${c.old.files} files, ${(c.indexed.bytes / 1e9).toFixed(2)} of ${(c.old.bytes / 1e9).toFixed(2)} GB; not indexed ${c.notIndexed.files}`,
|
|
35
|
+
`modified in report dates (all projects): ${c.inRange?.indexed ?? 0}/${c.inRange?.files ?? 0} files indexed`,
|
|
27
36
|
`all files: ${c.all.indexedFiles}/${c.all.files} indexed; index keeps ${c.retainedGone} sessions whose file is gone`,
|
|
28
37
|
"meaning: only indexed files keep their numbers if the session files are cleaned up",
|
|
29
38
|
].join("\n"),
|
|
30
39
|
);
|
|
31
40
|
}
|
|
32
|
-
const
|
|
33
|
-
if (!
|
|
41
|
+
const data = indexedModel(options, options.env, view === "findings");
|
|
42
|
+
if (!data) return "pi-evals: nothing extracted yet; the user can run /evals extract.";
|
|
43
|
+
const { report: m, index } = data;
|
|
44
|
+
if (view === "findings") return bound(findings(m), 1499);
|
|
34
45
|
const head = [
|
|
35
46
|
`pi-evals ${view} · ${m.window.since ?? "?"}..${m.window.until ?? "?"}${m.window.project ? ` · project ${m.window.project}` : ""} · sessions ${m.totals.sessions}`,
|
|
36
47
|
m.freshness.stale ? `STALE: last extract ${m.freshness.lastExtract ?? "never"} (${m.freshness.ageHours ?? "?"}h ago); /evals extract refreshes` : `last extract ${m.freshness.lastExtract}`,
|
|
@@ -42,6 +53,8 @@ export function query(view: View, options: { since?: string; project?: string; e
|
|
|
42
53
|
body.push(`ways: ${Object.entries(m.skills.triggers).map(([k, v]) => `${k} ${v}`).join(", ")}`);
|
|
43
54
|
body.push(`offered but never loaded (${m.skills.neverLoaded.length}/${m.skills.offered}): ${m.skills.neverLoaded.slice(0, 25).join(", ")}`);
|
|
44
55
|
} else if (view === "packages") {
|
|
56
|
+
const w = m.weekly;
|
|
57
|
+
for (const p of w?.packages.slice(0, 3) ?? []) body.push(`${p.name} weekly errors/calls: ${p.before.errors}/${p.before.calls} -> ${p.after.errors}/${p.after.calls}`);
|
|
45
58
|
body.push("package: calls, error rate, avg time");
|
|
46
59
|
for (const p of m.packages.slice(0, 15)) body.push(`${p.owner}${p.version ? `@${p.version}` : ""}: ${p.calls}, ${pct(p.errorRate)}, ${sec(p.avgMs)}`);
|
|
47
60
|
} else if (view === "ask_user") {
|
|
@@ -49,11 +62,13 @@ export function query(view: View, options: { since?: string; project?: string; e
|
|
|
49
62
|
body.push(`questions ${a.calls}; dismissed ${pct(a.cancelRate)}; avg wait for answer ${sec(a.avgWaitMs)} (n=${a.waitN}); errors ${a.errors}`);
|
|
50
63
|
body.push(`answer source: ${Object.entries(a.sources).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
|
|
51
64
|
} else if (view === "monitors") {
|
|
65
|
+
const w = m.weekly?.monitors;
|
|
66
|
+
if (w) body.push(`weekly jobs ending in error: ${w.before.errors}/${w.before.calls} -> ${w.after.errors}/${w.after.calls}`);
|
|
52
67
|
const mo = m.monitors;
|
|
53
68
|
body.push(`started ${mo.started}; ending recorded ${mo.finished}; avg duration ${sec(mo.avgMs)} (n=${mo.durationN})`);
|
|
54
69
|
body.push(`outcomes: ${Object.entries(mo.statuses).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
|
|
55
70
|
} else if (view === "subagents") {
|
|
56
|
-
body.push(`subagent sessions ${m.subagents.sessions}; linked to parent ${m.subagents.linked}/${m.subagents.subagentTotal}
|
|
71
|
+
body.push(`subagent sessions ${m.subagents.sessions}; linked to parent: ${m.subagents.linked === null ? "run /evals extract for counts in this range" : `${m.subagents.linked}/${m.subagents.subagentTotal}`}`);
|
|
57
72
|
body.push("role / model: launches");
|
|
58
73
|
for (const l of m.subagents.launches.slice(0, 12)) body.push(`${l.role} / ${l.model}: ${l.n}`);
|
|
59
74
|
body.push(`cost by role: ${m.subagents.costByRole.slice(0, 8).map((r) => `${r.role} $${r.cost}`).join(", ")}`);
|
|
@@ -71,14 +86,15 @@ export function query(view: View, options: { since?: string; project?: string; e
|
|
|
71
86
|
body.push("cost of sessions loading skill (not caused by it):");
|
|
72
87
|
for (const s of m.cost.bySkill.slice(0, 10)) body.push(`${s.skill}: $${s.cost} over ${s.sessions} sessions`);
|
|
73
88
|
} else if (view === "changes") {
|
|
74
|
-
body.push("newest changes, sessions split at the change time, metric before -> after; flags: small = <20 sessions a side, incomplete = a window runs past the data, confounded = other commits nearby");
|
|
75
|
-
|
|
89
|
+
body.push("highlighted then newest changes, sessions split at the change time, metric before -> after; flags: small = <20 sessions a side, incomplete = a window runs past the data, confounded = other commits nearby");
|
|
90
|
+
const { highlighted, folded } = select(m);
|
|
91
|
+
for (const c of [...highlighted, ...folded].slice(0, 8)) {
|
|
76
92
|
const what = c.package ? `${c.package} ${c.from ?? "-"}->${c.to ?? "-"}` : c.subject.slice(0, 60);
|
|
77
93
|
const i = c.impact;
|
|
78
94
|
const fx = i
|
|
79
95
|
? `sessions ${i.before.sessions}->${i.after.sessions}, tool errors ${pct(i.before.tool_error_rate)}->${pct(i.after.tool_error_rate)}, anchor-first ${pct(i.before.anchor_before_first_edit)}->${pct(i.after.anchor_before_first_edit)}${i.smallSample ? ", small" : ""}${i.incomplete ? `, incomplete (days with data ${i.daysWithData.before}/${i.daysWithData.after})` : ""}${i.confounded ? `, confounded ${i.confounded}` : ""}`
|
|
80
96
|
: "no data before";
|
|
81
|
-
body.push(`${c.at
|
|
97
|
+
body.push(`${c.at} ${c.kind} ${what}: ${fx}`);
|
|
82
98
|
}
|
|
83
99
|
}
|
|
84
100
|
return bound([...head, ...body, `report: ${reportPath(options.env)}`].join("\n"));
|
package/src/ranges.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Filter } from "./model.ts";
|
|
2
|
+
|
|
3
|
+
export const PRESETS = [14, 30, 90, "all"] as const;
|
|
4
|
+
export type Preset = typeof PRESETS[number];
|
|
5
|
+
export const suffix = (r: Preset | "custom") => r === 30 ? "" : typeof r === "number" ? `-${r}d` : `-${r}`;
|
|
6
|
+
|
|
7
|
+
/** Calendar ranges include the (possibly partial) UTC day of the last extraction. */
|
|
8
|
+
export function rangeFilter(input: Filter & { days?: number }, end: string, preset: Preset = 30): Filter {
|
|
9
|
+
const until = input.until ?? end.slice(0, 10), days = input.days ?? preset;
|
|
10
|
+
if (input.since && input.days !== undefined) throw new Error("Choose either --days or --since.");
|
|
11
|
+
if (days !== "all" && (!Number.isSafeInteger(days) || days < 1 || days > 365000)) throw new Error("--days must be a positive integer (at most 365000).");
|
|
12
|
+
if (input.since && (!/^\d{4}-\d\d-\d\d$/.test(input.since) || !Number.isFinite(Date.parse(input.since)) || new Date(input.since).toISOString().slice(0, 10) !== input.since)) throw new Error("since must be YYYY-MM-DD.");
|
|
13
|
+
const since = input.since ?? (days === "all" ? undefined : new Date(Date.parse(until) - (days - 1) * 86400000).toISOString().slice(0, 10));
|
|
14
|
+
return { since, until, project: input.project };
|
|
15
|
+
}
|