carrick 0.3.183 → 0.3.185

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 (85) hide show
  1. package/dist/contract.d.ts +0 -4
  2. package/dist/contract.js.map +1 -1
  3. package/dist/facts/fetch.d.ts +1 -1
  4. package/dist/facts/fetch.js +1 -1
  5. package/dist/facts/fetch.js.map +1 -1
  6. package/dist/held/client.d.ts +1 -1
  7. package/dist/held/client.js +27 -19
  8. package/dist/held/client.js.map +1 -1
  9. package/dist/held/clone-worker.d.ts +1 -0
  10. package/dist/held/clone-worker.js +7 -0
  11. package/dist/held/clone-worker.js.map +1 -0
  12. package/dist/held/daemon.d.ts +92 -4
  13. package/dist/held/daemon.js +418 -74
  14. package/dist/held/daemon.js.map +1 -1
  15. package/dist/held/paths.d.ts +9 -0
  16. package/dist/held/paths.js +9 -0
  17. package/dist/held/paths.js.map +1 -1
  18. package/dist/held/registry.d.ts +8 -0
  19. package/dist/held/registry.js +28 -0
  20. package/dist/held/registry.js.map +1 -1
  21. package/dist/held/run.js +8 -0
  22. package/dist/held/run.js.map +1 -1
  23. package/dist/held/runtime.js +88 -17
  24. package/dist/held/runtime.js.map +1 -1
  25. package/dist/held/shadow.d.ts +62 -0
  26. package/dist/held/shadow.js +359 -1
  27. package/dist/held/shadow.js.map +1 -1
  28. package/dist/held/state.d.ts +2 -1
  29. package/dist/held/state.js.map +1 -1
  30. package/dist/hook/added.d.ts +51 -0
  31. package/dist/hook/added.js +96 -0
  32. package/dist/hook/added.js.map +1 -0
  33. package/dist/hook/confirm.d.ts +15 -0
  34. package/dist/hook/confirm.js +28 -3
  35. package/dist/hook/confirm.js.map +1 -1
  36. package/dist/hook/edit-flow.d.ts +7 -0
  37. package/dist/hook/edit-flow.js +29 -8
  38. package/dist/hook/edit-flow.js.map +1 -1
  39. package/dist/hook/late.d.ts +24 -7
  40. package/dist/hook/late.js +100 -33
  41. package/dist/hook/late.js.map +1 -1
  42. package/dist/hook/not-checked.d.ts +13 -0
  43. package/dist/hook/not-checked.js +50 -1
  44. package/dist/hook/not-checked.js.map +1 -1
  45. package/dist/hook/post-edit.d.ts +2 -0
  46. package/dist/hook/post-edit.js +3 -1
  47. package/dist/hook/post-edit.js.map +1 -1
  48. package/dist/hook/post-read.js +8 -1
  49. package/dist/hook/post-read.js.map +1 -1
  50. package/dist/hook/rechecks.d.ts +23 -5
  51. package/dist/hook/rechecks.js +31 -6
  52. package/dist/hook/rechecks.js.map +1 -1
  53. package/dist/hook/refresh.d.ts +7 -2
  54. package/dist/hook/refresh.js +7 -2
  55. package/dist/hook/refresh.js.map +1 -1
  56. package/dist/hook/session-start.js +17 -1
  57. package/dist/hook/session-start.js.map +1 -1
  58. package/dist/hook/similar.d.ts +6 -3
  59. package/dist/hook/similar.js +10 -3
  60. package/dist/hook/similar.js.map +1 -1
  61. package/dist/hook/stop-wait.js +24 -9
  62. package/dist/hook/stop-wait.js.map +1 -1
  63. package/dist/hook/upgrade.d.ts +1 -1
  64. package/dist/hook/upgrade.js +4 -1
  65. package/dist/hook/upgrade.js.map +1 -1
  66. package/dist/hook/usage.d.ts +1 -1
  67. package/dist/hook/usage.js +1 -1
  68. package/dist/hook/usage.js.map +1 -1
  69. package/dist/hook/worktree-rules.d.ts +5 -0
  70. package/dist/hook/worktree-rules.js +30 -0
  71. package/dist/hook/worktree-rules.js.map +1 -0
  72. package/dist/hook/worktree.d.ts +5 -0
  73. package/dist/hook/worktree.js +7 -0
  74. package/dist/hook/worktree.js.map +1 -1
  75. package/dist/render.d.ts +3 -1
  76. package/dist/render.js +8 -9
  77. package/dist/render.js.map +1 -1
  78. package/dist/update.js +2 -1
  79. package/dist/update.js.map +1 -1
  80. package/package.json +6 -6
  81. package/plugin/.claude-plugin/plugin.json +1 -1
  82. package/templates/skills/carrick-audit.md +325 -95
  83. package/templates/skills/carrick-census.md +11 -2
  84. package/templates/skills/carrick-drift.md +56 -13
  85. package/templates/skills/carrick-reuse.md +13 -28
@@ -15,10 +15,10 @@ import { readJson, releaseLock, takeLock, touchLock } from "../hook/lock.js";
15
15
  import { answerEarly, supersededEntry } from "../hook/rechecks.js";
16
16
  import { linkedCheckoutTop, mainCheckoutOf } from "../hook/worktree.js";
17
17
  import { heldBuildId } from "./build.js";
18
- import { heldDir, helloPath, lockPath, LOCK_CAP_MS, logPath, socketPath } from "./paths.js";
18
+ import { heldDir, heldRootOf, helloPath, lockPath, LOCK_CAP_MS, logPath, placedPath, serviceFilesDir, socketPath, statePath } from "./paths.js";
19
19
  import { readState, writeState } from "./state.js";
