neurastream 0.2.59 → 0.2.60

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.59",
3
+ "version": "0.2.60",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -199,24 +199,28 @@ function subActionDetectors(cfg: Config, ctx: unknown, planFile: string, before:
199
199
  }
200
200
  }
201
201
 
202
- // Background queue-close for every plan Main marked complete. Ported from the
203
- // original autoClose: same filter, same "--- auto-close attempt" log line, detached child with
204
- // stdio on the per-plan close log. QUEUE_CLOSE_BIN overrides the binary (tests); without it the
205
- // package's own executable bin/queue-close runs (its `#!/usr/bin/env bun` shebang picks bun).
202
+ // Background queue-close for every plan Main marked complete — and (P4, plan 20261031_0911) for
203
+ // every OPEN plan whose work has landed. Ported from the original autoClose: same filter, same
204
+ // "--- auto-close attempt" log line, detached child with stdio on the per-plan close log.
205
+ // QUEUE_CLOSE_BIN overrides the binary (tests); without it the package's own executable
206
+ // bin/queue-close runs (its `#!/usr/bin/env bun` shebang picks bun).
206
207
  // Never process.execPath: inside the harness that is the harness binary itself, so the child was
207
208
  // a new agent session that loaded this plugin and auto-closed again — a process fork bomb
208
209
  // (2026-10-21 OOMs, ~175 processes).
