neurastream 0.1.28 → 0.2.1

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/README.md CHANGED
@@ -23,9 +23,9 @@ flowchart LR
23
23
 
24
24
  | Part | What it enforces |
25
25
  |---|---|
26
- | Queue (`queue-check`, `queue-close`, `queue-cancel`) | Every open plan is listed in an index and follows a template. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. A cancelled plan's unmerged work is saved under `refs/queue-archive/`. |
26
+ | Queue (`queue-check`, `queue-close`, `queue-cancel`) | Every open plan is a file in a main checkout, listed in the one main index (`paths.queue_index`, one absolute path per line — never repo directories) and follows a template; one plan = one worktree. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. Closing removes the plan's worktree when it is clean and its branch landed — a plain `git worktree remove`; a dirty, unmerged or unremovable worktree and the repo's main checkout are kept with the reason. Branches leave only via `git branch -d`, so a branch whose merge git cannot see stays. |
27
27
  | Blockers | Each plan's phase 0 lists what helpers may not do: push, touch a path, run a command, or write a text. The guard judges the command that runs and the files it changes, not words inside commit messages, quoted text or heredoc bodies: `git commit -m "... push ..."` is allowed, `git push` is refused. |
28
- | Guards | Helpers may only edit their plan's `## Progress`; they get a warning at call 90 and are stopped at call 100. Protected files need an owner unlock (a file the owner touches, valid 30 minutes). |
28
+ | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100. Protected files need an owner unlock (a file the owner touches, valid 30 minutes). |
29
29
  | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs 2. |
30
30
  | Scoring (`agent-score`) | Points only for work Main accepted by commit, times the phase difficulty. Ranked per dollar and per hour. |
31
31
  | Brief lint (`brief-lint`) | Refuses a helper brief that misses a required rule (acceptance, stop condition, no push, call budget). |
@@ -50,7 +50,7 @@ neurastream doctor
50
50
  neurastream uninstall --purge # the inverse: removes it all again
51
51
  ```
52
52
 
53
- `init` writes `~/.config/neurastream/config.yml` from the defaults in [docs/config.md](docs/config.md), plus an empty index, notes, the queue template, blocker wrappers, and the state directories. A second run changes nothing. `adapter install omp` links the extension (`~/.omp/agent/extensions` and `omp plugin link`). `doctor` exits 0 when the install matches the package. `uninstall` removes the installed bins, the plugin link, template-identical pins and the AGENTS.md block; `--purge` adds the config file and the agent-dir state. It prints the list first and refuses anything outside your HOME.
53
+ `init` writes `~/.config/neurastream/config.yml` from the defaults in [docs/config.md](docs/config.md), plus an empty index, notes, the queue template, blocker wrappers, and the state directories. A second run changes nothing. `adapter install omp` links the extension (`~/.omp/agent/extensions` and `omp plugin link`). `doctor` exits 0 when the install matches the package and flags a main index that still lists repo directories (the old two-level queue). `neurastream queue migrate` folds that old layout into the one main index: each repo line's `INDEX.md` plans move into the main index, the repo files are deleted; it is idempotent and reports plans that still live inside a linked worktree instead of moving them. `uninstall` removes the installed bins, the plugin link, template-identical pins and the AGENTS.md block; `--purge` adds the config file and the agent-dir state. It prints the list first and refuses anything outside your HOME.
54
54
 
55
55
  `init` also sets the subagent allow-list (`notes/subagents.md`, the `## Allowed` section). `neurastream init --allow a,b` adds those slugs on the first run and on later runs, and never removes one. Without `--allow`, a terminal run asks once: `Subagents allowed to spawn (comma-separated names, empty = none):`; a blank answer, or no terminal, leaves the list as it is. While the list is empty, init prints `no subagents allowed yet: neurastream agents allow <name>`. `neurastream agents list|allow|deny` changes it later. A slug must match `[a-z0-9-]+`; a bad one exits 2 and writes nothing.
56
56
 
@@ -136,14 +136,15 @@ Weekly loop: run `neurastream metrics report`, then propose ONE rule change to t
136
136
 
137
137
  Bugs in neurastream itself are found by code, written to a persistent list, and pushed on Main until each one has a plan or a recorded dismissal — not remembered. The list is `<paths.queue_state>/incidents.jsonl`; `neurastream incident list [--open] [--json]` reads it.
138
138
 
139
- Four sources feed it:
139
+ Five sources feed it:
140
140
 
