neurastream 0.3.18 → 0.3.21

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 (66) hide show
  1. package/README.md +88 -490
  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/inbox.ts +221 -0
  8. package/src/adapters/omp/index.ts +138 -1050
  9. package/src/adapters/omp/launch.ts +35 -9
  10. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  11. package/src/adapters/omp/rollover-controller.ts +334 -0
  12. package/src/adapters/omp/types.ts +143 -0
  13. package/src/cli/claim.ts +1 -3
  14. package/src/cli/commands.ts +33 -2
  15. package/src/cli/dispatch.ts +55 -30
  16. package/src/cli/guard.ts +0 -3
  17. package/src/cli/incident.ts +2 -2
  18. package/src/cli/metrics.ts +1 -1
  19. package/src/cli/recall.ts +6 -8
  20. package/src/cli/results-build.ts +2 -4
  21. package/src/cli/workspace.ts +13 -5
  22. package/src/core/adapter.ts +16 -0
  23. package/src/core/autonomy.ts +24 -21
  24. package/src/core/blockers.ts +326 -30
  25. package/src/core/file-lock.ts +71 -12
  26. package/src/core/guards/plan-edit.ts +338 -0
  27. package/src/core/guards/planner.ts +70 -0
  28. package/src/core/guards/review.ts +391 -0
  29. package/src/core/guards/spawn.ts +699 -0
  30. package/src/core/guards/state.ts +581 -0
  31. package/src/core/guards/stop.ts +235 -0
  32. package/src/core/guards/tool.ts +541 -0
  33. package/src/core/guards.ts +12 -2661
  34. package/src/core/incidents.ts +134 -99
  35. package/src/core/machine-guard.ts +23 -5
  36. package/src/core/main-start.ts +11 -9
  37. package/src/core/mr-sweep.ts +4 -2
  38. package/src/core/notify.ts +15 -15
  39. package/src/core/owner-log.ts +19 -17
  40. package/src/core/owner-topics.ts +38 -48
  41. package/src/core/owner-ui/auth.ts +164 -0
  42. package/src/core/owner-ui/data.ts +437 -0
  43. package/src/core/owner-ui/handlers.ts +250 -0
  44. package/src/core/owner-ui/messages.ts +209 -0
  45. package/src/core/owner-ui/render.ts +714 -0
  46. package/src/core/owner-ui/results.ts +266 -0
  47. package/src/core/owner-ui/server.ts +142 -0
  48. package/src/core/owner-ui.ts +11 -2118
  49. package/src/core/page-notes.ts +25 -0
  50. package/src/core/pages.ts +452 -78
  51. package/src/core/plan-approval.ts +24 -26
  52. package/src/core/queue/lib.ts +170 -137
  53. package/src/core/queue-cancel.ts +29 -15
  54. package/src/core/queue-check.ts +5 -7
  55. package/src/core/queue-close.ts +54 -29
  56. package/src/core/queue-finished.ts +9 -10
  57. package/src/core/queue-migrate.ts +1 -3
  58. package/src/core/queue-trim.ts +2 -4
  59. package/src/core/results.ts +0 -2
  60. package/src/core/rollover.ts +2 -3
  61. package/src/core/secret-redact.ts +65 -14
  62. package/src/core/tailscale.ts +79 -3
  63. package/src/core/team-client.ts +18 -6
  64. package/src/core/uninstall.ts +2 -0
  65. package/src/core/watch.ts +3 -2
  66. package/src/core/queue/env.ts +0 -14
@@ -2,12 +2,13 @@
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";
11
12
 
12
13
  // --- landing detection (plan 20261031_0911 P4/P5): lives here, not queue-close.ts, because
13
14
  // queueProblems' landed lock needs it and lib must not import the closer that imports lib ---
@@ -76,29 +77,32 @@ export function autoCloseCandidate(p: Plan): boolean {
76
77
  return landed(p.repo, p.branch, originBase(p.repo), p.text);
77
78
  }
78
79
 