209
- function closeChildArgs(plan: string): [string, string[]] {
210
+ function closeChildArgs(plan: string, auto: boolean): [string, string[]] {
210
211
  const bin = process.env.QUEUE_CLOSE_BIN;
211
- if (bin) return [bin, [plan]];
212
- return [join(import.meta.dir, "..", "..", "..", "bin", "queue-close"), [plan]];
212
+ const args = auto ? ["--auto", plan] : [plan];
213
+ if (bin) return [bin, args];
214
+ return [join(import.meta.dir, "..", "..", "..", "bin", "queue-close"), args];
213
215
  }
214
216
 
215
217
  export function autoClose(cfg: Config): string[] {
216
218
  const started: string[] = [];
217
219
  let plans: q.Plan[];
218
220
  try {
219
- plans = q.activePlans().filter(p => (p.status === "complete" || p.status === "cancelled") && !p.errors.length);
221
+ // P4: landed open plans auto-close too (q.autoCloseCandidate) — the child runs queue-close
222
+ // --auto and writes "Status: complete" itself when the done check passes.
223
+ plans = q.activePlans().filter(p => (p.status === "complete" || p.status === "cancelled" || q.autoCloseCandidate(p)) && !p.errors.length);
220
224
  } catch {
221
225
  return started;
222
226
  }
@@ -228,7 +232,7 @@ export function autoClose(cfg: Config): string[] {
228
232
  const outFile = q.closeLog(p.file);
229
233
  appendFileSync(outFile, `--- ${new Date().toISOString()} auto-close attempt\n`);
230
234
  const out = openSync(outFile, "a");
231
- const [bin, args] = closeChildArgs(p.file);
235
+ const [bin, args] = closeChildArgs(p.file, p.status === "open");
232
236
  const child = spawn(bin, args, { detached: true, stdio: ["ignore", out, out], env: process.env });
233
237
  child.unref();
234
238
  started.push(p.file);
@@ -1,4 +1,5 @@
1
- import { readFileSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
2
3
  import { pagesDoctor } from "../core/pages-doctor.ts";
3
4
  import { ConfigError, configFile, loadConfig, type Config } from "../core/config.ts";
4
5
  import { postReply } from "../core/notify.ts";
@@ -17,7 +18,7 @@ import { runNotes } from "./notes.ts";
17
18
  import { runPages } from "./pages.ts";
18
19
  import { runUninstall } from "../core/uninstall.ts";
19
20
  import { queueMigrate } from "../core/queue-migrate.ts";
20
- import { allowedAgents, subagentsPath } from "../core/queue/lib.ts";
21
+ import { allowedAgents, enforceReadOnlyIndex, indexPath, readIndex, subagentsPath, writeIndex } from "../core/queue/lib.ts";
21
22
  import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
22
23
 
23
24
  const BINS = [
@@ -64,6 +65,11 @@ export function helpText(): string {
64
65
  " neurastream redact filter stdin through the secret redactor: stdout gets the text,",
65
66
  " stderr the hit summary (types and counts only)",
66
67
  " neurastream queue migrate fold the old repo INDEX.md files into the one main index",
68
+ " neurastream queue add <plan.md> [--rank N]",
69
+ " add a plan to the index (append, or insert at 1-based rank N)",
70
+ " neurastream queue move <plan.md> <rank>",
71
+ " move a listed plan to rank N; the index file itself is 0444,",
72
+ " these two commands are the only agent writes to it",
67
73
  " neurastream config [--json] print the merged config (defaults + file + env)",
68
74
  " neurastream guard <event> --json",
69
75
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
@@ -130,6 +136,10 @@ export async function run(cmd: string, args: string[]): Promise<number> {
130
136
  }
131
137
  if (cmd === "doctor") {
132
138
  for (const warning of pagesDoctor()) console.warn(`warning: ${warning}`);
139
+ try {
140
+ const was = enforceReadOnlyIndex(loadConfig().paths.queue_index);
141
+ if (was) console.warn(`warning: ${indexPath()} — was ${was}, set 0444 (the plan index is read-only on disk)`);
142
+ } catch {} // a broken config is doctor's own report; the adapter doctor names it
133
143
  return getAdapter().doctor();
134
144
  }
135
145
  if (cmd === "notify") return runNotify(args);
@@ -143,6 +153,15 @@ export async function run(cmd: string, args: string[]): Promise<number> {
143
153
  return 1;
144
154
  }
145
155
  }
156
+ if (cmd === "queue" && (args[0] === "add" || args[0] === "move")) {
157
+ try {
158
+ applyQueueEnv(loadConfig());
159
+ } catch (err) {
160
+ console.error(err instanceof ConfigError ? err.message : String(err));
161
+ return 1;
162
+ }
163
+ return args[0] === "add" ? runQueueAdd(args.slice(1)) : runQueueMove(args.slice(1));
164
+ }
146
165
  if (cmd === "guard") {
147
166
  return runGuard(args[0] ?? "");
148
167
  }
@@ -160,6 +179,63 @@ export async function run(cmd: string, args: string[]): Promise<number> {
160
179
  return 2;
161
180
  }
162
181
 
182
+ const QUEUE_EDIT_USAGE =
183
+ "usage: neurastream queue add <plan.md> [--rank N] add a plan to the index (append, or insert at 1-based rank N)\n" +
184
+ " neurastream queue move <plan.md> <rank> move a listed plan to rank N";
185
+
186
+ // The index file is 0444 and guard-protected (plan 20261031_0911 P2), so these two commands are the
187
+ // only way an agent adds a plan or reorders it. Both write through writeIndex: the set of plans can
188
+ // only grow, and the file stays read-only on disk after every write.
189
+ function runQueueAdd(args: string[]): number {
190
+ const ri = args.indexOf("--rank");
191
+ const rest = args.filter((a, i) => a !== "--rank" && args[i - 1] !== "--rank");
192
+ const rankArg = ri >= 0 ? args[ri + 1] : undefined;
193
+ const n = Number(rankArg);
194
+ const rank = rankArg !== undefined && rankArg !== "" && Number.isInteger(n) && n >= 1 ? n : null;
195
+ if (rest.length !== 1 || (ri >= 0 && rank === null)) {
196
+ console.error(QUEUE_EDIT_USAGE);
197
+ return 2;
198
+ }
199
+ const abs = path.resolve(rest[0]!);
200
+ if (!existsSync(abs)) {
201
+ console.error(`queue add: ${abs} does not exist`);
202
+ return 1;
203
+ }
204
+ const lines = readIndex();
205
+ if (lines.includes(abs)) {
206
+ console.error(`queue add: ${abs} is already listed at rank ${lines.indexOf(abs) + 1} (queue move reorders it)`);
207
+ return 1;
208
+ }
209
+ const at = rank === null ? lines.length : Math.min(rank - 1, lines.length);
210
+ lines.splice(at, 0, abs);
211
+ writeIndex(lines);
212
+ console.log(`queue add: ${abs} at rank ${at + 1} of ${lines.length} in ${indexPath()}`);
213
+ return 0;
214
+ }
215
+
216
+ function runQueueMove(args: string[]): number {
217
+ const [fileArg, rankArg] = args;
218
+ const n = Number(rankArg);
219
+ const rank = rankArg !== undefined && rankArg !== "" && Number.isInteger(n) && n >= 1 ? n : null;
220
+ if (args.length !== 2 || rank === null) {
221
+ console.error(QUEUE_EDIT_USAGE);
222
+ return 2;
223
+ }
224
+ const abs = path.resolve(fileArg!);
225
+ const lines = readIndex();
226
+ const from = lines.indexOf(abs);
227
+ if (from === -1) {
228
+ console.error(`queue move: ${abs} is not in ${indexPath()}`);
229
+ return 1;
230
+ }
231
+ lines.splice(from, 1);
232
+ const to = Math.min(rank - 1, lines.length);
233
+ lines.splice(to, 0, abs);
234
+ writeIndex(lines);
235
+ console.log(`queue move: ${abs} rank ${from + 1} → ${to + 1} of ${lines.length} in ${indexPath()}`);
236
+ return 0;
237
+ }
238
+
163
239
  const NOTIFY_USAGE = "usage: neurastream notify test";
164
240
 
165
241
  /** `neurastream notify test`: post one line to every configured provider; exit 1 when any fails. */
@@ -592,6 +592,17 @@ export function planGate(text: string, label: string, cfg?: Config): [string | n
592
592
  `${label}: a brief must not ask for research for a plan to be written. Please never ever ever write a plan when another agent is doing the research or reading for you. Main reads the code for its plans itself.`,
593
593
  [],
594
594
  ];
595
+ // P5 (plan 20261031_0911): a landed open plan whose auto-close failed locks the queue — every
596
+ // brief must name it, so the next spawn works on closing it instead of around it. A named
597
+ // locked plan skips the unticked-phase checks below: its work has landed, the job is the close.
598
+ const locked = plans.filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file));
599
+ for (const s of locked) {
600
+ if (named.some(n => n.file === s.file)) continue;
601
+ return [
602
+ `${label}: ${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file) ?? "").replace(/^queue-close: /, "")}). The queue is locked on it: name this plan in the brief and fix the close before any other spawn.`,
603
+ [],
604
+ ];
605
+ }
595
606
  const spawns = readSpawns();
596
607
  for (const p of named) {
597
608
  if (p.errors.length) return [`${label}: plan ${p.file} is not ready (${p.errors.join("; ")}).`, []];
@@ -610,6 +621,8 @@ export function planGate(text: string, label: string, cfg?: Config): [string | n
610
621
  if (approval) return [approval, []];
611
622
  }
612
623
  const open = unticked(p);
624
+ // A locked plan's work has landed: closing it is the job, there is no phase left to tick.
625
+ if (locked.some(l => l.file === p.file)) continue;
613
626
  if (!open.length) return [`${label}: plan ${p.file} has no unticked phase left.`, []];
614
627
  if (!open.some(id => new RegExp(`\\b${id}\\b`).test(text)))
615
628
  return [`${label}: the brief must name an unticked phase of ${p.file} (${open.join(", ")}).`, []];
@@ -1363,10 +1376,14 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1363
1376
  const hit = protectedHit(openWrites, cfg);
1364
1377
  if (hit && !unlocked(cfg)) {
1365
1378
  log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} protected: ${hit}`);
1379
+ // The plan index (plan 20261031_0911 P2) is guard surface like the rest, but unlike the
1380
+ // others an agent has a sanctioned way to change it: the queue add/move CLI through
1381
+ // writeIndex. Name it, so the refusal says what to do instead of naming the unlock.
1382
+ const viaQueue = hit === q.INDEX ? ` Plans enter the index or move within it through \`neurastream queue add\` / \`neurastream queue move\`.` : "";
1366
1383
  return deny(
1367
1384
  `plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${q.UNLOCK}\` in a terminal${
1368
1385
  cfg.guards.chat_unlock ? `, or type \`unlock ${cfg.guards.unlock_minutes}\` in chat` : ""
1369
- }, valid ${cfg.guards.unlock_minutes} min).`,
1386
+ }, valid ${cfg.guards.unlock_minutes} min).${viaQueue}`,
1370
1387
  );
1371
1388
  }
1372
1389
  if (e.agent === "main") {
@@ -1948,6 +1965,24 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1948
1965
  state,
1949
1966
  };
1950
1967
  }
