neurastream 0.2.50 → 0.2.51

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/README.md CHANGED
@@ -352,6 +352,8 @@ The report ends with a `Provider honesty over N runs: …` line — provider-hon
352
352
 
353
353
  Weekly loop: run `neurastream metrics report`, then propose ONE rule change to the owner. When the owner decides, record it with `neurastream metrics rule "<text>" --approved|--rejected`; approved rules get a before/after check once a full window has passed. Record CI with `neurastream metrics ci <repo-dir> <mr-id>` and guard false alarms with `neurastream metrics false-alarm <log-ts> --why "<text>"`. main-start shows the report as due when it is missing or older than `metrics.report_days`.
354
354
 
355
+ Feature results: `neurastream metrics features [--days N] [--json]` prints $ per finished feature — a feature is a plan plus every later plan whose Goal names its file stem, finished means every plan in the chain has a closing Progress status or is archived; each hour's Main cost splits evenly over the plan files that hour's messages name (nothing named → overhead), and a sub run's cost goes to the plan its first message names. `neurastream metrics releases [--days N] [--json]` prints, per release (a `v*` tag of this repo or another repo's `metrics ci` merge), the same numbers for the N days before vs after it — $/feature, features/day, main calls/feature, tokens/call, fix plans/feature — plus each configured product number (`metrics.product_cmds`, last value before vs first after). The owner page's Results tab draws the releases as a line chart: the y links pick the metric ($/feature, features/day, calls, tokens, fix rate, or one per product number), the x links switch between time (days on the axis, dashed release markers) and feature/release order; product numbers are neutral — the table marks their direction with ▲/▼ but never colors them better or worse.
356
+
355
357
  ## Self-improvement
356
358
 
357
359
  Bugs in neurastream itself are found by code, written to a persistent list, and pushed on Main until each one has a plan or a recorded dismissal — not remembered. The list is `<paths.queue_state>/incidents.jsonl`; `neurastream incident list [--open] [--json]` reads it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.50",
3
+ "version": "0.2.51",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -158,13 +158,10 @@ function build(file: string, cfg: Config, mtime: number, agentsDir: string): Run
158
158
  } catch {
159
159
  continue;
160
160
  }
161
- const ts = d.timestamp;
162
- if (typeof ts === "string") {
163
- const t = parseTs(ts);
164
- if (t !== null) {
165
- first = first ?? t;
166
- last = t;
167
- }
161
+ const ts = typeof d.timestamp === "string" ? parseTs(d.timestamp) : null;
162
+ if (ts !== null) {
163
+ first = first ?? ts;
164
+ last = ts;
168
165
  }
169
166
  if (d.customType === "session_exit") exited = true;
170
167
  if (d.customType === "tool_execution_start") {
@@ -222,7 +219,12 @@ function build(file: string, cfg: Config, mtime: number, agentsDir: string): Run
222
219
  role: typeof m.role === "string" ? m.role : "",
223
220
  cost: lineCost,
224
221
  text: pyDumps(m.content ?? "").slice(0, 20000),
222
+ ts,
225
223
  });
224
+ } else if (m.role === "user" && !messages.length) {
225
+ // A sub keeps only its first user message: results (src/core/results.ts) price the run
226
+ // by the plan path that message names.
227
+ messages.push({ role: "user", cost: lineCost, text: pyDumps(m.content ?? "").slice(0, 20000), ts });
226
228
  }
227
229
  }
228
230
 
@@ -271,7 +273,8 @@ function build(file: string, cfg: Config, mtime: number, agentsDir: string): Run
271
273
  startedAt: first,
272
274
  lastWriteAt: mtime,
273
275
  endedAt: last,
274
- messages: isMain ? messages : [],
276
+ // Subs: build() above keeps only the first user message, which results.ts prices by.
277
+ messages,
275
278
  scoreModel,
276
279
  scoreCost,
277
280
  scoreHours: ((last ?? 0) - (first ?? 0)) / 3600,
@@ -68,7 +68,7 @@ export function helpText(): string {
68
68
  " neurastream guard <event> --json",
69
69
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
70
70
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
71
- " neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
71
+ " neurastream metrics <cmd> self-metrics: report, features, releases, ci, false-alarm, rule (see README)",
72
72
  " neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
73
73
  " neurastream traces claims <runId|--since 24h> [--json]",
74
74
  " check a run's final-report claims (test counts, exit codes,",
@@ -5,13 +5,15 @@
5
5
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
8
- import { appendMetric } from "../core/metrics.ts";
8
+ import { appendMetric, readMetricEvents } from "../core/metrics.ts";
9
9
  import { nowSec } from "../core/clock.ts";
10
10
  import type { RunSource } from "../core/adapter.ts";
11
11
  import { buildReport, type BloatSummary, type ProviderSummary } from "../core/report.ts";
12
12
  import { providerFindings } from "../core/trace-provider.ts";
13
13
  import { bloatRules } from "../core/trace-bloat.ts";
14
14
  import { getAdapter } from "../adapters/index.ts";
15
+ import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleasesReport } from "../core/results.ts";
16
+ import { gitTop } from "../core/queue/lib.ts";
15
17
  import { assignDumps, bloatReport } from "./traces.ts";
16
18
 
17
19
  export const METRICS_USAGE = [
@@ -19,6 +21,8 @@ export const METRICS_USAGE = [
19
21
  ' neurastream metrics false-alarm <log-ts> --why "<text>"',
20
22
  ' neurastream metrics rule "<text>" --approved|--rejected',
21
23
  " neurastream metrics report [--days N]",
24
+ " neurastream metrics features [--days N] [--json]",
25
+ " neurastream metrics releases [--days N] [--json]",
22
26
  ].join("\n");
23
27
 
24
28
  function flagValue(args: string[], name: string): string | undefined {
@@ -67,9 +71,31 @@ export function recordCi(cfg: Config, repoDir: string, mr: string, now: number):
67
71
  }
68
72
  appendMetric(cfg, { type: "ci", mr, repo: repoDir, tries: pipelines.length, ts: now });
69
73
  console.log(`ci: ${mr} needed ${pipelines.length} pipeline(s)`);
74
+ recordProducts(cfg, repoDir, now);
70
75
  return 0;
71
76
  }
72
77
 
78
+ const PRODUCT_TIMEOUT_MS = 10_000;
79
+
80
+ /**
81
+ * Runs the repo's configured product numbers once each (metrics.product_cmds) and appends one
82
+ * product record per number. A command that fails, times out or prints anything but one finite
83
+ * number is skipped with a stderr line; the ci record itself never fails on a product number.
84
+ */
85
+ function recordProducts(cfg: Config, repoDir: string, now: number): void {
86
+ for (const [name, cmd] of Object.entries(cfg.metrics.product_cmds[repoDir] ?? {})) {
87
+ const proc = Bun.spawnSync(["sh", "-c", cmd], { cwd: repoDir, stdout: "pipe", stderr: "pipe", timeout: PRODUCT_TIMEOUT_MS });
88
+ const out = proc.stdout.toString().trim();
89
+ const value = Number(out);
90
+ if (proc.exitCode !== 0 || out === "" || !Number.isFinite(value)) {
91
+ const why = proc.exitCode !== 0 ? `exit ${proc.exitCode ?? "signal"}` : `not one number: "${out.slice(0, 40)}"`;
92
+ console.error(`product_cmds.${name}: skipped (${why})`);
93
+ continue;
94
+ }
95
+ appendMetric(cfg, { type: "product", repo: repoDir, name, value, ts: now });
96
+ }
97
+ }
98
+
73
99
  /** Marks one guard BLOCK line (by its ISO timestamp) as a false alarm. */
