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
@@ -1,40 +1,52 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { fileURLToPath } from "node:url";
5
4
  import type { Config } from "./config.ts";
6
- import { applyQueueEnv } from "./queue/env.ts";
5
+ import { queueClose } from "./queue-close.ts";
7
6
  import {
8
7
  activePlans,
9
8
  banLine,
10
- CANCEL_PENDING,
11
9
  cancelledFile,
12
10
  cancelledMatches,
13
11
  cancelPending,
14
- GLOBAL_CANCELLED,
12
+ cancelPendingPath,
15
13
  repoRoot,
16
- STATE_DIR,
17
14
  } from "./queue/lib.ts";
18
15
 
16
+ /** Internal control-flow error thrown by `die()` so `queueCancel` returns exit code 1 cleanly without killing the process. */
17
+ class AbortCancel extends Error {}
18
+
19
+ /**
20
+ * Record a cancelled plan, global/repo never-do rule, or false-positive cancellation dismissal.
21
+ *
22
+ * Args:
23
+ * args (string[]): CLI arguments for `queue-cancel`
24
+ * cfg (Config): Loaded neurastream configuration
25
+ *
26
+ * Returns:
27
+ * number: Exit code (`0` succeeded, `1` refused, or child `queue-close` exit code)
28
+ */
19
29
  export function queueCancel(args: string[], cfg: Config): number {
20
- applyQueueEnv(cfg);
30
+ const STATE_DIR = cfg.paths.queue_state;
31
+ const CANCEL_PENDING = cancelPendingPath(cfg.paths);
32
+ const GLOBAL_CANCELLED = cfg.paths.cancelled;
21
33
  const today = new Date().toISOString().slice(0, 10);
22
34
  function die(msg: string): never {
23
35
  console.error(`queue-cancel: REFUSED: ${msg}`);
24
- process.exit(1);
36
+ throw new AbortCancel(msg);
25
37
  }
26
38
  function clearPending(how: string) {
27
- const p = cancelPending();
39
+ const p = cancelPending(cfg.paths);
28
40
  mkdirSync(STATE_DIR, { recursive: true });
29
41
  appendFileSync(path.join(STATE_DIR, "cancel.log"), `${new Date().toISOString()} ${how}${p ? ` (flagged message: ${p.words})` : ""}\n`);
30
42
  rmSync(CANCEL_PENDING, { force: true });
31
43
  }
32
44
  const usage = 'usage: queue-cancel <plan> "<owner words>" | --never "<what>" "<owner words>" [--repo <repo>] | --not-a-cancel "<why>"';
33
-
45
+ try {
34
46
  if (args[0] === "--not-a-cancel") {
35
47
  const why = (args[1] ?? "").trim();
36
48
  // Only a message main-guard flagged needs an answer; a bare call is a wasted round.
37
- if (!cancelPending()) die("nothing is flagged: main-guard did not see cancel words, so there is nothing to record");
49
+ if (!cancelPending(cfg.paths)) die("nothing is flagged: main-guard did not see cancel words, so there is nothing to record");
38
50
  if (why.length < 10) die(`say why the message was no cancel (at least 10 characters). ${usage}`);
39
51
  clearPending(`not a cancel: ${why}`);
40
52
  console.log("queue-cancel: noted, not a cancel");
@@ -70,7 +82,7 @@ export function queueCancel(args: string[], cfg: Config): number {
70
82
  console.log(c.status === 0 ? `queue-cancel: committed in ${repo}; push it with the usual rules` : `queue-cancel: WARNING commit failed (hooks above); the line is in the file and already enforced, commit it later`);
71
83
  }
72
84
  clearPending(`never: ${line}`);
73
- for (const p of activePlans()) if (cancelledMatches(p).some(c => line.startsWith(`- ${c.name} `)))
85
+ for (const p of activePlans(cfg.paths)) if (cancelledMatches(p, cfg.paths).some(c => line.startsWith(`- ${c.name} `)))
74
86
  console.log(`queue-cancel: open plan ${p.file} matches it and is now refused; cancel it too: queue-cancel ${p.file} "${owner}"`);
75
87
  return 0;
76
88
  }
@@ -78,7 +90,7 @@ export function queueCancel(args: string[], cfg: Config): number {
78
90
  const [planArg, owner = ""] = args;
79
91
  if (!planArg || planArg.startsWith("-")) die(usage);
80
92
  const file = path.resolve(planArg);
81
- const plan = activePlans().find(p => p.file === file);
93
+ const plan = activePlans(cfg.paths).find(p => p.file === file);
82
94
  if (!plan) die(`${file} is not an indexed plan; for work without a plan use --never`);
83
95
  if (owner.trim().length < 3) die(`quote the owner's words. ${usage}`);
84
96
  let text = readFileSync(file, "utf8");
@@ -86,7 +98,9 @@ export function queueCancel(args: string[], cfg: Config): number {
86
98
  text = text.replace(/^Status:\s*\S+\s*$/m, `Status: cancelled\nCancelled by owner: ${today} ${owner.trim().replace(/\n/g, " ")}`);
87
99
  writeFileSync(file, text);
88
100
  clearPending(`plan: ${file}`);
89
- const closeBin = path.join(path.dirname(fileURLToPath(import.meta.url)), "../cli/main.ts");
90
- const r = spawnSync("bun", [closeBin, "queue-close", file], { stdio: "inherit", env: process.env });
91
- return r.status ?? 1;
101
+ return queueClose([file], cfg);
102
+ } catch (e) {
103
+ if (e instanceof AbortCancel) return 1;
104
+ throw e;
105
+ }
92
106
  }
@@ -1,5 +1,4 @@
1
1
  import type { Config } from "./config.ts";
2
- import { applyQueueEnv } from "./queue/env.ts";
3
2
  import { activePlans, allowedAgents, holdWarnings, queueProblems, queueSummary, reviewAgentsProblem } from "./queue/lib.ts";
4
3
  import { mrSweep } from "./mr-sweep.ts";
5
4
  import { summaryHolder, teamSummaryLines, teamViews } from "./team-client.ts";
@@ -9,21 +8,20 @@ import { recheckHolds, staleHoldLines } from "./waiting-check.ts";
9
8
  // repo INDEX.md files to git-check and no work_roots scan; the queue problems carry the
10
9
  // worktree-placement and one-plan-one-worktree rules instead.
11
10
  export function queueCheck(args: string[], cfg: Config): number {
12
- applyQueueEnv(cfg);
13
11
  if (args.includes("--priority-ids")) {
14
- for (const p of activePlans()) if (p.priorityId && !p.waiting && p.status === "open") console.log(p.priorityId);
12
+ for (const p of activePlans(cfg.paths)) if (p.priorityId && !p.waiting && p.status === "open") console.log(p.priorityId);
15
13
  return 0;
16
14
  }
17
15
  // P4 (20261027_1305): one GET /view per team, read once for the holder and the team lines.
18
16
  const views = teamViews(cfg);
19
17
  const claims = summaryHolder(cfg, {}, views);
20
- const plans = activePlans();
18
+ const plans = activePlans(cfg.paths);
21
19
  const holds = recheckHolds(cfg, plans);
22
- console.log(queueSummary(undefined, cfg.review.agents, claims, Infinity));
20
+ console.log(queueSummary(cfg.paths, cfg.review.agents, claims, Infinity));
23
21
  for (const line of teamSummaryLines(cfg, views, Infinity)) console.log(line);
24
22
  for (const line of staleHoldLines(holds, plans)) console.log(line);
25
23
  // main-start prints the sweep itself and passes this so the child bin does not print it twice.
26
- let fail = queueProblems(undefined, undefined, cfg.review.agents).length > 0;
24
+ let fail = queueProblems(cfg.paths, cfg.review.agents).length > 0;
27
25
  // P4d (plan 20261028_1600): a review spawn needs a review.agents entry that Main may spawn.
28
26
  const review = reviewAgentsProblem(cfg, allowedAgents(cfg.paths.subagents));
29
27
  if (review.problem) {
@@ -35,7 +33,7 @@ export function queueCheck(args: string[], cfg: Config): number {
35
33
  for (const w of holdWarnings(plans)) console.log(`warning: ${w}`);
36
34
  if (!args.includes("--no-mr-sweep")) {
37
35
  try {
38
- const sweep = mrSweep();
36
+ const sweep = mrSweep({ paths: cfg.paths });
39
37
  for (const line of sweep.lines) console.log(line);
40
38
  if (sweep.fail) fail = true;
41
39
  } catch {
@@ -1,21 +1,34 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, fstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
- import os from "node:os";
4
3
  import path from "node:path";
5
4
  import { claimStoreFor } from "./team-client.ts";
6
5
 
7
6
  import type { Config } from "./config.ts";
8
- import { mainId } from "./guards.ts";
9
- import { applyQueueEnv } from "./queue/env.ts";
10
- import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, gitOut as git, INDEX, landed, prependFinished, sha, STATE_DIR, writeIndex } from "./queue/lib.ts";
7
+ import { tryLock } from "./file-lock.ts";
8
+ import { deleteSpawnRecord, mainId } from "./guards.ts";
9
+ import { activePlans, cancelledFile, cancelledLine, closeLog, expandHome, finishedEntry, finishedPath, gitOut as git, landed, prependFinished, sha, updateIndex } from "./queue/lib.ts";
11
10
  import { fixedIncident } from "./incidents.ts";
12
11
 
13
12
  // P4 (plan 20261031_0911): the landing check lives in queue/lib.ts (queueProblems' landed lock
14
13
  // shares it, and lib cannot import this closer back); re-exported here per the plan.
15
14
  export { landed };
16
15
 
16
+ /** Internal control-flow error thrown by `die()` so `queueClose` returns exit code 1 cleanly without killing the process. */
17
+ class AbortClose extends Error {}
18
+
19
+ /**
20
+ * Close and archive a completed or cancelled plan, run its done check, and remove it from the queue index.
21
+ *
22
+ * Args:
23
+ * args (string[]): CLI arguments (`[--auto] <plan file>` or `-h`/`--help`)
24
+ * cfg (Config): Loaded neurastream configuration
25
+ *
26
+ * Returns:
27
+ * number: Exit code (`0` closed, `1` refused, `3` already running, `4` awaiting merge)
28
+ */
17
29
  export function queueClose(args: string[], cfg: Config): number {
18
- applyQueueEnv(cfg);
30
+ const INDEX = cfg.paths.queue_index;
31
+ const STATE_DIR = cfg.paths.queue_state;
19
32
  const ARCHIVE_DAYS = cfg.queue.archive_days;
20
33
 
21
34
  let resultLog: string | null = null;
@@ -29,8 +42,9 @@ export function queueClose(args: string[], cfg: Config): number {
29
42
  }
30
43
  function die(msg: string): never {
31
44
  result(`queue-close: REFUSED: ${msg}`);
32
- process.exit(1);
45
+ throw new AbortClose(msg);
33
46
  }
47
+ try {
34
48
  // A clone of a clone judges "landed" against the middle copy's default branch, which can be
35
49
  // stale. Follow local-path origins (at most 3 hops) to the upstream repo and fetch its default
36
50
  // branch: that commit is the base. No local origin: the existing base, unchanged.
@@ -75,22 +89,26 @@ export function queueClose(args: string[], cfg: Config): number {
75
89
  }
76
90
  if (!arg) die("usage: queue-close [--auto] <plan file>");
77
91
  const file = path.resolve(arg);
78
- resultLog = closeLog(file);
92
+ resultLog = closeLog(file, cfg.paths);
79
93
 
80
94
  mkdirSync(STATE_DIR, { recursive: true });
81
95
  const lock = path.join(STATE_DIR, `close-${sha(file)}.lock`);
96
+ const held = tryLock(lock);
97
+ if (!held) {
98
+ let pidNote = "";
99
+ try {
100
+ const pid = Number(readFileSync(lock, "utf8").trim());
101
+ if (pid) pidNote = ` (pid ${pid})`;
102
+ } catch {}
103
+ console.error(`queue-close: already running for ${file}${pidNote}`);
104
+ return 3;
105
+ }
82
106
  try {
83
- const pid = Number(readFileSync(lock, "utf8"));
84
- if (pid && pid !== process.pid) {
85
- process.kill(pid, 0);
86
- console.error(`queue-close: already running for ${file} (pid ${pid})`);
87
- return 3;
88
- }
107
+ try {
108
+ writeFileSync(lock, `${process.pid}\n`);
89
109
  } catch {}
90
- writeFileSync(lock, String(process.pid));
91
- process.on("exit", () => rmSync(lock, { force: true }));
92
110
 
93
- const plan = activePlans().find(p => p.file === file);
111
+ const plan = activePlans(cfg.paths).find(p => p.file === file);
94
112
  if (!plan) die(`${file} is not listed in the main index ${INDEX}`);
95
113
  if (plan.errors.length) die(`plan does not match the template: ${plan.errors.join("; ")}`);
96
114
  if (plan.status !== "complete" && plan.status !== "cancelled" && !(auto && plan.status === "open"))
@@ -147,7 +165,8 @@ export function queueClose(args: string[], cfg: Config): number {
147
165
  // A shared clone of the base, deliberately NOT a registered worktree: it never shows up
148
166
  // in `git worktree list` and can be dropped with a plain delete when it stays clean.
149
167
  scratch = mkdtempSync(path.join(STATE_DIR, "done-base-"));
150
- const add = git(plan.repo, "clone", "-q", "--shared", ".", scratch) && git(scratch, "checkout", "-q", "--detach", base);
168
+ const cloned = git(plan.repo, "clone", "-q", "--shared", ".", scratch);
169
+ const add = cloned.ok ? git(scratch, "checkout", "-q", "--detach", base) : cloned;
151
170
  if (!add.ok) {
152
171
  rmSync(scratch, { recursive: true, force: true });
153
172
  die(`could not check out ${base} for the done check: ${add.out}`);
@@ -276,22 +295,21 @@ export function queueClose(args: string[], cfg: Config): number {
276
295
  console.log(`queue-close: plan moved to ${dest}`);
277
296
  }
278
297
  if (!cancelling) {
279
- const listed = finishedPath();
280
- const added = prependFinished(finishedEntry(plan, dest, today));
298
+ const listed = finishedPath(cfg.paths);
299
+ const added = prependFinished(finishedEntry(plan, dest, today), listed);
281
300
  console.log(added ? `queue-close: recorded in ${listed}` : `queue-close: already in ${listed}`);
282
301
  }
283
302
 
284
303
  // One index: the closed plan's line leaves the main index; there is no repo INDEX.md.
285
- const lines = readFileSync(INDEX, "utf8").split("\n").filter(l => l.trim());
286
- const keep = lines.filter(l => path.resolve(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").replace(/^~(?=\/)/, os.homedir())) !== file);
287
- writeIndex(keep, { removed: cancelling ? "cancel" : "close" });
288
- console.log(`queue-close: removed from ${INDEX} (${keep.length} plan(s) left)`);
289
- try {
290
- const sp = path.join(STATE_DIR, "spawns.json");
291
- const s = JSON.parse(readFileSync(sp, "utf8"));
292
- delete s[file];
293
- writeFileSync(sp, JSON.stringify(s, null, 1));
294
- } catch {}
304
+ let remaining = 0;
305
+ updateIndex(INDEX, { removed: cancelling ? "cancel" : "close" }, (currentText) => {
306
+ const lines = currentText.split("\n").filter(l => l.trim());
307
+ const keep = lines.filter(l => path.resolve(expandHome(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, ""))) !== file);
308
+ remaining = keep.length;
309
+ return keep;
310
+ });
311
+ console.log(`queue-close: removed from ${INDEX} (${remaining} plan(s) left)`);
312
+ deleteSpawnRecord(file, cfg.paths);
295
313
  // Incidents this plan fixes (plan P5): each INCIDENT <id> cited outside ## Progress gets a
296
314
  // fixed record, so the guards stop pushing a bug whose fix just shipped. Progress is
297
315
  // narrative, not fix work (I-20261031-349, P5b): an id Main only filed there ("needs a phase
@@ -324,4 +342,11 @@ export function queueClose(args: string[], cfg: Config): number {
324
342
  claimStoreFor(file, cfg).release(file, mainId());
325
343
  console.log("queue-close: CLOSED");
326
344
  return 0;
345
+ } finally {
346
+ held.release();
347
+ }
348
+ } catch (e) {
349
+ if (e instanceof AbortClose) return 1;
350
+ throw e;
351
+ }
327
352
  }
@@ -3,7 +3,6 @@
3
3
  import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import type { Config } from "./config.ts";
6
- import { applyQueueEnv } from "./queue/env.ts";
7
6
  import { finishedEntry, finishedKey, finishedPath, parsePlan, planRepo, prependFinished, repoRoot } from "./queue/lib.ts";
8
7
 
9
8
  const USAGE = "usage: queue-finished --backfill | --dedupe | queue-finished <word>";
@@ -92,23 +91,24 @@ function backfill(cfg: Config): number {
92
91
  } catch {
93
92
  return null;
94
93
  }
95
- const plan = parsePlan(planRepo(file), file, raw);
94
+ const plan = parsePlan(planRepo(file), file, raw, cfg.paths.blockers, [], true, cfg.paths.agent_dir);
96
95
  return plan.status === "complete" ? plan : null;
97
96
  })
98
97
  .filter(p => p !== null)
99
98
  .sort((a, b) => (path.basename(a.file) < path.basename(b.file) ? -1 : 1));
100
99
  let added = 0;
100
+ const target = finishedPath(cfg.paths);
101
101
  // Oldest first so each prepend leaves the newer entry on top.
102
102
  for (const plan of plans) {
103
- if (prependFinished(finishedEntry(plan, plan.file, stampDate(plan.file)))) added++;
103
+ if (prependFinished(finishedEntry(plan, plan.file, stampDate(plan.file)), target)) added++;
104
104
  }
105
105
  console.log(`queue-finished: backfill added ${added} (${plans.length} complete archived)`);
106
106
  return 0;
107
107
  }
108
108
 
109
109
  /** Keeps the first entry for each finished key and drops later repeats. */
110
- function dedupe(): number {
111
- const file = finishedPath();
110
+ function dedupe(cfg: Config): number {
111
+ const file = finishedPath(cfg.paths);
112
112
  let text = "";
113
113
  try {
114
114
  text = readFileSync(file, "utf8");
@@ -133,10 +133,10 @@ function entries(text: string): string[] {
133
133
  return text.split(/^(?=## )/m).filter(p => p.startsWith("## ")).map(p => p.trimEnd());
134
134
  }
135
135
 
136
- function search(word: string): number {
136
+ function search(word: string, cfg: Config): number {
137
137
  let text = "";
138
138
  try {
139
- text = readFileSync(finishedPath(), "utf8");
139
+ text = readFileSync(finishedPath(cfg.paths), "utf8");
140
140
  } catch {}
141
141
  const needle = word.toLowerCase();
142
142
  const hits = entries(text).filter(e => e.toLowerCase().includes(needle));
@@ -149,17 +149,16 @@ function search(word: string): number {
149
149
  }
150
150
 
151
151
  export function queueFinished(args: string[], cfg: Config): number {
152
- applyQueueEnv(cfg);
153
152
  if (args[0] === "--help" || args[0] === "-h") {
154
153
  console.log(USAGE);
155
154
  return 0;
156
155
  }
157
156
  if (args.includes("--backfill")) return backfill(cfg);
158
- if (args.includes("--dedupe")) return dedupe();
157
+ if (args.includes("--dedupe")) return dedupe(cfg);
159
158
  const word = args.filter(a => !a.startsWith("-")).join(" ").trim();
160
159
  if (!word) {
161
160
  console.error(USAGE);
162
161
  return 2;
163
162
  }
164
- return search(word);
163
+ return search(word, cfg);
165
164
  }
@@ -1,7 +1,6 @@
1
1
  import { existsSync, rmSync, statSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import type { Config } from "./config.ts";
4
- import { applyQueueEnv } from "./queue/env.ts";
5
4
  import { gitTop, readIndex, writeIndex } from "./queue/lib.ts";
6
5
 
7
6
  // One index (20261024_1400_one_index): fold the old two-level layout into the main index. Every
@@ -9,7 +8,6 @@ import { gitTop, readIndex, writeIndex } from "./queue/lib.ts";
9
8
  // and the repo INDEX.md deleted. Idempotent: with plan lines only, nothing changes. A plan still
10
9
  // inside a linked worktree is reported, not moved.
11
10
  export function queueMigrate(args: string[], cfg: Config): number {
12
- applyQueueEnv(cfg);
13
11
  const index = cfg.paths.queue_index;
14
12
  if (!existsSync(index)) {
15
13
  console.log(`queue migrate: ${index} does not exist; nothing to migrate`);
@@ -44,7 +42,7 @@ export function queueMigrate(args: string[], cfg: Config): number {
44
42
  rmSync(repoIndex);
45
43
  }
46
44
  const unique = [...new Set(kept)];
47
- writeIndex(unique, { removed: "migrate" });
45
+ writeIndex(unique, { removed: "migrate" }, index);
48
46
  console.log(`queue migrate: ${index} now lists ${unique.length} plan(s); folded ${folded} repo INDEX.md file(s)`);
49
47
  for (const p of unique) {
50
48
  const g = gitTop(p);
@@ -5,13 +5,11 @@ import { existsSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  import { rekeySpawnFile } from "./guards.ts";
7
7
  import type { Config } from "./config.ts";
8
- import { applyQueueEnv } from "./queue/env.ts";
9
8
  import * as q from "./queue/lib.ts";
10
9
 
11
10
  const USAGE = "usage: queue-trim <plan file> [--keep N]";
12
11
 
13
12
  export function queueTrim(args: string[], cfg: Config): number {
14
- applyQueueEnv(cfg);
15
13
  if (args[0] === "--help" || args[0] === "-h") {
16
14
  console.log(USAGE);
17
15
  return 0;
@@ -30,7 +28,7 @@ export function queueTrim(args: string[], cfg: Config): number {
30
28
  return 2;
31
29
  }
32
30
  const file = path.resolve(planArg);
33
- if (!existsSync(file) || !q.planAt(file, q.activePlans())) {
31
+ if (!existsSync(file) || !q.planAt(file, q.activePlans(cfg.paths))) {
34
32
  console.error(`queue-trim: ${file} is not an indexed plan`);
35
33
  return 2;
36
34
  }
@@ -39,7 +37,7 @@ export function queueTrim(args: string[], cfg: Config): number {
39
37
  console.log(`queue-trim: ${file} has no more than ${keep} Progress entries; nothing moved`);
40
38
  return 0;
41
39
  }
42
- rekeySpawnFile(file, t.before, t.after);
40
+ rekeySpawnFile(file, t.before, t.after, cfg.paths);
43
41
  console.log(`queue-trim: moved ${t.count} older Progress entries of ${file} to ${t.archive}`);
44
42
  return 0;
45
43
  }
@@ -8,7 +8,6 @@ import path from "node:path";
8
8
  import type { Run } from "./adapter.ts";
9
9
  import type { Config } from "./config.ts";
10
10
  import type { Ev } from "./metrics.ts";
11
- import { applyQueueEnv } from "./queue/env.ts";
12
11
  import { gitTop, parsePlan } from "./queue/lib.ts";
13
12
  import { repoRoots, walkMd } from "./queue-finished.ts";
14
13
 
@@ -65,7 +64,6 @@ function realRepo(p: string): string {
65
64
 
66
65
  /** Every dated plan under docs/plans/** of each repo the queue knows (work_roots plus one level of children). A git worktree carries a copy of docs/plans and gitTop maps it to the main checkout, so one node per (canonical repo, stem) survives: an archived or closed copy beats an open one, else the newest mtime wins. */
67
66
  export function loadPlans(cfg: Config): PlanNode[] {
68
- applyQueueEnv(cfg);
69
67
  const best = new Map<string, { node: PlanNode; mtime: number }>();
70
68
  for (const repo of repoRoots(cfg.paths.work_roots)) {
71
69
  const files: string[] = [];
@@ -5,7 +5,6 @@
5
5
  // the jobs and the note mtime, and performs the switch. No harness names here.
6
6
 
7
7
  import { join } from "node:path";
8
- import { mainStateDir } from "./guards.ts";
9
8
  import { strftime } from "./clock.ts";
10
9
  import type { OwnerAnswer, OwnerMessage } from "./incidents.ts";
11
10
 
@@ -167,11 +166,11 @@ export function noteRequest(path: string, reason = ""): string {
167
166
  }
168
167
 
169
168
  /** Where Main writes the handoff note for one session. */
170
- export function notePath(sessionId: string, stateDir = mainStateDir()): string {
169
+ export function notePath(sessionId: string, stateDir: string): string {
171
170
  return join(stateDir, "rollover", `${sessionId}.md`);
172
171
  }
173
172
 
174
173
  /** The launcher's relaunch request file: written by the harness just before it exits under `neurastream main`. */
175
- export function relaunchPath(stateDir = mainStateDir()): string {
174
+ export function relaunchPath(stateDir: string): string {
176
175
  return join(stateDir, "rollover", "relaunch.json");
177
176
  }
@@ -8,7 +8,6 @@
8
8
  // posts), `neurastream redact` and doctor all call this one module.
9
9
 
10
10
  import { readFileSync, readdirSync, statSync } from "node:fs";
11
- import { homedir } from "node:os";
12
11
  import { join } from "node:path";
13
12
  import type { Config } from "./config.ts";
14
13
 
@@ -187,7 +186,7 @@ interface CachedFile {
187
186
  values: string[];
188
187
  }
189
188
 
190
- type FileKind = "npmrc" | "env" | "text";
189
+ type FileKind = "npmrc" | "env-all" | "env-secret" | "text";
191
190
 
192
191
  const fileCache = new Map<string, CachedFile>();
193
192
  let discovered: { roots: string; atMs: number; files: string[] } | null = null;
@@ -211,16 +210,61 @@ function npmrcValues(text: string): string[] {
211
210
  return out;
212
211
  }
213
212
 
214
- /** `KEY=value` values of an env-style file (quotes stripped, comments ignored). */
215
- function envValues(text: string): string[] {
213
+ /**
214
+ * Parse one dotenv RHS value, handling quoted values (preserving `#` inside quotes and unescaping
215
+ * `\"`/`\\` inside double quotes) before stripping trailing inline `#` comments.
216
+ *
217
+ * Args:
218
+ * raw (string): Raw right-hand side of a `KEY=value` line
219
+ *
220
+ * Returns:
221
+ * string: Unquoted value with any trailing comment removed
222
+ */
223
+ function parseEnvValue(raw: string): string {
224
+ const trimmed = raw.trim();
225
+ if (trimmed.length === 0) return "";
226
+ if (trimmed[0] === '"') {
227
+ let out = "";
228
+ for (let i = 1; i < trimmed.length; i++) {
229
+ const ch = trimmed[i]!;
230
+ if (ch === "\\" && i + 1 < trimmed.length) {
231
+ const next = trimmed[i + 1]!;
232
+ if (next === '"' || next === "\\") {
233
+ out += next;
234
+ i++;
235
+ continue;
236
+ }
237
+ }
238
+ if (ch === '"') return out;
239
+ out += ch;
240
+ }
241
+ return out;
242
+ }
243
+ if (trimmed[0] === "'") {
244
+ const end = trimmed.indexOf("'", 1);
245
+ return end === -1 ? trimmed.slice(1) : trimmed.slice(1, end);
246
+ }
247
+ const hash = trimmed.search(/\s#/);
248
+ return (hash === -1 ? trimmed : trimmed.slice(0, hash)).trim();
249
+ }
250
+
251
+ /**
252
+ * Extract `KEY=value` values from an env-style file (quotes and inline comments parsed cleanly).
253
+ *
254
+ * Args:
255
+ * text (string): Full file contents
256
+ * secretKeysOnly (boolean): When true, keep only keys matching `SECRET_ENV_NAME`
257
+ *
258
+ * Returns:
259
+ * string[]: Extracted non-empty values
260
+ */
261
+ function envValues(text: string, secretKeysOnly: boolean): string[] {
216
262
  const out: string[] = [];
217
263
  for (const line of text.split("\n")) {
218
- const m = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/.exec(line);
219
- if (!m?.[1]) continue;
220
- let value = m[1].trim();
221
- if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])) value = value.slice(1, -1);
222
- const hash = value.search(/\s#/);
223
- if (hash !== -1) value = value.slice(0, hash).trim();
264
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$/.exec(line);
265
+ if (!m?.[1] || !m[2]) continue;
266
+ if (secretKeysOnly && !SECRET_ENV_NAME.test(m[1])) continue;
267
+ const value = parseEnvValue(m[2]);
224
268
  if (value !== "") out.push(value);
225
269
  }
226
270
  return out;
@@ -247,7 +291,14 @@ function fileValues(path: string, kind: FileKind): string[] {
247
291
  } catch {
248
292
  return hit?.values ?? [];
249
293
  }
250
- const values = kind === "npmrc" ? npmrcValues(text) : kind === "env" ? envValues(text) : [text.trim()];
294
+ const values =
295
+ kind === "npmrc"
296
+ ? npmrcValues(text)
297
+ : kind === "env-all"
298
+ ? envValues(text, false)
299
+ : kind === "env-secret"
300
+ ? envValues(text, true)
301
+ : [text.trim()];
251
302
  fileCache.set(key, { mtimeMs, size, values });
252
303
  return values;
253
304
  }
@@ -309,9 +360,9 @@ export function loadKnownSecrets(cfg: Config, env: NodeJS.ProcessEnv = process.e
309
360
  for (const [name, value] of Object.entries(env)) {
310
361
  if (typeof value === "string" && SECRET_ENV_NAME.test(name)) add(value);
311
362
  }
312
- for (const value of fileValues(join(homedir(), ".npmrc"), "npmrc")) add(value);
313
- for (const file of cfg.secrets.known_value_files) for (const value of fileValues(file, "env")) add(value);
314
- for (const file of workRootEnvFiles(cfg.paths.work_roots)) for (const value of fileValues(file, "env")) add(value);
363
+ for (const value of fileValues(join(cfg.paths.home, ".npmrc"), "npmrc")) add(value);
364
+ for (const file of cfg.secrets.known_value_files) for (const value of fileValues(file, "env-all")) add(value);
365
+ for (const file of workRootEnvFiles(cfg.paths.work_roots)) for (const value of fileValues(file, "env-secret")) add(value);
315
366
  for (const file of notifyFiles(cfg)) for (const value of fileValues(file, "text")) add(value);
316
367
  return [...out];
317
368
  }
@@ -72,6 +72,84 @@ export function parseBackendState(stdout: string): "running" | "stopped" {
72
72
  }
73
73
  }
74
74
 
75
+ /** How long a positive peer→login whois lookup stays cached (ms). */
76
+ export const WHOIS_TTL_MS = 30_000;
77
+
78
+ /** Maximum number of peer→login entries kept in the whois cache. */
79
+ export const WHOIS_MAX_ENTRIES = 256;
80
+
81
+ export interface CachedWhoisOptions {
82
+ ttlMs?: number;
83
+ maxEntries?: number;
84
+ now?: () => number;
85
+ }
86
+
87
+ export interface CachedWhois {
88
+ whois(peer: string): string | null;
89
+ clear(): void;
90
+ }
91
+
92
+ /**
93
+ * Wrap a synchronous peer→login lookup with a bounded, positive-only TTL cache.
94
+ * Transient `null` failures are never cached; expired entries are evicted on read;
95
+ * when capacity is reached, the oldest inserted entry is evicted.
96
+ *
97
+ * Args:
98
+ * lookup ((peer: string) => string | null): Underlying synchronous whois lookup
99
+ * opts (CachedWhoisOptions | undefined): Optional TTL, capacity, and clock overrides
100
+ *
101
+ * Returns:
102
+ * CachedWhois: Cached lookup function paired with a `clear()` reset helper
103
+ */
104
+ export function createCachedWhois(
105
+ lookup: (peer: string) => string | null,
106
+ opts: CachedWhoisOptions = {},
107
+ ): CachedWhois {
108
+ const ttlMs = opts.ttlMs ?? WHOIS_TTL_MS;
109
+ const maxEntries = opts.maxEntries ?? WHOIS_MAX_ENTRIES;
110
+ const now = opts.now ?? Date.now;
111
+ const cache = new Map<string, { login: string; expiresAt: number }>();
112
+
113
+ return {
114
+ whois(peer: string): string | null {
115
+ const nowMs = now();
116
+ const hit = cache.get(peer);
117
+ if (hit) {
118
+ if (nowMs < hit.expiresAt) return hit.login;
119
+ cache.delete(peer);
120
+ }
121
+ const login = lookup(peer);
122
+ if (login === null) return null;
123
+ if (ttlMs > 0 && maxEntries > 0) {
124
+ if (cache.has(peer)) cache.delete(peer);
125
+ while (cache.size >= maxEntries) {
126
+ const oldest = cache.keys().next().value;
127
+ if (oldest === undefined) break;
128
+ cache.delete(oldest);
129
+ }
130
+ cache.set(peer, { login, expiresAt: nowMs + ttlMs });
131
+ }
132
+ return login;
133
+ },
134
+ clear(): void {
135
+ cache.clear();
136
+ },
137
+ };
138
+ }
139
+
140
+ function rawWhois(peer: string): string | null {
141
+ const r = spawnSync("tailscale", ["whois", "--json", peer], { encoding: "utf8", timeout: 8000 });
142
+ if (r.error || r.status !== 0) return null;
143
+ return parseWhoisLogin(r.stdout ?? "");
144
+ }
145
+
146
+ const realWhoisCache = createCachedWhois(rawWhois);
147
+
148
+ /** Clear the process-wide `realTailscale.whois()` TTL cache (used by tests). */
149
+ export function clearWhoisCache(): void {
150
+ realWhoisCache.clear();
151
+ }
152
+
75
153
  export const realTailscale: Tailscale = {
76
154
  ip4() {
77
155
  return firstStdoutLine(["ip", "-4"]);
@@ -88,9 +166,7 @@ export const realTailscale: Tailscale = {
88
166
  }
89
167
  },
90
168
  whois(peer) {
91
- const r = spawnSync("tailscale", ["whois", "--json", peer], { encoding: "utf8", timeout: 8000 });
92
- if (r.error || r.status !== 0) return null;
93
- return parseWhoisLogin(r.stdout ?? "");
169
+ return realWhoisCache.whois(peer);
94
170
  },
95
171
  logins() {
96
172
  try {