141
141
  - Real time (at Main's prompt and after each Main bash result): a finished subagent the agent-ledger still shows RUNNING/WAITING past `incidents.contradiction_grace_min` (D1); a neurastream tool that crashed in a Main bash result (D2); the same guard block firing `incidents.block_repeat` times within one hour (D3); an owner message matching `metrics.correction_patterns` (D4). D2 and D4 run on every event; D1 and D3 read the session files and the guard logs at most once per `incidents.scan_interval_sec` (state: `incident-scan.json` in the queue state dir).
142
142
  - Daily: at the first main-start or Main prompt of a day, M1-M5 for the last 24 hours against the mean of the 7 days before; a metric worse by `incidents.daily_worse_pct` and above its `incidents.daily_floor` floor is an incident.
143
143
  - Weekly: when the metrics report is due, the code writes `<paths.notes>/metrics.md` itself and its worst ranked metric becomes an incident.
144
144
  - Main itself: `neurastream incident add "<summary>" --kind <k>`.
145
+ - A subagent's plan work: every new `## Progress` entry in a plan ends with a `Findings:` line (`Findings: none`, or one item per finding — bug, workaround, improvement, any repo — with `file:line` evidence, items separated by `;`). The plan-guard refuses and restores an entry without the line, and each item of an allowed edit becomes an incident (source `findings`, evidence = plan path + agent); the same text again dedupes into the open incident.
145
146
 
146
- While an incident is open (no plan, dismissal or fixed record), every Main prompt carries one `INCIDENT <id> [<source>/<kind>]: <summary>` line per open incident, Main's `task` spawns and bypass launches are refused unless the brief names a plan citing `INCIDENT <id>`, and Main cannot stop with an incident that has neither. The loop closes three ways: `neurastream incident plan <id> <plan.md>` (the plan must exist, be listed in its repo INDEX, cite `INCIDENT <id>`, and carry a fail-before phase — its regression test has to fail on the old code), `neurastream incident dismiss <id> --why "<text>"`, and `fixed` — written by the queue itself when it closes a plan that cites the incident. `neurastream metrics report` shows M6: incidents opened / planned / dismissed / fixed and the median hours from open to fixed.
147
+ While an incident is open (no plan, dismissal or fixed record), every Main prompt carries one `INCIDENT <id> [<source>/<kind>]: <summary>` line per open incident, Main's `task` spawns and bypass launches are refused unless the brief names a plan citing `INCIDENT <id>`, and Main cannot stop with an incident that has neither. The loop closes three ways: `neurastream incident plan <id> <plan.md>` (the plan must exist, be listed in the main index, cite `INCIDENT <id>`, and carry a fail-before phase — its regression test has to fail on the old code), `neurastream incident dismiss <id> --why "<text>"`, and `fixed` — written by the queue itself when it closes a plan that cites the incident. `neurastream metrics report` shows M6: incidents opened / planned / dismissed / fixed and the median hours from open to fixed.
147
148
 
148
149
  ## Changing a script
149
150
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.28",
3
+ "version": "0.2.1",
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": ["ai-agents", "coding-agents", "orchestration", "guardrails", "omp", "bun", "cli"],
6
6
  "homepage": "https://github.com/umiddey/neurastream#readme",
@@ -1,14 +1,17 @@
1
1
  // Reports hand-edited or missing live files the omp adapter installs, the managed block in
2
2
  // the owner's AGENTS.md, and a stale registry version. Offline `npm view` is a warning, not a failure.
3
- // Notes, INDEX, queue state and config are user state: not checked.
3
+ // Notes, queue state and config are user state: not checked. The one exception is the layout of the
4
+ // main index itself: repo-directory lines are the old two-level queue and get flagged until
5
+ // `neurastream queue migrate` folds them.
4
6
 
5
7
  import { spawnSync } from "node:child_process";
6
- import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
8
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
7
9
  import { homedir } from "node:os";
8
10
  import { dirname, join, relative, resolve } from "node:path";
9
11
  import { fileURLToPath } from "node:url";
10
12
  import { blockState, renderBlock } from "../../core/agents-md.ts";
11
13
  import { loadConfig } from "../../core/config.ts";
14
+ import { readIndex } from "../../core/queue/lib.ts";
12
15
 
13
16
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
14
17
 
@@ -175,6 +178,20 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
175
178
  const agents = liveAgentsMd(home);
176
179
  const text = existsSync(agents) ? readFileSync(agents, "utf8") : "";
177
180
  const cfg = loadConfig({ home, env });
181
+ // One index (20261024_1400_one_index): repo-directory lines in the main index are the old
182
+ // two-level queue; the plans they hold are invisible to queue-check until migrate folds them.
183
+ const idx = cfg.paths.queue_index;
184
+ const repoDirs = existsSync(idx)
185
+ ? readIndex(idx).filter(l => {
186
+ try {
187
+ return statSync(l).isDirectory();
188
+ } catch {
189
+ return false;
190
+ }
191
+ })
192
+ : [];
193
+ if (repoDirs.length)
194
+ problems.push(`${idx} still lists ${repoDirs.length} repo director${repoDirs.length === 1 ? "y" : "ies"} (${repoDirs.join(", ")}); run neurastream queue migrate`);
178
195
  const state = blockState(text, renderBlock(cfg));
179
196
  if (state === "ok") ok.push(`${agents} neurastream block`);
180
197
  else problems.push(`${state}: ${agents} neurastream block`);
@@ -8,6 +8,7 @@ import { PORTED, runMain, runPorted } from "./commands.ts";
8
8
  import { runMetrics } from "./metrics.ts";
9
9
  import { runIncident } from "./incident.ts";
10
10
  import { runUninstall } from "../core/uninstall.ts";
11
+ import { queueMigrate } from "../core/queue-migrate.ts";
11
12
  import { allowedAgents, subagentsPath } from "../core/queue/lib.ts";
12
13
  import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
13
14
 
@@ -50,6 +51,7 @@ export function helpText(): string {
50
51
  " template-identical pins and the AGENTS.md block (--purge adds",
51
52
  " config + agent-dir state); prints the list, refuses outside HOME",
52
53
  " neurastream doctor report hand-edited live files and a stale install",
54
+ " neurastream queue migrate fold the old repo INDEX.md files into the one main index",
53
55
  " neurastream config [--json] print the merged config (defaults + file + env)",
54
56
  " neurastream guard <event> --json",
55
57
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
@@ -89,6 +91,14 @@ export async function run(cmd: string, args: string[]): Promise<number> {
89
91
  }
90
92
  if (cmd === "doctor") return runDoctor();
91
93
  if (cmd === "uninstall") return runUninstall(args);
94
+ if (cmd === "queue" && args[0] === "migrate") {
95
+ try {
96
+ return queueMigrate(args.slice(1), loadConfig());
97
+ } catch (err) {
98
+ console.error(err instanceof ConfigError ? err.message : String(err));
99
+ return 1;
100
+ }
101
+ }
92
102
  if (cmd === "guard") {
93
103
  return runGuard(args[0] ?? "");
94
104
  }
@@ -22,7 +22,7 @@ import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from
22
22
  import path from "node:path";
23
23
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
24
24
  import type { Config } from "./config.ts";
25
- import { openIncidents, type IncidentView } from "./incidents.ts";
25
+ import { addIncident, openIncidents, type IncidentView } from "./incidents.ts";
26
26
  import * as q from "./queue/lib.ts";
27
27
  import type { Plan } from "./queue/lib.ts";
28
28
 
@@ -201,7 +201,7 @@ export function planGate(text: string, label: string): [string | null, string[]]
201
201
  const named = plans.filter(p => text.includes(p.file));
202
202
  if (!named.length)
203
203
  return [
204
- `${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in <repo>/INDEX.md and the repo in ${q.INDEX}.`,
204
+ `${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in ${q.INDEX}.`,
205
205
  [],
206
206
  ];
207
207
  if (RESEARCH_ASK.test(text) && PLAN_WRITE.test(text))
@@ -296,7 +296,7 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
296
296
  if (!plans.length || !paths.length) return null;
297
297
  for (const p of writes) {
298
298
  if (!q.isOrchestrationPath(p, plans)) continue;
299
- if (!q.planAt(p, plans)) return `${p} belongs to Main (repo index / blocker script); read it, never change it. Report instead.`;
299
+ if (!q.planAt(p, plans)) return `${p} belongs to Main (main index / blocker script); read it, never change it. Report instead.`;
300
300
  if (e.tool !== "write" && e.tool !== "edit")
301
301
  return `${p} is a plan file: change its "## Progress" section only with the edit or write tool.`;
302
302
  }
@@ -325,7 +325,7 @@ function editWindow(e: ToolEvent, input: Record<string, unknown>, cfg: Config):
325
325
  return deny(
326
326
  `main-guard: Main already changed project files ${w.used.length} times in this ${cfg.guards.main_window_min}-minute window ` +
327
327
  `(owner limit ${cfg.guards.main_edit_limit}; resets in ${mins} min). Main writes plans, not code: put the work in a plan ` +
328
- `(listed in <repo>/INDEX.md, phase-0 blockers first) and spawn an implementer. Changes so far: ${w.used.join(", ")}`,
328
+ `(listed in ${q.INDEX}, phase-0 blockers first) and spawn an implementer. Changes so far: ${w.used.join(", ")}`,
329
329
  );
330
330
  }
331
331
  if (!w.used.length) w.windowStart = now;
@@ -380,7 +380,7 @@ function incidentSpawnProblem(label: string, brief: string, namedPlans: string[]
380
380
  log(cfg.paths.guard_log, `BLOCK ${label}: open incidents: ${ids}`);
381
381
  return (
382
382
  `open incident(s) ${ids} must be acted on before other work. Write a plan that contains "INCIDENT <id>" ` +
383
- `(listed in its repo INDEX.md) and record it: \`neurastream incident plan <id> <plan.md>\`, or dismiss the ` +
383
+ `(listed in ${q.INDEX}) and record it: \`neurastream incident plan <id> <plan.md>\`, or dismiss the ` +
384
384
  'incident: `neurastream incident dismiss <id> --why "<text>"`. Fix work goes through: name that plan in the brief.'
385
385
  );
386
386
  }
@@ -592,23 +592,24 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
592
592
  return {
593
593
  allow: true,
594
594
  reason: "",
595
- inject: `${summary}\n(main-guard: read ${q.INDEX} and the listed repo INDEX.md files are summarised above; work the open plans, close finished ones with queue-close.)${editLimit}${cancel}${incidentText}`,
595
+ inject: `${summary}\n(main-guard: read ${q.INDEX}; the listed plans are summarised above; work the open plans, close finished ones with queue-close.)${editLimit}${cancel}${incidentText}`,
596
596
  ...(continuation ? {} : { state: { callsSinceStop: 0, idleStops: 0 } }),
597
597
  };
598
598
  }
