pi-evals 0.2.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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ - Open the report on the last 30 days and switch to 14 days, 90 days or all time without scripts. For other dates use `--since` or `--days`.
6
+ - Ask `/evals findings` or use the `findings` tool view for the headline, its limits, and which numbers to read next. Tool views now default to 30 days.
7
+ - The `analyzing-evals` skill includes three small queries for the details of a change, daily sessions using one skill, and a package’s daily errors.
8
+
3
9
  ## 0.2.0
4
10
 
5
11
  - The report opens on two architecture changes, with a workload chart and a comparison you can open for every entry in the timeline. Each comparison shows what was counted and what limits the conclusion.
package/README.md CHANGED
@@ -40,7 +40,8 @@ The observer loads in every session, subagents included.
40
40
  | --- | --- |
41
41
  | `/evals` or `/evals status` | Record counts, the last extract, index coverage of old sessions, and the report path. |
42
42
  | `/evals extract [--workers N]` | Back-fills changed sessions in a background process, with two workers by default to leave memory for pi. Progress shows in the footer. |
43
- | `/evals report [--since YYYY-MM-DD] [--project <key>]` | Builds the report and prints its path. |
43
+ | `/evals findings [--since YYYY-MM-DD] [--project <key>]` | Shows the report’s headline, what limits it, and where to look next. |
44
+ | `/evals report [--since YYYY-MM-DD \| --days N] [--project <key>]` | Builds the linked date ranges, or one custom report when a start date or day count is given. |
44
45
  | `/evals mark <note>` | Adds a note to the change timeline, e.g. `/evals mark workers moved to gpt-6.2-astra`. |
45
46
 
46
47
  The same operations run from a shell, where extraction defaults to one fewer worker than available CPUs (at least one, at most eight).
@@ -48,7 +49,7 @@ On either surface, `--workers 0` reads the files sequentially without worker thr
48
49
 
49
50
  ```sh
50
51
  pi-evals extract [--root <dir>]... [--workers <n>] [--json]
51
- pi-evals report [--out <dir>] [--since YYYY-MM-DD] [--project <key>] [--lang zh|en]
52
+ pi-evals report [--out <dir>] [--since YYYY-MM-DD | --days N] [--project <key>] [--lang zh|en]
52
53
  pi-evals status
53
54
  pi-evals query <view> [--since YYYY-MM-DD] [--project <key>]
54
55
  pi-evals mark <note>
@@ -56,23 +57,32 @@ pi-evals mark <note>
56
57
 
57
58
  ### The `evals_query` tool
58
59
 
59
- An agent calls `evals_query` with a `view` (`skills`, `packages`, `ask_user`, `monitors`, `subagents`, `process`, `cost`, `changes`, `coverage`) and optional `since` and `project`.
60
- The result is a plain-text summary under 2 KB with the report path; it says when the data is more than a day old.
60
+ Start with `findings` (under 1,500 bytes), then follow one pointer if you need the counts.
61
+ An agent calls `evals_query` with a `view` (`findings`, `skills`, `packages`, `ask_user`, `monitors`, `subagents`, `process`, `cost`, `changes`, `coverage`) and optional `since` and `project`.
62
+ The result is plain text under 2 KB, covering the latest 30 UTC dates through the last extract unless you give `since`.
63
+ `findings` flags the biggest package error-rate rise and a rise in jobs ending in error when the later of two complete weeks is at least five percentage points higher, with at least 20 calls or endings in **each** week.
64
+ It also counts offered skills with no loads in the selected period and checks whether all old files are indexed.
65
+ The [analysis skill](skills/analyzing-evals/SKILL.md) includes three read-only commands for a change’s full comparison, a skill’s daily session counts, and a package’s daily errors.
61
66
  The tool never starts an extract.
62
67
 
63
68
  ## The report
64
69
 
65
- One HTML file with no scripts, no network requests and no external assets; charts are inline SVG, and it follows the system's light or dark setting.
66
- It is written as `report.html` next to `model.json`, the ReportModel it is rendered from.
70
+ Open `report.html` for the last 30 UTC dates, including the day of the last extract.
71
+ The links at the top switch to 14 days, 90 days or all time; each opens another offline page in the same directory, with no scripts or external assets.
72
+ Each page has a matching `model*.json` with the numbers it shows.
73
+ `--since` or `--days` writes `report-custom.html` and `model-custom.json` without replacing the preset pages.
67
74
  Every number in the model carries a plain-language label, what it means, which direction is better, and how it is computed, in English and Traditional Chinese.
68
75
  ### Reading the report
69
76
 
77
+ The strip below the date switch counts the changes by kind; its labeled marks open the highlighted comparisons.
70
78
  Start with the sentence above the timeline: it says what changed in the numbers; the next line tells you what limits the comparison.
71
79
  Open a card to see which sessions started before and after the change.
72
80
  Read the count beside each rate: a check that applies to 48 sessions can say nothing about the other 116 sessions in a group of 164.
73
81
  If the window is short, or other changes landed in the same period, do not credit a difference to the new version alone.
74
82
 
75
- The sidebar shows workload for the last seven complete UTC dates, with markers on days you changed the setup.
83
+ The sidebar shows workload for the selected dates, with markers on days you changed the setup.
84
+ A change appears on the timeline by its own date; its before-and-after comparison can reach beyond the selected dates.
85
+ The cleanup check always considers **all** old files, so selecting two weeks cannot hide an unindexed file from last year.
76
86
  The date disclosures keep the rest of the timeline available without putting hundreds of cards on the first screen.
77
87
  Use the section links for usage, process checks, cost and cleanup coverage, or read the [five concepts with a worked example](docs/learn.zh-TW.md).
78
88
 
package/dist/build.js CHANGED
@@ -9,7 +9,7 @@ import { dirname, join } from "node:path";
9
9
  import { addLabel, bucketOf, bump, emptyDay, mergeDay, rowOf } from "./aggregate.js";
10
10
  import { buildChanges, versionAt, writeChanges } from "./changes.js";
11
11
  import { dayOf } from "./paths.js";
12
- import { NAMES } from "./schema.js";
12
+ import { NAMES, traceId } from "./schema.js";
13
13
  import { liveFiles, readRecords } from "./store.js";
14
14
  export const ANCHORLOOP_PACKAGES = ["pi-anchorloop", "pi-aaaav", "aaaav"];
15
15
  function atomicWrite(file, text) {
@@ -198,7 +198,8 @@ export function buildIndex(options) {
198
198
  if (Object.keys(labels).length)
199
199
  sessionEvals[s.sessionId] = labels;
200
200
  add(s.project, days);
201
- rows.push(rowOf(s.start, s.project, s.kind === "subagent", s.cost, days, s.evals));
201
+ rows.push({ ...rowOf(s.start, s.project, s.kind === "subagent", s.cost, days, s.evals), id: traceId(s.sessionId, "labels"),
202
+ linked: s.kind === "subagent" ? Boolean(s.parentId || (s.logicalId && links.has(s.logicalId))) : undefined });
202
203
  }
203
204
  let liveOnly = 0;
204
205
  for (const [id, records] of bySession) {
@@ -207,7 +208,7 @@ export function buildIndex(options) {
207
208
  liveOnly += 1;
208
209
  const summary = liveSummary(records);
209
210
  add(summary.project, summary.days);
210
- rows.push(rowOf(summary.start, summary.project, records.some((r) => r.name === NAMES.session && r.attrs["pi.session.kind"] === "subagent"), 0, 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), id: traceId(id, "labels"), linked: false });
211
212
  }
212
213
  const owners = {};
213
214
  for (const rec of [...snapshots].sort((a, b) => a.ts.localeCompare(b.ts))) {
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ import { context, mark, runExtract, runReport, statusText } from "./ops.js";
4
4
  import { query, VIEWS } from "./query.js";
5
5
  const USAGE = `usage:
