viewable-one 0.12.6 → 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.
@@ -9,6 +9,7 @@ import { createRowsAnswerPoll } from "./rowsAnswers.mjs";
9
9
  import { createPermissionAsker } from "./permissionAsk.mjs";
10
10
  import { makeRowEventStreamer } from "./rowsEvents.mjs";
11
11
  import { AGENTS, agentFor, prepareWorkspace, runnerFor } from "./agents.mjs";
12
+ import { readWorktreeRecord } from "./devserver.mjs";
12
13
  import { classifyExit } from "./exitClass.mjs";
13
14
  import { DEFAULTS, childEnv } from "./child.mjs";
14
15
  import { BOARD_DIR } from "./paths.mjs";
@@ -129,7 +130,14 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
129
130
 
130
131
  const makeRunOpts = runOptionsFor(ctx, state, { imageSuffix, onChunk, childEnvObj, stopCheck, answerPoll, askPermission, receipt });
131
132
  const runOpts = makeRunOpts(plan);
132
- const runFn = runnerFor(agent, useStreaming);
133
+ // A child that left something running in its group after Stop keeps the
134
+ // recovery record, so the next pass can still find and end it (#6557).
135
+ const runner = runnerFor(agent, useStreaming);
136
+ const runFn = async (options) => {
137
+ const outcome = await runner(options);
138
+ if (outcome?.descendantsRemain) await settings.recoveryTracker?.retain(outcome.descendantsRemain);
139
+ return outcome;
140
+ };
133
141
 
134
142
  if (settings.stopped?.has(id)) return await finish({ status: "stopped", result: settings.leaseLost?.has(id) ? "STOPPED\n\nRunner connection expired before the process was started.\n" : "STOPPED\n\nStopped by user request before the process was started.\n", finished_at: new Date().toISOString() });
135
143
  preparation.complete();
