neurastream 0.2.61 → 0.2.63

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 (39) hide show
  1. package/README.md +36 -0
  2. package/package.json +1 -1
  3. package/src/adapters/omp/index.ts +36 -30
  4. package/src/adapters/omp/launch.ts +6 -1
  5. package/src/cli/commands.ts +3 -2
  6. package/src/cli/dispatch.ts +76 -1
  7. package/src/cli/init.ts +8 -0
  8. package/src/cli/metrics.ts +15 -55
  9. package/src/cli/pages.ts +10 -3
  10. package/src/cli/ui.ts +8 -1
  11. package/src/cli/watch-setup.ts +74 -0
  12. package/src/core/brief-lint.ts +4 -0
  13. package/src/core/ci.ts +271 -0
  14. package/src/core/config.ts +73 -1
  15. package/src/core/guards.ts +146 -42
  16. package/src/core/heartbeat.ts +79 -0
  17. package/src/core/incident-detectors.ts +104 -17
  18. package/src/core/incidents.ts +31 -4
  19. package/src/core/main-start.ts +83 -2
  20. package/src/core/metrics.ts +3 -2
  21. package/src/core/mr-sweep.ts +14 -7
  22. package/src/core/owner-ui.ts +4 -2
  23. package/src/core/plan-approval.ts +1 -1
  24. package/src/core/queue/lib.ts +85 -10
  25. package/src/core/queue-cancel.ts +1 -1
  26. package/src/core/queue-check.ts +8 -2
  27. package/src/core/queue-close.ts +19 -2
  28. package/src/core/queue-trim.ts +4 -0
  29. package/src/core/report.ts +88 -6
  30. package/src/core/rollover.ts +47 -5
  31. package/src/core/ui-setup.ts +5 -3
  32. package/src/core/waiting-check.ts +131 -0
  33. package/src/core/watch.ts +509 -0
  34. package/templates/config.yml +27 -4
  35. package/templates/help/watch.txt +45 -0
  36. package/templates/launchd/neurastream-watch.plist +17 -0
  37. package/templates/queue/TEMPLATE.md +5 -1
  38. package/templates/systemd/neurastream-watch.service +6 -0
  39. package/templates/systemd/neurastream-watch.timer +10 -0