599
599
 
600
600
  // Lines only Main may write: the status, owner parking, owner cancellation, cancelled-list clearance.
601
+ const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Cancelled by owner:|False positive:)/;
602
+
601
603
  function mainOnlyLines(text: string): string {
602
- return text
603
- .split("\n")
604
- .filter(l => /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Cancelled by owner:|False positive:)/.test(l))
605
- .join("\n");
604
+ return text.split("\n").filter(l => MAIN_ONLY_LINE.test(l)).join("\n");
606
605
  }
607
606
 
608
607
  /**
609
608
  * plan-edit: after a subagent changed a plan, everything outside "## Progress" and every
610
- * Main-only line must be unchanged; `restore` hands back the untouched text for the caller to
611
- * write (the original restored the file itself before reporting).
609
+ * Main-only line must be unchanged, and every Progress entry the edit adds must carry a
610
+ * "Findings:" line (2026-10-24: a finding buried in a Progress note never became a plan);
611
+ * `restore` hands back the untouched text for the caller to write (the original restored the
612
+ * file itself before reporting).
612
613
  */
613
614
  export function checkPlanEdit(e: PlanEditEvent, cfg: Config): Decision {
614
615
  if (e.agent === "main") return checkMainPlan(e, cfg);
@@ -620,9 +621,71 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): Decision {
620
621
  restore: { path: e.path, text: e.before },
621
622
  };
622
623
  }
