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.
Files changed (52) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE +21 -0
  3. package/README.md +106 -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 +160 -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 +172 -0
  24. package/dist/schema.js +65 -0
  25. package/dist/skills.js +41 -0
  26. package/dist/store.js +51 -0
  27. package/docs/design.md +95 -0
  28. package/docs/schema.md +68 -0
  29. package/package.json +56 -4
  30. package/src/aggregate.ts +204 -0
  31. package/src/build.ts +257 -0
  32. package/src/changes.ts +178 -0
  33. package/src/cli.ts +89 -0
  34. package/src/coverage.ts +44 -0
  35. package/src/detectors.ts +182 -0
  36. package/src/extract/file.ts +46 -0
  37. package/src/extract/run.ts +198 -0
  38. package/src/extract/session.ts +430 -0
  39. package/src/extract/worker.ts +12 -0
  40. package/src/index.ts +155 -0
  41. package/src/meta.ts +259 -0
  42. package/src/model.ts +346 -0
  43. package/src/observer.ts +255 -0
  44. package/src/ops.ts +110 -0
  45. package/src/owners.ts +92 -0
  46. package/src/paths.ts +108 -0
  47. package/src/project.ts +43 -0
  48. package/src/query.ts +85 -0
  49. package/src/render.ts +189 -0
  50. package/src/schema.ts +84 -0
  51. package/src/skills.ts +46 -0
  52. package/src/store.ts +49 -0