1968
+ // P5 (plan 20261031_0911): a landed open plan whose auto-close failed holds the stop until a
1969
+ // running subagent's brief names it (staffing ∩ live ledger); unrelated live subagents release
1970
+ // nothing, and there is no idle-stop valve — the lock lifts when the plan closes or is staffed.
1971
+ const locked = q.activePlans().filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file));
1972
+ if (locked.length) {
1973
+ const staffed = staffedPlans(readStaffing(), liveSubagents(e.ledgerText));
1974
+ const unworked = locked.filter(s => !staffed.includes(s.file));
1975
+ if (unworked.length) {
1976
+ log(cfg.paths.guard_log, `BLOCK stop: landed but not closed: ${unworked.map(s => s.file).join(", ")}`);
1977
+ return {
1978
+ allow: false,
1979
+ reason:
1980
+ `main-guard: ${unworked.map(s => `${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file) ?? "").replace(/^queue-close: /, "")})`).join("; ")}. ` +
1981
+ "The stop stays locked: spawn an agent whose brief names the plan, or fix the close.",
1982
+ state,
1983
+ };
1984
+ }
1985
+ }
1951
1986
  if (open.length === 0) return { ...ALLOW, state };
1952
1987
  if (liveSubagents(e.ledgerText).length > 0) {
1953
1988
  log(cfg.paths.guard_log, "ALLOW stop: live subagents");
@@ -7,7 +7,7 @@
7
7
  // tests never call the binary; the peer address is an injectable seam too, so tests bind
8
8
  // 127.0.0.1 while the real server binds only the tailnet address from `tailscale ip -4`.
9
9
 
10
- import { appendFileSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, statfsSync, writeFileSync } from "node:fs";
10
+ import { appendFileSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, statfsSync, writeFileSync } from "node:fs";
11
11
  import { randomUUID } from "node:crypto";
12
12
  import os from "node:os";
13
13
  import { basename, resolve } from "node:path";
@@ -21,7 +21,7 @@ import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue,
21
21
  import { log } from "./guards.ts";
22
22
  import { publishedPages } from "./pages-expiry.ts";
23
23
  import { readMetricEvents } from "./metrics.ts";
24
- import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
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
27
 
@@ -1732,10 +1732,9 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
1732
1732
  if (from === -1 || to === -1) return fail("moved is not one of the page's plans", 400);
1733
1733
  const newText = reorderedIndexText(index, order, new Set(openPaths));
1734
1734
  if (newText === null) return fail("the queue index no longer lists every open plan", 400);
1735
- // Atomic write: a torn INDEX.md would break every reader, so temp file in the same dir + rename.
1736
- const tmp = `${index}.${randomUUID().slice(0, 8)}.tmp`;
1737
- writeFileSync(tmp, newText);
1738
- renameSync(tmp, index);
1735
+ // The queue library owns every index write (plan 20261031_0911 P2): a reorder is the same plan
1736
+ // set, so no removal reason, and the write lands temp+rename and leaves the file 0444.
1737
+ writeIndex(newText.trimEnd().split("\n"), undefined, index);
1739
1738
  mkdirSync(stateDirPath(), { recursive: true });
1740
1739
  appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "reorder", plan: moved, from: from + 1, to: to + 1, login })}\n`);
1741
1740
  if (wantsJson) return Response.json({ ok: true, to: to + 1 });
@@ -1,11 +1,78 @@
1
1
  // Queue model: ONE index — the main index lists plan files, one absolute path per line (templates/queue/TEMPLATE.md).
2
2
 
3
3
  import { createHash } from "node:crypto";
4
- import { accessSync, appendFileSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
4
+ import { spawnSync } from "node:child_process";
5
+ import { accessSync, appendFileSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
5
6
  import os from "node:os";
6
7
  import path from "node:path";
7
8
  import type { Config } from "../config.ts";
8
9
 
10
+ // --- landing detection (plan 20261031_0911 P4/P5): lives here, not queue-close.ts, because
11
+ // queueProblems' landed lock needs it and lib must not import the closer that imports lib ---
12
+
13
+ /** `{ ok, out }` from a git run in `cwd` (stdout+stderr, trimmed). */
14
+ export function gitOut(cwd: string, ...args: string[]): { ok: boolean; out: string } {
15
+ const r = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8" });
16
+ return { ok: r.status === 0, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
17
+ }
18
+
19
+ // True when commit `into` already holds everything in `from`: a clean merge of `from` into it
20
+ // yields exactly its own tree.
21
+ function contains(repo: string, into: string, from: string): boolean {
22
+ const m = gitOut(repo, "merge-tree", "--write-tree", into, from);
23
+ return m.ok && m.out.split("\n")[0] === gitOut(repo, "rev-parse", `${into}^{tree}`).out;
24
+ }
25
+
26
+ // Squash or rebase merges put a new commit on base, so the branch tip is never an ancestor of it.
27
+ // The branch counts as landed when (a) a commit on base carries the same combined patch as the
28
+ // whole branch, (b) every file the branch changed is identical on base, or (c) merging the branch
29
+ // into some first-parent commit of base since the fork point changes nothing (the release squash
30
+ // that shipped it; later edits on base would otherwise conflict).
31
+ function squashMerged(repo: string, ref: string, base: string): boolean {
32
+ const mb = gitOut(repo, "merge-base", ref, base);
33
+ if (!mb.ok) return false;
34
+ const probe = gitOut(repo, "commit-tree", `${ref}^{tree}`, "-p", mb.out, "-m", "queue-close squash probe");
35
+ if (probe.ok && gitOut(repo, "cherry", base, probe.out).out.startsWith("-")) return true;
36
+ const files = gitOut(repo, "diff", "--name-only", mb.out, ref);
37
+ if (!files.ok || !files.out) return false;
38
+ if (gitOut(repo, "diff", "--quiet", ref, base, "--", ...files.out.split("\n")).ok) return true;
39
+ const since = gitOut(repo, "rev-list", "--first-parent", "--max-count=200", `${mb.out}..${base}`);
40
+ return since.ok && !!since.out && since.out.split("\n").some(s => contains(repo, s, ref));
41
+ }
42
+
43
+ // (d) Stacked branches squashed together with later edits conflict in (c). The plan then names
44
+ // the release: "Landed: <commit on base> from <pre-squash commit>". Verified, never trusted: the
45
+ // first must be on base, the branch tip must be in the second's history, and the first must
46
+ // already contain the second.
47
+ function declaredLanded(repo: string, ref: string, base: string, text: string): boolean {
48
+ const m = text.match(/^(?:- )?Landed: ([0-9a-f]{7,40}) from ([0-9a-f]{7,40})\s*$/m);
49
+ if (!m || !m[1] || !m[2]) return false;
50
+ return gitOut(repo, "merge-base", "--is-ancestor", m[1], base).ok &&
51
+ gitOut(repo, "merge-base", "--is-ancestor", ref, m[2]).ok &&
52
+ contains(repo, m[1], m[2]);
53
+ }
54
+
55
+ /** P4 (plan 20261031_0911): `branch` has landed on `base` — an ancestor, squash/rebase-merged, or declared landed in the plan text. Re-exported by queue-close.ts. */
56
+ export function landed(repo: string, branch: string, base: string, text: string): boolean {
57
+ return gitOut(repo, "merge-base", "--is-ancestor", `refs/heads/${branch}`, base).ok ||
58
+ squashMerged(repo, `refs/heads/${branch}`, base) ||
59
+ declaredLanded(repo, `refs/heads/${branch}`, base, text);
60
+ }
61
+
62
+ /** The base landing is judged against outside queueClose: origin's default branch, no fetch (the filter and queueProblems run per prompt; queue-close --auto re-checks with its own upstreamBase). */
63
+ function originBase(repo: string): string {
64
+ const head = gitOut(repo, "symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD");
65
+ return head.ok && head.out ? `refs/remotes/${head.out}` : "refs/remotes/origin/main";
66
+ }
67
+
68
+ /** P4: an open plan auto-close starts for — its branch exists and has landed, or it names no branch (a Main-only plan) and every phase is ticked. Shared by the adapter's autoClose filter and queueProblems' landed lock (P5); queue-close --auto re-checks authoritatively. */
69
+ export function autoCloseCandidate(p: Plan): boolean {
70
+ if (p.status !== "open" || p.errors.length) return false;
71
+ if (!p.branch) return p.phases.total > 0 && p.phases.done === p.phases.total;
72
+ if (!gitOut(p.repo, "rev-parse", "--verify", "-q", `refs/heads/${p.branch}`).ok) return false;
73
+ return landed(p.repo, p.branch, originBase(p.repo), p.text);
74
+ }
75
+
9
76
  const HOME = os.homedir();
10
77
  // Base set by applyQueueEnv from paths.agent_dir. Specific QUEUE_* vars still win.
11
78
  function agentDir(): string {
@@ -100,6 +167,41 @@ export function readIndex(file = indexPath(), base = process.cwd()): string[] {
100
167
  return [...new Set((indexLines(file) ?? []).map(l => path.resolve(base, expandHome(l))))];
101
168
  }
102
169
 
170
+ // The one writer of the index (plan 20261031_0911 P2): the index can only grow. A plan that would
171
+ // disappear without an explicit close/cancel/migrate reason throws before anything is written, and
172
+ // every write lands temp+rename then chmods the file to 0444. No 0o644 before the rename: rename(2)
173
+ // replaces a read-only target with directory-write permission only, so the file is never writable —
174
+ // not even between the rename and the chmod. `file` defaults to the env index; the owner page
175
+ // reorders the cfg's queue_index, which tests point away from the env index.
176
+ export function writeIndex(lines: string[], why?: { removed?: "close" | "cancel" | "migrate" }, file = indexPath()): void {
177
+ const index = file;
178
+ const newSet = new Set(
179
+ lines.filter(l => l.trim()).map(l => path.resolve(expandHome(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").trim()))),
180
+ );
181
+ const gone = readIndex(index).filter(p => !newSet.has(p));
182
+ if (gone.length && !why?.removed)
183
+ throw new Error(
184
+ `writeIndex: ${gone.join(", ")} would leave the index; only a close, cancel or migrate removes a plan (why: { removed: "close" | "cancel" | "migrate" })`,
185
+ );
186
+ const tmp = `${index}.tmp`;
187
+ writeFileSync(tmp, lines.length ? `${lines.join("\n")}\n` : "");
188
+ renameSync(tmp, index);
189
+ chmodSync(index, 0o444);
190
+ }
191
+
192
+ // Doctor's enforcement half of the same plan: the live index must sit at 0444 between writes, so
193
+ // no program — not just an agent tool call — can rewrite it. Returns the mode it had to fix.
194
+ export function enforceReadOnlyIndex(index = indexPath()): string | null {
195
+ try {
196
+ const mode = statSync(index).mode & 0o777;
197
+ if (mode === 0o444) return null;
198
+ chmodSync(index, 0o444);
199
+ return `0${mode.toString(8)}`;
200
+ } catch {
201
+ return null;
202
+ }
203
+ }
204
+
103
205
  export function sections(text: string): Map<string, string> {
104
206
  const out = new Map<string, string>();
105
207
  const parts = text.split(/^## /m);
@@ -667,6 +769,9 @@ function protectedPaths(): string[] {
667
769
  `${agent}/agents/`,
668
770
  `${agent}/AGENTS.md`,
669
771
  `${agent}/CANCELLED.md`,
772
+ // The plan index (plan 20261031_0911 P2): append-only and 0444 on disk. Agents add or
773
+ // reorder through `neurastream queue add` / `queue move`; only the owner writes directly.
774
+ indexPath(),
670
775
  `${stateDirPath()}/`,
671
776
  `${agent}/config.yml`,
672
777
  // The user's neurastream config file, even when agent_dir points elsewhere: an agent that
@@ -947,6 +1052,12 @@ export function awaitingMerge(p: Plan): boolean {
947
1052
  return p.status === "complete" && (lastCloseResult(p.file) ?? "").startsWith("queue-close: AWAITING merge");
948
1053
  }
949
1054
 
1055
+ /** P5 (plan 20261031_0911): the plan's last queue-close attempt did not close it — a refusal or still awaiting merge ("already running" is another close in flight, not a failure). */
1056
+ export function lastCloseFailed(file: string): boolean {
1057
+ const last = lastCloseResult(file);
1058
+ return !!last && !last.startsWith("queue-close: CLOSED") && !last.startsWith("queue-close: already");
1059
+ }
1060
+
950
1061
  /**
951
1062
  * I-20261025-208: index order is priority, so an open plan must never sit above an open plan of
952
1063
  * this list it waits on. A "Waits on" target that is not an open plan of the list (complete,
@@ -985,6 +1096,14 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewA
985
1096
  const last = lastCloseResult(p.file);
986
1097
  probs.push({ where: p.file, problem: `says ${p.status} but is still indexed; auto-close runs at every prompt, every 15 min and after a push${last ? ` (last: ${last.replace(/^queue-close: /, "")})` : ""}` });
987
1098
  }
1099
+ // P5 (plan 20261031_0911): a landed open plan whose auto-close failed locks the queue — the
1100
+ // spawn gate and the stop gate refuse everything that does not name it until it closes.
1101
+ if (p.status === "open" && autoCloseCandidate(p) && lastCloseFailed(p.file))
1102
+ probs.push({ where: p.file, problem: `landed but not closed: ${path.basename(p.file)} — ${(lastCloseResult(p.file) ?? "").replace(/^queue-close: /, "")}` });
1103
+ // P5: a done check that rides `merge-base --is-ancestor` re-does the landing check the
1104
+ // closer already owns, squash-aware — and misses squashes.
1105
+ if (p.doneCheck?.includes("merge-base --is-ancestor"))
1106
+ probs.push({ where: p.file, problem: "done check runs git merge-base --is-ancestor — queue-close checks landing itself, squash-aware; drop it" });
988
1107
  for (const c of cancelledMatches(p)) probs.push({ where: p.file, problem: cancelledProblem(p, c) });
989
1108
  // A plan file must live in a main checkout, never in a linked worktree.
990
1109
  const g = gitTop(p.file);
@@ -4,9 +4,13 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import type { Config } from "./config.ts";
6
6
  import { applyQueueEnv } from "./queue/env.ts";
7
- import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, INDEX, prependFinished, sha, STATE_DIR } from "./queue/lib.ts";
7
+ import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, gitOut as git, INDEX, landed, prependFinished, sha, STATE_DIR, writeIndex } from "./queue/lib.ts";
8
8
  import { fixedIncident } from "./incidents.ts";
9
9
 
10
+ // P4 (plan 20261031_0911): the landing check lives in queue/lib.ts (queueProblems' landed lock
11
+ // shares it, and lib cannot import this closer back); re-exported here per the plan.
12
+ export { landed };
13
+
10
14
  export function queueClose(args: string[], cfg: Config): number {
11
15
  applyQueueEnv(cfg);
12
16
  const ARCHIVE_DAYS = cfg.queue.archive_days;
@@ -24,43 +28,6 @@ export function queueClose(args: string[], cfg: Config): number {
24
28
  result(`queue-close: REFUSED: ${msg}`);
25
29
  process.exit(1);
26
30
  }
27
- function git(cwd: string, ...gargs: string[]): { ok: boolean; out: string } {
28
- const r = spawnSync("git", ["-C", cwd, ...gargs], { encoding: "utf8" });
29
- return { ok: r.status === 0, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
30
- }
31
- // Squash or rebase merges put a new commit on base, so the branch tip is never an ancestor of it.
32
- // The branch counts as landed when (a) a commit on base carries the same combined patch as the
33
- // whole branch, (b) every file the branch changed is identical on base, or (c) merging the branch
34
- // into some first-parent commit of base since the fork point changes nothing (the release squash
35
- // that shipped it; later edits on base would otherwise conflict).
36
- function squashMerged(repo: string, ref: string, base: string): boolean {
37
- const mb = git(repo, "merge-base", ref, base);
38
- if (!mb.ok) return false;
39
- const probe = git(repo, "commit-tree", `${ref}^{tree}`, "-p", mb.out, "-m", "queue-close squash probe");
40
- if (probe.ok && git(repo, "cherry", base, probe.out).out.startsWith("-")) return true;
41
- const files = git(repo, "diff", "--name-only", mb.out, ref);
42
- if (!files.ok || !files.out) return false;
43
- if (git(repo, "diff", "--quiet", ref, base, "--", ...files.out.split("\n")).ok) return true;
44
- const since = git(repo, "rev-list", "--first-parent", "--max-count=200", `${mb.out}..${base}`);
45
- return since.ok && !!since.out && since.out.split("\n").some(s => contains(repo, s, ref));
46
- }
47
- // True when commit `into` already holds everything in `from`: a clean merge of `from` into it
48
- // yields exactly its own tree.
49
- function contains(repo: string, into: string, from: string): boolean {
50
- const m = git(repo, "merge-tree", "--write-tree", into, from);
51
- return m.ok && m.out.split("\n")[0] === git(repo, "rev-parse", `${into}^{tree}`).out;
52
- }
53
- // (d) Stacked branches squashed together with later edits conflict in (c). The plan then names
54
- // the release: "Landed: <commit on base> from <pre-squash commit>". Verified, never trusted: the
55
- // first must be on base, the branch tip must be in the second's history, and the first must
56
- // already contain the second.
57
- function declaredLanded(repo: string, ref: string, base: string, text: string): boolean {
58
- const m = text.match(/^(?:- )?Landed: ([0-9a-f]{7,40}) from ([0-9a-f]{7,40})\s*$/m);
59
- if (!m || !m[1] || !m[2]) return false;
60
- return git(repo, "merge-base", "--is-ancestor", m[1], base).ok &&
61
- git(repo, "merge-base", "--is-ancestor", ref, m[2]).ok &&
62
- contains(repo, m[1], m[2]);
63
- }
64
31
  // A clone of a clone judges "landed" against the middle copy's default branch, which can be
65
32
  // stale. Follow local-path origins (at most 3 hops) to the upstream repo and fetch its default
66
33
  // branch: that commit is the base. No local origin: the existing base, unchanged.
@@ -82,8 +49,11 @@ export function queueClose(args: string[], cfg: Config): number {
82
49
  }
83
50
  const today = new Date().toISOString().slice(0, 10);
84
51
 
85
- const arg = args[0];
86
- if (!arg) die("usage: queue-close <plan file>");
52
+ // --auto (plan 20261031_0911 P4): autoClose starts the closer for an OPEN plan whose branch has
53
+ // landed; the done check decides, and a pass writes "Status: complete" here, nobody else.
54
+ const auto = args[0] === "--auto";
55
+ const arg = auto ? args[1] : args[0];
56
+ if (!arg) die("usage: queue-close [--auto] <plan file>");
87
57
  const file = path.resolve(arg);
88
58
  resultLog = closeLog(file);
89
59
 
@@ -103,7 +73,8 @@ export function queueClose(args: string[], cfg: Config): number {
103
73
  const plan = activePlans().find(p => p.file === file);
104
74
  if (!plan) die(`${file} is not listed in the main index ${INDEX}`);
105
75
  if (plan.errors.length) die(`plan does not match the template: ${plan.errors.join("; ")}`);
106
- if (plan.status !== "complete" && plan.status !== "cancelled") die(`plan says "Status: ${plan.status}", not complete or cancelled`);
76
+ if (plan.status !== "complete" && plan.status !== "cancelled" && !(auto && plan.status === "open"))
77
+ die(`plan says "Status: ${plan.status}", not complete or cancelled`);
107
78
  const cancelling = plan.status === "cancelled";
108
79
  if (plan.worktree && (plan.file === plan.worktree || plan.file.startsWith(`${plan.worktree}/`))) {
109
80
  // The plan file may sit under the named worktree when that worktree IS the main checkout
@@ -138,11 +109,7 @@ export function queueClose(args: string[], cfg: Config): number {
138
109
  if (wtExists && !owned) console.log(`queue-close: worktree ${plan.worktree} kept: it is on ${wtEntry?.branch ?? (wtEntry ? "a detached HEAD" : "no branch of this repo")}`);
139
110
  const branch = plan.branch;
140
111
  const branchExists = !!branch && git(plan.repo, "rev-parse", "--verify", "-q", `refs/heads/${branch}`).ok;
141
- const merged = branchExists && (
142
- git(plan.repo, "merge-base", "--is-ancestor", `refs/heads/${branch}`, base).ok ||
143
- squashMerged(plan.repo, `refs/heads/${branch}`, base) ||
144
- declaredLanded(plan.repo, `refs/heads/${branch}`, base, readFileSync(file, "utf8"))
145
- );
112
+ const merged = branchExists && landed(plan.repo, branch!, base, readFileSync(file, "utf8"));
146
113
 
147
114
  // A plan whose worktree is missing or kept is checked against the upstream base, never a foreign checkout.
148
115
  const detached = !!plan.worktree && !owned;
@@ -176,16 +143,27 @@ export function queueClose(args: string[], cfg: Config): number {
176
143
  }
177
144
  if (dc.status !== 0) {
178
145
  rmSync(doneCache, { force: true });
179
- const text = readFileSync(file, "utf8")
180
- .replace(/^Status:\s*complete\s*$/m, "Status: open")
181
- .replace(/^(## Progress[^\n]*\n(?:Status:[^\n]*\n)?)/m, `$1- ${today} queue-close: done check failed (exit ${dc.status ?? "timeout"}); reopened.\n`);
182
- writeFileSync(file, text);
183
- die(`done check failed (exit ${dc.status ?? "timeout"}); plan reopened (Status: open)`);
146
+ if (!auto) {
147
+ const text = readFileSync(file, "utf8")
148
+ .replace(/^Status:\s*complete\s*$/m, "Status: open")
149
+ .replace(/^(## Progress[^\n]*\n(?:Status:[^\n]*\n)?)/m, `$1- ${today} queue-close: done check failed (exit ${dc.status ?? "timeout"}); reopened.\n`);
150
+ writeFileSync(file, text);
151
+ die(`done check failed (exit ${dc.status ?? "timeout"}); plan reopened (Status: open)`);
152
+ }
153
+ // --auto keeps the open plan as it is — no reopen text; the refusal lands in the close
154
+ // log for the landed lock (P5) to report, and the cache is dropped so the next attempt
155
+ // reruns the check.
156
+ die(`done check failed (exit ${dc.status ?? "timeout"})`);
184
157
  }
185
158
  writeFileSync(doneCache, `${doneKey}\n`);
186
159
  }
187
160
  }
188
161
 
162
+ // --auto on an open plan: the done check just passed, so this close writes "Status: complete"
163
+ // itself and everything below proceeds as for any complete plan.
164
+ if (auto && plan.status === "open")
165
+ writeFileSync(file, readFileSync(file, "utf8").replace(/^Status:\s*open\s*$/m, "Status: complete"));
166
+
189
167
  if (branchExists && !merged && !cancelling) {
190
168
  result(`queue-close: AWAITING merge: done check green; branch ${branch} is not merged into ${base} yet, plan stays indexed until it lands`);
191
169
  return 4;
@@ -204,11 +182,11 @@ export function queueClose(args: string[], cfg: Config): number {
204
182
  const named = wtExists && owned ? list.find(w => w.path === real(plan.worktree!)) : undefined;
205
183
  // The plan's worktrees: the one it names plus any registered worktree on the plan's branch.
206
184
  const mine = list.filter(w => (plan.branch && w.branch === plan.branch) || w === named);
207
- const landed = !branchExists || merged;
185
+ const landedOk = !branchExists || merged;
208
186
  for (const w of mine) {
209
187
  if (w.main) console.log(`queue-close: worktree ${w.path} kept: it is the repo's main checkout`);