6
6
  pi-evals extract [--root <dir>]... [--workers <n>] [--json]
7
- pi-evals report [--out <dir>] [--since YYYY-MM-DD] [--project <key>] [--lang zh|en]
7
+ pi-evals report [--out <dir>] [--since YYYY-MM-DD | --days N] [--project <key>] [--lang zh|en]
8
8
  pi-evals status
9
9
  pi-evals query <${VIEWS.join("|")}> [--since YYYY-MM-DD] [--project <key>]
10
10
  pi-evals mark <note>`;
@@ -50,7 +50,7 @@ async function main(argv) {
50
50
  }
51
51
  if (cmd === "report") {
52
52
  const lang = flag(args, "--lang") === "en" ? "en" : "zh";
53
- const out = runReport({ outDir: flag(args, "--out"), filter: { since: flag(args, "--since"), project: flag(args, "--project") }, lang });
53
+ const out = runReport({ outDir: flag(args, "--out"), filter: { since: flag(args, "--since"), days: args.includes("--days") ? Number(flag(args, "--days")) : undefined, project: flag(args, "--project") }, lang });
54
54
  if (!out) {
55
55
  console.error("nothing extracted yet: run pi-evals extract");
56
56
  return 1;
package/dist/coverage.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { listSessionFiles } from "./extract/run.js";
2
- export function coverage(roots, checkpoint, cutDays, now = Date.now()) {
2
+ export function coverage(roots, checkpoint, cutDays, now = Date.now(), activity) {
3
3
  const cutoff = now - cutDays * 86_400_000;
4
4
  const files = listSessionFiles(roots);
5
5
  const result = {
@@ -19,6 +19,13 @@ export function coverage(roots, checkpoint, cutDays, now = Date.now()) {
19
19
  const fresh = !!known && known.size === f.size && known.mtimeMs === f.mtimeMs;
20
20
  if (fresh)
21
21
  result.all.indexedFiles += 1;
22
+ if (activity) {
23
+ const day = new Date(f.mtimeMs).toISOString().slice(0, 10), row = activity.get(day) ?? { files: 0, indexed: 0 };
24
+ row.files++;
25
+ if (fresh)
26
+ row.indexed++;
27
+ activity.set(day, row);
28
+ }
22
29
  if (f.mtimeMs >= cutoff)
23
30
  continue;
24
31
  result.old.files += 1;
@@ -0,0 +1,50 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { overview, readings, value, verdict } from "./report/findings.js";
3
+ import { words } from "./report/format.js";
4
+ import { safeName } from "./schema.js";
5
+ import { trendPair } from "./trends.js";
6
+ export const scriptsDir = fileURLToPath(new URL("../scripts", import.meta.url));
7
+ /** Shorten only identifiers, never a verdict or its drill-down pointer. */
8
+ function name(s) {
9
+ const chars = Array.from(safeName(s));
10
+ if (Buffer.byteLength(chars.join("")) <= 72)
11
+ return chars.join("");
12
+ while (Buffer.byteLength(chars.join("")) > 69)
13
+ chars.pop();
14
+ return chars.join("") + "…";
15
+ }
16
+ export function findings(m) {
17
+ const { headline, trust, highlighted } = overview(m, "en"), L = words("en");
18
+ const lines = [
19
+ `${m.window.since ?? "?"}..${m.window.until ?? "?"} UTC${m.window.project ? ` · ${name(m.window.project)}` : ""} · ${m.freshness.stale ? "STALE: " : ""}last extract ${m.freshness.lastExtract ?? "never"} → coverage`,
20
+ `Scripts: ${scriptsDir}`, `${headline} → changes`, `${trust} → changes`,
21
+ ];
22
+ const extras = [];
23
+ for (const c of highlighted) {
24
+ const id = c.package ? `${name(c.package)} ${name(c.to ?? "unknown")}` : c.kind;
25
+ const rs = readings(c, m, "en"), r = rs.find(row => row.before?.value != null && row.after?.value != null);
26
+ const metric = r ? `${r.label} ${value(r, "before")} → ${value(r, "after")}; ` : "";
27
+ const prefix = `${c.at} ${id}: `;
28
+ extras.push({ line: lines.length, prefix, metric });
29
+ lines.push(`${prefix}${verdict(c, rs, L)} → changes`);
30
+ }
31
+ const unseen = m.skills.neverLoaded.length;
32
+ lines.push(`${unseen}/${m.skills.offered} offered skills never loaded in range → skills`);
33
+ const cov = m.coverage;
34
+ const gate = !cov ? "not measured" : !cov.old.files ? "no old files" : cov.notIndexed.files || cov.notIndexed.bytes
35
+ ? `blocked: ${cov.notIndexed.files}/${cov.old.files} old files not indexed` : `all ${cov.old.files} old files indexed`;
36
+ lines.push(`Cleanup (all projects/dates): ${gate} → coverage`);
37
+ const w = m.weekly;
38
+ if (!w)
39
+ lines.push("Need two weeks in range for error trends → packages / monitors");
40
+ else {
41
+ const p = w.packages[0];
42
+ lines.push(`${w.start}..${w.end} UTC, earlier week vs later: ${p ? `${p.name === "unknown" ? "tools with no known package" : name(p.name)} errors/calls ${trendPair(p)}` : "no package rise flagged"} → packages`);
43
+ lines.push(`Same weeks: ${w.monitors ? `failed/finished jobs ${trendPair(w.monitors)}` : "no job error rise flagged"} → monitors`);
44
+ }
45
+ for (const { line, prefix, metric } of extras) {
46
+ if (Buffer.byteLength(lines.join("\n") + metric) <= 1499)
47
+ lines[line] = prefix + metric + lines[line].slice(prefix.length);
48
+ }
49
+ return lines.join("\n");
50
+ }
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { spawn } from "node:child_process";
5
5
  import { existsSync } from "node:fs";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { Type } from "typebox";
8
+ import { scriptsDir } from "./findings.js";
8
9
  import { observe } from "./observer.js";
9
10
  import { context, mark, reportPath, runReport, statusText } from "./ops.js";
10
11
  import { query, VIEWS } from "./query.js";
@@ -17,12 +18,14 @@ export function cliPath() {
17
18
  const found = candidates.find((p) => existsSync(p));
18
19
  return found ? { cmd: process.execPath, args: [found] } : undefined;
19
20
  }
20
- const SUBCOMMANDS = ["status", "extract", "report", "mark"];
21
+ const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark"];
21
22
  function parseFlags(args) {
22
23
  const out = { rest: [] };
23
24
  for (let i = 0; i < args.length; i++) {
24
25
  if (args[i] === "--since")
25
26
  out.since = args[++i];
27
+ else if (args[i] === "--days")
28
+ out.days = Number(args[++i]);
26
29
  else if (args[i] === "--project")
27
30
  out.project = args[++i];
28
31
  else
@@ -95,7 +98,7 @@ export function createEvals(options = {}) {
95
98
  });
96
99
  };
97
100
  pi.registerCommand("evals", {
98
- description: "Usage and process records: /evals [status|extract|report|mark <note>]",
101
+ description: "Usage and process records: /evals [status|findings|extract|report|mark <note>]",
99
102
  getArgumentCompletions: (prefix) => {
100
103
  const items = SUBCOMMANDS.filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
101
104
  return items.length ? items : null;
@@ -106,6 +109,10 @@ export function createEvals(options = {}) {
106
109
  if (sub === "status") {
107
110
  ctx.ui.notify(statusText(env), "info");
108
111
  }
112
+ else if (sub === "findings") {
113
+ const flags = parseFlags(words.slice(1));
114
+ ctx.ui.notify(query("findings", { env, ...flags }), "info");
115
+ }
109
116
  else if (sub === "extract") {
110
117
  if (running) {
111
118
  ctx.ui.notify("pi-evals: an extract is already running.", "warning");
@@ -123,7 +130,7 @@ export function createEvals(options = {}) {
123
130
  }
124
131
  else if (sub === "report") {
125
132
  const flags = parseFlags(words.slice(1));
126
- const out = runReport({ env, filter: { since: flags.since, project: flags.project } });
133
+ const out = runReport({ env, filter: flags });
127
134
  ctx.ui.notify(out ? `pi-evals report: ${out.html}\nmodel: ${out.json}` : "pi-evals: nothing extracted yet; run /evals extract first.", out ? "info" : "warning");
128
135
  }
129
136
  else if (sub === "mark") {
@@ -143,11 +150,11 @@ export function createEvals(options = {}) {
143
150
  pi.registerTool({
144
151
  name: "evals_query",
145
152
  label: "Evals Query",
146
- description: "Summaries of how skills, packages, ask-user, monitors and subagents were used, process-rule adherence, cost, the user's architecture changes with before/after numbers, and index coverage. Numbers and names only.",
147
- promptSnippet: "Read pi usage and process summaries (skills, packages, process, cost, changes)",
153
+ description: "Start with findings for agent activity and changes; use one detail view for counts, cost or coverage.",
154
+ promptSnippet: "Analyze agent activity: query findings first, then one detail view",
148
155
  parameters: Type.Object({
149
156
  view: Type.Unsafe({ type: "string", enum: [...VIEWS], description: "Which summary" }),
150
- since: Type.Optional(Type.String({ description: "YYYY-MM-DD; default all data" })),
157
+ since: Type.Optional(Type.String({ description: "YYYY-MM-DD; default last 30 UTC dates through extraction" })),
151
158
  project: Type.Optional(Type.String({ description: "Project key, e.g. a repo name" })),
152
159
  }),
153
160
  async execute(_id, params) {
@@ -157,7 +164,7 @@ export function createEvals(options = {}) {
157
164
  if (params.since && !/^\d{4}-\d{2}-\d{2}$/.test(params.since))
158
165
  throw new Error("since must be YYYY-MM-DD.");
159
166
  const text = query(view, { since: params.since, project: params.project, env });
160
- return { content: [{ type: "text", text }], details: { view, report: reportPath(env) } };
167
+ return { content: [{ type: "text", text }], details: { view, scriptsDir, report: reportPath(env) } };
161
168
  },
162
169
  });
163
170
  };
package/dist/model.js CHANGED
@@ -7,7 +7,8 @@ import { ASK_BUCKETS, emptyDay, mergeDay } from "./aggregate.js";
7
7
  import { DETECTORS, ERA_START } from "./detectors.js";
8
8
  import { CHANGE_KIND_META, DETECTOR_META, METRICS, NOTICE_META } from "./meta.js";
9
9
  import { staticOwner } from "./owners.js";
10
- import { dayOf } from "./paths.js";
10
+ import { weeklyRises } from "./trends.js";
11
+ import { traceId } from "./schema.js";
11
12
  export const SMALL_SAMPLE = 20;
12
13
  /** Data older than this (hours) is reported as stale. */
13
14
  export const STALE_HOURS = 24;
@@ -151,7 +152,7 @@ export function impactFromRows(rows, change, all, windowDays, range, ownerOf) {
151
152
  confounders: kinds,
152
153
  };
153
154
  }
154
- function labelsJoin(labelsFile, evalsFile) {
155
+ function labelsJoin(labelsFile, evalsFile, sessionIds) {
155
156
  if (!existsSync(labelsFile))
156
157
  return { present: false, n: 0, agreement: [] };
157
158
  const codeLabels = existsSync(evalsFile) ? JSON.parse(readFileSync(evalsFile, "utf8")) : {};
@@ -167,7 +168,11 @@ function labelsJoin(labelsFile, evalsFile) {
167
168
  }
168
169
  });
169
170
  const by = new Map();
171
+ let n = 0;
170
172
  for (const row of rows) {
173
+ if (sessionIds && !sessionIds.has(traceId(row.session_id, "labels")))
174
+ continue;
175
+ n++;
171
176
  const code = codeLabels[row.session_id]?.[row.evaluation_name];
172
177
  if (!code || code === "na")
173
178
  continue;
@@ -177,7 +182,7 @@ function labelsJoin(labelsFile, evalsFile) {
177
182
  t.agree += 1;
178
183
  by.set(row.evaluation_name, t);
179
184
  }
180
- return { present: true, n: rows.length, agreement: [...by].map(([detector, t]) => ({ detector, n: t.n, agree: t.agree, rate: rate(t.agree, t.n) })) };
185
+ return { present: true, n, agreement: [...by].map(([detector, t]) => ({ detector, n: t.n, agree: t.agree, rate: rate(t.agree, t.n) })) };
181
186
  }
182
187
  export function buildModel(options) {
183
188
  const { index, filter } = options;
@@ -206,6 +211,11 @@ export function buildModel(options) {
206
211
  const byProject = [...projectSkills.values()].sort((a, b) => b.loads - a.loads);
207
212
  const projectRows = filter.project ? options.rows.filter((r) => r.p === filter.project) : options.rows;
208
213
  const owner = (tool) => ownerFor(index, tool);
214
+ const inRange = (at) => (!filter.since || at.slice(0, 10) >= filter.since) && (!filter.until || at.slice(0, 10) <= filter.until);
215
+ const selected = projectRows.filter(r => inRange(r.s)), children = selected.filter(r => r.k);
216
+ const scoped = Boolean(filter.since || filter.until || filter.project);
217
+ const hasSessionIds = selected.every(r => r.id !== undefined);
218
+ const labelIds = scoped && existsSync(options.labelsFile) ? new Set(selected.flatMap(r => r.id ? [r.id] : [])) : undefined;
209
219
  const calls = Object.values(total.tools).reduce((s, t) => s + t.calls, 0);
210
220
  const errors = Object.values(total.tools).reduce((s, t) => s + t.errors, 0);
211
221
  const tokens = total.usage.input + total.usage.output + total.usage.cacheRead + total.usage.cacheWrite;
@@ -219,11 +229,12 @@ export function buildModel(options) {
219
229
  versions.set(name, list);
220
230
  }
221
231
  const sortedChanges = [...options.changes].sort((a, b) => a.at.localeCompare(b.at));
222
- const firstDay = Object.keys(index.days).sort()[0] ?? "";
232
+ const earliest = [days[0], sortedChanges.find(c => inRange(c.at))?.at.slice(0, 10)].filter(Boolean).sort()[0];
223
233
  return {
224
234
  v: 1,
225
235
  generated: now.toISOString(),
226
- window: { since: days[0] ?? filter.since ?? null, until: days.at(-1) ?? filter.until ?? null, days: days.length, project: filter.project ?? null },
236
+ weekly: weeklyRises(index, filter.since ?? earliest, filter.project),
237
+ window: { since: filter.since ?? earliest ?? null, until: filter.until ?? days.at(-1) ?? null, days: days.length, project: filter.project ?? null },
227
238
  freshness: { lastExtract: lastExtract ?? null, built: index.built, stale: ageHours > STALE_HOURS, ageHours: Number.isFinite(ageHours) ? round(ageHours, 1) : null },
228
239
  meta: { metrics: METRICS, detectors: DETECTOR_META, notices: NOTICE_META, changeKinds: CHANGE_KIND_META },
229
240
  totals: {
@@ -281,8 +292,8 @@ export function buildModel(options) {
281
292
  costByRole: Object.entries(total.subagentCost)
282
293
  .map(([role, cost]) => ({ role, cost: round(cost, 2) }))
283
294
  .sort((a, b) => b.cost - a.cost),
284
- linked: index.sessions.linked,
285
- subagentTotal: index.sessions.subagent,
295
+ linked: scoped ? (children.every(r => r.linked !== undefined) ? children.filter(r => r.linked).length : null) : index.sessions.linked,
296
+ subagentTotal: scoped ? children.length : index.sessions.subagent,
286
297
  },
287
298
  process: {
288
299
  eraStart: ERA_START,
@@ -308,10 +319,10 @@ export function buildModel(options) {
308
319
  .slice(0, 25)
309
320
  .map(({ name, cost, sessions }) => ({ skill: name, cost, sessions })),
310
321
  },
311
- changes: sortedChanges
312
- .filter((c) => (!filter.since || c.at.slice(0, 10) >= filter.since) && (!filter.until || c.at.slice(0, 10) <= filter.until))
322
+ changes: options.comparisons?.filter(c => inRange(c.at)) ?? sortedChanges
323
+ .filter((c) => inRange(c.at))
313
324
  .map((c) => ({ ...c, impact: index.range.start && c.at > index.range.start ? impactFromRows(projectRows, c, sortedChanges, options.windowDays, index.range, owner) : null })),
314
- labels: labelsJoin(options.labelsFile, options.sessionEvalsFile),
325
+ labels: { ...labelsJoin(options.labelsFile, options.sessionEvalsFile, labelIds), needsIndex: !!labelIds && !hasSessionIds },
315
326
  coverage: options.coverage ?? null,
316
327
  };
317
328
  }
package/dist/ops.js CHANGED
@@ -5,6 +5,7 @@ import { buildIndex, loadIndex, loadRows } from "./build.js";
5
5
  import { addMark, readChanges } from "./changes.js";
6
6
  import { coverage } from "./coverage.js";
7
7
  import { extract, loadCheckpoint } from "./extract/run.js";
8
+ import { PRESETS, rangeFilter, suffix } from "./ranges.js";
8
9
  import { buildModel } from "./model.js";
9
10
  import { agentDir, home, layout, loadSettings, stateDir } from "./paths.js";
10
11
  import { renderHtml } from "./render.js";
@@ -38,35 +39,64 @@ export function coverageNow(env, cutDays) {
38
39
  const ctx = context(env);
39
40
  return coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), cutDays ?? ctx.settings.coverageDays);
40
41
  }
41
- export function model(filter, env, withCoverage = true) {
42
- const ctx = context(env);
43
- const index = loadIndex(ctx.layout);
42
+ function coverageReader(ctx, now) {
43
+ const activity = new Map();
44
+ const cov = coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), ctx.settings.coverageDays, now.getTime(), activity);
45
+ return (filter) => {
46
+ const inRange = { files: 0, indexed: 0 };
47
+ for (const [day, a] of activity)
48
+ if ((!filter.since || day >= filter.since) && (!filter.until || day <= filter.until)) {
49
+ inRange.files += a.files;
50
+ inRange.indexed += a.indexed;
51
+ }
52
+ return { ...cov, inRange };
53
+ };
54
+ }
55
+ export function coverageInRange(input, env) {
56
+ const ctx = context(env), now = new Date(), last = loadIndex(ctx.layout)?.lastExtract;
57
+ const filter = rangeFilter(input, last ?? now.toISOString());
58
+ return { filter, last, coverage: coverageReader(ctx, now)(filter) };
59
+ }
60
+ function snapshot(env, withCoverage = true) {
61
+ const ctx = context(env), index = loadIndex(ctx.layout);
44
62
  if (!index)
45
- return undefined;
46
- return buildModel({
47
- index,
48
- rows: loadRows(ctx.layout),
49
- changes: readChanges(ctx.layout.changes),
50
- filter,
51
- windowDays: ctx.settings.impactWindowDays,
52
- labelsFile: ctx.layout.labels,
53
- sessionEvalsFile: ctx.layout.sessionEvals,
54
- coverage: withCoverage ? coverageNow(env) : undefined,
55
- });
63
+ return;
64
+ const rows = loadRows(ctx.layout), changes = readChanges(ctx.layout.changes), now = new Date();
65
+ const cov = withCoverage ? coverageReader(ctx, now) : undefined;
66
+ return { index, build(input, preset, comparisons) {
67
+ const filter = rangeFilter(input, index.lastExtract ?? now.toISOString(), preset);
68
+ return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays,
69
+ labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter) });
70
+ } };
71
+ }
72
+ export function indexedModel(filter, env, withCoverage = true) {
73
+ const data = snapshot(env, withCoverage);
74
+ return data && { report: data.build(filter, 30), index: data.index };
75
+ }
76
+ export function model(filter, env, withCoverage = true) {
77
+ return indexedModel(filter, env, withCoverage)?.report;
56
78
  }
57
79
  /** Builds the report; returns the HTML path, or undefined when nothing was extracted yet. */
58
80
  export function runReport(options = {}) {
59
81
  const ctx = context(options.env);
60
- const m = model(options.filter ?? {}, options.env);
61
- if (!m)
62
- return undefined;
82
+ const data = snapshot(options.env), filter = options.filter ?? {};
83
+ if (!data)
84
+ return;
63
85
  const dir = resolve(options.outDir ?? ctx.layout.reports);
64
86
  mkdirSync(dir, { recursive: true });
65
- const html = join(dir, "report.html");
66
- const json = join(dir, "model.json");
67
- writeFileSync(json, JSON.stringify(m, null, 1));
68
- writeFileSync(html, renderHtml(m, options.lang ?? "zh"));
69
- return { html, json };
87
+ const write = (m, range) => {
88
+ const html = join(dir, `report${suffix(range)}.html`), json = join(dir, `model${suffix(range)}.json`);
89
+ writeFileSync(json, JSON.stringify(m, null, 1));
90
+ writeFileSync(html, renderHtml(m, options.lang ?? "zh", range));
91
+ return { html, json };
92
+ };
93
+ if (filter.since || filter.until || filter.days !== undefined)
94
+ return write(data.build(filter, 30), "custom");
95
+ const all = data.build(filter, "all");
96
+ for (const p of PRESETS)
97
+ if (p !== 30)
98
+ write(p === "all" ? all : data.build(filter, p, all.changes), p);
99
+ return write(data.build(filter, 30, all.changes), 30);
70
100
  }
71
101
  export function reportPath(env) {
72
102
  return join(context(env).layout.reports, "report.html");
package/dist/query.js CHANGED
@@ -1,6 +1,8 @@
1
1
  /** `evals_query`: bounded plain-text summaries of the index for an agent (names and numbers only, under 2 KB). */
2
- import { coverageNow, model, reportPath } from "./ops.js";
3
- export const VIEWS = ["skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"];
2
+ import { coverageInRange, indexedModel, reportPath } from "./ops.js";
3
+ import { findings } from "./findings.js";
4
+ import { select } from "./report/findings.js";
5
+ export const VIEWS = ["findings", "skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"];
4
6
  export const MAX_BYTES = 1900;
5
7
  const pct = (r) => (r && r.value !== null ? `${(r.value * 100).toFixed(1)}% (n=${r.n})` : `n/a (n=${r?.n ?? 0})`);
6
8
  const sec = (v) => (v === null ? "n/a" : `${(v / 1000).toFixed(1)}s`);
@@ -8,24 +10,34 @@ const sec = (v) => (v === null ? "n/a" : `${(v / 1000).toFixed(1)}s`);
8
10
  export function bound(text, limit = MAX_BYTES) {
9
11
  if (Buffer.byteLength(text) <= limit)
10
12
  return text;
11
- const lines = text.split("\n");
12
- while (lines.length > 1 && Buffer.byteLength(`${lines.join("\n")}\n…`) > limit)
13
- lines.splice(lines.length - 2, 1);
14
- return `${lines.join("\n")}\n…`.slice(0, limit);
13
+ const lines = text.split("\n"), tail = lines.at(-1) ?? "";
14
+ const suffix = tail.startsWith("report: ") && Buffer.byteLength(tail) < limit / 2 ? `\n…\n${tail}` : "\n…";
15
+ const kept = [];
16
+ for (const line of lines) {
17
+ if (Buffer.byteLength([...kept, line].join("\n") + suffix) > limit)
18
+ break;
19
+ kept.push(line);
20
+ }
21
+ return kept.join("\n") + suffix;
15
22
  }
16
23
  export function query(view, options = {}) {
17
24
  if (view === "coverage") {
18
- const c = coverageNow(options.env);
25
+ const { coverage: c, filter, last } = coverageInRange(options, options.env);
19
26
  return bound([
27
+ `${filter.since}..${filter.until} UTC; last extract ${last ?? "never"}; live cleanup check across all dates and projects`,
20
28
  `coverage, sessions inactive > ${c.cutDays} days (before ${c.cutoff.slice(0, 10)}):`,
21
29
  `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}`,
30
+ `modified in report dates (all projects): ${c.inRange?.indexed ?? 0}/${c.inRange?.files ?? 0} files indexed`,
22
31
  `all files: ${c.all.indexedFiles}/${c.all.files} indexed; index keeps ${c.retainedGone} sessions whose file is gone`,
23
32
  "meaning: only indexed files keep their numbers if the session files are cleaned up",
24
33
  ].join("\n"));
25
34
  }
26
- const m = model({ since: options.since, project: options.project }, options.env, false);
27
- if (!m)
35
+ const data = indexedModel(options, options.env, view === "findings");
36
+ if (!data)
28
37
  return "pi-evals: nothing extracted yet; the user can run /evals extract.";
38
+ const { report: m, index } = data;
39
+ if (view === "findings")
40
+ return bound(findings(m), 1499);
29
41
  const head = [
30
42
  `pi-evals ${view} · ${m.window.since ?? "?"}..${m.window.until ?? "?"}${m.window.project ? ` · project ${m.window.project}` : ""} · sessions ${m.totals.sessions}`,
31
43
  m.freshness.stale ? `STALE: last extract ${m.freshness.lastExtract ?? "never"} (${m.freshness.ageHours ?? "?"}h ago); /evals extract refreshes` : `last extract ${m.freshness.lastExtract}`,
@@ -39,6 +51,9 @@ export function query(view, options = {}) {
39
51
  body.push(`offered but never loaded (${m.skills.neverLoaded.length}/${m.skills.offered}): ${m.skills.neverLoaded.slice(0, 25).join(", ")}`);
40
52
  }
41
53
  else if (view === "packages") {
54
+ const w = m.weekly;
55
+ for (const p of w?.packages.slice(0, 3) ?? [])
56
+ body.push(`${p.name} weekly errors/calls: ${p.before.errors}/${p.before.calls} -> ${p.after.errors}/${p.after.calls}`);
42
57
  body.push("package: calls, error rate, avg time");
43
58
  for (const p of m.packages.slice(0, 15))
44
59
  body.push(`${p.owner}${p.version ? `@${p.version}` : ""}: ${p.calls}, ${pct(p.errorRate)}, ${sec(p.avgMs)}`);
@@ -49,12 +64,15 @@ export function query(view, options = {}) {
49
64
  body.push(`answer source: ${Object.entries(a.sources).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
50
65
  }
