neurastream 0.2.62 → 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.
@@ -20,6 +20,7 @@
20
20
  // "traces" and records an agent-score penalty event for that agent on the plan.
21
21
 
22
22
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
23
+ import { createHash } from "node:crypto";
23
24
  import { dirname, join } from "node:path";
24
25
  import { fileURLToPath } from "node:url";
25
26
  import type { Run, TraceEvent } from "./adapter.ts";
@@ -28,7 +29,7 @@ import { nowSec, strftime } from "./clock.ts";
28
29
  import { log } from "./guards.ts";
29
30
  import { addIncident, type IncidentView } from "./incidents.ts";
30
31
  import type { GuardBlock } from "./metrics.ts";
31
- import { verifyClaims, type Claim, type RelatedRun } from "./trace-claims.ts";
32
+ import { maskEvidence, verifyClaims, type Claim, type RelatedRun } from "./trace-claims.ts";
32
33
  import { recordPenalty } from "./agent-score.ts";
33
34
  import type { SuspiciousAction, UnreportedFinding } from "./trace-actions.ts";
34
35
 
@@ -135,6 +136,55 @@ export function blockLoop(blocks: GuardBlock[], now: number, repeat: number, win
135
136
  }));
136
137
  }
137
138
 
139
+ // ---- D8: a guard block the same action got past ----
140
+
141
+ const GUARD_BLOCK = /^(main|plan)-guard:/;
142
+
143
+ /** Token-set Jaccard similarity in [0, 1]. */
144
+ function jaccard(a: Set<string>, b: Set<string>): number {
145
+ let shared = 0;
146
+ for (const t of a) if (b.has(t)) shared++;
147
+ const union = a.size + b.size - shared;
148
+ return union === 0 ? 0 : shared / union;
149
+ }
150
+
151
+ /**
152
+ * A Main call a guard refused (an error result whose text starts main-guard:/plan-guard:) and the
153
+ * first later call of the same tool, within windowSec, whose result is not an error and whose args
154
+ * are token-similar (≥ similarity): a possible guard false positive. One finding per refused call.
155
+ */
156
+ export function blockThenBypass(events: TraceEvent[], windowSec: number, similarity: number, since = -Infinity): Finding[] {
157
+ const results = new Map<string, TraceEvent>();
158
+ for (const e of events) if (e.kind === "toolResult" && e.callId) results.set(e.callId, e);
159
+ // A call with no timestamp cannot be placed in the window, so it is neither a block nor a bypass.
160
+ const calls = events.filter((e): e is TraceEvent & { callId: string; ts: number } => e.kind === "toolCall" && !!e.callId && e.ts !== null);
161
+ const tokens = new Map(calls.map(c => [c.callId, new Set(JSON.stringify(c.args ?? null).toLowerCase().split(/\W+/).filter(Boolean))]));
162
+ const out: Finding[] = [];
163
+ for (const block of calls) {
164
+ // Blocks at or before `since` were decided by an earlier gated scan (the D8 frontier).
165
+ if (block.ts <= since) continue;
166
+ const refused = results.get(block.callId!);
167
+ if (!refused?.isError || !GUARD_BLOCK.test(refused.text ?? "")) continue;
168
+ const bypass = calls.find(c => {
169
+ const dt = c.ts - block.ts;
170
+ const r = results.get(c.callId!);
171
+ return c.callId !== block.callId && c.tool === block.tool && dt >= 0 && dt <= windowSec && r !== undefined && !r.isError && jaccard(tokens.get(block.callId!)!, tokens.get(c.callId!)!) >= similarity;
172
+ });
173
+ if (!bypass) continue;
174
+ const head = (refused.text ?? "").replace(/\s+/g, " ").trim();
175
+ const sha = createHash("sha256").update(head).digest("hex").slice(0, 16);
176
+ const blockedArgs = maskEvidence(JSON.stringify(block.args).slice(0, 200));
177
+ const allowedArgs = maskEvidence(JSON.stringify(bypass.args).slice(0, 200));
178
+ out.push({
179
+ kind: "block-then-bypass",
180
+ summary: `possible guard false positive: ${head.slice(0, 120)}`,
181
+ evidence: `blocked ${block.tool} at ${iso(block.ts)}: ${blockedArgs}; same tool allowed at ${iso(bypass.ts)}: ${allowedArgs}`,
182
+ fingerprint: `block-then-bypass:${block.tool}:${sha}`,
183
+ });
184
+ }
185
+ return out;
186
+ }
187
+
138
188
  // ---- D4: an owner message that corrects Main ----
139
189
 
140
190
  /** An owner message matching an M4 correction pattern, folded per day so a bad afternoon is one incident. */
@@ -216,6 +266,10 @@ export interface DetectorInput {
216
266
  actions?: SuspiciousAction[];
217
267
  /** D7: cross-product reads a subagent run hid behind a Findings: none line (src/core/trace-actions.ts). */
218
268
  unreported?: UnreportedFinding[];
269
+ /** D8: Main's session trace events, gathered behind the scan gate (runDetectorsGated). */
270
+ mainEvents?: TraceEvent[];
271
+ /** D8 frontier: the newest Main event time an earlier gated scan already saw (incident-scan.json mainTs). */
272
+ mainSince?: number;
219
273
  }
220
274
 
