neurastream 0.3.20 → 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 (49) hide show
  1. package/package.json +1 -1
  2. package/src/adapters/index.ts +3 -2
  3. package/src/adapters/omp/adapter.ts +2 -1
  4. package/src/adapters/omp/auto-close.ts +64 -0
  5. package/src/adapters/omp/chat-commands.ts +161 -0
  6. package/src/adapters/omp/inbox.ts +221 -0
  7. package/src/adapters/omp/index.ts +115 -1039
  8. package/src/adapters/omp/launch.ts +31 -3
  9. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  10. package/src/adapters/omp/rollover-controller.ts +334 -0
  11. package/src/adapters/omp/types.ts +143 -0
  12. package/src/cli/commands.ts +33 -2
  13. package/src/cli/dispatch.ts +37 -16
  14. package/src/cli/recall.ts +3 -2
  15. package/src/cli/results-build.ts +1 -1
  16. package/src/cli/workspace.ts +13 -2
  17. package/src/core/adapter.ts +16 -0
  18. package/src/core/blockers.ts +326 -30
  19. package/src/core/file-lock.ts +71 -12
  20. package/src/core/guards/plan-edit.ts +338 -0
  21. package/src/core/guards/planner.ts +70 -0
  22. package/src/core/guards/review.ts +391 -0
  23. package/src/core/guards/spawn.ts +699 -0
  24. package/src/core/guards/state.ts +581 -0
  25. package/src/core/guards/stop.ts +235 -0
  26. package/src/core/guards/tool.ts +541 -0
  27. package/src/core/guards.ts +12 -2658
  28. package/src/core/incidents.ts +125 -91
  29. package/src/core/machine-guard.ts +23 -5
  30. package/src/core/main-start.ts +10 -8
  31. package/src/core/owner-topics.ts +2 -13
  32. package/src/core/owner-ui/auth.ts +164 -0
  33. package/src/core/owner-ui/data.ts +437 -0
  34. package/src/core/owner-ui/handlers.ts +250 -0
  35. package/src/core/owner-ui/messages.ts +209 -0
  36. package/src/core/owner-ui/render.ts +714 -0
  37. package/src/core/owner-ui/results.ts +266 -0
  38. package/src/core/owner-ui/server.ts +142 -0
  39. package/src/core/owner-ui.ts +11 -2121
  40. package/src/core/page-notes.ts +25 -0
  41. package/src/core/pages.ts +452 -77
  42. package/src/core/plan-approval.ts +12 -14
  43. package/src/core/queue/lib.ts +88 -39
  44. package/src/core/queue-cancel.ts +21 -17
  45. package/src/core/queue-close.ts +48 -23
  46. package/src/core/secret-redact.ts +65 -14
  47. package/src/core/tailscale.ts +79 -3
  48. package/src/core/team-client.ts +13 -2
  49. package/src/core/uninstall.ts +2 -0
@@ -2,12 +2,13 @@
2
2
 
3
3
  import { createHash } from "node:crypto";
4
4
  import { spawnSync } from "node:child_process";
