opencode-model-router 2.10.0 → 2.11.0

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 (47) hide show
  1. package/CHANGELOG.md +306 -0
  2. package/README.md +3 -2
  3. package/package.json +8 -1
  4. package/src/compat/background.ts +5 -0
  5. package/src/compat/session-lookup.ts +21 -0
  6. package/src/compat/v2-hooks.ts +256 -88
  7. package/src/compat/v2-observations.ts +1 -0
  8. package/src/compat/v2-vocabulary.ts +14 -0
  9. package/src/executor/create.ts +3 -0
  10. package/src/executor/git.ts +110 -26
  11. package/src/executor/integrate/checks.ts +29 -11
  12. package/src/executor/integrate/queue.ts +95 -13
  13. package/src/executor/ledger.ts +16 -12
  14. package/src/executor/lfs-restore.ts +492 -0
  15. package/src/executor/paths.ts +7 -2
  16. package/src/executor/recovery.ts +2 -1
  17. package/src/executor/runtime.ts +1010 -226
  18. package/src/executor/slots/pool.ts +120 -19
  19. package/src/executor/slots/provision.ts +111 -23
  20. package/src/executor/slots/root.ts +81 -0
  21. package/src/executor/types.ts +28 -2
  22. package/src/executor/unattended.ts +6 -1
  23. package/src/executor/verify-trees.ts +507 -0
  24. package/src/guard/enforce.ts +2 -1
  25. package/src/guard/fingerprint.ts +9 -0
  26. package/src/guard/guards.ts +7 -1
  27. package/src/index.ts +107 -27
  28. package/src/router/answer-dedup.ts +198 -0
  29. package/src/router/common-dir.ts +241 -0
  30. package/src/router/config.ts +71 -12
  31. package/src/router/diff-handles.ts +322 -0
  32. package/src/router/diff-summary.ts +318 -0
  33. package/src/router/git-metadata-guard.ts +144 -7
  34. package/src/router/git-tools.ts +930 -73
  35. package/src/router/role-agents.ts +100 -36
  36. package/src/router/run-summary.ts +253 -0
  37. package/src/router/run-tools.ts +145 -23
  38. package/src/router/sessions.ts +14 -1
  39. package/src/routing/classify/rules.ts +93 -14
  40. package/src/routing/wire/hint.ts +9 -2
  41. package/src/v2.ts +3 -1
  42. package/src/verify/exec.ts +454 -2
  43. package/src/verify/plan-task.ts +86 -26
  44. package/src/verify/runner.ts +14 -6
  45. package/src/verify/tree.ts +5 -1
  46. package/src/verify/types.ts +44 -0
  47. package/src/verify/wiring.ts +87 -10
@@ -15,6 +15,7 @@ import { registerSlot, unregisterSlot } from "./env";
15
15
  import type { SlotBin } from "./env";
16
16
  import { DEPENDENCY_DIRS, SLOT_SWEEP_MAX_ENTRIES, needsProvision } from "./provision";
17
17
  import type { Detection, Provisioner } from "./provision";
18
+ import { defaultSlotsRoot, privateDirProblem } from "./root";
18
19
 
19
20
  export const UNKNOWN_PLAN_GC_AGE_MS = 7 * 24 * 3_600_000;
20
21
  export { SLOT_SWEEP_MAX_ENTRIES }; // one cap, defined next to the provisioner's own sweep
@@ -38,6 +39,10 @@ export interface SlotPoolDeps {
38
39
  /** The ledger's current integration head; required for acquireSpecial, omitted only by task-only/gc handles. */
39
40
  integrationHead?(): string | Promise<string>;
40
41
  platform?: NodeJS.Platform; logger?: { warn(m: string): void };
42
+ /** POSIX: the canonical home directory of the default slots root gc trusts (default: the process's, see slots/root.ts). */
43
+ homedir?: string;
44
+ /** POSIX: the uid the slots directory and its root must belong to (default: `process.getuid()`). */
45
+ uid?: number;
41
46
  onProvision?: (slot: string, managers: readonly string[]) => void; // test and smoke hook
42
47
  }
43
48
 
