viewable-one 0.12.8 → 0.12.10

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.
@@ -19,12 +19,26 @@
19
19
  // "Allow for this run": Claude's prompts, ACP's and Codex's sandbox
20
20
  // escalations all land there;
21
21
  // - opencode's own config (`OPENCODE_OTHER_LOGIN_RULES`, agents.mjs
22
- // prepareWorkspace), since `--auto` approves everything it does not deny.
22
+ // prepareWorkspace), since `--auto` approves everything it does not deny;
23
+ // - Codex's own PreToolUse hook (`codexOtherLoginArgs`, codex.mjs), which
24
+ // runs `usesAnotherLogin` on every command before it runs (#7466). The
25
+ // asker alone was not enough there: a plain command inside Codex's
26
+ // sandbox never asks, so it never reached the asker.
27
+ //
28
+ // EVERY ENGINE THE COMPUTER STARTS, and how the list holds on it (#7466):
29
+ // - Claude Code: `--disallowedTools` deny rules, then the asker.
30
+ // - Claude Code via ACP (the only ACP agent): the adapter's
31
+ // `disallowedTools`, then the asker.
32
+ // - Codex: the PreToolUse hook below, then the asker for a sandbox
33
+ // escalation. A Codex that does not list the hook as trusted is not
34
+ // given the run (codex.mjs `requireLoginHook`).
35
+ // - opencode: `permission.bash` deny patterns.
23
36
  //
24
37
  // WHAT IT DOES NOT STOP, said plainly so nobody repeats it as a fence: a
25
38
  // command the allowlist already lets through without asking can still reach
26
39
  // one through a script (`node -e`, `npm run <script>`, a `cat` of a token file
27
- // spelled some new way). The words cover those. The child's environment is
40
+ // spelled some new way). On Codex, text typed into a shell the run already
41
+ // opened (`write_stdin`) runs no hook. The words cover those. The child's environment is
28
42
  // already an allowlist (child.mjs `childEnv`), so a token exported in the
29
43
  // person's shell (SUPABASE_ACCESS_TOKEN, GH_TOKEN) is not handed to the run.
30
44
  //
@@ -35,6 +49,9 @@
35
49
  // `gh auth token`). A tool is judged where it RUNS, at a command's start, so
36
50
  // a commit message or a folder named `supabase` is not refused.
37
51
 
52
+ import { createHash } from "node:crypto";
53
+ import { fileURLToPath } from "node:url";
54
+
38
55
  /** Command-line tools that use a stored login of their own. */
39
56
  const LOGIN_TOOLS = ["supabase"];
40
57
 
