neurastream 0.2.49 → 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.
@@ -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
+ }
@@ -150,7 +150,7 @@ autonomy:
150
150
 
151
151
  review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
152
152
  since: "2026-10-28" # plans stamped before this ISO date are exempt from the reuse-line and reviewer-PASS gates; "" = off
153
- agents: ["reviewer"] # agents allowed to run a review spawn: the PASS exemption needs one plus the brief's `Plan review:` line
153
+ agents: ["reviewer"] # agents allowed to run a review spawn: one must be in "## Allowed" of notes/subagents.md (doctor and queue-check fail otherwise, e.g. ["glm"]); the PASS exemption needs one plus the brief's `Plan review:` line
154
154
  mr_cache_minutes: 10 # minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache
155
155
 
156
156
  ui:
@@ -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
@@ -14,16 +14,14 @@ Stop and report within ~20 tool calls.
14
14
  ## Task
15
15
  1. Read the plan whole, then every file it cites — each `## Reuse` line's `checked: <path>:<n>` opened at that path:line, confirming the cited code is what the line claims.
16
16
  2. For each unticked phase, grep the repo for code that already does that phase's job; a phase re-doing existing code is redundant.
17
- 3. List the repo's open MRs (`glab mr list`, or `gh pr list`) and compare each diff with the phases. Name every open MR on its own line here:
18
- MR !<N>: <what it holds> — this task: <why this review does not redo it>
19
- 4. Judge the plan's design for: secrets or credentials in examples, auth and input-trust mistakes, wasteful work (needless dependencies, duplicate state, what an existing guard or config key already covers).
17
+ 3. Judge the plan's design for: secrets or credentials in examples, auth and input-trust mistakes, wasteful work (needless dependencies, duplicate state, what an existing guard or config key already covers).
20
18
 
21
19
  ## Report
22
20
  Append one entry to the plan's `## Progress` — the PASS is recorded by plan-guard from that subagent edit only (Main can never write it), and it expires when the plan text changes:
23
21
 
24
- PLAN REVIEW: PASS|FAIL — redundant: <finding or none, file:line> — inefficient: <finding or none, file:line> — insecure: <finding or none, file:line> — MRs: <finding or none, file:line>
22
+ - <date> <time> <YourName>: PLAN REVIEW: PASS|FAIL — redundant: <finding or none, file:line> — inefficient: <finding or none, file:line> — insecure: <finding or none, file:line>
25
23
 
26
24
  ending with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence (a FAIL finding opens an incident like any other).
27
25
 
28
26
  ## Acceptance
29
- - the plan's `## Progress` holds the one `PLAN REVIEW:` entry with all four fields and a `Findings:` line
27
+ - the plan's `## Progress` holds the one `PLAN REVIEW:` entry with all three fields and a `Findings:` line