51
66
  else if (view === "monitors") {
67
+ const w = m.weekly?.monitors;
68
+ if (w)
69
+ body.push(`weekly jobs ending in error: ${w.before.errors}/${w.before.calls} -> ${w.after.errors}/${w.after.calls}`);
52
70
  const mo = m.monitors;
53
71
  body.push(`started ${mo.started}; ending recorded ${mo.finished}; avg duration ${sec(mo.avgMs)} (n=${mo.durationN})`);
54
72
  body.push(`outcomes: ${Object.entries(mo.statuses).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
55
73
  }
56
74
  else if (view === "subagents") {
57
- body.push(`subagent sessions ${m.subagents.sessions}; linked to parent ${m.subagents.linked}/${m.subagents.subagentTotal} (all time)`);
75
+ 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}`}`);
58
76
  body.push("role / model: launches");
59
77
  for (const l of m.subagents.launches.slice(0, 12))
60
78
  body.push(`${l.role} / ${l.model}: ${l.n}`);
@@ -78,14 +96,15 @@ export function query(view, options = {}) {
78
96
  body.push(`${s.skill}: $${s.cost} over ${s.sessions} sessions`);
79
97
  }
80
98
  else if (view === "changes") {
81
- 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");
82
- for (const c of m.changes.slice(-8).reverse()) {
99
+ 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");
100
+ const { highlighted, folded } = select(m);
101
+ for (const c of [...highlighted, ...folded].slice(0, 8)) {
83
102
  const what = c.package ? `${c.package} ${c.from ?? "-"}->${c.to ?? "-"}` : c.subject.slice(0, 60);
84
103
  const i = c.impact;
85
104
  const fx = i
86
105
  ? `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}` : ""}`