210
188
  else if (git(w.path, "status", "--porcelain").out) console.log(`queue-close: worktree ${w.path} kept: it has uncommitted changes`);
211
- else if (!landed) console.log(`queue-close: worktree ${w.path} kept: branch ${branch} is not merged`);
189
+ else if (!landedOk) console.log(`queue-close: worktree ${w.path} kept: branch ${branch} is not merged`);
212
190
  else {
213
191
  const rm = git(plan.repo, "worktree", "remove", w.path);
214
192
  if (!rm.ok || existsSync(w.path)) console.log(`queue-close: worktree ${w.path} kept: git worktree remove failed (${rm.out})`);
@@ -286,7 +264,7 @@ export function queueClose(args: string[], cfg: Config): number {
286
264
  // One index: the closed plan's line leaves the main index; there is no repo INDEX.md.
287
265
  const lines = readFileSync(INDEX, "utf8").split("\n").filter(l => l.trim());
288
266
  const keep = lines.filter(l => path.resolve(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").replace(/^~(?=\/)/, os.homedir())) !== file);
289
- writeFileSync(INDEX, keep.length ? `${keep.join("\n")}\n` : "");
267
+ writeIndex(keep, { removed: cancelling ? "cancel" : "close" });
290
268
  console.log(`queue-close: removed from ${INDEX} (${keep.length} plan(s) left)`);
291
269
  try {
292
270
  const sp = path.join(STATE_DIR, "spawns.json");
@@ -294,14 +272,26 @@ export function queueClose(args: string[], cfg: Config): number {
294
272
  delete s[file];
295
273
  writeFileSync(sp, JSON.stringify(s, null, 1));
296
274
  } catch {}
297
- // Incidents this plan fixes (plan P5): each INCIDENT <id> in a closing plan gets a fixed
298
- // record, so the guards stop pushing a bug whose fix just shipped. Cancelled plans did not
299
- // ship their fix — the owner records a dismissal instead. A refusal (unknown id, already
300
- // resolved) is logged into the close log and never fails the close.
275
+ // Incidents this plan fixes (plan P5): each INCIDENT <id> cited outside ## Progress gets a
276
+ // fixed record, so the guards stop pushing a bug whose fix just shipped. Progress is
277
+ // narrative, not fix work (I-20261031-349, P5b): an id Main only filed there ("needs a phase
278
+ // here") was never fixed by a phase — it stays open and the close logs it. Cancelled plans
279
+ // did not ship their fix — the owner records a dismissal instead. A refusal (unknown id,
280
+ // already resolved) is logged into the close log and never fails the close.
301
281
  if (!cancelling) {
282
+ // Cut ## Progress (until the next heading) before lifting ids: an id cited in the Goal or
283
+ // a phase counts whether or not the INCIDENT keyword prefixes it; an id whose only
284
+ // citation sits in Progress does not.
285
+ let inProgress = false;
286
+ const body = plan.text.split("\n").filter(l => {
287
+ if (l.startsWith("## ")) inProgress = l.trim() === "## Progress";
288
+ return !inProgress;
289
+ }).join("\n");
290
+ const ids = new Set([...body.matchAll(/\bI-\d{8}-\d+\b/g)].map(m => m[0]));
291
+ for (const id of new Set([...plan.text.matchAll(/\bINCIDENT\s+(I-\d{8}-\d+)\b/g)].map(m => m[1]!)))
292
+ if (!ids.has(id)) result(`queue-close: still open: ${id} (cited only in ## Progress)`);
302
293
  const recorded: string[] = [];
303
294
  // A plan may cite one incident several times; record it once so the second citation is not a refusal.
304
- const ids = new Set([...plan.text.matchAll(/\bINCIDENT\s+(I-\d{8}-\d+)\b/g)].map(m => m[1]!));
305
295
  for (const id of ids) {
306
296
  const why = fixedIncident(cfg, id, file);
307
297
  if (why) result(`queue-close: not recording fixed for ${id}: ${why}`);
@@ -1,8 +1,8 @@
1
- import { existsSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { existsSync, rmSync, statSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { Config } from "./config.ts";
4
4
  import { applyQueueEnv } from "./queue/env.ts";
5
- import { gitTop, readIndex } from "./queue/lib.ts";
5
+ import { gitTop, readIndex, writeIndex } from "./queue/lib.ts";
6
6
 
7
7
  // One index (20261024_1400_one_index): fold the old two-level layout into the main index. Every
8
8
  // repo directory the main index still lists has its INDEX.md plan lines moved into the main index
@@ -44,7 +44,7 @@ export function queueMigrate(args: string[], cfg: Config): number {
44
44
  rmSync(repoIndex);
45
45
  }
46
46
  const unique = [...new Set(kept)];
47
- writeFileSync(index, unique.length ? `${unique.join("\n")}\n` : "");
47
+ writeIndex(unique, { removed: "migrate" });
48
48
  console.log(`queue migrate: ${index} now lists ${unique.length} plan(s); folded ${folded} repo INDEX.md file(s)`);
49
49
  for (const p of unique) {
50
50
  const g = gitTop(p);