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
@@ -6,7 +6,8 @@
6
6
  // not remembered. A repeat sighting of an open fingerprint updates count and lastSeen on the
7
7
  // existing record instead of adding a second incident; after a resolution the same fingerprint
8
8
  // opens a new incident. Sources: realtime (detectors), daily, weekly, main (`incident add`),
9
- // findings (plan-guard: the Findings: items of a subagent's new Progress entry).
9
+ // findings (plan-guard: the Findings: items of a subagent's new Progress entry), watch (the
10
+ // src/core/watch.ts watcher: failed/stale heartbeats, failed units).
10
11
 
11
12
  import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
13
  import { dirname, join, resolve } from "node:path";
@@ -14,7 +15,7 @@ import { nowSec, strftime } from "./clock.ts";
14
15
  import type { Config } from "./config.ts";
15
16
  import * as q from "./queue/lib.ts";
16
17
 
17
- export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings" | "traces";
18
+ export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings" | "traces" | "watch";
18
19
 
19
20
  export interface IncidentRec {
20
21
  id: string;
@@ -94,7 +95,7 @@ function parseLine(line: string): IncidentRec | ResolutionRec | ProposalRec | nu
94
95
  if (rec.type !== undefined) return null;
95
96
  if (typeof rec.fingerprint !== "string" || typeof rec.kind !== "string" || typeof rec.summary !== "string" || typeof rec.ts !== "number")
96
97
  return null;
97
- const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" || rec.source === "traces" ? rec.source : "main";
98
+ const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" || rec.source === "traces" || rec.source === "watch" ? rec.source : "main";
98
99
  return {
99
100
  id: rec.id,
100
101
  fingerprint: rec.fingerprint,
@@ -232,6 +233,12 @@ export interface OwnerMessage {
232
233
  text: string;
233
234
  }
234
235
 
236
+ /** A real Main turn end, stored beside the messages (the page's lastAnswerFor shape, P5b): a message with a turn end after it is answered. */
237
+ export interface OwnerAnswer {
238
+ at: number;
239
+ answer: string;
240
+ }
241
+
235
242
  export function ownerMessagesFile(): string {
236
243
  return join(q.STATE_DIR, "owner-messages.jsonl");
237
244
  }
@@ -239,12 +246,32 @@ export function ownerMessagesFile(): string {
239
246
  export function readOwnerMessages(): OwnerMessage[] {
240
247
  try {
241
248
  return readFileSync(ownerMessagesFile(), "utf8").split("\n").filter(Boolean)
242
- .map(line => JSON.parse(line) as OwnerMessage);
249
+ .map(line => JSON.parse(line) as OwnerMessage).filter(m => typeof m.text === "string");
250
+ } catch {
251
+ return [];
252
+ }
253
+ }
254
+
255
+ export function readOwnerAnswers(): OwnerAnswer[] {
256
+ try {
257
+ return readFileSync(ownerMessagesFile(), "utf8").split("\n").filter(Boolean)
258
+ .map(line => JSON.parse(line) as OwnerAnswer).filter(a => typeof a.answer === "string");
243
259
  } catch {
244
260
  return [];
245
261
  }
246
262
  }
247
263
 
264
+ /** Rewrites the store: the newest 50 messages, then the newest 20 answers. */
265
+ export function writeOwnerStore(messages: OwnerMessage[], answers: OwnerAnswer[]): void {
266
+ mkdirSync(dirname(ownerMessagesFile()), { recursive: true });
267
+ writeFileSync(ownerMessagesFile(), [...messages.slice(-50).map(m => JSON.stringify(m)), ...answers.slice(-20).map(a => JSON.stringify(a))].join("\n") + "\n");
268
+ }
269
+
270
+ /** Records a real Main turn end as an answer in the same store (P5b); throws so the caller logs the failure. */
271
+ export function appendOwnerAnswer(answer: string, at = nowSec()): void {
272
+ writeOwnerStore(readOwnerMessages(), [...readOwnerAnswers(), { at, answer }]);
273
+ }
274
+
248
275
  export function ownerSaid(words: string, messages: OwnerMessage[], now: number): boolean {
249
276
  const quote = words.toLowerCase().replace(/\s+/g, " ").trim();
250
277
  if (quote.split(" ").length < 4) return false;
@@ -2,11 +2,11 @@ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "no
2
2
  import { spawn } from "node:child_process";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import type { RunSource } from "./adapter.ts";
5
+ import type { RunSource, TraceEvent } from "./adapter.ts";
6
6
  import { readEvents } from "./agent-score.ts";
7
7
  import type { Config } from "./config.ts";
8
8
  import { nowSec, strftime } from "./clock.ts";
9
- import { runDetectors, type TaskResult } from "./incident-detectors.ts";
9
+ import { runDetectors, runDetectorsGated, type GatedInputs, type TaskResult } from "./incident-detectors.ts";
10
10
  import { addIncident, type IncidentView } from "./incidents.ts";
11
11
  import { log as logGuard } from "./guards.ts";
12
12
  import { dailyChecks, readBlocks, readMetricEvents, worseThanMean } from "./metrics.ts";
@@ -14,6 +14,7 @@ import { buildReport } from "./report.ts";
14
14
  import { loadavgLine } from "./host.ts";
15
15
  import { providersLine } from "./provider-state.ts";
16
16
  import { mrSweep } from "./mr-sweep.ts";
17
+ import { watchHealth } from "./watch.ts";
17
18
 
18
19
  function bin(name: string, cfg: Config): string {
19
20
  return join(cfg.paths.home, ".local/bin", name);
@@ -112,6 +113,32 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
112
113
  const due = metricsDueLine(cfg, Date.now());
113
114
  if (due) say(due);
114
115
  }
116
+ // Watcher health (plan 20261027_1430 P4): silent unless `watch on` installed the timer. A run older
117
+ // than 3 intervals (or never) prints NOT RUNNING and opens a watch incident; watchOnce closes it
118
+ // again on the next successful pass.
119
+ const watchState = watchHealth(cfg, Date.now());
120
+ if (watchState.installed) {
121
+ if (watchState.lastRunMin !== null && watchState.lastRunMin <= 3 * watchState.intervalMin) {
122
+ say(`watch: last run ${watchState.lastRunMin} min ago`);
123
+ } else {
124
+ say(`watch: NOT RUNNING since ${watchState.lastRunAt ?? "never"}`);
125
+ try {
126
+ addIncident(
127
+ cfg,
128
+ {
129
+ source: "watch",
130
+ kind: "not-running",
131
+ summary: `watcher has not run since ${watchState.lastRunAt ?? "install"} (interval ${watchState.intervalMin} min)`,
132
+ evidence: `last watch heartbeat: ${watchState.lastRunAt ?? "none"}`,
133
+ fingerprint: "watch:not-running",
134
+ },
135
+ nowSec(),
136
+ );
137
+ } catch (err) {
138
+ logGuard(cfg.paths.guard_log, `watch incident failed: ${err instanceof Error ? err.message : String(err)}`);
139
+ }
140
+ }
141
+ }
115
142
  say("=== machine");
116
143
  const mg = await run(bin("machine-guard", cfg), [], { stderr: "ignore" });
117
144
  const mgLines = mg.stdout.trim().split("\n");
@@ -195,6 +222,46 @@ function fmtMetric(v: number | null): string {
195
222
  return v === null ? "n/a" : v >= 10 ? String(Math.round(v)) : v.toFixed(2);
196
223
  }
197
224
 
225
+ /** Where the expensive detector inputs come from: the harness adapter's session readers
226
+ * (src/adapters/<harness>; core never imports one — the caller hands the seam in). */
227
+ export interface DetectorSeam {
228
+ runSource(cfg: Config): RunSource;
229
+ completedResults(cfg: Config): TaskResult[];
230
+ /** D8 input. A seam without it gives the detectors no main events, so D8 stays silent. */
231
+ mainEvents?(cfg: Config): TraceEvent[];
232
+ }
233
+
234
+ /**
235
+ * The gather the prompt-time detectors and the watcher (src/core/watch.ts) share: fresh
236
+ * completed task-results, the last two days of ledger runs and the guard-log blocks — read
237
+ * only when runDetectorsGated's scan gate opens (incidents.scan_interval_sec).
238
+ */
239
+ export function defaultGather(cfg: Config, seam: DetectorSeam): () => GatedInputs {
240
+ return () => ({
241
+ results: seam.completedResults(cfg),
242
+ runs: seam.runSource(cfg).listRuns(nowSec() - 2 * 86400),
243
+ blocks: readBlocks(cfg),
244
+ mainEvents: seam.mainEvents?.(cfg) ?? [],
245
+ });
246
+ }
247
+
248
+ /**
249
+ * Real-time incident detectors (plan 20261022_2330 P3) at Main's prompt and after each Main bash
250
+ * result, plus the once-per-day metrics check (P4, retried until it marks the day). The cheap
251
+ * detectors (D2 bash, D4 prompt) run on every call; D1/D3 and their inputs — Main's session
252
+ * file, the ledger runs, both guard logs — are gathered behind the scan interval
253
+ * (incidents.scan_interval_sec, see runDetectorsGated). Best effort: a failed check is logged,
254
+ * never thrown.
255
+ */
256
+ export function mainDetectors(cfg: Config, seam: DetectorSeam, extra: { prompt?: string; bash?: { command: string; output: string } }): void {
257
+ try {
258
+ runDetectorsGated(cfg, extra, defaultGather(cfg, seam));
259
+ runDailyCheck(cfg, seam.runSource(cfg), nowSec());
260
+ } catch (err) {
261
+ logGuard(cfg.paths.guard_log, `incident detectors failed: ${err instanceof Error ? err.message : String(err)}`);
262
+ }
263
+ }
264
+
198
265
  /**
199
266
  * Once per calendar day (state file in queue_state), at the first main-start or Main
200
267
  * before_agent_start: M1-M5 for the last 24h against the mean of the 7 days before; each metric
@@ -249,6 +316,20 @@ export function runWeeklyCheck(cfg: Config, source: RunSource, now: number): str
249
316
  const rep = buildReport(cfg, source, cfg.metrics.report_days, now);
250
317
  mkdirSync(cfg.paths.notes, { recursive: true });
251
318
  writeFileSync(join(cfg.paths.notes, "metrics.md"), rep.md);
319
+ for (const n of rep.noisy) {
320
+ const { incident: noisy } = addIncident(
321
+ cfg,
322
+ {
323
+ source: "weekly",
324
+ kind: n.kind,
325
+ summary: n.summary,
326
+ evidence: n.evidence,
327
+ fingerprint: `noisy:${n.detector}:${strftime(now, "%Y%m%d")}`,
328
+ },
329
+ now,
330
+ );
331
+ logGuard(cfg.paths.guard_log, `incident ${noisy.id} [weekly/${noisy.kind}] opened: ${noisy.summary}`);
332
+ }
252
333
  const w = rep.worst;
253
334
  if (!w || w.change === null) {
254
335
  return `metrics: report due (last: ${last}) — wrote ${join(cfg.paths.notes, "metrics.md")}; no ranked metric moved this window`;
@@ -222,8 +222,9 @@ export interface GuardBlock {
222
222
  }
223
223
 
224
224
  /** Groups reasons by shape: paths cut to 40 chars, digit runs collapsed to N, and every
225
- * `open: <plan list>` tail collapsed to one key: the lists differ per plan set, the reason is one. */
226
- function reasonKey(text: string): string {
225
+ * `open: <plan list>` tail collapsed to one key: the lists differ per plan set, the reason is one.
226
+ * Exported for the release verdict, which compares M5 blocks per reason (P11). */
227
+ export function reasonKey(text: string): string {
227
228
  const shaped = text.replace(/\S*\/\S*/g, (p) => (p.length > 40 ? `${p.slice(0, 40)}…` : p)).replace(/\d+/g, "N");
228
229
  const at = shaped.indexOf("open: ");
229
230
  return at === -1 ? shaped : `${shaped.slice(0, at)}open: <list>`;
@@ -109,7 +109,7 @@ function asNumber(v: unknown): number | null {
109
109
  }
110
110
 
111
111
  /** Parse a JSON list. Null means the CLI answered but not with a list — treat as unreachable, never as "no MRs". */
112
- function parseList(stdout: string): Record<string, unknown>[] | null {
112
+ export function parseList(stdout: string): Record<string, unknown>[] | null {
113
113
  const t = stdout.trim();
114
114
  if (!t) return [];
115
115
  const from = (v: unknown): Record<string, unknown>[] | null => {
@@ -208,17 +208,24 @@ export interface OpenMr {
208
208
  /** `{ ok: false, why }` is the sweep's degrade: the caller logs it and never treats it as "no MRs". */
209
209
  export type OpenMrs = { ok: true; mrs: OpenMr[] } | { ok: false; why: string };
210
210
 
211
+ /** The forge behind a repo's origin remote: `{ forge }`, or `{ why }` (the sweep's degrade reason). */
212
+ export function repoForge(repo: string, run: CommandRunner = defaultRunner, env?: NodeJS.ProcessEnv): { forge: Forge } | { why: string } {
213
+ const remote = run(["git", "-C", repo, "remote", "get-url", "origin"], { env });
214
+ const url = remote.code === 0 ? remote.stdout.trim() : "";
215
+ if (!url) return { why: "no origin remote" };
216
+ const host = remoteHost(url);
217
+ const forge = host ? forgeOf(host) : null;
218
+ return forge ? { forge } : { why: "unknown forge" };
219
+ }
220
+
211
221
  /**
212
222
  * Open MRs of one repo (the sweep's lister, single-repo): `!N` / `#N` token plus source branch.
213
223
  * Everything — origin lookup included — goes through the runner, so callers can inject it.
214
224
  */
215
225
  export function listOpenMrs(repo: string, run: CommandRunner = defaultRunner, env?: NodeJS.ProcessEnv): OpenMrs {
216
- const remote = run(["git", "-C", repo, "remote", "get-url", "origin"], { env });
217
- const url = remote.code === 0 ? remote.stdout.trim() : "";
218
- if (!url) return { ok: false, why: "no origin remote" };
219
- const host = remoteHost(url);
220
- const forge = host ? forgeOf(host) : null;
221
- if (!forge) return { ok: false, why: "unknown forge" };
226
+ const found = repoForge(repo, run, env);
227
+ if ("why" in found) return { ok: false, why: found.why };
228
+ const forge = found.forge;
222
229
  const listed = forge === "gitlab" ? listGitlab(repo, run, env) : listGithub(repo, run, env);
223
230
  if (listed.missing) return { ok: false, why: "no forge CLI" };
224
231
  if (listed.fail) return { ok: false, why: "forge unreachable" };
@@ -24,6 +24,7 @@ import { readMetricEvents } from "./metrics.ts";
24
24
  import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, writeIndex, type Plan } from "./queue/lib.ts";
25
25
  import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleaseRow, type ReleaseSideStats, type ReleasesReport } from "./results.ts";
26
26
  import type { Tailscale } from "./tailscale.ts";
27
+ import { recheckHolds, staleFiles, type HoldRunner } from "./waiting-check.ts";
27
28
 
28
29
  const ANSWER_MAX = 2000;
29
30
  const MESSAGE_MAX = 4000;
@@ -189,11 +190,12 @@ export interface MachineRow {
189
190
  cores: number;
190
191
  }
191
192
 
192
- export function questionRows(cfg: Config): QuestionRow[] {
193
+ export function questionRows(cfg: Config, run?: HoldRunner): QuestionRow[] {
193
194
  const now = Date.now();
194
195
  const plans = activePlans(cfg.paths.queue_index);
196
+ const stale = staleFiles(recheckHolds(cfg, plans, run));
195
197
  return plans
196
- .filter(p => p.waiting && p.status === "open" && p.waitingLine)
198
+ .filter(p => p.waiting && p.status === "open" && p.waitingLine && !stale.has(p.file))
197
199
  .map(p => {
198
200
  let waitingMin = 0;
199
201
  try {
@@ -159,7 +159,7 @@ export function approvalProblem(text: string, file: string, pagesDir: string, si
159
159
  if (since === "") return null;
160
160
  const page = pageOfPlan(pagesDir, file);
161
161
  const stamp = /^\d{8}_\d{4}/.exec(basename(file))?.[0] ?? null;
162
- const gated = since !== "" && (stamp === null || stamp >= since);
162
+ const gated = stamp === null || stamp >= since;
163
163
  if (page === null) {
164
164
  if (!gated) return null; // predates the convention
165
165
  return `plan ${file} has no page: publish its page with neurastream pages publish <page.html> --plan ${file}`;
@@ -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),
@@ -554,7 +571,7 @@ export function touchedPaths(toolName: string, input: Record<string, unknown>, c
554
571
  }
555
572
 
556
573
  export const MUTATING =
557
- /(\brm\b|\bmv\b|\bcp\b|\btouch\b|\btruncate\b|\bchmod\b|\bln\b|\bsed\s+(-\w*\s+)*-i|\bperl\s+(-\w*\s+)*-[a-z]*i|\btee\b|(^|[^0-9&>=-])>{1,2}\s*[^\s&>]|\bgit\s+(rm|mv|checkout|restore|apply|am|stash|reset|clean)\b|\bpatch\b|\binstall\b|\bdd\b|writeFile|appendFile|Bun\.write|unlink|rmSync|\.write_text\(|\.write_bytes\(|\bopen\([^)]*,\s*["'][wax]b?\+?["']|shutil\.|os\.(remove|rename|replace|unlink|chmod)|\.writelines\()/;
574
+ /(\brm\b|\bmv\b|\bcp\b|\btouch\b|\btruncate\b|\bchmod\b|\bln\b|\bsed\s+(-\w*\s+)*-i|\bperl\s+(-\w*\s+)*-[a-z]*i|\btee\b|(^|[^0-9&>=-])>{1,2}\s*[^\s&>]|\bgit\s+(rm|mv|checkout|restore|apply|am|stash|reset|clean)\b|\bpatch\b|\binstall\b|\bdd\b|writeFile|appendFile|Bun\.write|unlink|rmSync|renameSync|cpSync|copyFileSync|linkSync|symlinkSync|mkdtempSync|mkdirSync|rmdirSync|\.write_text\(|\.write_bytes\(|\bopen\([^)]*,\s*["'][wax]b?\+?["']|shutil\.|os\.(remove|rename|replace|unlink|chmod)|\.writelines\()/;
558
575
 
559
576
  export function withoutQuotedRedirects(code: string): string {
560
577
  return code.replace(/'[^']*'/g, m => m.replace(/>/g, " ")).replace(/"(?:[^"\\]|\\.)*"/g, m => m.replace(/>/g, " "));
@@ -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];