87
106
  : "no data before";
88
- body.push(`${c.at.slice(0, 10)} ${c.kind} ${what}: ${fx}`);
107
+ body.push(`${c.at} ${c.kind} ${what}: ${fx}`);
89
108
  }
90
109
  }
91
110
  return bound([...head, ...body, `report: ${reportPath(options.env)}`].join("\n"));
package/dist/ranges.js ADDED
@@ -0,0 +1,14 @@
1
+ export const PRESETS = [14, 30, 90, "all"];
2
+ export const suffix = (r) => r === 30 ? "" : typeof r === "number" ? `-${r}d` : `-${r}`;
3
+ /** Calendar ranges include the (possibly partial) UTC day of the last extraction. */
4
+ export function rangeFilter(input, end, preset = 30) {
5
+ const until = input.until ?? end.slice(0, 10), days = input.days ?? preset;
6
+ if (input.since && input.days !== undefined)
7
+ throw new Error("Choose either --days or --since.");
8
+ if (days !== "all" && (!Number.isSafeInteger(days) || days < 1 || days > 365000))
9
+ throw new Error("--days must be a positive integer (at most 365000).");
10
+ 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))
11
+ throw new Error("since must be YYYY-MM-DD.");
12
+ const since = input.since ?? (days === "all" ? undefined : new Date(Date.parse(until) - (days - 1) * 86400000).toISOString().slice(0, 10));
13
+ return { since, until, project: input.project };
14
+ }
package/dist/render.js CHANGED
@@ -3,9 +3,18 @@ import { esc, num, words } from "./report/format.js";
3
3
  import { sections } from "./report/sections.js";