624
+ const missing = newProgressEntries(e.before, e.after).filter(b => !findingsValue(b));
625
+ if (missing.length) {
626
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (no Findings line)`);
627
+ return {
628
+ allow: false,
629
+ reason: `plan-guard: ${missing.length === 1 ? "your new entry in" : `${missing.length} of your new entries in`} ${e.path} ${missing.length === 1 ? "has" : "have"} no "Findings:" line. End every new "## Progress" entry with "Findings: none", or "Findings: <one item per finding (bug, workaround, improvement — any repo), each with file:line evidence>", items separated by ";". The file was restored.`,
630
+ restore: { path: e.path, text: e.before },
631
+ };
632
+ }
633
+ recordFindings(e, cfg);
623
634
  return ALLOW;
624
635
  }
625
636
 
637
+ /**
638
+ * Each finding item of an allowed subagent edit becomes an incident (source "findings", kind
639
+ * "agent-finding", evidence = plan path + agent; the default fingerprint dedupes the same item
640
+ * text). A store failure is logged and swallowed: it must not break the verified edit.
641
+ */
642
+ function recordFindings(e: PlanEditEvent, cfg: Config): void {
643
+ try {
644
+ const evidence = `${e.path} (${e.agent})`;
645
+ for (const block of newProgressEntries(e.before, e.after)) {
646
+ const value = findingsValue(block);
647
+ if (!value || /^none\.?$/i.test(value)) continue;
648
+ for (const item of value.split(";")) {
649
+ if (item.trim()) addIncident(cfg, { source: "findings", kind: "agent-finding", summary: item.trim(), evidence });
650
+ }
651
+ }
652
+ } catch (err) {
653
+ log(cfg.paths.plan_guard_log, `findings: cannot record incidents for ${e.path}: ${err}`);
654
+ }
655
+ }
656
+
657
+ /** One "## Progress" entry: its "- " line plus indented continuation lines (trimProgressBody's entry rule). */
658
+ function progressEntries(text: string): string[] {
659
+ const blocks: string[] = [];
660
+ const lines = q.progressBody(text).split("\n");
661
+ for (let i = 0; i < lines.length; i++) {
662
+ const head = lines[i];
663
+ if (head === undefined || !/^- /.test(head) || MAIN_ONLY_LINE.test(head)) continue;
664
+ const block = [head];
665
+ while (i + 1 < lines.length) {
666
+ const cont = lines[i + 1];
667
+ if (cont === undefined || !/^[ \t]/.test(cont)) break;
668
+ block.push(cont);
669
+ i++;
670
+ }
671
+ blocks.push(block.join("\n"));
672
+ }
673
+ return blocks;
674
+ }
675
+
676
+ /** Entries an edit adds or rewrites: blocks whose text was not in the Progress section before. */
677
+ function newProgressEntries(before: string, after: string): string[] {
678
+ const old = new Set(progressEntries(before));
679
+ return progressEntries(after).filter(b => !old.has(b));
680
+ }
681
+
682
+ /** The value after "Findings:" in an entry, or null when the entry has no Findings line with content. */
683
+ function findingsValue(block: string): string | null {
684
+ const line = block.split("\n").find(l => l.includes("Findings:"));
685
+ if (!line) return null;
686
+ return line.slice(line.indexOf("Findings:") + "Findings:".length).trim() || null;
687
+ }
688
+
626
689
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
627
690
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
628
691
  function checkMainPlan(e: PlanEditEvent, cfg: Config): Decision {
@@ -5,7 +5,8 @@
5
5
  // refuse spawns and the stop (src/core/guards.ts), so a found bug is deterministically pushed,
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
- // opens a new incident. Sources: realtime (detectors), daily, weekly, main (`incident add`).
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
10
 
10
11
  import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
11
12
  import { dirname, join, resolve } from "node:path";
@@ -13,7 +14,7 @@ import { nowSec, strftime } from "./clock.ts";
13
14
  import type { Config } from "./config.ts";
14
15
  import * as q from "./queue/lib.ts";
15
16
 
16
- export type IncidentSource = "realtime" | "daily" | "weekly" | "main";
17
+ export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings";
17
18
 
18
19
  export interface IncidentRec {
19
20
  id: string;
@@ -79,7 +80,7 @@ function parseLine(line: string): IncidentRec | ResolutionRec | null {
79
80
  if (rec.type !== undefined) return null;
80
81
  if (typeof rec.fingerprint !== "string" || typeof rec.kind !== "string" || typeof rec.summary !== "string" || typeof rec.ts !== "number")
81
82
  return null;
82
- const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" ? rec.source : "main";
83
+ const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" ? rec.source : "main";
83
84
  return {
84
85
  id: rec.id,
85
86
  fingerprint: rec.fingerprint,
@@ -169,20 +170,8 @@ export function addIncident(cfg: Config, input: IncidentInput, now = nowSec()):
169
170
  }
170
171
 
171
172
  /**
172
- * The repo a plan belongs to: the nearest directory from the plan's folder upward that holds the
173
- * repo INDEX.md. Plans live at any depth under the repo (docs/plans/immediate/…), so a fixed
174
- * number of dirname steps lands short of the root.
175
- */
176
- function repoForPlan(abs: string): string | null {
177
- for (let dir = dirname(abs); ; dir = dirname(dir)) {
178
- if (existsSync(join(dir, q.REPO_INDEX))) return dir;
179
- if (dirname(dir) === dir) return null;
180
- }
181
- }
182
-
183
- /**
184
- * Records the plan that fixes an incident: refused unless the file exists, is listed in its repo
185
- * INDEX.md, and contains `INCIDENT <id>` (the spawn gates look for that text). Returns the
173
+ * Records the plan that fixes an incident: refused unless the file exists, is listed in the main
174
+ * index, and contains `INCIDENT <id>` (the spawn gates look for that text). Returns the
186
175
  * refusal reason, or null when recorded.
187
176
  */
188
177
  export function planIncident(cfg: Config, id: string, planPath: string): string | null {
@@ -193,9 +182,7 @@ export function planIncident(cfg: Config, id: string, planPath: string): string
193
182
  if (res) return `incident ${id} already has a ${res.type} record`;
194
183
  const abs = resolve(q.expandHome(planPath));
195
184
  if (!existsSync(abs)) return `plan file not found: ${abs}`;
196
- const repo = repoForPlan(abs);
197
- if (!repo) return `${abs} is not under a directory holding ${q.REPO_INDEX}`;
198
- if (!q.readRepoIndex(repo).includes(abs)) return `${abs} is not listed in ${join(repo, q.REPO_INDEX)}`;
185
+ if (!q.readIndex(cfg.paths.queue_index).includes(abs)) return `${abs} is not listed in ${cfg.paths.queue_index}`;
199
186
  let text: string;
200
187
  try {
201
188
  text = readFileSync(abs, "utf8");
@@ -1,4 +1,4 @@
1
- // Queue model: main index, repo INDEX.md, plan shape (templates/queue/TEMPLATE.md).
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
4
  import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
@@ -24,7 +24,6 @@ export function stateDirPath(): string {
24
24
  export let INDEX = indexPath();
25
25
  export let BLOCKERS_DIR = blockersDirPath();
26
26
  export let STATE_DIR = stateDirPath();
27
- export const REPO_INDEX = "INDEX.md";
28
27
  export const BACKGROUND_MAX_LINES = 40;
29
28
  export const SUB_WARN_CALLS = 90;
30
29
  export const SUB_MAX_CALLS = 100;
@@ -74,12 +73,9 @@ function indexLines(file: string): string[] | null {
74
73
  .filter(Boolean);
75
74
  }
76
75
 
77
- export function readIndex(file = indexPath()): string[] {
78
- return [...new Set((indexLines(file) ?? []).map(l => path.resolve(expandHome(l))))];
79
- }
80
-
81
- export function readRepoIndex(repo: string): string[] {
82
- return [...new Set((indexLines(path.join(repo, REPO_INDEX)) ?? []).map(l => path.resolve(repo, expandHome(l))))];
76
+ // Relative lines resolve against `base` (default: the cwd); a repo INDEX.md passes its repo dir.
77
+ export function readIndex(file = indexPath(), base = process.cwd()): string[] {
78
+ return [...new Set((indexLines(file) ?? []).map(l => path.resolve(base, expandHome(l))))];
83
79
  }
84
80
 
85
81
  export function sections(text: string): Map<string, string> {
@@ -183,7 +179,7 @@ function headerField(text: string, name: string): string | null {
183
179
 
184
180
  export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath()): Plan {
185
181
  const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, priorityId: null };
186
- if (text === null) return { ...empty, errors: ["plan file listed in INDEX.md does not exist"] };
182
+ if (text === null) return { ...empty, errors: ["plan file listed in the index does not exist"] };
187
183
  const errors: string[] = [];
188
184
  const secs = sections(text);
189
185
  for (const s of REQUIRED) {
@@ -232,23 +228,30 @@ export function parsePlan(repo: string, file: string, text: string | null, block
232
228
  };
233
229
  }
234
230
 
235
- export function readPlans(repo: string, blockersDir = blockersDirPath()): Plan[] {
236
- return readRepoIndex(repo).map(file => {
231
+ /** A plan's repo: the main checkout holding the plan file; a linked worktree resolves to its main repo. */
232
+ export function planRepo(file: string): string {
233
+ return repoRoot(file) ?? path.dirname(file);
234
+ }
235
+
236
+ export function readPlans(files: string[], blockersDir = blockersDirPath()): Plan[] {
237
+ return files.map(file => {
237
238
  let text: string | null = null;
238
239
  try {
239
240
  text = readFileSync(file, "utf8");
240
241
  } catch {}
241
- return parsePlan(repo, file, text, blockersDir);
242
+ return parsePlan(planRepo(file), file, text, blockersDir);
242
243
  });
243
244
  }
244
245
 
245
246
  export function activePlans(index = indexPath(), blockersDir = blockersDirPath()): Plan[] {
246
- return readIndex(index).flatMap(r => readPlans(r, blockersDir));
247
+ return readPlans(readIndex(index), blockersDir);
247
248
  }
248
249
 
249
250
  /** Owner holds: one line per plan with a WAITING on owner line. The only real holds; the summary, the rollover context and the handoff all read them here. */
250
251
  export function ownerHolds(index = INDEX): string[] {
251
- return readIndex(index).flatMap(r => readPlans(r)).filter(p => p.waiting).map(p => `${p.file}: WAITING on owner: ${p.waitingLine ?? ""}`);
252
+ return activePlans(index)
253
+ .filter(p => p.waiting)
254
+ .map(p => `${p.file}: WAITING on owner: ${p.waitingLine ?? ""}`);
252
255
  }
253
256
 
254
257
  export function gitTop(p: string): { top: string; repo: string } | null {
@@ -295,7 +298,7 @@ export function planAt(p: string, plans: Plan[]): Plan | null {
295
298
  }
296
299
 
297
300
  export function isOrchestrationPath(p: string, plans: Plan[] = activePlans()): boolean {
298
- if (path.basename(p) === REPO_INDEX && existsSync(path.join(path.dirname(p), ".git"))) return true;
301
+ if (p === INDEX || p === indexPath()) return true;
299
302
  if (planAt(p, plans)) return true;
300
303
  return plans.some(pl => pl.blockers.some(b => b.script === p));
301
304
  }
@@ -689,7 +692,7 @@ export function cancelledProblem(plan: Plan, c: CancelledEntry): string {
689
692
  const what = c.name.startsWith("ban-")
690
693
  ? `work the owner said NEVER to do: ${c.name} (${c.date}, owner: ${c.owner}; list ${c.list})`
691
694
  : `a plan the owner CANCELLED: ${c.name} (${c.date}, owner: ${c.owner}; archived under ${path.dirname(plan.file)}/archive/)`;
692
- return `resembles ${what}. Check it before going on. Same work: drop this plan (remove it from ${REPO_INDEX}) and don't do it. Different work: add the line "False positive: ${c.name} — <why it differs>" to this plan.`;
695
+ return `resembles ${what}. Check it before going on. Same work: drop this plan (remove it from ${INDEX}) and don't do it. Different work: add the line "False positive: ${c.name} — <why it differs>" to this plan.`;
693
696
  }