@@ -208,6 +216,8 @@ function runOptionsFor({ id, request, runnerApi, rowsOpts, settings, log }, { ag
208
216
  onChunk,
209
217
  requireResume: request.recovery === true && Boolean(request.resumeSessionId),
210
218
  recoveryGroup: Boolean(settings.recoveryTracker),
219
+ // The server the session recorded survives Stop (ruling A, 2026-09-06).
220
+ keepPids: async () => { const record = await readWorktreeRecord(made.cwd); return record ? [Number(record.pid)] : []; },
211
221
  onProcess: settings.recoveryTracker ? (pid) => settings.recoveryTracker.onProcess(pid, { group: platform !== "win32" }) : undefined,
212
222
  onSession: async (threadId) => {
213
223
  receipt.sidecar = { ...receipt.sidecar, [agentFor(agent) === "codex" ? "codexThreadId" : "claudeSessionId"]: threadId, resumeSessionId: threadId, restartable: true };
@@ -60,6 +60,28 @@ async function retainGroups(record, snapshot, identity, gone, onChange = () => {
60
60
  if (retained.length !== (record.groups ?? []).length) { record.groups = retained; onChange(); }
61
61
  }
62
62
 
63
+ /** A retained record is only a reminder that something may still be running.
64
+ * Once every survivor has exited (or its pid belongs to another process now),
65
+ * delete it, so the run stops holding a slot. Only the record this call kept
66
+ * is removed: a newer run with the same id has a different token. */
67
+ function watchSurvivors(path, token, survivors, { readIdentity, isAlive }) {
68
+ const timer = setInterval(async () => {
69
+ try {
70
+ for (const member of survivors) {
71
+ if (!isAlive(member.pid)) continue;
72
+ const current = await readIdentity(member.pid);
73
+ if (current?.command?.includes("<defunct>")) continue;
74
+ if (sameProcessIdentity(member, current) !== false) return; // still running, or cannot tell
75
+ }
76
+ clearInterval(timer);
77
+ try {
78
+ if (JSON.parse(readFileSync(path, "utf8")).retainedToken === token) unlinkSync(path);
79
+ } catch { /* already replaced or removed */ }
80
+ } catch { /* look again next tick */ }
81
+ }, 2000);
82
+ timer.unref?.();
83
+ }
84
+
63
85
  export async function trackRun(project, run, settings, receipt, { readIdentity = readProcessIdentity, readTable = processTable, readGroups = processGroups, isAlive = alive, now = () => performance.now(), after = setTimeout, cancel = clearTimeout } = {}) {
64
86
  if (!run.lease_generation) return null; // Installed server without fencing.
65
87
  const path = recoveryPath(project, run.id, settings);
@@ -74,6 +96,10 @@ export async function trackRun(project, run, settings, receipt, { readIdentity =
74
96
  host: hostname(), pid: process.pid, ownerStartedAt: owner?.startedAt, ownerCommand: owner?.command, budgetMs: wallClockFor(run.request), workingMs: 0, sidecar: receipt.sidecar,
75
97
  ...(preparedResume ? { launching: true, preparedResume: true } : {}) };
76
98
  let closed = false;
99
+ // Set when a stopped child left a running process behind (#6557): the record
100
+ // is then the only thing that can still end it, so close() must not delete it.
101
+ let retained = false;
102
+ let survivors = [];
77
103
  const write = () => {
78
104
  record.workingMs = Math.ceil(performance.now() - started);
79
105
  record.savedAt = Date.now(); // Recovery charges a surviving agent from here.
@@ -180,12 +206,31 @@ export async function trackRun(project, run, settings, receipt, { readIdentity =
180
206
  registering.add(registration);
181
207
  try { persist(); void output(); } catch { (settings.stopped ??= new Set()).add(run.id); }
182
208
  },
183
- async close({ keep = false } = {}) {
209
+ /** A stopped child left these pids running. Save their identities now, so
210
+ * a restart can anchor and end them (stopOrphan), and let close() keep the
211
+ * record until they are gone. */
212
+ async retain(pids = []) {
213
+ retained = true;
214
+ const found = [];
215
+ for (const pid of pids) {
216
+ const identity = await readIdentity(pid);
217
+ if (identity) found.push({ pid, ...identity });
218
+ }
219
+ survivors = found;
220
+ if (found.length) {
221
+ const seen = new Set(found.map(member => member.pid));
222
+ record.processes = [...found, ...(record.processes ?? []).filter(member => !seen.has(member.pid))];
223
+ }
224
+ record.retainedToken = randomUUID();
225
+ try { write(); } catch { /* the previous save still stands */ }
226
+ },
227
+ async close({ keep = retained } = {}) {
184
228
  closed = true; clearInterval(timer);
185
229
  if (outputTimer) { cancel(outputTimer); outputTimer = null; }
186
230
  resolveOutput?.(); resolveOutput = null; pendingOutput = null;
187
231
  try {
188
232
  if (!keep) { try { unlinkSync(path); } catch (error) { if (error.code !== "ENOENT") throw error; } }
233
+ else if (retained && survivors.length) watchSurvivors(path, record.retainedToken, survivors, { readIdentity, isAlive });
189
234
  } finally { await lock.release(); }
190
235
  },
191
236
  };
@@ -95,6 +95,14 @@ export async function prepareRequestWorkspace(context, services = defaultService
95
95
  const isOwnTree = wantedRecordedTree && typeof ownTreePath === "string" && ownTreePath !== "";
96
96
  if (wantedRecordedTree && !isOwnTree) log(`[${id}] the named worktree ${request.worktreePath} is not this idea's own; not reused`);
97
97
  const reusedTree = isOwnTree ? await reuseWorktree(root, ownTreePath, log, lifecycle) : null;
98
+ // THE REPO LOCK COULD NOT BE HELD (#6558): spawn nothing. The tree is not
99
+ // gone and a fallback would put the session in the checkout the holder is
100
+ // changing, so neither "the copy is gone" nor an unisolated run is true.
101
+ const lockRefusal = (detail) => {
102
+ log(`[${id}] refused: ${detail}`);
103
+ return { ok: false, patch: { status: "error", result: `ERROR\n\nNOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n${detail}\n\nRun again once the other repository change has finished.\n`, finished_at: new Date().toISOString() } };
104
+ };
105
+ if (reusedTree?.lockRefused) return lockRefusal(reusedTree.detail);
98
106
  if ((request.recovery === true || (request.continues && isResume)) && wantedRecordedTree && !reusedTree) {
99
107
  return { ok: false, patch: { status: "error", result: "ERROR\n\nThis session cannot continue because its separate copy is gone. Run again to start a new session.\n", finished_at: new Date().toISOString(), sidecar: { ...(request.recovery === true ? { recoveryFailed: true } : {}) } } };
100
108
  }
@@ -118,6 +126,7 @@ export async function prepareRequestWorkspace(context, services = defaultService
118
126
  ? { cwd: root, isolated: false, detail: `Ran in the linked folder per idea setting (worktree off).` }
119
127
  : await makeWorktree(root, id, log, title(request), lifecycle);
120
128
  preparation?.check();
129
+ if (made.lockRefused) return lockRefusal(made.detail);
121
130
 
122
131
  const wantedIsolation = !isChat && !request.cwd && request.useWorktree !== false;
123
132
  if (wantedIsolation && !made.isolated) {
@@ -112,10 +112,11 @@ export async function credentialRemoved({ env = process.env, fetchImpl = fetch,
112
112
  * outside this process (a systemd unit, WMI) starts it with the user's
113
113
  * default environment instead, so the script carries these itself. Keys and
114
114
  * tokens stay out: the uninstall reads the stored sign-in from the home. */
115
- export function carriedEnv(env = process.env) {
115
+ export function carriedEnv(env = process.env, platform = process.platform) {
116
+ // Windows environment names are case-insensitive; retain the supplied Path spelling.
116
117
  const keep = /^(HOME|PATH|USERPROFILE|APPDATA|LOCALAPPDATA|TMPDIR|TEMP|TMP|XDG_[A-Z_]+|(VIEWABLE|GLYTCH)_[A-Z0-9_]+)$/;
117
118
  const secret = /TOKEN|SECRET|KEY|PASSWORD/i;
118
- return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string" && keep.test(name) && !secret.test(name)));
119
+ return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string" && (keep.test(name) || (platform === "win32" && /^PATH$/i.test(name))) && !secret.test(name)));
119
120
  }
120
121
 
121
122
  /** The detached command: `viewable uninstall --yes`, then, only when it
@@ -125,9 +126,19 @@ export function selfUninstallCommand({ execPath = process.execPath, cliPath = CL
125
126
  const npm = globalPackageDir(cliPath, target) ? npmCommand(["uninstall", "-g", "viewable-one"], target) : null;
126
127
  const script = [
127
128
  'const { spawnSync } = require("node:child_process");',
128
- `const env = { ...process.env, ...${JSON.stringify(carriedEnv(env))} };`,
129
+ // The launcher may spell Path differently from the daemon. Collapse aliases
130
+ // before either spawn so Node cannot discard the carried search path.
131
+ 'const mergeEnv = (base, carried) => {',
132
+ ' const merged = { ...base, ...carried };',
133
+ ' if (process.platform === "win32") {',
134
+ ' const key = Object.keys(carried).find((name) => /^path$/i.test(name)) ?? Object.keys(base).find((name) => /^path$/i.test(name));',
135
+ ' for (const name of Object.keys(merged)) if (/^path$/i.test(name) && name !== key) delete merged[name];',
136
+ ' }',
137
+ ' return merged;',
138
+ '};',
139
+ `const env = mergeEnv(process.env, ${JSON.stringify(carriedEnv(env, options.platform))});`,
129
140
  `const done = spawnSync(process.execPath, [${JSON.stringify(cliPath)}, "uninstall", "--yes"], { stdio: "ignore", env });`,
130
- npm ? `if (done.status === 0) spawnSync(${JSON.stringify(npm.file)}, ${JSON.stringify(npm.args)}, { stdio: "ignore", env: { ...env, ...${JSON.stringify(carriedEnv(npm.env))} }, shell: false });` : "",
141
+ npm ? `if (done.status === 0) spawnSync(${JSON.stringify(npm.file)}, ${JSON.stringify(npm.args)}, { stdio: "ignore", env: mergeEnv(env, ${JSON.stringify(carriedEnv(npm.env, options.platform))}), shell: false });` : "",
131
142
  ].join("\n");
132
143
  return { command: execPath, args: ["-e", script], script };
133
144
  }
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.6",
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",