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,170 @@
1
+ /**
2
+ * The change timeline: architecture changes the boss makes, from git history (read-only `git log`), version
3
+ * changes seen in live tool-owner snapshots, and manual marks (`/evals mark`).
4
+ */
5
+ import { spawnSync } from "node:child_process";
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { basename, dirname } from "node:path";
8
+ const PIN_FILE = "scripts/pi_root/pins.py";
9
+ /** Which kind of architecture change a repository path is, if any. */
10
+ export function classifyPath(path) {
11
+ if (path === PIN_FILE)
12
+ return "pin";
13
+ if (/(^|\/)herdr-agents-models[^/]*\.json$/.test(path) || /^pi\/models\.json$/.test(path))
14
+ return "model-routing";
15
+ if (/^rules\//.test(path) || /^pi\/AGENTS[^/]*\.md(\.in)?$/.test(path))
16
+ return "rule";
17
+ if (/^agents\//.test(path))
18
+ return "agent-role";
19
+ if (/^skills\//.test(path) || path === "overlay.json")
20
+ return "skill";
21
+ return undefined;
22
+ }
23
+ const SPEC = /npm:((?:@[\w.-]+\/)?[\w.-]+)@([\w.+-]+)|git:github\.com\/[\w.-]+\/([\w.-]+)@([0-9a-f]{7,40})/g;
24
+ /** Package versions named on one side of a diff. */
25
+ function specs(lines) {
26
+ const out = new Map();
27
+ for (const line of lines) {
28
+ for (const m of line.matchAll(SPEC)) {
29
+ if (m[1])
30
+ out.set(m[1], m[2]);
31
+ else if (m[3])
32
+ out.set(m[3], m[4].slice(0, 7));
33
+ }
34
+ }
35
+ return out;
36
+ }
37
+ /** Pin changes in one commit's `-U0` diff of pins.py. */
38
+ export function pinChanges(diff) {
39
+ const removed = specs(diff.split("\n").filter((l) => l.startsWith("-") && !l.startsWith("---")));
40
+ const added = specs(diff.split("\n").filter((l) => l.startsWith("+") && !l.startsWith("+++")));
41
+ const out = [];
42
+ for (const [name, to] of added)
43
+ if (removed.get(name) !== to)
44
+ out.push({ package: name, from: removed.get(name), to });
45
+ for (const [name, from] of removed)
46
+ if (!added.has(name))
47
+ out.push({ package: name, from });
48
+ return out;
49
+ }
50
+ function git(repo, args) {
51
+ const res = spawnSync("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 256 << 20 });
52
+ if (res.status !== 0)
53
+ throw new Error(`git ${args[0]} in ${repo} failed: ${res.stderr.trim()}`);
54
+ return res.stdout;
55
+ }
56
+ /** Changes from one repository's history. A missing repository yields none. */
57
+ export function gitChanges(repo) {
58
+ if (!existsSync(repo))
59
+ return [];
60
+ const name = basename(repo);
61
+ const out = [];
62
+ const log = git(repo, ["log", "--format=%x1e%H%x1f%cI%x1f%s", "--name-only", "--no-merges"]);
63
+ for (const block of log.split("\x1e").slice(1)) {
64
+ const [head, ...files] = block.split("\n");
65
+ const [sha, at, subject] = head.split("\x1f");
66
+ const kinds = new Set(files.map((f) => f.trim()).filter(Boolean).map(classifyPath).filter((k) => k && k !== "pin"));
67
+ for (const kind of kinds)
68
+ out.push({ at: new Date(at).toISOString(), kind: kind, subject, sha: sha.slice(0, 12), repo: name, source: "git" });
69
+ }
70
+ if (existsSync(`${repo}/${PIN_FILE}`) || git(repo, ["log", "-1", "--format=%H", "--", PIN_FILE]).trim()) {
71
+ const pins = git(repo, ["log", "-p", "-U0", "--no-merges", "--format=%x1e%H%x1f%cI%x1f%s", "--", PIN_FILE]);
72
+ for (const block of pins.split("\x1e").slice(1)) {
73
+ const nl = block.indexOf("\n");
74
+ const [sha, at, subject] = block.slice(0, nl).split("\x1f");
75
+ for (const change of pinChanges(block.slice(nl + 1))) {
76
+ out.push({ at: new Date(at).toISOString(), kind: "pin", subject, ...change, sha: sha.slice(0, 12), repo: name, source: "git" });
77
+ }
78
+ }
79
+ }
80
+ return out;
81
+ }
82
+ /** Version changes between consecutive live tool-owner snapshots, per package. */
83
+ export function liveChanges(snapshots) {
84
+ const last = new Map();
85
+ const out = [];
86
+ for (const rec of [...snapshots].sort((a, b) => a.ts.localeCompare(b.ts))) {
87
+ const tools = rec.attrs["pi.tools"];
88
+ if (!Array.isArray(tools))
89
+ continue;
90
+ const versions = new Map();
91
+ for (const entry of tools) {
92
+ const owner = entry.slice(entry.indexOf("=") + 1);
93
+ const at = owner.lastIndexOf("@");
94
+ if (at > 0)
95
+ versions.set(owner.slice(0, at), owner.slice(at + 1));
96
+ }
97
+ for (const [pkg, version] of versions) {
98
+ const before = last.get(pkg);
99
+ if (before && before !== version)
100
+ out.push({ at: rec.ts, kind: "pin", subject: `${pkg} ${before} → ${version} (seen live)`, package: pkg, from: before, to: version, source: "live" });
101
+ last.set(pkg, version);
102
+ }
103
+ }
104
+ return out;
105
+ }
106
+ export function readMarks(file) {
107
+ if (!existsSync(file))
108
+ return [];
109
+ return readFileSync(file, "utf8")
110
+ .split("\n")
111
+ .filter(Boolean)
112
+ .flatMap((line) => {
113
+ try {
114
+ const m = JSON.parse(line);
115
+ return [{ at: m.at, kind: "manual", subject: m.text, source: "mark" }];
116
+ }
117
+ catch {
118
+ return [];
119
+ }
120
+ });
121
+ }
122
+ export function addMark(file, text, at = new Date()) {
123
+ mkdirSync(dirname(file), { recursive: true });
124
+ appendFileSync(file, `${JSON.stringify({ at: at.toISOString(), text })}\n`);
125
+ return { at: at.toISOString(), kind: "manual", subject: text, source: "mark" };
126
+ }
127
+ /**
128
+ * All changes, oldest first; a live version change already pinned in git within three days before is dropped.
129
+ * A repository whose history cannot be read is reported through `errors` and skipped.
130
+ */
131
+ export function buildChanges(repos, snapshots, marksFile, errors = []) {
132
+ const fromGit = repos.flatMap((repo) => {
133
+ try {
134
+ return gitChanges(repo);
135
+ }
136
+ catch (error) {
137
+ errors.push(error instanceof Error ? error.message : String(error));
138
+ return [];
139
+ }
140
+ });
141
+ const live = liveChanges(snapshots).filter((c) => !fromGit.some((g) => g.kind === "pin" && g.package === c.package && g.to === c.to && Date.parse(c.at) - Date.parse(g.at) < 3 * 86_400_000 && Date.parse(c.at) >= Date.parse(g.at)));
142
+ return [...fromGit, ...live, ...readMarks(marksFile)].sort((a, b) => a.at.localeCompare(b.at));
143
+ }
144
+ export function writeChanges(file, changes) {
145
+ mkdirSync(dirname(file), { recursive: true });
146
+ const tmp = `${file}.${process.pid}.tmp`;
147
+ writeFileSync(tmp, changes.map((c) => `${JSON.stringify(c)}\n`).join(""));
148
+ renameSync(tmp, file);
149
+ }
150
+ export function readChanges(file) {
151
+ if (!existsSync(file))
152
+ return [];
153
+ return readFileSync(file, "utf8")
154
+ .split("\n")
155
+ .filter(Boolean)
156
+ .map((line) => JSON.parse(line));
157
+ }
158
+ /** The version of a package in effect at an ISO time: the newest pin change at or before it (changes oldest first). */
159
+ export function versionAt(changes, pkg, at) {
160
+ const names = Array.isArray(pkg) ? pkg : [pkg];
161
+ let version;
162
+ for (const c of changes) {
163
+ if (c.kind !== "pin" || !c.package || !names.includes(c.package))
164
+ continue;
165
+ if (c.at > at)
166
+ break;
167
+ version = c.to ?? version;
168
+ }
169
+ return version;
170
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env node
2
+ /** Thin CLI over the same operations as `/evals`. */
3
+ import { context, mark, runExtract, runReport, statusText } from "./ops.js";
4
+ import { query, VIEWS } from "./query.js";
5
+ const USAGE = `usage:
6
+ pi-evals extract [--root <dir>]... [--workers <n>] [--json]
7
+ pi-evals report [--out <dir>] [--since YYYY-MM-DD] [--project <key>] [--lang zh|en]
8
+ pi-evals status
9
+ pi-evals query <${VIEWS.join("|")}> [--since YYYY-MM-DD] [--project <key>]
10
+ pi-evals mark <note>`;
11
+ function flag(args, name) {
12
+ const i = args.indexOf(name);
13
+ return i >= 0 ? args[i + 1] : undefined;
14
+ }
15
+ function flags(args, name) {
16
+ return args.flatMap((a, i) => (a === name && args[i + 1] ? [args[i + 1]] : []));
17
+ }
18
+ async function main(argv) {
19
+ const [cmd, ...args] = argv;
20
+ const settingsError = context().settings.error;
21
+ if (settingsError)
22
+ process.stderr.write(`pi-evals settings: ${settingsError}\n`);
23
+ if (cmd === "extract") {
24
+ const json = args.includes("--json");
25
+ const workers = flag(args, "--workers");
26
+ let lastPrint = 0;
27
+ const status = await runExtract({
28
+ extraRoots: flags(args, "--root"),
29
+ workers: workers === undefined ? undefined : Number(workers),
30
+ onProgress: (done, total, bytes) => {
31
+ const now = Date.now();
32
+ if (now - lastPrint < 500 && done !== total)
33
+ return;
34
+ lastPrint = now;
35
+ if (json)
36
+ process.stdout.write(`${JSON.stringify({ progress: { done, total, bytes } })}\n`);
37
+ else
38
+ process.stderr.write(`\rextract ${done}/${total} files, ${(bytes / 1e9).toFixed(2)} GB `);
39
+ },
40
+ });
41
+ if (json)
42
+ process.stdout.write(`${JSON.stringify({ result: status })}\n`);
43
+ else {
44
+ process.stderr.write("\n");
45
+ const s = status.stats;
46
+ console.log(`read ${s.changed} of ${s.files} files (${(s.bytes / 1e9).toFixed(2)} GB) in ${(s.ms / 1000).toFixed(1)} s, ${s.mbPerSec} MB/s; ${s.records} records; ${s.failed} failed`);
47
+ console.log(`sessions ${status.sessions.backfill} indexed (subagent ${status.sessions.subagent}, linked ${status.sessions.linked}), live-only ${status.sessions.live}; changes ${status.changes}`);
48
+ }
49
+ return status.stats.failed ? 2 : 0;
50
+ }
51
+ if (cmd === "report") {
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 });
54
+ if (!out) {
55
+ console.error("nothing extracted yet: run pi-evals extract");
56
+ return 1;
57
+ }
58
+ console.log(out.html);
59
+ console.log(out.json);
60
+ return 0;
61
+ }
62
+ if (cmd === "status") {
63
+ console.log(statusText());
64
+ return 0;
65
+ }
66
+ if (cmd === "query") {
67
+ const view = args[0];
68
+ if (!VIEWS.includes(view)) {
69
+ console.error(USAGE);
70
+ return 1;
71
+ }
72
+ console.log(query(view, { since: flag(args, "--since"), project: flag(args, "--project") }));
73
+ return 0;
74
+ }
75
+ if (cmd === "mark" && args.length) {
76
+ const change = mark(args.join(" "));
77
+ console.log(`marked ${change.at}`);
78
+ return 0;
79
+ }
80
+ console.error(USAGE);
81
+ return cmd === "help" || cmd === "--help" ? 0 : 1;
82
+ }
83
+ main(process.argv.slice(2)).then((code) => process.exit(code), (error) => {
84
+ console.error(error instanceof Error ? error.stack : error);
85
+ process.exit(1);
86
+ });
@@ -0,0 +1,34 @@
1
+ import { listSessionFiles } from "./extract/run.js";
2
+ export function coverage(roots, checkpoint, cutDays, now = Date.now()) {
3
+ const cutoff = now - cutDays * 86_400_000;
4
+ const files = listSessionFiles(roots);
5
+ const result = {
6
+ cutDays,
7
+ cutoff: new Date(cutoff).toISOString(),
8
+ old: { files: 0, bytes: 0 },
9
+ indexed: { files: 0, bytes: 0 },
10
+ notIndexed: { files: 0, bytes: 0 },
11
+ all: { files: files.length, bytes: 0, indexedFiles: 0 },
12
+ retainedGone: 0,
13
+ };
14
+ const present = new Set();
15
+ for (const f of files) {
16
+ present.add(f.path);
17
+ result.all.bytes += f.size;
18
+ const known = checkpoint.files[f.path];
19
+ const fresh = !!known && known.size === f.size && known.mtimeMs === f.mtimeMs;
20
+ if (fresh)
21
+ result.all.indexedFiles += 1;
22
+ if (f.mtimeMs >= cutoff)
23
+ continue;
24
+ result.old.files += 1;
25
+ result.old.bytes += f.size;
26
+ const side = fresh ? result.indexed : result.notIndexed;
27
+ side.files += 1;
28
+ side.bytes += f.size;
29
+ }
30
+ for (const path of Object.keys(checkpoint.files))
31
+ if (!present.has(path))
32
+ result.retainedGone += 1;
33
+ return result;
34
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * anchorloop 3.0.0 (one anchor rule and the close guard) reached this setup when weihung-basic-agent pinned it
3
+ * (commit 9f72366, 2026-11-23T10:51:07Z). Sessions that started earlier are out of scope.
4
+ */
5
+ export const ERA_START = "2026-11-23T10:51:07.000Z";
6
+ export const DETECTORS = ["anchor_before_first_edit", "check_after_last_edit", "todo_evidence", "close_guard_quiet"];
7
+ const NOTICE_TYPE = "anchorloop-close-guard";
8
+ const MAX_RUNS = 5000;
9
+ export function noticeKind(text) {
10
+ if (typeof text !== "string")
11
+ return "other";
12
+ if (/no `Anchor: <check>` line was stated/.test(text))
13
+ return "no_anchor";
14
+ if (/no passing run of /.test(text))
15
+ return "no_passing_run";
16
+ if (/use todo update on #\d+ to append/.test(text))
17
+ return "evidence_handoff";
18
+ return "other";
19
+ }
20
+ const squeeze = (text) => text.replace(/[ \t]+/g, " ").trim();
21
+ function commandsOf(text, bare) {
22
+ const ticked = [...text.matchAll(/`([^`\n]+)`/g)].map((m) => squeeze(m[1])).filter(Boolean);
23
+ return ticked.length || !bare ? ticked : [squeeze(text)].filter(Boolean);
24
+ }
25
+ function anchorLine(text) {
26
+ const lines = [...text.matchAll(/^[ \t>*_-]*(?:reality )?anchor[*_]*:[*_]*\s*(.+)$/gim)];
27
+ return lines.at(-1)?.[1];
28
+ }
29
+ export class ProcessTracker {
30
+ seq = 0;
31
+ calls = new Map();
32
+ runs = [];
33
+ anchor;
34
+ anchoredBeforeChange = false;
35
+ firstChange = -1;
36
+ lastChange = -1;
37
+ tasks;
38
+ sawUser = false;
39
+ briefAnchor = false;
40
+ notices = new Map();
41
+ /** Notice kinds seen so far, for `anchorloop.close_guard.notice` records. */
42
+ feed(raw) {
43
+ const entry = raw;
44
+ const seq = ++this.seq;
45
+ if (entry?.type === "custom" && entry.customType === "todo/v1" && entry.data?.v === 1 && Array.isArray(entry.data.tasks)) {
46
+ this.tasks = entry.data.tasks;
47
+ return undefined;
48
+ }
49
+ if (entry?.type === "custom_message" && entry.customType === NOTICE_TYPE) {
50
+ const kind = noticeKind(entry.content);
51
+ this.notices.set(kind, (this.notices.get(kind) ?? 0) + 1);
52
+ return kind;
53
+ }
54
+ const message = entry?.message;
55
+ if (entry?.type !== "message" || !message)
56
+ return undefined;
57
+ if (message.role === "user" && !this.sawUser) {
58
+ this.sawUser = true;
59
+ const text = Array.isArray(message.content) ? message.content.map((p) => (p?.type === "text" ? (p.text ?? "") : "")).join("\n") : String(message.content ?? "");
60
+ this.briefAnchor = anchorLine(text) !== undefined;
61
+ }
62
+ else if (message.role === "assistant" && Array.isArray(message.content)) {
63
+ for (const part of message.content) {
64
+ if (part?.type === "text" && typeof part.text === "string") {
65
+ const line = anchorLine(part.text);
66
+ if (line !== undefined)
67
+ this.setAnchor(commandsOf(line, false));
68
+ }
69
+ else if (part?.type === "toolCall" && typeof part.id === "string") {
70
+ const command = part.name === "bash" && typeof part.arguments?.command === "string" ? squeeze(part.arguments.command) : undefined;
71
+ this.calls.set(part.id, { name: String(part.name), command });
72
+ if (part.name === "todo" && part.arguments) {
73
+ const batch = Array.isArray(part.arguments.tasks) ? part.arguments.tasks : [];
74
+ for (const item of [part.arguments, ...batch]) {
75
+ const meta = item?.metadata;
76
+ const value = [item?.anchor, meta?.anchor].find((v) => typeof v === "string" && v.trim());
77
+ if (value)
78
+ this.setAnchor(commandsOf(value, true));
79
+ }
80
+ }
81
+ }
82
+ }
83
+ }
84
+ else if (message.role === "toolResult" && typeof message.toolCallId === "string") {
85
+ const call = this.calls.get(message.toolCallId);
86
+ if (!call)
87
+ return undefined;
88
+ this.calls.delete(message.toolCallId);
89
+ const code = message.structuredContent?.exit_code;
90
+ const ok = typeof code === "number" ? code === 0 : message.isError !== true;
91
+ if ((call.name === "write" || call.name === "edit") && ok) {
92
+ if (this.firstChange < 0) {
93
+ this.firstChange = seq;
94
+ this.anchoredBeforeChange = this.anchor !== undefined;
95
+ }
96
+ this.lastChange = seq;
97
+ }
98
+ else if (call.name === "bash" && call.command) {
99
+ this.runs.push({ seq, command: call.command, ok });
100
+ if (this.runs.length > MAX_RUNS)
101
+ this.runs.splice(0, this.runs.length - MAX_RUNS);
102
+ }
103
+ }
104
+ return undefined;
105
+ }
106
+ setAnchor(commands) {
107
+ this.anchor = commands;
108
+ }
109
+ results(inScope) {
110
+ if (!inScope)
111
+ return DETECTORS_ALL.map((name) => ({ name, label: "na", explanation: "out_of_scope_pre_3.0" }));
112
+ return [this.anchorFirst(), this.checkAfter(), this.todoEvidence(), this.quiet()];
113
+ }
114
+ anchorFirst() {
115
+ const name = "anchor_before_first_edit";
116
+ if (this.firstChange < 0)
117
+ return { name, label: "na", explanation: "no_edit" };
118
+ if (this.anchoredBeforeChange)
119
+ return { name, label: "pass", explanation: "anchor_first" };
120
+ return { name, label: "fail", explanation: this.briefAnchor ? "anchor_only_in_brief" : "change_before_anchor" };
121
+ }
122
+ checkAfter() {
123
+ const name = "check_after_last_edit";
124
+ if (this.lastChange < 0)
125
+ return { name, label: "na", explanation: "no_edit" };
126
+ if (!this.anchor)
127
+ return { name, label: "na", explanation: "no_anchor" };
128
+ if (!this.anchor.length)
129
+ return { name, label: "na", explanation: "anchor_without_command" };
130
+ const green = this.anchor.every((command) => {
131
+ const last = this.runs.findLast((run) => run.command.includes(command));
132
+ return !!last && last.seq > this.lastChange && last.ok;
133
+ });
134
+ return green ? { name, label: "pass", explanation: "anchor_green" } : { name, label: "fail", explanation: "no_passing_run_after_change" };
135
+ }
136
+ todoEvidence() {
137
+ const name = "todo_evidence";
138
+ const done = (this.tasks ?? []).filter((t) => t?.status === "completed");
139
+ if (!done.length)
140
+ return { name, label: "na", explanation: "no_completed_task" };
141
+ const withEvidence = done.filter((t) => Array.isArray(t.evidence) && t.evidence.length > 0).length;
142
+ const value = withEvidence / done.length;
143
+ return { name, label: value === 1 ? "pass" : "fail", value, explanation: value === 1 ? "all_evidenced" : "completed_without_evidence" };
144
+ }
145
+ quiet() {
146
+ const name = "close_guard_quiet";
147
+ if (this.firstChange < 0)
148
+ return { name, label: "na", explanation: "no_edit" };
149
+ // An evidence hand-off asks the agent to record a run that passed; it is not a missing or failing check.
150
+ const top = [...this.notices].filter(([kind]) => kind !== "evidence_handoff").sort((a, b) => b[1] - a[1])[0];
151
+ return top ? { name, label: "fail", explanation: top[0] } : { name, label: "pass", explanation: "no_notice" };
152
+ }
153
+ }
154
+ const DETECTORS_ALL = [...DETECTORS];
@@ -0,0 +1,42 @@
1
+ /** Extracting one session file: stream its lines, write its records next to the index, return its summary. */
2
+ import { createReadStream, mkdirSync, openSync, renameSync, writeSync, closeSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { createInterface } from "node:readline";
5
+ import { SessionReader } from "./session.js";
6
+ /** Reads `path` (never writes it) and writes its records to `out` atomically. */
7
+ export async function extractFile(path, out, home) {
8
+ mkdirSync(dirname(out), { recursive: true });
9
+ const tmp = `${out}.${process.pid}.tmp`;
10
+ const fd = openSync(tmp, "w");
11
+ let buffer = [];
12
+ let count = 0;
13
+ const flush = () => {
14
+ if (buffer.length)
15
+ writeSync(fd, buffer.join(""));
16
+ buffer = [];
17
+ };
18
+ const emit = (r) => {
19
+ buffer.push(`${JSON.stringify(r)}\n`);
20
+ count += 1;
21
+ if (buffer.length >= 500)
22
+ flush();
23
+ };
24
+ try {
25
+ const reader = new SessionReader(path, home, emit);
26
+ const lines = createInterface({ input: createReadStream(path, { highWaterMark: 1 << 20 }), crlfDelay: Number.POSITIVE_INFINITY });
27
+ for await (const line of lines)
28
+ reader.feedLine(line);
29
+ const { summary, catalog } = reader.finish();
30
+ flush();
31
+ closeSync(fd);
32
+ renameSync(tmp, out);
33
+ return { summary, catalog, records: count };
34
+ }
35
+ catch (error) {
36
+ try {
37
+ closeSync(fd);
38
+ }
39
+ catch { }
40
+ throw error;
41
+ }
42
+ }
@@ -0,0 +1,149 @@
1
+ /** Incremental back-fill over session roots: only files whose size or mtime changed are read again. */
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
4
+ import { availableParallelism } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { Worker } from "node:worker_threads";
7
+ import { fileKey } from "../schema.js";
8
+ import { extractFile } from "./file.js";
9
+ /** Bump when extraction changes what it derives; a checkpoint from another version re-reads every file. */
10
+ export const EXTRACTOR_VERSION = 2;
11
+ export function loadCheckpoint(file) {
12
+ if (!existsSync(file))
13
+ return { v: 1, extractor: EXTRACTOR_VERSION, files: {}, catalogs: {} };
14
+ const raw = JSON.parse(readFileSync(file, "utf8"));
15
+ if (raw.v !== 1)
16
+ throw new Error(`pi-evals: unknown checkpoint version ${raw.v} in ${file}`);
17
+ return raw;
18
+ }
19
+ export function saveCheckpoint(file, checkpoint) {
20
+ mkdirSync(dirname(file), { recursive: true });
21
+ const tmp = `${file}.${process.pid}.tmp`;
22
+ writeFileSync(tmp, JSON.stringify(checkpoint));
23
+ renameSync(tmp, file);
24
+ }
25
+ /** Every `*.jsonl` under the roots (any depth), with size and mtime. Sidecars and missing roots are skipped. */
26
+ export function listSessionFiles(roots) {
27
+ const out = [];
28
+ const walk = (dir) => {
29
+ let entries;
30
+ try {
31
+ entries = readdirSync(dir, { withFileTypes: true });
32
+ }
33
+ catch {
34
+ return;
35
+ }
36
+ for (const entry of entries) {
37
+ const path = join(dir, entry.name);
38
+ if (entry.isDirectory())
39
+ walk(path);
40
+ else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
41
+ try {
42
+ const st = statSync(path);
43
+ out.push({ path, size: st.size, mtimeMs: Math.floor(st.mtimeMs) });
44
+ }
45
+ catch { }
46
+ }
47
+ }
48
+ };
49
+ for (const root of roots)
50
+ walk(root);
51
+ return out;
52
+ }
53
+ const monthOf = (path) => path.match(/(\d{4}-\d{2})-\d{2}T/)?.[1] ?? "unknown";
54
+ const workerUrl = () => new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url);
55
+ /** Runs `jobs` on a pool of worker threads, or in this thread when `workers` is 0. */
56
+ async function runPool(jobs, home, workers, onDone, signal) {
57
+ if (workers <= 0) {
58
+ for (const job of jobs) {
59
+ if (signal?.aborted)
60
+ return;
61
+ try {
62
+ onDone(job, await extractFile(job.path, job.out, home));
63
+ }
64
+ catch (error) {
65
+ onDone(job, undefined, error instanceof Error ? error.message : String(error));
66
+ }
67
+ }
68
+ return;
69
+ }
70
+ let next = 0;
71
+ const pool = Array.from({ length: Math.min(workers, jobs.length) }, () => new Worker(workerUrl()));
72
+ try {
73
+ await Promise.all(pool.map((worker) => new Promise((resolve, reject) => {
74
+ const pump = () => {
75
+ if (signal?.aborted || next >= jobs.length)
76
+ return resolve();
77
+ const id = next++;
78
+ worker.once("message", (msg) => {
79
+ onDone(jobs[id], msg.result, msg.error);
80
+ pump();
81
+ });
82
+ worker.postMessage({ id, ...jobs[id], home });
83
+ };
84
+ worker.once("error", reject);
85
+ pump();
86
+ })));
87
+ }
88
+ finally {
89
+ await Promise.all(pool.map((w) => w.terminate()));
90
+ }
91
+ }
92
+ export async function extract(options) {
93
+ const started = Date.now();
94
+ const checkpoint = loadCheckpoint(options.layout.checkpoint);
95
+ const files = listSessionFiles(options.roots);
96
+ const rereadAll = checkpoint.extractor !== EXTRACTOR_VERSION;
97
+ checkpoint.extractor = EXTRACTOR_VERSION;
98
+ const changed = files.filter((f) => {
99
+ const known = checkpoint.files[f.path];
100
+ if (rereadAll)
101
+ return true;
102
+ return !known || known.size !== f.size || known.mtimeMs !== f.mtimeMs;
103
+ });
104
+ const stats = { files: files.length, changed: changed.length, failed: 0, bytes: 0, records: 0, ms: 0, errors: [] };
105
+ const byPath = new Map(changed.map((f) => [f.path, f]));
106
+ const jobs = changed
107
+ .sort((a, b) => a.size - b.size)
108
+ .map((f) => {
109
+ const key = fileKey(f.path);
110
+ const month = monthOf(f.path);
111
+ return { path: f.path, out: join(options.layout.records, month, `${key}.jsonl`) };
112
+ });
113
+ let done = 0;
114
+ let sinceSave = 0;
115
+ const workers = options.workers ?? Math.max(1, Math.min(8, availableParallelism() - 1));
116
+ options.onProgress?.(0, jobs.length, 0);
117
+ await runPool(jobs, options.home, jobs.length < 4 ? 0 : workers, (job, result, error) => {
118
+ const file = byPath.get(job.path);
119
+ done += 1;
120
+ if (file)
121
+ stats.bytes += file.size;
122
+ if (!result || !file) {
123
+ stats.failed += 1;
124
+ if (stats.errors.length < 20)
125
+ stats.errors.push(`${job.path}: ${error ?? "no result"}`);
126
+ }
127
+ else {
128
+ stats.records += result.records;
129
+ const key = fileKey(file.path);
130
+ checkpoint.files[file.path] = { size: file.size, mtimeMs: file.mtimeMs, key, month: monthOf(file.path), summary: result.summary };
131
+ if (result.catalog?.length) {
132
+ const hash = createHash("sha1").update(result.catalog.join("\n")).digest("hex").slice(0, 16);
133
+ result.summary.catalog = hash;
134
+ const seen = checkpoint.catalogs[hash];
135
+ if (!seen || seen.last < result.summary.start)
136
+ checkpoint.catalogs[hash] = { names: result.catalog, last: result.summary.start };
137
+ }
138
+ }
139
+ if (++sinceSave >= 1000) {
140
+ sinceSave = 0;
141
+ saveCheckpoint(options.layout.checkpoint, checkpoint);
142
+ }
143
+ options.onProgress?.(done, jobs.length, stats.bytes);
144
+ }, options.signal);
145
+ checkpoint.lastExtract = (options.now?.() ?? new Date()).toISOString();
146
+ saveCheckpoint(options.layout.checkpoint, checkpoint);
147
+ stats.ms = Date.now() - started;
148
+ return { stats, checkpoint };
149
+ }