694
697
 
695
698
  export const CANCEL_WORDS =
@@ -738,32 +741,35 @@ export interface QueueProblem {
738
741
  export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR): QueueProblem[] {
739
742
  const probs: QueueProblem[] = [];
740
743
  if (!existsSync(index)) probs.push({ where: index, problem: "main index missing: create it (empty = no open work)" });
741
- for (const repo of readIndex(index)) {
742
- if (!existsSync(repo)) {
743
- probs.push({ where: repo, problem: "indexed repo does not exist: remove the line" });
744
- continue;
745
- }
746
- const plans = readPlans(repo, blockersDir);
747
- if (!plans.length) probs.push({ where: repo, problem: `indexed but ${REPO_INDEX} lists no plan: remove the repo from ${index}` });
748
- for (const p of plans) {
749
- for (const e of p.errors) probs.push({ where: p.file, problem: e });
750
- if ((p.status === "complete" || p.status === "cancelled") && !awaitingMerge(p)) {
751
- const last = lastCloseResult(p.file);
752
- 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: /, "")})` : ""}` });
753
- }
754
- for (const c of cancelledMatches(p)) probs.push({ where: p.file, problem: cancelledProblem(p, c) });
744
+ const byWorktree = new Map<string, Plan[]>();
745
+ for (const p of readPlans(readIndex(index), blockersDir)) {
746
+ for (const e of p.errors) probs.push({ where: p.file, problem: e });
747
+ if ((p.status === "complete" || p.status === "cancelled") && !awaitingMerge(p)) {
748
+ const last = lastCloseResult(p.file);
749
+ 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: /, "")})` : ""}` });
755
750
  }
751
+ for (const c of cancelledMatches(p)) probs.push({ where: p.file, problem: cancelledProblem(p, c) });
752
+ // A plan file must live in a main checkout, never in a linked worktree.
753
+ const g = gitTop(p.file);
754
+ if (g && g.top !== g.repo)
755
+ probs.push({ where: p.file, problem: `plan file lives in the linked worktree ${g.top}; move it to the main checkout ${g.repo}` });
756
+ // One plan = one worktree: two open plans naming the same worktree is a splitting bug.
757
+ if (p.status === "open" && p.worktree) byWorktree.set(p.worktree, [...(byWorktree.get(p.worktree) ?? []), p]);
756
758
  }
759
+ for (const [wt, ps] of byWorktree)
760
+ if (ps.length > 1)
761
+ probs.push({ where: wt, problem: `${ps.length} open plans name this worktree (${ps.map(p => p.file).join(", ")}); one plan = one worktree` });
757
762
  return probs;
758
763
  }
759
764
 