221
275
  /**
@@ -266,6 +320,9 @@ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()):
266
320
  if (input.actions) {
267
321
  attempt("suspicious-action", () => suspiciousAction(input.actions!));
268
322
  }
323
+ if (input.mainEvents) {
324
+ attempt("block-then-bypass", () => blockThenBypass(input.mainEvents!, cfg.incidents.bypass_window_sec, cfg.incidents.bypass_similarity, input.mainSince));
325
+ }
269
326
  if (input.unreported) {
270
327
  for (const f of input.unreported!) {
271
328
  try {
@@ -293,26 +350,42 @@ export interface GatedInputs {
293
350
  results: TaskResult[];
294
351
  runs: Run[];
295
352
  blocks: GuardBlock[];
353
+ /** D8: Main's session trace events (optional: a caller without a session file omits them). */
354
+ mainEvents?: TraceEvent[];
355
+ }
356
+
357
+ /** The scan gate state in <queue_state>/incident-scan.json: `lastScan` is the time of the last gated
358
+ * scan; `mainTs` is the newest Main session event time that scan saw (the D8 frontier). */
359
+ interface ScanState {
360
+ lastScan: number;
361
+ mainTs: number;
362
+ }
363
+
364
+ function readScan(file: string): ScanState {
365
+ const st: ScanState = { lastScan: 0, mainTs: 0 };
366
+ try {
367
+ const raw = JSON.parse(readFileSync(file, "utf8")) as { lastScan?: unknown; mainTs?: unknown };
368
+ if (typeof raw.lastScan === "number") st.lastScan = raw.lastScan;
369
+ if (typeof raw.mainTs === "number") st.mainTs = raw.mainTs;
370
+ } catch {}
371
+ return st;
372
+ }
373
+
374
+ function writeScan(file: string, st: ScanState): void {
375
+ mkdirSync(dirname(file), { recursive: true });
376
+ writeFileSync(file, `${JSON.stringify(st)}\n`);
296
377
  }
297
378
 
298
379
  /**
299
- * True when the expensive detectors (D1/D3) may run: at most once per
300
- * incidents.scan_interval_sec, tracked by a timestamp in <queue_state>/incident-scan.json. The
301
- * stamp is written BEFORE the inputs are read, so a slow or crashing scan cannot stack — the
302
- * next attempt is a full interval away (a failed scan retries then, not at the next event). An
303
- * unreadable state counts as never scanned; an unwritable one throws (the caller logs it and
304
- * runs the cheap detectors only).
380
+ * Whether a gated scan is due. The stamp is written BEFORE the inputs are read, so a slow or
381
+ * crashing scan cannot stack: the next attempt is a full interval away. An unreadable state counts
382
+ * as never scanned; an unwritable one throws (the caller logs it and runs the cheap detectors only).
305
383
  */
306
384
  export function scanDue(cfg: Config, now: number): boolean {
307
385
  const file = join(cfg.paths.queue_state, "incident-scan.json");
308
- let last = 0;
309
- try {
310
- const st = JSON.parse(readFileSync(file, "utf8")) as { lastScan?: unknown };
311
- if (typeof st.lastScan === "number") last = st.lastScan;
312
- } catch {}
313
- if (now - last < cfg.incidents.scan_interval_sec) return false;
314
- mkdirSync(dirname(file), { recursive: true });
315
- writeFileSync(file, `${JSON.stringify({ lastScan: now })}\n`);
386
+ const st = readScan(file);
387
+ if (now - st.lastScan < cfg.incidents.scan_interval_sec) return false;
388
+ writeScan(file, { ...st, lastScan: now });
316
389
  return true;
317
390
  }
318
391
 
@@ -321,6 +394,11 @@ export function scanDue(cfg: Config, now: number): boolean {
321
394
  * file, the ledger runs and both guard logs — seconds on a real machine — so they run at most
322
395
  * once per incidents.scan_interval_sec and `gather` is never called inside the interval. A
323
396
  * failed gate or gather is logged and the cheap detectors still run.
397
+ *
398
+ * D8 frontier: a gated scan records the newest Main event time it saw; the next scan's
399
+ * block-then-bypass only considers blocks after it, so a pair already seen is never raised twice.
400
+ * A bypass that lands only in a later scan than its block is not caught (the retry normally
401
+ * lands in the same turn, before the next prompt-start scan).
324
402
  */
325
403
  export function runDetectorsGated(
326
404
  cfg: Config,
@@ -328,11 +406,20 @@ export function runDetectorsGated(
328
406
  gather: () => GatedInputs,
329
407
  now = nowSec(),
330
408
  ): IncidentView[] {
409
+ const file = join(cfg.paths.queue_state, "incident-scan.json");
331
410
  const input: DetectorInput = { ...cheap };
411
+ let frontier: number | null = null;
332
412
  try {
333
- if (scanDue(cfg, now)) Object.assign(input, gather());
413
+ if (scanDue(cfg, now)) {
414
+ const since = readScan(file).mainTs;
415
+ const gathered = gather();
416
+ Object.assign(input, gathered, { mainSince: since });
417
+ frontier = (gathered.mainEvents ?? []).reduce((m, e) => Math.max(m, e.ts ?? 0), since);
418
+ }
334
419
  } catch (err) {
335
420
  log(cfg.paths.guard_log, `incident scan skipped: ${err instanceof Error ? err.message : String(err)}`);
336
421
  }
337
- return runDetectors(cfg, input, now);
422
+ const out = runDetectors(cfg, input, now);
423
+ if (frontier !== null) writeScan(file, { ...readScan(file), mainTs: frontier });
424
+ return out;
338
425
  }
@@ -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 {
@@ -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
  }