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.
Files changed (67) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +116 -2
  4. package/dist/aggregate.js +113 -0
  5. package/dist/build.js +260 -0
  6. package/dist/changes.js +170 -0
  7. package/dist/cli.js +86 -0
  8. package/dist/coverage.js +34 -0
  9. package/dist/detectors.js +154 -0
  10. package/dist/extract/file.js +42 -0
  11. package/dist/extract/run.js +149 -0
  12. package/dist/extract/session.js +430 -0
  13. package/dist/extract/worker.js +12 -0
  14. package/dist/index.js +165 -0
  15. package/dist/meta.js +233 -0
  16. package/dist/model.js +317 -0
  17. package/dist/observer.js +240 -0
  18. package/dist/ops.js +93 -0
  19. package/dist/owners.js +97 -0
  20. package/dist/paths.js +76 -0
  21. package/dist/project.js +43 -0
  22. package/dist/query.js +92 -0
  23. package/dist/render.js +31 -0
  24. package/dist/report/concepts.js +37 -0
  25. package/dist/report/findings.js +73 -0
  26. package/dist/report/format.js +16 -0
  27. package/dist/report/sections.js +61 -0
  28. package/dist/report/style.js +77 -0
  29. package/dist/report/timeline.js +91 -0
  30. package/dist/report/week.js +36 -0
  31. package/dist/schema.js +65 -0
  32. package/dist/skills.js +41 -0
  33. package/dist/store.js +51 -0
  34. package/docs/design.md +106 -0
  35. package/docs/learn.zh-TW.md +33 -0
  36. package/docs/schema.md +68 -0
  37. package/package.json +56 -4
  38. package/src/aggregate.ts +204 -0
  39. package/src/build.ts +257 -0
  40. package/src/changes.ts +178 -0
  41. package/src/cli.ts +89 -0
  42. package/src/coverage.ts +44 -0
  43. package/src/detectors.ts +182 -0
  44. package/src/extract/file.ts +46 -0
  45. package/src/extract/run.ts +198 -0
  46. package/src/extract/session.ts +430 -0
  47. package/src/extract/worker.ts +12 -0
  48. package/src/index.ts +160 -0
  49. package/src/meta.ts +259 -0
  50. package/src/model.ts +346 -0
  51. package/src/observer.ts +255 -0
  52. package/src/ops.ts +110 -0
  53. package/src/owners.ts +92 -0
  54. package/src/paths.ts +108 -0
  55. package/src/project.ts +43 -0
  56. package/src/query.ts +85 -0
  57. package/src/render.ts +63 -0
  58. package/src/report/concepts.ts +94 -0
  59. package/src/report/findings.ts +84 -0
  60. package/src/report/format.ts +24 -0
  61. package/src/report/sections.ts +188 -0
  62. package/src/report/style.ts +77 -0
  63. package/src/report/timeline.ts +143 -0
  64. package/src/report/week.ts +55 -0
  65. package/src/schema.ts +84 -0
  66. package/src/skills.ts +46 -0
  67. package/src/store.ts +49 -0
