@phren/cli 0.3.65 → 0.3.67

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.
Files changed (37) hide show
  1. package/dist/bridge/account-choice.d.ts +12 -3
  2. package/dist/bridge/account-choice.js +133 -19
  3. package/dist/bridge/account-last-known.d.ts +27 -0
  4. package/dist/bridge/account-last-known.js +124 -0
  5. package/dist/bridge/changes.d.ts +22 -0
  6. package/dist/bridge/changes.js +323 -82
  7. package/dist/bridge/claude-accounts.d.ts +27 -0
  8. package/dist/bridge/claude-accounts.js +63 -8
  9. package/dist/bridge/dispatch-returns.d.ts +8 -0
  10. package/dist/bridge/dispatch-returns.js +20 -2
  11. package/dist/bridge/files.d.ts +1 -1
  12. package/dist/bridge/harnesses.js +8 -2
  13. package/dist/bridge/helper.d.ts +3 -2
  14. package/dist/bridge/helper.js +5 -4
  15. package/dist/bridge/machine-health-alerts.d.ts +20 -0
  16. package/dist/bridge/machine-health-alerts.js +47 -0
  17. package/dist/bridge/machine-health.d.ts +42 -0
  18. package/dist/bridge/machine-health.js +124 -0
  19. package/dist/bridge/machine-probes.d.ts +58 -0
  20. package/dist/bridge/machine-probes.js +306 -0
  21. package/dist/bridge/push.d.ts +10 -0
  22. package/dist/bridge/push.js +15 -0
  23. package/dist/bridge/resources.d.ts +5 -0
  24. package/dist/bridge/resources.js +16 -2
  25. package/dist/bridge/schedule-launch.js +2 -2
  26. package/dist/bridge/server-launch.js +3 -1
  27. package/dist/bridge/server.js +5 -1
  28. package/dist/bridge-hook.mjs +29235 -28083
  29. package/dist/computers/read.d.ts +18 -0
  30. package/dist/computers/read.js +18 -0
  31. package/dist/governance/policy.js +4 -3
  32. package/dist/governance/scores.js +2 -1
  33. package/dist/modules/registry.js +1 -1
  34. package/dist/tools/dispatch.js +16 -0
  35. package/dist/tools/helper.js +1 -1
  36. package/package.json +1 -1
  37. package/starter/global/skills/conductor/SKILL.md +6 -0
@@ -1,6 +1,7 @@
1
1
  import { checkoutGitEnv } from "./projects.js";
2
2
  import { execFile } from "node:child_process";
3
- import { appendFile, copyFile, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, unlink, utimes } from "node:fs/promises";
3
+ import { randomBytes } from "node:crypto";
4
+ import { appendFile, copyFile, mkdir, readdir, readFile, realpath, rm, stat, unlink, utimes } from "node:fs/promises";
4
5
  import { homeDir } from "../home-paths.js";
5
6
  import path from "node:path";
6
7
  import { promisify } from "node:util";
@@ -17,10 +18,10 @@ export const changedFileSchema = z.object({ root: z.string(), path: z.string(),
17
18
  added: z.number().int().nonnegative(), removed: z.number().int().nonnegative(), redacted: z.boolean().optional(), binary: z.boolean().optional(), truncated: z.boolean().optional() });
18
19
  const changeRowSchema = z.object({ toolUseId: z.string(), files: z.array(changedFileSchema) });
19
20
  export const secretName = (file) => /^(?:\.env(?:\..*)?|.*\.(?:pem|key|p12|pfx|keychain-db|tfstate)|id_rsa.*|id_ed25519.*|(?:.*\.)?credentials\.json|\.netrc|\.npmrc|\.pypirc)$/i.test(path.basename(file));
20
- /** Two captures at a time, each holding its slot for all of its Git work. A
21
- * slot per Git process interleaved every waiting capture, so under load they
22
- * all finished late together and every one overran the budget; now they finish
23
- * in turn and only the end of a long queue misses it. */
21
+ /** Two Git jobs at a time: one repository's tree read (shared by every call
22
+ * waiting for it), one call's diff, or a repository lookup. Each holds its slot
23
+ * for all of its Git processes, so under load jobs finish in turn rather than
24
+ * all late together. */
24
25
  const capturePool = new ProcessPool(2);
25
26
  /** Tools whose filesystem changes are captured around the lifecycle callback. */
26
27
  export const SHELL_TOOLS = new Set(["Bash", "bash", "shell", "Shell", "exec_command", "shell_command", "local_shell", "write_stdin"]);
@@ -61,67 +62,145 @@ async function git(cwd, args, extra = {}, signal) {
61
62
  signal, timeout: 10_000, maxBuffer: 8_388_608, env: { ...checkoutGitEnv(), ...extra },
62
63
  })).stdout;
63
64
  }
