neurastream 0.3.20 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +1 -0
  2. package/package.json +1 -1
  3. package/src/adapters/index.ts +3 -2
  4. package/src/adapters/omp/adapter.ts +2 -1
  5. package/src/adapters/omp/auto-close.ts +64 -0
  6. package/src/adapters/omp/chat-commands.ts +161 -0
  7. package/src/adapters/omp/doctor.ts +6 -0
  8. package/src/adapters/omp/inbox.ts +221 -0
  9. package/src/adapters/omp/index.ts +115 -1039
  10. package/src/adapters/omp/launch.ts +31 -3
  11. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  12. package/src/adapters/omp/rollover-controller.ts +334 -0
  13. package/src/adapters/omp/types.ts +143 -0
  14. package/src/cli/commands.ts +33 -2
  15. package/src/cli/dispatch.ts +44 -16
  16. package/src/cli/recall.ts +3 -2
  17. package/src/cli/results-build.ts +1 -1
  18. package/src/cli/reuse.ts +109 -0
  19. package/src/cli/setup.ts +25 -1
  20. package/src/cli/workspace.ts +13 -2
  21. package/src/core/adapter.ts +16 -0
  22. package/src/core/blockers.ts +326 -30
  23. package/src/core/config.ts +29 -0
  24. package/src/core/file-lock.ts +71 -12
  25. package/src/core/guards/plan-edit.ts +530 -0
  26. package/src/core/guards/planner.ts +70 -0
  27. package/src/core/guards/review.ts +391 -0
  28. package/src/core/guards/spawn.ts +709 -0
  29. package/src/core/guards/state.ts +581 -0
  30. package/src/core/guards/stop.ts +235 -0
  31. package/src/core/guards/tool.ts +541 -0
  32. package/src/core/guards.ts +12 -2658
  33. package/src/core/incidents.ts +125 -91
  34. package/src/core/machine-guard.ts +23 -5
  35. package/src/core/main-start.ts +10 -8
  36. package/src/core/owner-topics.ts +2 -13
  37. package/src/core/owner-ui/auth.ts +164 -0
  38. package/src/core/owner-ui/data.ts +437 -0
  39. package/src/core/owner-ui/handlers.ts +250 -0
  40. package/src/core/owner-ui/messages.ts +209 -0
  41. package/src/core/owner-ui/render.ts +714 -0
  42. package/src/core/owner-ui/results.ts +266 -0
  43. package/src/core/owner-ui/server.ts +142 -0
  44. package/src/core/owner-ui.ts +11 -2121
  45. package/src/core/page-notes.ts +25 -0
  46. package/src/core/pages.ts +452 -77
  47. package/src/core/plan-approval.ts +12 -14
  48. package/src/core/queue/lib.ts +146 -43
  49. package/src/core/queue-cancel.ts +21 -17
  50. package/src/core/queue-close.ts +48 -23
  51. package/src/core/reuse-map.ts +742 -0
  52. package/src/core/secret-redact.ts +65 -14
  53. package/src/core/setup-detect.ts +8 -3
  54. package/src/core/tailscale.ts +79 -3
  55. package/src/core/team-client.ts +13 -2
  56. package/src/core/uninstall.ts +16 -0
  57. package/templates/config.yml +7 -0
@@ -2,12 +2,14 @@
2
2
 
3
3
  import { createHash } from "node:crypto";