@@ -0,0 +1,143 @@
1
+ import type { ReportModel } from "../model.ts";
2
+ import { concepts, lesson } from "./concepts.ts";
3
+ import { finding, type Reading, readings, select, value, verdict } from "./findings.ts";
4
+ import { type Change, esc, type Lang, num, stamp, title, type Words, words } from "./format.ts";
5
+ import type { Week } from "./week.ts";
6
+
7
+ function card(c: Change, id: string, rs: Reading[], L: Words) {
8
+ const i = c.impact;
9
+ return `<article class="card"><p class="eyebrow"><time datetime="${esc(c.at)}">${esc(stamp(c.at))} UTC</time></p><h3>${
10
+ esc(title(c))
11
+ }</h3>${
12
+ rs.map((r) =>
13
+ `<div class="reading"><b>${esc(r.label)} ${value(r, "before")} → ${value(r, "after")}</b><small>${num(r.before?.n ?? 0)} → ${
14
+ num(r.after?.n ?? 0)
15
+ } ${r.unit}</small></div>`
16
+ ).join("")
17
+ }<p class="muted">${
18
+ rs[0].direction === rs[1].direction
19
+ ? L(`Both: ${rs[0].direction}.`, `兩項都${rs[0].direction}。`)
20
+ : rs.map((r) => `${r.label}:${r.direction}`).join(" · ")
21
+ }${i ? ` ${num(i.before.sessions)} → ${num(i.after.sessions)} ${L("sessions.", "段工作。")}` : ""}<br><span class="verdict">${
22
+ esc(verdict(c, rs, L))
23
+ }</span></p><a class="button" href="#${id}">${L("Change details", "看調整明細")} →</a></article>`;
24
+ }
25
+ function ruler(c: Change, last: string | null, L: Words) {
26
+ const i = c.impact!;
27
+ const cutoff = last && last > c.at && last < i.window.after.until ? last : null;
28
+ const points = [
29
+ [i.window.before.since, L("Before starts", "開始算調整前")],
30
+ [c.at, L("Change", "做了調整")],
31
+ ...(cutoff ? [[cutoff, L("Last extract", "資料截至這裡")]] : []),
32
+ [i.window.after.until, L("After window ends", "調整後期間結束")],
33
+ ];
34
+ return `<div class="ruler-head"><h2>${
35
+ L(`Compare ${i.window.days} days on each side`, `同一條規則,前後各看 ${i.window.days} 天`)
36
+ }</h2><small>${L("Grouped by start time · not to scale", "依工作開始時間分組 / 時間線不按比例繪製")}</small></div><ol class="ruler${
37
+ cutoff ? " partial" : ""
38
+ }">${points.map(([at, text]) => `<li><time>${esc(stamp(at))}</time><i></i><span>${text}</span></li>`).join("")}</ol>`;
39
+ }
40
+ function panel(c: Change, side: "before" | "after", rs: Reading[], period: string, L: Words) {
41
+ const i = c.impact!;
42
+ return `<article class="panel compare ${side}"><p class="eyebrow">${
43
+ side === "before" ? L("Before", "調整前") : L("After", "調整後")
44
+ } / ${esc(period)}</p><h3>${num(i[side].sessions)} ${L("sessions", "段工作")}</h3>${
45
+ rs.map((r) => {
46
+ const x = r[side];
47
+ const sample = x?.value != null
48
+ ? (r.key === "cost_per_session" ? `${num(x.n)} ${r.unit}` : `${num(Math.round(x.value * x.n))} / ${num(x.n)} ${r.unit}`)
49
+ : L("no eligible records", "沒有適用紀錄");
50
+ return `<div class="reading"><span>${esc(r.label)}</span><b>${value(r, side)} <small>(${sample})</small></b></div>`;
51
+ }).join("")
52
+ }</article>`;
53
+ }
54
+ function detail(c: Change, id: string, rs: Reading[], m: ReportModel, w: Week, lang: Lang, siblings: Change[]) {
55
+ const L = words(lang), i = c.impact, lessons = concepts(m, w, c, L);
56
+ const peers = siblings.filter((s) => s !== c);
57
+ const together = peers.length
58
+ ? L(
59
+ `Same commit: ${peers.map((s) => s.package ?? m.meta.changeKinds[s.kind][lang]).join(", ")}.`,
60
+ `同一次提交也調整了 ${peers.map((s) => s.package ?? m.meta.changeKinds[s.kind][lang]).join("、")}。`,
61
+ )
62
+ : "";
63
+ const primary = rs[0];
64
+ const age = (Date.parse(m.freshness.lastExtract ?? "") - Date.parse(c.at)) / 3600000;
65
+ const partial = i?.incomplete && age >= 0 && age < i.window.days * 24;
66
+ const ageText = age < 1 ? L("less than an hour", "不到一小時") : L(`about ${Math.floor(age)} hours`, `約 ${Math.floor(age)} 小時`);
67
+ const heading = partial ? L(`Only ${ageText} since the change: too early to tell`, `調整後${ageText},還看不出效果`) : verdict(c, rs, L);
68
+ const fullPeriod = L(`${i?.window.days} days`, `${i?.window.days} 天`);
69
+ const beforePeriod = i?.incomplete ? L(`Planned: ${fullPeriod}`, `原定 ${fullPeriod}`) : fullPeriod;
70
+ return `<section class="detail" id="${id}" tabindex="-1"><div class="hero"><a class="back" href="#timeline">← ${
71
+ L("Timeline", "回時間軸")
72
+ }</a><p class="eyebrow">${L("Architecture change", "架構調整明細")} / ${esc(stamp(c.at))} UTC</p><h2 class="hero-title">${
73
+ esc(heading)
74
+ }</h2><p class="deck">${esc(title(c))} ${esc(together)}</p>${
75
+ i
76
+ ? `<p class="deck">${esc(primary.label)}:${value(primary, "before")} → ${value(primary, "after")}。 ${esc(verdict(c, rs, L))}</p>`
77
+ : ""
78
+ }</div>
79
+ ${
80
+ i
81
+ ? `${ruler(c, m.freshness.lastExtract, L)}<p class="eyebrow">${L("Records side by side", "紀錄對照")}</p><h2>${
82
+ L("Compare the two groups", "比較兩個時段的工作")
83
+ }</h2><div class="pair">${panel(c, "before", rs, beforePeriod, L)}${
84
+ panel(c, "after", rs, partial ? ageText : fullPeriod, L)
85
+ }</div><p>${rs.map((r) => `${esc(r.label)}:${r.direction}`).join(" / ")}</p>`
86
+ : ""
87
+ }
88
+ <div class="notes-grid">${lesson(lessons.sample, L)}${lesson(lessons.confounding, L)}${
89
+ c.package === "pi-anchorloop" ? lesson(lessons.check, L) : ""
90
+ }</div><p class="muted">${esc(c.repo)} ${esc(c.sha)} ${esc(c.subject)}</p><a href="#timeline">← ${
91
+ L("Timeline", "回時間軸")
92
+ }</a></section>`;
93
+ }
94
+ export function timeline(m: ReportModel, w: Week, lang: Lang) {
95
+ const L = words(lang), { all, lead, highlighted, folded } = select(m);
96
+ const ids = new Map(all.map((c, i) => [c, `change-${i + 1}`]));
97
+ const metrics = new Map(all.map((c) => [c, readings(c, m, lang)]));
98
+ const byDay = new Map<string, Change[]>(), byCommit = new Map<string, Change[]>();
99
+ for (const c of folded) {
100
+ const d = c.at.slice(0, 10);
101
+ if (!byDay.has(d)) byDay.set(d, []);
102
+ byDay.get(d)!.push(c);
103
+ }
104
+ for (const c of all) {
105
+ if (c.sha) {
106
+ const key = `${c.repo}/${c.sha}`;
107
+ if (!byCommit.has(key)) byCommit.set(key, []);
108
+ byCommit.get(key)!.push(c);
109
+ }
110
+ }
111
+ const headline = lead
112
+ ? finding(lead, metrics.get(lead)!, L)
113
+ : all.length
114
+ ? L("Not enough sessions to compare changes yet", "這批調整的工作段數還不夠比較")
115
+ : L("No changes recorded in this period", "這段期間沒有調整紀錄");
116
+ const reason = lead?.impact;
117
+ const trust = lead && reason?.incomplete && reason.confounded && !reason.smallSample
118
+ ? L(
119
+ `There were ${
120
+ num(reason.confounded)
121
+ } other changes, and one side has less than ${reason.window.days} days of data. We cannot credit this change alone.`,
122
+ `同期還有 ${num(reason.confounded)} 筆別的調整,一側的資料也未滿 ${reason.window.days} 天;目前不能把差異歸給這次調整。`,
123
+ )
124
+ : lead
125
+ ? verdict(lead, metrics.get(lead)!, L)
126
+ : L(
127
+ `There are ${num(m.totals.sessions)} sessions in this report, but no eligible comparison.`,
128
+ `報表收錄 ${num(m.totals.sessions)} 段工作,目前沒有適合放在首頁的比較。`,
129
+ );
130
+ return {
131
+ lead,
132
+ headline,
133
+ trust,
134
+ count: highlighted.length,
135
+ cards: highlighted.map((c) => card(c, ids.get(c)!, metrics.get(c)!, L)).join(""),
136
+ archive: [...byDay].map(([day, list]) =>
137
+ `<details class="day"><summary>${esc(day)} / ${num(list.length)} ${L("changes", "筆調整")}</summary><ul>${
138
+ list.map((c) => `<li><time>${esc(c.at.slice(11, 16))}</time> <a href="#${ids.get(c)}">${esc(title(c))}</a></li>`).join("")
139
+ }</ul></details>`
140
+ ).join(""),
141
+ details: all.map((c) => detail(c, ids.get(c)!, metrics.get(c)!, m, w, lang, byCommit.get(`${c.repo}/${c.sha}`) ?? [])).join(""),
142
+ };
143
+ }
@@ -0,0 +1,55 @@
1
+ import type { ReportModel } from "../model.ts";
2
+ import { esc, num, type Words } from "./format.ts";
3
+
4
+ /** Last seven calendar days ending on the last complete UTC day in the selected period. */
5
+ export function week(m: ReportModel) {
6
+ const last = m.freshness.lastExtract?.slice(0, 10);
7
+ if (!last || !m.window.until || !m.window.since) return [];
8
+ const end = Math.min(Date.parse(last) - 86400000, Date.parse(m.window.until));
9
+ const rows = [];
10
+ for (let t = Math.max(end - 6 * 86400000, Date.parse(m.window.since)); t <= end; t += 86400000) {
11
+ const day = new Date(t).toISOString().slice(0, 10), i = m.series.days.indexOf(day);
12
+ rows.push({
13
+ day,
14
+ sessions: m.series.sessions[i] ?? 0,
15
+ calls: m.series.toolCalls[i] ?? 0,
16
+ loads: m.series.skillLoads[i] ?? 0,
17
+ changes: m.changes.filter((c) => c.at.startsWith(day)).length,
18
+ });
19
+ }
20
+ return rows;
21
+ }
22
+ export type Week = ReturnType<typeof week>;
23
+ export function workload(rows: Week, L: Words) {
24
+ const heading = `<h2>${L("This week’s workload", "這週的工作量")}</h2>`;
25
+ if (!rows.length) return `<div class="panel">${heading}<p>${L("No complete recorded day yet.", "尚無完整一天的紀錄。")}</p></div>`;
26
+ const total = (key: "sessions" | "calls" | "loads") => num(rows.reduce((n, r) => n + r[key], 0));
27
+ const max = Math.max(1, ...rows.map((r) => r.sessions));
28
+ const points = rows.map((r, i) => [5 + i * 348 / Math.max(1, rows.length - 1), 89 - 64 * r.sessions / max]);
29
+ const line = points.map((p) => p.join(",")).join(" ");
30
+ const md = (d: string) => d.slice(5).replace("-", ".");
31
+ const desc = rows.map((r) => `${r.day}: ${num(r.sessions)} ${L("sessions", "段工作")} · ${r.changes} ${L("changes", "筆調整")}`).join(
32
+ "; ",
33
+ );
34
+ return `<div class="panel workload">${heading}<p class="muted">${md(rows[0].day)}–${md(rows.at(-1)!.day)} / ${
35
+ L("Volume is not quality", "多寡不代表好壞")
36
+ }</p><h3>${total("sessions")} ${L("sessions", "段工作")}</h3><p class="muted">${
37
+ L("Sessions per day · dashes mark changes", "每日工作段數 · 虛線表示當天有調整")
38
+ }</p>
39
+ <svg role="img" aria-label="${esc(desc)}" viewBox="0 0 358 96"><polygon points="5,89 ${line} ${
40
+ points.at(-1)![0]
41
+ },89" class="area"/><polyline points="${line}" class="trend"/>${
42
+ points.map(([x, y], i) =>
43
+ rows[i].changes
44
+ ? `<path d="M${x} 12V89" class="marker"/><circle cx="${x}" cy="${y}" r="3.5" class="dot"><title>${esc(rows[i].day)}: ${
45
+ rows[i].changes
46
+ } ${L("changes", "筆調整")}</title></circle>`
47
+ : ""
48
+ ).join("")
49
+ }</svg>
50
+ <div class="ends"><span>${md(rows[0].day)} ${num(rows[0].sessions)}</span><span>${md(rows.at(-1)!.day)} ${
51
+ num(rows.at(-1)!.sessions)
52
+ }</span></div><p class="footline">${L("Tool calls", "工具呼叫")} ${total("calls")} / ${L("Skill loads", "讀取技能")} ${
53
+ total("loads")
54
+ }</p></div>`;
55
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The one record shape (docs/schema.md): one JSON object per line, OpenTelemetry GenAI names where they exist,
3
+ * `pi.*` for pi facts, `anchorloop.*` for process facts, `eval.*` for evaluation metadata.
4
+ *
5
+ * Privacy is enforced here: every string attribute must look like a name (no spaces, no newlines, bounded length).
6
+ * Anything else is replaced by "redacted", so free text from a transcript cannot reach a record by accident.
7
+ */
8
+ import { createHash } from "node:crypto";
9
+
10
+ export const SCHEMA_VERSION = 1;
11
+
12
+ export type Source = "backfill" | "live";
13
+ export type AttrValue = string | number | boolean | string[];
14
+ export type Attrs = Record<string, AttrValue | undefined>;
15
+
16
+ export interface EvalRecord {
17
+ schema_version: number;
18
+ /** OTel span or event name, e.g. `execute_tool`, `invoke_agent`, `gen_ai.evaluation.result`. */
19
+ name: string;
20
+ kind: "span" | "event";
21
+ /** Start (span) or occurrence (event), ISO 8601 UTC. */
22
+ ts: string;
23
+ end_ts?: string;
24
+ duration_ms?: number;
25
+ /** One trace per user prompt. */
26
+ trace_id?: string;
27
+ span_id?: string;
28
+ source: Source;
29
+ attrs: Record<string, AttrValue>;
30
+ }
31
+
32
+ const NAME = /^[\p{L}\p{N}_@./:+#=|-]{0,160}$/u;
33
+
34
+ /** A string attribute that passes the name check, else "redacted". */
35
+ export function safeName(value: unknown): string {
36
+ if (typeof value !== "string") return "unknown";
37
+ return NAME.test(value) ? value : "redacted";
38
+ }
39
+
40
+ function clean(attrs: Attrs): Record<string, AttrValue> {
41
+ const out: Record<string, AttrValue> = {};
42
+ for (const [key, value] of Object.entries(attrs)) {
43
+ if (value === undefined) continue;
44
+ if (typeof value === "string") out[key] = safeName(value);
45
+ else if (Array.isArray(value)) out[key] = value.slice(0, 200).map(safeName);
46
+ else if (typeof value === "number") {
47
+ if (Number.isFinite(value)) out[key] = value;
48
+ } else out[key] = value;
49
+ }
50
+ return out;
51
+ }
52
+
53
+ export function record(fields: Omit<EvalRecord, "schema_version" | "attrs"> & { attrs: Attrs }): EvalRecord {
54
+ const out: EvalRecord = { schema_version: SCHEMA_VERSION, name: safeName(fields.name), kind: fields.kind, ts: fields.ts, source: fields.source, attrs: clean(fields.attrs) };
55
+ if (fields.end_ts) out.end_ts = fields.end_ts;
56
+ if (typeof fields.duration_ms === "number" && Number.isFinite(fields.duration_ms)) out.duration_ms = Math.max(0, Math.round(fields.duration_ms));
57
+ if (fields.trace_id) out.trace_id = fields.trace_id;
58
+ if (fields.span_id) out.span_id = fields.span_id;
59
+ return out;
60
+ }
61
+
62
+ const hex = (text: string, length: number) => createHash("sha1").update(text).digest("hex").slice(0, length);
63
+ /** 32-hex trace id, stable for a session and the entry that opened the prompt. */
64
+ export const traceId = (sessionId: string, anchor: string) => hex(`trace:${sessionId}:${anchor}`, 32);
65
+ /** 16-hex span id, stable across re-extraction. */
66
+ export const spanId = (sessionId: string, anchor: string) => hex(`span:${sessionId}:${anchor}`, 16);
67
+ export const fileKey = (path: string) => hex(`file:${path}`, 20);
68
+
69
+ /** Record names this package writes. */
70
+ export const NAMES = {
71
+ session: "pi.session",
72
+ prompt: "invoke_agent",
73
+ tool: "execute_tool",
74
+ skill: "pi.skill.load",
75
+ monitor: "pi.monitor",
76
+ notice: "anchorloop.close_guard.notice",
77
+ evaluation: "gen_ai.evaluation.result",
78
+ tools: "pi.tools.snapshot",
79
+ skills: "pi.skills.available",
80
+ compaction: "pi.compaction",
81
+ } as const;
82
+
83
+ export type SkillTrigger = "read" | "slash" | "declared" | "bash";
84
+ export type Label = "pass" | "fail" | "na";
package/src/skills.ts ADDED
@@ -0,0 +1,46 @@
1
+ /** Recognising skill loads, and listing the skills pi offers. */
2
+ import { posix } from "node:path";
3
+
4
+ const named = (name: string | undefined) => !!name && name !== "." && name !== "..";
5
+ export interface SkillHit {
6
+ skill: string;
7
+ /** Skill-relative path of a file other than SKILL.md (a playbook, reference, script). */
8
+ resource?: string;
9
+ }
10
+
11
+ /** A read of `<dir>/SKILL.md` loads skill `<dir>`; a read under `skills/<name>/` reads one of its resources. */
12
+ export function skillFromPath(path: unknown): SkillHit | undefined {
13
+ if (typeof path !== "string" || !path) return undefined;
14
+ const normal = posix.normalize(path.replace(/\\/g, "/"));
15
+ const load = normal.match(/(?:^|\/)([^/]+)\/SKILL\.md$/);
16
+ if (load) return named(load[1]) ? { skill: load[1] } : undefined;
17
+ const resource = normal.match(/(?:^|\/)skills\/([^/]+)\/(.+)$/);
18
+ if (resource && named(resource[1]) && !resource[2].endsWith("/")) return { skill: resource[1], resource: resource[2] };
19
+ return undefined;
20
+ }
21
+
22
+ /**
23
+ * The skill a shell command prints when the whole command is one read of one SKILL.md
24
+ * (`cat`, `head`, `bat`, `less`, `sed -n '…p'`, optionally after `cd <dir> &&`). Searches, edits, globs and
25
+ * bulk listings mention SKILL.md without loading it, so they do not count.
26
+ */
27
+ const PRINT = /^(?:cd\s+\S+\s*&&\s*)?(?:cat|bat|less|head(?:\s+-n)?(?:\s+-?\d+)?|sed\s+-n\s+'[\d,$]*p')\s+['"]?([^\s'";|&*?$]+)\/SKILL\.md['"]?\s*$/;
28
+
29
+ export function skillsFromCommand(command: unknown): string[] {
30
+ if (typeof command !== "string" || !command.includes("SKILL.md")) return [];
31
+ const m = command.trim().match(PRINT);
32
+ const name = m?.[1].split("/").at(-1);
33
+ return name && /^[A-Za-z0-9][\w.-]*$/.test(name) ? [name] : [];
34
+ }
35
+
36
+ /** Skill names in `<skill name="x" ...>` blocks (a `/skill:` expansion or a declared-skills message). */
37
+ export function skillsFromBlocks(text: unknown): string[] {
38
+ if (typeof text !== "string" || !text.includes("<skill name=")) return [];
39
+ return [...text.matchAll(/<skill name="([^"]+)"/g)].map((m) => m[1]);
40
+ }
41
+
42
+ /** Names in the `<available_skills>` section of pi's system prompt. */
43
+ export function skillsFromCatalog(text: unknown): string[] {
44
+ if (typeof text !== "string") return [];
45
+ return [...text.matchAll(/<skill>\s*<name>([^<]+)<\/name>/g)].map((m) => m[1].trim());
46
+ }
package/src/store.ts ADDED
@@ -0,0 +1,49 @@
1
+ /** Appending live records, and reading record files back. */
2
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { dayOf } from "./paths.ts";
5
+ import type { EvalRecord } from "./schema.ts";
6
+
7
+ /** An appender that swallows write failures after reporting the first one through `warn`. */
8
+ export function liveWriter(eventsDir: string, warn: (message: string) => void, now: () => number = Date.now) {
9
+ let warned = false;
10
+ let made = false;
11
+ return (records: EvalRecord | EvalRecord[]): void => {
12
+ try {
13
+ if (!made) {
14
+ mkdirSync(eventsDir, { recursive: true });
15
+ made = true;
16
+ }
17
+ const list = Array.isArray(records) ? records : [records];
18
+ if (!list.length) return;
19
+ appendFileSync(join(eventsDir, `${dayOf(now())}.jsonl`), list.map((r) => `${JSON.stringify(r)}\n`).join(""));
20
+ } catch (error) {
21
+ if (!warned) {
22
+ warned = true;
23
+ warn(`pi-evals: cannot write records (${error instanceof Error ? error.message : String(error)}); later failures in this session stay silent.`);
24
+ }
25
+ }
26
+ };
27
+ }
28
+
29
+ /** Records in one JSONL file; malformed lines are skipped. */
30
+ export function readRecords(file: string): EvalRecord[] {
31
+ if (!existsSync(file)) return [];
32
+ const out: EvalRecord[] = [];
33
+ for (const line of readFileSync(file, "utf8").split("\n")) {
34
+ if (!line) continue;
35
+ try {
36
+ out.push(JSON.parse(line) as EvalRecord);
37
+ } catch {}
38
+ }
39
+ return out;
40
+ }
41
+
42
+ /** Live record files, oldest first. */
43
+ export function liveFiles(eventsDir: string): string[] {
44
+ if (!existsSync(eventsDir)) return [];
45
+ return readdirSync(eventsDir)
46
+ .filter((name) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(name))
47
+ .sort()
48
+ .map((name) => join(eventsDir, name));
49
+ }