64
- /** The repository holding `target` (a file, a folder, or something not yet
65
- * created), confined to the user's home; undefined otherwise. */
66
- async function repositoryOf(target, cwd, home = homeDir(), signal) {
67
- const absolute = target === "~" || target.startsWith("~/") ? path.join(home, target.slice(1)) : path.resolve(cwd, target);
68
- let existing = absolute;
69
- while (!(await stat(existing).catch(() => undefined))) {
70
- const parent = path.dirname(existing);
71
- if (parent === existing)
72
- return undefined;
73
- existing = parent;
74
- }
75
- const real = await realpath(existing);
76
- home = await realpath(home);
77
- if (real !== home && !real.startsWith(home + path.sep))
78
- return undefined;
79
- const dir = (await stat(real)).isDirectory() ? real : path.dirname(real);
80
- try {
81
- return await realpath((await git(dir, ["rev-parse", "--show-toplevel"], {}, signal)).replace(/\r?\n$/, ""));
82
- }
83
- catch (error) {
84
- if (/not a git repository/.test(String(error.stderr)))
65
+ /** A capture that ran out of time (the hook budget, Git's own timeout, or the
66
+ * Hook closing). The call shows no changes; nothing is wrong with the repository. */
67
+ class CaptureTimeout extends Error {
68
+ }
69
+ function timedOut(error) {
70
+ const failure = error;
71
+ return error instanceof CaptureTimeout || failure?.name === "AbortError" || failure?.code === "ABORT_ERR" || failure?.killed === true;
72
+ }
73
+ /** The repository whose Git work failed, carried on the error so a report
74
+ * marks that root and not every repository the call happened to capture. */
75
+ const failedRepository = Symbol("failed-repository");
76
+ function failedIn(error, root) {
77
+ if (error && (typeof error === "object" || typeof error === "function"))
78
+ error[failedRepository] = root;
79
+ return error;
80
+ }
81
+ function failureRoot(error) {
82
+ return error && (typeof error === "object" || typeof error === "function") ? error[failedRepository] : undefined;
83
+ }
84
+ /** `work`, but given up on (not stopped) when `signal` fires. */
85
+ function until(work, signal) {
86
+ if (signal.aborted)
87
+ return Promise.reject(signal.reason);
88
+ return new Promise((resolve, reject) => {
89
+ const abort = () => reject(signal.reason);
90
+ signal.addEventListener("abort", abort, { once: true });
91
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
92
+ });
93
+ }
94
+ /** The nearest folder at or above `dir` with a `.git` entry: where Git's own
95
+ * discovery would start looking, found without starting a Git process. */
96
+ async function checkoutOf(dir) {
97
+ for (let at = dir;; at = path.dirname(at)) {
98
+ if (await stat(path.join(at, ".git")).then(() => true, () => false))
99
+ return at;
100
+ if (path.dirname(at) === at)
85
101
  return undefined;
86
- throw error;
87
102
  }
88
103
  }
89
- async function scratchTree(root, signal) {
90
- const dir = path.join(bridgeRoot(), "changes-scratch");
91
- await mkdir(dir, { recursive: true, mode: 0o700 });
92
- const scratch = await mkdtemp(path.join(dir, "repo-"));
93
- try {
94
- const objects = await realpath(path.resolve(root, (await git(root, ["rev-parse", "--git-path", "objects"], {}, signal)).trim()));
95
- await mkdir(path.join(scratch, "objects"), { mode: 0o700 });
96
- const env = { GIT_OBJECT_DIRECTORY: path.join(scratch, "objects"), GIT_ALTERNATE_OBJECT_DIRECTORIES: JSON.stringify(objects), GIT_INDEX_FILE: path.join(scratch, "index") };
97
- return { hash: await treeHash(root, env, signal), scratch, env };
98
- }
99
- catch (error) {
100
- await rm(scratch, { recursive: true, force: true });
101
- throw error;
104
+ /** One repository's captures share a scratch object store, kept between
105
+ * calls so each blob is written once, where every call used to write all its
106
+ * modified and untracked files twice into a store of its own. One read runs at
107
+ * a time and serves every call that asked for the tree while it waited.
108
+ * Retired after `SCRATCH_AGE` or a failed read; deleted once no snapshot holds
109
+ * a tree in it. */
110
+ class Scratch {
111
+ repo;
112
+ dir;
113
+ closing;
114
+ settled;
115
+ env;
116
+ born = Date.now();
117
+ /** Snapshots holding a tree whose objects live here. */
118
+ users = 0;
119
+ retired = false;
120
+ created;
121
+ reads = 0;
122
+ running;
123
+ next;
124
+ constructor(repo, dir, closing, settled) {
125
+ this.repo = repo;
126
+ this.dir = dir;
127
+ this.closing = closing;
128
+ this.settled = settled;
129
+ this.env = { GIT_OBJECT_DIRECTORY: path.join(dir, "objects"), GIT_ALTERNATE_OBJECT_DIRECTORIES: JSON.stringify(repo.objects), GIT_INDEX_FILE: path.join(dir, "index") };
130
+ }
131
+ get busy() { return !!(this.running || this.next); }
132
+ /** The working tree as read no earlier than this call: the read already
133
+ * running may have started before the caller's tool ran or finished, so a
134
+ * caller arriving then waits for the next one, shared with later arrivals.
135
+ * A read every caller gave up on is stopped. */
136
+ tree(signal) {
137
+ let read = this.next;
138
+ if (!read && this.running) {
139
+ const queued = this.next = { waiting: 0, controller: new AbortController(), result: this.running.result.then(() => { }, () => { }).then(() => {
140
+ this.next = undefined;
141
+ return this.start(queued);
142
+ }) };
143
+ read = queued;
144
+ }
145
+ if (!read) {
146
+ read = { waiting: 0, controller: new AbortController() };
147
+ this.start(read);
148
+ }
149
+ // A queued read its earlier callers gave up on has not started; it can still serve this one.
150
+ if (read.controller.signal.aborted && read === this.next)
151
+ read.controller = new AbortController();
152
+ read.waiting++;
153
+ return until(read.result, signal).catch(error => {
154
+ if (signal.aborted && --read.waiting === 0)
155
+ read.controller.abort();
156
+ throw error;
157
+ });
158
+ }
159
+ start(read) {
160
+ const signal = AbortSignal.any([this.closing, read.controller.signal]);
161
+ this.running = read;
162
+ // An index of its own: an aborted read's Git may still be exiting while the next one starts.
163
+ const env = { ...this.env, GIT_INDEX_FILE: path.join(this.dir, `index-${++this.reads}`) };
164
+ read.result = capturePool.run(signal, async () => {
165
+ await (this.created ??= mkdir(path.join(this.dir, "objects"), { recursive: true, mode: 0o700 }));
166
+ try {
167
+ await this.seed(env.GIT_INDEX_FILE);
168
+ await git(this.repo.root, ["add", "-A", "--", "."], env, signal);
169
+ return (await git(this.repo.root, ["write-tree"], env, signal)).trim();
170
+ }
171
+ finally {
172
+ await unlink(env.GIT_INDEX_FILE).catch(() => undefined);
173
+ }
174
+ }).catch(error => { if (!timedOut(error))
175
+ this.retired = true; throw error; })
176
+ .finally(() => { if (this.running === read)
177
+ this.running = undefined; this.settled(); });
178
+ read.result.catch(() => { });
179
+ return read.result;
180
+ }
181
+ /** Both the index and all new blobs/trees stay in scratch storage. The real
182
+ * object store is a read-only alternate, including for linked worktrees.
183
+ * Every read starts from a fresh copy of the real index: one kept from the
184
+ * last read would trust its own stat data, and miss a same-size rewrite that
185
+ * restored the file's mtime within the second its ctime was recorded. */
186
+ async seed(temp) {
187
+ // Keep the real index's mtime (a second early, for rounding): Git rechecks
188
+ // the content of entries as new as the index, so a file rewritten to the
189
+ // same size in one instant is still seen. Read before the copy, so an index
190
+ // replaced meanwhile only makes more entries racy. An epoch mtime instead
191
+ // made every tracked file racy, and rehashing them all overran the budget
192
+ // on a busy machine (about 3 s for 6,000 files).
193
+ const index = this.repo.index;
194
+ const real = await stat(index).catch(error => { if (error.code !== "ENOENT")
195
+ throw error; return undefined; });
196
+ if (real && await copyFile(index, temp).then(() => true, error => { if (error.code !== "ENOENT")
197
+ throw error; return false; })) {
198
+ await utimes(temp, real.atimeMs / 1000, real.mtimeMs / 1000 - 1);
199
+ }
102
200
  }
103
201
  }
104
- /** Both the index and all new blobs/trees stay in scratch storage. The real
105
- * object store is a read-only alternate, including for linked worktrees. */
106
- async function treeHash(root, env, signal) {
107
- const index = path.resolve(root, (await git(root, ["rev-parse", "--git-path", "index"], {}, signal)).trim());
108
- const temp = env.GIT_INDEX_FILE;
109
- await unlink(temp).catch(() => undefined);
110
- // Keep the real index's mtime (a second early, for rounding): Git rechecks
111
- // the content of entries as new as the index, so a file rewritten to the
112
- // same size in one instant is still seen. Read before the copy, so an index
113
- // replaced meanwhile only makes more entries racy. An epoch mtime instead
114
- // made every tracked file racy, and rehashing them all overran the budget
115
- // on a busy machine (about 3 s for 6,000 files).
116
- const real = await stat(index).catch(error => { if (error.code !== "ENOENT")
117
- throw error; return undefined; });
118
- if (real && await copyFile(index, temp).then(() => true, error => { if (error.code !== "ENOENT")
119
- throw error; return false; })) {
120
- await utimes(temp, real.atimeMs / 1000, real.mtimeMs / 1000 - 1);
121
- }
122
- await git(root, ["add", "-A", "--", "."], env, signal);
123
- return (await git(root, ["write-tree"], env, signal)).trim();
124
- }
202
+ const SCRATCH_AGE = 10 * 60_000;
203
+ const REPOSITORY_TTL = 5 * 60_000;
125
204
  const NO_DIFF = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
126
205
  async function treeDiff(root, before, after, env, signal) {
127
206
  if (before === after)
@@ -141,8 +220,16 @@ async function treeDiff(root, before, after, env, signal) {
141
220
  const counts = (await git(root, [...NO_DIFF, "--numstat", before, after, "--", ...specs], env, signal)).split("\t");
142
221
  const binary = counts[0] === "-" || counts[1] === "-";
143
222
  const redacted = secretName(original) || secretName(file) || binary;
144
- let patch = redacted ? "" : await git(root, [...NO_DIFF, before, after, "--", ...specs], env, signal);
145
- const truncated = patch.length > 200_000;
223
+ let overflowed = false;
224
+ let patch = redacted ? "" : await git(root, [...NO_DIFF, before, after, "--", ...specs], env, signal).catch(error => {
225
+ // One patch past Git's output buffer is shown truncated, not as a failed capture.
226
+ const failure = error;
227
+ if (failure.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
228
+ throw error;
229
+ overflowed = true;
230
+ return String(failure.stdout ?? "");
231
+ });
232
+ const truncated = overflowed || patch.length > 200_000;
146
233
  if (truncated)
147
234
  patch = patch.slice(0, 200_000) + "\n… (truncated)\n";
148
235
  const added = Number(counts[0]) || 0, removed = Number(counts[1]) || 0;
@@ -196,6 +283,14 @@ export async function pruneChanges(now = Date.now()) {
196
283
  else
197
284
  size += file.size;
198
285
  }
286
+ // Scratch a stopped Hook left behind; a live one is rewritten on every read
287
+ // and retired within SCRATCH_AGE of its first.
288
+ const scratch = path.join(bridgeRoot(), "changes-scratch");
289
+ for (const entry of await readdir(scratch, { withFileTypes: true }).catch(() => [])) {
290
+ const dir = path.join(scratch, entry.name), info = await stat(dir).catch(() => undefined);
291
+ if (info && now - info.mtimeMs > DAY)
292
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
293
+ }
199
294
  }
200
295
  export async function startChangeRetention() {
201
296
  await pruneChanges();
@@ -214,8 +309,35 @@ export class ToolChanges {
214
309
  controllers = new Set();
215
310
  claims = [];
216
311
  failures = new Map();
217
- failed(key, error) {
218
- const failure = error instanceof BridgeError ? error : new BridgeError(503, "Git change capture failed or timed out. Refresh repository Changes for the current status.", { code: "git-capture-failed" });
312
+ /** Conversation and repository root pairs already shown that Git could not capture changes. */
313
+ reported = new Set();
314
+ repositories = new Map();
315
+ scratches = new Map();
316
+ closing = new AbortController();
317
+ /** The failure to show on this call's row, if any. A capture that ran out of
318
+ * time shows no changes rather than an error: a busy machine is not
319
+ * something to act on per call, and repository Changes still has the
320
+ * status. A broken capture (Git missing, a corrupt repository) shows on the
321
+ * first call it hits in a conversation, not on every later one. A per-call
322
+ * limit (too many files) shows on its own call. */
323
+ failed(conversation, key, error, roots = []) {
324
+ if (timedOut(error))
325
+ return undefined;
326
+ const failure = error instanceof BridgeError ? error : new BridgeError(503, "Git change capture failed. Refresh repository Changes for the current status.", { code: "git-capture-failed" });
327
+ if (failure.details?.code === "git-capture-failed") {
328
+ // A breakage is news once per repository: a healthy checkout's capture
329
+ // must not let a corrupt sibling repo report its error again.
330
+ const root = failureRoot(error);
331
+ const marks = root ? [`${conversation}\0${root}`]
332
+ : roots.length ? [...new Set(roots)].map(entry => `${conversation}\0${entry}`) : [`${conversation}\0`];
333
+ if (marks.every(mark => this.reported.has(mark)))
334
+ return undefined;
335
+ for (const mark of marks) {
336
+ if (this.reported.size >= 512)
337
+ this.reported.delete(this.reported.keys().next().value);
338
+ this.reported.add(mark);
339
+ }
340
+ }
219
341
  if (this.failures.size >= 512)
220
342
  this.failures.delete(this.failures.keys().next().value);
221
343
  this.failures.set(key, failure);
@@ -234,23 +356,122 @@ export class ToolChanges {
234
356
  try {
235
357
  return await work(controller.signal);
236
358
  }
359
+ catch (error) {
360
+ throw controller.signal.aborted ? new CaptureTimeout() : error;
361
+ }
237
362
  finally {
238
363
  clearTimeout(timer);
239
364
  this.controllers.delete(controller);
365
+ // Leaving the scope gives up on every read this call started, including
366
+ // ones still running beside a sibling that failed: a shared read stops
367
+ // once its last waiter detaches, so it cannot hold a pool slot until
368
+ // Git's own timeout.
369
+ controller.abort();
240
370
  }
241
371
  }
242
372
  async discard(snapshot) {
243
373
  clearTimeout(snapshot.expiry);
244
- await Promise.all([...snapshot.trees.values()].map(tree => rm(tree.scratch, { recursive: true, force: true })));
374
+ const trees = [...snapshot.trees.values()];
375
+ snapshot.trees.clear();
376
+ for (const tree of trees) {
377
+ tree.scratch.users--;
378
+ await this.sweep(tree.scratch);
379
+ }
245
380
  }
246
381
  async close() {
247
382
  for (const controller of this.controllers)
248
383
  controller.abort();
384
+ for (const { lookup } of this.repositories.values())
385
+ lookup.controller.abort();
386
+ this.repositories.clear();
387
+ this.closing.abort();
249
388
  for (const snapshot of this.snapshots.values()) {
250
389
  await snapshot.result?.catch(() => { });
251
390
  await this.discard(snapshot);
252
391
  }
253
392
  this.snapshots.clear();
393
+ for (const scratch of this.scratches.values())
394
+ scratch.retired = true;
395
+ await Promise.all([...this.scratches.values()].map(scratch => this.sweep(scratch)));
396
+ }
397
+ /** The repository holding `target` (a file, a folder, or something not yet
398
+ * created), confined to the user's home; undefined otherwise. Git is asked
399
+ * once per checkout every few minutes, not once per path a command names. */
400
+ async repositoryOf(target, cwd, signal, home = homeDir()) {
401
+ const absolute = target === "~" || target.startsWith("~/") ? path.join(home, target.slice(1)) : path.resolve(cwd, target);
402
+ let existing = absolute;
403
+ while (!(await stat(existing).catch(() => undefined))) {
404
+ const parent = path.dirname(existing);
405
+ if (parent === existing)
406
+ return undefined;
407
+ existing = parent;
408
+ }
409
+ const real = await realpath(existing);
410
+ home = await realpath(home);
411
+ if (real !== home && !real.startsWith(home + path.sep))
412
+ return undefined;
413
+ const dir = (await stat(real)).isDirectory() ? real : path.dirname(real), checkout = await checkoutOf(dir);
414
+ if (!checkout)
415
+ return undefined;
416
+ const now = Date.now(), known = this.repositories.get(checkout);
417
+ // A lookup every caller gave up on is not reused: a new call starts a fresh one.
418
+ if (known && now - known.at < REPOSITORY_TTL && !known.lookup.controller.signal.aborted)
419
+ return this.awaitRepository(known.lookup, signal);
420
+ if (this.repositories.size >= 256)
421
+ this.repositories.clear();
422
+ // The lookup belongs to the repository, not to whichever call asked first:
423
+ // it stops only once every call waiting for it has given up.
424
+ const lookup = { waiting: 0, controller: new AbortController(), result: Promise.resolve(undefined) };
425
+ this.repositories.set(checkout, { at: now, lookup });
426
+ // Asked from the target's own folder, so Git's discovery limits (GIT_CEILING_DIRECTORIES) still apply.
427
+ const repository = capturePool.run(lookup.controller.signal, async () => {
428
+ const [root, objects, index] = (await git(dir, ["rev-parse", "--show-toplevel", "--git-path", "objects", "--git-path", "index"], {}, lookup.controller.signal)).split(/\r?\n/);
429
+ return { root: await realpath(root), objects: await realpath(path.resolve(dir, objects)), index: path.resolve(dir, index) };
430
+ }).catch(error => {
431
+ if (/not a git repository/.test(String(error.stderr)))
432
+ return undefined;
433
+ // Asked again next time rather than remembered.
434
+ if (this.repositories.get(checkout)?.lookup === lookup)
435
+ this.repositories.delete(checkout);
436
+ throw error;
437
+ });
438
+ lookup.result = repository;
439
+ repository.catch(() => { });
440
+ return this.awaitRepository(lookup, signal);
441
+ }
442
+ /** Wait for a shared repository lookup, dropping this caller's interest when
443
+ * it gives up; the lookup is stopped only when no caller is left. */
444
+ awaitRepository(lookup, signal) {
445
+ lookup.waiting++;
446
+ return until(lookup.result, signal).finally(() => {
447
+ if (--lookup.waiting === 0 && signal.aborted)
448
+ lookup.controller.abort();
449
+ });
450
+ }
451
+ /** The scratch a new snapshot of `repository` reads into. */
452
+ scratchFor(repository) {
453
+ const now = Date.now();
454
+ for (const scratch of this.scratches.values()) {
455
+ if (scratch.retired || now - scratch.born > SCRATCH_AGE) {
456
+ scratch.retired = true;
457
+ void this.sweep(scratch);
458
+ }
459
+ }
460
+ const current = this.scratches.get(repository.root);
461
+ if (current && !current.retired)
462
+ return current;
463
+ const dir = path.join(bridgeRoot(), "changes-scratch", `repo-${randomBytes(8).toString("hex")}`);
464
+ const scratch = new Scratch(repository, dir, this.closing.signal, () => void this.sweep(scratch));
465
+ this.scratches.set(repository.root, scratch);
466
+ return scratch;
467
+ }
468
+ /** Delete a retired scratch once nothing reads it or holds a tree in it. */
469
+ async sweep(scratch) {
470
+ if (!scratch.retired || scratch.users > 0 || scratch.busy)
471
+ return;
472
+ if (this.scratches.get(scratch.repo.root) === scratch)
473
+ this.scratches.delete(scratch.repo.root);
474
+ await rm(scratch.dir, { recursive: true, force: true }).catch(() => undefined);
254
475
  }
255
476
  async before(conversation, toolUseId, cwd, command, input = {}) {
256
477
  const key = `${conversation}\0${toolUseId}`;
@@ -261,25 +482,29 @@ export class ToolChanges {
261
482
  this.claim(conversation, toolUseId, claimed);
262
483
  if (this.snapshots.size >= 64 || this.snapshots.has(key))
263
484
  return;
264
- const snapshot = { at: Date.now(), conversation, own: new Set(claimed), trees: new Map(), taking: true };
485
+ const snapshot = { at: Date.now(), conversation, own: new Set(claimed), trees: new Map(), roots: [], taking: true };
265
486
  this.snapshots.set(key, snapshot);
266
487
  try {
267
- await this.budget(signal => capturePool.run(signal, async () => {
488
+ await this.budget(async (signal) => {
268
489
  await realpath(cwd); // A vanished checkout must not resolve to its parent repository.
269
- const roots = new Set();
490
+ const repositories = new Map();
270
491
  for (const target of [cwd, phrenStoreRoot(), ...namedPaths(command, input)]) {
271
492
  signal.throwIfAborted();
272
- if (roots.size >= 6)
493
+ if (repositories.size >= 6)
273
494
  break;
274
- const root = await repositoryOf(target, cwd, homeDir(), signal);
275
- if (root)
276
- roots.add(root);
277
- }
278
- for (const root of roots) {
279
- snapshot.trees.set(root, await scratchTree(root, signal));
495
+ const repository = await this.repositoryOf(target, cwd, signal);
496
+ if (repository)
497
+ repositories.set(repository.root, repository);
280
498
  }
499
+ snapshot.roots = [...repositories.keys()];
500
+ await Promise.all([...repositories.values()].map(async (repository) => {
501
+ const tree = { scratch: this.scratchFor(repository) };
502
+ tree.scratch.users++;
503
+ snapshot.trees.set(repository.root, tree);
504
+ tree.hash = await tree.scratch.tree(signal).catch(error => { throw failedIn(error, repository.root); });
505
+ }));
281
506
  signal.throwIfAborted();
282
- }));
507
+ });
283
508
  snapshot.taking = false;
284
509
  if (snapshot.dropped) {
285
510
  await this.discard(snapshot);
@@ -299,7 +524,7 @@ export class ToolChanges {
299
524
  snapshot.expiry.unref();
300
525
  }
301
526
  catch (error) {
302
- this.failed(key, error);
527
+ this.failed(conversation, key, error, snapshot.roots);
303
528
  if (this.snapshots.get(key) === snapshot)
304
529
  this.snapshots.delete(key);
305
530
  await this.discard(snapshot);
@@ -346,21 +571,37 @@ export class ToolChanges {
346
571
  files = await snapshot.result;
347
572
  }
348
573
  catch (error) {
349
- this.snapshots.delete(key);
350
- throw this.failed(key, error);
574
+ if (this.snapshots.get(key) === snapshot) {
575
+ this.snapshots.delete(key);
576
+ this.failed(conversation, key, error, snapshot.roots);
577
+ }
578
+ const failure = this.failures.get(key);
579
+ if (failure)
580
+ throw failure;
581
+ return;
351
582
  }
352
583
  if (this.snapshots.get(key) === snapshot) {
353
584
  this.snapshots.delete(key);
354
585
  await this.record(conversation, toolUseId, files);
586
+ // Capture works again for these repositories: a later breakage there is news worth one more row.
587
+ for (const root of snapshot.roots)
588
+ this.reported.delete(`${conversation}\0${root}`);
355
589
  }
356
590
  }
357
591
  async compute(snapshot) {
358
592
  try {
359
593
  return await this.budget(async (signal) => {
594
+ const trees = [...snapshot.trees.entries()];
595
+ const after = await Promise.all(trees.map(([root, tree]) => tree.scratch.tree(signal).catch(error => { throw failedIn(error, root); })));
360
596
  const files = await capturePool.run(signal, async () => {
361
597
  const found = [];
362
- for (const [root, before] of snapshot.trees) {
363
- found.push(...await treeDiff(root, before.hash, await treeHash(root, before.env, signal), before.env, signal));
598
+ for (const [i, [root, tree]] of trees.entries()) {
599
+ try {
600
+ found.push(...await treeDiff(root, tree.hash, after[i], tree.scratch.env, signal));
601
+ }
602
+ catch (error) {
603
+ throw failedIn(error, root);
604
+ }
364
605
  }
365
606
  return found;
366
607
  });
@@ -1,3 +1,4 @@
1
+ import { type ChildProcess } from "node:child_process";
1
2
  import { type Subscription } from "./subscription.js";
2
3
  export declare const DEFAULT_ACCOUNT = "default";
3
4
  export interface ClaudeHome {
@@ -55,6 +56,14 @@ export declare function claudePlanUnknown(home: ClaudeHome): boolean;
55
56
  */
56
57
  export declare function claudeAccountSubscription(home: ClaudeHome, now?: Date, fallbackPlan?: string): Subscription | undefined;
57
58
  export declare function claudeAccountRef(home: ClaudeHome, labels?: Record<string, string>): AccountRef;
59
+ /**
60
+ * A privacy-preserving fingerprint of a home's login: the signed-in account's stable identity and the
61
+ * credential file's own metadata, never the main config file's (a trust prompt or project setting
62
+ * rewrites it without changing the login). A re-login changes it, so cached and persisted answers for
63
+ * the old login are dropped. Undefined when the config names no identity: the last classification is
64
+ * then kept rather than discarded. Only the hash is ever stored.
65
+ */
66
+ export declare function claudeLoginFingerprint(home: ClaudeHome): string | undefined;
58
67
  export declare const CODEX_ACCOUNT: AccountRef;
59
68
  /** Only for tests. */
60
69
  export declare function clearAccountCaches(): void;
@@ -69,4 +78,22 @@ export interface AuthStatus {
69
78
  /** Parse `claude auth status --json`. Never keeps anything but the state and plan. */
70
79
  export declare function parseAuthStatus(output: string): AuthStatus;
71
80
  export type AuthRunner = (home: ClaudeHome) => Promise<string>;
81
+ /** How the sign-in probe starts Claude: an npm install on Windows is `claude.cmd`, which only a shell starts. */
82
+ export declare function claudeAuthSpawn(platform?: NodeJS.Platform): {
83
+ command: string;
84
+ shell: boolean;
85
+ };
86
+ type AuthKillSpawn = (command: string, args: readonly string[], options: {
87
+ stdio: "ignore";
88
+ windowsHide: boolean;
89
+ }) => Pick<ChildProcess, "on">;
90
+ /**
91
+ * Stops the sign-in probe and anything it started. On Windows the child is cmd.exe, so
92
+ * killing it alone leaves the claude started by claude.cmd running: kill the tree with
93
+ * taskkill. Elsewhere the child is claude itself.
94
+ */
95
+ export declare function claudeAuthKill(child: Pick<ChildProcess, "pid" | "kill">, platform?: NodeJS.Platform, run?: AuthKillSpawn, env?: NodeJS.ProcessEnv): void;
96
+ /** Only for tests: settles when the most recent sign-in probe's child has exited. */
97
+ export declare function claudeAuthProbeExit(): Promise<void> | undefined;
72
98
  export declare function claudeAuthStatus(home: ClaudeHome, run?: AuthRunner, now?: number): Promise<AuthStatus>;
99
+ export {};
@@ -210,6 +210,29 @@ export function claudeAccountSubscription(home, now = new Date(), fallbackPlan)
210
210
  export function claudeAccountRef(home, labels = readLabels()) {
211
211
  return { id: home.id, label: accountLabel(home.id, labels), key: claudeAccountKey(home) };
212
212
  }
213
+ /**
214
+ * A privacy-preserving fingerprint of a home's login: the signed-in account's stable identity and the
215
+ * credential file's own metadata, never the main config file's (a trust prompt or project setting
216
+ * rewrites it without changing the login). A re-login changes it, so cached and persisted answers for
217
+ * the old login are dropped. Undefined when the config names no identity: the last classification is
218
+ * then kept rather than discarded. Only the hash is ever stored.
219
+ */
220
+ export function claudeLoginFingerprint(home) {
221
+ const identity = oauthIdentity(home.configFile);
222
+ // accountUuid is the login; the organization separates two seats of one login. Email only when no uuid.
223
+ const stable = identity.uuid ? `${identity.uuid}|${identity.organization ?? ""}` : identity.email;
224
+ if (!stable)
225
+ return undefined;
226
+ let credentials;
227
+ try {
228
+ const value = statSync(path.join(home.dir, ".credentials.json"));
229
+ if (value.isFile())
230
+ credentials = { mtimeMs: value.mtimeMs, size: value.size, ino: value.ino };
231
+ }
232
+ catch { /* No credentials file here (macOS often keeps its own in the keychain). */ }
233
+ return createHash("sha256")
234
+ .update([stable, credentials?.mtimeMs ?? "", credentials?.size ?? "", credentials?.ino ?? ""].join("|")).digest("hex");
235
+ }
213
236
  export const CODEX_ACCOUNT = { id: DEFAULT_ACCOUNT, label: "Codex", key: "codex" };
214
237
  /** Only for tests. */
215
238
  export function clearAccountCaches() { identityCache.clear(); authCache.clear(); }
@@ -230,10 +253,40 @@ export function parseAuthStatus(output) {
230
253
  return { signedIn: false, unknown: true, reason: "Claude did not report its sign-in state" };
231
254
  }
232
255
  }
256
+ /** How the sign-in probe starts Claude: an npm install on Windows is `claude.cmd`, which only a shell starts. */
257
+ export function claudeAuthSpawn(platform = process.platform) {
258
+ return { command: "claude", shell: platform === "win32" };
259
+ }
260
+ /**
261
+ * Stops the sign-in probe and anything it started. On Windows the child is cmd.exe, so
262
+ * killing it alone leaves the claude started by claude.cmd running: kill the tree with
263
+ * taskkill. Elsewhere the child is claude itself.
264
+ */
265
+ export function claudeAuthKill(child, platform = process.platform, run = spawn, env = process.env) {
266
+ const signal = () => { try {
267
+ child.kill("SIGKILL");
268
+ }
269
+ catch { /* Already gone. */ } };
270
+ if (platform !== "win32" || !child.pid)
271
+ return signal();
272
+ const root = env.SystemRoot || env.SYSTEMROOT || env.windir || "C:\\Windows";
273
+ try {
274
+ run(path.win32.join(root, "System32", "taskkill.exe"), ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true })
275
+ .on("error", signal);
276
+ }
277
+ catch {
278
+ signal();
279
+ }
280
+ }
281
+ let probeExit;
282
+ /** Only for tests: settles when the most recent sign-in probe's child has exited. */
283
+ export function claudeAuthProbeExit() { return probeExit; }
233
284
  const runAuthStatus = home => new Promise(resolve => {
234
- let out = "", done = false;
235
- const child = spawn("claude", ["auth", "status", "--json"], {
236
- cwd: homeDir(), stdio: ["ignore", "pipe", "ignore"],
285
+ let out = "", done = false, exit;
286
+ probeExit = new Promise(settle => { exit = settle; });
287
+ const { command, shell } = claudeAuthSpawn();
288
+ const child = spawn(command, ["auth", "status", "--json"], {
289
+ cwd: homeDir(), stdio: ["ignore", "pipe", "ignore"], shell, windowsHide: true,
237
290
  env: { ...process.env, ...claudeLaunchEnv(home), NO_COLOR: "1" },
238
291
  });
239
292
  const finish = () => { if (!done) {
@@ -241,17 +294,19 @@ const runAuthStatus = home => new Promise(resolve => {
241
294
  clearTimeout(timer);
242
295
  resolve(out);
243
296
  } };
244
- const timer = setTimeout(() => { child.kill("SIGKILL"); finish(); }, AUTH_TIMEOUT_MS);
297
+ const timer = setTimeout(() => { claudeAuthKill(child); finish(); }, AUTH_TIMEOUT_MS);
245
298
  child.stdout.on("data", (chunk) => { if (out.length < 16_384)
246
299
  out += chunk.toString(); });
247
- child.on("error", finish);
248
- child.on("close", finish);
300
+ child.on("error", () => { exit(); finish(); });
301
+ child.on("close", () => { exit(); finish(); });
249
302
  });
250
303
  export function claudeAuthStatus(home, run = runAuthStatus, now = Date.now()) {
304
+ const fingerprint = claudeLoginFingerprint(home);
251
305
  const cached = authCache.get(home.dir);
252
- if (cached && now - cached.at < (cached.signedIn === false ? SIGNED_OUT_CACHE_MS : AUTH_CACHE_MS))
306
+ // A re-login changes the fingerprint: an answer cached for the old login must not be reused.
307
+ if (cached && cached.fingerprint === fingerprint && now - cached.at < (cached.signedIn === false ? SIGNED_OUT_CACHE_MS : AUTH_CACHE_MS))
253
308
  return cached.value;
254
- const entry = { at: now, value: Promise.resolve({ signedIn: false }) };
309
+ const entry = { at: now, fingerprint, value: Promise.resolve({ signedIn: false }) };
255
310
  // A signed-out answer is kept briefly so a fresh /login shows up within half a minute.
256
311
  entry.value = run(home).then(parseAuthStatus, () => ({ signedIn: false, unknown: true, reason: "Claude did not report its sign-in state" }))
257
312
  .then(status => { entry.signedIn = status.unknown ? false : status.signedIn; return status; });