neurastream 0.3.18 → 0.3.20

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.
@@ -3,9 +3,6 @@
3
3
  // --json`) maps its own events onto these, applies `restore`, and feeds back the counters the
4
4
  // decision returns in `state`.
5
5
  //
6
- // Callers must first map config into the queue paths (applyQueueEnv): the queue library resolves
7
- // INDEX.md, blockers, state, subagents, cancelled and unlock from those env vars.
8
- //
9
6
  // Ported rules:
10
7
  // - protected guard files, unlockable by the owner for `guards.unlock_minutes`
11
8
  // - subs: no queue-close/queue-cancel, call budget 90/100, plan edits only inside "## Progress",
@@ -119,33 +116,34 @@ function moveLegacyState(stateDir: string, dir: string): void {
119
116
  }
120
117
 
121
118
  /** This Main's own state dir, `<queue_state>/mains/<id>/`: edit window, rollover notes, running lock. */
122
- export function mainStateDir(cfg?: Config): string {
123
- const stateDir = cfg ? cfg.paths.queue_state : q.stateDirPath();
119
+ export function mainStateDir(cfgOrPaths: Config | Pick<q.QueuePaths, "queue_state">): string {
120
+ const stateDir = "paths" in cfgOrPaths ? cfgOrPaths.paths.queue_state : cfgOrPaths.queue_state;
124
121
  const id = mainId();
125
122
  const dir = path.join(stateDir, "mains", id);
126
123
  if (id === "main") moveLegacyState(stateDir, dir);
127
124
  return dir;
128
125
  }
129
126
 
130
- function windowFile(): string {
131
- return path.join(mainStateDir(), "edit-window.json");
127
+ function windowFile(paths: Pick<q.QueuePaths, "queue_state">): string {
128
+ return path.join(mainStateDir(paths), "edit-window.json");
132
129
  }
133
130
 
134
- export function readWindow(): EditWindow {
131
+ export function readWindow(paths: Pick<q.QueuePaths, "queue_state">): EditWindow {
135
132
  try {
136
- const w = JSON.parse(readFileSync(windowFile(), "utf8")) as Partial<EditWindow>;
133
+ const w = JSON.parse(readFileSync(windowFile(paths), "utf8")) as Partial<EditWindow>;
137
134
  if (Array.isArray(w.used) && typeof w.windowStart === "number")
138
135
  return { used: w.used, windowStart: w.windowStart, mainCalls: typeof w.mainCalls === "number" ? w.mainCalls : 0, mainCallsStart: typeof w.mainCallsStart === "number" ? w.mainCallsStart : 0 };
139
136
  } catch {}
140
137
  return { used: [], windowStart: 0, mainCalls: 0 };
141
138
  }
142
139
 
143
- export function writeWindow(w: EditWindow): void {
140
+ export function writeWindow(w: EditWindow, paths: Pick<q.QueuePaths, "queue_state">): void {
141
+ const file = windowFile(paths);
144
142
  try {
145
- mkdirSync(path.dirname(windowFile()), { recursive: true });
146
- writeFileSync(windowFile(), JSON.stringify(w, null, 1));
143
+ mkdirSync(path.dirname(file), { recursive: true });
144
+ writeFileSync(file, JSON.stringify(w, null, 1));
147
145
  } catch (err) {
148
- log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${windowFile()}: ${err}`);
146
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${file}: ${err}`);
149
147
  }
150
148
  }
151
149
 
@@ -156,13 +154,13 @@ interface MrCache {
156
154
  repos: Record<string, OpenMr[]>;
157
155
  }
158
156
 
159
- function mrCacheFile(): string {
160
- return path.join(q.STATE_DIR, "mr-cache.json");
157
+ function mrCacheFile(paths: Pick<q.QueuePaths, "queue_state">): string {
158
+ return path.join(paths.queue_state, "mr-cache.json");
161
159
  }
162
160
 
163
- function readMrCache(): MrCache {
161
+ function readMrCache(paths: Pick<q.QueuePaths, "queue_state">): MrCache {
164
162
  try {
165
- const c = JSON.parse(readFileSync(mrCacheFile(), "utf8")) as MrCache;
163
+ const c = JSON.parse(readFileSync(mrCacheFile(paths), "utf8")) as MrCache;
166
164
  if (typeof c.at === "number" && c.repos && typeof c.repos === "object") return c;
167
165
  } catch {}
168
166
  return { at: 0, repos: {} };
@@ -170,10 +168,10 @@ function readMrCache(): MrCache {
170
168
 
171
169
  function writeMrCache(c: MrCache, cfg: Config): void {
172
170
  try {
173
- mkdirSync(q.STATE_DIR, { recursive: true });
174
- writeFileSync(mrCacheFile(), JSON.stringify(c, null, 1));
171
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
172
+ writeFileSync(mrCacheFile(cfg.paths), JSON.stringify(c, null, 1));
175
173
  } catch (err) {
176
- log(cfg.paths.guard_log, `cannot write ${mrCacheFile()}: ${err}`);
174
+ log(cfg.paths.guard_log, `cannot write ${mrCacheFile(cfg.paths)}: ${err}`);
177
175
  }
178
176
  }
179
177
 
@@ -192,21 +190,21 @@ interface CodeReview extends PlanReview {
192
190
  phases: string[];
193
191
  }
194
192
 
195
- function planReviewsFile(): string {
196
- return path.join(q.STATE_DIR, "plan-reviews.json");
193
+ function planReviewsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
194
+ return path.join(paths.queue_state, "plan-reviews.json");
197
195
  }
198
196
 
199
- function readPlanReviews(): Record<string, PlanReview> {
197
+ function readPlanReviews(paths: Pick<q.QueuePaths, "queue_state">): Record<string, PlanReview> {
200
198
  try {
201
- const r = JSON.parse(readFileSync(planReviewsFile(), "utf8")) as { reviews?: Record<string, PlanReview> };
199
+ const r = JSON.parse(readFileSync(planReviewsFile(paths), "utf8")) as { reviews?: Record<string, PlanReview> };
202
200
  if (r.reviews && typeof r.reviews === "object") return r.reviews;
203
201
  } catch {}
204
202
  return {};
205
203
  }
206
204
 
207
- function readCodeReviews(): Record<string, CodeReview> {
205
+ function readCodeReviews(paths: Pick<q.QueuePaths, "queue_state">): Record<string, CodeReview> {
208
206
  try {
209
- const r = JSON.parse(readFileSync(planReviewsFile(), "utf8")) as { code?: Record<string, CodeReview> };
207
+ const r = JSON.parse(readFileSync(planReviewsFile(paths), "utf8")) as { code?: Record<string, CodeReview> };
210
208
  if (r.code && typeof r.code === "object") return r.code;
211
209
  } catch {}
212
210
  return {};
@@ -214,10 +212,10 @@ function readCodeReviews(): Record<string, CodeReview> {
214
212
 
215
213
  function writePlanReviews(reviews: Record<string, PlanReview>, code: Record<string, CodeReview>, cfg: Config): void {
216
214
  try {
217
- mkdirSync(q.STATE_DIR, { recursive: true });
218
- writeFileSync(planReviewsFile(), JSON.stringify({ reviews, code }, null, 1));
215
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
216
+ writeFileSync(planReviewsFile(cfg.paths), JSON.stringify({ reviews, code }, null, 1));
219
217
  } catch (err) {
220
- log(cfg.paths.plan_guard_log, `cannot write ${planReviewsFile()}: ${err}`);
218
+ log(cfg.paths.plan_guard_log, `cannot write ${planReviewsFile(cfg.paths)}: ${err}`);
221
219
  }
222
220
  }
223
221
 
@@ -239,7 +237,7 @@ export type Spawner = "main" | "sub";
239
237
  */
240
238
  export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): string | null {
241
239
  if (!cfg.review.plan) return null; // P6: review.plan: false skips the PASS gate; an empty review.agents list no longer does
242
- const reviews = readPlanReviews();
240
+ const reviews = readPlanReviews(cfg.paths);
243
241
  for (const file of named) {
244
242
  if (isReviewSpawn(file, brief, agent, cfg, spawner)) continue;
245
243
  const rec = reviews[file];
@@ -260,12 +258,12 @@ export function reviewPassProblem(named: string[], brief: string, agent: string,
260
258
  function recordReviews(e: PlanEditEvent, cfg: Config): void {
261
259
  const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
262
260
  if (!entries.length) return;
263
- const spawns = readReviewSpawns();
261
+ const spawns = readReviewSpawns(cfg.paths);
264
262
  const found = matchReviewSpawn(spawns, e.agentId ?? "");
265
263
  if (!found) return;
266
264
  const { name, spawn } = found;
267
- const reviews = readPlanReviews();
268
- const code = readCodeReviews();
265
+ const reviews = readPlanReviews(cfg.paths);
266
+ const code = readCodeReviews(cfg.paths);
269
267
  for (const block of entries) {
270
268
  const kind = REVIEW_LINE.exec(block)![1];
271
269
  const repeat = spawn.verdicts > 0;
@@ -284,12 +282,12 @@ function recordReviews(e: PlanEditEvent, cfg: Config): void {
284
282
  } else reviews[e.path] = record;
285
283
  }
286
284
  writePlanReviews(reviews, code, cfg);
287
- writeReviewSpawns(spawns);
285
+ writeReviewSpawns(spawns, cfg.paths);
288
286
  }
289
287
 
290
288
  /** P4k backstop, at a sub agent's end: a named review spawn whose PLAN REVIEW line reached no edit (a path the write targets miss) is recorded here. Returns Main's note when the spawn wrote no verdict at all. */
291
289
  export function reviewSpawnEnd(agentId: string, cfg: Config): string | null {
292
- const found = matchReviewSpawn(readReviewSpawns(), agentId);
290
+ const found = matchReviewSpawn(readReviewSpawns(cfg.paths), agentId);
293
291
  if (!found || found.spawn.verdicts > 0) return null;
294
292
  const { name, spawn } = found;
295
293
  const after = readPlanText(spawn.plan);
@@ -314,7 +312,7 @@ function reviewRole(name: string | undefined, named: string[], brief: string, ag
314
312
  if (reviewed.length && !/^Scope: whole plan\s*$/m.test(brief)) return { plan: null, problem: "a review spawn reviews the whole plan: add the line `Scope: whole plan` to the brief (every unticked phase, one pass; no per-phase reviews)." };
315
313
  const plan = reviewed[0] ?? null;
316
314
  if (plan) {
317
- const rec = readPlanReviews()[plan];
315
+ const rec = readPlanReviews(cfg.paths)[plan];
318
316
  if (rec?.verdict === "PASS" && rec.hash === reviewHash(readPlanText(plan)))
319
317
  return { plan: null, problem: `plan ${plan} already has a current reviewer PASS (by ${rec.by}); a second review is waste. Change the plan text, or spawn the implementer.` };
320
318
  }
@@ -329,22 +327,22 @@ interface ReviewSpawn {
329
327
  verdicts: number;
330
328
  }
331
329
 
332
- function reviewSpawnsFile(): string {
333
- return path.join(q.STATE_DIR, "review-spawns.json");
330
+ function reviewSpawnsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
331
+ return path.join(paths.queue_state, "review-spawns.json");
334
332
  }
335
333
 
336
- function readReviewSpawns(): Record<string, ReviewSpawn> {
334
+ function readReviewSpawns(paths: Pick<q.QueuePaths, "queue_state">): Record<string, ReviewSpawn> {
337
335
  try {
338
- const parsed = JSON.parse(readFileSync(reviewSpawnsFile(), "utf8"));
336
+ const parsed = JSON.parse(readFileSync(reviewSpawnsFile(paths), "utf8"));
339
337
  return parsed && typeof parsed === "object" ? parsed : {};
340
338
  } catch {
341
339
  return {};
342
340
  }
343
341
  }
344
342
 
345
- function writeReviewSpawns(spawns: Record<string, ReviewSpawn>): void {
346
- mkdirSync(q.STATE_DIR, { recursive: true });
347
- writeFileSync(reviewSpawnsFile(), `${JSON.stringify(spawns, null, 2)}\n`);
343
+ function writeReviewSpawns(spawns: Record<string, ReviewSpawn>, paths: Pick<q.QueuePaths, "queue_state">): void {
344
+ mkdirSync(paths.queue_state, { recursive: true });
345
+ writeFileSync(reviewSpawnsFile(paths), `${JSON.stringify(spawns, null, 2)}\n`);
348
346
  }
349
347
 
350
348
  function readPlanText(file: string): string {
@@ -356,13 +354,13 @@ function readPlanText(file: string): string {
356
354
  }
357
355
 
358
356
  /** Set (plan) or drop (null) a named spawn's review role; a non-review spawn under the same name drops it. */
359
- function recordReviewSpawn(name: string, plan: string | null): void {
360
- const spawns = readReviewSpawns();
357
+ function recordReviewSpawn(name: string, plan: string | null, paths: Pick<q.QueuePaths, "queue_state">): void {
358
+ const spawns = readReviewSpawns(paths);
361
359
  if (plan) {
362
360
  const text = readPlanText(plan);
363
361
  spawns[name] = { plan, text, hash: reviewHash(text), verdicts: 0 };
364
362
  } else delete spawns[name];
365
- writeReviewSpawns(spawns);
363
+ writeReviewSpawns(spawns, paths);
366
364
  }
367
365
 
368
366
  /** The review role an agent id belongs to: its spawn name, or the name without a -<digits> suffix (a sub agent's id, plan P4f gap). */
@@ -392,29 +390,29 @@ export function plannerPlanProblem(plan: string): string | null {
392
390
  }
393
391
 
394
392
  /** P2(b): the named planner spawns, spawn name → the one plan path its brief may create and edit (planner-spawns.json in the state dir). Recorded only on an approved spawn: in main mode the spawn gate refused the brief, so a binding exists only for a delegated planner. */
395
- function plannerSpawnsFile(): string {
396
- return path.join(q.STATE_DIR, "planner-spawns.json");
393
+ function plannerSpawnsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
394
+ return path.join(paths.queue_state, "planner-spawns.json");
397
395
  }
398
396
 
399
- function readPlannerSpawns(): Record<string, string> {
397
+ function readPlannerSpawns(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string> {
400
398
  try {
401
- const parsed: unknown = JSON.parse(readFileSync(plannerSpawnsFile(), "utf8"));
399
+ const parsed: unknown = JSON.parse(readFileSync(plannerSpawnsFile(paths), "utf8"));
402
400
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, string>) : {};
403
401
  } catch {
404
402
  return {};
405
403
  }
406
404
  }
407
405
 
408
- function recordPlannerSpawn(name: string, plan: string): void {
409
- const spawns = readPlannerSpawns();
406
+ function recordPlannerSpawn(name: string, plan: string, paths: Pick<q.QueuePaths, "queue_state">): void {
407
+ const spawns = readPlannerSpawns(paths);
410
408
  spawns[name] = plan;
411
- mkdirSync(q.STATE_DIR, { recursive: true });
412
- writeFileSync(plannerSpawnsFile(), `${JSON.stringify(spawns, null, 2)}\n`);
409
+ mkdirSync(paths.queue_state, { recursive: true });
410
+ writeFileSync(plannerSpawnsFile(paths), `${JSON.stringify(spawns, null, 2)}\n`);
413
411
  }
414
412
 
415
413
  /** The plan path the agent's brief named in its `Planner role for` line: its spawn name, or the name without a -<digits> suffix (the P4f id rule); null when no planner role is bound. */
416
- export function plannerSpawnPlan(agentId: string): string | null {
417
- const spawns = readPlannerSpawns();
414
+ export function plannerSpawnPlan(agentId: string, paths: Pick<q.QueuePaths, "queue_state">): string | null {
415
+ const spawns = readPlannerSpawns(paths);
418
416
  for (const name of [agentId, agentId.replace(/-\d+$/, "")]) {
419
417
  const plan = Object.hasOwn(spawns, name) ? spawns[name] : undefined;
420
418
  if (typeof plan === "string" && plan) return plan;
@@ -460,11 +458,11 @@ function reviewShellProblem(command: string, cfg: Config): string | null {
460
458
 
461
459
  /** P4f: a named review spawn may read, use todo, and edit only its own plan. Shell, spawn, cancel and MCP tools are denied; so are secret reads. */
462
460
  function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
463
- const plan = matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan ?? null;
461
+ const plan = matchReviewSpawn(readReviewSpawns(cfg.paths), e.agentId ?? "")?.spawn.plan ?? null;
464
462
  if (!plan) return null;
465
463
  const input = e.input ?? {};
466
464
  if (cfg.guards.write_tools.includes(e.tool)) {
467
- const writes = [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, [])];
465
+ const writes = [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, cfg.paths, [])];
468
466
  if (writes.length && writes.every(w => path.resolve(e.cwd, w) === path.resolve(plan))) return null;
469
467
  return `review spawn ${e.agentId} may edit only its plan ${plan}.`;
470
468
  }
@@ -488,12 +486,12 @@ function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
488
486
  return `review spawn ${e.agentId} may only read, use todo, and edit its plan; ${e.tool} is denied.`;
489
487
  }
490
488
 
491
- function spawnsFile(): string {
492
- return path.join(q.STATE_DIR, "spawns.json");
489
+ function spawnsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
490
+ return path.join(paths.queue_state, "spawns.json");
493
491
  }
494
492
 
495
- function staffingFile(): string {
496
- return path.join(q.STATE_DIR, "staffing.json");
493
+ function staffingFile(paths: Pick<q.QueuePaths, "queue_state">): string {
494
+ return path.join(paths.queue_state, "staffing.json");
497
495
  }
498
496
 
499
497
  // The owner-message store (owner-messages.jsonl) and its matcher live in src/core/incidents.ts
@@ -512,13 +510,13 @@ function recordOwnerMessage(text: string, cfg: Config): void {
512
510
  try {
513
511
  recordOwnerLog(cfg, "owner", owner);
514
512
  } catch (err) {
515
- log(cfg.paths.guard_log, `cannot write ${ownerLogFile()}: ${err}`);
513
+ log(cfg.paths.guard_log, `cannot write ${ownerLogFile(cfg.paths)}: ${err}`);
516
514
  }
517
515
  }
518
516
  try {
519
- writeOwnerStore([...readOwnerMessages(), { at: nowSec(), text }], readOwnerAnswers());
517
+ writeOwnerStore([...readOwnerMessages(cfg.paths), { at: nowSec(), text }], readOwnerAnswers(cfg.paths), cfg.paths);
520
518
  } catch (err) {
521
- log(cfg.paths.guard_log, `cannot write ${ownerMessagesFile()}: ${err}`);
519
+ log(cfg.paths.guard_log, `cannot write ${ownerMessagesFile(cfg.paths)}: ${err}`);
522
520
  }
523
521
  }
524
522
 
@@ -529,9 +527,9 @@ export interface StaffingEntry {
529
527
  }
530
528
 
531
529
  /** plan → its staffing entry (staffing.json). */
532
- export function readStaffingEntries(): Record<string, StaffingEntry> {
530
+ export function readStaffingEntries(paths: Pick<q.QueuePaths, "queue_state">): Record<string, StaffingEntry> {
533
531
  try {
534
- const raw: unknown = JSON.parse(readFileSync(staffingFile(), "utf8"));
532
+ const raw: unknown = JSON.parse(readFileSync(staffingFile(paths), "utf8"));
535
533
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
536
534
  const out: Record<string, StaffingEntry> = {};
537
535
  for (const [k, v] of Object.entries(raw)) {
@@ -547,13 +545,13 @@ export function readStaffingEntries(): Record<string, StaffingEntry> {
547
545
  }
548
546
 
549
547
  /** plan → the task names of its newest spawn (staffing.json); read for the staffed check. */
550
- export function readStaffing(): Record<string, string[]> {
551
- return Object.fromEntries(Object.entries(readStaffingEntries()).map(([f, e]) => [f, e.names]));
548
+ export function readStaffing(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string[]> {
549
+ return Object.fromEntries(Object.entries(readStaffingEntries(paths)).map(([f, e]) => [f, e.names]));
552
550
  }
553
551
 
554
- function readSpawns(): Record<string, string> {
552
+ function readSpawns(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string> {
555
553
  try {
556
- const raw: unknown = JSON.parse(readFileSync(spawnsFile(), "utf8"));
554
+ const raw: unknown = JSON.parse(readFileSync(spawnsFile(paths), "utf8"));
557
555
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
558
556
  const out: Record<string, string> = {};
559
557
  for (const [k, v] of Object.entries(raw)) out[k] = String(v);
@@ -564,28 +562,28 @@ function readSpawns(): Record<string, string> {
564
562
  }
565
563
 
566
564
  /** Remember the "## Progress" hash of the plans an agent was just spawned on. With `staffing`, also record the spawn's task names per plan (staffing.json); a plan's entry is replaced by the newest spawn that names it. */
567
- export function recordSpawns(files: string[], staffing: Record<string, string[]> = {}): void {
568
- const s = readSpawns();
565
+ export function recordSpawns(files: string[], paths: Pick<q.QueuePaths, "queue_state">, staffing: Record<string, string[]> = {}): void {
566
+ const s = readSpawns(paths);
569
567
  for (const f of files) {
570
568
  try {
571
569
  s[f] = q.sha(q.progressBody(readFileSync(f, "utf8")));
572
570
  } catch {}
573
571
  }
574
572
  try {
575
- mkdirSync(q.STATE_DIR, { recursive: true });
576
- writeFileSync(spawnsFile(), JSON.stringify(s, null, 1));
573
+ mkdirSync(paths.queue_state, { recursive: true });
574
+ writeFileSync(spawnsFile(paths), JSON.stringify(s, null, 1));
577
575
  } catch (err) {
578
- log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${spawnsFile()}: ${err}`);
576
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${spawnsFile(paths)}: ${err}`);
579
577
  }
580
578
  if (!Object.keys(staffing).length) return;
581
- const st = readStaffingEntries();
579
+ const st = readStaffingEntries(paths);
582
580
  const at = nowSec();
583
581
  for (const [f, names] of Object.entries(staffing)) if (names.length) st[f] = { names: [...names], at };
584
582
  try {
585
- mkdirSync(q.STATE_DIR, { recursive: true });
586
- writeFileSync(staffingFile(), JSON.stringify(st, null, 1));
583
+ mkdirSync(paths.queue_state, { recursive: true });
584
+ writeFileSync(staffingFile(paths), JSON.stringify(st, null, 1));
587
585
  } catch (err) {
588
- log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${staffingFile()}: ${err}`);
586
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${staffingFile(paths)}: ${err}`);
589
587
  }
590
588
  }
591
589
 
@@ -605,13 +603,13 @@ export function rekeySpawns(spawns: Record<string, string>, file: string, before
605
603
  }
606
604
 
607
605
  /** Apply rekeySpawns to the stored spawn hashes. */
608
- export function rekeySpawnFile(file: string, before: string, after: string): void {
609
- const s = readSpawns();
606
+ export function rekeySpawnFile(file: string, before: string, after: string, paths: Pick<q.QueuePaths, "queue_state">): void {
607
+ const s = readSpawns(paths);
610
608
  if (!rekeySpawns(s, file, before, after)) return;
611
609
  try {
612
- writeFileSync(spawnsFile(), JSON.stringify(s, null, 1));
610
+ writeFileSync(spawnsFile(paths), JSON.stringify(s, null, 1));
613
611
  } catch (err) {
614
- log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${spawnsFile()}: ${err}`);
612
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${spawnsFile(paths)}: ${err}`);
615
613
  }
616
614
  }
617
615
 
@@ -626,12 +624,12 @@ export function briefBudget(brief: string): number | null {
626
624
  return m ? Number(m[1]) : null;
627
625
  }
628
626
 
629
- function budgetsFile(): string {
630
- return path.join(q.STATE_DIR, "spawn-budgets.json");
627
+ function budgetsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
628
+ return path.join(paths.queue_state, "spawn-budgets.json");
631
629
  }
632
630
 
633
631
  /** The budgets recorded at spawn: task name → calls (next to the spawn hashes). */
634
- export function readBudgets(dir: string = q.STATE_DIR): Record<string, number> {
632
+ export function readBudgets(dir: string): Record<string, number> {
635
633
  try {
636
634
  const raw: unknown = JSON.parse(readFileSync(path.join(dir, "spawn-budgets.json"), "utf8"));
637
635
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
@@ -644,26 +642,26 @@ export function readBudgets(dir: string = q.STATE_DIR): Record<string, number> {
644
642
  }
645
643
 
646
644
  /** Remember the named tasks' call budgets; a name's old budget is replaced, a null one removed. */
647
- export function recordBudgets(entries: Record<string, number | null>): void {
645
+ export function recordBudgets(entries: Record<string, number | null>, paths: Pick<q.QueuePaths, "queue_state">): void {
648
646
  const names = Object.keys(entries);
649
647
  if (!names.length) return;
650
- const budgets = readBudgets();
648
+ const budgets = readBudgets(paths.queue_state);
651
649
  for (const n of names) {
652
650
  const b = entries[n];
653
651
  if (b == null) delete budgets[n];
654
652
  else budgets[n] = b;
655
653
  }
656
654
  try {
657
- mkdirSync(q.STATE_DIR, { recursive: true });
658
- writeFileSync(budgetsFile(), JSON.stringify(budgets, null, 1));
655
+ mkdirSync(paths.queue_state, { recursive: true });
656
+ writeFileSync(budgetsFile(paths), JSON.stringify(budgets, null, 1));
659
657
  } catch (err) {
660
- log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${budgetsFile()}: ${err}`);
658
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${budgetsFile(paths)}: ${err}`);
661
659
  }
662
660
  }
663
661
 
664
662
  /** A sub's hard call cap: the budget recorded for its task name at spawn, else the global cap. */
665
663
  export function subCallCap(agentId: string, cfg: Config): number {
666
- return readBudgets()[agentId] ?? cfg.guards.sub_max_calls;
664
+ return readBudgets(cfg.paths.queue_state)[agentId] ?? cfg.guards.sub_max_calls;
667
665
  }
668
666
 
669
667
  // --- shared pieces ---
@@ -671,7 +669,7 @@ export function subCallCap(agentId: string, cfg: Config): number {
671
669
  /** Epoch ms when the owner's open unlock window closes, or null when the guard is locked. */
672
670
  function unlockUntilMs(cfg: Config): number | null {
673
671
  try {
674
- const until = statSync(q.UNLOCK).mtimeMs + cfg.guards.unlock_minutes * 60_000;
672
+ const until = statSync(cfg.paths.unlock).mtimeMs + cfg.guards.unlock_minutes * 60_000;
675
673
  return Date.now() < until ? until : null;
676
674
  } catch {
677
675
  return null;
@@ -690,7 +688,7 @@ function unlockLine(cfg: Config): string {
690
688
  }
691
689
 
692
690
  function protectedHit(paths: string[], cfg: Config): string | null {
693
- const hit = q.protectedHit(paths);
691
+ const hit = q.protectedHit(paths, cfg.paths);
694
692
  if (hit) return hit;
695
693
  for (const p of paths) {
696
694
  for (const raw of cfg.guards.protected) {
@@ -715,7 +713,7 @@ export function isProjectPath(p: string, cfg: Config): boolean {
715
713
  return (
716
714
  roots.some(r => p.startsWith(r) && p.length > r.length) &&
717
715
  !free.some(f => p.startsWith(f) || `${p}/` === f) &&
718
- !q.isOrchestrationPath(p)
716
+ !q.isOrchestrationPath(p, q.activePlans(cfg.paths), cfg.paths.queue_index)
719
717
  );
720
718
  }
721
719
 
@@ -724,7 +722,7 @@ export function isProjectPath(p: string, cfg: Config): boolean {
724
722
  // cherry-pick, worktree) and paths merely mentioned in a body or command are free.
725
723
  export function changedProjectFiles(toolName: string, input: Record<string, unknown>, cwd: string, cfg: Config): string[] {
726
724
  return q
727
- .writeTargets(toolName, input ?? {}, cwd)
725
+ .writeTargets(toolName, input ?? {}, cwd, cfg.paths)
728
726
  .filter(p => !freeExt(cfg).test(p) && isProjectPath(p, cfg));
729
727
  }
730
728
 
@@ -754,15 +752,15 @@ function newlyTicked(before: string, after: string): string[] {
754
752
  }
755
753
 
756
754
  /** The open plans the text names — a `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3), so only the remaining text decides. planGate's targeting, shared with the spawn verdict's brief-lint and cap notes (plan 20261031_1207 P4). */
757
- function briefPlans(text: string, cfg?: Config): Plan[] {
755
+ function briefPlans(text: string, cfg: Config): Plan[] {
758
756
  const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
759
- return q.activePlans(undefined, undefined, cfg?.review.agents ?? []).filter(p => body.includes(p.file));
757
+ return q.activePlans(cfg.paths, cfg.review.agents).filter(p => body.includes(p.file));
760
758
  }
761
759
 
762
760
  // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
763
- export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
764
- const plans = q.activePlans(undefined, undefined, cfg?.review.agents ?? []);
765
- const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p));
761
+ export function planGate(text: string, label: string, cfg: Config): [string | null, string[]] {
762
+ const plans = q.activePlans(cfg.paths, cfg.review.agents);
763
+ const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p, cfg.paths));
766
764
  if (unclosed.length)
767
765
  return [
768
766
  `${label}: ${unclosed.map(p => `${p.file} (${p.status})`).join(", ")} is still indexed. Verify it and run \`queue-close <plan>\` before any new spawn.`,
@@ -771,7 +769,7 @@ export function planGate(text: string, label: string, cfg?: Config): [string | n
771
769
  const named = briefPlans(text, cfg);
772
770
  if (!named.length)
773
771
  return [
774
- `${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in ${q.INDEX}.`,
772
+ `${label}: an implementer needs an open plan. Name the plan's absolute path in the brief; the plan must be listed in ${cfg.paths.queue_index}.`,
775
773
  [],
776
774
  ];
777
775
  if (RESEARCH_ASK.test(text) && PLAN_WRITE.test(text))
@@ -782,31 +780,29 @@ export function planGate(text: string, label: string, cfg?: Config): [string | n
782
780
  // P5 (plan 20261031_0911): a landed open plan whose auto-close failed locks the queue — every
783
781
  // brief must name it, so the next spawn works on closing it instead of around it. A named
784
782
  // locked plan skips the unticked-phase checks below: its work has landed, the job is the close.
785
- const locked = plans.filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file));
783
+ const locked = plans.filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file, cfg.paths));
786
784
  for (const s of locked) {
787
785
  if (named.some(n => n.file === s.file)) continue;
788
786
  return [
789
- `${label}: ${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file) ?? "").replace(/^queue-close: /, "")}). The queue is locked on it: name this plan in the brief and fix the close before any other spawn.`,
787
+ `${label}: ${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file, cfg.paths) ?? "").replace(/^queue-close: /, "")}). The queue is locked on it: name this plan in the brief and fix the close before any other spawn.`,
790
788
  [],
791
789
  ];
792
790
  }
793
- const spawns = readSpawns();
791
+ const spawns = readSpawns(cfg.paths);
794
792
  for (const p of named) {
795
793
  if (p.errors.length) return [`${label}: plan ${p.file} is not ready (${p.errors.join("; ")}).`, []];
796
794
  if (p.waiting) return [`${label}: plan ${p.file} is parked "WAITING on owner".`, []];
797
795
  if (p.status !== "open") return [`${label}: plan ${p.file} says "Status: ${p.status}".`, []];
798
- const cancelled = q.cancelledMatches(p);
799
- if (cancelled.length) return [`${label}: plan ${p.file} ${q.cancelledProblem(p, cancelled[0]!)}`, []];
796
+ const cancelled = q.cancelledMatches(p, cfg.paths);
797
+ if (cancelled.length) return [`${label}: plan ${p.file} ${q.cancelledProblem(p, cancelled[0]!, cfg.paths)}`, []];
800
798
  const before = spawns[p.file];
801
799
  if (before && before === q.sha(q.progressBody(p.text)))
802
800
  return [
803
801
  `${label}: plan ${p.file} has no new "## Progress" entry since the last agent ran on it. Write that run's progress (from its report) into the plan first.`,
804
802
  [],
805
803
  ];
806
- if (cfg) {
807
- const approval = approvalProblem(p.text, p.file, cfg.pages.dir, cfg.approval.since);
808
- if (approval) return [approval, []];
809
- }
804
+ const approval = approvalProblem(p.text, p.file, cfg.pages.dir, cfg.approval.since, cfg.paths);
805
+ if (approval) return [approval, []];
810
806
  const open = unticked(p);
811
807
  // A locked plan's work has landed: closing it is the job, there is no phase left to tick.
812
808
  if (locked.some(l => l.file === p.file)) continue;
@@ -836,9 +832,9 @@ export interface PriorityOutcome {
836
832
  const SKIP_LINE = /^\s*(?:[-*]\s+)?priority skip:\s*(.+?)\s+[—–-]\s*(.+?)\s*$/gim;
837
833
 
838
834
  /** One plan is idle when a subagent could start on it right now: open, no owner hold, not awaiting merge, no template errors, an unticked phase left, and not waiting on another open plan of the active index. */
839
- function priorityIdle(p: Plan, plans: Plan[]): boolean {
835
+ function priorityIdle(p: Plan, plans: Plan[], paths?: Pick<q.QueuePaths, "queue_state">): boolean {
840
836
  if (p.waitsOn.some(f => plans.some(w => w.file === f && w.status === "open"))) return false;
841
- return p.status === "open" && !p.waiting && !q.awaitingMerge(p) && !p.errors.length && unticked(p).length > 0;
837
+ return p.status === "open" && !p.waiting && !(paths ? q.awaitingMerge(p, paths) : false) && !p.errors.length && unticked(p).length > 0;
842
838
  }
843
839
 
844
840
  /**
@@ -869,11 +865,11 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
869
865
  if (plan && why) skipLines[plan] = why;
870
866
  }
871
867
  const skips: PrioritySkip[] = [];
872
- const cache = readMrCache();
868
+ const cache = cfg ? readMrCache(cfg.paths) : { at: 0, repos: {} };
873
869
  const fresh = cfg ? now - cache.at < cfg.review.mr_cache_minutes * 60 : false;
874
870
  for (let i = 0; i < higher.length; i++) {
875
871
  const p = higher[i]!;
876
- if (!priorityIdle(p, plans) || staffed.includes(p.file)) continue;
872
+ if (!priorityIdle(p, plans, cfg?.paths) || staffed.includes(p.file)) continue;
877
873
  if (fresh && p.branch && (cache.repos[p.repo] ?? []).some(mr => mr.branch === p.branch)) continue;
878
874
  const why = skipLines[p.file];
879
875
  // Tier full (20261025_1940 P2): Main's own >= 4-word reason is proof enough; every other
@@ -896,7 +892,7 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
896
892
  /** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. P8 (I-20261031-353): the plans a Main-authored brief reviews drop out first — a plan waiting for its reviewer is not a priority slot, so a call naming only reviewed plans passes with no skip line; implementer plans keep the gate. */
897
893
  function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string, agent: string, spawner: Spawner): string | null {
898
894
  const implementer = named.filter(f => !isReviewSpawn(f, brief, agent, cfg, spawner));
899
- const outcome = priorityProblem(q.activePlans(), implementer, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief, readOwnerMessages(), nowSec(), cfg);
895
+ const outcome = priorityProblem(q.activePlans(cfg.paths), implementer, runningJobs === undefined ? undefined : staffedPlans(readStaffing(cfg.paths), runningJobs), brief, readOwnerMessages(cfg.paths), nowSec(), cfg);
900
896
  if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
901
897
  for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
902
898
  return outcome?.problem ? `${label}: ${outcome.problem}` : null;
@@ -924,9 +920,9 @@ function worktreeBranch(wt: string | null, run: CommandRunner): string | null {
924
920
  * no merge target: both checks skip it with one guard-log line.
925
921
  */
926
922
  export function pendingWorkProblem(named: string[], brief: string, cfg: Config, run: CommandRunner = defaultRunner): string | null {
927
- const plans = q.activePlans().filter(p => named.includes(p.file));
923
+ const plans = q.activePlans(cfg.paths).filter(p => named.includes(p.file));
928
924
  if (!plans.length) return null;
929
- const cache = readMrCache();
925
+ const cache = readMrCache(cfg.paths);
930
926
  const fresh = nowSec() - cache.at < cfg.review.mr_cache_minutes * 60;
931
927
  const openMrs = new Map<string, OpenMr[]>();
932
928
  const hasOrigin = new Set<string>();
@@ -1061,7 +1057,7 @@ export function spawnProblem(
1061
1057
  const plannerRoles: Record<string, string> = {};
1062
1058
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
1063
1059
  const context = String(input?.context ?? "");
1064
- const allowed = q.allowedAgents();
1060
+ const allowed = q.allowedAgents(cfg.paths.subagents);
1065
1061
  const shared = briefBudget(context);
1066
1062
  const problems: string[] = [];
1067
1063
  const named: Record<string, number | null> = {};
@@ -1091,14 +1087,14 @@ export function spawnProblem(
1091
1087
  }
1092
1088
  if (plannerFor) {
1093
1089
  if (!allowed.has(agent)) {
1094
- problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
1090
+ problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`);
1095
1091
  continue;
1096
1092
  }
1097
1093
  plannerRoles[label] = plannerFor;
1098
1094
  continue;
1099
1095
  }
1100
1096
  if (!allowed.has(agent)) {
1101
- problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
1097
+ problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`);
1102
1098
  continue;
1103
1099
  }
1104
1100
  const [why, plans] = planGate(text, label, cfg);
@@ -1165,8 +1161,8 @@ export function spawnProblem(
1165
1161
  cfg,
1166
1162
  );
1167
1163
  if (verdict) return verdict;
1168
- for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan);
1169
- for (const [name, plan] of Object.entries(plannerRoles)) recordPlannerSpawn(name, plan);
1164
+ for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan, cfg.paths);
1165
+ for (const [name, plan] of Object.entries(plannerRoles)) recordPlannerSpawn(name, plan, cfg.paths);
1170
1166
  return null;
1171
1167
  }
1172
1168
 
@@ -1174,7 +1170,7 @@ function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): stri
1174
1170
  // A caller staffed on a different plan (staffing.json holds the task names, keyed by agentId)
1175
1171
  // only grazes this plan (I-20261028-111): its path blockers must judge the covered paths,
1176
1172
  // not every path the command names.
1177
- const staffing = readStaffing();
1173
+ const staffing = readStaffing(cfg.paths);
1178
1174
  const foreign = !(staffing[plan.file] ?? []).includes(e.agentId) && Object.entries(staffing).some(([f, names]) => f !== plan.file && names.includes(e.agentId));
1179
1175
  for (const b of plan.blockers) {
1180
1176
  try {
@@ -1370,12 +1366,12 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
1370
1366
  // planner-spawns binding). A NEW plan file is invisible to the indexed-plan gate below
1371
1367
  // (isOrchestrationPath + planAt both false), so the refusal fires here — never by accident of
1372
1368
  // indexing — and covers shell redirects through writeTargets too.
1373
- const delegatedPlanner = currentPlanner(cfg) === "delegated" ? plannerSpawnPlan(e.agentId) : null;
1369
+ const delegatedPlanner = currentPlanner(cfg) === "delegated" ? plannerSpawnPlan(e.agentId, cfg.paths) : null;
1374
1370
  // I-20261102-27: the seam above also refused the REVIEW spawn, and a review spawn's only write
1375
1371
  // is its own PLAN REVIEW / CODE REVIEW line — so in delegated mode no plan could ever record a
1376
1372
  // PASS and no implementer could spawn. The named review spawn of a plan may still write that
1377
1373
  // plan; the REVIEW_LINE rule below then decides whether the line is its verdict.
1378
- const delegatedReview = currentPlanner(cfg) === "delegated" ? (matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan ?? null) : null;
1374
+ const delegatedReview = currentPlanner(cfg) === "delegated" ? (matchReviewSpawn(readReviewSpawns(cfg.paths), e.agentId ?? "")?.spawn.plan ?? null) : null;
1379
1375
  if (currentPlanner(cfg) === "delegated") {
1380
1376
  for (const p of writes) {
1381
1377
  if (!MAIN_PLAN_FILE.test(p) || p === delegatedPlanner) continue;
@@ -1384,7 +1380,7 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
1384
1380
  return `planner is delegated — plan files are the planner agent's; your brief carries no "Planner role for <plan path>" line, so ${p} is refused.`;
1385
1381
  }
1386
1382
  }
1387
- const plans = q.activePlans();
1383
+ const plans = q.activePlans(cfg.paths);
1388
1384
  if (e.calls >= cap) {
1389
1385
  // Plan edit targets come from writeTargets (write and structured/hashline edit)
1390
1386
  // with touchedPaths as fallback; plan reads match any read tool.
@@ -1397,7 +1393,7 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
1397
1393
  }
1398
1394
  if (!plans.length || !paths.length) return null;
1399
1395
  for (const p of writes) {
1400
- if (!q.isOrchestrationPath(p, plans)) continue;
1396
+ if (!q.isOrchestrationPath(p, plans, cfg.paths.queue_index)) continue;
1401
1397
  if (!q.planAt(p, plans)) {
1402
1398
  // planner mode P2 (b): the bound planner plan routes into checkPlanEdit (Planner header,
1403
1399
  // Main-only lines), it is not Main's — but only that path, and only while delegated.
@@ -1408,7 +1404,7 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
1408
1404
  return `${p} is a plan file: change its "## Progress" section only with the edit or write tool.`;
1409
1405
  }
1410
1406
  for (const plan of plans) {
1411
- const hit = paths.filter(p => !q.isOrchestrationPath(p, plans) && q.planCovers(plan, p, plans));
1407
+ const hit = paths.filter(p => !q.isOrchestrationPath(p, plans, cfg.paths.queue_index) && q.planCovers(plan, p, plans));
1412
1408
  if (!hit.length) continue;
1413
1409
  // An invalid plan stops code writes, not reads and not the repair of plan files: refusing those
1414
1410
  // too left a planner unable to fix the very errors the guard named (writes are checked before
@@ -1440,7 +1436,7 @@ function editWindow(e: ToolEvent, input: Record<string, unknown>, cfg: Config):
1440
1436
  const limit = tier === "strict" ? cfg.autonomy.strict_edit_limit : cfg.guards.main_edit_limit;
1441
1437
  const limitName = tier === "strict" ? "autonomy.strict_edit_limit" : "owner limit";
1442
1438
  const now = Date.now();
1443
- const w = readWindow();
1439
+ const w = readWindow(cfg.paths);
1444
1440
  if (w.used.length && now - w.windowStart >= cfg.guards.main_window_min * 60_000) w.used = [];
1445
1441
  if (w.used.length >= limit) {
1446
1442
  const mins = Math.ceil((w.windowStart + cfg.guards.main_window_min * 60_000 - now) / 60_000);
@@ -1448,13 +1444,13 @@ function editWindow(e: ToolEvent, input: Record<string, unknown>, cfg: Config):
1448
1444
  return deny(
1449
1445
  `main-guard: tier ${tier} — Main already changed project files ${w.used.length} times in this ${cfg.guards.main_window_min}-minute window ` +
1450
1446
  `(${limitName} ${limit}; resets in ${mins} min). Main writes plans, not code: put the work in a plan ` +
1451
- `(listed in ${q.INDEX}, phase-0 blockers first) and spawn an implementer. Changes so far: ${w.used.join(", ")}`,
1447
+ `(listed in ${cfg.paths.queue_index}, phase-0 blockers first) and spawn an implementer. Changes so far: ${w.used.join(", ")}`,
1452
1448
  "main.edit-window",
1453
1449
  );
1454
1450
  }
1455
1451
  if (!w.used.length) w.windowStart = now;
1456
1452
  w.used.push(`${e.tool}:${files[0]!}`);
1457
- writeWindow(w);
1453
+ writeWindow(w, cfg.paths);
1458
1454
  const left = limit - w.used.length;
1459
1455
  if (left <= 2)
1460
1456
  return {
@@ -1505,7 +1501,7 @@ function incidentSpawnProblem(label: string, brief: string, namedPlans: string[]
1505
1501
  log(cfg.paths.guard_log, `BLOCK ${label}: open incidents: ${ids}`);
1506
1502
  return (
1507
1503
  `open incident(s) ${ids} must be acted on before other work. Write a plan that contains "INCIDENT <id>" ` +
1508
- `(listed in ${q.INDEX}) and record it: \`neurastream incident plan <id> <plan.md>\`, or dismiss the ` +
1504
+ `(listed in ${cfg.paths.queue_index}) and record it: \`neurastream incident plan <id> <plan.md>\`, or dismiss the ` +
1509
1505
  'incident: `neurastream incident dismiss <id> --why "<text>"`. Fix work goes through: name that plan in the brief.'
1510
1506
  );
1511
1507
  }
@@ -1515,7 +1511,7 @@ function incidentSpawnProblem(label: string, brief: string, namedPlans: string[]
1515
1511
  * both come through here (plan 20261028_1600 P4i). Returns the refusal, or null.
1516
1512
  */
1517
1513
  function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: string[] | undefined, spawner: Spawner, runs?: RunSource): string | null {
1518
- const pending = q.cancelPending();
1514
+ const pending = q.cancelPending(cfg.paths);
1519
1515
  if (pending) {
1520
1516
  log(cfg.paths.guard_log, `BLOCK spawn: cancel pending (${pending.words})`);
1521
1517
  return `${CANCEL_TODO} Flagged: "${pending.words}"`;
@@ -1543,8 +1539,8 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
1543
1539
  log(cfg.paths.guard_log, `BLOCK spawn: ${held}`);
1544
1540
  return held;
1545
1541
  }
1546
- recordSpawns(files, staffing);
1547
- recordBudgets(budgets);
1542
+ recordSpawns(files, cfg.paths, staffing);
1543
+ recordBudgets(budgets, cfg.paths);
1548
1544
  return null;
1549
1545
  }
1550
1546
 
@@ -1555,7 +1551,7 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
1555
1551
  function bypassLaunch(command: string, cfg: Config, spawner: Spawner, runs?: RunSource): string | null {
1556
1552
  for (const entry of cfg.guards.bypass_spawn) {
1557
1553
  if (!bypassRegExp(entry).test(command)) continue;
1558
- const pending = q.cancelPending();
1554
+ const pending = q.cancelPending(cfg.paths);
1559
1555
  if (pending) {
1560
1556
  log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
1561
1557
  return `${CANCEL_TODO} Flagged: "${pending.words}"`;
@@ -1579,7 +1575,7 @@ function bypassLaunch(command: string, cfg: Config, spawner: Spawner, runs?: Run
1579
1575
  log(cfg.paths.guard_log, `BLOCK bypass launch: ${held}`);
1580
1576
  return held;
1581
1577
  }
1582
- if (named.length) recordSpawns(named);
1578
+ if (named.length) recordSpawns(named, cfg.paths);
1583
1579
  }
1584
1580
  return null;
1585
1581
  }
@@ -1631,7 +1627,7 @@ function mainCallsExpired(w: EditWindow): boolean {
1631
1627
  /** Refusal once this turn has spent main_max_calls, or null. */
1632
1628
  function mainCallStop(e: ToolEvent, cfg: Config): string | null {
1633
1629
  if (!mainCallApplies(e, cfg)) return null;
1634
- const w = readWindow();
1630
+ const w = readWindow(cfg.paths);
1635
1631
  if (w.mainCalls >= cfg.guards.main_max_calls && !mainCallsExpired(w))
1636
1632
  return `main-guard: call ${w.mainCalls}/${cfg.guards.main_max_calls} since the owner's last message or your last hand-back (guards.main_max_calls); the count starts over ${Math.ceil((MAIN_CALLS_RESET_SEC - (nowSec() - (w.mainCallsStart ?? 0))) / 60)} min from now. End your turn with the answer, or spawn an implementer.`;
1637
1633
  return null;
@@ -1640,13 +1636,13 @@ function mainCallStop(e: ToolEvent, cfg: Config): string | null {
1640
1636
  /** Count one allowed, non-exempt call; returns the warn-band inject at main_warn_calls, "" below it. */
1641
1637
  function mainCallWarn(e: ToolEvent, cfg: Config): string {
1642
1638
  if (!mainCallApplies(e, cfg)) return "";
1643
- const w = readWindow();
1639
+ const w = readWindow(cfg.paths);
1644
1640
  if (w.mainCalls === 0 || mainCallsExpired(w)) {
1645
1641
  w.mainCalls = 0;
1646
1642
  w.mainCallsStart = nowSec();
1647
1643
  }
1648
1644
  w.mainCalls += 1;
1649
- writeWindow(w);
1645
+ writeWindow(w, cfg.paths);
1650
1646
  if (w.mainCalls >= cfg.guards.main_warn_calls)
1651
1647
  return `main-guard: call ${w.mainCalls}/${cfg.guards.main_max_calls} this turn (guards.main_warn_calls). End your turn with the answer, or spawn an implementer.`;
1652
1648
  return "";
@@ -1654,11 +1650,11 @@ function mainCallWarn(e: ToolEvent, cfg: Config): string {
1654
1650
 
1655
1651
  /** Main's terminal hand-back (the adapter's agent_end without willContinue): the turn is over, so
1656
1652
  * the next one starts at 0 calls. The edit window keeps its own reset rules. */
1657
- export function resetMainCalls(): void {
1658
- const w = readWindow();
1653
+ export function resetMainCalls(paths: Pick<q.QueuePaths, "queue_state">): void {
1654
+ const w = readWindow(paths);
1659
1655
  if (w.mainCalls === 0) return;
1660
1656
  w.mainCalls = 0;
1661
- writeWindow(w);
1657
+ writeWindow(w, paths);
1662
1658
  }
1663
1659
 
1664
1660
  /** A live plan file (archived plans excluded); Main's plan-text checks run on these. Subfolders like docs/plans/immediate/ hold live plans too. */
@@ -1710,7 +1706,7 @@ function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
1710
1706
  for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
1711
1707
  const writes: string[] = [];
1712
1708
  const relative: string[] = [];
1713
- for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, relative)]) if (!writes.includes(p)) writes.push(p);
1709
+ for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd, cfg.paths, relative)]) if (!writes.includes(p)) writes.push(p);
1714
1710
  // A relative plan path resolves against cwd to a file that does not exist, so the plan gate never
1715
1711
  // sees the edit (plan 20261028_1600 P4j). A plan is named by its absolute path, for every agent.
1716
1712
  const relPlan = PLAN_WRITE_TOOLS[e.tool] ? relative.find(isPlanName) : undefined;
@@ -1745,9 +1741,9 @@ function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
1745
1741
  // The plan index (plan 20261031_0911 P2) is guard surface like the rest, but unlike the
1746
1742
  // others an agent has a sanctioned way to change it: the queue add/move CLI through
1747
1743
  // writeIndex. Name it, so the refusal says what to do instead of naming the unlock.
1748
- const viaQueue = hit === q.INDEX ? ` Plans enter the index or move within it through \`neurastream queue add\` / \`neurastream queue move\`.` : "";
1744
+ const viaQueue = hit === cfg.paths.queue_index ? ` Plans enter the index or move within it through \`neurastream queue add\` / \`neurastream queue move\`.` : "";
1749
1745
  return deny(
1750
- `plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${q.UNLOCK}\` in a terminal${
1746
+ `plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${cfg.paths.unlock}\` in a terminal${
1751
1747
  cfg.guards.chat_unlock ? `, or type \`unlock ${cfg.guards.unlock_minutes}\` in chat` : ""
1752
1748
  }, valid ${cfg.guards.unlock_minutes} min).${viaQueue}`,
1753
1749
  "tool.protected",
@@ -1763,14 +1759,14 @@ function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
1763
1759
  }
1764
1760
  const stop = mainCallStop(e, cfg);
1765
1761
  if (stop) {
1766
- log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${readWindow().mainCalls} calls this turn rule=main.call-budget`);
1762
+ log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${readWindow(cfg.paths).mainCalls} calls this turn rule=main.call-budget`);
1767
1763
  return deny(stop, "main.call-budget");
1768
1764
  }
1769
1765
  const d = mainTool(e, input, cfg, runs);
1770
1766
  if (!d.allow) return d;
1771
1767
  const warn = mainCallWarn(e, cfg);
1772
1768
  // A task brief names paths it does not read; only the other tools' paths count as reads.
1773
- if (e.tool !== "task") recordMainReads(paths.filter(p => !writes.includes(p)));
1769
+ if (e.tool !== "task") recordMainReads(paths.filter(p => !writes.includes(p)), cfg.paths);
1774
1770
  return warn ? { ...d, inject: d.inject ? `${d.inject}\n${warn}` : warn } : d;
1775
1771
  }
1776
1772
  const cap = subCallCap(e.agentId, cfg);
@@ -1805,8 +1801,8 @@ function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
1805
1801
  const MAIN_READ_KEEP_MS = 7 * 86_400_000;
1806
1802
  const GREP_LINE = /^([^\s:]+):\d+:/gm;
1807
1803
  /** Logs existing files as read now; entries older than 7 days are dropped on each write. */
1808
- function recordMainReads(files: string[], now = Date.now()): void {
1809
- const file = path.join(q.STATE_DIR, "main-reads.json");
1804
+ function recordMainReads(files: string[], paths: Pick<q.QueuePaths, "queue_state">, now = Date.now()): void {
1805
+ const file = path.join(paths.queue_state, "main-reads.json");
1810
1806
  const existing = files.filter(f => {
1811
1807
  try {
1812
1808
  return statSync(f).isFile();
@@ -1825,7 +1821,7 @@ function recordMainReads(files: string[], now = Date.now()): void {
1825
1821
  const cutoff = now - MAIN_READ_KEEP_MS;
1826
1822
  for (const [f, t] of Object.entries(reads)) if (!(Date.parse(t) >= cutoff)) delete reads[f];
1827
1823
  try {
1828
- mkdirSync(q.STATE_DIR, { recursive: true });
1824
+ mkdirSync(paths.queue_state, { recursive: true });
1829
1825
  writeFileSync(file, JSON.stringify(reads, null, 2));
1830
1826
  } catch {}
1831
1827
  }
@@ -1837,19 +1833,19 @@ function recordMainReads(files: string[], now = Date.now()): void {
1837
1833
  export function revertMainEdit(tool: string, input: Record<string, unknown>, cwd: string, cfg: Config): void {
1838
1834
  const files = changedProjectFiles(tool, input, cwd, cfg);
1839
1835
  if (!files.length) return;
1840
- const w = readWindow();
1836
+ const w = readWindow(cfg.paths);
1841
1837
  const entry = `${tool}:${files[0]!}`;
1842
1838
  const idx = w.used.lastIndexOf(entry);
1843
1839
  if (idx >= 0) {
1844
1840
  w.used.splice(idx, 1);
1845
- writeWindow(w);
1841
+ writeWindow(w, cfg.paths);
1846
1842
  }
1847
1843
  }
1848
1844
 
1849
- export function recordMainResult(tool: string, input: Record<string, unknown>, cwd: string, text: string): void {
1845
+ export function recordMainResult(tool: string, input: Record<string, unknown>, cwd: string, text: string, paths: Pick<q.QueuePaths, "queue_state">): void {
1850
1846
  const base = typeof input.cwd === "string" ? path.resolve(cwd, q.expandHome(input.cwd)) : cwd;
1851
1847
  const dir = q.shellCwd(String(input.command ?? input.code ?? ""), base);
1852
- recordMainReads([...text.matchAll(GREP_LINE)].map(m => path.resolve(dir, m[1] ?? "")));
1848
+ recordMainReads([...text.matchAll(GREP_LINE)].map(m => path.resolve(dir, m[1] ?? "")), paths);
1853
1849
  }
1854
1850
 
1855
1851
  /**
@@ -2034,14 +2030,14 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
2034
2030
  }
2035
2031
 
2036
2032
  function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = defaultRunner, runs?: RunSource): Decision {
2037
- const pending = q.cancelPending();
2033
+ const pending = q.cancelPending(cfg.paths);
2038
2034
  if (pending) {
2039
2035
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: cancel pending (${pending.words}) rule=spawn.cancel-pending`);
2040
2036
  return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`, "spawn.cancel-pending");
2041
2037
  }
2042
- const allowed = q.allowedAgents();
2038
+ const allowed = q.allowedAgents(cfg.paths.subagents);
2043
2039
  if (!allowed.has(e.agent))
2044
- return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`, "spawn.agent-allowed");
2040
+ return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${cfg.paths.subagents} (no expensive or unpinned models).`, "spawn.agent-allowed");
2045
2041
  if (e.invocationKind !== "task")
2046
2042
  return deny("main-guard: spawn implementers with the task tool (the plan gate checks its brief).", "spawn.task-tool");
2047
2043
  // P4 (plan 20261031_1207): every gate's refusal lands in one numbered verdict; nothing
@@ -2089,10 +2085,10 @@ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = def
2089
2085
  // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
2090
2086
  const staffing: Record<string, string[]> = {};
2091
2087
  for (const f of named) staffing[f] = [e.agent];
2092
- recordSpawns(named, staffing);
2093
- if (e.name) recordReviewSpawn(e.name, role.plan);
2088
+ recordSpawns(named, cfg.paths, staffing);
2089
+ if (e.name) recordReviewSpawn(e.name, role.plan, cfg.paths);
2094
2090
  // planner mode P2 (b): the approved planner spawn binds its name to the plan its brief named.
2095
- if (delegatedPlanner && e.name && plannerFor) recordPlannerSpawn(e.name, plannerFor);
2091
+ if (delegatedPlanner && e.name && plannerFor) recordPlannerSpawn(e.name, plannerFor, cfg.paths);
2096
2092
  return ALLOW;
2097
2093
  }
2098
2094
 
@@ -2103,12 +2099,13 @@ export function flagCancel(text: string, cfg: Config): string {
2103
2099
  if (!m) return "";
2104
2100
  const at = m.index ?? 0;
2105
2101
  const words = text.slice(Math.max(0, at - 60), at + 80).replace(/\s+/g, " ").trim();
2106
- const prev = q.cancelPending();
2102
+ const prev = q.cancelPending(cfg.paths);
2103
+ const pendingFile = q.cancelPendingPath(cfg.paths);
2107
2104
  try {
2108
- mkdirSync(q.STATE_DIR, { recursive: true });
2109
- writeFileSync(q.CANCEL_PENDING, JSON.stringify({ at: new Date().toISOString(), words: prev ? `${prev.words} … ${words}` : words }));
2105
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
2106
+ writeFileSync(pendingFile, JSON.stringify({ at: new Date().toISOString(), words: prev ? `${prev.words} … ${words}` : words }));
2110
2107
  } catch (err) {
2111
- log(cfg.paths.guard_log, `cannot write ${q.CANCEL_PENDING}: ${err}`);
2108
+ log(cfg.paths.guard_log, `cannot write ${pendingFile}: ${err}`);
2112
2109
  }
2113
2110
  log(cfg.paths.guard_log, `cancel flagged: ${words}`);
2114
2111
  return `\nmain-guard: ${CANCEL_TODO} Flagged: "${words}"`;
@@ -2126,18 +2123,18 @@ export function flagCancel(text: string, cfg: Config): string {
2126
2123
  export function checkInject(e: InjectEvent, cfg: Config): Decision {
2127
2124
  if (e.agent !== "main") return ALLOW;
2128
2125
  const continuation = e.inject.trimStart().startsWith("main-guard:");
2129
- if (!continuation) writeWindow({ used: [], windowStart: 0, mainCalls: 0 });
2126
+ if (!continuation) writeWindow({ used: [], windowStart: 0, mainCalls: 0 }, cfg.paths);
2130
2127
  recordOwnerMessage(e.inject, cfg);
2131
2128
  let summary: string;
2132
2129
  try {
2133
2130
  // P4 (20261027_1305): one GET /view per team, read once and handed to the holder and the
2134
2131
  // team lines, so the summary costs one request per team and never a second GET /claims.
2135
2132
  const views = teamViews(cfg);
2136
- summary = q.queueSummary(undefined, cfg.review.agents, summaryHolder(cfg, {}, views));
2133
+ summary = q.queueSummary(cfg.paths, cfg.review.agents, summaryHolder(cfg, {}, views));
2137
2134
  const teamLines = teamSummaryLines(cfg, views, q.SUMMARY_CAP);
2138
2135
  if (teamLines.length) summary += `\n${teamLines.join("\n")}`;
2139
2136
  } catch (err) {
2140
- summary = `Queue unreadable (${q.INDEX}): ${err}`;
2137
+ summary = `Queue unreadable (${cfg.paths.queue_index}): ${err}`;
2141
2138
  }
2142
2139
  // P3 (plan 20261031_1207): only owner prose flags cancel, and incident lines pasted into a
2143
2140
  // prompt (guard output quoting "stop …") never do — their words are not the owner's.
@@ -2160,7 +2157,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
2160
2157
  return {
2161
2158
  allow: true,
2162
2159
  reason: "",
2163
- 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}`,
2160
+ inject: `${summary}\n(main-guard: read ${cfg.paths.queue_index}; the listed plans are summarised above; work the open plans, close finished ones with queue-close.)${editLimit}${cancel}${incidentText}`,
2164
2161
  ...(continuation ? {} : { state: { callsSinceStop: 0, idleStops: 0 } }),
2165
2162
  };
2166
2163
  }
@@ -2182,7 +2179,7 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
2182
2179
  // line) is the planner agent's to write — body freedom, but never the Main-only lines, and the
2183
2180
  // header names its agent. Only while delegated: in main mode the spawn gate refused the
2184
2181
  // Planner-role brief, and the plain Progress-only rule holds.
2185
- if (currentPlanner(cfg) === "delegated" && e.agentId !== undefined && plannerSpawnPlan(e.agentId) === e.path) {
2182
+ if (currentPlanner(cfg) === "delegated" && e.agentId !== undefined && plannerSpawnPlan(e.agentId, cfg.paths) === e.path) {
2186
2183
  if (mainOnlyLines(e.after) !== mainOnlyLines(e.before)) {
2187
2184
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (planner wrote a Main-only line)`);
2188
2185
  return {
@@ -2230,7 +2227,7 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
2230
2227
  restore: { path: e.path, text: e.before },
2231
2228
  };
2232
2229
  }
2233
- if (e.agent === "sub" && newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b)) && matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan !== e.path) {
2230
+ if (e.agent === "sub" && newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b)) && matchReviewSpawn(readReviewSpawns(cfg.paths), e.agentId ?? "")?.spawn.plan !== e.path) {
2234
2231
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} review line from a spawn that is not its named review spawn`);
2235
2232
  return { allow: false, reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line counts only from the named review spawn of ${e.path}; the file was restored.`, restore: { path: e.path, text: e.before } };
2236
2233
  }
@@ -2272,8 +2269,8 @@ export function findingsValue(block: string): string | null {
2272
2269
  }
2273
2270
 
2274
2271
  /** P6 (plan 20261028_1600): the refusal for ticking `ids` with review.code on. Each phase needs a recorded CODE REVIEW: PASS from a named review spawn (the `code` map of plan-reviews.json), and its entry must still be the plan's last Progress entry naming the phase — last by the entry's `<YYYY-MM-DD HH:MM>` stamp, not file order (live plans are newest-first or appended): implementer work after the review voids it. */
2275
- function codeReviewProblem(file: string, after: string, ids: string[]): string | null {
2276
- const rec = readCodeReviews()[file];
2272
+ function codeReviewProblem(file: string, after: string, ids: string[], paths: Pick<q.QueuePaths, "queue_state">): string | null {
2273
+ const rec = readCodeReviews(paths)[file];
2277
2274
  // toSorted is stable: ties and unstamped entries ("") keep file order.
2278
2275
  const entries = progressEntries(after)
2279
2276
  .map(b => [b, /^\s*-\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/.exec(b)?.[1] ?? ""] as const)
@@ -2310,7 +2307,7 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
2310
2307
  // the text outside "## Progress" is the planner agent's work. Main keeps its Progress entries,
2311
2308
  // the Main-only lines (Status / WAITING on owner / Waits on / Cancelled by owner / False
2312
2309
  // positive) and the index; running the queue stays Main's.
2313
- if (currentPlanner(cfg) === "delegated" && e.path !== q.INDEX && plannerBody(e.after) !== plannerBody(e.before)) {
2310
+ if (currentPlanner(cfg) === "delegated" && e.path !== cfg.paths.queue_index && plannerBody(e.after) !== plannerBody(e.before)) {
2314
2311
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (planner delegated)`);
2315
2312
  return {
2316
2313
  allow: false,
@@ -2351,7 +2348,7 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
2351
2348
  // P6 (plan 20261028_1600): with review.code on, ticking a phase needs a named review spawn's CODE REVIEW: PASS behind it — the recorded verdict counts, never Main's own line.
2352
2349
  if (cfg.review.code) {
2353
2350
  const ticks = newlyTicked(e.before, e.after);
2354
- const problem = ticks.length ? codeReviewProblem(e.path, e.after, ticks) : null;
2351
+ const problem = ticks.length ? codeReviewProblem(e.path, e.after, ticks, cfg.paths) : null;
2355
2352
  if (problem) {
2356
2353
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (code review: ${ticks.join(", ")})`);
2357
2354
  return { allow: false, reason: problem, restore: { path: e.path, text: e.before || null } };
@@ -2397,7 +2394,7 @@ const NO_SECTION = `no "## Code read by Main" section lists a file (list each fi
2397
2394
  function planReadProblems(text: string, planPath: string, cfg: Config): string[] {
2398
2395
  const listed = [...(READ_SECTION.exec(text)?.[1] ?? "").matchAll(LISTED_PATH)].map(m => (m[1] ?? "").replace(/:[\d,+\- ]+$/, ""));
2399
2396
  if (!listed.length) return [NO_SECTION];
2400
- const reads = readMainReads();
2397
+ const reads = readMainReads(cfg.paths);
2401
2398
  const maxMs = cfg.guards.plan_read_max_hours * 3_600_000;
2402
2399
  const problems: string[] = [];
2403
2400
  const named = new Set<string>();
@@ -2469,7 +2466,7 @@ function namedOrTwin(named: Set<string>, abs: string, planPath: string, text: st
2469
2466
  * stay out: they are refused like today.
2470
2467
  */
2471
2468
  function autoListReads(text: string, planPath: string, cfg: Config): { text: string; paths: string[] } | null {
2472
- const reads = readMainReads();
2469
+ const reads = readMainReads(cfg.paths);
2473
2470
  const maxMs = cfg.guards.plan_read_max_hours * 3_600_000;
2474
2471
  const covered = new Set<string>();
2475
2472
  for (const p of [...(READ_SECTION.exec(text)?.[1] ?? "").matchAll(LISTED_PATH)].map(m => (m[1] ?? "").replace(/:[\d,+\- ]+$/, "")))
@@ -2511,21 +2508,21 @@ function isFile(file: string): boolean {
2511
2508
  }
2512
2509
  }
2513
2510
 
2514
- function readMainReads(): Record<string, string> {
2511
+ function readMainReads(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string> {
2515
2512
  try {
2516
- return JSON.parse(readFileSync(path.join(q.STATE_DIR, "main-reads.json"), "utf8")) as Record<string, string>;
2513
+ return JSON.parse(readFileSync(path.join(paths.queue_state, "main-reads.json"), "utf8")) as Record<string, string>;
2517
2514
  } catch {
2518
2515
  return {};
2519
2516
  }
2520
2517
  }
2521
2518
 
2522
2519
  // Plans still responsible for: open plans (parked "WAITING on owner" excluded) plus queue problems.
2523
- export function openQueue(reviewAgents: string[] = []): string[] {
2520
+ export function openQueue(paths: q.QueuePaths, reviewAgents: string[] = []): string[] {
2524
2521
  const open = q
2525
- .activePlans()
2526
- .filter(p => !p.waiting && !q.awaitingMerge(p))
2522
+ .activePlans(paths)
2523
+ .filter(p => !p.waiting && !q.awaitingMerge(p, paths))
2527
2524
  .map(p => p.file);
2528
- for (const prob of q.queueProblems(undefined, undefined, reviewAgents)) open.push(`${prob.where}: ${prob.problem}`);
2525
+ for (const prob of q.queueProblems(paths, reviewAgents)) open.push(`${prob.where}: ${prob.problem}`);
2529
2526
  const unique: string[] = [];
2530
2527
  for (const item of open) if (!unique.includes(item)) unique.push(item);
2531
2528
  return unique;
@@ -2565,7 +2562,7 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
2565
2562
  // refusing it would order a capped Main to keep making calls the cap itself refuses. The
2566
2563
  // 15-min window expiry restarts the count, and the keep-working rule with it.
2567
2564
  if (cfg.guards.main_max_calls > 0) {
2568
- const w = readWindow();
2565
+ const w = readWindow(cfg.paths);
2569
2566
  if (w.mainCalls >= cfg.guards.main_max_calls && !mainCallsExpired(w)) {
2570
2567
  log(cfg.paths.guard_log, `ALLOW stop: turn spent ${w.mainCalls}/${cfg.guards.main_max_calls} calls`);
2571
2568
  return { ...ALLOW, state };
@@ -2573,12 +2570,12 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
2573
2570
  }
2574
2571
  let open: string[];
2575
2572
  try {
2576
- open = openQueue(cfg.review.agents);
2573
+ open = openQueue(cfg.paths, cfg.review.agents);
2577
2574
  } catch (err) {
2578
2575
  log(cfg.paths.guard_log, `BLOCK stop: cannot read queue: ${err}`);
2579
- open = [`queue unreadable (${q.INDEX}): ${err}`];
2576
+ open = [`queue unreadable (${cfg.paths.queue_index}): ${err}`];
2580
2577
  }
2581
- const pending = q.cancelPending();
2578
+ const pending = q.cancelPending(cfg.paths);
2582
2579
  if (pending && state.idleStops < 2) {
2583
2580
  if (state.callsSinceStop === 0) state.idleStops++;
2584
2581
  state.callsSinceStop = 0;
@@ -2607,9 +2604,9 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
2607
2604
  // running subagent's brief names it (staffing ∩ live ledger); unrelated live subagents release
2608
2605
  // nothing. Valve (20261031_2320): like the incident block above, empty stops count toward
2609
2606
  // cfg.guards.idle_stops; a stop with calls in between resets the count and re-locks.
2610
- const locked = q.activePlans().filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file));
2607
+ const locked = q.activePlans(cfg.paths).filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file, cfg.paths));
2611
2608
  if (locked.length) {
2612
- const staffed = staffedPlans(readStaffing(), liveSubagents(e.ledgerText));
2609
+ const staffed = staffedPlans(readStaffing(cfg.paths), liveSubagents(e.ledgerText));
2613
2610
  const unworked = locked.filter(s => !staffed.includes(s.file));
2614
2611
  if (unworked.length) {
2615
2612
  if (state.callsSinceStop === 0) state.idleStops++;
@@ -2624,7 +2621,7 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
2624
2621
  return {
2625
2622
  allow: false,
2626
2623
  reason:
2627
- `main-guard: ${unworked.map(s => `${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file) ?? "").replace(/^queue-close: /, "")})`).join("; ")}. ` +
2624
+ `main-guard: ${unworked.map(s => `${s.file} landed but its auto-close failed (${(q.lastCloseResult(s.file, cfg.paths) ?? "").replace(/^queue-close: /, "")})`).join("; ")}. ` +
2628
2625
  "The stop stays locked: spawn an agent whose brief names the plan, or fix the close. " +
2629
2626
  `${left} idle stop ${left === 1 ? "attempt" : "attempts"} left before the stop is allowed.`,
2630
2627
  state,