neurastream 0.2.62 → 0.2.64

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.
@@ -127,6 +127,8 @@ export interface Plan {
127
127
  waitingBlocked: string | null;
128
128
  /** Why Main cannot do it. Null when the line has no `— why you:`. */
129
129
  waitingWhy: string | null;
130
+ /** The command from `— still true if: \`<cmd>\``; exit 0 keeps the card up. Null without one. */
131
+ waitingCheck: string | null;
130
132
  waitsOn: string[];
131
133
  priorityId: string | null;
132
134
  /** First level-1 "# " heading in the plan, else the file basename. */
@@ -246,26 +248,40 @@ const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Waits on:|Can
246
248
 
247
249
  const WAITING_BLOCKED = " — blocked: ";
248
250
  const WAITING_WHY = " — why you: ";
251
+ /** The hold's own proof: exit 0 means the hold is still real (src/core/waiting-check.ts). */
252
+ const WAITING_CHECK = " — still true if: ";
253
+
254
+ export interface WaitingParts {
255
+ ask: string;
256
+ blocked: string | null;
257
+ why: string | null;
258
+ /** The backticked command after `— still true if:`, or null. */
259
+ check: string | null;
260
+ }
249
261
 
250
262
  /** Split `WAITING on owner:` text. An old one-part line is ask only; a missing part is null. */
251
- export function splitWaiting(line: string): { ask: string; blocked: string | null; why: string | null } {
252
- const marks: { at: number; kind: "blocked" | "why"; len: number }[] = [];
263
+ export function splitWaiting(line: string): WaitingParts {
264
+ const marks: { at: number; kind: "blocked" | "why" | "check"; len: number }[] = [];
253
265
  const blockedAt = line.indexOf(WAITING_BLOCKED);
254
266
  const whyAt = line.indexOf(WAITING_WHY);
267
+ const checkAt = line.indexOf(WAITING_CHECK);
255
268
  if (blockedAt >= 0) marks.push({ at: blockedAt, kind: "blocked", len: WAITING_BLOCKED.length });
256
269
  if (whyAt >= 0) marks.push({ at: whyAt, kind: "why", len: WAITING_WHY.length });
270
+ if (checkAt >= 0) marks.push({ at: checkAt, kind: "check", len: WAITING_CHECK.length });
257
271
  marks.sort((a, b) => a.at - b.at);
258
- if (marks.length === 0) return { ask: line.trim(), blocked: null, why: null };
272
+ if (marks.length === 0) return { ask: line.trim(), blocked: null, why: null, check: null };
259
273
  let blocked: string | null = null;
260
274
  let why: string | null = null;
275
+ let check: string | null = null;
261
276
  for (let i = 0; i < marks.length; i++) {
262
277
  const mark = marks[i]!;
263
278
  const end = i + 1 < marks.length ? marks[i + 1]!.at : line.length;
264
279
  const text = line.slice(mark.at + mark.len, end).trim();
265
280
  if (mark.kind === "blocked") blocked = text || null;
266
- else why = text || null;
281
+ else if (mark.kind === "why") why = text || null;
282
+ else check = text.match(/`([^`]+)`/)?.[1]?.trim() || null;
267
283
  }
268
- return { ask: line.slice(0, marks[0]!.at).trim(), blocked, why };
284
+ return { ask: line.slice(0, marks[0]!.at).trim(), blocked, why, check };
269
285
  }
270
286
 
271
287
  /** Keep the first `keep` entries (the file lists them newest first) and move the rest. Pure. */
@@ -354,7 +370,7 @@ function reuseProblems(repo: string, file: string, secs: Map<string, string>, re
354
370
  }
355
371
 
356
372
  export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath(), reviewAgents: string[] = []): Plan {
357
- const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, waitingAsk: null, waitingBlocked: null, waitingWhy: null, waitsOn: [], priorityId: null, title: path.basename(file), goal: [], summary: null, phases: { done: 0, total: 0 }, started: false };
373
+ const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, waitingAsk: null, waitingBlocked: null, waitingWhy: null, waitingCheck: null, waitsOn: [], priorityId: null, title: path.basename(file), goal: [], summary: null, phases: { done: 0, total: 0 }, started: false };
358
374
  if (text === null) return { ...empty, errors: ["plan file listed in the index does not exist"] };
359
375
  const errors: string[] = [];
360
376
  const secs = sections(text);
@@ -391,7 +407,7 @@ export function parsePlan(repo: string, file: string, text: string | null, block
391
407
  if (bg > BACKGROUND_MAX_LINES) errors.push(`"## Background" has ${bg} lines (max ${BACKGROUND_MAX_LINES}); link a separate file for long context`);
392
408
  const wt = headerField(text, "Worktree");
393
409
  const waitingLine = text.match(/^WAITING on owner:[ \t]*(.*)$/m)?.[1] ?? null;
394
- const waitingParts = waitingLine === null ? { ask: null, blocked: null, why: null } : splitWaiting(waitingLine);
410
+ const waitingParts = waitingLine === null ? { ask: null, blocked: null, why: null, check: null } : splitWaiting(waitingLine);
395
411
  return {
396
412
  repo,
397
413
  file,
@@ -407,6 +423,7 @@ export function parsePlan(repo: string, file: string, text: string | null, block
407
423
  waitingAsk: waitingParts.ask,
408
424
  waitingBlocked: waitingParts.blocked,
409
425
  waitingWhy: waitingParts.why,
426
+ waitingCheck: waitingParts.check,
410
427
  waitsOn: [...text.matchAll(/^[ \t]*(?:[-*][ \t]+)?Waits on:[ \t]*(.+)$/gm)].map(m => m[1]!.trim()),
411
428
  priorityId: text.match(/^PRIORITY-ID:\s*`?([A-Z]{2}[0-9]{2})`?/m)?.[1] ?? null,
412
429
  title: text.match(/^# (.+)$/m)?.[1]?.trim() || path.basename(file),
@@ -1106,6 +1123,7 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewA
1106
1123
  if (p.doneCheck?.includes("merge-base --is-ancestor"))
1107
1124
  probs.push({ where: p.file, problem: "done check runs git merge-base --is-ancestor — queue-close checks landing itself, squash-aware; drop it" });
1108
1125
  for (const c of cancelledMatches(p)) probs.push({ where: p.file, problem: cancelledProblem(p, c) });
1126
+ probs.push(...doneClaimProblems(p));
1109
1127
  // A plan file must live in a main checkout, never in a linked worktree.
1110
1128
  const g = gitTop(p.file);
1111
1129
  if (g && g.top !== g.repo)
@@ -1124,12 +1142,68 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewA
1124
1142
  return probs;
1125
1143
  }
1126
1144
 
1145
+ // P4 (plan 20261027_0915): from this day on, a Progress entry claiming a phase done/complete/
1146
+ // "nothing left"/"finished" must quote that phase's verify command (or the Done check) and its
1147
+ // result, or queue-check fails the plan; entries without a date or dated before it are grandfathered.
1148
+ export const DONE_CLAIM_SINCE = "2026-11-01";
1149
+
1150
+ const DONE_WORD = /\b(?:done|completed?|nothing left|finished)\b/i;
1151
+ const NOT_DONE = /\b(?:not|never)\s+(?:done|completed?|finished)\b/i;
1152
+ const RESULT_MARK = /\bexit(?: code|ed)?\s*\d|\b\d+ pass|\b\d+ fail|\bpass(?:ed|ing)?\b|\bfail(?:ed|ing)?\b|\bresult\b/i;
1153
+
1154
+ /** Progress entries: the "- " line plus the lines up to the next entry start (trimProgressBody's rule). */
1155
+ function progressEntryBlocks(text: string): string[] {
1156
+ const lines = progressBody(text).split("\n").filter(l => !l.startsWith(POINTER_PREFIX));
1157
+ const blocks: string[] = [];
1158
+ for (let i = 0; i < lines.length; i++) {
1159
+ if (!lines[i]!.startsWith("- ") || MAIN_ONLY_LINE.test(lines[i]!)) continue;
1160
+ let j = i + 1;
1161
+ while (j < lines.length && !(lines[j]!.startsWith("- ") && !MAIN_ONLY_LINE.test(lines[j]!))) j++;
1162
+ blocks.push(lines.slice(i, j).join("\n"));
1163
+ i = j - 1;
1164
+ }
1165
+ return blocks;
1166
+ }
1167
+
1168
+ /** A dated done claim about phase Pn must quote Pn's verify (or the Done check) with its result; else one problem per entry. */
1169
+ function doneClaimProblems(p: Plan): QueueProblem[] {
1170
+ const probs: QueueProblem[] = [];
1171
+ const verifies = new Map<string, string>();
1172
+ for (const line of items(sections(p.text).get("phases") ?? "")) {
1173
+ const id = /\[.\]\s*(P\d+[a-z]?)/i.exec(line)?.[1];
1174
+ const cmd = /verify:\s*`([^`]+)`/.exec(line)?.[1];
1175
+ if (id && cmd) verifies.set(id.toUpperCase(), cmd);
1176
+ }
1177
+ for (const entry of progressEntryBlocks(p.text)) {
1178
+ const date = /^- (\d{4}-\d{2}-\d{2})/.exec(entry)?.[1];
1179
+ if (!date || date < DONE_CLAIM_SINCE || !DONE_WORD.test(entry) || NOT_DONE.test(entry)) continue;
1180
+ const ids = [...entry.matchAll(/\b(P\d+[a-z]?)\b/g)].map(m => m[1]!.toUpperCase());
1181
+ if (!ids.length) continue;
1182
+ const backings = [...new Set(ids.flatMap(id => verifies.get(id) ?? []))];
1183
+ if (p.doneCheck) backings.push(p.doneCheck);
1184
+ // No verify command and no Done check to quote: nothing this plan can back a claim with, so it is not judged.
1185
+ if (!backings.length) continue;
1186
+ if (backings.some(c => entry.includes(c)) && RESULT_MARK.test(entry)) continue;
1187
+ probs.push({ where: p.file, problem: `unbacked done claim: ${p.file} ${entry.split("\n")[0]!.slice(0, 80)}` });
1188
+ }
1189
+ return probs;
1190
+ }
1191
+
1192
+ /** P4: a hold dated DONE_CLAIM_SINCE or later without `still true if` is a warning; the exit code never changes. */
1193
+ export function holdWarnings(plans: Plan[]): string[] {
1194
+ return plans.flatMap(p => {
1195
+ if (!p.waiting || p.waitingCheck) return [];
1196
+ const date = /^(\d{4}-\d{2}-\d{2})/.exec(p.waitingLine ?? "")?.[1];
1197
+ return date && date >= DONE_CLAIM_SINCE ? [`${p.file}: WAITING hold dated ${date} carries no "still true if" check`] : [];
1198
+ });
1199
+ }
1200
+
1127
1201
  // P5b (plan 20261031_1207, I-20261031-330): the summary rides every Main prompt and the stop
1128
1202
  // refusal repeats on every blocked stop, so both cap their lists; queue-check prints everything
1129
1203
  // and passes `cap = Infinity`.
1130
1204
  export const SUMMARY_CAP = 10;
1131
1205
 
1132
- export function queueSummary(index = INDEX, reviewAgents: string[] = [], cap: number = SUMMARY_CAP): string {
1206
+ export function queueSummary(index = INDEX, reviewAgents: string[] = [], stale: ReadonlySet<string> = new Set(), cap: number = SUMMARY_CAP): string {
1133
1207
  // Index order IS priority (20261025_0215_index_priority): the list is flat and ranked,
1134
1208
  // rank 1 = the index's top line; repos only surface through each plan's own path.
1135
1209
  const plans = activePlans(index);
@@ -1138,7 +1212,8 @@ export function queueSummary(index = INDEX, reviewAgents: string[] = [], cap: nu
1138
1212
  const lines = [`Queue (${index}): ${plans.length ? `${plans.length} plan(s) in ${repos.length} repo(s)` : "empty, no open work"}`];
1139
1213
  plans.slice(0, cap).forEach((p, i) => {
1140
1214
  const status = awaitingMerge(p) ? "complete, awaiting merge" : (p.status ?? "INVALID");
1141
- const hold = p.waiting ? `WAITING on owner: ${(p.waitingLine ?? "").slice(0, 80)}` : "";
1215
+ const ask = (p.waitingLine ?? "").slice(0, 80);
1216
+ const hold = p.waiting ? (stale.has(p.file) ? `[STALE?] ${ask}` : `WAITING on owner: ${ask}`) : "";
1142
1217
  // I-20261025-208: an open plan waiting on an open plan of the queue shows the target's rank.
1143
1218
  const waits: string[] = [];
1144
1219
  if (p.status === "open")
@@ -86,7 +86,7 @@ export function queueCancel(args: string[], cfg: Config): number {
86
86
  text = text.replace(/^Status:\s*\S+\s*$/m, `Status: cancelled\nCancelled by owner: ${today} ${owner.trim().replace(/\n/g, " ")}`);
87
87
  writeFileSync(file, text);
88
88
  clearPending(`plan: ${file}`);
89
- const closeBin = fileURLToPath(new URL("../../cli/main.ts", import.meta.url));
89
+ const closeBin = path.join(path.dirname(fileURLToPath(import.meta.url)), "../cli/main.ts");
90
90
  const r = spawnSync("bun", [closeBin, "queue-close", file], { stdio: "inherit", env: process.env });
91
91
  return r.status ?? 1;
92
92
  }
@@ -1,7 +1,8 @@
1
1
  import type { Config } from "./config.ts";
2
2
  import { applyQueueEnv } from "./queue/env.ts";
3
- import { activePlans, allowedAgents, queueProblems, queueSummary, reviewAgentsProblem } from "./queue/lib.ts";
3
+ import { activePlans, allowedAgents, holdWarnings, queueProblems, queueSummary, reviewAgentsProblem } from "./queue/lib.ts";
4
4
  import { mrSweep } from "./mr-sweep.ts";
5
+ import { recheckHolds, staleFiles, staleHoldLines } from "./waiting-check.ts";
5
6
 
6
7
  // One index (20261024_1400_one_index): the main index lists plan files directly, so there are no
7
8
  // repo INDEX.md files to git-check and no work_roots scan; the queue problems carry the
@@ -12,7 +13,10 @@ export function queueCheck(args: string[], cfg: Config): number {
12
13
  for (const p of activePlans()) if (p.priorityId && !p.waiting && p.status === "open") console.log(p.priorityId);
13
14
  return 0;
14
15
  }
15
- console.log(queueSummary(undefined, cfg.review.agents, Infinity));
16
+ const plans = activePlans();
17
+ const holds = recheckHolds(cfg, plans);
18
+ console.log(queueSummary(undefined, cfg.review.agents, staleFiles(holds), Infinity));
19
+ for (const line of staleHoldLines(holds, plans)) console.log(line);
16
20
  // main-start prints the sweep itself and passes this so the child bin does not print it twice.
17
21
  let fail = queueProblems(undefined, undefined, cfg.review.agents).length > 0;
18
22
  // P4d (plan 20261028_1600): a review spawn needs a review.agents entry that Main may spawn.
@@ -22,6 +26,8 @@ export function queueCheck(args: string[], cfg: Config): number {
22
26
  fail = true;
23
27
  }
24
28
  for (const w of review.warnings) console.log(`warning: ${w}`);
29
+ // P4 (plan 20261027_0915): a hold dated DONE_CLAIM_SINCE or later without its own check warns; the exit code stays.
30
+ for (const w of holdWarnings(plans)) console.log(`warning: ${w}`);
25
31
  if (!args.includes("--no-mr-sweep")) {
26
32
  try {
27
33
  const sweep = mrSweep();
@@ -44,8 +44,21 @@ export function queueClose(args: string[], cfg: Config): number {
44
44
  const named = git(cur, "symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD").out.replace(/^origin\//, "");
45
45
  const def = named || git(cur, "symbolic-ref", "-q", "--short", "HEAD").out;
46
46
  const fetched = git(repo, "fetch", "-q", cur, def);
47
- if (!fetched.ok) die(`could not fetch ${def} from ${cur}: ${fetched.out}`);
48
- return git(repo, "rev-parse", "FETCH_HEAD").out;
47
+ if (fetched.ok) return git(repo, "rev-parse", "FETCH_HEAD").out;
48
+ // The remote's default branch can be gone upstream (renamed, pruned): fall back to the
49
+ // local base ref, then the local main branch, instead of refusing every close.
50
+ const local = git(repo, "rev-parse", "-q", "--verify", localBase);
51
+ if (local.ok) {
52
+ // A stale local base hides the fetch error from the landing check, so say so loudly.
53
+ console.warn(`warning: queue-close: could not fetch ${def} from ${cur}; using the stale local base ${localBase}`);
54
+ return local.out;
55
+ }
56
+ const fallback = git(repo, "rev-parse", "-q", "--verify", "refs/heads/main");
57
+ if (fallback.ok) {
58
+ console.warn(`warning: queue-close: could not fetch ${def} from ${cur}; using the local main branch`);
59
+ return fallback.out;
60
+ }
61
+ die(`could not fetch ${def} from ${cur}: ${fetched.out}`);
49
62
  }
50
63
  const today = new Date().toISOString().slice(0, 10);
51
64
 
@@ -53,6 +66,10 @@ export function queueClose(args: string[], cfg: Config): number {
53
66
  // landed; the done check decides, and a pass writes "Status: complete" here, nobody else.
54
67
  const auto = args[0] === "--auto";
55
68
  const arg = auto ? args[1] : args[0];
69
+ if (arg === "-h" || arg === "--help") {
70
+ console.log("usage: queue-close [--auto] <plan file>");
71
+ return 0;
72
+ }
56
73
  if (!arg) die("usage: queue-close [--auto] <plan file>");
57
74
  const file = path.resolve(arg);
58
75
  resultLog = closeLog(file);
@@ -12,6 +12,10 @@ const USAGE = "usage: queue-trim <plan file> [--keep N]";
12
12
 
13
13
  export function queueTrim(args: string[], cfg: Config): number {
14
14
  applyQueueEnv(cfg);
15
+ if (args[0] === "--help" || args[0] === "-h") {
16
+ console.log(USAGE);
17
+ return 0;
18
+ }
15
19
  const hasKeep = args.includes("--keep");
16
20
  const rest = args.filter((a, i) => a !== "--keep" && args[i - 1] !== "--keep");
17
21
  const planArg = rest[0];
@@ -11,6 +11,7 @@ import {
11
11
  m3,
12
12
  m4,
13
13
  m5,
14
+ inWindow,
14
15
  readBlocks,
15
16
  readMetricEvents,
16
17
  windows,
@@ -43,7 +44,8 @@ function day(t: number): string {
43
44
  return new Date(t * 1000).toISOString().slice(0, 10);
44
45
  }
45
46
 
46
- function snap(cfg: Config, source: RunSource, events: Ev[], blocks: GuardBlock[], incidents: IncidentView[], w: Window): Snap {
47
+ /** One window's raw metric values: the inputs every before/after view (weekly report, release verdict) compares. */
48
+ export function snap(cfg: Config, source: RunSource, events: Ev[], blocks: GuardBlock[], incidents: IncidentView[], w: Window): Snap {
47
49
  const runs = source.listRuns(w.from);
48
50
  const patterns = cfg.metrics.correction_patterns.map((p) => new RegExp(p, "i"));
49
51
  return {
@@ -83,12 +85,77 @@ export function m6(incidents: IncidentView[], w: Window): M6 {
83
85
  .map((i) => ({ opened: i.ts, at: fixedAt(i) }))
84
86
  .filter((x): x is { opened: number; at: number } => x.at !== null)
85
87
  .map((x) => (x.at - x.opened) / 3600)
86
- .sort((a, b) => a - b);
88
+ .toSorted((a, b) => a - b);
87
89
  const mid = Math.floor(hours.length / 2);
88
90
  const median = hours.length === 0 ? null : hours.length % 2 ? hours[mid]! : (hours[mid - 1]! + hours[mid]!) / 2;
89
91
  return { opened: inW.length, planned: byType("plan"), dismissed: byType("dismiss"), fixed: byType("fixed"), medianHours: median };
90
92
  }
91
93
 
94
+ /** Silent failures (P6): watch-source incidents opened in the window, i.e. failures the watcher found without anyone asking. */
95
+ export function silentFailures(incidents: IncidentView[], w: Window): number {
96
+ return incidents.filter((i) => i.source === "watch" && inWindow(i.ts, w)).length;
97
+ }
98
+
99
+ /** M7 (P6): suspected false blocks in one window: D8 block-then-bypass incidents plus false-alarm events. */
100
+ export function m7(incidents: IncidentView[], falseAlarms: number, w: Window): number {
101
+ return incidents.filter((i) => i.kind === "block-then-bypass" && inWindow(i.ts, w)).length + falseAlarms;
102
+ }
103
+
104
+ /** One kind's outcomes for incidents opened in the window; dismissRate is dismissed / opened. */
105
+ export interface KindStat {
106
+ kind: string;
107
+ opened: number;
108
+ planned: number;
109
+ dismissed: number;
110
+ dismissRate: number;
111
+ }
112
+
113
+ /** Per-kind outcomes, busiest kind first. */
114
+ export function kindStats(incidents: IncidentView[], w: Window): KindStat[] {
115
+ const byKind = new Map<string, IncidentView[]>();
116
+ for (const i of incidents) {
117
+ if (!inWindow(i.ts, w)) continue;
118
+ byKind.set(i.kind, [...(byKind.get(i.kind) ?? []), i]);
119
+ }
120
+ return [...byKind]
121
+ .map(([kind, list]): KindStat => {
122
+ const dismissed = list.filter((i) => i.resolution?.type === "dismiss").length;
123
+ return {
124
+ kind,
125
+ opened: list.length,
126
+ planned: list.filter((i) => i.resolution?.type === "plan").length,
127
+ dismissed,
128
+ dismissRate: dismissed / list.length,
129
+ };
130
+ })
131
+ .toSorted((a, b) => b.opened - a.opened || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0));
132
+ }
133
+
134
+ /** A noisy detector (P6): the finding the weekly check turns into one "noisy-detector" incident. */
135
+ export interface NoisyFinding {
136
+ kind: "noisy-detector";
137
+ /** The incident kind that is noisy. */
138
+ detector: string;
139
+ summary: string;
140
+ /** The three latest dismiss reasons, joined with "; ". */
141
+ evidence: string;
142
+ }
143
+
144
+ /** A kind is noisy when this window opened at least noisy_min incidents of it and at least
145
+ * noisy_ratio of them were dismissed. */
146
+ export function noisyDetectors(incidents: IncidentView[], w: Window, t: { noisy_min: number; noisy_ratio: number }): NoisyFinding[] {
147
+ return kindStats(incidents, w)
148
+ .filter((s) => s.opened >= t.noisy_min && s.dismissRate >= t.noisy_ratio)
149
+ .map((s): NoisyFinding => {
150
+ const why = incidents
151
+ .filter((i) => i.kind === s.kind && inWindow(i.ts, w) && i.resolution?.type === "dismiss")
152
+ .toSorted((a, b) => b.ts - a.ts)
153
+ .slice(0, 3)
154
+ .map((i) => (i.resolution?.type === "dismiss" ? i.resolution.why : ""));
155
+ return { kind: "noisy-detector", detector: s.kind, summary: `noisy detector: ${s.kind} (${s.dismissed}/${s.opened} dismissed)`, evidence: why.join("; ") };
156
+ });
157
+ }
158
+
92
159
  interface Row {
93
160
  /** Stable metric key (m1, m2, m3, m4_corrections, m4_questions, m4_users, m5). */
94
161
  key: string;
@@ -100,10 +167,12 @@ interface Row {
100
167
  rank: boolean;
101
168
  }
102
169
 
103
- function rowsOf(c: Snap, p: Snap): Row[] {
104
- const usd = (v: number | null) => (v === null ? "n/a (0 merged)" : `$${v.toFixed(2)}`);
105
- const num = (v: number | null) => (v === null ? "n/a" : String(v));
106
- const mean = (v: number | null) => (v === null ? "n/a" : v.toFixed(2));
170
+ const usd = (v: number | null) => (v === null ? "n/a (0 merged)" : `$${v.toFixed(2)}`);
171
+ const num = (v: number | null) => (v === null ? "n/a" : String(v));
172
+ const mean = (v: number | null) => (v === null ? "n/a" : v.toFixed(2));
173
+
174
+ /** The report's ranked rows: the release verdict reads the same numbers the owner sees (P11). */
175
+ export function rowsOf(c: Snap, p: Snap): Row[] {
107
176
  return [
108
177
  { key: "m1", name: "M1 cost per merge", cur: c.m1.perMerge, prev: p.m1.perMerge, fmt: usd, rank: true },
109
178
  { key: "m2", name: "M2 idle calls", cur: c.m2.calls, prev: p.m2.calls, fmt: num, rank: true },
@@ -170,6 +239,8 @@ export interface Report {
170
239
  text: string;
171
240
  /** The ranked row with the biggest percent increase; null when nothing ranked moved. */
172
241
  worst: { key: string; name: string; cur: number | null; prev: number | null; change: number | null } | null;
242
+ /** Noisy-detector findings for this window; runWeeklyCheck opens one incident for each. */
243
+ noisy: NoisyFinding[];
173
244
  }
174
245
 
175
246
  /** Weekly provider-honesty counts the report appends; the CLI caller builds them from the
@@ -220,6 +291,14 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
220
291
  return `| ${r.name} | ${r.fmt(r.cur)} | ${r.fmt(r.prev)} | ${signed(change(r))}${mark} |`;
221
292
  }),
222
293
  ];
294
+ const falseAlarms = events.filter((e) => e.type === "false-alarm" && inWindow(Number(e.ts), cur)).length;
295
+ const noisy = noisyDetectors(incidents, cur, cfg.watch);
296
+ const quality = [
297
+ `Silent failures: ${silentFailures(incidents, cur)} watch incidents; suspected false blocks: ${m7(incidents, falseAlarms, cur)}`,
298
+ `Flaky jobs: ${events.filter((e) => e.type === "ci-flaky" && inWindow(Number(e.ts), cur)).length} same-commit red→green re-runs`,
299
+ "Dismiss rate by kind (opened, planned, dismissed):",
300
+ ...kindStats(incidents, cur).map((k) => `- ${k.kind}: ${k.opened}, ${k.planned}, ${k.dismissed} (${Math.round(k.dismissRate * 100)}% dismissed)`),
301
+ ];
223
302
  const body = [
224
303
  `Self-metrics: last ${days} days [${day(cur.from)} to ${day(cur.to)}) vs previous ${days} days.`,
225
304
  "",
@@ -227,6 +306,8 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
227
306
  "",
228
307
  ...detail(c),
229
308
  "",
309
+ ...quality,
310
+ "",
230
311
  "Approved rules, before vs after:",
231
312
  ...ruleLines(cfg, source, events, blocks, incidents, days, now),
232
313
  ...(provider
@@ -260,5 +341,6 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
260
341
  md,
261
342
  text: body,
262
343
  worst: worst ? { key: worst.key, name: worst.name, cur: worst.cur, prev: worst.prev, change: change(worst) } : null,
344
+ noisy,
263
345
  };
264
346
  }
@@ -5,7 +5,9 @@
5
5
  // the jobs and the note mtime, and performs the switch. No harness names here.
6
6
 
7
7
  import { join } from "node:path";
8
+ import { strftime } from "./clock.ts";
8
9
  import { stateDirPath } from "./queue/lib.ts";
10
+ import type { OwnerAnswer, OwnerMessage } from "./incidents.ts";
9
11
 
10
12
  export type RolloverState = "below" | "need-note" | "wait-jobs" | "ready";
11
13
 
@@ -62,6 +64,8 @@ export interface HandoffInput {
62
64
  previousSessionFile: string;
63
65
  /** The owner's message exactly as typed; it is the last thing in the handoff. */
64
66
  ownerMessage: string;
67
+ /** Owner messages no turn has ended after (P5b); the handoff starts with their block. */
68
+ unanswered?: readonly OwnerMessage[];
65
69
  }
66
70
 
67
71
  /** Prefixes of the machine-written messages: the builders write them, ownerText reads them. */
@@ -69,13 +73,50 @@ const NOTE_REQUEST_PREFIX = "Session rollover:";
69
73
  const HANDOFF_PREFIX = "Previous session file:";
70
74
  const OWNER_MARK = "Owner's message:";
71
75
 
72
- /** The first user message of the new session: header, Main's note, generated state, owner message. */
76
+ /** The prefix both machine prompts start with while owner messages sit unanswered (P5b). */
77
+ export const UNANSWERED_PREFIX =
78
+ "UNANSWERED OWNER MESSAGES — answer these first, then end the turn so the reply reaches Discord:";
79
+
80
+ /** Owner messages no real turn end has followed: an answer record ({at, answer}, the page's lastAnswerFor shape) rides the message store, and a message with one after it is answered. */
81
+ export function unansweredOwnerMessages(messages: readonly OwnerMessage[], answers: readonly OwnerAnswer[]): OwnerMessage[] {
82
+ const answeredAt = Math.max(-1, ...answers.map(a => a.at));
83
+ return messages.filter(m => m.at > answeredAt);
84
+ }
85
+
86
+ /** The unanswered block proper: the prefix line, then each message's arrival time and first 300 characters. */
87
+ export function unansweredPrompt(unanswered: readonly OwnerMessage[]): string {
88
+ return [
89
+ UNANSWERED_PREFIX,
90
+ ...unanswered.map(m => {
91
+ const quote = m.text.replace(/\s+/g, " ").trim();
92
+ return `- ${strftime(m.at, "%Y-%m-%d %H:%M")}: ${quote.length > 300 ? `${quote.slice(0, 300)}…` : quote}`;
93
+ }),
94
+ ].join("\n");
95
+ }
96
+
97
+ /** The one wrapper for machine prompts — the resume text may be swapped (plan 20261027_1500_limit_probe), the prefix rides either way. Unchanged when nothing is unanswered. */
98
+ export function withUnanswered(resume: string, messages: readonly OwnerMessage[], answers: readonly OwnerAnswer[]): string {
99
+ const un = unansweredOwnerMessages(messages, answers);
100
+ return un.length === 0 ? resume : `${unansweredPrompt(un)}\n\n${resume}`;
101
+ }
102
+
103
+ /**
104
+ * The first user message of the new session: header, Main's note, generated state, owner message.
105
+ * Every `(from: \`cmd\`)` in the note is listed under "## Numbers to re-run" right after it — re-run
106
+ * these before repeating any number. No numbers, no section.
107
+ */
73
108
  export function buildHandoff(p: HandoffInput): string {
109
+ const note = p.note.trimEnd();
110
+ const numbers = [...note.matchAll(/\(from: `([^`]+)`\)/g)].map((m) => m[1]);
74
111
  return [
112
+ ...(p.unanswered && p.unanswered.length > 0 ? [unansweredPrompt(p.unanswered), ""] : []),
75
113
  `${HANDOFF_PREFIX} ${p.previousSessionFile}. Its full history stays there; this session continues from the handoff below.`,
76
114
  "",
77
115
  "## Main's handoff note (verbatim)",
78
- p.note.trimEnd(),
116
+ note,
117
+ ...(numbers.length > 0
118
+ ? ["", "## Numbers to re-run", "re-run these before repeating any number", ...numbers.map((c) => `- \`${c}\``)]
119
+ : []),
79
120
  "",
80
121
  "## Generated state (main-start)",
81
122
  p.generated.trimEnd(),
@@ -87,15 +128,16 @@ export function buildHandoff(p: HandoffInput): string {
87
128
 
88
129
  /**
89
130
  * The owner's own words in a user prompt, or undefined for a machine prompt: a guard continuation, the
90
- * rollover note request, or a handoff without its owner marker. A handoff yields only its owner message.
131
+ * rollover note request, or a handoff without its owner marker. A handoff yields only its owner message;
132
+ * since P5b the handoff may start with the unanswered block, which is machine text either way.
91
133
  */
92
134
  export function ownerText(prompt: string): string | undefined {
93
135
  const t = prompt.trimStart();
94
- if (t.startsWith("main-guard:") || t.startsWith(NOTE_REQUEST_PREFIX)) return undefined;
95
- if (t.startsWith(HANDOFF_PREFIX)) {
136
+ if (t.startsWith(HANDOFF_PREFIX) || t.startsWith(UNANSWERED_PREFIX)) {
96
137
  const at = prompt.lastIndexOf(OWNER_MARK);
97
138
  return at < 0 ? undefined : prompt.slice(at + OWNER_MARK.length).trim();
98
139
  }
140
+ if (t.startsWith("main-guard:") || t.startsWith(NOTE_REQUEST_PREFIX)) return undefined;
99
141
  return prompt;
100
142
  }
101
143
 
@@ -127,8 +127,6 @@ export function uiOn(opts: UiOnOptions): number {
127
127
  const original = existsSync(file) ? readFileSync(file, "utf8") : null;
128
128
  const edited = editUiBlock(original, { enabled: true, owner_login: opts.login, port: opts.port ?? null });
129
129
  if (!checkEdited(edited, home, "on", error)) return 1;
130
- mkdirSync(dirname(file), { recursive: true });
131
- writeFileSync(file, edited);
132
130
  const unitPath = join(home, ".config", "systemd", "user", "neurastream-ui.service");
133
131
  mkdirSync(dirname(unitPath), { recursive: true });
134
132
  copyFileSync(UI_UNIT_TEMPLATE, unitPath);
@@ -140,10 +138,14 @@ export function uiOn(opts: UiOnOptions): number {
140
138
  const r = runner(args);
141
139
  if (r.status !== 0) {
142
140
  if (r.stderr.trim()) error(r.stderr.trimEnd());
143
- error("neurastream ui: systemctl failed — the config was already written; fix the unit and run `neurastream ui` (or this command again).");
141
+ error("neurastream ui: systemctl failed — the config was not changed; fix the unit and run `neurastream ui` (or this command again).");
144
142
  return 1;
145
143
  }
146
144
  }
145
+ // The config only turns on once the unit is up: a systemctl failure leaves the config
146
+ // exactly as it was (a leftover unit file is fine).
147
+ mkdirSync(dirname(file), { recursive: true });
148
+ writeFileSync(file, edited);
147
149
  const name = tailscale.dnsName() ?? tailscale.ip4();
148
150
  const port = opts.port ?? cfg.ui.port;
149
151
  if (name) print(`http://${name}:${port}`);
@@ -0,0 +1,131 @@
1
+ // Live recheck: a `WAITING on owner:` line may carry `— still true if: `<cmd>``, the command that
2
+ // proves the hold is still real. Exit 0 keeps the owner card up; any other exit code hides it and
3
+ // opens a "stale-hold" incident naming the plan and the command; a timeout or a spawn error is
4
+ // "unknown" (the card stays, no incident) — a check that cannot run never counts as proof.
5
+ // Results are cached per (plan file mtime, command, HEAD) for queue.waiting_check_ttl_sec, so the
6
+ // same cheap command costs one spawn per real change, not one per turn. The runner is injected:
7
+ // tests never run a plan's command.
8
+
9
+ import { spawnSync } from "node:child_process";
10
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { nowSec } from "./clock.ts";
13
+ import type { Config } from "./config.ts";
14
+ import { addIncident } from "./incidents.ts";
15
+ import * as q from "./queue/lib.ts";
16
+
17
+ export type HoldState = "holds" | "stale" | "unknown";
18
+
19
+ export interface HoldResult {
20
+ /** The plan file that carries the hold. */
21
+ plan: string;
22
+ state: HoldState;
23
+ /** The command's exit code; null when it did not finish (timeout, spawn error). */
24
+ code: number | null;
25
+ /** Milliseconds the command took; the original measurement for a cached result. */
26
+ ms: number;
27
+ }
28
+
29
+ /** Runs one check command in a directory. `code` null means it did not finish. */
30
+ export type HoldRunner = (cmd: string, cwd: string) => { code: number | null };
31
+
32
+ interface CacheRec {
33
+ key: string;
34
+ state: HoldState;
35
+ code: number | null;
36
+ ms: number;
37
+ at: number;
38
+ }
39
+
40
+ /** bash -lc with the configured timeout: only whether the command still passes matters, not its output. */
41
+ export function spawnHoldRunner(timeoutSec: number): HoldRunner {
42
+ return (cmd, cwd) => {
43
+ const res = spawnSync("bash", ["-lc", cmd], { cwd, timeout: timeoutSec * 1000, stdio: "ignore" });
44
+ return { code: typeof res.status === "number" ? res.status : null };
45
+ };
46
+ }
47
+
48
+ function gitHead(dir: string): string {
49
+ const res = spawnSync("git", ["rev-parse", "HEAD"], { cwd: dir, encoding: "utf8" });
50
+ return res.status === 0 ? res.stdout.trim() : "";
51
+ }
52
+
53
+ function readCache(file: string): Record<string, CacheRec> {
54
+ try {
55
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
56
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, CacheRec>) : {};
57
+ } catch {
58
+ return {};
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Runs the `still true if` command of every open, waiting plan that has one. `now` is epoch seconds
64
+ * (the TTL and the incident stamps are seconds); a plan whose cached key still matches and is inside
65
+ * queue.waiting_check_ttl_sec is returned without running the command. `fresh` skips that cache read
66
+ * (metrics ci re-checks after a new CI record) but still writes the result back.
67
+ */
68
+ export function recheckHolds(
69
+ cfg: Config,
70
+ plans: q.Plan[],
71
+ run: HoldRunner = spawnHoldRunner(cfg.queue.waiting_check_timeout_sec),
72
+ now = nowSec(),
73
+ fresh = false,
74
+ ): HoldResult[] {
75
+ const file = join(cfg.paths.queue_state, "waiting-check.json");
76
+ const cache = readCache(file);
77
+ const ttl = cfg.queue.waiting_check_ttl_sec;
78
+ const out: HoldResult[] = [];
79
+ for (const p of plans) {
80
+ const cmd = p.waitingCheck;
81
+ if (!p.waiting || p.status !== "open" || !cmd) continue;
82
+ const cwd = p.worktree && existsSync(p.worktree) ? p.worktree : p.repo;
83
+ let mtime = 0;
84
+ try {
85
+ mtime = statSync(p.file).mtimeMs;
86
+ } catch {}
87
+ const key = q.sha(`${mtime}\n${cmd}\n${gitHead(cwd)}`);
88
+ const hit = cache[p.file];
89
+ let rec = !fresh && hit && hit.key === key && now - hit.at < ttl ? hit : undefined;
90
+ if (!rec) {
91
+ const started = Date.now();
92
+ const code = run(cmd, cwd).code;
93
+ const state: HoldState = code === 0 ? "holds" : code === null ? "unknown" : "stale";
94
+ rec = { key, state, code, ms: Date.now() - started, at: now };
95
+ if (state === "stale") {
96
+ addIncident(
97
+ cfg,
98
+ {
99
+ source: "realtime",
100
+ kind: "stale-hold",
101
+ summary: `stale hold: ${p.file} — \`${cmd}\` exited ${code}`,
102
+ evidence: `WAITING on owner: ${p.waitingAsk ?? ""} — still true if: \`${cmd}\` (exit ${code}) ran in ${cwd}`,
103
+ fingerprint: q.sha(`stale-hold|${p.file}|${cmd}`),
104
+ },
105
+ now,
106
+ );
107
+ }
108
+ }
109
+ cache[p.file] = rec;
110
+ out.push({ plan: p.file, state: rec.state, code: rec.code, ms: rec.ms });
111
+ }
112
+ mkdirSync(dirname(file), { recursive: true });
113
+ writeFileSync(file, `${JSON.stringify(cache)}\n`);
114
+ return out;
115
+ }
116
+
117
+ /** The plan files whose hold is stale: the queue summary and the owner page hide their owner line. */
118
+ export function staleFiles(holds: HoldResult[]): Set<string> {
119
+ return new Set(holds.filter(h => h.state === "stale").map(h => h.plan));
120
+ }
121
+
122
+ /** One line per stale hold for queue-check and metrics ci: the ask, the check, and its exit code. */
123
+ export function staleHoldLines(holds: HoldResult[], plans: q.Plan[]): string[] {
124
+ const byFile = new Map(plans.map(p => [p.file, p]));
125
+ return holds
126
+ .filter(h => h.state === "stale")
127
+ .map(h => {
128
+ const p = byFile.get(h.plan);
129
+ return `STALE HOLD: ${h.plan}: ${p?.waitingAsk ?? ""} — check \`${p?.waitingCheck ?? ""}\` exited ${h.code}`;
130
+ });
131
+ }