viewable-one 0.12.8 → 0.12.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -0
- package/README.md +8 -3
- package/SPAWN.md +26 -4
- package/glytch.mjs +5 -4
- package/lib/agents.mjs +195 -33
- 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 +85 -11
- package/lib/codexApps.mjs +84 -24
- package/lib/computerApps.mjs +85 -10
- package/lib/conversationRules.mjs +19 -3
- package/lib/detect.mjs +20 -5
- package/lib/doctor.mjs +18 -2
- package/lib/folderReads.mjs +15 -4
- package/lib/folderState.mjs +43 -0
- package/lib/init-connect.mjs +11 -3
- package/lib/lateResume.mjs +4 -1
- package/lib/mcpjson.mjs +99 -1
- package/lib/multiwatch.mjs +12 -4
- package/lib/otherLoginHook.mjs +31 -0
- package/lib/otherLogins.mjs +107 -3
- package/lib/permissionAsk.mjs +30 -5
- 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 +70 -11
- package/lib/runnerGates.mjs +30 -5
- package/lib/runnerLaunch.mjs +50 -9
- 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 +112 -2
- package/package.json +1 -1
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
|
+
}
|
package/lib/writePolicy.mjs
CHANGED
|
@@ -68,6 +68,18 @@ export function readsOnly(name, args = {}, hints) {
|
|
|
68
68
|
return false;
|
|
69
69
|
return !callVerbs(name, args).some((verb) => verb !== "read");
|
|
70
70
|
}
|
|
71
|
+
/** Whether a call says it changes something: its label (not read-only, or
|
|
72
|
+
* destructive) or a change verb in its name or an action. A call with no
|
|
73
|
+
* label and no verb ("customer_info") says nothing, and a read verb says it
|
|
74
|
+
* reads. Unlike readsOnly, which treats an unlabelled call as a write for
|
|
75
|
+
* safety, this asks whether the call itself claims a change (#7526). */
|
|
76
|
+
export function namesAChange(name, args = {}, hints) {
|
|
77
|
+
if (readsOnly(name, args, hints))
|
|
78
|
+
return false;
|
|
79
|
+
if (hints?.readOnlyHint === false || hints?.destructiveHint === true)
|
|
80
|
+
return true;
|
|
81
|
+
return callVerbs(name, args).some((verb) => verb === "plain" || verb === "change");
|
|
82
|
+
}
|
|
71
83
|
// AN AUTOMATION'S READS (ruling #5495): setting an automation is the
|
|
72
84
|
// person's yes for the reads it needs, label or not (a person's own server
|
|
73
85
|
// rarely labels its tools). A write still asks: anything below that may
|
|
@@ -136,8 +148,11 @@ const SQL_WRITE = /\b(?:insert|update|delete|merge|upsert|drop|undrop|create|alt
|
|
|
136
148
|
// A function a SELECT can call that changes something (a sequence, a
|
|
137
149
|
// session, a file, a lock, another database): the call is a write however it
|
|
138
150
|
// is wrapped. A list cannot be complete, so the database role the person
|
|
139
|
-
// connects with stays the real limit; these are the common ones.
|
|
140
|
-
|
|
151
|
+
// connects with stays the real limit; these are the common ones. Reading a
|
|
152
|
+
// server file or a sequence's counter, and the common extensions that run a
|
|
153
|
+
// job, keep a secret, queue a message or reach the web (cron., vault., pgmq.,
|
|
154
|
+
// net., http*) are on it too (#8071).
|
|
155
|
+
const SQL_SIDE_EFFECTS = /(?:^|[^\w$])(?:currval|pg_read_\w*|pg_ls_\w*|pg_stat_file|(?:cron|vault|net|pgmq)\s*\.\s*\w+|http\w*|nextval|txid_current|pg_current_xact_id|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_promote|pg_(?:create|drop|copy|file|write|replication|logical|advisory|try_advisory|import|export)\w*|pg_notify|pg_sleep\w*|pg_stat_reset\w*|pg_signal_backend|pg_backup_start|pg_start_backup|pg_wal_replay_pause|pg_truncate_visibility_map|brin_summarize_new_values|gin_clean_pending_list|pg_prewarm|pg_backup_stop|pg_stop_backup|pg_wal_replay_resume|pg_stat_statements_reset|lo_\w+|dblink\w*|query_to_xml\w*|table_to_xml\w*|system\$\w+|sp_\w+|xp_\w+|sleep|benchmark|load_file|get_lock|release_lock)\s*\(/i;
|
|
141
156
|
// THE READ RULE (#6628 lead decision): a closed allow list, not a list of
|
|
142
157
|
// writes. The same text means different things in different databases
|
|
143
158
|
// ("select 1 shutdown" is an alias in Postgres and a server stop in SQL
|
|
@@ -375,6 +390,101 @@ export function sentSql(name, args = {}) {
|
|
|
375
390
|
return "write";
|
|
376
391
|
return given.length > 0 && automationReads(name, args) ? "read" : null;
|
|
377
392
|
}
|
|
393
|
+
// ALLOW FOR THIS BOARD (#6771, #8071): a saved yes means no card at all, so a
|
|
394
|
+
// tool that runs whatever it is given (a SQL tool) is covered only while every
|
|
395
|
+
// text it is given is a plain value or a SQL read under two rules at once: the
|
|
396
|
+
// read rule above, and a word scan over the raw text, quoted strings included
|
|
397
|
+
// ("select cron.schedule('j', '* * * * *', 'delete from orders')" hides its
|
|
398
|
+
// write in a string). A function call reads only when it is a built-in read
|
|
399
|
+
// listed below: one the person wrote ("select delete_all_orders()") or an
|
|
400
|
+
// extension's asks. Automations keep the shorter list of side effects above
|
|
401
|
+
// (ruling #5495), so their reads do not start to ask. A false alarm only asks.
|
|
402
|
+
const BOARD_WRITE_WORDS = /\b(into|insert|update|upsert|delete|drop|truncate|alter|create|replace|rename|grant|revoke|merge|copy|call|do|execute|prepare|set|reset|refresh|vacuum|analyze|reindex|cluster|comment|lock|listen|notify|discard|begin|commit|rollback|setval|nextval|currval|set_config|dblink\w*|lo_\w+|pg_(sleep|terminate_backend|cancel_backend|reload_conf|rotate_logfile|read_\w+|ls_\w+|stat_file|advisory_\w+|switch_wal\w*|create_\w+|drop_\w+))\b|\bfor\s+(update|share|no\s+key\s+update|key\s+share)\b/i;
|
|
403
|
+
// The built-in functions that only read, by full name: no prefix family, since
|
|
404
|
+
// anyone may name a function "pg_get_cleanup" (box review of f0e2d1f2a). A
|
|
405
|
+
// function the person wrote with a listed name and other argument types could
|
|
406
|
+
// still be picked by the database; its role stays the last limit there.
|
|
407
|
+
const BOARD_READ_CALLS = new Set(("count sum avg min max array_agg string_agg json_agg jsonb_agg json_object_agg jsonb_object_agg bool_and bool_or every stddev stddev_pop stddev_samp " +
|
|
408
|
+
"variance var_pop var_samp percentile_cont percentile_disc mode corr covar_pop covar_samp group_concat listagg any_value median approx_count_distinct " +
|
|
409
|
+
"lower upper length char_length character_length octet_length bit_length substr btrim ltrim rtrim concat concat_ws left right replace repeat " +
|
|
410
|
+
"strpos instr locate reverse split_part lpad rpad initcap format to_char to_number md5 regexp_replace regexp_match regexp_matches regexp_like " +
|
|
411
|
+
"regexp_substr regexp_split_to_array starts_with string_to_array array_to_string translate ascii chr quote_ident quote_literal quote_nullable encode decode " +
|
|
412
|
+
"now date_trunc date_part age to_date to_timestamp make_date make_time make_timestamp make_interval date_add date_sub datediff dateadd timestampdiff " +
|
|
413
|
+
"timestampadd date_format clock_timestamp statement_timestamp transaction_timestamp justify_days justify_hours justify_interval isfinite timezone " +
|
|
414
|
+
"date year month day hour minute second week quarter dayofweek dayofmonth dayofyear abs round ceil ceiling floor trunc power pow sqrt cbrt exp ln log log10 " +
|
|
415
|
+
"sign pi degrees radians width_bucket random to_json to_jsonb row_to_json array_to_json json_build_object jsonb_build_object json_build_array " +
|
|
416
|
+
"jsonb_build_array json_object jsonb_object json_extract_path jsonb_extract_path json_extract_path_text jsonb_extract_path_text json_array_length " +
|
|
417
|
+
"jsonb_array_length json_typeof jsonb_typeof json_object_keys jsonb_object_keys json_array_elements jsonb_array_elements json_array_elements_text " +
|
|
418
|
+
"jsonb_array_elements_text json_each jsonb_each json_each_text jsonb_each_text jsonb_path_query jsonb_path_exists jsonb_pretty jsonb_strip_nulls " +
|
|
419
|
+
"json_extract json_value json_query array_length cardinality array_position array_positions array_upper array_lower array_dims unnest generate_series " +
|
|
420
|
+
"generate_subscripts lag lead rank dense_rank row_number ntile first_value last_value nth_value percent_rank cume_dist " +
|
|
421
|
+
"format_type to_regclass to_regtype obj_description col_description version current_setting current_database current_schemas " +
|
|
422
|
+
"pg_typeof pg_size_pretty pg_size_bytes pg_database_size pg_total_relation_size pg_relation_size pg_table_size pg_indexes_size pg_column_size " +
|
|
423
|
+
"pg_tablespace_size pg_is_in_recovery pg_backend_pid pg_current_wal_lsn pg_postmaster_start_time pg_conf_load_time pg_has_role " +
|
|
424
|
+
"pg_get_viewdef pg_get_functiondef pg_get_function_arguments pg_get_function_identity_arguments pg_get_function_result pg_get_indexdef " +
|
|
425
|
+
"pg_get_constraintdef pg_get_triggerdef pg_get_ruledef pg_get_expr pg_get_serial_sequence pg_get_userbyid pg_get_keywords pg_get_partkeydef " +
|
|
426
|
+
"pg_stat_get_numscans pg_stat_get_tuples_returned pg_stat_get_tuples_fetched pg_stat_get_tuples_inserted pg_stat_get_tuples_updated " +
|
|
427
|
+
"pg_stat_get_tuples_deleted pg_stat_get_live_tuples pg_stat_get_dead_tuples pg_stat_get_last_vacuum_time pg_stat_get_last_analyze_time " +
|
|
428
|
+
"pg_table_is_visible pg_type_is_visible pg_function_is_visible has_table_privilege has_schema_privilege has_database_privilege " +
|
|
429
|
+
"has_column_privilege has_function_privilege has_sequence_privilege has_any_column_privilege").split(" "));
|
|
430
|
+
// Words that may open a bracket and are never a function: Postgres reserves
|
|
431
|
+
// them, or bars them as function names ("in (", "as (", "exists (",
|
|
432
|
+
// "cast(", "numeric(10, 2)"). An everyday word ("first", "filter") may name
|
|
433
|
+
// a function someone wrote, so it is not here.
|
|
434
|
+
const BOARD_BRACKET_WORDS = new Set(("select in exists as values any all some on from where and or not when then else case having by union intersect " +
|
|
435
|
+
"except with between distinct array row interval cast coalesce nullif extract greatest least position substring trim overlay lateral using " +
|
|
436
|
+
"numeric decimal dec char character varchar nchar float time timestamp bit varying int integer smallint bigint real boolean precision group window").split(" "));
|
|
437
|
+
// Words that open a bracket only after a call's own closing one: "count(*) filter (where ...)", "over (partition by ...)".
|
|
438
|
+
const BOARD_AFTER_CALL_WORDS = new Set(["over", "filter"]);
|
|
439
|
+
// Whatever stands right before a bracket, in any script: a name ends at a
|
|
440
|
+
// space, a bracket, a comma or an operator, so "public.清空订单(" is one name.
|
|
441
|
+
const SQL_CALLS = /([^\s(),;'"+\-*/<>=!|&%^~:[\]{}@#?]*)\s*\(/gu;
|
|
442
|
+
/** Whether every call in a SQL read is a listed read; only pg_catalog may name
|
|
443
|
+
* one. A quoted name before a bracket ("any"(1)) may be any function: it asks. */
|
|
444
|
+
function callsOnlyRead(text) {
|
|
445
|
+
// Strings and quoted names in one pass from the left (QUOTED), so a quote
|
|
446
|
+
// inside one never opens the other ("x'y" is a name; box review of 059bf1a7e).
|
|
447
|
+
const unquoted = text.replace(QUOTED, (part) => (part.startsWith("'") ? " '' " : ' "q" '));
|
|
448
|
+
if (/"\s*\(/.test(unquoted))
|
|
449
|
+
return false;
|
|
450
|
+
const bare = unquoted.replace(/\s*\.\s*/g, ".");
|
|
451
|
+
for (const found of bare.matchAll(SQL_CALLS)) {
|
|
452
|
+
if (found[1] === "")
|
|
453
|
+
continue;
|
|
454
|
+
const parts = found[1].toLowerCase().split(".");
|
|
455
|
+
if (parts.length > 2 || (parts.length === 2 && parts[0] !== "pg_catalog"))
|
|
456
|
+
return false;
|
|
457
|
+
const name = parts[parts.length - 1];
|
|
458
|
+
if (BOARD_READ_CALLS.has(name))
|
|
459
|
+
continue;
|
|
460
|
+
if (parts.length === 1 && BOARD_BRACKET_WORDS.has(name))
|
|
461
|
+
continue;
|
|
462
|
+
if (parts.length === 1 && BOARD_AFTER_CALL_WORDS.has(name) && bare.slice(0, found.index).trimEnd().endsWith(")"))
|
|
463
|
+
continue;
|
|
464
|
+
return false;
|
|
465
|
+
}
|
|
466
|
+
return true;
|
|
467
|
+
}
|
|
468
|
+
/** Whether one text may run under Allow for this board: blank, a plain value
|
|
469
|
+
* that names no statement word ("abcd1234", "events_daily"), or one SQL
|
|
470
|
+
* read by both rules above whose calls are all listed reads. Free text, a
|
|
471
|
+
* comment and anything unsure ask. */
|
|
472
|
+
function boardText(text) {
|
|
473
|
+
const value = text.trim();
|
|
474
|
+
if (value === "")
|
|
475
|
+
return true;
|
|
476
|
+
if (PLAIN_VALUE.test(value))
|
|
477
|
+
return readWordsOnly(value) && sqlKind(value) !== "write";
|
|
478
|
+
return sqlKind(text) === "read" && !BOARD_WRITE_WORDS.test(text) && callsOnlyRead(text);
|
|
479
|
+
}
|
|
480
|
+
/** Whether every text a call is given, at any depth, may run under Allow for
|
|
481
|
+
* this board (see above): the one check the server makes for the card's
|
|
482
|
+
* offer, the saved yes and the run itself (#8071). A value past the walk
|
|
483
|
+
* limit asks. Generic: no app is named (#4419). */
|
|
484
|
+
export function boardMayRun(args = {}) {
|
|
485
|
+
const given = argTexts(args);
|
|
486
|
+
return !given.some(({ deep }) => deep) && given.every(({ text }) => boardText(text));
|
|
487
|
+
}
|
|
378
488
|
/** Whether a call has the shape `rule` names (CallRule in catalog.d.mts). */
|
|
379
489
|
export function callMatches(rule, name, args = {}) {
|
|
380
490
|
if (rule.tools && !rule.tools.includes(name))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "viewable-one",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.10",
|
|
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",
|