74
100
  export function recordFalseAlarm(cfg: Config, logTs: string, why: string, now: number): number {
75
101
  if (!logTs || !why) {
@@ -153,6 +179,102 @@ export function reportCmd(cfg: Config, source: RunSource, args: string[], now: n
153
179
  return 0;
154
180
  }
155
181
 
182
+ /** Local `YYYY-MM-DD HH:MM`, the stamp style Progress entries use. */
183
+ function localStamp(ts: number): string {
184
+ const d = new Date(ts * 1000);
185
+ const two = (n: number) => String(n).padStart(2, "0");
186
+ return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
187
+ }
188
+
189
+ function featuresTable(r: FeaturesReport): string {
190
+ const out = [`Results: last ${r.days} days [${localStamp(r.from)} to ${localStamp(r.to)})`];
191
+ out.push("stem kind plans fix $total $first closed at");
192
+ for (const row of r.rows) {
193
+ out.push(
194
+ `${row.stem.padEnd(30)} ${row.kind.padEnd(11)} ${String(row.plans).padEnd(5)} ${String(row.fixPlans).padEnd(4)} ` +
195
+ `${row.total.toFixed(2).padEnd(7)} ${row.first.toFixed(2).padEnd(7)} ${localStamp(row.closedAt)}`,
196
+ );
197
+ }
198
+ for (const s of r.summaries) {
199
+ const perFeature = s.perFeature === null ? "n/a" : `$${s.perFeature.toFixed(2)}`;
200
+ const firstPass = s.firstPass === null ? "n/a" : `$${s.firstPass.toFixed(2)}`;
201
+ const overhead = s.overheadPct === null ? "n/a" : `${s.overheadPct.toFixed(0)}%`;
202
+ out.push(
203
+ `${s.kind}: finished ${s.finished} (${s.perDay.toFixed(2)}/day), ${perFeature}/feature, first-pass ${firstPass}, ` +
204
+ `overhead ${overhead}, open chains ${s.openChains} ($${s.openSunk.toFixed(2)} sunk)`,
205
+ );
206
+ }
207
+ return out.join("\n");
208
+ }
209
+
210
+ /** `metrics features`: $ per finished feature over the queue's own plan chains. */
211
+ export function featuresCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
212
+ const raw = flagValue(args, "--days");
213
+ const days = raw === undefined ? cfg.metrics.report_days : Number(raw);
214
+ if (!Number.isInteger(days) || days < 1) {
215
+ console.error(METRICS_USAGE);
216
+ return 2;
217
+ }
218
+ const report = featuresReport(source.listRuns(now - days * 86400), loadPlans(cfg), gitTop(import.meta.dir)?.repo ?? null, now - days * 86400, now);
219
+ if (args.includes("--json")) {
220
+ console.log(JSON.stringify(report, null, 2));
221
+ return 0;
222
+ }
223
+ console.log(featuresTable(report));
224
+ return 0;
225
+ }
226
+
227
+ function releasesTable(r: ReleasesReport): string {
228
+ const out = [
229
+ `Releases: per release, ${r.days} days before vs after (measuring = the after window is still filling); ` +
230
+ "columns: $/feature, features/day, main calls/feature, tokens/call, fix plans/feature, product numbers",
231
+ ];
232
+ for (const row of r.rows) {
233
+ // Five columns share the before→after cell shape; digits differ per column.
234
+ const pair = (a: number | null, b: number | null, digits = 2) =>
235
+ `${a === null ? "n/a" : a.toFixed(digits)}→${b === null ? "n/a" : b.toFixed(digits)}`;
236
+ const products = row.before.products.map((p, i) => {
237
+ const after = row.after.products[i]?.value ?? null;
238
+ return `${p.name} ${p.value === null ? "-" : String(p.value)}→${after === null ? "-" : String(after)}`;
239
+ });
240
+ out.push(
241
+ `${row.name.padEnd(20)} ${row.kind.padEnd(12)} ${localStamp(row.ts)} ` +
242
+ `${pair(row.before.perFeature, row.after.perFeature)} ` +
243
+ `${pair(row.before.featuresPerDay, row.after.featuresPerDay)} ` +
244
+ `${pair(row.before.callsPerFeature, row.after.callsPerFeature, 1)} ` +
245
+ `${pair(row.before.tokensPerCall, row.after.tokensPerCall, 1)} ` +
246
+ `${pair(row.before.fixPlansPerFeature, row.after.fixPlansPerFeature)} ` +
247
+ products.join(" ") +
248
+ (row.measuring ? " measuring" : ""),
249
+ );
250
+ }
251
+ return out.join("\n");
252
+ }
253
+
254
+ /** `metrics releases`: per release — a self `v*` tag or another repo's `metrics ci` merge — the
255
+ * same ledger metrics for the N days before vs after it. */
256
+ export function releasesCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
257
+ const raw = flagValue(args, "--days");
258
+ const days = raw === undefined ? 7 : Number(raw);
259
+ if (!Number.isInteger(days) || days < 1) {
260
+ console.error(METRICS_USAGE);
261
+ return 2;
262
+ }
263
+ const selfRepo = gitTop(import.meta.dir)?.repo ?? null;
264
+ const tags = gatherTags(selfRepo);
265
+ const events = readMetricEvents(cfg);
266
+ // A release's before window reaches back past the features window, so ask for runs since the
267
+ // oldest release's window start.
268
+ const oldest = Math.min(now, ...tags.map(t => t.ts), ...events.filter(e => e.type === "ci").map(e => Number(e.ts)));
269
+ const report = releasesReport(source.listRuns(oldest - days * 86400), loadPlans(cfg), selfRepo, days, now, tags, events);
270
+ if (args.includes("--json")) {
271
+ console.log(JSON.stringify(report, null, 2));
272
+ return 0;
273
+ }
274
+ console.log(releasesTable(report));
275
+ return 0;
276
+ }
277
+
156
278
  export async function runMetrics(args: string[]): Promise<number> {
157
279
  let cfg: Config;
158
280
  try {
@@ -165,6 +287,8 @@ export async function runMetrics(args: string[]): Promise<number> {
165
287
  const now = nowSec();
166
288
  if (sub === "ci") return recordCi(cfg, rest[0] ?? "", rest[1] ?? "", now);
167
289
  if (sub === "report") return reportCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
290
+ if (sub === "features") return featuresCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
291
+ if (sub === "releases") return releasesCmd(cfg, getAdapter(cfg).runSource(cfg), rest, now);
168
292
  if (sub === "false-alarm") return recordFalseAlarm(cfg, rest[0] ?? "", flagValue(rest, "--why") ?? "", now);
169
293
  if (sub === "rule") {
170
294
  const approved = rest.includes("--approved");
@@ -8,6 +8,8 @@ export interface RunMessage {
8
8
  role: string;
9
9
  cost: number;
10
10
  text: string;
11
+ /** Unix seconds the line was written at; null when the line carried no readable timestamp. */
12
+ ts: number | null;
11
13
  }
12
14
 
13
15
  export interface Run {
@@ -179,7 +179,7 @@ export interface Config {
179
179
  /** Repo-local HTML explainers under docs/knowledge/ (owner page Knowledge tab). */
180
180
  knowledge: { roots: string[]; max_age_s: number };
181
181
  rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
182
- metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
182
+ metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string; product_cmds: Record<string, Record<string, string>> };
183
183
  /** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
184
184
  incidents: {
185
185
  /** Minutes after a finished task-result before a RUNNING/WAITING ledger row contradicts it. */
@@ -556,6 +556,15 @@ function check(cfg: Config): void {
556
556
  throw new ConfigError(`metrics.correction_patterns: not a valid regex: ${p}`);
557
557
  }
558
558
  }
559
+ if (typeof cfg.metrics.product_cmds !== "object" || cfg.metrics.product_cmds === null || Array.isArray(cfg.metrics.product_cmds))
560
+ throw new ConfigError("metrics.product_cmds must map a repo path to {name: command}");
561
+ for (const [repo, cmds] of Object.entries(cfg.metrics.product_cmds)) {
562
+ if (typeof cmds !== "object" || cmds === null || Array.isArray(cmds)) throw new ConfigError(`metrics.product_cmds.${repo} must map a name to a command`);
563
+ for (const [name, cmd] of Object.entries(cmds)) {
564
+ if (name === "") throw new ConfigError(`metrics.product_cmds.${repo}: command names must be non-empty`);
565
+ if (typeof cmd !== "string" || cmd.trim() === "") throw new ConfigError(`metrics.product_cmds.${repo}.${name} must be a non-empty shell command`);
566
+ }
567
+ }
559
568
  for (const [provider, pattern] of Object.entries(cfg.traces.provider.id_patterns)) {
560
569
  if (typeof pattern !== "string") throw new ConfigError(`traces.provider.id_patterns.${provider} must be a string`);
561
570
  try {
@@ -187,8 +187,8 @@ export interface M4 {
187
187
 
188
188
  /**
189
189
  * M4: user messages in main runs written in the window, how many match a correction pattern,
190
- * and assistant messages whose last text block ends in "?". RunMessage has no timestamp, so
191
- * a main run counts whole by its lastWriteAt.
190
+ * and assistant messages whose last text block ends in "?". Messages may carry ts, but M4
191
+ * keeps the whole-run measure: a main run counts by its lastWriteAt.
192
192
  */
193
193
  export function m4(runs: Run[], w: Window, patterns: RegExp[]): M4 {
194
194
  const out: M4 = { users: 0, corrections: 0, questions: 0 };
@@ -20,7 +20,8 @@ import { dismissIncident, isFindingKind, openIncidents } from "./incidents.ts";
20
20
  import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue, type KnowledgeEntry } from "./knowledge.ts";
21
21
  import { log } from "./guards.ts";
22
22
  import { readMetricEvents } from "./metrics.ts";
23
- import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
23
+ import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
24
+ import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleaseRow, type ReleaseSideStats, type ReleasesReport } from "./results.ts";
24
25
  import type { Tailscale } from "./tailscale.ts";
25
26
 
26
27
  const ANSWER_MAX = 2000;
@@ -31,7 +32,7 @@ const MESSAGE_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
31
32
  export const OWNER_MESSAGE_KEEP_SEC = 43200;
32
33
  const REFRESH_SEC = 20;
33
34
  /** The page's tabs, in pill order; anything else in `?tab=` renders Now. */
34
- const TABS: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"], ["knowledge", "Base"]];
35
+ const TABS: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"], ["knowledge", "Base"], ["results", "Results"]];
35
36
  const TAB_IDS = TABS.map(([id]) => id);
36
37
  // Tailscale hands out addresses from 100.64.0.0/10 (CGNAT) and its own ULA /48 for IPv6.
37
38
  const TAILNET6 = /^fd7a:115c:a1e0:/i;
@@ -747,6 +748,8 @@ export interface PageData {
747
748
  knowledge: KnowledgeEntry[] | null;
748
749
  /** The 24 h tile numbers; null when the run source is unreadable. */
749
750
  stats: NowStats | null;
751
+ /** The Results tab's ledger and release windows; null when unreadable, absent in hand-built PageData. */
752
+ results?: ResultsData | null;
750
753
  /** The owner's messages newer than the keep window, newest first; null when unreadable. */
751
754
  messages: MessageRow[] | null;
752
755
  /** Minutes left in the guard unlock; null = locked. */
@@ -783,6 +786,7 @@ export function buildPageData(cfg: Config, source: RunSource): PageData {
783
786
  machine: safe(() => machineRow(cfg)),
784
787
  knowledge: safe(() => knowledgeManifest(cfg)),
785
788
  stats: safe(() => nowStats(cfg, source, nowSec())),
789
+ results: safe(() => resultsData(cfg, source)),
786
790
  messages: safe(() => recentOwnerMessages(nowSec())),
787
791
  lockMinutesLeft: lockMinutesLeft(cfg),
788
792
  };
@@ -822,8 +826,8 @@ export function edgeScrollStep(y: number, viewportH: number): number {
822
826
  const SCRIPT = `(function(){
823
827
  var dropSlot=${dropSlot.toString()};
824
828
  var edgeScrollStep=${edgeScrollStep.toString()};
825
- // Keep only the tab in the address bar: receipts are one-time DOM, not a reloadable URL.
826
- if(location.search){var keep=new URLSearchParams(location.search).get("tab");history.replaceState(null,"",location.pathname+(keep?"?tab="+keep:""));}
829
+ // Keep the tab in the address bar (receipts are one-time DOM, not a reloadable URL); the Results tab keeps y/x so the 20 s refresh renders the same selection.
830
+ if(location.search){var q=new URLSearchParams(location.search);var keep=new URLSearchParams();if(q.get("tab"))keep.set("tab",q.get("tab"));if(q.get("tab")==="results"){if(q.get("y"))keep.set("y",q.get("y"));if(q.get("x"))keep.set("x",q.get("x"));}var ks=keep.toString();history.replaceState(null,"",location.pathname+(ks?"?"+ks:""));}
827
831
  function store(d,v){var k="nsui:"+d.id;if(v===undefined)return sessionStorage.getItem(k);sessionStorage.setItem(k,v?"1":"0");}
828
832
  function bindDetails(root){var ds=root.querySelectorAll("details[id]");for(var i=0;i<ds.length;i++){(function(d){var s=store(d);if(s!==null)d.open=s==="1";d.addEventListener("toggle",function(){store(d,d.open);});})(ds[i]);}}
829
833
  var dragging=false;
@@ -946,6 +950,222 @@ function knowledgeHtml(entries: KnowledgeEntry[], repo: string, topic: string):
946
950
  return `${crumb}<h1>${esc(hit.title)}</h1><div class="card"><iframe class="knowframe" title="${esc(hit.title)}" src="/knowledge/${urlValue(repo)}/${urlValue(topic)}"></iframe></div>`;
947
951
  }
948
952
 
953
+ // ---- Results tab (plan 20261025_2148 P4): $ per finished feature, releases before vs after ----
954
+
955
+ export interface ResultsData {
956
+ /** The ledger over the last `metrics.report_days` days — only the empty state reads it. */
957
+ features: FeaturesReport;
958
+ /** Per release, the N-day before/after windows: the chart's series and the table's rows. */
959
+ releases: ReleasesReport;
960
+ }
961
+
962
+ let resultsCache: { at: number; data: ResultsData } | null = null;
963
+
964
+ /**
965
+ * The tab's data from the P2/P3 functions, computed once per build (the chart and the table read
966
+ * the same object, like the Spend tile and its table). Cached for a minute: a release's before
967
+ * window reaches back past the features window, so one build can parse months of sessions while
968
+ * the page refetches every ${REFRESH_SEC} s.
969
+ */
970
+ function resultsData(cfg: Config, source: RunSource): ResultsData {
971
+ const now = nowSec();
972
+ if (resultsCache && now - resultsCache.at < 60) return resultsCache.data;
973
+ const days = 7;
974
+ const selfRepo = gitTop(import.meta.dir)?.repo ?? null;
975
+ const tags = gatherTags(selfRepo);
976
+ const events = readMetricEvents(cfg);
977
+ const oldest = Math.min(now, ...tags.map(t => t.ts), ...events.filter(e => e.type === "ci").map(e => Number(e.ts)));
978
+ const runs = source.listRuns(oldest - days * 86400);
979
+ const plans = loadPlans(cfg);
980
+ const data: ResultsData = {
981
+ features: featuresReport(runs, plans, selfRepo, now - cfg.metrics.report_days * 86400, now),
982
+ releases: releasesReport(runs, plans, selfRepo, days, now, tags, events),
983
+ };
984
+ resultsCache = { at: now, data };
985
+ return data;
986
+ }
987
+
988
+ /** One y axis choice: where the number sits on a release side and which way is better. */
989
+ interface YMetric {
990
+ key: string;
991
+ label: string;
992
+ axis: string;
993
+ /** null = no known direction (product numbers): the table's arrow carries no color. */
994
+ better: "lower" | "higher" | null;
995
+ fmt(v: number): string;
996
+ get(side: ReleaseSideStats): number | null;
997
+ }
998
+
999
+ const LEDGER_METRICS: YMetric[] = [
1000
+ { key: "usd", label: "$/feat", axis: "$ per feature", better: "lower", fmt: v => `$${v.toFixed(2)}`, get: s => s.perFeature },
1001
+ { key: "perday", label: "/day", axis: "features per day", better: "higher", fmt: v => v.toFixed(2), get: s => s.featuresPerDay },
1002
+ { key: "calls", label: "calls", axis: "main calls per feature", better: "lower", fmt: v => v.toFixed(1), get: s => s.callsPerFeature },
1003
+ { key: "tok", label: "tok", axis: "tokens per call", better: "lower", fmt: v => v.toFixed(0), get: s => s.tokensPerCall },
1004
+ { key: "fix", label: "fix", axis: "fix plans per feature", better: "lower", fmt: v => v.toFixed(2), get: s => s.fixPlansPerFeature },
1005
+ ];
1006
+
1007
+ /** One metric per recorded product number, keyed `p:<name>` (repo-qualified when names clash). */
1008
+ function productMetrics(releases: ReleasesReport): YMetric[] {
1009
+ const pairs = new Map<string, { repo: string; name: string }>();
1010
+ for (const row of releases.rows) for (const p of [...row.before.products, ...row.after.products]) pairs.set(`${p.repo}|${p.name}`, p);
1011
+ const clashes: Record<string, number> = {};
1012
+ for (const { name } of pairs.values()) clashes[name] = (clashes[name] ?? 0) + 1;
1013
+ return [...pairs.values()]
1014
+ .sort((a, b) => (a.name + a.repo).localeCompare(b.name + b.repo))
1015
+ .map(({ repo, name }) => {
1016
+ const clash = (clashes[name] ?? 0) > 1;
1017
+ return {
1018
+ key: clash ? `p:${basename(repo)}:${name}` : `p:${name}`,
1019
+ label: clash ? `${basename(repo)}/${name}` : name,
1020
+ axis: `${name} (product number)`,
1021
+ better: null,
1022
+ fmt: (v: number) => String(Math.round(v * 100) / 100),
1023
+ get: (s: ReleaseSideStats): number | null => s.products.find(p => p.repo === repo && p.name === name)?.value ?? null,
1024
+ };
1025
+ });
1026
+ }
1027
+
1028
+ const RESULT_KINDS = ["product", "neurastream"] as const;
1029
+ const KIND_COLOR: Record<(typeof RESULT_KINDS)[number], string> = { product: "var(--acc)", neurastream: "var(--teal)" };
1030
+ const CHART_W = 390;
1031
+ const CHART_H = 200;
1032
+ const CHART_L = 48;
1033
+ const CHART_R = 8;
1034
+ const CHART_T = 10;
1035
+ const CHART_B = 20;
1036
+
1037
+ interface ChartPoint {
1038
+ px: number;
1039
+ py: number;
1040
+ label: string;
1041
+ value: number;
1042
+ }
1043
+ interface ChartSeries {
1044
+ label: string;
1045
+ color: string;
1046
+ points: ChartPoint[];
1047
+ }
1048
+
1049
+ /** The tab's controls: plain links, so the page's existing fetch/pushState swap handles them with no new script. */
1050
+ function resultsControls(all: YMetric[], y: YMetric, x: "time" | "feature"): string {
1051
+ const yLinks = all
1052
+ .map(m => `<a href="/?tab=results&amp;y=${m.key}&amp;x=${x}"${m.key === y.key ? ` class="on"` : ""}>${esc(m.label)}</a>`)
1053
+ .join("");
1054
+ const xLinks = (["time", "feature"] as const)
1055
+ .map(v => `<a href="/?tab=results&amp;y=${y.key}&amp;x=${v}"${v === x ? ` class="on"` : ""}>${v === "time" ? "time" : "feature"}</a>`)
1056
+ .join("");
1057
+ return `<div class="rlinks"><span>y</span>${yLinks}</div><div class="rlinks"><span>x</span>${xLinks}</div>`;
1058
+ }
1059
+
1060
+ /**
1061
+ * Hand-written inline SVG under the page's CSP: one polyline per series (product vs neurastream
1062
+ * for a ledger metric, one per product number), points carrying <title> tooltips, releases as
1063
+ * dashed verticals on the time axis, theme colors via the page's CSS variables.
1064
+ */
1065
+ function resultsChart(releases: ReleasesReport, y: YMetric, x: "time" | "feature"): string {
1066
+ const rows = releases.rows;
1067
+ const mid = CHART_L + (CHART_W - CHART_L - CHART_R) / 2;
1068
+ const t0 = rows[0]!.ts;
1069
+ const t1 = rows[rows.length - 1]!.ts;
1070
+ const pxOf = (i: number, ts: number): number =>
1071
+ x === "feature" ? (rows.length < 2 ? mid : CHART_L + (i / (rows.length - 1)) * (CHART_W - CHART_L - CHART_R))
1072
+ : t1 === t0 ? mid : CHART_L + ((ts - t0) / (t1 - t0)) * (CHART_W - CHART_L - CHART_R);
1073
+ const tip = (row: ReleaseRow, v: number): string => `${row.name} · ${y.fmt(v)} · ${strftime(row.ts, "%m-%d %H:%M")}`;
1074
+ const point = (row: ReleaseRow, i: number, v: number): ChartPoint => ({ px: pxOf(i, row.ts), py: 0, label: tip(row, v), value: v });
1075
+ const series: ChartSeries[] = LEDGER_METRICS.includes(y)
1076
+ ? RESULT_KINDS.map(kind => ({
1077
+ label: kind,
1078
+ color: KIND_COLOR[kind],
1079
+ points: rows.flatMap((row, i) => {
1080
+ if (row.kind !== kind) return [];
1081
+ const v = y.get(row.after);
1082
+ return v === null ? [] : [point(row, i, v)];
1083
+ }),
1084
+ }))
1085
+ : [
1086
+ {
1087
+ label: y.label,
1088
+ color: "var(--warn)",
1089
+ points: rows.flatMap((row, i) => {
1090
+ const v = y.get(row.after);
1091
+ return v === null ? [] : [point(row, i, v)];
1092
+ }),
1093
+ },
1094
+ ];
1095
+ const yMax = Math.max(...series.flatMap(s => s.points.map(p => p.value)), 1e-9);
1096
+ const pyOf = (v: number): number => CHART_T + (1 - v / yMax) * (CHART_H - CHART_T - CHART_B);
1097
+ const parts: string[] = [];
1098
+ for (const v of [0, yMax / 2, yMax]) {
1099
+ parts.push(`<line x1="${CHART_L}" x2="${CHART_W - CHART_R}" y1="${pyOf(v).toFixed(1)}" y2="${pyOf(v).toFixed(1)}" stroke="var(--bd)"/>`);
1100
+ parts.push(`<text x="${CHART_L - 5}" y="${(pyOf(v) + 3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--mut)">${esc(y.fmt(v))}</text>`);
1101
+ }
1102
+ if (x === "time") {
1103
+ for (const row of rows) {
1104
+ const px = pxOf(0, row.ts).toFixed(1);
1105
+ parts.push(
1106
+ `<line x1="${px}" x2="${px}" y1="${CHART_T}" y2="${CHART_H - CHART_B}" stroke="var(--bd)" stroke-dasharray="3 3"><title>${esc(`${row.name} · ${strftime(row.ts, "%m-%d %H:%M")}`)}</title></line>`,
1107
+ );
1108
+ }
1109
+ parts.push(`<text x="${CHART_L}" y="${CHART_H - 6}" font-size="10" fill="var(--mut)">${esc(strftime(t0, "%m-%d"))}</text>`);
1110
+ parts.push(`<text x="${CHART_W - CHART_R}" y="${CHART_H - 6}" text-anchor="end" font-size="10" fill="var(--mut)">${esc(strftime(t1, "%m-%d"))}</text>`);
1111
+ }
1112
+ for (const s of series) {
1113
+ if (s.points.length > 1) {
1114
+ const pts = s.points.map(p => `${p.px.toFixed(1)},${pyOf(p.value).toFixed(1)}`).join(" ");
1115
+ parts.push(`<polyline points="${pts}" fill="none" stroke="${s.color}" stroke-width="2"/>`);
1116
+ }
1117
+ for (const p of s.points) {
1118
+ parts.push(`<circle cx="${p.px.toFixed(1)}" cy="${pyOf(p.value).toFixed(1)}" r="3" fill="${s.color}"><title>${esc(p.label)}</title></circle>`);
1119
+ }
1120
+ }
1121
+ const legend = series.map(s => `<span style="color:${s.color}">— ${esc(s.label)}</span>`).join("");
1122
+ return `<p class="rlegend">${legend}</p><svg class="rchart" role="img" aria-label="${esc(`${y.axis} by ${x === "time" ? "day" : "release"}`)}" viewBox="0 0 ${CHART_W} ${CHART_H}">${parts.join("")}</svg>`;
1123
+ }
1124
+
1125
+ /** One row per release, the `metrics releases` table: before→after cells with ▲/▼, green when the change is for the better. */
1126
+ function resultsTable(releases: ReleasesReport, all: YMetric[]): string {
1127
+ const cell = (row: ReleaseRow, m: YMetric): string => {
1128
+ const before = m.get(row.before);
1129
+ const after = m.get(row.after);
1130
+ if (before === null || after === null) return `<td class="mutcell">–</td>`;
1131
+ const arrow = after > before ? "▲" : after < before ? "▼" : "·";
1132
+ const cls = m.better !== null && after !== before ? ((m.better === "lower") === (after < before) ? ` class="good"` : ` class="badv"`) : "";
1133
+ return `<td>${esc(m.fmt(before))}→${esc(m.fmt(after))}<span${cls}>${arrow}</span></td>`;
1134
+ };
1135
+ const head = `<tr><th>release</th>${all.map(m => `<th>${esc(m.label)}</th>`).join("")}</tr>`;
1136
+ const body = releases.rows
1137
+ .map(row =>
1138
+ `<tr><td>${esc(row.name)} <span class="note">${strftime(row.ts, "%m-%d")}</span>${row.measuring ? ` <span class="chip c-ready">measuring</span>` : ""}</td>${all.map(m => cell(row, m)).join("")}</tr>`,
1139
+ )
1140
+ .join("");
1141
+ return `<div class="tscroll"><table><thead>${head}</thead><tbody>${body}</tbody></table></div>`;
1142
+ }
1143
+
1144
+ const RESULTS_CAVEAT = "Fixes inside the same plan are not split out; plans that do not cite an earlier stem are not linked. Product numbers carry no better/worse color.";
1145
+
1146
+ function resultsTabHtml(d: ResultsData | null | undefined, params: URLSearchParams): string {
1147
+ if (!d) return `<h1>Results</h1>${na("Results")}`;
1148
+ if (!d.releases.rows.length) {
1149
+ const empty = d.features.rows.length ? "No releases recorded yet" : "No finished features yet";
1150
+ return `<h1>Results</h1><div class="card"><p class="empty">${empty}</p></div><p class="sub">${RESULTS_CAVEAT}</p>`;
1151
+ }
1152
+ const x = params.get("x") === "feature" ? "feature" : "time";
1153
+ const all = [...LEDGER_METRICS, ...productMetrics(d.releases)];
1154
+ // An unknown y falls back to $/feature.
1155
+ const y = all.find(m => m.key === params.get("y")) ?? all[0]!;
1156
+ return `<h1>Results</h1>
1157
+ <p class="sub">What features cost and whether releases made it better or worse.</p>
1158
+ <div class="card">
1159
+ ${resultsControls(all, y, x)}
1160
+ ${resultsChart(d.releases, y, x)}
1161
+ </div>
1162
+ <h2>Releases <small>${d.releases.days} days before → after</small></h2>
1163
+ <div class="card">
1164
+ ${resultsTable(d.releases, all)}
1165
+ </div>
1166
+ <p class="sub">${RESULTS_CAVEAT}</p>`;
1167
+ }
1168
+
949
1169
  /** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
950
1170
  export function renderPage(cfg: Config, data: PageData, params: URLSearchParams, nonce: string): string {
951
1171
  const req = params.get("tab") ?? "";
@@ -1005,7 +1225,8 @@ ${machine}
1005
1225
  </div>`
1006
1226
  : tab === "knowledge"
1007
1227
  ? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "")}`
1008
- : `<h1>Spend</h1>
1228
+ : tab === "spend"
1229
+ ? `<h1>Spend</h1>
1009
1230
  <p class="sub">List price over the last 24 hours.</p>
1010
1231
  <div class="card">
1011
1232
  ${spendTileHtml(data)}
@@ -1013,7 +1234,8 @@ ${spendTileHtml(data)}
1013
1234
  <h2>By model</h2>
1014
1235
  <div class="card">
1015
1236
  ${modelSpendTable(data.stats)}
1016
- </div>`;
1237
+ </div>`
1238
+ : resultsTabHtml(data.results, params);
1017
1239
  return `<!doctype html>
1018
1240
  <html lang="en">
1019
1241
  <head>
@@ -1030,8 +1252,8 @@ html{scroll-padding-top:64px}
1030
1252
  body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.4 system-ui,-apple-system,sans-serif}
1031
1253
  .top{position:sticky;top:0;display:flex;align-items:center;gap:8px;padding:10px 12px;background:var(--bg);z-index:2}
1032
1254
  .logo{font-weight:800;color:var(--acc)}
1033
- .pills{display:flex;background:var(--card);border:1px solid var(--bd);border-radius:999px;padding:3px;flex:1}
1034
- .pills a{flex:1;text-align:center;padding:5px 0;border-radius:999px;color:var(--mut);text-decoration:none;font-size:13px}
1255
+ .pills{display:flex;background:var(--card);border:1px solid var(--bd);border-radius:999px;padding:3px;flex:1;gap:3px;overflow-x:auto}
1256
+ .pills a{flex:none;text-align:center;padding:5px 10px;border-radius:999px;color:var(--mut);text-decoration:none;font-size:13px;white-space:nowrap}
1035
1257
  .pills a.on{background:var(--bg);color:var(--fg);font-weight:600;box-shadow:0 0 0 1px var(--bd)}
1036
1258
  .lock{border:1px solid var(--bd);background:var(--card);border-radius:999px;padding:6px 10px;font-size:13px;color:var(--fg);position:relative;flex:none}
1037
1259
  .lock summary{list-style:none;white-space:nowrap}
@@ -1110,6 +1332,15 @@ table{border-collapse:collapse;width:100%;font-size:13px}
1110
1332
  th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--bd);font-variant-numeric:tabular-nums}
1111
1333
  th{color:var(--mut);font-weight:600}
1112
1334
  tr:last-child td{border-bottom:none}
1335
+ .tscroll{overflow-x:auto}
1336
+ td.mutcell{color:var(--mut)}
1337
+ span.good{color:var(--ok);font-weight:600}
1338
+ span.badv{color:var(--red);font-weight:600}
1339
+ .rlinks{display:flex;gap:6px;align-items:center;flex-wrap:wrap;padding:10px 14px 0;font-size:12px;color:var(--mut)}
1340
+ .rlinks a{border:1px solid var(--bd);border-radius:999px;padding:3px 10px;color:var(--mut);text-decoration:none;background:var(--card)}
1341
+ .rlinks a.on{color:var(--fg);background:var(--bg);font-weight:600;box-shadow:0 0 0 1px var(--bd)}
1342
+ .rlegend{margin:0;padding:10px 14px 0;font-size:12px;color:var(--mut);display:flex;gap:12px}
1343
+ .rchart{width:100%;height:auto;display:block;padding:4px 2px 8px}
1113
1344
  .merges,.incidents{margin:0;padding:8px 14px 8px 32px}
1114
1345
  .merges li,.incidents li{margin:6px 0}
1115
1346
  .mrow{display:flex;justify-content:space-between;gap:12px;padding:6px 0;border-bottom:1px solid var(--bd)}
@@ -8,7 +8,8 @@ import { finishedEntry, finishedKey, finishedPath, parsePlan, planRepo, prependF
8
8
 
9
9
  const USAGE = "usage: queue-finished --backfill | --dedupe | queue-finished <word>";
10
10
 
11
- function walkMd(dir: string, out: string[]): void {
11
+ /** Shared with src/core/results.ts: every *.md under dir, recursively. */
12
+ export function walkMd(dir: string, out: string[]): void {
12
13
  let names: string[];
13
14
  try {
14
15
  names = readdirSync(dir);
@@ -28,8 +29,8 @@ function walkMd(dir: string, out: string[]): void {
28
29
  }
29
30
  }
30
31
 
31
- /** Repos named by work_roots, plus one level of children so a root that holds many checkouts still counts. */
32
- function repoRoots(roots: string[]): string[] {
32
+ /** Repos named by work_roots, plus one level of children so a root that holds many checkouts still counts. Shared with src/core/results.ts. */
33
+ export function repoRoots(roots: string[]): string[] {
33
34
  const out: string[] = [];
34
35
  for (const root of roots) {
35
36
  if (!existsSync(root)) continue;
@@ -0,0 +1,408 @@
1
+ // Feature results (plan 20261025_2148 P2): a feature is a plan plus every later plan whose
2
+ // ## Goal names its file stem; finished chains are priced from the runs' message costs. Plan
3
+ // discovery reuses the queue's walkers (no new path config); all functions here are pure over
4
+ // their arguments — the CLI passes the run source, the window and the self repo.
5
+
6
+ import { readFileSync, realpathSync, statSync } from "node:fs";
7
+ import path from "node:path";
8
+ import type { Run } from "./adapter.ts";
9
+ import type { Config } from "./config.ts";
10
+ import type { Ev } from "./metrics.ts";
11
+ import { applyQueueEnv } from "./queue/env.ts";
12
+ import { gitTop, parsePlan } from "./queue/lib.ts";
13
+ import { repoRoots, walkMd } from "./queue-finished.ts";
14
+
15
+ const HOUR = 3600;
16
+ const DAY = 86400;
17
+ const STEM = /^\d{8}_\d{4}_/;
18
+
19
+ export interface PlanNode {
20
+ stem: string;
21
+ file: string;
22
+ repo: string;
23
+ /** Earlier stems this plan's Goal names that exist. */
24
+ parents: string[];
25
+ archived: boolean;
26
+ closed: boolean;
27
+ /** Newest dated Progress entry, unix seconds; null when none parses. */
28
+ closedAt: number | null;
29
+ }
30
+
31
+ export interface Chain {
32
+ stem: string;
33
+ kind: "product" | "neurastream";
34
+ repo: string;
35
+ stems: string[];
36
+ fixPlans: number;
37
+ closed: boolean;
38
+ closedAt: number | null;
39
+ }
40
+
41
+ /** One dated Progress entry: `- 2026-10-26 12:00 CEST Main: ...`; time and zone are optional and a bare stamp is local time. */
42
+ const DATED = /^- (\d{4})-(\d{2})-(\d{2})(?: (\d{2}):(\d{2}))?(?: \(?(CEST|CET)\)?)?/gm;
43
+ const ZONE_OFFSET: Record<string, number> = { CEST: 120, CET: 60 };
44
+
45
+ /** Newest dated Progress entry as unix seconds; null when the text has none. */
46
+ export function closeTime(text: string): number | null {
47
+ let best: number | null = null;
48
+ for (const m of text.matchAll(DATED)) {
49
+ const [, Y, M, D, h = "0", min = "0", zone] = m as RegExpExecArray & string[];
50
+ const utc = Date.UTC(Number(Y), Number(M) - 1, Number(D), Number(h), Number(min)) / 1000;
51
+ const ts = zone ? utc - ZONE_OFFSET[zone]! * 60 : new Date(Number(Y), Number(M) - 1, Number(D), Number(h), Number(min)).getTime() / 1000;
52
+ if (best === null || ts > best) best = ts;
53
+ }
54
+ return best;
55
+ }
56
+
57
+ /** git writes a worktree's gitdir through symlinks resolved (macOS /var → /private/var), so a repo path is compared in its real form. */
58
+ function realRepo(p: string): string {
59
+ try {
60
+ return realpathSync(p);
61
+ } catch {
62
+ return p;
63
+ }
64
+ }
65
+
66
+ /** Every dated plan under docs/plans/** of each repo the queue knows (work_roots plus one level of children). A git worktree carries a copy of docs/plans and gitTop maps it to the main checkout, so one node per (canonical repo, stem) survives: an archived or closed copy beats an open one, else the newest mtime wins. */
67
+ export function loadPlans(cfg: Config): PlanNode[] {
68
+ applyQueueEnv(cfg);
69
+ const best = new Map<string, { node: PlanNode; mtime: number }>();
70
+ for (const repo of repoRoots(cfg.paths.work_roots)) {
71
+ const files: string[] = [];
72
+ walkMd(path.join(repo, "docs/plans"), files);
73
+ for (const file of files) {
74
+ const base = path.basename(file);
75
+ // Progress archives (<stem>-progress.md) and unstamped lists (CANCELLED.md) are not plans.
76
+ if (!STEM.test(base) || base.endsWith("-progress.md")) continue;
77
+ let text: string;
78
+ try {
79
+ text = readFileSync(file, "utf8");
80
+ } catch {
81
+ continue;
82
+ }
83
+ let mtime = 0;
84
+ try {
85
+ mtime = statSync(file).mtimeMs;
86
+ } catch {}
87
+ const archived = file.split(path.sep).includes("archive");
88
+ const status = parsePlan(repo, file, text).status;
89
+ const node: PlanNode = {
90
+ stem: base.slice(0, -3),
91
+ file,
92
+ repo: realRepo(gitTop(file)?.repo ?? repo),
93
+ parents: [],
94
+ archived,
95
+ closed: archived || status === "complete" || status === "cancelled",
96
+ closedAt: closeTime(text),
97
+ };
98
+ const key = `${node.repo}/${node.stem}`;
99
+ const cur = best.get(key);
100
+ if (!cur || (node.closed !== cur.node.closed ? node.closed : mtime > cur.mtime)) best.set(key, { node, mtime });
101
+ }
102
+ }
103
+ const nodes = [...best.values()].map(b => b.node);
104
+ const stems = new Set(nodes.map(n => n.stem));
105
+ for (const n of nodes) {
106
+ let text = "";
107
+ try {
108
+ text = readFileSync(n.file, "utf8");
109
+ } catch {
110
+ continue;
111
+ }
112
+ const goal = parsePlan(n.repo, n.file, text).goal.join("\n");
113
+ n.parents = [...stems].filter(s => s !== n.stem && goal.includes(s));
114
+ }
115
+ return nodes;
116
+ }
117
+
118
+ /** Connected chains: B joins A when B's Goal names A's stem; the root is the oldest member. */
119
+ export function chains(plans: PlanNode[], selfRepo: string | null): Chain[] {
120
+ if (selfRepo !== null) selfRepo = realRepo(selfRepo);
121
+ const up = new Map<string, string>();
122
+ const find = (s: string): string => {
123
+ let root = s;
124
+ while (up.get(root) !== root) root = up.get(root)!;
125
+ return root;
126
+ };
127
+ for (const p of plans) up.set(p.stem, p.stem);
128
+ const known = new Set(plans.map(p => p.stem));
129
+ for (const p of plans) for (const parent of p.parents) if (known.has(parent)) up.set(p.stem, parent);
130
+ const members = new Map<string, PlanNode[]>();
131
+ for (const p of plans) {
132
+ const root = find(p.stem);
133
+ members.set(root, [...(members.get(root) ?? []), p]);
134
+ }
135
+ const out: Chain[] = [];
136
+ for (const group of members.values()) {
137
+ group.sort((a, b) => (a.stem < b.stem ? -1 : 1));
138
+ const closed = group.every(p => p.closed);
139
+ const closedAt = group.reduce<number | null>((best, p) => (p.closedAt !== null && (best === null || p.closedAt > best) ? p.closedAt : best), null);
140
+ out.push({
141
+ stem: group[0]!.stem,
142
+ kind: selfRepo !== null && group[0]!.repo === selfRepo ? "neurastream" : "product",
143
+ repo: group[0]!.repo,
144
+ stems: group.map(p => p.stem),
145
+ fixPlans: group.length - 1,
146
+ closed,
147
+ closedAt,
148
+ });
149
+ }
150
+ return out;
151
+ }
152
+
153
+ export interface Attribution {
154
+ byPlan: Map<string, number>;
155
+ overhead: number;
156
+ /** Every bucketed Main $ in the window: the denominator of overhead %. */
157
+ mainTotal: number;
158
+ }
159
+
160
+ /** Stems named in a text, in order of first mention. */
161
+ function namedStems(text: string, stems: string[]): string[] {
162
+ const hits: [string, number][] = [];
163
+ for (const s of stems) {
164
+ const at = text.indexOf(s);
165
+ if (at >= 0) hits.push([s, at]);
166
+ }
167
+ return hits.sort((a, b) => a[1] - b[1]).map(([s]) => s);
168
+ }
169
+
170
+ /**
171
+ * Main message cost is bucketed per hour; an hour's cost splits evenly over the plan stems that
172
+ * hour's messages name (none → overhead). A sub run's whole cost goes to the stem in its first
173
+ * user message (none → overhead). A message without ts is not bucketable and counts nowhere.
174
+ */
175
+ export function attributeCosts(runs: Run[], stems: string[], from: number, to: number): Attribution {
176
+ const byPlan = new Map<string, number>();
177
+ const inWindow = (t: number) => t >= from && t < to;
178
+ const hours = new Map<number, { cost: number; text: string }>();
179
+ let overhead = 0;
180
+ let mainTotal = 0;
181
+ for (const run of runs) {
182
+ if (run.kind === "main") {
183
+ for (const m of run.messages) {
184
+ if (m.ts === null || !inWindow(m.ts)) continue;
185
+ const bucket = Math.floor(m.ts / HOUR) * HOUR;
186
+ const h = hours.get(bucket) ?? { cost: 0, text: "" };
187
+ h.cost += m.cost;
188
+ h.text += `\n${m.text}`;
189
+ hours.set(bucket, h);
190
+ mainTotal += m.cost;
191
+ }
192
+ continue;
193
+ }
194
+ const first = run.messages.find(m => m.role === "user");
195
+ if (!first) continue;
196
+ if (!inWindow(first.ts ?? run.lastWriteAt)) continue;
197
+ const named = namedStems(first.text, stems)[0];
198
+ if (named) byPlan.set(named, (byPlan.get(named) ?? 0) + run.cost);
199
+ else overhead += run.cost;
200
+ }
201
+ for (const h of hours.values()) {
202
+ const named = namedStems(h.text, stems);
203
+ if (!named.length) overhead += h.cost;
204
+ else for (const s of named) byPlan.set(s, (byPlan.get(s) ?? 0) + h.cost / named.length);
205
+ }
206
+ return { byPlan, overhead, mainTotal };
207
+ }
208
+
209
+ export interface ChainRow {
210
+ stem: string;
211
+ kind: "product" | "neurastream";
212
+ plans: number;
213
+ fixPlans: number;
214
+ total: number;
215
+ first: number;
216
+ closedAt: number;
217
+ }
218
+
219
+ export interface KindSummary {
220
+ kind: "product" | "neurastream";
221
+ finished: number;
222
+ perDay: number;
223
+ perFeature: number | null;
224
+ firstPass: number | null;
225
+ overheadPct: number | null;
226
+ openChains: number;
227
+ openSunk: number;
228
+ }
229
+
230
+ export interface FeaturesReport {
231
+ days: number;
232
+ from: number;
233
+ to: number;
234
+ rows: ChainRow[];
235
+ summaries: KindSummary[];
236
+ }
237
+
238
+ const KINDS = ["product", "neurastream"] as const;
239
+
240
+ /** One row per finished chain closed in [from, to), plus a per-kind summary. A closed chain with no dated Progress entry has no place in a window and is left out. */
241
+ export function featuresReport(runs: Run[], plans: PlanNode[], selfRepo: string | null, from: number, to: number): FeaturesReport {
242
+ const days = (to - from) / DAY;
243
+ const all = chains(plans, selfRepo);
244
+ const att = attributeCosts(runs, all.flatMap(c => c.stems), from, to);
245
+ const chainCost = (c: Chain) => c.stems.reduce((sum, s) => sum + (att.byPlan.get(s) ?? 0), 0);
246
+ const rows: ChainRow[] = all
247
+ .filter(c => c.closed && c.closedAt !== null && c.closedAt >= from && c.closedAt < to)
248
+ .map(c => ({
249
+ stem: c.stem,
250
+ kind: c.kind,
251
+ plans: c.stems.length,
252
+ fixPlans: c.fixPlans,
253
+ total: chainCost(c),
254
+ first: att.byPlan.get(c.stem) ?? 0,
255
+ closedAt: c.closedAt!,
256
+ }))
257
+ .sort((a, b) => a.closedAt - b.closedAt);
258
+ const summaries = KINDS.map(kind => {
259
+ const mine = rows.filter(r => r.kind === kind);
260
+ const finished = mine.length;
261
+ const total = mine.reduce((s, r) => s + r.total, 0);
262
+ const first = mine.reduce((s, r) => s + r.first, 0);
263
+ const open = all.filter(c => !c.closed && c.kind === kind && chainCost(c) > 0);
264
+ return {
265
+ kind,
266
+ finished,
267
+ perDay: finished / days,
268
+ perFeature: finished > 0 ? total / finished : null,
269
+ firstPass: finished > 0 ? first / finished : null,
270
+ overheadPct: att.mainTotal > 0 ? (att.overhead / att.mainTotal) * 100 : null,
271
+ openChains: open.length,
272
+ openSunk: open.reduce((s, c) => s + chainCost(c), 0),
273
+ };
274
+ });
275
+ return { days, from, to, rows, summaries };
276
+ }
277
+
278
+ // ---- P3: releases ----
279
+
280
+ export interface ReleaseTag {
281
+ name: string;
282
+ ts: number;
283
+ }
284
+
285
+ /** The self repo's `v*` tags with their tag dates; a non-git repo or a git failure lists none. Lives here (not cli/) because the owner page's Results tab reads it too. */
286
+ export function gatherTags(repo: string | null): ReleaseTag[] {
287
+ if (!repo) return [];
288
+ const proc = Bun.spawnSync(["git", "-C", repo, "for-each-ref", "refs/tags/v*", "--format=%(refname:short) %(creatordate:unix)"], {
289
+ stdout: "pipe",
290
+ stderr: "pipe",
291
+ });
292
+ if (proc.exitCode !== 0) return [];
293
+ const out: ReleaseTag[] = [];
294
+ for (const line of proc.stdout.toString().split("\n")) {
295
+ const m = line.match(/^(\S+) (\d+)$/);
296
+ if (m) out.push({ name: m[1]!, ts: Number(m[2]) });
297
+ }
298
+ return out;
299
+ }
300
+
301
+ export interface ProductValue {
302
+ repo: string;
303
+ name: string;
304
+ /** null = this side has no recorded value for the number yet. */
305
+ value: number | null;
306
+ }
307
+
308
+ export interface ReleaseSideStats {
309
+ perFeature: number | null;
310
+ featuresPerDay: number | null;
311
+ /** Main calls in the window per finished feature of the release's kind. */
312
+ callsPerFeature: number | null;
313
+ /** Tokens per call over every run written in the window. */
314
+ tokensPerCall: number | null;
315
+ fixPlansPerFeature: number | null;
316
+ products: ProductValue[];
317
+ }
318
+
319
+ export interface ReleaseRow {
320
+ name: string;
321
+ kind: "product" | "neurastream";
322
+ repo: string;
323
+ ts: number;
324
+ /** True until `days` have passed since the release: the after side is still filling. */
325
+ measuring: boolean;
326
+ before: ReleaseSideStats;
327
+ after: ReleaseSideStats;
328
+ }
329
+
330
+ export interface ReleasesReport {
331
+ days: number;
332
+ rows: ReleaseRow[];
333
+ }
334
+
335
+ /** The ledger metrics for one side of a release's window [from, to), same source as `metrics features`. */
336
+ function releaseSide(kind: Chain["kind"], runs: Run[], plans: PlanNode[], selfRepo: string | null, from: number, to: number): Omit<ReleaseSideStats, "products"> {
337
+ const rep = featuresReport(runs, plans, selfRepo, from, to);
338
+ const mine = rep.rows.filter(r => r.kind === kind);
339
+ let mainCalls = 0;
340
+ let tokens = 0;
341
+ let calls = 0;
342
+ for (const r of runs) {
343
+ if (r.lastWriteAt < from || r.lastWriteAt >= to) continue;
344
+ if (r.kind === "main") mainCalls += r.calls;
345
+ tokens += r.tokens;
346
+ calls += r.calls;
347
+ }
348
+ return {
349
+ perFeature: rep.summaries.find(s => s.kind === kind)!.perFeature,
350
+ featuresPerDay: rep.summaries.find(s => s.kind === kind)!.perDay,
351
+ callsPerFeature: mine.length > 0 ? mainCalls / mine.length : null,
352
+ tokensPerCall: calls > 0 ? tokens / calls : null,
353
+ fixPlansPerFeature: mine.length > 0 ? mine.reduce((sum, r) => sum + r.fixPlans, 0) / mine.length : null,
354
+ };
355
+ }
356
+
357
+ interface ProductRow {
358
+ repo: string;
359
+ name: string;
360
+ value: number;
361
+ ts: number;
362
+ }
363
+
364
+ /**
365
+ * One row per release: the same N-day ledger metrics before vs after it. A release is a `v*` tag
366
+ * of the self repo (kind neurastream) or a `metrics ci` merge of another repo (kind product); a
367
+ * ci merge of the self repo is not a release — its tag already is. Each product number recorded
368
+ * in metrics.jsonl shows its last value before vs its first value after the release.
369
+ */
370
+ export function releasesReport(runs: Run[], plans: PlanNode[], selfRepo: string | null, days: number, now: number, tags: ReleaseTag[], events: Ev[]): ReleasesReport {
371
+ if (selfRepo !== null) selfRepo = realRepo(selfRepo);
372
+ const span = days * DAY;
373
+ const products: ProductRow[] = [];
374
+ const merges: { repo: string; mr: string; ts: number }[] = [];
375
+ for (const e of events) {
376
+ if (e.type === "product" && typeof e.repo === "string" && typeof e.name === "string" && typeof e.value === "number" && typeof e.ts === "number") {
377
+ products.push({ repo: e.repo, name: e.name, value: e.value, ts: e.ts });
378
+ } else if (e.type === "ci" && typeof e.repo === "string" && typeof e.ts === "number" && realRepo(e.repo) !== selfRepo) {
379
+ merges.push({ repo: e.repo, mr: String(e.mr), ts: e.ts });
380
+ }
381
+ }
382
+ const keys = [...new Set(products.map(p => `${p.repo}|${p.name}`))].sort();
383
+ const releases = [
384
+ ...tags.map(t => ({ name: t.name, kind: "neurastream" as const, repo: selfRepo ?? "", ts: t.ts })),
385
+ ...merges.map(m => ({ name: `${path.basename(m.repo)}#${m.mr}`, kind: "product" as const, repo: m.repo, ts: m.ts })),
386
+ ].sort((a, b) => a.ts - b.ts);
387
+ const rows = releases.map((r) => {
388
+ const productValues = (before: boolean): ProductValue[] =>
389
+ keys.map((k) => {
390
+ const [repo, name] = k.split("|") as [string, string];
391
+ const mine = products.filter(p => p.repo === repo && p.name === name).sort((a, b) => a.ts - b.ts);
392
+ const hit = before ? (mine.filter(p => p.ts < r.ts).at(-1) ?? null) : (mine.find(p => p.ts >= r.ts) ?? null);
393
+ return { repo, name, value: hit?.value ?? null };
394
+ });
395
+ const before = releaseSide(r.kind, runs, plans, selfRepo, r.ts - span, r.ts);
396
+ const after = releaseSide(r.kind, runs, plans, selfRepo, r.ts, r.ts + span);
397
+ return {
398
+ name: r.name,
399
+ kind: r.kind,
400
+ repo: r.repo,
401
+ ts: r.ts,
402
+ measuring: r.ts + span > now,
403
+ before: { ...before, products: productValues(true) },
404
+ after: { ...after, products: productValues(false) },
405
+ };
406
+ });
407
+ return { days, rows };
408
+ }
@@ -176,6 +176,10 @@ metrics:
176
176
  report_days: 7
177
177
  correction_patterns: ['\bno\b', 'wrong', 'why did', 'properly', 'not what', 'stop', 'bullshit', 'fuck']
178
178
  ci_pipelines_cmd: "" # command run in the repo dir with {mr} replaced; stdout must be a JSON array; "" = not set
179
+ product_cmds: {} # {<repo path>: {<name>: shell command printing one number}}, run in that repo after every `metrics ci` merge
180
+ # product_cmds:
181
+ # /opt/myapp:
182
+ # dist_mb: "du -sm frontend/dist | cut -f1"
179
183
 
180
184
  incidents:
181
185
  contradiction_grace_min: 3 # minutes after a finished task-result before a RUNNING/WAITING ledger row is a contradiction