viewable-one 0.12.5 → 0.12.7

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.
package/lib/update.mjs CHANGED
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { createRequire } from "node:module";
18
18
  import { execFile } from "node:child_process";
19
- import { existsSync, readFileSync } from "node:fs";
19
+ import { readFileSync } from "node:fs";
20
20
  import { realpath } from "node:fs/promises";
21
21
  import { basename, join, posix, win32 } from "node:path";
22
22
  import { readRunnerHealth, waitForRunnerHealth } from "./runner-health.mjs";
@@ -24,6 +24,7 @@ import { noDaemonInstall } from "./logindaemon.mjs";
24
24
  import { markQuietStop } from "./goodbye.mjs";
25
25
  import { fileURLToPath } from "node:url";
26
26
 
27
+ import { npmCommand } from "./npm-command.mjs";
27
28
  import { runnableCommand } from "./windows-command.mjs";
28
29
 
29
30
  export const DAY_MS = 86_400_000;
@@ -61,61 +62,16 @@ export function compareVersions(a, b) {
61
62
  return 0;
62
63
  }
63
64
 
64
- /** Run npm. `exec` is injected so the tests never touch the network.
65
- *
66
- * npm installs as `npm.cmd` on Windows, so this goes through the same
67
- * `runnableCommand` resolution as every other binary this package looks for -
68
- * otherwise the version row lies and says "offline" on a machine with a
69
- * perfectly good connection.
70
- *
71
- * WHICH npm (#5305). The first `npm` on the PATH is not necessarily the one
72
- * whose prefix holds this Viewable: a Mac with a system Node and nvm has
73
- * `/usr/local/bin/npm` first while Viewable lives under nvm, and installing
74
- * with the wrong one writes to a folder the person cannot write to. So the
75
- * npm that sits next to the Node running this process goes first on the
76
- * child's PATH (npm's own `#!/usr/bin/env node` then finds that Node too).
77
- * When no npm sits beside this Node (npx), or the Node is one of Volta's
78
- * images, the PATH decides as before: Volta's own npm shim installs into the
79
- * package image that #707's verification expects, and the image's bundled npm
80
- * would not.
81
- * Every npm call in this file goes through `execNpm`, so `viewable update`,
82
- * the no-paste Update, and the version checks all agree. This returns the env
83
- * to run npm with. */
84
- export function npmPathFor({ platform = process.platform, env = process.env, nodePath = process.execPath, exists = existsSync } = {}) {
85
- const path = platform === "win32" ? win32 : posix;
86
- const nodeDir = path.dirname(nodePath);
87
- const voltaHome = String(env?.VOLTA_HOME ?? "");
88
- if (/[\\/]tools[\\/]image[\\/]node[\\/]/.test(nodePath) || (voltaHome && nodePath.startsWith(voltaHome))) return env;
89
- if (!exists(path.join(nodeDir, platform === "win32" ? "npm.cmd" : "npm"))) return env;
90
- const key = Object.keys(env ?? {}).find((k) => (platform === "win32" ? k.toUpperCase() === "PATH" : k === "PATH")) ?? "PATH";
91
- const rest = String(env?.[key] ?? "").split(path.delimiter).filter((dir) => dir && dir !== nodeDir);
92
- return { ...env, [key]: [nodeDir, ...rest].join(path.delimiter) };
93
- }
94
-
95
- /** Resolves `{ ok, stdout, stderr, timedOut }`; `stderr` is what
96
- * `installFailureReason` reads. */
97
- /** Node's own Windows install ships `npm.cmd` as a launcher that starts
98
- * through variables ("%NODE_EXE%" "%NPM_CLI_JS%" %*), which `runnableCommand`
99
- * rightly refuses. Beside that Node the entry script is always at the same
100
- * place, so run it with that Node instead of the shim. */
101
- function nodeBesideNpm({ platform, nodePath, exists = existsSync }) {
102
- if (platform !== "win32") return null;
103
- const cli = win32.join(win32.dirname(nodePath), "node_modules", "npm", "bin", "npm-cli.js");
104
- return exists(cli) ? { file: nodePath, args: [cli], shell: false } : null;
105
- }
106
-
107
- export const execNpm = (args, { timeoutMs = NPM_TIMEOUT_MS, platform = process.platform, env = process.env, exists, readFile, execImpl = execFile, nodePath = process.execPath } = {}) =>
65
+ /** All npm calls target the running package's global prefix, even when
66
+ * env node started it with another Node. See npm-command.mjs for manager
67
+ * fallbacks; CLI, board Update and daily checks share this resolution. */
68
+ export { npmPathFor } from "./npm-command.mjs";
69
+ export const execNpm = (args, { timeoutMs = NPM_TIMEOUT_MS, execImpl = execFile, ...options } = {}) =>
108
70
  new Promise((resolve) => {
109
- let resolved;
110
- const npmEnv = npmPathFor({ platform, env, nodePath, ...(exists ? { exists } : {}) });
111
- const beside = nodeBesideNpm({ platform, nodePath, ...(exists ? { exists } : {}) });
112
- try {
113
- resolved = beside ? { ...beside, args: [...beside.args, ...args] } : runnableCommand("npm", args, { platform, env: npmEnv, nodePath, ...(exists ? { exists } : {}), ...(readFile ? { readFile } : {}) });
114
- } catch {
115
- resolve({ ok: false, stdout: "", stderr: "" });
116
- return;
117
- }
118
- execImpl(resolved.file, resolved.args, { timeout: timeoutMs, windowsHide: true, env: npmEnv, shell: resolved.shell }, (error, stdout, stderr) =>
71
+ let command;
72
+ try { command = npmCommand(args, options); }
73
+ catch { resolve({ ok: false, stdout: "", stderr: "" }); return; }
74
+ execImpl(command.file, command.args, { timeout: timeoutMs, windowsHide: true, env: command.env, shell: command.shell }, (error, stdout, stderr) =>
119
75
  resolve({ ok: !error, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), ...(error?.killed ? { timedOut: true } : {}) }),
120
76
  );
121
77
  });