760
765
  export function queueSummary(index = INDEX): string {
761
- const repos = readIndex(index);
762
- const lines = [`Queue (${index}): ${repos.length ? `${repos.length} repo(s)` : "empty, no open work"}`];
766
+ const plans = activePlans(index);
767
+ const repos = [...new Set(plans.map(p => p.repo))];
768
+ const lines = [`Queue (${index}): ${plans.length ? `${plans.length} plan(s) in ${repos.length} repo(s)` : "empty, no open work"}`];
763
769
  for (const repo of repos) {
764
770
  const nCancelled = readCancelled(repo).length;
765
771
  lines.push(`- ${repo}${nCancelled ? ` (${nCancelled} cancelled)` : ""}`);
766
- for (const p of readPlans(repo)) {
772
+ for (const p of plans.filter(pl => pl.repo === repo)) {
767
773
  const status = awaitingMerge(p) ? "complete, awaiting merge" : (p.status ?? "INVALID");
768
774
  const hold = p.waiting ? `WAITING on owner: ${(p.waitingLine ?? "").slice(0, 80)}` : "";
769
775
  const flags = [status, hold, p.priorityId ?? ""].filter(Boolean).join(", ");
@@ -1,45 +1,16 @@
1
- import { execFileSync } from "node:child_process";
2
- import { readdirSync } from "node:fs";
3
- import path from "node:path";
4
1
  import type { Config } from "./config.ts";
5
2
  import { applyQueueEnv } from "./queue/env.ts";
6
- import { activePlans, queueProblems, queueSummary, readIndex, readPlans, REPO_INDEX } from "./queue/lib.ts";
3
+ import { activePlans, queueProblems, queueSummary } from "./queue/lib.ts";
7
4
 
5
+ // One index (20261024_1400_one_index): the main index lists plan files directly, so there are no
6
+ // repo INDEX.md files to git-check and no work_roots scan; the queue problems carry the
7
+ // worktree-placement and one-plan-one-worktree rules instead.
8
8
  export function queueCheck(args: string[], cfg: Config): number {
9
9
  applyQueueEnv(cfg);
10
10
  if (args.includes("--priority-ids")) {
11
11
  for (const p of activePlans()) if (p.priorityId && !p.waiting && p.status === "open") console.log(p.priorityId);
12
12
  return 0;
13
13
  }
14
- function git(repo: string, ...gargs: string[]): boolean {
15
- try {
16
- execFileSync("git", ["-C", repo, ...gargs], { stdio: "ignore" });
17
- return true;
18
- } catch {
19
- return false;
20
- }
21
- }
22
- const index = readIndex();
23
- const extra: string[] = [];
24
- for (const repo of index) {
25
- if (!git(repo, "rev-parse", "--git-dir")) continue;
26
- if (git(repo, "ls-files", "--error-unmatch", REPO_INDEX))
27
- extra.push(`${repo}: ${REPO_INDEX} is tracked by git; it never goes into git (git rm --cached ${REPO_INDEX})`);
28
- else if (!git(repo, "check-ignore", "-q", "--no-index", REPO_INDEX))
29
- extra.push(`${repo}: ${REPO_INDEX} is not git-ignored; add "/${REPO_INDEX}" to ${repo}/.git/info/exclude`);
30
- }
31
- for (const root of cfg.paths.work_roots) {
32
- let dirs: string[] = [];
33
- try {
34
- dirs = readdirSync(root);
35
- } catch {}
36
- for (const d of dirs) {
37
- const repo = path.join(root, d);
38
- if (!index.includes(repo) && readPlans(repo).length)
39
- extra.push(`${repo}: ${REPO_INDEX} lists plans but the repo is not in the main index (add it, or empty the repo index)`);
40
- }
41
- }
42
14
  console.log(queueSummary());
43
- if (extra.length) console.log(`More problems:\n${extra.map(e => ` - ${e}`).join("\n")}`);
44
- return queueProblems().length || extra.length ? 1 : 0;
15
+ return queueProblems().length ? 1 : 0;
45
16
  }
@@ -4,7 +4,7 @@ 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, INDEX, readIndex, readRepoIndex, REPO_INDEX, sha, STATE_DIR } from "./queue/lib.ts";
7
+ import { activePlans, cancelledFile, cancelledLine, closeLog, INDEX, readIndex, sha, STATE_DIR } from "./queue/lib.ts";
8
8
  import { fixedIncident } from "./incidents.ts";
9
9
 
10
10
  export function queueClose(args: string[], cfg: Config): number {
@@ -61,10 +61,6 @@ export function queueClose(args: string[], cfg: Config): number {
61
61
  git(repo, "merge-base", "--is-ancestor", ref, m[2]).ok &&
62
62
  contains(repo, m[1], m[2]);
63
63
  }
64
- function writeLines(file: string, lines: string[]) {
65
- if (lines.length) writeFileSync(file, `${lines.join("\n")}\n`);
66
- else rmSync(file, { force: true });
67
- }
68
64
  // A clone of a clone judges "landed" against the middle copy's default branch, which can be
69
65
  // stale. Follow local-path origins (at most 3 hops) to the upstream repo and fetch its default
70
66
  // branch: that commit is the base. No local origin: the existing base, unchanged.
@@ -105,22 +101,27 @@ export function queueClose(args: string[], cfg: Config): number {
105
101
  process.on("exit", () => rmSync(lock, { force: true }));
106
102
 
107
103
  const plan = activePlans().find(p => p.file === file);
108
- if (!plan) die(`${file} is not listed in any repo INDEX.md of a repo in ${INDEX}`);
104
+ if (!plan) die(`${file} is not listed in the main index ${INDEX}`);
109
105
  if (plan.errors.length) die(`plan does not match the template: ${plan.errors.join("; ")}`);
110
106
  if (plan.status !== "complete" && plan.status !== "cancelled") die(`plan says "Status: ${plan.status}", not complete or cancelled`);
111
107
  const cancelling = plan.status === "cancelled";
112
- if (plan.worktree && (plan.file === plan.worktree || plan.file.startsWith(`${plan.worktree}/`)))
113
- die("the indexed plan file lives inside its worktree; index the copy in the main checkout");
108
+ if (plan.worktree && (plan.file === plan.worktree || plan.file.startsWith(`${plan.worktree}/`))) {
109
+ // The plan file may sit under the named worktree when that worktree IS the main checkout
110
+ // (the main checkout is every plan's repo); only a linked worktree is refused.
111
+ let linked = true;
112
+ try { linked = realpathSync(plan.worktree) !== realpathSync(plan.repo); } catch {}
113
+ if (linked) die("the indexed plan file lives inside its worktree; index the copy in the main checkout");
114
+ }
114
115
 
115
116
  git(plan.repo, "fetch", "-q", "origin");
116
117
  const head = git(plan.repo, "symbolic-ref", "-q", "refs/remotes/origin/HEAD");
117
118
  const base = upstreamBase(plan.repo, head.ok ? head.out : "refs/remotes/origin/main");
118
119
  // git reports worktree paths through symlinks resolved (macOS: /tmp -> /private/tmp); match resolved paths on both sides.
119
120
  const real = (p: string): string => { try { return realpathSync(p); } catch { return path.resolve(p); } };
120
- const worktrees = (): { path: string; branch: string | null; head: string }[] => {
121
- const list: { path: string; branch: string | null; head: string }[] = [];
121
+ const worktrees = (): { path: string; branch: string | null; head: string; main: boolean }[] => {
122
+ const list: { path: string; branch: string | null; head: string; main: boolean }[] = [];
122
123
  for (const line of git(plan.repo, "worktree", "list", "--porcelain").out.split("\n")) {
123
- if (line.startsWith("worktree ")) list.push({ path: real(line.slice(9)), branch: null, head: "" });
124
+ if (line.startsWith("worktree ")) list.push({ path: real(line.slice(9)), branch: null, head: "", main: list.length === 0 });
124
125
  const cur = list.at(-1);
125
126
  if (!cur) continue;
126
127
  if (line.startsWith("HEAD ")) cur.head = line.slice(5);
@@ -156,8 +157,10 @@ export function queueClose(args: string[], cfg: Config): number {
156
157
  else {
157
158
  let scratch: string | undefined;
158
159
  if (detached) {
160
+ // A shared clone of the base, deliberately NOT a registered worktree: it never shows up
161
+ // in `git worktree list` and can be dropped with a plain delete when it stays clean.
159
162
  scratch = mkdtempSync(path.join(STATE_DIR, "done-base-"));
160
- const add = git(plan.repo, "worktree", "add", "--detach", scratch, base);
163
+ const add = git(plan.repo, "clone", "-q", "--shared", ".", scratch) && git(scratch, "checkout", "-q", "--detach", base);
161
164
  if (!add.ok) {
162
165
  rmSync(scratch, { recursive: true, force: true });
163
166
  die(`could not check out ${base} for the done check: ${add.out}`);
@@ -166,9 +169,10 @@ export function queueClose(args: string[], cfg: Config): number {
166
169
  console.log(`queue-close: done check in ${detached ? `${base} (temporary worktree)` : runIn}: ${plan.doneCheck}`);
167
170
  const dc = spawnSync("bash", ["-lc", plan.doneCheck!], { cwd: scratch ?? runIn, stdio: "inherit", timeout: 3600_000 });
168
171
  if (scratch) {
169
- git(plan.repo, "worktree", "remove", "--force", scratch);
170
- rmSync(scratch, { recursive: true, force: true });
171
- git(plan.repo, "worktree", "prune");
172
+ // Whatever the check left behind stays: a dirty scratch is kept for inspection, a clean
173
+ // one equals the base commit and is deleted outright.
174
+ if (git(scratch, "status", "--porcelain").out) console.log(`queue-close: kept the check scratch ${scratch}: the done check left changes in it`);
175
+ else rmSync(scratch, { recursive: true, force: true });
172
176
  }
173
177
  if (dc.status !== 0) {
174
178
  rmSync(doneCache, { force: true });
@@ -192,44 +196,34 @@ export function queueClose(args: string[], cfg: Config): number {
192
196
  const [ref, t] = line.split(" ");
193
197
  if (ref && Number(t) < cutoff) git(plan.repo, "update-ref", "-d", ref);
194
198
  }
195
- if (owned) {
196
- const stash = git(plan.worktree!, "stash", "create", `queue-close: uncommitted work of ${path.basename(file)}`);
197
- const saved = stash.ok ? stash.out : "";
198
- if (saved) {
199
- const ref = `refs/queue-archive/${path.basename(file, ".md")}-${today}`;
200
- if (!git(plan.repo, "update-ref", ref, saved).ok || !git(plan.repo, "stash", "show", "-p", ref).out)
201
- die(`could not save the worktree's uncommitted changes to ${ref}; nothing removed`);
202
- console.log(`queue-close: uncommitted changes saved as ${ref} (restore: git -C ${plan.repo} stash apply ${ref}; pruned after ${ARCHIVE_DAYS} days)`);
203
- }
204
- }
205
- if (branchExists && !merged) {
206
- const tip = git(plan.repo, "rev-parse", `refs/heads/${branch}`).out;
207
- const keep = git(plan.repo, "commit-tree", `${tip}^{tree}`, "-p", tip, "-m", `queue-close: branch ${branch} of cancelled ${path.basename(file)}`);
208
- const ref = `refs/queue-archive/${path.basename(file, ".md")}-${today}-branch`;
209
- if (!keep.ok || !git(plan.repo, "update-ref", ref, keep.out).ok) die(`could not save branch ${branch} to ${ref}; nothing removed`);
210
- console.log(`queue-close: branch ${branch} saved as ${ref} (restore: git -C ${plan.repo} branch ${branch} ${ref}^; pruned after ${ARCHIVE_DAYS} days)`);
211
- }
212
- if (owned) {
213
- let rm = git(plan.repo, "worktree", "remove", "--force", plan.worktree!);
214
- if (!rm.ok && existsSync(plan.worktree!)) {
215
- spawnSync("docker", ["run", "--rm", "-v", `${plan.worktree}:/w`, "alpine", "chown", "-R", `${os.userInfo().uid}:${os.userInfo().gid}`, "/w"], { stdio: "ignore" });
216
- rm = git(plan.repo, "worktree", "remove", "--force", plan.worktree!);
217
- if (!rm.ok && existsSync(plan.worktree!)) {
218
- rmSync(plan.worktree!, { recursive: true, force: true });
219
- git(plan.repo, "worktree", "prune");
220
- rm = { ok: !existsSync(plan.worktree!), out: rm.out };
221
- }
199
+ // One plan = one worktree (20261024_1400_one_index): a successful close removes the plan's
200
+ // worktree with a plain `git worktree remove`, only when it is clean and its branch landed.
201
+ // Dirty, unmerged, unremovable worktrees and main checkouts are kept and the reason printed.
202
+ // Nothing is ever forced: no --force, no rm -rf, no branch -D, no uncommitted work destroyed.
203
+ const list = worktrees();
204
+ const named = wtExists && owned ? list.find(w => w.path === real(plan.worktree!)) : undefined;
205
+ // The plan's worktrees: the one it names plus any registered worktree on the plan's branch.
206
+ const mine = list.filter(w => (plan.branch && w.branch === plan.branch) || w === named);
207
+ const landed = !branchExists || merged;
208
+ for (const w of mine) {
209
+ if (w.main) console.log(`queue-close: worktree ${w.path} kept: it is the repo's main checkout`);
210
+ 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`);
212
+ else {
213
+ const rm = git(plan.repo, "worktree", "remove", w.path);
214
+ if (!rm.ok || existsSync(w.path)) console.log(`queue-close: worktree ${w.path} kept: git worktree remove failed (${rm.out})`);
215
+ else console.log(`queue-close: worktree ${w.path} removed`);
222
216
  }
223
- if (!rm.ok) die(`could not remove worktree ${plan.worktree}: ${rm.out}`);
224
- console.log(`queue-close: worktree ${plan.worktree} removed`);
225
217
  }
226
218
  if (branchExists) {
227
219
  const holder = worktrees().find(w => w.branch === branch);
228
220
  if (holder) console.log(`queue-close: branch ${branch} kept: checked out in ${holder.path}`);
229
221
  else {
230
- const d = git(plan.repo, "branch", "-D", branch!);
231
- if (!d.ok) die(`could not delete branch ${branch}: ${d.out}`);
232
- console.log(`queue-close: branch ${branch} deleted`);
222
+ // git refuses -d when it cannot see the branch merged (a stale upstream hides the landing);
223
+ // the branch then stays instead of being deleted behind git's back.
224
+ const d = git(plan.repo, "branch", "-d", branch!);
225
+ if (!d.ok) console.log(`queue-close: branch ${branch} kept: git would not delete it (${d.out.split("\n")[0]})`);
226
+ else console.log(`queue-close: branch ${branch} deleted`);
233
227
  }
234
228
  }
235
229
 
@@ -284,20 +278,11 @@ export function queueClose(args: string[], cfg: Config): number {
284
278
  console.log(`queue-close: plan moved to ${dest}`);
285
279
  }
286
280
 
287
- const repoIndexFile = path.join(plan.repo, REPO_INDEX);
288
- const remaining = readRepoIndex(plan.repo).filter(p => p !== file);
289
- const rawLines = readFileSync(repoIndexFile, "utf8").split("\n").filter(l => l.trim());
290
- writeLines(
291
- repoIndexFile,
292
- rawLines.filter(l => path.resolve(plan.repo, l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "")) !== file),
293
- );
294
- console.log(`queue-close: removed from ${repoIndexFile}${remaining.length ? ` (${remaining.length} plan(s) left)` : " (now empty: deleted)"}`);
295
- if (!remaining.length) {
296
- const lines = readFileSync(INDEX, "utf8").split("\n").filter(l => l.trim());
297
- const keep = lines.filter(l => path.resolve(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").replace(/^~(?=\/)/, os.homedir())) !== plan.repo);
298
- writeFileSync(INDEX, keep.length ? `${keep.join("\n")}\n` : "");
299
- console.log(`queue-close: ${plan.repo} removed from ${INDEX} (${readIndex().length} repo(s) left)`);
300
- }
281
+ // One index: the closed plan's line leaves the main index; there is no repo INDEX.md.
282
+ const lines = readFileSync(INDEX, "utf8").split("\n").filter(l => l.trim());
283
+ const keep = lines.filter(l => path.resolve(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").replace(/^~(?=\/)/, os.homedir())) !== file);
284
+ writeFileSync(INDEX, keep.length ? `${keep.join("\n")}\n` : "");
285
+ console.log(`queue-close: removed from ${INDEX} (${keep.length} plan(s) left)`);
301
286
  try {
302
287
  const sp = path.join(STATE_DIR, "spawns.json");
303
288
  const s = JSON.parse(readFileSync(sp, "utf8"));
@@ -0,0 +1,54 @@
1
+ import { existsSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import type { Config } from "./config.ts";
4
+ import { applyQueueEnv } from "./queue/env.ts";
5
+ import { gitTop, readIndex } from "./queue/lib.ts";
6
+
7
+ // One index (20261024_1400_one_index): fold the old two-level layout into the main index. Every
8
+ // repo directory the main index still lists has its INDEX.md plan lines moved into the main index
9
+ // and the repo INDEX.md deleted. Idempotent: with plan lines only, nothing changes. A plan still
10
+ // inside a linked worktree is reported, not moved.
11
+ export function queueMigrate(args: string[], cfg: Config): number {
12
+ applyQueueEnv(cfg);
13
+ const index = cfg.paths.queue_index;
14
+ if (!existsSync(index)) {
15
+ console.log(`queue migrate: ${index} does not exist; nothing to migrate`);
16
+ return 0;
17
+ }
18
+ const lines = readIndex(index);
19
+ const dirs = lines.filter(l => {
20
+ try {
21
+ return statSync(l).isDirectory();
22
+ } catch {
23
+ return false;
24
+ }
25
+ });
26
+ if (dirs.length === 0) {
27
+ console.log(`queue migrate: ${index} lists plans only; nothing to migrate`);
28
+ return 0;
29
+ }
30
+ const kept: string[] = [];
31
+ let folded = 0;
32
+ for (const l of lines) {
33
+ if (!dirs.includes(l)) {
34
+ kept.push(l);
35
+ continue;
36
+ }
37
+ const repoIndex = path.join(l, "INDEX.md");
38
+ if (!existsSync(repoIndex)) {
39
+ console.log(`queue migrate: ${l} lists no INDEX.md; its line is dropped`);
40
+ continue;
41
+ }
42
+ folded++;
43
+ kept.push(...readIndex(repoIndex, l));
44
+ rmSync(repoIndex);
45
+ }
46
+ const unique = [...new Set(kept)];
47
+ writeFileSync(index, unique.length ? `${unique.join("\n")}\n` : "");
48
+ console.log(`queue migrate: ${index} now lists ${unique.length} plan(s); folded ${folded} repo INDEX.md file(s)`);
49
+ for (const p of unique) {
50
+ const g = gitTop(p);
51
+ if (g && g.top !== g.repo) console.log(`queue migrate: ${p} still lives in the linked worktree ${g.top}; move it to the main checkout ${g.repo}`);
52
+ }
53
+ return 0;
54
+ }
@@ -3,11 +3,12 @@
3
3
  You are Main, the orchestrator. Main plans, delegates, reviews and lands; implementers do the work.
4
4
 
5
5
  ## Plans
6
- - When the owner asks for work in a repo, add the repo to `{{AGENT_DIR}}/INDEX.md` and the plan to the repo's INDEX.md.
6
+ - When the owner asks for work in a repo, write the plan to `<main checkout>/docs/plans/` and list its absolute path in the one index `{{AGENT_DIR}}/INDEX.md` (one plan file per line, never a repo directory). One plan = one worktree: the plan's Worktree line names a worktree no other open plan names.
7
7
  - Entering a repo: read its AGENTS.md first.
8
8
  - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
9
9
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
10
10
  - An open plan gets an implementer subagent. When it claims done, verify (another subagent or yourself). Not done → spawn another implementer for the rest. Done → set `Status: complete`; `queue-close` then archives it and cleans the indexes.
11
+ - An implementer's new `## Progress` entry ends with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence; plan-guard restores an entry without it, and each item becomes an incident.
11
12
  - Main may push and publish once the repo's AGENTS.md test rules are met.
12
13
 
13
14
  ## Scripts (run at the stated moment)
@@ -2,6 +2,8 @@
2
2
  Worktree: <work root>/<repo>-<topic> (configure paths.work_roots, e.g. {{HOME}}/work)
3
3
  Branch: <type>/<topic>
4
4
  PRIORITY-ID: <optional, e.g. PR01>
5
+ <!-- One plan = one worktree: this file lives in the main checkout (<main checkout>/docs/plans/), never
6
+ inside its worktree, and the main index (paths.queue_index) lists its absolute path, one line per plan. -->
5
7
 
6
8
  ## Goal
7
9
  - <owner's words, 1-3 lines: what must be true when this is done>
@@ -30,8 +32,13 @@ PRIORITY-ID: <optional, e.g. PR01>
30
32
  Status: open
31
33
  <!-- The implementer may only append dated entries here: what was done, what was verified (command +
32
34
  result), commits, what is next. It never changes the Status line or adds "WAITING on owner".
35
+ Every new entry ends with a Findings line: "Findings: none", or one item per finding (bug,
36
+ workaround, improvement — any repo) with file:line evidence, items separated by ";". Plan-guard
37
+ restores an entry without it, and each item becomes an incident Main must plan or dismiss.
33
38
  Main reviews the work and then writes "Status: complete"; main-guard auto-runs queue-close, which
34
- closes the plan once the branch is on main and the done check passes (else reopens it).
39
+ closes the plan once the branch is on main and the done check passes (else reopens it), then removes
40
+ the plan's worktree with a plain git worktree remove when it is clean and its branch landed — a dirty,
41
+ unmerged or unremovable worktree (or the repo's main checkout) is kept and the reason printed.
35
42
  Owner calls it off: Main writes "Status: cancelled" + "Cancelled by owner: <date> "<words>"";
36
43
  queue-close archives it and adds it to docs/plans/CANCELLED.md. A new plan resembling a cancelled
37
44
  one is refused until Main checks and writes "False positive: <cancelled file> — <why>". -->