package/dist/meta.js ADDED
@@ -0,0 +1,233 @@
1
+ const t = (en, zh) => ({ en, zh });
2
+ export const METRICS = {
3
+ sessions: {
4
+ label: t("Sessions", "工作階段數"),
5
+ meaning: t("How much agent work happened; every other number should be read against it.", "代理人做了多少工作;其他數字都要對照這個量來看。"),
6
+ goodDirection: "none",
7
+ howComputed: t("Session files and live-only sessions that started in the window, each counted once.", "在期間內開始的工作階段檔與只有即時紀錄的工作階段,各算一次。"),
8
+ },
9
+ subagent_sessions: {
10
+ label: t("Subagent sessions", "子代理工作階段數"),
11
+ meaning: t("How much work was handed to helper agents instead of done by a main agent.", "有多少工作交給輔助代理人,而不是主代理人自己做。"),
12
+ goodDirection: "none",
13
+ howComputed: t("Sessions whose file name marks them as launched by another session.", "檔名顯示由另一個工作階段啟動的工作階段。"),
14
+ },
15
+ prompts: {
16
+ label: t("Prompts", "提示次數"),
17
+ meaning: t("How many times someone (you or another agent) asked an agent to do something.", "你或其他代理人要求代理人做事的次數。"),
18
+ goodDirection: "none",
19
+ howComputed: t("User messages in the session files.", "工作階段檔中的使用者訊息數。"),
20
+ },
21
+ tool_calls: {
22
+ label: t("Tool calls", "工具呼叫次數"),
23
+ meaning: t("How busy the agents were; a sudden jump can mean an agent is going in circles.", "代理人有多忙;突然暴增可能代表代理人在原地打轉。"),
24
+ goodDirection: "none",
25
+ howComputed: t("Finished tool calls, including ones that failed or were blocked.", "已結束的工具呼叫,包括失敗或被擋下的。"),
26
+ },
27
+ tool_error_rate: {
28
+ label: t("Tool error rate", "工具出錯比例"),
29
+ meaning: t("How often a tool call came back as an error; high means wasted turns or a broken tool.", "工具呼叫回報錯誤的頻率;偏高代表浪費回合或工具壞了。"),
30
+ goodDirection: "lower",
31
+ howComputed: t("Calls marked as errors divided by all calls.", "標為錯誤的呼叫數除以全部呼叫數。"),
32
+ },
33
+ avg_duration_ms: {
34
+ label: t("Average time per call", "每次呼叫平均耗時"),
35
+ meaning: t("How long a tool call usually takes; slow tools hold the agent up.", "一次工具呼叫通常花多久;慢的工具會拖住代理人。"),
36
+ goodDirection: "lower",
37
+ howComputed: t("Mean of the measured run time; older calls without a measurement use the time between the call and its result.", "量到的執行時間平均;舊紀錄沒有量測時,用呼叫到結果之間的時間。"),
38
+ },
39
+ skill_loads: {
40
+ label: t("Skill loads", "技能載入次數"),
41
+ meaning: t("How often agents opened a skill's instructions; a skill nobody loads is not shaping the work.", "代理人打開技能說明的次數;沒人載入的技能等於沒在影響工作。"),
42
+ goodDirection: "none",
43
+ howComputed: t("Reads of a skill's SKILL.md, /skill: commands, and skills a subagent role declares.", "讀取技能的 SKILL.md、/skill: 指令,以及子代理角色宣告的技能。"),
44
+ },
45
+ skill_sessions: {
46
+ label: t("Sessions that loaded it", "載入過的工作階段數"),
47
+ meaning: t("How widely a skill is used, not counting repeated loads in one session.", "技能用得多廣,同一工作階段重複載入只算一次。"),
48
+ goodDirection: "none",
49
+ howComputed: t("Sessions with at least one load of the skill.", "至少載入一次該技能的工作階段數。"),
50
+ },
51
+ never_loaded: {
52
+ label: t("Offered but never loaded", "有提供但從未載入"),
53
+ meaning: t("Skills pi lists to agents that no agent opened in the window; candidates to fix their description or remove.", "pi 有列給代理人、但期間內沒有代理人打開的技能;可考慮改寫說明或移除。"),
54
+ goodDirection: "lower",
55
+ howComputed: t("Skills in pi's skill list in the newest sessions, minus skills loaded in the window.", "最新工作階段裡 pi 提供的技能清單,扣掉期間內載入過的技能。"),
56
+ },
57
+ skill_cost: {
58
+ label: t("Cost of sessions using the skill", "使用該技能的工作階段花費"),
59
+ meaning: t("Money spent in sessions that loaded the skill; it shows where spend goes, not that the skill caused it.", "載入該技能的工作階段花了多少錢;顯示錢花在哪,不代表是技能造成的。"),
60
+ goodDirection: "none",
61
+ howComputed: t("Sum of each session's model cost, for every skill it loaded.", "每個工作階段的模型費用,加到它載入的每個技能上。"),
62
+ },
63
+ package_calls: {
64
+ label: t("Calls by package", "各套件被呼叫次數"),
65
+ meaning: t("Which installed packages the agents actually rely on.", "代理人實際依賴哪些已安裝的套件。"),
66
+ goodDirection: "none",
67
+ howComputed: t("Tool calls grouped by the package that registered the tool.", "依註冊該工具的套件分組的工具呼叫數。"),
68
+ },
69
+ ask_calls: {
70
+ label: t("Questions to you", "問你的次數"),
71
+ meaning: t("How often agents stopped to ask you something.", "代理人停下來問你問題的次數。"),
72
+ goodDirection: "none",
73
+ howComputed: t("Calls to the ask-user tools.", "呼叫詢問使用者工具的次數。"),
74
+ },
75
+ ask_wait_ms: {
76
+ label: t("Average wait for your answer", "等你回答的平均時間"),
77
+ meaning: t("How long agents sat idle waiting for you; long waits block the work.", "代理人閒著等你回答多久;等太久會卡住工作。"),
78
+ goodDirection: "lower",
79
+ howComputed: t("Mean time from the question appearing to the answer, for answered questions.", "從問題出現到收到回答的平均時間,只算有回答的。"),
80
+ },
81
+ ask_cancel_rate: {
82
+ label: t("Questions dismissed", "被取消的提問比例"),
83
+ meaning: t("How often you dismissed a question instead of answering; high can mean questions you did not need.", "你取消而非回答提問的頻率;偏高可能代表問了不必要的問題。"),
84
+ goodDirection: "lower",
85
+ howComputed: t("Cancelled questions divided by all questions.", "被取消的提問數除以全部提問數。"),
86
+ },
87
+ monitor_outcomes: {
88
+ label: t("Background jobs by outcome", "背景工作結果分布"),
89
+ meaning: t("How background commands (builds, tests, watchers) ended.", "背景指令(建置、測試、監看)最後怎麼結束。"),
90
+ goodDirection: "none",
91
+ howComputed: t("Finished monitors grouped by their final status; older sessions only kept about half of the endings.", "依最終狀態分組的已結束監看;較舊的工作階段大約只留下一半的結束紀錄。"),
92
+ },
93
+ monitor_duration_ms: {
94
+ label: t("Average background job time", "背景工作平均時長"),
95
+ meaning: t("How long background jobs ran.", "背景工作跑了多久。"),
96
+ goodDirection: "none",
97
+ howComputed: t("Mean time from start to finish where both are known.", "起訖時間都知道時,從開始到結束的平均時間。"),
98
+ },
99
+ subagent_launches: {
100
+ label: t("Subagents launched", "啟動的子代理"),
101
+ meaning: t("Which helper roles and models the agents hand work to.", "代理人把工作交給哪些輔助角色與模型。"),
102
+ goodDirection: "none",
103
+ howComputed: t("Successful subagent launches, grouped by the role and model asked for.", "成功啟動的子代理,依要求的角色與模型分組。"),
104
+ },
105
+ subagent_cost: {
106
+ label: t("Subagent cost by role", "各角色子代理花費"),
107
+ meaning: t("Where the helper agents' spend goes.", "輔助代理人的錢花在哪些角色上。"),
108
+ goodDirection: "none",
109
+ howComputed: t("Model cost of each subagent session, credited to the role its parent launched it with.", "每個子代理工作階段的模型費用,算在母工作階段啟動它時指定的角色上。"),
110
+ },
111
+ cost: {
112
+ label: t("Model cost (USD)", "模型費用(美元)"),
113
+ meaning: t("What the work cost, as reported by the model providers.", "這些工作花了多少錢,依模型供應商回報。"),
114
+ goodDirection: "lower",
115
+ howComputed: t("Sum of the cost recorded on every model reply.", "每則模型回覆記錄的費用加總。"),
116
+ },
117
+ cost_per_session: {
118
+ label: t("Cost per session", "每個工作階段花費"),
119
+ meaning: t("Average spend for one piece of agent work.", "一份代理人工作的平均花費。"),
120
+ goodDirection: "lower",
121
+ howComputed: t("Total model cost divided by sessions.", "模型費用總額除以工作階段數。"),
122
+ },
123
+ skill_loads_per_session: {
124
+ label: t("Skill loads per session", "每個工作階段載入技能數"),
125
+ meaning: t("How much skill instruction an average session reads.", "平均每個工作階段讀了多少技能說明。"),
126
+ goodDirection: "none",
127
+ howComputed: t("Skill loads divided by sessions.", "技能載入次數除以工作階段數。"),
128
+ },
129
+ notices_per_session: {
130
+ label: t("Close-guard reminders per session", "每個工作階段收到的收尾提醒"),
131
+ meaning: t("How often the close guard had to remind an agent to show its check passing.", "收尾檢查需要提醒代理人證明檢查通過的頻率。"),
132
+ goodDirection: "lower",
133
+ howComputed: t("Close-guard notices divided by sessions.", "收尾提醒次數除以工作階段數。"),
134
+ },
135
+ pass_rate: {
136
+ label: t("Share that followed the rule", "遵守規則的比例"),
137
+ meaning: t("Of the sessions where the rule applied, the share where the agent followed it.", "在規則適用的工作階段裡,代理人有遵守的比例。"),
138
+ goodDirection: "higher",
139
+ howComputed: t("Sessions that passed divided by sessions that passed or failed; sessions where it did not apply are left out.", "通過數除以(通過數+未通過數);不適用的工作階段不算。"),
140
+ },
141
+ agreement: {
142
+ label: t("Your verdict matches the automatic check", "你的判斷與自動檢查一致"),
143
+ meaning: t("How far the automatic check can be trusted: it is the share of sessions you labelled where you and it gave the same verdict.", "自動檢查有多可信:在你標記過的工作階段中,你和它判斷相同的比例。"),
144
+ goodDirection: "higher",
145
+ howComputed: t("Sessions where your label equals the check's label, divided by sessions you labelled for that check.", "你的標記與檢查結果相同的工作階段數,除以你為該檢查標記的工作階段數。"),
146
+ },
147
+ coverage: {
148
+ label: t("Old sessions already indexed", "已建索引的舊工作階段"),
149
+ meaning: t("Whether it is safe to clean up old session files: only indexed files keep their numbers after deletion.", "能否安全清理舊工作階段檔:只有建過索引的檔案在刪除後數字仍保留。"),
150
+ goodDirection: "higher",
151
+ howComputed: t("Session files inactive longer than the cut whose current size and time match the index, against all such files.", "閒置超過門檻、且目前大小與時間和索引相符的工作階段檔,對比所有這類檔案。"),
152
+ },
153
+ impact: {
154
+ label: t("Before and after a change", "變更前後比較"),
155
+ meaning: t("The same numbers in the days before and after one of your changes; a difference hints at an effect but does not prove it.", "你做某項變更前後幾天的同一組數字;有差異只是提示可能有影響,不能證明。"),
156
+ goodDirection: "none",
157
+ howComputed: t("Sessions are split by when they started: before the change's time or after it, within the same number of days on each side.", "依工作階段開始的時間分成變更時間之前與之後,兩邊取相同天數。"),
158
+ },
159
+ small_sample: {
160
+ label: t("Too few sessions to read", "工作階段太少,不宜解讀"),
161
+ meaning: t("One side had fewer than 20 sessions, so a difference may be chance.", "其中一邊少於 20 個工作階段,差異可能只是巧合。"),
162
+ goodDirection: "none",
163
+ howComputed: t("Flag set when either window has fewer than 20 sessions.", "任一邊少於 20 個工作階段時標記。"),
164
+ },
165
+ confounded: {
166
+ label: t("Other changes nearby", "附近還有其他變更"),
167
+ meaning: t("Other changes happened in the same days, so a difference cannot be credited to this one alone.", "同一段時間還有別的變更,差異不能只算在這一項。"),
168
+ goodDirection: "none",
169
+ howComputed: t("Other commits and notes inside either window, counted once each and grouped by what they changed.", "兩邊期間內的其他提交與手動標記,每筆算一次,並依變更種類分組。"),
170
+ },
171
+ incomplete_window: {
172
+ label: t("Window reaches past the data", "比較期間超出資料範圍"),
173
+ meaning: t("One side covers days with no data yet (or before the first session), so its numbers cover fewer days than the other side.", "其中一邊包含還沒有資料(或早於第一個工作階段)的日子,所以它涵蓋的天數比另一邊少。"),
174
+ goodDirection: "none",
175
+ howComputed: t("Set when the window before starts before the first session or the window after ends after the last extract; the days with data on each side are shown.", "變更前的期間早於第一個工作階段、或變更後的期間晚於上次抽取時標記;並列出兩邊各有資料的天數。"),
176
+ },
177
+ };
178
+ export const DETECTOR_META = {
179
+ anchor_before_first_edit: {
180
+ label: t("Said how to check before editing", "動手前先說好怎麼驗證"),
181
+ meaning: t("The agent named the check that proves the work (its Anchor) before changing any file.", "代理人在改任何檔案前,先說出用什麼檢查證明工作完成(Anchor)。"),
182
+ goodDirection: "higher",
183
+ howComputed: t("Passes when an Anchor line or a todo anchor appears before the first successful edit or write; sessions without edits do not count.", "第一次成功修改或寫檔之前出現 Anchor 行或待辦的 anchor 即通過;沒改檔的工作階段不算。"),
184
+ example: {
185
+ pass: t("Writes 'Anchor: `npm test`', then edits src/app.ts.", "先寫「Anchor: `npm test`」,再修改 src/app.ts。"),
186
+ fail: t("Edits src/app.ts first and names the check afterwards.", "先修改 src/app.ts,之後才說要怎麼檢查。"),
187
+ },
188
+ },
189
+ check_after_last_edit: {
190
+ label: t("Ran the check after the last edit", "最後一次修改後有跑檢查"),
191
+ meaning: t("After its final change, the agent ran the check it named and the check passed.", "最後一次修改後,代理人有跑它說好的檢查,而且通過。"),
192
+ goodDirection: "higher",
193
+ howComputed: t("Passes when every command in the Anchor has a passing run after the last edit; sessions with no edit or no runnable Anchor do not count.", "Anchor 裡每個指令在最後一次修改後都有通過的執行即通過;沒改檔或 Anchor 不是可執行指令的不算。"),
194
+ example: {
195
+ pass: t("Edits a file, then runs `npm test`, which exits 0.", "改完檔案後執行 `npm test`,結束碼 0。"),
196
+ fail: t("Runs `npm test`, edits one more file, and stops.", "跑完 `npm test` 又改了一個檔案就結束。"),
197
+ },
198
+ },
199
+ todo_evidence: {
200
+ label: t("Finished tasks carry proof", "完成的待辦附有證據"),
201
+ meaning: t("Tasks marked done in the todo list record which check showed them done.", "待辦清單中標為完成的項目,有記錄是哪個檢查證明它完成。"),
202
+ goodDirection: "higher",
203
+ howComputed: t("Share of completed tasks in the final todo list that have evidence; passes only when all do. Sessions without completed tasks do not count.", "最終待辦清單中已完成項目附有證據的比例;全部都有才算通過。沒有完成項目的不算。"),
204
+ example: {
205
+ pass: t("Task 'Fix login' is completed with evidence 'npm test: pass'.", "「修好登入」完成,證據記錄「npm test: pass」。"),
206
+ fail: t("Task 'Fix login' is completed with no evidence.", "「修好登入」標為完成,但沒有證據。"),
207
+ },
208
+ },
209
+ close_guard_quiet: {
210
+ label: t("Closed without a reminder", "收尾時不需要提醒"),
211
+ meaning: t("The anchorloop close guard never had to remind the agent about a missing or failing check.", "anchorloop 收尾檢查從未需要提醒代理人缺少或未通過檢查。"),
212
+ goodDirection: "higher",
213
+ howComputed: t("Passes when a session that edited files got no close-guard notice; fails name the most frequent reminder.", "有改檔的工作階段沒收到任何收尾提醒即通過;未通過時記錄最常出現的提醒種類。"),
214
+ example: {
215
+ pass: t("Edits, runs the check green, ends; no reminder appears.", "改檔、跑檢查通過、結束,沒有出現提醒。"),
216
+ fail: t("Edits and ends; the guard adds 'no passing run of `npm test`'.", "改檔就結束,收尾檢查加上「沒有 `npm test` 的通過紀錄」。"),
217
+ },
218
+ },
219
+ };
220
+ export const NOTICE_META = {
221
+ no_anchor: t("Files changed but no Anchor was stated", "改了檔案但沒說要怎麼驗證"),
222
+ no_passing_run: t("No passing run of the Anchor after the last change", "最後修改後沒有通過的檢查"),
223
+ evidence_handoff: t("Reminded to record a passing run as todo evidence", "提醒把通過的檢查記到待辦證據"),
224
+ other: t("Other reminder", "其他提醒"),
225
+ };
226
+ export const CHANGE_KIND_META = {
227
+ pin: t("Package version", "套件版本"),
228
+ "model-routing": t("Model routing", "模型分派"),
229
+ rule: t("Rule or instructions", "規則或指示"),
230
+ skill: t("Skill", "技能"),
231
+ "agent-role": t("Agent role", "代理人角色"),
232
+ manual: t("Your note", "手動標記"),
233
+ };
package/dist/model.js ADDED
@@ -0,0 +1,317 @@
1
+ /**
2
+ * The ReportModel: every number the report can show, each with its n and window, plus the plain-language
3
+ * metadata to explain it. The renderer reads only this; `evals_query` reads parts of it.
4
+ */
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { ASK_BUCKETS, emptyDay, mergeDay } from "./aggregate.js";
7
+ import { DETECTORS, ERA_START } from "./detectors.js";
8
+ import { CHANGE_KIND_META, DETECTOR_META, METRICS, NOTICE_META } from "./meta.js";
9
+ import { staticOwner } from "./owners.js";
10
+ import { dayOf } from "./paths.js";
11
+ export const SMALL_SAMPLE = 20;
12
+ /** Data older than this (hours) is reported as stale. */
13
+ export const STALE_HOURS = 24;
14
+ const rate = (num, den) => ({ value: den > 0 ? num / den : null, n: den });
15
+ const round = (v, digits = 4) => Math.round(v * 10 ** digits) / 10 ** digits;
16
+ /** Aggregates over the days and project in the filter; also the per-day totals. */
17
+ export function sumDays(index, filter) {
18
+ const total = emptyDay();
19
+ const perDay = [];
20
+ for (const day of Object.keys(index.days).sort()) {
21
+ if (filter.since && day < filter.since)
22
+ continue;
23
+ if (filter.until && day > filter.until)
24
+ continue;
25
+ const dayTotal = emptyDay();
26
+ for (const [project, agg] of Object.entries(index.days[day])) {
27
+ if (filter.project && project !== filter.project)
28
+ continue;
29
+ mergeDay(dayTotal, agg);
30
+ }
31
+ mergeDay(total, dayTotal);
32
+ perDay.push([day, dayTotal]);
33
+ }
34
+ return { total, perDay };
35
+ }
36
+ export function ownerFor(index, tool) {
37
+ return index.owners[tool]?.owner ?? staticOwner(tool);
38
+ }
39
+ function packages(index, total) {
40
+ const by = new Map();
41
+ for (const [tool, t] of Object.entries(total.tools)) {
42
+ const owner = ownerFor(index, tool);
43
+ const row = by.get(owner) ?? { owner, version: Object.values(index.owners).find((o) => o.owner === owner)?.version, calls: 0, errors: 0, durSum: 0, durN: 0, tools: [] };
44
+ row.calls += t.calls;
45
+ row.errors += t.errors;
46
+ row.durSum += t.durSum;
47
+ row.durN += t.durN;
48
+ row.tools.push(tool);
49
+ by.set(owner, row);
50
+ }
51
+ return [...by.values()]
52
+ .sort((a, b) => b.calls - a.calls)
53
+ .map((r) => ({ owner: r.owner, version: r.version, calls: r.calls, errors: r.errors, errorRate: rate(r.errors, r.calls), avgMs: r.durN ? Math.round(r.durSum / r.durN) : null, tools: r.tools.sort() }));
54
+ }
55
+ function detectorRates(total) {
56
+ return DETECTORS.map((name) => {
57
+ const d = total.detectors[name] ?? { pass: 0, fail: 0, na: 0 };
58
+ return { name, pass: d.pass, fail: d.fail, na: d.na, passRate: rate(d.pass, d.pass + d.fail) };
59
+ });
60
+ }
61
+ const DAY = 86_400_000;
62
+ /** The handful of numbers compared before and after a change, over the sessions that started in one window. */
63
+ export function impactMetrics(rows, ownerOf, pkg) {
64
+ let calls = 0;
65
+ let errors = 0;
66
+ let pkgCalls = 0;
67
+ let pkgErrors = 0;
68
+ let ask = 0;
69
+ let dismissed = 0;
70
+ let cost = 0;
71
+ let loads = 0;
72
+ let notices = 0;
73
+ const det = {};
74
+ for (const r of rows) {
75
+ for (const [tool, [c, e]] of Object.entries(r.t)) {
76
+ calls += c;
77
+ errors += e;
78
+ if (pkg && ownerOf(tool) === pkg) {
79
+ pkgCalls += c;
80
+ pkgErrors += e;
81
+ }
82
+ }
83
+ ask += r.ac;
84
+ dismissed += r.ax;
85
+ cost += r.c;
86
+ loads += r.sl;
87
+ notices += r.nt;
88
+ for (const [name, v] of Object.entries(r.ev)) {
89
+ const cell = (det[name] ??= [0, 0]);
90
+ cell[0] += v;
91
+ cell[1] += 1;
92
+ }
93
+ }
94
+ const d = (name) => rate(det[name]?.[0] ?? 0, det[name]?.[1] ?? 0);
95
+ return {
96
+ sessions: rows.length,
97
+ tool_error_rate: rate(errors, calls),
98
+ package_error_rate: pkg ? rate(pkgErrors, pkgCalls) : undefined,
99
+ ask_cancel_rate: rate(dismissed, ask),
100
+ cost_per_session: rate(cost, rows.length),
101
+ skill_loads_per_session: rate(loads, rows.length),
102
+ notices_per_session: rate(notices, rows.length),
103
+ anchor_before_first_edit: d("anchor_before_first_edit"),
104
+ check_after_last_edit: d("check_after_last_edit"),
105
+ todo_evidence: d("todo_evidence"),
106
+ };
107
+ }
108
+ /** Changes from one commit (or one mark) count once. */
109
+ const commitOf = (c) => c.sha ?? `${c.source}:${c.at}:${c.subject}`;
110
+ /**
111
+ * Before = sessions that started in [at - W, at), after = [at, at + W), by start time. `incomplete` when either window
112
+ * reaches past the data; `confounders` are the other commits inside both windows, by the kinds they changed.
113
+ */
114
+ export function impactFromRows(rows, change, all, windowDays, range, ownerOf) {
115
+ const at = Date.parse(change.at);
116
+ const lo = at - windowDays * DAY;
117
+ const hi = at + windowDays * DAY;
118
+ const before = [];
119
+ const after = [];
120
+ for (const r of rows) {
121
+ const t = Date.parse(r.s);
122
+ if (t >= lo && t < at)
123
+ before.push(r);
124
+ else if (t >= at && t < hi)
125
+ after.push(r);
126
+ }
127
+ const daysWith = (list) => new Set(list.map((r) => r.s.slice(0, 10))).size;
128
+ const self = commitOf(change);
129
+ const others = new Map();
130
+ for (const c of all) {
131
+ const t = Date.parse(c.at);
132
+ if (t < lo || t >= hi || commitOf(c) === self)
133
+ continue;
134
+ const kinds = others.get(commitOf(c)) ?? new Set();
135
+ kinds.add(c.kind);
136
+ others.set(commitOf(c), kinds);
137
+ }
138
+ const kinds = {};
139
+ for (const set of others.values())
140
+ for (const k of set)
141
+ kinds[k] = (kinds[k] ?? 0) + 1;
142
+ const pkg = change.kind === "pin" ? change.package : undefined;
143
+ return {
144
+ window: { before: { since: new Date(lo).toISOString(), until: change.at }, after: { since: change.at, until: new Date(hi).toISOString() }, days: windowDays },
145
+ before: impactMetrics(before, ownerOf, pkg),
146
+ after: impactMetrics(after, ownerOf, pkg),
147
+ daysWithData: { before: daysWith(before), after: daysWith(after) },
148
+ incomplete: !range.start || lo < Date.parse(range.start) || hi > Date.parse(range.end || range.start),
149
+ smallSample: before.length < SMALL_SAMPLE || after.length < SMALL_SAMPLE,
150
+ confounded: others.size,
151
+ confounders: kinds,
152
+ };
153
+ }
154
+ function labelsJoin(labelsFile, evalsFile) {
155
+ if (!existsSync(labelsFile))
156
+ return { present: false, n: 0, agreement: [] };
157
+ const codeLabels = existsSync(evalsFile) ? JSON.parse(readFileSync(evalsFile, "utf8")) : {};
158
+ const rows = readFileSync(labelsFile, "utf8")
159
+ .split("\n")
160
+ .filter(Boolean)
161
+ .flatMap((line) => {
162
+ try {
163
+ return [JSON.parse(line)];
164
+ }
165
+ catch {
166
+ return [];
167
+ }
168
+ });
169
+ const by = new Map();
170
+ for (const row of rows) {
171
+ const code = codeLabels[row.session_id]?.[row.evaluation_name];
172
+ if (!code || code === "na")
173
+ continue;
174
+ const t = by.get(row.evaluation_name) ?? { n: 0, agree: 0 };
175
+ t.n += 1;
176
+ if (code === row.label)
177
+ t.agree += 1;
178
+ by.set(row.evaluation_name, t);
179
+ }
180
+ return { present: true, n: rows.length, agreement: [...by].map(([detector, t]) => ({ detector, n: t.n, agree: t.agree, rate: rate(t.agree, t.n) })) };
181
+ }
182
+ export function buildModel(options) {
183
+ const { index, filter } = options;
184
+ const now = options.now ?? new Date();
185
+ const { total, perDay } = sumDays(index, filter);
186
+ const days = perDay.map(([d]) => d);
187
+ const loaded = new Set(Object.keys(total.skills));
188
+ const skillTop = Object.entries(total.skills)
189
+ .sort((a, b) => b[1] - a[1])
190
+ .map(([name, loads]) => ({ name, loads, sessions: total.skillSessions[name] ?? 0, cost: round(total.skillCost[name] ?? 0, 2), perDay: perDay.map(([, agg]) => agg.skills[name] ?? 0) }));
191
+ const projectSkills = new Map();
192
+ for (const day of days) {
193
+ for (const [project, agg] of Object.entries(index.days[day])) {
194
+ if (filter.project && project !== filter.project)
195
+ continue;
196
+ for (const [skill, n] of Object.entries(agg.skills)) {
197
+ const key = `${project}\u0000${skill}`;
198
+ const row = projectSkills.get(key);
199
+ if (row)
200
+ row.loads += n;
201
+ else
202
+ projectSkills.set(key, { project, skill, loads: n });
203
+ }
204
+ }
205
+ }
206
+ const byProject = [...projectSkills.values()].sort((a, b) => b.loads - a.loads);
207
+ const projectRows = filter.project ? options.rows.filter((r) => r.p === filter.project) : options.rows;
208
+ const owner = (tool) => ownerFor(index, tool);
209
+ const calls = Object.values(total.tools).reduce((s, t) => s + t.calls, 0);
210
+ const errors = Object.values(total.tools).reduce((s, t) => s + t.errors, 0);
211
+ const tokens = total.usage.input + total.usage.output + total.usage.cacheRead + total.usage.cacheWrite;
212
+ const lastExtract = index.lastExtract;
213
+ const ageHours = lastExtract ? (now.getTime() - Date.parse(lastExtract)) / 3_600_000 : Number.POSITIVE_INFINITY;
214
+ const versions = new Map();
215
+ for (const [key, v] of Object.entries(total.detectorVersions)) {
216
+ const [name, version] = key.split("|");
217
+ const list = versions.get(name) ?? [];
218
+ list.push({ version, pass: v.pass, fail: v.fail });
219
+ versions.set(name, list);
220
+ }
221
+ const sortedChanges = [...options.changes].sort((a, b) => a.at.localeCompare(b.at));
222
+ const firstDay = Object.keys(index.days).sort()[0] ?? "";
223
+ return {
224
+ v: 1,
225
+ generated: now.toISOString(),
226
+ window: { since: days[0] ?? filter.since ?? null, until: days.at(-1) ?? filter.until ?? null, days: days.length, project: filter.project ?? null },
227
+ freshness: { lastExtract: lastExtract ?? null, built: index.built, stale: ageHours > STALE_HOURS, ageHours: Number.isFinite(ageHours) ? round(ageHours, 1) : null },
228
+ meta: { metrics: METRICS, detectors: DETECTOR_META, notices: NOTICE_META, changeKinds: CHANGE_KIND_META },
229
+ totals: {
230
+ sessions: total.sessions,
231
+ subagentSessions: total.subagentSessions,
232
+ prompts: total.prompts,
233
+ toolCalls: calls,
234
+ toolErrorRate: rate(errors, calls),
235
+ cost: round(total.usage.cost, 2),
236
+ tokens,
237
+ modelReplies: total.usage.calls,
238
+ compactions: total.compactions,
239
+ indexSessions: index.sessions,
240
+ },
241
+ series: {
242
+ days,
243
+ sessions: perDay.map(([, a]) => a.sessions),
244
+ toolCalls: perDay.map(([, a]) => Object.values(a.tools).reduce((s, t) => s + t.calls, 0)),
245
+ cost: perDay.map(([, a]) => round(a.usage.cost, 2)),
246
+ skillLoads: perDay.map(([, a]) => Object.values(a.skills).reduce((s, v) => s + v, 0)),
247
+ },
248
+ skills: {
249
+ top: skillTop,
250
+ byProject: byProject.slice(0, 200),
251
+ triggers: total.skillTriggers,
252
+ offered: index.offeredSkills.length,
253
+ neverLoaded: index.offeredSkills.filter((s) => !loaded.has(s)),
254
+ },
255
+ packages: packages(index, total),
256
+ tools: Object.entries(total.tools)
257
+ .sort((a, b) => b[1].calls - a[1].calls)
258
+ .map(([name, t]) => ({ name, owner: ownerFor(index, name), calls: t.calls, errors: t.errors, errorRate: rate(t.errors, t.calls), avgMs: t.durN ? Math.round(t.durSum / t.durN) : null })),
259
+ askUser: {
260
+ calls: total.ask.calls,
261
+ cancelled: total.ask.cancelled,
262
+ errors: total.ask.errors,
263
+ cancelRate: rate(total.ask.cancelled, total.ask.calls),
264
+ avgWaitMs: total.ask.durN ? Math.round(total.ask.durSum / total.ask.durN) : null,
265
+ waitN: total.ask.durN,
266
+ buckets: total.ask.buckets.map((n, i) => ({ upToMs: ASK_BUCKETS[i] ?? null, n })),
267
+ sources: total.ask.sources,
268
+ },
269
+ monitors: {
270
+ started: total.monitors.started,
271
+ finished: total.monitors.finished,
272
+ statuses: total.monitors.statuses,
273
+ avgMs: total.monitors.durN ? Math.round(total.monitors.durSum / total.monitors.durN) : null,
274
+ durationN: total.monitors.durN,
275
+ },
276
+ subagents: {
277
+ sessions: total.subagentSessions,
278
+ launches: Object.entries(total.subagents)
279
+ .map(([key, n]) => ({ role: key.split("|")[0], model: key.split("|")[1] ?? "unknown", n }))
280
+ .sort((a, b) => b.n - a.n),
281
+ costByRole: Object.entries(total.subagentCost)
282
+ .map(([role, cost]) => ({ role, cost: round(cost, 2) }))
283
+ .sort((a, b) => b.cost - a.cost),
284
+ linked: index.sessions.linked,
285
+ subagentTotal: index.sessions.subagent,
286
+ },
287
+ process: {
288
+ eraStart: ERA_START,
289
+ detectors: detectorRates(total).map((d) => ({
290
+ ...d,
291
+ perDay: perDay.map(([day, a]) => {
292
+ const x = a.detectors[d.name] ?? { pass: 0, fail: 0, na: 0 };
293
+ return { day, pass: x.pass, fail: x.fail };
294
+ }),
295
+ byVersion: (versions.get(d.name) ?? []).map((v) => ({ ...v, passRate: rate(v.pass, v.pass + v.fail) })),
296
+ })),
297
+ notices: total.notices,
298
+ },
299
+ cost: {
300
+ total: round(total.usage.cost, 2),
301
+ perSession: rate(total.usage.cost, total.sessions),
302
+ byModel: Object.entries(total.models)
303
+ .sort((a, b) => b[1] - a[1])
304
+ .map(([model, replies]) => ({ model, replies })),
305
+ bySkill: skillTop
306
+ .slice()
307
+ .sort((a, b) => b.cost - a.cost)
308
+ .slice(0, 25)
309
+ .map(({ name, cost, sessions }) => ({ skill: name, cost, sessions })),
310
+ },
311
+ changes: sortedChanges
312
+ .filter((c) => (!filter.since || c.at.slice(0, 10) >= filter.since) && (!filter.until || c.at.slice(0, 10) <= filter.until))
313
+ .map((c) => ({ ...c, impact: index.range.start && c.at > index.range.start ? impactFromRows(projectRows, c, sortedChanges, options.windowDays, index.range, owner) : null })),
314
+ labels: labelsJoin(options.labelsFile, options.sessionEvalsFile),
315
+ coverage: options.coverage ?? null,
316
+ };
317
+ }