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
package/CHANGELOG.md ADDED
@@ -0,0 +1,21 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - 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.
6
+ - Five short explanations and two self-check questions introduce the numbers in the report; see [the worked example](docs/learn.zh-TW.md).
7
+ - `/evals extract` uses two workers by default to leave memory for pi. Pass `--workers N` to override; the standalone CLI retains its CPU-based default.
8
+ - Use npm’s canonical bin path so the packed CLI installs as `pi-evals` without a publish correction.
9
+
10
+ ## 0.1.0
11
+
12
+ First release.
13
+
14
+ - One record shape with OpenTelemetry GenAI names (`execute_tool`, `invoke_agent`, `gen_ai.skill.name`, `gen_ai.evaluation.result`) plus `pi.*`, `anchorloop.*` and `eval.*`; strings must look like names or are stored as `redacted` ([docs/schema.md](docs/schema.md)).
15
+ - Back-fill of past sessions (`/evals extract`, `pi-evals extract`): streaming, worker threads, incremental by size and modification time, extra roots, subagents linked to their parents.
16
+ - Live observer: tool owners and versions, every finished tool call, skill loads, monitor lifecycles, ask-user answer source.
17
+ - Four anchorloop process checks per session from 2026-11-23 on.
18
+ - Change timeline from setup repositories' git history, live version changes and `/evals mark`, with before-and-after numbers per change.
19
+ - Index coverage of old session files, the gate for a later cleanup.
20
+ - ReportModel (`model.json`) with plain-language metadata in English and Traditional Chinese, and a plain static HTML report.
21
+ - `evals_query` tool: bounded summaries for agents.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wayne930242
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,117 @@
1
- # Temporary Holding Version
1
+ # pi-evals
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Records of how [pi](https://github.com/earendil-works/pi) agents use skills, packages, ask-user, monitors and subagents, and whether their work follows the anchorloop process rules.
4
+ It reads past session files once, keeps a small observer running for what those files do not hold, and builds a static HTML report.
5
+ Agents can read the same numbers through one tool, `evals_query`.
6
+
7
+ ## What it records
8
+
9
+ - **Skills**: loads per day and per project, how each was loaded (a read of its `SKILL.md`, a `/skill:` command, a subagent role's declared skills, a shell `cat` of the file), and the skills pi offers that no agent loaded.
10
+ - **Packages**: tool calls, errors and run time grouped by the package that registered each tool.
11
+ - **Ask-user**: questions asked, how long you took to answer, how many you dismissed, and whether the answer came from the terminal or a remote channel.
12
+ - **Monitors**: background jobs by outcome and duration.
13
+ - **Subagents**: launches by role and model, and their cost by role.
14
+ - **Process**: four checks of the anchorloop rules per session, for sessions started after anchorloop 3.0.0 was pinned (2026-11-23T10:51:07Z); see [docs/design.md](docs/design.md#process-detectors).
15
+ - **Cost**: model cost and tokens, and the cost of the sessions that loaded each skill.
16
+ - **Your changes**: package pins, model routing, rules, skills and agent roles from the git history of your setup repositories, version changes seen live, and notes you add with `/evals mark`, each with the same numbers in the days before and after.
17
+
18
+ ## Privacy
19
+
20
+ Records hold derived facts only: names (tools, skills, packages, models, roles, project keys), counts, durations, exit codes, outcomes, and token and cost numbers.
21
+ They never hold transcript text, tool arguments, file contents, commands, questions, or answers.
22
+ Every string written to a record must look like a name (no spaces, no line breaks, at most 160 characters), or it is stored as `redacted`.
23
+ A test plants a secret in every text field of a session and checks that it reaches no output file and no query result.
24
+
25
+ Everything stays on your machine, under `$XDG_STATE_HOME/pi-evals` (default `~/.local/state/pi-evals`).
26
+ Session files are only read, never written.
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ pi install npm:pi-evals
32
+ ```
33
+
34
+ Then run `/reload` or restart pi.
35
+ The observer loads in every session, subagents included.
36
+
37
+ ## Commands
38
+
39
+ | Command | What it does |
40
+ | --- | --- |
41
+ | `/evals` or `/evals status` | Record counts, the last extract, index coverage of old sessions, and the report path. |
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. |
44
+ | `/evals mark <note>` | Adds a note to the change timeline, e.g. `/evals mark workers moved to gpt-6.2-astra`. |
45
+
46
+ The same operations run from a shell, where extraction defaults to one fewer worker than available CPUs (at least one, at most eight).
47
+ On either surface, `--workers 0` reads the files sequentially without worker threads:
48
+
49
+ ```sh
50
+ 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 status
53
+ pi-evals query <view> [--since YYYY-MM-DD] [--project <key>]
54
+ pi-evals mark <note>
55
+ ```
56
+
57
+ ### The `evals_query` tool
58
+
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.
61
+ The tool never starts an extract.
62
+
63
+ ## The report
64
+
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.
67
+ 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
+ ### Reading the report
69
+
70
+ Start with the sentence above the timeline: it says what changed in the numbers; the next line tells you what limits the comparison.
71
+ Open a card to see which sessions started before and after the change.
72
+ 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
+ If the window is short, or other changes landed in the same period, do not credit a difference to the new version alone.
74
+
75
+ The sidebar shows workload for the last seven complete UTC dates, with markers on days you changed the setup.
76
+ The date disclosures keep the rest of the timeline available without putting hundreds of cards on the first screen.
77
+ 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
+
79
+ ## Settings
80
+
81
+ `$XDG_CONFIG_HOME/pi-evals/settings.json` (default `~/.config/pi-evals/settings.json`), all optional:
82
+
83
+ ```json
84
+ {
85
+ "extraRoots": ["/path/to/session-trash"],
86
+ "changeRepos": ["~/projects/weihung-basic-agent", "~/projects/weihung-agent-root"],
87
+ "coverageDays": 60,
88
+ "impactWindowDays": 7
89
+ }
90
+ ```
91
+
92
+ - `extraRoots`: more directories of session files to back-fill, such as a retention tool's trash. `PI_EVALS_ROOTS` (colon-separated) adds more.
93
+ - `changeRepos`: repositories whose `git log` feeds the change timeline. A leading `~` means your home directory.
94
+ - `coverageDays`: the age, in days without changes, at which a session file counts as old in the coverage figure.
95
+ - `impactWindowDays`: days on each side of a change in the before-and-after comparison.
96
+
97
+ `PI_EVALS_STATE_DIR` moves the state dir; `PI_CODING_AGENT_DIR` points at another pi agent dir.
98
+
99
+ ## Files
100
+
101
+ | Path under the state dir | Contents |
102
+ | --- | --- |
103
+ | `events/<YYYY-MM-DD>.jsonl` | Live observer records. |
104
+ | `index/records/<YYYY-MM>/<key>.jsonl` | Back-filled records, one file per session file. |
105
+ | `index/checkpoint.json` | Size, modification time and summary per session file. |
106
+ | `index/days.json` | Aggregates by day and project. |
107
+ | `index/sessions.json` | A few numbers per session with its start time, for splitting sessions at a change's time. |
108
+ | `index/session-evals.json` | Process check results per session, for joining your labels. |
109
+ | `changes.jsonl`, `marks.jsonl` | The change timeline and your notes. |
110
+ | `labels.jsonl` | Your labels, when you add them (a later phase): `{ "session_id", "evaluation_name", "label": "pass" \| "fail" }` per line. The report then shows how often you and the automatic checks agree. |
111
+ | `reports/report.html`, `reports/model.json` | The report. |
112
+
113
+ The record format is in [docs/schema.md](docs/schema.md); the decisions behind it are in [docs/design.md](docs/design.md).
114
+
115
+ ## License
116
+
117
+ MIT
@@ -0,0 +1,113 @@
1
+ /** Upper bounds (ms) of the ask-user wait buckets; the last bucket is open. */
2
+ export const ASK_BUCKETS = [10_000, 30_000, 60_000, 300_000, 1_800_000];
3
+ export function emptyDay() {
4
+ return {
5
+ sessions: 0,
6
+ subagentSessions: 0,
7
+ prompts: 0,
8
+ tools: {},
9
+ skills: {},
10
+ skillTriggers: {},
11
+ skillSessions: {},
12
+ skillCost: {},
13
+ ask: { calls: 0, cancelled: 0, errors: 0, durSum: 0, durN: 0, buckets: ASK_BUCKETS.map(() => 0).concat(0), sources: {} },
14
+ monitors: { started: 0, finished: 0, statuses: {}, durSum: 0, durN: 0 },
15
+ subagents: {},
16
+ subagentCost: {},
17
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, calls: 0 },
18
+ models: {},
19
+ detectors: {},
20
+ detectorVersions: {},
21
+ notices: {},
22
+ compactions: 0,
23
+ };
24
+ }
25
+ export const bump = (map, key, by = 1) => {
26
+ map[key] = (map[key] ?? 0) + by;
27
+ };
28
+ export function bucketOf(ms) {
29
+ const i = ASK_BUCKETS.findIndex((limit) => ms < limit);
30
+ return i < 0 ? ASK_BUCKETS.length : i;
31
+ }
32
+ function addCounts(into, from) {
33
+ for (const [k, v] of Object.entries(from))
34
+ bump(into, k, v);
35
+ }
36
+ function addLabels(into, from) {
37
+ for (const [k, v] of Object.entries(from)) {
38
+ const t = (into[k] ??= { pass: 0, fail: 0, na: 0 });
39
+ t.pass += v.pass;
40
+ t.fail += v.fail;
41
+ t.na += v.na;
42
+ }
43
+ }
44
+ export function addLabel(into, key, label) {
45
+ const t = (into[key] ??= { pass: 0, fail: 0, na: 0 });
46
+ t[label] += 1;
47
+ }
48
+ /** Adds `from` into `into` and returns `into`. */
49
+ export function mergeDay(into, from) {
50
+ into.sessions += from.sessions;
51
+ into.subagentSessions += from.subagentSessions;
52
+ into.prompts += from.prompts;
53
+ for (const [name, t] of Object.entries(from.tools)) {
54
+ const a = (into.tools[name] ??= { calls: 0, errors: 0, durSum: 0, durN: 0 });
55
+ a.calls += t.calls;
56
+ a.errors += t.errors;
57
+ a.durSum += t.durSum;
58
+ a.durN += t.durN;
59
+ }
60
+ addCounts(into.skills, from.skills);
61
+ addCounts(into.skillTriggers, from.skillTriggers);
62
+ addCounts(into.skillSessions, from.skillSessions);
63
+ addCounts(into.skillCost, from.skillCost);
64
+ mergeAsk(into.ask, from.ask);
65
+ mergeMonitors(into.monitors, from.monitors);
66
+ addCounts(into.subagents, from.subagents);
67
+ addCounts(into.subagentCost, from.subagentCost);
68
+ for (const key of Object.keys(into.usage))
69
+ into.usage[key] += from.usage[key];
70
+ addCounts(into.models, from.models);
71
+ addLabels(into.detectors, from.detectors);
72
+ addLabels(into.detectorVersions, from.detectorVersions);
73
+ addCounts(into.notices, from.notices);
74
+ into.compactions += from.compactions;
75
+ return into;
76
+ }
77
+ export function mergeAsk(into, from) {
78
+ into.calls += from.calls;
79
+ into.cancelled += from.cancelled;
80
+ into.errors += from.errors;
81
+ into.durSum += from.durSum;
82
+ into.durN += from.durN;
83
+ from.buckets.forEach((v, i) => (into.buckets[i] = (into.buckets[i] ?? 0) + v));
84
+ addCounts(into.sources, from.sources);
85
+ }
86
+ export function mergeMonitors(into, from) {
87
+ into.started += from.started;
88
+ into.finished += from.finished;
89
+ into.durSum += from.durSum;
90
+ into.durN += from.durN;
91
+ addCounts(into.statuses, from.statuses);
92
+ }
93
+ export function rowOf(start, project, subagent, cost, days, evals = {}) {
94
+ const row = { s: start, p: project, k: subagent ? 1 : 0, c: Math.round(cost * 1e4) / 1e4, t: {}, ac: 0, ax: 0, sl: 0, nt: 0, ev: {} };
95
+ for (const day of Object.values(days)) {
96
+ for (const [tool, t] of Object.entries(day.tools)) {
97
+ const cell = (row.t[tool] ??= [0, 0]);
98
+ cell[0] += t.calls;
99
+ cell[1] += t.errors;
100
+ }
101
+ row.ac += day.ask.calls;
102
+ row.ax += day.ask.cancelled;
103
+ row.sl += Object.values(day.skills).reduce((s, v) => s + v, 0);
104
+ row.nt += Object.values(day.notices).reduce((s, v) => s + v, 0);
105
+ }
106
+ for (const [name, result] of Object.entries(evals)) {
107
+ if (result?.label === "pass")
108
+ row.ev[name] = 1;
109
+ else if (result?.label === "fail")
110
+ row.ev[name] = 0;
111
+ }
112
+ return row;
113
+ }
package/dist/build.js ADDED
@@ -0,0 +1,260 @@
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, emptyDay, mergeDay, rowOf } from "./aggregate.js";
10
+ import { buildChanges, versionAt, writeChanges } from "./changes.js";
11
+ import { dayOf } from "./paths.js";
12
+ import { NAMES } from "./schema.js";
13
+ import { liveFiles, readRecords } from "./store.js";
14
+ export const ANCHORLOOP_PACKAGES = ["pi-anchorloop", "pi-aaaav", "aaaav"];
15
+ function atomicWrite(file, text) {
16
+ mkdirSync(dirname(file), { recursive: true });
17
+ const tmp = `${file}.${process.pid}.tmp`;
18
+ writeFileSync(tmp, text);
19
+ renameSync(tmp, file);
20
+ }
21
+ /** Live records grouped by session id. */
22
+ function liveSessions(layout) {
23
+ const bySession = new Map();
24
+ const snapshots = [];
25
+ for (const file of liveFiles(layout.events)) {
26
+ for (const rec of readRecords(file)) {
27
+ const id = String(rec.attrs?.["session.id"] ?? "");
28
+ if (!id)
29
+ continue;
30
+ if (rec.name === NAMES.tools)
31
+ snapshots.push(rec);
32
+ const list = bySession.get(id);
33
+ if (list)
34
+ list.push(rec);
35
+ else
36
+ bySession.set(id, [rec]);
37
+ }
38
+ }
39
+ return { bySession, snapshots };
40
+ }
41
+ const dayAgg = (days, ts) => (days[dayOf(ts)] ??= emptyDay());
42
+ /** Aggregates from live records alone, for a session no session file covers (e.g. `--no-session`). */
43
+ export function liveSummary(records) {
44
+ const days = {};
45
+ const start = records.reduce((min, r) => (r.ts < min ? r.ts : min), records[0]?.ts ?? new Date(0).toISOString());
46
+ const project = String(records[0]?.attrs["pi.project"] ?? "unknown");
47
+ const loaded = new Set();
48
+ for (const r of records) {
49
+ const a = r.attrs;
50
+ if (r.name === NAMES.tool) {
51
+ const day = dayAgg(days, r.end_ts ?? r.ts);
52
+ const name = String(a["gen_ai.tool.name"]);
53
+ const t = (day.tools[name] ??= { calls: 0, errors: 0, durSum: 0, durN: 0 });
54
+ t.calls += 1;
55
+ if (a["error.type"])
56
+ t.errors += 1;
57
+ if (typeof r.duration_ms === "number") {
58
+ t.durSum += r.duration_ms;
59
+ t.durN += 1;
60
+ }
61
+ if (a["pi.ask_user.source"] !== undefined)
62
+ addAsk(day, r);
63
+ if (name === "subagent" && a["gen_ai.agent.name"])
64
+ bump(day.subagents, `${a["gen_ai.agent.name"]}|${a["gen_ai.request.model"]}`);
65
+ }
66
+ else if (r.name === NAMES.skill) {
67
+ const day = dayAgg(days, r.ts);
68
+ const skill = String(a["gen_ai.skill.name"]);
69
+ bump(day.skills, skill);
70
+ bump(day.skillTriggers, String(a["pi.skill.trigger"]));
71
+ loaded.add(skill);
72
+ }
73
+ else if (r.name === NAMES.prompt)
74
+ dayAgg(days, r.ts).prompts += 1;
75
+ else if (r.name === NAMES.monitor)
76
+ addMonitor(dayAgg(days, r.end_ts ?? r.ts), r);
77
+ }
78
+ const first = dayAgg(days, start);
79
+ first.sessions += 1;
80
+ if (records.some((r) => r.name === NAMES.session && r.attrs["pi.session.kind"] === "subagent"))
81
+ first.subagentSessions += 1;
82
+ for (const skill of loaded)
83
+ bump(first.skillSessions, skill);
84
+ return { project, start, days };
85
+ }
86
+ function addAsk(day, r) {
87
+ const a = r.attrs;
88
+ day.ask.calls += 1;
89
+ if (a["pi.ask_user.cancelled"] === true)
90
+ day.ask.cancelled += 1;
91
+ if (a["error.type"])
92
+ day.ask.errors += 1;
93
+ bump(day.ask.sources, String(a["pi.ask_user.source"]));
94
+ if (typeof r.duration_ms === "number" && !a["error.type"]) {
95
+ day.ask.durSum += r.duration_ms;
96
+ day.ask.durN += 1;
97
+ day.ask.buckets[bucketOf(r.duration_ms)] += 1;
98
+ }
99
+ }
100
+ function addMonitor(day, r) {
101
+ day.monitors.finished += 1;
102
+ bump(day.monitors.statuses, String(r.attrs["pi.monitor.status"] ?? "unknown"));
103
+ if (typeof r.duration_ms === "number") {
104
+ day.monitors.durSum += r.duration_ms;
105
+ day.monitors.durN += 1;
106
+ }
107
+ }
108
+ /** Back-fill days of one session with live-only facts laid over: monitor lifecycles and ask-user answer sources. */
109
+ export function overlayLive(days, records) {
110
+ const out = structuredClone(days);
111
+ const monitors = records.filter((r) => r.name === NAMES.monitor);
112
+ if (monitors.length) {
113
+ for (const day of Object.values(out))
114
+ day.monitors = { started: day.monitors.started, finished: 0, statuses: {}, durSum: 0, durN: 0 };
115
+ for (const r of monitors)
116
+ addMonitor(dayAgg(out, r.end_ts ?? r.ts), r);
117
+ }
118
+ for (const r of records) {
119
+ const source = r.attrs["pi.ask_user.source"];
120
+ if (r.name !== NAMES.tool || typeof source !== "string")
121
+ continue;
122
+ const day = dayAgg(out, r.end_ts ?? r.ts);
123
+ if ((day.ask.sources.unknown ?? 0) > 0) {
124
+ day.ask.sources.unknown -= 1;
125
+ bump(day.ask.sources, source);
126
+ }
127
+ }
128
+ return out;
129
+ }
130
+ /** child logical id → parent session id and the role and model it was launched with. */
131
+ export function subagentLinks(summaries, ledgerDir) {
132
+ const links = new Map();
133
+ if (existsSync(ledgerDir)) {
134
+ for (const name of readdirSync(ledgerDir).filter((n) => n.endsWith(".json"))) {
135
+ try {
136
+ const rows = JSON.parse(readFileSync(join(ledgerDir, name), "utf8"));
137
+ if (!Array.isArray(rows))
138
+ continue;
139
+ for (const row of rows)
140
+ if (row?.id)
141
+ links.set(row.id, { parent: name.slice(0, -5), role: row.agent ?? "unknown", model: row.model ?? "unknown" });
142
+ }
143
+ catch { }
144
+ }
145
+ }
146
+ for (const s of summaries)
147
+ for (const child of s.spawned)
148
+ links.set(child.id, { parent: s.sessionId, role: child.role, model: child.model });
149
+ return links;
150
+ }
151
+ export function buildIndex(options) {
152
+ const { layout, checkpoint } = options;
153
+ const { bySession, snapshots } = liveSessions(layout);
154
+ const errors = [];
155
+ const changes = buildChanges(options.settings.changeRepos, snapshots, layout.marks, errors);
156
+ writeChanges(layout.changes, changes);
157
+ const summaries = Object.values(checkpoint.files).map((f) => f.summary);
158
+ const links = subagentLinks(summaries, join(options.agentDir, "dispatch-ledger"));
159
+ const cube = {};
160
+ const add = (project, days) => {
161
+ for (const [day, agg] of Object.entries(days)) {
162
+ const byProject = (cube[day] ??= {});
163
+ byProject[project] = mergeDay(byProject[project] ?? emptyDay(), agg);
164
+ }
165
+ };
166
+ const versionFor = (start) => versionAt(changes, ANCHORLOOP_PACKAGES, start) ?? "unknown";
167
+ const rows = [];
168
+ const sessionEvals = {};
169
+ const seen = new Set();
170
+ let both = 0;
171
+ let linked = 0;
172
+ let subagent = 0;
173
+ for (const s of summaries) {
174
+ if (!s.sessionId || seen.has(s.sessionId))
175
+ continue;
176
+ seen.add(s.sessionId);
177
+ const live = bySession.get(s.sessionId);
178
+ const days = live ? overlayLive(s.days, live) : structuredClone(s.days);
179
+ if (live)
180
+ both += 1;
181
+ const startDay = dayOf(s.start || 0);
182
+ const first = (days[startDay] ??= emptyDay());
183
+ if (s.kind === "subagent") {
184
+ subagent += 1;
185
+ const link = s.logicalId ? links.get(s.logicalId) : undefined;
186
+ if (link || s.parentId)
187
+ linked += 1;
188
+ bump(first.subagentCost, link?.role ?? (s.parentId ? "role-unknown" : "unlinked"), s.cost);
189
+ }
190
+ const version = versionFor(s.start);
191
+ const labels = {};
192
+ for (const [name, result] of Object.entries(s.evals)) {
193
+ if (!result || result.explanation === "out_of_scope_pre_3.0")
194
+ continue;
195
+ addLabel(first.detectorVersions, `${name}|${version}`, result.label);
196
+ labels[name] = result.label;
197
+ }
198
+ if (Object.keys(labels).length)
199
+ sessionEvals[s.sessionId] = labels;
200
+ add(s.project, days);
201
+ rows.push(rowOf(s.start, s.project, s.kind === "subagent", s.cost, days, s.evals));
202
+ }
203
+ let liveOnly = 0;
204
+ for (const [id, records] of bySession) {
205
+ if (seen.has(id))
206
+ continue;
207
+ liveOnly += 1;
208
+ const summary = liveSummary(records);
209
+ 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
+ }
212
+ const owners = {};
213
+ for (const rec of [...snapshots].sort((a, b) => a.ts.localeCompare(b.ts))) {
214
+ const tools = rec.attrs["pi.tools"];
215
+ if (!Array.isArray(tools))
216
+ continue;
217
+ for (const entry of tools) {
218
+ const eq = entry.indexOf("=");
219
+ const owner = entry.slice(eq + 1);
220
+ const at = owner.lastIndexOf("@");
221
+ owners[entry.slice(0, eq)] = at > 0 ? { owner: owner.slice(0, at), version: owner.slice(at + 1) } : { owner };
222
+ }
223
+ }
224
+ const allDays = Object.keys(cube).sort();
225
+ const lastDay = allDays.at(-1) ?? "";
226
+ rows.sort((a, b) => a.s.localeCompare(b.s));
227
+ const cutoff = lastDay ? dayOf(Date.parse(lastDay) - 7 * 86_400_000) : "";
228
+ const offered = new Set();
229
+ for (const cat of Object.values(checkpoint.catalogs))
230
+ if (cat.last.slice(0, 10) >= cutoff)
231
+ for (const n of cat.names)
232
+ offered.add(n);
233
+ for (const rec of bySession.values())
234
+ for (const r of rec)
235
+ if (r.name === NAMES.skills && Array.isArray(r.attrs["pi.skills"]))
236
+ for (const n of r.attrs["pi.skills"])
237
+ offered.add(n);
238
+ const index = {
239
+ v: 1,
240
+ built: (options.now?.() ?? new Date()).toISOString(),
241
+ lastExtract: checkpoint.lastExtract,
242
+ days: cube,
243
+ owners,
244
+ offeredSkills: [...offered].sort(),
245
+ sessions: { backfill: seen.size, live: liveOnly, both, subagent, linked },
246
+ range: { start: rows[0]?.s ?? "", end: checkpoint.lastExtract ?? rows.at(-1)?.s ?? "" },
247
+ };
248
+ atomicWrite(layout.days, JSON.stringify(index));
249
+ atomicWrite(layout.sessionRows, JSON.stringify(rows));
250
+ atomicWrite(layout.sessionEvals, JSON.stringify(sessionEvals));
251
+ return { index, changes, errors };
252
+ }
253
+ export function loadRows(layout) {
254
+ return existsSync(layout.sessionRows) ? JSON.parse(readFileSync(layout.sessionRows, "utf8")) : [];
255
+ }
256
+ export function loadIndex(layout) {
257
+ if (!existsSync(layout.days))
258
+ return undefined;
259
+ return JSON.parse(readFileSync(layout.days, "utf8"));
260
+ }