5
- import { accessSync, appendFileSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
5
+ import { accessSync, appendFileSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
8
  import type { Config } from "../config.ts";
9
9
  import type { ClaimStore } from "../claims.ts";
10
10
  import { strftime } from "../clock.ts";
11
+ import { withFileLock, writeAtomicSync } from "../file-lock.ts";
11
12
 
12
13
  // --- landing detection (plan 20261031_0911 P4/P5): lives here, not queue-close.ts, because
13
14
  // queueProblems' landed lock needs it and lib must not import the closer that imports lib ---
@@ -76,7 +77,10 @@ export function autoCloseCandidate(p: Plan): boolean {
76
77
  return landed(p.repo, p.branch, originBase(p.repo), p.text);
77
78
  }
78
79
 
79
- const HOME = os.homedir();
80
+ /** Resolve the current home directory dynamically so runtime `process.env.HOME` changes take effect. */
81
+ function currentHome(): string {
82
+ return process.env.HOME || os.homedir();
83
+ }
80
84
 
81
85
  /** Explicit filesystem paths for queue operations (structurally satisfied by `Config["paths"]`). */
82
86
  export interface QueuePaths {
@@ -147,50 +151,94 @@ export interface Plan {
147
151
  }
148
152
 
149
153
  export function expandHome(p: string): string {
150
- return p === "~" ? HOME : p.startsWith("~/") ? `${HOME}/${p.slice(2)}` : p;
154
+ const home = currentHome();
155
+ return p === "~" ? home : p.startsWith("~/") ? `${home}/${p.slice(2)}` : p;
151
156
  }
152
157
 
153
158
  export function sha(text: string): string {
154
159
  return createHash("sha256").update(text).digest("hex").slice(0, 16);
155
160
  }
156
161
 
157
- function indexLines(file: string): string[] | null {
158
- let text: string;
159
- try {
160
- text = readFileSync(file, "utf8");
161
- } catch {
162
- return null;
163
- }
164
- return text
162
+ /** Parse normalized absolute plan paths from index file text, resolving relative lines against `base`. */
163
+ export function parseIndex(text: string, base = process.cwd()): string[] {
164
+ const lines = text
165
165
  .split("\n")
166
166
  .map(l => l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").trim())
167
167
  .filter(Boolean);
168
+ return [...new Set(lines.map(l => path.resolve(base, expandHome(l))))];
168
169
  }
169
170
 
170
171
  // Relative lines resolve against `base` (default: the cwd); a repo INDEX.md passes its repo dir.
171
172
  export function readIndex(file: string, base = process.cwd()): string[] {
172
- return [...new Set((indexLines(file) ?? []).map(l => path.resolve(base, expandHome(l))))];
173
+ let text: string;
174
+ try {
175
+ text = readFileSync(file, "utf8");
176
+ } catch {
177
+ return [];
178
+ }
179
+ return parseIndex(text, base);
173
180
  }
174
181
 
175
- // The one writer of the index (plan 20261031_0911 P2): the index can only grow. A plan that would
176
- // disappear without an explicit close/cancel/migrate reason throws before anything is written, and
177
- // every write lands temp+rename then chmods the file to 0444. No 0o644 before the rename: rename(2)
178
- // replaces a read-only target with directory-write permission only, so the file is never writable —
179
- // not even between the rename and the chmod.
180
- export function writeIndex(lines: string[], why: { removed?: "close" | "cancel" | "migrate" } | undefined, file: string): void {
181
- const index = file;
182
+ /** Lock file sibling for `INDEX.md`, serializing read-modify-write index updates. */
183
+ export function indexLockPath(index: string): string {
184
+ return path.join(path.dirname(index), `.${path.basename(index)}.lock`);
185
+ }
186
+
187
+ function writeIndexUnlocked(
188
+ lines: string[],
189
+ why: { removed?: "close" | "cancel" | "migrate" } | undefined,
190
+ file: string,
191
+ currentText: string,
192
+ ): void {
182
193
  const newSet = new Set(
183
194
  lines.filter(l => l.trim()).map(l => path.resolve(expandHome(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").trim()))),
184
195
  );
185
- const gone = readIndex(index).filter(p => !newSet.has(p));
196
+ const gone = parseIndex(currentText).filter(p => !newSet.has(p));
186
197
  if (gone.length && !why?.removed)
187
198
  throw new Error(
188
199
  `writeIndex: ${gone.join(", ")} would leave the index; only a close, cancel or migrate removes a plan (why: { removed: "close" | "cancel" | "migrate" })`,
189
200
  );
190
- const tmp = `${index}.tmp`;
191
- writeFileSync(tmp, lines.length ? `${lines.join("\n")}\n` : "");
192
- renameSync(tmp, index);
193
- chmodSync(index, 0o444);
201
+ writeAtomicSync(file, lines.length ? `${lines.join("\n")}\n` : "", 0o444);
202
+ }
203
+
204
+ /**
205
+ * Locked read-modify-write helper for the queue index: acquires `indexLockPath(file)`, reads the
206
+ * current text under the lock, invokes `mutate(currentText)`, verifies no plan disappears without
207
+ * an explicit `why.removed` reason, and atomically writes the new index with `0o444` applied
208
+ * before `renameSync`. Returning `null` from `mutate` aborts cleanly without writing.
209
+ *
210
+ * Args:
211
+ * file (string): Path to the queue index file
212
+ * why ({ removed?: "close" | "cancel" | "migrate" } | undefined): Removal authorization if lines are dropped
213
+ * mutate ((currentText: string) => string[] | null): Pure transform from current file text to next lines
214
+ *
215
+ * Returns:
216
+ * boolean: True when the index was written; false when `mutate` returned null
217
+ */
218
+ export function updateIndex(
219
+ file: string,
220
+ why: { removed?: "close" | "cancel" | "migrate" } | undefined,
221
+ mutate: (currentText: string) => string[] | null,
222
+ ): boolean {
223
+ return withFileLock(indexLockPath(file), () => {
224
+ let currentText = "";
225
+ try {
226
+ currentText = readFileSync(file, "utf8");
227
+ } catch {}
228
+ const next = mutate(currentText);
229
+ if (next === null) return false;
230
+ writeIndexUnlocked(next, why, file, currentText);
231
+ return true;
232
+ });
233
+ }
234
+
235
+ // The one writer of the index (plan 20261031_0911 P2): the index can only grow. A plan that would
236
+ // disappear without an explicit close/cancel/migrate reason throws before anything is written, and
237
+ // every write lands temp + chmod 0444 + rename under the index lock. No 0o644 before the rename:
238
+ // rename(2) replaces a read-only target with directory-write permission only, so the file is never
239
+ // writable — not even between the rename and the chmod.
240
+ export function writeIndex(lines: string[], why: { removed?: "close" | "cancel" | "migrate" } | undefined, file: string): void {
241
+ updateIndex(file, why, () => lines);
194
242
  }
195
243
 
196
244
  // Doctor's enforcement half of the same plan: the live index must sit at 0444 between writes, so
@@ -641,7 +689,7 @@ function packageOpTarget(code: string, paths?: Pick<QueuePaths, "agent_dir">): s
641
689
  })) {
642
690
  const envHome = toks.slice(0, i).find(t => t.startsWith("HOME="));
643
691
  if (envHome && envHome.slice("HOME=".length).replace(/^["']|["']$/g, "").startsWith("/tmp/")) continue;
644
- return `${paths?.agent_dir ?? `${HOME}/.config/neurastream`}/extensions/`;
692
+ return `${paths?.agent_dir ?? `${currentHome()}/.config/neurastream`}/extensions/`;
645
693
  }
646
694
  }
647
695
  return packageOpMatcher?.(code) ?? null;
@@ -759,7 +807,7 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
759
807
  ])
760
808
  for (const m of code.matchAll(re)) add((m[1] ?? "").replace(/`/g, ""), dir);
761
809
  if (pkgOp) out.add(pkgOp);
762
- if (subOp) out.add(paths?.subagents ?? `${HOME}/.config/neurastream/notes/subagents.md`);
810
+ if (subOp) out.add(paths?.subagents ?? `${currentHome()}/.config/neurastream/notes/subagents.md`);
763
811
  return [...out];
764
812
  }
765
813
 
@@ -781,11 +829,12 @@ function packageManifest(): { root: string; bins: string[] } | null {
781
829
  }
782
830
 
783
831
  function bunGlobalRoot(): string {
784
- return process.env.BUN_INSTALL ? path.resolve(expandHome(process.env.BUN_INSTALL)) : `${HOME}/.bun`;
832
+ return process.env.BUN_INSTALL ? path.resolve(expandHome(process.env.BUN_INSTALL)) : `${currentHome()}/.bun`;
785
833
  }
786
834
 
787
835
  export function protectedPaths(paths: QueuePaths): string[] {
788
836
  const agent = paths.agent_dir;
837
+ const home = currentHome();
789
838
  const out = [
790
839
  `${agent}/extensions/`,
791
840
  `${agent}/queue/`,
@@ -802,25 +851,25 @@ export function protectedPaths(paths: QueuePaths): string[] {
802
851
  `${agent}/config.yml`,
803
852
  // The user's neurastream config file, even when agent_dir points elsewhere: an agent that
804
853
  // could rewrite it could point notify at its own webhook.
805
- `${HOME}/.config/neurastream/config.yml`,
854
+ `${home}/.config/neurastream/config.yml`,
806
855
  // The planner mode guard baseline beside that file (plan 20261102_1515 P2 d): the
807
856
  // owner-only anchor of the mode facts. A write that could plant or edit it would make the
808
857
  // writer's own dirt the truth, so no tool may touch it.
809
- `${HOME}/.config/neurastream/guard-baseline`,
858
+ `${home}/.config/neurastream/guard-baseline`,
810
859
  `${agent}/notes/subagents.md`,
811
860
  paths.subagents,
812
861
  `${agent}/.guard-unlock`,
813
862
  paths.unlock,
814
863
  `${path.dirname(agent)}/git-no-verify-guard.mjs`,
815
- `${HOME}/.local/bin/queue-check`,
816
- `${HOME}/.local/bin/queue-close`,
817
- `${HOME}/.local/bin/queue-cancel`,
818
- `${HOME}/.local/bin/agent-ledger`,
819
- `${HOME}/.local/bin/brief-lint`,
820
- `${HOME}/.local/bin/main-start`,
821
- `${HOME}/.local/bin/git`,
822
- `${HOME}/.local/bin/git-secret-gate`,
823
- `${HOME}/.config/git-secret-gate/`,
864
+ `${home}/.local/bin/queue-check`,
865
+ `${home}/.local/bin/queue-close`,
866
+ `${home}/.local/bin/queue-cancel`,
867
+ `${home}/.local/bin/agent-ledger`,
868
+ `${home}/.local/bin/brief-lint`,
869
+ `${home}/.local/bin/main-start`,
870
+ `${home}/.local/bin/git`,
871
+ `${home}/.local/bin/git-secret-gate`,
872
+ `${home}/.config/git-secret-gate/`,
824
873
  // Where `bun add -g neurastream` lands; writeTargets points package
825
874
  // operations here so they need the owner's unlock like any guard edit.
826
875
  // The plugin dir is adapter surface: the installer lists it in the
@@ -830,7 +879,7 @@ export function protectedPaths(paths: QueuePaths): string[] {
830
879
  const pkg = packageManifest();
831
880
  if (pkg) {
832
881
  out.push(`${pkg.root}/`);
833
- for (const name of pkg.bins) out.push(`${HOME}/.bun/bin/${name}`);
882
+ for (const name of pkg.bins) out.push(`${home}/.bun/bin/${name}`);
834
883
  }
835
884
  return out;
836
885
  }
@@ -1,8 +1,8 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { fileURLToPath } from "node:url";
5
4
  import type { Config } from "./config.ts";
5
+ import { queueClose } from "./queue-close.ts";
6
6
  import {
7
7
  activePlans,
8
8
  banLine,
@@ -13,6 +13,19 @@ import {
13
13
  repoRoot,
14
14
  } from "./queue/lib.ts";
15
15
 
16
+ /** Internal control-flow error thrown by `die()` so `queueCancel` returns exit code 1 cleanly without killing the process. */
17
+ class AbortCancel extends Error {}
18
+
19
+ /**
20
+ * Record a cancelled plan, global/repo never-do rule, or false-positive cancellation dismissal.
21
+ *
22
+ * Args:
23
+ * args (string[]): CLI arguments for `queue-cancel`
24
+ * cfg (Config): Loaded neurastream configuration
25
+ *
26
+ * Returns:
27
+ * number: Exit code (`0` succeeded, `1` refused, or child `queue-close` exit code)
28
+ */
16
29
  export function queueCancel(args: string[], cfg: Config): number {
17
30
  const STATE_DIR = cfg.paths.queue_state;
18
31
  const CANCEL_PENDING = cancelPendingPath(cfg.paths);
@@ -20,7 +33,7 @@ export function queueCancel(args: string[], cfg: Config): number {
20
33
  const today = new Date().toISOString().slice(0, 10);
21
34
  function die(msg: string): never {
22
35
  console.error(`queue-cancel: REFUSED: ${msg}`);
23
- process.exit(1);
36
+ throw new AbortCancel(msg);
24
37
  }
25
38
  function clearPending(how: string) {
26
39
  const p = cancelPending(cfg.paths);
@@ -29,7 +42,7 @@ export function queueCancel(args: string[], cfg: Config): number {
29
42
  rmSync(CANCEL_PENDING, { force: true });
30
43
  }
31
44
  const usage = 'usage: queue-cancel <plan> "<owner words>" | --never "<what>" "<owner words>" [--repo <repo>] | --not-a-cancel "<why>"';
32
-
45
+ try {
33
46
  if (args[0] === "--not-a-cancel") {
34
47
  const why = (args[1] ?? "").trim();
35
48
  // Only a message main-guard flagged needs an answer; a bare call is a wasted round.
@@ -85,18 +98,9 @@ export function queueCancel(args: string[], cfg: Config): number {
85
98
  text = text.replace(/^Status:\s*\S+\s*$/m, `Status: cancelled\nCancelled by owner: ${today} ${owner.trim().replace(/\n/g, " ")}`);
86
99
  writeFileSync(file, text);
87
100
  clearPending(`plan: ${file}`);
88
- const closeBin = path.join(path.dirname(fileURLToPath(import.meta.url)), "../cli/main.ts");
89
- const childEnv: NodeJS.ProcessEnv = {
90
- ...process.env,
91
- HOME: cfg.paths.home,
92
- QUEUE_AGENT: cfg.paths.agent_dir,
93
- QUEUE_INDEX: cfg.paths.queue_index,
94
- QUEUE_BLOCKERS: cfg.paths.blockers,
95
- QUEUE_STATE: cfg.paths.queue_state,
96
- QUEUE_SUBAGENTS: cfg.paths.subagents,
97
- QUEUE_CANCELLED: cfg.paths.cancelled,
98
- QUEUE_UNLOCK: cfg.paths.unlock,
99
- };
100
- const r = spawnSync("bun", [closeBin, "queue-close", file], { stdio: "inherit", env: childEnv });
101
- return r.status ?? 1;
101
+ return queueClose([file], cfg);
102
+ } catch (e) {
103
+ if (e instanceof AbortCancel) return 1;
104
+ throw e;
105
+ }
102
106
  }
@@ -1,18 +1,31 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, fstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
- import os from "node:os";
4
3
  import path from "node:path";
5
4
  import { claimStoreFor } from "./team-client.ts";
6
5
 
7
6
  import type { Config } from "./config.ts";
8
- import { mainId } from "./guards.ts";
9
- import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, gitOut as git, landed, prependFinished, sha, writeIndex } from "./queue/lib.ts";
7
+ import { tryLock } from "./file-lock.ts";
8
+ import { deleteSpawnRecord, mainId } from "./guards.ts";
9
+ import { activePlans, cancelledFile, cancelledLine, closeLog, expandHome, finishedEntry, finishedPath, gitOut as git, landed, prependFinished, sha, updateIndex } from "./queue/lib.ts";
10
10
  import { fixedIncident } from "./incidents.ts";
11
11
 
12
12
  // P4 (plan 20261031_0911): the landing check lives in queue/lib.ts (queueProblems' landed lock
13
13
  // shares it, and lib cannot import this closer back); re-exported here per the plan.
14
14
  export { landed };
15
15
 
16
+ /** Internal control-flow error thrown by `die()` so `queueClose` returns exit code 1 cleanly without killing the process. */
17
+ class AbortClose extends Error {}
18
+
19
+ /**
20
+ * Close and archive a completed or cancelled plan, run its done check, and remove it from the queue index.
21
+ *
22
+ * Args:
23
+ * args (string[]): CLI arguments (`[--auto] <plan file>` or `-h`/`--help`)
24
+ * cfg (Config): Loaded neurastream configuration
25
+ *
26
+ * Returns:
27
+ * number: Exit code (`0` closed, `1` refused, `3` already running, `4` awaiting merge)
28
+ */
16
29
  export function queueClose(args: string[], cfg: Config): number {
17
30
  const INDEX = cfg.paths.queue_index;
18
31
  const STATE_DIR = cfg.paths.queue_state;
@@ -29,8 +42,9 @@ export function queueClose(args: string[], cfg: Config): number {
29
42
  }
30
43
  function die(msg: string): never {
31
44
  result(`queue-close: REFUSED: ${msg}`);
32
- process.exit(1);
45
+ throw new AbortClose(msg);
33
46
  }
47
+ try {
34
48
  // A clone of a clone judges "landed" against the middle copy's default branch, which can be
35
49
  // stale. Follow local-path origins (at most 3 hops) to the upstream repo and fetch its default
36
50
  // branch: that commit is the base. No local origin: the existing base, unchanged.
@@ -79,16 +93,20 @@ export function queueClose(args: string[], cfg: Config): number {
79
93
 
80
94
  mkdirSync(STATE_DIR, { recursive: true });
81
95
  const lock = path.join(STATE_DIR, `close-${sha(file)}.lock`);
96
+ const held = tryLock(lock);
97
+ if (!held) {
98
+ let pidNote = "";
99
+ try {
100
+ const pid = Number(readFileSync(lock, "utf8").trim());
101
+ if (pid) pidNote = ` (pid ${pid})`;
102
+ } catch {}
103
+ console.error(`queue-close: already running for ${file}${pidNote}`);
104
+ return 3;
105
+ }
82
106
  try {
83
- const pid = Number(readFileSync(lock, "utf8"));
84
- if (pid && pid !== process.pid) {
85
- process.kill(pid, 0);
86
- console.error(`queue-close: already running for ${file} (pid ${pid})`);
87
- return 3;
88
- }
107
+ try {
108
+ writeFileSync(lock, `${process.pid}\n`);
89
109
  } catch {}
90
- writeFileSync(lock, String(process.pid));
91
- process.on("exit", () => rmSync(lock, { force: true }));
92
110
 
93
111
  const plan = activePlans(cfg.paths).find(p => p.file === file);
94
112
  if (!plan) die(`${file} is not listed in the main index ${INDEX}`);
@@ -147,7 +165,8 @@ export function queueClose(args: string[], cfg: Config): number {
147
165
  // A shared clone of the base, deliberately NOT a registered worktree: it never shows up
148
166
  // in `git worktree list` and can be dropped with a plain delete when it stays clean.
149
167
  scratch = mkdtempSync(path.join(STATE_DIR, "done-base-"));
150
- const add = git(plan.repo, "clone", "-q", "--shared", ".", scratch) && git(scratch, "checkout", "-q", "--detach", base);
168
+ const cloned = git(plan.repo, "clone", "-q", "--shared", ".", scratch);
169
+ const add = cloned.ok ? git(scratch, "checkout", "-q", "--detach", base) : cloned;
151
170
  if (!add.ok) {
152
171
  rmSync(scratch, { recursive: true, force: true });
153
172
  die(`could not check out ${base} for the done check: ${add.out}`);
@@ -282,16 +301,15 @@ export function queueClose(args: string[], cfg: Config): number {
282
301
  }
283
302
 
284
303
  // One index: the closed plan's line leaves the main index; there is no repo INDEX.md.
285
- const lines = readFileSync(INDEX, "utf8").split("\n").filter(l => l.trim());
286
- const keep = lines.filter(l => path.resolve(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, "").replace(/^~(?=\/)/, os.homedir())) !== file);
287
- writeIndex(keep, { removed: cancelling ? "cancel" : "close" }, INDEX);
288
- console.log(`queue-close: removed from ${INDEX} (${keep.length} plan(s) left)`);
289
- try {
290
- const sp = path.join(STATE_DIR, "spawns.json");
291
- const s = JSON.parse(readFileSync(sp, "utf8"));
292
- delete s[file];
293
- writeFileSync(sp, JSON.stringify(s, null, 1));
294
- } catch {}
304
+ let remaining = 0;
305
+ updateIndex(INDEX, { removed: cancelling ? "cancel" : "close" }, (currentText) => {
306
+ const lines = currentText.split("\n").filter(l => l.trim());
307
+ const keep = lines.filter(l => path.resolve(expandHome(l.trim().replace(/^[-*]\s+/, "").replace(/`/g, ""))) !== file);
308
+ remaining = keep.length;
309
+ return keep;
310
+ });
311
+ console.log(`queue-close: removed from ${INDEX} (${remaining} plan(s) left)`);
312
+ deleteSpawnRecord(file, cfg.paths);
295
313
  // Incidents this plan fixes (plan P5): each INCIDENT <id> cited outside ## Progress gets a
296
314
  // fixed record, so the guards stop pushing a bug whose fix just shipped. Progress is
297
315
  // narrative, not fix work (I-20261031-349, P5b): an id Main only filed there ("needs a phase
@@ -324,4 +342,11 @@ export function queueClose(args: string[], cfg: Config): number {
324
342
  claimStoreFor(file, cfg).release(file, mainId());
325
343
  console.log("queue-close: CLOSED");
326
344
  return 0;
345
+ } finally {
346
+ held.release();
347
+ }
348
+ } catch (e) {
349
+ if (e instanceof AbortClose) return 1;
350
+ throw e;
351
+ }
327
352
  }