@@ -131,7 +87,7 @@ export function installFailureReason(result, where = "") {
131
87
  // npm prints the path quoted after a colon, or bare ("npm error path /x/.npm/_cacache").
132
88
  const named = /^(?:npm (?:error|ERR!)\s+)?path:?\s+'?([^'\r\n]+?)'?\s*$/im.exec(text)?.[1] ?? /'((?:\/|[A-Za-z]:\\)[^']+)'/.exec(text)?.[1] ?? where;
133
89
  if (/[\\/]_cacache\b/.test(named)) return `No permission to write npm's cache folder ${named}. Fix the folder's owner; never run sudo.`;
134
- return `No permission to write ${named || "the npm folder"}. Never run sudo; use the npm that came with the Node running Viewable, or fix the folder's owner.`;
90
+ return `No permission to write ${named || "the npm folder"}. Never run sudo; fix the folder's owner.`;
135
91
  }
136
92
  if (/\bENOSPC\b|no space left/i.test(text)) return "The disk is full.";
137
93
  if (/\b(?:ENOTFOUND|EAI_AGAIN|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENETUNREACH|EPROTO)\b|network/i.test(text)) return "Could not reach npm. Check your connection.";
@@ -331,12 +287,13 @@ export async function initServiceScript({ env = process.env, verify = verifyInst
331
287
  * No init/login/config rewrite, agent execution, or automatic updater. */
332
288
  export async function runUpdate({
333
289
  env = process.env, platform = process.platform, exec = execNpm,
290
+ cliPath = fileURLToPath(new URL("../glytch.mjs", import.meta.url)),
334
291
  verify = verifyInstalledCli, sync, wait = waitForRunnerHealth,
335
292
  readHealth = () => readRunnerHealth(env), now = Date.now, log = () => {},
336
293
  } = {}) {
337
294
  const failure = (error) => ({ ok: false, error });
338
295
  if (noDaemonInstall(env)) return failure("Service changes are disabled. Nothing was installed or restarted.");
339
- const npm = (args, options) => exec(args, { env, platform, ...options });
296
+ const npm = (args, options) => exec(args, { env, platform, cliPath, ...options });
340
297
  const latest = await latestFromNpm({ exec: npm });
341
298
  if (!latest) return failure("Could not check the latest published version. Check your connection and try viewable update again. Nothing was restarted.");
342
299
  const root = await npm(["root", "-g"]);
@@ -400,7 +357,7 @@ export async function installUpdate({
400
357
  } = {}) {
401
358
  const failure = (error) => ({ ok: false, error });
402
359
  if (noDaemonInstall(env)) return failure("Updates are turned off on this computer.");
403
- const npm = (args, options) => exec(args, { env, platform, ...options });
360
+ const npm = (args, options) => exec(args, { env, platform, cliPath: scriptPath, ...options });
404
361
  const latest = await latestFromNpm({ exec: npm });
405
362
  if (!latest) return failure("Could not reach npm to find the new version.");
406
363
  if (compareVersions(latest, version) <= 0) return { ok: true, version, restart: false };
package/lib/worktree.mjs CHANGED
@@ -27,8 +27,7 @@
27
27
  // usually thrown away.
28
28
 
29
29
  import { execFile } from "node:child_process";
30
- import { symlink, mkdir, rm, access, readFile, writeFile, stat, lstat } from "node:fs/promises";
31
- import { hostname } from "node:os";
30
+ import { symlink, access, readFile, writeFile, lstat } from "node:fs/promises";
32
31
  import { canonicalPath, staysInProject } from "./projectPaths.mjs";
33
32
  import { basename, isAbsolute, join, resolve, sep } from "node:path";
34
33
  // THE PROCESS KILLING LIVES IN procs.mjs since 2026-09-02: it is about
@@ -42,6 +41,7 @@ import { basename, isAbsolute, join, resolve, sep } from "node:path";
42
41
  // from here is what keeps these two modules a straight line instead of a
43
42
  // cycle, which is the thing check-portable --strict now looks for.
44
43
  import { CHAT_PREFIX, GLYTCH, killProcessesIn } from "./procs.mjs";
44
+ import { acquireAdmission } from "./admission.mjs";
45
45
  export { CHAT_PREFIX, GLYTCH };
46
46
  export { isOursToKill, parseProcessTable, reapOrphanedWorktreeProcesses, reapableWorktreeName } from "./procs.mjs";
47
47
 
@@ -99,121 +99,91 @@ const exists = async (path) => {
99
99
  // inside one runner can no longer both `git checkout main` and merge at once.
100
100
  // This is the lock that has been here since 2026-09-01.
101
101
  //
102
- // CROSS-PROCESS, a lockdir under the repo's own `.git/`. The comment above
103
- // used to say "one runner process owns a root (the claim files keep two
104
- // runners apart), so an in-process lock is enough", and that was not true of
105
- // the code standing beside it: `spawn-runner.mjs merge <path>` and
106
- // `spawn-runner.mjs delete-worktree <path>` are a SECOND process, typed by a
107
- // person, calling straight into mergeWorktree while a watcher is running. The
108
- // claim files keep two runners from taking the same REQUEST; they say nothing
109
- // about two processes running `git checkout main` in the same second.
102
+ // CROSS-PROCESS, through the SAME exclusive-hard-link protocol the runner's
103
+ // admission lock uses (`admission.mjs`), filed in Git's COMMON directory.
104
+ // `spawn-runner.mjs merge <path>` and `delete-worktree <path>` are a SECOND
105
+ // process, typed by a person, calling straight into mergeWorktree while a
106
+ // watcher is running. The claim files keep two runners from taking the same
107
+ // REQUEST; they say nothing about two processes running `git checkout main` in
108
+ // the same second.
110
109
  //
111
- // `mkdir` is the primitive because it is the one atomic exclusive create every
112
- // filesystem agrees on - the same reasoning the claim file uses `flag: "wx"`.
113
- // The owner file inside it is who holds it, and it is how a lock survives its
114
- // holder being killed: a pid that is gone on this host frees it immediately, a
115
- // lock from another host frees on age alone. Waiting is bounded and losing the
116
- // wait is not fatal - it logs loudly and proceeds, because refusing to clean up
117
- // a worktree is worse than the small race that was there all along.
110
+ // THE COMMON DIRECTORY, NOT `<root>/.git` (#6558). `.git` is a FILE in a linked
111
+ // worktree, so the old `mkdir <root>/.git/pm-repo.lock` always failed there,
112
+ // and a bridge started from a linked worktree never held the lock at all.
113
+ // `git rev-parse --git-common-dir` is the one folder every worktree of a repo
114
+ // shares, so the checkout and each of its linked worktrees now contend for the
115
+ // same lock. It is inside `.git/` for the same reason as before: mergeWorktreeImpl
116
+ // refuses a dirty checkout, and `git status` never reports that folder.
117
+ //
118
+ // NO LOCK, NO CHANGE (#6558). This used to log "proceeding without it" when the
119
+ // lock could not be made or the wait ran out, and then ran the change anyway,
120
+ // which is the one outcome a lock exists to prevent: checkout, stash, merge and
121
+ // reset steps from two callers interleaved. Now a repository that cannot be
122
+ // locked, or a holder that outlasts the wait, REFUSES the change with a
123
+ // RepoLockError that says who holds it. The one exception is a folder that is
124
+ // not a git repository at all: there is nothing to lock and no repository
125
+ // change to make.
118
126
  const lockChains = new Map(); // root -> Promise that resolves when the lock is free
119
127
 
120
- /** How long a lockdir is believed before it is treated as abandoned. Git
121
- * mutations here take seconds; ten minutes is a crashed holder, not a busy
122
- * one. */
123
- export const LOCK_STALE_MS = 10 * 60_000;
124
- /** How long to wait for another process to finish before going ahead anyway. */
128
+ /** How long to wait for another holder to finish before refusing the change. */
125
129
  export const LOCK_WAIT_MS = 60_000;
126
130
  const LOCK_POLL_MS = 150;
127
131
 
128
- // INSIDE `.git/`, and the reason is not tidiness. mergeWorktreeImpl refuses to
129
- // merge into a dirty checkout, and rightly - so a lock that git can SEE makes
130
- // every merge refuse itself. `.git/` is the one directory `git status` never
131
- // reports, it is exactly per-repo, and it is already where git keeps its own
132
- // locks. When `.git` is a file rather than a directory (this root is itself a
133
- // linked worktree) the mkdir fails, and acquireFileLock says so and proceeds.
134
- const lockDirFor = (root) => join(resolve(root), ".git", "pm-repo.lock");
135
-
136
- const stillAlive = (pid) => {
137
- try {
138
- process.kill(pid, 0);
139
- return true;
140
- } catch (error) {
141
- // EPERM means it exists and belongs to somebody else.
142
- return error?.code === "EPERM";
132
+ /** Thrown by withRepoLock, and never run past: the callback did NOT run. */
133
+ export class RepoLockError extends Error {
134
+ constructor(detail) {
135
+ super(detail);
136
+ this.name = "RepoLockError";
137
+ this.code = "REPO_LOCK";
143
138
  }
144
- };
139
+ }
145
140
 
146
- /** Take the cross-process lock. Returns a release function, or null when the
147
- * wait ran out - the caller proceeds either way, and says so. */
141
+ /** Git's common directory for `root`, absolute; null when `root` is not in a
142
+ * repository. Relative output (`.git`) is relative to `root`. */
143
+ async function commonDirOf(root) {
144
+ const found = await git(["rev-parse", "--git-common-dir"], root);
145
+ const out = found.stdout.trim();
146
+ return found.ok && out ? resolve(root, out) : null;
147
+ }
148
+
149
+ /** Where the repository's lock lives, for tests and docs. */
150
+ export const repoLockDirFor = (commonDir) => join(commonDir, "pm-repo-admission");
151
+
152
+ /** Take the cross-process lock. Returns `{ release }` once it is REALLY held,
153
+ * or `{ release: null }` for a folder that is not a repository. Throws
154
+ * RepoLockError when the lock cannot be held. */
148
155
  async function acquireFileLock(root, log) {
149
- const dir = lockDirFor(root);
156
+ const commonDir = await commonDirOf(root);
157
+ if (!commonDir) {
158
+ log("not a git repository; nothing to lock");
159
+ return { release: null };
160
+ }
161
+ const directory = repoLockDirFor(commonDir);
150
162
  const startedAt = Date.now();
151
163
  const deadline = startedAt + LOCK_WAIT_MS;
152
- const mine = { pid: process.pid, host: hostname(), at: Date.now() };
153
- // WAITED, NAMED (2026-09-21, the claim-to-spawn gap). `busy` is only true
154
- // once the FIRST `mkdir` has already lost to EEXIST - so a lock taken on
155
- // the first try logs nothing, same as before, and only a caller that
156
- // actually queued behind another holder pays for a line. `lastOwner` is
157
- // whichever `owner.json` was last read while waiting, so the eventual
158
- // success can say who it waited on even though that holder may have
159
- // released and vanished by the time this loop wins.
160
- let busy = false;
161
- let lastOwner = null;
164
+ let waited = false;
162
165
  for (;;) {
166
+ let admission;
163
167
  try {
164
- await mkdir(dir); // EEXIST when somebody holds it: the whole of the lock
165
- await writeFile(join(dir, "owner.json"), `${JSON.stringify(mine)}\n`, "utf8").catch(() => {});
166
- if (busy) {
167
- const waitedSecs = ((Date.now() - startedAt) / 1000).toFixed(1);
168
- log(
169
- `took the repo lock at ${dir} after waiting ${waitedSecs}s ` +
170
- `(previously held by pid ${lastOwner?.pid ?? "?"} on ${lastOwner?.host ?? "?"})`,
171
- );
172
- }
173
- return async () => { await rm(dir, { recursive: true, force: true }).catch(() => {}); };
168
+ admission = await acquireAdmission(root, { directory });
174
169
  } catch (error) {
175
- if (error?.code !== "EEXIST") {
176
- // No lock is better than no worktree operation: a `.git` that is a
177
- // file (this root is a linked worktree), a read-only checkout, or a
178
- // filesystem that will not mkdir must not stop a merge.
179
- log(`could not take the repo lock (${error?.code ?? error}); proceeding without it`);
180
- return null;
181
- }
182
- busy = true;
183
- let owner = null;
184
- try { owner = JSON.parse(await readFile(join(dir, "owner.json"), "utf8")); } catch { /* mid-write, or crashed between mkdir and write */ }
185
- if (owner) lastOwner = owner;
186
- // A holder that just won the `mkdir` has not written `owner.json` yet,
187
- // so a reader landing in that gap sees the same ENOENT a crashed holder
188
- // would leave forever. Treating "unreadable" as "infinitely old" (age
189
- // measured from `at: 0`) cleared a LIVE lock out from under its holder
190
- // on every such read - a real cross-process race, not just a test one.
191
- // Falling back to the lock DIRECTORY's own age keeps a lock that was
192
- // just taken safe (its mtime is now) while still reclaiming one whose
193
- // holder crashed before ever writing owner.json (the dir ages past
194
- // LOCK_STALE_MS same as always).
195
- let age;
196
- if (owner) {
197
- age = Date.now() - (Number(owner.at) || 0);
198
- } else {
199
- const dirStat = await stat(dir).catch(() => null);
200
- age = dirStat ? Date.now() - dirStat.mtimeMs : 0;
201
- }
202
- const deadHolder = owner?.host === mine.host && Number.isFinite(owner?.pid) && !stillAlive(owner.pid);
203
- if (deadHolder || age > LOCK_STALE_MS) {
204
- log(`clearing a ${deadHolder ? "dead" : "stale"} repo lock at ${dir} (pid ${owner?.pid ?? "?"})`);
205
- await rm(dir, { recursive: true, force: true }).catch(() => {});
206
- continue;
207
- }
208
- if (Date.now() >= deadline) {
209
- log(
210
- `waited ${Math.round(LOCK_WAIT_MS / 1000)}s for the repo lock held by pid ${owner?.pid ?? "?"} ` +
211
- `on ${owner?.host ?? "?"}; going ahead anyway`,
212
- );
213
- return null;
214
- }
215
- await new Promise((r) => setTimeout(r, LOCK_POLL_MS));
170
+ // A read-only repository or a filesystem that will not link: the lock
171
+ // cannot be held, so the change does not run.
172
+ throw new RepoLockError(`Could not take the repo lock at ${directory} (${error?.code ?? error?.message ?? error}). Nothing was changed.`);
216
173
  }
174
+ if (admission.ok) {
175
+ if (waited) log(`took the repo lock at ${directory} after waiting ${((Date.now() - startedAt) / 1000).toFixed(1)}s`);
176
+ return { release: admission.release };
177
+ }
178
+ waited = true;
179
+ if (Date.now() >= deadline) {
180
+ throw new RepoLockError(
181
+ `Waited ${Math.round(LOCK_WAIT_MS / 1000)}s for the repo lock and another process still holds it. ` +
182
+ `Nothing was changed. ${admission.detail} ` +
183
+ `Once you have confirmed that process is stopped, delete ${join(directory, ".admission.lock")} and try again.`,
184
+ );
185
+ }
186
+ await new Promise((r) => setTimeout(r, LOCK_POLL_MS));
217
187
  }
218
188
  }
219
189
 
@@ -233,21 +203,36 @@ async function acquireRepoLock(root) {
233
203
  * first, so a queue of callers inside this process waits on a promise rather
234
204
  * than on a directory. Preparation may supply check/own: check cancellation
235
205
  * after each lock wait, then own the started mutation through its result.
236
- * Callers must not treat the queued lock wait itself as an owned mutation. */
206
+ * Callers must not treat the queued lock wait itself as an owned mutation.
207
+ *
208
+ * `fn` runs only while the lock is held. When it cannot be taken this throws
209
+ * RepoLockError without running `fn`; the exported wrappers below turn that into
210
+ * each operation's own refusal shape. */
237
211
  export async function withRepoLock(root, fn, log = () => {}, lifecycle = {}) {
238
212
  const release = await acquireRepoLock(root);
239
213
  let releaseFile = null;
240
214
  try {
241
215
  lifecycle.check?.();
242
- releaseFile = await acquireFileLock(root, log);
216
+ ({ release: releaseFile } = await acquireFileLock(root, log));
243
217
  lifecycle.check?.();
244
218
  return await (lifecycle.own ? lifecycle.own(fn) : fn());
245
219
  } finally {
246
- if (releaseFile) await releaseFile();
220
+ if (releaseFile) await releaseFile().catch(() => {});
247
221
  release();
248
222
  }
249
223
  }
250
224
 
225
+ /** Run `fn` under the repo lock; a refused lock becomes `onRefused(detail)`.
226
+ * It does not log: the caller that reads the refusal says it once. */
227
+ async function lockedOr(root, fn, lifecycle, onRefused) {
228
+ try {
229
+ return await withRepoLock(root, fn, () => {}, lifecycle);
230
+ } catch (error) {
231
+ if (!(error instanceof RepoLockError)) throw error;
232
+ return onRefused(error.message);
233
+ }
234
+ }
235
+
251
236
  /** The repo's default branch, LOCAL only: `main` if `refs/heads/main` exists,
252
237
  * else `master` if that exists, else null.
253
238
  *
@@ -1166,30 +1151,44 @@ function cachePathspecs(entries) {
1166
1151
  // mergeWorktree calls on the same root are guaranteed to run sequentially, order
1167
1152
  // preserved. Reads (branchOfWorktree, worktreeSummary)
1168
1153
  // stay unlocked.
1154
+ // A REFUSED LOCK IS NOT "NOT A REPOSITORY" (#6558 judge). makeWorktree and
1155
+ // reuseWorktree mark it `lockRefused`, and the runner then spawns NOTHING:
1156
+ // falling back to the linked folder would put the new session in the very
1157
+ // checkout the holder is stashing, merging or resetting.
1169
1158
  export async function makeWorktree(root, id, log = () => {}, title = "", lifecycle) {
1170
- return withRepoLock(root, () => makeWorktreeImpl(root, id, log, title), log, lifecycle);
1159
+ return lockedOr(root, () => makeWorktreeImpl(root, id, log, title), lifecycle, (detail) => ({
1160
+ cwd: root,
1161
+ isolated: false,
1162
+ lockRefused: true,
1163
+ detail,
1164
+ }));
1171
1165
  }
1172
1166
 
1173
1167
  /** The chat tree's mint takes the repo lock like every other git mutation:
1174
1168
  * two rooms' first messages to the same agent, typed at once, are two
1175
1169
  * `worktree add` calls for one path. */
1176
1170
  export async function makeChatWorktree(root, path, log = () => {}, lifecycle) {
1177
- return withRepoLock(root, () => makeChatWorktreeImpl(root, path, log), log, lifecycle);
1171
+ return lockedOr(root, () => makeChatWorktreeImpl(root, path, log), lifecycle, (detail) => ({ ok: false, reason: detail }));
1178
1172
  }
1179
1173
 
1180
1174
  export async function cleanWorktree(root, made, log = () => {}, wroteFiles = []) {
1181
- return withRepoLock(root, () => cleanWorktreeImpl(root, made, log, wroteFiles), log);
1175
+ return lockedOr(root, () => cleanWorktreeImpl(root, made, log, wroteFiles), undefined, (detail) => {
1176
+ log(detail);
1177
+ return { removed: false, detail: `${made?.detail ?? ""}\nKEPT: ${detail}` };
1178
+ });
1182
1179
  }
1183
1180
 
1181
+ /** The tree, null when it is gone, or `{ lockRefused: true, detail }` when the
1182
+ * lock could not be held: the tree may well still be there. */
1184
1183
  export async function reuseWorktree(root, existingPath, log = () => {}, lifecycle) {
1185
- return withRepoLock(root, () => reuseWorktreeImpl(root, existingPath, log), log, lifecycle);
1184
+ return lockedOr(root, () => reuseWorktreeImpl(root, existingPath, log), lifecycle, (detail) => ({ lockRefused: true, detail }));
1186
1185
  }
1187
1186
 
1188
1187
  export async function mergeWorktree(root, worktreePath, log = () => {}) {
1189
- return withRepoLock(root, () => mergeWorktreeImpl(root, worktreePath, log), log);
1188
+ return lockedOr(root, () => mergeWorktreeImpl(root, worktreePath, log), undefined, (detail) => ({ ok: false, detail }));
1190
1189
  }
1191
1190
 
1192
1191
  export async function deleteWorktree(root, worktreePath, log = () => {}) {
1193
- return withRepoLock(root, () => deleteWorktreeImpl(root, worktreePath, log), log);
1192
+ return lockedOr(root, () => deleteWorktreeImpl(root, worktreePath, log), undefined, (detail) => ({ ok: false, detail }));
1194
1193
  }
1195
1194
 
@@ -68,9 +68,23 @@ export function readsOnly(name, args = {}, hints) {
68
68
  return false;
69
69
  return !callVerbs(name, args).some((verb) => verb !== "read");
70
70
  }
71
- export function writeRisk(provider, name, args = {}, hints) {
71
+ /** Whether a call has the shape `rule` names (CallRule in catalog.d.mts). */
72
+ export function callMatches(rule, name, args = {}) {
73
+ if (rule.tools && !rule.tools.includes(name))
74
+ return false;
75
+ if (rule.name !== undefined && !new RegExp(rule.name).test(name))
76
+ return false;
77
+ if (rule.words !== undefined && !new RegExp(rule.words).test(`${name} ${actionTexts(args).join(" ")}`.toLowerCase()))
78
+ return false;
79
+ for (const [arg, values] of Object.entries(rule.args ?? {})) {
80
+ if (!values.some((value) => value === null ? args[arg] === undefined : args[arg] === value))
81
+ return false;
82
+ }
83
+ return !rule.flags || rule.flags.some((flag) => args[flag] === true);
84
+ }
85
+ export function writeRisk(app, name, args = {}, hints) {
72
86
  const words = `${name.replace(/([a-z])([A-Z])/g, "$1_$2")} ${actionTexts(args).join(" ")}`.toLowerCase();
73
- if (provider === "stripe" || MONEY.test(words))
87
+ if (app?.money === true || MONEY.test(words))
74
88
  return "money";
75
89
  if (SENDING.test(words))
76
90
  return "sending";
@@ -94,17 +108,8 @@ export function writeRisk(provider, name, args = {}, hints) {
94
108
  if (callVerbs(name, args).every((verb) => verb === "plain"))
95
109
  return null;
96
110
  }
97
- // A small reviewed list. Any other is open-ended.
98
- if (provider === "linear" && ["create_issue", "update_issue", "save_issue"].includes(name))
99
- return null;
100
- if (provider === "notion" && ["notion-create-pages", "create_pages"].includes(name))
101
- return null;
102
- if (provider === "notion" && ["notion-update-page", "update_page"].includes(name)
103
- && [undefined, "insert_content", "update_properties", "replace_content_range"].includes(args.command))
104
- return null;
105
- if (provider === "github" && (name === "add_issue_comment" || (name === "issue_write" && ["create", "update"].includes(String(args.method)))))
106
- return null;
107
- if (["jira", "atlassian"].includes(provider) && ["createJiraIssue", "editJiraIssue"].includes(name))
111
+ // The app's own reviewed writes, from its catalog row. Any other is open-ended.
112
+ if (app?.reviewed?.some((rule) => callMatches(rule, name, args)))
108
113
  return null;
109
114
  return "open-ended";
110
115
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viewable-one",
3
- "version": "0.12.5",
3
+ "version": "0.12.7",
4
4
  "description": "Run coding agents from the Viewable board. Connects your machine to app.viewable.one, launches a session in its own worktree when you press Run, and streams what it does back to the canvas.",
5
5
  "keywords": [
6
6
  "mcp",