4
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
+ import { accessSync, appendFileSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
8
  import type { Config } from "../config.ts";
9
9
  import type { ClaimStore } from "../claims.ts";
10
10
  import { strftime } from "../clock.ts";
11
+ import { withFileLock, writeAtomicSync } from "../file-lock.ts";
12
+ import { MAX_TERMS, NONE_TERMS_MIN, citedQuotes, hasBareChecked, isMapOrNoneLine, normRel, parseMapLine, parseNoneLine, type ParsedMapLine, type ParsedNoneLine } from "../reuse-map.ts";
11
13
 
12
14
  // --- landing detection (plan 20261031_0911 P4/P5): lives here, not queue-close.ts, because
13
15
  // queueProblems' landed lock needs it and lib must not import the closer that imports lib ---
@@ -76,7 +78,10 @@ export function autoCloseCandidate(p: Plan): boolean {
76
78
  return landed(p.repo, p.branch, originBase(p.repo), p.text);
77
79
  }
78
80
 
79
- const HOME = os.homedir();
81
+ /** Resolve the current home directory dynamically so runtime `process.env.HOME` changes take effect. */
82
+ function currentHome(): string {
83
+ return process.env.HOME || os.homedir();
84
+ }
80
85
 
81
86
  /** Explicit filesystem paths for queue operations (structurally satisfied by `Config["paths"]`). */
82
87
  export interface QueuePaths {
@@ -147,50 +152,94 @@ export interface Plan {
147
152
  }
148
153
 
149
154
  export function expandHome(p: string): string {
150
- return p === "~" ? HOME : p.startsWith("~/") ? `${HOME}/${p.slice(2)}` : p;
155
+ const home = currentHome();
156
+ return p === "~" ? home : p.startsWith("~/") ? `${home}/${p.slice(2)}` : p;
151
157
  }
152
158
 
153
159
  export function sha(text: string): string {
154
160
  return createHash("sha256").update(text).digest("hex").slice(0, 16);
155
161
  }
156
162
 
157
- function indexLines(file: string): string[] | null {
158
- let text: string;
159
- try {
160
- text = readFileSync(file, "utf8");
161
- } catch {
162
- return null;
163
- }
164
- return text
163
+ /** Parse normalized absolute plan paths from index file text, resolving relative lines against `base`. */
164
+ export function parseIndex(text: string, base = process.cwd()): string[] {
165
+ const lines = text
165
166
  .split("\n")
166
167
  .map(l => l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").trim())
167
168
  .filter(Boolean);
169
+ return [...new Set(lines.map(l => path.resolve(base, expandHome(l))))];
168
170
  }
169
171
 
170
172
  // Relative lines resolve against `base` (default: the cwd); a repo INDEX.md passes its repo dir.
171
173
  export function readIndex(file: string, base = process.cwd()): string[] {
172
- return [...new Set((indexLines(file) ?? []).map(l => path.resolve(base, expandHome(l))))];
174
+ let text: string;
175
+ try {
176
+ text = readFileSync(file, "utf8");
177
+ } catch {
178
+ return [];
179
+ }
180
+ return parseIndex(text, base);
173
181
  }
174
182
 
175
- // The one writer of the index (plan 20261031_0911 P2): the index can only grow. A plan that would
176
- // disappear without an explicit close/cancel/migrate reason throws before anything is written, and
177
- // every write lands temp+rename then chmods the file to 0444. No 0o644 before the rename: rename(2)
178
- // replaces a read-only target with directory-write permission only, so the file is never writable —
179
- // not even between the rename and the chmod.
180
- export function writeIndex(lines: string[], why: { removed?: "close" | "cancel" | "migrate" } | undefined, file: string): void {
181
- const index = file;
183
+ /** Lock file sibling for `INDEX.md`, serializing read-modify-write index updates. */
184
+ export function indexLockPath(index: string): string {
185
+ return path.join(path.dirname(index), `.${path.basename(index)}.lock`);
186
+ }
187
+
188
+ function writeIndexUnlocked(
189
+ lines: string[],
190
+ why: { removed?: "close" | "cancel" | "migrate" } | undefined,
191
+ file: string,
192
+ currentText: string,
193
+ ): void {
182
194
  const newSet = new Set(
183
195
  lines.filter(l => l.trim()).map(l => path.resolve(expandHome(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").trim()))),
184
196
  );
185
- const gone = readIndex(index).filter(p => !newSet.has(p));
197
+ const gone = parseIndex(currentText).filter(p => !newSet.has(p));
186
198
  if (gone.length && !why?.removed)
187
199
  throw new Error(
188
200
  `writeIndex: ${gone.join(", ")} would leave the index; only a close, cancel or migrate removes a plan (why: { removed: "close" | "cancel" | "migrate" })`,
189
201
  );
190
- const tmp = `${index}.tmp`;
191
- writeFileSync(tmp, lines.length ? `${lines.join("\n")}\n` : "");
192
- renameSync(tmp, index);
193
- chmodSync(index, 0o444);
202
+ writeAtomicSync(file, lines.length ? `${lines.join("\n")}\n` : "", 0o444);
203
+ }
204
+
205
+ /**
206
+ * Locked read-modify-write helper for the queue index: acquires `indexLockPath(file)`, reads the
207
+ * current text under the lock, invokes `mutate(currentText)`, verifies no plan disappears without
208
+ * an explicit `why.removed` reason, and atomically writes the new index with `0o444` applied
209
+ * before `renameSync`. Returning `null` from `mutate` aborts cleanly without writing.
210
+ *
211
+ * Args:
212
+ * file (string): Path to the queue index file
213
+ * why ({ removed?: "close" | "cancel" | "migrate" } | undefined): Removal authorization if lines are dropped
214
+ * mutate ((currentText: string) => string[] | null): Pure transform from current file text to next lines
215
+ *
216
+ * Returns:
217
+ * boolean: True when the index was written; false when `mutate` returned null
218
+ */
219
+ export function updateIndex(
220
+ file: string,
221
+ why: { removed?: "close" | "cancel" | "migrate" } | undefined,
222
+ mutate: (currentText: string) => string[] | null,
223
+ ): boolean {
224
+ return withFileLock(indexLockPath(file), () => {
225
+ let currentText = "";
226
+ try {
227
+ currentText = readFileSync(file, "utf8");
228
+ } catch {}
229
+ const next = mutate(currentText);
230
+ if (next === null) return false;
231
+ writeIndexUnlocked(next, why, file, currentText);
232
+ return true;
233
+ });
234
+ }
235
+
236
+ // The one writer of the index (plan 20261031_0911 P2): the index can only grow. A plan that would
237
+ // disappear without an explicit close/cancel/migrate reason throws before anything is written, and
238
+ // every write lands temp + chmod 0444 + rename under the index lock. No 0o644 before the rename:
239
+ // rename(2) replaces a read-only target with directory-write permission only, so the file is never
240
+ // writable — not even between the rename and the chmod.
241
+ export function writeIndex(lines: string[], why: { removed?: "close" | "cancel" | "migrate" } | undefined, file: string): void {
242
+ updateIndex(file, why, () => lines);
194
243
  }
195
244
 
196
245
  // Doctor's enforcement half of the same plan: the live index must sit at 0444 between writes, so
@@ -355,18 +404,64 @@ export function headerField(text: string, name: string): string | null {
355
404
  * P1 (plan 20261028_1600): every new thing a plan adds carries a reuse line with a checked
356
405
  * `path:line` citation that exists relative to the plan's repo. Applies to every plan (P5
357
406
  * removed the cutover); an empty `review.agents` list turns the gate off (P5c).
407
+ *
408
+ * P2 (plan 20261122_1828_reuse_map): text only. When a map or none line is present the section
409
+ * follows the map rule instead: those lines skip the plain `checked:` rule, every `new:` citation
410
+ * carries a quoted line, the map's matched files are cited on >= N distinct lines, a none line
411
+ * searches >= 3 and at most MAX_TERMS distinct terms. Quote equality and the graphify re-run live
412
+ * in plan-edit's reuseMapWriteProblems — this function stays on the hot path, so it never reads
413
+ * a graph or runs graphify.
358
414
  */
359
415
  function reuseProblems(repo: string, file: string, secs: Map<string, string>, reviewAgents: string[]): string[] {
360
416
  if (!reviewAgents.length) return [];
361
417
  const lines = items(secs.get("reuse") ?? "");
362
418
  if (!lines.length)
363
419
  return [`missing or empty "## Reuse" section (one line per new thing: - new: <thing> — checked: <path>:<line> — reuse: <how, or why not>; "- new: none — ..." when nothing is new)`];
420
+ const map = lines.map(parseMapLine).find((m) => m !== null) ?? null;
421
+ const none = lines.map(parseNoneLine).find((n) => n !== null) ?? null;
422
+ if (!map && !none) {
423
+ const probs: string[] = [];
424
+ for (const line of lines) {
425
+ const m = /checked:\s*`?([^`\s—]+):(\d+)(?:-\d+)?`?/.exec(line);
426
+ if (!m) probs.push(`reuse line without "checked: <path>:<line>": ${line.slice(0, 80)}`);
427
+ else if (!existsSync(path.resolve(repo, m[1]!))) probs.push(`reuse citation does not exist: ${m[1]}`);
428
+ }
429
+ return probs;
430
+ }
431
+ return mapGateProblems(repo, lines, map, none);
432
+ }
433
+
434
+ /** Text half of the map gate (plan 20261122_1828_reuse_map P2a): shapes only, never a graphify run. */
435
+ function mapGateProblems(repo: string, lines: string[], map: ParsedMapLine | null, none: ParsedNoneLine | null): string[] {
364
436
  const probs: string[] = [];
437
+ if (map && none) probs.push("either a - map: line or a none-to-reuse line under ## Reuse, not both");
438
+ for (const line of lines) {
439
+ if (isMapOrNoneLine(line) || !/map:|none to reuse/.test(line)) continue;
440
+ probs.push(`a "- map:" or "none to reuse" line that does not parse — rerun \`neurastream reuse map\`: ${line.slice(0, 80)}`);
441
+ }
442
+ if (map && map.terms.length > MAX_TERMS)
443
+ probs.push(`${map.terms.length} terms on the map line (at most ${MAX_TERMS} — each term is one graphify query)`);
444
+ if (none) {
445
+ if (none.terms.length < NONE_TERMS_MIN)
446
+ probs.push(`the none line searches ${none.terms.length} terms (search at least ${NONE_TERMS_MIN} distinct terms: - new: none to reuse — searched: "t1", "t2", "t3")`);
447
+ if (none.terms.length > MAX_TERMS)
448
+ probs.push(`${none.terms.length} terms on the none line (at most ${MAX_TERMS} — each term is one graphify query)`);
449
+ }
450
+ const matched = map ? new Set(map.files.map(normRel)) : null;
451
+ const cited = new Set<string>();
365
452
  for (const line of lines) {
366
- const m = /checked:\s*`?([^`\s—]+):(\d+)(?:-\d+)?`?/.exec(line);
367
- if (!m) probs.push(`reuse line without "checked: <path>:<line>": ${line.slice(0, 80)}`);
368
- else if (!existsSync(path.resolve(repo, m[1]!))) probs.push(`reuse citation does not exist: ${m[1]}`);
453
+ if (isMapOrNoneLine(line) || !line.includes("new:")) continue;
454
+ if (hasBareChecked(line)) {
455
+ probs.push(`reuse citation without a quoted line ("checked: <path>:<n> \\"the file's text at that line\\""): ${line.slice(0, 80)}`);
456
+ continue;
457
+ }
458
+ for (const c of citedQuotes(line)) {
459
+ if (!existsSync(path.resolve(repo, c.file))) probs.push(`reuse citation does not exist: ${c.file}`);
460
+ if (matched) cited.add(normRel(c.file));
461
+ }
369
462
  }
463
+ if (matched && cited.size < map!.cite)
464
+ probs.push(`${cited.size} of the map's ${map!.cite} matched files cited — cite ${map!.cite} of ${[...matched].join(", ")} as "checked: <path>:<n> \\"the file's text at that line\\""`);
370
465
  return probs;
371
466
  }
372
467
 
@@ -641,7 +736,7 @@ function packageOpTarget(code: string, paths?: Pick<QueuePaths, "agent_dir">): s
641
736
  })) {
642
737
  const envHome = toks.slice(0, i).find(t => t.startsWith("HOME="));
643
738
  if (envHome && envHome.slice("HOME=".length).replace(/^["']|["']$/g, "").startsWith("/tmp/")) continue;
644
- return `${paths?.agent_dir ?? `${HOME}/.config/neurastream`}/extensions/`;
739
+ return `${paths?.agent_dir ?? `${currentHome()}/.config/neurastream`}/extensions/`;
645
740
  }
646
741
  }
647
742
  return packageOpMatcher?.(code) ?? null;
@@ -759,7 +854,7 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
759
854
  ])
760
855
  for (const m of code.matchAll(re)) add((m[1] ?? "").replace(/`/g, ""), dir);
761
856
  if (pkgOp) out.add(pkgOp);
762
- if (subOp) out.add(paths?.subagents ?? `${HOME}/.config/neurastream/notes/subagents.md`);
857
+ if (subOp) out.add(paths?.subagents ?? `${currentHome()}/.config/neurastream/notes/subagents.md`);
763
858
  return [...out];
764
859
  }
765
860
 
@@ -781,11 +876,12 @@ function packageManifest(): { root: string; bins: string[] } | null {
781
876
  }
782
877
 
783
878
  function bunGlobalRoot(): string {
784
- return process.env.BUN_INSTALL ? path.resolve(expandHome(process.env.BUN_INSTALL)) : `${HOME}/.bun`;
879
+ return process.env.BUN_INSTALL ? path.resolve(expandHome(process.env.BUN_INSTALL)) : `${currentHome()}/.bun`;
785
880
  }
786
881
 
787
882
  export function protectedPaths(paths: QueuePaths): string[] {
788
883
  const agent = paths.agent_dir;
884
+ const home = currentHome();
789
885
  const out = [
790
886
  `${agent}/extensions/`,
791
887
  `${agent}/queue/`,
@@ -802,25 +898,25 @@ export function protectedPaths(paths: QueuePaths): string[] {
802
898
  `${agent}/config.yml`,
803
899
  // The user's neurastream config file, even when agent_dir points elsewhere: an agent that
804
900
  // could rewrite it could point notify at its own webhook.
805
- `${HOME}/.config/neurastream/config.yml`,
901
+ `${home}/.config/neurastream/config.yml`,
806
902
  // The planner mode guard baseline beside that file (plan 20261102_1515 P2 d): the
807
903
  // owner-only anchor of the mode facts. A write that could plant or edit it would make the
808
904
  // writer's own dirt the truth, so no tool may touch it.
809
- `${HOME}/.config/neurastream/guard-baseline`,
905
+ `${home}/.config/neurastream/guard-baseline`,
810
906
  `${agent}/notes/subagents.md`,
811
907
  paths.subagents,
812
908
  `${agent}/.guard-unlock`,
813
909
  paths.unlock,
814
910
  `${path.dirname(agent)}/git-no-verify-guard.mjs`,
815
- `${HOME}/.local/bin/queue-check`,
816
- `${HOME}/.local/bin/queue-close`,
817
- `${HOME}/.local/bin/queue-cancel`,
818
- `${HOME}/.local/bin/agent-ledger`,
819
- `${HOME}/.local/bin/brief-lint`,
820
- `${HOME}/.local/bin/main-start`,
821
- `${HOME}/.local/bin/git`,
822
- `${HOME}/.local/bin/git-secret-gate`,
823
- `${HOME}/.config/git-secret-gate/`,
911
+ `${home}/.local/bin/queue-check`,
912
+ `${home}/.local/bin/queue-close`,
913
+ `${home}/.local/bin/queue-cancel`,
914
+ `${home}/.local/bin/agent-ledger`,
915
+ `${home}/.local/bin/brief-lint`,
916
+ `${home}/.local/bin/main-start`,
917
+ `${home}/.local/bin/git`,
918
+ `${home}/.local/bin/git-secret-gate`,
919
+ `${home}/.config/git-secret-gate/`,
824
920
  // Where `bun add -g neurastream` lands; writeTargets points package
825
921
  // operations here so they need the owner's unlock like any guard edit.
826
922
  // The plugin dir is adapter surface: the installer lists it in the
@@ -830,7 +926,7 @@ export function protectedPaths(paths: QueuePaths): string[] {
830
926
  const pkg = packageManifest();
831
927
  if (pkg) {
832
928
  out.push(`${pkg.root}/`);
833
- for (const name of pkg.bins) out.push(`${HOME}/.bun/bin/${name}`);
929
+ for (const name of pkg.bins) out.push(`${home}/.bun/bin/${name}`);
834
930
  }
835
931
  return out;
836
932
  }
@@ -890,9 +986,16 @@ export function chatUnlock(text: string, cfg: Config, source: string, word: "cha
890
986
  return { applied: true, command: "unlock", minutes: n, until: Math.floor(past + minutes * 60) };
891
987
  }
892
988
 
989
+ // P2b (plan 20261122_1828_reuse_map): the reuse map's own directory and the worktree registry are
990
+ // protected in any repo, the directory itself included (`rm -rf graphify-out`, `ln -s … graphify-out`).
991
+ const PROTECTED_SEGMENTS = [/(^|\/)graphify-out(\/|$)/, /(^|\/)\.git\/worktrees(\/|$)/];
992
+
893
993
  export function protectedHit(targetPaths: string[], paths: QueuePaths): string | null {
894
994
  const guarded = protectedPaths(paths);
895
- for (const p of targetPaths) for (const g of guarded) if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
995
+ for (const p of targetPaths) {
996
+ if (PROTECTED_SEGMENTS.some((re) => re.test(p))) return p;
997
+ for (const g of guarded) if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
998
+ }
896
999
  return null;
897
1000
  }
898
1001
 
@@ -1,8 +1,8 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { fileURLToPath } from "node:url";
5
4
  import type { Config } from "./config.ts";
5
+ import { queueClose } from "./queue-close.ts";
6
6
  import {
7
7
  activePlans,
8
8
  banLine,
@@ -13,6 +13,19 @@ import {
13
13
  repoRoot,
14
14
  } from "./queue/lib.ts";
15
15
 
16
+ /** Internal control-flow error thrown by `die()` so `queueCancel` returns exit code 1 cleanly without killing the process. */
17
+ class AbortCancel extends Error {}
18
+
19
+ /**
20
+ * Record a cancelled plan, global/repo never-do rule, or false-positive cancellation dismissal.
21
+ *
22
+ * Args:
23
+ * args (string[]): CLI arguments for `queue-cancel`
24
+ * cfg (Config): Loaded neurastream configuration
25
+ *
26
+ * Returns:
27
+ * number: Exit code (`0` succeeded, `1` refused, or child `queue-close` exit code)
28
+ */
16
29
  export function queueCancel(args: string[], cfg: Config): number {
17
30
  const STATE_DIR = cfg.paths.queue_state;
18
31
  const CANCEL_PENDING = cancelPendingPath(cfg.paths);
@@ -20,7 +33,7 @@ export function queueCancel(args: string[], cfg: Config): number {
20
33
  const today = new Date().toISOString().slice(0, 10);
21
34
  function die(msg: string): never {
22
35
  console.error(`queue-cancel: REFUSED: ${msg}`);
23
- process.exit(1);
36
+ throw new AbortCancel(msg);
24
37
  }
25
38
  function clearPending(how: string) {
26
39
  const p = cancelPending(cfg.paths);
@@ -29,7 +42,7 @@ export function queueCancel(args: string[], cfg: Config): number {
29
42
  rmSync(CANCEL_PENDING, { force: true });
30
43
  }
31
44
  const usage = 'usage: queue-cancel <plan> "<owner words>" | --never "<what>" "<owner words>" [--repo <repo>] | --not-a-cancel "<why>"';
32
-
45
+ try {
33
46
  if (args[0] === "--not-a-cancel") {
34
47
  const why = (args[1] ?? "").trim();
35
48
  // Only a message main-guard flagged needs an answer; a bare call is a wasted round.
@@ -85,18 +98,9 @@ export function queueCancel(args: string[], cfg: Config): number {
85
98
  text = text.replace(/^Status:\s*\S+\s*$/m, `Status: cancelled\nCancelled by owner: ${today} ${owner.trim().replace(/\n/g, " ")}`);
86
99
  writeFileSync(file, text);
87
100
  clearPending(`plan: ${file}`);
88
- const closeBin = path.join(path.dirname(fileURLToPath(import.meta.url)), "../cli/main.ts");
89
- const childEnv: NodeJS.ProcessEnv = {
90
- ...process.env,
91
- HOME: cfg.paths.home,
92
- QUEUE_AGENT: cfg.paths.agent_dir,
93
- QUEUE_INDEX: cfg.paths.queue_index,
94
- QUEUE_BLOCKERS: cfg.paths.blockers,
95
- QUEUE_STATE: cfg.paths.queue_state,
96
- QUEUE_SUBAGENTS: cfg.paths.subagents,
97
- QUEUE_CANCELLED: cfg.paths.cancelled,
98
- QUEUE_UNLOCK: cfg.paths.unlock,
99
- };
100
- const r = spawnSync("bun", [closeBin, "queue-close", file], { stdio: "inherit", env: childEnv });
101
- return r.status ?? 1;
101
+ return queueClose([file], cfg);
102
+ } catch (e) {
103
+ if (e instanceof AbortCancel) return 1;
104
+ throw e;
105
+ }
102
106
  }
@@ -1,18 +1,31 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, fstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
- import os from "node:os";
4
3
  import path from "node:path";
5
4
  import { claimStoreFor } from "./team-client.ts";
6
5
 
7
6
  import type { Config } from "./config.ts";
8
- import { mainId } from "./guards.ts";
9
- import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, gitOut as git, landed, prependFinished, sha, writeIndex } from "./queue/lib.ts";
7
+ import { tryLock } from "./file-lock.ts";
8
+ import { deleteSpawnRecord, mainId } from "./guards.ts";
9
+ import { activePlans, cancelledFile, cancelledLine, closeLog, expandHome, finishedEntry, finishedPath, gitOut as git, landed, prependFinished, sha, updateIndex } from "./queue/lib.ts";
10
10
  import { fixedIncident } from "./incidents.ts";
11
11
 
12
12
  // P4 (plan 20261031_0911): the landing check lives in queue/lib.ts (queueProblems' landed lock
13
13
  // shares it, and lib cannot import this closer back); re-exported here per the plan.
14
14
  export { landed };
15
15
 
16
+ /** Internal control-flow error thrown by `die()` so `queueClose` returns exit code 1 cleanly without killing the process. */
17
+ class AbortClose extends Error {}
18
+
19
+ /**
20
+ * Close and archive a completed or cancelled plan, run its done check, and remove it from the queue index.
21
+ *
22
+ * Args:
23
+ * args (string[]): CLI arguments (`[--auto] <plan file>` or `-h`/`--help`)
24
+ * cfg (Config): Loaded neurastream configuration
25
+ *
26
+ * Returns:
27
+ * number: Exit code (`0` closed, `1` refused, `3` already running, `4` awaiting merge)
28
+ */
16
29
  export function queueClose(args: string[], cfg: Config): number {
17
30
  const INDEX = cfg.paths.queue_index;
18
31
  const STATE_DIR = cfg.paths.queue_state;
@@ -29,8 +42,9 @@ export function queueClose(args: string[], cfg: Config): number {
29
42
  }
30
43
  function die(msg: string): never {
31
44
  result(`queue-close: REFUSED: ${msg}`);
32
- process.exit(1);
45
+ throw new AbortClose(msg);
33
46
  }
47
+ try {
34
48
  // A clone of a clone judges "landed" against the middle copy's default branch, which can be
35
49
  // stale. Follow local-path origins (at most 3 hops) to the upstream repo and fetch its default
36
50
  // branch: that commit is the base. No local origin: the existing base, unchanged.
@@ -79,16 +93,20 @@ export function queueClose(args: string[], cfg: Config): number {
79
93
 
80
94
  mkdirSync(STATE_DIR, { recursive: true });
81
95
  const lock = path.join(STATE_DIR, `close-${sha(file)}.lock`);
96
+ const held = tryLock(lock);
97
+ if (!held) {
98
+ let pidNote = "";
99
+ try {
100
+ const pid = Number(readFileSync(lock, "utf8").trim());
101
+ if (pid) pidNote = ` (pid ${pid})`;
102
+ } catch {}
103
+ console.error(`queue-close: already running for ${file}${pidNote}`);
104
+ return 3;
105
+ }
82
106
  try {
83
- const pid = Number(readFileSync(lock, "utf8"));
84
- if (pid && pid !== process.pid) {
85
- process.kill(pid, 0);
86
- console.error(`queue-close: already running for ${file} (pid ${pid})`);
87
- return 3;
88
- }
107
+ try {
108
+ writeFileSync(lock, `${process.pid}\n`);
89
109
  } catch {}
90
- writeFileSync(lock, String(process.pid));
91
- process.on("exit", () => rmSync(lock, { force: true }));
92
110
 
93
111
  const plan = activePlans(cfg.paths).find(p => p.file === file);
94
112
  if (!plan) die(`${file} is not listed in the main index ${INDEX}`);
@@ -147,7 +165,8 @@ export function queueClose(args: string[], cfg: Config): number {
147
165
  // A shared clone of the base, deliberately NOT a registered worktree: it never shows up
148
166
  // in `git worktree list` and can be dropped with a plain delete when it stays clean.
149
167
  scratch = mkdtempSync(path.join(STATE_DIR, "done-base-"));
150
- const add = git(plan.repo, "clone", "-q", "--shared", ".", scratch) && git(scratch, "checkout", "-q", "--detach", base);
168
+ const cloned = git(plan.repo, "clone", "-q", "--shared", ".", scratch);
169
+ const add = cloned.ok ? git(scratch, "checkout", "-q", "--detach", base) : cloned;
151
170
  if (!add.ok) {
152
171
  rmSync(scratch, { recursive: true, force: true });
153
172
  die(`could not check out ${base} for the done check: ${add.out}`);
@@ -282,16 +301,15 @@ export function queueClose(args: string[], cfg: Config): number {
282
301
  }
283
302
 
284
303
  // One index: the closed plan's line leaves the main index; there is no repo INDEX.md.
285
- const lines = readFileSync(INDEX, "utf8").split("\n").filter(l => l.trim());
286
- const keep = lines.filter(l => path.resolve(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").replace(/^~(?=\/)/, os.homedir())) !== file);
287
- writeIndex(keep, { removed: cancelling ? "cancel" : "close" }, INDEX);
288
- console.log(`queue-close: removed from ${INDEX} (${keep.length} plan(s) left)`);
289
- try {
290
- const sp = path.join(STATE_DIR, "spawns.json");
291
- const s = JSON.parse(readFileSync(sp, "utf8"));
292
- delete s[file];
293
- writeFileSync(sp, JSON.stringify(s, null, 1));
294
- } catch {}
304
+ let remaining = 0;
305
+ updateIndex(INDEX, { removed: cancelling ? "cancel" : "close" }, (currentText) => {
306
+ const lines = currentText.split("\n").filter(l => l.trim());
307
+ const keep = lines.filter(l => path.resolve(expandHome(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, ""))) !== file);
308
+ remaining = keep.length;
309
+ return keep;
310
+ });
311
+ console.log(`queue-close: removed from ${INDEX} (${remaining} plan(s) left)`);
312
+ deleteSpawnRecord(file, cfg.paths);
295
313
  // Incidents this plan fixes (plan P5): each INCIDENT <id> cited outside ## Progress gets a
296
314
  // fixed record, so the guards stop pushing a bug whose fix just shipped. Progress is
297
315
  // narrative, not fix work (I-20261031-349, P5b): an id Main only filed there ("needs a phase
@@ -324,4 +342,11 @@ export function queueClose(args: string[], cfg: Config): number {
324
342
  claimStoreFor(file, cfg).release(file, mainId());
325
343
  console.log("queue-close: CLOSED");
326
344
  return 0;
345
+ } finally {
346
+ held.release();
347
+ }
348
+ } catch (e) {
349
+ if (e instanceof AbortClose) return 1;
350
+ throw e;
351
+ }
327
352
  }