@@ -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 {
@@ -162,9 +162,20 @@ if (import.meta.main) {
162
162
  );
163
163
  }
164
164
 
165
- /** The default transport: one synchronous child, JSON request on stdin, JSON answer on stdout. */
165
+ /**
166
+ * The default transport: one synchronous child, JSON request on stdin, JSON answer on stdout.
167
+ *
168
+ * Args:
169
+ * req (WireRequest): HTTP request parameters to execute in the child process
170
+ *
171
+ * Returns:
172
+ * WireResponse | null: Parsed response object or an error envelope
173
+ */
166
174
  function defaultSend(req: WireRequest): WireResponse | null {
167
- const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url)], {
175
+ // Always invoke `bun` by name, never `process.execPath`: when core is loaded inside a
176
+ // compiled host harness, `process.execPath` points at the harness binary itself, so spawning
177
+ // it would recursively launch full host sessions instead of running this request script.
178
+ const r = spawnSync("bun", [fileURLToPath(import.meta.url)], {
168
179
  input: JSON.stringify(req),
169
180
  timeout: REQUEST_TIMEOUT_MS,
170
181
  encoding: "utf8",
@@ -11,6 +11,7 @@ import { fileURLToPath } from "node:url";
11
11
  import { stripBlock } from "./agents-md.ts";
12
12
  import { configFile, loadConfig, type Config } from "./config.ts";
13
13
  import { printText } from "./help.ts";
14
+ import { indexLockPath } from "./queue/lib.ts";
14
15
 
15
16
  const HERE = dirname(fileURLToPath(import.meta.url));
16
17
  const PACKAGE_ROOT = resolve(HERE, "../..");
@@ -162,6 +163,7 @@ function purgeState(cfg: Config, out: UninstallTarget[]): void {
162
163
  const entries: [string, string, boolean][] = [
163
164
  [configFile(cfg.paths.home), "--purge: config file", false],
164
165
  [cfg.paths.queue_index, "--purge: index", false],
166
+ [indexLockPath(cfg.paths.queue_index), "--purge: index lock", false],
165
167
  [join(cfg.paths.agent_dir, "queue"), "--purge: queue dir", true],
166
168
  [cfg.paths.notes, "--purge: notes dir", true],
167
169
  [cfg.paths.blockers, "--purge: blockers dir", true],