@ordewell/core 0.12.3 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3318,6 +3318,10 @@ function exclusionWord(pattern) {
3318
3318
  function isScopePattern(entry) {
3319
3319
  return /^(\/|~|https?:\/\/|web_search:|mcp__|mcp-server:|[A-Za-z]:[\\/])/.test(entry);
3320
3320
  }
3321
+ var backslashed = (scope) => scope.replace(/\//g, "\\");
3322
+ function scopeExclusion(entry) {
3323
+ return /^[A-Za-z]:[\\/]/.test(entry) ? globRegExp(backslashed(entry), "i") : globRegExp(entry);
3324
+ }
3321
3325
  function parseAllowlist(entries) {
3322
3326
  const list2 = { commands: [], commandExclusions: [], tools: [], toolExclusions: [], scopes: [], scopeExclusions: [] };
3323
3327
  for (const raw of entries) {
@@ -3327,7 +3331,8 @@ function parseAllowlist(entries) {
3327
3331
  if (entry.startsWith("mcp:")) {
3328
3332
  (exclude ? list2.toolExclusions : list2.tools).push(globRegExp(entry.slice(4).trim(), "i"));
3329
3333
  } else if (isScopePattern(entry)) {
3330
- (exclude ? list2.scopeExclusions : list2.scopes).push(globRegExp(entry));
3334
+ if (exclude) list2.scopeExclusions.push(scopeExclusion(entry));
3335
+ else list2.scopes.push(globRegExp(entry));
3331
3336
  } else {
3332
3337
  const [binary, ...words] = entry.split(/\s+/);
3333
3338
  (exclude ? list2.commandExclusions : list2.commands).push({ text: raw.trim(), binary, words: words.map(exclude ? exclusionWord : ruleWord) });
@@ -3375,7 +3380,7 @@ function toolAllowed(list2, tool2) {
3375
3380
  }
3376
3381
  function scopeExcluded(list2, scope) {
3377
3382
  const origin = /^(?:curl|wget) (https?:\/\/\S+\/\*)$/.exec(scope)?.[1];
3378
- return list2.scopeExclusions.some((re) => re.test(scope) || origin !== void 0 && re.test(origin));
3383
+ return list2.scopeExclusions.some((re) => re.test(scope) || re.test(backslashed(scope)) || origin !== void 0 && re.test(origin));
3379
3384
  }
3380
3385
  function scopeAllowed(list2, scope) {
3381
3386
  if (scopeExcluded(list2, scope)) return false;
@@ -3749,13 +3754,13 @@ function vetHostUnresolved(host) {
3749
3754
  if (LOCAL_NAMES.has(bare.toLowerCase())) return { ok: false, reason: `local host name ${bare}` };
3750
3755
  return void 0;
3751
3756
  }
3752
- async function vetHost(host, resolve17) {
3757
+ async function vetHost(host, resolve18) {
3753
3758
  const settled = vetHostUnresolved(host);
3754
3759
  if (settled) return settled;
3755
3760
  const bare = stripBrackets(host);
3756
3761
  let addresses;
3757
3762
  try {
3758
- addresses = await resolve17(bare);
3763
+ addresses = await resolve18(bare);
3759
3764
  } catch {
3760
3765
  return { ok: false, reason: `${bare} did not resolve` };
3761
3766
  }
@@ -3766,16 +3771,16 @@ async function vetHost(host, resolve17) {
3766
3771
  }
3767
3772
  return { ok: true, addresses };
3768
3773
  }
3769
- async function vetEgress(host, port, resolve17 = resolveAll) {
3770
- return vetEgressUnresolved(host, port) ?? vetHost(host, resolve17);
3774
+ async function vetEgress(host, port, resolve18 = resolveAll) {
3775
+ return vetEgressUnresolved(host, port) ?? vetHost(host, resolve18);
3771
3776
  }
3772
3777
  function vetEgressUnresolved(host, port) {
3773
3778
  if (!ALLOWED_PORTS.has(port)) return { ok: false, reason: `port ${port} is not 80 or 443` };
3774
3779
  return vetHostUnresolved(host);
3775
3780
  }
3776
- function guardedLookup(resolve17 = resolveAll) {
3781
+ function guardedLookup(resolve18 = resolveAll) {
3777
3782
  return (hostname, options, callback) => {
3778
- void vetHost(hostname, resolve17).then((check2) => {
3783
+ void vetHost(hostname, resolve18).then((check2) => {
3779
3784
  if (!check2.ok) {
3780
3785
  callback(Object.assign(new Error(`blocked host: ${check2.reason}`), { code: "EBLOCKEDHOST" }), []);
3781
3786
  return;
@@ -4983,14 +4988,14 @@ function keptEnv(invocation, profile) {
4983
4988
  return profile.inheritEnv === void 0 ? invocation.env : Object.fromEntries(profile.inheritEnv.flatMap((name) => invocation.env[name] === void 0 ? [] : [[name, invocation.env[name]]]));
4984
4989
  }
4985
4990
  var PROBE_TIMEOUT_MS = 1e4;
4986
- var execProbe = (file, args, env) => new Promise((resolve17) => {
4991
+ var execProbe = (file, args, env) => new Promise((resolve18) => {
4987
4992
  try {
4988
4993
  execFile(file, args, { env, timeout: PROBE_TIMEOUT_MS, encoding: "utf8" }, (err, stdout, stderr) => {
4989
4994
  const code = !err ? 0 : typeof err.code === "number" ? err.code : null;
4990
- resolve17({ code, output: `${stdout ?? ""}${stderr ?? ""}`.trim() || (err?.message ?? "") });
4995
+ resolve18({ code, output: `${stdout ?? ""}${stderr ?? ""}`.trim() || (err?.message ?? "") });
4991
4996
  });
4992
4997
  } catch (err) {
4993
- resolve17({ code: null, output: err instanceof Error ? err.message : String(err) });
4998
+ resolve18({ code: null, output: err instanceof Error ? err.message : String(err) });
4994
4999
  }
4995
5000
  });
4996
5001
  async function probeByRunning(backend, profile, exec5) {
@@ -5448,12 +5453,12 @@ function killTree(proc, deps = {}) {
5448
5453
  if (typeof proc.pid !== "number") return;
5449
5454
  const pid = proc.pid;
5450
5455
  const run = deps.execFileImpl ?? defaultExecFile;
5451
- run("taskkill", ["/pid", String(pid), "/T"], () => {
5456
+ const force = () => run("taskkill", ["/pid", String(pid), "/T", "/F"], () => {
5452
5457
  });
5453
- const hardKill = setTimeoutImpl(() => {
5454
- run("taskkill", ["/pid", String(pid), "/T", "/F"], () => {
5455
- });
5456
- }, HARD_KILL_DELAY_MS);
5458
+ run("taskkill", ["/pid", String(pid), "/T"], (err) => {
5459
+ if (err && !hasExited(proc)) force();
5460
+ });
5461
+ const hardKill = setTimeoutImpl(force, HARD_KILL_DELAY_MS);
5457
5462
  hardKill.unref?.();
5458
5463
  proc.once("exit", () => clearTimeoutImpl(hardKill));
5459
5464
  return;
@@ -5777,8 +5782,8 @@ function createScratch() {
5777
5782
  return dir;
5778
5783
  }
5779
5784
  var PlannerShellSandbox = class _PlannerShellSandbox {
5780
- constructor(resolve17 = () => resolvePlannerSandbox()) {
5781
- this.resolve = resolve17;
5785
+ constructor(resolve18 = () => resolvePlannerSandbox()) {
5786
+ this.resolve = resolve18;
5782
5787
  }
5783
5788
  resolve;
5784
5789
  scratch = /* @__PURE__ */ new Map();
@@ -6931,33 +6936,33 @@ function grepOptions(args) {
6931
6936
  };
6932
6937
  }
6933
6938
  var STOPPED_TOOL_RESULT = "Stopped by the user \u2014 this call was not executed, and no further tool calls will run this turn.";
6934
- async function executeTool(name, args, fs28, fetcher, signal) {
6935
- const outcome = await runTool(name, args, fs28, fetcher, signal);
6939
+ async function executeTool(name, args, fs29, fetcher, signal) {
6940
+ const outcome = await runTool(name, args, fs29, fetcher, signal);
6936
6941
  return { ...outcome, output: redactSecrets(outcome.output) };
6937
6942
  }
6938
- async function runTool(name, args, fs28, fetcher, signal) {
6943
+ async function runTool(name, args, fs29, fetcher, signal) {
6939
6944
  if (signal?.aborted) return { success: false, output: STOPPED_TOOL_RESULT, truncated: false };
6940
6945
  switch (name) {
6941
6946
  case "read_file": {
6942
6947
  const offset = num(args.offset);
6943
6948
  const limit = num(args.limit);
6944
6949
  const maxBytes = num(args.maxBytes);
6945
- return fs28.readFile(String(args.path ?? ""), { offset, limit, maxBytes });
6950
+ return fs29.readFile(String(args.path ?? ""), { offset, limit, maxBytes });
6946
6951
  }
6947
6952
  case "read_files": {
6948
6953
  const paths = Array.isArray(args.paths) ? args.paths.map(String) : [];
6949
- return fs28.readFiles(paths);
6954
+ return fs29.readFiles(paths);
6950
6955
  }
6951
6956
  case "glob":
6952
- return fs28.glob(String(args.pattern ?? ""), { path: str(args.path), headLimit: num(args.head_limit ?? args.headLimit) });
6957
+ return fs29.glob(String(args.pattern ?? ""), { path: str(args.path), headLimit: num(args.head_limit ?? args.headLimit) });
6953
6958
  case "grep":
6954
- return fs28.grep(String(args.pattern ?? ""), grepOptions(args));
6959
+ return fs29.grep(String(args.pattern ?? ""), grepOptions(args));
6955
6960
  case "find_symbol":
6956
- return fs28.findSymbol(String(args.symbol ?? ""), { language: str(args.language), path: str(args.path) });
6961
+ return fs29.findSymbol(String(args.symbol ?? ""), { language: str(args.language), path: str(args.path) });
6957
6962
  case "list_dir":
6958
- return fs28.listDir(String(args.path ?? ""), num(args.depth));
6963
+ return fs29.listDir(String(args.path ?? ""), num(args.depth));
6959
6964
  case "bash":
6960
- return args.sealed === true ? fs28.bash(String(args.command ?? ""), signal, { sealed: true }) : fs28.bash(String(args.command ?? ""), signal);
6965
+ return args.sealed === true ? fs29.bash(String(args.command ?? ""), signal, { sealed: true }) : fs29.bash(String(args.command ?? ""), signal);
6961
6966
  case "fetch": {
6962
6967
  if (!fetcher) return { success: false, output: "Web fetching is not available in this environment.", truncated: false };
6963
6968
  return fetcher.fetch(String(args.url ?? ""));
@@ -7729,7 +7734,7 @@ function decodedBody(res) {
7729
7734
  return decoder;
7730
7735
  }
7731
7736
  function pinnedTransport(lookup2) {
7732
- return (url, init) => new Promise((resolve17, reject) => {
7737
+ return (url, init) => new Promise((resolve18, reject) => {
7733
7738
  const target = new URL(url);
7734
7739
  const client = target.protocol === "https:" ? https : http;
7735
7740
  const req = client.request(
@@ -7750,7 +7755,7 @@ function pinnedTransport(lookup2) {
7750
7755
  (res) => {
7751
7756
  res.on("error", () => void 0);
7752
7757
  const body = decodedBody(res);
7753
- resolve17({
7758
+ resolve18({
7754
7759
  ok: res.statusCode !== void 0 && res.statusCode >= 200 && res.statusCode < 300,
7755
7760
  status: res.statusCode ?? 0,
7756
7761
  headers: headerGetter(res),
@@ -8093,7 +8098,7 @@ var PendingApprovals = class {
8093
8098
  return Promise.resolve(refused4);
8094
8099
  }
8095
8100
  const pending = { id: id2, request, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
8096
- return new Promise((resolve17) => {
8101
+ return new Promise((resolve18) => {
8097
8102
  const settle = (decision) => {
8098
8103
  const entry = this.entries.get(id2);
8099
8104
  if (!entry) return;
@@ -8101,7 +8106,7 @@ var PendingApprovals = class {
8101
8106
  this.entries.delete(id2);
8102
8107
  options.onDecision?.(decision);
8103
8108
  this.opts.onSettled?.(id2, isGranted(decision), { request, decision });
8104
- resolve17(decision);
8109
+ resolve18(decision);
8105
8110
  };
8106
8111
  let timer = null;
8107
8112
  if (!options.noTimeout) {
@@ -8245,16 +8250,35 @@ function grepRegexFromProbe(exitCode) {
8245
8250
  return exitCode === 0 || exitCode === 1 ? "pcre" : "ere";
8246
8251
  }
8247
8252
  function toPosixClasses(pattern) {
8253
+ const converted = convertForEre(pattern, true);
8254
+ return converted ?? convertForEre(pattern, false);
8255
+ }
8256
+ var BACKREFERENCE = /\0([1-9])\0/g;
8257
+ function convertForEre(pattern, plainGroups) {
8248
8258
  const CLASS_ESCAPES = { s: "[:space:]", w: "[:alnum:]_", d: "[:digit:]", t: " " };
8259
+ const groupOf = [];
8260
+ let groups = 0;
8261
+ let captures = 0;
8249
8262
  let out = "";
8250
8263
  let i = 0;
8251
8264
  while (i < pattern.length) {
8252
8265
  const c = pattern[i];
8253
8266
  if (c === "\\") {
8254
- out += pattern.slice(i, i + 2);
8267
+ const next = pattern[i + 1] ?? "";
8268
+ out += /[1-9]/.test(next) ? `\0${next}\0` : pattern.slice(i, i + 2);
8255
8269
  i += 2;
8256
8270
  continue;
8257
8271
  }
8272
+ if (c === "(") {
8273
+ groups++;
8274
+ if (plainGroups && pattern.startsWith("(?:", i)) {
8275
+ out += "(";
8276
+ i += 3;
8277
+ continue;
8278
+ }
8279
+ const named3 = /^\(\?(?:P?<(?![=!])|')/.test(pattern.slice(i, i + 4));
8280
+ if (pattern[i + 1] !== "?" || named3) groupOf[++captures] = groups;
8281
+ }
8258
8282
  if (c !== "[") {
8259
8283
  out += c;
8260
8284
  i++;
@@ -8306,7 +8330,13 @@ function toPosixClasses(pattern) {
8306
8330
  }
8307
8331
  out += `[${negate ? "^" : ""}${closeBracket ? "]" : ""}${body}${openBracket ? "[" : ""}${dash ? "-" : ""}]`;
8308
8332
  }
8309
- return out;
8333
+ let representable = true;
8334
+ const renumbered2 = out.replace(BACKREFERENCE, (_, n) => {
8335
+ const group = plainGroups ? groupOf[Number(n)] ?? Number(n) : Number(n);
8336
+ if (group > 9) representable = false;
8337
+ return `\\${group}`;
8338
+ });
8339
+ return representable ? renumbered2 : null;
8310
8340
  }
8311
8341
  function buildFallbackGrepArgs(pattern, opts, root, regex = "pcre") {
8312
8342
  const args = ["-r", "-n"];
@@ -8342,7 +8372,7 @@ function filterFallbackByAnchoredInclude(stdout, include, anchor, outputMode) {
8342
8372
  if (!line) return false;
8343
8373
  const reportedPath = extractFallbackGrepPath(line, outputMode);
8344
8374
  const relPath = path11.isAbsolute(reportedPath) ? path11.relative(anchor, reportedPath) : reportedPath;
8345
- return matchesAnchoredGlob(relPath, include);
8375
+ return matchesAnchoredGlob(relPath.split(path11.sep).join("/"), include);
8346
8376
  }).join("\n");
8347
8377
  }
8348
8378
  function applyHeadLimit(stdout, headLimit) {
@@ -8351,9 +8381,14 @@ function applyHeadLimit(stdout, headLimit) {
8351
8381
  }
8352
8382
  function formatSearchOutput(capped, root, opts) {
8353
8383
  if (capped.rows.length === 0) return opts.emptyMessage;
8354
- const sep14 = opts.sep ?? path11.sep;
8355
- const prefix = root === sep14 || root.endsWith(sep14) ? root : `${root}${sep14}`;
8356
- const body = prefix === sep14 ? capped.rows.join("\n") : capped.rows.map((row) => row.startsWith(prefix) ? row.slice(prefix.length) : row).join("\n");
8384
+ const sep13 = opts.sep ?? path11.sep;
8385
+ const prefix = root === sep13 || root.endsWith(sep13) ? root : `${root}${sep13}`;
8386
+ const prefixes = sep13 === "\\" ? [prefix, `${prefix.slice(0, -1)}/`] : [prefix];
8387
+ const strip = (row) => {
8388
+ const found = prefixes.find((p) => row.startsWith(p));
8389
+ return found ? row.slice(found.length) : row;
8390
+ };
8391
+ const body = prefix === sep13 ? capped.rows.join("\n") : capped.rows.map(strip).join("\n");
8357
8392
  if (!capped.truncated) return body;
8358
8393
  const hint = opts.hint ? ` ${opts.hint}` : "";
8359
8394
  return `${body}
@@ -8471,9 +8506,9 @@ function claudeManagedSettingsDir(platform = process.platform) {
8471
8506
  }
8472
8507
  function readClaudeSettingsModels(files, platform = process.platform) {
8473
8508
  const managed = claudeManagedSettingsDir(platform);
8474
- const join51 = platform === "win32" ? path12.win32.join : path12.posix.join;
8475
- const dropIns = files.list(join51(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => join51(managed, "managed-settings.d", name));
8476
- const ranked = [...dropIns.reverse(), join51(managed, "managed-settings.json"), join51(claudeConfigDir(files.env), "settings.json")];
8509
+ const join50 = platform === "win32" ? path12.win32.join : path12.posix.join;
8510
+ const dropIns = files.list(join50(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => join50(managed, "managed-settings.d", name));
8511
+ const ranked = [...dropIns.reverse(), join50(managed, "managed-settings.json"), join50(claudeConfigDir(files.env), "settings.json")];
8477
8512
  for (const file of ranked) {
8478
8513
  const content = files.read(file);
8479
8514
  const lineup = content === null ? null : parseClaudeSettingsModels(content);
@@ -9972,7 +10007,7 @@ var OrdewellMcpServer = class {
9972
10007
  this.boundHost = void 0;
9973
10008
  if (!http2) return;
9974
10009
  http2.closeAllConnections();
9975
- await new Promise((resolve17) => http2.close(() => resolve17()));
10010
+ await new Promise((resolve18) => http2.close(() => resolve18()));
9976
10011
  }
9977
10012
  async issue(grant) {
9978
10013
  const url = await this.start();
@@ -9981,7 +10016,7 @@ var OrdewellMcpServer = class {
9981
10016
  return { url, token };
9982
10017
  }
9983
10018
  start() {
9984
- this.listening ??= new Promise((resolve17, reject) => {
10019
+ this.listening ??= new Promise((resolve18, reject) => {
9985
10020
  const http2 = createServer((req, res) => {
9986
10021
  this.handle(req, res).catch(() => {
9987
10022
  if (!res.headersSent) reply(res, 500, "Internal error");
@@ -10000,7 +10035,7 @@ var OrdewellMcpServer = class {
10000
10035
  }
10001
10036
  this.boundHost = `127.0.0.1:${address.port}`;
10002
10037
  this.boundUrl = `http://${this.boundHost}${ORDEWELL_MCP_PATH}`;
10003
- resolve17(this.boundUrl);
10038
+ resolve18(this.boundUrl);
10004
10039
  });
10005
10040
  http2.unref();
10006
10041
  this.http = http2;
@@ -10823,28 +10858,28 @@ function posixBinDirs() {
10823
10858
  ];
10824
10859
  }
10825
10860
  function windowsBinDirs(env, home) {
10826
- const join51 = (...parts) => path14.win32.join(...parts);
10827
- const under = (base, ...parts) => base ? [join51(base, ...parts)] : [];
10861
+ const join50 = (...parts) => path14.win32.join(...parts);
10862
+ const under = (base, ...parts) => base ? [join50(base, ...parts)] : [];
10828
10863
  const appData = env.APPDATA;
10829
10864
  const localAppData = env.LOCALAPPDATA;
10830
10865
  const programData = env.ProgramData;
10831
10866
  return [
10832
10867
  // Native per-user installers, PowerShell-driven and otherwise.
10833
- join51(home, ".local", "bin"),
10834
- join51(home, ".opencode", "bin"),
10835
- join51(home, ".claude", "bin"),
10836
- join51(home, ".codex", "bin"),
10868
+ join50(home, ".local", "bin"),
10869
+ join50(home, ".opencode", "bin"),
10870
+ join50(home, ".claude", "bin"),
10871
+ join50(home, ".codex", "bin"),
10837
10872
  ...under(localAppData, "Programs", "claude"),
10838
10873
  // Node package managers. npm's global prefix is `%APPDATA%\npm`; the
10839
10874
  // literal spelling is kept as a fallback for a host that does not export
10840
10875
  // APPDATA (a service account, a stripped CI container).
10841
10876
  ...under(appData, "npm"),
10842
- join51(home, "AppData", "Roaming", "npm"),
10877
+ join50(home, "AppData", "Roaming", "npm"),
10843
10878
  ...under(localAppData, "pnpm"),
10844
10879
  ...under(localAppData, "Yarn", "bin"),
10845
- join51(home, ".bun", "bin"),
10880
+ join50(home, ".bun", "bin"),
10846
10881
  // Windows package managers.
10847
- join51(home, "scoop", "shims"),
10882
+ join50(home, "scoop", "shims"),
10848
10883
  ...under(env.SCOOP, "shims"),
10849
10884
  ...under(env.SCOOP_GLOBAL ?? programData, "scoop", "shims"),
10850
10885
  ...under(programData, "chocolatey", "bin"),
@@ -10854,7 +10889,7 @@ function windowsBinDirs(env, home) {
10854
10889
  ...under(localAppData, "Microsoft", "WindowsApps"),
10855
10890
  // Version managers. Volta's Windows home is not the POSIX `~/.volta`.
10856
10891
  ...under(localAppData, "Volta", "bin"),
10857
- join51(home, ".volta", "bin")
10892
+ join50(home, ".volta", "bin")
10858
10893
  ];
10859
10894
  }
10860
10895
  function wellKnownBinDirs(deps = {}) {
@@ -10965,7 +11000,7 @@ var BatchQuoteError = class extends Error {
10965
11000
 
10966
11001
  cmd.exe has no way to carry a quote inside a quoted argument, so the text after it would run as commands of their own.
10967
11002
 
10968
- Install the native executable from the coding agent's own Windows installer or release binary. Ordewell will launch it directly, with no interpreter in the way. A PowerShell shim (${command}.ps1) beside the batch one is also enough.`
11003
+ Install the native executable from the coding agent's own Windows installer or release binary. Ordewell will launch it directly, with no interpreter in the way.`
10969
11004
  );
10970
11005
  this.command = command;
10971
11006
  this.name = "BatchQuoteError";
@@ -10986,12 +11021,17 @@ Searched: ${searchedPath || "(empty PATH)"}`);
10986
11021
  };
10987
11022
  function isResolvableOnPosixPath(command, PATH, exists) {
10988
11023
  if (command.includes("/")) return exists(command);
10989
- return PATH.split(path15.delimiter).map((d) => d.trim()).filter(Boolean).some((dir) => exists(path15.join(dir, command)));
11024
+ return PATH.split(path15.posix.delimiter).map((d) => d.trim()).filter(Boolean).some((dir) => exists(path15.posix.join(dir, command)));
10990
11025
  }
10991
11026
  function isExecutableResolved(command, plan, PATH, deps = {}) {
10992
- if ((deps.platform ?? process.platform) === "win32") return plan.file !== command;
11027
+ if ((deps.platform ?? process.platform) === "win32") return plan.file !== command || namesDirectFile(command, deps);
10993
11028
  return isResolvableOnPosixPath(command, PATH, deps.exists ?? defaultExists3);
10994
11029
  }
11030
+ function namesDirectFile(command, deps) {
11031
+ if (path15.win32.basename(command) === command) return false;
11032
+ const pathExt = (deps.pathExt ?? (() => process.env.PATHEXT ?? ""))();
11033
+ return candidateExtensions(command, pathExt).direct.includes("") && (deps.exists ?? defaultExists3)(command);
11034
+ }
10995
11035
  function defaultExists3(candidate) {
10996
11036
  try {
10997
11037
  return fsSync4.statSync(candidate).isFile();
@@ -11720,10 +11760,10 @@ var DIRENV_TIMEOUT_MS = 5e3;
11720
11760
  var KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
11721
11761
  function defaultDeps() {
11722
11762
  return {
11723
- run: (command, args, opts) => new Promise((resolve17) => {
11763
+ run: (command, args, opts) => new Promise((resolve18) => {
11724
11764
  execFile3(command, args, { ...opts, timeout: DIRENV_TIMEOUT_MS, encoding: "utf8" }, (err, stdout, stderr) => {
11725
11765
  const code = err ? typeof err.code === "number" ? Number(err.code) : -1 : 0;
11726
- resolve17({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
11766
+ resolve18({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
11727
11767
  });
11728
11768
  }),
11729
11769
  readFile: (file) => {
@@ -11812,10 +11852,10 @@ async function fromDirenv(cwd, deps) {
11812
11852
  }
11813
11853
  return { env, blocked: null };
11814
11854
  }
11815
- function findUp(start, relative21, deps) {
11855
+ function findUp(start, relative20, deps) {
11816
11856
  let dir = path18.resolve(start);
11817
11857
  for (; ; ) {
11818
- const candidate = path18.join(dir, relative21);
11858
+ const candidate = path18.join(dir, relative20);
11819
11859
  if (deps.readFile(candidate) !== null) return candidate;
11820
11860
  const parent = path18.dirname(dir);
11821
11861
  if (parent === dir) return null;
@@ -11860,14 +11900,14 @@ function parseEnvFile(content, context, home) {
11860
11900
 
11861
11901
  // src/services/harness/settleWithin.ts
11862
11902
  function settleWithin(promise, wait) {
11863
- return new Promise((resolve17, reject) => {
11903
+ return new Promise((resolve18, reject) => {
11864
11904
  let settled = false;
11865
11905
  const settle = (outcome) => {
11866
11906
  if (settled) return;
11867
11907
  settled = true;
11868
11908
  clearTimeout(timer);
11869
11909
  try {
11870
- resolve17(outcome());
11910
+ resolve18(outcome());
11871
11911
  } catch (err) {
11872
11912
  reject(err);
11873
11913
  }
@@ -11930,14 +11970,14 @@ function unlessCancelled(work, signal) {
11930
11970
  if (!signal) return work;
11931
11971
  work.catch(() => {
11932
11972
  });
11933
- return new Promise((resolve17, reject) => {
11973
+ return new Promise((resolve18, reject) => {
11934
11974
  if (signal.aborted) {
11935
- resolve17(CANCELLED2);
11975
+ resolve18(CANCELLED2);
11936
11976
  return;
11937
11977
  }
11938
- const onAbort = () => resolve17(CANCELLED2);
11978
+ const onAbort = () => resolve18(CANCELLED2);
11939
11979
  signal.addEventListener("abort", onAbort, { once: true });
11940
- work.then(resolve17, reject).finally(() => signal.removeEventListener("abort", onAbort));
11980
+ work.then(resolve18, reject).finally(() => signal.removeEventListener("abort", onAbort));
11941
11981
  });
11942
11982
  }
11943
11983
  async function spawnAttached(steps) {
@@ -12036,8 +12076,8 @@ async function awaitAttach(probe, timeoutMs, pollMs, ended2) {
12036
12076
  const state = await settleWithin(probe(left), ended2 ? { timeoutMs: left, onTimeout, ended: ended2, onEnded: () => "failed" } : { timeoutMs: left, onTimeout });
12037
12077
  if (state !== "pending") return state;
12038
12078
  if (pollMs > 0) {
12039
- await new Promise((resolve17) => {
12040
- const timer = setTimeout(resolve17, pollMs);
12079
+ await new Promise((resolve18) => {
12080
+ const timer = setTimeout(resolve18, pollMs);
12041
12081
  timer.unref?.();
12042
12082
  });
12043
12083
  }
@@ -12254,8 +12294,8 @@ function releasePipes(child) {
12254
12294
  var RunnerProcess = class {
12255
12295
  constructor(deps) {
12256
12296
  this.deps = deps;
12257
- this.ended = new Promise((resolve17) => {
12258
- this.markEnded = resolve17;
12297
+ this.ended = new Promise((resolve18) => {
12298
+ this.markEnded = resolve18;
12259
12299
  });
12260
12300
  }
12261
12301
  deps;
@@ -12304,7 +12344,8 @@ var RunnerProcess = class {
12304
12344
  const PATH = await resolvePath();
12305
12345
  const launch = await planDirectLaunch(command.command, command.args, {
12306
12346
  platform: this.deps.platform,
12307
- resolvePath
12347
+ resolvePath,
12348
+ exists: this.deps.exists
12308
12349
  });
12309
12350
  if (!isExecutableResolved(command.command, launch, PATH, { platform: this.deps.platform, exists: this.deps.exists })) {
12310
12351
  throw new ExecutableNotFoundError(command.command, PATH);
@@ -12721,7 +12762,7 @@ var StdioAgentAdapter = class extends ProcessLifecycle {
12721
12762
  onEvent({ type: "error", message: this.exitMessage() });
12722
12763
  return;
12723
12764
  }
12724
- await new Promise((resolve17, reject) => {
12765
+ await new Promise((resolve18, reject) => {
12725
12766
  let settled = false;
12726
12767
  const release2 = () => {
12727
12768
  settled = true;
@@ -12733,7 +12774,7 @@ var StdioAgentAdapter = class extends ProcessLifecycle {
12733
12774
  const finish2 = () => {
12734
12775
  if (settled) return;
12735
12776
  release2();
12736
- resolve17();
12777
+ resolve18();
12737
12778
  };
12738
12779
  const fail = (err) => {
12739
12780
  if (settled) return;
@@ -12947,7 +12988,7 @@ var PermissionLedger = class {
12947
12988
  const open = this.open.get(id2);
12948
12989
  if (!open || this.answering.has(id2)) return false;
12949
12990
  this.answering.add(id2);
12950
- const sent = new Promise((resolve17) => resolve17(this.reply(open.handle, decision)));
12991
+ const sent = new Promise((resolve18) => resolve18(this.reply(open.handle, decision)));
12951
12992
  return this.awaitReply(id2, open, sent);
12952
12993
  }
12953
12994
  async awaitReply(id2, open, sent) {
@@ -13801,8 +13842,8 @@ var ClaudeCodeAdapter = class extends StdioAgentAdapter {
13801
13842
  if (!this.process) return Promise.resolve(null);
13802
13843
  this.controlCount += 1;
13803
13844
  const requestId = `ordewell-${request.subtype}-${this.controlCount}`;
13804
- const answered2 = new Promise((resolve17) => {
13805
- this.pendingControl.set(requestId, resolve17);
13845
+ const answered2 = new Promise((resolve18) => {
13846
+ this.pendingControl.set(requestId, resolve18);
13806
13847
  });
13807
13848
  this.writeLine({ type: "control_request", request_id: requestId, request });
13808
13849
  return settleWithin(answered2, { timeoutMs, ended: this.processEnded, onTimeout: () => null, onEnded: () => null }).finally(() => {
@@ -14307,7 +14348,7 @@ var ClaudeCodeAdapter = class extends StdioAgentAdapter {
14307
14348
 
14308
14349
  // src/services/harness/CodexAdapter.ts
14309
14350
  import { randomUUID as randomUUID4 } from "crypto";
14310
- import { isAbsolute as isAbsolute6, relative as relative8, sep as sep3 } from "path";
14351
+ import * as hostPath from "path";
14311
14352
 
14312
14353
  // src/services/harness/codexSandbox.ts
14313
14354
  var CODEX_RUNNER = "codex";
@@ -14417,7 +14458,7 @@ var CodexSandboxAvailability = class {
14417
14458
  async function runProbe(deps, cwd, env, flags) {
14418
14459
  const args = ["sandbox", ...flags, "--", "/bin/true"];
14419
14460
  const placed = await deps.placement?.place({ command: "codex", args, env: {}, files: [] });
14420
- return new Promise((resolve17) => {
14461
+ return new Promise((resolve18) => {
14421
14462
  let output = "";
14422
14463
  let settled = false;
14423
14464
  let proc = null;
@@ -14426,7 +14467,7 @@ async function runProbe(deps, cwd, env, flags) {
14426
14467
  settled = true;
14427
14468
  clearTimeout(timer);
14428
14469
  placed?.ended();
14429
- resolve17({ code, output });
14470
+ resolve18({ code, output });
14430
14471
  };
14431
14472
  const timer = setTimeout(() => {
14432
14473
  placed?.stop();
@@ -14612,7 +14653,7 @@ var CodexRpc = class {
14612
14653
  }
14613
14654
  /** The request as the awaited form of {@link send}, for steps that wait on one answer and nothing else. */
14614
14655
  call(method, params) {
14615
- return new Promise((resolve17) => this.send(method, params, (response) => resolve17(response)));
14656
+ return new Promise((resolve18) => this.send(method, params, (response) => resolve18(response)));
14616
14657
  }
14617
14658
  /**
14618
14659
  * A request framed as the line to write, left to the caller to write — for
@@ -15154,8 +15195,8 @@ ${this.exitMessage()}`);
15154
15195
  return awaitAttach(async (left) => {
15155
15196
  const known = CODEX_ORDEWELL.attachState(this.mcpStartup);
15156
15197
  if (known !== "pending") return known;
15157
- const reported = new Promise((resolve17) => {
15158
- this.mcpStartupSettled = () => resolve17(CODEX_ORDEWELL.attachState(this.mcpStartup));
15198
+ const reported = new Promise((resolve18) => {
15199
+ this.mcpStartupSettled = () => resolve18(CODEX_ORDEWELL.attachState(this.mcpStartup));
15159
15200
  });
15160
15201
  const state = await settleWithin(reported, {
15161
15202
  timeoutMs: left,
@@ -15180,10 +15221,10 @@ ${this.exitMessage()}`);
15180
15221
  const turn = this.turn;
15181
15222
  if (!this.process || !turn) return Promise.resolve(false);
15182
15223
  this.interruptRequested = true;
15183
- const acknowledged = new Promise((resolve17) => {
15224
+ const acknowledged = new Promise((resolve18) => {
15184
15225
  this.whenNamed(turn, () => this.rpc.send("turn/interrupt", { threadId: this.threadId, turnId: turn.id }, (response) => {
15185
15226
  if (!response.ok) this.interruptRequested = false;
15186
- resolve17(response.ok);
15227
+ resolve18(response.ok);
15187
15228
  }));
15188
15229
  });
15189
15230
  return settleWithin(acknowledged, { timeoutMs, ended: this.processEnded, onTimeout: () => false, onEnded: () => false });
@@ -15205,7 +15246,7 @@ ${this.exitMessage()}`);
15205
15246
  const turn = this.turn;
15206
15247
  if (!this.process || !turn) return Promise.resolve(false);
15207
15248
  const clientId = randomUUID4();
15208
- return new Promise((resolve17) => {
15249
+ return new Promise((resolve18) => {
15209
15250
  let settled = false;
15210
15251
  const steer = {
15211
15252
  id: id2,
@@ -15214,7 +15255,7 @@ ${this.exitMessage()}`);
15214
15255
  if (settled) return;
15215
15256
  settled = true;
15216
15257
  if (!accepted) turn.steers.delete(clientId);
15217
- resolve17(accepted);
15258
+ resolve18(accepted);
15218
15259
  }
15219
15260
  };
15220
15261
  turn.steers.set(clientId, steer);
@@ -15763,10 +15804,11 @@ ${this.exitMessage()}`);
15763
15804
  }
15764
15805
  /** Relative to the task's worktree, where every path but a stray one lies; a move names both ends. */
15765
15806
  shownChangePath(change) {
15807
+ const { isAbsolute: isAbsolute13, relative: relative20, sep: sep13 } = this.deps.placement ? hostPath.posix : hostPath;
15766
15808
  const shown = (path52) => {
15767
15809
  const cwd = this.startOpts && this.runnerCwd(this.startOpts);
15768
- const rel = cwd ? relative8(cwd, path52) : path52;
15769
- return rel && rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute6(rel) ? rel : path52;
15810
+ const rel = cwd ? relative20(cwd, path52) : path52;
15811
+ return rel && rel !== ".." && !rel.startsWith(`..${sep13}`) && !isAbsolute13(rel) ? rel : path52;
15770
15812
  };
15771
15813
  const from = shown(change.path ?? "");
15772
15814
  return change.kind?.move_path ? `${from} \u2192 ${shown(change.kind.move_path)}` : from;
@@ -15973,14 +16015,14 @@ function splitModelId(id2) {
15973
16015
  return { providerID: id2.slice(0, slash), modelID: id2.slice(slash + 1) };
15974
16016
  }
15975
16017
  function delay(ms, signal) {
15976
- return new Promise((resolve17) => {
16018
+ return new Promise((resolve18) => {
15977
16019
  const onAbort = () => {
15978
16020
  clearTimeout(timer);
15979
- resolve17();
16021
+ resolve18();
15980
16022
  };
15981
16023
  const timer = setTimeout(() => {
15982
16024
  signal?.removeEventListener("abort", onAbort);
15983
- resolve17();
16025
+ resolve18();
15984
16026
  }, ms);
15985
16027
  timer.unref?.();
15986
16028
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -16102,8 +16144,8 @@ function streamTurn() {
16102
16144
  }
16103
16145
  function turnLatch() {
16104
16146
  let markDone;
16105
- const ended2 = new Promise((resolve17) => {
16106
- markDone = resolve17;
16147
+ const ended2 = new Promise((resolve18) => {
16148
+ markDone = resolve18;
16107
16149
  });
16108
16150
  const turn = { live: false, done: false, ended: ended2, finish: () => {
16109
16151
  turn.done = true;
@@ -16115,9 +16157,9 @@ async function settleTurn(turn, how, onEvent) {
16115
16157
  const { signal } = how;
16116
16158
  let onAbort = () => {
16117
16159
  };
16118
- const aborted = new Promise((resolve17) => {
16119
- onAbort = resolve17;
16120
- if (signal?.aborted) resolve17();
16160
+ const aborted = new Promise((resolve18) => {
16161
+ onAbort = resolve18;
16162
+ if (signal?.aborted) resolve18();
16121
16163
  signal?.addEventListener("abort", onAbort, { once: true });
16122
16164
  });
16123
16165
  try {
@@ -16144,8 +16186,8 @@ async function interruptAcknowledged(turn, processEnded, timeoutMs) {
16144
16186
  async function openEventStream(connect2, onFrame, onActivity) {
16145
16187
  const streamAbort = new AbortController();
16146
16188
  let connected;
16147
- const ready = new Promise((resolve17) => {
16148
- connected = resolve17;
16189
+ const ready = new Promise((resolve18) => {
16190
+ connected = resolve18;
16149
16191
  });
16150
16192
  let fail;
16151
16193
  const failed2 = new Promise((_resolve, reject) => {
@@ -16159,7 +16201,7 @@ async function openEventStream(connect2, onFrame, onActivity) {
16159
16201
  const attemptAbort = new AbortController();
16160
16202
  const abortAttempt = () => attemptAbort.abort();
16161
16203
  streamAbort.signal.addEventListener("abort", abortAttempt, { once: true });
16162
- const stopped2 = new Promise((resolve17) => attemptAbort.signal.addEventListener("abort", () => resolve17(), { once: true }));
16204
+ const stopped2 = new Promise((resolve18) => attemptAbort.signal.addEventListener("abort", () => resolve18(), { once: true }));
16163
16205
  try {
16164
16206
  await streamEvents((signal) => settleWithin(connect2(signal), {
16165
16207
  timeoutMs: STREAM_CONNECT_TIMEOUT_MS,
@@ -16960,7 +17002,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
16960
17002
  * only until the address is known.
16961
17003
  */
16962
17004
  serverAddress() {
16963
- return new Promise((resolve17) => {
17005
+ return new Promise((resolve18) => {
16964
17006
  let partial = "";
16965
17007
  const stopReading = this.runner.readStdout((text4) => {
16966
17008
  const lines = (partial + text4).split("\n");
@@ -16975,7 +17017,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
16975
17017
  const settle = (url) => {
16976
17018
  stopReading();
16977
17019
  clearTimeout(timer);
16978
- resolve17(url);
17020
+ resolve18(url);
16979
17021
  };
16980
17022
  void this.processEnded.then(() => settle(null));
16981
17023
  });
@@ -17675,7 +17717,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
17675
17717
  if (servers) this.mcpServers = Object.keys(servers).filter((name) => name !== ordewell.name);
17676
17718
  return OPENCODE_ORDEWELL.attachState(servers?.[ordewell.name]?.status);
17677
17719
  }, MCP_ATTACH_TIMEOUT_MS, MCP_STATUS_POLL_MS2, this.processEnded);
17678
- if (state === "connected" && this.v2) await new Promise((resolve17) => setTimeout(resolve17, V2_TOOLS_OFFERED_MS));
17720
+ if (state === "connected" && this.v2) await new Promise((resolve18) => setTimeout(resolve18, V2_TOOLS_OFFERED_MS));
17679
17721
  return state;
17680
17722
  }
17681
17723
  /** 2.x lists its servers as `{ name, status: { status } }`, and only once it has started connecting them. */
@@ -18057,8 +18099,8 @@ async function openAppServer(command, args, launch) {
18057
18099
  })) launch.onMessage?.(message);
18058
18100
  };
18059
18101
  let inputBroken;
18060
- const broken = new Promise((resolve17) => {
18061
- inputBroken = resolve17;
18102
+ const broken = new Promise((resolve18) => {
18103
+ inputBroken = resolve18;
18062
18104
  });
18063
18105
  try {
18064
18106
  await runner.start(launch.cwd, () => ({ command, args }), (started) => {
@@ -20014,11 +20056,11 @@ async function committedInHead(files) {
20014
20056
  }
20015
20057
  const result = /* @__PURE__ */ new Map();
20016
20058
  await Promise.all([...byDir].map(async ([dir, inDir]) => {
20017
- const relative21 = (file) => path33.relative(dir, file).split(path33.sep).join("/");
20059
+ const relative20 = (file) => path33.relative(dir, file).split(path33.sep).join("/");
20018
20060
  try {
20019
- const { stdout } = await runGit("git", ["ls-tree", "--name-only", "HEAD", "--", ...inDir.map(relative21)], { cwd: dir, env: cleanEnv() });
20061
+ const { stdout } = await runGit("git", ["ls-tree", "--name-only", "HEAD", "--", ...inDir.map(relative20)], { cwd: dir, env: cleanEnv() });
20020
20062
  const listed4 = new Set(stdout.split("\n").map((line) => line.trim()).filter(Boolean));
20021
- for (const file of inDir) result.set(file, listed4.has(relative21(file)));
20063
+ for (const file of inDir) result.set(file, listed4.has(relative20(file)));
20022
20064
  } catch {
20023
20065
  }
20024
20066
  }));
@@ -21340,12 +21382,12 @@ function buildConflictRepairPrompt(task2, conflict, integrationBranch, plan) {
21340
21382
  const merge = `git merge --no-edit ${quotedMessageArgs(conflict.message)} ${integrationBranch}`;
21341
21383
  const asked = `What the task was asked to do:
21342
21384
  ${task2.prompt ?? task2.description}`;
21343
- const resolve17 = "resolve every conflict so that both sides' intent survives: keep the work already integrated and add what the task contributed.";
21385
+ const resolve18 = "resolve every conflict so that both sides' intent survives: keep the work already integrated and add what the task contributed.";
21344
21386
  const repos = conflict.repos.filter((repo) => repo !== SELF_REPO);
21345
21387
  if (repos.length === 0) {
21346
21388
  return [
21347
21389
  `Task ${ref2} "${task2.title}" passed, but merging its branch \`${branch}\` into \`${integrationBranch}\` conflicted${files.length > 0 ? ` in ${files.join(", ")}` : ""}. None of its work has landed yet.`,
21348
- `This is the task's own worktree, on \`${branch}\`, with its work committed. Run \`${merge}\` here and ${resolve17} Never drop either side wholesale, and never abort the merge or reset it away.`,
21390
+ `This is the task's own worktree, on \`${branch}\`, with its work committed. Run \`${merge}\` here and ${resolve18} Never drop either side wholesale, and never abort the merge or reset it away.`,
21349
21391
  `Build and test the result the way this project does, commit the merge with \`${COMMIT_MERGE}\`, and only then call \`task_complete\`.`,
21350
21392
  "",
21351
21393
  asked
@@ -21354,7 +21396,7 @@ ${task2.prompt ?? task2.description}`;
21354
21396
  const stoppedIn = conflict.conflictRepo ?? repos[0];
21355
21397
  return [
21356
21398
  `Task ${ref2} "${task2.title}" passed, but landing its branch \`${branch}\` on \`${integrationBranch}\` conflicted in ${stoppedIn}${files.length > 0 ? ` (${files.join(", ")})` : ""}. A task lands in every repository it changed or in none, so none of its work has landed yet.`,
21357
- `This is the task's own workspace, with each repository at its usual path on \`${branch}\` and the task's work committed. In each repository the task changed \u2014 ${repos.join(", ")} \u2014 run \`${merge}\` inside that repository's directory, and ${resolve17} Never drop either side wholesale, and never abort a merge or reset it away.`,
21399
+ `This is the task's own workspace, with each repository at its usual path on \`${branch}\` and the task's work committed. In each repository the task changed \u2014 ${repos.join(", ")} \u2014 run \`${merge}\` inside that repository's directory, and ${resolve18} Never drop either side wholesale, and never abort a merge or reset it away.`,
21358
21400
  `Build and test the result the way this project does, commit the merge in each repository with \`${COMMIT_MERGE}\`, and only then call \`task_complete\`.`,
21359
21401
  "",
21360
21402
  asked
@@ -22678,12 +22720,12 @@ var PlannerConversation = class {
22678
22720
  }
22679
22721
  /** Resolves once no turn holds the conversation: what a subtree's stop waits on (ADR-0055 D16). */
22680
22722
  idle() {
22681
- return this.live ? new Promise((resolve17) => {
22682
- this.idling.push(resolve17);
22723
+ return this.live ? new Promise((resolve18) => {
22724
+ this.idling.push(resolve18);
22683
22725
  }) : Promise.resolve();
22684
22726
  }
22685
22727
  settleIdle() {
22686
- for (const resolve17 of this.idling.splice(0)) resolve17();
22728
+ for (const resolve18 of this.idling.splice(0)) resolve18();
22687
22729
  }
22688
22730
  /** Stop the planner turn in flight; it settles as stopped. False when none is. */
22689
22731
  stopTurn(by) {
@@ -24939,7 +24981,7 @@ async function runNotifyCommand(command, env, { timeLimitMs = NOTIFY_TIME_LIMIT_
24939
24981
  });
24940
24982
  proc.unref();
24941
24983
  const leaveTeardown = onHostTeardown(() => stop(proc));
24942
- await new Promise((resolve17, reject) => {
24984
+ await new Promise((resolve18, reject) => {
24943
24985
  const settle = () => {
24944
24986
  clearTimeout(limit);
24945
24987
  leaveTeardown();
@@ -24956,7 +24998,7 @@ async function runNotifyCommand(command, env, { timeLimitMs = NOTIFY_TIME_LIMIT_
24956
24998
  });
24957
24999
  proc.once("exit", (code, signal) => {
24958
25000
  settle();
24959
- if (code === 0) resolve17();
25001
+ if (code === 0) resolve18();
24960
25002
  else reject(new Error(code === null ? `ended on ${signal}` : `exited with code ${code}`));
24961
25003
  });
24962
25004
  });
@@ -25004,8 +25046,8 @@ function detectInstalledPlanner(installation) {
25004
25046
  return probe;
25005
25047
  }
25006
25048
  async function installedPlannerDetected() {
25007
- while (!answered) await new Promise((resolve17) => {
25008
- waiters.push(resolve17);
25049
+ while (!answered) await new Promise((resolve18) => {
25050
+ waiters.push(resolve18);
25009
25051
  });
25010
25052
  }
25011
25053
  function installedPlannerAnswered() {
@@ -25460,9 +25502,8 @@ var EnvConfig = class extends BaseConfig {
25460
25502
 
25461
25503
  // src/services/taskDiffRead.ts
25462
25504
  import { createHash as createHash3 } from "crypto";
25463
- import * as fs14 from "fs";
25505
+ import * as fs15 from "fs";
25464
25506
  import * as path36 from "path";
25465
- import { devNull } from "os";
25466
25507
 
25467
25508
  // src/services/stateRoot.ts
25468
25509
  import * as fs13 from "fs";
@@ -25490,6 +25531,16 @@ function refuseUsersCheckout(codeRoot, stateRoot) {
25490
25531
  }
25491
25532
  }
25492
25533
 
25534
+ // src/utils/realPath.ts
25535
+ import * as fs14 from "fs";
25536
+ function realPathOf(p) {
25537
+ try {
25538
+ return fs14.realpathSync.native(p);
25539
+ } catch {
25540
+ return fs14.realpathSync(p);
25541
+ }
25542
+ }
25543
+
25493
25544
  // src/services/taskDiffRead.ts
25494
25545
  var TASK_DIFF_UNAVAILABLE = "Task diff is not available for this run: no task-specific changes were recorded (shared runs cannot attribute workspace changes to one task).";
25495
25546
  function allowedPath(file) {
@@ -25597,18 +25648,18 @@ async function readTaskDiff(invoker, run, taskId, options) {
25597
25648
  };
25598
25649
  try {
25599
25650
  const files = [];
25600
- const workspaceRoot = fs14.realpathSync(stateRootOf(run));
25651
+ const workspaceRoot = fs15.realpathSync(stateRootOf(run));
25601
25652
  for (const repo of run.repos) {
25602
25653
  if (options.repo !== void 0 && repo.path !== options.repo) continue;
25603
25654
  const entry = record.repos[repo.path];
25604
25655
  if (!entry?.baseRef) return { available: false, reason: `Task diff is not available for repository ${repo.path}: this older run did not record the task's starting commit.` };
25605
25656
  if (!/^[a-f0-9]{40,64}$/.test(entry.baseRef)) throw new Error("Invalid recorded starting commit.");
25606
- const live2 = record.status !== "merged" && fs14.existsSync(entry.worktree);
25657
+ const live2 = record.status !== "merged" && fs15.existsSync(entry.worktree);
25607
25658
  const cwd = live2 ? entry.worktree : repo.root;
25608
- if (!inside(workspaceRoot, fs14.realpathSync(cwd))) throw new Error("The recorded task repository moved outside the workspace.");
25659
+ if (!inside(workspaceRoot, fs15.realpathSync(cwd))) throw new Error("The recorded task repository moved outside the workspace.");
25609
25660
  if (live2) {
25610
25661
  const toplevel = (await git(reader, cwd, ["rev-parse", "--show-toplevel"])).trim();
25611
- if (fs14.realpathSync(toplevel) !== fs14.realpathSync(entry.worktree)) throw new Error("The recorded task worktree is no longer a repository.");
25662
+ if (realPathOf(toplevel) !== realPathOf(entry.worktree)) throw new Error("The recorded task worktree is no longer a repository.");
25612
25663
  }
25613
25664
  const prefix = (await git(reader, repo.root, ["rev-parse", "--show-prefix"])).trim();
25614
25665
  const common = ["--no-pager", "-c", "core.fsmonitor=false"];
@@ -25643,9 +25694,9 @@ async function readTaskDiff(invoker, run, taskId, options) {
25643
25694
  const others = await git(reader, workspace, [...common, "ls-files", "--others", "--exclude-standard", "-z", "--", "."]);
25644
25695
  for (const file of others.split("\0").filter((f) => f && allowed(f))) {
25645
25696
  const full = path36.join(workspace, file);
25646
- if (!inside(fs14.realpathSync(workspace), fs14.realpathSync(path36.dirname(full)))) continue;
25697
+ if (!inside(fs15.realpathSync(workspace), fs15.realpathSync(path36.dirname(full)))) continue;
25647
25698
  const untracked = async (numstat) => {
25648
- const result = await tryGit(reader, workspace, [...common, "diff", "--no-index", "--no-renames", "--no-ext-diff", "--no-textconv", ...numstat ? ["--numstat", "-z"] : [], "--", devNull, file]);
25699
+ const result = await tryGit(reader, workspace, [...common, "diff", "--no-index", "--no-renames", "--no-ext-diff", "--no-textconv", ...numstat ? ["--numstat", "-z"] : [], "--", "/dev/null", file]);
25649
25700
  if (!result.ok && result.code !== 1) throw new Error(result.stderr.trim() || "Could not read an untracked file diff.");
25650
25701
  return result.stdout;
25651
25702
  };
@@ -25673,7 +25724,7 @@ ${await file.patch()}`);
25673
25724
  // src/services/GitWorktreeIsolation.ts
25674
25725
  import { randomBytes as randomBytes6 } from "crypto";
25675
25726
  import { spawnSync } from "child_process";
25676
- import * as fs16 from "fs";
25727
+ import * as fs17 from "fs";
25677
25728
  import * as path38 from "path";
25678
25729
 
25679
25730
  // src/utils/shell.ts
@@ -25686,7 +25737,7 @@ function shellQuoted(text4) {
25686
25737
  }
25687
25738
 
25688
25739
  // src/utils/prdStore.ts
25689
- import * as fs15 from "fs";
25740
+ import * as fs16 from "fs";
25690
25741
  import * as path37 from "path";
25691
25742
  var PRD_BLOCK_RE = /<!--\s*ORDEWELL_PRD_START\s+slug="([^"]+)"\s*-->\s*([\s\S]*?)\s*<!--\s*ORDEWELL_PRD_END\s*-->/;
25692
25743
  function extractPrdBlock(text4) {
@@ -25702,9 +25753,9 @@ function sanitizeSlug(raw) {
25702
25753
  }
25703
25754
  function savePrdMarkdown(workspace, slug, markdown) {
25704
25755
  const dir = path37.join(workspace, ".scratch", sanitizeSlug(slug));
25705
- fs15.mkdirSync(dir, { recursive: true });
25756
+ fs16.mkdirSync(dir, { recursive: true });
25706
25757
  const file = path37.join(dir, "PRD.md");
25707
- fs15.writeFileSync(file, markdown.endsWith("\n") ? markdown : markdown + "\n", "utf8");
25758
+ fs16.writeFileSync(file, markdown.endsWith("\n") ? markdown : markdown + "\n", "utf8");
25708
25759
  return file;
25709
25760
  }
25710
25761
 
@@ -25864,7 +25915,7 @@ function isInside(parent, child) {
25864
25915
  }
25865
25916
  function resolvesAsNamed(base, p) {
25866
25917
  try {
25867
- return fs16.realpathSync(p) === path38.join(fs16.realpathSync(base), path38.relative(base, p));
25918
+ return fs17.realpathSync(p) === path38.join(fs17.realpathSync(base), path38.relative(base, p));
25868
25919
  } catch {
25869
25920
  return false;
25870
25921
  }
@@ -25958,7 +26009,7 @@ function settleStatus(record, status) {
25958
26009
  }
25959
26010
  function realDir(p) {
25960
26011
  try {
25961
- return fs16.realpathSync.native(p);
26012
+ return fs17.realpathSync.native(p);
25962
26013
  } catch {
25963
26014
  return path38.resolve(p);
25964
26015
  }
@@ -25968,7 +26019,7 @@ function sameDir(a, b) {
25968
26019
  }
25969
26020
  function resolves(target) {
25970
26021
  try {
25971
- fs16.statSync(target);
26022
+ fs17.statSync(target);
25972
26023
  return true;
25973
26024
  } catch {
25974
26025
  return false;
@@ -25988,7 +26039,7 @@ function leftoverLinks(dir) {
25988
26039
  }
25989
26040
  function isLink(target) {
25990
26041
  try {
25991
- return fs16.lstatSync(target).isSymbolicLink();
26042
+ return fs17.lstatSync(target).isSymbolicLink();
25992
26043
  } catch {
25993
26044
  return false;
25994
26045
  }
@@ -26200,7 +26251,7 @@ var GitWorktreeIsolation = class {
26200
26251
  async acceptsWorktree(run, repo) {
26201
26252
  const dir = this.integrationDir(run, repo);
26202
26253
  ensureStateDirIgnored(stateRootOf(run));
26203
- fs16.mkdirSync(path38.dirname(dir), { recursive: true });
26254
+ fs17.mkdirSync(path38.dirname(dir), { recursive: true });
26204
26255
  const added = await this.tryGit(repo.root, ["worktree", "add", "-q", "--no-checkout", dir, repo.integrationBranch]);
26205
26256
  await this.removeWorktreeDir(run, repo, dir, []);
26206
26257
  return added.ok;
@@ -26268,7 +26319,7 @@ var GitWorktreeIsolation = class {
26268
26319
  for (const repo of run.repos) {
26269
26320
  const worktree = path38.join(dir, repo.path);
26270
26321
  const tip = (await this.git(repo.root, ["rev-parse", repo.integrationBranch])).trim();
26271
- fs16.mkdirSync(path38.dirname(worktree), { recursive: true });
26322
+ fs17.mkdirSync(path38.dirname(worktree), { recursive: true });
26272
26323
  await this.git(repo.root, ["worktree", "add", "-q", "-B", branch, worktree, tip]);
26273
26324
  record.repos[repo.path] = { worktree, linked: [], baseRef: tip };
26274
26325
  }
@@ -26300,7 +26351,7 @@ var GitWorktreeIsolation = class {
26300
26351
  const source = path38.join(run.workspaceRoot, rel);
26301
26352
  const target = path38.join(cwd, rel);
26302
26353
  if (!resolves(source) || lexists(target)) continue;
26303
- fs16.mkdirSync(path38.dirname(target), { recursive: true });
26354
+ fs17.mkdirSync(path38.dirname(target), { recursive: true });
26304
26355
  if (linkPath(source, target, this.platform) === "copy") copied.push(rel);
26305
26356
  const entry = self ? record.repos[SELF_REPO] : void 0;
26306
26357
  if (entry) entry.linked.push(rel);
@@ -26353,7 +26404,7 @@ var GitWorktreeIsolation = class {
26353
26404
  }
26354
26405
  const base = { branch: names2.branch, name: path38.basename(names2.dir), title: task2.title };
26355
26406
  for (const worktree of at) {
26356
- if (!fs16.existsSync(worktree)) continue;
26407
+ if (!fs17.existsSync(worktree)) continue;
26357
26408
  const linked = leftoverLinks(path38.join(worktree, await this.prefixOf(repo)));
26358
26409
  found.push({ repo, worktree, target: { ...base, worktree, linked } });
26359
26410
  }
@@ -26372,7 +26423,7 @@ var GitWorktreeIsolation = class {
26372
26423
  if (target.worktree) await this.removeWorktreeDir(run, repo, worktree, target.linked);
26373
26424
  }
26374
26425
  for (const repo of run.repos) await this.tryGit(repo.root, ["branch", "-D", names2.branch]);
26375
- this.removeTaskWorkspace(run, names2.dir);
26426
+ await this.removeTaskWorkspace(run, names2.dir);
26376
26427
  return removal;
26377
26428
  }
26378
26429
  async restorePrevious(record, preserved) {
@@ -26402,7 +26453,7 @@ var GitWorktreeIsolation = class {
26402
26453
  for (const repo of run.repos) {
26403
26454
  const entry = record.repos[repo.path];
26404
26455
  if (!entry) continue;
26405
- if (!fs16.existsSync(entry.worktree)) throw new Error(`The worktree of task ${task2.order} is gone: ${entry.worktree}`);
26456
+ if (!fs17.existsSync(entry.worktree)) throw new Error(`The worktree of task ${task2.order} is gone: ${entry.worktree}`);
26406
26457
  if (repo.path === SELF_REPO) cwd = await this.inWorkspacePlace(repo, entry.worktree);
26407
26458
  if (entry.changed || repo.path === record.conflictRepo) {
26408
26459
  repairBase[repo.path] = (await this.git(repo.root, ["rev-parse", "--verify", repo.integrationBranch])).trim();
@@ -26551,7 +26602,7 @@ var GitWorktreeIsolation = class {
26551
26602
  * out of sync, and deleting it is the one action that cannot be undone.
26552
26603
  */
26553
26604
  async worktreeHasChanges(entry, prefix) {
26554
- if (!fs16.existsSync(entry.worktree)) return false;
26605
+ if (!fs17.existsSync(entry.worktree)) return false;
26555
26606
  const status = await this.tryGit(entry.worktree, ["status", "--porcelain", "-z", "--untracked-files=normal"]);
26556
26607
  if (!status.ok) return true;
26557
26608
  const linked = new Set(entry.linked);
@@ -26957,7 +27008,7 @@ var GitWorktreeIsolation = class {
26957
27008
  for (const repo of run.repos) {
26958
27009
  const entry = record.repos[repo.path];
26959
27010
  if (!entry) continue;
26960
- if (!fs16.existsSync(entry.worktree)) {
27011
+ if (!fs17.existsSync(entry.worktree)) {
26961
27012
  return this.stopLanding(record, "failed", repo, void 0, `its worktree is gone (${entry.worktree})`);
26962
27013
  }
26963
27014
  try {
@@ -27207,7 +27258,7 @@ var GitWorktreeIsolation = class {
27207
27258
  const ref2 = `refs/heads/${repo.integrationBranch}`;
27208
27259
  if (!(await this.tryGit(repo.root, ["update-ref", ref2, made, onto])).ok) return { strayed: true };
27209
27260
  const dir = this.integrationDir(run, repo);
27210
- if (!fs16.existsSync(path38.join(dir, ".git"))) return { onto: made };
27261
+ if (!fs17.existsSync(path38.join(dir, ".git"))) return { onto: made };
27211
27262
  const read2 = await this.readAcross(dir, onto, made);
27212
27263
  if (read2.ok) return { onto: made };
27213
27264
  if (!(await this.tryGit(repo.root, ["update-ref", ref2, onto, made])).ok) return { strayed: true };
@@ -27312,7 +27363,7 @@ var GitWorktreeIsolation = class {
27312
27363
  if (!await (reverts ? this.isRevertsOn(repo, head, tip, reverts) : this.isOneMergeOn(repo, head, tip))) return false;
27313
27364
  const dir = this.integrationDir(run, repo);
27314
27365
  const held2 = await this.worktreeHolding(repo, repo.integrationBranch);
27315
- if (!held2 && (!fs16.existsSync(path38.join(dir, ".git")) || await this.integrationOffBranch(run, repo))) return false;
27366
+ if (!held2 && (!fs17.existsSync(path38.join(dir, ".git")) || await this.integrationOffBranch(run, repo))) return false;
27316
27367
  const holder = held2 ? held2.worktree : dir;
27317
27368
  if (holder === null) return (await this.tryGit(repo.root, ["update-ref", `refs/heads/${repo.integrationBranch}`, tip, head])).ok;
27318
27369
  if (!sameDir(holder, dir)) return false;
@@ -27367,7 +27418,7 @@ var GitWorktreeIsolation = class {
27367
27418
  */
27368
27419
  async integrationOffBranch(run, repo) {
27369
27420
  const dir = this.integrationDir(run, repo);
27370
- if (!fs16.existsSync(path38.join(dir, ".git"))) return null;
27421
+ if (!fs17.existsSync(path38.join(dir, ".git"))) return null;
27371
27422
  const head = (await this.tryGit(dir, ["symbolic-ref", "-q", "HEAD"])).stdout.trim();
27372
27423
  if (head === `refs/heads/${repo.integrationBranch}`) return null;
27373
27424
  return `${head ? `on ${head.replace(/^refs\/heads\//, "")}` : "detached"}, not on ${repo.integrationBranch}`;
@@ -27378,7 +27429,7 @@ var GitWorktreeIsolation = class {
27378
27429
  if (!listed4.ok) return null;
27379
27430
  let worktree = null;
27380
27431
  for (const line of listed4.stdout.split(/\r?\n/)) {
27381
- if (line.startsWith("worktree ")) worktree = line.slice("worktree ".length);
27432
+ if (line.startsWith("worktree ")) worktree = path38.normalize(line.slice("worktree ".length));
27382
27433
  else if (line === `branch refs/heads/${branch}`) return { worktree };
27383
27434
  }
27384
27435
  return { worktree: null };
@@ -27395,12 +27446,58 @@ var GitWorktreeIsolation = class {
27395
27446
  if ((await this.tryGit(entry.worktree, ["check-ignore", "-q", "--", prefix + name])).ok) continue;
27396
27447
  excludes.push(`:(exclude,literal)${(prefix + name).replace(/\\/g, "/")}`);
27397
27448
  }
27449
+ if (this.platform === "win32") {
27450
+ const made = entry.linked.map((name) => (prefix + name).replace(/\\/g, "/"));
27451
+ const under = (link) => made.some((dir) => link === dir || link.startsWith(`${dir}/`));
27452
+ for (const link of await this.linksGitWalksInto(entry.worktree)) {
27453
+ if (!under(link)) excludes.push(`:(exclude,literal)${link}`);
27454
+ }
27455
+ }
27398
27456
  await this.git(entry.worktree, ["add", "-A", "--", ".", ...excludes]);
27399
27457
  const staged = await this.tryGit(entry.worktree, ["diff", "--cached", "--quiet"]);
27400
27458
  if (staged.ok) return;
27401
27459
  const commit = opts.rescue ? ["-c", "commit.gpgsign=false", "commit", "--no-verify"] : ["commit"];
27402
27460
  await this.git(entry.worktree, [...VERBATIM, ...commit, "-q", ...messageArgs(message)]);
27403
27461
  }
27462
+ /**
27463
+ * The links git would walk into when it stages `worktree`: on Windows a
27464
+ * junction reads to git as the directory it leads to, so staging one a task
27465
+ * left commits what it holds, a folder of the user's as readily as anything.
27466
+ * A symbolic link git stages as a link, as it does elsewhere, and keeps. Read
27467
+ * from git's own listing, one call, so what git ignores, a mirrored install
27468
+ * among it, is never walked; and a link is told by lstat, as Windows reports
27469
+ * every reparse point, a OneDrive placeholder too, as a link in a directory
27470
+ * listing.
27471
+ */
27472
+ async linksGitWalksInto(worktree) {
27473
+ const listed4 = await this.tryGit(worktree, ["status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all"]);
27474
+ if (!listed4.ok) throw new Error(`git could not list what the worktree holds: ${firstLine3(listed4.stderr.trim() || `exit ${listed4.code}`)}`);
27475
+ const isLink2 = /* @__PURE__ */ new Map();
27476
+ const linkAt = (rel) => {
27477
+ let link = isLink2.get(rel);
27478
+ if (link === void 0) {
27479
+ try {
27480
+ link = fs17.lstatSync(path38.join(worktree, rel)).isSymbolicLink();
27481
+ } catch {
27482
+ link = false;
27483
+ }
27484
+ isLink2.set(rel, link);
27485
+ }
27486
+ return link;
27487
+ };
27488
+ const found = /* @__PURE__ */ new Set();
27489
+ for (const entry of listed4.stdout.split("\0")) {
27490
+ const parts = entry.slice(3).split("/");
27491
+ for (let depth = 1; depth < parts.length; depth++) {
27492
+ const dir = parts.slice(0, depth).join("/");
27493
+ if (linkAt(dir)) {
27494
+ found.add(dir);
27495
+ break;
27496
+ }
27497
+ }
27498
+ }
27499
+ return [...found];
27500
+ }
27404
27501
  /** A message Ordewell writes, with the trailer if the user's setting says so right now. */
27405
27502
  message(kind, from) {
27406
27503
  return landingMessage(kind, from, this.deps.plannedWith?.() ?? false);
@@ -27411,10 +27508,10 @@ var GitWorktreeIsolation = class {
27411
27508
  async ensureIntegrationWorktree(run, repo) {
27412
27509
  return this.admin(stateRootOf(run), async () => {
27413
27510
  const dir = this.integrationDir(run, repo);
27414
- if (fs16.existsSync(path38.join(dir, ".git"))) return dir;
27511
+ if (fs17.existsSync(path38.join(dir, ".git"))) return dir;
27415
27512
  await this.tryGit(repo.root, ["worktree", "prune"]);
27416
27513
  ensureStateDirIgnored(stateRootOf(run));
27417
- fs16.mkdirSync(path38.dirname(dir), { recursive: true });
27514
+ fs17.mkdirSync(path38.dirname(dir), { recursive: true });
27418
27515
  await this.git(repo.root, ["worktree", "add", "-q", dir, repo.integrationBranch]);
27419
27516
  return dir;
27420
27517
  });
@@ -27451,7 +27548,7 @@ var GitWorktreeIsolation = class {
27451
27548
  if (entry) await this.removeWorktreeDir(run, repo, entry.worktree, entry.linked);
27452
27549
  await this.tryGit(repo.root, ["branch", "-D", record.branch]);
27453
27550
  }
27454
- this.removeTaskWorkspace(run, record.workspace);
27551
+ await this.removeTaskWorkspace(run, record.workspace);
27455
27552
  if (opts.dropRecord) delete run.tasks[record.taskId];
27456
27553
  return removal;
27457
27554
  }
@@ -27475,7 +27572,7 @@ var GitWorktreeIsolation = class {
27475
27572
  }
27476
27573
  async tipToKeep(repo, target) {
27477
27574
  const { worktree } = target;
27478
- if (worktree && fs16.existsSync(worktree)) {
27575
+ if (worktree && fs17.existsSync(worktree)) {
27479
27576
  if (!hasGitEntry(worktree)) throw new Error("it is not a git worktree any more");
27480
27577
  if (await this.worktreeHasChanges({ worktree, linked: target.linked }, await this.prefixOf(repo))) {
27481
27578
  await this.commitWorktree(repo, { worktree, linked: target.linked }, this.message("rescue", target), { rescue: true });
@@ -27505,23 +27602,40 @@ var GitWorktreeIsolation = class {
27505
27602
  * links and the directories that held deeper repos. Links are unlinked
27506
27603
  * first, so removing the rest can never walk into the real workspace.
27507
27604
  */
27508
- removeTaskWorkspace(run, dir) {
27509
- if (!isInside(this.runRoot(run), dir) || !fs16.existsSync(dir)) return;
27605
+ async removeTaskWorkspace(run, dir) {
27606
+ if (!isInside(this.runRoot(run), dir) || !fs17.existsSync(dir)) return;
27510
27607
  this.unlinkLinksUnder(dir);
27511
27608
  clearImmutableFlags(this.platform, dir);
27512
- fs16.rmSync(dir, { recursive: true, force: true });
27609
+ await this.removeDir(dir);
27610
+ }
27611
+ /**
27612
+ * Windows removes no directory a process works in, and a runner stopped
27613
+ * there a moment ago may still be going: taskkill ends it from another
27614
+ * process. So there the removal waits for it, a while, before it gives up.
27615
+ */
27616
+ async removeDir(dir) {
27617
+ if (this.platform === "win32") await fs17.promises.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
27618
+ else fs17.rmSync(dir, { recursive: true, force: true });
27513
27619
  }
27514
27620
  unlinkLinksUnder(dir) {
27515
27621
  let entries;
27516
27622
  try {
27517
- entries = fs16.readdirSync(dir, { withFileTypes: true });
27623
+ entries = fs17.readdirSync(dir, { withFileTypes: true });
27518
27624
  } catch {
27519
27625
  return;
27520
27626
  }
27521
27627
  for (const entry of entries) {
27522
27628
  const target = path38.join(dir, entry.name);
27523
- if (entry.isSymbolicLink()) this.unlinkIfLink(target);
27524
- else if (entry.isDirectory()) this.unlinkLinksUnder(target);
27629
+ if (entry.isDirectory()) this.unlinkLinksUnder(target);
27630
+ else if (entry.isSymbolicLink()) {
27631
+ let stat;
27632
+ try {
27633
+ stat = fs17.lstatSync(target);
27634
+ } catch {
27635
+ }
27636
+ if (stat?.isSymbolicLink()) this.unlinkIfLink(target);
27637
+ else if (stat?.isDirectory()) this.unlinkLinksUnder(target);
27638
+ }
27525
27639
  }
27526
27640
  }
27527
27641
  /**
@@ -27543,8 +27657,8 @@ var GitWorktreeIsolation = class {
27543
27657
  };
27544
27658
  const owned = new Set(Object.values(run.tasks).map((r) => path38.resolve(r.workspace)));
27545
27659
  const root = this.runRoot(run);
27546
- if (fs16.existsSync(root)) {
27547
- for (const entry of fs16.readdirSync(root)) {
27660
+ if (fs17.existsSync(root)) {
27661
+ for (const entry of fs17.readdirSync(root)) {
27548
27662
  const dir = path38.join(root, entry);
27549
27663
  if (entry === INTEGRATION_DIR || owned.has(path38.resolve(dir))) continue;
27550
27664
  let kept = true;
@@ -27555,7 +27669,7 @@ var GitWorktreeIsolation = class {
27555
27669
  }
27556
27670
  if (!kept) continue;
27557
27671
  for (const repo of run.repos) await this.removeWorktreeDir(run, repo, path38.join(dir, repo.path), []);
27558
- this.removeTaskWorkspace(run, dir);
27672
+ await this.removeTaskWorkspace(run, dir);
27559
27673
  }
27560
27674
  }
27561
27675
  const taskBranches = Object.values(run.tasks).map((r) => r.branch);
@@ -27571,32 +27685,36 @@ var GitWorktreeIsolation = class {
27571
27685
  return removal;
27572
27686
  }
27573
27687
  async removeWorktreeDir(run, repo, dir, linked) {
27574
- for (const name of /* @__PURE__ */ new Set([...linked, ...installDirs(dir)])) {
27575
- const target = path38.join(dir, name);
27576
- if (!resolvesAsNamed(this.runRoot(run), path38.dirname(target))) continue;
27577
- this.unlinkIfLink(target);
27578
- this.unlinkLinksUnder(target);
27579
- }
27580
- for (const name of resolvesAsNamed(this.runRoot(run), dir) ? fs16.readdirSync(dir) : []) {
27581
- if (LINKED_ARTIFACTS.has(name) || isEnvFile(name)) this.unlinkIfLink(path38.join(dir, name));
27688
+ const prefix = (await this.tryGit(repo.root, ["rev-parse", "--show-prefix"])).stdout.trim();
27689
+ for (const base of /* @__PURE__ */ new Set([dir, path38.join(dir, prefix)])) {
27690
+ for (const name of /* @__PURE__ */ new Set([...linked, ...installDirs(base)])) {
27691
+ const target = path38.join(base, name);
27692
+ if (!resolvesAsNamed(this.runRoot(run), path38.dirname(target))) continue;
27693
+ this.unlinkIfLink(target);
27694
+ this.unlinkLinksUnder(target);
27695
+ }
27696
+ for (const name of resolvesAsNamed(this.runRoot(run), base) ? fs17.readdirSync(base) : []) {
27697
+ if (LINKED_ARTIFACTS.has(name) || isEnvFile(name)) this.unlinkIfLink(path38.join(base, name));
27698
+ }
27582
27699
  }
27700
+ if (this.platform === "win32" && resolvesAsNamed(this.runRoot(run), dir)) this.unlinkLinksUnder(dir);
27583
27701
  await this.tryGit(repo.root, ["worktree", "remove", "--force", dir]);
27584
- if (fs16.existsSync(dir) && isInside(this.runRoot(run), dir)) {
27702
+ if (fs17.existsSync(dir) && isInside(this.runRoot(run), dir)) {
27585
27703
  clearImmutableFlags(this.platform, dir);
27586
- fs16.rmSync(dir, { recursive: true, force: true });
27704
+ await this.removeDir(dir);
27587
27705
  }
27588
27706
  await this.tryGit(repo.root, ["worktree", "prune"]);
27589
27707
  for (let parent = path38.dirname(dir); isInside(this.runRoot(run), parent); parent = path38.dirname(parent)) this.removeIfEmpty(parent);
27590
27708
  }
27591
27709
  unlinkIfLink(target) {
27592
27710
  try {
27593
- if (fs16.lstatSync(target).isSymbolicLink()) fs16.rmSync(target, { force: true });
27711
+ if (fs17.lstatSync(target).isSymbolicLink()) fs17.rmSync(target, { force: true });
27594
27712
  } catch {
27595
27713
  }
27596
27714
  }
27597
27715
  removeIfEmpty(dir) {
27598
27716
  try {
27599
- fs16.rmdirSync(dir);
27717
+ fs17.rmdirSync(dir);
27600
27718
  } catch {
27601
27719
  }
27602
27720
  }
@@ -27623,7 +27741,7 @@ var GitWorktreeIsolation = class {
27623
27741
  async rebaseInProgress(cwd) {
27624
27742
  for (const dir of ["rebase-merge", "rebase-apply"]) {
27625
27743
  const found = await this.tryGit(cwd, ["rev-parse", "--git-path", dir]);
27626
- if (found.ok && fs16.existsSync(path38.resolve(cwd, found.stdout.trim()))) return true;
27744
+ if (found.ok && fs17.existsSync(path38.resolve(cwd, found.stdout.trim()))) return true;
27627
27745
  }
27628
27746
  return false;
27629
27747
  }
@@ -27654,7 +27772,7 @@ function createWorktreeIsolation(deps) {
27654
27772
  }
27655
27773
 
27656
27774
  // src/utils/sessionStore.ts
27657
- import * as fs17 from "fs";
27775
+ import * as fs18 from "fs";
27658
27776
  import * as path39 from "path";
27659
27777
 
27660
27778
  // src/interfaces/ILogger.ts
@@ -27708,7 +27826,7 @@ var NO_RESEARCH_LOG = [];
27708
27826
  var writtenLogs = /* @__PURE__ */ new Map();
27709
27827
  function saveResearchLog(log, file) {
27710
27828
  const written = writtenLogs.get(file);
27711
- const unchanged = fs17.existsSync(file) ? written?.log.deref() === log && written.length === log.length : log.length === 0;
27829
+ const unchanged = fs18.existsSync(file) ? written?.log.deref() === log && written.length === log.length : log.length === 0;
27712
27830
  if (unchanged) return;
27713
27831
  writeFileAtomic(file, JSON.stringify(log));
27714
27832
  writtenLogs.set(file, { log: new WeakRef(log), length: log.length });
@@ -27716,7 +27834,7 @@ function saveResearchLog(log, file) {
27716
27834
  function restoreResearchLog(plan, sessionId, file, logger) {
27717
27835
  if (plan.researchLog) return;
27718
27836
  try {
27719
- plan.researchLog = JSON.parse(fs17.readFileSync(file, "utf-8"));
27837
+ plan.researchLog = JSON.parse(fs18.readFileSync(file, "utf-8"));
27720
27838
  } catch (err) {
27721
27839
  if (err.code !== "ENOENT") logger.warn("sessionStore", `failed to read the research log of ${sessionId}; going on without it`, err);
27722
27840
  }
@@ -27747,10 +27865,10 @@ function legacySessionFilename(session) {
27747
27865
  }
27748
27866
  function dropLegacyFile(sessionsDir, meta) {
27749
27867
  const legacy = path39.join(sessionsDir, legacySessionFilename(meta));
27750
- if (legacy === path39.join(sessionsDir, sessionFilename(meta)) || !fs17.existsSync(legacy)) return;
27868
+ if (legacy === path39.join(sessionsDir, sessionFilename(meta)) || !fs18.existsSync(legacy)) return;
27751
27869
  try {
27752
- const held2 = JSON.parse(fs17.readFileSync(legacy, "utf-8")).meta?.id;
27753
- if (held2 === meta.id) fs17.unlinkSync(legacy);
27870
+ const held2 = JSON.parse(fs18.readFileSync(legacy, "utf-8")).meta?.id;
27871
+ if (held2 === meta.id) fs18.unlinkSync(legacy);
27754
27872
  } catch {
27755
27873
  }
27756
27874
  }
@@ -27792,7 +27910,7 @@ function listChildSessions(rootSessionId, baseDir) {
27792
27910
  const dir = childSessionsDir(rootSessionId, baseDir);
27793
27911
  const named3 = (entry) => {
27794
27912
  try {
27795
- const session = JSON.parse(fs17.readFileSync(path39.join(dir, entry, CHILD_SESSION_FILE), "utf-8"));
27913
+ const session = JSON.parse(fs18.readFileSync(path39.join(dir, entry, CHILD_SESSION_FILE), "utf-8"));
27796
27914
  return isSessionMeta(session.meta) ? session.meta.id : null;
27797
27915
  } catch {
27798
27916
  return null;
@@ -27800,7 +27918,7 @@ function listChildSessions(rootSessionId, baseDir) {
27800
27918
  };
27801
27919
  let entries;
27802
27920
  try {
27803
- entries = fs17.readdirSync(dir);
27921
+ entries = fs18.readdirSync(dir);
27804
27922
  } catch {
27805
27923
  return [];
27806
27924
  }
@@ -27808,12 +27926,12 @@ function listChildSessions(rootSessionId, baseDir) {
27808
27926
  }
27809
27927
  function listSessions(baseDir, logger = defaultLogger) {
27810
27928
  const sessionsDir = getSessionsDir(baseDir);
27811
- if (!fs17.existsSync(sessionsDir)) return [];
27812
- const files = fs17.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
27929
+ if (!fs18.existsSync(sessionsDir)) return [];
27930
+ const files = fs18.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
27813
27931
  return files.map((f) => {
27814
27932
  let parsed;
27815
27933
  try {
27816
- parsed = JSON.parse(fs17.readFileSync(path39.join(sessionsDir, f), "utf-8"));
27934
+ parsed = JSON.parse(fs18.readFileSync(path39.join(sessionsDir, f), "utf-8"));
27817
27935
  } catch (err) {
27818
27936
  if (err instanceof SyntaxError) return moveAside(sessionsDir, f, "is not valid JSON", logger);
27819
27937
  logger.warn("sessionStore", `failed to read session file ${f}; skipping`, err);
@@ -27834,7 +27952,7 @@ function listSessions(baseDir, logger = defaultLogger) {
27834
27952
  function moveAside(sessionsDir, file, reason, logger) {
27835
27953
  const aside = `${file}.${Date.now()}.corrupt`;
27836
27954
  try {
27837
- fs17.renameSync(path39.join(sessionsDir, file), path39.join(sessionsDir, aside));
27955
+ fs18.renameSync(path39.join(sessionsDir, file), path39.join(sessionsDir, aside));
27838
27956
  logger.warn("sessionStore", `session file ${file} ${reason}; moved aside to ${aside} rather than overwritten`);
27839
27957
  } catch {
27840
27958
  logger.warn("sessionStore", `failed to read session file ${file}; skipping`);
@@ -27843,12 +27961,12 @@ function moveAside(sessionsDir, file, reason, logger) {
27843
27961
  }
27844
27962
  var filenameEndings = (sessionId) => [sessionId.replace(/^session-/, ""), sessionId].map((id2) => `_${id2.slice(0, 8)}.json`);
27845
27963
  function findSessionFile(sessionsDir, sessionId, logger) {
27846
- const files = fs17.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
27964
+ const files = fs18.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
27847
27965
  const endings = filenameEndings(sessionId);
27848
27966
  const named3 = files.filter((f) => endings.some((ending) => f.endsWith(ending)));
27849
27967
  for (const file of /* @__PURE__ */ new Set([...named3, ...files])) {
27850
27968
  try {
27851
- const session = JSON.parse(fs17.readFileSync(path39.join(sessionsDir, file), "utf-8"));
27969
+ const session = JSON.parse(fs18.readFileSync(path39.join(sessionsDir, file), "utf-8"));
27852
27970
  if (session.meta.id === sessionId) return { file, session };
27853
27971
  } catch (err) {
27854
27972
  logger.warn("sessionStore", `failed to read session file ${file}; skipping`, err);
@@ -27870,7 +27988,7 @@ function settledOnLoad(session, researchLog, logger) {
27870
27988
  function loadChildSession(place, logger = defaultLogger) {
27871
27989
  let parsed;
27872
27990
  try {
27873
- parsed = JSON.parse(fs17.readFileSync(childSessionPath(place), "utf-8"));
27991
+ parsed = JSON.parse(fs18.readFileSync(childSessionPath(place), "utf-8"));
27874
27992
  } catch (err) {
27875
27993
  if (err.code !== "ENOENT") logger.warn("sessionStore", `failed to read child session ${place.sessionId}`, err);
27876
27994
  return null;
@@ -27880,7 +27998,7 @@ function loadChildSession(place, logger = defaultLogger) {
27880
27998
  }
27881
27999
  function loadSession(sessionId, baseDir, logger = defaultLogger) {
27882
28000
  const sessionsDir = getSessionsDir(baseDir);
27883
- if (!fs17.existsSync(sessionsDir)) return null;
28001
+ if (!fs18.existsSync(sessionsDir)) return null;
27884
28002
  try {
27885
28003
  const found = findSessionFile(sessionsDir, sessionId, logger);
27886
28004
  if (found) {
@@ -27907,16 +28025,16 @@ function getLatestSession(baseDir, logger = defaultLogger) {
27907
28025
  }
27908
28026
  function deleteSession(sessionId, baseDir, logger = defaultLogger) {
27909
28027
  const sessionsDir = getSessionsDir(baseDir);
27910
- if (!fs17.existsSync(sessionsDir)) return false;
28028
+ if (!fs18.existsSync(sessionsDir)) return false;
27911
28029
  try {
27912
- fs17.rmSync(sessionDataDir(sessionId, baseDir), { recursive: true, force: true });
28030
+ fs18.rmSync(sessionDataDir(sessionId, baseDir), { recursive: true, force: true });
27913
28031
  } catch (err) {
27914
28032
  logger.warn("sessionStore", `failed to remove the task logs of ${sessionId}`, err);
27915
28033
  }
27916
28034
  try {
27917
28035
  const found = findSessionFile(sessionsDir, sessionId, logger);
27918
28036
  if (found) {
27919
- fs17.unlinkSync(path39.join(sessionsDir, found.file));
28037
+ fs18.unlinkSync(path39.join(sessionsDir, found.file));
27920
28038
  return true;
27921
28039
  }
27922
28040
  } catch (err) {
@@ -27976,8 +28094,8 @@ import { v4 as uuidv43 } from "uuid";
27976
28094
 
27977
28095
  // src/services/ContextCollector.ts
27978
28096
  var ORDEWELL_CONTEXT_MAX = 8e3;
27979
- async function collectResearchContext(fs28, runners) {
27980
- const collector = new ContextCollector(fs28);
28097
+ async function collectResearchContext(fs29, runners) {
28098
+ const collector = new ContextCollector(fs29);
27981
28099
  let contextStr = "";
27982
28100
  let firstContext = null;
27983
28101
  for (const r of runners) {
@@ -28004,8 +28122,8 @@ ${firstContext.dirStructure}
28004
28122
  return contextStr;
28005
28123
  }
28006
28124
  var ContextCollector = class {
28007
- constructor(fs28, registry) {
28008
- this.fs = fs28;
28125
+ constructor(fs29, registry) {
28126
+ this.fs = fs29;
28009
28127
  this.registry = registry;
28010
28128
  }
28011
28129
  fs;
@@ -28053,28 +28171,28 @@ var ALLOWED_TOOL_NAMES = new Set(subagentToolSpecs().map((t) => t.name));
28053
28171
  function refused2(output) {
28054
28172
  return { success: false, output, truncated: false };
28055
28173
  }
28056
- function nonPromptingFs(fs28) {
28057
- const withinWorkspace = (p) => resolveWithin(fs28.getWorkspaceRoot(), p ?? ".").inside;
28174
+ function nonPromptingFs(fs29) {
28175
+ const withinWorkspace = (p) => resolveWithin(fs29.getWorkspaceRoot(), p ?? ".").inside;
28058
28176
  const outsideRefusal = (p) => refused2(
28059
28177
  `Path "${p}" is outside the workspace. Research agents are confined to the workspace root \u2014 note the gap in your digest and let the planner request it directly.`
28060
28178
  );
28061
28179
  return {
28062
- getWorkspaceRoot: () => fs28.getWorkspaceRoot(),
28063
- readFile: (p, opts) => withinWorkspace(p) ? fs28.readFile(p, opts) : Promise.resolve(outsideRefusal(p)),
28180
+ getWorkspaceRoot: () => fs29.getWorkspaceRoot(),
28181
+ readFile: (p, opts) => withinWorkspace(p) ? fs29.readFile(p, opts) : Promise.resolve(outsideRefusal(p)),
28064
28182
  readFiles: (paths) => {
28065
28183
  const escaping = paths.find((p) => !withinWorkspace(p));
28066
- return escaping ? Promise.resolve(outsideRefusal(escaping)) : fs28.readFiles(paths);
28184
+ return escaping ? Promise.resolve(outsideRefusal(escaping)) : fs29.readFiles(paths);
28067
28185
  },
28068
- glob: (pattern, opts) => withinWorkspace(opts?.path) ? fs28.glob(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
28069
- grep: (pattern, opts) => withinWorkspace(opts?.path) ? fs28.grep(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
28070
- findSymbol: (symbol, opts) => withinWorkspace(opts?.path) ? fs28.findSymbol(symbol, opts) : Promise.resolve(outsideRefusal(opts.path)),
28071
- listDir: (p, depth) => withinWorkspace(p) ? fs28.listDir(p, depth) : Promise.resolve(outsideRefusal(p)),
28186
+ glob: (pattern, opts) => withinWorkspace(opts?.path) ? fs29.glob(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
28187
+ grep: (pattern, opts) => withinWorkspace(opts?.path) ? fs29.grep(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
28188
+ findSymbol: (symbol, opts) => withinWorkspace(opts?.path) ? fs29.findSymbol(symbol, opts) : Promise.resolve(outsideRefusal(opts.path)),
28189
+ listDir: (p, depth) => withinWorkspace(p) ? fs29.listDir(p, depth) : Promise.resolve(outsideRefusal(p)),
28072
28190
  bash: async (command, signal, opts) => {
28073
28191
  const policy = researchPolicyOptions(resolveResearchShell());
28074
28192
  const { tier, reason } = classifyCommand(command, policy);
28075
- const escaping = pathRefs(command, policy).map((ref2) => resolveRef(fs28.getWorkspaceRoot(), ref2)).find((r) => !r.inside);
28076
- if (tier === "auto" && !escaping && !opts?.sealed) return fs28.bash(command, signal);
28077
- if (opts?.sealed || await fs28.canSeal?.()) return fs28.bash(command, signal, { sealed: true });
28193
+ const escaping = pathRefs(command, policy).map((ref2) => resolveRef(fs29.getWorkspaceRoot(), ref2)).find((r) => !r.inside);
28194
+ if (tier === "auto" && !escaping && !opts?.sealed) return fs29.bash(command, signal);
28195
+ if (opts?.sealed || await fs29.canSeal?.()) return fs29.bash(command, signal, { sealed: true });
28078
28196
  if (tier === "refuse") return refused2(`Command refused: ${reason}`);
28079
28197
  if (tier === "auto" && escaping) return outsideRefusal(escaping.abs);
28080
28198
  return refused2(`"${command}" needs user approval, and research agents run in the background where nothing can be approved. Use the read-only research tools, and note in your digest that this command would answer the question.`);
@@ -28086,7 +28204,7 @@ function withoutContext({ contextTokens: _context, ...record }) {
28086
28204
  }
28087
28205
  async function runLoop(prompt, deps) {
28088
28206
  if (deps.signal?.aborted) return "[research agent aborted before starting]";
28089
- const fs28 = nonPromptingFs(deps.fs);
28207
+ const fs29 = nonPromptingFs(deps.fs);
28090
28208
  const chat = deps.createChat(
28091
28209
  (delta) => deps.onProgress?.({ type: "thinking", text: delta, subagentId: deps.subagentId }),
28092
28210
  // The record says who made the call: unstamped, the ledger would read the
@@ -28109,7 +28227,7 @@ ${turn.text}`;
28109
28227
  if (tc.name === "read_file" && !("maxBytes" in args) && !("limit" in args)) args.limit = 2e3;
28110
28228
  const toolArgs = JSON.stringify(tc.args);
28111
28229
  deps.onProgress?.({ type: "tool_call", tool: tc.name, toolArgs, toolCallId: tc.id, subagentId: deps.subagentId });
28112
- const res = await executeTool(tc.name, args, fs28, deps.fetcher, deps.signal);
28230
+ const res = await executeTool(tc.name, args, fs29, deps.fetcher, deps.signal);
28113
28231
  const output = res.output.length > SUBAGENT_LIMITS.toolOutputMaxChars ? res.output.slice(0, SUBAGENT_LIMITS.toolOutputMaxChars) + `
28114
28232
  [... truncated to ${SUBAGENT_LIMITS.toolOutputMaxChars} chars, total ${res.output.length}]` : res.output;
28115
28233
  const stepEntry = {
@@ -28317,7 +28435,7 @@ var BaseAiService = class _BaseAiService {
28317
28435
  * steering/failed result and the loop continues sequentially: a subagent can
28318
28436
  * never fail a plan or a turn.
28319
28437
  */
28320
- async executeSpawnAgent(args, fs28, onProgress, signal, subagentId, fetcher) {
28438
+ async executeSpawnAgent(args, fs29, onProgress, signal, subagentId, fetcher) {
28321
28439
  const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
28322
28440
  if (!prompt) {
28323
28441
  return { success: false, output: 'spawn_research_agent requires a non-empty "prompt" string: a self-contained task for the agent, including what its digest must report back.', truncated: false };
@@ -28329,7 +28447,7 @@ var BaseAiService = class _BaseAiService {
28329
28447
  if (!chat) throw new Error("subagent chats are not available for this provider");
28330
28448
  return chat;
28331
28449
  },
28332
- fs: fs28,
28450
+ fs: fs29,
28333
28451
  signal,
28334
28452
  subagentId,
28335
28453
  // The subagent gets web tools only behind a non-prompting gate: no
@@ -28345,14 +28463,14 @@ var BaseAiService = class _BaseAiService {
28345
28463
  });
28346
28464
  }
28347
28465
  /** Collect project context for the planning phase. Shared with the harness backend. */
28348
- static async collectResearchContext(fs28, runners) {
28349
- return collectResearchContext(fs28, runners);
28466
+ static async collectResearchContext(fs29, runners) {
28467
+ return collectResearchContext(fs29, runners);
28350
28468
  }
28351
28469
  /**
28352
28470
  * Execute one round of tool calls and report each through onProgress.
28353
28471
  * Returns the results to feed back plus the log entries produced.
28354
28472
  */
28355
- async executeToolCalls(toolCalls, fs28, onProgress, fetcher, stepIndex, thinking, signal, plannerTools) {
28473
+ async executeToolCalls(toolCalls, fs29, onProgress, fetcher, stepIndex, thinking, signal, plannerTools) {
28356
28474
  const toolResults = [];
28357
28475
  const logEntries = [];
28358
28476
  let resultsText = "";
@@ -28373,12 +28491,12 @@ var BaseAiService = class _BaseAiService {
28373
28491
  spawnSubagentIds.set(i, subagentId);
28374
28492
  announcedAt.set(i, (/* @__PURE__ */ new Date()).toISOString());
28375
28493
  onProgress({ type: "tool_call", tool: toolCalls[i].name, toolArgs: JSON.stringify(toolCalls[i].args), subagentId, toolCallId: toolCalls[i].id });
28376
- precomputed.set(i, await this.executeSpawnAgent({ ...toolCalls[i].args }, fs28, onProgress, signal, subagentId, fetcher));
28494
+ precomputed.set(i, await this.executeSpawnAgent({ ...toolCalls[i].args }, fs29, onProgress, signal, subagentId, fetcher));
28377
28495
  }) : Promise.resolve(),
28378
28496
  parallelIndexes.length > 1 ? mapWithConcurrency(parallelIndexes, TOOL_ROUND_CONCURRENCY, async (i) => {
28379
28497
  announcedAt.set(i, (/* @__PURE__ */ new Date()).toISOString());
28380
28498
  onProgress({ type: "tool_call", tool: toolCalls[i].name, toolArgs: JSON.stringify(toolCalls[i].args), toolCallId: toolCalls[i].id });
28381
- precomputed.set(i, await executeTool(toolCalls[i].name, normalizedArgs[i], fs28, fetcher, signal));
28499
+ precomputed.set(i, await executeTool(toolCalls[i].name, normalizedArgs[i], fs29, fetcher, signal));
28382
28500
  }) : Promise.resolve()
28383
28501
  ]);
28384
28502
  for (const [index, tc] of toolCalls.entries()) {
@@ -28389,7 +28507,7 @@ var BaseAiService = class _BaseAiService {
28389
28507
  announcedAt.set(index, (/* @__PURE__ */ new Date()).toISOString());
28390
28508
  onProgress({ type: "tool_call", ...named3, toolArgs: JSON.stringify(tc.args), toolCallId: tc.id });
28391
28509
  }
28392
- const toolResult = preResult ?? await callPlannerTool(plannerTools, tc.name, toolArgs, signal) ?? await executeTool(tc.name, toolArgs, fs28, fetcher, signal);
28510
+ const toolResult = preResult ?? await callPlannerTool(plannerTools, tc.name, toolArgs, signal) ?? await executeTool(tc.name, toolArgs, fs29, fetcher, signal);
28393
28511
  const MAX_RESPONSE_CHARS = 5e4;
28394
28512
  const truncatedResponse = toolResult.success && (toolResult.truncated || toolResult.output.length > MAX_RESPONSE_CHARS);
28395
28513
  const llmOutput = toolResult.output.length > MAX_RESPONSE_CHARS ? toolResult.output.slice(0, MAX_RESPONSE_CHARS) + `
@@ -28562,7 +28680,7 @@ ${llmOutput}
28562
28680
  * parsed tasks if a plan was emitted mid-loop, or null if the loop
28563
28681
  * exhausted without a valid plan.
28564
28682
  */
28565
- async runResearchLoop(chat, firstMessage, fs28, onProgress, runners, initialLog, fetcher, userGoal, runnerModes, autonomousDefault, signal) {
28683
+ async runResearchLoop(chat, firstMessage, fs29, onProgress, runners, initialLog, fetcher, userGoal, runnerModes, autonomousDefault, signal) {
28566
28684
  const researchLog = initialLog ? [...initialLog] : [];
28567
28685
  if (!initialLog && userGoal) {
28568
28686
  researchLog.push({
@@ -28588,7 +28706,7 @@ ${llmOutput}
28588
28706
  if (!turn.hasToolCalls) break;
28589
28707
  const { toolResults, logEntries, resultsText } = await this.executeToolCalls(
28590
28708
  turn.toolCalls,
28591
- fs28,
28709
+ fs29,
28592
28710
  onProgress,
28593
28711
  fetcher,
28594
28712
  step,
@@ -28637,15 +28755,15 @@ import {
28637
28755
  import { execFile as execFile5 } from "child_process";
28638
28756
  import { resolve as resolve12 } from "path";
28639
28757
  var AUTH_TIMEOUT_MS = 8e3;
28640
- var defaultExec3 = (command, args, options) => new Promise((resolve17) => {
28758
+ var defaultExec3 = (command, args, options) => new Promise((resolve18) => {
28641
28759
  let settled = false;
28642
28760
  const settle = (result) => {
28643
28761
  if (settled) return;
28644
28762
  settled = true;
28645
28763
  clearTimeout(timer);
28646
- resolve17(result);
28764
+ resolve18(result);
28647
28765
  };
28648
- const child = execFile5(command, args, { timeout: options.timeout, env: options.env, encoding: "utf8" }, (err, stdout, stderr) => {
28766
+ const child = execFile5(command, args, { timeout: options.timeout, env: options.env, encoding: "utf8", windowsVerbatimArguments: options.verbatim }, (err, stdout, stderr) => {
28649
28767
  const raw = err?.code;
28650
28768
  const code = err ? typeof raw === "number" ? raw : -1 : 0;
28651
28769
  settle({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
@@ -28670,9 +28788,11 @@ async function readRunnerAuth(manifest, options = {}) {
28670
28788
  let env;
28671
28789
  try {
28672
28790
  env = withPath(process.env, await augmentedPath(), options.env ?? {});
28673
- answer2 = await (options.exec ?? defaultExec3)(command, spec.statusArgs, {
28791
+ const launch = await planDirectLaunch(command, spec.statusArgs, options.launch);
28792
+ answer2 = await (options.exec ?? defaultExec3)(launch.file, launch.args, {
28674
28793
  timeout: options.timeoutMs ?? AUTH_TIMEOUT_MS,
28675
- env
28794
+ env,
28795
+ ...launch.verbatim ? { verbatim: true } : {}
28676
28796
  });
28677
28797
  } catch {
28678
28798
  return { state: "unknown", loginCommand };
@@ -29755,10 +29875,10 @@ ${repairHint}` }] : parts;
29755
29875
  }, { signal });
29756
29876
  }
29757
29877
  // --- IAiService implementation ---
29758
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
29878
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
29759
29879
  this.ensureInit();
29760
29880
  const { autonomousDefault } = modes;
29761
- const contextStr = await BaseAiService.collectResearchContext(fs28, runners);
29881
+ const contextStr = await BaseAiService.collectResearchContext(fs29, runners);
29762
29882
  const systemPrompt = buildResearchPrompt(userDescription, contextStr, modelsByRunner, runners, runnerModes, modes);
29763
29883
  const firstMessage = `${buildResearchToolsPrompt(false)}
29764
29884
 
@@ -29766,17 +29886,17 @@ Explore the workspace to understand the codebase, then generate the plan.`;
29766
29886
  const researchChat = this.chat([{ role: "user", content: systemPrompt }], [{ functionDeclarations: TOOL_DEFINITIONS }], {
29767
29887
  onUsage: (record) => onProgress({ type: "usage", record })
29768
29888
  });
29769
- const result = await this.runResearchLoop(researchChat, firstMessage, fs28, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
29889
+ const result = await this.runResearchLoop(researchChat, firstMessage, fs29, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
29770
29890
  if (result.tasks) return { tasks: result.tasks, researchLog: result.researchLog, researchResults: result.researchResults };
29771
29891
  const fallback = await this.generatePlanFallback(userDescription, contextStr, result.researchResults, modelsByRunner, runners, onProgress, result.researchLog, runnerModes, autonomousDefault, signal, modes);
29772
29892
  return { tasks: fallback.tasks, researchLog: fallback.researchLog, researchResults: result.researchResults };
29773
29893
  }
29774
- async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs28, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
29894
+ async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs29, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
29775
29895
  this.ensureInit();
29776
29896
  const { autonomousDefault } = modes;
29777
29897
  let ctx = "";
29778
- if (fs28) {
29779
- const collected = await new ContextCollector(fs28).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
29898
+ if (fs29) {
29899
+ const collected = await new ContextCollector(fs29).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
29780
29900
  if (collected.aiflowContext) ctx = `
29781
29901
  <aiflow_context>
29782
29902
  ${collected.aiflowContext}
@@ -30143,10 +30263,10 @@ ${buildResearchToolsPrompt()}` }
30143
30263
  }
30144
30264
  }
30145
30265
  // --- IAiService implementation ---
30146
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30266
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30147
30267
  this.ensureInit();
30148
30268
  const { autonomousDefault } = modes;
30149
- const contextStr = await BaseAiService.collectResearchContext(fs28, runners);
30269
+ const contextStr = await BaseAiService.collectResearchContext(fs29, runners);
30150
30270
  const systemPrompt = buildResearchPrompt(userDescription, contextStr, modelsByRunner, runners, runnerModes, modes);
30151
30271
  const userText = `User goal: ${userDescription}`;
30152
30272
  const firstMessage = `${buildResearchToolsPrompt()}
@@ -30166,17 +30286,17 @@ ${userText}`;
30166
30286
  onUsage: (record) => onProgress({ type: "usage", record }),
30167
30287
  budget: this.plannerBudget()
30168
30288
  });
30169
- const result = await this.runResearchLoop(researchChat, firstMessage, fs28, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
30289
+ const result = await this.runResearchLoop(researchChat, firstMessage, fs29, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
30170
30290
  if (result.tasks) return { tasks: result.tasks, researchLog: result.researchLog, researchResults: result.researchResults };
30171
30291
  const fallback = await this.generatePlanFallback(userDescription, contextStr, result.researchResults, modelsByRunner, runners, onProgress, result.researchLog, runnerModes, autonomousDefault, signal, modes);
30172
30292
  return { tasks: fallback.tasks, researchLog: fallback.researchLog, researchResults: result.researchResults };
30173
30293
  }
30174
- async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs28, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30294
+ async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs29, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30175
30295
  this.ensureInit();
30176
30296
  const { autonomousDefault } = modes;
30177
30297
  let ctx = "";
30178
- if (fs28) {
30179
- const collected = await new ContextCollector(fs28).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
30298
+ if (fs29) {
30299
+ const collected = await new ContextCollector(fs29).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
30180
30300
  if (collected.aiflowContext) ctx = `
30181
30301
  <aiflow_context>
30182
30302
  ${collected.aiflowContext}
@@ -31024,7 +31144,7 @@ var PlanEditError = class extends Error {
31024
31144
  };
31025
31145
 
31026
31146
  // src/services/sessionLease.ts
31027
- import * as fs18 from "fs";
31147
+ import * as fs19 from "fs";
31028
31148
  import * as path40 from "path";
31029
31149
  import { randomUUID as randomUUID6 } from "crypto";
31030
31150
  var LEASE_HEARTBEAT_MS = 1e4;
@@ -31093,7 +31213,7 @@ function isRecord6(value) {
31093
31213
  function readRecord(file) {
31094
31214
  let raw;
31095
31215
  try {
31096
- raw = fs18.readFileSync(file, "utf8");
31216
+ raw = fs19.readFileSync(file, "utf8");
31097
31217
  } catch (err) {
31098
31218
  if (err.code === "ENOENT") return null;
31099
31219
  throw err;
@@ -31225,9 +31345,9 @@ var LeaseHost = class {
31225
31345
  if (this.held.size === 0) this.stopHeartbeat();
31226
31346
  try {
31227
31347
  withFileLock(file, () => {
31228
- if (readRecord(file)?.hostId === this.id) fs18.rmSync(file, { force: true });
31348
+ if (readRecord(file)?.hostId === this.id) fs19.rmSync(file, { force: true });
31229
31349
  }, "release a session lease");
31230
- fs18.rmdirSync(path40.dirname(file));
31350
+ fs19.rmdirSync(path40.dirname(file));
31231
31351
  } catch {
31232
31352
  }
31233
31353
  }
@@ -31363,8 +31483,9 @@ function preservedNotice(kept) {
31363
31483
  const owner = first.task ? `Task "${first.task.title}"` : "A leftover task workspace no record accounted for";
31364
31484
  return `${owner} had work that never landed, so before its worktree was removed it was kept on branch ${first.branch}${where}. \`git log ${first.branch}\` shows it; merge or cherry-pick it to bring it back, and delete the branch once you no longer need it.`;
31365
31485
  }
31366
- function refusedNotice(worktree, reason, task2) {
31367
- return `Left ${task2 ? `the worktree of task "${task2.title}"` : "a leftover worktree"} in place at ${worktree}: it holds work Ordewell could not keep (${reason}). Save what you need from it, then remove it with \`git worktree remove --force ${worktree}\`.`;
31486
+ function refusedNotice(worktree, reason, task2, platform = process.platform) {
31487
+ const remove = platform === "win32" ? `remove it with \`rmdir /s /q "${worktree}"\` in a Command Prompt, then \`git worktree prune\`` : `remove it with \`git worktree remove --force ${worktree}\``;
31488
+ return `Left ${task2 ? `the worktree of task "${task2.title}"` : "a leftover worktree"} in place at ${worktree}: it holds work Ordewell could not keep (${reason}). Save what you need from it, then ${remove}.`;
31368
31489
  }
31369
31490
  function sharedPathsNotice(run) {
31370
31491
  if (run.repos.some((r) => r.path === SELF_REPO)) {
@@ -32744,16 +32865,27 @@ function liveConfig(dir) {
32744
32865
  const selected = new Set(repositoryRunnerConfigPaths([...found.keys()]));
32745
32866
  return new Map([...found].filter(([name]) => selected.has(name)));
32746
32867
  }
32747
- function linkedRoots(dir) {
32868
+ function linkedRoots(dir, checkout) {
32748
32869
  const linked = /* @__PURE__ */ new Set();
32749
32870
  for (const root of RUNNER_CONFIG_ROOTS) {
32750
32871
  try {
32751
- if (lstatSync4(path41.join(dir, root)).isSymbolicLink()) linked.add(root);
32872
+ const here = lstatSync4(path41.join(dir, root), { bigint: true });
32873
+ if (here.isSymbolicLink() || here.isFile() && here.nlink > 1n && sameFile(here, statSync12(path41.join(checkout, root), { bigint: true }))) linked.add(root);
32752
32874
  } catch {
32753
32875
  }
32754
32876
  }
32755
32877
  return linked;
32756
32878
  }
32879
+ function sameFile(a, b) {
32880
+ return a.dev === b.dev && a.ino === b.ino;
32881
+ }
32882
+ function linksTo(link, target) {
32883
+ try {
32884
+ return lstatSync4(link).isSymbolicLink() && realPathOf(link) === realPathOf(target);
32885
+ } catch {
32886
+ return false;
32887
+ }
32888
+ }
32757
32889
  function readDirs(root) {
32758
32890
  const dirs = [{ dir: root, prefix: "" }];
32759
32891
  for (let dir = root, prefix = ""; !existsSync16(path41.join(dir, ".git")); ) {
@@ -32798,7 +32930,7 @@ var TaskStartConfig = class {
32798
32930
  */
32799
32931
  worktreeDifferences(id2, dir, root) {
32800
32932
  const now = liveConfig(dir);
32801
- const linked = linkedRoots(dir);
32933
+ const linked = linkedRoots(dir, root);
32802
32934
  const fromCheckout2 = (name) => linked.has(name.split("/")[0]);
32803
32935
  const key = `${id2}:worktree:${dir}`;
32804
32936
  let local = this.live.get(key);
@@ -32827,10 +32959,14 @@ var TaskStartConfig = class {
32827
32959
  if (!cwd || !repo.baseRef || !existsSync16(cwd)) continue;
32828
32960
  const prefix = repo.path === "." ? (await tryGit(invoker, repo.root, ["rev-parse", "--show-prefix"])).stdout.trim() : "";
32829
32961
  const roots = [...RUNNER_CONFIG_ROOTS, ...prefix ? RUNNER_CONFIG_ROOTS.map((r) => `${prefix}${r}`) : []];
32962
+ const top = path41.resolve(repo.root, ...prefix.split("/").filter(Boolean).map(() => ".."));
32963
+ const runnerRoots = prefix ? roots.filter((root) => root.startsWith(prefix)) : roots;
32964
+ const linked = runnerRoots.filter((root) => linksTo(path41.join(cwd, root), path41.join(top, root))).map((root) => `${root}/`);
32830
32965
  const diff = await tryGit(invoker, cwd, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "--diff-filter=ACMRTU", "-z", repo.baseRef, "--"]);
32831
32966
  const untracked = await tryGit(invoker, cwd, ["ls-files", "--others", "-z", "--", ...roots]);
32832
32967
  if (!diff.ok || !untracked.ok) continue;
32833
32968
  for (const name of [...diff.stdout.split("\0"), ...untracked.stdout.split("\0")]) {
32969
+ if (linked.some((root) => name.startsWith(root))) continue;
32834
32970
  const here = prefix && name.startsWith(prefix) ? name.slice(prefix.length) : void 0;
32835
32971
  if (repositoryRunnerConfigPaths([name]).length || here !== void 0 && repositoryRunnerConfigPaths([here]).length) {
32836
32972
  found.push(repo.path === "." ? name : path41.posix.join(repo.path, name));
@@ -32843,7 +32979,7 @@ var TaskStartConfig = class {
32843
32979
 
32844
32980
  // src/services/ScriptRunner.ts
32845
32981
  import { spawn as nodeSpawn2 } from "child_process";
32846
- import * as fs19 from "fs";
32982
+ import * as fs20 from "fs";
32847
32983
  import * as path42 from "path";
32848
32984
  import { EventEmitter as EventEmitter2 } from "events";
32849
32985
  import { StringDecoder as StringDecoder2 } from "string_decoder";
@@ -32929,8 +33065,8 @@ var ScriptSession = class extends AbstractRunnerSession {
32929
33065
  /** Aborted to end a sealed step, which has no process of its own here to signal. */
32930
33066
  sealedEnd = new AbortController();
32931
33067
  markGone;
32932
- gone = new Promise((resolve17) => {
32933
- this.markGone = resolve17;
33068
+ gone = new Promise((resolve18) => {
33069
+ this.markGone = resolve18;
32934
33070
  });
32935
33071
  /** Whoever spawned it attaches its listeners when the spawn resolves, so the body starts a macrotask later. */
32936
33072
  begin() {
@@ -33032,7 +33168,7 @@ var ScriptSession = class extends AbstractRunnerSession {
33032
33168
  return shell.file === null ? { file: step.script, args: [], shell: true } : { file: shell.file, args: [...shell.args, step.script], shell: false };
33033
33169
  }
33034
33170
  spawnStep(launch) {
33035
- return new Promise((resolve17) => {
33171
+ return new Promise((resolve18) => {
33036
33172
  let settled = false;
33037
33173
  const stdout = new StringDecoder2("utf8");
33038
33174
  const stderr = new StringDecoder2("utf8");
@@ -33044,7 +33180,7 @@ var ScriptSession = class extends AbstractRunnerSession {
33044
33180
  this.child = null;
33045
33181
  this.placed = null;
33046
33182
  launch.placed?.ended();
33047
- resolve17(status);
33183
+ resolve18(status);
33048
33184
  };
33049
33185
  this.placed = launch.placed ?? null;
33050
33186
  const child = spawnInOwnGroup((detached) => this.setup.spawn(launch.file, launch.args, {
@@ -33095,7 +33231,7 @@ var ScriptSession = class extends AbstractRunnerSession {
33095
33231
  openFullOutput() {
33096
33232
  const target = this.setup.fullOutput;
33097
33233
  if (!target) return;
33098
- const stream = fs19.createWriteStream(target.file);
33234
+ const stream = fs20.createWriteStream(target.file);
33099
33235
  const full = { file: target.file, stream, written: 0, dropped: 0, failed: false };
33100
33236
  stream.on("error", (err) => {
33101
33237
  if (!full.failed) console.error(`[ScriptSession] could not save the output of ${this.id} to ${target.file}:`, err);
@@ -33120,12 +33256,12 @@ var ScriptSession = class extends AbstractRunnerSession {
33120
33256
  if (!full.failed && full.dropped > 0) full.stream.write(`
33121
33257
  [Ordewell stopped saving output here: ${full.dropped} more characters were not saved]
33122
33258
  `);
33123
- await new Promise((resolve17) => {
33259
+ await new Promise((resolve18) => {
33124
33260
  if (full.stream.closed) {
33125
- resolve17();
33261
+ resolve18();
33126
33262
  return;
33127
33263
  }
33128
- full.stream.once("close", () => resolve17());
33264
+ full.stream.once("close", () => resolve18());
33129
33265
  full.stream.end();
33130
33266
  });
33131
33267
  return full.failed ? void 0 : { file: full.file, droppedChars: full.dropped };
@@ -33277,7 +33413,7 @@ function passed(status) {
33277
33413
 
33278
33414
  // src/services/PatchCapture.ts
33279
33415
  import { createHash as createHash5, randomBytes as randomBytes8 } from "crypto";
33280
- import * as fs20 from "fs";
33416
+ import * as fs21 from "fs";
33281
33417
  import * as os11 from "os";
33282
33418
  import * as path43 from "path";
33283
33419
 
@@ -33357,9 +33493,9 @@ var Subtree = class _Subtree {
33357
33493
  at(path52) {
33358
33494
  const { here } = this.source;
33359
33495
  const absolute = `${ROOT_NODE2}/${path52}`;
33360
- const relative21 = `${here}/${path52}`;
33496
+ const relative20 = `${here}/${path52}`;
33361
33497
  const nodes = this.nodes();
33362
- const found = (absolute !== here && isWithin(absolute, here) ? nodes.find((node) => node.path === absolute) : void 0) ?? nodes.find((node) => node.path === relative21);
33498
+ const found = (absolute !== here && isWithin(absolute, here) ? nodes.find((node) => node.path === absolute) : void 0) ?? nodes.find((node) => node.path === relative20);
33363
33499
  return found && this.planOf(found);
33364
33500
  }
33365
33501
  /** The same as a reference is pinned against it. */
@@ -33777,17 +33913,17 @@ function linkInPatch(patch) {
33777
33913
  function readOwn(scratch, name, max) {
33778
33914
  let fd;
33779
33915
  try {
33780
- fd = fs20.openSync(path43.join(scratch, name), fs20.constants.O_RDONLY | (fs20.constants.O_NOFOLLOW ?? 0));
33916
+ fd = fs21.openSync(path43.join(scratch, name), fs21.constants.O_RDONLY | (fs21.constants.O_NOFOLLOW ?? 0));
33781
33917
  } catch (err) {
33782
33918
  throw new Refusal(`the capture left no ${name.split(".").pop()} Ordewell could read (${err.code ?? String(err)})`);
33783
33919
  }
33784
33920
  try {
33785
- if (!fs20.fstatSync(fd).isFile()) throw new Refusal(`the capture's ${name.split(".").pop()} is not a file`);
33921
+ if (!fs21.fstatSync(fd).isFile()) throw new Refusal(`the capture's ${name.split(".").pop()} is not a file`);
33786
33922
  const chunks = [];
33787
33923
  let total = 0;
33788
33924
  for (; ; ) {
33789
33925
  const chunk = Buffer.alloc(Math.min(1024 * 1024, max + 1 - total));
33790
- const read2 = fs20.readSync(fd, chunk, 0, chunk.length, null);
33926
+ const read2 = fs21.readSync(fd, chunk, 0, chunk.length, null);
33791
33927
  if (read2 === 0) break;
33792
33928
  total += read2;
33793
33929
  chunks.push(chunk.subarray(0, read2));
@@ -33795,7 +33931,7 @@ function readOwn(scratch, name, max) {
33795
33931
  }
33796
33932
  return Buffer.concat(chunks);
33797
33933
  } finally {
33798
- fs20.closeSync(fd);
33934
+ fs21.closeSync(fd);
33799
33935
  }
33800
33936
  }
33801
33937
  function failure(step, outcome) {
@@ -33833,7 +33969,7 @@ async function captureHeld(runs, opts, signal) {
33833
33969
  if (clash) return { kind: "refused", reason: clash };
33834
33970
  const flags = [...flag("excluded", excluded.map((c) => c.name)), ...flag("dropped", dropped.map((p) => `${p.name} (${byteSize(p.size)})`))];
33835
33971
  if (kept.length === 0) return { kind: "empty", reason: "none of the worktree's changes is one a patch carries.", flags };
33836
- fs20.writeFileSync(`${stem}.revert`, revertRecords([...excluded, ...dropped.flatMap((p) => p.changes)]), { flag: "wx", mode: 384 });
33972
+ fs21.writeFileSync(`${stem}.revert`, revertRecords([...excluded, ...dropped.flatMap((p) => p.changes)]), { flag: "wx", mode: 384 });
33837
33973
  const exported = await runs.run(exportScript(stem), worktree);
33838
33974
  if (signal?.aborted) return { kind: "refused", reason: "the attempt ended while its changes were being captured." };
33839
33975
  if (!exported.success) return { kind: "refused", reason: failure("git could not write or replay the patch", exported) };
@@ -33859,8 +33995,8 @@ async function captureHeld(runs, opts, signal) {
33859
33995
  if (err instanceof Refusal) return { kind: "refused", reason: `${err.message}.` };
33860
33996
  throw err;
33861
33997
  } finally {
33862
- fs20.rmSync(`${stem}.d`, { recursive: true, force: true });
33863
- for (const suffix of ["base", "raw", "files", "sizes", "renames", "revert", "kept", "hashes", "patch", "tree", "replayed"]) fs20.rmSync(`${stem}.${suffix}`, { force: true });
33998
+ fs21.rmSync(`${stem}.d`, { recursive: true, force: true });
33999
+ for (const suffix of ["base", "raw", "files", "sizes", "renames", "revert", "kept", "hashes", "patch", "tree", "replayed"]) fs21.rmSync(`${stem}.${suffix}`, { force: true });
33864
34000
  }
33865
34001
  }
33866
34002
  async function capturePatch(shell, opts = {}, signal) {
@@ -33909,7 +34045,7 @@ async function indexEntries(invoker, worktree) {
33909
34045
  async function trialApply(invoker, worktree, patchFile, scratch) {
33910
34046
  const index = path43.resolve(worktree, (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--git-path", "index"])).trim());
33911
34047
  const copy = path43.join(scratch, "index");
33912
- fs20.copyFileSync(index, copy);
34048
+ fs21.copyFileSync(index, copy);
33913
34049
  const trial = { ...invoker, exec: (file, args, opts) => invoker.exec(file, args, { ...opts, env: { ...opts.env, GIT_INDEX_FILE: copy } }) };
33914
34050
  const tried = await tryGit(trial, worktree, [...APPLY_GIT, "apply", "--cached", "--3way", "--whitespace=nowarn", patchFile]);
33915
34051
  return { left: await indexEntries(trial, worktree), ...tried.ok ? {} : { failed: tried.stderr } };
@@ -33928,7 +34064,7 @@ function gitRefused(lead, stderr) {
33928
34064
  function onDisk3(worktree, names2) {
33929
34065
  return names2.map((name) => {
33930
34066
  try {
33931
- const stat = fs20.lstatSync(path43.join(worktree, name), { bigint: true, throwIfNoEntry: false });
34067
+ const stat = fs21.lstatSync(path43.join(worktree, name), { bigint: true, throwIfNoEntry: false });
33932
34068
  return stat ? `${stat.mode} ${stat.ino} ${stat.size} ${stat.mtimeNs} ${stat.ctimeNs}` : "none";
33933
34069
  } catch (err) {
33934
34070
  return err.code ?? "unreadable";
@@ -33969,12 +34105,12 @@ function leavesWorktree(worktree, names2, linked, held2, left) {
33969
34105
  return `the patch writes ${name}, under ${at}, a submodule, whose files are another repository's.`;
33970
34106
  }
33971
34107
  const full = path43.join(worktree, ...parts.slice(0, i));
33972
- const stat = fs20.lstatSync(full, { throwIfNoEntry: false });
34108
+ const stat = fs21.lstatSync(full, { throwIfNoEntry: false });
33973
34109
  if (!stat) break;
33974
34110
  const last = i === parts.length;
33975
34111
  if (stat.isSymbolicLink()) {
33976
34112
  if (last && held2.get(at)?.some((entry) => entry.mode === LINK)) break;
33977
- const target = fs20.readlinkSync(full);
34113
+ const target = fs21.readlinkSync(full);
33978
34114
  return `the patch writes ${name}, ${last ? `a link to ${target}` : `under ${at}, a link to ${target}`}, so git would write through it, outside your worktree.`;
33979
34115
  }
33980
34116
  if (last || stat.isDirectory()) continue;
@@ -33996,10 +34132,10 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
33996
34132
  if (link !== void 0) {
33997
34133
  return refused4(`the patch holds a link or a submodule (${JSON.stringify(link.slice(0, 80))}), which a saved patch never does, so it is not one that was saved.`);
33998
34134
  }
33999
- const dir = fs20.mkdtempSync(path43.join(os11.tmpdir(), "ordewell-apply-"));
34135
+ const dir = fs21.mkdtempSync(path43.join(os11.tmpdir(), "ordewell-apply-"));
34000
34136
  try {
34001
34137
  const toplevel = (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--show-toplevel"])).trim();
34002
- if (fs20.realpathSync(toplevel) !== fs20.realpathSync(worktree)) return refused4(`${worktree} is not the root of a worktree of its own.`);
34138
+ if (realPathOf(toplevel) !== realPathOf(worktree)) return refused4(`${worktree} is not the root of a worktree of its own.`);
34003
34139
  const head = (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--verify", "HEAD^{commit}"])).trim();
34004
34140
  if (!(await tryGit(invoker, worktree, [...APPLY_GIT, "cat-file", "-e", `${saved.base}^{commit}`])).ok) {
34005
34141
  return refused4(`the commit the patch was taken against (${saved.base.slice(0, 12)}) is not in this repository, so there is nothing to merge it from.`);
@@ -34007,7 +34143,7 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
34007
34143
  const before = await unmergedPaths(invoker, worktree);
34008
34144
  if (before.length > 0) return refused4(`your worktree still has unresolved conflicts (${listed(before.slice(0, 10))}${before.length > 10 ? `, +${before.length - 10} more` : ""}). Resolve them and git add them, or undo them, then apply the patch.`);
34009
34145
  const file = path43.join(dir, "saved.patch");
34010
- fs20.writeFileSync(file, patch, { flag: "wx", mode: 384 });
34146
+ fs21.writeFileSync(file, patch, { flag: "wx", mode: 384 });
34011
34147
  const held2 = await indexEntries(invoker, worktree);
34012
34148
  const named3 = await pathsNamed(invoker, worktree, file);
34013
34149
  const { left, failed: failed2 } = await trialApply(invoker, worktree, file, dir);
@@ -34039,7 +34175,7 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
34039
34175
  } catch (err) {
34040
34176
  return refused4(`git could not apply the patch (${err instanceof Error ? err.message : String(err)}).`);
34041
34177
  } finally {
34042
- fs20.rmSync(dir, { recursive: true, force: true });
34178
+ fs21.rmSync(dir, { recursive: true, force: true });
34043
34179
  }
34044
34180
  }
34045
34181
  function resolution(c) {
@@ -34106,17 +34242,17 @@ async function applySavedPatch(args, site) {
34106
34242
 
34107
34243
  // src/services/Board.ts
34108
34244
  import { createHash as createHash6 } from "crypto";
34109
- import * as fs21 from "fs";
34245
+ import * as fs22 from "fs";
34110
34246
  import * as path44 from "path";
34111
34247
  var BLOB_READ_MAX = 16 * 1024 * 1024;
34112
34248
  async function workBlob(cwd, file) {
34113
34249
  try {
34114
- const root = await fs21.promises.realpath(cwd);
34115
- const full = await fs21.promises.realpath(path44.join(root, file));
34250
+ const root = await fs22.promises.realpath(cwd);
34251
+ const full = await fs22.promises.realpath(path44.join(root, file));
34116
34252
  if (!full.startsWith(`${root}${path44.sep}`)) return void 0;
34117
- const stat = await fs21.promises.stat(full);
34253
+ const stat = await fs22.promises.stat(full);
34118
34254
  if (!stat.isFile() || stat.size > BLOB_READ_MAX) return void 0;
34119
- const bytes = await fs21.promises.readFile(full);
34255
+ const bytes = await fs22.promises.readFile(full);
34120
34256
  return createHash6("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
34121
34257
  } catch {
34122
34258
  return void 0;
@@ -35502,7 +35638,7 @@ function leasedIsolation(isolation, held2) {
35502
35638
  closeChanges: async () => {
35503
35639
  do {
35504
35640
  await Promise.all(underWay);
35505
- await new Promise((resolve17) => setImmediate(resolve17));
35641
+ await new Promise((resolve18) => setImmediate(resolve18));
35506
35642
  } while (underWay.size > 0);
35507
35643
  closed = true;
35508
35644
  }
@@ -35743,9 +35879,9 @@ var SlotPool = class {
35743
35879
  try {
35744
35880
  while (this.keptStarts.length > 0 && !this.full) {
35745
35881
  const node = this.keptStarts.shift();
35746
- await new Promise((resolve17) => {
35747
- this.taken = resolve17;
35748
- void node.tick().catch(() => void 0).finally(resolve17);
35882
+ await new Promise((resolve18) => {
35883
+ this.taken = resolve18;
35884
+ void node.tick().catch(() => void 0).finally(resolve18);
35749
35885
  });
35750
35886
  this.taken = null;
35751
35887
  }
@@ -38666,6 +38802,7 @@ var RunnerInstallation = class {
38666
38802
  env;
38667
38803
  workspace;
38668
38804
  authExec;
38805
+ launch;
38669
38806
  constructor(registry, execImpl = defaultExec4, now = Date.now, options = {}) {
38670
38807
  this.registry = registry;
38671
38808
  this.execImpl = execImpl;
@@ -38673,6 +38810,7 @@ var RunnerInstallation = class {
38673
38810
  this.env = options.env ?? (async () => ({}));
38674
38811
  this.workspace = options.workspace ?? (() => void 0);
38675
38812
  this.authExec = options.authExec;
38813
+ this.launch = options.launch ?? {};
38676
38814
  }
38677
38815
  /** True if the runner's CLI responds to `--version`. Cached per process. */
38678
38816
  async isInstalled(runner) {
@@ -38756,7 +38894,8 @@ var RunnerInstallation = class {
38756
38894
  try {
38757
38895
  return await readRunnerAuth(manifest, {
38758
38896
  ...this.authExec ? { exec: this.authExec } : {},
38759
- env: await this.env(workspace)
38897
+ env: await this.env(workspace),
38898
+ launch: this.launch
38760
38899
  });
38761
38900
  } catch {
38762
38901
  return { state: "unknown" };
@@ -38783,10 +38922,10 @@ var RunnerInstallation = class {
38783
38922
  * with `isInstalled` there.
38784
38923
  */
38785
38924
  async isSpawnable(command) {
38786
- if (process.platform !== "win32") return true;
38925
+ if ((this.launch.platform ?? process.platform) !== "win32") return true;
38787
38926
  try {
38788
- const plan = await planDirectLaunch(command, []);
38789
- return plan.file !== command;
38927
+ const plan = await planDirectLaunch(command, [], this.launch);
38928
+ return isExecutableResolved(command, plan, "", this.launch);
38790
38929
  } catch {
38791
38930
  return false;
38792
38931
  }
@@ -38976,10 +39115,10 @@ var AccountLimitMonitor = class {
38976
39115
  entry.inFlight = controller;
38977
39116
  entry.lastStartedAt = this.now();
38978
39117
  let deadline;
38979
- const abandoned = new Promise((resolve17) => {
39118
+ const abandoned = new Promise((resolve18) => {
38980
39119
  deadline = setTimeout(() => {
38981
39120
  controller.abort();
38982
- resolve17({ kind: "failed" });
39121
+ resolve18({ kind: "failed" });
38983
39122
  }, DEADLINE_MS);
38984
39123
  deadline.unref?.();
38985
39124
  });
@@ -39158,9 +39297,9 @@ async function readCodexAccountLimits(command, args, options, signal) {
39158
39297
  const initialized = await rpc.call("initialize", { clientInfo: APP_SERVER_CLIENT_INFO });
39159
39298
  if (!initialized.ok) return failed2();
39160
39299
  server4.notify("initialized", {});
39161
- const account = await new Promise((resolve17) => rpc.send("account/read", { refreshToken: false }, (response) => {
39300
+ const account = await new Promise((resolve18) => rpc.send("account/read", { refreshToken: false }, (response) => {
39162
39301
  accountRead = true;
39163
- resolve17(response);
39302
+ resolve18(response);
39164
39303
  }));
39165
39304
  if (!account.ok) return account.code === METHOD_NOT_FOUND ? { kind: "unsupported" } : failed2();
39166
39305
  const who = codexAccountOwner(account.result);
@@ -39178,7 +39317,7 @@ async function readCodexAccountLimits(command, args, options, signal) {
39178
39317
  ...followUp ? { followUp: true } : {}
39179
39318
  };
39180
39319
  })();
39181
- const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
39320
+ const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
39182
39321
  try {
39183
39322
  return await settleWithin(asked, {
39184
39323
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS4,
@@ -39235,7 +39374,7 @@ import { spawn as nodeSpawn3 } from "child_process";
39235
39374
  import { randomUUID as randomUUID7 } from "crypto";
39236
39375
  import { mkdtempSync as mkdtempSync5, rmSync as rmSync12 } from "fs";
39237
39376
  import { tmpdir as tmpdir6 } from "os";
39238
- import { join as join41 } from "path";
39377
+ import { join as join40 } from "path";
39239
39378
  var DEFAULT_TIMEOUT_MS5 = 2e4;
39240
39379
  var INITIALIZE_TIMEOUT_MS2 = 1e4;
39241
39380
  var USAGE_TIMEOUT_MS = 1e4;
@@ -39267,7 +39406,7 @@ function claudeAccountLimitCollector(options) {
39267
39406
  };
39268
39407
  }
39269
39408
  async function readClaudeAccountLimits(options, signal) {
39270
- const cwd = mkdtempSync5(join41(tmpdir6(), "ordewell-claude-limits-"));
39409
+ const cwd = mkdtempSync5(join40(tmpdir6(), "ordewell-claude-limits-"));
39271
39410
  const removeCwd = () => {
39272
39411
  try {
39273
39412
  rmSync12(cwd, { recursive: true, force: true });
@@ -39296,7 +39435,7 @@ async function readClaudeAccountLimits(options, signal) {
39296
39435
  if (usage.kind === "refused" && UNSUPPORTED_REQUEST.test(usage.error)) return { kind: "unsupported" };
39297
39436
  return claudeLimitReading(usage, owner, isRecord8(account) ? text3(account.subscriptionType) : void 0) ?? failed2();
39298
39437
  })().catch(failed2);
39299
- const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
39438
+ const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
39300
39439
  try {
39301
39440
  return await settleWithin(asked, {
39302
39441
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS5,
@@ -39355,9 +39494,9 @@ import { homedir as homedir10 } from "os";
39355
39494
 
39356
39495
  // src/services/harness/openCodeCredentials.ts
39357
39496
  import { createHash as createHash7 } from "crypto";
39358
- import { promises as fs22 } from "fs";
39497
+ import { promises as fs23 } from "fs";
39359
39498
  import { homedir as osHomedir } from "os";
39360
- import { join as join42, resolve as resolve14 } from "path";
39499
+ import { join as join41, resolve as resolve15 } from "path";
39361
39500
  import { Worker } from "worker_threads";
39362
39501
  var DEFAULT_TIMEOUT_MS6 = 5e3;
39363
39502
  var BUSY_MS = 250;
@@ -39414,9 +39553,9 @@ parentPort.postMessage(select());
39414
39553
  var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
39415
39554
  var digest = (...parts) => createHash7("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
39416
39555
  function openCodeStorePaths(env, home) {
39417
- const data = join42(env.XDG_DATA_HOME || join42(home, ".local", "share"), "opencode");
39556
+ const data = join41(env.XDG_DATA_HOME || join41(home, ".local", "share"), "opencode");
39418
39557
  const file = env.OPENCODE_DB || "opencode.db";
39419
- return { db: file === ":memory:" ? null : resolve14(data, file), auth: join42(data, "auth.json") };
39558
+ return { db: file === ":memory:" ? null : resolve15(data, file), auth: join41(data, "auth.json") };
39420
39559
  }
39421
39560
  function openCodeGoLoginReader(deps = {}) {
39422
39561
  const homedir11 = deps.homedir ?? osHomedir;
@@ -39525,7 +39664,7 @@ function queryStore(path52, signal, deps) {
39525
39664
  }
39526
39665
  async function stamp(path52) {
39527
39666
  try {
39528
- const stat = await fs22.stat(path52);
39667
+ const stat = await fs23.stat(path52);
39529
39668
  return [stat.ino, stat.size, stat.mtimeMs];
39530
39669
  } catch {
39531
39670
  return null;
@@ -39533,9 +39672,9 @@ async function stamp(path52) {
39533
39672
  }
39534
39673
  async function readSmall(path52) {
39535
39674
  try {
39536
- const stat = await fs22.stat(path52);
39675
+ const stat = await fs23.stat(path52);
39537
39676
  if (!stat.isFile() || stat.size > MAX_AUTH_FILE_BYTES) return null;
39538
- return await fs22.readFile(path52, "utf8");
39677
+ return await fs23.readFile(path52, "utf8");
39539
39678
  } catch (err) {
39540
39679
  return err.code === "ENOENT" ? void 0 : null;
39541
39680
  }
@@ -40700,8 +40839,8 @@ Before submitting, call list_runners and list_models to check the available assi
40700
40839
  session.discard();
40701
40840
  }
40702
40841
  }
40703
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
40704
- const contextStr = await collectResearchContext(fs28, runners);
40842
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
40843
+ const contextStr = await collectResearchContext(fs29, runners);
40705
40844
  const prompt = buildPlanWithResults(userDescription, contextStr, "", modelsByRunner, runners, runnerModes, modes, true);
40706
40845
  const plan = await this.submittedPlan(prompt, oneShotCatalog(runners, modelsByRunner, runnerModes, modes), onProgress, signal);
40707
40846
  return {
@@ -40742,22 +40881,22 @@ function createAiService(config, deps) {
40742
40881
  import * as path49 from "path";
40743
40882
 
40744
40883
  // src/services/handoffReferences.ts
40745
- import * as fs23 from "fs";
40884
+ import * as fs24 from "fs";
40746
40885
  import * as path46 from "path";
40747
40886
  import { spawnSync as spawnSync2 } from "child_process";
40748
40887
  function resolveHandoffReferences(handoff, workspace) {
40749
40888
  const checked = /* @__PURE__ */ new Map();
40750
40889
  const contained = (candidate) => {
40751
40890
  try {
40752
- const root = fs23.realpathSync(workspace);
40753
- const resolved2 = fs23.realpathSync(path46.resolve(root, candidate));
40754
- const relative21 = path46.relative(root, resolved2);
40755
- return relative21 !== ".." && !relative21.startsWith(`..${path46.sep}`) && !path46.isAbsolute(relative21) ? resolved2 : void 0;
40891
+ const root = fs24.realpathSync(workspace);
40892
+ const resolved2 = fs24.realpathSync(path46.resolve(root, candidate));
40893
+ const relative20 = path46.relative(root, resolved2);
40894
+ return relative20 !== ".." && !relative20.startsWith(`..${path46.sep}`) && !path46.isAbsolute(relative20) ? resolved2 : void 0;
40756
40895
  } catch {
40757
40896
  return void 0;
40758
40897
  }
40759
40898
  };
40760
- const resolve17 = (ref2) => {
40899
+ const resolve18 = (ref2) => {
40761
40900
  if (ref2.kind !== "file" && ref2.kind !== "commit") return ref2;
40762
40901
  const key = JSON.stringify(ref2);
40763
40902
  const known = checked.get(key);
@@ -40767,13 +40906,13 @@ function resolveHandoffReferences(handoff, workspace) {
40767
40906
  const file = contained(ref2.path);
40768
40907
  if (file) {
40769
40908
  try {
40770
- resolved2 = fs23.statSync(file).isFile();
40909
+ resolved2 = fs24.statSync(file).isFile();
40771
40910
  } catch {
40772
40911
  }
40773
40912
  }
40774
40913
  } else if (/^[0-9a-fA-F]{4,64}$/.test(ref2.sha)) {
40775
40914
  const repo = contained(ref2.repo ?? ".");
40776
- if (repo && fs23.existsSync(path46.join(repo, ".git"))) {
40915
+ if (repo && fs24.existsSync(path46.join(repo, ".git"))) {
40777
40916
  const result2 = spawnSync2("git", ["--no-optional-locks", "--no-replace-objects", "cat-file", "-t", ref2.sha], {
40778
40917
  cwd: repo,
40779
40918
  encoding: "utf8",
@@ -40790,9 +40929,9 @@ function resolveHandoffReferences(handoff, workspace) {
40790
40929
  };
40791
40930
  return {
40792
40931
  ...handoff,
40793
- findings: handoff.findings.map((f) => ({ ...f, ...f.evidence ? { evidence: f.evidence.map(resolve17) } : {} })),
40932
+ findings: handoff.findings.map((f) => ({ ...f, ...f.evidence ? { evidence: f.evidence.map(resolve18) } : {} })),
40794
40933
  // A saved patch is Ordewell's own record, not a claim about a tree (ADR-0050).
40795
- ...handoff.artifacts ? { artifacts: handoff.artifacts.map((a) => a.kind === "patch" ? a : resolve17(a)) } : {}
40934
+ ...handoff.artifacts ? { artifacts: handoff.artifacts.map((a) => a.kind === "patch" ? a : resolve18(a)) } : {}
40796
40935
  };
40797
40936
  }
40798
40937
 
@@ -41458,8 +41597,8 @@ var PlanTurns = class {
41458
41597
  this.pump();
41459
41598
  return Promise.resolve(plan);
41460
41599
  }
41461
- const settled = new Promise((resolve17, reject) => {
41462
- this.waiters.set(entry.id, { resolve: resolve17, reject, signal: input.signal });
41600
+ const settled = new Promise((resolve18, reject) => {
41601
+ this.waiters.set(entry.id, { resolve: resolve18, reject, signal: input.signal });
41463
41602
  });
41464
41603
  this.pump();
41465
41604
  return settled;
@@ -42362,8 +42501,8 @@ var ChildPlanSession = class extends AbstractRunnerSession {
42362
42501
  counts;
42363
42502
  stopping = null;
42364
42503
  markGone;
42365
- gone = new Promise((resolve17) => {
42366
- this.markGone = resolve17;
42504
+ gone = new Promise((resolve18) => {
42505
+ this.markGone = resolve18;
42367
42506
  });
42368
42507
  /** Whoever spawned it attaches its listeners when the spawn resolves, so the child starts a macrotask later. */
42369
42508
  begin() {
@@ -43305,7 +43444,7 @@ var TreeLedger = class _TreeLedger {
43305
43444
  };
43306
43445
 
43307
43446
  // src/utils/treeEventLog.ts
43308
- import * as fs24 from "fs";
43447
+ import * as fs25 from "fs";
43309
43448
  import * as path47 from "path";
43310
43449
 
43311
43450
  // src/services/eventStore.ts
@@ -43326,7 +43465,7 @@ function treeEventLogFile(rootSessionId, baseDir) {
43326
43465
  return path47.join(sessionDataDir(rootSessionId, baseDir), LOG_FILE);
43327
43466
  }
43328
43467
  function hasTreeEventLog(rootSessionId, baseDir) {
43329
- return fs24.existsSync(treeEventLogFile(rootSessionId, baseDir));
43468
+ return fs25.existsSync(treeEventLogFile(rootSessionId, baseDir));
43330
43469
  }
43331
43470
  function batchOf(line) {
43332
43471
  try {
@@ -43339,8 +43478,8 @@ function batchOf(line) {
43339
43478
  async function* landed2(file) {
43340
43479
  let stream;
43341
43480
  try {
43342
- await fs24.promises.access(file);
43343
- stream = fs24.createReadStream(file);
43481
+ await fs25.promises.access(file);
43482
+ stream = fs25.createReadStream(file);
43344
43483
  } catch (err) {
43345
43484
  if (err.code === "ENOENT") return;
43346
43485
  throw err;
@@ -43375,15 +43514,15 @@ function jsonlEventStore(file) {
43375
43514
  let walked = null;
43376
43515
  let doubted = null;
43377
43516
  async function open() {
43378
- await fs24.promises.mkdir(path47.dirname(file), { recursive: true });
43379
- const size = await fs24.promises.stat(file).then(({ size: size2 }) => size2, () => 0);
43517
+ await fs25.promises.mkdir(path47.dirname(file), { recursive: true });
43518
+ const size = await fs25.promises.stat(file).then(({ size: size2 }) => size2, () => 0);
43380
43519
  let found = walked?.end === size ? walked : null;
43381
43520
  if (!found) {
43382
43521
  found = { end: 0, next: 1 };
43383
43522
  for await (const batch of landed2(file)) found = pastBatch(found, batch);
43384
43523
  }
43385
- if (size > found.end) await fs24.promises.truncate(file, found.end);
43386
- return { handle: await fs24.promises.open(file, "a"), next: found.next };
43524
+ if (size > found.end) await fs25.promises.truncate(file, found.end);
43525
+ return { handle: await fs25.promises.open(file, "a"), next: found.next };
43387
43526
  }
43388
43527
  async function write(events) {
43389
43528
  writer ??= await open();
@@ -43779,7 +43918,7 @@ var SessionEventRelay = class {
43779
43918
  };
43780
43919
 
43781
43920
  // src/utils/taskLogStore.ts
43782
- import * as fs25 from "fs";
43921
+ import * as fs26 from "fs";
43783
43922
  import * as path48 from "path";
43784
43923
  var EXTENSION = ".jsonl";
43785
43924
  function taskDir({ baseDir, sessionId, rootSessionId }, taskId) {
@@ -43788,7 +43927,7 @@ function taskDir({ baseDir, sessionId, rootSessionId }, taskId) {
43788
43927
  function listTaskLogAttempts(location, taskId) {
43789
43928
  let names2;
43790
43929
  try {
43791
- names2 = fs25.readdirSync(taskDir(location, taskId));
43930
+ names2 = fs26.readdirSync(taskDir(location, taskId));
43792
43931
  } catch {
43793
43932
  return [];
43794
43933
  }
@@ -43797,13 +43936,13 @@ function listTaskLogAttempts(location, taskId) {
43797
43936
  function openTaskLog(location, taskId, attempt) {
43798
43937
  ensureStateDirIgnored(location.baseDir);
43799
43938
  const dir = taskDir(location, taskId);
43800
- fs25.mkdirSync(dir, { recursive: true });
43939
+ fs26.mkdirSync(dir, { recursive: true });
43801
43940
  const next = (listTaskLogAttempts(location, taskId).pop() ?? 0) + 1;
43802
43941
  let number = attempt !== void 0 && Number.isInteger(attempt) && attempt >= 1 ? attempt : next;
43803
43942
  for (; ; ) {
43804
43943
  const file = path48.join(dir, `${number}${EXTENSION}`);
43805
43944
  try {
43806
- fs25.writeFileSync(file, "", { flag: "wx" });
43945
+ fs26.writeFileSync(file, "", { flag: "wx" });
43807
43946
  } catch (err) {
43808
43947
  if (err.code === "EEXIST") {
43809
43948
  number = Math.max(number + 1, next);
@@ -43815,7 +43954,7 @@ function openTaskLog(location, taskId, attempt) {
43815
43954
  attempt: number,
43816
43955
  append(events) {
43817
43956
  if (events.length === 0) return;
43818
- fs25.appendFileSync(file, events.map((e) => `${JSON.stringify(e)}
43957
+ fs26.appendFileSync(file, events.map((e) => `${JSON.stringify(e)}
43819
43958
  `).join(""));
43820
43959
  }
43821
43960
  };
@@ -43824,7 +43963,7 @@ function openTaskLog(location, taskId, attempt) {
43824
43963
  function prepareTaskOutputFile(location, taskId, attempt) {
43825
43964
  ensureStateDirIgnored(location.baseDir);
43826
43965
  const dir = taskDir(location, taskId);
43827
- fs25.mkdirSync(dir, { recursive: true });
43966
+ fs26.mkdirSync(dir, { recursive: true });
43828
43967
  return path48.join(dir, `${attempt}.output.txt`);
43829
43968
  }
43830
43969
  function taskPatchFile(location, taskId, attempt) {
@@ -43833,16 +43972,16 @@ function taskPatchFile(location, taskId, attempt) {
43833
43972
  function saveTaskPatch(location, taskId, attempt, patch) {
43834
43973
  ensureStateDirIgnored(location.baseDir);
43835
43974
  const file = taskPatchFile(location, taskId, attempt);
43836
- fs25.mkdirSync(path48.dirname(file), { recursive: true });
43975
+ fs26.mkdirSync(path48.dirname(file), { recursive: true });
43837
43976
  const partial = `${file}.${process.pid}-${Date.now()}.partial`;
43838
- fs25.writeFileSync(partial, patch, { flag: "wx" });
43839
- fs25.renameSync(partial, file);
43977
+ fs26.writeFileSync(partial, patch, { flag: "wx" });
43978
+ fs26.renameSync(partial, file);
43840
43979
  return file;
43841
43980
  }
43842
43981
  function readTaskPatch(location, taskId, attempt) {
43843
43982
  if (!Number.isInteger(attempt) || attempt < 1) return void 0;
43844
43983
  try {
43845
- return fs25.readFileSync(taskPatchFile(location, taskId, attempt));
43984
+ return fs26.readFileSync(taskPatchFile(location, taskId, attempt));
43846
43985
  } catch {
43847
43986
  return void 0;
43848
43987
  }
@@ -43854,7 +43993,7 @@ function readTaskLog(location, taskId, attempt) {
43854
43993
  if (!Number.isInteger(attempt) || attempt < 1) return [];
43855
43994
  let raw;
43856
43995
  try {
43857
- raw = fs25.readFileSync(path48.join(taskDir(location, taskId), `${attempt}${EXTENSION}`), "utf-8");
43996
+ raw = fs26.readFileSync(path48.join(taskDir(location, taskId), `${attempt}${EXTENSION}`), "utf-8");
43858
43997
  } catch {
43859
43998
  return [];
43860
43999
  }
@@ -44080,7 +44219,7 @@ function withTaskRunnerConfig(runner, setting) {
44080
44219
  import { createHash as createHash11, randomBytes as randomBytes11 } from "crypto";
44081
44220
  import { mkdtempSync as mkdtempSync8, readFileSync as readFileSync17, rmSync as rmSync15 } from "fs";
44082
44221
  import { tmpdir as tmpdir9 } from "os";
44083
- import { basename as basename7, join as join48, posix as posix13, relative as relative19, sep as sep12 } from "path";
44222
+ import { basename as basename7, join as join47, posix as posix15, relative as relative18, sep as sep11 } from "path";
44084
44223
 
44085
44224
  // src/services/container/modelGateway.ts
44086
44225
  import { createHash as createHash8, randomBytes as randomBytes9, timingSafeEqual as timingSafeEqual2 } from "crypto";
@@ -44131,19 +44270,19 @@ var ModelGateway = class {
44131
44270
  api;
44132
44271
  /** The port it took on this host's loopback. */
44133
44272
  listen() {
44134
- return new Promise((resolve17, reject) => {
44273
+ return new Promise((resolve18, reject) => {
44135
44274
  this.server.once("error", reject);
44136
44275
  this.server.listen(0, "127.0.0.1", () => {
44137
44276
  const { port } = this.server.address();
44138
44277
  this.host = `127.0.0.1:${port}`;
44139
- resolve17(port);
44278
+ resolve18(port);
44140
44279
  });
44141
44280
  });
44142
44281
  }
44143
44282
  async close() {
44144
44283
  this.server.closeAllConnections();
44145
- await new Promise((resolve17) => {
44146
- this.server.close(() => resolve17());
44284
+ await new Promise((resolve18) => {
44285
+ this.server.close(() => resolve18());
44147
44286
  });
44148
44287
  }
44149
44288
  carries({ headers }) {
@@ -44253,7 +44392,7 @@ var CredentialBroker = class {
44253
44392
 
44254
44393
  // src/services/container/taskWorkspace.ts
44255
44394
  import { createHash as createHash9 } from "crypto";
44256
- import { posix as posix11 } from "path";
44395
+ import { posix as posix13 } from "path";
44257
44396
  var MIRROR_ROOT = "/mirror";
44258
44397
  var TASK_ROOT = "/task";
44259
44398
  var WORK_ROOT = `${TASK_ROOT}/work`;
@@ -44270,8 +44409,8 @@ printf %s "$kept" > ${mark}
44270
44409
  `;
44271
44410
  var SIGN_IN_COPY = `${TASK_ROOT}/login/claude`;
44272
44411
  var SIGN_IN_MARK = `${TASK_ROOT}/login/handed`;
44273
- var repoDir = (repo) => repo.path === SELF_REPO ? WORK_ROOT : posix11.join(WORK_ROOT, repo.path);
44274
- var mirrorDir2 = (repo) => posix11.join(MIRROR_ROOT, `${repo.path === SELF_REPO ? "self" : createHash9("sha256").update(repo.path).digest("hex").slice(0, 16)}.git`);
44412
+ var repoDir = (repo) => repo.path === SELF_REPO ? WORK_ROOT : posix13.join(WORK_ROOT, repo.path);
44413
+ var mirrorDir2 = (repo) => posix13.join(MIRROR_ROOT, `${repo.path === SELF_REPO ? "self" : createHash9("sha256").update(repo.path).digest("hex").slice(0, 16)}.git`);
44275
44414
  var exportRef = (attempt) => `refs/ordewell/export/${attempt}`;
44276
44415
  var receiveScript = (mirror) => `set -e; [ -d ${mirror} ] || git init -q --bare ${mirror}; cd ${mirror}; git config gc.auto 0; git config gc.pruneExpire never; git config receive.autogc false; exec git receive-pack .`;
44277
44416
  var extArgument = (arg) => arg.replace(/%/g, "%%").replace(/ /g, "% ");
@@ -44416,7 +44555,7 @@ function parseContainerSettings(raw) {
44416
44555
  }
44417
44556
 
44418
44557
  // src/services/container/containerRunners.ts
44419
- import { posix as posix12 } from "path";
44558
+ import { posix as posix14 } from "path";
44420
44559
  var LOGIN_VOLUME = "ordewell-login-claude-code";
44421
44560
  var CODEX_LOGIN_VOLUME = "ordewell-login-codex";
44422
44561
  var OPENCODE_LOGIN_VOLUME = "ordewell-login-opencode";
@@ -44469,7 +44608,7 @@ var CONTAINER_RUNNERS = [
44469
44608
  api: ANTHROPIC_API,
44470
44609
  unbrokered: { openai: OPENAI_API },
44471
44610
  // The copy is the runner's data directory, which `XDG_DATA_HOME` names the parent of.
44472
- signIn: { volume: OPENCODE_LOGIN_VOLUME, hosts: OPENCODE_HOSTS, copy: ["sh", "-c", COPY_OPENCODE_SIGN_IN], path: OPENCODE_SIGN_IN_COPY, env: { XDG_DATA_HOME: posix12.join(TASK_ROOT, "login") } },
44611
+ signIn: { volume: OPENCODE_LOGIN_VOLUME, hosts: OPENCODE_HOSTS, copy: ["sh", "-c", COPY_OPENCODE_SIGN_IN], path: OPENCODE_SIGN_IN_COPY, env: { XDG_DATA_HOME: posix14.join(TASK_ROOT, "login") } },
44473
44612
  args: (launch) => launch.args
44474
44613
  }
44475
44614
  ];
@@ -44632,7 +44771,7 @@ import { randomBytes as randomBytes10 } from "crypto";
44632
44771
  import { mkdtempSync as mkdtempSync6, realpathSync as realpathSync14, rmSync as rmSync13, writeFileSync as writeFileSync11 } from "fs";
44633
44772
  import { createServer as createServer3 } from "net";
44634
44773
  import { release, tmpdir as tmpdir7, type as osType } from "os";
44635
- import { join as join46 } from "path";
44774
+ import { join as join45 } from "path";
44636
44775
 
44637
44776
  // src/services/container/guaranteeProbe.ts
44638
44777
  var METADATA = "169.254.169.254:80";
@@ -44770,8 +44909,8 @@ var OUTSIDE = "1.1.1.1:443";
44770
44909
  var OUTSIDE_NAME = "example.com";
44771
44910
  var PROBE_MS = 12e4;
44772
44911
  function plantFile() {
44773
- const dir = mkdtempSync6(join46(realpathSync14(tmpdir7()), "ordewell-canary-"));
44774
- const file = join46(dir, "canary");
44912
+ const dir = mkdtempSync6(join45(realpathSync14(tmpdir7()), "ordewell-canary-"));
44913
+ const file = join45(dir, "canary");
44775
44914
  writeFileSync11(file, randomBytes10(16).toString("hex"));
44776
44915
  return { file, remove: () => rmSync13(dir, { recursive: true, force: true }) };
44777
44916
  }
@@ -44781,9 +44920,9 @@ function listenOnLoopback() {
44781
44920
  hits += 1;
44782
44921
  socket.destroy();
44783
44922
  });
44784
- return new Promise((resolve17, reject) => {
44923
+ return new Promise((resolve18, reject) => {
44785
44924
  server4.once("error", reject);
44786
- server4.listen(0, "127.0.0.1", () => resolve17({ port: server4.address().port, hits: () => hits, close: () => server4.close() }));
44925
+ server4.listen(0, "127.0.0.1", () => resolve18({ port: server4.address().port, hits: () => hits, close: () => server4.close() }));
44787
44926
  });
44788
44927
  }
44789
44928
  async function withCanaries(use) {
@@ -44847,7 +44986,7 @@ var SpawnedDockerCli = class {
44847
44986
  }
44848
44987
  async call(args, { input, env, timeoutMs = CALL_TIMEOUT_MS, stdoutTo } = {}) {
44849
44988
  const child = spawn2("docker", [...args], { env: await this.environment(env), stdio: ["pipe", "pipe", "pipe"] });
44850
- return new Promise((resolve17) => {
44989
+ return new Promise((resolve18) => {
44851
44990
  let stdout = "";
44852
44991
  let stderr = "";
44853
44992
  let written = 0;
@@ -44873,7 +45012,7 @@ var SpawnedDockerCli = class {
44873
45012
  child.stdin.end(input);
44874
45013
  const finish2 = (code) => {
44875
45014
  clearTimeout(timer);
44876
- const done = () => resolve17({ code, stdout, stderr, ...overflowed ? { overflowed: true } : {} });
45015
+ const done = () => resolve18({ code, stdout, stderr, ...overflowed ? { overflowed: true } : {} });
44877
45016
  if (sink) sink.end(done);
44878
45017
  else done();
44879
45018
  };
@@ -44978,8 +45117,8 @@ function listening(entry) {
44978
45117
  entry.stderr?.on("data", (chunk) => {
44979
45118
  said2 = (said2 + chunk.toString()).slice(-STDERR_TAIL_CHARS2);
44980
45119
  });
44981
- return new Promise((resolve17, reject) => {
44982
- entry.stdout?.once("data", () => resolve17());
45120
+ return new Promise((resolve18, reject) => {
45121
+ entry.stdout?.once("data", () => resolve18());
44983
45122
  entry.once("error", reject);
44984
45123
  entry.once("close", () => reject(new Error(`The egress sidecar ended before it listened${said2.trim() ? `: ${said2.trim()}` : "."}`)));
44985
45124
  });
@@ -45113,20 +45252,20 @@ send(READY, 0);
45113
45252
  var LeaseRelay = class {
45114
45253
  constructor(entry) {
45115
45254
  this.entry = entry;
45116
- this.ready = new Promise((resolve17, reject) => {
45117
- this.markReady = resolve17;
45255
+ this.ready = new Promise((resolve18, reject) => {
45256
+ this.markReady = resolve18;
45118
45257
  this.failReady = reject;
45119
45258
  });
45120
45259
  this.ready.catch(() => void 0);
45121
- this.ended = new Promise((resolve17) => {
45260
+ this.ended = new Promise((resolve18) => {
45122
45261
  entry.once("close", () => {
45123
45262
  this.gone();
45124
- resolve17();
45263
+ resolve18();
45125
45264
  });
45126
45265
  entry.once("error", (err) => {
45127
45266
  this.stderrTail += err.message;
45128
45267
  this.gone();
45129
- resolve17();
45268
+ resolve18();
45130
45269
  });
45131
45270
  });
45132
45271
  entry.stdin?.on("error", () => void 0);
@@ -45163,8 +45302,8 @@ var LeaseRelay = class {
45163
45302
  if (known) return known.listening;
45164
45303
  let heard;
45165
45304
  let failed2;
45166
- const listening2 = new Promise((resolve17, reject) => {
45167
- heard = resolve17;
45305
+ const listening2 = new Promise((resolve18, reject) => {
45306
+ heard = resolve18;
45168
45307
  failed2 = reject;
45169
45308
  });
45170
45309
  this.forwards.set(containerPort, { hostPort, listening: listening2, heard, failed: failed2 });
@@ -45199,9 +45338,9 @@ var LeaseRelay = class {
45199
45338
  this.send(CONNECT, conn, port);
45200
45339
  });
45201
45340
  this.exposed.add(server4);
45202
- await new Promise((resolve17, reject) => {
45341
+ await new Promise((resolve18, reject) => {
45203
45342
  server4.once("error", reject);
45204
- server4.listen(0, "127.0.0.1", () => resolve17());
45343
+ server4.listen(0, "127.0.0.1", () => resolve18());
45205
45344
  });
45206
45345
  return server4.address().port;
45207
45346
  }
@@ -45296,8 +45435,8 @@ async function tryVolume(cli, volume) {
45296
45435
  const removed = await cli.call(["volume", "rm", "-f", volume]);
45297
45436
  if (removed.code === 0) return null;
45298
45437
  if (tried === VOLUME_TRIES) return removed.stderr.trim();
45299
- await new Promise((resolve17) => {
45300
- setTimeout(resolve17, VOLUME_WAIT_MS);
45438
+ await new Promise((resolve18) => {
45439
+ setTimeout(resolve18, VOLUME_WAIT_MS);
45301
45440
  });
45302
45441
  }
45303
45442
  }
@@ -45362,9 +45501,9 @@ async function reclaimContainers(tree, raw, { cli = new SpawnedDockerCli(), tell
45362
45501
  }
45363
45502
 
45364
45503
  // src/services/container/pushGate.ts
45365
- import { accessSync, constants as constants2, mkdtempSync as mkdtempSync7, realpathSync as realpathSync15, rmSync as rmSync14 } from "fs";
45504
+ import { accessSync, constants as constants2, mkdtempSync as mkdtempSync7, rmSync as rmSync14 } from "fs";
45366
45505
  import { tmpdir as tmpdir8 } from "os";
45367
- import { isAbsolute as isAbsolute13, join as join47, relative as relative18, resolve as resolve16, sep as sep11 } from "path";
45506
+ import { isAbsolute as isAbsolute12, join as join46, relative as relative17, resolve as resolve17, sep as sep10 } from "path";
45368
45507
  var FSCK = ["-c", "transfer.fsckObjects=true", "-c", "fetch.fsckObjects=true"];
45369
45508
  var LANDING_HOOKS = ["pre-commit", "prepare-commit-msg", "commit-msg", "post-commit", "pre-merge-commit", "post-merge", "post-checkout", "post-rewrite", "reference-transaction", "post-index-change"];
45370
45509
  var PushRefused = class extends Error {
@@ -45396,8 +45535,8 @@ async function takeThroughGate(invoker, repo, bundle, { ref: ref2, base }) {
45396
45535
  async function hooksWritten(invoker, repo, base, snapshot) {
45397
45536
  const top = (await git(invoker, repo, ["rev-parse", "--show-toplevel"])).trim();
45398
45537
  const path52 = (await git(invoker, repo, ["rev-parse", "--git-path", "hooks"])).trim();
45399
- const given = resolve16(top, path52);
45400
- const folders = [.../* @__PURE__ */ new Set([given, realOf(given)])].map((dir) => relative18(top, dir).split(sep11).join("/").toLowerCase()).filter((dir) => dir !== ".." && !dir.startsWith("../") && !isAbsolute13(dir));
45538
+ const given = resolve17(top, path52);
45539
+ const folders = [.../* @__PURE__ */ new Set([given, realOf(given)])].map((dir) => relative17(top, dir).split(sep10).join("/").toLowerCase()).filter((dir) => dir !== ".." && !dir.startsWith("../") && !isAbsolute12(dir));
45401
45540
  if (folders.length === 0) return [];
45402
45541
  const changed = (await git(invoker, repo, ["diff-tree", "-r", "-z", "--name-only", "--no-renames", base, snapshot])).split("\0").filter(Boolean);
45403
45542
  return changed.filter((file) => {
@@ -45407,20 +45546,20 @@ async function hooksWritten(invoker, repo, base, snapshot) {
45407
45546
  }
45408
45547
  function realOf(path52) {
45409
45548
  try {
45410
- return realpathSync15(path52);
45549
+ return realPathOf(path52);
45411
45550
  } catch {
45412
45551
  return path52;
45413
45552
  }
45414
45553
  }
45415
45554
  async function checkObjects(invoker, repo, snapshot, base) {
45416
- const scratch = mkdtempSync7(join47(tmpdir8(), "ordewell-gate-"));
45555
+ const scratch = mkdtempSync7(join46(tmpdir8(), "ordewell-gate-"));
45417
45556
  try {
45418
- const prefix = join47(scratch, "taken");
45557
+ const prefix = join46(scratch, "taken");
45419
45558
  const packed = await tryGit(invoker, repo, ["pack-objects", "--revs", "-q", prefix], `${snapshot}
45420
45559
  ^${base}
45421
45560
  `);
45422
45561
  if (!packed.ok) throw new PushRefused(`git could not read what it holds (${packed.stderr.trim()})`);
45423
- const checked = await tryGit(invoker, repo, ["index-pack", "--strict", "-o", join47(scratch, "checked.idx"), `${prefix}-${packed.stdout.trim()}.pack`]);
45562
+ const checked = await tryGit(invoker, repo, ["index-pack", "--strict", "-o", join46(scratch, "checked.idx"), `${prefix}-${packed.stdout.trim()}.pack`]);
45424
45563
  if (!checked.ok) throw new PushRefused(`git would not take it (${checked.stderr.trim()})`);
45425
45564
  } finally {
45426
45565
  rmSync14(scratch, { recursive: true, force: true });
@@ -45435,10 +45574,10 @@ async function restoreSnapshot(invoker, worktree, snapshot, linked) {
45435
45574
  await run("reset", "-q");
45436
45575
  }
45437
45576
  async function hooksLandingWouldRun(invoker, worktree) {
45438
- const dir = resolve16(worktree, (await git(invoker, worktree, ["rev-parse", "--git-path", "hooks"])).trim());
45577
+ const dir = resolve17(worktree, (await git(invoker, worktree, ["rev-parse", "--git-path", "hooks"])).trim());
45439
45578
  return LANDING_HOOKS.filter((hook) => {
45440
45579
  try {
45441
- accessSync(resolve16(dir, hook), constants2.X_OK);
45580
+ accessSync(resolve17(dir, hook), constants2.X_OK);
45442
45581
  return true;
45443
45582
  } catch {
45444
45583
  return false;
@@ -45546,7 +45685,7 @@ var DockerExecutionBackend = class {
45546
45685
  */
45547
45686
  async preflight(runner, model) {
45548
45687
  const setupCommand = this.options.setupCommand?.();
45549
- const { problems, settings } = await inspectReadiness(this.options.settings, { cli: this.cli, broker: this.broker, agent: runner !== null, ...runner ? { runner } : {}, ...setupCommand ? { setupCommand } : {} });
45688
+ const { problems, settings } = await inspectReadiness(this.options.settings, { cli: this.cli, broker: this.broker, ...this.options.platform ? { platform: this.options.platform } : {}, agent: runner !== null, ...runner ? { runner } : {}, ...setupCommand ? { setupCommand } : {} });
45550
45689
  if (!settings) throw new Error(`This session runs tasks in containers, and this task cannot start in one. ${describeProblems(problems)}`);
45551
45690
  const refusal4 = runner && settings.login.kind === "broker" ? brokerRefusal(runner, model) : null;
45552
45691
  if (refusal4) throw new Error(`This session runs tasks in containers, and this task cannot start in one. ${refusal4}`);
@@ -45573,7 +45712,7 @@ var DockerExecutionBackend = class {
45573
45712
  }
45574
45713
  async workingDirectory(opened2) {
45575
45714
  const { worktree, writable, cwd } = opened2.workspace;
45576
- return posix13.join(WORK_ROOT, worktree ? relative19(writable ?? cwd, cwd).split(sep12).join("/") : await this.checkoutFolder(cwd));
45715
+ return posix15.join(WORK_ROOT, worktree ? relative18(writable ?? cwd, cwd).split(sep11).join("/") : await this.checkoutFolder(cwd));
45577
45716
  }
45578
45717
  async start({ runner, settings, spec, opened: opened2, repos }, signal) {
45579
45718
  const taskId = spec.task.id;
@@ -45933,10 +46072,10 @@ var DockerExecutionBackend = class {
45933
46072
  */
45934
46073
  bringBack(box) {
45935
46074
  box.bringing ??= (async () => {
45936
- const dir = mkdtempSync8(join48(tmpdir9(), "ordewell-export-"));
46075
+ const dir = mkdtempSync8(join47(tmpdir9(), "ordewell-export-"));
45937
46076
  try {
45938
46077
  const taken = [];
45939
- for (const repo of box.repos) taken.push({ repo, snapshot: await this.take(box, repo, join48(dir, `${taken.length}.bundle`)) });
46078
+ for (const repo of box.repos) taken.push({ repo, snapshot: await this.take(box, repo, join47(dir, `${taken.length}.bundle`)) });
45940
46079
  for (const { repo, snapshot } of taken) await restoreSnapshot(this.git, repo.worktree, snapshot, repo.linked);
45941
46080
  } catch (err) {
45942
46081
  await this.cli.call(["volume", "create", ...this.labels(box.taskId), this.heldVolume(box.taskId)]);
@@ -49294,12 +49433,12 @@ var Session = class {
49294
49433
  return !task2 || reportEnded(task2) || task2.status !== "in_progress" && !this.orchestrator.getAttempt(taskId);
49295
49434
  };
49296
49435
  if (over() || signal?.aborted) return Promise.resolve();
49297
- return new Promise((resolve17) => {
49436
+ return new Promise((resolve18) => {
49298
49437
  const done = () => {
49299
49438
  clearTimeout(timer);
49300
49439
  unsubscribe();
49301
49440
  signal?.removeEventListener("abort", done);
49302
- resolve17();
49441
+ resolve18();
49303
49442
  };
49304
49443
  const timer = setTimeout(done, ms);
49305
49444
  const check2 = () => {
@@ -50495,7 +50634,7 @@ ${pins.join("\n")}` : goal;
50495
50634
  slotForTurn(signal) {
50496
50635
  if (this.turnRoom()) return null;
50497
50636
  if (signal?.aborted) return Promise.reject(new PlannerTurnStoppedError());
50498
- return new Promise((resolve17, reject) => {
50637
+ return new Promise((resolve18, reject) => {
50499
50638
  const onAbort = () => {
50500
50639
  if (this.openingsWaiting.delete(end)) end(new PlannerTurnStoppedError());
50501
50640
  };
@@ -50511,7 +50650,7 @@ ${pins.join("\n")}` : goal;
50511
50650
  this.roomWaiter = null;
50512
50651
  this.openingsWaiting.delete(end);
50513
50652
  signal?.removeEventListener("abort", onAbort);
50514
- resolve17();
50653
+ resolve18();
50515
50654
  return true;
50516
50655
  };
50517
50656
  });
@@ -50522,7 +50661,7 @@ ${pins.join("\n")}` : goal;
50522
50661
  return null;
50523
50662
  }
50524
50663
  if (signal?.aborted) return Promise.reject(new PlannerTurnStoppedError());
50525
- return new Promise((resolve17, reject) => {
50664
+ return new Promise((resolve18, reject) => {
50526
50665
  const onAbort = () => {
50527
50666
  if (this.openingsWaiting.delete(end)) end(new PlannerTurnStoppedError());
50528
50667
  };
@@ -50536,7 +50675,7 @@ ${pins.join("\n")}` : goal;
50536
50675
  if (!this.openingsWaiting.delete(end)) return;
50537
50676
  signal?.removeEventListener("abort", onAbort);
50538
50677
  this.assertPlannerReady();
50539
- }).then(resolve17, reject);
50678
+ }).then(resolve18, reject);
50540
50679
  });
50541
50680
  }
50542
50681
  /**
@@ -50716,8 +50855,8 @@ ${pins.join("\n")}` : goal;
50716
50855
  if (!pending) return null;
50717
50856
  const held2 = pending.held;
50718
50857
  if (!held2) return this.turns.follow(input, forced);
50719
- return new Promise((resolve17, reject) => {
50720
- held2.push({ input, forced, resolve: resolve17, reject });
50858
+ return new Promise((resolve18, reject) => {
50859
+ held2.push({ input, forced, resolve: resolve18, reject });
50721
50860
  });
50722
50861
  }
50723
50862
  /**
@@ -51967,8 +52106,8 @@ var StructuredSession = class extends AbstractRunnerSession {
51967
52106
  if (this.stopping) return this.stopping;
51968
52107
  if (this.exited) return Promise.resolve();
51969
52108
  let woundDown;
51970
- this.stopping = new Promise((resolve17) => {
51971
- woundDown = resolve17;
52109
+ this.stopping = new Promise((resolve18) => {
52110
+ woundDown = resolve18;
51972
52111
  });
51973
52112
  void this.windDown().catch(() => this.kill()).then(woundDown);
51974
52113
  return this.stopping;
@@ -51997,7 +52136,7 @@ var StructuredSession = class extends AbstractRunnerSession {
51997
52136
  }
51998
52137
  /** Whether `turn` closed within the deadline once interrupted. */
51999
52138
  async turnClosed(turn, adapter, deadline) {
52000
- const closed = new Promise((resolve17) => this.structuredEmitter.once("turnEnd", () => resolve17()));
52139
+ const closed = new Promise((resolve18) => this.structuredEmitter.once("turnEnd", () => resolve18()));
52001
52140
  adapter.interrupt(Math.max(0, deadline - Date.now())).catch(() => false);
52002
52141
  return await this.within(closed, deadline) && turn.ended;
52003
52142
  }
@@ -52008,7 +52147,7 @@ var StructuredSession = class extends AbstractRunnerSession {
52008
52147
  gone() {
52009
52148
  const { signal } = this.ended;
52010
52149
  if (signal.aborted) return Promise.resolve();
52011
- return new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
52150
+ return new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
52012
52151
  }
52013
52152
  turnState() {
52014
52153
  return this.state;
@@ -52160,7 +52299,7 @@ var StructuredSession = class extends AbstractRunnerSession {
52160
52299
  }
52161
52300
  async interruptTurn(turn, adapter) {
52162
52301
  const grace = this.launch.interruptGraceMs;
52163
- const ended2 = new Promise((resolve17) => this.structuredEmitter.once("turnEnd", () => resolve17()));
52302
+ const ended2 = new Promise((resolve18) => this.structuredEmitter.once("turnEnd", () => resolve18()));
52164
52303
  const acknowledged = await settleWithin(adapter.interrupt(grace).catch(() => false), { timeoutMs: grace, onTimeout: () => false });
52165
52304
  if (acknowledged) {
52166
52305
  const settled = await settleWithin(ended2.then(() => true), { timeoutMs: grace, onTimeout: () => false });
@@ -52592,11 +52731,11 @@ var RunnerRegistry = class {
52592
52731
  };
52593
52732
 
52594
52733
  // src/plugins/removedPluginNotice.ts
52595
- import * as fs26 from "fs";
52734
+ import * as fs27 from "fs";
52596
52735
  import * as path50 from "path";
52597
52736
  function isManifestFile(file) {
52598
52737
  try {
52599
- return fs26.statSync(file).isFile();
52738
+ return fs27.statSync(file).isFile();
52600
52739
  } catch {
52601
52740
  return false;
52602
52741
  }
@@ -52604,7 +52743,7 @@ function isManifestFile(file) {
52604
52743
  function removedPluginNotice(dataDir = globalDataDir()) {
52605
52744
  const directory = path50.join(dataDir, "plugins");
52606
52745
  try {
52607
- const hasManifest = isManifestFile(path50.join(directory, "manifest.json")) || fs26.readdirSync(directory, { withFileTypes: true }).some(
52746
+ const hasManifest = isManifestFile(path50.join(directory, "manifest.json")) || fs27.readdirSync(directory, { withFileTypes: true }).some(
52608
52747
  (entry) => (entry.isDirectory() || entry.isSymbolicLink()) && isManifestFile(path50.join(directory, entry.name, "manifest.json"))
52609
52748
  );
52610
52749
  if (hasManifest) return "Plugin runners were removed; manifests in ~/.ordewell/plugins/ are ignored. See the CHANGELOG.";
@@ -52615,7 +52754,7 @@ function removedPluginNotice(dataDir = globalDataDir()) {
52615
52754
  }
52616
52755
 
52617
52756
  // src/utils/stateStore.ts
52618
- import * as fs27 from "fs";
52757
+ import * as fs28 from "fs";
52619
52758
  import * as path51 from "path";
52620
52759
  var STATE_FILE2 = "state.json";
52621
52760
  function getStatePath(baseDir) {
@@ -52633,9 +52772,9 @@ function saveState(plan, baseDir, sessionId) {
52633
52772
  function loadState(baseDir, logger = defaultLogger) {
52634
52773
  const dir = baseDir ?? process.cwd();
52635
52774
  const statePath = getStatePath(dir);
52636
- if (!fs27.existsSync(statePath)) return null;
52775
+ if (!fs28.existsSync(statePath)) return null;
52637
52776
  try {
52638
- const raw = fs27.readFileSync(statePath, "utf-8");
52777
+ const raw = fs28.readFileSync(statePath, "utf-8");
52639
52778
  const parsed = JSON.parse(raw);
52640
52779
  if (!Array.isArray(parsed.runners)) {
52641
52780
  logger.warn("stateStore", `rejecting state from ${statePath}: old format (scalar "runner" instead of "runners" array). Please re-plan.`);
@@ -52659,11 +52798,11 @@ function loadState(baseDir, logger = defaultLogger) {
52659
52798
  function clearState(baseDir) {
52660
52799
  const dir = baseDir ?? process.cwd();
52661
52800
  const statePath = getStatePath(dir);
52662
- if (fs27.existsSync(statePath)) fs27.unlinkSync(statePath);
52801
+ if (fs28.existsSync(statePath)) fs28.unlinkSync(statePath);
52663
52802
  }
52664
52803
  function stateExists(baseDir) {
52665
52804
  const dir = baseDir ?? process.cwd();
52666
- return fs27.existsSync(getStatePath(dir));
52805
+ return fs28.existsSync(getStatePath(dir));
52667
52806
  }
52668
52807
 
52669
52808
  // src/services/selectPlanner.ts