79
- const HOME = os.homedir();
80
- // Base set by applyQueueEnv from paths.agent_dir. Specific QUEUE_* vars still win.
81
- function agentDir(): string {
82
- return process.env.QUEUE_AGENT ?? `${HOME}/.config/neurastream`;
80
+ /** Resolve the current home directory dynamically so runtime `process.env.HOME` changes take effect. */
81
+ function currentHome(): string {
82
+ return process.env.HOME || os.homedir();
83
83
  }
84
- export function indexPath(): string {
85
- return process.env.QUEUE_INDEX ?? `${agentDir()}/INDEX.md`;
84
+
85
+ /** Explicit filesystem paths for queue operations (structurally satisfied by `Config["paths"]`). */
86
+ export interface QueuePaths {
87
+ agent_dir: string;
88
+ queue_index: string;
89
+ blockers: string;
90
+ queue_state: string;
91
+ subagents: string;
92
+ cancelled: string;
93
+ unlock: string;
86
94
  }
95
+
87
96
  /** FINISHED.md sits beside the main index: one short entry per closed plan. */
88
- export function finishedPath(): string {
89
- return path.join(path.dirname(indexPath()), "FINISHED.md");
90
- }
91
- export function blockersDirPath(): string {
92
- return process.env.QUEUE_BLOCKERS ?? `${agentDir()}/blockers`;
97
+ export function finishedPath(paths: Pick<QueuePaths, "queue_index">): string {
98
+ return path.join(path.dirname(paths.queue_index), "FINISHED.md");
93
99
  }
94
- export function stateDirPath(): string {
95
- return process.env.QUEUE_STATE ?? `${HOME}/.local/state/queue`;
100
+
101
+ /** Pending-cancel flag file inside the queue state directory. */
102
+ export function cancelPendingPath(paths: Pick<QueuePaths, "queue_state">): string {
103
+ return path.join(paths.queue_state, "cancel-pending.json");
96
104
  }
97
- // Import-time snapshots under the live lib's names; the bins import them as values.
98
- // refreshQueuePaths() reassigns them after applyQueueEnv, so a static import still sees config.
99
- export let INDEX = indexPath();
100
- export let BLOCKERS_DIR = blockersDirPath();
101
- export let STATE_DIR = stateDirPath();
105
+
102
106
  export const BACKGROUND_MAX_LINES = 40;
103
107
  export const SUB_WARN_CALLS = 90;
104
108
  export const SUB_MAX_CALLS = 100;
@@ -147,56 +151,99 @@ export interface Plan {
147
151
  }
148
152
 
149
153
  export function expandHome(p: string): string {
150
- return p === "~" ? HOME : p.startsWith("~/") ? `${HOME}/${p.slice(2)}` : p;
154
+ const home = currentHome();
155
+ return p === "~" ? home : p.startsWith("~/") ? `${home}/${p.slice(2)}` : p;
151
156
  }
152
157
 
153
158
  export function sha(text: string): string {
154
159
  return createHash("sha256").update(text).digest("hex").slice(0, 16);
155
160
  }
156
161
 
157
- function indexLines(file: string): string[] | null {
162
+ /** Parse normalized absolute plan paths from index file text, resolving relative lines against `base`. */
163
+ export function parseIndex(text: string, base = process.cwd()): string[] {
164
+ const lines = text
165
+ .split("\n")
166
+ .map(l => l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").trim())
167
+ .filter(Boolean);
168
+ return [...new Set(lines.map(l => path.resolve(base, expandHome(l))))];
169
+ }
170
+
171
+ // Relative lines resolve against `base` (default: the cwd); a repo INDEX.md passes its repo dir.
172
+ export function readIndex(file: string, base = process.cwd()): string[] {
158
173
  let text: string;
159
174
  try {
160
175
  text = readFileSync(file, "utf8");
161
176
  } catch {
162
- return null;
177
+ return [];
163
178
  }
164
- return text
165
- .split("\n")
166
- .map(l => l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").trim())
167
- .filter(Boolean);
179
+ return parseIndex(text, base);
168
180
  }
169
181
 
170
- // Relative lines resolve against `base` (default: the cwd); a repo INDEX.md passes its repo dir.
171
- export function readIndex(file = indexPath(), base = process.cwd()): string[] {
172
- return [...new Set((indexLines(file) ?? []).map(l => path.resolve(base, expandHome(l))))];
182
+ /** Lock file sibling for `INDEX.md`, serializing read-modify-write index updates. */
183
+ export function indexLockPath(index: string): string {
184
+ return path.join(path.dirname(index), `.${path.basename(index)}.lock`);
173
185
  }
174
186
 
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. `file` defaults to the env index; the owner page
180
- // reorders the cfg's queue_index, which tests point away from the env index.
181
- export function writeIndex(lines: string[], why?: { removed?: "close" | "cancel" | "migrate" }, file = indexPath()): void {
182
- const index = file;
187
+ function writeIndexUnlocked(
188
+ lines: string[],
189
+ why: { removed?: "close" | "cancel" | "migrate" } | undefined,
190
+ file: string,
191
+ currentText: string,
192
+ ): void {
183
193
  const newSet = new Set(
184
194
  lines.filter(l => l.trim()).map(l => path.resolve(expandHome(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").trim()))),
185
195
  );
186
- const gone = readIndex(index).filter(p => !newSet.has(p));
196
+ const gone = parseIndex(currentText).filter(p => !newSet.has(p));
187
197
  if (gone.length && !why?.removed)
188
198
  throw new Error(
189
199
  `writeIndex: ${gone.join(", ")} would leave the index; only a close, cancel or migrate removes a plan (why: { removed: "close" | "cancel" | "migrate" })`,
190
200
  );
191
- const tmp = `${index}.tmp`;
192
- writeFileSync(tmp, lines.length ? `${lines.join("\n")}\n` : "");
193
- renameSync(tmp, index);
194
- chmodSync(index, 0o444);
201
+ writeAtomicSync(file, lines.length ? `${lines.join("\n")}\n` : "", 0o444);
202
+ }
203
+
204
+ /**
205
+ * Locked read-modify-write helper for the queue index: acquires `indexLockPath(file)`, reads the
206
+ * current text under the lock, invokes `mutate(currentText)`, verifies no plan disappears without
207
+ * an explicit `why.removed` reason, and atomically writes the new index with `0o444` applied
208
+ * before `renameSync`. Returning `null` from `mutate` aborts cleanly without writing.
209
+ *
210
+ * Args:
211
+ * file (string): Path to the queue index file
212
+ * why ({ removed?: "close" | "cancel" | "migrate" } | undefined): Removal authorization if lines are dropped
213
+ * mutate ((currentText: string) => string[] | null): Pure transform from current file text to next lines
214
+ *
215
+ * Returns:
216
+ * boolean: True when the index was written; false when `mutate` returned null
217
+ */
218
+ export function updateIndex(
219
+ file: string,
220
+ why: { removed?: "close" | "cancel" | "migrate" } | undefined,
221
+ mutate: (currentText: string) => string[] | null,
222
+ ): boolean {
223
+ return withFileLock(indexLockPath(file), () => {
224
+ let currentText = "";
225
+ try {
226
+ currentText = readFileSync(file, "utf8");
227
+ } catch {}
228
+ const next = mutate(currentText);
229
+ if (next === null) return false;
230
+ writeIndexUnlocked(next, why, file, currentText);
231
+ return true;
232
+ });
233
+ }
234
+
235
+ // The one writer of the index (plan 20261031_0911 P2): the index can only grow. A plan that would
236
+ // disappear without an explicit close/cancel/migrate reason throws before anything is written, and
237
+ // every write lands temp + chmod 0444 + rename under the index lock. No 0o644 before the rename:
238
+ // rename(2) replaces a read-only target with directory-write permission only, so the file is never
239
+ // writable — not even between the rename and the chmod.
240
+ export function writeIndex(lines: string[], why: { removed?: "close" | "cancel" | "migrate" } | undefined, file: string): void {
241
+ updateIndex(file, why, () => lines);
195
242
  }
196
243
 
197
244
  // Doctor's enforcement half of the same plan: the live index must sit at 0444 between writes, so
198
245
  // no program — not just an agent tool call — can rewrite it. Returns the mode it had to fix.
199
- export function enforceReadOnlyIndex(index = indexPath()): string | null {
246
+ export function enforceReadOnlyIndex(index: string): string | null {
200
247
  try {
201
248
  const mode = statSync(index).mode & 0o777;
202
249
  if (mode === 0o444) return null;
@@ -376,14 +423,15 @@ function reuseProblems(repo: string, file: string, secs: Map<string, string>, re
376
423
  * author's machine, so nothing here may stat this machine's disk — no blocker executable()
377
424
  * check and no reuse existsSync. Its blockers are `[]`; every other field is parsed as usual.
378
425
  */
379
- export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath(), reviewAgents: string[] = [], localPaths = true): Plan {
426
+ export function parsePlan(repo: string, file: string, text: string | null, blockersDir = "", reviewAgents: string[] = [], localPaths = true, agentDir?: string): Plan {
380
427
  const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, waitingAsk: null, waitingBlocked: null, waitingWhy: null, waitingCheck: null, waitsOn: [], priorityId: null, title: path.basename(file), goal: [], summary: null, phases: { done: 0, total: 0 }, started: false };
381
428
  if (text === null) return { ...empty, errors: ["plan file listed in the index does not exist"] };
382
429
  const errors: string[] = [];
383
430
  const secs = sections(text);
431
+ const templateHint = agentDir ? `${agentDir}/queue/TEMPLATE.md` : "queue/TEMPLATE.md";
384
432
  for (const s of REQUIRED) {
385
433
  if (s === "progress" ? !secs.has(s) : !items(secs.get(s) ?? "").length)
386
- errors.push(`missing or empty "## ${s.replace(/^\w/, c => c.toUpperCase())}" section (template: ${agentDir()}/queue/TEMPLATE.md)`);
434
+ errors.push(`missing or empty "## ${s.replace(/^\w/, c => c.toUpperCase())}" section (template: ${templateHint})`);
387
435
  }
388
436
  const stamp = /^(\d{8}_\d{4})/.exec(path.basename(file))?.[1] ?? "";
389
437
  if (stamp >= READ_CUTOVER && !items(secs.get("code read by main") ?? "").length)
@@ -454,23 +502,23 @@ export function planRepo(file: string): string {
454
502
  return m?.[1] ? m[1].replace(/\/$/, "") : dir;
455
503
  }
456
504
 
457
- export function readPlans(files: string[], blockersDir = blockersDirPath(), reviewAgents: string[] = []): Plan[] {
505
+ export function readPlans(files: string[], blockersDir = "", reviewAgents: string[] = [], agentDir?: string): Plan[] {
458
506
  return files.map(file => {
459
507
  let text: string | null = null;
460
508
  try {
461
509
  text = readFileSync(file, "utf8");
462
510
  } catch {}
463
- return parsePlan(planRepo(file), file, text, blockersDir, reviewAgents);
511
+ return parsePlan(planRepo(file), file, text, blockersDir, reviewAgents, true, agentDir);
464
512
  });
465
513
  }
466
514
 
467
- export function activePlans(index = indexPath(), blockersDir = blockersDirPath(), reviewAgents: string[] = []): Plan[] {
468
- return readPlans(readIndex(index), blockersDir, reviewAgents);
515
+ export function activePlans(paths: Pick<QueuePaths, "queue_index" | "blockers" | "agent_dir">, reviewAgents: string[] = []): Plan[] {
516
+ return readPlans(readIndex(paths.queue_index), paths.blockers, reviewAgents, paths.agent_dir);
469
517
  }
470
518
 
471
519
  /** 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. */
472
- export function ownerHolds(index = INDEX): string[] {
473
- return activePlans(index)
520
+ export function ownerHolds(paths: Pick<QueuePaths, "queue_index" | "blockers" | "agent_dir">): string[] {
521
+ return activePlans(paths)
474
522
  .filter(p => p.waiting)
475
523
  .map(p => `${p.file}: WAITING on owner: ${p.waitingLine ?? ""}`);
476
524
  }
@@ -526,8 +574,8 @@ export function planAt(p: string, plans: Plan[]): Plan | null {
526
574
  return plans.find(pl => pl.repo === g.repo && path.relative(pl.repo, pl.file) === rel) ?? null;
527
575
  }
528
576
 
529
- export function isOrchestrationPath(p: string, plans: Plan[] = activePlans()): boolean {
530
- if (p === INDEX || p === indexPath()) return true;
577
+ export function isOrchestrationPath(p: string, plans: Plan[], indexFile: string): boolean {
578
+ if (p === indexFile) return true;
531
579
  if (planAt(p, plans)) return true;
532
580
  return plans.some(pl => pl.blockers.some(b => b.script === p));
533
581
  }
@@ -615,7 +663,7 @@ export function registerPackageOpTarget(fn: PackageOpMatcher): void {
615
663
  packageOpMatcher = fn;
616
664
  }
617
665
 
618
- function packageOpTarget(code: string): string | null {
666
+ function packageOpTarget(code: string, paths?: Pick<QueuePaths, "agent_dir">): string | null {
619
667
  for (const seg of code.split(/&&|\|\||;|\n|\|/)) {
620
668
  const toks = seg.trim().split(/\s+/).filter(Boolean);
621
669
  let i = 0;
@@ -641,7 +689,7 @@ function packageOpTarget(code: string): string | null {
641
689
  })) {
642
690
  const envHome = toks.slice(0, i).find(t => t.startsWith("HOME="));
643
691
  if (envHome && envHome.slice("HOME=".length).replace(/^["']|["']$/g, "").startsWith("/tmp/")) continue;
644
- return `${agentDir()}/extensions/`;
692
+ return `${paths?.agent_dir ?? `${currentHome()}/.config/neurastream`}/extensions/`;
645
693
  }
646
694
  }
647
695
  return packageOpMatcher?.(code) ?? null;
@@ -687,7 +735,7 @@ function subagentsOpWrites(code: string): boolean {
687
735
  return false;
688
736
  }
689
737
 
690
- export function writeTargets(toolName: string, input: Record<string, unknown>, cwd: string, relative?: string[]): string[] {
738
+ export function writeTargets(toolName: string, input: Record<string, unknown>, cwd: string, paths?: Pick<QueuePaths, "agent_dir" | "subagents">, relative?: string[]): string[] {
691
739
  const out = new Set<string>();
692
740
  const add = (raw: string, from: string) => {
693
741
  const typed = String(raw).trim().replace(/^["']|["']$/g, "");
@@ -721,7 +769,7 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
721
769
  const code = String(input?.command ?? input?.code ?? "");
722
770
  // A package/plugin/cutover command is a write even though none of the
723
771
  // generic mutating heuristics fire on its text.
724
- const pkgOp = packageOpTarget(code);
772
+ const pkgOp = packageOpTarget(code, paths);
725
773
  const subOp = subagentsOpWrites(code);
726
774
  if (!MUTATING.test(withoutQuotedRedirects(code)) && !pkgOp && !subOp) return [];
727
775
  let dir = typeof input?.cwd === "string" ? path.resolve(cwd, expandHome(input.cwd)) : cwd;
@@ -759,14 +807,10 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
759
807
  ])
760
808
  for (const m of code.matchAll(re)) add((m[1] ?? "").replace(/`/g, ""), dir);
761
809
  if (pkgOp) out.add(pkgOp);
762
- if (subOp) out.add(subagentsPath());
810
+ if (subOp) out.add(paths?.subagents ?? `${currentHome()}/.config/neurastream/notes/subagents.md`);
763
811
  return [...out];
764
812
  }
765
813
 
766
- export function unlockPath(): string {
767
- return process.env.QUEUE_UNLOCK ?? `${agentDir()}/.guard-unlock`;
768
- }
769
- export let UNLOCK = unlockPath();
770
814
  export const UNLOCK_MINUTES = 30;
771
815
  // P8 (2026-10-21): after the npm cutover the running guards load from the
772
816
  // installed package, so the package itself is guard surface. The package root
@@ -785,42 +829,47 @@ function packageManifest(): { root: string; bins: string[] } | null {
785
829
  }
786
830
 
787
831
  function bunGlobalRoot(): string {
788
- return process.env.BUN_INSTALL ? path.resolve(expandHome(process.env.BUN_INSTALL)) : `${HOME}/.bun`;
832
+ return process.env.BUN_INSTALL ? path.resolve(expandHome(process.env.BUN_INSTALL)) : `${currentHome()}/.bun`;
789
833
  }
790
834
 
791
- function protectedPaths(): string[] {
792
- const agent = agentDir();
793
- const paths = [
835
+ export function protectedPaths(paths: QueuePaths): string[] {
836
+ const agent = paths.agent_dir;
837
+ const home = currentHome();
838
+ const out = [
794
839
  `${agent}/extensions/`,
795
840
  `${agent}/queue/`,
796
841
  `${agent}/blockers/`,
842
+ `${paths.blockers.replace(/\/$/, "")}/`,
797
843
  `${agent}/agents/`,
798
844
  `${agent}/AGENTS.md`,
799
845
  `${agent}/CANCELLED.md`,
846
+ paths.cancelled,
800
847
  // The plan index (plan 20261031_0911 P2): append-only and 0444 on disk. Agents add or
801
848
  // reorder through `neurastream queue add` / `queue move`; only the owner writes directly.
802
- indexPath(),
803
- `${stateDirPath()}/`,
849
+ paths.queue_index,
850
+ `${paths.queue_state.replace(/\/$/, "")}/`,
804
851
  `${agent}/config.yml`,
805
852
  // The user's neurastream config file, even when agent_dir points elsewhere: an agent that
806
853
  // could rewrite it could point notify at its own webhook.
807
- `${HOME}/.config/neurastream/config.yml`,
854
+ `${home}/.config/neurastream/config.yml`,
808
855
  // The planner mode guard baseline beside that file (plan 20261102_1515 P2 d): the
809
856
  // owner-only anchor of the mode facts. A write that could plant or edit it would make the
810
857
  // writer's own dirt the truth, so no tool may touch it.
811
- `${HOME}/.config/neurastream/guard-baseline`,
858
+ `${home}/.config/neurastream/guard-baseline`,
812
859
  `${agent}/notes/subagents.md`,
860
+ paths.subagents,
813
861
  `${agent}/.guard-unlock`,
862
+ paths.unlock,
814
863
  `${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/`,
864
+ `${home}/.local/bin/queue-check`,
865
+ `${home}/.local/bin/queue-close`,
866
+ `${home}/.local/bin/queue-cancel`,
867
+ `${home}/.local/bin/agent-ledger`,
868
+ `${home}/.local/bin/brief-lint`,
869
+ `${home}/.local/bin/main-start`,
870
+ `${home}/.local/bin/git`,
871
+ `${home}/.local/bin/git-secret-gate`,
872
+ `${home}/.config/git-secret-gate/`,
824
873
  // Where `bun add -g neurastream` lands; writeTargets points package
825
874
  // operations here so they need the owner's unlock like any guard edit.
826
875
  // The plugin dir is adapter surface: the installer lists it in the
@@ -829,16 +878,15 @@ function protectedPaths(): string[] {
829
878
  ];
830
879
  const pkg = packageManifest();
831
880
  if (pkg) {
832
- paths.push(`${pkg.root}/`);
833
- for (const name of pkg.bins) paths.push(`${HOME}/.bun/bin/${name}`);
881
+ out.push(`${pkg.root}/`);
882
+ for (const name of pkg.bins) out.push(`${home}/.bun/bin/${name}`);
834
883
  }
835
- return paths;
884
+ return out;
836
885
  }
837
- export let PROTECTED = protectedPaths();
838
886
 
839
- export function unlocked(): boolean {
887
+ export function unlocked(paths: Pick<QueuePaths, "unlock">, unlockMinutes = UNLOCK_MINUTES): boolean {
840
888
  try {
841
- return Date.now() - statSync(UNLOCK).mtimeMs < UNLOCK_MINUTES * 60_000;
889
+ return Date.now() - statSync(paths.unlock).mtimeMs < unlockMinutes * 60_000;
842
890
  } catch {
843
891
  return false;
844
892
  }
@@ -871,7 +919,7 @@ export function chatUnlock(text: string, cfg: Config, source: string, word: "cha
871
919
  if (!m) return { applied: false };
872
920
  const minutes = cfg.guards.unlock_minutes;
873
921
  if ((m[1] ?? "").toLowerCase() === "lock") {
874
- rmSync(unlockPath(), { force: true });
922
+ rmSync(cfg.paths.unlock, { force: true });
875
923
  try {
876
924
  appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} LOCK ${word} source=${source}\n`);
877
925
  } catch {}
@@ -880,7 +928,7 @@ export function chatUnlock(text: string, cfg: Config, source: string, word: "cha
880
928
  const want = m[2] === undefined ? minutes : Number(m[2]);
881
929
  if (want < 1) return { applied: false }; // "unlock 0" is no unlock
882
930
  const n = Math.min(want, minutes);
883
- const file = unlockPath();
931
+ const file = cfg.paths.unlock;
884
932
  writeFileSync(file, "");
885
933
  // Backdate the mtime so the existing window (mtime + unlock_minutes) closes after exactly n minutes.
886
934
  const past = (Date.now() - (minutes - n) * 60_000) / 1000; // utimesSync takes seconds
@@ -891,16 +939,13 @@ export function chatUnlock(text: string, cfg: Config, source: string, word: "cha
891
939
  return { applied: true, command: "unlock", minutes: n, until: Math.floor(past + minutes * 60) };
892
940
  }
893
941
 
894
- export function protectedHit(paths: string[]): string | null {
895
- for (const p of paths) for (const g of PROTECTED) if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
942
+ export function protectedHit(targetPaths: string[], paths: QueuePaths): string | null {
943
+ const guarded = protectedPaths(paths);
944
+ for (const p of targetPaths) for (const g of guarded) if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
896
945
  return null;
897
946
  }
898
947
 
899
- export function subagentsPath(): string {
900
- return process.env.QUEUE_SUBAGENTS ?? `${agentDir()}/notes/subagents.md`;
901
- }
902
- export let SUBAGENTS_MD = subagentsPath();
903
- export function allowedAgents(file = subagentsPath()): Set<string> {
948
+ export function allowedAgents(file: string): Set<string> {
904
949
  let text = "";
905
950
  try {
906
951
  text = readFileSync(file, "utf8");
@@ -927,10 +972,6 @@ export function reviewAgentsProblem(cfg: Config, allowed: Set<string>): { proble
927
972
  }
928
973
 
929
974
  export const CANCELLED_REL = "docs/plans/CANCELLED.md";
930
- export function globalCancelledPath(): string {
931
- return process.env.QUEUE_CANCELLED ?? `${agentDir()}/CANCELLED.md`;
932
- }
933
- export let GLOBAL_CANCELLED = globalCancelledPath();
934
975
  export function cancelledFile(repo: string): string {
935
976
  return path.join(repo, CANCELLED_REL);
936
977
  }
@@ -971,8 +1012,8 @@ function readList(file: string): CancelledEntry[] {
971
1012
  export function readCancelled(repo: string): CancelledEntry[] {
972
1013
  return readList(cancelledFile(repo));
973
1014
  }
974
- export function readGlobalCancelled(): CancelledEntry[] {
975
- return readList(globalCancelledPath());
1015
+ export function readGlobalCancelled(paths: Pick<QueuePaths, "cancelled">): CancelledEntry[] {
1016
+ return readList(paths.cancelled);
976
1017
  }
977
1018
  export function banLine(what: string, owner: string, date: string): string {
978
1019
  const words = keyWords(what);
@@ -1004,7 +1045,7 @@ export function finishedKey(entry: string): string {
1004
1045
  }
1005
1046
 
1006
1047
  /** Inserts the entry above older ones. Returns false when the same plan (title + file name) is already listed. */
1007
- export function prependFinished(entry: string, file = finishedPath()): boolean {
1048
+ export function prependFinished(entry: string, file: string): boolean {
1008
1049
  let current = "";
1009
1050
  try {
1010
1051
  current = readFileSync(file, "utf8");
@@ -1023,11 +1064,11 @@ export function prependFinished(entry: string, file = finishedPath()): boolean {
1023
1064
  return true;
1024
1065
  }
1025
1066
  const slug = (name: string) => name.replace(/\.md$/, "").replace(/^\d{8}_\d{4}_/, "");
1026
- export function cancelledMatches(plan: Plan): CancelledEntry[] {
1067
+ export function cancelledMatches(plan: Plan, paths: Pick<QueuePaths, "cancelled">): CancelledEntry[] {
1027
1068
  if (plan.status !== "open") return [];
1028
1069
  const mine = new Set(planWords(plan.text));
1029
1070
  const name = path.basename(plan.file);
1030
- return [...readCancelled(plan.repo), ...readGlobalCancelled()].filter(c => {
1071
+ return [...readCancelled(plan.repo), ...readGlobalCancelled(paths)].filter(c => {
1031
1072
  const cleared = plan.text.split("\n").some(l => {
1032
1073
  const m = l.match(/^\s*(?:[-*]\s+)?False positive:\s*`?([^\s`]+)`?\s+[—:–-]+\s*(.+)$/);
1033
1074
  return m && m[1] === c.name && (m[2] ?? "").trim().length >= 15;
@@ -1039,54 +1080,44 @@ export function cancelledMatches(plan: Plan): CancelledEntry[] {
1039
1080
  return need >= 2 && shared >= need && shared / Math.max(1, Math.min(c.words.length, mine.size)) >= 0.5;
1040
1081
  });
1041
1082
  }
1042
- export function cancelledProblem(plan: Plan, c: CancelledEntry): string {
1083
+ export function cancelledProblem(plan: Plan, c: CancelledEntry, paths: Pick<QueuePaths, "queue_index">): string {
1043
1084
  const what = c.name.startsWith("ban-")
1044
1085
  ? `work the owner said NEVER to do: ${c.name} (${c.date}, owner: ${c.owner}; list ${c.list})`
1045
1086
  : `a plan the owner CANCELLED: ${c.name} (${c.date}, owner: ${c.owner}; archived under ${path.dirname(plan.file)}/archive/)`;
1046
- 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.`;
1087
+ return `resembles ${what}. Check it before going on. Same work: drop this plan (remove it from ${paths.queue_index}) and don't do it. Different work: add the line "False positive: ${c.name} — <why it differs>" to this plan.`;
1047
1088
  }
1048
1089
 
1049
1090
  export const CANCEL_WORDS =
1050
1091
  /\b(?:cancel(?:led|ed)?|abort|scrap|call (?:it|that|this) off|forget (?:it|about)|no longer (?:do|need|want)|skip (?:it|that|this|the)|(?:don'?t|do not|never|stop|quit|not to|not) (?:do|doing|start|starting|work(?:ing)? on|implement|implementing|build|building|touch|run|running|continue|continuing|bother|pursue|go ahead|proceed)|stop (?:it|that|this|the|working|now)|drop (?:it|that|this|the))\b/i;
1051
- export let CANCEL_PENDING = path.join(STATE_DIR, "cancel-pending.json");
1052
- export function refreshQueuePaths(): void {
1053
- INDEX = indexPath();
1054
- BLOCKERS_DIR = blockersDirPath();
1055
- STATE_DIR = stateDirPath();
1056
- UNLOCK = unlockPath();
1057
- PROTECTED = protectedPaths();
1058
- SUBAGENTS_MD = subagentsPath();
1059
- GLOBAL_CANCELLED = globalCancelledPath();
1060
- CANCEL_PENDING = path.join(STATE_DIR, "cancel-pending.json");
1061
- }
1062
- export function cancelPending(): { at: string; words: string } | null {
1092
+
1093
+ export function cancelPending(paths: Pick<QueuePaths, "queue_state">): { at: string; words: string } | null {
1063
1094
  try {
1064
- return JSON.parse(readFileSync(CANCEL_PENDING, "utf8"));
1095
+ return JSON.parse(readFileSync(cancelPendingPath(paths), "utf8"));
1065
1096
  } catch {
1066
1097
  return null;
1067
1098
  }
1068
1099
  }
1069
1100
 
1070
- export function closeLog(file: string): string {
1071
- return path.join(STATE_DIR, `close-${path.basename(file, ".md")}-${sha(file).slice(0, 6)}.log`);
1101
+ export function closeLog(file: string, paths: Pick<QueuePaths, "queue_state">): string {
1102
+ return path.join(paths.queue_state, `close-${path.basename(file, ".md")}-${sha(file).slice(0, 6)}.log`);
1072
1103
  }
1073
1104
 
1074
- export function lastCloseResult(file: string): string | null {
1105
+ export function lastCloseResult(file: string, paths: Pick<QueuePaths, "queue_state">): string | null {
1075
1106
  try {
1076
- const lines = readFileSync(closeLog(file), "utf8").split("\n").filter(l => /^queue-close: (REFUSED|CLOSED|AWAITING|already)/.test(l));
1107
+ const lines = readFileSync(closeLog(file, paths), "utf8").split("\n").filter(l => /^queue-close: (REFUSED|CLOSED|AWAITING|already)/.test(l));
1077
1108
  return lines.at(-1) ?? null;
1078
1109
  } catch {
1079
1110
  return null;
1080
1111
  }
1081
1112
  }
1082
1113
 
1083
- export function awaitingMerge(p: Plan): boolean {
1084
- return p.status === "complete" && (lastCloseResult(p.file) ?? "").startsWith("queue-close: AWAITING merge");
1114
+ export function awaitingMerge(p: Plan, paths: Pick<QueuePaths, "queue_state">): boolean {
1115
+ return p.status === "complete" && (lastCloseResult(p.file, paths) ?? "").startsWith("queue-close: AWAITING merge");
1085
1116
  }
1086
1117
 
1087
1118
  /** 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). */
1088
- export function lastCloseFailed(file: string): boolean {
1089
- const last = lastCloseResult(file);
1119
+ export function lastCloseFailed(file: string, paths: Pick<QueuePaths, "queue_state">): boolean {
1120
+ const last = lastCloseResult(file, paths);
1090
1121
  return !!last && !last.startsWith("queue-close: CLOSED") && !last.startsWith("queue-close: already");
1091
1122
  }
1092
1123
 
@@ -1117,26 +1148,27 @@ export interface QueueProblem {
1117
1148
  problem: string;
1118
1149
  }
1119
1150
 
1120
- export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewAgents: string[] = []): QueueProblem[] {
1151
+ export function queueProblems(paths: QueuePaths, reviewAgents: string[] = []): QueueProblem[] {
1152
+ const index = paths.queue_index;
1121
1153
  const probs: QueueProblem[] = [];
1122
1154
  if (!existsSync(index)) probs.push({ where: index, problem: "main index missing: create it (empty = no open work)" });
1123
- const plans = readPlans(readIndex(index), blockersDir, reviewAgents);
1155
+ const plans = activePlans(paths, reviewAgents);
1124
1156
  const byWorktree = new Map<string, Plan[]>();
1125
1157
  for (const p of plans) {
1126
1158
  for (const e of p.errors) probs.push({ where: p.file, problem: e });
1127
- if ((p.status === "complete" || p.status === "cancelled") && !awaitingMerge(p)) {
1128
- const last = lastCloseResult(p.file);
1159
+ if ((p.status === "complete" || p.status === "cancelled") && !awaitingMerge(p, paths)) {
1160
+ const last = lastCloseResult(p.file, paths);
1129
1161
  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: /, "")})` : ""}` });
1130
1162
  }
1131
1163
  // P5 (plan 20261031_0911): a landed open plan whose auto-close failed locks the queue — the
1132
1164
  // spawn gate and the stop gate refuse everything that does not name it until it closes.
1133
- if (p.status === "open" && autoCloseCandidate(p) && lastCloseFailed(p.file))
1134
- probs.push({ where: p.file, problem: `landed but not closed: ${path.basename(p.file)} — ${(lastCloseResult(p.file) ?? "").replace(/^queue-close: /, "")}` });
1165
+ if (p.status === "open" && autoCloseCandidate(p) && lastCloseFailed(p.file, paths))
1166
+ probs.push({ where: p.file, problem: `landed but not closed: ${path.basename(p.file)} — ${(lastCloseResult(p.file, paths) ?? "").replace(/^queue-close: /, "")}` });
1135
1167
  // P5: a done check that rides `merge-base --is-ancestor` re-does the landing check the
1136
1168
  // closer already owns, squash-aware — and misses squashes.
1137
1169
  if (p.doneCheck?.includes("merge-base --is-ancestor"))
1138
1170
  probs.push({ where: p.file, problem: "done check runs git merge-base --is-ancestor — queue-close checks landing itself, squash-aware; drop it" });
1139
- for (const c of cancelledMatches(p)) probs.push({ where: p.file, problem: cancelledProblem(p, c) });
1171
+ for (const c of cancelledMatches(p, paths)) probs.push({ where: p.file, problem: cancelledProblem(p, c, paths) });
1140
1172
  probs.push(...doneClaimProblems(p));
1141
1173
  // A plan file must live in a main checkout, never in a linked worktree.
1142
1174
  const g = gitTop(p.file);
@@ -1232,10 +1264,11 @@ export function holdWarnings(plans: Plan[]): string[] {
1232
1264
  // and passes `cap = Infinity`.
1233
1265
  export const SUMMARY_CAP = 10;
1234
1266
 
1235
- export function queueSummary(index = INDEX, reviewAgents: string[] = [], staleOrClaims: ReadonlySet<string> | Pick<ClaimStore, "holder"> | null = null, cap: number = SUMMARY_CAP): string {
1267
+ export function queueSummary(paths: QueuePaths, reviewAgents: string[] = [], staleOrClaims: ReadonlySet<string> | Pick<ClaimStore, "holder"> | null = null, cap: number = SUMMARY_CAP): string {
1236
1268
  // Index order IS priority (20261025_0215_index_priority): the list is flat and ranked,
1237
1269
  // rank 1 = the index's top line; repos only surface through each plan's own path.
1238
- const plans = activePlans(index);
1270
+ const index = paths.queue_index;
1271
+ const plans = activePlans(paths);
1239
1272
  const rank = new Map(plans.map((p, i) => [p.file, i + 1] as const));
1240
1273
  const repos = [...new Set(plans.map(p => p.repo))];
1241
1274
  const lines = [`Queue (${index}): ${plans.length ? `${plans.length} plan(s) in ${repos.length} repo(s)` : "empty, no open work"}`];
@@ -1247,7 +1280,7 @@ export function queueSummary(index = INDEX, reviewAgents: string[] = [], staleOr
1247
1280
  stale = staleOrClaims as ReadonlySet<string> ?? new Set<string>();
1248
1281
  }
1249
1282
  plans.slice(0, cap).forEach((p, i) => {
1250
- const status = awaitingMerge(p) ? "complete, awaiting merge" : (p.status ?? "INVALID");
1283
+ const status = awaitingMerge(p, paths) ? "complete, awaiting merge" : (p.status ?? "INVALID");
1251
1284
  const ask = (p.waitingLine ?? "").slice(0, 80);
1252
1285
  const hold = p.waiting ? (stale?.has(p.file) ? `[STALE?] ${ask}` : `WAITING on owner: ${ask}`) : "";
1253
1286
  // I-20261025-208: an open plan waiting on an open plan of the queue shows the target's rank.
@@ -1277,7 +1310,7 @@ export function queueSummary(index = INDEX, reviewAgents: string[] = [], staleOr
1277
1310
  if (nCancelled) lines.push(`Cancelled rules: ${nCancelled}`);
1278
1311
  const more = plans.length - Math.min(plans.length, cap);
1279
1312
  if (more > 0) lines.push(`… ${more} more plans (queue-check lists all)`);
1280
- const probs = queueProblems(index, BLOCKERS_DIR, reviewAgents);
1313
+ const probs = queueProblems(paths, reviewAgents);
1281
1314
  const shown = new Set(plans.slice(0, cap).map(p => p.file));
1282
1315
  const planProbs = probs.filter(x => shown.has(x.where));
1283
1316
  const hidden = probs.length - planProbs.length;