opencode-model-router 2.8.0 → 2.9.1

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 (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -0,0 +1,1564 @@
1
+ // Slot pool (phase 2.4.3), see docs/qa/critical-path-execution/phase-2.4.md sections 3 and 4.
2
+ // Layout: <slotsDir>\slot-<n>, <slotsDir>\integration, <slotsDir>\ci. Markers: <markersDir>\<planId>\<slot>.json (DV1).
3
+ // All I/O goes through the seams (GitOps, FileSystem, Clock, Provisioner); no node:fs here.
4
+ // Every destructive clean is preceded by a sweep of exactly the paths `git clean -n` lists (GitOps.cleanPreview), because
5
+ // git's recursive delete can follow a junction. Phase 3.1 commits before it calls `cleanForChecks`.
6
+
7
+ import { posix, win32 } from "node:path";
8
+ import { CLEANUP_RETRIES, CLEANUP_RETRY_BASE_MS, TRANSIENT_FS_CODES, isStrictlyInside } from "../../verify/reference";
9
+ import type { ObservationValue } from "../../compat/v2-observations";
10
+ import type { GitOps } from "../git";
11
+ import { observeSlotPool } from "../observations";
12
+ import { ExecutorError, GIT_ID_PATTERN, PLAN_ID_PATTERN, isTaskId } from "../types";
13
+ import type { Clock, FileSystem, PlanId, SlotAcquisition, SlotLease, SlotPool, SlotRecord } from "../types";
14
+ import { registerSlot, unregisterSlot } from "./env";
15
+ import type { SlotBin } from "./env";
16
+ import { DEPENDENCY_DIRS, SLOT_SWEEP_MAX_ENTRIES, needsProvision } from "./provision";
17
+ import type { Detection, Provisioner } from "./provision";
18
+
19
+ export const UNKNOWN_PLAN_GC_AGE_MS = 7 * 24 * 3_600_000;
20
+ export { SLOT_SWEEP_MAX_ENTRIES }; // one cap, defined next to the provisioner's own sweep
21
+ export const SLOT_RM_BUDGET_MS = 120_000; // per slot, confirm with M7
22
+ export const RESET_RETRY_DELAY_MS = 2_000;
23
+ export const SLOT_NAME_PATTERN = /^(?:slot-[1-9][0-9]{0,2}|integration|ci)$/;
24
+
25
+ const MARKER_MAX_BYTES = 64 * 1024;
26
+ const MAX_TASK_SLOT_NUMBER = 999;
27
+ const OWNER_PATTERN = /^[\x20-\x7e]{1,128}$/;
28
+ const MANIFEST_DIGEST_PATTERN = /^[0-9a-f]{64}$/;
29
+ const SLOT_STATES: readonly SlotRecord["state"][] = ["creating", "provisioning", "ready", "leased", "resetting", "broken", "retired"];
30
+ const STAGE_STATES: readonly SlotRecord["state"][] = ["creating", "provisioning", "resetting"];
31
+ const DEPENDENCY_DIR_NAMES: ReadonlySet<string> = new Set(Object.values(DEPENDENCY_DIRS).flat());
32
+ const NODE_MANAGER_NAMES: readonly string[] = ["npm", "pnpm", "yarn"];
33
+ const PYTHON_MANAGER_NAMES: readonly string[] = ["pip", "poetry", "uv"];
34
+
35
+ export interface SlotPoolDeps {
36
+ planId: PlanId; repoKey: string; toplevel: string; slotsDir: string; markersDir: string; executorHome: string;
37
+ maxParallel: number; git: GitOps; fs: FileSystem; clock: Clock; provisioner: Provisioner;
38
+ /** The ledger's current integration head; required for acquireSpecial, omitted only by task-only/gc handles. */
39
+ integrationHead?(): string | Promise<string>;
40
+ platform?: NodeJS.Platform; logger?: { warn(m: string): void };
41
+ onProvision?: (slot: string, managers: readonly string[]) => void; // test and smoke hook
42
+ }
43
+
44
+ type GcDeps = Omit<SlotPoolDeps, "planId" | "maxParallel" | "provisioner" | "onProvision" | "integrationHead">;
45
+
46
+ export interface SlotPoolOpenOptions {
47
+ /**
48
+ * QA-5.1-22: `false` opens a gc-only handle (purge, a closed plan's gc): no directory is created, a missing slotsDir holds
49
+ * no slot, no sidecar is rewritten, no slot environment is registered, and nothing is ever leased. Default true.
50
+ */
51
+ readonly create?: boolean;
52
+ }
53
+
54
+ /** The pool `createSlotPool` returns: the SlotPool, its open/close, and the purge's empty-directory removal (QA-5.1-22). */
55
+ export type OpenSlotPool = SlotPool & { open(opts?: SlotPoolOpenOptions): Promise<void>; close(): void; removeEmptyDir(): Promise<boolean> };
56
+
57
+ /**
58
+ * QA-5.1-22: how many slot markers (valid or not) plan `planId` still has under `markersDir`. Reads only: a purge that cannot
59
+ * build the plan's pool (an invalid slotsDir) asks it before skipping the gc.
60
+ */
61
+ export async function countPlanMarkers(x: { fs: FileSystem; markersDir: string; platform?: NodeJS.Platform }, planId: PlanId): Promise<number> {
62
+ if (!PLAN_ID_PATTERN.test(planId)) throw new ExecutorError("E_INVALID_INPUT", "invalid plan id", { planId: String(planId).slice(0, 80) });
63
+ const api = pathApi(x.platform ?? process.platform);
64
+ const dir = api.join(x.markersDir, planId);
65
+ const st = await x.fs.lstat(dir);
66
+ if (st === null) return 0;
67
+ // Not a directory: unreadable markers count as present (fail closed).
68
+ if (st.kind !== "dir") return 1;
69
+ return (await readdirOrEmpty(x.fs, dir)).filter((name) => name.endsWith(".json")).length;
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------------------------------------------
73
+ // Pure helpers
74
+ // ---------------------------------------------------------------------------------------------------------------
75
+
76
+ function pathApi(platform: NodeJS.Platform): typeof win32 {
77
+ return platform === "win32" ? win32 : posix;
78
+ }
79
+
80
+ function shapeApi(p: string): typeof win32 {
81
+ return /^[A-Za-z]:[\\/]|^[\\/]{2}/.test(p) ? win32 : posix;
82
+ }
83
+
84
+ function comparable(p: string, platform: NodeJS.Platform): string {
85
+ const resolved = pathApi(platform).resolve(p);
86
+ return platform === "win32" ? resolved.toLowerCase() : resolved;
87
+ }
88
+
89
+ function isInsideOrEqual(child: string, parent: string, platform: NodeJS.Platform): boolean {
90
+ return comparable(child, platform) === comparable(parent, platform) || isStrictlyInside(child, parent, platform);
91
+ }
92
+
93
+ function hasDotSegment(p: string): boolean {
94
+ return p.split(/[\\/]+/).some((segment) => segment === "." || segment === "..");
95
+ }
96
+
97
+ function errorCode(error: unknown): string | undefined {
98
+ if (typeof error === "object" && error !== null && "code" in error) {
99
+ const code: unknown = Reflect.get(error, "code");
100
+ return typeof code === "string" ? code : undefined;
101
+ }
102
+ return undefined;
103
+ }
104
+
105
+ function messageOf(error: unknown): string {
106
+ return error instanceof Error ? error.message : String(error);
107
+ }
108
+
109
+ function isPlainRecord(v: unknown): v is Record<string, unknown> {
110
+ return typeof v === "object" && v !== null && !Array.isArray(v);
111
+ }
112
+
113
+ function slotKindOf(slot: string): SlotRecord["kind"] {
114
+ return slot === "integration" ? "integration" : slot === "ci" ? "ci" : "task";
115
+ }
116
+
117
+ function slotOrder(slot: string): number {
118
+ if (slot === "integration") return 1_000_000;
119
+ if (slot === "ci") return 1_000_001;
120
+ const n = Number(slot.slice("slot-".length));
121
+ return Number.isFinite(n) ? n : 2_000_000;
122
+ }
123
+
124
+ function compareSlots(a: string, b: string): number {
125
+ return slotOrder(a) - slotOrder(b);
126
+ }
127
+
128
+ function timeOf(iso: string): number {
129
+ const t = Date.parse(iso);
130
+ return Number.isNaN(t) ? 0 : t;
131
+ }
132
+
133
+ /** A `.produced` sidecar: a JSON array of clean exclusions (each 1-400 characters, no newline). */
134
+ function parseStringArray(text: string | null): string[] | null {
135
+ if (text === null) return null;
136
+ let value: unknown;
137
+ try {
138
+ value = JSON.parse(text);
139
+ } catch {
140
+ // A torn or foreign file is treated like a missing one; the caller warns.
141
+ return null;
142
+ }
143
+ if (!Array.isArray(value)) return null;
144
+ const out: string[] = [];
145
+ for (const item of value as unknown[]) {
146
+ if (typeof item !== "string" || item.length === 0 || item.length > 400 || item.includes("\n")) return null;
147
+ out.push(item);
148
+ }
149
+ return out;
150
+ }
151
+
152
+ /** A `.bins` sidecar: a JSON array of `{path, size, mtimeMs}`. */
153
+ function parseBins(text: string | null): SlotBin[] | null {
154
+ if (text === null) return null;
155
+ let value: unknown;
156
+ try {
157
+ value = JSON.parse(text);
158
+ } catch {
159
+ // A torn or foreign file is treated like a missing one; the caller warns.
160
+ return null;
161
+ }
162
+ if (!Array.isArray(value)) return null;
163
+ const out: SlotBin[] = [];
164
+ for (const item of value as unknown[]) {
165
+ if (!isPlainRecord(item)) return null;
166
+ const { path, size, mtimeMs } = item;
167
+ if (typeof path !== "string" || path.length === 0 || typeof size !== "number" || typeof mtimeMs !== "number") return null;
168
+ out.push({ path, size, mtimeMs });
169
+ }
170
+ return out;
171
+ }
172
+
173
+ function cloneRecord(r: SlotRecord): SlotRecord {
174
+ return { ...r, managers: [...r.managers], manifests: { ...r.manifests } };
175
+ }
176
+
177
+ /** Guard for a marker read from disk (memo 3); the content is exactly `SlotRecord`. */
178
+ export function isSlotRecord(v: unknown): v is SlotRecord {
179
+ if (!isPlainRecord(v)) return false;
180
+ if (v["schema"] !== 1) return false;
181
+ const slot = v["slot"];
182
+ if (typeof slot !== "string" || !SLOT_NAME_PATTERN.test(slot)) return false;
183
+ const path = v["path"];
184
+ if (typeof path !== "string" || path.length === 0 || path.length > 4096) return false;
185
+ if (v["kind"] !== slotKindOf(slot)) return false;
186
+ const planId = v["planId"];
187
+ if (typeof planId !== "string" || !PLAN_ID_PATTERN.test(planId)) return false;
188
+ const repoKey = v["repoKey"];
189
+ if (typeof repoKey !== "string" || repoKey.length === 0 || repoKey.length > 512) return false;
190
+ const state = v["state"];
191
+ if (typeof state !== "string" || !(SLOT_STATES as readonly string[]).includes(state)) return false;
192
+ const owner = v["owner"];
193
+ if (owner !== null && (typeof owner !== "string" || !OWNER_PATTERN.test(owner))) return false;
194
+ const commit = v["commit"];
195
+ if (commit !== null && (typeof commit !== "string" || !GIT_ID_PATTERN.test(commit))) return false;
196
+ const managers = v["managers"];
197
+ if (!Array.isArray(managers) || managers.length > 16) return false;
198
+ if (!managers.every((m: unknown) => typeof m === "string" && m.length > 0 && m.length <= 32)) return false;
199
+ const manifests = v["manifests"];
200
+ if (!isPlainRecord(manifests)) return false;
201
+ if (!Object.values(manifests).every((h) => typeof h === "string" && MANIFEST_DIGEST_PATTERN.test(h))) return false;
202
+ const createdAt = v["createdAt"];
203
+ const updatedAt = v["updatedAt"];
204
+ return typeof createdAt === "string" && createdAt.length <= 40 && typeof updatedAt === "string" && updatedAt.length <= 40;
205
+ }
206
+
207
+ export function slotLockReason(planId: PlanId, slot: string): string {
208
+ return `omr-executor slot ${planId}/${slot}: managed by the model-router executor; remove with router_plan action=gc`;
209
+ }
210
+
211
+ export function markerPath(markersDir: string, planId: PlanId, slot: string): string {
212
+ if (!PLAN_ID_PATTERN.test(planId)) throw new ExecutorError("E_INVALID_INPUT", "invalid plan id for a slot marker", { planId: String(planId).slice(0, 80) });
213
+ if (!SLOT_NAME_PATTERN.test(slot)) throw new ExecutorError("E_INVALID_INPUT", "invalid slot name for a slot marker", { slot: String(slot).slice(0, 80) });
214
+ return shapeApi(markersDir).join(markersDir, planId, `${slot}.json`);
215
+ }
216
+
217
+ /**
218
+ * Pure guard, called immediately before every destructive operation on a slot directory: absolute, no "."/".." segment,
219
+ * basename matches SLOT_NAME_PATTERN and equals `slot`, the parent IS `slotsDir` (comparable), and `slotsDir` is not a filesystem root.
220
+ */
221
+ export function assertSafeSlotDir(path: string, slot: string, slotsDir: string, platform: NodeJS.Platform = process.platform): void {
222
+ const api = pathApi(platform);
223
+ const fail = (why: string): never => {
224
+ throw new ExecutorError("E_INVALID_INPUT", `refusing slot dir ${JSON.stringify(path)}: ${why}`, { slot: String(slot).slice(0, 80) });
225
+ };
226
+ if (typeof path !== "string" || path.length === 0 || !api.isAbsolute(path)) fail("not absolute");
227
+ if (typeof slotsDir !== "string" || slotsDir.length === 0 || !api.isAbsolute(slotsDir)) fail("slotsDir is not absolute");
228
+ if (hasDotSegment(path) || hasDotSegment(slotsDir)) fail("dot segment");
229
+ if (typeof slot !== "string" || !SLOT_NAME_PATTERN.test(slot)) fail("name does not match the slot pattern");
230
+ const resolved = api.resolve(path);
231
+ if (api.basename(resolved) !== slot) fail("name differs from the slot");
232
+ const root = api.resolve(slotsDir);
233
+ if (api.parse(root).root === root) fail("slotsDir is a filesystem root");
234
+ if (comparable(api.dirname(resolved), platform) !== comparable(root, platform)) fail("parent is not slotsDir");
235
+ }
236
+
237
+ /** Default `slotsDir`: `<repo drive>:\.omr-slots\<planId>` (D18). A repository without a drive letter has no default. */
238
+ export function defaultSlotsDir(toplevel: string, planId: PlanId): string {
239
+ if (!PLAN_ID_PATTERN.test(planId)) throw new ExecutorError("E_INVALID_INPUT", "invalid plan id", { planId: String(planId).slice(0, 80) });
240
+ const drive = /^([A-Za-z]):[\\/]/.exec(toplevel);
241
+ if (drive === null) {
242
+ throw new ExecutorError("E_INVALID_INPUT", "the repository is not on a drive-letter path; set executor.slotsDir", { toplevel: String(toplevel).slice(0, 200) });
243
+ }
244
+ return `${drive[1]}:\\.omr-slots\\${planId}`;
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------------------------------------------
248
+ // Concurrency, retry, file helpers
249
+ // ---------------------------------------------------------------------------------------------------------------
250
+
251
+ class Mutex {
252
+ private tail: Promise<void> = Promise.resolve();
253
+ /** FIFO. The call is queued synchronously, so the order of `run` calls is the order of execution. */
254
+ run<T>(fn: () => Promise<T>): Promise<T> {
255
+ const result = this.tail.then(fn);
256
+ this.tail = result.then(() => undefined, () => undefined);
257
+ return result;
258
+ }
259
+ }
260
+
261
+ function sleep(clock: Clock, ms: number): Promise<void> {
262
+ return new Promise((resolve) => {
263
+ clock.setTimer(ms, () => resolve());
264
+ });
265
+ }
266
+
267
+ /** The flat retry loop of verify/reference withRetry (private there): `op` must not retry on its own. */
268
+ async function withRetry<T>(clock: Clock, op: () => Promise<T>, deadline = Number.POSITIVE_INFINITY): Promise<T> {
269
+ for (let attempt = 0; ; attempt++) {
270
+ try {
271
+ return await op();
272
+ } catch (error) {
273
+ const code = errorCode(error);
274
+ const delay = CLEANUP_RETRY_BASE_MS * 2 ** attempt;
275
+ if (attempt >= CLEANUP_RETRIES || code === undefined || !TRANSIENT_FS_CODES.has(code)) throw error;
276
+ if (clock.now() + delay >= deadline) throw error;
277
+ await sleep(clock, delay);
278
+ }
279
+ }
280
+ }
281
+
282
+ interface FileCtx {
283
+ fs: FileSystem; clock: Clock; markersDir: string; platform: NodeJS.Platform; logger?: { warn(m: string): void };
284
+ }
285
+
286
+ async function mkdirp(fs: FileSystem, p: string, platform: NodeJS.Platform): Promise<void> {
287
+ const api = pathApi(platform);
288
+ const missing: string[] = [];
289
+ let cur = api.resolve(p);
290
+ for (;;) {
291
+ if (await fs.lstat(cur) !== null) break;
292
+ missing.push(cur);
293
+ const up = api.dirname(cur);
294
+ if (up === cur) break;
295
+ cur = up;
296
+ }
297
+ for (const dir of missing.reverse()) {
298
+ try {
299
+ await fs.mkdir(dir);
300
+ } catch (error) {
301
+ if (errorCode(error) !== "EEXIST") throw error;
302
+ }
303
+ }
304
+ }
305
+
306
+ async function removeFile(x: FileCtx, p: string): Promise<void> {
307
+ try {
308
+ await withRetry(x.clock, () => x.fs.rm(p, { recursive: false }));
309
+ } catch (error) {
310
+ if (errorCode(error) !== "ENOENT") throw error;
311
+ }
312
+ }
313
+
314
+ /** Sidecars beside a marker: `<slot>.produced` (the keep list) and `<slot>.bins` (the executable snapshot, QA-2.4-27). */
315
+ const SIDECAR_EXTENSIONS: readonly string[] = ["produced", "bins"];
316
+
317
+ function sidecarPath(markersDir: string, planId: PlanId, slot: string, extension: string): string {
318
+ return markerPath(markersDir, planId, slot).replace(/\.json$/, `.${extension}`);
319
+ }
320
+
321
+ /** Temp file with fsync, rename, then fsyncDir (memo 3). */
322
+ async function writeMarkerFile(x: FileCtx, rec: SlotRecord): Promise<void> {
323
+ const text = `${JSON.stringify(rec)}\n`;
324
+ if (Buffer.byteLength(text, "utf8") > MARKER_MAX_BYTES) {
325
+ throw new ExecutorError("E_SLOT_BROKEN", `the marker of ${rec.slot} would exceed ${MARKER_MAX_BYTES} bytes`, { slot: rec.slot });
326
+ }
327
+ await writeAtomic(x, markerPath(x.markersDir, rec.planId, rec.slot), text);
328
+ }
329
+
330
+ /** The marker's atomic write for any file in the plan's marker directory. */
331
+ async function writeAtomic(x: FileCtx, final: string, text: string): Promise<void> {
332
+ const api = pathApi(x.platform);
333
+ const dir = api.dirname(final);
334
+ await mkdirp(x.fs, dir, x.platform);
335
+ const tmp = `${final}.${x.clock.randomHex(8)}.tmp`;
336
+ await x.fs.writeText(tmp, text, { exclusive: true, fsync: true });
337
+ try {
338
+ await withRetry(x.clock, () => x.fs.rename(tmp, final));
339
+ } catch (error) {
340
+ try {
341
+ await removeFile(x, tmp);
342
+ } catch (cleanup) {
343
+ x.logger?.warn(`could not remove ${tmp}: ${messageOf(cleanup)}`);
344
+ }
345
+ throw error;
346
+ }
347
+ await x.fs.fsyncDir(dir);
348
+ }
349
+
350
+ type MarkerRead = { ok: true; rec: SlotRecord } | { ok: false; reason: string; missing: boolean };
351
+
352
+ /** Bounded to 64 KiB and checked by `isSlotRecord`. */
353
+ async function readMarkerFile(x: FileCtx, file: string): Promise<MarkerRead> {
354
+ const st = await x.fs.lstat(file);
355
+ if (st === null) return { ok: false, reason: "missing", missing: true };
356
+ if (st.kind !== "file") return { ok: false, reason: `not a regular file (${st.kind})`, missing: false };
357
+ if (st.size > MARKER_MAX_BYTES) return { ok: false, reason: `larger than ${MARKER_MAX_BYTES} bytes`, missing: false };
358
+ let text: string;
359
+ try {
360
+ text = await x.fs.readText(file);
361
+ } catch (error) {
362
+ return { ok: false, reason: `unreadable: ${messageOf(error)}`, missing: errorCode(error) === "ENOENT" };
363
+ }
364
+ if (Buffer.byteLength(text, "utf8") > MARKER_MAX_BYTES) return { ok: false, reason: `larger than ${MARKER_MAX_BYTES} bytes`, missing: false };
365
+ let value: unknown;
366
+ try {
367
+ value = JSON.parse(text);
368
+ } catch (error) {
369
+ return { ok: false, reason: `not valid JSON: ${messageOf(error)}`, missing: false };
370
+ }
371
+ if (!isSlotRecord(value)) return { ok: false, reason: "not a slot record", missing: false };
372
+ return { ok: true, rec: value };
373
+ }
374
+
375
+ /**
376
+ * Writes a sidecar. A sidecar is an optimisation, never a reason to refuse a slot (QA-2.4-31): one over the cap is
377
+ * not written (a stale one is removed) with a warning, and false is returned so the caller keeps its list in memory only.
378
+ */
379
+ async function writeSidecar(x: FileCtx, planId: PlanId, slot: string, extension: string, text: string): Promise<boolean> {
380
+ if (Buffer.byteLength(text, "utf8") > MARKER_MAX_BYTES) {
381
+ x.logger?.warn(`slot ${slot}: the .${extension} file would exceed ${MARKER_MAX_BYTES} bytes; it is not written`);
382
+ await removeSidecar(x, planId, slot, extension);
383
+ return false;
384
+ }
385
+ await writeAtomic(x, sidecarPath(x.markersDir, planId, slot, extension), text);
386
+ return true;
387
+ }
388
+
389
+ /** The text of a sidecar, or null when it is missing, not a regular file, too large or unreadable (a warning for the last three). */
390
+ async function readSidecar(x: FileCtx, planId: PlanId, slot: string, extension: string): Promise<string | null> {
391
+ const file = sidecarPath(x.markersDir, planId, slot, extension);
392
+ const st = await x.fs.lstat(file);
393
+ if (st === null) return null;
394
+ if (st.kind !== "file" || st.size > MARKER_MAX_BYTES) {
395
+ x.logger?.warn(`ignoring ${file}: not a regular file of at most ${MARKER_MAX_BYTES} bytes`);
396
+ return null;
397
+ }
398
+ try {
399
+ return await x.fs.readText(file);
400
+ } catch (error) {
401
+ if (errorCode(error) !== "ENOENT") x.logger?.warn(`could not read ${file}: ${messageOf(error)}`);
402
+ return null;
403
+ }
404
+ }
405
+
406
+ async function removeSidecar(x: FileCtx, planId: PlanId, slot: string, extension: string): Promise<void> {
407
+ await removeFile(x, sidecarPath(x.markersDir, planId, slot, extension));
408
+ }
409
+
410
+ async function readdirOrEmpty(fs: FileSystem, dir: string): Promise<string[]> {
411
+ try {
412
+ return await fs.readdir(dir);
413
+ } catch (error) {
414
+ if (errorCode(error) === "ENOENT") return [];
415
+ throw error;
416
+ }
417
+ }
418
+
419
+ interface PlanMarkers {
420
+ records: Array<{ file: string; rec: SlotRecord }>;
421
+ invalid: Array<{ file: string; reason: string }>;
422
+ }
423
+
424
+ /** The markers of one plan; a record whose file name or plan directory does not match its content is invalid. */
425
+ async function readPlanMarkers(x: FileCtx, planId: PlanId): Promise<PlanMarkers> {
426
+ const api = pathApi(x.platform);
427
+ const dir = api.join(x.markersDir, planId);
428
+ const out: PlanMarkers = { records: [], invalid: [] };
429
+ const st = await x.fs.lstat(dir);
430
+ if (st === null || st.kind !== "dir") return out;
431
+ for (const name of await readdirOrEmpty(x.fs, dir)) {
432
+ if (!name.endsWith(".json")) continue;
433
+ const file = api.join(dir, name);
434
+ const read = await readMarkerFile(x, file);
435
+ if (!read.ok) {
436
+ if (!read.missing) out.invalid.push({ file, reason: read.reason });
437
+ continue;
438
+ }
439
+ if (read.rec.planId !== planId || `${read.rec.slot}.json` !== name) {
440
+ out.invalid.push({ file, reason: "the content does not match the file name or plan directory" });
441
+ continue;
442
+ }
443
+ out.records.push({ file, rec: read.rec });
444
+ }
445
+ return out;
446
+ }
447
+
448
+ async function listPlanDirs(x: FileCtx): Promise<string[]> {
449
+ return (await readdirOrEmpty(x.fs, x.markersDir)).filter((name) => PLAN_ID_PATTERN.test(name)).sort();
450
+ }
451
+
452
+ /** Deletes the marker and, once empty, the plan's marker directory. Never touches slotsDir. */
453
+ async function deleteMarker(x: FileCtx, rec: SlotRecord): Promise<void> {
454
+ const api = pathApi(x.platform);
455
+ const file = markerPath(x.markersDir, rec.planId, rec.slot);
456
+ const dir = api.dirname(file);
457
+ await removeFile(x, file);
458
+ for (const extension of SIDECAR_EXTENSIONS) await removeSidecar(x, rec.planId, rec.slot, extension);
459
+ await x.fs.fsyncDir(dir);
460
+ try {
461
+ if ((await readdirOrEmpty(x.fs, dir)).length === 0) await x.fs.rm(dir, { recursive: false });
462
+ } catch (error) {
463
+ if (errorCode(error) !== "ENOENT") x.logger?.warn(`could not remove the marker directory ${dir}: ${messageOf(error)}`);
464
+ }
465
+ }
466
+
467
+ // ---------------------------------------------------------------------------------------------------------------
468
+ // Link sweep and slot removal (memo 4.5)
469
+ // ---------------------------------------------------------------------------------------------------------------
470
+
471
+ interface SweepCtx { fs: FileSystem; clock: Clock; platform: NodeJS.Platform }
472
+
473
+ /**
474
+ * lstat walk: a symlink or junction is removed with a non-recursive `fs.rm`, never descended into; before each `readdir` the
475
+ * `realpath` of the directory must be inside the `realpath` of the slot. `tracked` links (pre-clean mode) are left alone.
476
+ * Two shapes: the whole slot (`starts` null; `skipDependencyDirs` then skips `node_modules` and `.venv`, which is only safe
477
+ * when the destructive op cannot enter them), or exactly the given slot-relative `starts` (the output of `cleanPreview`),
478
+ * each swept in full with no skipping. `removeRootGitLink` also removes a link at `<root>/.git` (retire only).
479
+ */
480
+ async function sweepLinks(
481
+ x: SweepCtx, root: string,
482
+ o: { skipDependencyDirs: boolean; tracked: ReadonlySet<string> | null; starts?: readonly string[]; removeRootGitLink?: boolean },
483
+ ): Promise<{ removed: string[]; truncated: boolean }> {
484
+ const api = pathApi(x.platform);
485
+ const realRoot = await x.fs.realpath(root);
486
+ const removed: string[] = [];
487
+ let seen = 0;
488
+ const isLink = (kind: string): boolean => kind === "symlink" || kind === "junction";
489
+ const stack: string[] = [];
490
+ if (o.starts === undefined) stack.push("");
491
+ else {
492
+ for (const start of o.starts) {
493
+ const rel = start.replace(/\/+$/, "");
494
+ if (rel === "" || rel.split("/").some((s) => s === "" || s === "." || s === "..")) {
495
+ throw new ExecutorError("E_SLOT_BROKEN", `unsafe clean candidate ${JSON.stringify(start)}`, { start: start.slice(0, 200) });
496
+ }
497
+ // Every parent of a candidate is walked by lstat: a link in the middle is removed, never followed.
498
+ const parts = rel.split("/");
499
+ let cur = "";
500
+ for (let n = 0; n < parts.length; n++) {
501
+ cur = cur === "" ? parts[n] ?? "" : `${cur}/${parts[n] ?? ""}`;
502
+ const path = api.join(root, ...cur.split("/"));
503
+ const st = await x.fs.lstat(path);
504
+ if (st === null) break;
505
+ if (isLink(st.kind)) {
506
+ if (o.tracked === null || !o.tracked.has(cur)) {
507
+ await withRetry(x.clock, () => x.fs.rm(path, { recursive: false }));
508
+ removed.push(cur);
509
+ }
510
+ break;
511
+ }
512
+ if (n === parts.length - 1 && st.kind === "dir") stack.push(cur);
513
+ if (st.kind !== "dir") break;
514
+ }
515
+ }
516
+ }
517
+ for (;;) {
518
+ const rel = stack.pop();
519
+ if (rel === undefined) break;
520
+ const dir = rel === "" ? root : api.join(root, ...rel.split("/"));
521
+ const real = await x.fs.realpath(dir);
522
+ if (!isInsideOrEqual(real, realRoot, x.platform)) {
523
+ throw new ExecutorError("E_SLOT_BROKEN", `${dir} resolves outside its slot`, { dir });
524
+ }
525
+ for (const name of await x.fs.readdir(dir)) {
526
+ seen++;
527
+ if (seen > SLOT_SWEEP_MAX_ENTRIES) return { removed, truncated: true };
528
+ const childRel = rel === "" ? name : `${rel}/${name}`;
529
+ const child = api.join(dir, name);
530
+ const st = await x.fs.lstat(child);
531
+ if (st === null) continue;
532
+ if (rel === "" && name === ".git") {
533
+ if (o.removeRootGitLink === true && isLink(st.kind)) {
534
+ await withRetry(x.clock, () => x.fs.rm(child, { recursive: false }));
535
+ removed.push(childRel);
536
+ }
537
+ continue;
538
+ }
539
+ if (isLink(st.kind)) {
540
+ if (o.tracked !== null && o.tracked.has(childRel)) continue;
541
+ await withRetry(x.clock, () => x.fs.rm(child, { recursive: false }));
542
+ removed.push(childRel);
543
+ } else if (st.kind === "dir") {
544
+ if (o.skipDependencyDirs && o.starts === undefined && DEPENDENCY_DIR_NAMES.has(name)) continue;
545
+ stack.push(childRel);
546
+ }
547
+ }
548
+ }
549
+ return { removed, truncated: false };
550
+ }
551
+
552
+ /** The slot itself must be a real directory whose real path is its parent's real path plus its own name. */
553
+ async function assertRealSlotDir(fs: FileSystem, path: string, platform: NodeJS.Platform): Promise<void> {
554
+ const api = pathApi(platform);
555
+ const st = await fs.lstat(path);
556
+ if (st === null || st.kind !== "dir") {
557
+ throw new ExecutorError("E_SLOT_BROKEN", `${path} is not a real directory (${st === null ? "missing" : st.kind})`, { path });
558
+ }
559
+ const expected = api.join(await fs.realpath(api.dirname(path)), api.basename(path));
560
+ if (comparable(await fs.realpath(path), platform) !== comparable(expected, platform)) {
561
+ throw new ExecutorError("E_SLOT_BROKEN", `${path} resolves through a link`, { path });
562
+ }
563
+ }
564
+
565
+ interface RetireCtx extends FileCtx { git: GitOps; toplevel: string }
566
+
567
+ /**
568
+ * The per-slot GC pipeline (memo 4.5, DV2): marker to `retired`, pointers, guard, link sweep, `fs.rm`, ENOENT check,
569
+ * `git worktree remove` only once the directory is gone, marker deleted. Any failure leaves the marker `retired` and throws.
570
+ * Returns a note when the worktree entry had to be left for manual removal.
571
+ */
572
+ async function retireSlot(x: RetireCtx, rec: SlotRecord, deadline: number, trustedParent: string, saved?: boolean): Promise<string | null> {
573
+ const read = await readMarkerFile(x, markerPath(x.markersDir, rec.planId, rec.slot));
574
+ if (!read.ok) throw new Error(`marker is ${read.reason}`);
575
+ const cur = read.rec;
576
+ if (cur.planId !== rec.planId || cur.slot !== rec.slot || comparable(cur.path, x.platform) !== comparable(rec.path, x.platform)) {
577
+ throw new Error("marker changed while collecting");
578
+ }
579
+ // The parent is the folder the caller trusts for this plan, never one derived from the marker's own path.
580
+ assertSafeSlotDir(cur.path, cur.slot, trustedParent, x.platform);
581
+ if (isInsideOrEqual(cur.path, x.toplevel, x.platform)) throw new Error("slot is inside the repository");
582
+ const parentStat = await x.fs.lstat(trustedParent);
583
+ if (parentStat !== null) {
584
+ if (parentStat.kind !== "dir" || comparable(await x.fs.realpath(trustedParent), x.platform) !== comparable(trustedParent, x.platform)) {
585
+ throw new Error(`${trustedParent} is not the real slots directory (it resolves through a link)`);
586
+ }
587
+ }
588
+ const reason = slotLockReason(cur.planId, cur.slot);
589
+ // GC is not permission to discard work. Check before retiring the marker too: a refusal must keep its owner so
590
+ // a restarted runtime can reconstruct the hold and save it. Invalid metadata is likewise not a clean tree.
591
+ if (saved === false && await x.fs.lstat(cur.path) !== null) {
592
+ try {
593
+ await assertRealSlotDir(x.fs, cur.path, x.platform);
594
+ await x.git.verifySlotPointers(cur.path);
595
+ if ((await x.git.statusPorcelain(cur.path)).length > 0) throw new Error("slot has uncommitted changes; save its work before gc");
596
+ } catch (error) {
597
+ throw new Error(`unsaved work prevents collection: ${messageOf(error)}`);
598
+ }
599
+ }
600
+ await writeMarkerFile(x, { ...cur, state: "retired", owner: null, updatedAt: x.clock.iso() });
601
+
602
+ let st = await x.fs.lstat(cur.path);
603
+ let note: string | null = null;
604
+ if (st !== null) {
605
+ if (st.kind !== "dir") throw new Error(`not a real directory (${st.kind})`);
606
+ // Only a folder git itself lists as locked by this executor for this slot is ever deleted.
607
+ const entry = (await x.git.worktreeList()).find((w) => comparable(w.path, x.platform) === comparable(cur.path, x.platform));
608
+ if (entry === undefined || entry.locked !== reason) {
609
+ throw new Error("git does not list the folder as a worktree locked by the executor for this slot; nothing was deleted");
610
+ }
611
+ try {
612
+ await x.git.verifySlotPointers(cur.path);
613
+ } catch (error) {
614
+ if (saved === false) throw new Error(`cannot collect unsaved work with invalid git pointers: ${messageOf(error)}`);
615
+ note = `git pointers were invalid (${messageOf(error)}); the worktree entry was dropped by path and lock reason`;
616
+ }
617
+ assertSafeSlotDir(cur.path, cur.slot, trustedParent, x.platform);
618
+ if (st.kind !== "dir") throw new Error(`not a real directory (${st.kind})`);
619
+ const sweep = await sweepLinks(x, cur.path, { skipDependencyDirs: false, tracked: null, removeRootGitLink: true });
620
+ if (sweep.truncated) throw new Error(`more than ${SLOT_SWEEP_MAX_ENTRIES} entries; link sweep stopped`);
621
+ const limit = Math.min(x.clock.now() + SLOT_RM_BUDGET_MS, deadline);
622
+ await withRetry(x.clock, () => x.fs.rm(cur.path, { recursive: true }), limit);
623
+ st = await x.fs.lstat(cur.path);
624
+ if (st !== null) throw new Error("directory still present after removal");
625
+ }
626
+ // The folder is gone: drop the admin entry keyed by path and lock reason (a no-op when git no longer lists it).
627
+ await x.git.worktreeRemove(cur.path, reason);
628
+ await deleteMarker(x, cur);
629
+ return note;
630
+ }
631
+
632
+ // ---------------------------------------------------------------------------------------------------------------
633
+ // GC
634
+ // ---------------------------------------------------------------------------------------------------------------
635
+
636
+ /** Standalone, for router_plan action=gc with no plan open; SlotPool.gc delegates to it. `opts.deadline` is an absolute `clock.now()` ms. */
637
+ export async function gcSlots(
638
+ d: GcDeps,
639
+ isFinished: (planId: PlanId) => Promise<boolean | null>,
640
+ opts: { deadline?: number; trustedSlotsDirs?: readonly string[]; savedSlots?: ReadonlySet<string> } = {},
641
+ ): Promise<{ removed: string[]; reported: string[] }> {
642
+ const platform = d.platform ?? process.platform;
643
+ const api = pathApi(platform);
644
+ /** A marker's path is a candidate only when its parent is one of these (d.slotsDir plus the executor's known per-plan dirs). */
645
+ const trusted: readonly string[] = [d.slotsDir, ...(opts.trustedSlotsDirs ?? [])];
646
+ const x: RetireCtx = {
647
+ fs: d.fs, clock: d.clock, markersDir: d.markersDir, platform, git: d.git, toplevel: d.toplevel,
648
+ ...(d.logger === undefined ? {} : { logger: d.logger }),
649
+ };
650
+ const deadline = opts.deadline ?? Number.POSITIVE_INFINITY;
651
+ const removed: string[] = [];
652
+ const reported: string[] = [];
653
+
654
+ const valid: SlotRecord[] = [];
655
+ const trustedFor = new Map<string, string>();
656
+ for (const planId of await listPlanDirs(x)) {
657
+ const plan = await readPlanMarkers(x, planId);
658
+ for (const bad of plan.invalid) reported.push(`${bad.file}: ${bad.reason}`);
659
+ const planTrusted: string[] = [...trusted];
660
+ try {
661
+ planTrusted.push(defaultSlotsDir(d.toplevel, planId));
662
+ } catch {
663
+ // no drive-letter default for this repository: only the explicitly trusted directories apply
664
+ planTrusted.length = trusted.length;
665
+ }
666
+ for (const { file, rec } of plan.records) {
667
+ if (rec.repoKey !== d.repoKey) continue;
668
+ try {
669
+ const parent = api.dirname(rec.path);
670
+ const trustedParent = planTrusted.find((dir) => comparable(dir, platform) === comparable(parent, platform));
671
+ if (trustedParent === undefined) throw new Error("parent is not a known slots directory");
672
+ assertSafeSlotDir(rec.path, rec.slot, trustedParent, platform);
673
+ if (isInsideOrEqual(rec.path, d.toplevel, platform)) throw new Error("slot is inside the repository");
674
+ trustedFor.set(comparable(rec.path, platform), trustedParent);
675
+ } catch (error) {
676
+ reported.push(`${file}: ${messageOf(error)}`);
677
+ continue;
678
+ }
679
+ valid.push(rec);
680
+ }
681
+ }
682
+
683
+ const known = new Set(valid.map((rec) => comparable(rec.path, platform)));
684
+ for (const rec of valid) {
685
+ let finished: boolean | null;
686
+ try {
687
+ finished = await isFinished(rec.planId);
688
+ } catch (error) {
689
+ reported.push(`${rec.path}: could not tell whether plan ${rec.planId} is finished: ${messageOf(error)}`);
690
+ continue;
691
+ }
692
+ if (finished === false) continue;
693
+ if (finished === null && d.clock.now() - timeOf(rec.updatedAt) < UNKNOWN_PLAN_GC_AGE_MS) continue;
694
+ if (d.clock.now() >= deadline) {
695
+ reported.push(`${rec.path}: gc deadline reached`);
696
+ continue;
697
+ }
698
+ try {
699
+ const note = await retireSlot(x, rec, deadline, trustedFor.get(comparable(rec.path, platform)) ?? d.slotsDir, opts.savedSlots?.has(rec.path) === true);
700
+ known.delete(comparable(rec.path, platform));
701
+ removed.push(rec.path);
702
+ if (note !== null) reported.push(`${rec.path}: ${note}`);
703
+ } catch (error) {
704
+ reported.push(`${rec.path}: ${messageOf(error)}`);
705
+ }
706
+ }
707
+
708
+ const scan = new Map<string, string>();
709
+ scan.set(comparable(d.slotsDir, platform), d.slotsDir);
710
+ for (const rec of valid) {
711
+ const dir = api.dirname(rec.path);
712
+ scan.set(comparable(dir, platform), dir);
713
+ }
714
+ for (const dir of scan.values()) {
715
+ for (const name of await readdirOrEmpty(d.fs, dir)) {
716
+ const entry = api.join(dir, name);
717
+ if (!known.has(comparable(entry, platform))) reported.push(`${entry}: unmarked`);
718
+ }
719
+ }
720
+ return { removed, reported };
721
+ }
722
+
723
+ // ---------------------------------------------------------------------------------------------------------------
724
+ // The pool
725
+ // ---------------------------------------------------------------------------------------------------------------
726
+
727
+ type ClaimMode = "same" | "reset" | "create" | "recreate";
728
+
729
+ type StageRecord = SlotRecord & { state: "creating" | "provisioning" | "resetting" };
730
+
731
+ function isStage(rec: SlotRecord): rec is StageRecord {
732
+ return rec.state === "creating" || rec.state === "provisioning" || rec.state === "resetting";
733
+ }
734
+
735
+ interface AcquireSpec {
736
+ kind: SlotRecord["kind"];
737
+ owner: string;
738
+ /** Canonical commit: the base for a task slot, the toplevel HEAD for a special slot (used only to create it). */
739
+ base: string;
740
+ }
741
+
742
+ function keepFor(managers: readonly string[], yarnBerry: boolean): string[] {
743
+ const keep: string[] = [];
744
+ if (managers.some((m) => NODE_MANAGER_NAMES.includes(m))) keep.push("node_modules");
745
+ if (yarnBerry) keep.push("/.yarn", "/.pnp.*");
746
+ if (managers.some((m) => PYTHON_MANAGER_NAMES.includes(m))) keep.push("/.venv");
747
+ return keep;
748
+ }
749
+
750
+ export function createSlotPool(d: SlotPoolDeps): OpenSlotPool {
751
+ const platform = d.platform ?? process.platform;
752
+ const api = pathApi(platform);
753
+ const logger = d.logger;
754
+ const fileCtx: FileCtx = {
755
+ fs: d.fs, clock: d.clock, markersDir: d.markersDir, platform,
756
+ ...(logger === undefined ? {} : { logger }),
757
+ };
758
+ const retireCtx: RetireCtx = { ...fileCtx, git: d.git, toplevel: d.toplevel };
759
+
760
+ const records = new Map<string, SlotRecord>();
761
+ const releaseListeners = new Set<() => void>();
762
+ const corrupt = new Set<string>();
763
+ const poolLock = new Mutex();
764
+ const slotLocks = new Map<string, Mutex>();
765
+ let opened = false;
766
+ /** Set by `close()` and by a gc of this very plan: no new acquire, and in-flight provisioning is aborted. */
767
+ let closed = false;
768
+ const abort = new AbortController();
769
+ /** Paths provisioning produced besides the dependency dirs (for example `*.egg-info`), per slot: kept by every clean. */
770
+ const produced = new Map<string, string[]>();
771
+ /** The executable snapshot of each provisioned slot (path, size, mtime), registered with the slot environment. */
772
+ const binsOf = new Map<string, SlotBin[]>();
773
+
774
+ const taskIdOf = (owner: string | null): string | null => {
775
+ const id = owner?.startsWith(`plan:${d.planId}:`) === true ? owner.slice(`plan:${d.planId}:`.length) : null;
776
+ return isTaskId(id) ? id : null;
777
+ };
778
+ // Lazy, exception-contained copies of existing memory only: no get/list, filesystem or scheduling queries.
779
+ const observe = (action: string, detail: () => ObservationValue = () => null): void => {
780
+ observeSlotPool(d.clock, d.planId, action, () => ({ clockMs: d.clock.now(), maxParallel: d.maxParallel, opened, closed,
781
+ slots: [...records.values()].map(r => ({ slot: r.slot, kind: r.kind, state: r.state, taskId: taskIdOf(r.owner) })),
782
+ corrupt: [...corrupt], detail: detail() }));
783
+ };
784
+
785
+ const slotLock = (slot: string): Mutex => {
786
+ let m = slotLocks.get(slot);
787
+ if (m === undefined) {
788
+ m = new Mutex();
789
+ slotLocks.set(slot, m);
790
+ }
791
+ return m;
792
+ };
793
+ const slotPath = (slot: string): string => api.join(d.slotsDir, slot);
794
+
795
+ const assertOpen = (): void => {
796
+ if (!opened) throw new ExecutorError("E_PLAN_STATE", "the slot pool is not open", { planId: d.planId });
797
+ };
798
+ const assertLive = (): void => {
799
+ assertOpen();
800
+ if (closed) throw new ExecutorError("E_PLAN_STATE", "the slot pool is closed", { planId: d.planId });
801
+ };
802
+ const assertSlot = (slot: string): void => {
803
+ if (typeof slot !== "string" || !SLOT_NAME_PATTERN.test(slot)) {
804
+ throw new ExecutorError("E_INVALID_INPUT", "invalid slot name", { slot: String(slot).slice(0, 80) });
805
+ }
806
+ };
807
+ const need = <T>(value: T | null, what: string, slot: string): T => {
808
+ if (value === null) throw new ExecutorError("E_SLOT_BROKEN", `slot ${slot} has no ${what}`, { slot });
809
+ return value;
810
+ };
811
+
812
+ // ---- records ----------------------------------------------------------------------------------------------
813
+
814
+ /** Write-through: the marker first, then memory. `updatedAt` is stamped here. */
815
+ async function save(rec: SlotRecord): Promise<SlotRecord> {
816
+ const next: SlotRecord = { ...cloneRecord(rec), updatedAt: d.clock.iso() };
817
+ await writeMarkerFile(fileCtx, next);
818
+ records.set(next.slot, next);
819
+ observe("slot-state", () => ({ slot: next.slot }));
820
+ return next;
821
+ }
822
+
823
+ function newRecord(slot: string, owner: string, commit: string): SlotRecord {
824
+ const now = d.clock.iso();
825
+ return {
826
+ schema: 1, slot, path: slotPath(slot), kind: slotKindOf(slot), planId: d.planId, repoKey: d.repoKey,
827
+ state: "creating", owner, commit, managers: [], manifests: {}, createdAt: now, updatedAt: now,
828
+ };
829
+ }
830
+
831
+ function syncEnv(rec: SlotRecord): void {
832
+ if (rec.managers.length > 0) registerSlot({ root: rec.path, managers: rec.managers, bins: binsOf.get(rec.slot) ?? [] });
833
+ else unregisterSlot(rec.path);
834
+ }
835
+
836
+ /** `broken` with owner null; the digests stay the old ones (memo 4.4). A failing marker write still breaks the in-memory slot. */
837
+ async function markBroken(slot: string): Promise<void> {
838
+ const cur = records.get(slot);
839
+ if (cur === undefined) return;
840
+ unregisterSlot(cur.path);
841
+ const broken: SlotRecord = { ...cloneRecord(cur), state: "broken", owner: null };
842
+ try {
843
+ await save(broken);
844
+ } catch (error) {
845
+ logger?.warn(`could not write the broken marker of ${slot}: ${messageOf(error)}`);
846
+ records.set(slot, { ...broken, updatedAt: d.clock.iso() });
847
+ observe("slot-state", () => ({ slot }));
848
+ }
849
+ }
850
+
851
+ async function failStage(slot: string, error: unknown): Promise<ExecutorError> {
852
+ const cur = records.get(slot);
853
+ if (cur !== undefined && STAGE_STATES.includes(cur.state)) await markBroken(slot);
854
+ return wrap(slot, error);
855
+ }
856
+
857
+ /** Installer failures stay `E_PROVISION`; git and fs failures in the slot are `E_SLOT_BROKEN` (the commit was checked up front). */
858
+ function wrap(slot: string, error: unknown): ExecutorError {
859
+ if (error instanceof ExecutorError) {
860
+ if (error.code === "E_GIT") return new ExecutorError("E_SLOT_BROKEN", `slot ${slot}: ${error.message}`, { slot, cause: "E_GIT" });
861
+ return error;
862
+ }
863
+ return new ExecutorError("E_SLOT_BROKEN", `slot ${slot}: ${messageOf(error)}`, { slot, code: errorCode(error) ?? null });
864
+ }
865
+
866
+ function leaseOf(rec: SlotRecord): SlotLease {
867
+ return {
868
+ slot: rec.slot, path: rec.path, planId: rec.planId,
869
+ owner: need(rec.owner, "owner", rec.slot), commit: need(rec.commit, "commit", rec.slot),
870
+ };
871
+ }
872
+
873
+ // ---- tree, detection, provisioning ------------------------------------------------------------------------
874
+
875
+ /** The tracked paths of the index (`ls-files -z`). Phase 3.1 commits before `cleanForChecks`, so index and HEAD agree there. */
876
+ function trackedFiles(path: string): Promise<string[]> {
877
+ return d.git.lsFiles(path);
878
+ }
879
+
880
+ async function detectFor(rec: SlotRecord): Promise<Detection> {
881
+ return d.provisioner.detect(rec.path, await trackedFiles(rec.path));
882
+ }
883
+
884
+ /** What a clean of this slot must keep: the dependency dirs of its managers and what provisioning produced (QA-2.4-14). */
885
+ async function keepList(rec: SlotRecord): Promise<string[]> {
886
+ const berry = rec.managers.includes("yarn") && await d.fs.lstat(api.join(rec.path, ".yarnrc.yml")) !== null;
887
+ return [...keepFor(rec.managers, berry), ...(produced.get(rec.slot) ?? [])];
888
+ }
889
+
890
+ /**
891
+ * Right after an install the slot was clean, so whatever `clean -x` would now delete besides the kept dirs was produced by it.
892
+ * The list is also written beside the marker (`<slot>.produced`, QA-2.4-25), so a later process keeps the same paths.
893
+ */
894
+ async function recordProduced(rec: SlotRecord, managers: readonly string[]): Promise<void> {
895
+ const berry = managers.includes("yarn") && await d.fs.lstat(api.join(rec.path, ".yarnrc.yml")) !== null;
896
+ const listed = await d.git.cleanPreview(rec.path, keepFor(managers, berry));
897
+ const patterns = listed.map((p) => `/${p.replace(/\/+$/, "").replace(/[\\*?[\]]/g, "\\$&")}`);
898
+ // Too large for a sidecar: the patterns stay in memory only (a restart then warns and keeps nothing).
899
+ await writeSidecar(fileCtx, rec.planId, rec.slot, "produced", `${JSON.stringify(patterns)}\n`);
900
+ produced.set(rec.slot, patterns);
901
+ }
902
+
903
+ /** The executables the install left in the slot's tool directories: the only files router_run takes from the slot (QA-2.4-27). */
904
+ async function recordBins(rec: SlotRecord, managers: readonly string[]): Promise<void> {
905
+ const dirs: string[] = [];
906
+ if (managers.some((m) => PYTHON_MANAGER_NAMES.includes(m))) dirs.push(api.join(rec.path, ".venv", platform === "win32" ? "Scripts" : "bin"));
907
+ // router_run only takes .exe/.com on win32, where node_modules\.bin holds none (only .cmd/.ps1 shims): skip it (QA-2.4-31).
908
+ if (platform !== "win32" && managers.some((m) => NODE_MANAGER_NAMES.includes(m))) dirs.push(api.join(rec.path, "node_modules", ".bin"));
909
+ const bins: SlotBin[] = [];
910
+ for (const dir of dirs) {
911
+ for (const name of await readdirOrEmpty(d.fs, dir)) {
912
+ if (platform === "win32" && !/\.(exe|com)$/i.test(name)) continue;
913
+ const file = api.join(dir, name);
914
+ const st = await d.fs.lstat(file);
915
+ if (st !== null && (st.kind === "file" || st.kind === "symlink")) bins.push({ path: file, size: st.size, mtimeMs: st.mtimeMs });
916
+ }
917
+ }
918
+ // Too large for a sidecar: no snapshot at all, so router_run falls back to PATH for this slot.
919
+ if (await writeSidecar(fileCtx, rec.planId, rec.slot, "bins", `${JSON.stringify(bins)}\n`)) binsOf.set(rec.slot, bins);
920
+ else binsOf.delete(rec.slot);
921
+ }
922
+
923
+ /** The slot has no install (no managers, retired, recreated): forget what the previous one produced. */
924
+ async function clearProvisioned(rec: SlotRecord): Promise<void> {
925
+ produced.delete(rec.slot);
926
+ binsOf.delete(rec.slot);
927
+ for (const extension of SIDECAR_EXTENSIONS) await removeSidecar(fileCtx, rec.planId, rec.slot, extension);
928
+ }
929
+
930
+ async function install(rec: SlotRecord, detection: Detection, fresh: boolean): Promise<void> {
931
+ await d.provisioner.provision(rec.path, detection, { fresh, signal: abort.signal });
932
+ await recordProduced(rec, detection.managers);
933
+ await recordBins(rec, detection.managers);
934
+ d.onProvision?.(rec.slot, detection.managers);
935
+ }
936
+
937
+ /** `open()`: the sidecars of a slot that has managers; an unreadable or malformed one is ignored with a warning. */
938
+ async function restoreProvisioned(rec: SlotRecord): Promise<void> {
939
+ if (rec.managers.length === 0) {
940
+ await clearProvisioned(rec);
941
+ return;
942
+ }
943
+ const keep = parseStringArray(await readSidecar(fileCtx, rec.planId, rec.slot, "produced"));
944
+ if (keep === null) logger?.warn(`slot ${rec.slot}: no usable .produced file; build outputs are not kept by a clean`);
945
+ else produced.set(rec.slot, keep);
946
+ const bins = parseBins(await readSidecar(fileCtx, rec.planId, rec.slot, "bins"));
947
+ if (bins === null) logger?.warn(`slot ${rec.slot}: no usable .bins file; router_run falls back to PATH for this slot`);
948
+ else binsOf.set(rec.slot, bins);
949
+ }
950
+
951
+ /** Re-detects and, on drift (memo 4.4), writes `provisioning` and installs. The returned record is not yet saved with the new digests. */
952
+ async function driftProvision(rec: SlotRecord): Promise<{ rec: SlotRecord; drifted: boolean }> {
953
+ const detection = await detectFor(rec);
954
+ if (!needsProvision(rec, detection)) return { rec, drifted: false };
955
+ const prov = await save({ ...rec, state: "provisioning" });
956
+ observe("slot-provision-start", () => ({ slot: rec.slot }));
957
+ try {
958
+ if (detection.managers.length > 0) await install(prov, detection, true);
959
+ else await clearProvisioned(prov);
960
+ observe("slot-provision-end", () => ({ slot: rec.slot, result: "completed" }));
961
+ return { rec: { ...prov, managers: [...detection.managers], manifests: { ...detection.manifests } }, drifted: true };
962
+ } catch (error) {
963
+ observe("slot-provision-end", () => ({ slot: rec.slot, result: "failed" }));
964
+ throw error;
965
+ }
966
+ }
967
+
968
+ async function stageProvision(rec: SlotRecord, fresh: boolean): Promise<SlotRecord> {
969
+ const prov = rec.state === "provisioning" ? rec : await save({ ...rec, state: "provisioning" });
970
+ observe("slot-provision-start", () => ({ slot: rec.slot }));
971
+ try {
972
+ const detection = await detectFor(prov);
973
+ if (detection.managers.length > 0) await install(prov, detection, fresh);
974
+ else await clearProvisioned(prov);
975
+ const done = await save({
976
+ ...prov, managers: [...detection.managers], manifests: { ...detection.manifests },
977
+ state: prov.owner === null ? "ready" : "leased",
978
+ });
979
+ syncEnv(done);
980
+ observe("slot-provision-end", () => ({ slot: rec.slot, result: "completed" }));
981
+ return done;
982
+ } catch (error) {
983
+ observe("slot-provision-end", () => ({ slot: rec.slot, result: "failed" }));
984
+ throw error;
985
+ }
986
+ }
987
+
988
+ // ---- stages -----------------------------------------------------------------------------------------------
989
+
990
+ /** Interrupted `creating` (memo 4.1): pointers fine -> go on; absent or empty -> add again; anything else -> retire and recreate. */
991
+ async function repairCreate(rec: SlotRecord, base: string, reason: string): Promise<void> {
992
+ const st = await d.fs.lstat(rec.path);
993
+ if (st !== null) {
994
+ if (st.kind !== "dir") throw new ExecutorError("E_SLOT_BROKEN", `${rec.path} is not a real directory (${st.kind})`, { slot: rec.slot });
995
+ let pointersOk = false;
996
+ try {
997
+ await d.git.verifySlotPointers(rec.path);
998
+ pointersOk = true;
999
+ } catch (error) {
1000
+ logger?.warn(`slot ${rec.slot} is half created (${messageOf(error)}); recreating it`);
1001
+ }
1002
+ if (pointersOk) {
1003
+ // The checkout of an interrupted `worktree add` may be partial or dirty: bring it to the base commit first.
1004
+ observe("slot-reset-start", () => ({ slot: rec.slot }));
1005
+ try {
1006
+ await resetRoutine(rec);
1007
+ observe("slot-reset-end", () => ({ slot: rec.slot, result: "completed" }));
1008
+ } catch (error) {
1009
+ observe("slot-reset-end", () => ({ slot: rec.slot, result: "failed" }));
1010
+ throw error;
1011
+ }
1012
+ return;
1013
+ }
1014
+ if ((await d.fs.readdir(rec.path)).length === 0) {
1015
+ await withRetry(d.clock, () => d.fs.rm(rec.path, { recursive: true }));
1016
+ } else {
1017
+ await retireSlot(retireCtx, rec, Number.POSITIVE_INFINITY, d.slotsDir);
1018
+ records.delete(rec.slot);
1019
+ observe("slot-state", () => ({ slot: rec.slot }));
1020
+ await clearProvisioned(rec);
1021
+ await save({ ...rec, state: "creating" });
1022
+ }
1023
+ }
1024
+ await d.git.worktreeRemove(rec.path, reason);
1025
+ await d.git.worktreeAdd(rec.path, base, reason);
1026
+ }
1027
+
1028
+ async function stageCreate(rec: SlotRecord, firstRun: boolean): Promise<SlotRecord> {
1029
+ const base = need(rec.commit, "commit", rec.slot);
1030
+ const reason = slotLockReason(rec.planId, rec.slot);
1031
+ if (firstRun) await d.git.worktreeAdd(rec.path, base, reason);
1032
+ else await repairCreate(rec, base, reason);
1033
+ await d.git.verifySlotPointers(rec.path);
1034
+ return stageProvision(rec, !firstRun);
1035
+ }
1036
+
1037
+ /** `reset` routine (memo 4.3): pointers, link sweep, checkout, clean; HEAD and status verified; one retry. */
1038
+ async function resetRoutine(rec: SlotRecord): Promise<void> {
1039
+ const commit = need(rec.commit, "commit", rec.slot);
1040
+ await d.git.verifySlotPointers(rec.path);
1041
+ const attempt = async (): Promise<void> => {
1042
+ await assertRealSlotDir(d.fs, rec.path, platform);
1043
+ const tracked = new Set(await d.git.trackedLinks(rec.path));
1044
+ const ctx = { fs: d.fs, clock: d.clock, platform };
1045
+ // The checkout can only touch tracked paths: the whole-slot sweep (dependency dirs skipped) covers it.
1046
+ const sweep = await sweepLinks(ctx, rec.path, { skipDependencyDirs: true, tracked });
1047
+ if (sweep.truncated) throw new ExecutorError("E_SLOT_BROKEN", `more than ${SLOT_SWEEP_MAX_ENTRIES} entries in ${rec.slot}`, { slot: rec.slot });
1048
+ await d.git.checkoutDetach(rec.path, commit);
1049
+ // The clean is different: sweep exactly what git is about to delete, whatever its depth or name.
1050
+ const keep = await keepList(rec);
1051
+ const doomed = await sweepLinks(ctx, rec.path, { skipDependencyDirs: false, tracked, starts: await d.git.cleanPreview(rec.path, keep) });
1052
+ if (doomed.truncated) throw new ExecutorError("E_SLOT_BROKEN", `more than ${SLOT_SWEEP_MAX_ENTRIES} entries in ${rec.slot}`, { slot: rec.slot });
1053
+ await d.git.cleanTracked(rec.path, keep);
1054
+ const head = await d.git.revParse(rec.path, "HEAD");
1055
+ if (head !== commit) throw new ExecutorError("E_SLOT_BROKEN", `HEAD of ${rec.slot} is ${head}, expected ${commit}`, { slot: rec.slot });
1056
+ const status = await d.git.statusPorcelain(rec.path);
1057
+ if (status.length !== 0) throw new ExecutorError("E_SLOT_BROKEN", `${rec.slot} is not clean after reset`, { slot: rec.slot, entries: status.length });
1058
+ };
1059
+ try {
1060
+ await attempt();
1061
+ } catch (first) {
1062
+ logger?.warn(`reset of ${rec.slot} failed (${messageOf(first)}); retrying`);
1063
+ await sleep(d.clock, RESET_RETRY_DELAY_MS);
1064
+ try {
1065
+ await attempt();
1066
+ } catch (second) {
1067
+ const code = errorCode(second);
1068
+ const transient = code !== undefined && TRANSIENT_FS_CODES.has(code);
1069
+ throw new ExecutorError(
1070
+ "E_SLOT_BROKEN",
1071
+ transient ? `files in ${rec.slot} are held by a running process; stop it and retry` : `reset of ${rec.slot} failed: ${messageOf(second).slice(0, 200)}`,
1072
+ { slot: rec.slot, cause: messageOf(second).slice(0, 300) },
1073
+ );
1074
+ }
1075
+ }
1076
+ }
1077
+
1078
+ async function stageReset(rec: SlotRecord, verifyAfterProvision = false): Promise<{ rec: SlotRecord; provisioned: boolean }> {
1079
+ observe("slot-reset-start", () => ({ slot: rec.slot }));
1080
+ try {
1081
+ await resetRoutine(rec);
1082
+ const drift = await driftProvision(rec);
1083
+ const provisioned = drift.drifted && drift.rec.managers.length > 0;
1084
+ // Public reset is launch's last preparation, including when integration moved after a proven acquisition.
1085
+ // An installer can change HEAD or tracked files: restore and verify once more, without another install.
1086
+ if (verifyAfterProvision && provisioned) await resetRoutine(drift.rec);
1087
+ const done = await save({ ...drift.rec, state: drift.rec.owner === null ? "ready" : "leased" });
1088
+ syncEnv(done);
1089
+ observe("slot-reset-end", () => ({ slot: rec.slot, result: "completed" }));
1090
+ return { rec: done, provisioned };
1091
+ } catch (error) {
1092
+ observe("slot-reset-end", () => ({ slot: rec.slot, result: "failed" }));
1093
+ throw error;
1094
+ }
1095
+ }
1096
+
1097
+ /** Runs the stage the marker is in, from its start (also the repair of an interrupted stage, memo 4.1). */
1098
+ async function driveStage(rec: StageRecord, firstRun: boolean): Promise<SlotRecord> {
1099
+ switch (rec.state) {
1100
+ case "creating":
1101
+ return stageCreate(rec, firstRun);
1102
+ case "provisioning":
1103
+ await d.git.verifySlotPointers(rec.path);
1104
+ return stageProvision(rec, true);
1105
+ case "resetting":
1106
+ return (await stageReset(rec)).rec;
1107
+ }
1108
+ }
1109
+
1110
+ /** The destructive reset must never run for a state that is not a stage (QA-2.4-29): the type says so, this checks it. */
1111
+ function staged(rec: SlotRecord): StageRecord {
1112
+ if (isStage(rec)) return rec;
1113
+ throw new ExecutorError("E_SLOT_BROKEN", `slot ${rec.slot} is ${rec.state}, not in a stage`, { slot: rec.slot, state: rec.state });
1114
+ }
1115
+
1116
+ // ---- acquire ----------------------------------------------------------------------------------------------
1117
+
1118
+ const unavailable = (): ExecutorError => {
1119
+ const live = [...records.values()].filter((r) => r.kind === "task" && r.state !== "retired");
1120
+ return new ExecutorError("E_SLOT_UNAVAILABLE", `all ${d.maxParallel} task slots are in use`, {
1121
+ maxParallel: d.maxParallel,
1122
+ leased: live.map((r) => ({ slot: r.slot, owner: r.owner, state: r.state })),
1123
+ });
1124
+ };
1125
+
1126
+ async function createNewTaskSlot(owner: string, base: string): Promise<{ slot: string; mode: ClaimMode }> {
1127
+ for (let n = 1; n <= MAX_TASK_SLOT_NUMBER; n++) {
1128
+ const slot = `slot-${n}`;
1129
+ if (records.has(slot) || corrupt.has(slot)) continue;
1130
+ if (await d.fs.lstat(slotPath(slot)) !== null) continue;
1131
+ await save(newRecord(slot, owner, base));
1132
+ return { slot, mode: "create" };
1133
+ }
1134
+ throw unavailable();
1135
+ }
1136
+
1137
+ /** Marker I/O only (memo 4.2, DV10); runs under the pool mutex. */
1138
+ async function claimTask(owner: string, base: string): Promise<{ slot: string; mode: ClaimMode }> {
1139
+ const tasks = [...records.values()].filter((r) => r.kind === "task");
1140
+ const mine = tasks.find((r) => r.state !== "retired" && r.owner === owner);
1141
+ if (mine !== undefined) return { slot: mine.slot, mode: "same" };
1142
+ const ready = tasks
1143
+ .filter((r) => r.state === "ready")
1144
+ .sort((a, b) => Number(b.commit === base) - Number(a.commit === base) || timeOf(a.updatedAt) - timeOf(b.updatedAt) || compareSlots(a.slot, b.slot));
1145
+ const pick = ready[0];
1146
+ if (pick !== undefined) {
1147
+ await save({ ...pick, state: "resetting", owner, commit: base });
1148
+ return { slot: pick.slot, mode: "reset" };
1149
+ }
1150
+ const live = tasks.filter((r) => r.state !== "retired");
1151
+ if (live.length < d.maxParallel) return createNewTaskSlot(owner, base);
1152
+ const broken = live
1153
+ .filter((r) => r.state === "broken")
1154
+ .sort((a, b) => timeOf(a.updatedAt) - timeOf(b.updatedAt) || compareSlots(a.slot, b.slot))[0];
1155
+ if (broken !== undefined) {
1156
+ unregisterSlot(broken.path);
1157
+ await save({ ...broken, state: "retired", owner: null });
1158
+ await clearProvisioned(broken);
1159
+ return createNewTaskSlot(owner, base);
1160
+ }
1161
+ throw unavailable();
1162
+ }
1163
+
1164
+ async function claimSpecial(kind: "integration" | "ci", base: string): Promise<{ slot: string; mode: ClaimMode }> {
1165
+ const rec = records.get(kind);
1166
+ if (rec === undefined) {
1167
+ if (corrupt.has(kind)) {
1168
+ throw new ExecutorError("E_SLOT_UNAVAILABLE", `the marker of ${kind} is unreadable; run router_plan action=gc`, { slot: kind });
1169
+ }
1170
+ // A folder with no marker is somebody else's: never adopt it (the task slots check the same in createNewTaskSlot).
1171
+ if (await d.fs.lstat(slotPath(kind)) !== null) {
1172
+ throw new ExecutorError("E_SLOT_UNAVAILABLE", `${slotPath(kind)} exists without a slot marker; run router_plan action=gc or remove it`, { slot: kind });
1173
+ }
1174
+ await save(newRecord(kind, kind, base));
1175
+ return { slot: kind, mode: "create" };
1176
+ }
1177
+ if (rec.state === "broken" || rec.state === "retired") return { slot: kind, mode: "recreate" };
1178
+ if (rec.state === "ready") {
1179
+ await save({ ...rec, state: "resetting", owner: kind });
1180
+ return { slot: kind, mode: "reset" };
1181
+ }
1182
+ return { slot: kind, mode: "same" };
1183
+ }
1184
+
1185
+ /** Under the slot mutex: re-reads the record and does the slow work. */
1186
+ async function work(slot: string, mode: ClaimMode, spec: AcquireSpec): Promise<SlotAcquisition> {
1187
+ const acquired = (record: SlotRecord): SlotLease => {
1188
+ const lease = leaseOf(record);
1189
+ observe("slot-acquire-result", () => ({ slot, kind: spec.kind, taskId: taskIdOf(spec.owner), mode,
1190
+ result: mode === "create" || mode === "recreate" ? "created" : "reused" }));
1191
+ return lease;
1192
+ };
1193
+ let rec = records.get(slot);
1194
+ if (rec === undefined) {
1195
+ observe("slot-acquire-result", () => ({ slot, kind: spec.kind, taskId: taskIdOf(spec.owner), mode, result: "failed" }));
1196
+ throw new ExecutorError("E_SLOT_BROKEN", `slot ${slot} disappeared`, { slot });
1197
+ }
1198
+ try {
1199
+ let firstRun = mode === "create" || mode === "reset";
1200
+ if (mode === "recreate" && (rec.state === "broken" || rec.state === "retired")) {
1201
+ unregisterSlot(rec.path);
1202
+ await retireSlot(retireCtx, rec, Number.POSITIVE_INFINITY, d.slotsDir);
1203
+ records.delete(slot);
1204
+ observe("slot-state", () => ({ slot }));
1205
+ await clearProvisioned(rec);
1206
+ rec = await save(newRecord(slot, spec.owner, spec.base));
1207
+ firstRun = true;
1208
+ } else if (rec.state === "ready") {
1209
+ // Released between the claim and this step: claim it again.
1210
+ rec = await save({ ...rec, state: "resetting", owner: spec.owner, commit: spec.base });
1211
+ firstRun = true;
1212
+ }
1213
+ if (rec.state === "leased") {
1214
+ if (rec.owner !== spec.owner) throw unavailable();
1215
+ return acquired(rec);
1216
+ }
1217
+ if (rec.state === "broken" || rec.state === "retired") {
1218
+ throw new ExecutorError("E_SLOT_BROKEN", `slot ${slot} is ${rec.state}`, { slot, state: rec.state });
1219
+ }
1220
+ if (spec.kind !== "task" && rec.state === "resetting" && firstRun) {
1221
+ // A special slot is leased at its current HEAD; the queue resets it afterwards.
1222
+ rec = await save({ ...rec, commit: await d.git.revParse(rec.path, "HEAD") });
1223
+ }
1224
+ // Only a full reset in this acquisition proves launch cleanliness. Same-owner/recovery and create/recreate
1225
+ // remain unproven, even if their marker already names the requested base.
1226
+ if (mode === "reset" && rec.state === "resetting" && rec.commit === spec.base) {
1227
+ const reset = await stageReset(staged(rec));
1228
+ const lease = acquired(reset.rec);
1229
+ // Install hooks can dirty tracked files or move HEAD after resetRoutine verified them.
1230
+ // Withhold the proof so launch's forced reset restores the requested base in that case.
1231
+ return reset.provisioned ? lease : { ...lease, verifiedResetBase: spec.base };
1232
+ }
1233
+ return acquired(await driveStage(staged(rec), firstRun));
1234
+ } catch (error) {
1235
+ const failed = await failStage(slot, error);
1236
+ observe("slot-acquire-result", () => ({ slot, kind: spec.kind, taskId: taskIdOf(spec.owner), mode,
1237
+ result: errorCode(error) === "E_SLOT_UNAVAILABLE" ? "unavailable" : "failed" }));
1238
+ throw failed;
1239
+ }
1240
+ }
1241
+
1242
+ async function acquireSlot(
1243
+ claim: (base: string) => Promise<{ slot: string; mode: ClaimMode }>, spec: Omit<AcquireSpec, "base">,
1244
+ baseLookup: Promise<string>,
1245
+ ): Promise<SlotAcquisition> {
1246
+ assertLive();
1247
+ observe("slot-acquire-start", () => ({ kind: spec.kind, taskId: taskIdOf(spec.owner) }));
1248
+ const scheduled = await poolLock.run(async () => {
1249
+ try {
1250
+ // Queued on the pool mutex before awaiting this caller's lookup, so lookup timing cannot reorder claims.
1251
+ const base = await baseLookup;
1252
+ const { slot, mode } = await claim(base);
1253
+ observe("slot-claim", () => ({ slot, kind: spec.kind, taskId: taskIdOf(spec.owner), mode }));
1254
+ // Queued on the slot mutex before the pool mutex is released, so nothing runs on this slot ahead of the claim.
1255
+ return { run: slotLock(slot).run(() => work(slot, mode, { ...spec, base })) };
1256
+ } catch (error) {
1257
+ observe("slot-acquire-result", () => ({ slot: null, kind: spec.kind, taskId: taskIdOf(spec.owner), mode: null,
1258
+ result: errorCode(error) === "E_SLOT_UNAVAILABLE" ? "unavailable" : "failed" }));
1259
+ throw error;
1260
+ }
1261
+ });
1262
+ return scheduled.run;
1263
+ }
1264
+
1265
+ // ---- reset, cleanForChecks, release -----------------------------------------------------------------------
1266
+
1267
+ async function reset(slot: string, commit: string): Promise<void> {
1268
+ assertLive();
1269
+ assertSlot(slot);
1270
+ if (typeof commit !== "string" || !GIT_ID_PATTERN.test(commit)) {
1271
+ throw new ExecutorError("E_INVALID_INPUT", "commit must be a full git object id", { commit: String(commit).slice(0, 80) });
1272
+ }
1273
+ const oid = await d.git.revParse(d.toplevel, commit);
1274
+ await slotLock(slot).run(async () => {
1275
+ let rec = records.get(slot);
1276
+ if (rec === undefined) throw new ExecutorError("E_INVALID_INPUT", `unknown slot ${slot}`, { slot });
1277
+ if (rec.state !== "leased" && rec.state !== "resetting" && rec.state !== "creating" && rec.state !== "provisioning") {
1278
+ throw new ExecutorError("E_INVALID_INPUT", `slot ${slot} is ${rec.state}, not leased`, { slot, state: rec.state });
1279
+ }
1280
+ try {
1281
+ if (rec.state === "creating" || rec.state === "provisioning") rec = await driveStage(staged(rec), false);
1282
+ const resetting = await save({ ...rec, state: "resetting", commit: oid });
1283
+ await stageReset(staged(resetting), true);
1284
+ } catch (error) {
1285
+ throw await failStage(slot, error);
1286
+ }
1287
+ });
1288
+ }
1289
+
1290
+ async function noteCommit(slot: string, commit: string): Promise<void> {
1291
+ assertLive();
1292
+ assertSlot(slot);
1293
+ if (typeof commit !== "string" || !GIT_ID_PATTERN.test(commit)) {
1294
+ throw new ExecutorError("E_INVALID_INPUT", "commit must be a full git object id", { commit: String(commit).slice(0, 80) });
1295
+ }
1296
+ await slotLock(slot).run(async () => {
1297
+ const rec = records.get(slot);
1298
+ if (rec === undefined) throw new ExecutorError("E_INVALID_INPUT", `unknown slot ${slot}`, { slot });
1299
+ if (rec.state !== "leased") throw new ExecutorError("E_INVALID_INPUT", `slot ${slot} is ${rec.state}, not leased`, { slot, state: rec.state });
1300
+ await save({ ...rec, commit });
1301
+ });
1302
+ }
1303
+
1304
+ async function cleanForChecks(slot: string): Promise<{ drifted: boolean }> {
1305
+ assertLive();
1306
+ assertSlot(slot);
1307
+ return slotLock(slot).run(async () => {
1308
+ const rec = records.get(slot);
1309
+ if (rec === undefined) throw new ExecutorError("E_INVALID_INPUT", `unknown slot ${slot}`, { slot });
1310
+ if (rec.state !== "leased") throw new ExecutorError("E_INVALID_INPUT", `slot ${slot} is ${rec.state}, not leased`, { slot, state: rec.state });
1311
+ try {
1312
+ await d.git.verifySlotPointers(rec.path);
1313
+ await assertRealSlotDir(d.fs, rec.path, platform);
1314
+ const tracked = new Set(await d.git.trackedLinks(rec.path));
1315
+ const ctx = { fs: d.fs, clock: d.clock, platform };
1316
+ // The restoring checkout can only touch tracked paths: a whole-slot sweep (dependency dirs skipped) covers it.
1317
+ const walk = await sweepLinks(ctx, rec.path, { skipDependencyDirs: true, tracked });
1318
+ if (walk.truncated) throw new ExecutorError("E_SLOT_BROKEN", `more than ${SLOT_SWEEP_MAX_ENTRIES} entries in ${slot}`, { slot });
1319
+ // The agent's files include links anywhere; the clean removes whatever `clean -ffndx -e <keep>` lists, so sweep
1320
+ // exactly that list in full (a `node_modules` below the root is deleted unless excluded with the same anchoring).
1321
+ const keep = await keepList(rec);
1322
+ const sweep = await sweepLinks(ctx, rec.path, { skipDependencyDirs: false, tracked, starts: await d.git.cleanPreview(rec.path, keep) });
1323
+ if (sweep.truncated) throw new ExecutorError("E_SLOT_BROKEN", `more than ${SLOT_SWEEP_MAX_ENTRIES} entries in ${slot}`, { slot });
1324
+ await d.git.cleanForChecks(rec.path, keep);
1325
+ const drift = await driftProvision(rec);
1326
+ if (drift.drifted) syncEnv(await save({ ...drift.rec, state: "leased" }));
1327
+ return { drifted: drift.drifted };
1328
+ } catch (error) {
1329
+ throw await failStage(slot, error);
1330
+ }
1331
+ });
1332
+ }
1333
+
1334
+ async function release(slot: string): Promise<void> {
1335
+ assertOpen();
1336
+ assertSlot(slot);
1337
+ const released = await slotLock(slot).run(async () => {
1338
+ const rec = records.get(slot);
1339
+ observe("slot-release-start", () => ({ slot }));
1340
+ if (rec === undefined || rec.state !== "leased") {
1341
+ observe("slot-release-complete", () => ({ slot, result: "unchanged" }));
1342
+ return false;
1343
+ }
1344
+ try {
1345
+ await save({ ...rec, state: "ready", owner: null });
1346
+ observe("slot-release-complete", () => ({ slot, result: "released" }));
1347
+ return rec.kind === "task";
1348
+ } catch (error) {
1349
+ observe("slot-release-failed", () => ({ slot }));
1350
+ throw error;
1351
+ }
1352
+ });
1353
+ if (released) for (const listener of releaseListeners) {
1354
+ try { listener(); } catch { /* A notification cannot undo a successful durable release. */ }
1355
+ }
1356
+ }
1357
+
1358
+ // ---- open -------------------------------------------------------------------------------------------------
1359
+
1360
+ function validateSlotsDir(): void {
1361
+ const bad = (why: string): never => {
1362
+ throw new ExecutorError("E_INVALID_INPUT", `invalid slotsDir ${JSON.stringify(d.slotsDir)}: ${why}`, { planId: d.planId });
1363
+ };
1364
+ if (typeof d.slotsDir !== "string" || d.slotsDir.length === 0) bad("empty");
1365
+ if (platform === "win32" ? !/^[A-Za-z]:[\\/]/.test(d.slotsDir) : !api.isAbsolute(d.slotsDir)) {
1366
+ bad("not an absolute drive-letter path (UNC paths are not supported)");
1367
+ }
1368
+ if (hasDotSegment(d.slotsDir)) bad("dot segment");
1369
+ const resolved = api.resolve(d.slotsDir);
1370
+ if (api.parse(resolved).root === resolved) bad("is a filesystem root");
1371
+ if (isInsideOrEqual(d.slotsDir, d.toplevel, platform) || isInsideOrEqual(d.toplevel, d.slotsDir, platform)) {
1372
+ bad("overlaps the repository");
1373
+ }
1374
+ if (!Number.isInteger(d.maxParallel) || d.maxParallel < 1) {
1375
+ throw new ExecutorError("E_INVALID_INPUT", "maxParallel must be a positive integer", { maxParallel: String(d.maxParallel) });
1376
+ }
1377
+ }
1378
+
1379
+ async function open(opts: SlotPoolOpenOptions = {}): Promise<void> {
1380
+ if (opened) return;
1381
+ validateSlotsDir();
1382
+ // QA-5.1-22: a gc-only handle (`create: false`) creates no directory; a missing slotsDir holds no slot to check.
1383
+ const create = opts.create !== false;
1384
+ if (create) await mkdirp(d.fs, d.slotsDir, platform);
1385
+ const st = await d.fs.lstat(d.slotsDir);
1386
+ if (st === null ? create : st.kind !== "dir") {
1387
+ throw new ExecutorError("E_SLOT_UNAVAILABLE", `slotsDir ${d.slotsDir} is not a real directory`, { slotsDir: d.slotsDir });
1388
+ }
1389
+ if (st !== null && comparable(await d.fs.realpath(d.slotsDir), platform) !== comparable(d.slotsDir, platform)) {
1390
+ throw new ExecutorError("E_SLOT_UNAVAILABLE", `slotsDir ${d.slotsDir} resolves through a link`, { slotsDir: d.slotsDir });
1391
+ }
1392
+ for (const other of await listPlanDirs(fileCtx)) {
1393
+ if (other === d.planId) continue;
1394
+ for (const { rec } of (await readPlanMarkers(fileCtx, other)).records) {
1395
+ if (isInsideOrEqual(rec.path, d.slotsDir, platform) || isInsideOrEqual(d.slotsDir, rec.path, platform)) {
1396
+ throw new ExecutorError("E_SLOT_UNAVAILABLE", `slotsDir ${d.slotsDir} is claimed by plan ${other} (${rec.slot})`, { planId: other, slot: rec.slot });
1397
+ }
1398
+ }
1399
+ }
1400
+ const own = await readPlanMarkers(fileCtx, d.planId);
1401
+ for (const bad of own.invalid) {
1402
+ logger?.warn(`ignoring slot marker ${bad.file}: ${bad.reason}`);
1403
+ const slot = api.basename(bad.file, ".json");
1404
+ if (SLOT_NAME_PATTERN.test(slot)) corrupt.add(slot);
1405
+ }
1406
+ for (const { file, rec } of own.records) {
1407
+ if (rec.repoKey !== d.repoKey || comparable(rec.path, platform) !== comparable(slotPath(rec.slot), platform)) {
1408
+ logger?.warn(`ignoring slot marker ${file}: it belongs to another repository or slots directory`);
1409
+ corrupt.add(rec.slot);
1410
+ continue;
1411
+ }
1412
+ records.set(rec.slot, rec);
1413
+ // A gc-only handle only collects: no sidecar is rewritten and no slot environment is registered.
1414
+ if (!create) continue;
1415
+ if (rec.state !== "retired") await restoreProvisioned(rec);
1416
+ if (rec.state === "ready" || rec.state === "leased") syncEnv(rec);
1417
+ }
1418
+ opened = true;
1419
+ // A gc-only handle never leases a slot.
1420
+ if (!create) closed = true;
1421
+ observe("slot-pool-open");
1422
+ }
1423
+
1424
+ /**
1425
+ * QA-5.1-22: removes slotsDir (`<root>\<planId>`) when it is a real directory with nothing in it, once a purge's gc left no
1426
+ * slot of the plan. A link, a non-empty or a missing directory is left alone. True when slotsDir is gone.
1427
+ */
1428
+ async function removeEmptyDir(): Promise<boolean> {
1429
+ assertOpen();
1430
+ if (records.size > 0) return false;
1431
+ const st = await d.fs.lstat(d.slotsDir);
1432
+ if (st === null) return true;
1433
+ if (st.kind !== "dir" || (await readdirOrEmpty(d.fs, d.slotsDir)).length > 0) return false;
1434
+ try {
1435
+ await d.fs.rm(d.slotsDir, { recursive: false });
1436
+ return true;
1437
+ } catch (error) {
1438
+ if (errorCode(error) === "ENOENT") return true;
1439
+ logger?.warn(`could not remove the empty slots directory ${d.slotsDir}: ${messageOf(error)}`);
1440
+ return false;
1441
+ }
1442
+ }
1443
+
1444
+ // ---- reads and gc -----------------------------------------------------------------------------------------
1445
+
1446
+ async function list(planId?: PlanId): Promise<SlotRecord[]> {
1447
+ if (planId === undefined || planId === d.planId) {
1448
+ return [...records.values()].sort((a, b) => compareSlots(a.slot, b.slot)).map(cloneRecord);
1449
+ }
1450
+ if (!PLAN_ID_PATTERN.test(planId)) throw new ExecutorError("E_INVALID_INPUT", "invalid plan id", { planId: String(planId).slice(0, 80) });
1451
+ const found = await readPlanMarkers(fileCtx, planId);
1452
+ return found.records.map((r) => r.rec).sort((a, b) => compareSlots(a.slot, b.slot));
1453
+ }
1454
+
1455
+ async function gc(isFinished: (planId: PlanId) => Promise<boolean | null>, opts: { savedSlots?: ReadonlySet<string> } = {}): Promise<{ removed: string[]; reported: string[] }> {
1456
+ assertOpen();
1457
+ // A gc that is about to collect this very plan closes the pool first: no new acquire, and provisioning in flight stops.
1458
+ // The answer is asked once and reused for this plan below (QA-2.4-26): `false` means gcSlots will not touch this plan's slots.
1459
+ let ownAnswer: boolean | null | undefined;
1460
+ try {
1461
+ ownAnswer = await isFinished(d.planId);
1462
+ } catch (error) {
1463
+ logger?.warn(`gc: could not tell whether plan ${d.planId} is finished: ${messageOf(error)}`);
1464
+ }
1465
+ if (ownAnswer === true) close();
1466
+ const asked = (planId: PlanId): Promise<boolean | null> =>
1467
+ planId === d.planId && ownAnswer !== undefined ? Promise.resolve(ownAnswer) : isFinished(planId);
1468
+ return poolLock.run(() => {
1469
+ // Under the mutex of every slot of this plan, so no acquire, reset or clean runs on a slot while it is deleted;
1470
+ // an unfinished plan keeps its slots, so a gc of other plans must not wait for its running work.
1471
+ const mine = ownAnswer === false ? [] : [...records.keys()].sort(compareSlots);
1472
+ const collect = async (): Promise<{ removed: string[]; reported: string[] }> => {
1473
+ const out = await gcSlots({
1474
+ repoKey: d.repoKey, toplevel: d.toplevel, slotsDir: d.slotsDir, markersDir: d.markersDir, executorHome: d.executorHome,
1475
+ git: d.git, fs: d.fs, clock: d.clock, platform, ...(logger === undefined ? {} : { logger }),
1476
+ }, asked, opts);
1477
+ for (const rec of [...records.values()]) {
1478
+ const read = await readMarkerFile(fileCtx, markerPath(d.markersDir, rec.planId, rec.slot));
1479
+ if (read.ok) {
1480
+ records.set(rec.slot, read.rec);
1481
+ observe("slot-state", () => ({ slot: rec.slot }));
1482
+ if (read.rec.state === "retired" || read.rec.state === "broken") unregisterSlot(read.rec.path);
1483
+ } else if (read.missing) {
1484
+ records.delete(rec.slot);
1485
+ observe("slot-state", () => ({ slot: rec.slot }));
1486
+ unregisterSlot(rec.path);
1487
+ produced.delete(rec.slot);
1488
+ binsOf.delete(rec.slot);
1489
+ }
1490
+ }
1491
+ return out;
1492
+ };
1493
+ const nest = (n: number): Promise<{ removed: string[]; reported: string[] }> => {
1494
+ const slot = mine[n];
1495
+ return slot === undefined ? collect() : slotLock(slot).run(() => nest(n + 1));
1496
+ };
1497
+ return nest(0);
1498
+ });
1499
+ }
1500
+
1501
+ /** Refuses new acquires from now on and aborts provisioning in flight; idempotent. */
1502
+ function close(): void {
1503
+ if (closed) return;
1504
+ closed = true;
1505
+ releaseListeners.clear();
1506
+ observe("slot-pool-close");
1507
+ abort.abort();
1508
+ }
1509
+
1510
+ return {
1511
+ open,
1512
+ close,
1513
+ removeEmptyDir,
1514
+ async acquire(planId, owner, baseCommit) {
1515
+ if (planId !== d.planId) throw new ExecutorError("E_INVALID_INPUT", "plan id differs from the pool's plan", { planId: String(planId).slice(0, 80) });
1516
+ if (typeof baseCommit !== "string" || !GIT_ID_PATTERN.test(baseCommit)) {
1517
+ throw new ExecutorError("E_INVALID_INPUT", "baseCommit must be a full git object id", { baseCommit: String(baseCommit).slice(0, 80) });
1518
+ }
1519
+ if (typeof owner !== "string" || !OWNER_PATTERN.test(owner)) {
1520
+ throw new ExecutorError("E_INVALID_INPUT", "owner must be 1-128 printable characters", { length: typeof owner === "string" ? owner.length : -1 });
1521
+ }
1522
+ assertLive();
1523
+ const baseLookup = d.git.revParse(d.toplevel, baseCommit);
1524
+ void baseLookup.catch(() => {}); // A lookup can reject while its claim is still queued.
1525
+ return acquireSlot(base => claimTask(owner, base), { kind: "task", owner }, baseLookup);
1526
+ },
1527
+ async acquireSpecial(planId, kind) {
1528
+ if (planId !== d.planId) throw new ExecutorError("E_INVALID_INPUT", "plan id differs from the pool's plan", { planId: String(planId).slice(0, 80) });
1529
+ if (kind !== "integration" && kind !== "ci") throw new ExecutorError("E_INVALID_INPUT", "kind must be integration or ci", { kind: String(kind).slice(0, 40) });
1530
+ assertLive();
1531
+ const lookup = (head: string | undefined): Promise<string> => {
1532
+ if (typeof head !== "string" || !GIT_ID_PATTERN.test(head)) {
1533
+ throw new ExecutorError("E_INVALID_INPUT", "integration head must be a full git object id", null);
1534
+ }
1535
+ return d.git.revParse(d.toplevel, head);
1536
+ };
1537
+ let baseLookup: Promise<string>;
1538
+ try {
1539
+ const head = d.integrationHead?.();
1540
+ // A synchronous head must start rev-parse synchronously too, just like acquire. Awaiting it here would let
1541
+ // later task lookups start first, although this special slot already reserved the earlier claim position.
1542
+ baseLookup = typeof head === "string" || head === undefined ? lookup(head) : head.then(lookup);
1543
+ } catch (error) {
1544
+ baseLookup = Promise.reject(error);
1545
+ }
1546
+ void baseLookup.catch(() => {}); // A lookup can reject while its claim is still queued.
1547
+ return acquireSlot(base => claimSpecial(kind, base), { kind, owner: kind }, baseLookup);
1548
+ },
1549
+ reset,
1550
+ noteCommit,
1551
+ cleanForChecks,
1552
+ release,
1553
+ onTaskSlotReleased(listener) {
1554
+ releaseListeners.add(listener);
1555
+ return () => { releaseListeners.delete(listener); };
1556
+ },
1557
+ async get(slot) {
1558
+ const rec = records.get(slot);
1559
+ return rec === undefined ? null : cloneRecord(rec);
1560
+ },
1561
+ list,
1562
+ gc,
1563
+ };
1564
+ }