@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.js CHANGED
@@ -1115,14 +1115,14 @@ var VerdictEngine = class {
1115
1115
  if (this.toolCheckpoints.has(taskId)) {
1116
1116
  return Promise.resolve({ kind: "withdrawn", why: "another checkpoint is still waiting for an answer. Wait for it before asking again." });
1117
1117
  }
1118
- return new Promise((resolve17) => {
1118
+ return new Promise((resolve18) => {
1119
1119
  const settle = (answer2) => {
1120
1120
  signal.removeEventListener("abort", onAbort);
1121
1121
  if (this.toolCheckpoints.get(taskId) === settle) {
1122
1122
  this.toolCheckpoints.delete(taskId);
1123
1123
  this.checkpointQuestions.delete(taskId);
1124
1124
  }
1125
- resolve17(answer2);
1125
+ resolve18(answer2);
1126
1126
  };
1127
1127
  const onAbort = () => {
1128
1128
  settle({ kind: "withdrawn", why: "the call was cancelled." });
@@ -5813,6 +5813,10 @@ function exclusionWord(pattern) {
5813
5813
  function isScopePattern(entry) {
5814
5814
  return /^(\/|~|https?:\/\/|web_search:|mcp__|mcp-server:|[A-Za-z]:[\\/])/.test(entry);
5815
5815
  }
5816
+ var backslashed = (scope) => scope.replace(/\//g, "\\");
5817
+ function scopeExclusion(entry) {
5818
+ return /^[A-Za-z]:[\\/]/.test(entry) ? globRegExp(backslashed(entry), "i") : globRegExp(entry);
5819
+ }
5816
5820
  function parseAllowlist(entries) {
5817
5821
  const list2 = { commands: [], commandExclusions: [], tools: [], toolExclusions: [], scopes: [], scopeExclusions: [] };
5818
5822
  for (const raw of entries) {
@@ -5822,7 +5826,8 @@ function parseAllowlist(entries) {
5822
5826
  if (entry.startsWith("mcp:")) {
5823
5827
  (exclude ? list2.toolExclusions : list2.tools).push(globRegExp(entry.slice(4).trim(), "i"));
5824
5828
  } else if (isScopePattern(entry)) {
5825
- (exclude ? list2.scopeExclusions : list2.scopes).push(globRegExp(entry));
5829
+ if (exclude) list2.scopeExclusions.push(scopeExclusion(entry));
5830
+ else list2.scopes.push(globRegExp(entry));
5826
5831
  } else {
5827
5832
  const [binary, ...words] = entry.split(/\s+/);
5828
5833
  (exclude ? list2.commandExclusions : list2.commands).push({ text: raw.trim(), binary, words: words.map(exclude ? exclusionWord : ruleWord) });
@@ -5870,7 +5875,7 @@ function toolAllowed(list2, tool2) {
5870
5875
  }
5871
5876
  function scopeExcluded(list2, scope) {
5872
5877
  const origin = /^(?:curl|wget) (https?:\/\/\S+\/\*)$/.exec(scope)?.[1];
5873
- return list2.scopeExclusions.some((re) => re.test(scope) || origin !== void 0 && re.test(origin));
5878
+ return list2.scopeExclusions.some((re) => re.test(scope) || re.test(backslashed(scope)) || origin !== void 0 && re.test(origin));
5874
5879
  }
5875
5880
  function scopeAllowed(list2, scope) {
5876
5881
  if (scopeExcluded(list2, scope)) return false;
@@ -6244,13 +6249,13 @@ function vetHostUnresolved(host) {
6244
6249
  if (LOCAL_NAMES.has(bare.toLowerCase())) return { ok: false, reason: `local host name ${bare}` };
6245
6250
  return void 0;
6246
6251
  }
6247
- async function vetHost(host, resolve17) {
6252
+ async function vetHost(host, resolve18) {
6248
6253
  const settled = vetHostUnresolved(host);
6249
6254
  if (settled) return settled;
6250
6255
  const bare = stripBrackets(host);
6251
6256
  let addresses;
6252
6257
  try {
6253
- addresses = await resolve17(bare);
6258
+ addresses = await resolve18(bare);
6254
6259
  } catch {
6255
6260
  return { ok: false, reason: `${bare} did not resolve` };
6256
6261
  }
@@ -6261,16 +6266,16 @@ async function vetHost(host, resolve17) {
6261
6266
  }
6262
6267
  return { ok: true, addresses };
6263
6268
  }
6264
- async function vetEgress(host, port, resolve17 = resolveAll) {
6265
- return vetEgressUnresolved(host, port) ?? vetHost(host, resolve17);
6269
+ async function vetEgress(host, port, resolve18 = resolveAll) {
6270
+ return vetEgressUnresolved(host, port) ?? vetHost(host, resolve18);
6266
6271
  }
6267
6272
  function vetEgressUnresolved(host, port) {
6268
6273
  if (!ALLOWED_PORTS.has(port)) return { ok: false, reason: `port ${port} is not 80 or 443` };
6269
6274
  return vetHostUnresolved(host);
6270
6275
  }
6271
- function guardedLookup(resolve17 = resolveAll) {
6276
+ function guardedLookup(resolve18 = resolveAll) {
6272
6277
  return (hostname, options, callback) => {
6273
- void vetHost(hostname, resolve17).then((check2) => {
6278
+ void vetHost(hostname, resolve18).then((check2) => {
6274
6279
  if (!check2.ok) {
6275
6280
  callback(Object.assign(new Error(`blocked host: ${check2.reason}`), { code: "EBLOCKEDHOST" }), []);
6276
6281
  return;
@@ -7556,14 +7561,14 @@ function keptEnv(invocation, profile) {
7556
7561
  return profile.inheritEnv === void 0 ? invocation.env : Object.fromEntries(profile.inheritEnv.flatMap((name) => invocation.env[name] === void 0 ? [] : [[name, invocation.env[name]]]));
7557
7562
  }
7558
7563
  var PROBE_TIMEOUT_MS = 1e4;
7559
- var execProbe = (file, args, env) => new Promise((resolve17) => {
7564
+ var execProbe = (file, args, env) => new Promise((resolve18) => {
7560
7565
  try {
7561
7566
  (0, import_child_process.execFile)(file, args, { env, timeout: PROBE_TIMEOUT_MS, encoding: "utf8" }, (err, stdout, stderr) => {
7562
7567
  const code = !err ? 0 : typeof err.code === "number" ? err.code : null;
7563
- resolve17({ code, output: `${stdout ?? ""}${stderr ?? ""}`.trim() || (err?.message ?? "") });
7568
+ resolve18({ code, output: `${stdout ?? ""}${stderr ?? ""}`.trim() || (err?.message ?? "") });
7564
7569
  });
7565
7570
  } catch (err) {
7566
- resolve17({ code: null, output: err instanceof Error ? err.message : String(err) });
7571
+ resolve18({ code: null, output: err instanceof Error ? err.message : String(err) });
7567
7572
  }
7568
7573
  });
7569
7574
  async function probeByRunning(backend, profile, exec5) {
@@ -8021,12 +8026,12 @@ function killTree(proc, deps = {}) {
8021
8026
  if (typeof proc.pid !== "number") return;
8022
8027
  const pid = proc.pid;
8023
8028
  const run = deps.execFileImpl ?? defaultExecFile;
8024
- run("taskkill", ["/pid", String(pid), "/T"], () => {
8029
+ const force = () => run("taskkill", ["/pid", String(pid), "/T", "/F"], () => {
8025
8030
  });
8026
- const hardKill = setTimeoutImpl(() => {
8027
- run("taskkill", ["/pid", String(pid), "/T", "/F"], () => {
8028
- });
8029
- }, HARD_KILL_DELAY_MS);
8031
+ run("taskkill", ["/pid", String(pid), "/T"], (err) => {
8032
+ if (err && !hasExited(proc)) force();
8033
+ });
8034
+ const hardKill = setTimeoutImpl(force, HARD_KILL_DELAY_MS);
8030
8035
  hardKill.unref?.();
8031
8036
  proc.once("exit", () => clearTimeoutImpl(hardKill));
8032
8037
  return;
@@ -8350,8 +8355,8 @@ function createScratch() {
8350
8355
  return dir;
8351
8356
  }
8352
8357
  var PlannerShellSandbox = class _PlannerShellSandbox {
8353
- constructor(resolve17 = () => resolvePlannerSandbox()) {
8354
- this.resolve = resolve17;
8358
+ constructor(resolve18 = () => resolvePlannerSandbox()) {
8359
+ this.resolve = resolve18;
8355
8360
  }
8356
8361
  resolve;
8357
8362
  scratch = /* @__PURE__ */ new Map();
@@ -9504,33 +9509,33 @@ function grepOptions(args) {
9504
9509
  };
9505
9510
  }
9506
9511
  var STOPPED_TOOL_RESULT = "Stopped by the user \u2014 this call was not executed, and no further tool calls will run this turn.";
9507
- async function executeTool(name, args, fs28, fetcher, signal) {
9508
- const outcome = await runTool(name, args, fs28, fetcher, signal);
9512
+ async function executeTool(name, args, fs29, fetcher, signal) {
9513
+ const outcome = await runTool(name, args, fs29, fetcher, signal);
9509
9514
  return { ...outcome, output: redactSecrets(outcome.output) };
9510
9515
  }
9511
- async function runTool(name, args, fs28, fetcher, signal) {
9516
+ async function runTool(name, args, fs29, fetcher, signal) {
9512
9517
  if (signal?.aborted) return { success: false, output: STOPPED_TOOL_RESULT, truncated: false };
9513
9518
  switch (name) {
9514
9519
  case "read_file": {
9515
9520
  const offset = num(args.offset);
9516
9521
  const limit = num(args.limit);
9517
9522
  const maxBytes = num(args.maxBytes);
9518
- return fs28.readFile(String(args.path ?? ""), { offset, limit, maxBytes });
9523
+ return fs29.readFile(String(args.path ?? ""), { offset, limit, maxBytes });
9519
9524
  }
9520
9525
  case "read_files": {
9521
9526
  const paths = Array.isArray(args.paths) ? args.paths.map(String) : [];
9522
- return fs28.readFiles(paths);
9527
+ return fs29.readFiles(paths);
9523
9528
  }
9524
9529
  case "glob":
9525
- return fs28.glob(String(args.pattern ?? ""), { path: str(args.path), headLimit: num(args.head_limit ?? args.headLimit) });
9530
+ return fs29.glob(String(args.pattern ?? ""), { path: str(args.path), headLimit: num(args.head_limit ?? args.headLimit) });
9526
9531
  case "grep":
9527
- return fs28.grep(String(args.pattern ?? ""), grepOptions(args));
9532
+ return fs29.grep(String(args.pattern ?? ""), grepOptions(args));
9528
9533
  case "find_symbol":
9529
- return fs28.findSymbol(String(args.symbol ?? ""), { language: str(args.language), path: str(args.path) });
9534
+ return fs29.findSymbol(String(args.symbol ?? ""), { language: str(args.language), path: str(args.path) });
9530
9535
  case "list_dir":
9531
- return fs28.listDir(String(args.path ?? ""), num(args.depth));
9536
+ return fs29.listDir(String(args.path ?? ""), num(args.depth));
9532
9537
  case "bash":
9533
- return args.sealed === true ? fs28.bash(String(args.command ?? ""), signal, { sealed: true }) : fs28.bash(String(args.command ?? ""), signal);
9538
+ return args.sealed === true ? fs29.bash(String(args.command ?? ""), signal, { sealed: true }) : fs29.bash(String(args.command ?? ""), signal);
9534
9539
  case "fetch": {
9535
9540
  if (!fetcher) return { success: false, output: "Web fetching is not available in this environment.", truncated: false };
9536
9541
  return fetcher.fetch(String(args.url ?? ""));
@@ -10302,7 +10307,7 @@ function decodedBody(res) {
10302
10307
  return decoder;
10303
10308
  }
10304
10309
  function pinnedTransport(lookup2) {
10305
- return (url, init) => new Promise((resolve17, reject) => {
10310
+ return (url, init) => new Promise((resolve18, reject) => {
10306
10311
  const target = new URL(url);
10307
10312
  const client = target.protocol === "https:" ? https : http;
10308
10313
  const req = client.request(
@@ -10323,7 +10328,7 @@ function pinnedTransport(lookup2) {
10323
10328
  (res) => {
10324
10329
  res.on("error", () => void 0);
10325
10330
  const body = decodedBody(res);
10326
- resolve17({
10331
+ resolve18({
10327
10332
  ok: res.statusCode !== void 0 && res.statusCode >= 200 && res.statusCode < 300,
10328
10333
  status: res.statusCode ?? 0,
10329
10334
  headers: headerGetter(res),
@@ -10666,7 +10671,7 @@ var PendingApprovals = class {
10666
10671
  return Promise.resolve(refused5);
10667
10672
  }
10668
10673
  const pending = { id: id2, request, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
10669
- return new Promise((resolve17) => {
10674
+ return new Promise((resolve18) => {
10670
10675
  const settle = (decision) => {
10671
10676
  const entry = this.entries.get(id2);
10672
10677
  if (!entry) return;
@@ -10674,7 +10679,7 @@ var PendingApprovals = class {
10674
10679
  this.entries.delete(id2);
10675
10680
  options.onDecision?.(decision);
10676
10681
  this.opts.onSettled?.(id2, isGranted(decision), { request, decision });
10677
- resolve17(decision);
10682
+ resolve18(decision);
10678
10683
  };
10679
10684
  let timer = null;
10680
10685
  if (!options.noTimeout) {
@@ -11587,16 +11592,35 @@ function grepRegexFromProbe(exitCode) {
11587
11592
  return exitCode === 0 || exitCode === 1 ? "pcre" : "ere";
11588
11593
  }
11589
11594
  function toPosixClasses(pattern) {
11595
+ const converted = convertForEre(pattern, true);
11596
+ return converted ?? convertForEre(pattern, false);
11597
+ }
11598
+ var BACKREFERENCE = /\0([1-9])\0/g;
11599
+ function convertForEre(pattern, plainGroups) {
11590
11600
  const CLASS_ESCAPES = { s: "[:space:]", w: "[:alnum:]_", d: "[:digit:]", t: " " };
11601
+ const groupOf = [];
11602
+ let groups = 0;
11603
+ let captures = 0;
11591
11604
  let out = "";
11592
11605
  let i = 0;
11593
11606
  while (i < pattern.length) {
11594
11607
  const c = pattern[i];
11595
11608
  if (c === "\\") {
11596
- out += pattern.slice(i, i + 2);
11609
+ const next = pattern[i + 1] ?? "";
11610
+ out += /[1-9]/.test(next) ? `\0${next}\0` : pattern.slice(i, i + 2);
11597
11611
  i += 2;
11598
11612
  continue;
11599
11613
  }
11614
+ if (c === "(") {
11615
+ groups++;
11616
+ if (plainGroups && pattern.startsWith("(?:", i)) {
11617
+ out += "(";
11618
+ i += 3;
11619
+ continue;
11620
+ }
11621
+ const named3 = /^\(\?(?:P?<(?![=!])|')/.test(pattern.slice(i, i + 4));
11622
+ if (pattern[i + 1] !== "?" || named3) groupOf[++captures] = groups;
11623
+ }
11600
11624
  if (c !== "[") {
11601
11625
  out += c;
11602
11626
  i++;
@@ -11648,7 +11672,13 @@ function toPosixClasses(pattern) {
11648
11672
  }
11649
11673
  out += `[${negate ? "^" : ""}${closeBracket ? "]" : ""}${body}${openBracket ? "[" : ""}${dash ? "-" : ""}]`;
11650
11674
  }
11651
- return out;
11675
+ let representable = true;
11676
+ const renumbered2 = out.replace(BACKREFERENCE, (_, n) => {
11677
+ const group = plainGroups ? groupOf[Number(n)] ?? Number(n) : Number(n);
11678
+ if (group > 9) representable = false;
11679
+ return `\\${group}`;
11680
+ });
11681
+ return representable ? renumbered2 : null;
11652
11682
  }
11653
11683
  function buildFallbackGrepArgs(pattern, opts, root, regex = "pcre") {
11654
11684
  const args = ["-r", "-n"];
@@ -11684,7 +11714,7 @@ function filterFallbackByAnchoredInclude(stdout, include, anchor, outputMode) {
11684
11714
  if (!line) return false;
11685
11715
  const reportedPath = extractFallbackGrepPath(line, outputMode);
11686
11716
  const relPath = import_node_path.default.isAbsolute(reportedPath) ? import_node_path.default.relative(anchor, reportedPath) : reportedPath;
11687
- return matchesAnchoredGlob(relPath, include);
11717
+ return matchesAnchoredGlob(relPath.split(import_node_path.default.sep).join("/"), include);
11688
11718
  }).join("\n");
11689
11719
  }
11690
11720
  function applyHeadLimit(stdout, headLimit) {
@@ -11693,9 +11723,14 @@ function applyHeadLimit(stdout, headLimit) {
11693
11723
  }
11694
11724
  function formatSearchOutput(capped, root, opts) {
11695
11725
  if (capped.rows.length === 0) return opts.emptyMessage;
11696
- const sep14 = opts.sep ?? import_node_path.default.sep;
11697
- const prefix = root === sep14 || root.endsWith(sep14) ? root : `${root}${sep14}`;
11698
- const body = prefix === sep14 ? capped.rows.join("\n") : capped.rows.map((row) => row.startsWith(prefix) ? row.slice(prefix.length) : row).join("\n");
11726
+ const sep13 = opts.sep ?? import_node_path.default.sep;
11727
+ const prefix = root === sep13 || root.endsWith(sep13) ? root : `${root}${sep13}`;
11728
+ const prefixes = sep13 === "\\" ? [prefix, `${prefix.slice(0, -1)}/`] : [prefix];
11729
+ const strip = (row) => {
11730
+ const found = prefixes.find((p) => row.startsWith(p));
11731
+ return found ? row.slice(found.length) : row;
11732
+ };
11733
+ const body = prefix === sep13 ? capped.rows.join("\n") : capped.rows.map(strip).join("\n");
11699
11734
  if (!capped.truncated) return body;
11700
11735
  const hint = opts.hint ? ` ${opts.hint}` : "";
11701
11736
  return `${body}
@@ -11813,9 +11848,9 @@ function claudeManagedSettingsDir(platform = process.platform) {
11813
11848
  }
11814
11849
  function readClaudeSettingsModels(files, platform = process.platform) {
11815
11850
  const managed = claudeManagedSettingsDir(platform);
11816
- const join52 = platform === "win32" ? path13.win32.join : path13.posix.join;
11817
- const dropIns = files.list(join52(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => join52(managed, "managed-settings.d", name));
11818
- const ranked = [...dropIns.reverse(), join52(managed, "managed-settings.json"), join52(claudeConfigDir(files.env), "settings.json")];
11851
+ const join51 = platform === "win32" ? path13.win32.join : path13.posix.join;
11852
+ 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));
11853
+ const ranked = [...dropIns.reverse(), join51(managed, "managed-settings.json"), join51(claudeConfigDir(files.env), "settings.json")];
11819
11854
  for (const file of ranked) {
11820
11855
  const content = files.read(file);
11821
11856
  const lineup = content === null ? null : parseClaudeSettingsModels(content);
@@ -13565,7 +13600,7 @@ var OrdewellMcpServer = class {
13565
13600
  this.boundHost = void 0;
13566
13601
  if (!http2) return;
13567
13602
  http2.closeAllConnections();
13568
- await new Promise((resolve17) => http2.close(() => resolve17()));
13603
+ await new Promise((resolve18) => http2.close(() => resolve18()));
13569
13604
  }
13570
13605
  async issue(grant) {
13571
13606
  const url = await this.start();
@@ -13574,7 +13609,7 @@ var OrdewellMcpServer = class {
13574
13609
  return { url, token };
13575
13610
  }
13576
13611
  start() {
13577
- this.listening ??= new Promise((resolve17, reject) => {
13612
+ this.listening ??= new Promise((resolve18, reject) => {
13578
13613
  const http2 = (0, import_http.createServer)((req, res) => {
13579
13614
  this.handle(req, res).catch(() => {
13580
13615
  if (!res.headersSent) reply(res, 500, "Internal error");
@@ -13593,7 +13628,7 @@ var OrdewellMcpServer = class {
13593
13628
  }
13594
13629
  this.boundHost = `127.0.0.1:${address.port}`;
13595
13630
  this.boundUrl = `http://${this.boundHost}${ORDEWELL_MCP_PATH}`;
13596
- resolve17(this.boundUrl);
13631
+ resolve18(this.boundUrl);
13597
13632
  });
13598
13633
  http2.unref();
13599
13634
  this.http = http2;
@@ -14416,28 +14451,28 @@ function posixBinDirs() {
14416
14451
  ];
14417
14452
  }
14418
14453
  function windowsBinDirs(env, home) {
14419
- const join52 = (...parts) => path15.win32.join(...parts);
14420
- const under = (base, ...parts) => base ? [join52(base, ...parts)] : [];
14454
+ const join51 = (...parts) => path15.win32.join(...parts);
14455
+ const under = (base, ...parts) => base ? [join51(base, ...parts)] : [];
14421
14456
  const appData = env.APPDATA;
14422
14457
  const localAppData = env.LOCALAPPDATA;
14423
14458
  const programData = env.ProgramData;
14424
14459
  return [
14425
14460
  // Native per-user installers, PowerShell-driven and otherwise.
14426
- join52(home, ".local", "bin"),
14427
- join52(home, ".opencode", "bin"),
14428
- join52(home, ".claude", "bin"),
14429
- join52(home, ".codex", "bin"),
14461
+ join51(home, ".local", "bin"),
14462
+ join51(home, ".opencode", "bin"),
14463
+ join51(home, ".claude", "bin"),
14464
+ join51(home, ".codex", "bin"),
14430
14465
  ...under(localAppData, "Programs", "claude"),
14431
14466
  // Node package managers. npm's global prefix is `%APPDATA%\npm`; the
14432
14467
  // literal spelling is kept as a fallback for a host that does not export
14433
14468
  // APPDATA (a service account, a stripped CI container).
14434
14469
  ...under(appData, "npm"),
14435
- join52(home, "AppData", "Roaming", "npm"),
14470
+ join51(home, "AppData", "Roaming", "npm"),
14436
14471
  ...under(localAppData, "pnpm"),
14437
14472
  ...under(localAppData, "Yarn", "bin"),
14438
- join52(home, ".bun", "bin"),
14473
+ join51(home, ".bun", "bin"),
14439
14474
  // Windows package managers.
14440
- join52(home, "scoop", "shims"),
14475
+ join51(home, "scoop", "shims"),
14441
14476
  ...under(env.SCOOP, "shims"),
14442
14477
  ...under(env.SCOOP_GLOBAL ?? programData, "scoop", "shims"),
14443
14478
  ...under(programData, "chocolatey", "bin"),
@@ -14447,7 +14482,7 @@ function windowsBinDirs(env, home) {
14447
14482
  ...under(localAppData, "Microsoft", "WindowsApps"),
14448
14483
  // Version managers. Volta's Windows home is not the POSIX `~/.volta`.
14449
14484
  ...under(localAppData, "Volta", "bin"),
14450
- join52(home, ".volta", "bin")
14485
+ join51(home, ".volta", "bin")
14451
14486
  ];
14452
14487
  }
14453
14488
  function wellKnownBinDirs(deps = {}) {
@@ -14558,7 +14593,7 @@ var BatchQuoteError = class extends Error {
14558
14593
 
14559
14594
  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.
14560
14595
 
14561
- 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.`
14596
+ 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.`
14562
14597
  );
14563
14598
  this.command = command;
14564
14599
  this.name = "BatchQuoteError";
@@ -14579,12 +14614,17 @@ Searched: ${searchedPath || "(empty PATH)"}`);
14579
14614
  };
14580
14615
  function isResolvableOnPosixPath(command, PATH, exists) {
14581
14616
  if (command.includes("/")) return exists(command);
14582
- return PATH.split(path16.delimiter).map((d) => d.trim()).filter(Boolean).some((dir) => exists(path16.join(dir, command)));
14617
+ return PATH.split(path16.posix.delimiter).map((d) => d.trim()).filter(Boolean).some((dir) => exists(path16.posix.join(dir, command)));
14583
14618
  }
14584
14619
  function isExecutableResolved(command, plan, PATH, deps = {}) {
14585
- if ((deps.platform ?? process.platform) === "win32") return plan.file !== command;
14620
+ if ((deps.platform ?? process.platform) === "win32") return plan.file !== command || namesDirectFile(command, deps);
14586
14621
  return isResolvableOnPosixPath(command, PATH, deps.exists ?? defaultExists3);
14587
14622
  }
14623
+ function namesDirectFile(command, deps) {
14624
+ if (path16.win32.basename(command) === command) return false;
14625
+ const pathExt = (deps.pathExt ?? (() => process.env.PATHEXT ?? ""))();
14626
+ return candidateExtensions(command, pathExt).direct.includes("") && (deps.exists ?? defaultExists3)(command);
14627
+ }
14588
14628
  function defaultExists3(candidate) {
14589
14629
  try {
14590
14630
  return fsSync4.statSync(candidate).isFile();
@@ -15313,10 +15353,10 @@ var DIRENV_TIMEOUT_MS = 5e3;
15313
15353
  var KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
15314
15354
  function defaultDeps() {
15315
15355
  return {
15316
- run: (command, args, opts) => new Promise((resolve17) => {
15356
+ run: (command, args, opts) => new Promise((resolve18) => {
15317
15357
  (0, import_child_process4.execFile)(command, args, { ...opts, timeout: DIRENV_TIMEOUT_MS, encoding: "utf8" }, (err, stdout, stderr) => {
15318
15358
  const code = err ? typeof err.code === "number" ? Number(err.code) : -1 : 0;
15319
- resolve17({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
15359
+ resolve18({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
15320
15360
  });
15321
15361
  }),
15322
15362
  readFile: (file) => {
@@ -15405,10 +15445,10 @@ async function fromDirenv(cwd, deps) {
15405
15445
  }
15406
15446
  return { env, blocked: null };
15407
15447
  }
15408
- function findUp(start, relative21, deps) {
15448
+ function findUp(start, relative20, deps) {
15409
15449
  let dir = path19.resolve(start);
15410
15450
  for (; ; ) {
15411
- const candidate = path19.join(dir, relative21);
15451
+ const candidate = path19.join(dir, relative20);
15412
15452
  if (deps.readFile(candidate) !== null) return candidate;
15413
15453
  const parent = path19.dirname(dir);
15414
15454
  if (parent === dir) return null;
@@ -15453,14 +15493,14 @@ function parseEnvFile(content, context, home) {
15453
15493
 
15454
15494
  // src/services/harness/settleWithin.ts
15455
15495
  function settleWithin(promise, wait) {
15456
- return new Promise((resolve17, reject) => {
15496
+ return new Promise((resolve18, reject) => {
15457
15497
  let settled = false;
15458
15498
  const settle = (outcome) => {
15459
15499
  if (settled) return;
15460
15500
  settled = true;
15461
15501
  clearTimeout(timer);
15462
15502
  try {
15463
- resolve17(outcome());
15503
+ resolve18(outcome());
15464
15504
  } catch (err) {
15465
15505
  reject(err);
15466
15506
  }
@@ -15523,14 +15563,14 @@ function unlessCancelled(work, signal) {
15523
15563
  if (!signal) return work;
15524
15564
  work.catch(() => {
15525
15565
  });
15526
- return new Promise((resolve17, reject) => {
15566
+ return new Promise((resolve18, reject) => {
15527
15567
  if (signal.aborted) {
15528
- resolve17(CANCELLED2);
15568
+ resolve18(CANCELLED2);
15529
15569
  return;
15530
15570
  }
15531
- const onAbort = () => resolve17(CANCELLED2);
15571
+ const onAbort = () => resolve18(CANCELLED2);
15532
15572
  signal.addEventListener("abort", onAbort, { once: true });
15533
- work.then(resolve17, reject).finally(() => signal.removeEventListener("abort", onAbort));
15573
+ work.then(resolve18, reject).finally(() => signal.removeEventListener("abort", onAbort));
15534
15574
  });
15535
15575
  }
15536
15576
  async function spawnAttached(steps) {
@@ -15629,8 +15669,8 @@ async function awaitAttach(probe, timeoutMs, pollMs, ended2) {
15629
15669
  const state = await settleWithin(probe(left), ended2 ? { timeoutMs: left, onTimeout, ended: ended2, onEnded: () => "failed" } : { timeoutMs: left, onTimeout });
15630
15670
  if (state !== "pending") return state;
15631
15671
  if (pollMs > 0) {
15632
- await new Promise((resolve17) => {
15633
- const timer = setTimeout(resolve17, pollMs);
15672
+ await new Promise((resolve18) => {
15673
+ const timer = setTimeout(resolve18, pollMs);
15634
15674
  timer.unref?.();
15635
15675
  });
15636
15676
  }
@@ -15847,8 +15887,8 @@ function releasePipes(child) {
15847
15887
  var RunnerProcess = class {
15848
15888
  constructor(deps) {
15849
15889
  this.deps = deps;
15850
- this.ended = new Promise((resolve17) => {
15851
- this.markEnded = resolve17;
15890
+ this.ended = new Promise((resolve18) => {
15891
+ this.markEnded = resolve18;
15852
15892
  });
15853
15893
  }
15854
15894
  deps;
@@ -15897,7 +15937,8 @@ var RunnerProcess = class {
15897
15937
  const PATH = await resolvePath();
15898
15938
  const launch = await planDirectLaunch(command.command, command.args, {
15899
15939
  platform: this.deps.platform,
15900
- resolvePath
15940
+ resolvePath,
15941
+ exists: this.deps.exists
15901
15942
  });
15902
15943
  if (!isExecutableResolved(command.command, launch, PATH, { platform: this.deps.platform, exists: this.deps.exists })) {
15903
15944
  throw new ExecutableNotFoundError(command.command, PATH);
@@ -16314,7 +16355,7 @@ var StdioAgentAdapter = class extends ProcessLifecycle {
16314
16355
  onEvent({ type: "error", message: this.exitMessage() });
16315
16356
  return;
16316
16357
  }
16317
- await new Promise((resolve17, reject) => {
16358
+ await new Promise((resolve18, reject) => {
16318
16359
  let settled = false;
16319
16360
  const release2 = () => {
16320
16361
  settled = true;
@@ -16326,7 +16367,7 @@ var StdioAgentAdapter = class extends ProcessLifecycle {
16326
16367
  const finish2 = () => {
16327
16368
  if (settled) return;
16328
16369
  release2();
16329
- resolve17();
16370
+ resolve18();
16330
16371
  };
16331
16372
  const fail = (err) => {
16332
16373
  if (settled) return;
@@ -16540,7 +16581,7 @@ var PermissionLedger = class {
16540
16581
  const open = this.open.get(id2);
16541
16582
  if (!open || this.answering.has(id2)) return false;
16542
16583
  this.answering.add(id2);
16543
- const sent = new Promise((resolve17) => resolve17(this.reply(open.handle, decision)));
16584
+ const sent = new Promise((resolve18) => resolve18(this.reply(open.handle, decision)));
16544
16585
  return this.awaitReply(id2, open, sent);
16545
16586
  }
16546
16587
  async awaitReply(id2, open, sent) {
@@ -17394,8 +17435,8 @@ var ClaudeCodeAdapter = class extends StdioAgentAdapter {
17394
17435
  if (!this.process) return Promise.resolve(null);
17395
17436
  this.controlCount += 1;
17396
17437
  const requestId = `ordewell-${request.subtype}-${this.controlCount}`;
17397
- const answered3 = new Promise((resolve17) => {
17398
- this.pendingControl.set(requestId, resolve17);
17438
+ const answered3 = new Promise((resolve18) => {
17439
+ this.pendingControl.set(requestId, resolve18);
17399
17440
  });
17400
17441
  this.writeLine({ type: "control_request", request_id: requestId, request });
17401
17442
  return settleWithin(answered3, { timeoutMs, ended: this.processEnded, onTimeout: () => null, onEnded: () => null }).finally(() => {
@@ -17900,7 +17941,7 @@ var ClaudeCodeAdapter = class extends StdioAgentAdapter {
17900
17941
 
17901
17942
  // src/services/harness/CodexAdapter.ts
17902
17943
  var import_crypto7 = require("crypto");
17903
- var import_path6 = require("path");
17944
+ var hostPath = __toESM(require("path"));
17904
17945
 
17905
17946
  // src/services/harness/codexSandbox.ts
17906
17947
  var CODEX_RUNNER = "codex";
@@ -18010,7 +18051,7 @@ var CodexSandboxAvailability = class {
18010
18051
  async function runProbe(deps, cwd, env, flags) {
18011
18052
  const args = ["sandbox", ...flags, "--", "/bin/true"];
18012
18053
  const placed = await deps.placement?.place({ command: "codex", args, env: {}, files: [] });
18013
- return new Promise((resolve17) => {
18054
+ return new Promise((resolve18) => {
18014
18055
  let output = "";
18015
18056
  let settled = false;
18016
18057
  let proc = null;
@@ -18019,7 +18060,7 @@ async function runProbe(deps, cwd, env, flags) {
18019
18060
  settled = true;
18020
18061
  clearTimeout(timer);
18021
18062
  placed?.ended();
18022
- resolve17({ code, output });
18063
+ resolve18({ code, output });
18023
18064
  };
18024
18065
  const timer = setTimeout(() => {
18025
18066
  placed?.stop();
@@ -18205,7 +18246,7 @@ var CodexRpc = class {
18205
18246
  }
18206
18247
  /** The request as the awaited form of {@link send}, for steps that wait on one answer and nothing else. */
18207
18248
  call(method, params) {
18208
- return new Promise((resolve17) => this.send(method, params, (response) => resolve17(response)));
18249
+ return new Promise((resolve18) => this.send(method, params, (response) => resolve18(response)));
18209
18250
  }
18210
18251
  /**
18211
18252
  * A request framed as the line to write, left to the caller to write — for
@@ -18747,8 +18788,8 @@ ${this.exitMessage()}`);
18747
18788
  return awaitAttach(async (left) => {
18748
18789
  const known = CODEX_ORDEWELL.attachState(this.mcpStartup);
18749
18790
  if (known !== "pending") return known;
18750
- const reported2 = new Promise((resolve17) => {
18751
- this.mcpStartupSettled = () => resolve17(CODEX_ORDEWELL.attachState(this.mcpStartup));
18791
+ const reported2 = new Promise((resolve18) => {
18792
+ this.mcpStartupSettled = () => resolve18(CODEX_ORDEWELL.attachState(this.mcpStartup));
18752
18793
  });
18753
18794
  const state = await settleWithin(reported2, {
18754
18795
  timeoutMs: left,
@@ -18773,10 +18814,10 @@ ${this.exitMessage()}`);
18773
18814
  const turn = this.turn;
18774
18815
  if (!this.process || !turn) return Promise.resolve(false);
18775
18816
  this.interruptRequested = true;
18776
- const acknowledged = new Promise((resolve17) => {
18817
+ const acknowledged = new Promise((resolve18) => {
18777
18818
  this.whenNamed(turn, () => this.rpc.send("turn/interrupt", { threadId: this.threadId, turnId: turn.id }, (response) => {
18778
18819
  if (!response.ok) this.interruptRequested = false;
18779
- resolve17(response.ok);
18820
+ resolve18(response.ok);
18780
18821
  }));
18781
18822
  });
18782
18823
  return settleWithin(acknowledged, { timeoutMs, ended: this.processEnded, onTimeout: () => false, onEnded: () => false });
@@ -18798,7 +18839,7 @@ ${this.exitMessage()}`);
18798
18839
  const turn = this.turn;
18799
18840
  if (!this.process || !turn) return Promise.resolve(false);
18800
18841
  const clientId = (0, import_crypto7.randomUUID)();
18801
- return new Promise((resolve17) => {
18842
+ return new Promise((resolve18) => {
18802
18843
  let settled = false;
18803
18844
  const steer = {
18804
18845
  id: id2,
@@ -18807,7 +18848,7 @@ ${this.exitMessage()}`);
18807
18848
  if (settled) return;
18808
18849
  settled = true;
18809
18850
  if (!accepted) turn.steers.delete(clientId);
18810
- resolve17(accepted);
18851
+ resolve18(accepted);
18811
18852
  }
18812
18853
  };
18813
18854
  turn.steers.set(clientId, steer);
@@ -19356,10 +19397,11 @@ ${this.exitMessage()}`);
19356
19397
  }
19357
19398
  /** Relative to the task's worktree, where every path but a stray one lies; a move names both ends. */
19358
19399
  shownChangePath(change) {
19400
+ const { isAbsolute: isAbsolute13, relative: relative20, sep: sep13 } = this.deps.placement ? hostPath.posix : hostPath;
19359
19401
  const shown = (path53) => {
19360
19402
  const cwd = this.startOpts && this.runnerCwd(this.startOpts);
19361
- const rel = cwd ? (0, import_path6.relative)(cwd, path53) : path53;
19362
- return rel && rel !== ".." && !rel.startsWith(`..${import_path6.sep}`) && !(0, import_path6.isAbsolute)(rel) ? rel : path53;
19403
+ const rel = cwd ? relative20(cwd, path53) : path53;
19404
+ return rel && rel !== ".." && !rel.startsWith(`..${sep13}`) && !isAbsolute13(rel) ? rel : path53;
19363
19405
  };
19364
19406
  const from = shown(change.path ?? "");
19365
19407
  return change.kind?.move_path ? `${from} \u2192 ${shown(change.kind.move_path)}` : from;
@@ -19566,14 +19608,14 @@ function splitModelId(id2) {
19566
19608
  return { providerID: id2.slice(0, slash), modelID: id2.slice(slash + 1) };
19567
19609
  }
19568
19610
  function delay(ms, signal) {
19569
- return new Promise((resolve17) => {
19611
+ return new Promise((resolve18) => {
19570
19612
  const onAbort = () => {
19571
19613
  clearTimeout(timer);
19572
- resolve17();
19614
+ resolve18();
19573
19615
  };
19574
19616
  const timer = setTimeout(() => {
19575
19617
  signal?.removeEventListener("abort", onAbort);
19576
- resolve17();
19618
+ resolve18();
19577
19619
  }, ms);
19578
19620
  timer.unref?.();
19579
19621
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -19695,8 +19737,8 @@ function streamTurn() {
19695
19737
  }
19696
19738
  function turnLatch() {
19697
19739
  let markDone;
19698
- const ended2 = new Promise((resolve17) => {
19699
- markDone = resolve17;
19740
+ const ended2 = new Promise((resolve18) => {
19741
+ markDone = resolve18;
19700
19742
  });
19701
19743
  const turn = { live: false, done: false, ended: ended2, finish: () => {
19702
19744
  turn.done = true;
@@ -19708,9 +19750,9 @@ async function settleTurn(turn, how, onEvent) {
19708
19750
  const { signal } = how;
19709
19751
  let onAbort = () => {
19710
19752
  };
19711
- const aborted = new Promise((resolve17) => {
19712
- onAbort = resolve17;
19713
- if (signal?.aborted) resolve17();
19753
+ const aborted = new Promise((resolve18) => {
19754
+ onAbort = resolve18;
19755
+ if (signal?.aborted) resolve18();
19714
19756
  signal?.addEventListener("abort", onAbort, { once: true });
19715
19757
  });
19716
19758
  try {
@@ -19737,8 +19779,8 @@ async function interruptAcknowledged(turn, processEnded, timeoutMs) {
19737
19779
  async function openEventStream(connect2, onFrame, onActivity) {
19738
19780
  const streamAbort = new AbortController();
19739
19781
  let connected;
19740
- const ready = new Promise((resolve17) => {
19741
- connected = resolve17;
19782
+ const ready = new Promise((resolve18) => {
19783
+ connected = resolve18;
19742
19784
  });
19743
19785
  let fail;
19744
19786
  const failed2 = new Promise((_resolve, reject) => {
@@ -19752,7 +19794,7 @@ async function openEventStream(connect2, onFrame, onActivity) {
19752
19794
  const attemptAbort = new AbortController();
19753
19795
  const abortAttempt = () => attemptAbort.abort();
19754
19796
  streamAbort.signal.addEventListener("abort", abortAttempt, { once: true });
19755
- const stopped2 = new Promise((resolve17) => attemptAbort.signal.addEventListener("abort", () => resolve17(), { once: true }));
19797
+ const stopped2 = new Promise((resolve18) => attemptAbort.signal.addEventListener("abort", () => resolve18(), { once: true }));
19756
19798
  try {
19757
19799
  await streamEvents((signal) => settleWithin(connect2(signal), {
19758
19800
  timeoutMs: STREAM_CONNECT_TIMEOUT_MS,
@@ -20553,7 +20595,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
20553
20595
  * only until the address is known.
20554
20596
  */
20555
20597
  serverAddress() {
20556
- return new Promise((resolve17) => {
20598
+ return new Promise((resolve18) => {
20557
20599
  let partial = "";
20558
20600
  const stopReading = this.runner.readStdout((text6) => {
20559
20601
  const lines2 = (partial + text6).split("\n");
@@ -20568,7 +20610,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
20568
20610
  const settle = (url) => {
20569
20611
  stopReading();
20570
20612
  clearTimeout(timer);
20571
- resolve17(url);
20613
+ resolve18(url);
20572
20614
  };
20573
20615
  void this.processEnded.then(() => settle(null));
20574
20616
  });
@@ -21268,7 +21310,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
21268
21310
  if (servers) this.mcpServers = Object.keys(servers).filter((name) => name !== ordewell.name);
21269
21311
  return OPENCODE_ORDEWELL.attachState(servers?.[ordewell.name]?.status);
21270
21312
  }, MCP_ATTACH_TIMEOUT_MS, MCP_STATUS_POLL_MS2, this.processEnded);
21271
- if (state === "connected" && this.v2) await new Promise((resolve17) => setTimeout(resolve17, V2_TOOLS_OFFERED_MS));
21313
+ if (state === "connected" && this.v2) await new Promise((resolve18) => setTimeout(resolve18, V2_TOOLS_OFFERED_MS));
21272
21314
  return state;
21273
21315
  }
21274
21316
  /** 2.x lists its servers as `{ name, status: { status } }`, and only once it has started connecting them. */
@@ -21650,8 +21692,8 @@ async function openAppServer(command, args, launch) {
21650
21692
  })) launch.onMessage?.(message);
21651
21693
  };
21652
21694
  let inputBroken;
21653
- const broken = new Promise((resolve17) => {
21654
- inputBroken = resolve17;
21695
+ const broken = new Promise((resolve18) => {
21696
+ inputBroken = resolve18;
21655
21697
  });
21656
21698
  try {
21657
21699
  await runner.start(launch.cwd, () => ({ command, args }), (started) => {
@@ -25564,11 +25606,11 @@ async function committedInHead(files) {
25564
25606
  }
25565
25607
  const result = /* @__PURE__ */ new Map();
25566
25608
  await Promise.all([...byDir].map(async ([dir, inDir]) => {
25567
- const relative21 = (file) => path34.relative(dir, file).split(path34.sep).join("/");
25609
+ const relative20 = (file) => path34.relative(dir, file).split(path34.sep).join("/");
25568
25610
  try {
25569
- const { stdout } = await runGit("git", ["ls-tree", "--name-only", "HEAD", "--", ...inDir.map(relative21)], { cwd: dir, env: cleanEnv() });
25611
+ const { stdout } = await runGit("git", ["ls-tree", "--name-only", "HEAD", "--", ...inDir.map(relative20)], { cwd: dir, env: cleanEnv() });
25570
25612
  const listed5 = new Set(stdout.split("\n").map((line) => line.trim()).filter(Boolean));
25571
- for (const file of inDir) result.set(file, listed5.has(relative21(file)));
25613
+ for (const file of inDir) result.set(file, listed5.has(relative20(file)));
25572
25614
  } catch {
25573
25615
  }
25574
25616
  }));
@@ -26904,12 +26946,12 @@ function buildConflictRepairPrompt(task2, conflict, integrationBranch, plan) {
26904
26946
  const merge = `git merge --no-edit ${quotedMessageArgs(conflict.message)} ${integrationBranch}`;
26905
26947
  const asked = `What the task was asked to do:
26906
26948
  ${task2.prompt ?? task2.description}`;
26907
- const resolve17 = "resolve every conflict so that both sides' intent survives: keep the work already integrated and add what the task contributed.";
26949
+ const resolve18 = "resolve every conflict so that both sides' intent survives: keep the work already integrated and add what the task contributed.";
26908
26950
  const repos = conflict.repos.filter((repo) => repo !== SELF_REPO);
26909
26951
  if (repos.length === 0) {
26910
26952
  return [
26911
26953
  `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.`,
26912
- `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.`,
26954
+ `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.`,
26913
26955
  `Build and test the result the way this project does, commit the merge with \`${COMMIT_MERGE}\`, and only then call \`task_complete\`.`,
26914
26956
  "",
26915
26957
  asked
@@ -26918,7 +26960,7 @@ ${task2.prompt ?? task2.description}`;
26918
26960
  const stoppedIn = conflict.conflictRepo ?? repos[0];
26919
26961
  return [
26920
26962
  `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.`,
26921
- `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.`,
26963
+ `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.`,
26922
26964
  `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\`.`,
26923
26965
  "",
26924
26966
  asked
@@ -28270,12 +28312,12 @@ var PlannerConversation = class {
28270
28312
  }
28271
28313
  /** Resolves once no turn holds the conversation: what a subtree's stop waits on (ADR-0055 D16). */
28272
28314
  idle() {
28273
- return this.live ? new Promise((resolve17) => {
28274
- this.idling.push(resolve17);
28315
+ return this.live ? new Promise((resolve18) => {
28316
+ this.idling.push(resolve18);
28275
28317
  }) : Promise.resolve();
28276
28318
  }
28277
28319
  settleIdle() {
28278
- for (const resolve17 of this.idling.splice(0)) resolve17();
28320
+ for (const resolve18 of this.idling.splice(0)) resolve18();
28279
28321
  }
28280
28322
  /** Stop the planner turn in flight; it settles as stopped. False when none is. */
28281
28323
  stopTurn(by) {
@@ -30003,13 +30045,13 @@ function delegationSwitchedOn({ env, moduleDir, exists }) {
30003
30045
  return exists(`${root}/.git`) && exists(`${root}/packages/core/package.json`);
30004
30046
  }
30005
30047
  function placeHere(variable) {
30006
- const fs28 = typeof process === "undefined" ? void 0 : process.getBuiltinModule?.("fs");
30007
- if (!fs28) return { env: void 0, moduleDir: null, exists: () => false };
30048
+ const fs29 = typeof process === "undefined" ? void 0 : process.getBuiltinModule?.("fs");
30049
+ if (!fs29) return { env: void 0, moduleDir: null, exists: () => false };
30008
30050
  const file = typeof __filename !== "undefined" ? __filename : new URL(
30009
30051
  // @ts-expect-error - import.meta is only valid under an ESM module setting; see builtinSkills.ts
30010
30052
  __filename
30011
30053
  ).pathname;
30012
- return { env: process.env[variable], moduleDir: file.replace(/[\\/][^\\/]*$/, ""), exists: (path53) => fs28.existsSync(path53) };
30054
+ return { env: process.env[variable], moduleDir: file.replace(/[\\/][^\\/]*$/, ""), exists: (path53) => fs29.existsSync(path53) };
30013
30055
  }
30014
30056
  var DELEGATION_OFFERED = delegationSwitchedOn(placeHere(DELEGATION_ENV));
30015
30057
  var CONTAINERS_ENV = "ORDEWELL_CONTAINERS";
@@ -30588,7 +30630,7 @@ async function runNotifyCommand(command, env, { timeLimitMs = NOTIFY_TIME_LIMIT_
30588
30630
  });
30589
30631
  proc.unref();
30590
30632
  const leaveTeardown = onHostTeardown(() => stop(proc));
30591
- await new Promise((resolve17, reject) => {
30633
+ await new Promise((resolve18, reject) => {
30592
30634
  const settle = () => {
30593
30635
  clearTimeout(limit);
30594
30636
  leaveTeardown();
@@ -30605,7 +30647,7 @@ async function runNotifyCommand(command, env, { timeLimitMs = NOTIFY_TIME_LIMIT_
30605
30647
  });
30606
30648
  proc.once("exit", (code, signal) => {
30607
30649
  settle();
30608
- if (code === 0) resolve17();
30650
+ if (code === 0) resolve18();
30609
30651
  else reject(new Error(code === null ? `ended on ${signal}` : `exited with code ${code}`));
30610
30652
  });
30611
30653
  });
@@ -30653,8 +30695,8 @@ function detectInstalledPlanner(installation) {
30653
30695
  return probe;
30654
30696
  }
30655
30697
  async function installedPlannerDetected() {
30656
- while (!answered2) await new Promise((resolve17) => {
30657
- waiters.push(resolve17);
30698
+ while (!answered2) await new Promise((resolve18) => {
30699
+ waiters.push(resolve18);
30658
30700
  });
30659
30701
  }
30660
30702
  function installedPlannerAnswered() {
@@ -31195,9 +31237,8 @@ function mergeOutcome(result, branch, group, repaired = []) {
31195
31237
 
31196
31238
  // src/services/taskDiffRead.ts
31197
31239
  var import_crypto13 = require("crypto");
31198
- var fs14 = __toESM(require("fs"));
31240
+ var fs15 = __toESM(require("fs"));
31199
31241
  var path37 = __toESM(require("path"));
31200
- var import_os3 = require("os");
31201
31242
 
31202
31243
  // src/services/stateRoot.ts
31203
31244
  var fs13 = __toESM(require("fs"));
@@ -31225,6 +31266,16 @@ function refuseUsersCheckout(codeRoot, stateRoot) {
31225
31266
  }
31226
31267
  }
31227
31268
 
31269
+ // src/utils/realPath.ts
31270
+ var fs14 = __toESM(require("fs"));
31271
+ function realPathOf(p) {
31272
+ try {
31273
+ return fs14.realpathSync.native(p);
31274
+ } catch {
31275
+ return fs14.realpathSync(p);
31276
+ }
31277
+ }
31278
+
31228
31279
  // src/services/taskDiffRead.ts
31229
31280
  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).";
31230
31281
  function allowedPath(file) {
@@ -31332,18 +31383,18 @@ async function readTaskDiff(invoker, run, taskId, options) {
31332
31383
  };
31333
31384
  try {
31334
31385
  const files = [];
31335
- const workspaceRoot = fs14.realpathSync(stateRootOf(run));
31386
+ const workspaceRoot = fs15.realpathSync(stateRootOf(run));
31336
31387
  for (const repo of run.repos) {
31337
31388
  if (options.repo !== void 0 && repo.path !== options.repo) continue;
31338
31389
  const entry = record.repos[repo.path];
31339
31390
  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.` };
31340
31391
  if (!/^[a-f0-9]{40,64}$/.test(entry.baseRef)) throw new Error("Invalid recorded starting commit.");
31341
- const live3 = record.status !== "merged" && fs14.existsSync(entry.worktree);
31392
+ const live3 = record.status !== "merged" && fs15.existsSync(entry.worktree);
31342
31393
  const cwd = live3 ? entry.worktree : repo.root;
31343
- if (!inside(workspaceRoot, fs14.realpathSync(cwd))) throw new Error("The recorded task repository moved outside the workspace.");
31394
+ if (!inside(workspaceRoot, fs15.realpathSync(cwd))) throw new Error("The recorded task repository moved outside the workspace.");
31344
31395
  if (live3) {
31345
31396
  const toplevel = (await git(reader, cwd, ["rev-parse", "--show-toplevel"])).trim();
31346
- if (fs14.realpathSync(toplevel) !== fs14.realpathSync(entry.worktree)) throw new Error("The recorded task worktree is no longer a repository.");
31397
+ if (realPathOf(toplevel) !== realPathOf(entry.worktree)) throw new Error("The recorded task worktree is no longer a repository.");
31347
31398
  }
31348
31399
  const prefix = (await git(reader, repo.root, ["rev-parse", "--show-prefix"])).trim();
31349
31400
  const common = ["--no-pager", "-c", "core.fsmonitor=false"];
@@ -31378,9 +31429,9 @@ async function readTaskDiff(invoker, run, taskId, options) {
31378
31429
  const others = await git(reader, workspace, [...common, "ls-files", "--others", "--exclude-standard", "-z", "--", "."]);
31379
31430
  for (const file of others.split("\0").filter((f) => f && allowed(f))) {
31380
31431
  const full = path37.join(workspace, file);
31381
- if (!inside(fs14.realpathSync(workspace), fs14.realpathSync(path37.dirname(full)))) continue;
31432
+ if (!inside(fs15.realpathSync(workspace), fs15.realpathSync(path37.dirname(full)))) continue;
31382
31433
  const untracked = async (numstat) => {
31383
- const result = await tryGit(reader, workspace, [...common, "diff", "--no-index", "--no-renames", "--no-ext-diff", "--no-textconv", ...numstat ? ["--numstat", "-z"] : [], "--", import_os3.devNull, file]);
31434
+ const result = await tryGit(reader, workspace, [...common, "diff", "--no-index", "--no-renames", "--no-ext-diff", "--no-textconv", ...numstat ? ["--numstat", "-z"] : [], "--", "/dev/null", file]);
31384
31435
  if (!result.ok && result.code !== 1) throw new Error(result.stderr.trim() || "Could not read an untracked file diff.");
31385
31436
  return result.stdout;
31386
31437
  };
@@ -31408,7 +31459,7 @@ ${await file.patch()}`);
31408
31459
  // src/services/GitWorktreeIsolation.ts
31409
31460
  var import_crypto14 = require("crypto");
31410
31461
  var import_child_process10 = require("child_process");
31411
- var fs16 = __toESM(require("fs"));
31462
+ var fs17 = __toESM(require("fs"));
31412
31463
  var path39 = __toESM(require("path"));
31413
31464
 
31414
31465
  // src/utils/shell.ts
@@ -31421,7 +31472,7 @@ function shellQuoted(text6) {
31421
31472
  }
31422
31473
 
31423
31474
  // src/utils/prdStore.ts
31424
- var fs15 = __toESM(require("fs"));
31475
+ var fs16 = __toESM(require("fs"));
31425
31476
  var path38 = __toESM(require("path"));
31426
31477
  var PRD_BLOCK_RE = /<!--\s*ORDEWELL_PRD_START\s+slug="([^"]+)"\s*-->\s*([\s\S]*?)\s*<!--\s*ORDEWELL_PRD_END\s*-->/;
31427
31478
  function extractPrdBlock(text6) {
@@ -31437,9 +31488,9 @@ function sanitizeSlug(raw) {
31437
31488
  }
31438
31489
  function savePrdMarkdown(workspace, slug, markdown) {
31439
31490
  const dir = path38.join(workspace, ".scratch", sanitizeSlug(slug));
31440
- fs15.mkdirSync(dir, { recursive: true });
31491
+ fs16.mkdirSync(dir, { recursive: true });
31441
31492
  const file = path38.join(dir, "PRD.md");
31442
- fs15.writeFileSync(file, markdown.endsWith("\n") ? markdown : markdown + "\n", "utf8");
31493
+ fs16.writeFileSync(file, markdown.endsWith("\n") ? markdown : markdown + "\n", "utf8");
31443
31494
  return file;
31444
31495
  }
31445
31496
 
@@ -31599,7 +31650,7 @@ function isInside(parent, child) {
31599
31650
  }
31600
31651
  function resolvesAsNamed(base, p) {
31601
31652
  try {
31602
- return fs16.realpathSync(p) === path39.join(fs16.realpathSync(base), path39.relative(base, p));
31653
+ return fs17.realpathSync(p) === path39.join(fs17.realpathSync(base), path39.relative(base, p));
31603
31654
  } catch {
31604
31655
  return false;
31605
31656
  }
@@ -31693,7 +31744,7 @@ function settleStatus(record, status) {
31693
31744
  }
31694
31745
  function realDir(p) {
31695
31746
  try {
31696
- return fs16.realpathSync.native(p);
31747
+ return fs17.realpathSync.native(p);
31697
31748
  } catch {
31698
31749
  return path39.resolve(p);
31699
31750
  }
@@ -31703,7 +31754,7 @@ function sameDir(a, b) {
31703
31754
  }
31704
31755
  function resolves(target) {
31705
31756
  try {
31706
- fs16.statSync(target);
31757
+ fs17.statSync(target);
31707
31758
  return true;
31708
31759
  } catch {
31709
31760
  return false;
@@ -31723,7 +31774,7 @@ function leftoverLinks(dir) {
31723
31774
  }
31724
31775
  function isLink(target) {
31725
31776
  try {
31726
- return fs16.lstatSync(target).isSymbolicLink();
31777
+ return fs17.lstatSync(target).isSymbolicLink();
31727
31778
  } catch {
31728
31779
  return false;
31729
31780
  }
@@ -31935,7 +31986,7 @@ var GitWorktreeIsolation = class {
31935
31986
  async acceptsWorktree(run, repo) {
31936
31987
  const dir = this.integrationDir(run, repo);
31937
31988
  ensureStateDirIgnored(stateRootOf(run));
31938
- fs16.mkdirSync(path39.dirname(dir), { recursive: true });
31989
+ fs17.mkdirSync(path39.dirname(dir), { recursive: true });
31939
31990
  const added = await this.tryGit(repo.root, ["worktree", "add", "-q", "--no-checkout", dir, repo.integrationBranch]);
31940
31991
  await this.removeWorktreeDir(run, repo, dir, []);
31941
31992
  return added.ok;
@@ -32003,7 +32054,7 @@ var GitWorktreeIsolation = class {
32003
32054
  for (const repo of run.repos) {
32004
32055
  const worktree = path39.join(dir, repo.path);
32005
32056
  const tip = (await this.git(repo.root, ["rev-parse", repo.integrationBranch])).trim();
32006
- fs16.mkdirSync(path39.dirname(worktree), { recursive: true });
32057
+ fs17.mkdirSync(path39.dirname(worktree), { recursive: true });
32007
32058
  await this.git(repo.root, ["worktree", "add", "-q", "-B", branch, worktree, tip]);
32008
32059
  record.repos[repo.path] = { worktree, linked: [], baseRef: tip };
32009
32060
  }
@@ -32035,7 +32086,7 @@ var GitWorktreeIsolation = class {
32035
32086
  const source = path39.join(run.workspaceRoot, rel);
32036
32087
  const target = path39.join(cwd, rel);
32037
32088
  if (!resolves(source) || lexists(target)) continue;
32038
- fs16.mkdirSync(path39.dirname(target), { recursive: true });
32089
+ fs17.mkdirSync(path39.dirname(target), { recursive: true });
32039
32090
  if (linkPath(source, target, this.platform) === "copy") copied.push(rel);
32040
32091
  const entry = self ? record.repos[SELF_REPO] : void 0;
32041
32092
  if (entry) entry.linked.push(rel);
@@ -32088,7 +32139,7 @@ var GitWorktreeIsolation = class {
32088
32139
  }
32089
32140
  const base = { branch: names2.branch, name: path39.basename(names2.dir), title: task2.title };
32090
32141
  for (const worktree of at) {
32091
- if (!fs16.existsSync(worktree)) continue;
32142
+ if (!fs17.existsSync(worktree)) continue;
32092
32143
  const linked = leftoverLinks(path39.join(worktree, await this.prefixOf(repo)));
32093
32144
  found.push({ repo, worktree, target: { ...base, worktree, linked } });
32094
32145
  }
@@ -32107,7 +32158,7 @@ var GitWorktreeIsolation = class {
32107
32158
  if (target.worktree) await this.removeWorktreeDir(run, repo, worktree, target.linked);
32108
32159
  }
32109
32160
  for (const repo of run.repos) await this.tryGit(repo.root, ["branch", "-D", names2.branch]);
32110
- this.removeTaskWorkspace(run, names2.dir);
32161
+ await this.removeTaskWorkspace(run, names2.dir);
32111
32162
  return removal;
32112
32163
  }
32113
32164
  async restorePrevious(record, preserved) {
@@ -32137,7 +32188,7 @@ var GitWorktreeIsolation = class {
32137
32188
  for (const repo of run.repos) {
32138
32189
  const entry = record.repos[repo.path];
32139
32190
  if (!entry) continue;
32140
- if (!fs16.existsSync(entry.worktree)) throw new Error(`The worktree of task ${task2.order} is gone: ${entry.worktree}`);
32191
+ if (!fs17.existsSync(entry.worktree)) throw new Error(`The worktree of task ${task2.order} is gone: ${entry.worktree}`);
32141
32192
  if (repo.path === SELF_REPO) cwd = await this.inWorkspacePlace(repo, entry.worktree);
32142
32193
  if (entry.changed || repo.path === record.conflictRepo) {
32143
32194
  repairBase[repo.path] = (await this.git(repo.root, ["rev-parse", "--verify", repo.integrationBranch])).trim();
@@ -32286,7 +32337,7 @@ var GitWorktreeIsolation = class {
32286
32337
  * out of sync, and deleting it is the one action that cannot be undone.
32287
32338
  */
32288
32339
  async worktreeHasChanges(entry, prefix) {
32289
- if (!fs16.existsSync(entry.worktree)) return false;
32340
+ if (!fs17.existsSync(entry.worktree)) return false;
32290
32341
  const status = await this.tryGit(entry.worktree, ["status", "--porcelain", "-z", "--untracked-files=normal"]);
32291
32342
  if (!status.ok) return true;
32292
32343
  const linked = new Set(entry.linked);
@@ -32692,7 +32743,7 @@ var GitWorktreeIsolation = class {
32692
32743
  for (const repo of run.repos) {
32693
32744
  const entry = record.repos[repo.path];
32694
32745
  if (!entry) continue;
32695
- if (!fs16.existsSync(entry.worktree)) {
32746
+ if (!fs17.existsSync(entry.worktree)) {
32696
32747
  return this.stopLanding(record, "failed", repo, void 0, `its worktree is gone (${entry.worktree})`);
32697
32748
  }
32698
32749
  try {
@@ -32942,7 +32993,7 @@ var GitWorktreeIsolation = class {
32942
32993
  const ref2 = `refs/heads/${repo.integrationBranch}`;
32943
32994
  if (!(await this.tryGit(repo.root, ["update-ref", ref2, made, onto])).ok) return { strayed: true };
32944
32995
  const dir = this.integrationDir(run, repo);
32945
- if (!fs16.existsSync(path39.join(dir, ".git"))) return { onto: made };
32996
+ if (!fs17.existsSync(path39.join(dir, ".git"))) return { onto: made };
32946
32997
  const read2 = await this.readAcross(dir, onto, made);
32947
32998
  if (read2.ok) return { onto: made };
32948
32999
  if (!(await this.tryGit(repo.root, ["update-ref", ref2, onto, made])).ok) return { strayed: true };
@@ -33047,7 +33098,7 @@ var GitWorktreeIsolation = class {
33047
33098
  if (!await (reverts ? this.isRevertsOn(repo, head, tip, reverts) : this.isOneMergeOn(repo, head, tip))) return false;
33048
33099
  const dir = this.integrationDir(run, repo);
33049
33100
  const held2 = await this.worktreeHolding(repo, repo.integrationBranch);
33050
- if (!held2 && (!fs16.existsSync(path39.join(dir, ".git")) || await this.integrationOffBranch(run, repo))) return false;
33101
+ if (!held2 && (!fs17.existsSync(path39.join(dir, ".git")) || await this.integrationOffBranch(run, repo))) return false;
33051
33102
  const holder = held2 ? held2.worktree : dir;
33052
33103
  if (holder === null) return (await this.tryGit(repo.root, ["update-ref", `refs/heads/${repo.integrationBranch}`, tip, head])).ok;
33053
33104
  if (!sameDir(holder, dir)) return false;
@@ -33102,7 +33153,7 @@ var GitWorktreeIsolation = class {
33102
33153
  */
33103
33154
  async integrationOffBranch(run, repo) {
33104
33155
  const dir = this.integrationDir(run, repo);
33105
- if (!fs16.existsSync(path39.join(dir, ".git"))) return null;
33156
+ if (!fs17.existsSync(path39.join(dir, ".git"))) return null;
33106
33157
  const head = (await this.tryGit(dir, ["symbolic-ref", "-q", "HEAD"])).stdout.trim();
33107
33158
  if (head === `refs/heads/${repo.integrationBranch}`) return null;
33108
33159
  return `${head ? `on ${head.replace(/^refs\/heads\//, "")}` : "detached"}, not on ${repo.integrationBranch}`;
@@ -33113,7 +33164,7 @@ var GitWorktreeIsolation = class {
33113
33164
  if (!listed5.ok) return null;
33114
33165
  let worktree = null;
33115
33166
  for (const line of listed5.stdout.split(/\r?\n/)) {
33116
- if (line.startsWith("worktree ")) worktree = line.slice("worktree ".length);
33167
+ if (line.startsWith("worktree ")) worktree = path39.normalize(line.slice("worktree ".length));
33117
33168
  else if (line === `branch refs/heads/${branch}`) return { worktree };
33118
33169
  }
33119
33170
  return { worktree: null };
@@ -33130,12 +33181,58 @@ var GitWorktreeIsolation = class {
33130
33181
  if ((await this.tryGit(entry.worktree, ["check-ignore", "-q", "--", prefix + name])).ok) continue;
33131
33182
  excludes.push(`:(exclude,literal)${(prefix + name).replace(/\\/g, "/")}`);
33132
33183
  }
33184
+ if (this.platform === "win32") {
33185
+ const made = entry.linked.map((name) => (prefix + name).replace(/\\/g, "/"));
33186
+ const under = (link) => made.some((dir) => link === dir || link.startsWith(`${dir}/`));
33187
+ for (const link of await this.linksGitWalksInto(entry.worktree)) {
33188
+ if (!under(link)) excludes.push(`:(exclude,literal)${link}`);
33189
+ }
33190
+ }
33133
33191
  await this.git(entry.worktree, ["add", "-A", "--", ".", ...excludes]);
33134
33192
  const staged = await this.tryGit(entry.worktree, ["diff", "--cached", "--quiet"]);
33135
33193
  if (staged.ok) return;
33136
33194
  const commit = opts.rescue ? ["-c", "commit.gpgsign=false", "commit", "--no-verify"] : ["commit"];
33137
33195
  await this.git(entry.worktree, [...VERBATIM, ...commit, "-q", ...messageArgs(message)]);
33138
33196
  }
33197
+ /**
33198
+ * The links git would walk into when it stages `worktree`: on Windows a
33199
+ * junction reads to git as the directory it leads to, so staging one a task
33200
+ * left commits what it holds, a folder of the user's as readily as anything.
33201
+ * A symbolic link git stages as a link, as it does elsewhere, and keeps. Read
33202
+ * from git's own listing, one call, so what git ignores, a mirrored install
33203
+ * among it, is never walked; and a link is told by lstat, as Windows reports
33204
+ * every reparse point, a OneDrive placeholder too, as a link in a directory
33205
+ * listing.
33206
+ */
33207
+ async linksGitWalksInto(worktree) {
33208
+ const listed5 = await this.tryGit(worktree, ["status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all"]);
33209
+ if (!listed5.ok) throw new Error(`git could not list what the worktree holds: ${firstLine3(listed5.stderr.trim() || `exit ${listed5.code}`)}`);
33210
+ const isLink2 = /* @__PURE__ */ new Map();
33211
+ const linkAt = (rel) => {
33212
+ let link = isLink2.get(rel);
33213
+ if (link === void 0) {
33214
+ try {
33215
+ link = fs17.lstatSync(path39.join(worktree, rel)).isSymbolicLink();
33216
+ } catch {
33217
+ link = false;
33218
+ }
33219
+ isLink2.set(rel, link);
33220
+ }
33221
+ return link;
33222
+ };
33223
+ const found = /* @__PURE__ */ new Set();
33224
+ for (const entry of listed5.stdout.split("\0")) {
33225
+ const parts = entry.slice(3).split("/");
33226
+ for (let depth = 1; depth < parts.length; depth++) {
33227
+ const dir = parts.slice(0, depth).join("/");
33228
+ if (linkAt(dir)) {
33229
+ found.add(dir);
33230
+ break;
33231
+ }
33232
+ }
33233
+ }
33234
+ return [...found];
33235
+ }
33139
33236
  /** A message Ordewell writes, with the trailer if the user's setting says so right now. */
33140
33237
  message(kind, from) {
33141
33238
  return landingMessage(kind, from, this.deps.plannedWith?.() ?? false);
@@ -33146,10 +33243,10 @@ var GitWorktreeIsolation = class {
33146
33243
  async ensureIntegrationWorktree(run, repo) {
33147
33244
  return this.admin(stateRootOf(run), async () => {
33148
33245
  const dir = this.integrationDir(run, repo);
33149
- if (fs16.existsSync(path39.join(dir, ".git"))) return dir;
33246
+ if (fs17.existsSync(path39.join(dir, ".git"))) return dir;
33150
33247
  await this.tryGit(repo.root, ["worktree", "prune"]);
33151
33248
  ensureStateDirIgnored(stateRootOf(run));
33152
- fs16.mkdirSync(path39.dirname(dir), { recursive: true });
33249
+ fs17.mkdirSync(path39.dirname(dir), { recursive: true });
33153
33250
  await this.git(repo.root, ["worktree", "add", "-q", dir, repo.integrationBranch]);
33154
33251
  return dir;
33155
33252
  });
@@ -33186,7 +33283,7 @@ var GitWorktreeIsolation = class {
33186
33283
  if (entry) await this.removeWorktreeDir(run, repo, entry.worktree, entry.linked);
33187
33284
  await this.tryGit(repo.root, ["branch", "-D", record.branch]);
33188
33285
  }
33189
- this.removeTaskWorkspace(run, record.workspace);
33286
+ await this.removeTaskWorkspace(run, record.workspace);
33190
33287
  if (opts.dropRecord) delete run.tasks[record.taskId];
33191
33288
  return removal;
33192
33289
  }
@@ -33210,7 +33307,7 @@ var GitWorktreeIsolation = class {
33210
33307
  }
33211
33308
  async tipToKeep(repo, target) {
33212
33309
  const { worktree } = target;
33213
- if (worktree && fs16.existsSync(worktree)) {
33310
+ if (worktree && fs17.existsSync(worktree)) {
33214
33311
  if (!hasGitEntry(worktree)) throw new Error("it is not a git worktree any more");
33215
33312
  if (await this.worktreeHasChanges({ worktree, linked: target.linked }, await this.prefixOf(repo))) {
33216
33313
  await this.commitWorktree(repo, { worktree, linked: target.linked }, this.message("rescue", target), { rescue: true });
@@ -33240,23 +33337,40 @@ var GitWorktreeIsolation = class {
33240
33337
  * links and the directories that held deeper repos. Links are unlinked
33241
33338
  * first, so removing the rest can never walk into the real workspace.
33242
33339
  */
33243
- removeTaskWorkspace(run, dir) {
33244
- if (!isInside(this.runRoot(run), dir) || !fs16.existsSync(dir)) return;
33340
+ async removeTaskWorkspace(run, dir) {
33341
+ if (!isInside(this.runRoot(run), dir) || !fs17.existsSync(dir)) return;
33245
33342
  this.unlinkLinksUnder(dir);
33246
33343
  clearImmutableFlags(this.platform, dir);
33247
- fs16.rmSync(dir, { recursive: true, force: true });
33344
+ await this.removeDir(dir);
33345
+ }
33346
+ /**
33347
+ * Windows removes no directory a process works in, and a runner stopped
33348
+ * there a moment ago may still be going: taskkill ends it from another
33349
+ * process. So there the removal waits for it, a while, before it gives up.
33350
+ */
33351
+ async removeDir(dir) {
33352
+ if (this.platform === "win32") await fs17.promises.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
33353
+ else fs17.rmSync(dir, { recursive: true, force: true });
33248
33354
  }
33249
33355
  unlinkLinksUnder(dir) {
33250
33356
  let entries;
33251
33357
  try {
33252
- entries = fs16.readdirSync(dir, { withFileTypes: true });
33358
+ entries = fs17.readdirSync(dir, { withFileTypes: true });
33253
33359
  } catch {
33254
33360
  return;
33255
33361
  }
33256
33362
  for (const entry of entries) {
33257
33363
  const target = path39.join(dir, entry.name);
33258
- if (entry.isSymbolicLink()) this.unlinkIfLink(target);
33259
- else if (entry.isDirectory()) this.unlinkLinksUnder(target);
33364
+ if (entry.isDirectory()) this.unlinkLinksUnder(target);
33365
+ else if (entry.isSymbolicLink()) {
33366
+ let stat;
33367
+ try {
33368
+ stat = fs17.lstatSync(target);
33369
+ } catch {
33370
+ }
33371
+ if (stat?.isSymbolicLink()) this.unlinkIfLink(target);
33372
+ else if (stat?.isDirectory()) this.unlinkLinksUnder(target);
33373
+ }
33260
33374
  }
33261
33375
  }
33262
33376
  /**
@@ -33278,8 +33392,8 @@ var GitWorktreeIsolation = class {
33278
33392
  };
33279
33393
  const owned = new Set(Object.values(run.tasks).map((r) => path39.resolve(r.workspace)));
33280
33394
  const root = this.runRoot(run);
33281
- if (fs16.existsSync(root)) {
33282
- for (const entry of fs16.readdirSync(root)) {
33395
+ if (fs17.existsSync(root)) {
33396
+ for (const entry of fs17.readdirSync(root)) {
33283
33397
  const dir = path39.join(root, entry);
33284
33398
  if (entry === INTEGRATION_DIR || owned.has(path39.resolve(dir))) continue;
33285
33399
  let kept = true;
@@ -33290,7 +33404,7 @@ var GitWorktreeIsolation = class {
33290
33404
  }
33291
33405
  if (!kept) continue;
33292
33406
  for (const repo of run.repos) await this.removeWorktreeDir(run, repo, path39.join(dir, repo.path), []);
33293
- this.removeTaskWorkspace(run, dir);
33407
+ await this.removeTaskWorkspace(run, dir);
33294
33408
  }
33295
33409
  }
33296
33410
  const taskBranches = Object.values(run.tasks).map((r) => r.branch);
@@ -33306,32 +33420,36 @@ var GitWorktreeIsolation = class {
33306
33420
  return removal;
33307
33421
  }
33308
33422
  async removeWorktreeDir(run, repo, dir, linked) {
33309
- for (const name of /* @__PURE__ */ new Set([...linked, ...installDirs(dir)])) {
33310
- const target = path39.join(dir, name);
33311
- if (!resolvesAsNamed(this.runRoot(run), path39.dirname(target))) continue;
33312
- this.unlinkIfLink(target);
33313
- this.unlinkLinksUnder(target);
33314
- }
33315
- for (const name of resolvesAsNamed(this.runRoot(run), dir) ? fs16.readdirSync(dir) : []) {
33316
- if (LINKED_ARTIFACTS.has(name) || isEnvFile(name)) this.unlinkIfLink(path39.join(dir, name));
33423
+ const prefix = (await this.tryGit(repo.root, ["rev-parse", "--show-prefix"])).stdout.trim();
33424
+ for (const base of /* @__PURE__ */ new Set([dir, path39.join(dir, prefix)])) {
33425
+ for (const name of /* @__PURE__ */ new Set([...linked, ...installDirs(base)])) {
33426
+ const target = path39.join(base, name);
33427
+ if (!resolvesAsNamed(this.runRoot(run), path39.dirname(target))) continue;
33428
+ this.unlinkIfLink(target);
33429
+ this.unlinkLinksUnder(target);
33430
+ }
33431
+ for (const name of resolvesAsNamed(this.runRoot(run), base) ? fs17.readdirSync(base) : []) {
33432
+ if (LINKED_ARTIFACTS.has(name) || isEnvFile(name)) this.unlinkIfLink(path39.join(base, name));
33433
+ }
33317
33434
  }
33435
+ if (this.platform === "win32" && resolvesAsNamed(this.runRoot(run), dir)) this.unlinkLinksUnder(dir);
33318
33436
  await this.tryGit(repo.root, ["worktree", "remove", "--force", dir]);
33319
- if (fs16.existsSync(dir) && isInside(this.runRoot(run), dir)) {
33437
+ if (fs17.existsSync(dir) && isInside(this.runRoot(run), dir)) {
33320
33438
  clearImmutableFlags(this.platform, dir);
33321
- fs16.rmSync(dir, { recursive: true, force: true });
33439
+ await this.removeDir(dir);
33322
33440
  }
33323
33441
  await this.tryGit(repo.root, ["worktree", "prune"]);
33324
33442
  for (let parent = path39.dirname(dir); isInside(this.runRoot(run), parent); parent = path39.dirname(parent)) this.removeIfEmpty(parent);
33325
33443
  }
33326
33444
  unlinkIfLink(target) {
33327
33445
  try {
33328
- if (fs16.lstatSync(target).isSymbolicLink()) fs16.rmSync(target, { force: true });
33446
+ if (fs17.lstatSync(target).isSymbolicLink()) fs17.rmSync(target, { force: true });
33329
33447
  } catch {
33330
33448
  }
33331
33449
  }
33332
33450
  removeIfEmpty(dir) {
33333
33451
  try {
33334
- fs16.rmdirSync(dir);
33452
+ fs17.rmdirSync(dir);
33335
33453
  } catch {
33336
33454
  }
33337
33455
  }
@@ -33358,7 +33476,7 @@ var GitWorktreeIsolation = class {
33358
33476
  async rebaseInProgress(cwd) {
33359
33477
  for (const dir of ["rebase-merge", "rebase-apply"]) {
33360
33478
  const found = await this.tryGit(cwd, ["rev-parse", "--git-path", dir]);
33361
- if (found.ok && fs16.existsSync(path39.resolve(cwd, found.stdout.trim()))) return true;
33479
+ if (found.ok && fs17.existsSync(path39.resolve(cwd, found.stdout.trim()))) return true;
33362
33480
  }
33363
33481
  return false;
33364
33482
  }
@@ -33389,7 +33507,7 @@ function createWorktreeIsolation(deps) {
33389
33507
  }
33390
33508
 
33391
33509
  // src/utils/sessionStore.ts
33392
- var fs17 = __toESM(require("fs"));
33510
+ var fs18 = __toESM(require("fs"));
33393
33511
  var path40 = __toESM(require("path"));
33394
33512
 
33395
33513
  // src/interfaces/ILogger.ts
@@ -33443,7 +33561,7 @@ var NO_RESEARCH_LOG = [];
33443
33561
  var writtenLogs = /* @__PURE__ */ new Map();
33444
33562
  function saveResearchLog(log, file) {
33445
33563
  const written = writtenLogs.get(file);
33446
- const unchanged = fs17.existsSync(file) ? written?.log.deref() === log && written.length === log.length : log.length === 0;
33564
+ const unchanged = fs18.existsSync(file) ? written?.log.deref() === log && written.length === log.length : log.length === 0;
33447
33565
  if (unchanged) return;
33448
33566
  writeFileAtomic(file, JSON.stringify(log));
33449
33567
  writtenLogs.set(file, { log: new WeakRef(log), length: log.length });
@@ -33451,7 +33569,7 @@ function saveResearchLog(log, file) {
33451
33569
  function restoreResearchLog(plan, sessionId, file, logger) {
33452
33570
  if (plan.researchLog) return;
33453
33571
  try {
33454
- plan.researchLog = JSON.parse(fs17.readFileSync(file, "utf-8"));
33572
+ plan.researchLog = JSON.parse(fs18.readFileSync(file, "utf-8"));
33455
33573
  } catch (err) {
33456
33574
  if (err.code !== "ENOENT") logger.warn("sessionStore", `failed to read the research log of ${sessionId}; going on without it`, err);
33457
33575
  }
@@ -33482,10 +33600,10 @@ function legacySessionFilename(session) {
33482
33600
  }
33483
33601
  function dropLegacyFile(sessionsDir, meta) {
33484
33602
  const legacy = path40.join(sessionsDir, legacySessionFilename(meta));
33485
- if (legacy === path40.join(sessionsDir, sessionFilename(meta)) || !fs17.existsSync(legacy)) return;
33603
+ if (legacy === path40.join(sessionsDir, sessionFilename(meta)) || !fs18.existsSync(legacy)) return;
33486
33604
  try {
33487
- const held2 = JSON.parse(fs17.readFileSync(legacy, "utf-8")).meta?.id;
33488
- if (held2 === meta.id) fs17.unlinkSync(legacy);
33605
+ const held2 = JSON.parse(fs18.readFileSync(legacy, "utf-8")).meta?.id;
33606
+ if (held2 === meta.id) fs18.unlinkSync(legacy);
33489
33607
  } catch {
33490
33608
  }
33491
33609
  }
@@ -33527,7 +33645,7 @@ function listChildSessions(rootSessionId, baseDir) {
33527
33645
  const dir = childSessionsDir(rootSessionId, baseDir);
33528
33646
  const named3 = (entry) => {
33529
33647
  try {
33530
- const session = JSON.parse(fs17.readFileSync(path40.join(dir, entry, CHILD_SESSION_FILE), "utf-8"));
33648
+ const session = JSON.parse(fs18.readFileSync(path40.join(dir, entry, CHILD_SESSION_FILE), "utf-8"));
33531
33649
  return isSessionMeta(session.meta) ? session.meta.id : null;
33532
33650
  } catch {
33533
33651
  return null;
@@ -33535,7 +33653,7 @@ function listChildSessions(rootSessionId, baseDir) {
33535
33653
  };
33536
33654
  let entries;
33537
33655
  try {
33538
- entries = fs17.readdirSync(dir);
33656
+ entries = fs18.readdirSync(dir);
33539
33657
  } catch {
33540
33658
  return [];
33541
33659
  }
@@ -33543,12 +33661,12 @@ function listChildSessions(rootSessionId, baseDir) {
33543
33661
  }
33544
33662
  function listSessions(baseDir, logger = defaultLogger) {
33545
33663
  const sessionsDir = getSessionsDir(baseDir);
33546
- if (!fs17.existsSync(sessionsDir)) return [];
33547
- const files = fs17.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
33664
+ if (!fs18.existsSync(sessionsDir)) return [];
33665
+ const files = fs18.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
33548
33666
  return files.map((f) => {
33549
33667
  let parsed;
33550
33668
  try {
33551
- parsed = JSON.parse(fs17.readFileSync(path40.join(sessionsDir, f), "utf-8"));
33669
+ parsed = JSON.parse(fs18.readFileSync(path40.join(sessionsDir, f), "utf-8"));
33552
33670
  } catch (err) {
33553
33671
  if (err instanceof SyntaxError) return moveAside(sessionsDir, f, "is not valid JSON", logger);
33554
33672
  logger.warn("sessionStore", `failed to read session file ${f}; skipping`, err);
@@ -33569,7 +33687,7 @@ function listSessions(baseDir, logger = defaultLogger) {
33569
33687
  function moveAside(sessionsDir, file, reason, logger) {
33570
33688
  const aside = `${file}.${Date.now()}.corrupt`;
33571
33689
  try {
33572
- fs17.renameSync(path40.join(sessionsDir, file), path40.join(sessionsDir, aside));
33690
+ fs18.renameSync(path40.join(sessionsDir, file), path40.join(sessionsDir, aside));
33573
33691
  logger.warn("sessionStore", `session file ${file} ${reason}; moved aside to ${aside} rather than overwritten`);
33574
33692
  } catch {
33575
33693
  logger.warn("sessionStore", `failed to read session file ${file}; skipping`);
@@ -33578,12 +33696,12 @@ function moveAside(sessionsDir, file, reason, logger) {
33578
33696
  }
33579
33697
  var filenameEndings = (sessionId) => [sessionId.replace(/^session-/, ""), sessionId].map((id2) => `_${id2.slice(0, 8)}.json`);
33580
33698
  function findSessionFile(sessionsDir, sessionId, logger) {
33581
- const files = fs17.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
33699
+ const files = fs18.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
33582
33700
  const endings = filenameEndings(sessionId);
33583
33701
  const named3 = files.filter((f) => endings.some((ending) => f.endsWith(ending)));
33584
33702
  for (const file of /* @__PURE__ */ new Set([...named3, ...files])) {
33585
33703
  try {
33586
- const session = JSON.parse(fs17.readFileSync(path40.join(sessionsDir, file), "utf-8"));
33704
+ const session = JSON.parse(fs18.readFileSync(path40.join(sessionsDir, file), "utf-8"));
33587
33705
  if (session.meta.id === sessionId) return { file, session };
33588
33706
  } catch (err) {
33589
33707
  logger.warn("sessionStore", `failed to read session file ${file}; skipping`, err);
@@ -33605,7 +33723,7 @@ function settledOnLoad(session, researchLog, logger) {
33605
33723
  function loadChildSession(place, logger = defaultLogger) {
33606
33724
  let parsed;
33607
33725
  try {
33608
- parsed = JSON.parse(fs17.readFileSync(childSessionPath(place), "utf-8"));
33726
+ parsed = JSON.parse(fs18.readFileSync(childSessionPath(place), "utf-8"));
33609
33727
  } catch (err) {
33610
33728
  if (err.code !== "ENOENT") logger.warn("sessionStore", `failed to read child session ${place.sessionId}`, err);
33611
33729
  return null;
@@ -33615,7 +33733,7 @@ function loadChildSession(place, logger = defaultLogger) {
33615
33733
  }
33616
33734
  function loadSession(sessionId, baseDir, logger = defaultLogger) {
33617
33735
  const sessionsDir = getSessionsDir(baseDir);
33618
- if (!fs17.existsSync(sessionsDir)) return null;
33736
+ if (!fs18.existsSync(sessionsDir)) return null;
33619
33737
  try {
33620
33738
  const found = findSessionFile(sessionsDir, sessionId, logger);
33621
33739
  if (found) {
@@ -33642,16 +33760,16 @@ function getLatestSession(baseDir, logger = defaultLogger) {
33642
33760
  }
33643
33761
  function deleteSession(sessionId, baseDir, logger = defaultLogger) {
33644
33762
  const sessionsDir = getSessionsDir(baseDir);
33645
- if (!fs17.existsSync(sessionsDir)) return false;
33763
+ if (!fs18.existsSync(sessionsDir)) return false;
33646
33764
  try {
33647
- fs17.rmSync(sessionDataDir(sessionId, baseDir), { recursive: true, force: true });
33765
+ fs18.rmSync(sessionDataDir(sessionId, baseDir), { recursive: true, force: true });
33648
33766
  } catch (err) {
33649
33767
  logger.warn("sessionStore", `failed to remove the task logs of ${sessionId}`, err);
33650
33768
  }
33651
33769
  try {
33652
33770
  const found = findSessionFile(sessionsDir, sessionId, logger);
33653
33771
  if (found) {
33654
- fs17.unlinkSync(path40.join(sessionsDir, found.file));
33772
+ fs18.unlinkSync(path40.join(sessionsDir, found.file));
33655
33773
  return true;
33656
33774
  }
33657
33775
  } catch (err) {
@@ -33798,8 +33916,8 @@ var import_uuid6 = require("uuid");
33798
33916
 
33799
33917
  // src/services/ContextCollector.ts
33800
33918
  var ORDEWELL_CONTEXT_MAX = 8e3;
33801
- async function collectResearchContext(fs28, runners) {
33802
- const collector = new ContextCollector(fs28);
33919
+ async function collectResearchContext(fs29, runners) {
33920
+ const collector = new ContextCollector(fs29);
33803
33921
  let contextStr = "";
33804
33922
  let firstContext = null;
33805
33923
  for (const r of runners) {
@@ -33826,8 +33944,8 @@ ${firstContext.dirStructure}
33826
33944
  return contextStr;
33827
33945
  }
33828
33946
  var ContextCollector = class {
33829
- constructor(fs28, registry) {
33830
- this.fs = fs28;
33947
+ constructor(fs29, registry) {
33948
+ this.fs = fs29;
33831
33949
  this.registry = registry;
33832
33950
  }
33833
33951
  fs;
@@ -33875,28 +33993,28 @@ var ALLOWED_TOOL_NAMES = new Set(subagentToolSpecs().map((t) => t.name));
33875
33993
  function refused3(output) {
33876
33994
  return { success: false, output, truncated: false };
33877
33995
  }
33878
- function nonPromptingFs(fs28) {
33879
- const withinWorkspace = (p) => resolveWithin(fs28.getWorkspaceRoot(), p ?? ".").inside;
33996
+ function nonPromptingFs(fs29) {
33997
+ const withinWorkspace = (p) => resolveWithin(fs29.getWorkspaceRoot(), p ?? ".").inside;
33880
33998
  const outsideRefusal = (p) => refused3(
33881
33999
  `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.`
33882
34000
  );
33883
34001
  return {
33884
- getWorkspaceRoot: () => fs28.getWorkspaceRoot(),
33885
- readFile: (p, opts) => withinWorkspace(p) ? fs28.readFile(p, opts) : Promise.resolve(outsideRefusal(p)),
34002
+ getWorkspaceRoot: () => fs29.getWorkspaceRoot(),
34003
+ readFile: (p, opts) => withinWorkspace(p) ? fs29.readFile(p, opts) : Promise.resolve(outsideRefusal(p)),
33886
34004
  readFiles: (paths) => {
33887
34005
  const escaping = paths.find((p) => !withinWorkspace(p));
33888
- return escaping ? Promise.resolve(outsideRefusal(escaping)) : fs28.readFiles(paths);
34006
+ return escaping ? Promise.resolve(outsideRefusal(escaping)) : fs29.readFiles(paths);
33889
34007
  },
33890
- glob: (pattern, opts) => withinWorkspace(opts?.path) ? fs28.glob(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
33891
- grep: (pattern, opts) => withinWorkspace(opts?.path) ? fs28.grep(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
33892
- findSymbol: (symbol, opts) => withinWorkspace(opts?.path) ? fs28.findSymbol(symbol, opts) : Promise.resolve(outsideRefusal(opts.path)),
33893
- listDir: (p, depth) => withinWorkspace(p) ? fs28.listDir(p, depth) : Promise.resolve(outsideRefusal(p)),
34008
+ glob: (pattern, opts) => withinWorkspace(opts?.path) ? fs29.glob(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
34009
+ grep: (pattern, opts) => withinWorkspace(opts?.path) ? fs29.grep(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
34010
+ findSymbol: (symbol, opts) => withinWorkspace(opts?.path) ? fs29.findSymbol(symbol, opts) : Promise.resolve(outsideRefusal(opts.path)),
34011
+ listDir: (p, depth) => withinWorkspace(p) ? fs29.listDir(p, depth) : Promise.resolve(outsideRefusal(p)),
33894
34012
  bash: async (command, signal, opts) => {
33895
34013
  const policy = researchPolicyOptions(resolveResearchShell());
33896
34014
  const { tier, reason } = classifyCommand(command, policy);
33897
- const escaping = pathRefs(command, policy).map((ref2) => resolveRef(fs28.getWorkspaceRoot(), ref2)).find((r) => !r.inside);
33898
- if (tier === "auto" && !escaping && !opts?.sealed) return fs28.bash(command, signal);
33899
- if (opts?.sealed || await fs28.canSeal?.()) return fs28.bash(command, signal, { sealed: true });
34015
+ const escaping = pathRefs(command, policy).map((ref2) => resolveRef(fs29.getWorkspaceRoot(), ref2)).find((r) => !r.inside);
34016
+ if (tier === "auto" && !escaping && !opts?.sealed) return fs29.bash(command, signal);
34017
+ if (opts?.sealed || await fs29.canSeal?.()) return fs29.bash(command, signal, { sealed: true });
33900
34018
  if (tier === "refuse") return refused3(`Command refused: ${reason}`);
33901
34019
  if (tier === "auto" && escaping) return outsideRefusal(escaping.abs);
33902
34020
  return refused3(`"${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.`);
@@ -33908,7 +34026,7 @@ function withoutContext({ contextTokens: _context, ...record }) {
33908
34026
  }
33909
34027
  async function runLoop(prompt, deps) {
33910
34028
  if (deps.signal?.aborted) return "[research agent aborted before starting]";
33911
- const fs28 = nonPromptingFs(deps.fs);
34029
+ const fs29 = nonPromptingFs(deps.fs);
33912
34030
  const chat = deps.createChat(
33913
34031
  (delta) => deps.onProgress?.({ type: "thinking", text: delta, subagentId: deps.subagentId }),
33914
34032
  // The record says who made the call: unstamped, the ledger would read the
@@ -33931,7 +34049,7 @@ ${turn.text}`;
33931
34049
  if (tc.name === "read_file" && !("maxBytes" in args) && !("limit" in args)) args.limit = 2e3;
33932
34050
  const toolArgs = JSON.stringify(tc.args);
33933
34051
  deps.onProgress?.({ type: "tool_call", tool: tc.name, toolArgs, toolCallId: tc.id, subagentId: deps.subagentId });
33934
- const res = await executeTool(tc.name, args, fs28, deps.fetcher, deps.signal);
34052
+ const res = await executeTool(tc.name, args, fs29, deps.fetcher, deps.signal);
33935
34053
  const output = res.output.length > SUBAGENT_LIMITS.toolOutputMaxChars ? res.output.slice(0, SUBAGENT_LIMITS.toolOutputMaxChars) + `
33936
34054
  [... truncated to ${SUBAGENT_LIMITS.toolOutputMaxChars} chars, total ${res.output.length}]` : res.output;
33937
34055
  const stepEntry = {
@@ -34139,7 +34257,7 @@ var BaseAiService = class _BaseAiService {
34139
34257
  * steering/failed result and the loop continues sequentially: a subagent can
34140
34258
  * never fail a plan or a turn.
34141
34259
  */
34142
- async executeSpawnAgent(args, fs28, onProgress, signal, subagentId, fetcher) {
34260
+ async executeSpawnAgent(args, fs29, onProgress, signal, subagentId, fetcher) {
34143
34261
  const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
34144
34262
  if (!prompt) {
34145
34263
  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 };
@@ -34151,7 +34269,7 @@ var BaseAiService = class _BaseAiService {
34151
34269
  if (!chat) throw new Error("subagent chats are not available for this provider");
34152
34270
  return chat;
34153
34271
  },
34154
- fs: fs28,
34272
+ fs: fs29,
34155
34273
  signal,
34156
34274
  subagentId,
34157
34275
  // The subagent gets web tools only behind a non-prompting gate: no
@@ -34167,14 +34285,14 @@ var BaseAiService = class _BaseAiService {
34167
34285
  });
34168
34286
  }
34169
34287
  /** Collect project context for the planning phase. Shared with the harness backend. */
34170
- static async collectResearchContext(fs28, runners) {
34171
- return collectResearchContext(fs28, runners);
34288
+ static async collectResearchContext(fs29, runners) {
34289
+ return collectResearchContext(fs29, runners);
34172
34290
  }
34173
34291
  /**
34174
34292
  * Execute one round of tool calls and report each through onProgress.
34175
34293
  * Returns the results to feed back plus the log entries produced.
34176
34294
  */
34177
- async executeToolCalls(toolCalls, fs28, onProgress, fetcher, stepIndex, thinking, signal, plannerTools) {
34295
+ async executeToolCalls(toolCalls, fs29, onProgress, fetcher, stepIndex, thinking, signal, plannerTools) {
34178
34296
  const toolResults = [];
34179
34297
  const logEntries = [];
34180
34298
  let resultsText = "";
@@ -34195,12 +34313,12 @@ var BaseAiService = class _BaseAiService {
34195
34313
  spawnSubagentIds.set(i, subagentId);
34196
34314
  announcedAt.set(i, (/* @__PURE__ */ new Date()).toISOString());
34197
34315
  onProgress({ type: "tool_call", tool: toolCalls[i].name, toolArgs: JSON.stringify(toolCalls[i].args), subagentId, toolCallId: toolCalls[i].id });
34198
- precomputed.set(i, await this.executeSpawnAgent({ ...toolCalls[i].args }, fs28, onProgress, signal, subagentId, fetcher));
34316
+ precomputed.set(i, await this.executeSpawnAgent({ ...toolCalls[i].args }, fs29, onProgress, signal, subagentId, fetcher));
34199
34317
  }) : Promise.resolve(),
34200
34318
  parallelIndexes.length > 1 ? mapWithConcurrency(parallelIndexes, TOOL_ROUND_CONCURRENCY, async (i) => {
34201
34319
  announcedAt.set(i, (/* @__PURE__ */ new Date()).toISOString());
34202
34320
  onProgress({ type: "tool_call", tool: toolCalls[i].name, toolArgs: JSON.stringify(toolCalls[i].args), toolCallId: toolCalls[i].id });
34203
- precomputed.set(i, await executeTool(toolCalls[i].name, normalizedArgs[i], fs28, fetcher, signal));
34321
+ precomputed.set(i, await executeTool(toolCalls[i].name, normalizedArgs[i], fs29, fetcher, signal));
34204
34322
  }) : Promise.resolve()
34205
34323
  ]);
34206
34324
  for (const [index, tc] of toolCalls.entries()) {
@@ -34211,7 +34329,7 @@ var BaseAiService = class _BaseAiService {
34211
34329
  announcedAt.set(index, (/* @__PURE__ */ new Date()).toISOString());
34212
34330
  onProgress({ type: "tool_call", ...named3, toolArgs: JSON.stringify(tc.args), toolCallId: tc.id });
34213
34331
  }
34214
- const toolResult = preResult ?? await callPlannerTool(plannerTools, tc.name, toolArgs, signal) ?? await executeTool(tc.name, toolArgs, fs28, fetcher, signal);
34332
+ const toolResult = preResult ?? await callPlannerTool(plannerTools, tc.name, toolArgs, signal) ?? await executeTool(tc.name, toolArgs, fs29, fetcher, signal);
34215
34333
  const MAX_RESPONSE_CHARS = 5e4;
34216
34334
  const truncatedResponse = toolResult.success && (toolResult.truncated || toolResult.output.length > MAX_RESPONSE_CHARS);
34217
34335
  const llmOutput = toolResult.output.length > MAX_RESPONSE_CHARS ? toolResult.output.slice(0, MAX_RESPONSE_CHARS) + `
@@ -34384,7 +34502,7 @@ ${llmOutput}
34384
34502
  * parsed tasks if a plan was emitted mid-loop, or null if the loop
34385
34503
  * exhausted without a valid plan.
34386
34504
  */
34387
- async runResearchLoop(chat, firstMessage, fs28, onProgress, runners, initialLog, fetcher, userGoal, runnerModes, autonomousDefault, signal) {
34505
+ async runResearchLoop(chat, firstMessage, fs29, onProgress, runners, initialLog, fetcher, userGoal, runnerModes, autonomousDefault, signal) {
34388
34506
  const researchLog = initialLog ? [...initialLog] : [];
34389
34507
  if (!initialLog && userGoal) {
34390
34508
  researchLog.push({
@@ -34410,7 +34528,7 @@ ${llmOutput}
34410
34528
  if (!turn.hasToolCalls) break;
34411
34529
  const { toolResults, logEntries, resultsText } = await this.executeToolCalls(
34412
34530
  turn.toolCalls,
34413
- fs28,
34531
+ fs29,
34414
34532
  onProgress,
34415
34533
  fetcher,
34416
34534
  step,
@@ -34455,17 +34573,17 @@ var import_generative_ai2 = require("@google/generative-ai");
34455
34573
 
34456
34574
  // src/services/runnerAuth.ts
34457
34575
  var import_child_process11 = require("child_process");
34458
- var import_path7 = require("path");
34576
+ var import_path6 = require("path");
34459
34577
  var AUTH_TIMEOUT_MS = 8e3;
34460
- var defaultExec3 = (command, args, options) => new Promise((resolve17) => {
34578
+ var defaultExec3 = (command, args, options) => new Promise((resolve18) => {
34461
34579
  let settled = false;
34462
34580
  const settle = (result) => {
34463
34581
  if (settled) return;
34464
34582
  settled = true;
34465
34583
  clearTimeout(timer);
34466
- resolve17(result);
34584
+ resolve18(result);
34467
34585
  };
34468
- const child = (0, import_child_process11.execFile)(command, args, { timeout: options.timeout, env: options.env, encoding: "utf8" }, (err, stdout, stderr) => {
34586
+ const child = (0, import_child_process11.execFile)(command, args, { timeout: options.timeout, env: options.env, encoding: "utf8", windowsVerbatimArguments: options.verbatim }, (err, stdout, stderr) => {
34469
34587
  const raw = err?.code;
34470
34588
  const code = err ? typeof raw === "number" ? raw : -1 : 0;
34471
34589
  settle({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
@@ -34490,9 +34608,11 @@ async function readRunnerAuth(manifest, options = {}) {
34490
34608
  let env;
34491
34609
  try {
34492
34610
  env = withPath(process.env, await augmentedPath(), options.env ?? {});
34493
- answer2 = await (options.exec ?? defaultExec3)(command, spec.statusArgs, {
34611
+ const launch = await planDirectLaunch(command, spec.statusArgs, options.launch);
34612
+ answer2 = await (options.exec ?? defaultExec3)(launch.file, launch.args, {
34494
34613
  timeout: options.timeoutMs ?? AUTH_TIMEOUT_MS,
34495
- env
34614
+ env,
34615
+ ...launch.verbatim ? { verbatim: true } : {}
34496
34616
  });
34497
34617
  } catch {
34498
34618
  return { state: "unknown", loginCommand };
@@ -34543,7 +34663,7 @@ function verdictFromExit(spec, output, code) {
34543
34663
  }
34544
34664
  var recorded2 = /* @__PURE__ */ new Map();
34545
34665
  function recordKey(runner, workspace) {
34546
- return workspace ? `${(0, import_path7.resolve)(workspace)}\0${runner}` : runner;
34666
+ return workspace ? `${(0, import_path6.resolve)(workspace)}\0${runner}` : runner;
34547
34667
  }
34548
34668
  function recordRunnerAuth(runner, auth, workspace) {
34549
34669
  recorded2.set(recordKey(runner, workspace), auth);
@@ -35575,10 +35695,10 @@ ${repairHint}` }] : parts;
35575
35695
  }, { signal });
35576
35696
  }
35577
35697
  // --- IAiService implementation ---
35578
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
35698
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
35579
35699
  this.ensureInit();
35580
35700
  const { autonomousDefault } = modes;
35581
- const contextStr = await BaseAiService.collectResearchContext(fs28, runners);
35701
+ const contextStr = await BaseAiService.collectResearchContext(fs29, runners);
35582
35702
  const systemPrompt = buildResearchPrompt(userDescription, contextStr, modelsByRunner, runners, runnerModes, modes);
35583
35703
  const firstMessage = `${buildResearchToolsPrompt(false)}
35584
35704
 
@@ -35586,17 +35706,17 @@ Explore the workspace to understand the codebase, then generate the plan.`;
35586
35706
  const researchChat = this.chat([{ role: "user", content: systemPrompt }], [{ functionDeclarations: TOOL_DEFINITIONS }], {
35587
35707
  onUsage: (record) => onProgress({ type: "usage", record })
35588
35708
  });
35589
- const result = await this.runResearchLoop(researchChat, firstMessage, fs28, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
35709
+ const result = await this.runResearchLoop(researchChat, firstMessage, fs29, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
35590
35710
  if (result.tasks) return { tasks: result.tasks, researchLog: result.researchLog, researchResults: result.researchResults };
35591
35711
  const fallback = await this.generatePlanFallback(userDescription, contextStr, result.researchResults, modelsByRunner, runners, onProgress, result.researchLog, runnerModes, autonomousDefault, signal, modes);
35592
35712
  return { tasks: fallback.tasks, researchLog: fallback.researchLog, researchResults: result.researchResults };
35593
35713
  }
35594
- async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs28, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
35714
+ async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs29, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
35595
35715
  this.ensureInit();
35596
35716
  const { autonomousDefault } = modes;
35597
35717
  let ctx = "";
35598
- if (fs28) {
35599
- const collected = await new ContextCollector(fs28).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
35718
+ if (fs29) {
35719
+ const collected = await new ContextCollector(fs29).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
35600
35720
  if (collected.aiflowContext) ctx = `
35601
35721
  <aiflow_context>
35602
35722
  ${collected.aiflowContext}
@@ -35963,10 +36083,10 @@ ${buildResearchToolsPrompt()}` }
35963
36083
  }
35964
36084
  }
35965
36085
  // --- IAiService implementation ---
35966
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
36086
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
35967
36087
  this.ensureInit();
35968
36088
  const { autonomousDefault } = modes;
35969
- const contextStr = await BaseAiService.collectResearchContext(fs28, runners);
36089
+ const contextStr = await BaseAiService.collectResearchContext(fs29, runners);
35970
36090
  const systemPrompt = buildResearchPrompt(userDescription, contextStr, modelsByRunner, runners, runnerModes, modes);
35971
36091
  const userText = `User goal: ${userDescription}`;
35972
36092
  const firstMessage = `${buildResearchToolsPrompt()}
@@ -35986,17 +36106,17 @@ ${userText}`;
35986
36106
  onUsage: (record) => onProgress({ type: "usage", record }),
35987
36107
  budget: this.plannerBudget()
35988
36108
  });
35989
- const result = await this.runResearchLoop(researchChat, firstMessage, fs28, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
36109
+ const result = await this.runResearchLoop(researchChat, firstMessage, fs29, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
35990
36110
  if (result.tasks) return { tasks: result.tasks, researchLog: result.researchLog, researchResults: result.researchResults };
35991
36111
  const fallback = await this.generatePlanFallback(userDescription, contextStr, result.researchResults, modelsByRunner, runners, onProgress, result.researchLog, runnerModes, autonomousDefault, signal, modes);
35992
36112
  return { tasks: fallback.tasks, researchLog: fallback.researchLog, researchResults: result.researchResults };
35993
36113
  }
35994
- async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs28, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
36114
+ async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs29, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
35995
36115
  this.ensureInit();
35996
36116
  const { autonomousDefault } = modes;
35997
36117
  let ctx = "";
35998
- if (fs28) {
35999
- const collected = await new ContextCollector(fs28).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
36118
+ if (fs29) {
36119
+ const collected = await new ContextCollector(fs29).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
36000
36120
  if (collected.aiflowContext) ctx = `
36001
36121
  <aiflow_context>
36002
36122
  ${collected.aiflowContext}
@@ -36874,7 +36994,7 @@ var PlanEditError = class extends Error {
36874
36994
  };
36875
36995
 
36876
36996
  // src/services/sessionLease.ts
36877
- var fs18 = __toESM(require("fs"));
36997
+ var fs19 = __toESM(require("fs"));
36878
36998
  var path41 = __toESM(require("path"));
36879
36999
  var import_crypto16 = require("crypto");
36880
37000
  var LEASE_HEARTBEAT_MS = 1e4;
@@ -36943,7 +37063,7 @@ function isRecord9(value) {
36943
37063
  function readRecord(file) {
36944
37064
  let raw;
36945
37065
  try {
36946
- raw = fs18.readFileSync(file, "utf8");
37066
+ raw = fs19.readFileSync(file, "utf8");
36947
37067
  } catch (err) {
36948
37068
  if (err.code === "ENOENT") return null;
36949
37069
  throw err;
@@ -37075,9 +37195,9 @@ var LeaseHost = class {
37075
37195
  if (this.held.size === 0) this.stopHeartbeat();
37076
37196
  try {
37077
37197
  withFileLock(file, () => {
37078
- if (readRecord(file)?.hostId === this.id) fs18.rmSync(file, { force: true });
37198
+ if (readRecord(file)?.hostId === this.id) fs19.rmSync(file, { force: true });
37079
37199
  }, "release a session lease");
37080
- fs18.rmdirSync(path41.dirname(file));
37200
+ fs19.rmdirSync(path41.dirname(file));
37081
37201
  } catch {
37082
37202
  }
37083
37203
  }
@@ -37213,8 +37333,9 @@ function preservedNotice(kept) {
37213
37333
  const owner = first.task ? `Task "${first.task.title}"` : "A leftover task workspace no record accounted for";
37214
37334
  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.`;
37215
37335
  }
37216
- function refusedNotice(worktree, reason, task2) {
37217
- 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}\`.`;
37336
+ function refusedNotice(worktree, reason, task2, platform = process.platform) {
37337
+ 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}\``;
37338
+ 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}.`;
37218
37339
  }
37219
37340
  function sharedPathsNotice(run) {
37220
37341
  if (run.repos.some((r) => r.path === SELF_REPO)) {
@@ -38594,16 +38715,27 @@ function liveConfig(dir) {
38594
38715
  const selected = new Set(repositoryRunnerConfigPaths([...found.keys()]));
38595
38716
  return new Map([...found].filter(([name]) => selected.has(name)));
38596
38717
  }
38597
- function linkedRoots(dir) {
38718
+ function linkedRoots(dir, checkout) {
38598
38719
  const linked = /* @__PURE__ */ new Set();
38599
38720
  for (const root of RUNNER_CONFIG_ROOTS) {
38600
38721
  try {
38601
- if ((0, import_fs13.lstatSync)(path42.join(dir, root)).isSymbolicLink()) linked.add(root);
38722
+ const here = (0, import_fs13.lstatSync)(path42.join(dir, root), { bigint: true });
38723
+ if (here.isSymbolicLink() || here.isFile() && here.nlink > 1n && sameFile(here, (0, import_fs13.statSync)(path42.join(checkout, root), { bigint: true }))) linked.add(root);
38602
38724
  } catch {
38603
38725
  }
38604
38726
  }
38605
38727
  return linked;
38606
38728
  }
38729
+ function sameFile(a, b) {
38730
+ return a.dev === b.dev && a.ino === b.ino;
38731
+ }
38732
+ function linksTo(link, target) {
38733
+ try {
38734
+ return (0, import_fs13.lstatSync)(link).isSymbolicLink() && realPathOf(link) === realPathOf(target);
38735
+ } catch {
38736
+ return false;
38737
+ }
38738
+ }
38607
38739
  function readDirs(root) {
38608
38740
  const dirs = [{ dir: root, prefix: "" }];
38609
38741
  for (let dir = root, prefix = ""; !(0, import_fs13.existsSync)(path42.join(dir, ".git")); ) {
@@ -38648,7 +38780,7 @@ var TaskStartConfig = class {
38648
38780
  */
38649
38781
  worktreeDifferences(id2, dir, root) {
38650
38782
  const now = liveConfig(dir);
38651
- const linked = linkedRoots(dir);
38783
+ const linked = linkedRoots(dir, root);
38652
38784
  const fromCheckout2 = (name) => linked.has(name.split("/")[0]);
38653
38785
  const key = `${id2}:worktree:${dir}`;
38654
38786
  let local = this.live.get(key);
@@ -38677,10 +38809,14 @@ var TaskStartConfig = class {
38677
38809
  if (!cwd || !repo.baseRef || !(0, import_fs13.existsSync)(cwd)) continue;
38678
38810
  const prefix = repo.path === "." ? (await tryGit(invoker, repo.root, ["rev-parse", "--show-prefix"])).stdout.trim() : "";
38679
38811
  const roots = [...RUNNER_CONFIG_ROOTS, ...prefix ? RUNNER_CONFIG_ROOTS.map((r) => `${prefix}${r}`) : []];
38812
+ const top = path42.resolve(repo.root, ...prefix.split("/").filter(Boolean).map(() => ".."));
38813
+ const runnerRoots = prefix ? roots.filter((root) => root.startsWith(prefix)) : roots;
38814
+ const linked = runnerRoots.filter((root) => linksTo(path42.join(cwd, root), path42.join(top, root))).map((root) => `${root}/`);
38680
38815
  const diff = await tryGit(invoker, cwd, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "--diff-filter=ACMRTU", "-z", repo.baseRef, "--"]);
38681
38816
  const untracked = await tryGit(invoker, cwd, ["ls-files", "--others", "-z", "--", ...roots]);
38682
38817
  if (!diff.ok || !untracked.ok) continue;
38683
38818
  for (const name of [...diff.stdout.split("\0"), ...untracked.stdout.split("\0")]) {
38819
+ if (linked.some((root) => name.startsWith(root))) continue;
38684
38820
  const here = prefix && name.startsWith(prefix) ? name.slice(prefix.length) : void 0;
38685
38821
  if (repositoryRunnerConfigPaths([name]).length || here !== void 0 && repositoryRunnerConfigPaths([here]).length) {
38686
38822
  found.push(repo.path === "." ? name : path42.posix.join(repo.path, name));
@@ -38693,7 +38829,7 @@ var TaskStartConfig = class {
38693
38829
 
38694
38830
  // src/services/ScriptRunner.ts
38695
38831
  var import_child_process12 = require("child_process");
38696
- var fs19 = __toESM(require("fs"));
38832
+ var fs20 = __toESM(require("fs"));
38697
38833
  var path43 = __toESM(require("path"));
38698
38834
  var import_events2 = require("events");
38699
38835
  var import_string_decoder2 = require("string_decoder");
@@ -38779,8 +38915,8 @@ var ScriptSession = class extends AbstractRunnerSession {
38779
38915
  /** Aborted to end a sealed step, which has no process of its own here to signal. */
38780
38916
  sealedEnd = new AbortController();
38781
38917
  markGone;
38782
- gone = new Promise((resolve17) => {
38783
- this.markGone = resolve17;
38918
+ gone = new Promise((resolve18) => {
38919
+ this.markGone = resolve18;
38784
38920
  });
38785
38921
  /** Whoever spawned it attaches its listeners when the spawn resolves, so the body starts a macrotask later. */
38786
38922
  begin() {
@@ -38882,7 +39018,7 @@ var ScriptSession = class extends AbstractRunnerSession {
38882
39018
  return shell.file === null ? { file: step.script, args: [], shell: true } : { file: shell.file, args: [...shell.args, step.script], shell: false };
38883
39019
  }
38884
39020
  spawnStep(launch) {
38885
- return new Promise((resolve17) => {
39021
+ return new Promise((resolve18) => {
38886
39022
  let settled = false;
38887
39023
  const stdout = new import_string_decoder2.StringDecoder("utf8");
38888
39024
  const stderr = new import_string_decoder2.StringDecoder("utf8");
@@ -38894,7 +39030,7 @@ var ScriptSession = class extends AbstractRunnerSession {
38894
39030
  this.child = null;
38895
39031
  this.placed = null;
38896
39032
  launch.placed?.ended();
38897
- resolve17(status);
39033
+ resolve18(status);
38898
39034
  };
38899
39035
  this.placed = launch.placed ?? null;
38900
39036
  const child = spawnInOwnGroup((detached) => this.setup.spawn(launch.file, launch.args, {
@@ -38945,7 +39081,7 @@ var ScriptSession = class extends AbstractRunnerSession {
38945
39081
  openFullOutput() {
38946
39082
  const target = this.setup.fullOutput;
38947
39083
  if (!target) return;
38948
- const stream = fs19.createWriteStream(target.file);
39084
+ const stream = fs20.createWriteStream(target.file);
38949
39085
  const full = { file: target.file, stream, written: 0, dropped: 0, failed: false };
38950
39086
  stream.on("error", (err) => {
38951
39087
  if (!full.failed) console.error(`[ScriptSession] could not save the output of ${this.id} to ${target.file}:`, err);
@@ -38970,12 +39106,12 @@ var ScriptSession = class extends AbstractRunnerSession {
38970
39106
  if (!full.failed && full.dropped > 0) full.stream.write(`
38971
39107
  [Ordewell stopped saving output here: ${full.dropped} more characters were not saved]
38972
39108
  `);
38973
- await new Promise((resolve17) => {
39109
+ await new Promise((resolve18) => {
38974
39110
  if (full.stream.closed) {
38975
- resolve17();
39111
+ resolve18();
38976
39112
  return;
38977
39113
  }
38978
- full.stream.once("close", () => resolve17());
39114
+ full.stream.once("close", () => resolve18());
38979
39115
  full.stream.end();
38980
39116
  });
38981
39117
  return full.failed ? void 0 : { file: full.file, droppedChars: full.dropped };
@@ -39127,7 +39263,7 @@ function passed(status) {
39127
39263
 
39128
39264
  // src/services/PatchCapture.ts
39129
39265
  var import_crypto18 = require("crypto");
39130
- var fs20 = __toESM(require("fs"));
39266
+ var fs21 = __toESM(require("fs"));
39131
39267
  var os11 = __toESM(require("os"));
39132
39268
  var path44 = __toESM(require("path"));
39133
39269
 
@@ -39207,9 +39343,9 @@ var Subtree = class _Subtree {
39207
39343
  at(path53) {
39208
39344
  const { here } = this.source;
39209
39345
  const absolute = `${ROOT_NODE2}/${path53}`;
39210
- const relative21 = `${here}/${path53}`;
39346
+ const relative20 = `${here}/${path53}`;
39211
39347
  const nodes = this.nodes();
39212
- const found = (absolute !== here && isWithin(absolute, here) ? nodes.find((node) => node.path === absolute) : void 0) ?? nodes.find((node) => node.path === relative21);
39348
+ const found = (absolute !== here && isWithin(absolute, here) ? nodes.find((node) => node.path === absolute) : void 0) ?? nodes.find((node) => node.path === relative20);
39213
39349
  return found && this.planOf(found);
39214
39350
  }
39215
39351
  /** The same as a reference is pinned against it. */
@@ -39627,17 +39763,17 @@ function linkInPatch(patch) {
39627
39763
  function readOwn(scratch, name, max) {
39628
39764
  let fd;
39629
39765
  try {
39630
- fd = fs20.openSync(path44.join(scratch, name), fs20.constants.O_RDONLY | (fs20.constants.O_NOFOLLOW ?? 0));
39766
+ fd = fs21.openSync(path44.join(scratch, name), fs21.constants.O_RDONLY | (fs21.constants.O_NOFOLLOW ?? 0));
39631
39767
  } catch (err) {
39632
39768
  throw new Refusal(`the capture left no ${name.split(".").pop()} Ordewell could read (${err.code ?? String(err)})`);
39633
39769
  }
39634
39770
  try {
39635
- if (!fs20.fstatSync(fd).isFile()) throw new Refusal(`the capture's ${name.split(".").pop()} is not a file`);
39771
+ if (!fs21.fstatSync(fd).isFile()) throw new Refusal(`the capture's ${name.split(".").pop()} is not a file`);
39636
39772
  const chunks = [];
39637
39773
  let total = 0;
39638
39774
  for (; ; ) {
39639
39775
  const chunk = Buffer.alloc(Math.min(1024 * 1024, max + 1 - total));
39640
- const read2 = fs20.readSync(fd, chunk, 0, chunk.length, null);
39776
+ const read2 = fs21.readSync(fd, chunk, 0, chunk.length, null);
39641
39777
  if (read2 === 0) break;
39642
39778
  total += read2;
39643
39779
  chunks.push(chunk.subarray(0, read2));
@@ -39645,7 +39781,7 @@ function readOwn(scratch, name, max) {
39645
39781
  }
39646
39782
  return Buffer.concat(chunks);
39647
39783
  } finally {
39648
- fs20.closeSync(fd);
39784
+ fs21.closeSync(fd);
39649
39785
  }
39650
39786
  }
39651
39787
  function failure(step, outcome) {
@@ -39683,7 +39819,7 @@ async function captureHeld(runs, opts, signal) {
39683
39819
  if (clash) return { kind: "refused", reason: clash };
39684
39820
  const flags = [...flag("excluded", excluded.map((c) => c.name)), ...flag("dropped", dropped.map((p) => `${p.name} (${byteSize(p.size)})`))];
39685
39821
  if (kept.length === 0) return { kind: "empty", reason: "none of the worktree's changes is one a patch carries.", flags };
39686
- fs20.writeFileSync(`${stem}.revert`, revertRecords([...excluded, ...dropped.flatMap((p) => p.changes)]), { flag: "wx", mode: 384 });
39822
+ fs21.writeFileSync(`${stem}.revert`, revertRecords([...excluded, ...dropped.flatMap((p) => p.changes)]), { flag: "wx", mode: 384 });
39687
39823
  const exported = await runs.run(exportScript(stem), worktree);
39688
39824
  if (signal?.aborted) return { kind: "refused", reason: "the attempt ended while its changes were being captured." };
39689
39825
  if (!exported.success) return { kind: "refused", reason: failure("git could not write or replay the patch", exported) };
@@ -39709,8 +39845,8 @@ async function captureHeld(runs, opts, signal) {
39709
39845
  if (err instanceof Refusal) return { kind: "refused", reason: `${err.message}.` };
39710
39846
  throw err;
39711
39847
  } finally {
39712
- fs20.rmSync(`${stem}.d`, { recursive: true, force: true });
39713
- for (const suffix of ["base", "raw", "files", "sizes", "renames", "revert", "kept", "hashes", "patch", "tree", "replayed"]) fs20.rmSync(`${stem}.${suffix}`, { force: true });
39848
+ fs21.rmSync(`${stem}.d`, { recursive: true, force: true });
39849
+ for (const suffix of ["base", "raw", "files", "sizes", "renames", "revert", "kept", "hashes", "patch", "tree", "replayed"]) fs21.rmSync(`${stem}.${suffix}`, { force: true });
39714
39850
  }
39715
39851
  }
39716
39852
  async function capturePatch(shell, opts = {}, signal) {
@@ -39759,7 +39895,7 @@ async function indexEntries(invoker, worktree) {
39759
39895
  async function trialApply(invoker, worktree, patchFile, scratch) {
39760
39896
  const index = path44.resolve(worktree, (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--git-path", "index"])).trim());
39761
39897
  const copy = path44.join(scratch, "index");
39762
- fs20.copyFileSync(index, copy);
39898
+ fs21.copyFileSync(index, copy);
39763
39899
  const trial = { ...invoker, exec: (file, args, opts) => invoker.exec(file, args, { ...opts, env: { ...opts.env, GIT_INDEX_FILE: copy } }) };
39764
39900
  const tried = await tryGit(trial, worktree, [...APPLY_GIT, "apply", "--cached", "--3way", "--whitespace=nowarn", patchFile]);
39765
39901
  return { left: await indexEntries(trial, worktree), ...tried.ok ? {} : { failed: tried.stderr } };
@@ -39778,7 +39914,7 @@ function gitRefused(lead, stderr) {
39778
39914
  function onDisk3(worktree, names2) {
39779
39915
  return names2.map((name) => {
39780
39916
  try {
39781
- const stat = fs20.lstatSync(path44.join(worktree, name), { bigint: true, throwIfNoEntry: false });
39917
+ const stat = fs21.lstatSync(path44.join(worktree, name), { bigint: true, throwIfNoEntry: false });
39782
39918
  return stat ? `${stat.mode} ${stat.ino} ${stat.size} ${stat.mtimeNs} ${stat.ctimeNs}` : "none";
39783
39919
  } catch (err) {
39784
39920
  return err.code ?? "unreadable";
@@ -39819,12 +39955,12 @@ function leavesWorktree(worktree, names2, linked, held2, left) {
39819
39955
  return `the patch writes ${name}, under ${at}, a submodule, whose files are another repository's.`;
39820
39956
  }
39821
39957
  const full = path44.join(worktree, ...parts.slice(0, i));
39822
- const stat = fs20.lstatSync(full, { throwIfNoEntry: false });
39958
+ const stat = fs21.lstatSync(full, { throwIfNoEntry: false });
39823
39959
  if (!stat) break;
39824
39960
  const last = i === parts.length;
39825
39961
  if (stat.isSymbolicLink()) {
39826
39962
  if (last && held2.get(at)?.some((entry) => entry.mode === LINK)) break;
39827
- const target = fs20.readlinkSync(full);
39963
+ const target = fs21.readlinkSync(full);
39828
39964
  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.`;
39829
39965
  }
39830
39966
  if (last || stat.isDirectory()) continue;
@@ -39846,10 +39982,10 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
39846
39982
  if (link !== void 0) {
39847
39983
  return refused5(`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.`);
39848
39984
  }
39849
- const dir = fs20.mkdtempSync(path44.join(os11.tmpdir(), "ordewell-apply-"));
39985
+ const dir = fs21.mkdtempSync(path44.join(os11.tmpdir(), "ordewell-apply-"));
39850
39986
  try {
39851
39987
  const toplevel = (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--show-toplevel"])).trim();
39852
- if (fs20.realpathSync(toplevel) !== fs20.realpathSync(worktree)) return refused5(`${worktree} is not the root of a worktree of its own.`);
39988
+ if (realPathOf(toplevel) !== realPathOf(worktree)) return refused5(`${worktree} is not the root of a worktree of its own.`);
39853
39989
  const head = (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--verify", "HEAD^{commit}"])).trim();
39854
39990
  if (!(await tryGit(invoker, worktree, [...APPLY_GIT, "cat-file", "-e", `${saved.base}^{commit}`])).ok) {
39855
39991
  return refused5(`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.`);
@@ -39857,7 +39993,7 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
39857
39993
  const before = await unmergedPaths(invoker, worktree);
39858
39994
  if (before.length > 0) return refused5(`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.`);
39859
39995
  const file = path44.join(dir, "saved.patch");
39860
- fs20.writeFileSync(file, patch, { flag: "wx", mode: 384 });
39996
+ fs21.writeFileSync(file, patch, { flag: "wx", mode: 384 });
39861
39997
  const held2 = await indexEntries(invoker, worktree);
39862
39998
  const named3 = await pathsNamed(invoker, worktree, file);
39863
39999
  const { left, failed: failed2 } = await trialApply(invoker, worktree, file, dir);
@@ -39889,7 +40025,7 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
39889
40025
  } catch (err) {
39890
40026
  return refused5(`git could not apply the patch (${err instanceof Error ? err.message : String(err)}).`);
39891
40027
  } finally {
39892
- fs20.rmSync(dir, { recursive: true, force: true });
40028
+ fs21.rmSync(dir, { recursive: true, force: true });
39893
40029
  }
39894
40030
  }
39895
40031
  function resolution(c) {
@@ -39956,17 +40092,17 @@ async function applySavedPatch(args, site) {
39956
40092
 
39957
40093
  // src/services/Board.ts
39958
40094
  var import_crypto19 = require("crypto");
39959
- var fs21 = __toESM(require("fs"));
40095
+ var fs22 = __toESM(require("fs"));
39960
40096
  var path45 = __toESM(require("path"));
39961
40097
  var BLOB_READ_MAX = 16 * 1024 * 1024;
39962
40098
  async function workBlob(cwd, file) {
39963
40099
  try {
39964
- const root = await fs21.promises.realpath(cwd);
39965
- const full = await fs21.promises.realpath(path45.join(root, file));
40100
+ const root = await fs22.promises.realpath(cwd);
40101
+ const full = await fs22.promises.realpath(path45.join(root, file));
39966
40102
  if (!full.startsWith(`${root}${path45.sep}`)) return void 0;
39967
- const stat = await fs21.promises.stat(full);
40103
+ const stat = await fs22.promises.stat(full);
39968
40104
  if (!stat.isFile() || stat.size > BLOB_READ_MAX) return void 0;
39969
- const bytes = await fs21.promises.readFile(full);
40105
+ const bytes = await fs22.promises.readFile(full);
39970
40106
  return (0, import_crypto19.createHash)("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
39971
40107
  } catch {
39972
40108
  return void 0;
@@ -41435,7 +41571,7 @@ function leasedIsolation(isolation, held2) {
41435
41571
  closeChanges: async () => {
41436
41572
  do {
41437
41573
  await Promise.all(underWay);
41438
- await new Promise((resolve17) => setImmediate(resolve17));
41574
+ await new Promise((resolve18) => setImmediate(resolve18));
41439
41575
  } while (underWay.size > 0);
41440
41576
  closed = true;
41441
41577
  }
@@ -41676,9 +41812,9 @@ var SlotPool = class {
41676
41812
  try {
41677
41813
  while (this.keptStarts.length > 0 && !this.full) {
41678
41814
  const node = this.keptStarts.shift();
41679
- await new Promise((resolve17) => {
41680
- this.taken = resolve17;
41681
- void node.tick().catch(() => void 0).finally(resolve17);
41815
+ await new Promise((resolve18) => {
41816
+ this.taken = resolve18;
41817
+ void node.tick().catch(() => void 0).finally(resolve18);
41682
41818
  });
41683
41819
  this.taken = null;
41684
41820
  }
@@ -44599,6 +44735,7 @@ var RunnerInstallation = class {
44599
44735
  env;
44600
44736
  workspace;
44601
44737
  authExec;
44738
+ launch;
44602
44739
  constructor(registry, execImpl = defaultExec4, now = Date.now, options = {}) {
44603
44740
  this.registry = registry;
44604
44741
  this.execImpl = execImpl;
@@ -44606,6 +44743,7 @@ var RunnerInstallation = class {
44606
44743
  this.env = options.env ?? (async () => ({}));
44607
44744
  this.workspace = options.workspace ?? (() => void 0);
44608
44745
  this.authExec = options.authExec;
44746
+ this.launch = options.launch ?? {};
44609
44747
  }
44610
44748
  /** True if the runner's CLI responds to `--version`. Cached per process. */
44611
44749
  async isInstalled(runner) {
@@ -44689,7 +44827,8 @@ var RunnerInstallation = class {
44689
44827
  try {
44690
44828
  return await readRunnerAuth(manifest, {
44691
44829
  ...this.authExec ? { exec: this.authExec } : {},
44692
- env: await this.env(workspace)
44830
+ env: await this.env(workspace),
44831
+ launch: this.launch
44693
44832
  });
44694
44833
  } catch {
44695
44834
  return { state: "unknown" };
@@ -44716,10 +44855,10 @@ var RunnerInstallation = class {
44716
44855
  * with `isInstalled` there.
44717
44856
  */
44718
44857
  async isSpawnable(command) {
44719
- if (process.platform !== "win32") return true;
44858
+ if ((this.launch.platform ?? process.platform) !== "win32") return true;
44720
44859
  try {
44721
- const plan = await planDirectLaunch(command, []);
44722
- return plan.file !== command;
44860
+ const plan = await planDirectLaunch(command, [], this.launch);
44861
+ return isExecutableResolved(command, plan, "", this.launch);
44723
44862
  } catch {
44724
44863
  return false;
44725
44864
  }
@@ -44909,10 +45048,10 @@ var AccountLimitMonitor = class {
44909
45048
  entry.inFlight = controller;
44910
45049
  entry.lastStartedAt = this.now();
44911
45050
  let deadline;
44912
- const abandoned = new Promise((resolve17) => {
45051
+ const abandoned = new Promise((resolve18) => {
44913
45052
  deadline = setTimeout(() => {
44914
45053
  controller.abort();
44915
- resolve17({ kind: "failed" });
45054
+ resolve18({ kind: "failed" });
44916
45055
  }, DEADLINE_MS);
44917
45056
  deadline.unref?.();
44918
45057
  });
@@ -45048,7 +45187,7 @@ function freeze(snapshot) {
45048
45187
  }
45049
45188
 
45050
45189
  // src/services/harness/codexAccountLimits.ts
45051
- var import_os4 = require("os");
45190
+ var import_os3 = require("os");
45052
45191
  var DEFAULT_TIMEOUT_MS4 = 2e4;
45053
45192
  var METHOD_NOT_FOUND = -32601;
45054
45193
  var INVALID_REQUEST = -32600;
@@ -45076,7 +45215,7 @@ async function readCodexAccountLimits(command, args, options, signal) {
45076
45215
  let owner;
45077
45216
  const root = options.workspaceRoot?.();
45078
45217
  const server4 = await openAppServer(command, args, {
45079
- cwd: (0, import_os4.tmpdir)(),
45218
+ cwd: (0, import_os3.tmpdir)(),
45080
45219
  deps: { ...root ? { workspaceEnv: () => workspaceEnvOf(root) } : {}, ...options.deps },
45081
45220
  onMessage: (message) => {
45082
45221
  if (message.method === "account/updated") accountChanged ||= accountRead;
@@ -45091,9 +45230,9 @@ async function readCodexAccountLimits(command, args, options, signal) {
45091
45230
  const initialized = await rpc.call("initialize", { clientInfo: APP_SERVER_CLIENT_INFO });
45092
45231
  if (!initialized.ok) return failed2();
45093
45232
  server4.notify("initialized", {});
45094
- const account = await new Promise((resolve17) => rpc.send("account/read", { refreshToken: false }, (response) => {
45233
+ const account = await new Promise((resolve18) => rpc.send("account/read", { refreshToken: false }, (response) => {
45095
45234
  accountRead = true;
45096
- resolve17(response);
45235
+ resolve18(response);
45097
45236
  }));
45098
45237
  if (!account.ok) return account.code === METHOD_NOT_FOUND ? { kind: "unsupported" } : failed2();
45099
45238
  const who = codexAccountOwner(account.result);
@@ -45111,7 +45250,7 @@ async function readCodexAccountLimits(command, args, options, signal) {
45111
45250
  ...followUp ? { followUp: true } : {}
45112
45251
  };
45113
45252
  })();
45114
- const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
45253
+ const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
45115
45254
  try {
45116
45255
  return await settleWithin(asked, {
45117
45256
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS4,
@@ -45167,8 +45306,8 @@ function codexWindow(slot, raw) {
45167
45306
  var import_child_process14 = require("child_process");
45168
45307
  var import_crypto20 = require("crypto");
45169
45308
  var import_fs14 = require("fs");
45170
- var import_os5 = require("os");
45171
- var import_path8 = require("path");
45309
+ var import_os4 = require("os");
45310
+ var import_path7 = require("path");
45172
45311
  var DEFAULT_TIMEOUT_MS5 = 2e4;
45173
45312
  var INITIALIZE_TIMEOUT_MS2 = 1e4;
45174
45313
  var USAGE_TIMEOUT_MS = 1e4;
@@ -45200,7 +45339,7 @@ function claudeAccountLimitCollector(options) {
45200
45339
  };
45201
45340
  }
45202
45341
  async function readClaudeAccountLimits(options, signal) {
45203
- const cwd = (0, import_fs14.mkdtempSync)((0, import_path8.join)((0, import_os5.tmpdir)(), "ordewell-claude-limits-"));
45342
+ const cwd = (0, import_fs14.mkdtempSync)((0, import_path7.join)((0, import_os4.tmpdir)(), "ordewell-claude-limits-"));
45204
45343
  const removeCwd = () => {
45205
45344
  try {
45206
45345
  (0, import_fs14.rmSync)(cwd, { recursive: true, force: true });
@@ -45229,7 +45368,7 @@ async function readClaudeAccountLimits(options, signal) {
45229
45368
  if (usage.kind === "refused" && UNSUPPORTED_REQUEST.test(usage.error)) return { kind: "unsupported" };
45230
45369
  return claudeLimitReading(usage, owner, isRecord11(account) ? text5(account.subscriptionType) : void 0) ?? failed2();
45231
45370
  })().catch(failed2);
45232
- const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
45371
+ const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
45233
45372
  try {
45234
45373
  return await settleWithin(asked, {
45235
45374
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS5,
@@ -45284,13 +45423,13 @@ function isoInstant(value) {
45284
45423
  }
45285
45424
 
45286
45425
  // src/services/harness/openCodeGoLimits.ts
45287
- var import_os7 = require("os");
45426
+ var import_os6 = require("os");
45288
45427
 
45289
45428
  // src/services/harness/openCodeCredentials.ts
45290
45429
  var import_crypto21 = require("crypto");
45291
45430
  var import_fs15 = require("fs");
45292
- var import_os6 = require("os");
45293
- var import_path9 = require("path");
45431
+ var import_os5 = require("os");
45432
+ var import_path8 = require("path");
45294
45433
  var import_worker_threads = require("worker_threads");
45295
45434
  var DEFAULT_TIMEOUT_MS6 = 5e3;
45296
45435
  var BUSY_MS = 250;
@@ -45347,12 +45486,12 @@ parentPort.postMessage(select());
45347
45486
  var isRecord12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
45348
45487
  var digest = (...parts) => (0, import_crypto21.createHash)("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
45349
45488
  function openCodeStorePaths(env, home) {
45350
- const data = (0, import_path9.join)(env.XDG_DATA_HOME || (0, import_path9.join)(home, ".local", "share"), "opencode");
45489
+ const data = (0, import_path8.join)(env.XDG_DATA_HOME || (0, import_path8.join)(home, ".local", "share"), "opencode");
45351
45490
  const file = env.OPENCODE_DB || "opencode.db";
45352
- return { db: file === ":memory:" ? null : (0, import_path9.resolve)(data, file), auth: (0, import_path9.join)(data, "auth.json") };
45491
+ return { db: file === ":memory:" ? null : (0, import_path8.resolve)(data, file), auth: (0, import_path8.join)(data, "auth.json") };
45353
45492
  }
45354
45493
  function openCodeGoLoginReader(deps = {}) {
45355
- const homedir11 = deps.homedir ?? import_os6.homedir;
45494
+ const homedir11 = deps.homedir ?? import_os5.homedir;
45356
45495
  let last;
45357
45496
  return {
45358
45497
  async read(env, signal) {
@@ -45501,7 +45640,7 @@ function openCodeGoAccountLimitCollector(options) {
45501
45640
  label: "OpenCode Go",
45502
45641
  provider: "opencode-go",
45503
45642
  scope: () => {
45504
- const paths = openCodeStorePaths(env(), (deps.reader?.homedir ?? import_os7.homedir)());
45643
+ const paths = openCodeStorePaths(env(), (deps.reader?.homedir ?? import_os6.homedir)());
45505
45644
  return ["opencode", paths.db ?? ":memory:", paths.auth].join("\0");
45506
45645
  },
45507
45646
  acquire: async (signal) => {
@@ -46633,8 +46772,8 @@ Before submitting, call list_runners and list_models to check the available assi
46633
46772
  session.discard();
46634
46773
  }
46635
46774
  }
46636
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
46637
- const contextStr = await collectResearchContext(fs28, runners);
46775
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
46776
+ const contextStr = await collectResearchContext(fs29, runners);
46638
46777
  const prompt = buildPlanWithResults(userDescription, contextStr, "", modelsByRunner, runners, runnerModes, modes, true);
46639
46778
  const plan = await this.submittedPlan(prompt, oneShotCatalog(runners, modelsByRunner, runnerModes, modes), onProgress, signal);
46640
46779
  return {
@@ -46675,22 +46814,22 @@ function createAiService(config, deps) {
46675
46814
  var path50 = __toESM(require("path"));
46676
46815
 
46677
46816
  // src/services/handoffReferences.ts
46678
- var fs23 = __toESM(require("fs"));
46817
+ var fs24 = __toESM(require("fs"));
46679
46818
  var path47 = __toESM(require("path"));
46680
46819
  var import_child_process16 = require("child_process");
46681
46820
  function resolveHandoffReferences(handoff, workspace) {
46682
46821
  const checked = /* @__PURE__ */ new Map();
46683
46822
  const contained = (candidate) => {
46684
46823
  try {
46685
- const root = fs23.realpathSync(workspace);
46686
- const resolved2 = fs23.realpathSync(path47.resolve(root, candidate));
46687
- const relative21 = path47.relative(root, resolved2);
46688
- return relative21 !== ".." && !relative21.startsWith(`..${path47.sep}`) && !path47.isAbsolute(relative21) ? resolved2 : void 0;
46824
+ const root = fs24.realpathSync(workspace);
46825
+ const resolved2 = fs24.realpathSync(path47.resolve(root, candidate));
46826
+ const relative20 = path47.relative(root, resolved2);
46827
+ return relative20 !== ".." && !relative20.startsWith(`..${path47.sep}`) && !path47.isAbsolute(relative20) ? resolved2 : void 0;
46689
46828
  } catch {
46690
46829
  return void 0;
46691
46830
  }
46692
46831
  };
46693
- const resolve17 = (ref2) => {
46832
+ const resolve18 = (ref2) => {
46694
46833
  if (ref2.kind !== "file" && ref2.kind !== "commit") return ref2;
46695
46834
  const key = JSON.stringify(ref2);
46696
46835
  const known = checked.get(key);
@@ -46700,13 +46839,13 @@ function resolveHandoffReferences(handoff, workspace) {
46700
46839
  const file = contained(ref2.path);
46701
46840
  if (file) {
46702
46841
  try {
46703
- resolved2 = fs23.statSync(file).isFile();
46842
+ resolved2 = fs24.statSync(file).isFile();
46704
46843
  } catch {
46705
46844
  }
46706
46845
  }
46707
46846
  } else if (/^[0-9a-fA-F]{4,64}$/.test(ref2.sha)) {
46708
46847
  const repo = contained(ref2.repo ?? ".");
46709
- if (repo && fs23.existsSync(path47.join(repo, ".git"))) {
46848
+ if (repo && fs24.existsSync(path47.join(repo, ".git"))) {
46710
46849
  const result2 = (0, import_child_process16.spawnSync)("git", ["--no-optional-locks", "--no-replace-objects", "cat-file", "-t", ref2.sha], {
46711
46850
  cwd: repo,
46712
46851
  encoding: "utf8",
@@ -46723,9 +46862,9 @@ function resolveHandoffReferences(handoff, workspace) {
46723
46862
  };
46724
46863
  return {
46725
46864
  ...handoff,
46726
- findings: handoff.findings.map((f) => ({ ...f, ...f.evidence ? { evidence: f.evidence.map(resolve17) } : {} })),
46865
+ findings: handoff.findings.map((f) => ({ ...f, ...f.evidence ? { evidence: f.evidence.map(resolve18) } : {} })),
46727
46866
  // A saved patch is Ordewell's own record, not a claim about a tree (ADR-0050).
46728
- ...handoff.artifacts ? { artifacts: handoff.artifacts.map((a) => a.kind === "patch" ? a : resolve17(a)) } : {}
46867
+ ...handoff.artifacts ? { artifacts: handoff.artifacts.map((a) => a.kind === "patch" ? a : resolve18(a)) } : {}
46729
46868
  };
46730
46869
  }
46731
46870
 
@@ -47391,8 +47530,8 @@ var PlanTurns = class {
47391
47530
  this.pump();
47392
47531
  return Promise.resolve(plan);
47393
47532
  }
47394
- const settled = new Promise((resolve17, reject) => {
47395
- this.waiters.set(entry.id, { resolve: resolve17, reject, signal: input.signal });
47533
+ const settled = new Promise((resolve18, reject) => {
47534
+ this.waiters.set(entry.id, { resolve: resolve18, reject, signal: input.signal });
47396
47535
  });
47397
47536
  this.pump();
47398
47537
  return settled;
@@ -48582,8 +48721,8 @@ var ChildPlanSession = class extends AbstractRunnerSession {
48582
48721
  counts;
48583
48722
  stopping = null;
48584
48723
  markGone;
48585
- gone = new Promise((resolve17) => {
48586
- this.markGone = resolve17;
48724
+ gone = new Promise((resolve18) => {
48725
+ this.markGone = resolve18;
48587
48726
  });
48588
48727
  /** Whoever spawned it attaches its listeners when the spawn resolves, so the child starts a macrotask later. */
48589
48728
  begin() {
@@ -49525,7 +49664,7 @@ var TreeLedger = class _TreeLedger {
49525
49664
  };
49526
49665
 
49527
49666
  // src/utils/treeEventLog.ts
49528
- var fs24 = __toESM(require("fs"));
49667
+ var fs25 = __toESM(require("fs"));
49529
49668
  var path48 = __toESM(require("path"));
49530
49669
 
49531
49670
  // src/services/eventStore.ts
@@ -49546,7 +49685,7 @@ function treeEventLogFile(rootSessionId, baseDir) {
49546
49685
  return path48.join(sessionDataDir(rootSessionId, baseDir), LOG_FILE);
49547
49686
  }
49548
49687
  function hasTreeEventLog(rootSessionId, baseDir) {
49549
- return fs24.existsSync(treeEventLogFile(rootSessionId, baseDir));
49688
+ return fs25.existsSync(treeEventLogFile(rootSessionId, baseDir));
49550
49689
  }
49551
49690
  function batchOf(line) {
49552
49691
  try {
@@ -49559,8 +49698,8 @@ function batchOf(line) {
49559
49698
  async function* landed2(file) {
49560
49699
  let stream;
49561
49700
  try {
49562
- await fs24.promises.access(file);
49563
- stream = fs24.createReadStream(file);
49701
+ await fs25.promises.access(file);
49702
+ stream = fs25.createReadStream(file);
49564
49703
  } catch (err) {
49565
49704
  if (err.code === "ENOENT") return;
49566
49705
  throw err;
@@ -49595,15 +49734,15 @@ function jsonlEventStore(file) {
49595
49734
  let walked = null;
49596
49735
  let doubted = null;
49597
49736
  async function open() {
49598
- await fs24.promises.mkdir(path48.dirname(file), { recursive: true });
49599
- const size = await fs24.promises.stat(file).then(({ size: size2 }) => size2, () => 0);
49737
+ await fs25.promises.mkdir(path48.dirname(file), { recursive: true });
49738
+ const size = await fs25.promises.stat(file).then(({ size: size2 }) => size2, () => 0);
49600
49739
  let found = walked?.end === size ? walked : null;
49601
49740
  if (!found) {
49602
49741
  found = { end: 0, next: 1 };
49603
49742
  for await (const batch of landed2(file)) found = pastBatch(found, batch);
49604
49743
  }
49605
- if (size > found.end) await fs24.promises.truncate(file, found.end);
49606
- return { handle: await fs24.promises.open(file, "a"), next: found.next };
49744
+ if (size > found.end) await fs25.promises.truncate(file, found.end);
49745
+ return { handle: await fs25.promises.open(file, "a"), next: found.next };
49607
49746
  }
49608
49747
  async function write(events) {
49609
49748
  writer ??= await open();
@@ -49999,7 +50138,7 @@ var SessionEventRelay = class {
49999
50138
  };
50000
50139
 
50001
50140
  // src/utils/taskLogStore.ts
50002
- var fs25 = __toESM(require("fs"));
50141
+ var fs26 = __toESM(require("fs"));
50003
50142
  var path49 = __toESM(require("path"));
50004
50143
  var EXTENSION = ".jsonl";
50005
50144
  function taskDir({ baseDir, sessionId, rootSessionId }, taskId) {
@@ -50008,7 +50147,7 @@ function taskDir({ baseDir, sessionId, rootSessionId }, taskId) {
50008
50147
  function listTaskLogAttempts(location, taskId) {
50009
50148
  let names2;
50010
50149
  try {
50011
- names2 = fs25.readdirSync(taskDir(location, taskId));
50150
+ names2 = fs26.readdirSync(taskDir(location, taskId));
50012
50151
  } catch {
50013
50152
  return [];
50014
50153
  }
@@ -50017,13 +50156,13 @@ function listTaskLogAttempts(location, taskId) {
50017
50156
  function openTaskLog(location, taskId, attempt) {
50018
50157
  ensureStateDirIgnored(location.baseDir);
50019
50158
  const dir = taskDir(location, taskId);
50020
- fs25.mkdirSync(dir, { recursive: true });
50159
+ fs26.mkdirSync(dir, { recursive: true });
50021
50160
  const next = (listTaskLogAttempts(location, taskId).pop() ?? 0) + 1;
50022
50161
  let number = attempt !== void 0 && Number.isInteger(attempt) && attempt >= 1 ? attempt : next;
50023
50162
  for (; ; ) {
50024
50163
  const file = path49.join(dir, `${number}${EXTENSION}`);
50025
50164
  try {
50026
- fs25.writeFileSync(file, "", { flag: "wx" });
50165
+ fs26.writeFileSync(file, "", { flag: "wx" });
50027
50166
  } catch (err) {
50028
50167
  if (err.code === "EEXIST") {
50029
50168
  number = Math.max(number + 1, next);
@@ -50035,7 +50174,7 @@ function openTaskLog(location, taskId, attempt) {
50035
50174
  attempt: number,
50036
50175
  append(events) {
50037
50176
  if (events.length === 0) return;
50038
- fs25.appendFileSync(file, events.map((e) => `${JSON.stringify(e)}
50177
+ fs26.appendFileSync(file, events.map((e) => `${JSON.stringify(e)}
50039
50178
  `).join(""));
50040
50179
  }
50041
50180
  };
@@ -50044,7 +50183,7 @@ function openTaskLog(location, taskId, attempt) {
50044
50183
  function prepareTaskOutputFile(location, taskId, attempt) {
50045
50184
  ensureStateDirIgnored(location.baseDir);
50046
50185
  const dir = taskDir(location, taskId);
50047
- fs25.mkdirSync(dir, { recursive: true });
50186
+ fs26.mkdirSync(dir, { recursive: true });
50048
50187
  return path49.join(dir, `${attempt}.output.txt`);
50049
50188
  }
50050
50189
  function taskPatchFile(location, taskId, attempt) {
@@ -50053,16 +50192,16 @@ function taskPatchFile(location, taskId, attempt) {
50053
50192
  function saveTaskPatch(location, taskId, attempt, patch) {
50054
50193
  ensureStateDirIgnored(location.baseDir);
50055
50194
  const file = taskPatchFile(location, taskId, attempt);
50056
- fs25.mkdirSync(path49.dirname(file), { recursive: true });
50195
+ fs26.mkdirSync(path49.dirname(file), { recursive: true });
50057
50196
  const partial = `${file}.${process.pid}-${Date.now()}.partial`;
50058
- fs25.writeFileSync(partial, patch, { flag: "wx" });
50059
- fs25.renameSync(partial, file);
50197
+ fs26.writeFileSync(partial, patch, { flag: "wx" });
50198
+ fs26.renameSync(partial, file);
50060
50199
  return file;
50061
50200
  }
50062
50201
  function readTaskPatch(location, taskId, attempt) {
50063
50202
  if (!Number.isInteger(attempt) || attempt < 1) return void 0;
50064
50203
  try {
50065
- return fs25.readFileSync(taskPatchFile(location, taskId, attempt));
50204
+ return fs26.readFileSync(taskPatchFile(location, taskId, attempt));
50066
50205
  } catch {
50067
50206
  return void 0;
50068
50207
  }
@@ -50074,7 +50213,7 @@ function readTaskLog(location, taskId, attempt) {
50074
50213
  if (!Number.isInteger(attempt) || attempt < 1) return [];
50075
50214
  let raw;
50076
50215
  try {
50077
- raw = fs25.readFileSync(path49.join(taskDir(location, taskId), `${attempt}${EXTENSION}`), "utf-8");
50216
+ raw = fs26.readFileSync(path49.join(taskDir(location, taskId), `${attempt}${EXTENSION}`), "utf-8");
50078
50217
  } catch {
50079
50218
  return [];
50080
50219
  }
@@ -50299,8 +50438,8 @@ function withTaskRunnerConfig(runner, setting) {
50299
50438
  // src/services/container/dockerLease.ts
50300
50439
  var import_crypto26 = require("crypto");
50301
50440
  var import_fs19 = require("fs");
50302
- var import_os10 = require("os");
50303
- var import_path14 = require("path");
50441
+ var import_os9 = require("os");
50442
+ var import_path13 = require("path");
50304
50443
 
50305
50444
  // src/services/container/modelGateway.ts
50306
50445
  var import_crypto22 = require("crypto");
@@ -50351,19 +50490,19 @@ var ModelGateway = class {
50351
50490
  api;
50352
50491
  /** The port it took on this host's loopback. */
50353
50492
  listen() {
50354
- return new Promise((resolve17, reject) => {
50493
+ return new Promise((resolve18, reject) => {
50355
50494
  this.server.once("error", reject);
50356
50495
  this.server.listen(0, "127.0.0.1", () => {
50357
50496
  const { port } = this.server.address();
50358
50497
  this.host = `127.0.0.1:${port}`;
50359
- resolve17(port);
50498
+ resolve18(port);
50360
50499
  });
50361
50500
  });
50362
50501
  }
50363
50502
  async close() {
50364
50503
  this.server.closeAllConnections();
50365
- await new Promise((resolve17) => {
50366
- this.server.close(() => resolve17());
50504
+ await new Promise((resolve18) => {
50505
+ this.server.close(() => resolve18());
50367
50506
  });
50368
50507
  }
50369
50508
  carries({ headers }) {
@@ -50473,7 +50612,7 @@ var CredentialBroker = class {
50473
50612
 
50474
50613
  // src/services/container/taskWorkspace.ts
50475
50614
  var import_crypto23 = require("crypto");
50476
- var import_path10 = require("path");
50615
+ var import_path9 = require("path");
50477
50616
  var MIRROR_ROOT = "/mirror";
50478
50617
  var TASK_ROOT = "/task";
50479
50618
  var WORK_ROOT = `${TASK_ROOT}/work`;
@@ -50490,8 +50629,8 @@ printf %s "$kept" > ${mark}
50490
50629
  `;
50491
50630
  var SIGN_IN_COPY = `${TASK_ROOT}/login/claude`;
50492
50631
  var SIGN_IN_MARK = `${TASK_ROOT}/login/handed`;
50493
- var repoDir = (repo) => repo.path === SELF_REPO ? WORK_ROOT : import_path10.posix.join(WORK_ROOT, repo.path);
50494
- var mirrorDir2 = (repo) => import_path10.posix.join(MIRROR_ROOT, `${repo.path === SELF_REPO ? "self" : (0, import_crypto23.createHash)("sha256").update(repo.path).digest("hex").slice(0, 16)}.git`);
50632
+ var repoDir = (repo) => repo.path === SELF_REPO ? WORK_ROOT : import_path9.posix.join(WORK_ROOT, repo.path);
50633
+ var mirrorDir2 = (repo) => import_path9.posix.join(MIRROR_ROOT, `${repo.path === SELF_REPO ? "self" : (0, import_crypto23.createHash)("sha256").update(repo.path).digest("hex").slice(0, 16)}.git`);
50495
50634
  var exportRef = (attempt) => `refs/ordewell/export/${attempt}`;
50496
50635
  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 .`;
50497
50636
  var extArgument = (arg) => arg.replace(/%/g, "%%").replace(/ /g, "% ");
@@ -50636,7 +50775,7 @@ function parseContainerSettings(raw) {
50636
50775
  }
50637
50776
 
50638
50777
  // src/services/container/containerRunners.ts
50639
- var import_path11 = require("path");
50778
+ var import_path10 = require("path");
50640
50779
  var LOGIN_VOLUME = "ordewell-login-claude-code";
50641
50780
  var CODEX_LOGIN_VOLUME = "ordewell-login-codex";
50642
50781
  var OPENCODE_LOGIN_VOLUME = "ordewell-login-opencode";
@@ -50689,7 +50828,7 @@ var CONTAINER_RUNNERS = [
50689
50828
  api: ANTHROPIC_API,
50690
50829
  unbrokered: { openai: OPENAI_API },
50691
50830
  // The copy is the runner's data directory, which `XDG_DATA_HOME` names the parent of.
50692
- signIn: { volume: OPENCODE_LOGIN_VOLUME, hosts: OPENCODE_HOSTS, copy: ["sh", "-c", COPY_OPENCODE_SIGN_IN], path: OPENCODE_SIGN_IN_COPY, env: { XDG_DATA_HOME: import_path11.posix.join(TASK_ROOT, "login") } },
50831
+ signIn: { volume: OPENCODE_LOGIN_VOLUME, hosts: OPENCODE_HOSTS, copy: ["sh", "-c", COPY_OPENCODE_SIGN_IN], path: OPENCODE_SIGN_IN_COPY, env: { XDG_DATA_HOME: import_path10.posix.join(TASK_ROOT, "login") } },
50693
50832
  args: (launch) => launch.args
50694
50833
  }
50695
50834
  ];
@@ -50851,8 +50990,8 @@ var describeProblems = (problems) => problems.map(({ message, remedy }) => [mess
50851
50990
  var import_crypto24 = require("crypto");
50852
50991
  var import_fs16 = require("fs");
50853
50992
  var import_net2 = require("net");
50854
- var import_os8 = require("os");
50855
- var import_path12 = require("path");
50993
+ var import_os7 = require("os");
50994
+ var import_path11 = require("path");
50856
50995
 
50857
50996
  // src/services/container/guaranteeProbe.ts
50858
50997
  var METADATA = "169.254.169.254:80";
@@ -50990,8 +51129,8 @@ var OUTSIDE = "1.1.1.1:443";
50990
51129
  var OUTSIDE_NAME = "example.com";
50991
51130
  var PROBE_MS = 12e4;
50992
51131
  function plantFile() {
50993
- const dir = (0, import_fs16.mkdtempSync)((0, import_path12.join)((0, import_fs16.realpathSync)((0, import_os8.tmpdir)()), "ordewell-canary-"));
50994
- const file = (0, import_path12.join)(dir, "canary");
51132
+ const dir = (0, import_fs16.mkdtempSync)((0, import_path11.join)((0, import_fs16.realpathSync)((0, import_os7.tmpdir)()), "ordewell-canary-"));
51133
+ const file = (0, import_path11.join)(dir, "canary");
50995
51134
  (0, import_fs16.writeFileSync)(file, (0, import_crypto24.randomBytes)(16).toString("hex"));
50996
51135
  return { file, remove: () => (0, import_fs16.rmSync)(dir, { recursive: true, force: true }) };
50997
51136
  }
@@ -51001,9 +51140,9 @@ function listenOnLoopback() {
51001
51140
  hits += 1;
51002
51141
  socket.destroy();
51003
51142
  });
51004
- return new Promise((resolve17, reject) => {
51143
+ return new Promise((resolve18, reject) => {
51005
51144
  server4.once("error", reject);
51006
- server4.listen(0, "127.0.0.1", () => resolve17({ port: server4.address().port, hits: () => hits, close: () => server4.close() }));
51145
+ server4.listen(0, "127.0.0.1", () => resolve18({ port: server4.address().port, hits: () => hits, close: () => server4.close() }));
51007
51146
  });
51008
51147
  }
51009
51148
  async function withCanaries(use) {
@@ -51024,7 +51163,7 @@ function networkAsked(route, port) {
51024
51163
  return { outside, name: OUTSIDE_NAME, proxy: route.proxied ? { refused: [...outside, METADATA] } : null };
51025
51164
  }
51026
51165
  function probeExpected(settings, mounts) {
51027
- return { mounts, memoryBytes: settings.memoryBytes, pids: PIDS_LIMIT, hostKernel: `${(0, import_os8.type)()} ${(0, import_os8.release)()}` };
51166
+ return { mounts, memoryBytes: settings.memoryBytes, pids: PIDS_LIMIT, hostKernel: `${(0, import_os7.type)()} ${(0, import_os7.release)()}` };
51028
51167
  }
51029
51168
  function probeFindings(stdout, stderr) {
51030
51169
  try {
@@ -51067,7 +51206,7 @@ var SpawnedDockerCli = class {
51067
51206
  }
51068
51207
  async call(args, { input, env, timeoutMs = CALL_TIMEOUT_MS, stdoutTo } = {}) {
51069
51208
  const child = (0, import_child_process17.spawn)("docker", [...args], { env: await this.environment(env), stdio: ["pipe", "pipe", "pipe"] });
51070
- return new Promise((resolve17) => {
51209
+ return new Promise((resolve18) => {
51071
51210
  let stdout = "";
51072
51211
  let stderr = "";
51073
51212
  let written = 0;
@@ -51093,7 +51232,7 @@ var SpawnedDockerCli = class {
51093
51232
  child.stdin.end(input);
51094
51233
  const finish2 = (code) => {
51095
51234
  clearTimeout(timer);
51096
- const done = () => resolve17({ code, stdout, stderr, ...overflowed ? { overflowed: true } : {} });
51235
+ const done = () => resolve18({ code, stdout, stderr, ...overflowed ? { overflowed: true } : {} });
51097
51236
  if (sink) sink.end(done);
51098
51237
  else done();
51099
51238
  };
@@ -51198,8 +51337,8 @@ function listening(entry) {
51198
51337
  entry.stderr?.on("data", (chunk) => {
51199
51338
  said2 = (said2 + chunk.toString()).slice(-STDERR_TAIL_CHARS2);
51200
51339
  });
51201
- return new Promise((resolve17, reject) => {
51202
- entry.stdout?.once("data", () => resolve17());
51340
+ return new Promise((resolve18, reject) => {
51341
+ entry.stdout?.once("data", () => resolve18());
51203
51342
  entry.once("error", reject);
51204
51343
  entry.once("close", () => reject(new Error(`The egress sidecar ended before it listened${said2.trim() ? `: ${said2.trim()}` : "."}`)));
51205
51344
  });
@@ -51333,20 +51472,20 @@ send(READY, 0);
51333
51472
  var LeaseRelay = class {
51334
51473
  constructor(entry) {
51335
51474
  this.entry = entry;
51336
- this.ready = new Promise((resolve17, reject) => {
51337
- this.markReady = resolve17;
51475
+ this.ready = new Promise((resolve18, reject) => {
51476
+ this.markReady = resolve18;
51338
51477
  this.failReady = reject;
51339
51478
  });
51340
51479
  this.ready.catch(() => void 0);
51341
- this.ended = new Promise((resolve17) => {
51480
+ this.ended = new Promise((resolve18) => {
51342
51481
  entry.once("close", () => {
51343
51482
  this.gone();
51344
- resolve17();
51483
+ resolve18();
51345
51484
  });
51346
51485
  entry.once("error", (err) => {
51347
51486
  this.stderrTail += err.message;
51348
51487
  this.gone();
51349
- resolve17();
51488
+ resolve18();
51350
51489
  });
51351
51490
  });
51352
51491
  entry.stdin?.on("error", () => void 0);
@@ -51383,8 +51522,8 @@ var LeaseRelay = class {
51383
51522
  if (known) return known.listening;
51384
51523
  let heard;
51385
51524
  let failed2;
51386
- const listening2 = new Promise((resolve17, reject) => {
51387
- heard = resolve17;
51525
+ const listening2 = new Promise((resolve18, reject) => {
51526
+ heard = resolve18;
51388
51527
  failed2 = reject;
51389
51528
  });
51390
51529
  this.forwards.set(containerPort, { hostPort, listening: listening2, heard, failed: failed2 });
@@ -51419,9 +51558,9 @@ var LeaseRelay = class {
51419
51558
  this.send(CONNECT, conn, port);
51420
51559
  });
51421
51560
  this.exposed.add(server4);
51422
- await new Promise((resolve17, reject) => {
51561
+ await new Promise((resolve18, reject) => {
51423
51562
  server4.once("error", reject);
51424
- server4.listen(0, "127.0.0.1", () => resolve17());
51563
+ server4.listen(0, "127.0.0.1", () => resolve18());
51425
51564
  });
51426
51565
  return server4.address().port;
51427
51566
  }
@@ -51516,8 +51655,8 @@ async function tryVolume(cli, volume) {
51516
51655
  const removed = await cli.call(["volume", "rm", "-f", volume]);
51517
51656
  if (removed.code === 0) return null;
51518
51657
  if (tried === VOLUME_TRIES) return removed.stderr.trim();
51519
- await new Promise((resolve17) => {
51520
- setTimeout(resolve17, VOLUME_WAIT_MS);
51658
+ await new Promise((resolve18) => {
51659
+ setTimeout(resolve18, VOLUME_WAIT_MS);
51521
51660
  });
51522
51661
  }
51523
51662
  }
@@ -51583,8 +51722,8 @@ async function reclaimContainers(tree, raw, { cli = new SpawnedDockerCli(), tell
51583
51722
 
51584
51723
  // src/services/container/pushGate.ts
51585
51724
  var import_fs18 = require("fs");
51586
- var import_os9 = require("os");
51587
- var import_path13 = require("path");
51725
+ var import_os8 = require("os");
51726
+ var import_path12 = require("path");
51588
51727
  var FSCK = ["-c", "transfer.fsckObjects=true", "-c", "fetch.fsckObjects=true"];
51589
51728
  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"];
51590
51729
  var PushRefused = class extends Error {
@@ -51616,8 +51755,8 @@ async function takeThroughGate(invoker, repo, bundle, { ref: ref2, base }) {
51616
51755
  async function hooksWritten(invoker, repo, base, snapshot) {
51617
51756
  const top = (await git(invoker, repo, ["rev-parse", "--show-toplevel"])).trim();
51618
51757
  const path53 = (await git(invoker, repo, ["rev-parse", "--git-path", "hooks"])).trim();
51619
- const given = (0, import_path13.resolve)(top, path53);
51620
- const folders = [.../* @__PURE__ */ new Set([given, realOf(given)])].map((dir) => (0, import_path13.relative)(top, dir).split(import_path13.sep).join("/").toLowerCase()).filter((dir) => dir !== ".." && !dir.startsWith("../") && !(0, import_path13.isAbsolute)(dir));
51758
+ const given = (0, import_path12.resolve)(top, path53);
51759
+ const folders = [.../* @__PURE__ */ new Set([given, realOf(given)])].map((dir) => (0, import_path12.relative)(top, dir).split(import_path12.sep).join("/").toLowerCase()).filter((dir) => dir !== ".." && !dir.startsWith("../") && !(0, import_path12.isAbsolute)(dir));
51621
51760
  if (folders.length === 0) return [];
51622
51761
  const changed = (await git(invoker, repo, ["diff-tree", "-r", "-z", "--name-only", "--no-renames", base, snapshot])).split("\0").filter(Boolean);
51623
51762
  return changed.filter((file) => {
@@ -51627,20 +51766,20 @@ async function hooksWritten(invoker, repo, base, snapshot) {
51627
51766
  }
51628
51767
  function realOf(path53) {
51629
51768
  try {
51630
- return (0, import_fs18.realpathSync)(path53);
51769
+ return realPathOf(path53);
51631
51770
  } catch {
51632
51771
  return path53;
51633
51772
  }
51634
51773
  }
51635
51774
  async function checkObjects(invoker, repo, snapshot, base) {
51636
- const scratch = (0, import_fs18.mkdtempSync)((0, import_path13.join)((0, import_os9.tmpdir)(), "ordewell-gate-"));
51775
+ const scratch = (0, import_fs18.mkdtempSync)((0, import_path12.join)((0, import_os8.tmpdir)(), "ordewell-gate-"));
51637
51776
  try {
51638
- const prefix = (0, import_path13.join)(scratch, "taken");
51777
+ const prefix = (0, import_path12.join)(scratch, "taken");
51639
51778
  const packed = await tryGit(invoker, repo, ["pack-objects", "--revs", "-q", prefix], `${snapshot}
51640
51779
  ^${base}
51641
51780
  `);
51642
51781
  if (!packed.ok) throw new PushRefused(`git could not read what it holds (${packed.stderr.trim()})`);
51643
- const checked = await tryGit(invoker, repo, ["index-pack", "--strict", "-o", (0, import_path13.join)(scratch, "checked.idx"), `${prefix}-${packed.stdout.trim()}.pack`]);
51782
+ const checked = await tryGit(invoker, repo, ["index-pack", "--strict", "-o", (0, import_path12.join)(scratch, "checked.idx"), `${prefix}-${packed.stdout.trim()}.pack`]);
51644
51783
  if (!checked.ok) throw new PushRefused(`git would not take it (${checked.stderr.trim()})`);
51645
51784
  } finally {
51646
51785
  (0, import_fs18.rmSync)(scratch, { recursive: true, force: true });
@@ -51655,10 +51794,10 @@ async function restoreSnapshot(invoker, worktree, snapshot, linked) {
51655
51794
  await run("reset", "-q");
51656
51795
  }
51657
51796
  async function hooksLandingWouldRun(invoker, worktree) {
51658
- const dir = (0, import_path13.resolve)(worktree, (await git(invoker, worktree, ["rev-parse", "--git-path", "hooks"])).trim());
51797
+ const dir = (0, import_path12.resolve)(worktree, (await git(invoker, worktree, ["rev-parse", "--git-path", "hooks"])).trim());
51659
51798
  return LANDING_HOOKS.filter((hook) => {
51660
51799
  try {
51661
- (0, import_fs18.accessSync)((0, import_path13.resolve)(dir, hook), import_fs18.constants.X_OK);
51800
+ (0, import_fs18.accessSync)((0, import_path12.resolve)(dir, hook), import_fs18.constants.X_OK);
51662
51801
  return true;
51663
51802
  } catch {
51664
51803
  return false;
@@ -51766,7 +51905,7 @@ var DockerExecutionBackend = class {
51766
51905
  */
51767
51906
  async preflight(runner, model) {
51768
51907
  const setupCommand = this.options.setupCommand?.();
51769
- const { problems, settings } = await inspectReadiness(this.options.settings, { cli: this.cli, broker: this.broker, agent: runner !== null, ...runner ? { runner } : {}, ...setupCommand ? { setupCommand } : {} });
51908
+ 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 } : {} });
51770
51909
  if (!settings) throw new Error(`This session runs tasks in containers, and this task cannot start in one. ${describeProblems(problems)}`);
51771
51910
  const refusal4 = runner && settings.login.kind === "broker" ? brokerRefusal(runner, model) : null;
51772
51911
  if (refusal4) throw new Error(`This session runs tasks in containers, and this task cannot start in one. ${refusal4}`);
@@ -51793,7 +51932,7 @@ var DockerExecutionBackend = class {
51793
51932
  }
51794
51933
  async workingDirectory(opened2) {
51795
51934
  const { worktree, writable, cwd } = opened2.workspace;
51796
- return import_path14.posix.join(WORK_ROOT, worktree ? (0, import_path14.relative)(writable ?? cwd, cwd).split(import_path14.sep).join("/") : await this.checkoutFolder(cwd));
51935
+ return import_path13.posix.join(WORK_ROOT, worktree ? (0, import_path13.relative)(writable ?? cwd, cwd).split(import_path13.sep).join("/") : await this.checkoutFolder(cwd));
51797
51936
  }
51798
51937
  async start({ runner, settings, spec, opened: opened2, repos }, signal) {
51799
51938
  const taskId = spec.task.id;
@@ -52030,7 +52169,7 @@ var DockerExecutionBackend = class {
52030
52169
  const launchNumber = ++box.launches;
52031
52170
  const moved = /* @__PURE__ */ new Map();
52032
52171
  for (const file of launch.files) {
52033
- const inside2 = `/tmp/ordewell/${launchNumber}-${(0, import_path14.basename)(file)}`;
52172
+ const inside2 = `/tmp/ordewell/${launchNumber}-${(0, import_path13.basename)(file)}`;
52034
52173
  const wrote = await this.cli.call(["exec", "-i", box.name, "sh", "-c", 'umask 077; mkdir -p /tmp/ordewell; cat > "$0"', inside2], { input: (0, import_fs19.readFileSync)(file) });
52035
52174
  if (wrote.code !== 0) throw new Error(`Could not hand the runner its configuration: ${wrote.stderr.trim()}`);
52036
52175
  moved.set(file, inside2);
@@ -52153,10 +52292,10 @@ var DockerExecutionBackend = class {
52153
52292
  */
52154
52293
  bringBack(box) {
52155
52294
  box.bringing ??= (async () => {
52156
- const dir = (0, import_fs19.mkdtempSync)((0, import_path14.join)((0, import_os10.tmpdir)(), "ordewell-export-"));
52295
+ const dir = (0, import_fs19.mkdtempSync)((0, import_path13.join)((0, import_os9.tmpdir)(), "ordewell-export-"));
52157
52296
  try {
52158
52297
  const taken = [];
52159
- for (const repo of box.repos) taken.push({ repo, snapshot: await this.take(box, repo, (0, import_path14.join)(dir, `${taken.length}.bundle`)) });
52298
+ for (const repo of box.repos) taken.push({ repo, snapshot: await this.take(box, repo, (0, import_path13.join)(dir, `${taken.length}.bundle`)) });
52160
52299
  for (const { repo, snapshot } of taken) await restoreSnapshot(this.git, repo.worktree, snapshot, repo.linked);
52161
52300
  } catch (err) {
52162
52301
  await this.cli.call(["volume", "create", ...this.labels(box.taskId), this.heldVolume(box.taskId)]);
@@ -55557,12 +55696,12 @@ var Session = class {
55557
55696
  return !task2 || reportEnded(task2) || task2.status !== "in_progress" && !this.orchestrator.getAttempt(taskId);
55558
55697
  };
55559
55698
  if (over() || signal?.aborted) return Promise.resolve();
55560
- return new Promise((resolve17) => {
55699
+ return new Promise((resolve18) => {
55561
55700
  const done = () => {
55562
55701
  clearTimeout(timer);
55563
55702
  unsubscribe();
55564
55703
  signal?.removeEventListener("abort", done);
55565
- resolve17();
55704
+ resolve18();
55566
55705
  };
55567
55706
  const timer = setTimeout(done, ms);
55568
55707
  const check2 = () => {
@@ -56758,7 +56897,7 @@ ${pins.join("\n")}` : goal;
56758
56897
  slotForTurn(signal) {
56759
56898
  if (this.turnRoom()) return null;
56760
56899
  if (signal?.aborted) return Promise.reject(new PlannerTurnStoppedError());
56761
- return new Promise((resolve17, reject) => {
56900
+ return new Promise((resolve18, reject) => {
56762
56901
  const onAbort = () => {
56763
56902
  if (this.openingsWaiting.delete(end)) end(new PlannerTurnStoppedError());
56764
56903
  };
@@ -56774,7 +56913,7 @@ ${pins.join("\n")}` : goal;
56774
56913
  this.roomWaiter = null;
56775
56914
  this.openingsWaiting.delete(end);
56776
56915
  signal?.removeEventListener("abort", onAbort);
56777
- resolve17();
56916
+ resolve18();
56778
56917
  return true;
56779
56918
  };
56780
56919
  });
@@ -56785,7 +56924,7 @@ ${pins.join("\n")}` : goal;
56785
56924
  return null;
56786
56925
  }
56787
56926
  if (signal?.aborted) return Promise.reject(new PlannerTurnStoppedError());
56788
- return new Promise((resolve17, reject) => {
56927
+ return new Promise((resolve18, reject) => {
56789
56928
  const onAbort = () => {
56790
56929
  if (this.openingsWaiting.delete(end)) end(new PlannerTurnStoppedError());
56791
56930
  };
@@ -56799,7 +56938,7 @@ ${pins.join("\n")}` : goal;
56799
56938
  if (!this.openingsWaiting.delete(end)) return;
56800
56939
  signal?.removeEventListener("abort", onAbort);
56801
56940
  this.assertPlannerReady();
56802
- }).then(resolve17, reject);
56941
+ }).then(resolve18, reject);
56803
56942
  });
56804
56943
  }
56805
56944
  /**
@@ -56979,8 +57118,8 @@ ${pins.join("\n")}` : goal;
56979
57118
  if (!pending) return null;
56980
57119
  const held2 = pending.held;
56981
57120
  if (!held2) return this.turns.follow(input, forced);
56982
- return new Promise((resolve17, reject) => {
56983
- held2.push({ input, forced, resolve: resolve17, reject });
57121
+ return new Promise((resolve18, reject) => {
57122
+ held2.push({ input, forced, resolve: resolve18, reject });
56984
57123
  });
56985
57124
  }
56986
57125
  /**
@@ -59417,8 +59556,8 @@ var StructuredSession = class extends AbstractRunnerSession {
59417
59556
  if (this.stopping) return this.stopping;
59418
59557
  if (this.exited) return Promise.resolve();
59419
59558
  let woundDown;
59420
- this.stopping = new Promise((resolve17) => {
59421
- woundDown = resolve17;
59559
+ this.stopping = new Promise((resolve18) => {
59560
+ woundDown = resolve18;
59422
59561
  });
59423
59562
  void this.windDown().catch(() => this.kill()).then(woundDown);
59424
59563
  return this.stopping;
@@ -59447,7 +59586,7 @@ var StructuredSession = class extends AbstractRunnerSession {
59447
59586
  }
59448
59587
  /** Whether `turn` closed within the deadline once interrupted. */
59449
59588
  async turnClosed(turn, adapter, deadline) {
59450
- const closed = new Promise((resolve17) => this.structuredEmitter.once("turnEnd", () => resolve17()));
59589
+ const closed = new Promise((resolve18) => this.structuredEmitter.once("turnEnd", () => resolve18()));
59451
59590
  adapter.interrupt(Math.max(0, deadline - Date.now())).catch(() => false);
59452
59591
  return await this.within(closed, deadline) && turn.ended;
59453
59592
  }
@@ -59458,7 +59597,7 @@ var StructuredSession = class extends AbstractRunnerSession {
59458
59597
  gone() {
59459
59598
  const { signal } = this.ended;
59460
59599
  if (signal.aborted) return Promise.resolve();
59461
- return new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
59600
+ return new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
59462
59601
  }
59463
59602
  turnState() {
59464
59603
  return this.state;
@@ -59610,7 +59749,7 @@ var StructuredSession = class extends AbstractRunnerSession {
59610
59749
  }
59611
59750
  async interruptTurn(turn, adapter) {
59612
59751
  const grace = this.launch.interruptGraceMs;
59613
- const ended2 = new Promise((resolve17) => this.structuredEmitter.once("turnEnd", () => resolve17()));
59752
+ const ended2 = new Promise((resolve18) => this.structuredEmitter.once("turnEnd", () => resolve18()));
59614
59753
  const acknowledged = await settleWithin(adapter.interrupt(grace).catch(() => false), { timeoutMs: grace, onTimeout: () => false });
59615
59754
  if (acknowledged) {
59616
59755
  const settled = await settleWithin(ended2.then(() => true), { timeoutMs: grace, onTimeout: () => false });
@@ -60042,11 +60181,11 @@ var RunnerRegistry = class {
60042
60181
  };
60043
60182
 
60044
60183
  // src/plugins/removedPluginNotice.ts
60045
- var fs26 = __toESM(require("fs"));
60184
+ var fs27 = __toESM(require("fs"));
60046
60185
  var path51 = __toESM(require("path"));
60047
60186
  function isManifestFile(file) {
60048
60187
  try {
60049
- return fs26.statSync(file).isFile();
60188
+ return fs27.statSync(file).isFile();
60050
60189
  } catch {
60051
60190
  return false;
60052
60191
  }
@@ -60054,7 +60193,7 @@ function isManifestFile(file) {
60054
60193
  function removedPluginNotice(dataDir = globalDataDir()) {
60055
60194
  const directory = path51.join(dataDir, "plugins");
60056
60195
  try {
60057
- const hasManifest = isManifestFile(path51.join(directory, "manifest.json")) || fs26.readdirSync(directory, { withFileTypes: true }).some(
60196
+ const hasManifest = isManifestFile(path51.join(directory, "manifest.json")) || fs27.readdirSync(directory, { withFileTypes: true }).some(
60058
60197
  (entry) => (entry.isDirectory() || entry.isSymbolicLink()) && isManifestFile(path51.join(directory, entry.name, "manifest.json"))
60059
60198
  );
60060
60199
  if (hasManifest) return "Plugin runners were removed; manifests in ~/.ordewell/plugins/ are ignored. See the CHANGELOG.";
@@ -60065,7 +60204,7 @@ function removedPluginNotice(dataDir = globalDataDir()) {
60065
60204
  }
60066
60205
 
60067
60206
  // src/utils/stateStore.ts
60068
- var fs27 = __toESM(require("fs"));
60207
+ var fs28 = __toESM(require("fs"));
60069
60208
  var path52 = __toESM(require("path"));
60070
60209
  var STATE_FILE2 = "state.json";
60071
60210
  function getStatePath(baseDir) {
@@ -60083,9 +60222,9 @@ function saveState(plan, baseDir, sessionId) {
60083
60222
  function loadState(baseDir, logger = defaultLogger) {
60084
60223
  const dir = baseDir ?? process.cwd();
60085
60224
  const statePath = getStatePath(dir);
60086
- if (!fs27.existsSync(statePath)) return null;
60225
+ if (!fs28.existsSync(statePath)) return null;
60087
60226
  try {
60088
- const raw = fs27.readFileSync(statePath, "utf-8");
60227
+ const raw = fs28.readFileSync(statePath, "utf-8");
60089
60228
  const parsed = JSON.parse(raw);
60090
60229
  if (!Array.isArray(parsed.runners)) {
60091
60230
  logger.warn("stateStore", `rejecting state from ${statePath}: old format (scalar "runner" instead of "runners" array). Please re-plan.`);
@@ -60109,11 +60248,11 @@ function loadState(baseDir, logger = defaultLogger) {
60109
60248
  function clearState(baseDir) {
60110
60249
  const dir = baseDir ?? process.cwd();
60111
60250
  const statePath = getStatePath(dir);
60112
- if (fs27.existsSync(statePath)) fs27.unlinkSync(statePath);
60251
+ if (fs28.existsSync(statePath)) fs28.unlinkSync(statePath);
60113
60252
  }
60114
60253
  function stateExists(baseDir) {
60115
60254
  const dir = baseDir ?? process.cwd();
60116
- return fs27.existsSync(getStatePath(dir));
60255
+ return fs28.existsSync(getStatePath(dir));
60117
60256
  }
60118
60257
 
60119
60258
  // src/services/selectPlanner.ts