@@ -47,7 +64,7 @@ const KEYCHAIN_READS = new Set(["find-generic-password", "find-internet-password
47
64
  /** Token files a login tool keeps on disk, matched anywhere in a command:
48
65
  * `cat`, `head`, `node -e` or a redirection that names one is refused. Each
49
66
  * is written with `/`; a `\\` (Windows) is matched too. */
50
- const TOKEN_FILE_PATHS = [".supabase/access-token"];
67
+ const TOKEN_FILE_PATHS = [".supabase/access-token", ".config/gh/hosts.yml"];
51
68
  const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
52
69
  const TOKEN_FILES = new RegExp(TOKEN_FILE_PATHS.map((path) => path.split("/").map(escapeRegExp).join("[\\\\/]")).join("|"), "i");
53
70
 
@@ -260,10 +277,17 @@ export const CLAUDE_OTHER_LOGIN_TOOLS = [
260
277
  // "credential fill" to be caught.
261
278
  "Bash(git credential:*)",
262
279
  ...GIT_CREDENTIAL_WORDS.flatMap((word) => [`Bash(git ${word}:*)`, `Bash(git * ${word}*)`]),
280
+ // The saved-secret stores, so Claude Code bars the same list the others do
281
+ // (#7466); none is on the allowlist, so the asker refuses them as well.
282
+ ...[...PASSWORD_MANAGERS].map((tool) => `Bash(${tool}:*)`),
283
+ ...[...KEYCHAIN_READS].map((sub) => `Bash(security ${sub}:*)`),
284
+ "Bash(secret-tool lookup:*)", "Bash(secret-tool search:*)",
285
+ "Bash(gh auth token:*)", "Bash(gh auth status *--show-token*)", "Bash(gh auth status *-t*)",
263
286
  // A shell read of a token file (`cat`, `head`, `node -e`) is on the
264
287
  // allowlist too: deny any command that names one.
265
288
  ...TOKEN_FILE_PATHS.flatMap((path) => [`Bash(*${path}*)`, `Bash(*${path.replaceAll("/", "\\")}*)`]),
266
289
  "Read(~/.supabase/**)",
290
+ ...TOKEN_FILE_PATHS.filter((path) => !path.startsWith(".supabase/")).map((path) => `Read(~/${path})`),
267
291
  ];
268
292
 
269
293
  /** opencode's own deny rules (its `permission.bash` patterns), for the same
@@ -280,3 +304,83 @@ export const OPENCODE_OTHER_LOGIN_RULES = Object.fromEntries([
280
304
  ...GIT_CREDENTIAL_WORDS.map((word) => `git * ${word}*`),
281
305
  ...TOKEN_FILE_PATHS.flatMap((path) => [`*${path}*`, `*${path.replaceAll("/", "\\")}*`]),
282
306
  ].map((pattern) => [pattern, "deny"]));
307
+
308
+ // CODEX'S OWN HOOK (#7466). Codex runs a plain command inside its sandbox
309
+ // without asking, and its sandbox reads files outside the workspace, so
310
+ // neither the asker nor the sandbox sees `ls ~/.supabase/access-token`. Its
311
+ // PreToolUse hook does: Codex runs it before every tool call (exec_command
312
+ // sends `{ tool_name: "Bash", tool_input: { command } }`) and does not run
313
+ // the call when the hook exits 2 with a reason on stderr. The hook is
314
+ // otherLoginHook.mjs, which runs the same `usesAnotherLogin` as the asker.
315
+ //
316
+ // TRUST. Codex runs a hook only when its config holds the hook's hash
317
+ // (`hooks.state."<key>".trusted_hash`); `--dangerously-bypass-hook-trust`
318
+ // would also run every untrusted hook in a project, so it is not used. The
319
+ // hash is Codex's own: sha256 of the hook's normalized identity as JSON with
320
+ // sorted keys (codex-rs hooks/src/engine/discovery.rs `hook_hash`, config
321
+ // fingerprint.rs `version_for_toml`), checked against codex-cli 0.165.0's
322
+ // `hooks/list`. Both go in as `-c` flags, which Codex merges into the
323
+ // person's own hook trust rather than replacing it. If a later Codex hashes
324
+ // differently, `hooks/list` shows the hook untrusted and codex.mjs refuses to
325
+ // start the run: it fails closed, never open.
326
+ //
327
+ // A hook that crashes or times out does not block in Codex, so the hook
328
+ // refuses whatever it cannot read, and runs on the node running this bridge.
329
+
330
+ /** The key Codex gives the first PreToolUse hook passed with `-c`. */
331
+ export const CODEX_LOGIN_HOOK_KEY = "/<session-flags>/config.toml:pre_tool_use:0:0";
332
+ const CODEX_HOOK_SCRIPT = fileURLToPath(new URL("./otherLoginHook.mjs", import.meta.url));
333
+ const CODEX_HOOK_TIMEOUT_SEC = 30;
334
+
335
+ /** A word as one literal shell word for the shell Codex runs a hook with
336
+ * (`$SHELL -lc` on a Mac or Linux, `cmd /C` on Windows). A hook that fails to
337
+ * start lets the call run in Codex, so a path must never expand: in sh a
338
+ * single-quoted word is literal (`$`, backticks and `\` included; a `'` is
339
+ * written `'\''`). cmd.exe has no such quote: inside `"..."` a `%` still
340
+ * expands and a `"` ends the word, so a path holding either is refused, and
341
+ * the run with it (codex.mjs), rather than quoted wrongly. */
342
+ const shellWord = (word, platform = process.platform) => {
343
+ const text = String(word);
344
+ if (platform !== "win32") return `'${text.replaceAll("'", "'\\''")}'`;
345
+ if (/["%\r\n]/.test(text)) throw new Error(`The block on other logins cannot be started from this path on Windows: ${text}`);
346
+ return `"${text}"`;
347
+ };
348
+
349
+ /** Sorted-key JSON, the way serde_json's `sort_all_objects` writes it. */
350
+ const sortedJson = (value) => {
351
+ if (Array.isArray(value)) return `[${value.map(sortedJson).join(",")}]`;
352
+ if (value && typeof value === "object") {
353
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${sortedJson(value[key])}`).join(",")}}`;
354
+ }
355
+ return JSON.stringify(value);
356
+ };
357
+
358
+ /** Codex's trust hash for one command hook (see TRUST above). */
359
+ export const codexHookHash = ({ eventName, matcher, handler }) =>
360
+ `sha256:${createHash("sha256").update(sortedJson({ event_name: eventName, matcher, hooks: [handler] })).digest("hex")}`;
361
+
362
+ /** The hook's command line: this node, the hook script, and the name of the
363
+ * board's ask in Codex's words, for the refusal it hands back. */
364
+ export const codexLoginHookCommand = ({ ask, node = process.execPath, script = CODEX_HOOK_SCRIPT, platform = process.platform } = {}) =>
365
+ [node, script, ...(ask ? [ask] : [])].map((word) => shellWord(word, platform)).join(" ");
366
+
367
+ /** The `-c` flags that give a Codex run the hook, already trusted. */
368
+ export function codexOtherLoginArgs(options = {}) {
369
+ const command = codexLoginHookCommand(options);
370
+ const handler = { type: "command", command, timeout: CODEX_HOOK_TIMEOUT_SEC, async: false };
371
+ const hash = codexHookHash({ eventName: "pre_tool_use", matcher: "*", handler });
372
+ return [
373
+ "-c", `hooks.PreToolUse=[{matcher="*", hooks=[{type="command", command=${JSON.stringify(command)}, timeout=${CODEX_HOOK_TIMEOUT_SEC}}]}]`,
374
+ "-c", `hooks.state={${JSON.stringify(CODEX_LOGIN_HOOK_KEY)}={trusted_hash=${JSON.stringify(hash)}}}`,
375
+ ];
376
+ }
377
+
378
+ /** The command a hook's tool input runs, or null when it runs none (an MCP
379
+ * tool's arguments). An argv list is quoted word by word, so `bash -lc '...'`
380
+ * is read inside. */
381
+ export function hookCommandOf(input) {
382
+ const command = input?.command ?? input?.cmd;
383
+ if (typeof command === "string") return command;
384
+ if (Array.isArray(command)) return command.map((word) => `'${String(word).replaceAll("'", "'\\''")}'`).join(" ");
385
+ return command == null ? null : String(command);
386
+ }
@@ -50,6 +50,11 @@ export const ALLOW = "Allow";
50
50
  * allow" (one exact command, #3726) never covers. */
51
51
  export const ALLOW_RUN = "Allow for this run";
52
52
  export const NOT_THIS = "Not this";
53
+ /** The lead the app puts before words typed on a permission (#8224), so they
54
+ * can never equal a label, even on a runner that only matches labels. */
55
+ export const TYPED_NO = "Not this: ";
56
+ /** What check_answer says after a typed answer's question id (board-mcp questionStatus.mjs). */
57
+ const TYPED_MARK = "typed in their own words, not a pick";
53
58
  /** "Always allow git status in my-app" names the safe family it saves (#3726);
54
59
  * without one (a tool, not a shell command) it stays "Always allow in my-app". */
55
60
  export const alwaysLabel = (folderName, word = "") => word === "" ? `Always allow in ${folderName}` : `Always allow ${word} in ${folderName}`;
@@ -602,11 +607,17 @@ export function ruleCovers(rules, toolName, input, folder, base) {
602
607
  // ---------------------------------------------------------------------------
603
608
 
604
609
  /** What check_answer said, as one of: {state:"open"}, {state:"answered",
605
- * decision}, {state:"gone"} (dismissed, or no such question). */
610
+ * decision, typed}, {state:"gone"} (dismissed, or no such question). `typed`:
611
+ * the person wrote the answer rather than picked it (#8224). The decision is
612
+ * every line up to the question's id, so words on several lines stay whole. */
606
613
  export function readAnswer(text) {
607
614
  const t = String(text ?? "");
608
- const answered = /^Answered\. The user's decision: (.*)$/m.exec(t);
609
- if (answered) return { state: "answered", decision: answered[1].trim() };
615
+ const whole = /^Answered\. The user's decision: ([\s\S]*)\n\(question [^\n]*\)\s*$/.exec(t);
616
+ const answered = whole ?? /^Answered\. The user's decision: (.*)$/m.exec(t);
617
+ if (answered) {
618
+ const typed = new RegExp(`\\n\\(question [^\\n]*; ${TYPED_MARK}\\)\\s*$`).test(t);
619
+ return { state: "answered", decision: answered[1].trim(), typed };
620
+ }
610
621
  if (/^Answered\./m.test(t)) return { state: "answered", decision: "" };
611
622
  if (/dismissed|^No such question/m.test(t)) return { state: "gone" };
612
623
  return { state: "open" };
@@ -623,15 +634,29 @@ export function verdictFor(answer, folderName, always = alwaysLabel(folderName),
623
634
  if (answer.state === "gone") {
624
635
  return { behavior: "deny", remember: false, message: "The person dismissed the question without answering. Carry on without it, and do not ask for it again." };
625
636
  }
637
+ // WORDS NEVER GRANT (#8224): only a picked Allow, Always or run label does.
638
+ // Typed words are a no plus the words, even words that spell a label.
639
+ if (answer.typed === true || isTypedNo(answer.decision)) return wordsVerdict(typedWords(answer.decision));
626
640
  if (answer.decision === ALLOW) return { behavior: "allow", remember: false };
627
641
  if (runOffered && answer.decision === ALLOW_RUN) return { behavior: "allow", remember: false, forRun: true };
628
642
  if (always && answer.decision === always) return { behavior: "allow", remember: true };
629
643
  if (answer.decision === NOT_THIS || answer.decision === "") return { behavior: "deny", remember: false, message: NO_MESSAGE };
630
644
  // Their own words: not a button. That is a no, with the words passed along,
631
645
  // because "use yarn instead" is guidance the agent should read.
632
- return { behavior: "deny", remember: false, message: `The person said no to this, and wrote: ${oneLine(answer.decision, 400)}. Carry on without it.` };
646
+ return wordsVerdict(answer.decision);
633
647
  }
634
648
 
649
+ /** The words behind the app's typed lead, or the answer as it came. */
650
+ export const typedWords = (decision) => isTypedNo(decision) ? decision.slice(TYPED_NO.trim().length).trim() : decision.trim();
651
+
652
+ /** The answer starts with the app's typed lead (its space may be trimmed off). */
653
+ export const isTypedNo = (decision) => decision === TYPED_NO.trim() || decision.startsWith(TYPED_NO);
654
+
655
+ /** A no that passes the person's words on, or a plain no when there are none. */
656
+ const wordsVerdict = (words) => words === ""
657
+ ? { behavior: "deny", remember: false, message: NO_MESSAGE }
658
+ : { behavior: "deny", remember: false, message: `The person said no to this, and wrote: ${oneLine(words, 400)}. Carry on without it.` };
659
+
635
660
  /** The deny an agent reads when the question could not be filed. The board's
636
661
  * own refusal ("The run's idea is missing or deleted...") is the reason, so it
637
662
  * reaches the run's transcript instead of a vague "could not be asked" (#592). */
@@ -802,7 +827,7 @@ export function createPermissionAsker({
802
827
  if (answer.state !== "open") {
803
828
  if (question) return answer.state === "gone"
804
829
  ? { behavior: "cancel" }
805
- : { behavior: "answer", answer: answer.decision };
830
+ : { behavior: "answer", answer: answer.decision, ...(answer.typed ? { typed: true } : {}) };
806
831
  const verdict = verdictFor(answer, folderName, q.options.find((o) => o.startsWith("Always allow")) ?? null, { runOffered: q.options.includes(ALLOW_RUN) });
807
832
  if (verdict.forRun) runAllowed.abort();
808
833
  if (verdict.remember && !rememberable(toolName, input)) log("permission: this grant names no scope, so it is allowed once and not remembered");
@@ -21,7 +21,7 @@ import { mkdir, readFile, stat } from "node:fs/promises";
21
21
  import { dirname, join } from "node:path";
22
22
  import { parse as parseToml, stringify } from "smol-toml";
23
23
  import { parse as parseJsonc, modify, applyEdits } from "jsonc-parser";
24
- import { BOARD_MCP_URL, CODEX_TOOL_TIMEOUT_SEC, RETIRED_BOARD_MCP_URLS, entryIsAtRetiredUrl, isLegacyBoardCommand, moveRetiredUrl } from "./mcpjson.mjs";
24
+ import { BOARD_MCP_URL, CODEX_TOOL_TIMEOUT_SEC, RETIRED_BOARD_MCP_URLS, boardEntryIsOurs, entryIsAtRetiredUrl, isLegacyBoardCommand, moveRetiredUrl } from "./mcpjson.mjs";
25
25
  import { writeFileAtomic } from "./atomic.mjs";
26
26
 
27
27
  const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -110,31 +110,11 @@ function withMovedTomlUrl(text, header, to) {
110
110
  return null;
111
111
  }
112
112
 
113
- /** Is this Codex `board` table ours - the retired spawned-command shape, or
114
- * a `board` entry already sitting at our hosted URL from before this
115
- * rename? Mirrors `boardEntryIsOurs` in lib/mcpjson.mjs; kept as its own
116
- * function here because the TOML shape (`{url}`, no `type`) is Codex's own.
117
- *
118
- * EXPORTED (brief 31 review, 2026-09-12) for the same reuse reason as
119
- * `withoutTomlTable` above. */
120
- export function boardEntryIsOurs(entry, env) {
121
- if (!object(entry)) return false;
122
- if (isLegacyBoardCommand(entry.command, entry.args)) return true;
123
- return typeof entry.url === "string" && (entry.url === BOARD_MCP_URL(env) || RETIRED_BOARD_MCP_URLS.includes(entry.url));
124
- }
125
-
126
- /** opencode's own shape: a `command` ARRAY rather than separate
127
- * `command`/`args` strings, plus `{type, url}` for the hosted shape. Kept as
128
- * its own function (rather than reusing `boardEntryIsOurs` above) because
129
- * opencode's `command` field is an array where Codex's and `.mcp.json`'s are
130
- * separate `command`/`args` strings - EXPORTED for the same reuse reason as
131
- * `withoutTomlTable` and `boardEntryIsOurs` above: lib/uninstall-project.mjs
132
- * used to keep a byte-identical copy of exactly this check. */
133
- export function opencodeBoardEntryIsOurs(entry, env) {
134
- if (!object(entry)) return false;
135
- if (Array.isArray(entry.command) && isLegacyBoardCommand(entry.command[0], entry.command.slice(1))) return true;
136
- return typeof entry.url === "string" && (entry.url === BOARD_MCP_URL(env) || RETIRED_BOARD_MCP_URLS.includes(entry.url));
137
- }
113
+ /** Is this Codex `board` table or opencode `board` entry ours? One check for
114
+ * every format since #7550: `boardEntryIsOurs` in lib/mcpjson.mjs reads a
115
+ * `command`/`args` pair and opencode's command array alike. Both names stay
116
+ * exported because lib/uninstall-project.mjs imports them. */
117
+ export { boardEntryIsOurs, boardEntryIsOurs as opencodeBoardEntryIsOurs };
138
118
 
139
119
  export function mergeCodexBoard(existing, env = process.env) {
140
120
  try {
@@ -208,7 +188,7 @@ export function mergeOpencodeBoard(existing, env = process.env) {
208
188
  const glytchPresent = Object.hasOwn(parsed.mcp ?? {}, "glytch");
209
189
  const boardPresent = Object.hasOwn(parsed.mcp ?? {}, "board");
210
190
  const existingBoard = parsed.mcp?.board;
211
- const boardIsOurs = boardPresent && opencodeBoardEntryIsOurs(existingBoard, env);
191
+ const boardIsOurs = boardPresent && boardEntryIsOurs(existingBoard, env);
212
192
  const legacyCommand = boardIsOurs && object(existingBoard) && Array.isArray(existingBoard.command) &&
213
193
  isLegacyBoardCommand(existingBoard.command[0], existingBoard.command.slice(1));
214
194
  const server = { type: "remote", url: BOARD_MCP_URL(env), enabled: true };
package/lib/registry.mjs CHANGED
@@ -75,6 +75,16 @@ export async function folderWasRemoved(folder, env = process.env) {
75
75
  return existsSync(removedPath(folder, env));
76
76
  }
77
77
 
78
+ /** The listed folders minus those the person removed. Only an explicit add
79
+ * clears the mark, so a stray write that puts a folder back in the list
80
+ * cannot bring it back to life: the watcher, the registration and the
81
+ * presence list all read through this (#8325). */
82
+ export async function withoutRemoved(listed, env = process.env) {
83
+ const kept = [];
84
+ for (const folder of listed) if (!(await folderWasRemoved(folder, env))) kept.push(folder);
85
+ return kept;
86
+ }
87
+
78
88
  // TEMPORARY FOLDERS ARE NEVER REGISTERED (QA 2026-10-01, ticket e7). An agent
79
89
  // once started a runner from its scratchpad, and "proof-project
80
90
  // (/private/tmp/claude-501/...)" sat in Settings > Connection for days. A
@@ -167,12 +177,31 @@ async function writeRegistry(folders, env = process.env) {
167
177
  await writeFileAtomic(registryPath(env), `${JSON.stringify(folders, null, 2)}\n`);
168
178
  }
169
179
 
180
+ // EVERY READ-MODIFY-WRITE OF THE LIST RUNS UNDER THE ONE REGISTRY LOCK (#8325).
181
+ // touchRegistry once read the list, waited, and wrote it back after a Forget
182
+ // had removed the folder, which restored it and made the daemon watch it again.
183
+ // The public writers below take the lock themselves. The lock is not
184
+ // reentrant, so a caller that already holds it (a Forget, a restore) calls the
185
+ // `...HoldingLock` twin of the same writer: the code is shared, only the
186
+ // locking differs.
187
+
188
+ function refuseScratchFolder(path, env) {
189
+ if (isScratchFolder(path, env)) throw new Error(`${path} is a temporary folder, and those are never registered. Run viewable init in the project folder itself.`);
190
+ }
191
+
170
192
  /** Add a folder. Idempotent by absolute path: running `init` twice in one
171
193
  * folder leaves one entry, and the second run is not an error. Returns
172
194
  * {folders, added}. */
173
195
  export async function addFolder(folder, env = process.env) {
196
+ // Refused before the lock, so a refused folder never touches the home.
197
+ refuseScratchFolder(resolve(folder), env);
198
+ return withRegistryLock(() => addFolderHoldingLock(folder, env), env);
199
+ }
200
+
201
+ /** addFolder for a caller that already holds the registry lock. */
202
+ export async function addFolderHoldingLock(folder, env = process.env) {
174
203
  const path = resolve(folder);
175
- if (isScratchFolder(path, env)) throw new Error(`${path} is a temporary folder, and those are never registered. Run viewable init in the project folder itself.`);
204
+ refuseScratchFolder(path, env);
176
205
  const folders = await readRegistry(env);
177
206
  // Adding is the person asking for the folder back (init, sync): the record
178
207
  // of its removal ends here, even when it is already listed.
@@ -189,7 +218,7 @@ export async function addFolder(folder, env = process.env) {
189
218
  export async function addFolderUnlessRemoved(folder, env = process.env) {
190
219
  return withRegistryLock(async () => {
191
220
  if (await folderWasRemoved(folder, env)) return null;
192
- return addFolder(folder, env);
221
+ return addFolderHoldingLock(folder, env);
193
222
  }, env);
194
223
  }
195
224
 
@@ -198,6 +227,11 @@ export async function addFolderUnlessRemoved(folder, env = process.env) {
198
227
  * which is how `viewable init` in a folder already watched gets the fresh beat
199
228
  * it waits for (#813 review). A registry that is not there stays absent. */
200
229
  export async function touchRegistry(env = process.env) {
230
+ return withRegistryLock(() => touchRegistryHoldingLock(env), env);
231
+ }
232
+
233
+ /** touchRegistry for a caller that already holds the registry lock. */
234
+ export async function touchRegistryHoldingLock(env = process.env) {
201
235
  const { folders, ok } = await readRegistryChecked(env);
202
236
  if (!ok || folders.length === 0) return false;
203
237
  await writeRegistry(folders, env);
@@ -208,6 +242,11 @@ export async function touchRegistry(env = process.env) {
208
242
  * never registered is not an error either - the end state is what was asked
209
243
  * for. */
210
244
  export async function removeFolder(folder, env = process.env) {
245
+ return withRegistryLock(() => removeFolderHoldingLock(folder, env), env);
246
+ }
247
+
248
+ /** removeFolder for a caller that already holds the registry lock. */
249
+ export async function removeFolderHoldingLock(folder, env = process.env) {
211
250
  const path = resolve(folder);
212
251
  const folders = await readRegistry(env);
213
252
  // Recorded even when it was not listed: the person asked for it gone.
@@ -223,6 +262,11 @@ export async function removeFolder(folder, env = process.env) {
223
262
  * the caller can log one line each (the sweep does). A folder that is gone is
224
263
  * gone: nothing here creates it back, and nothing exits over it. */
225
264
  export async function pruneMissing(env = process.env) {
265
+ return withRegistryLock(() => pruneMissingHoldingLock(env), env);
266
+ }
267
+
268
+ /** pruneMissing for a caller that already holds the registry lock. */
269
+ export async function pruneMissingHoldingLock(env = process.env) {
226
270
  const folders = await readRegistry(env);
227
271
  const kept = [];
228
272
  const dropped = [];
@@ -13,6 +13,7 @@ import { liveRuns, restartPass, RECOVERY_RECHECK_MS, RESTART_RECHECK_MS } from "
13
13
  import { orphanRecoveries } from "./runnerRecovery.mjs";
14
14
  import { flushCompletions } from "./runnerSettlement.mjs";
15
15
  import { SERVER_SWEEP_INTERVAL_MS, sweepDetachedServers } from "./serverSweep.mjs";
16
+ import { sweepIdleWorktrees } from "./worktreeSweep.mjs";
16
17
  import { createSharedPreviewService } from "./sharedPreview.mjs";
17
18
  import { createMemberPreviewTunnel } from "./memberPreview.mjs";
18
19
  import { beatPace } from "./runnerPace.mjs";
@@ -102,6 +103,19 @@ export function makeBeatLoop(w) {
102
103
  log(`dev server sweep failed: ${error instanceof Error ? error.message : String(error)}`);
103
104
  }
104
105
  };
106
+ // THE TREES BEFORE #8266 LEFT BEHIND, once when this watcher starts, after
107
+ // the restart pass so a run it carries on is live and not looked at
108
+ // (lib/worktreeSweep.mjs). A failure is tried again at the next start.
109
+ let treesSwept = false;
110
+ const sweepTrees = async () => {
111
+ if (treesSwept) return;
112
+ treesSwept = true;
113
+ try {
114
+ await (settings.sweepIdleWorktrees ?? sweepIdleWorktrees)(w.project, settings, { log });
115
+ } catch (error) {
116
+ log(`worktree sweep failed: ${error instanceof Error ? error.message : String(error)}`);
117
+ }
118
+ };
105
119
  // Recheck periodically too: the same watcher may lose touch and recover
106
120
  // more than once without restarting its own process (#1252).
107
121
  let restartDueAt = 0;
@@ -256,6 +270,7 @@ export function makeBeatLoop(w) {
256
270
  try { lateMessagesDueAt = nextLateLookAt(await resumeLateMessages(w.project, settings, log), settings); }
257
271
  catch (error) { opsFailed = true; log(`late answers: ${error.message}`); }
258
272
  }
273
+ if (flushed) await sweepTrees();
259
274
  await sweepServers();
260
275
  preview.tick();
261
276
  // Use the existing failure backoff while an answer is waiting, rather
@@ -110,28 +110,29 @@ export async function completeRequest(context, services = defaultServices) {
110
110
 
111
111
  const claudeSessionId = extractSessionIdFromLog(sessionIdSource ?? outcome.log ?? "");
112
112
 
113
- // A CHILD THAT NEVER RAN KEEPS NOTHING "FOR SESSION RESUME" (2026-09-20).
114
- // `outcome.spawnError` means `child.on("error")` fired in child.mjs -
115
- // this machine could not even start the binary (spawn ENOENT, most often)
116
- // - so the worktree `made` names was never touched: no commits, no
117
- // uncommitted changes, nothing a resume could possibly continue. Before
118
- // this, `isPersistent` alone decided the branch below, and a request that
119
- // carries a sessionId/resumeSessionId (every board-spawned session does)
120
- // took the "KEPT for session resume" literal unconditionally - so a run
121
- // that failed to start still held its worktree forever, and the very next
122
- // request on the same prompt was refused as "already has an active
123
- // session" against a tree with nothing in it. `cleanWorktree` is safe to
124
- // call here even though it is NOT normally called for a persistent
125
- // request: it inspects the tree's own git status before removing anything
126
- // (worktree.mjs's `cleanWorktreeImpl`), so a request that also happened to
127
- // fail AFTER doing real work is still `spawnError`-free by definition
128
- // (the child ran, so this branch is not reached) and never hits this path.
129
- const neverStarted = Boolean(outcome.spawnError);
130
- const cleaned = neverStarted
131
- ? await cleanWorktree(root, made, log, [])
132
- : isPersistent
133
- ? { removed: false, detail: `${made.detail}\nKEPT for session resume (persistent session).` }
134
- : await cleanWorktree(root, made, log, []);
113
+ // EVERY ENDED RUN ASKS `cleanWorktree`, A SESSION INCLUDED (#8266, ruling
114
+ // #470: unchanged goes, changed stays until Keep or Throw away). This used
115
+ // to skip the call for any run with a session id and log "KEPT for session
116
+ // resume" - and every board ask has one, so each ask on Your computer left
117
+ // a `.claude/worktrees/glytch-*` tree and a branch behind even when it
118
+ // changed nothing. `cleanWorktree` inspects the tree itself (worktree.mjs's
119
+ // `cleanWorktreeImpl`): commits or uncommitted changes keep it, a failed
120
+ // inspection keeps it, a chat tree is never touched. What a removal costs a
121
+ // session is the conversation Claude Code keeps per working directory,
122
+ // which an unchanged tree had nothing worth resuming for; a reply to it
123
+ // gets a fresh tree (runnerWorkspace.mjs), told by `worktreeRemoved` below.
124
+ //
125
+ // A child that never started (`outcome.spawnError`, 2026-09-20: spawn
126
+ // ENOENT) is the same call; its tree was never touched.
127
+ //
128
+ // ONE TREE IS NOT REMOVED EVEN WHEN NOTHING IN IT CHANGED: the one a
129
+ // detached dev server runs from (the session left a preview going, `server`
130
+ // above). Taking its folder away breaks the preview the person was shown.
131
+ // It stays, with Keep and Throw away, until the server's own sweep or Throw
132
+ // away ends it.
133
+ const cleaned = server && made.isolated && made.path
134
+ ? { removed: false, detail: `${made.detail}\nKEPT: a dev server it started is still running from this worktree.` }
135
+ : await cleanWorktree(root, made, log, []);
135
136
 
136
137
  const treeKept = !cleaned.removed && made.isolated && made.path;
137
138
  let sidecar;
@@ -173,6 +174,10 @@ export async function completeRequest(context, services = defaultServices) {
173
174
  // A chat turn is the one non-isolated case that still needs the path:
174
175
  // it IS the room's cwd, and the next turn is sent back there.
175
176
  ...(cleaned.removed || (!made.isolated && !isChat) ? {} : { worktreePath: made.path ?? made.cwd }),
177
+ // Says WHY a reply finds no tree (#8266): the unchanged tree this run
178
+ // ended in (its own, or an earlier run's it reused) was removed, so a
179
+ // continuation naming that path may start a fresh one (runnerGates.mjs).
180
+ ...(cleaned.removed && made.path ? { worktreeRemoved: made.path } : {}),
176
181
  ...(from ? { fromId: from } : {}),
177
182
  expired: isPersistent ? (!claudeSessionId || outcome.ok !== true) : undefined,
178
183
  ...(summary?.line ? { worktreeSummary: summary.line } : {}),
@@ -210,6 +215,7 @@ export async function completeRequest(context, services = defaultServices) {
210
215
  preview: Number.isFinite(Number(server?.port)) ? `http://localhost:${Number(server.port)}` : undefined,
211
216
  });
212
217
  resultLanded = receipt?.landed === true;
218
+ if (typeof receipt?.refusal === "string") log(`[${id}] the closing reply did not land on the board: ${receipt.refusal.slice(0, 500)}`);
213
219
  } catch (error) {
214
220
  log(`[${id}] could not comment the outcome onto the board: ${error instanceof Error ? error.message : String(error)}`);
215
221
  }