viewable-one 0.12.7 → 0.12.9
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/CHANGELOG.md +119 -0
- package/README.md +8 -3
- package/SPAWN.md +24 -3
- package/glytch.mjs +11 -6
- package/lib/acp.mjs +8 -1
- package/lib/agent-selection.mjs +84 -0
- package/lib/agents.mjs +218 -31
- package/lib/auth.mjs +245 -276
- package/lib/authenticatedHttp.mjs +2 -2
- package/lib/boardside.mjs +3 -1
- package/lib/child.mjs +33 -2
- package/lib/codex.mjs +123 -11
- package/lib/codexApps.mjs +100 -25
- package/lib/computerApps.mjs +85 -10
- package/lib/conversationRules.mjs +37 -3
- package/lib/detect.mjs +20 -5
- package/lib/doctor.mjs +18 -2
- package/lib/folderReads.mjs +15 -4
- package/lib/init-connect.mjs +11 -3
- package/lib/lateResume.mjs +4 -1
- package/lib/mcpjson.mjs +99 -1
- package/lib/multiwatch.mjs +37 -6
- package/lib/otherLoginHook.mjs +31 -0
- package/lib/otherLogins.mjs +386 -0
- package/lib/permissionAsk.mjs +69 -7
- package/lib/project-mcp.mjs +7 -27
- package/lib/registry.mjs +46 -2
- package/lib/runnerBeat.mjs +15 -0
- package/lib/runnerCompletion.mjs +28 -22
- package/lib/runnerExecute.mjs +78 -16
- package/lib/runnerGates.mjs +30 -5
- package/lib/runnerLaunch.mjs +33 -6
- package/lib/runnerOps.mjs +2 -2
- package/lib/runnerRegister.mjs +5 -4
- package/lib/runnerWorkspace.mjs +39 -12
- package/lib/selfUninstall.mjs +6 -8
- package/lib/spawn.mjs +9 -0
- package/lib/sync.mjs +10 -4
- package/lib/update.mjs +12 -6
- package/lib/worktree.mjs +75 -31
- package/lib/worktreeSweep.mjs +122 -0
- package/lib/writePolicy.mjs +434 -0
- package/package.json +1 -1
- package/spawn-runner.mjs +5 -1
package/lib/runnerWorkspace.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// here has nothing to "close" that was not already open - it writes a
|
|
10
10
|
// comment (when the run has an idea at all) and hands the caller a result
|
|
11
11
|
// whose `patch` flips the row straight to `status:'error'`.
|
|
12
|
-
import { makeWorktree, reuseWorktree, resolveContainedCwd } from "./worktree.mjs";
|
|
12
|
+
import { branchOfTreePath, makeWorktree, reuseWorktree, resolveContainedCwd } from "./worktree.mjs";
|
|
13
13
|
import { commentOnAnchor } from "./boardside.mjs";
|
|
14
14
|
import { titleFor } from "./spawn.mjs";
|
|
15
15
|
|
|
@@ -44,7 +44,7 @@ export const IN_PLACE_WORKPLACE =
|
|
|
44
44
|
* made, resumeTreeGone, resumeSessionId}` or `{ok:false, patch}` - the
|
|
45
45
|
* caller writes `patch` through `runnerApi.update`. */
|
|
46
46
|
export async function prepareRequestWorkspace(context, services = defaultServices) {
|
|
47
|
-
const { root, id, request, isResume, session, from, log, otherRunningCount, updateSidecarEarly, isChat, chatCwd, claimedAt, ownTreePath } = context;
|
|
47
|
+
const { root, id, request, isResume, session, from, log, otherRunningCount, updateSidecarEarly, isChat, chatCwd, chatInFolder, claimedAt, ownTreePath, ownTreeRemoved, callTool } = context;
|
|
48
48
|
const { makeWorktree, reuseWorktree, commentOnAnchor: comment, titleFor: title } = services;
|
|
49
49
|
const { preparation, retainSidecar } = context;
|
|
50
50
|
// Only an operation that has acquired the repo lock can own a mutation.
|
|
@@ -91,7 +91,10 @@ export async function prepareRequestWorkspace(context, services = defaultService
|
|
|
91
91
|
// a run of the request's idea made that resolves to the named path, in
|
|
92
92
|
// the tree's own spelling (runner.mjs, round 4 item 70); null when the
|
|
93
93
|
// request names another idea's tree or a path no row of this idea made.
|
|
94
|
-
|
|
94
|
+
// AN ASK THAT ONLY READS APPS (#8261) runs in the folder with tools that only
|
|
95
|
+
// read (agents.mjs), so it needs no copy and leaves none behind.
|
|
96
|
+
const readOnly = !isChat && request.readOnly === true;
|
|
97
|
+
const wantedRecordedTree = !isChat && !readOnly && !request.cwd && request.useWorktree !== false && Boolean(request.worktreePath);
|
|
95
98
|
const isOwnTree = wantedRecordedTree && typeof ownTreePath === "string" && ownTreePath !== "";
|
|
96
99
|
if (wantedRecordedTree && !isOwnTree) log(`[${id}] the named worktree ${request.worktreePath} is not this idea's own; not reused`);
|
|
97
100
|
const reusedTree = isOwnTree ? await reuseWorktree(root, ownTreePath, log, lifecycle) : null;
|
|
@@ -103,7 +106,17 @@ export async function prepareRequestWorkspace(context, services = defaultService
|
|
|
103
106
|
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
107
|
};
|
|
105
108
|
if (reusedTree?.lockRefused) return lockRefusal(reusedTree.detail);
|
|
106
|
-
|
|
109
|
+
// A COPY THE RUNNER REMOVED BECAUSE THE ASK CHANGED NOTHING is not a copy
|
|
110
|
+
// that went missing (#8266). `ownTreeRemoved` is its path, found by the path
|
|
111
|
+
// the request names or by the session it resumes. The reply gets the tree
|
|
112
|
+
// MADE AGAIN AT THAT PATH, so Claude Code (which keeps a conversation per
|
|
113
|
+
// working directory) resumes the whole conversation, not a fresh one told
|
|
114
|
+
// only the new message. Recovery still refuses (it carries on a run that was
|
|
115
|
+
// cut off mid-way), and so does a continuation whose tree vanished any other
|
|
116
|
+
// way (#2446).
|
|
117
|
+
const removedUnchanged = typeof ownTreeRemoved === "string" && ownTreeRemoved !== "" && request.recovery !== true
|
|
118
|
+
&& !isChat && !request.cwd && request.useWorktree !== false && isResume && !reusedTree;
|
|
119
|
+
if ((request.recovery === true || (request.continues && isResume)) && wantedRecordedTree && !reusedTree && !removedUnchanged) {
|
|
107
120
|
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 } : {}) } } };
|
|
108
121
|
}
|
|
109
122
|
if (wantedRecordedTree && !isResume && !reusedTree) log(`[${id}] the kept worktree ${request.worktreePath} is gone; this session gets a new one`);
|
|
@@ -116,25 +129,37 @@ export async function prepareRequestWorkspace(context, services = defaultService
|
|
|
116
129
|
// directory.
|
|
117
130
|
cwd: chatCwd,
|
|
118
131
|
isolated: false,
|
|
119
|
-
detail:
|
|
132
|
+
detail: chatInFolder === true
|
|
133
|
+
? `Chat turn: ran in the folder itself, ${chatCwd}, because it has no commit to make a separate copy from. Anything it changed, it changed there.`
|
|
134
|
+
: `Chat turn: ran in ${chatCwd}, the agent's own chat copy. No copy was made for this message and none was reused.`,
|
|
120
135
|
}
|
|
121
136
|
: reusedTree
|
|
122
137
|
? reusedTree
|
|
123
138
|
: namedCwd
|
|
124
139
|
? { cwd: namedCwd, isolated: false, detail: `Ran in the cwd the request named, ${namedCwd}.` }
|
|
140
|
+
: readOnly
|
|
141
|
+
? { cwd: root, isolated: false, detail: "Read-only app reads in the linked folder. No worktree created." }
|
|
125
142
|
: request.useWorktree === false
|
|
126
143
|
? { cwd: root, isolated: false, detail: `Ran in the linked folder per idea setting (worktree off).` }
|
|
127
|
-
: await makeWorktree(root, id, log, title(request), lifecycle);
|
|
144
|
+
: await makeWorktree(root, id, log, title(request), lifecycle, removedUnchanged ? { path: ownTreeRemoved, branch: branchOfTreePath(ownTreeRemoved) } : undefined);
|
|
128
145
|
preparation?.check();
|
|
129
146
|
if (made.lockRefused) return lockRefusal(made.detail);
|
|
130
147
|
|
|
131
|
-
const wantedIsolation = !isChat && !request.cwd && request.useWorktree !== false;
|
|
132
|
-
|
|
148
|
+
const wantedIsolation = !isChat && !readOnly && !request.cwd && request.useWorktree !== false;
|
|
149
|
+
// A chat that fell back to the folder has the same collision a session does
|
|
150
|
+
// (#7959): a second agent in the same tree, with no branch between them.
|
|
151
|
+
const chatSharesFolder = isChat && chatInFolder === true;
|
|
152
|
+
if ((wantedIsolation && !made.isolated) || chatSharesFolder) {
|
|
133
153
|
const others = typeof otherRunningCount === "function" ? await otherRunningCount() : 0;
|
|
134
154
|
preparation?.check();
|
|
135
155
|
if (others > 0) {
|
|
136
|
-
const detail =
|
|
137
|
-
`NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n` +
|
|
156
|
+
const detail = chatSharesFolder
|
|
157
|
+
? `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n` +
|
|
158
|
+
`This folder has no commit yet, so this chat has no copy of its own, and ${others} other ` +
|
|
159
|
+
`session${others === 1 ? " is" : "s are"} running. Running here would have put two agents in one ` +
|
|
160
|
+
`folder, editing the same files with no branch between them.\n\n` +
|
|
161
|
+
`Send the message again once they are done, or make a first commit in the folder.`
|
|
162
|
+
: `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n` +
|
|
138
163
|
`This session could not get its own worktree, and ${others} other ` +
|
|
139
164
|
`session${others === 1 ? " is" : "s are"} running. Falling back to the linked ` +
|
|
140
165
|
`folder would have put two agents in one working tree, editing the same files ` +
|
|
@@ -142,7 +167,7 @@ export async function prepareRequestWorkspace(context, services = defaultService
|
|
|
142
167
|
`File the request again once they are done, or fix what stopped the worktree.`;
|
|
143
168
|
const frameId = typeof from === "string" ? from : undefined;
|
|
144
169
|
if (frameId) {
|
|
145
|
-
await comment(session, frameId, `Refused before spawning: no worktree, and another session is running\nNothing was spawned and nothing was billed. ${made.detail}
|
|
170
|
+
await comment(session, frameId, `Refused before spawning: no worktree, and another session is running\nNothing was spawned and nothing was billed. ${made.detail}`, callTool ? { callTool } : {});
|
|
146
171
|
}
|
|
147
172
|
log(`[${id}] refused: no worktree while ${others} other session(s) run`);
|
|
148
173
|
return { ok: false, patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
|
|
@@ -180,7 +205,9 @@ export async function prepareRequestWorkspace(context, services = defaultService
|
|
|
180
205
|
// "the recorded tree is gone" and the conversation would restart on every
|
|
181
206
|
// turn. Its directory was checked at the top of `runRequest`, which IS the
|
|
182
207
|
// "can this conversation be reached" question this line exists to ask.
|
|
183
|
-
|
|
208
|
+
// A tree made again at its old path is the same working directory: nothing is gone.
|
|
209
|
+
const remade = removedUnchanged && made.isolated && made.path === ownTreeRemoved;
|
|
210
|
+
const resumeTreeGone = isResume && wantedRecordedTree && !reusedTree && !remade;
|
|
184
211
|
const resumeSessionId = isResume && !resumeTreeGone ? String(request.resumeSessionId).trim() : "";
|
|
185
212
|
return { ok: true, made, resumeTreeGone, resumeSessionId };
|
|
186
213
|
}
|
package/lib/selfUninstall.mjs
CHANGED
|
@@ -18,14 +18,12 @@
|
|
|
18
18
|
// an older board, odd JSON, `removed: false`) for any key leaves the
|
|
19
19
|
// computer exactly as it is.
|
|
20
20
|
//
|
|
21
|
-
// Every key, not the first yes:
|
|
22
|
-
// older OAuth pair beside it
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
// back to the old pair and sends its access token, and a refused refresh
|
|
28
|
-
// sends no key at all.
|
|
21
|
+
// Every key, not the first yes: an older bridge's sign-in with a personal
|
|
22
|
+
// key kept the older OAuth pair beside it, and such records are still on
|
|
23
|
+
// some disks (auth.mjs no longer uses them, #8324). If that older pair was
|
|
24
|
+
// taken away by an earlier Remove and the new personal key is refused for
|
|
25
|
+
// another reason, the pair's yes alone would uninstall a computer nobody
|
|
26
|
+
// removed.
|
|
29
27
|
//
|
|
30
28
|
// `viewable uninstall` stops the background app, revokes the key and deletes
|
|
31
29
|
// ~/.glytch. It never touches the Viewable folder or its files: the folder
|
package/lib/spawn.mjs
CHANGED
|
@@ -285,6 +285,15 @@ export function checkRequest(request) {
|
|
|
285
285
|
"computerApps, when present, must be a boolean. True lets this run use the apps the person set up in Claude Code or Codex.",
|
|
286
286
|
);
|
|
287
287
|
}
|
|
288
|
+
// AN ASK THAT ONLY READS APPS (#8261): the read-only tool set, no worktree,
|
|
289
|
+
// and the apps its plan named, which board-mcp's app_read reads (#8254).
|
|
290
|
+
if (request.readOnly !== undefined && typeof request.readOnly !== "boolean") {
|
|
291
|
+
found.note("readOnly, when present, must be a boolean. True runs the session with tools that only read, in the linked folder.");
|
|
292
|
+
}
|
|
293
|
+
if (request.readApps !== undefined && (!Array.isArray(request.readApps) || request.readApps.length > 50
|
|
294
|
+
|| !request.readApps.every((app) => typeof app === "string" && app.trim() !== "" && app.length <= 100))) {
|
|
295
|
+
found.note("readApps, when present, must be a list of app ids: the apps connected in Viewable that this ask's plan reads.");
|
|
296
|
+
}
|
|
288
297
|
// PERSISTENT SESSIONS: session id fields are UUIDs, worktreePath is an
|
|
289
298
|
// absolute path. All are optional. Validated as strings when present.
|
|
290
299
|
for (const field of ["sessionId", "resumeSessionId"]) {
|
package/lib/sync.mjs
CHANGED
|
@@ -43,7 +43,7 @@ import {
|
|
|
43
43
|
noDaemonInstall,
|
|
44
44
|
} from "./logindaemon.mjs";
|
|
45
45
|
import { BOARD_MCP_URL, mergeBoardServer } from "./mcpjson.mjs";
|
|
46
|
-
import { viewableDisplayPath, addFolder, readRegistry } from "./registry.mjs";
|
|
46
|
+
import { viewableDisplayPath, addFolder, addFolderUnlessRemoved, readRegistry } from "./registry.mjs";
|
|
47
47
|
import { readAgentSelection, parseAgentSelection } from "./agent-selection.mjs";
|
|
48
48
|
import { syncProjectMcp } from "./project-mcp.mjs";
|
|
49
49
|
import { packageVersion } from "./update.mjs";
|
|
@@ -139,12 +139,18 @@ export async function syncOpencode(root, { exec = execProbe, found, write = true
|
|
|
139
139
|
* became "a runner project" because nothing here ever told the person why. A
|
|
140
140
|
* write failure is now the same shape every other row in this file uses -
|
|
141
141
|
* red, with the OS's own reason and something to try - never a crash. */
|
|
142
|
-
export async function syncRegistry(root, { env = process.env, write = true } = {}) {
|
|
142
|
+
export async function syncRegistry(root, { env = process.env, write = true, automatic = false } = {}) {
|
|
143
143
|
const folders = await readRegistry(env);
|
|
144
144
|
if (folders.includes(root)) return row("registry", "folder registered", true, "present", "your computer watches this folder");
|
|
145
145
|
if (!write) return row("registry", "folder registered", false, "missing", `this folder is not in ${viewableDisplayPath(env, "folders.json")}`);
|
|
146
146
|
try {
|
|
147
|
-
|
|
147
|
+
// The daemon's own sync is not the person asking for the folder back:
|
|
148
|
+
// it leaves a removed folder removed (#8325). init and doctor still add.
|
|
149
|
+
if (automatic) {
|
|
150
|
+
if (await addFolderUnlessRemoved(root, env) === null) {
|
|
151
|
+
return row("registry", "folder registered", true, "removed", "this folder was removed; run `viewable init` in it to watch it again");
|
|
152
|
+
}
|
|
153
|
+
} else await addFolder(root, env);
|
|
148
154
|
} catch (error) {
|
|
149
155
|
const why = error instanceof Error ? error.message : String(error);
|
|
150
156
|
return row(
|
|
@@ -480,7 +486,7 @@ export async function syncFolder(
|
|
|
480
486
|
? []
|
|
481
487
|
: parseAgentSelection(selectedAgents);
|
|
482
488
|
const found = agents ?? (await detectAgents({ env }));
|
|
483
|
-
const rows = deferRegistry ? [] : [await syncRegistry(root, { env, write })];
|
|
489
|
+
const rows = deferRegistry ? [] : [await syncRegistry(root, { env, write, automatic: daemon })];
|
|
484
490
|
if (selected === null) {
|
|
485
491
|
rows.push(await syncMcpJson(root, { write, platform, env }));
|
|
486
492
|
rows.push(await syncOpencode(root, { exec, found: found?.opencode?.found === true, write }));
|
package/lib/update.mjs
CHANGED
|
@@ -66,12 +66,15 @@ export function compareVersions(a, b) {
|
|
|
66
66
|
* env node started it with another Node. See npm-command.mjs for manager
|
|
67
67
|
* fallbacks; CLI, board Update and daily checks share this resolution. */
|
|
68
68
|
export { npmPathFor } from "./npm-command.mjs";
|
|
69
|
-
export const execNpm = (args, { timeoutMs = NPM_TIMEOUT_MS, execImpl = execFile, ...options } = {}) =>
|
|
69
|
+
export const execNpm = (args, { timeoutMs = NPM_TIMEOUT_MS, execImpl = execFile, signal, ...options } = {}) =>
|
|
70
70
|
new Promise((resolve) => {
|
|
71
71
|
let command;
|
|
72
72
|
try { command = npmCommand(args, options); }
|
|
73
73
|
catch { resolve({ ok: false, stdout: "", stderr: "" }); return; }
|
|
74
|
-
|
|
74
|
+
// `signal` kills npm when the caller stops, so a background lookup never
|
|
75
|
+
// outlives the process that asked for it (#7557).
|
|
76
|
+
if (signal?.aborted) { resolve({ ok: false, stdout: "", stderr: "" }); return; }
|
|
77
|
+
execImpl(command.file, command.args, { timeout: timeoutMs, windowsHide: true, env: command.env, shell: command.shell, ...(signal ? { signal } : {}) }, (error, stdout, stderr) =>
|
|
75
78
|
resolve({ ok: !error, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), ...(error?.killed ? { timedOut: true } : {}) }),
|
|
76
79
|
);
|
|
77
80
|
});
|
|
@@ -98,8 +101,8 @@ export function installFailureReason(result, where = "") {
|
|
|
98
101
|
return line ? `npm said: ${line.slice(0, 200)}` : "npm did not say why.";
|
|
99
102
|
}
|
|
100
103
|
|
|
101
|
-
export async function latestFromNpm({ exec = execNpm, name = PACKAGE_NAME, timeoutMs = NPM_TIMEOUT_MS } = {}) {
|
|
102
|
-
const result = await exec(["view", name, "version"], { timeoutMs });
|
|
104
|
+
export async function latestFromNpm({ exec = execNpm, name = PACKAGE_NAME, timeoutMs = NPM_TIMEOUT_MS, signal } = {}) {
|
|
105
|
+
const result = await exec(["view", name, "version"], { timeoutMs, ...(signal ? { signal } : {}) });
|
|
103
106
|
if (!result?.ok) return null;
|
|
104
107
|
const version = String(result.stdout).trim().split(/\s+/)[0];
|
|
105
108
|
return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) ? version : null;
|
|
@@ -118,6 +121,9 @@ export function makeUpdateChecker({
|
|
|
118
121
|
intervalMs = DAY_MS,
|
|
119
122
|
now = () => Date.now(),
|
|
120
123
|
log = () => {},
|
|
124
|
+
// Stops the lookup in flight: the runner's stop signal, so Ctrl-C does not
|
|
125
|
+
// leave an `npm view` writing its cache after the runner has exited (#7557).
|
|
126
|
+
signal,
|
|
121
127
|
} = {}) {
|
|
122
128
|
// null rather than 0, so the FIRST beat always asks. With Date.now() a zero
|
|
123
129
|
// would happen to work; with an injected clock starting at zero it silently
|
|
@@ -135,7 +141,7 @@ export function makeUpdateChecker({
|
|
|
135
141
|
running = true;
|
|
136
142
|
checkedAt = now();
|
|
137
143
|
try {
|
|
138
|
-
const found = await latest();
|
|
144
|
+
const found = await latest(signal ? { signal } : undefined);
|
|
139
145
|
if (found) {
|
|
140
146
|
known = found;
|
|
141
147
|
if (compareVersions(found, version) > 0) log(`update available: ${version} -> ${found} (npm i -g ${PACKAGE_NAME})`);
|
|
@@ -150,7 +156,7 @@ export function makeUpdateChecker({
|
|
|
150
156
|
state,
|
|
151
157
|
/** What goes into the mark file, and a check kicked off when one is due. */
|
|
152
158
|
mark() {
|
|
153
|
-
if (!running && (checkedAt === null || now() - checkedAt >= intervalMs)) void run();
|
|
159
|
+
if (!running && !signal?.aborted && (checkedAt === null || now() - checkedAt >= intervalMs)) void run();
|
|
154
160
|
return { version: state().version, updateAvailable: state().updateAvailable };
|
|
155
161
|
},
|
|
156
162
|
/** Await one check. `doctor` and the tests use this. */
|
package/lib/worktree.mjs
CHANGED
|
@@ -293,6 +293,8 @@ export const worktreeName = (id, title) => `${GLYTCH}-${worktreeStem(id, title)}
|
|
|
293
293
|
export const worktreePath = (root, id, title) =>
|
|
294
294
|
join(root, ".claude", "worktrees", worktreeName(id, title));
|
|
295
295
|
export const worktreeBranch = (id, title) => `${GLYTCH}/${worktreeStem(id, title)}`;
|
|
296
|
+
/** The branch a `glytch-<stem>` tree sat on, read off its path (#8266). */
|
|
297
|
+
export const branchOfTreePath = (path) => `${GLYTCH}/${basename(String(path)).replace(new RegExp(`^${GLYTCH}-`), "")}`;
|
|
296
298
|
|
|
297
299
|
/** True only when `target` resolves to a path strictly inside
|
|
298
300
|
* `<root>/.claude/worktrees/` — the one directory makeWorktree ever creates.
|
|
@@ -410,6 +412,21 @@ export function resolveContainedCwd(root, cwd, what = "a run") {
|
|
|
410
412
|
return { ok: true, path };
|
|
411
413
|
}
|
|
412
414
|
|
|
415
|
+
/** The commit a new tree is cut from, for both makeChatWorktreeImpl and
|
|
416
|
+
* makeWorktreeImpl so the two cannot drift: the repo's default branch (main,
|
|
417
|
+
* else master), else HEAD. `empty` is true when none of them has a commit yet
|
|
418
|
+
* (a fresh `git init`): there is nothing to cut a tree from, and writing a
|
|
419
|
+
* commit into someone's repo to make one is not ours to do. */
|
|
420
|
+
async function baseForNewTree(root) {
|
|
421
|
+
const defaultBranch = await defaultBranchOf(root);
|
|
422
|
+
const baseRev = await git(["rev-parse", "--verify", "--quiet", `${defaultBranch ?? "HEAD"}^{commit}`], root);
|
|
423
|
+
const base = baseRev.ok ? baseRev.stdout.trim() : (defaultBranch ?? "HEAD");
|
|
424
|
+
const baseLabel = defaultBranch
|
|
425
|
+
? `${defaultBranch} at ${base.slice(0, 7)}`
|
|
426
|
+
: `HEAD at ${base.slice(0, 7)}, no main or master branch`;
|
|
427
|
+
return { base, baseLabel, empty: !baseRev.ok };
|
|
428
|
+
}
|
|
429
|
+
|
|
413
430
|
/** Mint the chat worktree, once, for a turn that found it missing.
|
|
414
431
|
*
|
|
415
432
|
* `mintIfMissing: true` on the request is what asks for this, and it is asked
|
|
@@ -444,8 +461,8 @@ async function makeChatWorktreeImpl(root, path, log = () => {}) {
|
|
|
444
461
|
ok: false,
|
|
445
462
|
reason:
|
|
446
463
|
`${root} is not a git repository, and a chat with a coding agent needs one: the agent ` +
|
|
447
|
-
`gets its OWN long-lived
|
|
448
|
-
`touching the checkout you are working in, and a
|
|
464
|
+
`gets its OWN long-lived copy of the project so it can read, edit and commit without ` +
|
|
465
|
+
`touching the checkout you are working in, and a copy can only be cut from a repo. ` +
|
|
449
466
|
`Link a folder that is a git checkout, or run \`git init\` in this one, and send the ` +
|
|
450
467
|
`message again.`,
|
|
451
468
|
};
|
|
@@ -470,13 +487,19 @@ async function makeChatWorktreeImpl(root, path, log = () => {}) {
|
|
|
470
487
|
// happens to have checked out - a chat tree cut from a side branch someone
|
|
471
488
|
// left checked out would carry that branch's commits forever. Falls back to
|
|
472
489
|
// HEAD only when neither local branch exists.
|
|
473
|
-
const
|
|
474
|
-
const baseRev = await git(["rev-parse", defaultBranch ?? "HEAD"], root);
|
|
475
|
-
const base = baseRev.ok ? baseRev.stdout.trim() : (defaultBranch ?? "HEAD");
|
|
476
|
-
const baseLabel = defaultBranch
|
|
477
|
-
? `${defaultBranch} at ${base.slice(0, 7)}`
|
|
478
|
-
: `HEAD at ${base.slice(0, 7)}, no main or master branch`;
|
|
490
|
+
const { base, baseLabel, empty } = await baseForNewTree(root);
|
|
479
491
|
const known = await git(["rev-parse", "--verify", branch], root);
|
|
492
|
+
if (empty && !known.ok) {
|
|
493
|
+
// A fresh `git init` has no commit to cut a copy from. The chat runs in
|
|
494
|
+
// the folder itself, as a session does (makeWorktreeImpl), and nothing is
|
|
495
|
+
// written to the person's repo.
|
|
496
|
+
return {
|
|
497
|
+
ok: true,
|
|
498
|
+
path: root,
|
|
499
|
+
folder: true,
|
|
500
|
+
detail: `This folder has no commit yet, so the chat ran in the folder itself rather than a separate copy.`,
|
|
501
|
+
};
|
|
502
|
+
}
|
|
480
503
|
const add = known.ok
|
|
481
504
|
? await git(["worktree", "add", path, branch], root)
|
|
482
505
|
: await git(["worktree", "add", "-b", branch, path, base], root);
|
|
@@ -484,8 +507,8 @@ async function makeChatWorktreeImpl(root, path, log = () => {}) {
|
|
|
484
507
|
return {
|
|
485
508
|
ok: false,
|
|
486
509
|
reason:
|
|
487
|
-
`
|
|
488
|
-
`nothing was billed.\ngit said: ${add.detail}`,
|
|
510
|
+
`This chat's own copy of the project could not be created, so this message did not run and ` +
|
|
511
|
+
`nothing was billed.\n${path}\ngit said: ${add.detail}`,
|
|
489
512
|
};
|
|
490
513
|
}
|
|
491
514
|
|
|
@@ -519,7 +542,7 @@ async function makeChatWorktreeImpl(root, path, log = () => {}) {
|
|
|
519
542
|
* runner that would rather spawn nothing than spawn unisolated is a runner
|
|
520
543
|
* that stops working the day someone tries it outside a checkout, and the
|
|
521
544
|
* money gate - not this - is what decides whether anything runs at all. */
|
|
522
|
-
async function makeWorktreeImpl(root, id, log = () => {}, title = "") {
|
|
545
|
+
async function makeWorktreeImpl(root, id, log = () => {}, title = "", again) {
|
|
523
546
|
const inRepo = await git(["rev-parse", "--is-inside-work-tree"], root);
|
|
524
547
|
if (!inRepo.ok || inRepo.stdout.trim() !== "true") {
|
|
525
548
|
return {
|
|
@@ -533,21 +556,32 @@ async function makeWorktreeImpl(root, id, log = () => {}, title = "") {
|
|
|
533
556
|
|
|
534
557
|
await ensureIgnored(root, log);
|
|
535
558
|
|
|
536
|
-
|
|
559
|
+
// `again`: the tree the runner removed because its ask changed nothing,
|
|
560
|
+
// made once more at the SAME path and branch (#8266). Claude Code keeps a
|
|
561
|
+
// conversation per working directory, so a reply resumes it only from there.
|
|
562
|
+
const path = again?.path ?? worktreePath(root, id, title);
|
|
537
563
|
if (!isContainedWorktree(root, path)) throw new Error("Worktree creation refused: the path leaves this project or traverses a symbolic link.");
|
|
538
|
-
const branch = worktreeBranch(id, title);
|
|
564
|
+
const branch = again?.branch ?? worktreeBranch(id, title);
|
|
565
|
+
// The removed tree's branch is gone with it; one left behind (its removal
|
|
566
|
+
// failed) sits at the base with nothing on it, since only an unchanged tree
|
|
567
|
+
// is ever removed, and would refuse `worktree add -b`.
|
|
568
|
+
if (again) await git(["branch", "-D", branch], root);
|
|
539
569
|
// Branch off the repo's DEFAULT BRANCH (main, else master), not whatever
|
|
540
570
|
// the main checkout happens to have checked out. PROVEN 2026-09-21: basing
|
|
541
571
|
// on HEAD meant a run cut while the checkout sat on a side branch inherited
|
|
542
572
|
// that branch's commits, and "Keep changes" would have dragged the whole
|
|
543
573
|
// thing into main. Falls back to HEAD, and says so, only when neither local
|
|
544
574
|
// branch exists.
|
|
545
|
-
const
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
575
|
+
const { base, baseLabel, empty } = await baseForNewTree(root);
|
|
576
|
+
if (empty) {
|
|
577
|
+
return {
|
|
578
|
+
cwd: root,
|
|
579
|
+
isolated: false,
|
|
580
|
+
detail:
|
|
581
|
+
`This folder has no commit yet, so this session ran in the folder itself ` +
|
|
582
|
+
`rather than a separate copy. Anything it changed, it changed there.`,
|
|
583
|
+
};
|
|
584
|
+
}
|
|
551
585
|
|
|
552
586
|
const add = await git(["worktree", "add", "-b", branch, path, base], root);
|
|
553
587
|
if (!add.ok) {
|
|
@@ -604,7 +638,11 @@ async function cleanWorktreeImpl(root, made, log = () => {}, wroteFiles = []) {
|
|
|
604
638
|
if (!made?.isolated || !made.path) return { removed: false, detail: made?.detail ?? "" };
|
|
605
639
|
if (!(await registeredWorktree(root, made.path))) return { removed: false, detail: "KEPT: worktree ownership could not be verified." };
|
|
606
640
|
|
|
607
|
-
|
|
641
|
+
// THE SAME QUESTION Keep and the summary ask, `uncommittedFiles` (#8266):
|
|
642
|
+
// bare `git status --porcelain` listed the node_modules link the runner made
|
|
643
|
+
// and every untracked cache folder, so a tree whose session changed nothing
|
|
644
|
+
// read as "changed" and was never removed.
|
|
645
|
+
const dirty = await inspectUncommitted(made.path);
|
|
608
646
|
const start = await startOf(made.branch, root);
|
|
609
647
|
const commits = start
|
|
610
648
|
? await git(["log", "--oneline", `${start}..HEAD`], made.path)
|
|
@@ -625,11 +663,7 @@ async function cleanWorktreeImpl(root, made, log = () => {}, wroteFiles = []) {
|
|
|
625
663
|
// opencode.json un-trackable across the whole repository, which only
|
|
626
664
|
// surfaced when checking the file in failed. Deciding it at the one place
|
|
627
665
|
// that asks the question touches no shared git config and cannot leak.
|
|
628
|
-
const theirs = dirty.
|
|
629
|
-
.split("\n")
|
|
630
|
-
.map((l) => l.trim())
|
|
631
|
-
.filter((l) => l !== "")
|
|
632
|
-
.filter((l) => !wroteFiles.some((f) => l.endsWith(` ${f}`) || l.endsWith(`/${f}`)));
|
|
666
|
+
const theirs = dirty.files.filter((path) => !wroteFiles.some((f) => path === f || path.endsWith(`/${f}`)));
|
|
633
667
|
const changed = (theirs.length > 0 || commits.stdout.trim() !== "");
|
|
634
668
|
|
|
635
669
|
if (changed) {
|
|
@@ -1095,11 +1129,21 @@ export async function changedFiles(worktreePath, root) {
|
|
|
1095
1129
|
/** The session's changes not yet committed in its copy, as paths. The
|
|
1096
1130
|
* node_modules link the runner made (makeWorktree) is not the session's. */
|
|
1097
1131
|
async function uncommittedFiles(worktreePath) {
|
|
1132
|
+
return (await inspectUncommitted(worktreePath)).files;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/** `uncommittedFiles` that says whether git answered: a failed status reads
|
|
1136
|
+
* as no files there, which is fine for a count but not for deciding that a
|
|
1137
|
+
* tree is empty and may be removed (cleanWorktreeImpl, #8266). */
|
|
1138
|
+
async function inspectUncommitted(worktreePath) {
|
|
1098
1139
|
const status = await git(["status", "--porcelain", "-z", "--untracked-files=all"], worktreePath);
|
|
1099
|
-
if (!status.ok) return [];
|
|
1100
|
-
return
|
|
1101
|
-
|
|
1102
|
-
|
|
1140
|
+
if (!status.ok) return { ok: false, detail: status.detail, files: [] };
|
|
1141
|
+
return {
|
|
1142
|
+
ok: true,
|
|
1143
|
+
files: statusEntries(status.stdout)
|
|
1144
|
+
.filter((e) => e.path !== "node_modules" && !isUntrackedCache(e))
|
|
1145
|
+
.map((e) => e.path),
|
|
1146
|
+
};
|
|
1103
1147
|
}
|
|
1104
1148
|
|
|
1105
1149
|
/** `git status --porcelain -z` as { code, path } entries. A rename or copy is
|
|
@@ -1155,8 +1199,8 @@ function cachePathspecs(entries) {
|
|
|
1155
1199
|
// reuseWorktree mark it `lockRefused`, and the runner then spawns NOTHING:
|
|
1156
1200
|
// falling back to the linked folder would put the new session in the very
|
|
1157
1201
|
// checkout the holder is stashing, merging or resetting.
|
|
1158
|
-
export async function makeWorktree(root, id, log = () => {}, title = "", lifecycle) {
|
|
1159
|
-
return lockedOr(root, () => makeWorktreeImpl(root, id, log, title), lifecycle, (detail) => ({
|
|
1202
|
+
export async function makeWorktree(root, id, log = () => {}, title = "", lifecycle, again) {
|
|
1203
|
+
return lockedOr(root, () => makeWorktreeImpl(root, id, log, title, again), lifecycle, (detail) => ({
|
|
1160
1204
|
cwd: root,
|
|
1161
1205
|
isolated: false,
|
|
1162
1206
|
lockRefused: true,
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// THE LEFTOVERS OF BEFORE #8266, taken away once when a watcher starts.
|
|
2
|
+
//
|
|
3
|
+
// Until that fix every ask on Your computer left its `.claude/worktrees/
|
|
4
|
+
// glytch-*` tree and branch behind, changed or not. cleanWorktree now removes
|
|
5
|
+
// an unchanged one when its run ends; this removes the ones already there.
|
|
6
|
+
//
|
|
7
|
+
// THE NEVER-TOUCH LIST, spelled first (ruling #470: unchanged goes, changed
|
|
8
|
+
// stays until Keep or Throw away):
|
|
9
|
+
// - a tree with a commit or an uncommitted change: it is not asked about
|
|
10
|
+
// at all, `cleanWorktree` is, and it keeps any tree it cannot prove empty;
|
|
11
|
+
// - a tree whose run has not ended, is running in this process, or waits
|
|
12
|
+
// for a recovery: only a row that is `done`, `stopped` or an `error` with
|
|
13
|
+
// no recovery pending is looked at, and none of an idea that has a run
|
|
14
|
+
// still going (a follow-up runs in an earlier run's tree);
|
|
15
|
+
// - a chat tree (`chat-*`): the paths come from run rows, never from a scan
|
|
16
|
+
// of the folder, so a tree no row of this folder made is never listed.
|
|
17
|
+
// A tree this removes is marked on its row (`worktreeRemoved`, its path
|
|
18
|
+
// dropped), so a reply to that session starts a fresh tree instead of
|
|
19
|
+
// finding "the separate copy is gone" and Keep/Throw away are not offered
|
|
20
|
+
// over a path that is not there.
|
|
21
|
+
//
|
|
22
|
+
// A TREE REMOVED BUT NOT MARKED IS MARKED AT THE NEXT START. Before a tree is
|
|
23
|
+
// removed, a note naming the run and the path is written in this computer's
|
|
24
|
+
// Viewable folder; it goes once the row carries the marker. A note left
|
|
25
|
+
// behind (the mark failed, the process ended in between) is finished the next
|
|
26
|
+
// time: the directory is gone, the row still names the path and has no
|
|
27
|
+
// marker, so the marker is written then. Only a note makes that repair: a
|
|
28
|
+
// tree that went through Keep or Throw away, or vanished another way (#2446),
|
|
29
|
+
// also leaves a row naming a missing path, and is never marked as removed.
|
|
30
|
+
|
|
31
|
+
import { createHash } from "node:crypto";
|
|
32
|
+
import { access, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
|
33
|
+
import { join } from "node:path";
|
|
34
|
+
import * as runnerApiModule from "./runnerApi.mjs";
|
|
35
|
+
import { liveRuns } from "./restartPass.mjs";
|
|
36
|
+
import { titleFor } from "./spawn.mjs";
|
|
37
|
+
import { fromIdOf } from "./boardside.mjs";
|
|
38
|
+
import { cleanWorktree, worktreeBranch, worktreePath } from "./worktree.mjs";
|
|
39
|
+
import { viewableHome } from "./registry.mjs";
|
|
40
|
+
import { samePath } from "./runnerGates.mjs";
|
|
41
|
+
|
|
42
|
+
const pathExists = (path) => access(path).then(() => true, () => false);
|
|
43
|
+
const ENDED = new Set(["done", "stopped", "error"]);
|
|
44
|
+
const digest = (value) => createHash("sha256").update(value).digest("hex");
|
|
45
|
+
|
|
46
|
+
/** The notes of trees this folder's sweep removed, one file per run. */
|
|
47
|
+
const notesDirectory = (project, settings) => join(viewableHome(settings.env), "swept-worktrees", digest(`${project.id}\0${project.path}`));
|
|
48
|
+
const noteFile = (project, settings, runId) => join(notesDirectory(project, settings), `${digest(runId)}.json`);
|
|
49
|
+
async function readNote(file) {
|
|
50
|
+
try { return JSON.parse(await readFile(file, "utf8")); }
|
|
51
|
+
catch { return null; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Remove every unchanged, ended run's tree under `root`, and mark the ones
|
|
55
|
+
* an earlier sweep removed but could not mark. Returns `{ removed, kept,
|
|
56
|
+
* marked }` as run ids. Never throws for one tree: a failure on it
|
|
57
|
+
* leaves it for the next start. */
|
|
58
|
+
export async function sweepIdleWorktrees(project, settings, { log = () => {}, exists = pathExists, live = liveRuns } = {}) {
|
|
59
|
+
const runnerApi = settings.runnerApi ?? runnerApiModule;
|
|
60
|
+
const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
|
|
61
|
+
const root = project.path;
|
|
62
|
+
const removed = [];
|
|
63
|
+
const kept = [];
|
|
64
|
+
const marked = [];
|
|
65
|
+
const listed = await runnerApi.runs({ projectIds: [project.id] }, rowsOpts);
|
|
66
|
+
if (!listed.ok) throw new Error(`could not list runs: ${listed.error}`);
|
|
67
|
+
const rows = listed.runs ?? [];
|
|
68
|
+
// A run still going, or an errored one a recovery will carry on, works in
|
|
69
|
+
// its idea's tree, which may be an EARLIER run's: that idea is busy.
|
|
70
|
+
const holds = (r) => !ENDED.has(r.status) || live.has(r.id) || (r.status === "error" && (r.sidecar?.recoveryPending === true || Boolean(r.recovery_reason)));
|
|
71
|
+
const busy = new Set(rows.filter((r) => holds(r) || r.server).map((r) => fromIdOf(r.request)).filter(Boolean));
|
|
72
|
+
for (const run of rows) {
|
|
73
|
+
// An idea with a detached dev server running is left whole too: completion
|
|
74
|
+
// keeps such a tree, and the server sweep ends the server first.
|
|
75
|
+
if (holds(run) || busy.has(fromIdOf(run.request))) continue;
|
|
76
|
+
const path = worktreePath(root, run.id, titleFor(run.request));
|
|
77
|
+
const note = noteFile(project, settings, run.id);
|
|
78
|
+
const mark = async () => {
|
|
79
|
+
const { worktreePath: _gone, ...rest } = run.sidecar ?? {};
|
|
80
|
+
let written;
|
|
81
|
+
try { written = await runnerApi.update({ runId: run.id, patch: { sidecar: { ...rest, worktreeRemoved: path } } }, rowsOpts); }
|
|
82
|
+
catch (error) { written = { ok: false, error: error instanceof Error ? error.message : String(error) }; }
|
|
83
|
+
if (!written.ok) { log(`[${run.id}] could not mark the swept tree on its row; the next start tries again: ${written.error}`); return false; }
|
|
84
|
+
await unlink(note).catch(() => {});
|
|
85
|
+
return true;
|
|
86
|
+
};
|
|
87
|
+
if (!(await exists(path))) {
|
|
88
|
+
// THE REPAIR: a tree this sweep removed whose row was not marked.
|
|
89
|
+
const left = await readNote(note);
|
|
90
|
+
if (!left || !samePath(left.path, path)) continue;
|
|
91
|
+
if (typeof run.sidecar?.worktreeRemoved === "string") { await unlink(note).catch(() => {}); continue; }
|
|
92
|
+
if (!samePath(run.sidecar?.worktreePath, path)) { await unlink(note).catch(() => {}); continue; }
|
|
93
|
+
if (await mark()) { marked.push(run.id); log(`[${run.id}] marked ${path}, swept before, on its row`); }
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const made = { isolated: true, path, cwd: path, branch: worktreeBranch(run.id, titleFor(run.request)), detail: "" };
|
|
97
|
+
// The note first: a tree is never removed without one, so a mark that
|
|
98
|
+
// fails below is finished at the next start.
|
|
99
|
+
try {
|
|
100
|
+
await mkdir(notesDirectory(project, settings), { recursive: true, mode: 0o700 });
|
|
101
|
+
await writeFile(note, JSON.stringify({ runId: run.id, path }), { mode: 0o600 });
|
|
102
|
+
} catch (error) {
|
|
103
|
+
log(`[${run.id}] sweep left ${path}: could not write its note: ${error instanceof Error ? error.message : String(error)}`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
let result;
|
|
107
|
+
try { result = await cleanWorktree(root, made, log, []); }
|
|
108
|
+
catch (error) {
|
|
109
|
+
log(`[${run.id}] sweep could not look at ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
110
|
+
}
|
|
111
|
+
if (!result?.removed) {
|
|
112
|
+
// Not removed here, so never marked as removed here.
|
|
113
|
+
await unlink(note).catch(() => {});
|
|
114
|
+
if (result) kept.push(run.id);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
removed.push(run.id);
|
|
118
|
+
log(`[${run.id}] swept ${path}: its run ended and it changed nothing`);
|
|
119
|
+
await mark();
|
|
120
|
+
}
|
|
121
|
+
return { removed, kept, marked };
|
|
122
|
+
}
|