4
4
  import { css } from "./report/style.js";
5
5
  import { timeline } from "./report/timeline.js";
6
- import { week, workload } from "./report/week.js";
7
- export function renderHtml(m, lang = "zh") {
8
- const L = words(lang), w = week(m), t = timeline(m, w, lang), c = concepts(m, w, t.lead, L);
6
+ import { PRESETS, suffix } from "./ranges.js";
7
+ import { trendPair } from "./trends.js";
8
+ import { periodRows, workload } from "./report/week.js";
9
+ function weeklyPanel(m, L) {
10
+ const w = m.weekly, p = w?.packages[0];
11
+ if (!w || (!p && !w.monitors))
12
+ return "";
13
+ const rows = [p && `${p.name === "unknown" ? L("Tools with no known package", "套件不明的工具") : p.name} ${L("errors/calls", "錯誤數/呼叫數")} ${trendPair(p)}`, w.monitors && `${L("Failed/finished jobs", "失敗數/已結束工作數")} ${trendPair(w.monitors)}`];
14
+ return `<section class="panel"><h2>${L("Weekly error increases", "每週錯誤比例上升")}</h2><p>${esc(w.start)}–${esc(w.end)} UTC · ${L("Earlier week → later week", "前一週 → 後一週")}</p>${rows.filter(Boolean).map(s => `<p>${esc(s)}</p>`).join("")}</section>`;
15
+ }
16
+ export function renderHtml(m, lang = "zh", range = "custom") {
17
+ const L = words(lang), w = periodRows(m), t = timeline(m, w, lang, range), c = concepts(m, w, t.lead, L);
9
18
  const nav = [
10
19
  ["archive", L("All changes", "所有調整")],
11
20
  ["skills", L("Skills", "技能")],
@@ -21,10 +30,10 @@ export function renderHtml(m, lang = "zh") {
21
30
  ];
22
31
  const date = m.generated.slice(0, 10);
23
32
  return `<!doctype html><html lang="${lang === "zh" ? "zh-Hant-TW" : "en"}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>pi-evals · ${L("Change timeline", "調整時間軸")}</title><style>${css}</style></head><body><header><a href="#timeline" class="brand"><svg width="30" height="30" viewBox="0 0 30 30" aria-hidden="true"><rect width="30" height="30" rx="8" fill="#174e47"/><path d="M7 22V15M15 22V8M23 22V12" fill="none" stroke="white" stroke-width="3"/></svg>pi-evals<span>${L("Agent work, observed", "代理工作觀察")}</span></a><small>${esc(date)} ${L("report", "更新")} / ${L("All times UTC", "時間皆為 UTC")}</small></header>
24
- <main id="timeline"><div class="hero"><p class="eyebrow">${L("Change journal / Newest first", "調整紀事 / 依更新時間排列")}</p><h1>${esc(t.headline)}</h1><p class="deck">${esc(t.trust)}</p>${m.freshness.stale
33
+ <main id="timeline"><div class="ranges">${range === "custom" ? "" : `<nav aria-label="${L("Time range", "時間範圍")}">${PRESETS.map(p => `<a href="report${suffix(p)}.html"${p === range ? ' aria-current="page"' : ""}>${p === "all" ? L("All time", "全部") : L(`Last ${p} days`, `近 ${p} 天`)}</a>`).join("")}</nav>`}<small>${esc(m.window.since ?? "—")} – ${esc(m.window.until ?? "—")} UTC</small></div>${t.strip}<div class="hero"><p class="eyebrow">${L("Change journal / Newest first", "調整紀事 / 依更新時間排列")}</p><h1>${esc(t.headline)}</h1><p class="deck">${esc(t.trust)}</p>${m.freshness.stale
25
34
  ? `<p class="stale">${L("Last extract", "上次抽取")}:${esc(m.freshness.lastExtract ?? "—")} · ${L("Refresh with /evals extract.", "資料過時,請執行 /evals extract。")}</p>`
26
35
  : ""}</div>
27
- <div class="spine"><h2>${L(`${t.count} changes worth a closer look`, `${t.count === 2 ? "兩" : t.count === 1 ? "一" : "零"}筆值得回看的調整`)}</h2><div class="layout"><div class="rail">${t.cards || `<p>${L("Nothing to highlight yet.", "還沒有適合比較的調整。")}</p>`}</div><aside class="side">${workload(w, L)}${lesson(c.record, L)}${lesson(c.metric, L)}</aside></div><details><summary>${L("How to read the comparisons", "怎麼讀時間軸上的比較?")}</summary><div class="notes-grid">${lesson(c.sample, L)}${lesson(c.confounding, L)}${lesson(c.check, L)}</div></details></div>
36
+ <div class="spine"><h2>${L(`${t.count} changes worth a closer look`, `${t.count === 2 ? "兩" : t.count === 1 ? "一" : "零"}筆值得回看的調整`)}</h2><div class="layout"><div class="rail">${t.cards || `<p>${L("Nothing to highlight yet.", "還沒有適合比較的調整。")}</p>`}</div><aside class="side">${workload(w, L)}${weeklyPanel(m, L)}${lesson(c.record, L)}${lesson(c.metric, L)}</aside></div><details><summary>${L("How to read the comparisons", "怎麼讀時間軸上的比較?")}</summary><div class="notes-grid">${lesson(c.sample, L)}${lesson(c.confounding, L)}${lesson(c.check, L)}</div></details></div>
28
37
  <nav class="jump" aria-label="${L("Report sections", "報表章節")}">${nav.map(([id, text]) => `<a href="#${id}">${text}</a>`).join("")}</nav><section class="topic" id="archive"><h2>${L("Other changes by day", "按日期查其餘調整")}</h2><p>${L("Open a day for its changes. Each link opens the before-and-after comparison.", "展開一天,點選調整名稱,就能看到它的前後比較。")}</p>${t.archive || "—"}</section>
29
38
  <p class="muted">${esc(m.window.project ?? L("All projects", "全部專案"))} · ${esc(m.window.since ?? "—")} → ${esc(m.window.until ?? "—")} · ${num(m.totals.sessions)} ${L("sessions", "段工作")} · ${num(m.totals.prompts)} ${L("prompts", "次提示")}</p>${sections(m, lang, c)}</main>
30
39
  ${t.details}<footer><b>PI-EVALS / ${L("Change timeline", "調整時間軸")}</b><span>${esc(m.window.project ?? L("All projects", "全部專案"))} · ${L("Transcript text not included", "統計不含對話原文")}</span></footer></body></html>`;