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