@@ -0,0 +1,509 @@
1
+ // The watcher (plan 20261027_1430 P2, replaces live_recheck P5d): one pass over the job
2
+ // heartbeats (P1), the failed user units and the gated incident detectors — with or without a
3
+ // Main session open. Every problem folds into the incident store with source "watch" and a
4
+ // fingerprint per job+state, so a still-failing job dedupes into one open incident and a new
5
+ // failure after recovery opens a fresh one; a watch incident whose problem is gone is closed
6
+ // again via dismissIncident. Each NEW incident also posts one ⚠ message (P3) through the
7
+ // injected notifier — the watcher pushes, it never restarts a service or edits plans. The
8
+ // clock, the unit lister, the detector gather and the notifier are injected: tests touch only a
9
+ // temp queue_state, never a real home, network or service manager.
10
+ // CI (P6b, ci.ts) adds four checks per repo of an active plan: a red default branch (ci-red-main),
11
+ // a red open MR past watch.ci_red_hours (ci-red-mr), M3 `ci` for every newly merged MR, and a
12
+ // `ci-flaky` metric when a commit goes red then green.
13
+
14
+ import { spawnSync } from "node:child_process";
15
+ import { existsSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { Glob } from "bun";
18
+ import type { Config } from "./config.ts";
19
+ import type { RunSource } from "./adapter.ts";
20
+ import { readEvents } from "./agent-score.ts";
21
+ import { strftime } from "./clock.ts";
22
+ import { readBeats, type Heartbeat } from "./heartbeat.ts";
23
+ import { runDetectorsGated, type GatedInputs } from "./incident-detectors.ts";
24
+ import { log, readStaffingEntries } from "./guards.ts";
25
+ import { appendMetric, inWindow, readBlocks, readMetricEvents, reasonKey, type Window } from "./metrics.ts";
26
+ import { notifyProviders } from "./notify.ts";
27
+ import { addIncident, dismissIncident, openIncidents, readIncidents, type IncidentView } from "./incidents.ts";
28
+ import { m7, rowsOf, silentFailures, snap } from "./report.ts";
29
+ import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
30
+ import { ciScan } from "./ci.ts";
31
+ import type { CommandRunner } from "./mr-sweep.ts";
32
+ import type { ReleaseTag } from "./results.ts";
33
+
34
+ /** One failed user unit, as the lister reports it. */
35
+ export interface FailedUnit {
36
+ /** Unit name as the service manager spells it, e.g. wip-backup.service. */
37
+ name: string;
38
+ /** The unit's last error line; "" or undefined when the journal cannot be read. */
39
+ error?: string;
40
+ }
41
+
42
+ /** Reads the failed user units. Production: systemUnitLister; tests inject their own. */
43
+ export type UnitLister = () => FailedUnit[];
44
+
45
+ /** The last error-looking line of a unit's user journal, or "" when none is readable. */
46
+ function lastErrorLine(unit: string): string {
47
+ try {
48
+ const r = spawnSync("journalctl", ["--user", "-u", unit, "-n", "200", "--no-pager", "-o", "cat"], { encoding: "utf8", timeout: 30000 });
49
+ if (r.status !== 0 || !r.stdout) return "";
50
+ const lines = r.stdout.split("\n").filter(l => l.trim());
51
+ for (let i = lines.length - 1; i >= 0; i--) {
52
+ if (/fail|error|exit-code|exception|fatal|panic|denied|timeout/i.test(lines[i]!)) return lines[i]!.slice(0, 200);
53
+ }
54
+ return "";
55
+ } catch {
56
+ return "";
57
+ }
58
+ }
59
+
60
+ /** Production lister: failed systemd user units, read-only. launchd keeps no failed state to
61
+ * list; the timer side of the service-manager seam is P4. A missing or erroring manager (no
62
+ * user bus, non-Linux box) lists nothing — a watcher must not crash for lack of systemd. */
63
+ export const systemUnitLister: UnitLister = () => {
64
+ let names: string[] = [];
65
+ try {
66
+ const r = spawnSync("systemctl", ["--user", "list-units", "--state=failed", "--no-legend", "--no-pager"], { encoding: "utf8", timeout: 30000 });
67
+ if (r.status !== 0 || !r.stdout) return [];
68
+ names = r.stdout.split("\n").map(l => l.trim().split(/\s+/)[0] ?? "").filter(n => n.includes("."));
69
+ } catch {
70
+ return [];
71
+ }
72
+ return names.map(name => ({ name, error: lastErrorLine(name) }));
73
+ };
74
+
75
+ /** Injectable seams of one watch run. */
76
+ export interface WatchDeps {
77
+ /** Unix seconds "now"; injected so tests control the staleness windows. */
78
+ now: () => number;
79
+ /** The failed user units; injected so tests never touch a service manager. */
80
+ listUnits: UnitLister;
81
+ /** Expensive detector inputs; the same gather mainDetectors uses (src/core/main-start.ts). */
82
+ gather: () => GatedInputs;
83
+ /** The chat notifier, e.g. a fire-and-forget postReply — injected so tests never post for
84
+ * real. Called at most watch.max_posts_per_run times per run plus one overflow line, and
85
+ * only when a notify provider is configured. */
86
+ notify: (text: string) => void;
87
+ /** The forge CLI runner the CI check uses (mr-sweep's CommandRunner), so tests never run glab or gh. */
88
+ runner: CommandRunner;
89
+ /** The active plans: the CI check reads their repos and the MRs they name. */
90
+ plans: () => { file: string; repo: string; text: string }[];
91
+ /** Plan files held back from ci-red-mr: a running agent right now (a timer run passes timerStaffedPlans, the spawn record). `now` is this pass's clock. */
92
+ staffed: (now: number) => string[];
93
+ /** Run data for the release verdict (P11): Main tool calls and run costs per window. Absent — the caller has no session source — and no verdicts happen. */
94
+ source?: RunSource;
95
+ /** The self repo's `v*` tags (results.ts gatherTags, handed in by the CLI). Absent or empty — no verdicts. */
96
+ tags?: ReleaseTag[];
97
+ }
98
+
99
+ export interface WatchReport {
100
+ /** Incidents this run opened (first sighting). */
101
+ opened: IncidentView[];
102
+ /** Open incidents this run re-sighted (count and last seen updated, no new incident). */
103
+ deduped: IncidentView[];
104
+ /** Open watch incidents whose problem is gone — dismissed by this run. */
105
+ closed: IncidentView[];
106
+ /** Incidents the gated detectors folded themselves (their own sources and kinds). */
107
+ detectors: IncidentView[];
108
+ }
109
+
110
+ /** One problem the watcher found: exactly one addIncident input plus the fields its ⚠ post
111
+ * needs — the job it is about, when it happened, and the first error line. */
112
+ interface WatchProblem {
113
+ fingerprint: string;
114
+ kind: string;
115
+ /** The job or unit the problem is about: the post's subject. */
116
+ job: string;
117
+ /** When it happened: the heartbeat time, or the run time when there is none. */
118
+ at: string;
119
+ /** The first error line (a heartbeat detail or a journal line, already cut to 200). */
120
+ line: string;
121
+ summary: string;
122
+ evidence: string;
123
+ }
124
+
125
+ /** (a) heartbeats with ok:false — every job, listed in watch.expect or not. Then (b) stale
126
+ * heartbeats: only jobs listed in watch.expect are expected to beat at all, and only while
127
+ * healthy — a failed beat is already reported by (a), one incident per job and state. */
128
+ function beatProblems(cfg: Config, beats: Record<string, Heartbeat>, now: number): WatchProblem[] {
129
+ const out: WatchProblem[] = [];
130
+ for (const name of Object.keys(beats).toSorted()) {
131
+ const hb = beats[name]!;
132
+ if (hb.ok) continue;
133
+ const detail = hb.detail || "no detail";
134
+ out.push({
135
+ fingerprint: `watch:beat-failed:${name}`,
136
+ kind: "beat-failed",
137
+ job: name,
138
+ at: hb.at,
139
+ line: detail,
140
+ summary: `${name} heartbeat failed: ${detail}`,
141
+ evidence: `heartbeat at ${hb.at}: ${detail}`,
142
+ });
143
+ }
144
+ for (const [name, hours] of Object.entries(cfg.watch.expect)) {
145
+ const hb = beats[name];
146
+ if (!hb) {
147
+ out.push({
148
+ fingerprint: `watch:beat-stale:${name}`,
149
+ kind: "beat-stale",
150
+ job: name,
151
+ at: new Date(now * 1000).toISOString(),
152
+ line: `no heartbeat ever (watch.expect ${hours}h)`,
153
+ summary: `${name}: no heartbeat ever (watch.expect ${hours}h)`,
154
+ evidence: `listed in watch.expect (${hours}h), no heartbeats/${name}.json`,
155
+ });
156
+ continue;
157
+ }
158
+ if (!hb.ok) continue;
159
+ const ageH = (now - Date.parse(hb.at) / 1000) / 3600;
160
+ if (!(ageH > hours)) continue;
161
+ out.push({
162
+ fingerprint: `watch:beat-stale:${name}`,
163
+ kind: "beat-stale",
164
+ job: name,
165
+ at: hb.at,
166
+ line: `last beat ${Math.round(ageH * 10) / 10}h ago, expect ${hours}h`,
167
+ summary: `${name} heartbeat stale: last beat ${Math.round(ageH * 10) / 10}h ago, expect ${hours}h`,
168
+ evidence: `heartbeat at ${hb.at} (watch.expect: ${hours}h)`,
169
+ });
170
+ }
171
+ return out;
172
+ }
173
+
174
+ /** (c) failed units from the injected lister, filtered by the watch.units globs. */
175
+ function unitProblems(cfg: Config, listUnits: UnitLister, now: number): WatchProblem[] {
176
+ const globs = cfg.watch.units.map(p => new Glob(p));
177
+ const out: WatchProblem[] = [];
178
+ for (const unit of listUnits()) {
179
+ if (!globs.some(g => g.match(unit.name))) continue;
180
+ const err = unit.error || "state failed";
181
+ out.push({
182
+ fingerprint: `watch:unit-failed:${unit.name}`,
183
+ kind: "unit-failed",
184
+ job: unit.name,
185
+ at: new Date(now * 1000).toISOString(),
186
+ line: err,
187
+ summary: `${unit.name} unit failed: ${err}`,
188
+ evidence: `failed user unit (watch.units: ${cfg.watch.units.join(", ")}); last error line: ${err}`,
189
+ });
190
+ }
191
+ return out;
192
+ }
193
+
194
+ /** One watcher pass: heartbeats, failed units, CI, gated detectors, release verdicts — in that order. */
195
+ export function watchOnce(cfg: Config, deps: WatchDeps): WatchReport {
196
+ const now = deps.now();
197
+ const ci = ciScan(cfg, { run: deps.runner, now, plans: deps.plans(), staffed: deps.staffed(now) });
198
+ for (const s of ci.skipped) log(cfg.paths.guard_log, `ci: skipped ${s}`);
199
+ if (ci.recorded) log(cfg.paths.guard_log, `ci: recorded M3 for ${ci.recorded} merged MR(s)`);
200
+ if (ci.flaky) log(cfg.paths.guard_log, `ci: recorded ${ci.flaky} flaky commit(s)`);
201
+ const problems = [...beatProblems(cfg, readBeats(cfg), now), ...unitProblems(cfg, deps.listUnits, now), ...ci.problems];
202
+ // A ci-red-mr a staffed plan held back is still red: it stays open, it is not dismissed as recovered.
203
+ const current = new Set([...problems.map(p => p.fingerprint), ...ci.held]);
204
+
205
+ // Recovery first, so a problem that recovers and re-fails between two runs opens a new
206
+ // incident instead of sighting the old one: dedup counts open incidents only. Views are
207
+ // re-read after the dismissals: a pushed pre-dismissal view would carry resolution null
208
+ // (IncidentView's "open" marker) for an incident this run just closed.
209
+ const closedIds: string[] = [];
210
+ for (const inc of openIncidents(cfg)) {
211
+ // A release-regression incident (P11) is a finding, not a live problem: a later run seeing
212
+ // nothing is not a recovery — Main plans or dismisses it.
213
+ if (inc.source !== "watch" || inc.kind === "release-regression" || current.has(inc.fingerprint)) continue;
214
+ const subject = inc.fingerprint.split(":").slice(2).join(":") || inc.kind;
215
+ const refusal = dismissIncident(cfg, inc.id, `watch: recovered — ${subject} healthy again (watch run ${new Date(now * 1000).toISOString()})`);
216
+ if (refusal) {
217
+ log(cfg.paths.guard_log, `watch recovery refused for ${inc.id}: ${refusal}`);
218
+ continue;
219
+ }
220
+ log(cfg.paths.guard_log, `incident ${inc.id} [watch/${inc.kind}] closed: recovered`);
221
+ closedIds.push(inc.id);
222
+ }
223
+ const closed: IncidentView[] = [];
224
+ if (closedIds.length) {
225
+ const views = readIncidents(cfg);
226
+ for (const id of closedIds) {
227
+ const v = views.find(i => i.id === id);
228
+ if (v) closed.push(v);
229
+ }
230
+ }
231
+
232
+ const opened: IncidentView[] = [];
233
+ const deduped: IncidentView[] = [];
234
+ const posts: string[] = [];
235
+ for (const p of problems) {
236
+ const { incident, deduped: seen } = addIncident(
237
+ cfg,
238
+ { source: "watch", kind: p.kind, summary: p.summary, evidence: p.evidence, fingerprint: p.fingerprint },
239
+ now,
240
+ );
241
+ log(cfg.paths.guard_log, `incident ${incident.id} [watch/${p.kind}]${seen ? ` sighting #${incident.count}` : " opened"}: ${p.summary}`);
242
+ (seen ? deduped : opened).push(incident);
243
+ // Push, not pull (P3): one ⚠ post per NEW incident only — a deduped sighting stays silent.
244
+ if (!seen) posts.push(`⚠ ${p.job}: ${p.kind} at ${p.at} — ${p.line} (incident ${incident.id})`);
245
+ }
246
+
247
+ // At most watch.max_posts_per_run posts per run; the rest fold into one "+N more" line.
248
+ // Nothing at all when no notify provider is configured (the incidents still opened above).
249
+ // The seam is injected; the text goes through the same redactor the notify path applies,
250
+ // since the injected notifier may not scrub by itself (redactSecrets is idempotent, so a
251
+ // postReply hand-off scrubbing again is stable).
252
+ if (posts.length > 0 && notifyProviders(cfg).length > 0) {
253
+ const overflow = posts.splice(cfg.watch.max_posts_per_run);
254
+ if (overflow.length > 0) posts.push(`+${overflow.length} more, see \`neurastream incident list --open\``);
255
+ for (const post of posts) {
256
+ deps.notify(cfg.secrets.redact ? redactSecrets(post, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text : post);
257
+ }
258
+ }
259
+
260
+ // (d) the gated detectors fold their own incidents (D1/D3 behind incidents.scan_interval_sec).
261
+ const detectors = runDetectorsGated(cfg, {}, deps.gather, now);
262
+ // (e) P11: the release verdict — one judgment per tag whose after-window has closed and
263
+ // whose tag has no `{type:"release-verdict"}` record on the metrics ledger yet.
264
+ if (deps.source && deps.tags && deps.tags.length > 0) {
265
+ releaseVerdicts(cfg, {
266
+ now,
267
+ tags: deps.tags,
268
+ source: deps.source,
269
+ notify: text => deps.notify(cfg.secrets.redact ? redactSecrets(text, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text : text),
270
+ });
271
+ }
272
+ return { opened, deduped, closed, detectors };
273
+ }
274
+
275
+ // ---- P11: the release verdict — is the new version better or worse? ----
276
+
277
+ /** The inputs of one verdict pass. Tags and the run source are injected: core never runs git or
278
+ * reads harness sessions itself. */
279
+ export interface ReleaseVerdictDeps {
280
+ /** Unix seconds now; an after-window is closed once this passes its end. */
281
+ now: number;
282
+ /** The self repo's `v*` tags, oldest first. */
283
+ tags: ReleaseTag[];
284
+ /** Run data for the windows: Main tool calls and run costs. */
285
+ source: RunSource;
286
+ /** The chat notifier: one line per newly closable tag. */
287
+ notify: (text: string) => void;
288
+ }
289
+
290
+ export type VerdictWord = "BETTER" | "WORSE" | "MIXED" | "watcher-off";
291
+
292
+ export interface ReleaseVerdict {
293
+ tag: string;
294
+ verdict: VerdictWord;
295
+ /** The notify line, when one posted. */
296
+ post: string | null;
297
+ }
298
+
299
+ /** An after-window runs from the tag to the next tag or 24 h, whichever is first (the heartbeat
300
+ * is one overwritten file, so longer outages are not provable). */
301
+ const VERDICT_CAP_SEC = 86400;
302
+
303
+ /** The value per 100 Main tool calls in the window, so a busy night is not read as a worse version. */
304
+ const rate = (v: number | null, calls: number): number | null => (v === null ? null : (v * 100) / calls);
305
+
306
+ /** Percent change of one judged number from before to after; null reads "not comparable"
307
+ * (nothing before — a counter new in this release — or a zero before value). Owner pain
308
+ * appearing from zero is the exception: any positive after vetoes, reported as +100%. */
309
+ const pctOf = (n: VerdictNum): number | null => {
310
+ if (n.before === null || n.after === null) return null;
311
+ if (n.group === 1 && n.after > 0 && (n.before === 0 || n.beforeCount === 0)) return 100;
312
+ if (n.beforeCount === 0 || n.before === 0) return null;
313
+ return ((n.after - n.before) / n.before) * 100;
314
+ };
315
+
316
+ const isBetter = (n: VerdictNum, pct: number): boolean => (n.group === 5 ? pct > 0 : pct < 0);
317
+
318
+ /** Phases ticked in the window: a scored accept or validate names the plan and phase it
319
+ * finished (the only time series the ledger holds for output). */
320
+ const phasesTicked = (cfg: Config, w: Window): number => new Set(readEvents(cfg).filter(e => (e.type === "accept" || e.type === "validate") && inWindow(Number(e.ts), w)).map(e => `${String(e.plan)}/${String(e.phase)}`)).size;
321
+
322
+ /** Dot-version compare for the launcher's version-change events: "0.2.9" < "0.2.10". */
323
+ function verCompare(a: string, b: string): number {
324
+ const pa = a.split(".").map(p => Number.parseInt(p, 10) || 0);
325
+ const pb = b.split(".").map(p => Number.parseInt(p, 10) || 0);
326
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
327
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
328
+ if (d !== 0) return d;
329
+ }
330
+ return 0;
331
+ }
332
+
333
+ /** Was the incident alive at some point of the window: opened before the window ended, and
334
+ * either still open or seen again after the window began — a resolution record carries no close
335
+ * time, so the last sighting stands in for it. */
336
+ function overlapsWindow(i: IncidentView, w: Window): boolean {
337
+ return i.ts < w.to && (i.resolution === null || i.lastSeen > w.from);
338
+ }
339
+
340
+ const signed = (pct: number): string => `${pct >= 0 ? "+" : "-"}${Math.abs(pct).toFixed(0)}%`;
341
+ const fmtNum = (v: number): string => String(Number(v.toFixed(1)));
342
+
343
+ /** One judged number: the same value in both windows. Rates are per 100 Main tool calls. */
344
+ interface VerdictNum {
345
+ name: string;
346
+ /** 1 = owner pain (any of it worse reads WORSE outright), 2-4 = worse when higher, 5 = output (worse when lower). */
347
+ group: 1 | 2 | 3 | 4 | 5;
348
+ before: number | null;
349
+ after: number | null;
350
+ /** The raw counts: 0 before means the counter is new in the release — "new, not compared". */
351
+ beforeCount: number;
352
+ afterCount: number;
353
+ /** The daily-check metric key whose open incident this may not double, when one exists. */
354
+ dailyKey?: string;
355
+ }
356
+
357
+ /** One verdict per tag once its after-window closes; the `{type:"release-verdict"}` metrics
358
+ * record is the ledger marker, so no tag is ever judged twice. */
359
+ export function releaseVerdicts(cfg: Config, deps: ReleaseVerdictDeps): ReleaseVerdict[] {
360
+ const done = new Set(readMetricEvents(cfg).filter(e => e.type === "release-verdict").map(e => String(e.tag)));
361
+ const tags = deps.tags.toSorted((a, b) => a.ts - b.ts);
362
+ const out: ReleaseVerdict[] = [];
363
+ for (let i = 0; i < tags.length; i++) {
364
+ const tag = tags[i]!;
365
+ if (done.has(tag.name)) continue;
366
+ const end = Math.min(tag.ts + VERDICT_CAP_SEC, tags[i + 1]?.ts ?? tag.ts + VERDICT_CAP_SEC);
367
+ if (deps.now < end) continue;
368
+ const verdict = judgeRelease(cfg, tag.name, { from: tag.ts - (end - tag.ts), to: tag.ts }, { from: tag.ts, to: end }, deps);
369
+ if (verdict === null) continue; // not enough data yet: no verdict, nothing recorded, nothing posted
370
+ appendMetric(cfg, { type: "release-verdict", tag: tag.name, verdict: verdict.verdict, ts: deps.now });
371
+ if (verdict.post !== null) deps.notify(verdict.post);
372
+ out.push(verdict);
373
+ }
374
+ return out;
375
+ }
376
+
377
+ /** Judges one closed after-window against the same-length before window; null reads "not enough data yet". */
378
+ function judgeRelease(cfg: Config, tag: string, before: Window, after: Window, deps: ReleaseVerdictDeps): ReleaseVerdict | null {
379
+ const incidents = readIncidents(cfg);
380
+ // Watcher gap: a not-running incident open at any time in either window means that window's
381
+ // watcher-fed numbers read ~0 for want of a watcher — no verdict is possible.
382
+ if (incidents.some(i => i.fingerprint === "watch:not-running" && (overlapsWindow(i, before) || overlapsWindow(i, after)))) {
383
+ return { tag, verdict: "watcher-off", post: `${tag}: watcher off, no verdict` };
384
+ }
385
+ const callsOf = (w: Window) => deps.source.listRuns(w.from).filter(r => r.kind === "main" && inWindow(r.lastWriteAt, w)).reduce((s, r) => s + r.calls, 0);
386
+ const bc = callsOf(before);
387
+ const ac = callsOf(after);
388
+ if (bc < cfg.watch.release_min_calls || ac < cfg.watch.release_min_calls) return null;
389
+ const metricEvents = readMetricEvents(cfg);
390
+ const events = [...readEvents(cfg), ...metricEvents];
391
+ const blocks = readBlocks(cfg);
392
+ const b = snap(cfg, deps.source, events, blocks, incidents, before);
393
+ const a = snap(cfg, deps.source, events, blocks, incidents, after);
394
+ // The weekly report's own rows carry M2 idle calls, M3 mean tries and both M4 counts: the
395
+ // verdict reads the same numbers the owner sees.
396
+ const rows = new Map(rowsOf(a, b).map(r => [r.key, r]));
397
+ const row = (key: string) => rows.get(key)!;
398
+ const inCount = (type: string, w: Window) => metricEvents.filter(e => e.type === type && inWindow(Number(e.ts), w)).length;
399
+ const kindIn = (kind: string, w: Window) => incidents.filter(i => i.kind === kind && inWindow(i.ts, w)).length;
400
+ const merges = (w: Window) => inCount("ci", w);
401
+ const nums: VerdictNum[] = [
402
+ // 1 owner pain (veto — any of these worse reads WORSE outright)
403
+ { name: "corrections", group: 1, before: rate(row("m4_corrections").prev, bc), after: rate(row("m4_corrections").cur, ac), beforeCount: row("m4_corrections").prev ?? 0, afterCount: row("m4_corrections").cur ?? 0, dailyKey: "m4_corrections" },
404
+ { name: "questions", group: 1, before: rate(row("m4_questions").prev, bc), after: rate(row("m4_questions").cur, ac), beforeCount: row("m4_questions").prev ?? 0, afterCount: row("m4_questions").cur ?? 0, dailyKey: "m4_questions" },
405
+ { name: "m8 waits", group: 1, before: rate(inCount("m8", before), bc), after: rate(inCount("m8", after), ac), beforeCount: inCount("m8", before), afterCount: inCount("m8", after) },
406
+ // 2 stuck
407
+ { name: "idle", group: 2, before: rate(row("m2").prev, bc), after: rate(row("m2").cur, ac), beforeCount: row("m2").prev ?? 0, afterCount: row("m2").cur ?? 0, dailyKey: "m2" },
408
+ { name: "false blocks", group: 2, before: rate(m7(incidents, b.m5.falseAlarms, before), bc), after: rate(m7(incidents, a.m5.falseAlarms, after), ac), beforeCount: m7(incidents, b.m5.falseAlarms, before), afterCount: m7(incidents, a.m5.falseAlarms, after) },
409
+ // 3 quality
410
+ { name: "ci tries", group: 3, before: row("m3").prev, after: row("m3").cur, beforeCount: merges(before), afterCount: merges(after), dailyKey: "m3" },
411
+ { name: "silent failures", group: 3, before: rate(silentFailures(incidents, before), bc), after: rate(silentFailures(incidents, after), ac), beforeCount: silentFailures(incidents, before), afterCount: silentFailures(incidents, after) },
412
+ { name: "open→fix median h", group: 3, before: b.m6.medianHours, after: a.m6.medianHours, beforeCount: b.m6.fixed, afterCount: a.m6.fixed },
413
+ { name: "ci-flaky", group: 3, before: rate(inCount("ci-flaky", before), bc), after: rate(inCount("ci-flaky", after), ac), beforeCount: inCount("ci-flaky", before), afterCount: inCount("ci-flaky", after) },
414
+ { name: "ci-red-main", group: 3, before: rate(kindIn("ci-red-main", before), bc), after: rate(kindIn("ci-red-main", after), ac), beforeCount: kindIn("ci-red-main", before), afterCount: kindIn("ci-red-main", after) },
415
+ { name: "incidents", group: 3, before: rate(b.m6.opened, bc), after: rate(a.m6.opened, ac), beforeCount: b.m6.opened, afterCount: a.m6.opened },
416
+ { name: "fix plans", group: 3, before: rate(b.m6.planned, bc), after: rate(a.m6.planned, ac), beforeCount: b.m6.planned, afterCount: a.m6.planned },
417
+ // 4 cost — merges counted from the forge merges P6b records, so a missing `agent-score accept` does not blank it
418
+ { name: "$/merge", group: 4, before: merges(before) > 0 ? (b.m1.worker + b.m1.main) / merges(before) : null, after: merges(after) > 0 ? (a.m1.worker + a.m1.main) / merges(after) : null, beforeCount: merges(before), afterCount: merges(after) },
419
+ // 5 output — worse when lower
420
+ { name: "merges", group: 5, before: rate(merges(before), bc), after: rate(merges(after), ac), beforeCount: merges(before), afterCount: merges(after) },
421
+ { name: "phases", group: 5, before: rate(phasesTicked(cfg, before), bc), after: rate(phasesTicked(cfg, after), ac), beforeCount: phasesTicked(cfg, before), afterCount: phasesTicked(cfg, after) },
422
+ ];
423
+ // M5 by reason: each refusal shape is its own number; the daily m5 total stays the fingerprint.
424
+ const shaped = new Map<string, { b: number; a: number }>();
425
+ for (const bl of blocks) {
426
+ if (!inWindow(bl.ts, before) && !inWindow(bl.ts, after)) continue;
427
+ const k = reasonKey(bl.reason);
428
+ const e = shaped.get(k) ?? { b: 0, a: 0 };
429
+ if (inWindow(bl.ts, before)) e.b++;
430
+ else e.a++;
431
+ shaped.set(k, e);
432
+ }
433
+ for (const [k, e] of shaped) nums.push({ name: `blocks(${k})`, group: 2, before: rate(e.b, bc), after: rate(e.a, ac), beforeCount: e.b, afterCount: e.a, dailyKey: "m5" });
434
+
435
+ const isWorse = (n: VerdictNum, pct: number): boolean => {
436
+ if (n.group === 1) return n.after! > n.before!;
437
+ return n.group === 5 ? pct <= -cfg.watch.release_regress_pct : pct >= cfg.watch.release_regress_pct;
438
+ };
439
+ const downgrade = metricEvents
440
+ .filter(e => e.type === "version-change" && inWindow(Number(e.ts), after))
441
+ .map(e => ({ from: String(e.from ?? ""), to: String(e.to ?? "") }))
442
+ .find(v => verCompare(v.to, v.from) < 0) ?? null;
443
+ const judged = nums.map(n => ({ n, pct: pctOf(n) })).filter((jd): jd is { n: VerdictNum; pct: number } => jd.pct !== null);
444
+ const worseOnes = judged.filter(jd => isWorse(jd.n, jd.pct));
445
+ const improved24 = judged.some(jd => jd.n.group >= 2 && jd.n.group <= 4 && isBetter(jd.n, jd.pct));
446
+ let verdict: "BETTER" | "WORSE" | "MIXED";
447
+ if (downgrade !== null || worseOnes.length > 0) verdict = "WORSE";
448
+ else if (judged.filter(jd => jd.n.group >= 2).every(jd => !isWorse(jd.n, jd.pct)) && improved24) verdict = "BETTER";
449
+ else verdict = "MIXED";
450
+
451
+ const parts: string[] = [];
452
+ if (downgrade !== null) parts.push(`downgrade ${downgrade.from}→${downgrade.to}`);
453
+ for (const v of judged.filter(jd => jd.n.group === 1)) parts.push(`${v.n.name} ${signed(v.pct)}`);
454
+ for (const g of [2, 3, 4, 5] as const) {
455
+ const top = judged.filter(jd => jd.n.group === g).toSorted((p, q) => Math.abs(q.pct) - Math.abs(p.pct))[0];
456
+ if (top) parts.push(`${top.n.name} ${signed(top.pct)}`);
457
+ }
458
+ const fresh = nums.filter(n => n.beforeCount === 0 && pctOf(n) === null).map(n => n.name);
459
+ const freshLine = fresh.length === 0 ? "" : `${(fresh.length > 4 ? [...fresh.slice(0, 4), `+${fresh.length - 4} more`] : fresh).join(", ")} new, not compared`;
460
+ const post = `${tag}: ${verdict} — ${[...parts, freshLine].filter(p => p !== "").join(", ")}`;
461
+
462
+ if (verdict === "WORSE") {
463
+ const top = worseOnes.toSorted((p, q) => Math.abs(q.pct) - Math.abs(p.pct))[0];
464
+ const name = top ? top.n.name : "downgrade";
465
+ const vals = top ? `${fmtNum(top.n.before!)}→${fmtNum(top.n.after!)}` : `${downgrade!.from}→${downgrade!.to}`;
466
+ // The daily/weekly check may already hold today's open incident on this metric: the shared
467
+ // fingerprint dedups into it instead of doubling the story.
468
+ const fingerprint = top?.n.dailyKey !== undefined ? `daily:${top.n.dailyKey}:${strftime(deps.now, "%Y-%m-%d")}` : `release:${tag}:${name}`;
469
+ addIncident(cfg, { source: "watch", kind: "release-regression", summary: `release ${tag} worse: ${name} ${vals}`, evidence: post, fingerprint }, deps.now);
470
+ }
471
+ return { tag, verdict, post };
472
+ }
473
+
474
+ /** The plan files a timer run treats as staffed: a plan whose newest spawn (staffing.json) names tasks and is newer than `ciRedHours` before `now`. An older spawn's agent is gone, so its red MR is not held back (I-20261031-265). A timer run has no live job list, so the spawn record is the only signal it has. */
475
+ export function timerStaffedPlans(now: number, ciRedHours: number): string[] {
476
+ const since = now - ciRedHours * 3600;
477
+ return Object.entries(readStaffingEntries()).filter(([, e]) => e.names.length > 0 && e.at > since).map(([file]) => file);
478
+ }
479
+
480
+ /** The watcher's unit files under one home: the systemd user service and timer on Linux, the
481
+ * LaunchAgent plist on macOS. `watch on|off` (src/cli/watch-setup.ts) writes and removes them. */
482
+ export function watchUnitPaths(home: string, platform: NodeJS.Platform = process.platform): string[] {
483
+ if (platform === "darwin") return [join(home, "Library/LaunchAgents/neurastream-watch.plist")];
484
+ return [join(home, ".config/systemd/user/neurastream-watch.service"), join(home, ".config/systemd/user/neurastream-watch.timer")];
485
+ }
486
+
487
+ /** Whether the watcher timer is installed, and when its "watch" heartbeat last beat. */
488
+ export interface WatchHealth {
489
+ installed: boolean;
490
+ /** ISO time of the last watch run, or null when it never beat. */
491
+ lastRunAt: string | null;
492
+ /** Whole minutes since lastRunAt, or null when it never beat. */
493
+ lastRunMin: number | null;
494
+ /** watch.interval_min: the timer's period, the basis of the stale rule. */
495
+ intervalMin: number;
496
+ }
497
+
498
+ /** Read-only: unit files present and the "watch" heartbeat age. No service-manager call. */
499
+ export function watchHealth(cfg: Config, nowMs: number, platform: NodeJS.Platform = process.platform): WatchHealth {
500
+ const installed = watchUnitPaths(cfg.paths.home, platform).every(p => existsSync(p));
501
+ const lastRunAt = readBeats(cfg).watch?.at ?? null;
502
+ const lastRunMin = lastRunAt === null ? null : Math.max(0, Math.floor((nowMs - Date.parse(lastRunAt)) / 60000));
503
+ return { installed, lastRunAt, lastRunMin, intervalMin: cfg.watch.interval_min };
504
+ }
505
+
506
+ /** The doctor line: `watch: on, last run 5 min ago`, or `watch: off, last run never`. */
507
+ export function watchDoctorLine(h: WatchHealth): string {
508
+ return `watch: ${h.installed ? "on" : "off"}, last run ${h.lastRunMin === null ? "never" : `${h.lastRunMin} min ago`}`;
509
+ }
@@ -111,6 +111,8 @@ queue:
111
111
  auto_close_min: 15
112
112
  repo_index: "INDEX.md"
113
113
  cancelled_rel: "docs/plans/CANCELLED.md"
114
+ waiting_check_ttl_sec: 600 # a hold's `still true if` result is reused this long (key: plan mtime, command, HEAD)
115
+ waiting_check_timeout_sec: 60 # one check may run this long; a timeout is "unknown" (card stays, no incident)
114
116
 
115
117
  guards:
116
118
  sub_warn_calls: 90
@@ -149,7 +151,10 @@ autonomy:
149
151
  go_phrase: "go push" # the whole chat message that approves one push/merge in tier strict (I-20261025-201); a bare `go` is an ordinary message
150
152
 
151
153
  review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
152
- 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; an empty list turns both review gates off
154
+ plan: true # the reviewer PASS gate: false skips it (P6); an empty agents list no longer turns it off
155
+ code: false # the code review gate: true refuses Main ticking a phase until a review spawn's `CODE REVIEW: PASS` entry covers it (P6)
156
+ 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; an empty list only turns the `## Reuse` requirement off
157
+ shell_allow: ["git show", "git log", "git diff", "git blame", "git rev-parse", "git ls-files", "git status", "git merge-base", "grep", "cat", "head", "tail", "wc", "ls", "jq", "glab mr list", "glab mr view", "glab mr diff", "gh pr list", "gh pr view", "gh pr diff", "date"] # the bash prefixes a review spawn may run (P7): every |/&&/||/;/& segment starts with one, single-line, no redirects or substitution; eval is denied outright
153
158
  mr_cache_minutes: 10 # minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache
154
159
  approval: # plan approval hard gate (plan 20261029_1455 P3): docs/config.md
155
160
  since: "" # a plan stamped at or after this (YYYYMMDD_HHMM) needs a page and an approval record; "" = off
@@ -187,14 +192,32 @@ incidents:
187
192
  contradiction_grace_min: 3 # minutes after a finished task-result before a RUNNING/WAITING ledger row is a contradiction
188
193
  block_repeat: 20 # same guard BLOCK reason within 60 minutes that means a block loop
189
194
  scan_interval_sec: 120 # seconds between scans of the expensive detectors (D1 ledger, D3 block loop); the cheap ones run on every event
195
+ bypass_window_sec: 600 # seconds after a guard block within which a similar call of the same tool is a bypass (detector D8)
196
+ bypass_similarity: 0.6 # token-set Jaccard similarity (0, 1] between the blocked call's args and the bypass (detector D8)
190
197
  daily_worse_pct: 25 # a daily metric must be worse than the 7-day mean by at least this percent
191
198
  daily_floor: # per-metric daily floors: a regression below the floor is noise
192
199
  m1: 0.5 # $ per merge
193
200
  m2: 50 # idle calls/day
194
201
  m3: 1.5 # mean CI tries
195
- m4_corrections: 1 # owner corrections/day
196
- m4_questions: 3 # Main questions/day
197
- m5: 50 # guard blocks/day
202
+ m4_corrections: 1 # owner corrections/day
203
+ m4_questions: 3 # Main questions/day
204
+ m5: 50 # guard blocks/day
205
+
206
+ watch: # the watcher (src/core/watch.ts): heartbeats, failed units, detectors
207
+ expect: # hours after which a job's last heartbeat is stale; only listed jobs must beat at all
208
+ wip-snapshot: 2 # hourly snapshot
209
+ wip-backup: 26 # nightly 23:30 backup; one missed day is not yet stale
210
+ metrics-report: 192 # 8 days; the weekly report job
211
+ units: # user units the watcher reports when failed
212
+ - "neurastream-*"
213
+ - "wip-*"
214
+ max_posts_per_run: 3 # per run: at most this many new-incident posts, then one "+N more" line
215
+ interval_min: 15 # minutes between watcher runs; `neurastream watch on` installs the timer at this interval
216
+ noisy_min: 5 # weekly report: a detector kind with at least this many incidents in the window ...
217
+ noisy_ratio: 0.5 # ... and at least this dismiss rate opens one "noisy detector" incident
218
+ ci_red_hours: 2 # an open MR whose last finished pipeline stays failed longer than this opens incident "ci-red-mr"
219
+ release_regress_pct: 25 # release verdict: any group but owner pain worse by this percent over the before window reads WORSE
220
+ release_min_calls: 300 # release verdict: fewer Main tool calls on either side reads "not enough data yet", no verdict
198
221
 
199
222
  machine:
200
223
  load_over_cores: 4
@@ -0,0 +1,45 @@
1
+ watch: one pass of the watcher — scheduled jobs report in with heartbeats, the watcher checks
2
+ the reports, failed units, CI, the detectors and the release verdicts; each NEW problem opens
3
+ one incident and posts one notice. `watch on` installs the timer that runs the pass every
4
+ watch.interval_min.
5
+
6
+ What one pass checks, in order:
7
+ 1. Heartbeats <queue_state>/heartbeats/<name>.json: ok:false, or older than watch.expect[name]
8
+ hours (only jobs listed there must beat at all; defaults: wip-snapshot 2h, wip-backup 26h,
9
+ metrics-report 8 days).
10
+ 2. Failed user units matching the watch.units globs (default neurastream-*, wip-*), with the
11
+ unit's last error line.
12
+ 3. CI per active-plan repo: a red default branch (ci-red-main), an open MR red longer than
13
+ watch.ci_red_hours (ci-red-mr, held back while an agent runs on its plan), M3 records for
14
+ MRs merged since the last pass (the ledger is the cursor, so `metrics ci` is no longer
15
+ forgotten), and a commit that went red then green as a ci-flaky metric.
16
+ 4. The gated incident detectors (ledger contradiction, block loop, ...).
17
+ 5. Release verdict: one judgment per tag whose after-window has closed — better or worse over
18
+ the before window, from the weekly report's numbers. A verdict is a finding for Main: it
19
+ stays open until planned or dismissed and is never auto-closed as recovered.
20
+
21
+ Notify: every NEW incident posts one "⚠ <job>: <state> at <time> — <first error line>
22
+ (incident <id>)" through the configured providers — at most watch.max_posts_per_run (3) per
23
+ run, then "+N more, see `neurastream incident list --open`"; without a provider the incident
24
+ still opens and nothing posts; already-open problems post nothing; every post goes through
25
+ the secret redactor (a job name, a time, a first error line — never file contents). A
26
+ recovered problem closes its incident again.
27
+
28
+ Timer: `watch on` installs the systemd user timer neurastream-watch.{service,timer} (or the
29
+ LaunchAgent neurastream-watch.plist on macOS) running one pass every watch.interval_min;
30
+ `watch off` removes it. The service manager is probed first; a failed probe writes nothing.
31
+ `neurastream doctor` prints "watch: on|off, last run N min ago"; main-start raises a
32
+ watch:not-running incident once the last pass is older than 3 intervals.
33
+
34
+ Your own cron jobs join the same loop — after each run (or on failure) beat by hand:
35
+ neurastream heartbeat <name> # the run was fine
36
+ neurastream heartbeat <name> --fail "why" # report a failure
37
+
38
+ Noisy-detector rule: the weekly report opens one "noisy detector: <kind> (<d>/<n> dismissed)"
39
+ incident when a detector kind reaches watch.noisy_min incidents in the window and a
40
+ watch.noisy_ratio dismiss rate, with the three latest dismiss reasons — the alarm saying its
41
+ own alarm is crying wolf.
42
+
43
+ Usage: neurastream watch one pass now (beats its own "watch" heartbeat after the run)
44
+ neurastream watch on|off install/remove the timer
45
+ neurastream watch --help this text
@@ -0,0 +1,17 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>Label</key>
6
+ <string>com.neurastream.watch</string>
7
+ <key>ProgramArguments</key>
8
+ <array>
9
+ <string>__HOME__/.bun/bin/neurastream</string>
10
+ <string>watch</string>
11
+ </array>
12
+ <key>StartInterval</key>
13
+ <integer>__INTERVAL_SEC__</integer>
14
+ <key>RunAtLoad</key>
15
+ <true/>
16
+ </dict>
17
+ </plist>
@@ -33,7 +33,11 @@ PRIORITY-ID: <optional, e.g. PR01>
33
33
  Status: open
34
34
  <!-- The implementer may only append dated entries here: what was done, what was verified (command +
35
35
  result), commits, what is next. It never changes the Status line or adds "WAITING on owner".
36
- A hold is one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>` (blocked and why you may be omitted).
36
+ A hold is one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it> — still true if: \`<cmd>\`` (blocked, why you and still true if may be omitted).
37
+ `still true if` is the hold's own proof: neurastream runs the command in the plan's worktree (else its repo)
38
+ before the question card is shown — exit 0 keeps the card up, non-zero hides it, opens a "stale-hold"
39
+ incident and prints it (a timeout counts as unknown: the card stays, no incident).
40
+ The hold line itself is never edited automatically; Main removes or rewrites it.
37
41
  Every new entry ends with a Findings line: "Findings: none", or one item per finding (bug,
38
42
  workaround, improvement — any repo) with file:line evidence, items separated by ";". Plan-guard
39
43
  restores an entry without it. Findings stay notes: Main reads them, they never become incidents.
@@ -0,0 +1,6 @@
1
+ [Unit]
2
+ Description=neurastream watcher (heartbeats, failed units, incident detectors)
3
+
4
+ [Service]
5
+ Type=oneshot
6
+ ExecStart=%h/.bun/bin/neurastream watch