@@ -199,6 +204,8 @@ export function isSlotRecord(v: unknown): v is SlotRecord {
199
204
  const manifests = v["manifests"];
200
205
  if (!isPlainRecord(manifests)) return false;
201
206
  if (!Object.values(manifests).every((h) => typeof h === "string" && MANIFEST_DIGEST_PATTERN.test(h))) return false;
207
+ const removing = v["removing"];
208
+ if (removing !== undefined && (removing !== true || state !== "retired")) return false;
202
209
  const createdAt = v["createdAt"];
203
210
  const updatedAt = v["updatedAt"];
204
211
  return typeof createdAt === "string" && createdAt.length <= 40 && typeof updatedAt === "string" && updatedAt.length <= 40;
@@ -234,14 +241,14 @@ export function assertSafeSlotDir(path: string, slot: string, slotsDir: string,
234
241
  if (comparable(api.dirname(resolved), platform) !== comparable(root, platform)) fail("parent is not slotsDir");
235
242
  }
236
243
 
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 {
244
+ /**
245
+ * Default `slotsDir`: `<default slots root>\<planId>` (D18, #192): `<repo drive>:\.omr-slots\<planId>` on win32 (a
246
+ * repository without a drive letter has no default), `<real home>/.omr-slots/<planId>` on POSIX ({@link defaultSlotsRoot}).
247
+ */
248
+ export function defaultSlotsDir(toplevel: string, planId: PlanId, opts: { platform?: NodeJS.Platform; homedir?: string } = {}): string {
239
249
  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}`;
250
+ const root = defaultSlotsRoot({ ...opts, toplevel: String(toplevel) });
251
+ return shapeApi(root).join(root, planId);
245
252
  }
246
253
 
247
254
  // ---------------------------------------------------------------------------------------------------------------
@@ -283,7 +290,8 @@ interface FileCtx {
283
290
  fs: FileSystem; clock: Clock; markersDir: string; platform: NodeJS.Platform; logger?: { warn(m: string): void };
284
291
  }
285
292
 
286
- async function mkdirp(fs: FileSystem, p: string, platform: NodeJS.Platform): Promise<void> {
293
+ /** `mode` (POSIX only, #192): the permission bits of every directory created, e.g. 0o700 for the slots directory. */
294
+ async function mkdirp(fs: FileSystem, p: string, platform: NodeJS.Platform, mode?: number): Promise<void> {
287
295
  const api = pathApi(platform);
288
296
  const missing: string[] = [];
289
297
  let cur = api.resolve(p);
@@ -296,7 +304,8 @@ async function mkdirp(fs: FileSystem, p: string, platform: NodeJS.Platform): Pro
296
304
  }
297
305
  for (const dir of missing.reverse()) {
298
306
  try {
299
- await fs.mkdir(dir);
307
+ if (mode === undefined || platform === "win32") await fs.mkdir(dir);
308
+ else await fs.mkdir(dir, { mode });
300
309
  } catch (error) {
301
310
  if (errorCode(error) !== "EEXIST") throw error;
302
311
  }
@@ -586,9 +595,12 @@ async function retireSlot(x: RetireCtx, rec: SlotRecord, deadline: number, trust
586
595
  }
587
596
  }
588
597
  const reason = slotLockReason(cur.planId, cur.slot);
598
+ // #187: an earlier gc passed the check below and began deleting this slot (`removing`); what is left of it (its `.git`
599
+ // link and part of its files already gone) is finished without the check, which it could never pass again.
600
+ const removing = cur.state === "retired" && cur.removing === true;
589
601
  // GC is not permission to discard work. Check before retiring the marker too: a refusal must keep its owner so
590
602
  // 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) {
603
+ if (saved === false && !removing && await x.fs.lstat(cur.path) !== null) {
592
604
  try {
593
605
  await assertRealSlotDir(x.fs, cur.path, x.platform);
594
606
  await x.git.verifySlotPointers(cur.path);
@@ -611,11 +623,13 @@ async function retireSlot(x: RetireCtx, rec: SlotRecord, deadline: number, trust
611
623
  try {
612
624
  await x.git.verifySlotPointers(cur.path);
613
625
  } catch (error) {
614
- if (saved === false) throw new Error(`cannot collect unsaved work with invalid git pointers: ${messageOf(error)}`);
626
+ if (saved === false && !removing) throw new Error(`cannot collect unsaved work with invalid git pointers: ${messageOf(error)}`);
615
627
  note = `git pointers were invalid (${messageOf(error)}); the worktree entry was dropped by path and lock reason`;
616
628
  }
617
629
  assertSafeSlotDir(cur.path, cur.slot, trustedParent, x.platform);
618
630
  if (st.kind !== "dir") throw new Error(`not a real directory (${st.kind})`);
631
+ // #187: from here on the slot is being deleted; the marker says so before the first destructive step.
632
+ if (!removing) await writeMarkerFile(x, { ...cur, state: "retired", owner: null, removing: true, updatedAt: x.clock.iso() });
619
633
  const sweep = await sweepLinks(x, cur.path, { skipDependencyDirs: false, tracked: null, removeRootGitLink: true });
620
634
  if (sweep.truncated) throw new Error(`more than ${SLOT_SWEEP_MAX_ENTRIES} entries; link sweep stopped`);
621
635
  const limit = Math.min(x.clock.now() + SLOT_RM_BUDGET_MS, deadline);
@@ -658,9 +672,9 @@ export async function gcSlots(
658
672
  for (const bad of plan.invalid) reported.push(`${bad.file}: ${bad.reason}`);
659
673
  const planTrusted: string[] = [...trusted];
660
674
  try {
661
- planTrusted.push(defaultSlotsDir(d.toplevel, planId));
675
+ planTrusted.push(defaultSlotsDir(d.toplevel, planId, { platform, ...(d.homedir === undefined ? {} : { homedir: d.homedir }) }));
662
676
  } catch {
663
- // no drive-letter default for this repository: only the explicitly trusted directories apply
677
+ // no default for this repository (win32: no drive letter; POSIX: it holds the home): only the explicitly trusted directories apply
664
678
  planTrusted.length = trusted.length;
665
679
  }
666
680
  for (const { file, rec } of plan.records) {
@@ -1239,16 +1253,73 @@ export function createSlotPool(d: SlotPoolDeps): OpenSlotPool {
1239
1253
  }
1240
1254
  }
1241
1255
 
1256
+ /**
1257
+ * R2-3 (#189): the claim's base lookup, abandoned when the pool closes (rejected as closed) or, Recovery-R1-m1 (#190), when
1258
+ * the claim's own `cancel` aborts (rejected as cancelled); the original error otherwise.
1259
+ */
1260
+ function lookupUntilClosed(baseLookup: Promise<string>, cancel?: AbortSignal): Promise<string> {
1261
+ return new Promise<string>((resolve, reject) => {
1262
+ const signal = abort.signal;
1263
+ const onClose = (): void => {
1264
+ cancel?.removeEventListener("abort", onCancel);
1265
+ reject(new ExecutorError("E_PLAN_STATE", "the slot pool is closed", { planId: d.planId }));
1266
+ };
1267
+ const onCancel = (): void => {
1268
+ signal.removeEventListener("abort", onClose);
1269
+ reject(claimCancelled());
1270
+ };
1271
+ if (signal.aborted) {
1272
+ onClose();
1273
+ return;
1274
+ }
1275
+ if (cancel?.aborted === true) {
1276
+ onCancel();
1277
+ return;
1278
+ }
1279
+ signal.addEventListener("abort", onClose, { once: true });
1280
+ cancel?.addEventListener("abort", onCancel, { once: true });
1281
+ baseLookup.then(
1282
+ (base) => {
1283
+ signal.removeEventListener("abort", onClose);
1284
+ cancel?.removeEventListener("abort", onCancel);
1285
+ resolve(base);
1286
+ },
1287
+ (error: unknown) => {
1288
+ signal.removeEventListener("abort", onClose);
1289
+ cancel?.removeEventListener("abort", onCancel);
1290
+ reject(error);
1291
+ },
1292
+ );
1293
+ });
1294
+ }
1295
+
1296
+ /** Recovery-R1-m1 (#190): the rejection of a claim its caller cancelled while it was still queued. */
1297
+ function claimCancelled(): ExecutorError {
1298
+ return new ExecutorError("E_PLAN_STATE", "the slot claim was cancelled before it started", { planId: d.planId });
1299
+ }
1300
+
1242
1301
  async function acquireSlot(
1243
1302
  claim: (base: string) => Promise<{ slot: string; mode: ClaimMode }>, spec: Omit<AcquireSpec, "base">,
1244
- baseLookup: Promise<string>,
1303
+ baseLookup: Promise<string>, cancel?: AbortSignal,
1245
1304
  ): Promise<SlotAcquisition> {
1246
1305
  assertLive();
1306
+ if (cancel?.aborted === true) throw claimCancelled();
1247
1307
  observe("slot-acquire-start", () => ({ kind: spec.kind, taskId: taskIdOf(spec.owner) }));
1248
- const scheduled = await poolLock.run(async () => {
1308
+ // Recovery-R1-m1 (#190): `cancel` ends only a claim still queued (on the pool mutex or its base lookup). Once the claim
1309
+ // starts (`claiming`), it runs to its end: a slot it claims is leased and returned, never abandoned half-provisioned.
1310
+ const state: { phase: "queued" | "claiming" | "cancelled" } = { phase: "queued" };
1311
+ const cancelled = (): boolean => state.phase === "cancelled";
1312
+ const queued = poolLock.run(async () => {
1249
1313
  try {
1250
1314
  // Queued on the pool mutex before awaiting this caller's lookup, so lookup timing cannot reorder claims.
1251
- const base = await baseLookup;
1315
+ // R2-3 (#189): once the pool closes, no claim waits on its lookup (the head one stops waiting, the queued ones
1316
+ // never start) and none claims a slot.
1317
+ assertLive();
1318
+ if (cancelled()) throw claimCancelled();
1319
+ const base = await lookupUntilClosed(baseLookup, cancel);
1320
+ assertLive();
1321
+ if (cancelled()) throw claimCancelled();
1322
+ state.phase = "claiming";
1252
1323
  const { slot, mode } = await claim(base);
1253
1324
  observe("slot-claim", () => ({ slot, kind: spec.kind, taskId: taskIdOf(spec.owner), mode }));
1254
1325
  // Queued on the slot mutex before the pool mutex is released, so nothing runs on this slot ahead of the claim.
@@ -1259,6 +1330,25 @@ export function createSlotPool(d: SlotPoolDeps): OpenSlotPool {
1259
1330
  throw error;
1260
1331
  }
1261
1332
  });
1333
+ if (cancel === undefined) return (await queued).run;
1334
+ const scheduled = await new Promise<Awaited<typeof queued>>((resolve, reject) => {
1335
+ const onCancel = (): void => {
1336
+ if (state.phase !== "queued") return;
1337
+ state.phase = "cancelled";
1338
+ reject(claimCancelled());
1339
+ };
1340
+ cancel.addEventListener("abort", onCancel, { once: true });
1341
+ queued.then(
1342
+ (value) => {
1343
+ cancel.removeEventListener("abort", onCancel);
1344
+ resolve(value);
1345
+ },
1346
+ (error: unknown) => {
1347
+ cancel.removeEventListener("abort", onCancel);
1348
+ reject(error);
1349
+ },
1350
+ );
1351
+ });
1262
1352
  return scheduled.run;
1263
1353
  }
1264
1354
 
@@ -1381,7 +1471,17 @@ export function createSlotPool(d: SlotPoolDeps): OpenSlotPool {
1381
1471
  validateSlotsDir();
1382
1472
  // QA-5.1-22: a gc-only handle (`create: false`) creates no directory; a missing slotsDir holds no slot to check.
1383
1473
  const create = opts.create !== false;
1384
- if (create) await mkdirp(d.fs, d.slotsDir, platform);
1474
+ // POSIX (#192): mkdirp's 0700 applies only to what it creates. The slots root (the parent) and slotsDir must be ours;
1475
+ // one of ours open to the group or others is made private, while a gc-only handle only checks the owner. The root
1476
+ // is checked before anything is created in it.
1477
+ const ensurePrivate = async (dir: string): Promise<void> => {
1478
+ if (platform === "win32") return;
1479
+ const problem = await privateDirProblem(d.fs, dir, { uid: d.uid ?? process.getuid?.(), makePrivate: create });
1480
+ if (problem !== undefined) throw new ExecutorError("E_SLOT_UNAVAILABLE", `slots directory ${dir} ${problem}`, { slotsDir: dir });
1481
+ };
1482
+ await ensurePrivate(api.dirname(api.resolve(d.slotsDir)));
1483
+ // POSIX (#192): the slots directory and any parent the pool creates (`~/.omr-slots`) are private to the user.
1484
+ if (create) await mkdirp(d.fs, d.slotsDir, platform, 0o700);
1385
1485
  const st = await d.fs.lstat(d.slotsDir);
1386
1486
  if (st === null ? create : st.kind !== "dir") {
1387
1487
  throw new ExecutorError("E_SLOT_UNAVAILABLE", `slotsDir ${d.slotsDir} is not a real directory`, { slotsDir: d.slotsDir });
@@ -1389,6 +1489,7 @@ export function createSlotPool(d: SlotPoolDeps): OpenSlotPool {
1389
1489
  if (st !== null && comparable(await d.fs.realpath(d.slotsDir), platform) !== comparable(d.slotsDir, platform)) {
1390
1490
  throw new ExecutorError("E_SLOT_UNAVAILABLE", `slotsDir ${d.slotsDir} resolves through a link`, { slotsDir: d.slotsDir });
1391
1491
  }
1492
+ if (st !== null) await ensurePrivate(d.slotsDir);
1392
1493
  for (const other of await listPlanDirs(fileCtx)) {
1393
1494
  if (other === d.planId) continue;
1394
1495
  for (const { rec } of (await readPlanMarkers(fileCtx, other)).records) {
@@ -1511,7 +1612,7 @@ export function createSlotPool(d: SlotPoolDeps): OpenSlotPool {
1511
1612
  open,
1512
1613
  close,
1513
1614
  removeEmptyDir,
1514
- async acquire(planId, owner, baseCommit) {
1615
+ async acquire(planId, owner, baseCommit, opts) {
1515
1616
  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
1617
  if (typeof baseCommit !== "string" || !GIT_ID_PATTERN.test(baseCommit)) {
1517
1618
  throw new ExecutorError("E_INVALID_INPUT", "baseCommit must be a full git object id", { baseCommit: String(baseCommit).slice(0, 80) });
@@ -1522,7 +1623,7 @@ export function createSlotPool(d: SlotPoolDeps): OpenSlotPool {
1522
1623
  assertLive();
1523
1624
  const baseLookup = d.git.revParse(d.toplevel, baseCommit);
1524
1625
  void baseLookup.catch(() => {}); // A lookup can reject while its claim is still queued.
1525
- return acquireSlot(base => claimTask(owner, base), { kind: "task", owner }, baseLookup);
1626
+ return acquireSlot(base => claimTask(owner, base), { kind: "task", owner }, baseLookup, opts?.signal);
1526
1627
  },
1527
1628
  async acquireSpecial(planId, kind) {
1528
1629
  if (planId !== d.planId) throw new ExecutorError("E_INVALID_INPUT", "plan id differs from the pool's plan", { planId: String(planId).slice(0, 80) });
@@ -12,6 +12,7 @@ import {
12
12
  type RunHost,
13
13
  } from "../../router/run-tools";
14
14
  import { CLEANUP_RETRIES, CLEANUP_RETRY_BASE_MS, DEPENDENCY_FILES, TRANSIENT_FS_CODES } from "../../verify/reference";
15
+ import { privateDirProblem } from "./root";
15
16
  import {
16
17
  ExecutorError, type Clock, type ExecutorConfig, type FileSystem, type ProcessResult, type SlotRecord, type Spawner,
17
18
  } from "../types";
@@ -229,6 +230,8 @@ export interface ProvisionStep {
229
230
  label: string;
230
231
  /** Run the step only when `command <condition>` (same env and cwd) exits 0. */
231
232
  condition?: string[];
233
+ /** The remedy named when the step fails, instead of the manager's (POSIX venv step, #192). */
234
+ hint?: string;
232
235
  }
233
236
 
234
237
  export interface ProvisionHost {
@@ -237,6 +240,13 @@ export interface ProvisionHost {
237
240
  nodeExecPath?: string;
238
241
  /** workRootGuards(slot): no tool binary may live inside these (G4). */
239
242
  guards: readonly string[];
243
+ /**
244
+ * Test seam for the tool lookups (PATH entries, launchers, corepack): the real path of an existing regular file, or
245
+ * undefined. Default: the host file system (`realFileOrUndefined`).
246
+ */
247
+ realFile?: (path: string) => string | undefined;
248
+ /** POSIX: the uid the manager lock directory must belong to (default: `process.getuid()`). */
249
+ uid?: number;
240
250
  }
241
251
 
242
252
  type Provision = Pick<ExecutorConfig, "provision" | "python">;
@@ -260,10 +270,14 @@ function pathDirs(host: ProvisionHost): string[] {
260
270
  .filter((entry) => entry !== "" && isFullPath(entry, host.platform));
261
271
  }
262
272
 
273
+ function realFileOf(path: string, host: ProvisionHost): string | undefined {
274
+ return (host.realFile ?? realFileOrUndefined)(path);
275
+ }
276
+
263
277
  /** An existing regular file, as found, with the found path and its real path both outside the guards. */
264
278
  function locate(path: string, host: ProvisionHost): string | undefined {
265
279
  if (!isFullPath(path, host.platform)) return undefined;
266
- const real = realFileOrUndefined(path);
280
+ const real = realFileOf(path, host);
267
281
  if (real === undefined) return undefined;
268
282
  const found = api(host.platform).normalize(path);
269
283
  if (firstOutside([found], host.guards) === undefined || firstOutside([real], host.guards) === undefined) return undefined;
@@ -289,12 +303,32 @@ function requireTool(manager: Manager, host: ProvisionHost, hint: string): strin
289
303
  { manager });
290
304
  }
291
305
 
292
- /** A node entry script beside a package manager's launcher, run as `node <entry>`. */
293
- function entryBesideLauncher(launcher: string, entries: readonly string[], host: ProvisionHost): string | undefined {
306
+ /**
307
+ * POSIX (#192): the node script a launcher links to (npm's global layout: `<prefix>/bin/yarn` ->
308
+ * `../lib/node_modules/yarn/bin/yarn.js`), so the step runs `node <script>` with the resolved node instead of the
309
+ * launcher's `#!/usr/bin/env node`. The real path of a `.js`/`.cjs` target, the launcher and the target both outside the
310
+ * guards; undefined on win32 and for any other target (a native binary, a shell script).
311
+ */
312
+ export function linkedNodeScript(launcher: string, host: ProvisionHost): string | undefined {
313
+ if (host.platform === "win32") return undefined;
314
+ const real = realFileOf(launcher, host);
315
+ if (real === undefined || !/\.c?js$/.test(real)) return undefined;
316
+ if (firstOutside([launcher], host.guards) === undefined || firstOutside([real], host.guards) === undefined) return undefined;
317
+ return real;
318
+ }
319
+
320
+ /**
321
+ * A node entry script for a package manager's launcher on PATH, run as `node <entry>`: on POSIX first the script the
322
+ * launcher links to ({@link linkedNodeScript}), then `entries` beside the launcher (the Windows npm global layout:
323
+ * `yarn.cmd` next to `node_modules\yarn\bin\yarn.js`).
324
+ */
325
+ export function entryBesideLauncher(launcher: string, entries: readonly string[], host: ProvisionHost): string | undefined {
294
326
  const p = api(host.platform);
295
327
  for (const dir of pathDirs(host)) {
296
328
  const launchers = host.platform === "win32" ? [`${launcher}.cmd`, `${launcher}.exe`] : [launcher];
297
- if (!launchers.some((name) => realFileOrUndefined(p.join(dir, name)) !== undefined)) continue;
329
+ if (!launchers.some((name) => realFileOf(p.join(dir, name), host) !== undefined)) continue;
330
+ const linked = linkedNodeScript(p.join(dir, launcher), host);
331
+ if (linked !== undefined) return linked;
298
332
  for (const entry of entries) {
299
333
  const found = locate(p.join(dir, entry), host);
300
334
  if (found !== undefined) return found;
@@ -310,9 +344,25 @@ function nodeTools(host: ProvisionHost): NodeTools {
310
344
  return { node: resolving("node executable", () => resolveNodeExecutable(runHost, host.guards)), runHost };
311
345
  }
312
346
 
313
- function corepackEntry(name: string, node: string, host: ProvisionHost): string | undefined {
347
+ /**
348
+ * corepack's `dist/<name>` in the node install: `<node dir>\node_modules\corepack` (Windows). On POSIX (#192) also
349
+ * `<node dir>/../lib/node_modules/corepack`, and both beside the node's real path too (Homebrew, nvm: `bin/node` links
350
+ * into the install), as resolveNpmCli looks for npm-cli.js.
351
+ */
352
+ export function corepackEntry(name: string, node: string, host: ProvisionHost): string | undefined {
314
353
  const p = api(host.platform);
315
- return locate(p.join(p.dirname(node), "node_modules", "corepack", "dist", name), host);
354
+ const dirs = [p.dirname(node)];
355
+ if (host.platform !== "win32") {
356
+ const real = realFileOf(node, host);
357
+ if (real !== undefined && !dirs.includes(p.dirname(real))) dirs.push(p.dirname(real));
358
+ }
359
+ const candidates = dirs.flatMap((dir) => [p.join(dir, "node_modules", "corepack", "dist", name),
360
+ ...(host.platform === "win32" ? [] : [p.join(dir, "..", "lib", "node_modules", "corepack", "dist", name)])]);
361
+ for (const candidate of candidates) {
362
+ const found = locate(candidate, host);
363
+ if (found !== undefined) return found;
364
+ }
365
+ return undefined;
316
366
  }
317
367
 
318
368
  interface Resolved { command: string; prefix: string[] }
@@ -445,13 +495,18 @@ export function planProvision(slot: string, d: Detection, host: ProvisionHost, c
445
495
  "--frozen-lockfile", "--prefer-offline", "--config.confirm-modules-purge=false"];
446
496
  const exe = findExecutable("pnpm", host);
447
497
  if (exe !== undefined) {
448
- steps.push(step("pnpm", exe, args, "pnpm install"));
498
+ // POSIX (#192): an npm-installed pnpm links to pnpm.cjs: run it with the resolved node, not through its shebang.
499
+ const script = linkedNodeScript(exe, host);
500
+ steps.push(script === undefined ? step("pnpm", exe, args, "pnpm install") : step("pnpm", node().node, [script, ...args], "pnpm install"));
449
501
  break;
450
502
  }
451
503
  const entry = entryBesideLauncher("pnpm", [p.join("node_modules", "pnpm", "bin", "pnpm.cjs")], host)
452
504
  ?? corepackEntry("pnpm.js", node().node, host);
453
505
  if (entry === undefined) {
454
- throw fail("pnpm was not found (pnpm.exe on PATH, pnpm.cmd beside node_modules\\pnpm, or corepack in the node install); install pnpm or enable corepack, or set executor.provision", { manager });
506
+ throw fail(host.platform === "win32"
507
+ ? "pnpm was not found (pnpm.exe on PATH, pnpm.cmd beside node_modules\\pnpm, or corepack in the node install); install pnpm or enable corepack, or set executor.provision"
508
+ : "pnpm was not found (pnpm on PATH, or corepack in the node install, as <prefix>/lib/node_modules/corepack); install pnpm or enable corepack, or set executor.provision",
509
+ { manager });
455
510
  }
456
511
  steps.push(step("pnpm", node().node, [entry, ...args], "pnpm install"));
457
512
  break;
@@ -472,7 +527,10 @@ export function planProvision(slot: string, d: Detection, host: ProvisionHost, c
472
527
  }
473
528
  entry ??= corepackEntry("yarn.js", node().node, host);
474
529
  if (entry === undefined) {
475
- throw fail("yarn was not found (yarn.cmd on PATH with its yarn.js, or corepack in the node install); install yarn or enable corepack, or set executor.provision", { manager });
530
+ throw fail(host.platform === "win32"
531
+ ? "yarn was not found (yarn.cmd on PATH with its yarn.js, or corepack in the node install); install yarn or enable corepack, or set executor.provision"
532
+ : "yarn was not found (yarn on PATH linking to its yarn.js, or corepack in the node install, as <prefix>/lib/node_modules/corepack); install yarn or enable corepack, or set executor.provision",
533
+ { manager });
476
534
  }
477
535
  steps.push(step("yarn", node().node, [entry, ...args], "yarn install"));
478
536
  break;
@@ -491,7 +549,8 @@ export function planProvision(slot: string, d: Detection, host: ProvisionHost, c
491
549
  case "pip": {
492
550
  const python = resolvePython(d, config, host);
493
551
  const venv = venvPython(slot, host.platform);
494
- steps.push(step("pip", python.command, [...python.prefix, "-m", "venv", ".venv"], "pip venv"));
552
+ const venvStep = step("pip", python.command, [...python.prefix, "-m", "venv", ".venv"], "pip venv");
553
+ steps.push(host.platform === "win32" ? venvStep : { ...venvStep, hint: pipVenvPosixHint(python.command) });
495
554
  const requirements = ["requirements.txt", "requirements-dev.txt"].filter((file) => file in d.manifests);
496
555
  if (requirements.length > 0) {
497
556
  steps.push(step("pip", venv, ["-m", "pip", "install", "--disable-pip-version-check", "--no-input",
@@ -558,6 +617,14 @@ const HINTS: Readonly<Record<Manager, string>> = {
558
617
  pip: "check requirements*.txt and the Python version, or set executor.python or executor.provision",
559
618
  };
560
619
 
620
+ /**
621
+ * #192: the hint of a failed venv step on POSIX, naming the interpreter that ran it. Most often Debian/Ubuntu's Python
622
+ * without its separately packaged venv module.
623
+ */
624
+ export function pipVenvPosixHint(python: string): string {
625
+ return `${python} -m venv needs the venv module and ensurepip (on Debian or Ubuntu, install the python3-venv package, or pythonX.Y-venv for that version), or set executor.python or executor.provision`;
626
+ }
627
+
561
628
  /** In-process chain per lock path: waiters in this process queue here, so they never poll the file against each other. */
562
629
  const CHAINS = new Map<string, Promise<void>>();
563
630
 
@@ -578,8 +645,11 @@ export function createProvisioner(deps: {
578
645
  if (signal?.aborted) throw fail(`provisioning of ${slot} was aborted`, { slot });
579
646
  };
580
647
 
581
- /** Creates `path` and every missing parent (the FileSystem port's mkdir is not recursive). */
582
- async function ensureDir(path: string): Promise<void> {
648
+ /**
649
+ * Creates `path` and every missing parent (the FileSystem port's mkdir is not recursive). `mode`: the permission bits of
650
+ * the created directories, passed on POSIX only.
651
+ */
652
+ async function ensureDir(path: string, mode?: number): Promise<void> {
583
653
  const missing: string[] = [];
584
654
  let cur = path;
585
655
  for (;;) {
@@ -591,7 +661,8 @@ export function createProvisioner(deps: {
591
661
  }
592
662
  for (const dir of missing.reverse()) {
593
663
  try {
594
- await fs.mkdir(dir);
664
+ if (mode === undefined || host.platform === "win32") await fs.mkdir(dir);
665
+ else await fs.mkdir(dir, { mode });
595
666
  } catch (error) {
596
667
  if (errorCode(error) !== "EEXIST") throw error;
597
668
  }
@@ -650,11 +721,10 @@ export function createProvisioner(deps: {
650
721
  await removeRetrying(target, st.kind === "dir");
651
722
  }
652
723
 
653
- async function freshen(slot: string, d: Detection): Promise<void> {
654
- for (const manager of d.managers) {
655
- const rel = FRESH_REMOVES[manager] ?? (manager === "yarn" && !d.yarnBerry ? "node_modules" : undefined);
656
- if (rel !== undefined) await removeDependencyDir(slot, rel);
657
- }
724
+ /** The fresh removal of one manager's dependency directory (`.venv`, yarn classic's `node_modules`), if it has one. */
725
+ async function freshen(slot: string, d: Detection, manager: Manager): Promise<void> {
726
+ const rel = FRESH_REMOVES[manager] ?? (manager === "yarn" && !d.yarnBerry ? "node_modules" : undefined);
727
+ if (rel !== undefined) await removeDependencyDir(slot, rel);
658
728
  }
659
729
 
660
730
  /** Heartbeat write: tmp + rename, but only while `held()` is true, so a release can never be undone by a late beat. */
@@ -679,7 +749,14 @@ export function createProvisioner(deps: {
679
749
  try {
680
750
  await previous;
681
751
  const deadline = clock.now() + PROVISION_STEP_TIMEOUT_MS;
682
- await ensureDir(p.dirname(lockPath));
752
+ // POSIX (#192): the machine-wide lock directory (`~/.cache/omr-executor/locks`) is private to the user, also when
753
+ // it already existed: another user's is refused, one of ours open to others is made 0700.
754
+ await ensureDir(p.dirname(lockPath), 0o700);
755
+ if (host.platform !== "win32") {
756
+ const lockDir = p.dirname(lockPath);
757
+ const problem = await privateDirProblem(fs, lockDir, { uid: host.uid ?? process.getuid?.(), makePrivate: true });
758
+ if (problem !== undefined) throw fail(`the ${manager} install lock directory ${lockDir} ${problem}`, { manager, slot });
759
+ }
683
760
  const body = await acquireFileLock(manager, slot, lockPath, deadline, signal);
684
761
  let beat: { readonly id: number } | undefined;
685
762
  let stopped = false;
@@ -745,11 +822,15 @@ export function createProvisioner(deps: {
745
822
  }
746
823
  }
747
824
 
825
+ /**
826
+ * R2-pre-1 (#187): only the heartbeat age makes a well-formed lock stale, on every host. A dead owner pid is no proof
827
+ * that its install stopped: the process tree below a killed server outlives it (ADR 0007 C16/O16) and may still write
828
+ * in the slot, so an interrupted provisioning stage reruns only once the dead owner's heartbeat is LOCK_STALE_MS old.
829
+ */
748
830
  const isStale = (text: string | null): boolean => {
749
831
  if (text === null) return false;
750
832
  const body = parseLock(text);
751
833
  if (body === null) return true;
752
- if (body.hostname === spawner.hostname && !spawner.isAlive(body.pid)) return true;
753
834
  return clock.now() - body.heartbeatAt > LOCK_STALE_MS;
754
835
  };
755
836
 
@@ -825,7 +906,8 @@ export function createProvisioner(deps: {
825
906
  const result = await spawner.run(step.command, step.args, { ...common, timeoutMs: step.timeoutMs });
826
907
  if (result.code === 0 && result.signal === null) return;
827
908
  const how = result.code === null ? `signal ${result.signal ?? "unknown"}` : `exit ${result.code}`;
828
- throw fail(`${step.label} failed in ${slot} (${how}): ${tailOf(result)} — ${HINTS[step.manager]}`,
909
+ const hint = step.hint ?? HINTS[step.manager];
910
+ throw fail(`${step.label} failed in ${slot} (${how}): ${tailOf(result)} — ${hint}`,
829
911
  { manager: step.manager, slot, label: step.label });
830
912
  } catch (error) {
831
913
  if (error instanceof ExecutorError) throw error;
@@ -840,11 +922,17 @@ export function createProvisioner(deps: {
840
922
  async provision(slot, d, o) {
841
923
  const steps = planProvision(slot, d, host, config);
842
924
  aborted(slot, o.signal);
843
- if (o.fresh) await freshen(slot, d);
844
925
  for (const manager of d.managers) {
845
926
  const own = steps.filter((s) => s.manager === manager);
846
- if (own.length === 0) continue;
927
+ if (own.length === 0) {
928
+ // No install of this manager runs, here or in an earlier run with this configuration: nothing to wait for.
929
+ if (o.fresh) await freshen(slot, d, manager);
930
+ continue;
931
+ }
932
+ // R2-pre-1 (#187): the fresh removal runs under the manager's install lock too. An interrupted stage reruns fresh,
933
+ // and a dead owner's install may still write in that directory until its lock goes stale.
847
934
  await withManagerLock(manager, slot, o.signal, async () => {
935
+ if (o.fresh) await freshen(slot, d, manager);
848
936
  for (const step of own) await runStep(step, slot, o.signal);
849
937
  });
850
938
  }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * #192: the default root of the executor's slot worktrees (`routing.executor.slotsDir: null`). One rule serves every
3
+ * caller: the pool's per-plan default and its gc trusted list (`defaultSlotsDir`), create.ts (`slotsDirOf`) and the
4
+ * role-agent slots grant.
5
+ *
6
+ * - win32: `<repository drive>:\.omr-slots` (D18). A repository without a drive letter has no default.
7
+ * - POSIX: `<realpathSync.native(os.homedir())>/.omr-slots`. The home is canonical, so the pool's "slotsDir is its own
8
+ * real path" check holds under a linked home (a symlinked `$HOME`, macOS `/var`). A repository that is the home
9
+ * directory, or holds it, would contain that root: refused, set `executor.slotsDir`; so is an unknown toplevel.
10
+ *
11
+ * Without `platform`, a drive-letter toplevel selects the Windows rule and any other the host's (a toplevel is a native
12
+ * real path, so on a real host this is the host's rule).
13
+ */
14
+ import { realpathSync } from "node:fs";
15
+ import { homedir as osHomedir } from "node:os";
16
+ import { posix } from "node:path";
17
+ import { ExecutorError, type FileSystem } from "../types";
18
+
19
+ /** The default root's directory name, under the repository drive (win32) or the home directory (POSIX). */
20
+ export const SLOTS_ROOT_DIRNAME = ".omr-slots";
21
+
22
+ export interface SlotsRootInput {
23
+ readonly platform?: NodeJS.Platform;
24
+ /** POSIX: the home directory, already canonical (default: `realpathSync.native(os.homedir())`). */
25
+ readonly homedir?: string;
26
+ /** The repository's top-level directory; absent when unknown, and then there is no default (either platform). */
27
+ readonly toplevel?: string;
28
+ }
29
+
30
+ function canonicalHome(): string {
31
+ const home = osHomedir();
32
+ try {
33
+ return realpathSync.native(home);
34
+ } catch {
35
+ // Without a real home directory there is nowhere to put the default root.
36
+ throw new ExecutorError("E_INVALID_INPUT", `the home directory ${JSON.stringify(home)} does not resolve; set executor.slotsDir`, { home: home.slice(0, 200) });
37
+ }
38
+ }
39
+
40
+ /** The default slots root for `x.toplevel` (see the module comment). Throws E_INVALID_INPUT when there is none. */
41
+ export function defaultSlotsRoot(x: SlotsRootInput): string {
42
+ const toplevel = x.toplevel ?? "";
43
+ const drive = /^([A-Za-z]):[\\/]/.exec(toplevel);
44
+ const platform = x.platform ?? (drive !== null ? "win32" : process.platform);
45
+ if (platform === "win32") {
46
+ if (drive === null) {
47
+ throw new ExecutorError("E_INVALID_INPUT", "the repository is not on a drive-letter path; set executor.slotsDir", { toplevel: toplevel.slice(0, 200) });
48
+ }
49
+ return `${drive[1]}:\\${SLOTS_ROOT_DIRNAME}`;
50
+ }
51
+ // As on win32: a repository whose toplevel is unknown cannot be checked against the home, so it has no default.
52
+ if (toplevel === "") throw new ExecutorError("E_INVALID_INPUT", "the repository toplevel is unknown; set executor.slotsDir", { toplevel: "" });
53
+ const home = x.homedir ?? canonicalHome();
54
+ const top = posix.resolve(toplevel);
55
+ if (home === top || home.startsWith(top.endsWith("/") ? top : `${top}/`)) {
56
+ throw new ExecutorError("E_INVALID_INPUT",
57
+ `the repository ${top} is or contains the home directory ${home}, which holds the default slots root; set executor.slotsDir`,
58
+ { toplevel: toplevel.slice(0, 200) });
59
+ }
60
+ return posix.join(home, SLOTS_ROOT_DIRNAME);
61
+ }
62
+
63
+ /**
64
+ * #192 (POSIX): why `dir` (a slots directory, its slots root, or the manager lock directory) may not be used, or undefined.
65
+ * It must belong to `uid`; one of ours that the group or others may access is made private (0700) when `makePrivate`
66
+ * (a gc-only handle writes nothing, so it only checks the owner). A missing directory, an unknown uid, a port that
67
+ * reports no owner or mode, or anything but a real directory (a link: the callers' link checks refuse it, and chmod
68
+ * would follow it) is not checked here.
69
+ */
70
+ export async function privateDirProblem(
71
+ fs: Pick<FileSystem, "lstat" | "chmod">, dir: string, o: { readonly uid: number | undefined; readonly makePrivate: boolean },
72
+ ): Promise<string | undefined> {
73
+ if (o.uid === undefined) return undefined;
74
+ const st = await fs.lstat(dir);
75
+ if (st === null || st.kind !== "dir" || st.uid === undefined || st.mode === undefined) return undefined;
76
+ if (st.uid !== o.uid) return `is owned by another user (uid ${st.uid}, not ${o.uid}); use a directory you own`;
77
+ if ((st.mode & 0o077) === 0 || !o.makePrivate) return undefined;
78
+ if (fs.chmod === undefined) return `is accessible to the group or others (mode ${(st.mode & 0o777).toString(8)}) and cannot be made private`;
79
+ await fs.chmod(dir, 0o700);
80
+ return undefined;
81
+ }