20
20
  import { addSteps, tenth } from "./steps.js";
21
- import { admits, ADMISSION_MB, EVICT_IDLE_MS, liveEntries, memoryBudgetMb, removeEntry, closeCeilingMb, writeEntry, } from "./registry.js";
21
+ import { admits, ADMISSION_MB, EVICT_IDLE_MS, liveEntries, memoryBudgetMb, removeEntry, closeCeilingMb, isWorktreeEntry, worktreeSlotsMax, worktreesEnabled, writeEntry, } from "./registry.js";
22
22
  const log = createLogger("carrick-held");
23
23
  const MIN = 60_000;
24
24
  /** D2: an engine closes after this long with no request. */
@@ -29,10 +29,45 @@ const DAEMON_IDLE_MS = 30 * MIN;
29
29
  const EMPTY_EXIT_MS = 5 * MIN;
30
30
  /** A start that failed is tried again after this long. */
31
31
  const RETRY_MS = 5 * MIN;
32
+ /**
33
+ * A linked worktree's engine closes after this long with no request (#5038, T2): it starts again from a
34
+ * clone of main's shadow in seconds, so it gives its memory back sooner than a main-checkout engine.
35
+ */
36
+ export const WORKTREE_IDLE_MS = 60_000;
37
+ /** A worktree ask that waited out its `wait_ms` is kept this long, and answered late if a slot frees (#5038, T3). */
38
+ const WORKTREE_PARK_MS = 2 * MIN;
39
+ /** The note a worktree ask gets when every worktree slot is busy and the cap or budget has no room. */
40
+ const SLOTS_BUSY = "worktree slots busy";
41
+ /** A worktree clone refused for one of these is tried once more after the main checkout's service has started (it writes a fresh shadow and stamp). */
42
+ const STALE_MAIN = new Set(["no_saved_answer", "stale_build", "stale_main_inputs"]);
43
+ /** ...and for these the main checkout's engine is stale too: a ready one is closed and started again first (T2 F3). */
44
+ const RESTART_MAIN = new Set(["stale_build", "stale_main_inputs"]);
45
+ /** T2 F5: a main start waits at most this long for a worktree engine's ask in flight before it closes that engine. */
46
+ const MAIN_START_WAIT_MS = 2_000;
32
47
  /** A reason as one short line. */
33
48
  const oneLine = (text) => text.replace(/\s+/g, " ").trim().slice(0, 160);
34
- const key = (init) => `${init.repo}\0${init.service}`;
49
+ const key = (init) => `${init.repo}\0${init.service}${init.checkout === undefined ? "" : `\0${init.checkout}`}`;
50
+ /** One service, whichever checkout: its starts (and its worktree engines' closes) run one at a time. */
51
+ const serviceKey = (init) => `${init.repo}\0${init.service}`;
35
52
  const within = (file, dir) => file === dir || file.startsWith(dir + path.sep);
53
+ /**
54
+ * The main checkout's init for a service, re-pointed at a linked worktree (#5038, T2): the same service,
55
+ * with its folders at the same place under the worktree's top, and `checkout` naming that top. Null when
56
+ * a folder of the init is not under the main checkout's top.
57
+ */
58
+ function initInWorktree(init, mainTop, top) {
59
+ const move = (p) => {
60
+ const rel = path.relative(mainTop, realPath(p));
61
+ return rel.startsWith("..") || path.isAbsolute(rel) ? null : path.join(top, rel);
62
+ };
63
+ const repoPath = move(init.repo_path);
64
+ const sidecarRoot = move(init.sidecar_root);
65
+ const scanRoot = move(init.scan_root);
66
+ if (repoPath === null || sidecarRoot === null || scanRoot === null)
67
+ return null;
68
+ const tsconfig = init.tsconfig !== null && path.isAbsolute(init.tsconfig) ? (move(init.tsconfig) ?? init.tsconfig) : init.tsconfig;
69
+ return { ...init, repo_path: repoPath, sidecar_root: sidecarRoot, scan_root: scanRoot, tsconfig, checkout: top };
70
+ }
36
71
  /**
37
72
  * Whether a program serves a file: the file is inside the program's folder AND in the
38
73
  * same git checkout. A nested worktree's file sits under a repo-root program's folder
@@ -48,10 +83,16 @@ export class HeldDaemon {
48
83
  deps;
49
84
  root;
50
85
  slots = new Map();
86
+ /** Per service (`serviceKey`): the tail of its starts and worktree closes, run one at a time. */
87
+ chains = new Map();
51
88
  programs = null;
52
89
  lastRequest;
53
90
  emptySince = null;
54
91
  closed = false;
92
+ /** Worktree admissions run one at a time, so the cap and the budget are counted before each start, never beside it (T3). */
93
+ admitChain = Promise.resolve();
94
+ /** Worktree edit asks that waited out their `wait_ms`, per slot key: answered late once a slot frees (T3). */
95
+ parked = new Map();
55
96
  constructor(deps) {
56
97
  this.deps = deps;
57
98
  this.root = realPath(deps.root);
@@ -109,13 +150,7 @@ export class HeldDaemon {
109
150
  const commits = [];
110
151
  const steps = { programs: tenth(performance.now() - started) };
111
152
  const served = new Set();
112
- for (const { init, dir } of programs) {
113
- const mine = files.filter((f) => serves(f, dir));
114
- if (mine.length === 0)
115
- continue;
116
- for (const f of mine)
117
- served.add(f);
118
- const answer = await this.serveService(init, mine, request);
153
+ const take = (init, answer) => {
119
154
  states.push(answer.state);
120
155
  if (answer.state === "ready")
121
156
  ready.push(`${init.repo}/${init.service}`);
@@ -126,8 +161,19 @@ export class HeldDaemon {
126
161
  if (answer.engine !== undefined)
127
162
  engines.push(answer.engine);
128
163
  addSteps(steps, answer.steps);
164
+ };
165
+ for (const { init, dir } of programs) {
166
+ const mine = files.filter((f) => serves(f, dir));
167
+ if (mine.length === 0)
168
+ continue;
169
+ for (const f of mine)
170
+ served.add(f);
171
+ take(init, await this.serveService(init, mine, request));
129
172
  }
130
- // A worktree file no program serves is not checked: say so, and start nothing (T2, #5038).
173
+ // A worktree file no program serves goes to that worktree's own slot of its twin's service: an engine
174
+ // over a clone of main's shadow with the worktree's files (T2, #5038). Where the init cannot be
175
+ // re-pointed at the worktree, it is not checked: say so, and start nothing.
176
+ const worktrees = new Map();
131
177
  const told = new Set();
132
178
  for (const file of files) {
133
179
  if (served.has(file))
@@ -136,9 +182,20 @@ export class HeldDaemon {
136
182
  const main = top === null ? null : mainCheckoutOf(top);
137
183
  if (top === null || main === null)
138
184
  continue;
139
- const twin = path.join(realPath(main), path.relative(realPath(top), file));
185
+ const mainTop = realPath(main);
186
+ const twin = path.join(mainTop, path.relative(realPath(top), file));
140
187
  for (const { init, dir } of programs) {
141
- if (!within(twin, dir) || told.has(`${init.service}\0${top}`))
188
+ if (!within(twin, dir))
189
+ continue;
190
+ const theirs = worktreesEnabled(this.env()) ? initInWorktree(init, mainTop, realPath(top)) : null;
191
+ if (theirs !== null) {
192
+ const group = worktrees.get(key(theirs)) ?? { init: theirs, files: [] };
193
+ if (!group.files.includes(file))
194
+ group.files.push(file);
195
+ worktrees.set(key(theirs), group);
196
+ continue;
197
+ }
198
+ if (told.has(`${init.service}\0${top}`))
142
199
  continue;
143
200
  if (((await this.deps.runtime.rowCount?.(init)) ?? 1) === 0)
144
201
  continue;
@@ -147,6 +204,8 @@ export class HeldDaemon {
147
204
  states.push("worktree");
148
205
  }
149
206
  }
207
+ for (const { init, files: theirs } of worktrees.values())
208
+ take(init, await this.serveService(init, theirs, request));
150
209
  // One state for the whole request: the most useful one any service gave.
151
210
  const order = ["ready", "cold", "capped", "no_compiler", "error", "worktree"];
152
211
  const state = order.find((s) => states.includes(s)) ?? "none";
@@ -155,14 +214,24 @@ export class HeldDaemon {
155
214
  }
156
215
  async serveService(init, files, request) {
157
216
  const now = this.now();
217
+ // The off switch is read per request: no worktree slot starts, and a worktree file is answered `worktree` (T3).
218
+ if (init.checkout !== undefined && !worktreesEnabled(this.env()))
219
+ return this.notChecked(init, "worktree");
158
220
  let slot = this.slots.get(key(init));
159
- if (slot?.status === "failed" && now - slot.failedAt >= RETRY_MS) {
221
+ if ((slot?.status === "failed" || slot?.status === "refused") && now - slot.failedAt >= RETRY_MS) {
160
222
  this.slots.delete(key(init));
161
223
  slot = undefined;
162
224
  }
163
225
  if (slot === undefined) {
164
226
  if ((await this.deps.runtime.rowCount?.(init)) === 0)
165
227
  return { state: "none", lines: [], steps: {} };
228
+ if (init.checkout !== undefined) {
229
+ if (await this.admitWorktree(init, request.wait_ms ?? 0, request.kind === "edit" ? files : undefined))
230
+ return this.serveService(init, files, request);
231
+ this.park(init, files, request);
232
+ this.slotLog("capped", init);
233
+ return this.notChecked(init, "capped", SLOTS_BUSY);
234
+ }
166
235
  if (!(await this.makeRoom(init)))
167
236
  return this.notChecked(init, "capped");
168
237
  this.begin(init, now);
@@ -176,14 +245,25 @@ export class HeldDaemon {
176
245
  }
177
246
  if (slot.status === "no_compiler")
178
247
  return this.notChecked(init, "no_compiler");
248
+ if (slot.status === "refused")
249
+ return this.notChecked(init, "worktree", slot.reason);
179
250
  if (slot.status === "failed" || slot.engine === null)
180
251
  return this.notChecked(init, "error", slot.reason);
181
252
  const asked = await this.ask(slot, slot.engine, files, request);
182
253
  return asked === null ? this.notChecked(init, "error", "the engine could not answer") : { state: "ready", ...asked };
183
254
  }
184
- /** N2: keep an edit ask that named its entry and was answered `cold`; a read, or an ask with no entry, files nothing to answer later. */
255
+ /**
256
+ * N2: keep an edit ask that named its entry and was answered `cold`; a read, or an ask with no entry, files nothing to
257
+ * answer later. On a worktree slot still starting, the ask's files join the files its start reads at the worktree's
258
+ * HEAD (T2 F1): a start that waits for the main checkout's engine snapshots the files only after that wait, and an
259
+ * edit made during it would otherwise be the gate's own text, its break left unarmed and never stated (T10, #5038).
260
+ */
185
261
  remember(slot, files, request) {
186
- if (slot === undefined || request.kind !== "edit" || request.seq === undefined)
262
+ if (slot === undefined || request.kind !== "edit")
263
+ return;
264
+ if (slot.init.checkout !== undefined && slot.status === "starting")
265
+ slot.edited = [...new Set([...(slot.edited ?? []), ...files])];
266
+ if (request.seq === undefined)
187
267
  return;
188
268
  slot.cold.set(`${request.session}\0${files.join("\0")}`, { request, files });
189
269
  }
@@ -213,6 +293,8 @@ export class HeldDaemon {
213
293
  const note = { service: init.service, state };
214
294
  if (reason !== undefined)
215
295
  note.reason = reason;
296
+ if (state === "worktree" && init.checkout !== undefined)
297
+ note.checkout = init.checkout;
216
298
  if (state === "capped") {
217
299
  const holders = liveEntries(this.deps.home).length;
218
300
  note.budget_mb = this.budget();
@@ -220,7 +302,7 @@ export class HeldDaemon {
220
302
  this.keep(init, { state: "capped", budget_mb: note.budget_mb, holders });
221
303
  }
222
304
  if (state === "cold") {
223
- const took = readState(this.root, init.service, this.deps.home)?.last_start_ms;
305
+ const took = readState(heldRootOf(init, this.root), init.service, this.deps.home)?.last_start_ms;
224
306
  if (took !== undefined)
225
307
  note.took_s = Math.round(took / 1000);
226
308
  }
@@ -228,51 +310,60 @@ export class HeldDaemon {
228
310
  }
229
311
  /** Write the service's state record (`state.ts`); a start's duration carries over to the next one. */
230
312
  keep(init, change) {
231
- const before = readState(this.root, init.service, this.deps.home);
313
+ const before = readState(heldRootOf(init, this.root), init.service, this.deps.home);
232
314
  const lastStart = change.start_ms ?? before?.start_ms ?? before?.last_start_ms;
233
315
  const settled = change.settled_mb ?? before?.settled_mb;
234
- writeState(this.root, init.service, { at: new Date(this.now()).toISOString(), service: init.service, repo: init.repo, ...(settled === undefined ? {} : { settled_mb: settled }), ...change, ...(lastStart === undefined || change.state === "ready" ? {} : { last_start_ms: lastStart }) }, this.deps.home);
316
+ writeState(heldRootOf(init, this.root), init.service, { at: new Date(this.now()).toISOString(), service: init.service, repo: init.repo, ...(settled === undefined ? {} : { settled_mb: settled }), ...change, ...(lastStart === undefined || change.state === "ready" ? {} : { last_start_ms: lastStart }) }, this.deps.home);
235
317
  }
236
318
  /** Asked through the slot's queue; `null` when the engine could not answer. */
237
319
  ask(slot, engine, files, request) {
238
320
  const queued = performance.now();
321
+ slot.busy += 1;
239
322
  return new Promise((resolve) => {
240
323
  slot.queue = slot.queue.then(async () => {
241
- const begun = performance.now();
242
- // A newer edit of the file asked again while this waited: its answer is
243
- // the one to give, and this one would only be stale.
244
- if (this.superseded(request)) {
245
- resolve({ lines: [], steps: { queue_wait: tenth(begun - queued) } });
246
- return;
247
- }
248
- let after;
249
- try {
250
- const answered = await engine.answer(files, request);
251
- after = answered.after;
252
- const engineMs = performance.now() - begun;
253
- resolve({
254
- lines: answered.lines,
255
- steps: { queue_wait: tenth(begun - queued), engine: tenth(engineMs), ...answered.steps },
256
- ...(answered.commit ? { commits: [answered.commit] } : {}),
257
- ...(answered.engine === undefined ? {} : { engine: answered.engine }),
258
- });
259
- }
260
- catch (error) {
261
- log("engine could not answer", String(error));
262
- resolve(null);
263
- }
264
- const afterBegun = performance.now();
265
324
  try {
266
- const afterSteps = await after?.();
267
- if (afterSteps !== undefined)
268
- this.recordAfter(request, slot.init.service, Math.round(performance.now() - afterBegun), afterSteps);
325
+ await this.askNow(slot, engine, files, request, queued, resolve);
269
326
  }
270
- catch (error) {
271
- log("after-answer step failed", String(error));
327
+ finally {
328
+ slot.busy -= 1;
272
329
  }
273
330
  });
274
331
  });
275
332
  }
333
+ async askNow(slot, engine, files, request, queued, resolve) {
334
+ const begun = performance.now();
335
+ // A newer edit of the file asked again while this waited: its answer is
336
+ // the one to give, and this one would only be stale.
337
+ if (this.superseded(request)) {
338
+ resolve({ lines: [], steps: { queue_wait: tenth(begun - queued) } });
339
+ return;
340
+ }
341
+ let after;
342
+ try {
343
+ const answered = await engine.answer(files, request);
344
+ after = answered.after;
345
+ const engineMs = performance.now() - begun;
346
+ resolve({
347
+ lines: answered.lines,
348
+ steps: { queue_wait: tenth(begun - queued), engine: tenth(engineMs), ...answered.steps },
349
+ ...(answered.commit ? { commits: [answered.commit] } : {}),
350
+ ...(answered.engine === undefined ? {} : { engine: answered.engine }),
351
+ });
352
+ }
353
+ catch (error) {
354
+ log("engine could not answer", String(error));
355
+ resolve(null);
356
+ }
357
+ const afterBegun = performance.now();
358
+ try {
359
+ const afterSteps = await after?.();
360
+ if (afterSteps !== undefined)
361
+ this.recordAfter(request, slot.init.service, Math.round(performance.now() - afterBegun), afterSteps);
362
+ }
363
+ catch (error) {
364
+ log("after-answer step failed", String(error));
365
+ }
366
+ }
276
367
  superseded(request) {
277
368
  return request.seq !== undefined && supersededEntry(request.session, request.seq, this.deps.home);
278
369
  }
@@ -285,7 +376,7 @@ export class HeldDaemon {
285
376
  log("held ask superseded by a newer edit; nothing filed");
286
377
  return false;
287
378
  }
288
- const named = { ...(by.service === undefined ? {} : { service: by.service }), ...(by.engine === undefined ? {} : { engine: by.engine }) };
379
+ const named = { ...(by.service === undefined ? {} : { service: by.service }), ...(by.engine === undefined ? {} : { engine: by.engine }), ...(by.notes === undefined ? {} : { not_checked: by.notes }) };
289
380
  return answerEarly(request.session, request.seq, { state, lines, ms, ...named }, this.now(), this.deps.home);
290
381
  }
291
382
  catch (error) {
@@ -293,49 +384,232 @@ export class HeldDaemon {
293
384
  return false;
294
385
  }
295
386
  }
387
+ env() {
388
+ return this.deps.env ?? process.env;
389
+ }
296
390
  budget() {
297
391
  return memoryBudgetMb(this.deps.env, this.deps.totalmem?.());
298
392
  }
299
393
  /**
300
- * Free room for one more engine, counted at the service's last settled size: close idle
301
- * engines, least recently used first. A service that alone exceeds the budget is never started.
394
+ * What a new slot is counted at in the budget. A main-checkout slot: its service's last settled size, else
395
+ * the plateau. A worktree slot: its own settled size when known, else the main checkout's for that service
396
+ * (the same program), else the plateau (#5038, T3).
397
+ */
398
+ admissionMb(init) {
399
+ const own = readState(heldRootOf(init, this.root), init.service, this.deps.home)?.settled_mb;
400
+ if (own !== undefined || init.checkout === undefined)
401
+ return own ?? ADMISSION_MB;
402
+ return readState(this.root, init.service, this.deps.home)?.settled_mb ?? ADMISSION_MB;
403
+ }
404
+ /**
405
+ * Free room for one more engine, counted at its admission size. A main-checkout start closes idle engines,
406
+ * least recently used first. A worktree start must also keep the live worktree slots on the machine under the
407
+ * cap: it closes the least recently used idle worktree slot first (whatever its idle age), then, for the
408
+ * budget only, an idle main slot by the usual rule; a busy slot is never closed for it (#5038, T3).
409
+ * A service that alone exceeds the budget is never started.
302
410
  */
303
411
  async makeRoom(init) {
304
412
  const budget = this.budget();
305
413
  const now = this.now();
306
- const need = readState(this.root, init.service, this.deps.home)?.settled_mb ?? ADMISSION_MB;
414
+ const need = this.admissionMb(init);
307
415
  if (need > budget)
308
416
  return false;
417
+ const worktree = init.checkout !== undefined;
418
+ const cap = worktreeSlotsMax(this.env());
309
419
  for (;;) {
310
- if (admits(liveEntries(this.deps.home), budget, need))
420
+ const entries = liveEntries(this.deps.home);
421
+ const overCap = worktree && entries.filter(isWorktreeEntry).length >= cap;
422
+ if (!overCap && admits(entries, budget, need))
311
423
  return true;
312
- const victim = [...this.slots.values()]
313
- .filter((s) => s.status === "ready" && now - s.lastUsed >= EVICT_IDLE_MS)
314
- .sort((a, b) => a.lastUsed - b.lastUsed)[0];
424
+ const ready = [...this.slots.values()].filter((s) => s.status === "ready");
425
+ const byUse = (a, b) => a.lastUsed - b.lastUsed;
426
+ let victim;
427
+ if (!worktree) {
428
+ victim = ready.filter((s) => now - s.lastUsed >= EVICT_IDLE_MS).sort(byUse)[0];
429
+ }
430
+ else {
431
+ victim = ready.filter((s) => s.init.checkout !== undefined && s.busy === 0).sort(byUse)[0];
432
+ if (victim === undefined && !overCap)
433
+ victim = ready.filter((s) => s.init.checkout === undefined && s.busy === 0 && now - s.lastUsed >= EVICT_IDLE_MS).sort(byUse)[0];
434
+ }
315
435
  if (victim === undefined)
316
436
  return false;
437
+ if (worktree)
438
+ this.slotLog("evict", init, { victim: victim.init.checkout ?? "main", victim_service: victim.init.service });
317
439
  await this.closeSlot(victim, "evicted");
318
440
  }
319
441
  }
320
- begin(init, now) {
321
- const settledMb = readState(this.root, init.service, this.deps.home)?.settled_mb;
322
- const slot = { init, status: "starting", engine: null, lastUsed: now, failedAt: 0, begunAt: now, queue: Promise.resolve(), cold: new Map(), ...(settledMb === undefined ? {} : { settledMb }) };
442
+ /** One row in the held log per worktree admit, evict, queue or capped decision, with the counts a soak test reads. */
443
+ slotLog(decision, init, more = {}) {
444
+ const entries = liveEntries(this.deps.home);
445
+ this.write({
446
+ at: new Date(this.now()).toISOString(),
447
+ kind: "slot",
448
+ decision,
449
+ service: init.service,
450
+ checkout: init.checkout,
451
+ worktrees: entries.filter(isWorktreeEntry).length,
452
+ cap: worktreeSlotsMax(this.env()),
453
+ held_mb: Math.round(entries.reduce((sum, e) => sum + e.rss_mb, 0)),
454
+ budget_mb: this.budget(),
455
+ need_mb: this.admissionMb(init),
456
+ ...more,
457
+ });
458
+ }
459
+ /** One attempt to admit a worktree slot, after every earlier attempt: true when the slot exists (made here or before). */
460
+ admitOnce(init, edited) {
461
+ const attempt = this.admitChain.then(async () => {
462
+ if (this.closed)
463
+ return false;
464
+ if (this.slots.has(key(init)))
465
+ return true;
466
+ if (!(await this.makeRoom(init)))
467
+ return false;
468
+ this.begin(init, this.now(), edited);
469
+ this.slotLog("admit", init);
470
+ return true;
471
+ });
472
+ this.admitChain = attempt.catch(() => undefined);
473
+ return attempt;
474
+ }
475
+ sleep(ms) {
476
+ return new Promise((resolve) => setTimeout(resolve, ms).unref());
477
+ }
478
+ /** Admit a worktree slot, waiting up to `waitMs` for the cap or the budget to free. False when it did not. */
479
+ async admitWorktree(init, waitMs, edited) {
480
+ const began = performance.now();
481
+ let queued = false;
482
+ for (;;) {
483
+ if (await this.admitOnce(init, edited))
484
+ return true;
485
+ const left = waitMs - (performance.now() - began);
486
+ if (left <= 0 || this.closed || this.admissionMb(init) > this.budget())
487
+ return false;
488
+ if (!queued) {
489
+ queued = true;
490
+ this.slotLog("queue", init, { wait_ms: waitMs });
491
+ }
492
+ await this.sleep(Math.min(left, this.deps.queuePollMs ?? 250));
493
+ }
494
+ }
495
+ /** Keep a capped worktree edit ask, so its answer still lands late through the early-answer path once a slot frees. */
496
+ park(init, files, request) {
497
+ if (request.kind !== "edit" || request.seq === undefined)
498
+ return;
499
+ const k = key(init);
500
+ const held = this.parked.get(k);
501
+ if (held !== undefined) {
502
+ held.asks.push({ files, request });
503
+ return;
504
+ }
505
+ const parked = { init, asks: [{ files, request }] };
506
+ this.parked.set(k, parked);
507
+ void this.drain(k, parked);
508
+ }
509
+ async drain(k, parked) {
510
+ const until = performance.now() + WORKTREE_PARK_MS;
511
+ try {
512
+ while (!this.closed && performance.now() < until) {
513
+ await this.sleep(this.deps.queuePollMs ?? 250);
514
+ const edited = [...new Set(parked.asks.flatMap((a) => a.files))];
515
+ if (!(await this.admitOnce(parked.init, edited)))
516
+ continue;
517
+ const slot = this.slots.get(k);
518
+ for (const { files, request } of parked.asks)
519
+ this.remember(slot, files, request);
520
+ if (slot?.status === "ready" && slot.engine !== null)
521
+ void this.askAgain(slot, slot.engine);
522
+ return;
523
+ }
524
+ }
525
+ finally {
526
+ this.parked.delete(k);
527
+ }
528
+ }
529
+ begin(init, now, edited) {
530
+ const settledMb = readState(heldRootOf(init, this.root), init.service, this.deps.home)?.settled_mb;
531
+ let settle = () => undefined;
532
+ const started = new Promise((resolve) => (settle = resolve));
533
+ const slot = { init, status: "starting", engine: null, lastUsed: now, failedAt: 0, begunAt: now, queue: Promise.resolve(), busy: 0, cold: new Map(), started, settle, ...(settledMb === undefined ? {} : { settledMb }), ...(edited === undefined ? {} : { edited }) };
323
534
  this.slots.set(key(init), slot);
324
535
  this.keep(init, { state: "starting" });
325
536
  this.emptySince = null;
326
- this.entry(slot, slot.settledMb ?? ADMISSION_MB);
537
+ this.entry(slot, init.checkout === undefined ? (slot.settledMb ?? ADMISSION_MB) : this.admissionMb(init));
327
538
  // The next turn of the event loop: a start's synchronous work (it clears the old shadow folder before its
328
539
  // first await) must not hold back the `cold` answer this ask is about to return.
329
540
  setImmediate(() => {
330
541
  void Promise.resolve()
331
- .then(() => this.deps.runtime.start(init))
332
- .then((result) => this.started(slot, result), (error) => this.started(slot, { state: "error", reason: String(error) }));
542
+ .then(() => this.run(slot))
543
+ .then((result) => this.started(slot, result), (error) => this.started(slot, { state: "error", reason: String(error) }))
544
+ .finally(() => slot.settle());
545
+ });
546
+ }
547
+ /** Run `fn` after every earlier start (and worktree close) of the same service has ended. */
548
+ serial(init, fn) {
549
+ const k = serviceKey(init);
550
+ const run = (this.chains.get(k) ?? Promise.resolve()).then(fn, fn);
551
+ this.chains.set(k, run.catch(() => undefined));
552
+ return run;
553
+ }
554
+ /**
555
+ * A start, one at a time per service. A main-checkout start rewrites the shadow its service's worktree
556
+ * clones read packages from (`v/`), so it first closes those worktree engines; they clone again on their
557
+ * next ask. A worktree start whose clone was refused for a stale or missing main shadow starts the main
558
+ * checkout's service first, through its normal path, and clones once more (#5038, T2).
559
+ */
560
+ async run(slot) {
561
+ const init = slot.init;
562
+ if (init.checkout === undefined) {
563
+ return this.serial(init, async () => {
564
+ // A worktree slot whose start already gave an engine is closed, ready or not yet marked so: it read the `v/` this start rewrites.
565
+ for (const other of [...this.slots.values()]) {
566
+ if (other.init.checkout !== undefined && serviceKey(other.init) === serviceKey(init) && (other.status === "ready" || other.cloned))
567
+ await this.closeSlot(other, "main_start", true, MAIN_START_WAIT_MS);
568
+ }
569
+ return this.deps.runtime.start(init);
570
+ });
571
+ }
572
+ const clone = () => this.serial(init, async () => {
573
+ const result = await this.deps.runtime.start(init, slot.edited === undefined ? {} : { edited: slot.edited });
574
+ if ("engine" in result)
575
+ slot.cloned = true;
576
+ return result;
333
577
  });
578
+ const first = await clone();
579
+ if (!("refused" in first) || !STALE_MAIN.has(first.refused))
580
+ return first;
581
+ log(`worktree clone of ${init.service} refused (${first.refused}); starting the main checkout's engine first`);
582
+ if (!(await this.startMain(init, first.refused)))
583
+ return first;
584
+ return clone();
585
+ }
586
+ /** Start the main checkout's slot of a worktree init's service, unless it has one, and wait for its start to end. False when it cannot be admitted. */
587
+ async startMain(worktree, refused) {
588
+ const main = (await this.loadPrograms()).find(({ init }) => init.checkout === undefined && serviceKey(init) === serviceKey(worktree))?.init;
589
+ if (main === undefined)
590
+ return false;
591
+ let slot = this.slots.get(key(main));
592
+ // Main's own engine read the same stale inputs or build: close it and start it again (T2 F3).
593
+ if (slot?.status === "ready" && RESTART_MAIN.has(refused)) {
594
+ log(`restarting ${main.service} in the main checkout: its shadow is stale (${refused})`);
595
+ await this.closeSlot(slot, "stale");
596
+ slot = undefined;
597
+ }
598
+ if (slot === undefined) {
599
+ if (!(await this.makeRoom(main)))
600
+ return false;
601
+ this.begin(main, this.now());
602
+ slot = this.slots.get(key(main));
603
+ }
604
+ await slot?.started;
605
+ return true;
334
606
  }
335
607
  started(slot, result) {
336
608
  if ("engine" in result) {
337
609
  if (this.closed || this.slots.get(key(slot.init)) !== slot) {
338
- void result.engine.close();
610
+ // A worktree engine's close (it removes the clone) runs in the service's chain, before any new start of that worktree clones.
611
+ const engine = result.engine;
612
+ void (slot.init.checkout === undefined ? engine.close() : this.serial(slot.init, () => engine.close())).catch((error) => log("engine close failed", String(error)));
339
613
  return;
340
614
  }
341
615
  slot.engine = result.engine;
@@ -350,35 +624,88 @@ export class HeldDaemon {
350
624
  this.keep(slot.init, { state: "ready", start_ms: this.now() - slot.begunAt, ...(settled === undefined ? {} : { settled_mb: settled }) });
351
625
  // Give back the admission slot; the slot stays ready so its asks still answer.
352
626
  if (result.engine.holdsCompiler === false)
353
- removeEntry(this.deps.home, process.pid, this.root, slot.init.service);
627
+ removeEntry(this.deps.home, process.pid, heldRootOf(slot.init, this.root), slot.init.service);
354
628
  void this.askAgain(slot, result.engine);
355
629
  return;
356
630
  }
631
+ if (result.state === "refused") {
632
+ log(`no engine for ${slot.init.service} in ${slot.init.checkout ?? "the main checkout"}: clone refused (${result.refused}): ${result.detail}`);
633
+ slot.status = "refused";
634
+ slot.failedAt = this.now();
635
+ slot.reason = result.refused;
636
+ this.tellKept(slot, this.notChecked(slot.init, "worktree", result.refused).note);
637
+ this.keep(slot.init, { state: "failed", reason: oneLine(`${result.refused}: ${result.detail}`) });
638
+ removeEntry(this.deps.home, process.pid, heldRootOf(slot.init, this.root), slot.init.service);
639
+ // A refused slot holds nothing: it does not keep the daemon from its empty exit (T2 F4).
640
+ if (this.holding() === 0)
641
+ this.emptySince ??= this.now();
642
+ return;
643
+ }
357
644
  log(`no engine for ${slot.init.service}: ${result.reason}`);
358
645
  slot.status = result.state === "no_compiler" ? "no_compiler" : "failed";
359
646
  slot.failedAt = this.now();
360
647
  slot.reason = oneLine(result.reason);
648
+ if (slot.init.checkout !== undefined)
649
+ this.tellKept(slot, this.notChecked(slot.init, slot.status === "no_compiler" ? "no_compiler" : "error", slot.status === "no_compiler" ? undefined : slot.reason).note);
361
650
  this.keep(slot.init, { state: slot.status === "no_compiler" ? "no_compiler" : "failed", reason: slot.reason });
362
- removeEntry(this.deps.home, process.pid, this.root, slot.init.service);
651
+ removeEntry(this.deps.home, process.pid, heldRootOf(slot.init, this.root), slot.init.service);
652
+ }
653
+ /**
654
+ * A worktree slot that will never answer: each edit ask it kept while starting gets the not-checked note in its
655
+ * early answer, so the next carrier says why instead of nothing (T10, #5038). Only ever a worktree slot's.
656
+ */
657
+ tellKept(slot, note) {
658
+ const kept = [...slot.cold.values()];
659
+ slot.cold.clear();
660
+ for (const { request } of kept)
661
+ this.file(request, note.state === "worktree" ? "worktree" : note.state === "no_compiler" ? "no_compiler" : "error", [], 0, { service: `${slot.init.repo}/${slot.init.service}`, notes: [note] });
363
662
  }
364
663
  entry(slot, rssMb) {
365
664
  writeEntry(this.deps.home, {
366
665
  pid: process.pid,
367
- root: this.root,
666
+ root: heldRootOf(slot.init, this.root),
368
667
  service: slot.init.service,
369
668
  rss_mb: rssMb,
370
669
  last_used: slot.lastUsed,
371
670
  });
372
671
  }
373
- async closeSlot(slot, reason) {
672
+ /**
673
+ * `chained`: the caller already runs in the service's start chain. A worktree engine's close otherwise
674
+ * joins that chain, so a new start of the same worktree never clones while the old clone is removed.
675
+ */
676
+ async closeSlot(slot, reason, chained = false, waitMs) {
374
677
  this.write({ at: new Date(this.now()).toISOString(), kind: "close", service: slot.init.service, reason });
375
678
  this.slots.delete(key(slot.init));
376
- removeEntry(this.deps.home, process.pid, this.root, slot.init.service);
377
- if (this.slots.size === 0)
679
+ removeEntry(this.deps.home, process.pid, heldRootOf(slot.init, this.root), slot.init.service);
680
+ if (this.holding() === 0)
378
681
  this.emptySince = this.now();
379
682
  const engine = slot.engine;
380
- // After the call in flight, never under it.
381
- await slot.queue.then(() => engine?.close()).catch((error) => log("engine close failed", String(error)));
683
+ // After the call in flight, never under it; with `waitMs`, no longer than that (T2 F5).
684
+ const done = slot.queue.catch(() => undefined);
685
+ const waited = waitMs === undefined ? done : Promise.race([done, new Promise((resolve) => setTimeout(resolve, waitMs).unref())]);
686
+ const close = () => waited
687
+ .then(() => engine?.close())
688
+ .catch((error) => log("engine close failed", String(error)))
689
+ .then(() => this.forget(slot));
690
+ await (slot.init.checkout === undefined || chained ? close() : this.serial(slot.init, close));
691
+ }
692
+ /** A closed worktree slot's placed and state files go with its clone, unless a new slot of that worktree holds them now (T2 F4). */
693
+ forget(slot) {
694
+ if (slot.init.checkout === undefined || this.slots.has(key(slot.init)))
695
+ return;
696
+ const root = heldRootOf(slot.init, this.root);
697
+ for (const file of [placedPath(root, slot.init.service, this.deps.home), statePath(root, slot.init.service, this.deps.home)])
698
+ fs.rmSync(file, { force: true });
699
+ try {
700
+ fs.rmdirSync(serviceFilesDir(root, this.deps.home));
701
+ }
702
+ catch {
703
+ // Another service of that worktree still has files there.
704
+ }
705
+ }
706
+ /** Slots that hold or wait for an engine: a refused worktree slot holds nothing. */
707
+ holding() {
708
+ return [...this.slots.values()].filter((s) => s.status !== "refused").length;
382
709
  }
383
710
  /** Housekeeping: close idle or oversized engines, refresh the registry. */
384
711
  async tick() {
@@ -392,7 +719,8 @@ export class HeldDaemon {
392
719
  const oversized = rss !== null && rss > ceiling;
393
720
  if (oversized)
394
721
  log(`closing ${slot.init.service} for size: ${Math.round(rss)} MB is above ${ceiling} MB (1.5 x ${slot.settledMb ?? "the floor"})`);
395
- if (now - slot.lastUsed >= ENGINE_IDLE_MS || oversized) {
722
+ const idleMs = slot.init.checkout === undefined ? ENGINE_IDLE_MS : WORKTREE_IDLE_MS;
723
+ if (now - slot.lastUsed >= idleMs || oversized) {
396
724
  await this.closeSlot(slot, oversized ? "size" : "idle");
397
725
  }
398
726
  else if (holdsEntry && rss !== null) {
@@ -404,7 +732,7 @@ export class HeldDaemon {
404
732
  const now = this.now();
405
733
  if (now - this.lastRequest >= DAEMON_IDLE_MS)
406
734
  return true;
407
- return this.slots.size === 0 && this.emptySince !== null && now - this.emptySince >= EMPTY_EXIT_MS;
735
+ return this.holding() === 0 && this.emptySince !== null && now - this.emptySince >= EMPTY_EXIT_MS;
408
736
  }
409
737
  async close() {
410
738
  this.closed = true;
@@ -480,6 +808,11 @@ export async function serve(deps, options = {}) {
480
808
  if (frame !== null && "hello" in frame) {
481
809
  conn.write(`${JSON.stringify({ hello })}\n`);
482
810
  }
811
+ else if (frame !== null && "ask" in frame) {
812
+ // Another build's ask is never answered, and the connection stays open for the `exit` its asker sends next.
813
+ if (frame.build_id === hello.build_id)
814
+ conn.end(`${JSON.stringify(await answerRequest(daemon, frame.ask))}\n`);
815
+ }
483
816
  else if (frame !== null) {
484
817
  retire();
485
818
  conn.end(`${JSON.stringify({ bye: true })}\n`);
@@ -551,6 +884,9 @@ function parseFrame(text) {
551
884
  return { hello: true };
552
885
  if (parsed["exit"] === true)
553
886
  return { exit: true };
887
+ if (typeof parsed["build_id"] === "string" && typeof parsed["ask"] === "object" && parsed["ask"] !== null) {
888
+ return { ask: parsed["ask"], build_id: parsed["build_id"] };
889
+ }
554
890
  }
555
891
  catch {
556
892
  // Not a frame: a request line, answered (or failed) as one.
@@ -559,7 +895,15 @@ function parseFrame(text) {
559
895
  }
560
896
  async function answer(daemon, text) {
561
897
  try {
562
- return await daemon.handle(JSON.parse(text));
898
+ return await answerRequest(daemon, JSON.parse(text));
899
+ }
900
+ catch {
901
+ return { state: "error", lines: [], ms: 0 };
902
+ }
903
+ }
904
+ async function answerRequest(daemon, request) {
905
+ try {
906
+ return await daemon.handle(request);
563
907
  }
564
908
  catch {
565
909
  return { state: "error", lines: [], ms: 0 };