@ordewell/core 0.12.3 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3318,6 +3318,10 @@ function exclusionWord(pattern) {
3318
3318
  function isScopePattern(entry) {
3319
3319
  return /^(\/|~|https?:\/\/|web_search:|mcp__|mcp-server:|[A-Za-z]:[\\/])/.test(entry);
3320
3320
  }
3321
+ var backslashed = (scope) => scope.replace(/\//g, "\\");
3322
+ function scopeExclusion(entry) {
3323
+ return /^[A-Za-z]:[\\/]/.test(entry) ? globRegExp(backslashed(entry), "i") : globRegExp(entry);
3324
+ }
3321
3325
  function parseAllowlist(entries) {
3322
3326
  const list2 = { commands: [], commandExclusions: [], tools: [], toolExclusions: [], scopes: [], scopeExclusions: [] };
3323
3327
  for (const raw of entries) {
@@ -3327,7 +3331,8 @@ function parseAllowlist(entries) {
3327
3331
  if (entry.startsWith("mcp:")) {
3328
3332
  (exclude ? list2.toolExclusions : list2.tools).push(globRegExp(entry.slice(4).trim(), "i"));
3329
3333
  } else if (isScopePattern(entry)) {
3330
- (exclude ? list2.scopeExclusions : list2.scopes).push(globRegExp(entry));
3334
+ if (exclude) list2.scopeExclusions.push(scopeExclusion(entry));
3335
+ else list2.scopes.push(globRegExp(entry));
3331
3336
  } else {
3332
3337
  const [binary, ...words] = entry.split(/\s+/);
3333
3338
  (exclude ? list2.commandExclusions : list2.commands).push({ text: raw.trim(), binary, words: words.map(exclude ? exclusionWord : ruleWord) });
@@ -3375,7 +3380,7 @@ function toolAllowed(list2, tool2) {
3375
3380
  }
3376
3381
  function scopeExcluded(list2, scope) {
3377
3382
  const origin = /^(?:curl|wget) (https?:\/\/\S+\/\*)$/.exec(scope)?.[1];
3378
- return list2.scopeExclusions.some((re) => re.test(scope) || origin !== void 0 && re.test(origin));
3383
+ return list2.scopeExclusions.some((re) => re.test(scope) || re.test(backslashed(scope)) || origin !== void 0 && re.test(origin));
3379
3384
  }
3380
3385
  function scopeAllowed(list2, scope) {
3381
3386
  if (scopeExcluded(list2, scope)) return false;
@@ -3749,13 +3754,13 @@ function vetHostUnresolved(host) {
3749
3754
  if (LOCAL_NAMES.has(bare.toLowerCase())) return { ok: false, reason: `local host name ${bare}` };
3750
3755
  return void 0;
3751
3756
  }
3752
- async function vetHost(host, resolve17) {
3757
+ async function vetHost(host, resolve18) {
3753
3758
  const settled = vetHostUnresolved(host);
3754
3759
  if (settled) return settled;
3755
3760
  const bare = stripBrackets(host);
3756
3761
  let addresses;
3757
3762
  try {
3758
- addresses = await resolve17(bare);
3763
+ addresses = await resolve18(bare);
3759
3764
  } catch {
3760
3765
  return { ok: false, reason: `${bare} did not resolve` };
3761
3766
  }
@@ -3766,16 +3771,16 @@ async function vetHost(host, resolve17) {
3766
3771
  }
3767
3772
  return { ok: true, addresses };
3768
3773
  }
3769
- async function vetEgress(host, port, resolve17 = resolveAll) {
3770
- return vetEgressUnresolved(host, port) ?? vetHost(host, resolve17);
3774
+ async function vetEgress(host, port, resolve18 = resolveAll) {
3775
+ return vetEgressUnresolved(host, port) ?? vetHost(host, resolve18);
3771
3776
  }
3772
3777
  function vetEgressUnresolved(host, port) {
3773
3778
  if (!ALLOWED_PORTS.has(port)) return { ok: false, reason: `port ${port} is not 80 or 443` };
3774
3779
  return vetHostUnresolved(host);
3775
3780
  }
3776
- function guardedLookup(resolve17 = resolveAll) {
3781
+ function guardedLookup(resolve18 = resolveAll) {
3777
3782
  return (hostname, options, callback) => {
3778
- void vetHost(hostname, resolve17).then((check2) => {
3783
+ void vetHost(hostname, resolve18).then((check2) => {
3779
3784
  if (!check2.ok) {
3780
3785
  callback(Object.assign(new Error(`blocked host: ${check2.reason}`), { code: "EBLOCKEDHOST" }), []);
3781
3786
  return;
@@ -4882,10 +4887,139 @@ function allowlistRule(parts, allow, trustedResolves) {
4882
4887
  }
4883
4888
 
4884
4889
  // src/services/researchShell.ts
4890
+ import { execFileSync } from "child_process";
4885
4891
  import * as fsSync from "fs";
4892
+ import * as path2 from "path";
4893
+
4894
+ // src/services/pathScope.ts
4895
+ import * as os from "os";
4886
4896
  import * as path from "path";
4897
+ function expandHome(target) {
4898
+ if (!target.startsWith("~")) return target;
4899
+ const home = os.homedir();
4900
+ if (target === "~" || target.startsWith("~/")) return path.join(home, target.slice(1));
4901
+ return path.join(path.dirname(home), target.slice(1));
4902
+ }
4903
+ function resolveWithin(root, target, from = root, hostPath2) {
4904
+ const spelled = hostPath2 ? hostPath2(target, from) : target;
4905
+ if (spelled === void 0) return { abs: target, inside: false, unfollowable: true };
4906
+ if (hostPath2 && isInertDevice(spelled)) return { abs: spelled, inside: false, device: true };
4907
+ const abs = path.resolve(from, expandHome(spelled));
4908
+ const rel = path.relative(root, abs);
4909
+ return { abs, inside: rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel), ...isInertDevice(abs) ? { device: true } : {} };
4910
+ }
4911
+ function resolveRef(root, ref2, hostPath2) {
4912
+ let from = root;
4913
+ for (const target of ref2.cwd) {
4914
+ const dir = resolveWithin(root, target, from, hostPath2);
4915
+ if (dir.unfollowable) return { abs: ref2.path, inside: false, unfollowable: true };
4916
+ from = dir.abs;
4917
+ }
4918
+ return resolveWithin(root, ref2.path, from, hostPath2);
4919
+ }
4920
+ function grantScopeFor(abs, kind) {
4921
+ if (kind === "directory") return path.join(abs, "*");
4922
+ const parent = path.dirname(abs);
4923
+ if (parent === path.parse(abs).root) return path.join(abs, "*");
4924
+ return path.join(parent, "*");
4925
+ }
4926
+ var INERT_DEVICES = ["/dev/null", "/dev/stdin", "/dev/stdout", "/dev/stderr"];
4927
+ function isInertDevice(abs) {
4928
+ return INERT_DEVICES.includes(abs);
4929
+ }
4930
+
4931
+ // src/services/researchShell.ts
4887
4932
  var POSIX_SHELL = { file: null, args: [], dialect: "posix", utilsDir: null };
4888
4933
  var CMD_SHELL = { file: null, args: [], dialect: "cmd", utilsDir: null };
4934
+ function defaultReadMounts(root) {
4935
+ const mount = path2.win32.join(root, "usr", "bin", "mount.exe");
4936
+ try {
4937
+ const read2 = (args) => execFileSync(mount, args, { encoding: "utf8", timeout: 5e3, windowsHide: true });
4938
+ return [read2([]), read2(["-p"])];
4939
+ } catch {
4940
+ return void 0;
4941
+ }
4942
+ }
4943
+ function parseMounts(mounts, prefix) {
4944
+ const points = [];
4945
+ for (const line of mounts.split(/\r?\n/)) {
4946
+ const m = /^(.+?) on (\/.*?) type \S+ \(([^)]*)\)/.exec(line);
4947
+ if (!m) continue;
4948
+ const host = m[1].replace(/\//g, "\\");
4949
+ points.push({ point: m[2], host: /^[A-Za-z]:$/.test(host) ? `${host}\\` : host, caseless: m[3].split(",").includes("posix=0") });
4950
+ }
4951
+ if (!points.some((p) => p.point === "/")) return void 0;
4952
+ const cygdrive = /^\s*(\/\S*)\s+\S+\s+\S+/m.exec(prefix.split(/\r?\n/).slice(1).join("\n"))?.[1] ?? "/";
4953
+ return { points, cygdrive };
4954
+ }
4955
+ function defaultMounts(root, env) {
4956
+ const temp = env.TEMP || env.TMP;
4957
+ return {
4958
+ points: [
4959
+ { point: "/", host: root, caseless: false },
4960
+ { point: "/bin", host: path2.win32.join(root, "usr", "bin"), caseless: false },
4961
+ ...temp ? [{ point: "/tmp", host: temp, caseless: true }] : []
4962
+ ],
4963
+ cygdrive: "/"
4964
+ };
4965
+ }
4966
+ function mountedHostPath(table, spelled, from, home) {
4967
+ if (isInertDevice(spelled)) return spelled;
4968
+ if (spelled.startsWith("/")) return mountedAbsolute(table, spelled.replace(/\\/g, "/"));
4969
+ if (home && (spelled === "~" || /^~[\\/]/.test(spelled))) {
4970
+ const base = home.startsWith("/") ? mountedAbsolute(table, home) : home;
4971
+ return base === void 0 ? void 0 : path2.win32.join(base, spelled.slice(1));
4972
+ }
4973
+ if (from === void 0 || /^[A-Za-z]:/.test(spelled) || spelled.startsWith("\\") || spelled.startsWith("~")) return spelled;
4974
+ return staysOnDrive(table, spelled.replace(/\\/g, "/"), from) ? spelled : void 0;
4975
+ }
4976
+ function mountedAbsolute(table, posix17) {
4977
+ if (/^\/\/[^/]/.test(posix17)) return posix17.replace(/\//g, "\\");
4978
+ const segments = posix17.split("/").filter((s) => s !== "" && s !== ".");
4979
+ if (segments.includes("..")) return void 0;
4980
+ const prefix = table.cygdrive.endsWith("/") ? table.cygdrive : `${table.cygdrive}/`;
4981
+ const top = segments[0]?.toLowerCase();
4982
+ if (top === "proc" && segments[1]?.toLowerCase() === "cygdrive") return mountedAbsolute(table, prefix + segments.slice(2).join("/"));
4983
+ if (top === "proc" || top === "dev") return void 0;
4984
+ const normal = `/${segments.join("/")}`;
4985
+ const under = ({ point, caseless }) => {
4986
+ if (point === "/") return true;
4987
+ const [at, here] = caseless ? [point.toLowerCase(), normal.toLowerCase()] : [point, normal];
4988
+ return here === at || here.startsWith(`${at}/`);
4989
+ };
4990
+ let best = table.points.filter(under).sort((a, b) => b.point.length - a.point.length)[0];
4991
+ const drive = normal.toLowerCase().startsWith(prefix.toLowerCase()) ? /^([a-z])(?:\/|$)/i.exec(normal.slice(prefix.length)) : null;
4992
+ if (drive && (!best || prefix.length + 1 > best.point.length)) {
4993
+ best = { point: normal.slice(0, prefix.length + 1), host: `${drive[1].toUpperCase()}:\\` };
4994
+ }
4995
+ if (!best) return void 0;
4996
+ const rest = normal.slice(best.point.length).split("/").filter(Boolean);
4997
+ return rest.length ? path2.win32.join(best.host, ...rest) : best.host;
4998
+ }
4999
+ function staysOnDrive(table, relative20, from) {
5000
+ if (!relative20.split("/").includes("..")) return true;
5001
+ const drive = /^([A-Za-z]):(?:[\\/]|$)/.exec(from);
5002
+ const underMount = table.points.some((p) => {
5003
+ if (/^[A-Za-z]:\\$/.test(p.host)) return false;
5004
+ const rel = path2.win32.relative(p.host, from);
5005
+ return !rel.startsWith("..") && !path2.win32.isAbsolute(rel);
5006
+ });
5007
+ if (!drive || underMount) return false;
5008
+ const top = `/${drive[1].toLowerCase()}`;
5009
+ const climbed = path2.posix.join(`${top}/${from.slice(drive[0].length).replace(/\\/g, "/")}`, relative20);
5010
+ return climbed === top || climbed.startsWith(`${top}/`);
5011
+ }
5012
+ function gitBashHostPath(root, env, readMounts) {
5013
+ let table;
5014
+ return (spelled, from) => {
5015
+ if (!spelled.startsWith("/") && !spelled.startsWith("~") && !/(^|[\\/])\.\.([\\/]|$)/.test(spelled)) return spelled;
5016
+ if (!table) {
5017
+ const read2 = readMounts(root);
5018
+ table = (read2 && parseMounts(...read2)) ?? defaultMounts(root, env);
5019
+ }
5020
+ return mountedHostPath(table, spelled, from, env.HOME);
5021
+ };
5022
+ }
4889
5023
  function defaultExists(candidate) {
4890
5024
  try {
4891
5025
  return fsSync.statSync(candidate).isFile();
@@ -4895,9 +5029,9 @@ function defaultExists(candidate) {
4895
5029
  }
4896
5030
  function gitBashRoots(env) {
4897
5031
  const roots = [
4898
- env.ProgramFiles && path.win32.join(env.ProgramFiles, "Git"),
4899
- env["ProgramFiles(x86)"] && path.win32.join(env["ProgramFiles(x86)"], "Git"),
4900
- env.LOCALAPPDATA && path.win32.join(env.LOCALAPPDATA, "Programs", "Git"),
5032
+ env.ProgramFiles && path2.win32.join(env.ProgramFiles, "Git"),
5033
+ env["ProgramFiles(x86)"] && path2.win32.join(env["ProgramFiles(x86)"], "Git"),
5034
+ env.LOCALAPPDATA && path2.win32.join(env.LOCALAPPDATA, "Programs", "Git"),
4901
5035
  "C:\\Program Files\\Git",
4902
5036
  "C:\\Program Files (x86)\\Git"
4903
5037
  ].filter((r) => !!r);
@@ -4905,32 +5039,34 @@ function gitBashRoots(env) {
4905
5039
  }
4906
5040
  var cached = null;
4907
5041
  function resolveResearchShell(deps = {}) {
4908
- if (cached && !deps.platform && !deps.exists && !deps.env) return cached;
5042
+ const probe = !!(deps.platform || deps.exists || deps.env || deps.readMounts);
5043
+ if (cached && !probe) return cached;
4909
5044
  const platform = deps.platform ?? process.platform;
4910
5045
  if (platform !== "win32") {
4911
- if (!deps.platform && !deps.exists && !deps.env) cached = POSIX_SHELL;
5046
+ if (!probe) cached = POSIX_SHELL;
4912
5047
  return POSIX_SHELL;
4913
5048
  }
4914
5049
  const exists = deps.exists ?? defaultExists;
4915
5050
  const env = deps.env ?? process.env;
4916
5051
  for (const root of gitBashRoots(env)) {
4917
5052
  for (const rel of [["bin", "bash.exe"], ["usr", "bin", "bash.exe"]]) {
4918
- const file = path.win32.join(root, ...rel);
5053
+ const file = path2.win32.join(root, ...rel);
4919
5054
  if (!exists(file)) continue;
4920
- const utilsDir = path.win32.join(root, "usr", "bin");
5055
+ const utilsDir = path2.win32.join(root, "usr", "bin");
4921
5056
  const resolved2 = {
4922
5057
  file,
4923
5058
  // `-c`, not `-lc`: a login shell sources the user's profile, which can
4924
5059
  // change directory out from under a command whose cwd is the workspace.
4925
5060
  args: ["-c"],
4926
5061
  dialect: "posix",
4927
- utilsDir: exists(path.win32.join(utilsDir, "grep.exe")) ? utilsDir : null
5062
+ utilsDir: exists(path2.win32.join(utilsDir, "grep.exe")) ? utilsDir : null,
5063
+ hostPath: gitBashHostPath(root, env, deps.readMounts ?? defaultReadMounts)
4928
5064
  };
4929
- if (!deps.platform && !deps.exists && !deps.env) cached = resolved2;
5065
+ if (!probe) cached = resolved2;
4930
5066
  return resolved2;
4931
5067
  }
4932
5068
  }
4933
- if (!deps.platform && !deps.exists && !deps.env) cached = CMD_SHELL;
5069
+ if (!probe) cached = CMD_SHELL;
4934
5070
  return CMD_SHELL;
4935
5071
  }
4936
5072
  function clearResearchShellCache() {
@@ -4938,8 +5074,8 @@ function clearResearchShellCache() {
4938
5074
  }
4939
5075
  function researchToolsPath(shell, basePath) {
4940
5076
  if (!shell.utilsDir) return basePath ?? "";
4941
- const segments = [shell.utilsDir, ...(basePath ?? "").split(path.win32.delimiter)].filter(Boolean);
4942
- return [...new Set(segments)].join(path.win32.delimiter);
5077
+ const segments = [shell.utilsDir, ...(basePath ?? "").split(path2.win32.delimiter)].filter(Boolean);
5078
+ return [...new Set(segments)].join(path2.win32.delimiter);
4943
5079
  }
4944
5080
  function researchShellWarning(shell) {
4945
5081
  if (shell.dialect !== "cmd") return null;
@@ -4951,16 +5087,16 @@ function researchPolicyOptions(shell) {
4951
5087
 
4952
5088
  // src/services/sandbox/plannerSandbox.ts
4953
5089
  import * as fsSync3 from "fs";
4954
- import * as os from "os";
4955
- import * as path5 from "path";
5090
+ import * as os2 from "os";
5091
+ import * as path6 from "path";
4956
5092
 
4957
5093
  // src/services/sandbox/bubblewrap.ts
4958
5094
  import * as fsSync2 from "fs";
4959
- import * as path3 from "path";
5095
+ import * as path4 from "path";
4960
5096
 
4961
5097
  // src/services/sandbox/SandboxBackend.ts
4962
5098
  import { execFile } from "child_process";
4963
- import * as path2 from "path";
5099
+ import * as path3 from "path";
4964
5100
  var MEMORY_LIMIT_SIGNAL = "SIGUSR2";
4965
5101
  var SandboxUnsupportedError = class extends Error {
4966
5102
  constructor(backend, what) {
@@ -4971,7 +5107,7 @@ var SandboxUnsupportedError = class extends Error {
4971
5107
  function assertProfilePaths(backend, profile) {
4972
5108
  const paths = [...profile.write, ...profile.linkless ?? [], ...profile.gitWorktrees ?? [], ...(profile.gitEntries ?? []).map((entry) => entry.path), ...profile.gitless ?? [], ...profile.read === "host" ? [] : profile.read, ...profile.throwaway ?? [], ...profile.masked ?? []];
4973
5109
  for (const p of paths) {
4974
- if (!path2.posix.isAbsolute(p) || p.includes("\0")) throw new SandboxUnsupportedError(backend, `the path ${JSON.stringify(p)}`);
5110
+ if (!path3.posix.isAbsolute(p) || p.includes("\0")) throw new SandboxUnsupportedError(backend, `the path ${JSON.stringify(p)}`);
4975
5111
  }
4976
5112
  }
4977
5113
  function assertLimits(backend, limits) {
@@ -4983,14 +5119,14 @@ function keptEnv(invocation, profile) {
4983
5119
  return profile.inheritEnv === void 0 ? invocation.env : Object.fromEntries(profile.inheritEnv.flatMap((name) => invocation.env[name] === void 0 ? [] : [[name, invocation.env[name]]]));
4984
5120
  }
4985
5121
  var PROBE_TIMEOUT_MS = 1e4;
4986
- var execProbe = (file, args, env) => new Promise((resolve17) => {
5122
+ var execProbe = (file, args, env) => new Promise((resolve18) => {
4987
5123
  try {
4988
5124
  execFile(file, args, { env, timeout: PROBE_TIMEOUT_MS, encoding: "utf8" }, (err, stdout, stderr) => {
4989
5125
  const code = !err ? 0 : typeof err.code === "number" ? err.code : null;
4990
- resolve17({ code, output: `${stdout ?? ""}${stderr ?? ""}`.trim() || (err?.message ?? "") });
5126
+ resolve18({ code, output: `${stdout ?? ""}${stderr ?? ""}`.trim() || (err?.message ?? "") });
4991
5127
  });
4992
5128
  } catch (err) {
4993
- resolve17({ code: null, output: err instanceof Error ? err.message : String(err) });
5129
+ resolve18({ code: null, output: err instanceof Error ? err.message : String(err) });
4994
5130
  }
4995
5131
  });
4996
5132
  async function probeByRunning(backend, profile, exec5) {
@@ -5007,7 +5143,7 @@ async function probeByRunning(backend, profile, exec5) {
5007
5143
  // src/services/sandbox/bubblewrap.ts
5008
5144
  var SYSTEM_BWRAP = ["/usr/bin/bwrap", "/bin/bwrap", "/usr/local/bin/bwrap", "/run/current-system/sw/bin/bwrap"];
5009
5145
  function findBubblewrap(env, exists) {
5010
- const onPath = (env.PATH ?? "").split(path3.posix.delimiter).filter((dir) => path3.posix.isAbsolute(dir)).map((dir) => path3.posix.join(dir, "bwrap"));
5146
+ const onPath = (env.PATH ?? "").split(path4.posix.delimiter).filter((dir) => path4.posix.isAbsolute(dir)).map((dir) => path4.posix.join(dir, "bwrap"));
5011
5147
  return [.../* @__PURE__ */ new Set([...SYSTEM_BWRAP, ...onPath])].find(exists) ?? null;
5012
5148
  }
5013
5149
  function defaultIsDirectory(p) {
@@ -5102,7 +5238,7 @@ var BubblewrapBackend = class {
5102
5238
  for (const p of shallowFirst(profile.masked ?? [])) args.push(...this.isDirectory(p) ? ["--tmpfs", p] : ["--ro-bind", "/dev/null", p]);
5103
5239
  for (const p of shallowFirst(profile.write)) args.push("--bind", p, p);
5104
5240
  const readOnlyGit = /* @__PURE__ */ new Set([
5105
- ...(profile.gitWorktrees ?? []).map((worktree) => path3.posix.join(worktree, ".git")),
5241
+ ...(profile.gitWorktrees ?? []).map((worktree) => path4.posix.join(worktree, ".git")),
5106
5242
  ...(profile.gitEntries ?? []).map((entry) => entry.path)
5107
5243
  ]);
5108
5244
  for (const gitPath of readOnlyGit) args.push("--ro-bind", gitPath, gitPath);
@@ -5115,7 +5251,7 @@ var BubblewrapBackend = class {
5115
5251
  };
5116
5252
 
5117
5253
  // src/services/sandbox/seatbelt.ts
5118
- import * as path4 from "path";
5254
+ import * as path5 from "path";
5119
5255
  var SANDBOX_EXEC = "/usr/bin/sandbox-exec";
5120
5256
  var BASE_PROFILE = `(version 1)
5121
5257
  (deny default)
@@ -5274,7 +5410,7 @@ var SeatbeltBackend = class {
5274
5410
  if (profile.write.length) rules.push(`(allow file-read* file-test-existence file-map-executable file-write* ${filters("WRITABLE", "subpath", profile.write)})`);
5275
5411
  if (profile.linkless?.length) rules.push(`(deny file-write-create (require-all (vnode-type SYMLINK) (require-any ${filters("LINKLESS", "subpath", profile.linkless)})))`);
5276
5412
  if (profile.gitWorktrees?.length) {
5277
- const gitDirs = profile.gitWorktrees.map((worktree) => path4.posix.join(worktree, ".git"));
5413
+ const gitDirs = profile.gitWorktrees.map((worktree) => path5.posix.join(worktree, ".git"));
5278
5414
  rules.push(`(deny file-write* ${filters("GIT", "literal", gitDirs)})`);
5279
5415
  rules.push(`(deny file-write* ${filters("WORKTREE", "literal", profile.gitWorktrees)})`);
5280
5416
  }
@@ -5303,7 +5439,7 @@ var SeatbeltBackend = class {
5303
5439
  function directoriesAbove(paths) {
5304
5440
  const above = /* @__PURE__ */ new Set();
5305
5441
  for (const p of paths) {
5306
- for (let dir = path4.posix.dirname(p); dir !== "/" && !above.has(dir); dir = path4.posix.dirname(dir)) above.add(dir);
5442
+ for (let dir = path5.posix.dirname(p); dir !== "/" && !above.has(dir); dir = path5.posix.dirname(dir)) above.add(dir);
5307
5443
  }
5308
5444
  return [...above];
5309
5445
  }
@@ -5448,12 +5584,12 @@ function killTree(proc, deps = {}) {
5448
5584
  if (typeof proc.pid !== "number") return;
5449
5585
  const pid = proc.pid;
5450
5586
  const run = deps.execFileImpl ?? defaultExecFile;
5451
- run("taskkill", ["/pid", String(pid), "/T"], () => {
5587
+ const force = () => run("taskkill", ["/pid", String(pid), "/T", "/F"], () => {
5452
5588
  });
5453
- const hardKill = setTimeoutImpl(() => {
5454
- run("taskkill", ["/pid", String(pid), "/T", "/F"], () => {
5455
- });
5456
- }, HARD_KILL_DELAY_MS);
5589
+ run("taskkill", ["/pid", String(pid), "/T"], (err) => {
5590
+ if (err && !hasExited(proc)) force();
5591
+ });
5592
+ const hardKill = setTimeoutImpl(force, HARD_KILL_DELAY_MS);
5457
5593
  hardKill.unref?.();
5458
5594
  proc.once("exit", () => clearTimeoutImpl(hardKill));
5459
5595
  return;
@@ -5532,22 +5668,22 @@ function scratchEnv(scratch, platform) {
5532
5668
  GIT_OPTIONAL_LOCKS: "0",
5533
5669
  // npm writes a debug log under its cache for every command, `npm ls` too,
5534
5670
  // and records its update check there.
5535
- npm_config_cache: path5.join(scratch, "npm"),
5671
+ npm_config_cache: path6.join(scratch, "npm"),
5536
5672
  npm_config_update_notifier: "false",
5537
5673
  // `go list` opens the build cache.
5538
- GOCACHE: path5.join(scratch, "go-build"),
5674
+ GOCACHE: path6.join(scratch, "go-build"),
5539
5675
  // Where Linux tools that follow the XDG layout (pip among them) keep caches.
5540
- XDG_CACHE_HOME: path5.join(scratch, "cache"),
5676
+ XDG_CACHE_HOME: path6.join(scratch, "cache"),
5541
5677
  // Python otherwise writes bytecode beside the sources, in the workspace.
5542
- PYTHONPYCACHEPREFIX: path5.join(scratch, "pycache"),
5678
+ PYTHONPYCACHEPREFIX: path6.join(scratch, "pycache"),
5543
5679
  // The `/usr/bin` shims of Apple's command-line tools (`git` among them)
5544
5680
  // cache lookups in the user's temporary directory, ignoring TMPDIR, and
5545
5681
  // print an error on every call when they cannot.
5546
- ...platform === "darwin" ? { xcrun_db: path5.join(scratch, "xcrun_db") } : {}
5682
+ ...platform === "darwin" ? { xcrun_db: path6.join(scratch, "xcrun_db") } : {}
5547
5683
  };
5548
5684
  }
5549
5685
  function localServices(env, stat, uid) {
5550
- const runtimeDir = env.XDG_RUNTIME_DIR && path5.posix.isAbsolute(env.XDG_RUNTIME_DIR) ? env.XDG_RUNTIME_DIR : void 0;
5686
+ const runtimeDir = env.XDG_RUNTIME_DIR && path6.posix.isAbsolute(env.XDG_RUNTIME_DIR) ? env.XDG_RUNTIME_DIR : void 0;
5551
5687
  const candidates = [runtimeDir, uid === void 0 ? void 0 : `/run/user/${uid}`, "/run/dbus", "/tmp/.X11-unix", "/run/docker.sock"];
5552
5688
  const found = candidates.flatMap((p) => p ? [stat(p)?.canonical] : []).filter((p) => !!p && p !== "/");
5553
5689
  return [...new Set(found)];
@@ -5652,8 +5788,8 @@ function sealedShellProfile(host, opts) {
5652
5788
  };
5653
5789
  }
5654
5790
  function strictlyWithin(child, parent) {
5655
- const rel = path5.relative(parent, child);
5656
- return rel !== "" && !rel.startsWith("..") && !path5.isAbsolute(rel);
5791
+ const rel = path6.relative(parent, child);
5792
+ return rel !== "" && !rel.startsWith("..") && !path6.isAbsolute(rel);
5657
5793
  }
5658
5794
  function canonicalGitEntries(entries) {
5659
5795
  return entries.flatMap((entry) => {
@@ -5706,9 +5842,9 @@ async function detect(deps) {
5706
5842
  }
5707
5843
  return unavailable(`${backend.name} could not start (${detail})`);
5708
5844
  }
5709
- async function detectSealed(backend, platform, stat, probeWorkspace = os.tmpdir()) {
5845
+ async function detectSealed(backend, platform, stat, probeWorkspace = os2.tmpdir()) {
5710
5846
  const existing = (paths) => (paths ?? []).filter((p) => stat(p) !== null);
5711
- const named3 = (paths) => platform === "darwin" ? paths.map((p) => path5.posix.join(stat(path5.posix.dirname(p))?.canonical ?? path5.posix.dirname(p), path5.posix.basename(p))) : paths;
5847
+ const named3 = (paths) => platform === "darwin" ? paths.map((p) => path6.posix.join(stat(path6.posix.dirname(p))?.canonical ?? path6.posix.dirname(p), path6.posix.basename(p))) : paths;
5712
5848
  const developerDir = platform === "darwin" ? stat("/private/var/select/developer_dir")?.canonical : void 0;
5713
5849
  const reads = [.../* @__PURE__ */ new Set([...named3(existing(SEALED_READS[platform])), ...developerDir ? [developerDir] : []])];
5714
5850
  const masked = named3(existing(SEALED_MASKS[platform]));
@@ -5756,7 +5892,7 @@ function sweepOrphanScratch(root) {
5756
5892
  for (const name of names2) {
5757
5893
  const pid = Number(/^ordewell-planner-(\d+)-/.exec(name)?.[1]);
5758
5894
  if (!pid || pid === process.pid || processAlive(pid)) continue;
5759
- const dir = path5.join(root, name);
5895
+ const dir = path6.join(root, name);
5760
5896
  try {
5761
5897
  const stat = fsSync3.lstatSync(dir);
5762
5898
  if (stat.isDirectory() && stat.uid === process.getuid?.()) fsSync3.rmSync(dir, { recursive: true, force: true });
@@ -5770,15 +5906,15 @@ function createScratch() {
5770
5906
  process.once("exit", () => {
5771
5907
  for (const dir2 of [...liveScratch]) removeScratch(dir2);
5772
5908
  });
5773
- sweepOrphanScratch(os.tmpdir());
5909
+ sweepOrphanScratch(os2.tmpdir());
5774
5910
  }
5775
- const dir = fsSync3.realpathSync(fsSync3.mkdtempSync(path5.join(os.tmpdir(), `ordewell-planner-${process.pid}-`)));
5911
+ const dir = fsSync3.realpathSync(fsSync3.mkdtempSync(path6.join(os2.tmpdir(), `ordewell-planner-${process.pid}-`)));
5776
5912
  liveScratch.add(dir);
5777
5913
  return dir;
5778
5914
  }
5779
5915
  var PlannerShellSandbox = class _PlannerShellSandbox {
5780
- constructor(resolve17 = () => resolvePlannerSandbox()) {
5781
- this.resolve = resolve17;
5916
+ constructor(resolve18 = () => resolvePlannerSandbox()) {
5917
+ this.resolve = resolve18;
5782
5918
  }
5783
5919
  resolve;
5784
5920
  scratch = /* @__PURE__ */ new Map();
@@ -5927,35 +6063,6 @@ function sealedMemoryLimitNote(outcome, memoryBytes, forTask) {
5927
6063
  }
5928
6064
  var SEALED_FAILURE_NOTE = "A sealed run cannot reach the network, the user's credentials or their files outside the workspace, and cannot change the workspace, so running it sealed again fails the same way. To read something it could not, run each command on its own, without a loop or inline code, so Ordewell's command rules can judge it; a change belongs in the plan as a task.";
5929
6065
 
5930
- // src/services/pathScope.ts
5931
- import * as os2 from "os";
5932
- import * as path6 from "path";
5933
- function expandHome(target) {
5934
- if (!target.startsWith("~")) return target;
5935
- const home = os2.homedir();
5936
- if (target === "~" || target.startsWith("~/")) return path6.join(home, target.slice(1));
5937
- return path6.join(path6.dirname(home), target.slice(1));
5938
- }
5939
- function resolveWithin(root, target, from = root) {
5940
- const abs = path6.resolve(from, expandHome(target));
5941
- const rel = path6.relative(root, abs);
5942
- return { abs, inside: rel === "" || !rel.startsWith("..") && !path6.isAbsolute(rel) };
5943
- }
5944
- function resolveRef(root, ref2) {
5945
- const from = ref2.cwd.reduce((dir, target) => resolveWithin(root, target, dir).abs, root);
5946
- return resolveWithin(root, ref2.path, from);
5947
- }
5948
- function grantScopeFor(abs, kind) {
5949
- if (kind === "directory") return path6.join(abs, "*");
5950
- const parent = path6.dirname(abs);
5951
- if (parent === path6.parse(abs).root) return path6.join(abs, "*");
5952
- return path6.join(parent, "*");
5953
- }
5954
- var INERT_DEVICES = ["/dev/null", "/dev/stdin", "/dev/stdout", "/dev/stderr"];
5955
- function isInertDevice(abs) {
5956
- return INERT_DEVICES.includes(abs);
5957
- }
5958
-
5959
6066
  // src/services/symbolPatterns.ts
5960
6067
  var SYMBOL_LANGUAGES = [
5961
6068
  {
@@ -6295,6 +6402,9 @@ var CD_HINT = ' A "cd" is followed only on a line joined by "&&" alone, so after
6295
6402
  function refusal(output) {
6296
6403
  return { success: false, output, truncated: false };
6297
6404
  }
6405
+ function unfollowableReason(spelled) {
6406
+ return `Git Bash reads "${spelled}" by rules this check cannot follow, so it cannot tell which folder the command would reach: a ".." past one of its mounts, or its own /proc or /dev. Name the path from its drive (/c/Users/...) or as a Windows path (C:\\Users\\...), with no "..".`;
6407
+ }
6298
6408
  var TASK_UNSEALED = "A read-only task asks nobody, so this command could only run sealed, and this machine has no sandbox to seal it in.";
6299
6409
  var OWN_UNSEALED = "this machine has no sandbox to seal it in, and Ordewell runs nothing in a read-only task's worktree outside one.";
6300
6410
  var TASK_CONTINUE = "Continue without it, and say in your report if what it would have shown matters.";
@@ -6467,12 +6577,13 @@ ${refs.output.trim()}`);
6467
6577
  outsidePaths(command, root) {
6468
6578
  const found = /* @__PURE__ */ new Map();
6469
6579
  for (const ref2 of pathRefs(command, this.policyOptions())) {
6470
- const { abs, inside: inside2 } = resolveRef(root, ref2);
6471
- if (inside2 || isInertDevice(abs)) continue;
6580
+ const { abs, inside: inside2, device, unfollowable } = resolveRef(root, ref2, this.researchShell.hostPath);
6581
+ if (unfollowable) return { outside: [], unfollowable: ref2.path };
6582
+ if (inside2 || device) continue;
6472
6583
  const scope = grantScopeFor(abs, "file");
6473
6584
  if (!found.has(scope)) found.set(scope, abs);
6474
6585
  }
6475
- return [...found].map(([scope, abs]) => ({ abs, scope }));
6586
+ return { outside: [...found].map(([scope, abs]) => ({ abs, scope })) };
6476
6587
  }
6477
6588
  policyOptions() {
6478
6589
  return researchPolicyOptions(this.researchShell);
@@ -6563,7 +6674,7 @@ ${TASK_CONTINUE}`);
6563
6674
  ...approval.commandPolicy?.(),
6564
6675
  ...allow ? { allow } : {}
6565
6676
  });
6566
- const outside = this.outsidePaths(command, root);
6677
+ const { outside, unfollowable } = this.outsidePaths(command, root);
6567
6678
  const asks = tier === "ask";
6568
6679
  const scopes = [...asks ? commandScopes ?? [scope] : [], ...outside.map((o) => o.scope)];
6569
6680
  const touched = outside.map((o) => o.abs).join(", ");
@@ -6582,6 +6693,8 @@ ${TASK_CONTINUE}`);
6582
6693
  }
6583
6694
  if (site.task?.sealed) return this.runSealed(site, command, request, "after", signal);
6584
6695
  if (tier === "refuse") return this.sealedInstead(site, command, request, refusal(`Command refused: ${reason}${site.task ? `
6696
+ ${TASK_UNSEALED} ${TASK_CONTINUE}` : ""}`), signal);
6697
+ if (unfollowable !== void 0) return this.sealedInstead(site, command, request, refusal(`Command refused: ${unfollowableReason(unfollowable)}${site.task ? `
6585
6698
  ${TASK_UNSEALED} ${TASK_CONTINUE}` : ""}`), signal);
6586
6699
  const outbound = [...outboundTexts ?? [], ...(webUrls ?? []).map((url) => url.href)];
6587
6700
  if (outbound.length && carriesSecret(outbound, [...this.outboundSecrets(), ...sensitiveEnvValues(process.env)])) {
@@ -6931,33 +7044,33 @@ function grepOptions(args) {
6931
7044
  };
6932
7045
  }
6933
7046
  var STOPPED_TOOL_RESULT = "Stopped by the user \u2014 this call was not executed, and no further tool calls will run this turn.";
6934
- async function executeTool(name, args, fs28, fetcher, signal) {
6935
- const outcome = await runTool(name, args, fs28, fetcher, signal);
7047
+ async function executeTool(name, args, fs29, fetcher, signal) {
7048
+ const outcome = await runTool(name, args, fs29, fetcher, signal);
6936
7049
  return { ...outcome, output: redactSecrets(outcome.output) };
6937
7050
  }
6938
- async function runTool(name, args, fs28, fetcher, signal) {
7051
+ async function runTool(name, args, fs29, fetcher, signal) {
6939
7052
  if (signal?.aborted) return { success: false, output: STOPPED_TOOL_RESULT, truncated: false };
6940
7053
  switch (name) {
6941
7054
  case "read_file": {
6942
7055
  const offset = num(args.offset);
6943
7056
  const limit = num(args.limit);
6944
7057
  const maxBytes = num(args.maxBytes);
6945
- return fs28.readFile(String(args.path ?? ""), { offset, limit, maxBytes });
7058
+ return fs29.readFile(String(args.path ?? ""), { offset, limit, maxBytes });
6946
7059
  }
6947
7060
  case "read_files": {
6948
7061
  const paths = Array.isArray(args.paths) ? args.paths.map(String) : [];
6949
- return fs28.readFiles(paths);
7062
+ return fs29.readFiles(paths);
6950
7063
  }
6951
7064
  case "glob":
6952
- return fs28.glob(String(args.pattern ?? ""), { path: str(args.path), headLimit: num(args.head_limit ?? args.headLimit) });
7065
+ return fs29.glob(String(args.pattern ?? ""), { path: str(args.path), headLimit: num(args.head_limit ?? args.headLimit) });
6953
7066
  case "grep":
6954
- return fs28.grep(String(args.pattern ?? ""), grepOptions(args));
7067
+ return fs29.grep(String(args.pattern ?? ""), grepOptions(args));
6955
7068
  case "find_symbol":
6956
- return fs28.findSymbol(String(args.symbol ?? ""), { language: str(args.language), path: str(args.path) });
7069
+ return fs29.findSymbol(String(args.symbol ?? ""), { language: str(args.language), path: str(args.path) });
6957
7070
  case "list_dir":
6958
- return fs28.listDir(String(args.path ?? ""), num(args.depth));
7071
+ return fs29.listDir(String(args.path ?? ""), num(args.depth));
6959
7072
  case "bash":
6960
- return args.sealed === true ? fs28.bash(String(args.command ?? ""), signal, { sealed: true }) : fs28.bash(String(args.command ?? ""), signal);
7073
+ return args.sealed === true ? fs29.bash(String(args.command ?? ""), signal, { sealed: true }) : fs29.bash(String(args.command ?? ""), signal);
6961
7074
  case "fetch": {
6962
7075
  if (!fetcher) return { success: false, output: "Web fetching is not available in this environment.", truncated: false };
6963
7076
  return fetcher.fetch(String(args.url ?? ""));
@@ -7729,7 +7842,7 @@ function decodedBody(res) {
7729
7842
  return decoder;
7730
7843
  }
7731
7844
  function pinnedTransport(lookup2) {
7732
- return (url, init) => new Promise((resolve17, reject) => {
7845
+ return (url, init) => new Promise((resolve18, reject) => {
7733
7846
  const target = new URL(url);
7734
7847
  const client = target.protocol === "https:" ? https : http;
7735
7848
  const req = client.request(
@@ -7750,7 +7863,7 @@ function pinnedTransport(lookup2) {
7750
7863
  (res) => {
7751
7864
  res.on("error", () => void 0);
7752
7865
  const body = decodedBody(res);
7753
- resolve17({
7866
+ resolve18({
7754
7867
  ok: res.statusCode !== void 0 && res.statusCode >= 200 && res.statusCode < 300,
7755
7868
  status: res.statusCode ?? 0,
7756
7869
  headers: headerGetter(res),
@@ -8093,7 +8206,7 @@ var PendingApprovals = class {
8093
8206
  return Promise.resolve(refused4);
8094
8207
  }
8095
8208
  const pending = { id: id2, request, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
8096
- return new Promise((resolve17) => {
8209
+ return new Promise((resolve18) => {
8097
8210
  const settle = (decision) => {
8098
8211
  const entry = this.entries.get(id2);
8099
8212
  if (!entry) return;
@@ -8101,7 +8214,7 @@ var PendingApprovals = class {
8101
8214
  this.entries.delete(id2);
8102
8215
  options.onDecision?.(decision);
8103
8216
  this.opts.onSettled?.(id2, isGranted(decision), { request, decision });
8104
- resolve17(decision);
8217
+ resolve18(decision);
8105
8218
  };
8106
8219
  let timer = null;
8107
8220
  if (!options.noTimeout) {
@@ -8245,16 +8358,35 @@ function grepRegexFromProbe(exitCode) {
8245
8358
  return exitCode === 0 || exitCode === 1 ? "pcre" : "ere";
8246
8359
  }
8247
8360
  function toPosixClasses(pattern) {
8361
+ const converted = convertForEre(pattern, true);
8362
+ return converted ?? convertForEre(pattern, false);
8363
+ }
8364
+ var BACKREFERENCE = /\0([1-9])\0/g;
8365
+ function convertForEre(pattern, plainGroups) {
8248
8366
  const CLASS_ESCAPES = { s: "[:space:]", w: "[:alnum:]_", d: "[:digit:]", t: " " };
8367
+ const groupOf = [];
8368
+ let groups = 0;
8369
+ let captures = 0;
8249
8370
  let out = "";
8250
8371
  let i = 0;
8251
8372
  while (i < pattern.length) {
8252
8373
  const c = pattern[i];
8253
8374
  if (c === "\\") {
8254
- out += pattern.slice(i, i + 2);
8375
+ const next = pattern[i + 1] ?? "";
8376
+ out += /[1-9]/.test(next) ? `\0${next}\0` : pattern.slice(i, i + 2);
8255
8377
  i += 2;
8256
8378
  continue;
8257
8379
  }
8380
+ if (c === "(") {
8381
+ groups++;
8382
+ if (plainGroups && pattern.startsWith("(?:", i)) {
8383
+ out += "(";
8384
+ i += 3;
8385
+ continue;
8386
+ }
8387
+ const named3 = /^\(\?(?:P?<(?![=!])|')/.test(pattern.slice(i, i + 4));
8388
+ if (pattern[i + 1] !== "?" || named3) groupOf[++captures] = groups;
8389
+ }
8258
8390
  if (c !== "[") {
8259
8391
  out += c;
8260
8392
  i++;
@@ -8271,7 +8403,12 @@ function toPosixClasses(pattern) {
8271
8403
  let closeBracket = false;
8272
8404
  let openBracket = false;
8273
8405
  let dash = false;
8406
+ let caret = false;
8274
8407
  let closed = false;
8408
+ if (pattern[i] === "]") {
8409
+ closeBracket = true;
8410
+ i++;
8411
+ }
8275
8412
  while (i < pattern.length) {
8276
8413
  const ch = pattern[i];
8277
8414
  if (ch === "]") {
@@ -8294,6 +8431,7 @@ function toPosixClasses(pattern) {
8294
8431
  else if (e === "]") closeBracket = true;
8295
8432
  else if (e === "[") openBracket = true;
8296
8433
  else if (e === "-") dash = true;
8434
+ else if (e === "^") caret = true;
8297
8435
  else body += e;
8298
8436
  continue;
8299
8437
  }
@@ -8304,9 +8442,17 @@ function toPosixClasses(pattern) {
8304
8442
  out += pattern.slice(start);
8305
8443
  break;
8306
8444
  }
8307
- out += `[${negate ? "^" : ""}${closeBracket ? "]" : ""}${body}${openBracket ? "[" : ""}${dash ? "-" : ""}]`;
8445
+ const members = `${closeBracket ? "]" : ""}${body}`;
8446
+ if (caret && !negate && members === "") out += openBracket || dash ? `[${dash ? "-" : ""}${openBracket ? "[" : ""}^]` : "\\^";
8447
+ else out += `[${negate ? "^" : ""}${members}${caret ? "^" : ""}${openBracket ? "[" : ""}${dash ? "-" : ""}]`;
8308
8448
  }
8309
- return out;
8449
+ let representable = true;
8450
+ const renumbered2 = out.replace(BACKREFERENCE, (_, n) => {
8451
+ const group = plainGroups ? groupOf[Number(n)] ?? Number(n) : Number(n);
8452
+ if (group > 9) representable = false;
8453
+ return `\\${group}`;
8454
+ });
8455
+ return representable ? renumbered2 : null;
8310
8456
  }
8311
8457
  function buildFallbackGrepArgs(pattern, opts, root, regex = "pcre") {
8312
8458
  const args = ["-r", "-n"];
@@ -8342,7 +8488,7 @@ function filterFallbackByAnchoredInclude(stdout, include, anchor, outputMode) {
8342
8488
  if (!line) return false;
8343
8489
  const reportedPath = extractFallbackGrepPath(line, outputMode);
8344
8490
  const relPath = path11.isAbsolute(reportedPath) ? path11.relative(anchor, reportedPath) : reportedPath;
8345
- return matchesAnchoredGlob(relPath, include);
8491
+ return matchesAnchoredGlob(relPath.split(path11.sep).join("/"), include);
8346
8492
  }).join("\n");
8347
8493
  }
8348
8494
  function applyHeadLimit(stdout, headLimit) {
@@ -8351,9 +8497,14 @@ function applyHeadLimit(stdout, headLimit) {
8351
8497
  }
8352
8498
  function formatSearchOutput(capped, root, opts) {
8353
8499
  if (capped.rows.length === 0) return opts.emptyMessage;
8354
- const sep14 = opts.sep ?? path11.sep;
8355
- const prefix = root === sep14 || root.endsWith(sep14) ? root : `${root}${sep14}`;
8356
- const body = prefix === sep14 ? capped.rows.join("\n") : capped.rows.map((row) => row.startsWith(prefix) ? row.slice(prefix.length) : row).join("\n");
8500
+ const sep13 = opts.sep ?? path11.sep;
8501
+ const prefix = root === sep13 || root.endsWith(sep13) ? root : `${root}${sep13}`;
8502
+ const prefixes = sep13 === "\\" ? [prefix, `${prefix.slice(0, -1)}/`] : [prefix];
8503
+ const strip = (row) => {
8504
+ const found = prefixes.find((p) => row.startsWith(p));
8505
+ return found ? row.slice(found.length) : row;
8506
+ };
8507
+ const body = prefix === sep13 ? capped.rows.join("\n") : capped.rows.map(strip).join("\n");
8357
8508
  if (!capped.truncated) return body;
8358
8509
  const hint = opts.hint ? ` ${opts.hint}` : "";
8359
8510
  return `${body}
@@ -8471,9 +8622,9 @@ function claudeManagedSettingsDir(platform = process.platform) {
8471
8622
  }
8472
8623
  function readClaudeSettingsModels(files, platform = process.platform) {
8473
8624
  const managed = claudeManagedSettingsDir(platform);
8474
- const join51 = platform === "win32" ? path12.win32.join : path12.posix.join;
8475
- const dropIns = files.list(join51(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => join51(managed, "managed-settings.d", name));
8476
- const ranked = [...dropIns.reverse(), join51(managed, "managed-settings.json"), join51(claudeConfigDir(files.env), "settings.json")];
8625
+ const join50 = platform === "win32" ? path12.win32.join : path12.posix.join;
8626
+ const dropIns = files.list(join50(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => join50(managed, "managed-settings.d", name));
8627
+ const ranked = [...dropIns.reverse(), join50(managed, "managed-settings.json"), join50(claudeConfigDir(files.env), "settings.json")];
8477
8628
  for (const file of ranked) {
8478
8629
  const content = files.read(file);
8479
8630
  const lineup = content === null ? null : parseClaudeSettingsModels(content);
@@ -9972,7 +10123,7 @@ var OrdewellMcpServer = class {
9972
10123
  this.boundHost = void 0;
9973
10124
  if (!http2) return;
9974
10125
  http2.closeAllConnections();
9975
- await new Promise((resolve17) => http2.close(() => resolve17()));
10126
+ await new Promise((resolve18) => http2.close(() => resolve18()));
9976
10127
  }
9977
10128
  async issue(grant) {
9978
10129
  const url = await this.start();
@@ -9981,7 +10132,7 @@ var OrdewellMcpServer = class {
9981
10132
  return { url, token };
9982
10133
  }
9983
10134
  start() {
9984
- this.listening ??= new Promise((resolve17, reject) => {
10135
+ this.listening ??= new Promise((resolve18, reject) => {
9985
10136
  const http2 = createServer((req, res) => {
9986
10137
  this.handle(req, res).catch(() => {
9987
10138
  if (!res.headersSent) reply(res, 500, "Internal error");
@@ -10000,7 +10151,7 @@ var OrdewellMcpServer = class {
10000
10151
  }
10001
10152
  this.boundHost = `127.0.0.1:${address.port}`;
10002
10153
  this.boundUrl = `http://${this.boundHost}${ORDEWELL_MCP_PATH}`;
10003
- resolve17(this.boundUrl);
10154
+ resolve18(this.boundUrl);
10004
10155
  });
10005
10156
  http2.unref();
10006
10157
  this.http = http2;
@@ -10823,28 +10974,28 @@ function posixBinDirs() {
10823
10974
  ];
10824
10975
  }
10825
10976
  function windowsBinDirs(env, home) {
10826
- const join51 = (...parts) => path14.win32.join(...parts);
10827
- const under = (base, ...parts) => base ? [join51(base, ...parts)] : [];
10977
+ const join50 = (...parts) => path14.win32.join(...parts);
10978
+ const under = (base, ...parts) => base ? [join50(base, ...parts)] : [];
10828
10979
  const appData = env.APPDATA;
10829
10980
  const localAppData = env.LOCALAPPDATA;
10830
10981
  const programData = env.ProgramData;
10831
10982
  return [
10832
10983
  // Native per-user installers, PowerShell-driven and otherwise.
10833
- join51(home, ".local", "bin"),
10834
- join51(home, ".opencode", "bin"),
10835
- join51(home, ".claude", "bin"),
10836
- join51(home, ".codex", "bin"),
10984
+ join50(home, ".local", "bin"),
10985
+ join50(home, ".opencode", "bin"),
10986
+ join50(home, ".claude", "bin"),
10987
+ join50(home, ".codex", "bin"),
10837
10988
  ...under(localAppData, "Programs", "claude"),
10838
10989
  // Node package managers. npm's global prefix is `%APPDATA%\npm`; the
10839
10990
  // literal spelling is kept as a fallback for a host that does not export
10840
10991
  // APPDATA (a service account, a stripped CI container).
10841
10992
  ...under(appData, "npm"),
10842
- join51(home, "AppData", "Roaming", "npm"),
10993
+ join50(home, "AppData", "Roaming", "npm"),
10843
10994
  ...under(localAppData, "pnpm"),
10844
10995
  ...under(localAppData, "Yarn", "bin"),
10845
- join51(home, ".bun", "bin"),
10996
+ join50(home, ".bun", "bin"),
10846
10997
  // Windows package managers.
10847
- join51(home, "scoop", "shims"),
10998
+ join50(home, "scoop", "shims"),
10848
10999
  ...under(env.SCOOP, "shims"),
10849
11000
  ...under(env.SCOOP_GLOBAL ?? programData, "scoop", "shims"),
10850
11001
  ...under(programData, "chocolatey", "bin"),
@@ -10854,7 +11005,7 @@ function windowsBinDirs(env, home) {
10854
11005
  ...under(localAppData, "Microsoft", "WindowsApps"),
10855
11006
  // Version managers. Volta's Windows home is not the POSIX `~/.volta`.
10856
11007
  ...under(localAppData, "Volta", "bin"),
10857
- join51(home, ".volta", "bin")
11008
+ join50(home, ".volta", "bin")
10858
11009
  ];
10859
11010
  }
10860
11011
  function wellKnownBinDirs(deps = {}) {
@@ -10965,7 +11116,7 @@ var BatchQuoteError = class extends Error {
10965
11116
 
10966
11117
  cmd.exe has no way to carry a quote inside a quoted argument, so the text after it would run as commands of their own.
10967
11118
 
10968
- Install the native executable from the coding agent's own Windows installer or release binary. Ordewell will launch it directly, with no interpreter in the way. A PowerShell shim (${command}.ps1) beside the batch one is also enough.`
11119
+ Install the native executable from the coding agent's own Windows installer or release binary. Ordewell will launch it directly, with no interpreter in the way.`
10969
11120
  );
10970
11121
  this.command = command;
10971
11122
  this.name = "BatchQuoteError";
@@ -10986,12 +11137,17 @@ Searched: ${searchedPath || "(empty PATH)"}`);
10986
11137
  };
10987
11138
  function isResolvableOnPosixPath(command, PATH, exists) {
10988
11139
  if (command.includes("/")) return exists(command);
10989
- return PATH.split(path15.delimiter).map((d) => d.trim()).filter(Boolean).some((dir) => exists(path15.join(dir, command)));
11140
+ return PATH.split(path15.posix.delimiter).map((d) => d.trim()).filter(Boolean).some((dir) => exists(path15.posix.join(dir, command)));
10990
11141
  }
10991
11142
  function isExecutableResolved(command, plan, PATH, deps = {}) {
10992
- if ((deps.platform ?? process.platform) === "win32") return plan.file !== command;
11143
+ if ((deps.platform ?? process.platform) === "win32") return plan.file !== command || namesDirectFile(command, deps);
10993
11144
  return isResolvableOnPosixPath(command, PATH, deps.exists ?? defaultExists3);
10994
11145
  }
11146
+ function namesDirectFile(command, deps) {
11147
+ if (path15.win32.basename(command) === command) return false;
11148
+ const pathExt = (deps.pathExt ?? (() => process.env.PATHEXT ?? ""))();
11149
+ return candidateExtensions(command, pathExt).direct.includes("") && (deps.exists ?? defaultExists3)(command);
11150
+ }
10995
11151
  function defaultExists3(candidate) {
10996
11152
  try {
10997
11153
  return fsSync4.statSync(candidate).isFile();
@@ -10999,6 +11155,65 @@ function defaultExists3(candidate) {
10999
11155
  return false;
11000
11156
  }
11001
11157
  }
11158
+ var MAX_SHIM_BYTES = 4096;
11159
+ function defaultReadShim(file) {
11160
+ try {
11161
+ return fsSync4.statSync(file).size > MAX_SHIM_BYTES ? void 0 : fsSync4.readFileSync(file, "utf8");
11162
+ } catch {
11163
+ return void 0;
11164
+ }
11165
+ }
11166
+ var NPM_SHIM_HEAD = "@ECHO off\nGOTO start\n:find_dp0\nSET dp0=%~dp0\nEXIT /b\n:start\nSETLOCAL\nCALL :find_dp0\n";
11167
+ var NPM_SHIMS = {
11168
+ node: `${NPM_SHIM_HEAD}
11169
+ IF EXIST "%dp0%\\node.exe" (
11170
+ SET "_prog=%dp0%\\node.exe"
11171
+ ) ELSE (
11172
+ SET "_prog=node"
11173
+ SET PATHEXT=%PATHEXT:;.JS;=;%
11174
+ )
11175
+
11176
+ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\TARGET" %*
11177
+ `,
11178
+ program: `${NPM_SHIM_HEAD}"%dp0%\\TARGET" %*
11179
+ `
11180
+ };
11181
+ function shimPattern(template) {
11182
+ const [before, after] = template.split("TARGET").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
11183
+ return new RegExp(`^${before}([^"%\\n]+)${after}$`);
11184
+ }
11185
+ var NPM_SHIM_PATTERNS = { node: shimPattern(NPM_SHIMS.node), program: shimPattern(NPM_SHIMS.program) };
11186
+ function npmShimTarget(shim, pathDirs, deps) {
11187
+ const raw = (deps.readShim ?? defaultReadShim)(shim);
11188
+ if (raw === void 0) return void 0;
11189
+ const text4 = raw.replace(/\r\n/g, "\n").replace(/\n?$/, "\n");
11190
+ const exists = deps.exists ?? defaultExists3;
11191
+ const folder = path15.win32.dirname(shim);
11192
+ const program = NPM_SHIM_PATTERNS.program.exec(text4)?.[1];
11193
+ if (program !== void 0) {
11194
+ const file2 = path15.win32.join(folder, program);
11195
+ return DIRECT_EXTENSIONS.includes(path15.win32.extname(file2).toLowerCase()) && exists(file2) ? { file: file2, leading: [] } : void 0;
11196
+ }
11197
+ const script = NPM_SHIM_PATTERNS.node.exec(text4)?.[1];
11198
+ if (script === void 0) return void 0;
11199
+ const file = path15.win32.join(folder, script);
11200
+ if (!exists(file)) return void 0;
11201
+ const beside = path15.win32.join(folder, "node.exe");
11202
+ const node = exists(beside) ? beside : shimNode(pathDirs, deps);
11203
+ return node ? { file: node, leading: [file] } : void 0;
11204
+ }
11205
+ function shimNode(pathDirs, deps) {
11206
+ const exists = deps.exists ?? defaultExists3;
11207
+ const declared = (deps.pathExt ?? (() => process.env.PATHEXT ?? ""))().split(path15.win32.delimiter).map((e) => e.trim().toLowerCase()).filter(Boolean);
11208
+ const extensions = (declared.length > 0 ? declared : [".com", ".exe", ".bat", ".cmd"]).filter((e) => e !== ".js");
11209
+ for (const dir of pathDirs) {
11210
+ for (const ext of extensions) {
11211
+ const candidate = path15.win32.join(dir, `node${ext}`);
11212
+ if (exists(candidate)) return DIRECT_EXTENSIONS.includes(ext) ? candidate : void 0;
11213
+ }
11214
+ }
11215
+ return void 0;
11216
+ }
11002
11217
  function quoteForCmd(arg) {
11003
11218
  if (arg === "") return '""';
11004
11219
  if (!/[\s"^&|<>()]/.test(arg)) return arg;
@@ -11049,7 +11264,8 @@ async function findWindowsExecutables(command, deps) {
11049
11264
  const exists = deps.exists ?? defaultExists3;
11050
11265
  const pathExt = (deps.pathExt ?? (() => process.env.PATHEXT ?? ""))();
11051
11266
  const byRoute = candidateExtensions(command, pathExt);
11052
- const dirs = path15.win32.basename(command) !== command ? [path15.win32.dirname(path15.win32.resolve(command))] : (await (deps.resolvePath ?? augmentedPath)() || "").split(path15.win32.delimiter).map((d) => d.trim().replace(/^"|"$/g, "")).filter(Boolean);
11267
+ const pathDirs = (await (deps.resolvePath ?? augmentedPath)() || "").split(path15.win32.delimiter).map((d) => d.trim().replace(/^"|"$/g, "")).filter(Boolean);
11268
+ const dirs = path15.win32.basename(command) !== command ? [path15.win32.dirname(path15.win32.resolve(command))] : pathDirs;
11053
11269
  const base = path15.win32.basename(command);
11054
11270
  const found = [];
11055
11271
  for (const route of ROUTES) {
@@ -11057,7 +11273,8 @@ async function findWindowsExecutables(command, deps) {
11057
11273
  for (const dir of dirs) {
11058
11274
  const candidate = path15.win32.join(dir, `${base}${ext}`);
11059
11275
  if (exists(candidate)) {
11060
- found.push({ file: candidate, route });
11276
+ const target = route === "cmd" ? npmShimTarget(candidate, pathDirs, deps) : void 0;
11277
+ found.push(target ? { ...target, route: "direct" } : { file: candidate, route });
11061
11278
  break outer;
11062
11279
  }
11063
11280
  }
@@ -11067,8 +11284,9 @@ async function findWindowsExecutables(command, deps) {
11067
11284
  }
11068
11285
  function planFor(found, args, deps) {
11069
11286
  if (found.route === "direct") {
11070
- const length2 = windowsCommandLine(found.file, args).length;
11071
- return length2 > WINDOWS_MAX_COMMAND_LINE ? { tooLong: length2, limit: WINDOWS_MAX_COMMAND_LINE } : { file: found.file, args };
11287
+ const all = [...found.leading ?? [], ...args];
11288
+ const length2 = windowsCommandLine(found.file, all).length;
11289
+ return length2 > WINDOWS_MAX_COMMAND_LINE ? { tooLong: length2, limit: WINDOWS_MAX_COMMAND_LINE } : { file: found.file, args: all };
11072
11290
  }
11073
11291
  if (found.route === "cmd") {
11074
11292
  if (hasLineBreak([found.file, ...args])) return { lineBreak: true };
@@ -11720,10 +11938,10 @@ var DIRENV_TIMEOUT_MS = 5e3;
11720
11938
  var KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
11721
11939
  function defaultDeps() {
11722
11940
  return {
11723
- run: (command, args, opts) => new Promise((resolve17) => {
11941
+ run: (command, args, opts) => new Promise((resolve18) => {
11724
11942
  execFile3(command, args, { ...opts, timeout: DIRENV_TIMEOUT_MS, encoding: "utf8" }, (err, stdout, stderr) => {
11725
11943
  const code = err ? typeof err.code === "number" ? Number(err.code) : -1 : 0;
11726
- resolve17({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
11944
+ resolve18({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
11727
11945
  });
11728
11946
  }),
11729
11947
  readFile: (file) => {
@@ -11812,10 +12030,10 @@ async function fromDirenv(cwd, deps) {
11812
12030
  }
11813
12031
  return { env, blocked: null };
11814
12032
  }
11815
- function findUp(start, relative21, deps) {
12033
+ function findUp(start, relative20, deps) {
11816
12034
  let dir = path18.resolve(start);
11817
12035
  for (; ; ) {
11818
- const candidate = path18.join(dir, relative21);
12036
+ const candidate = path18.join(dir, relative20);
11819
12037
  if (deps.readFile(candidate) !== null) return candidate;
11820
12038
  const parent = path18.dirname(dir);
11821
12039
  if (parent === dir) return null;
@@ -11860,14 +12078,14 @@ function parseEnvFile(content, context, home) {
11860
12078
 
11861
12079
  // src/services/harness/settleWithin.ts
11862
12080
  function settleWithin(promise, wait) {
11863
- return new Promise((resolve17, reject) => {
12081
+ return new Promise((resolve18, reject) => {
11864
12082
  let settled = false;
11865
12083
  const settle = (outcome) => {
11866
12084
  if (settled) return;
11867
12085
  settled = true;
11868
12086
  clearTimeout(timer);
11869
12087
  try {
11870
- resolve17(outcome());
12088
+ resolve18(outcome());
11871
12089
  } catch (err) {
11872
12090
  reject(err);
11873
12091
  }
@@ -11930,14 +12148,14 @@ function unlessCancelled(work, signal) {
11930
12148
  if (!signal) return work;
11931
12149
  work.catch(() => {
11932
12150
  });
11933
- return new Promise((resolve17, reject) => {
12151
+ return new Promise((resolve18, reject) => {
11934
12152
  if (signal.aborted) {
11935
- resolve17(CANCELLED2);
12153
+ resolve18(CANCELLED2);
11936
12154
  return;
11937
12155
  }
11938
- const onAbort = () => resolve17(CANCELLED2);
12156
+ const onAbort = () => resolve18(CANCELLED2);
11939
12157
  signal.addEventListener("abort", onAbort, { once: true });
11940
- work.then(resolve17, reject).finally(() => signal.removeEventListener("abort", onAbort));
12158
+ work.then(resolve18, reject).finally(() => signal.removeEventListener("abort", onAbort));
11941
12159
  });
11942
12160
  }
11943
12161
  async function spawnAttached(steps) {
@@ -12036,8 +12254,8 @@ async function awaitAttach(probe, timeoutMs, pollMs, ended2) {
12036
12254
  const state = await settleWithin(probe(left), ended2 ? { timeoutMs: left, onTimeout, ended: ended2, onEnded: () => "failed" } : { timeoutMs: left, onTimeout });
12037
12255
  if (state !== "pending") return state;
12038
12256
  if (pollMs > 0) {
12039
- await new Promise((resolve17) => {
12040
- const timer = setTimeout(resolve17, pollMs);
12257
+ await new Promise((resolve18) => {
12258
+ const timer = setTimeout(resolve18, pollMs);
12041
12259
  timer.unref?.();
12042
12260
  });
12043
12261
  }
@@ -12254,8 +12472,8 @@ function releasePipes(child) {
12254
12472
  var RunnerProcess = class {
12255
12473
  constructor(deps) {
12256
12474
  this.deps = deps;
12257
- this.ended = new Promise((resolve17) => {
12258
- this.markEnded = resolve17;
12475
+ this.ended = new Promise((resolve18) => {
12476
+ this.markEnded = resolve18;
12259
12477
  });
12260
12478
  }
12261
12479
  deps;
@@ -12304,7 +12522,8 @@ var RunnerProcess = class {
12304
12522
  const PATH = await resolvePath();
12305
12523
  const launch = await planDirectLaunch(command.command, command.args, {
12306
12524
  platform: this.deps.platform,
12307
- resolvePath
12525
+ resolvePath,
12526
+ exists: this.deps.exists
12308
12527
  });
12309
12528
  if (!isExecutableResolved(command.command, launch, PATH, { platform: this.deps.platform, exists: this.deps.exists })) {
12310
12529
  throw new ExecutableNotFoundError(command.command, PATH);
@@ -12407,8 +12626,8 @@ ${tail}` : ""}`;
12407
12626
  }
12408
12627
  /**
12409
12628
  * Tree-wide, because the direct child may be a CLI whose shells, MCP servers
12410
- * and test runs would outlive it — or, on Windows, the cmd.exe shim rather
12411
- * than the runner. The forced follow-up is scheduled and unref'd, so a
12629
+ * and test runs would outlive it — or, on Windows, the cmd.exe or PowerShell
12630
+ * that runs a shim rather than the runner. The forced follow-up is scheduled and unref'd, so a
12412
12631
  * disposed runner is never the reason the host refuses to exit.
12413
12632
  */
12414
12633
  dispose() {
@@ -12721,7 +12940,7 @@ var StdioAgentAdapter = class extends ProcessLifecycle {
12721
12940
  onEvent({ type: "error", message: this.exitMessage() });
12722
12941
  return;
12723
12942
  }
12724
- await new Promise((resolve17, reject) => {
12943
+ await new Promise((resolve18, reject) => {
12725
12944
  let settled = false;
12726
12945
  const release2 = () => {
12727
12946
  settled = true;
@@ -12733,7 +12952,7 @@ var StdioAgentAdapter = class extends ProcessLifecycle {
12733
12952
  const finish2 = () => {
12734
12953
  if (settled) return;
12735
12954
  release2();
12736
- resolve17();
12955
+ resolve18();
12737
12956
  };
12738
12957
  const fail = (err) => {
12739
12958
  if (settled) return;
@@ -12947,7 +13166,7 @@ var PermissionLedger = class {
12947
13166
  const open = this.open.get(id2);
12948
13167
  if (!open || this.answering.has(id2)) return false;
12949
13168
  this.answering.add(id2);
12950
- const sent = new Promise((resolve17) => resolve17(this.reply(open.handle, decision)));
13169
+ const sent = new Promise((resolve18) => resolve18(this.reply(open.handle, decision)));
12951
13170
  return this.awaitReply(id2, open, sent);
12952
13171
  }
12953
13172
  async awaitReply(id2, open, sent) {
@@ -13801,8 +14020,8 @@ var ClaudeCodeAdapter = class extends StdioAgentAdapter {
13801
14020
  if (!this.process) return Promise.resolve(null);
13802
14021
  this.controlCount += 1;
13803
14022
  const requestId = `ordewell-${request.subtype}-${this.controlCount}`;
13804
- const answered2 = new Promise((resolve17) => {
13805
- this.pendingControl.set(requestId, resolve17);
14023
+ const answered2 = new Promise((resolve18) => {
14024
+ this.pendingControl.set(requestId, resolve18);
13806
14025
  });
13807
14026
  this.writeLine({ type: "control_request", request_id: requestId, request });
13808
14027
  return settleWithin(answered2, { timeoutMs, ended: this.processEnded, onTimeout: () => null, onEnded: () => null }).finally(() => {
@@ -14307,7 +14526,7 @@ var ClaudeCodeAdapter = class extends StdioAgentAdapter {
14307
14526
 
14308
14527
  // src/services/harness/CodexAdapter.ts
14309
14528
  import { randomUUID as randomUUID4 } from "crypto";
14310
- import { isAbsolute as isAbsolute6, relative as relative8, sep as sep3 } from "path";
14529
+ import * as hostPath from "path";
14311
14530
 
14312
14531
  // src/services/harness/codexSandbox.ts
14313
14532
  var CODEX_RUNNER = "codex";
@@ -14321,6 +14540,17 @@ async function probeCodexSandbox(deps, cwd, env) {
14321
14540
  const landlock = await runProbe(deps, cwd, env, ["--enable", "use_legacy_landlock"]);
14322
14541
  return landlock.code === 0 ? "legacy-landlock" : "unavailable";
14323
14542
  }
14543
+ var CODEX_WINDOWS_DOCS = "https://developers.openai.com/codex/windows";
14544
+ function codexWindowsReadOnlyNote(readiness) {
14545
+ const state = readiness === "updateRequired" ? "needs its setup run again" : "is not set up";
14546
+ return [
14547
+ `Codex's Windows sandbox ${state} on this machine, so Codex runs this task read-only with no sandbox: each edit, and each command it does not judge safe, goes to Codex's reviewer, and what the reviewer approves runs unconfined.`,
14548
+ "",
14549
+ `To give Codex its sandbox, run \`codex\` in a terminal and choose "Set up default sandbox" (it asks for Administrator once), or run /setup-default-sandbox there. Not the non-admin sandbox: under it Codex refuses every command of a task like this one. ${CODEX_WINDOWS_DOCS}`
14550
+ ].join("\n");
14551
+ }
14552
+ var CODEX_WINDOWS_READ_ONLY_ADVICE = "Codex's Windows sandbox is not ready on this machine, so your sandbox may be read-only. That does not stop this task: make edits with apply_patch, and run a command that must write (a build, an install, tests that write files) with escalated permissions. A reviewer decides each such request. Do not end the task because the sandbox is read-only.";
14553
+ var CODEX_WINDOWS_SHELL_ADVICE = "Your shell on this Windows machine is PowerShell. Where its execution policy refuses an npm-installed tool's .ps1 script (npm, npx, pnpm), call the .cmd beside it instead, as in npm.cmd test. Report a test run as passed only when you saw it pass.";
14324
14554
  var NAMESPACE_CAUSE = "Its Linux sandbox needs unprivileged user namespaces, which this kernel restricts (Ubuntu 24.04's AppArmor default), and the legacy Landlock backend did not work either.";
14325
14555
  var SYSCTL_FIX = " sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0";
14326
14556
  function codexSandboxUnavailableMessage(role = "planner") {
@@ -14417,7 +14647,7 @@ var CodexSandboxAvailability = class {
14417
14647
  async function runProbe(deps, cwd, env, flags) {
14418
14648
  const args = ["sandbox", ...flags, "--", "/bin/true"];
14419
14649
  const placed = await deps.placement?.place({ command: "codex", args, env: {}, files: [] });
14420
- return new Promise((resolve17) => {
14650
+ return new Promise((resolve18) => {
14421
14651
  let output = "";
14422
14652
  let settled = false;
14423
14653
  let proc = null;
@@ -14426,7 +14656,7 @@ async function runProbe(deps, cwd, env, flags) {
14426
14656
  settled = true;
14427
14657
  clearTimeout(timer);
14428
14658
  placed?.ended();
14429
- resolve17({ code, output });
14659
+ resolve18({ code, output });
14430
14660
  };
14431
14661
  const timer = setTimeout(() => {
14432
14662
  placed?.stop();
@@ -14584,13 +14814,14 @@ ${taskCompletionContract(commits ? { commits } : {})}`;
14584
14814
  */
14585
14815
  plannerInstructions(nativeSearch, hidden, ownShell = true, extra) {
14586
14816
  const tools = ordewellToolNames("planner", hidden, extra);
14817
+ const runCommand = !hidden?.includes("run_command");
14587
14818
  return [
14588
14819
  `You have ${countOf(tools)} tools from the \`${ORDEWELL_MCP_SERVER_NAME}\` MCP server: ${quoted3(tools)}.`,
14589
14820
  `They are not in your tool list up front. Find them with the tool discovery you have (the \`exec\` tool's \`ALL_TOOLS\` list) and call them by their full names, ${quoted3(this.toolNames("planner", hidden, extra))}.`,
14590
- ownShell ? `Run shell commands with \`${this.toolName("run_command")}\`, not your own shell: yours is sandboxed without network, so git remotes, gh and cloud CLIs fail there.` : `You have no shell of your own on this machine: run every command, reads included, with \`${this.toolName("run_command")}\`.`,
14821
+ !runCommand ? "" : ownShell ? `Run shell commands with \`${this.toolName("run_command")}\`, not your own shell: yours is sandboxed without network, so git remotes, gh and cloud CLIs fail there.` : `You have no shell of your own on this machine: run every command, reads included, with \`${this.toolName("run_command")}\`.`,
14591
14822
  `Fetch web pages with \`${this.toolName("fetch")}\`, not curl or your shell.`,
14592
14823
  nativeSearch ? "Search the web with your built-in web search." : `Your built-in web search is off for this session; search with \`${this.toolName("web_search")}\`.`
14593
- ].join(" ");
14824
+ ].filter(Boolean).join(" ");
14594
14825
  },
14595
14826
  plannerWebSearch: (nativeSearch) => nativeSearch ? "cached" : "disabled"
14596
14827
  };
@@ -14612,7 +14843,7 @@ var CodexRpc = class {
14612
14843
  }
14613
14844
  /** The request as the awaited form of {@link send}, for steps that wait on one answer and nothing else. */
14614
14845
  call(method, params) {
14615
- return new Promise((resolve17) => this.send(method, params, (response) => resolve17(response)));
14846
+ return new Promise((resolve18) => this.send(method, params, (response) => resolve18(response)));
14616
14847
  }
14617
14848
  /**
14618
14849
  * A request framed as the line to write, left to the caller to write — for
@@ -14934,7 +15165,9 @@ var CodexAdapter = class extends StdioAgentAdapter {
14934
15165
  /** The row each announced file of an in-flight `fileChange` item is shown under, by the file's shown path. */
14935
15166
  fileChangeRows = /* @__PURE__ */ new Map();
14936
15167
  sandbox = "default";
14937
- /** A planner on a host where no sandbox starts: Codex's own shell is off, and `run_command` is its only one (ADR-0033). */
15168
+ /** Whether the user set up Codex's Windows sandbox, asked for a change task on a Windows host; null where nothing asked or Codex did not say. */
15169
+ windowsSandbox = null;
15170
+ /** Codex's own shell is off, and `run_command` is the only one: a read-only task's, and a planner's on a host where no sandbox starts (ADR-0033) or on Windows (ADR-0010). */
14938
15171
  ownShellOff = false;
14939
15172
  /** A read-only task's: every MCP server Codex would start beside Ordewell's, each switched off for its thread (ADR-0046). */
14940
15173
  withheldServers = [];
@@ -14970,9 +15203,11 @@ var CodexAdapter = class extends StdioAgentAdapter {
14970
15203
  const needsSandbox = opts.kind === "planner" || opts.flags.permissionMode !== "danger-full-access";
14971
15204
  const nothingToAsk = readOnly || this.deps.placement !== void 0 && !needsSandbox;
14972
15205
  this.sandbox = nothingToAsk ? "default" : await probeCodexSandbox(this.deps, opts.cwd, this.spawnEnv);
14973
- this.ownShellOff = readOnly || this.sandbox === "unavailable" && opts.kind === "planner" && !!opts.mcp;
15206
+ const unsandboxedPlanner = this.sandbox === "unavailable" && opts.kind === "planner" && !!opts.mcp;
15207
+ const readsThroughOrdewell = !!opts.mcp && !opts.mcp.hidden?.includes("run_command");
15208
+ this.ownShellOff = readOnly || unsandboxedPlanner || opts.kind === "planner" && readsThroughOrdewell && this.onWindowsHost();
14974
15209
  if (this.sandbox === "unavailable" && needsSandbox && !this.ownShellOff) throw new Error(codexSandboxUnavailableMessage(this.deps.placement ? "container" : opts.kind));
14975
- if (this.ownShellOff && !readOnly) this.announce({ type: "thinking", text: codexShellOffNote() });
15210
+ if (unsandboxedPlanner) this.announce({ type: "thinking", text: codexShellOffNote() });
14976
15211
  const incomplete = () => {
14977
15212
  throw this.handshakeIncomplete();
14978
15213
  };
@@ -14998,6 +15233,7 @@ ${this.exitMessage()}`);
14998
15233
  throw initialized.closed ? this.handshakeIncomplete() : new Error(`The Codex app-server rejected initialize: ${initialized.message ?? "unknown error"}`);
14999
15234
  }
15000
15235
  if (readOnlyTask(opts)) this.withheldServers = await this.configuredServers(opts.cwd);
15236
+ if (this.runsWindowsSandbox(opts)) this.windowsSandbox = await this.windowsSandboxReadiness();
15001
15237
  const resumeId = opts.resumeSessionId;
15002
15238
  let opened2 = await this.requestThread(resumeId);
15003
15239
  if ("reason" in opened2 && resumeId) {
@@ -15008,8 +15244,34 @@ ${this.exitMessage()}`);
15008
15244
  this.threadId = opened2.id;
15009
15245
  this.sessionId = opened2.id;
15010
15246
  this.threadModel = opened2.model;
15247
+ if (opts.kind === "task" && this.windowsSandbox !== null && this.windowsSandbox !== "ready" && opened2.sandbox === "readOnly") {
15248
+ this.announce({ type: "thinking", text: codexWindowsReadOnlyNote(this.windowsSandbox) });
15249
+ }
15011
15250
  if (opts.kind === "task") await this.loadCommands(this.runnerCwd(opts));
15012
15251
  }
15252
+ /**
15253
+ * Codex runs on this Windows host, not placed on another machine. Its
15254
+ * sandboxes here cannot keep a planner's command off the network: with none
15255
+ * set up there is none, and under the non-admin one Node reaches the network
15256
+ * (measured, ADR-0010). So a planner's own shell is off here, and every
15257
+ * command goes through Ordewell's `run_command`, as every other planner's
15258
+ * does on Windows (ADR-0026). A one-shot plan, which runs no command, keeps
15259
+ * Codex's shell with its approvals declined: it has no other way to read.
15260
+ */
15261
+ onWindowsHost() {
15262
+ return !this.deps.placement && (this.deps.platform ?? process.platform) === "win32";
15263
+ }
15264
+ /** A change task whose commands Codex runs in its own Windows sandbox, which the user may not have set up. */
15265
+ runsWindowsSandbox(opts) {
15266
+ return opts.kind === "task" && this.onWindowsHost() && !this.ownShellOff && opts.flags.permissionMode === "workspace-write";
15267
+ }
15268
+ /** Codex's answer, or null from a Codex that has no such question: that one is left as it configures itself. */
15269
+ async windowsSandboxReadiness() {
15270
+ const response = await this.rpc.call("windowsSandbox/readiness", {});
15271
+ if (!response.ok && response.closed) throw this.handshakeIncomplete();
15272
+ const status = response.ok ? response.result.status : void 0;
15273
+ return status === "ready" || status === "notConfigured" || status === "updateRequired" ? status : null;
15274
+ }
15013
15275
  commands() {
15014
15276
  return this.nativeCommands.map((command) => ({ ...command }));
15015
15277
  }
@@ -15077,6 +15339,7 @@ ${this.exitMessage()}`);
15077
15339
  }
15078
15340
  return Object.keys(servers).filter((name) => name !== ORDEWELL_MCP_SERVER_NAME);
15079
15341
  }
15342
+ /** The thread, the model it runs, and the sandbox Codex granted it, which need not be the one asked for. */
15080
15343
  async requestThread(resumeSessionId) {
15081
15344
  const response = await this.rpc.call(resumeSessionId ? "thread/resume" : "thread/start", {
15082
15345
  ...resumeSessionId ? { threadId: resumeSessionId } : {},
@@ -15086,7 +15349,8 @@ ${this.exitMessage()}`);
15086
15349
  const thread = response.ok ? response.result.thread : void 0;
15087
15350
  if (!thread?.id) return { reason: !response.ok && response.message || "no thread id returned" };
15088
15351
  const model = response.ok ? response.result.model : void 0;
15089
- return { id: thread.id, model: typeof model === "string" ? model : null };
15352
+ const sandbox = response.ok ? response.result.sandbox?.type : void 0;
15353
+ return { id: thread.id, model: typeof model === "string" ? model : null, sandbox: typeof sandbox === "string" ? sandbox : null };
15090
15354
  }
15091
15355
  threadParams() {
15092
15356
  const opts = this.startOpts;
@@ -15104,14 +15368,20 @@ ${this.exitMessage()}`);
15104
15368
  ...opts?.mcp ? { mcp_servers: CODEX_ORDEWELL.threadServers(opts.mcp) } : {}
15105
15369
  };
15106
15370
  const threadConfig = Object.keys(config).length ? { config } : {};
15371
+ const noWindowsSandbox = this.windowsSandbox !== null && this.windowsSandbox !== "ready";
15107
15372
  if (opts?.kind === "task") {
15108
15373
  const { approvalPolicy, approvalsReviewer } = opts.flags.modeSettings;
15374
+ const developerInstructions = [
15375
+ opts.mcp ? CODEX_ORDEWELL.taskInstructions({ readOnly: readOnlyTask(opts), ...opts.commits ? { commits: true } : {}, ...opts.mcp.extraTools ? { extra: opts.mcp.extraTools } : {} }) : "",
15376
+ this.onWindowsHost() && !this.ownShellOff ? CODEX_WINDOWS_SHELL_ADVICE : "",
15377
+ noWindowsSandbox ? CODEX_WINDOWS_READ_ONLY_ADVICE : ""
15378
+ ].filter(Boolean).join("\n\n");
15109
15379
  return {
15110
15380
  ...common,
15111
15381
  sandbox: opts.flags.permissionMode,
15112
15382
  ...approvalPolicy ? { approvalPolicy } : {},
15113
15383
  ...approvalsReviewer ? { approvalsReviewer } : {},
15114
- ...opts.mcp ? { developerInstructions: CODEX_ORDEWELL.taskInstructions({ readOnly: readOnlyTask(opts), ...opts.commits ? { commits: true } : {}, ...opts.mcp.extraTools ? { extra: opts.mcp.extraTools } : {} }) } : {},
15384
+ ...developerInstructions ? { developerInstructions } : {},
15115
15385
  ...threadConfig,
15116
15386
  ...readOnlyTask(opts) ? { config: { ...config, mcp_servers: { ...withheld(this.withheldServers), ...config.mcp_servers }, projects: untrustedProjects(opts.cwd), web_search: "disabled" } } : {}
15117
15387
  };
@@ -15154,8 +15424,8 @@ ${this.exitMessage()}`);
15154
15424
  return awaitAttach(async (left) => {
15155
15425
  const known = CODEX_ORDEWELL.attachState(this.mcpStartup);
15156
15426
  if (known !== "pending") return known;
15157
- const reported = new Promise((resolve17) => {
15158
- this.mcpStartupSettled = () => resolve17(CODEX_ORDEWELL.attachState(this.mcpStartup));
15427
+ const reported = new Promise((resolve18) => {
15428
+ this.mcpStartupSettled = () => resolve18(CODEX_ORDEWELL.attachState(this.mcpStartup));
15159
15429
  });
15160
15430
  const state = await settleWithin(reported, {
15161
15431
  timeoutMs: left,
@@ -15180,10 +15450,10 @@ ${this.exitMessage()}`);
15180
15450
  const turn = this.turn;
15181
15451
  if (!this.process || !turn) return Promise.resolve(false);
15182
15452
  this.interruptRequested = true;
15183
- const acknowledged = new Promise((resolve17) => {
15453
+ const acknowledged = new Promise((resolve18) => {
15184
15454
  this.whenNamed(turn, () => this.rpc.send("turn/interrupt", { threadId: this.threadId, turnId: turn.id }, (response) => {
15185
15455
  if (!response.ok) this.interruptRequested = false;
15186
- resolve17(response.ok);
15456
+ resolve18(response.ok);
15187
15457
  }));
15188
15458
  });
15189
15459
  return settleWithin(acknowledged, { timeoutMs, ended: this.processEnded, onTimeout: () => false, onEnded: () => false });
@@ -15205,7 +15475,7 @@ ${this.exitMessage()}`);
15205
15475
  const turn = this.turn;
15206
15476
  if (!this.process || !turn) return Promise.resolve(false);
15207
15477
  const clientId = randomUUID4();
15208
- return new Promise((resolve17) => {
15478
+ return new Promise((resolve18) => {
15209
15479
  let settled = false;
15210
15480
  const steer = {
15211
15481
  id: id2,
@@ -15214,7 +15484,7 @@ ${this.exitMessage()}`);
15214
15484
  if (settled) return;
15215
15485
  settled = true;
15216
15486
  if (!accepted) turn.steers.delete(clientId);
15217
- resolve17(accepted);
15487
+ resolve18(accepted);
15218
15488
  }
15219
15489
  };
15220
15490
  turn.steers.set(clientId, steer);
@@ -15763,10 +16033,11 @@ ${this.exitMessage()}`);
15763
16033
  }
15764
16034
  /** Relative to the task's worktree, where every path but a stray one lies; a move names both ends. */
15765
16035
  shownChangePath(change) {
16036
+ const { isAbsolute: isAbsolute13, relative: relative20, sep: sep13 } = this.deps.placement ? hostPath.posix : hostPath;
15766
16037
  const shown = (path52) => {
15767
16038
  const cwd = this.startOpts && this.runnerCwd(this.startOpts);
15768
- const rel = cwd ? relative8(cwd, path52) : path52;
15769
- return rel && rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute6(rel) ? rel : path52;
16039
+ const rel = cwd ? relative20(cwd, path52) : path52;
16040
+ return rel && rel !== ".." && !rel.startsWith(`..${sep13}`) && !isAbsolute13(rel) ? rel : path52;
15770
16041
  };
15771
16042
  const from = shown(change.path ?? "");
15772
16043
  return change.kind?.move_path ? `${from} \u2192 ${shown(change.kind.move_path)}` : from;
@@ -15973,14 +16244,14 @@ function splitModelId(id2) {
15973
16244
  return { providerID: id2.slice(0, slash), modelID: id2.slice(slash + 1) };
15974
16245
  }
15975
16246
  function delay(ms, signal) {
15976
- return new Promise((resolve17) => {
16247
+ return new Promise((resolve18) => {
15977
16248
  const onAbort = () => {
15978
16249
  clearTimeout(timer);
15979
- resolve17();
16250
+ resolve18();
15980
16251
  };
15981
16252
  const timer = setTimeout(() => {
15982
16253
  signal?.removeEventListener("abort", onAbort);
15983
- resolve17();
16254
+ resolve18();
15984
16255
  }, ms);
15985
16256
  timer.unref?.();
15986
16257
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -16102,8 +16373,8 @@ function streamTurn() {
16102
16373
  }
16103
16374
  function turnLatch() {
16104
16375
  let markDone;
16105
- const ended2 = new Promise((resolve17) => {
16106
- markDone = resolve17;
16376
+ const ended2 = new Promise((resolve18) => {
16377
+ markDone = resolve18;
16107
16378
  });
16108
16379
  const turn = { live: false, done: false, ended: ended2, finish: () => {
16109
16380
  turn.done = true;
@@ -16115,9 +16386,9 @@ async function settleTurn(turn, how, onEvent) {
16115
16386
  const { signal } = how;
16116
16387
  let onAbort = () => {
16117
16388
  };
16118
- const aborted = new Promise((resolve17) => {
16119
- onAbort = resolve17;
16120
- if (signal?.aborted) resolve17();
16389
+ const aborted = new Promise((resolve18) => {
16390
+ onAbort = resolve18;
16391
+ if (signal?.aborted) resolve18();
16121
16392
  signal?.addEventListener("abort", onAbort, { once: true });
16122
16393
  });
16123
16394
  try {
@@ -16144,8 +16415,8 @@ async function interruptAcknowledged(turn, processEnded, timeoutMs) {
16144
16415
  async function openEventStream(connect2, onFrame, onActivity) {
16145
16416
  const streamAbort = new AbortController();
16146
16417
  let connected;
16147
- const ready = new Promise((resolve17) => {
16148
- connected = resolve17;
16418
+ const ready = new Promise((resolve18) => {
16419
+ connected = resolve18;
16149
16420
  });
16150
16421
  let fail;
16151
16422
  const failed2 = new Promise((_resolve, reject) => {
@@ -16159,7 +16430,7 @@ async function openEventStream(connect2, onFrame, onActivity) {
16159
16430
  const attemptAbort = new AbortController();
16160
16431
  const abortAttempt = () => attemptAbort.abort();
16161
16432
  streamAbort.signal.addEventListener("abort", abortAttempt, { once: true });
16162
- const stopped2 = new Promise((resolve17) => attemptAbort.signal.addEventListener("abort", () => resolve17(), { once: true }));
16433
+ const stopped2 = new Promise((resolve18) => attemptAbort.signal.addEventListener("abort", () => resolve18(), { once: true }));
16163
16434
  try {
16164
16435
  await streamEvents((signal) => settleWithin(connect2(signal), {
16165
16436
  timeoutMs: STREAM_CONNECT_TIMEOUT_MS,
@@ -16960,7 +17231,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
16960
17231
  * only until the address is known.
16961
17232
  */
16962
17233
  serverAddress() {
16963
- return new Promise((resolve17) => {
17234
+ return new Promise((resolve18) => {
16964
17235
  let partial = "";
16965
17236
  const stopReading = this.runner.readStdout((text4) => {
16966
17237
  const lines = (partial + text4).split("\n");
@@ -16975,7 +17246,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
16975
17246
  const settle = (url) => {
16976
17247
  stopReading();
16977
17248
  clearTimeout(timer);
16978
- resolve17(url);
17249
+ resolve18(url);
16979
17250
  };
16980
17251
  void this.processEnded.then(() => settle(null));
16981
17252
  });
@@ -17675,7 +17946,7 @@ var OpenCodeAdapter = class extends ProcessLifecycle {
17675
17946
  if (servers) this.mcpServers = Object.keys(servers).filter((name) => name !== ordewell.name);
17676
17947
  return OPENCODE_ORDEWELL.attachState(servers?.[ordewell.name]?.status);
17677
17948
  }, MCP_ATTACH_TIMEOUT_MS, MCP_STATUS_POLL_MS2, this.processEnded);
17678
- if (state === "connected" && this.v2) await new Promise((resolve17) => setTimeout(resolve17, V2_TOOLS_OFFERED_MS));
17949
+ if (state === "connected" && this.v2) await new Promise((resolve18) => setTimeout(resolve18, V2_TOOLS_OFFERED_MS));
17679
17950
  return state;
17680
17951
  }
17681
17952
  /** 2.x lists its servers as `{ name, status: { status } }`, and only once it has started connecting them. */
@@ -18057,8 +18328,8 @@ async function openAppServer(command, args, launch) {
18057
18328
  })) launch.onMessage?.(message);
18058
18329
  };
18059
18330
  let inputBroken;
18060
- const broken = new Promise((resolve17) => {
18061
- inputBroken = resolve17;
18331
+ const broken = new Promise((resolve18) => {
18332
+ inputBroken = resolve18;
18062
18333
  });
18063
18334
  try {
18064
18335
  await runner.start(launch.cwd, () => ({ command, args }), (started) => {
@@ -20014,11 +20285,11 @@ async function committedInHead(files) {
20014
20285
  }
20015
20286
  const result = /* @__PURE__ */ new Map();
20016
20287
  await Promise.all([...byDir].map(async ([dir, inDir]) => {
20017
- const relative21 = (file) => path33.relative(dir, file).split(path33.sep).join("/");
20288
+ const relative20 = (file) => path33.relative(dir, file).split(path33.sep).join("/");
20018
20289
  try {
20019
- const { stdout } = await runGit("git", ["ls-tree", "--name-only", "HEAD", "--", ...inDir.map(relative21)], { cwd: dir, env: cleanEnv() });
20290
+ const { stdout } = await runGit("git", ["ls-tree", "--name-only", "HEAD", "--", ...inDir.map(relative20)], { cwd: dir, env: cleanEnv() });
20020
20291
  const listed4 = new Set(stdout.split("\n").map((line) => line.trim()).filter(Boolean));
20021
- for (const file of inDir) result.set(file, listed4.has(relative21(file)));
20292
+ for (const file of inDir) result.set(file, listed4.has(relative20(file)));
20022
20293
  } catch {
20023
20294
  }
20024
20295
  }));
@@ -20736,7 +21007,7 @@ function researchTasksGuide(tools) {
20736
21007
  function sealedGuide(tool2) {
20737
21008
  return `${tool2} with "sealed": true runs a command without asking anyone, for local computation over the workspace: a loop over files, a script, a pipe into an interpreter. A sealed run has no network, the workspace read-only, and no home directory or credentials; $TMPDIR is a scratch directory kept for the session's sealed runs, so read what one left there with another sealed run. A command that would be refused for being a loop, a here-document or a pipe into an interpreter runs sealed on its own where this machine has a sandbox, and you can ask for it yourself when you know a command is local computation. Never seal a command that needs the network or the user's accounts: it fails there. An allowlist exclusion and a command the user denied are refused either way, and without a sandbox a command that would run sealed is refused.`;
20738
21009
  }
20739
- function researchPhaseBlock(harnessMode, agents) {
21010
+ function researchPhaseBlock(harnessMode, agents, researchShell) {
20740
21011
  const shared2 = [
20741
21012
  "RESEARCH PHASE:",
20742
21013
  "- Start by reading README.md and any agent config files (AGENTS.md, CLAUDE.md)"
@@ -20745,6 +21016,7 @@ function researchPhaseBlock(harnessMode, agents) {
20745
21016
  "- Explore the repository with your own tools until you understand its architecture",
20746
21017
  "- You are planning, not implementing: do NOT edit, create, or delete any file, and do not run commands that change the workspace",
20747
21018
  "- Run commands \u2014 git, gh, cloud CLIs, the project's own tooling \u2014 with the run_command tool, not a shell of your own. MCP tools the user configured (issue trackers, todo lists) are yours to read from too. Reads run at once; anything else is approved or refused by the user's settings. When something the plan needs to change is refused, add it to the plan instead: a script task when you can state the exact commands, an ops task when it needs judgment",
21019
+ ...researchShellLine(researchShell),
20748
21020
  `- ${sealedGuide("run_command")}`,
20749
21021
  ...agents === null ? [] : ["- When you delegate orientation to your own agents (WHO EXPLORES below), WAIT for their results inside this reply. Do NOT launch them in the background or async and end your turn saying you will report back later: your turn ending is what hands the conversation back to the user, and anything you say after it never reaches them."]
20750
21022
  ] : [
@@ -20792,6 +21064,11 @@ var NATIVE_SHELL_GUIDE = [
20792
21064
  ].join("\n");
20793
21065
  var AUTORUN_ON = "AUTORUN is on: a plan you submit starts when your reply ends, without the user's review. When you are ready to plan, write the outline in your reply as the plan's summary and submit the plan in the same reply; do not wait for the user to confirm it, and do not start its tasks yourself. Still ask clarifying questions first when the goal is vague or a decision would materially change the outcome.";
20794
21066
  var AUTORUN_OFF = "AUTORUN is off now: show the outline and wait for the user to confirm it before you submit a plan.";
21067
+ function researchShellLine(shell) {
21068
+ if (shell === "git-bash") return ["- On this Windows machine run_command runs Git Bash, a POSIX shell: read with cat, ls, grep and find, not PowerShell cmdlets such as Get-Content."];
21069
+ if (shell === "cmd") return ["- On this Windows machine run_command runs cmd.exe: read with type, dir and findstr, not PowerShell cmdlets such as Get-Content."];
21070
+ return [];
21071
+ }
20795
21072
  var EXECUTION_TOOLS_SECTION = [
20796
21073
  "RUNNING THE PLAN:",
20797
21074
  "When the user asks you to start, stop or retry work, do it with these tools rather than telling them which button to press. Ordewell checks every call, may ask the user first, and a refusal says why and what would be accepted.",
@@ -20987,7 +21264,7 @@ function buildConversationBody(goal, context, modelsJson, runners, modeGuide, va
20987
21264
  "4. When the strategy calls for a plan and you have enough context, produce a prose outline \u2014 a short list describing each task in order.",
20988
21265
  autorun ? `5. Write the outline in your reply, then ${submit} in the same reply.` : `5. After the user confirms the outline, ${submit}.`,
20989
21266
  "",
20990
- researchPhaseBlock(tools, agents),
21267
+ researchPhaseBlock(tools, agents, variant.researchShell),
20991
21268
  "",
20992
21269
  ...whoExploresSection(agents),
20993
21270
  "",
@@ -21340,12 +21617,12 @@ function buildConflictRepairPrompt(task2, conflict, integrationBranch, plan) {
21340
21617
  const merge = `git merge --no-edit ${quotedMessageArgs(conflict.message)} ${integrationBranch}`;
21341
21618
  const asked = `What the task was asked to do:
21342
21619
  ${task2.prompt ?? task2.description}`;
21343
- const resolve17 = "resolve every conflict so that both sides' intent survives: keep the work already integrated and add what the task contributed.";
21620
+ const resolve18 = "resolve every conflict so that both sides' intent survives: keep the work already integrated and add what the task contributed.";
21344
21621
  const repos = conflict.repos.filter((repo) => repo !== SELF_REPO);
21345
21622
  if (repos.length === 0) {
21346
21623
  return [
21347
21624
  `Task ${ref2} "${task2.title}" passed, but merging its branch \`${branch}\` into \`${integrationBranch}\` conflicted${files.length > 0 ? ` in ${files.join(", ")}` : ""}. None of its work has landed yet.`,
21348
- `This is the task's own worktree, on \`${branch}\`, with its work committed. Run \`${merge}\` here and ${resolve17} Never drop either side wholesale, and never abort the merge or reset it away.`,
21625
+ `This is the task's own worktree, on \`${branch}\`, with its work committed. Run \`${merge}\` here and ${resolve18} Never drop either side wholesale, and never abort the merge or reset it away.`,
21349
21626
  `Build and test the result the way this project does, commit the merge with \`${COMMIT_MERGE}\`, and only then call \`task_complete\`.`,
21350
21627
  "",
21351
21628
  asked
@@ -21354,7 +21631,7 @@ ${task2.prompt ?? task2.description}`;
21354
21631
  const stoppedIn = conflict.conflictRepo ?? repos[0];
21355
21632
  return [
21356
21633
  `Task ${ref2} "${task2.title}" passed, but landing its branch \`${branch}\` on \`${integrationBranch}\` conflicted in ${stoppedIn}${files.length > 0 ? ` (${files.join(", ")})` : ""}. A task lands in every repository it changed or in none, so none of its work has landed yet.`,
21357
- `This is the task's own workspace, with each repository at its usual path on \`${branch}\` and the task's work committed. In each repository the task changed \u2014 ${repos.join(", ")} \u2014 run \`${merge}\` inside that repository's directory, and ${resolve17} Never drop either side wholesale, and never abort a merge or reset it away.`,
21634
+ `This is the task's own workspace, with each repository at its usual path on \`${branch}\` and the task's work committed. In each repository the task changed \u2014 ${repos.join(", ")} \u2014 run \`${merge}\` inside that repository's directory, and ${resolve18} Never drop either side wholesale, and never abort a merge or reset it away.`,
21358
21635
  `Build and test the result the way this project does, commit the merge in each repository with \`${COMMIT_MERGE}\`, and only then call \`task_complete\`.`,
21359
21636
  "",
21360
21637
  asked
@@ -22678,12 +22955,12 @@ var PlannerConversation = class {
22678
22955
  }
22679
22956
  /** Resolves once no turn holds the conversation: what a subtree's stop waits on (ADR-0055 D16). */
22680
22957
  idle() {
22681
- return this.live ? new Promise((resolve17) => {
22682
- this.idling.push(resolve17);
22958
+ return this.live ? new Promise((resolve18) => {
22959
+ this.idling.push(resolve18);
22683
22960
  }) : Promise.resolve();
22684
22961
  }
22685
22962
  settleIdle() {
22686
- for (const resolve17 of this.idling.splice(0)) resolve17();
22963
+ for (const resolve18 of this.idling.splice(0)) resolve18();
22687
22964
  }
22688
22965
  /** Stop the planner turn in flight; it settles as stopped. False when none is. */
22689
22966
  stopTurn(by) {
@@ -24939,7 +25216,7 @@ async function runNotifyCommand(command, env, { timeLimitMs = NOTIFY_TIME_LIMIT_
24939
25216
  });
24940
25217
  proc.unref();
24941
25218
  const leaveTeardown = onHostTeardown(() => stop(proc));
24942
- await new Promise((resolve17, reject) => {
25219
+ await new Promise((resolve18, reject) => {
24943
25220
  const settle = () => {
24944
25221
  clearTimeout(limit);
24945
25222
  leaveTeardown();
@@ -24956,7 +25233,7 @@ async function runNotifyCommand(command, env, { timeLimitMs = NOTIFY_TIME_LIMIT_
24956
25233
  });
24957
25234
  proc.once("exit", (code, signal) => {
24958
25235
  settle();
24959
- if (code === 0) resolve17();
25236
+ if (code === 0) resolve18();
24960
25237
  else reject(new Error(code === null ? `ended on ${signal}` : `exited with code ${code}`));
24961
25238
  });
24962
25239
  });
@@ -25004,8 +25281,8 @@ function detectInstalledPlanner(installation) {
25004
25281
  return probe;
25005
25282
  }
25006
25283
  async function installedPlannerDetected() {
25007
- while (!answered) await new Promise((resolve17) => {
25008
- waiters.push(resolve17);
25284
+ while (!answered) await new Promise((resolve18) => {
25285
+ waiters.push(resolve18);
25009
25286
  });
25010
25287
  }
25011
25288
  function installedPlannerAnswered() {
@@ -25460,9 +25737,8 @@ var EnvConfig = class extends BaseConfig {
25460
25737
 
25461
25738
  // src/services/taskDiffRead.ts
25462
25739
  import { createHash as createHash3 } from "crypto";
25463
- import * as fs14 from "fs";
25740
+ import * as fs15 from "fs";
25464
25741
  import * as path36 from "path";
25465
- import { devNull } from "os";
25466
25742
 
25467
25743
  // src/services/stateRoot.ts
25468
25744
  import * as fs13 from "fs";
@@ -25490,6 +25766,16 @@ function refuseUsersCheckout(codeRoot, stateRoot) {
25490
25766
  }
25491
25767
  }
25492
25768
 
25769
+ // src/utils/realPath.ts
25770
+ import * as fs14 from "fs";
25771
+ function realPathOf(p) {
25772
+ try {
25773
+ return fs14.realpathSync.native(p);
25774
+ } catch {
25775
+ return fs14.realpathSync(p);
25776
+ }
25777
+ }
25778
+
25493
25779
  // src/services/taskDiffRead.ts
25494
25780
  var TASK_DIFF_UNAVAILABLE = "Task diff is not available for this run: no task-specific changes were recorded (shared runs cannot attribute workspace changes to one task).";
25495
25781
  function allowedPath(file) {
@@ -25597,18 +25883,18 @@ async function readTaskDiff(invoker, run, taskId, options) {
25597
25883
  };
25598
25884
  try {
25599
25885
  const files = [];
25600
- const workspaceRoot = fs14.realpathSync(stateRootOf(run));
25886
+ const workspaceRoot = fs15.realpathSync(stateRootOf(run));
25601
25887
  for (const repo of run.repos) {
25602
25888
  if (options.repo !== void 0 && repo.path !== options.repo) continue;
25603
25889
  const entry = record.repos[repo.path];
25604
25890
  if (!entry?.baseRef) return { available: false, reason: `Task diff is not available for repository ${repo.path}: this older run did not record the task's starting commit.` };
25605
25891
  if (!/^[a-f0-9]{40,64}$/.test(entry.baseRef)) throw new Error("Invalid recorded starting commit.");
25606
- const live2 = record.status !== "merged" && fs14.existsSync(entry.worktree);
25892
+ const live2 = record.status !== "merged" && fs15.existsSync(entry.worktree);
25607
25893
  const cwd = live2 ? entry.worktree : repo.root;
25608
- if (!inside(workspaceRoot, fs14.realpathSync(cwd))) throw new Error("The recorded task repository moved outside the workspace.");
25894
+ if (!inside(workspaceRoot, fs15.realpathSync(cwd))) throw new Error("The recorded task repository moved outside the workspace.");
25609
25895
  if (live2) {
25610
25896
  const toplevel = (await git(reader, cwd, ["rev-parse", "--show-toplevel"])).trim();
25611
- if (fs14.realpathSync(toplevel) !== fs14.realpathSync(entry.worktree)) throw new Error("The recorded task worktree is no longer a repository.");
25897
+ if (realPathOf(toplevel) !== realPathOf(entry.worktree)) throw new Error("The recorded task worktree is no longer a repository.");
25612
25898
  }
25613
25899
  const prefix = (await git(reader, repo.root, ["rev-parse", "--show-prefix"])).trim();
25614
25900
  const common = ["--no-pager", "-c", "core.fsmonitor=false"];
@@ -25643,9 +25929,9 @@ async function readTaskDiff(invoker, run, taskId, options) {
25643
25929
  const others = await git(reader, workspace, [...common, "ls-files", "--others", "--exclude-standard", "-z", "--", "."]);
25644
25930
  for (const file of others.split("\0").filter((f) => f && allowed(f))) {
25645
25931
  const full = path36.join(workspace, file);
25646
- if (!inside(fs14.realpathSync(workspace), fs14.realpathSync(path36.dirname(full)))) continue;
25932
+ if (!inside(fs15.realpathSync(workspace), fs15.realpathSync(path36.dirname(full)))) continue;
25647
25933
  const untracked = async (numstat) => {
25648
- const result = await tryGit(reader, workspace, [...common, "diff", "--no-index", "--no-renames", "--no-ext-diff", "--no-textconv", ...numstat ? ["--numstat", "-z"] : [], "--", devNull, file]);
25934
+ const result = await tryGit(reader, workspace, [...common, "diff", "--no-index", "--no-renames", "--no-ext-diff", "--no-textconv", ...numstat ? ["--numstat", "-z"] : [], "--", "/dev/null", file]);
25649
25935
  if (!result.ok && result.code !== 1) throw new Error(result.stderr.trim() || "Could not read an untracked file diff.");
25650
25936
  return result.stdout;
25651
25937
  };
@@ -25673,7 +25959,7 @@ ${await file.patch()}`);
25673
25959
  // src/services/GitWorktreeIsolation.ts
25674
25960
  import { randomBytes as randomBytes6 } from "crypto";
25675
25961
  import { spawnSync } from "child_process";
25676
- import * as fs16 from "fs";
25962
+ import * as fs17 from "fs";
25677
25963
  import * as path38 from "path";
25678
25964
 
25679
25965
  // src/utils/shell.ts
@@ -25686,7 +25972,7 @@ function shellQuoted(text4) {
25686
25972
  }
25687
25973
 
25688
25974
  // src/utils/prdStore.ts
25689
- import * as fs15 from "fs";
25975
+ import * as fs16 from "fs";
25690
25976
  import * as path37 from "path";
25691
25977
  var PRD_BLOCK_RE = /<!--\s*ORDEWELL_PRD_START\s+slug="([^"]+)"\s*-->\s*([\s\S]*?)\s*<!--\s*ORDEWELL_PRD_END\s*-->/;
25692
25978
  function extractPrdBlock(text4) {
@@ -25702,9 +25988,9 @@ function sanitizeSlug(raw) {
25702
25988
  }
25703
25989
  function savePrdMarkdown(workspace, slug, markdown) {
25704
25990
  const dir = path37.join(workspace, ".scratch", sanitizeSlug(slug));
25705
- fs15.mkdirSync(dir, { recursive: true });
25991
+ fs16.mkdirSync(dir, { recursive: true });
25706
25992
  const file = path37.join(dir, "PRD.md");
25707
- fs15.writeFileSync(file, markdown.endsWith("\n") ? markdown : markdown + "\n", "utf8");
25993
+ fs16.writeFileSync(file, markdown.endsWith("\n") ? markdown : markdown + "\n", "utf8");
25708
25994
  return file;
25709
25995
  }
25710
25996
 
@@ -25864,7 +26150,7 @@ function isInside(parent, child) {
25864
26150
  }
25865
26151
  function resolvesAsNamed(base, p) {
25866
26152
  try {
25867
- return fs16.realpathSync(p) === path38.join(fs16.realpathSync(base), path38.relative(base, p));
26153
+ return fs17.realpathSync(p) === path38.join(fs17.realpathSync(base), path38.relative(base, p));
25868
26154
  } catch {
25869
26155
  return false;
25870
26156
  }
@@ -25958,7 +26244,7 @@ function settleStatus(record, status) {
25958
26244
  }
25959
26245
  function realDir(p) {
25960
26246
  try {
25961
- return fs16.realpathSync.native(p);
26247
+ return fs17.realpathSync.native(p);
25962
26248
  } catch {
25963
26249
  return path38.resolve(p);
25964
26250
  }
@@ -25968,7 +26254,7 @@ function sameDir(a, b) {
25968
26254
  }
25969
26255
  function resolves(target) {
25970
26256
  try {
25971
- fs16.statSync(target);
26257
+ fs17.statSync(target);
25972
26258
  return true;
25973
26259
  } catch {
25974
26260
  return false;
@@ -25988,7 +26274,7 @@ function leftoverLinks(dir) {
25988
26274
  }
25989
26275
  function isLink(target) {
25990
26276
  try {
25991
- return fs16.lstatSync(target).isSymbolicLink();
26277
+ return fs17.lstatSync(target).isSymbolicLink();
25992
26278
  } catch {
25993
26279
  return false;
25994
26280
  }
@@ -26200,7 +26486,7 @@ var GitWorktreeIsolation = class {
26200
26486
  async acceptsWorktree(run, repo) {
26201
26487
  const dir = this.integrationDir(run, repo);
26202
26488
  ensureStateDirIgnored(stateRootOf(run));
26203
- fs16.mkdirSync(path38.dirname(dir), { recursive: true });
26489
+ fs17.mkdirSync(path38.dirname(dir), { recursive: true });
26204
26490
  const added = await this.tryGit(repo.root, ["worktree", "add", "-q", "--no-checkout", dir, repo.integrationBranch]);
26205
26491
  await this.removeWorktreeDir(run, repo, dir, []);
26206
26492
  return added.ok;
@@ -26268,7 +26554,7 @@ var GitWorktreeIsolation = class {
26268
26554
  for (const repo of run.repos) {
26269
26555
  const worktree = path38.join(dir, repo.path);
26270
26556
  const tip = (await this.git(repo.root, ["rev-parse", repo.integrationBranch])).trim();
26271
- fs16.mkdirSync(path38.dirname(worktree), { recursive: true });
26557
+ fs17.mkdirSync(path38.dirname(worktree), { recursive: true });
26272
26558
  await this.git(repo.root, ["worktree", "add", "-q", "-B", branch, worktree, tip]);
26273
26559
  record.repos[repo.path] = { worktree, linked: [], baseRef: tip };
26274
26560
  }
@@ -26300,7 +26586,7 @@ var GitWorktreeIsolation = class {
26300
26586
  const source = path38.join(run.workspaceRoot, rel);
26301
26587
  const target = path38.join(cwd, rel);
26302
26588
  if (!resolves(source) || lexists(target)) continue;
26303
- fs16.mkdirSync(path38.dirname(target), { recursive: true });
26589
+ fs17.mkdirSync(path38.dirname(target), { recursive: true });
26304
26590
  if (linkPath(source, target, this.platform) === "copy") copied.push(rel);
26305
26591
  const entry = self ? record.repos[SELF_REPO] : void 0;
26306
26592
  if (entry) entry.linked.push(rel);
@@ -26353,7 +26639,7 @@ var GitWorktreeIsolation = class {
26353
26639
  }
26354
26640
  const base = { branch: names2.branch, name: path38.basename(names2.dir), title: task2.title };
26355
26641
  for (const worktree of at) {
26356
- if (!fs16.existsSync(worktree)) continue;
26642
+ if (!fs17.existsSync(worktree)) continue;
26357
26643
  const linked = leftoverLinks(path38.join(worktree, await this.prefixOf(repo)));
26358
26644
  found.push({ repo, worktree, target: { ...base, worktree, linked } });
26359
26645
  }
@@ -26372,7 +26658,7 @@ var GitWorktreeIsolation = class {
26372
26658
  if (target.worktree) await this.removeWorktreeDir(run, repo, worktree, target.linked);
26373
26659
  }
26374
26660
  for (const repo of run.repos) await this.tryGit(repo.root, ["branch", "-D", names2.branch]);
26375
- this.removeTaskWorkspace(run, names2.dir);
26661
+ await this.removeTaskWorkspace(run, names2.dir);
26376
26662
  return removal;
26377
26663
  }
26378
26664
  async restorePrevious(record, preserved) {
@@ -26402,7 +26688,7 @@ var GitWorktreeIsolation = class {
26402
26688
  for (const repo of run.repos) {
26403
26689
  const entry = record.repos[repo.path];
26404
26690
  if (!entry) continue;
26405
- if (!fs16.existsSync(entry.worktree)) throw new Error(`The worktree of task ${task2.order} is gone: ${entry.worktree}`);
26691
+ if (!fs17.existsSync(entry.worktree)) throw new Error(`The worktree of task ${task2.order} is gone: ${entry.worktree}`);
26406
26692
  if (repo.path === SELF_REPO) cwd = await this.inWorkspacePlace(repo, entry.worktree);
26407
26693
  if (entry.changed || repo.path === record.conflictRepo) {
26408
26694
  repairBase[repo.path] = (await this.git(repo.root, ["rev-parse", "--verify", repo.integrationBranch])).trim();
@@ -26551,7 +26837,7 @@ var GitWorktreeIsolation = class {
26551
26837
  * out of sync, and deleting it is the one action that cannot be undone.
26552
26838
  */
26553
26839
  async worktreeHasChanges(entry, prefix) {
26554
- if (!fs16.existsSync(entry.worktree)) return false;
26840
+ if (!fs17.existsSync(entry.worktree)) return false;
26555
26841
  const status = await this.tryGit(entry.worktree, ["status", "--porcelain", "-z", "--untracked-files=normal"]);
26556
26842
  if (!status.ok) return true;
26557
26843
  const linked = new Set(entry.linked);
@@ -26957,7 +27243,7 @@ var GitWorktreeIsolation = class {
26957
27243
  for (const repo of run.repos) {
26958
27244
  const entry = record.repos[repo.path];
26959
27245
  if (!entry) continue;
26960
- if (!fs16.existsSync(entry.worktree)) {
27246
+ if (!fs17.existsSync(entry.worktree)) {
26961
27247
  return this.stopLanding(record, "failed", repo, void 0, `its worktree is gone (${entry.worktree})`);
26962
27248
  }
26963
27249
  try {
@@ -27207,7 +27493,7 @@ var GitWorktreeIsolation = class {
27207
27493
  const ref2 = `refs/heads/${repo.integrationBranch}`;
27208
27494
  if (!(await this.tryGit(repo.root, ["update-ref", ref2, made, onto])).ok) return { strayed: true };
27209
27495
  const dir = this.integrationDir(run, repo);
27210
- if (!fs16.existsSync(path38.join(dir, ".git"))) return { onto: made };
27496
+ if (!fs17.existsSync(path38.join(dir, ".git"))) return { onto: made };
27211
27497
  const read2 = await this.readAcross(dir, onto, made);
27212
27498
  if (read2.ok) return { onto: made };
27213
27499
  if (!(await this.tryGit(repo.root, ["update-ref", ref2, onto, made])).ok) return { strayed: true };
@@ -27312,7 +27598,7 @@ var GitWorktreeIsolation = class {
27312
27598
  if (!await (reverts ? this.isRevertsOn(repo, head, tip, reverts) : this.isOneMergeOn(repo, head, tip))) return false;
27313
27599
  const dir = this.integrationDir(run, repo);
27314
27600
  const held2 = await this.worktreeHolding(repo, repo.integrationBranch);
27315
- if (!held2 && (!fs16.existsSync(path38.join(dir, ".git")) || await this.integrationOffBranch(run, repo))) return false;
27601
+ if (!held2 && (!fs17.existsSync(path38.join(dir, ".git")) || await this.integrationOffBranch(run, repo))) return false;
27316
27602
  const holder = held2 ? held2.worktree : dir;
27317
27603
  if (holder === null) return (await this.tryGit(repo.root, ["update-ref", `refs/heads/${repo.integrationBranch}`, tip, head])).ok;
27318
27604
  if (!sameDir(holder, dir)) return false;
@@ -27367,7 +27653,7 @@ var GitWorktreeIsolation = class {
27367
27653
  */
27368
27654
  async integrationOffBranch(run, repo) {
27369
27655
  const dir = this.integrationDir(run, repo);
27370
- if (!fs16.existsSync(path38.join(dir, ".git"))) return null;
27656
+ if (!fs17.existsSync(path38.join(dir, ".git"))) return null;
27371
27657
  const head = (await this.tryGit(dir, ["symbolic-ref", "-q", "HEAD"])).stdout.trim();
27372
27658
  if (head === `refs/heads/${repo.integrationBranch}`) return null;
27373
27659
  return `${head ? `on ${head.replace(/^refs\/heads\//, "")}` : "detached"}, not on ${repo.integrationBranch}`;
@@ -27378,7 +27664,7 @@ var GitWorktreeIsolation = class {
27378
27664
  if (!listed4.ok) return null;
27379
27665
  let worktree = null;
27380
27666
  for (const line of listed4.stdout.split(/\r?\n/)) {
27381
- if (line.startsWith("worktree ")) worktree = line.slice("worktree ".length);
27667
+ if (line.startsWith("worktree ")) worktree = path38.normalize(line.slice("worktree ".length));
27382
27668
  else if (line === `branch refs/heads/${branch}`) return { worktree };
27383
27669
  }
27384
27670
  return { worktree: null };
@@ -27395,12 +27681,58 @@ var GitWorktreeIsolation = class {
27395
27681
  if ((await this.tryGit(entry.worktree, ["check-ignore", "-q", "--", prefix + name])).ok) continue;
27396
27682
  excludes.push(`:(exclude,literal)${(prefix + name).replace(/\\/g, "/")}`);
27397
27683
  }
27684
+ if (this.platform === "win32") {
27685
+ const made = entry.linked.map((name) => (prefix + name).replace(/\\/g, "/"));
27686
+ const under = (link) => made.some((dir) => link === dir || link.startsWith(`${dir}/`));
27687
+ for (const link of await this.linksGitWalksInto(entry.worktree)) {
27688
+ if (!under(link)) excludes.push(`:(exclude,literal)${link}`);
27689
+ }
27690
+ }
27398
27691
  await this.git(entry.worktree, ["add", "-A", "--", ".", ...excludes]);
27399
27692
  const staged = await this.tryGit(entry.worktree, ["diff", "--cached", "--quiet"]);
27400
27693
  if (staged.ok) return;
27401
27694
  const commit = opts.rescue ? ["-c", "commit.gpgsign=false", "commit", "--no-verify"] : ["commit"];
27402
27695
  await this.git(entry.worktree, [...VERBATIM, ...commit, "-q", ...messageArgs(message)]);
27403
27696
  }
27697
+ /**
27698
+ * The links git would walk into when it stages `worktree`: on Windows a
27699
+ * junction reads to git as the directory it leads to, so staging one a task
27700
+ * left commits what it holds, a folder of the user's as readily as anything.
27701
+ * A symbolic link git stages as a link, as it does elsewhere, and keeps. Read
27702
+ * from git's own listing, one call, so what git ignores, a mirrored install
27703
+ * among it, is never walked; and a link is told by lstat, as Windows reports
27704
+ * every reparse point, a OneDrive placeholder too, as a link in a directory
27705
+ * listing.
27706
+ */
27707
+ async linksGitWalksInto(worktree) {
27708
+ const listed4 = await this.tryGit(worktree, ["status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all"]);
27709
+ if (!listed4.ok) throw new Error(`git could not list what the worktree holds: ${firstLine3(listed4.stderr.trim() || `exit ${listed4.code}`)}`);
27710
+ const isLink2 = /* @__PURE__ */ new Map();
27711
+ const linkAt = (rel) => {
27712
+ let link = isLink2.get(rel);
27713
+ if (link === void 0) {
27714
+ try {
27715
+ link = fs17.lstatSync(path38.join(worktree, rel)).isSymbolicLink();
27716
+ } catch {
27717
+ link = false;
27718
+ }
27719
+ isLink2.set(rel, link);
27720
+ }
27721
+ return link;
27722
+ };
27723
+ const found = /* @__PURE__ */ new Set();
27724
+ for (const entry of listed4.stdout.split("\0")) {
27725
+ const parts = entry.slice(3).split("/");
27726
+ for (let depth = 1; depth < parts.length; depth++) {
27727
+ const dir = parts.slice(0, depth).join("/");
27728
+ if (linkAt(dir)) {
27729
+ found.add(dir);
27730
+ break;
27731
+ }
27732
+ }
27733
+ }
27734
+ return [...found];
27735
+ }
27404
27736
  /** A message Ordewell writes, with the trailer if the user's setting says so right now. */
27405
27737
  message(kind, from) {
27406
27738
  return landingMessage(kind, from, this.deps.plannedWith?.() ?? false);
@@ -27411,10 +27743,10 @@ var GitWorktreeIsolation = class {
27411
27743
  async ensureIntegrationWorktree(run, repo) {
27412
27744
  return this.admin(stateRootOf(run), async () => {
27413
27745
  const dir = this.integrationDir(run, repo);
27414
- if (fs16.existsSync(path38.join(dir, ".git"))) return dir;
27746
+ if (fs17.existsSync(path38.join(dir, ".git"))) return dir;
27415
27747
  await this.tryGit(repo.root, ["worktree", "prune"]);
27416
27748
  ensureStateDirIgnored(stateRootOf(run));
27417
- fs16.mkdirSync(path38.dirname(dir), { recursive: true });
27749
+ fs17.mkdirSync(path38.dirname(dir), { recursive: true });
27418
27750
  await this.git(repo.root, ["worktree", "add", "-q", dir, repo.integrationBranch]);
27419
27751
  return dir;
27420
27752
  });
@@ -27451,7 +27783,7 @@ var GitWorktreeIsolation = class {
27451
27783
  if (entry) await this.removeWorktreeDir(run, repo, entry.worktree, entry.linked);
27452
27784
  await this.tryGit(repo.root, ["branch", "-D", record.branch]);
27453
27785
  }
27454
- this.removeTaskWorkspace(run, record.workspace);
27786
+ await this.removeTaskWorkspace(run, record.workspace);
27455
27787
  if (opts.dropRecord) delete run.tasks[record.taskId];
27456
27788
  return removal;
27457
27789
  }
@@ -27475,7 +27807,7 @@ var GitWorktreeIsolation = class {
27475
27807
  }
27476
27808
  async tipToKeep(repo, target) {
27477
27809
  const { worktree } = target;
27478
- if (worktree && fs16.existsSync(worktree)) {
27810
+ if (worktree && fs17.existsSync(worktree)) {
27479
27811
  if (!hasGitEntry(worktree)) throw new Error("it is not a git worktree any more");
27480
27812
  if (await this.worktreeHasChanges({ worktree, linked: target.linked }, await this.prefixOf(repo))) {
27481
27813
  await this.commitWorktree(repo, { worktree, linked: target.linked }, this.message("rescue", target), { rescue: true });
@@ -27505,23 +27837,40 @@ var GitWorktreeIsolation = class {
27505
27837
  * links and the directories that held deeper repos. Links are unlinked
27506
27838
  * first, so removing the rest can never walk into the real workspace.
27507
27839
  */
27508
- removeTaskWorkspace(run, dir) {
27509
- if (!isInside(this.runRoot(run), dir) || !fs16.existsSync(dir)) return;
27840
+ async removeTaskWorkspace(run, dir) {
27841
+ if (!isInside(this.runRoot(run), dir) || !fs17.existsSync(dir)) return;
27510
27842
  this.unlinkLinksUnder(dir);
27511
27843
  clearImmutableFlags(this.platform, dir);
27512
- fs16.rmSync(dir, { recursive: true, force: true });
27844
+ await this.removeDir(dir);
27845
+ }
27846
+ /**
27847
+ * Windows removes no directory a process works in, and a runner stopped
27848
+ * there a moment ago may still be going: taskkill ends it from another
27849
+ * process. So there the removal waits for it, a while, before it gives up.
27850
+ */
27851
+ async removeDir(dir) {
27852
+ if (this.platform === "win32") await fs17.promises.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
27853
+ else fs17.rmSync(dir, { recursive: true, force: true });
27513
27854
  }
27514
27855
  unlinkLinksUnder(dir) {
27515
27856
  let entries;
27516
27857
  try {
27517
- entries = fs16.readdirSync(dir, { withFileTypes: true });
27858
+ entries = fs17.readdirSync(dir, { withFileTypes: true });
27518
27859
  } catch {
27519
27860
  return;
27520
27861
  }
27521
27862
  for (const entry of entries) {
27522
27863
  const target = path38.join(dir, entry.name);
27523
- if (entry.isSymbolicLink()) this.unlinkIfLink(target);
27524
- else if (entry.isDirectory()) this.unlinkLinksUnder(target);
27864
+ if (entry.isDirectory()) this.unlinkLinksUnder(target);
27865
+ else if (entry.isSymbolicLink()) {
27866
+ let stat;
27867
+ try {
27868
+ stat = fs17.lstatSync(target);
27869
+ } catch {
27870
+ }
27871
+ if (stat?.isSymbolicLink()) this.unlinkIfLink(target);
27872
+ else if (stat?.isDirectory()) this.unlinkLinksUnder(target);
27873
+ }
27525
27874
  }
27526
27875
  }
27527
27876
  /**
@@ -27543,8 +27892,8 @@ var GitWorktreeIsolation = class {
27543
27892
  };
27544
27893
  const owned = new Set(Object.values(run.tasks).map((r) => path38.resolve(r.workspace)));
27545
27894
  const root = this.runRoot(run);
27546
- if (fs16.existsSync(root)) {
27547
- for (const entry of fs16.readdirSync(root)) {
27895
+ if (fs17.existsSync(root)) {
27896
+ for (const entry of fs17.readdirSync(root)) {
27548
27897
  const dir = path38.join(root, entry);
27549
27898
  if (entry === INTEGRATION_DIR || owned.has(path38.resolve(dir))) continue;
27550
27899
  let kept = true;
@@ -27555,7 +27904,7 @@ var GitWorktreeIsolation = class {
27555
27904
  }
27556
27905
  if (!kept) continue;
27557
27906
  for (const repo of run.repos) await this.removeWorktreeDir(run, repo, path38.join(dir, repo.path), []);
27558
- this.removeTaskWorkspace(run, dir);
27907
+ await this.removeTaskWorkspace(run, dir);
27559
27908
  }
27560
27909
  }
27561
27910
  const taskBranches = Object.values(run.tasks).map((r) => r.branch);
@@ -27571,32 +27920,36 @@ var GitWorktreeIsolation = class {
27571
27920
  return removal;
27572
27921
  }
27573
27922
  async removeWorktreeDir(run, repo, dir, linked) {
27574
- for (const name of /* @__PURE__ */ new Set([...linked, ...installDirs(dir)])) {
27575
- const target = path38.join(dir, name);
27576
- if (!resolvesAsNamed(this.runRoot(run), path38.dirname(target))) continue;
27577
- this.unlinkIfLink(target);
27578
- this.unlinkLinksUnder(target);
27579
- }
27580
- for (const name of resolvesAsNamed(this.runRoot(run), dir) ? fs16.readdirSync(dir) : []) {
27581
- if (LINKED_ARTIFACTS.has(name) || isEnvFile(name)) this.unlinkIfLink(path38.join(dir, name));
27923
+ const prefix = (await this.tryGit(repo.root, ["rev-parse", "--show-prefix"])).stdout.trim();
27924
+ for (const base of /* @__PURE__ */ new Set([dir, path38.join(dir, prefix)])) {
27925
+ for (const name of /* @__PURE__ */ new Set([...linked, ...installDirs(base)])) {
27926
+ const target = path38.join(base, name);
27927
+ if (!resolvesAsNamed(this.runRoot(run), path38.dirname(target))) continue;
27928
+ this.unlinkIfLink(target);
27929
+ this.unlinkLinksUnder(target);
27930
+ }
27931
+ for (const name of resolvesAsNamed(this.runRoot(run), base) ? fs17.readdirSync(base) : []) {
27932
+ if (LINKED_ARTIFACTS.has(name) || isEnvFile(name)) this.unlinkIfLink(path38.join(base, name));
27933
+ }
27582
27934
  }
27935
+ if (this.platform === "win32" && resolvesAsNamed(this.runRoot(run), dir)) this.unlinkLinksUnder(dir);
27583
27936
  await this.tryGit(repo.root, ["worktree", "remove", "--force", dir]);
27584
- if (fs16.existsSync(dir) && isInside(this.runRoot(run), dir)) {
27937
+ if (fs17.existsSync(dir) && isInside(this.runRoot(run), dir)) {
27585
27938
  clearImmutableFlags(this.platform, dir);
27586
- fs16.rmSync(dir, { recursive: true, force: true });
27939
+ await this.removeDir(dir);
27587
27940
  }
27588
27941
  await this.tryGit(repo.root, ["worktree", "prune"]);
27589
27942
  for (let parent = path38.dirname(dir); isInside(this.runRoot(run), parent); parent = path38.dirname(parent)) this.removeIfEmpty(parent);
27590
27943
  }
27591
27944
  unlinkIfLink(target) {
27592
27945
  try {
27593
- if (fs16.lstatSync(target).isSymbolicLink()) fs16.rmSync(target, { force: true });
27946
+ if (fs17.lstatSync(target).isSymbolicLink()) fs17.rmSync(target, { force: true });
27594
27947
  } catch {
27595
27948
  }
27596
27949
  }
27597
27950
  removeIfEmpty(dir) {
27598
27951
  try {
27599
- fs16.rmdirSync(dir);
27952
+ fs17.rmdirSync(dir);
27600
27953
  } catch {
27601
27954
  }
27602
27955
  }
@@ -27623,7 +27976,7 @@ var GitWorktreeIsolation = class {
27623
27976
  async rebaseInProgress(cwd) {
27624
27977
  for (const dir of ["rebase-merge", "rebase-apply"]) {
27625
27978
  const found = await this.tryGit(cwd, ["rev-parse", "--git-path", dir]);
27626
- if (found.ok && fs16.existsSync(path38.resolve(cwd, found.stdout.trim()))) return true;
27979
+ if (found.ok && fs17.existsSync(path38.resolve(cwd, found.stdout.trim()))) return true;
27627
27980
  }
27628
27981
  return false;
27629
27982
  }
@@ -27654,7 +28007,7 @@ function createWorktreeIsolation(deps) {
27654
28007
  }
27655
28008
 
27656
28009
  // src/utils/sessionStore.ts
27657
- import * as fs17 from "fs";
28010
+ import * as fs18 from "fs";
27658
28011
  import * as path39 from "path";
27659
28012
 
27660
28013
  // src/interfaces/ILogger.ts
@@ -27708,7 +28061,7 @@ var NO_RESEARCH_LOG = [];
27708
28061
  var writtenLogs = /* @__PURE__ */ new Map();
27709
28062
  function saveResearchLog(log, file) {
27710
28063
  const written = writtenLogs.get(file);
27711
- const unchanged = fs17.existsSync(file) ? written?.log.deref() === log && written.length === log.length : log.length === 0;
28064
+ const unchanged = fs18.existsSync(file) ? written?.log.deref() === log && written.length === log.length : log.length === 0;
27712
28065
  if (unchanged) return;
27713
28066
  writeFileAtomic(file, JSON.stringify(log));
27714
28067
  writtenLogs.set(file, { log: new WeakRef(log), length: log.length });
@@ -27716,7 +28069,7 @@ function saveResearchLog(log, file) {
27716
28069
  function restoreResearchLog(plan, sessionId, file, logger) {
27717
28070
  if (plan.researchLog) return;
27718
28071
  try {
27719
- plan.researchLog = JSON.parse(fs17.readFileSync(file, "utf-8"));
28072
+ plan.researchLog = JSON.parse(fs18.readFileSync(file, "utf-8"));
27720
28073
  } catch (err) {
27721
28074
  if (err.code !== "ENOENT") logger.warn("sessionStore", `failed to read the research log of ${sessionId}; going on without it`, err);
27722
28075
  }
@@ -27747,10 +28100,10 @@ function legacySessionFilename(session) {
27747
28100
  }
27748
28101
  function dropLegacyFile(sessionsDir, meta) {
27749
28102
  const legacy = path39.join(sessionsDir, legacySessionFilename(meta));
27750
- if (legacy === path39.join(sessionsDir, sessionFilename(meta)) || !fs17.existsSync(legacy)) return;
28103
+ if (legacy === path39.join(sessionsDir, sessionFilename(meta)) || !fs18.existsSync(legacy)) return;
27751
28104
  try {
27752
- const held2 = JSON.parse(fs17.readFileSync(legacy, "utf-8")).meta?.id;
27753
- if (held2 === meta.id) fs17.unlinkSync(legacy);
28105
+ const held2 = JSON.parse(fs18.readFileSync(legacy, "utf-8")).meta?.id;
28106
+ if (held2 === meta.id) fs18.unlinkSync(legacy);
27754
28107
  } catch {
27755
28108
  }
27756
28109
  }
@@ -27792,7 +28145,7 @@ function listChildSessions(rootSessionId, baseDir) {
27792
28145
  const dir = childSessionsDir(rootSessionId, baseDir);
27793
28146
  const named3 = (entry) => {
27794
28147
  try {
27795
- const session = JSON.parse(fs17.readFileSync(path39.join(dir, entry, CHILD_SESSION_FILE), "utf-8"));
28148
+ const session = JSON.parse(fs18.readFileSync(path39.join(dir, entry, CHILD_SESSION_FILE), "utf-8"));
27796
28149
  return isSessionMeta(session.meta) ? session.meta.id : null;
27797
28150
  } catch {
27798
28151
  return null;
@@ -27800,7 +28153,7 @@ function listChildSessions(rootSessionId, baseDir) {
27800
28153
  };
27801
28154
  let entries;
27802
28155
  try {
27803
- entries = fs17.readdirSync(dir);
28156
+ entries = fs18.readdirSync(dir);
27804
28157
  } catch {
27805
28158
  return [];
27806
28159
  }
@@ -27808,12 +28161,12 @@ function listChildSessions(rootSessionId, baseDir) {
27808
28161
  }
27809
28162
  function listSessions(baseDir, logger = defaultLogger) {
27810
28163
  const sessionsDir = getSessionsDir(baseDir);
27811
- if (!fs17.existsSync(sessionsDir)) return [];
27812
- const files = fs17.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
28164
+ if (!fs18.existsSync(sessionsDir)) return [];
28165
+ const files = fs18.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
27813
28166
  return files.map((f) => {
27814
28167
  let parsed;
27815
28168
  try {
27816
- parsed = JSON.parse(fs17.readFileSync(path39.join(sessionsDir, f), "utf-8"));
28169
+ parsed = JSON.parse(fs18.readFileSync(path39.join(sessionsDir, f), "utf-8"));
27817
28170
  } catch (err) {
27818
28171
  if (err instanceof SyntaxError) return moveAside(sessionsDir, f, "is not valid JSON", logger);
27819
28172
  logger.warn("sessionStore", `failed to read session file ${f}; skipping`, err);
@@ -27834,7 +28187,7 @@ function listSessions(baseDir, logger = defaultLogger) {
27834
28187
  function moveAside(sessionsDir, file, reason, logger) {
27835
28188
  const aside = `${file}.${Date.now()}.corrupt`;
27836
28189
  try {
27837
- fs17.renameSync(path39.join(sessionsDir, file), path39.join(sessionsDir, aside));
28190
+ fs18.renameSync(path39.join(sessionsDir, file), path39.join(sessionsDir, aside));
27838
28191
  logger.warn("sessionStore", `session file ${file} ${reason}; moved aside to ${aside} rather than overwritten`);
27839
28192
  } catch {
27840
28193
  logger.warn("sessionStore", `failed to read session file ${file}; skipping`);
@@ -27843,12 +28196,12 @@ function moveAside(sessionsDir, file, reason, logger) {
27843
28196
  }
27844
28197
  var filenameEndings = (sessionId) => [sessionId.replace(/^session-/, ""), sessionId].map((id2) => `_${id2.slice(0, 8)}.json`);
27845
28198
  function findSessionFile(sessionsDir, sessionId, logger) {
27846
- const files = fs17.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
28199
+ const files = fs18.readdirSync(sessionsDir).filter((f) => f.endsWith(".json"));
27847
28200
  const endings = filenameEndings(sessionId);
27848
28201
  const named3 = files.filter((f) => endings.some((ending) => f.endsWith(ending)));
27849
28202
  for (const file of /* @__PURE__ */ new Set([...named3, ...files])) {
27850
28203
  try {
27851
- const session = JSON.parse(fs17.readFileSync(path39.join(sessionsDir, file), "utf-8"));
28204
+ const session = JSON.parse(fs18.readFileSync(path39.join(sessionsDir, file), "utf-8"));
27852
28205
  if (session.meta.id === sessionId) return { file, session };
27853
28206
  } catch (err) {
27854
28207
  logger.warn("sessionStore", `failed to read session file ${file}; skipping`, err);
@@ -27870,7 +28223,7 @@ function settledOnLoad(session, researchLog, logger) {
27870
28223
  function loadChildSession(place, logger = defaultLogger) {
27871
28224
  let parsed;
27872
28225
  try {
27873
- parsed = JSON.parse(fs17.readFileSync(childSessionPath(place), "utf-8"));
28226
+ parsed = JSON.parse(fs18.readFileSync(childSessionPath(place), "utf-8"));
27874
28227
  } catch (err) {
27875
28228
  if (err.code !== "ENOENT") logger.warn("sessionStore", `failed to read child session ${place.sessionId}`, err);
27876
28229
  return null;
@@ -27880,7 +28233,7 @@ function loadChildSession(place, logger = defaultLogger) {
27880
28233
  }
27881
28234
  function loadSession(sessionId, baseDir, logger = defaultLogger) {
27882
28235
  const sessionsDir = getSessionsDir(baseDir);
27883
- if (!fs17.existsSync(sessionsDir)) return null;
28236
+ if (!fs18.existsSync(sessionsDir)) return null;
27884
28237
  try {
27885
28238
  const found = findSessionFile(sessionsDir, sessionId, logger);
27886
28239
  if (found) {
@@ -27907,16 +28260,16 @@ function getLatestSession(baseDir, logger = defaultLogger) {
27907
28260
  }
27908
28261
  function deleteSession(sessionId, baseDir, logger = defaultLogger) {
27909
28262
  const sessionsDir = getSessionsDir(baseDir);
27910
- if (!fs17.existsSync(sessionsDir)) return false;
28263
+ if (!fs18.existsSync(sessionsDir)) return false;
27911
28264
  try {
27912
- fs17.rmSync(sessionDataDir(sessionId, baseDir), { recursive: true, force: true });
28265
+ fs18.rmSync(sessionDataDir(sessionId, baseDir), { recursive: true, force: true });
27913
28266
  } catch (err) {
27914
28267
  logger.warn("sessionStore", `failed to remove the task logs of ${sessionId}`, err);
27915
28268
  }
27916
28269
  try {
27917
28270
  const found = findSessionFile(sessionsDir, sessionId, logger);
27918
28271
  if (found) {
27919
- fs17.unlinkSync(path39.join(sessionsDir, found.file));
28272
+ fs18.unlinkSync(path39.join(sessionsDir, found.file));
27920
28273
  return true;
27921
28274
  }
27922
28275
  } catch (err) {
@@ -27976,8 +28329,8 @@ import { v4 as uuidv43 } from "uuid";
27976
28329
 
27977
28330
  // src/services/ContextCollector.ts
27978
28331
  var ORDEWELL_CONTEXT_MAX = 8e3;
27979
- async function collectResearchContext(fs28, runners) {
27980
- const collector = new ContextCollector(fs28);
28332
+ async function collectResearchContext(fs29, runners) {
28333
+ const collector = new ContextCollector(fs29);
27981
28334
  let contextStr = "";
27982
28335
  let firstContext = null;
27983
28336
  for (const r of runners) {
@@ -28004,8 +28357,8 @@ ${firstContext.dirStructure}
28004
28357
  return contextStr;
28005
28358
  }
28006
28359
  var ContextCollector = class {
28007
- constructor(fs28, registry) {
28008
- this.fs = fs28;
28360
+ constructor(fs29, registry) {
28361
+ this.fs = fs29;
28009
28362
  this.registry = registry;
28010
28363
  }
28011
28364
  fs;
@@ -28053,28 +28406,29 @@ var ALLOWED_TOOL_NAMES = new Set(subagentToolSpecs().map((t) => t.name));
28053
28406
  function refused2(output) {
28054
28407
  return { success: false, output, truncated: false };
28055
28408
  }
28056
- function nonPromptingFs(fs28) {
28057
- const withinWorkspace = (p) => resolveWithin(fs28.getWorkspaceRoot(), p ?? ".").inside;
28409
+ function nonPromptingFs(fs29) {
28410
+ const withinWorkspace = (p) => resolveWithin(fs29.getWorkspaceRoot(), p ?? ".").inside;
28058
28411
  const outsideRefusal = (p) => refused2(
28059
28412
  `Path "${p}" is outside the workspace. Research agents are confined to the workspace root \u2014 note the gap in your digest and let the planner request it directly.`
28060
28413
  );
28061
28414
  return {
28062
- getWorkspaceRoot: () => fs28.getWorkspaceRoot(),
28063
- readFile: (p, opts) => withinWorkspace(p) ? fs28.readFile(p, opts) : Promise.resolve(outsideRefusal(p)),
28415
+ getWorkspaceRoot: () => fs29.getWorkspaceRoot(),
28416
+ readFile: (p, opts) => withinWorkspace(p) ? fs29.readFile(p, opts) : Promise.resolve(outsideRefusal(p)),
28064
28417
  readFiles: (paths) => {
28065
28418
  const escaping = paths.find((p) => !withinWorkspace(p));
28066
- return escaping ? Promise.resolve(outsideRefusal(escaping)) : fs28.readFiles(paths);
28419
+ return escaping ? Promise.resolve(outsideRefusal(escaping)) : fs29.readFiles(paths);
28067
28420
  },
28068
- glob: (pattern, opts) => withinWorkspace(opts?.path) ? fs28.glob(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
28069
- grep: (pattern, opts) => withinWorkspace(opts?.path) ? fs28.grep(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
28070
- findSymbol: (symbol, opts) => withinWorkspace(opts?.path) ? fs28.findSymbol(symbol, opts) : Promise.resolve(outsideRefusal(opts.path)),
28071
- listDir: (p, depth) => withinWorkspace(p) ? fs28.listDir(p, depth) : Promise.resolve(outsideRefusal(p)),
28421
+ glob: (pattern, opts) => withinWorkspace(opts?.path) ? fs29.glob(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
28422
+ grep: (pattern, opts) => withinWorkspace(opts?.path) ? fs29.grep(pattern, opts) : Promise.resolve(outsideRefusal(opts.path)),
28423
+ findSymbol: (symbol, opts) => withinWorkspace(opts?.path) ? fs29.findSymbol(symbol, opts) : Promise.resolve(outsideRefusal(opts.path)),
28424
+ listDir: (p, depth) => withinWorkspace(p) ? fs29.listDir(p, depth) : Promise.resolve(outsideRefusal(p)),
28072
28425
  bash: async (command, signal, opts) => {
28073
- const policy = researchPolicyOptions(resolveResearchShell());
28426
+ const shell = resolveResearchShell();
28427
+ const policy = researchPolicyOptions(shell);
28074
28428
  const { tier, reason } = classifyCommand(command, policy);
28075
- const escaping = pathRefs(command, policy).map((ref2) => resolveRef(fs28.getWorkspaceRoot(), ref2)).find((r) => !r.inside);
28076
- if (tier === "auto" && !escaping && !opts?.sealed) return fs28.bash(command, signal);
28077
- if (opts?.sealed || await fs28.canSeal?.()) return fs28.bash(command, signal, { sealed: true });
28429
+ const escaping = pathRefs(command, policy).map((ref2) => resolveRef(fs29.getWorkspaceRoot(), ref2, shell.hostPath)).find((r) => !r.inside);
28430
+ if (tier === "auto" && !escaping && !opts?.sealed) return fs29.bash(command, signal);
28431
+ if (opts?.sealed || await fs29.canSeal?.()) return fs29.bash(command, signal, { sealed: true });
28078
28432
  if (tier === "refuse") return refused2(`Command refused: ${reason}`);
28079
28433
  if (tier === "auto" && escaping) return outsideRefusal(escaping.abs);
28080
28434
  return refused2(`"${command}" needs user approval, and research agents run in the background where nothing can be approved. Use the read-only research tools, and note in your digest that this command would answer the question.`);
@@ -28086,7 +28440,7 @@ function withoutContext({ contextTokens: _context, ...record }) {
28086
28440
  }
28087
28441
  async function runLoop(prompt, deps) {
28088
28442
  if (deps.signal?.aborted) return "[research agent aborted before starting]";
28089
- const fs28 = nonPromptingFs(deps.fs);
28443
+ const fs29 = nonPromptingFs(deps.fs);
28090
28444
  const chat = deps.createChat(
28091
28445
  (delta) => deps.onProgress?.({ type: "thinking", text: delta, subagentId: deps.subagentId }),
28092
28446
  // The record says who made the call: unstamped, the ledger would read the
@@ -28109,7 +28463,7 @@ ${turn.text}`;
28109
28463
  if (tc.name === "read_file" && !("maxBytes" in args) && !("limit" in args)) args.limit = 2e3;
28110
28464
  const toolArgs = JSON.stringify(tc.args);
28111
28465
  deps.onProgress?.({ type: "tool_call", tool: tc.name, toolArgs, toolCallId: tc.id, subagentId: deps.subagentId });
28112
- const res = await executeTool(tc.name, args, fs28, deps.fetcher, deps.signal);
28466
+ const res = await executeTool(tc.name, args, fs29, deps.fetcher, deps.signal);
28113
28467
  const output = res.output.length > SUBAGENT_LIMITS.toolOutputMaxChars ? res.output.slice(0, SUBAGENT_LIMITS.toolOutputMaxChars) + `
28114
28468
  [... truncated to ${SUBAGENT_LIMITS.toolOutputMaxChars} chars, total ${res.output.length}]` : res.output;
28115
28469
  const stepEntry = {
@@ -28317,7 +28671,7 @@ var BaseAiService = class _BaseAiService {
28317
28671
  * steering/failed result and the loop continues sequentially: a subagent can
28318
28672
  * never fail a plan or a turn.
28319
28673
  */
28320
- async executeSpawnAgent(args, fs28, onProgress, signal, subagentId, fetcher) {
28674
+ async executeSpawnAgent(args, fs29, onProgress, signal, subagentId, fetcher) {
28321
28675
  const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
28322
28676
  if (!prompt) {
28323
28677
  return { success: false, output: 'spawn_research_agent requires a non-empty "prompt" string: a self-contained task for the agent, including what its digest must report back.', truncated: false };
@@ -28329,7 +28683,7 @@ var BaseAiService = class _BaseAiService {
28329
28683
  if (!chat) throw new Error("subagent chats are not available for this provider");
28330
28684
  return chat;
28331
28685
  },
28332
- fs: fs28,
28686
+ fs: fs29,
28333
28687
  signal,
28334
28688
  subagentId,
28335
28689
  // The subagent gets web tools only behind a non-prompting gate: no
@@ -28345,14 +28699,14 @@ var BaseAiService = class _BaseAiService {
28345
28699
  });
28346
28700
  }
28347
28701
  /** Collect project context for the planning phase. Shared with the harness backend. */
28348
- static async collectResearchContext(fs28, runners) {
28349
- return collectResearchContext(fs28, runners);
28702
+ static async collectResearchContext(fs29, runners) {
28703
+ return collectResearchContext(fs29, runners);
28350
28704
  }
28351
28705
  /**
28352
28706
  * Execute one round of tool calls and report each through onProgress.
28353
28707
  * Returns the results to feed back plus the log entries produced.
28354
28708
  */
28355
- async executeToolCalls(toolCalls, fs28, onProgress, fetcher, stepIndex, thinking, signal, plannerTools) {
28709
+ async executeToolCalls(toolCalls, fs29, onProgress, fetcher, stepIndex, thinking, signal, plannerTools) {
28356
28710
  const toolResults = [];
28357
28711
  const logEntries = [];
28358
28712
  let resultsText = "";
@@ -28373,12 +28727,12 @@ var BaseAiService = class _BaseAiService {
28373
28727
  spawnSubagentIds.set(i, subagentId);
28374
28728
  announcedAt.set(i, (/* @__PURE__ */ new Date()).toISOString());
28375
28729
  onProgress({ type: "tool_call", tool: toolCalls[i].name, toolArgs: JSON.stringify(toolCalls[i].args), subagentId, toolCallId: toolCalls[i].id });
28376
- precomputed.set(i, await this.executeSpawnAgent({ ...toolCalls[i].args }, fs28, onProgress, signal, subagentId, fetcher));
28730
+ precomputed.set(i, await this.executeSpawnAgent({ ...toolCalls[i].args }, fs29, onProgress, signal, subagentId, fetcher));
28377
28731
  }) : Promise.resolve(),
28378
28732
  parallelIndexes.length > 1 ? mapWithConcurrency(parallelIndexes, TOOL_ROUND_CONCURRENCY, async (i) => {
28379
28733
  announcedAt.set(i, (/* @__PURE__ */ new Date()).toISOString());
28380
28734
  onProgress({ type: "tool_call", tool: toolCalls[i].name, toolArgs: JSON.stringify(toolCalls[i].args), toolCallId: toolCalls[i].id });
28381
- precomputed.set(i, await executeTool(toolCalls[i].name, normalizedArgs[i], fs28, fetcher, signal));
28735
+ precomputed.set(i, await executeTool(toolCalls[i].name, normalizedArgs[i], fs29, fetcher, signal));
28382
28736
  }) : Promise.resolve()
28383
28737
  ]);
28384
28738
  for (const [index, tc] of toolCalls.entries()) {
@@ -28389,7 +28743,7 @@ var BaseAiService = class _BaseAiService {
28389
28743
  announcedAt.set(index, (/* @__PURE__ */ new Date()).toISOString());
28390
28744
  onProgress({ type: "tool_call", ...named3, toolArgs: JSON.stringify(tc.args), toolCallId: tc.id });
28391
28745
  }
28392
- const toolResult = preResult ?? await callPlannerTool(plannerTools, tc.name, toolArgs, signal) ?? await executeTool(tc.name, toolArgs, fs28, fetcher, signal);
28746
+ const toolResult = preResult ?? await callPlannerTool(plannerTools, tc.name, toolArgs, signal) ?? await executeTool(tc.name, toolArgs, fs29, fetcher, signal);
28393
28747
  const MAX_RESPONSE_CHARS = 5e4;
28394
28748
  const truncatedResponse = toolResult.success && (toolResult.truncated || toolResult.output.length > MAX_RESPONSE_CHARS);
28395
28749
  const llmOutput = toolResult.output.length > MAX_RESPONSE_CHARS ? toolResult.output.slice(0, MAX_RESPONSE_CHARS) + `
@@ -28562,7 +28916,7 @@ ${llmOutput}
28562
28916
  * parsed tasks if a plan was emitted mid-loop, or null if the loop
28563
28917
  * exhausted without a valid plan.
28564
28918
  */
28565
- async runResearchLoop(chat, firstMessage, fs28, onProgress, runners, initialLog, fetcher, userGoal, runnerModes, autonomousDefault, signal) {
28919
+ async runResearchLoop(chat, firstMessage, fs29, onProgress, runners, initialLog, fetcher, userGoal, runnerModes, autonomousDefault, signal) {
28566
28920
  const researchLog = initialLog ? [...initialLog] : [];
28567
28921
  if (!initialLog && userGoal) {
28568
28922
  researchLog.push({
@@ -28588,7 +28942,7 @@ ${llmOutput}
28588
28942
  if (!turn.hasToolCalls) break;
28589
28943
  const { toolResults, logEntries, resultsText } = await this.executeToolCalls(
28590
28944
  turn.toolCalls,
28591
- fs28,
28945
+ fs29,
28592
28946
  onProgress,
28593
28947
  fetcher,
28594
28948
  step,
@@ -28637,15 +28991,15 @@ import {
28637
28991
  import { execFile as execFile5 } from "child_process";
28638
28992
  import { resolve as resolve12 } from "path";
28639
28993
  var AUTH_TIMEOUT_MS = 8e3;
28640
- var defaultExec3 = (command, args, options) => new Promise((resolve17) => {
28994
+ var defaultExec3 = (command, args, options) => new Promise((resolve18) => {
28641
28995
  let settled = false;
28642
28996
  const settle = (result) => {
28643
28997
  if (settled) return;
28644
28998
  settled = true;
28645
28999
  clearTimeout(timer);
28646
- resolve17(result);
29000
+ resolve18(result);
28647
29001
  };
28648
- const child = execFile5(command, args, { timeout: options.timeout, env: options.env, encoding: "utf8" }, (err, stdout, stderr) => {
29002
+ const child = execFile5(command, args, { timeout: options.timeout, env: options.env, encoding: "utf8", windowsVerbatimArguments: options.verbatim }, (err, stdout, stderr) => {
28649
29003
  const raw = err?.code;
28650
29004
  const code = err ? typeof raw === "number" ? raw : -1 : 0;
28651
29005
  settle({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
@@ -28670,9 +29024,11 @@ async function readRunnerAuth(manifest, options = {}) {
28670
29024
  let env;
28671
29025
  try {
28672
29026
  env = withPath(process.env, await augmentedPath(), options.env ?? {});
28673
- answer2 = await (options.exec ?? defaultExec3)(command, spec.statusArgs, {
29027
+ const launch = await planDirectLaunch(command, spec.statusArgs, options.launch);
29028
+ answer2 = await (options.exec ?? defaultExec3)(launch.file, launch.args, {
28674
29029
  timeout: options.timeoutMs ?? AUTH_TIMEOUT_MS,
28675
- env
29030
+ env,
29031
+ ...launch.verbatim ? { verbatim: true } : {}
28676
29032
  });
28677
29033
  } catch {
28678
29034
  return { state: "unknown", loginCommand };
@@ -29755,10 +30111,10 @@ ${repairHint}` }] : parts;
29755
30111
  }, { signal });
29756
30112
  }
29757
30113
  // --- IAiService implementation ---
29758
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30114
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
29759
30115
  this.ensureInit();
29760
30116
  const { autonomousDefault } = modes;
29761
- const contextStr = await BaseAiService.collectResearchContext(fs28, runners);
30117
+ const contextStr = await BaseAiService.collectResearchContext(fs29, runners);
29762
30118
  const systemPrompt = buildResearchPrompt(userDescription, contextStr, modelsByRunner, runners, runnerModes, modes);
29763
30119
  const firstMessage = `${buildResearchToolsPrompt(false)}
29764
30120
 
@@ -29766,17 +30122,17 @@ Explore the workspace to understand the codebase, then generate the plan.`;
29766
30122
  const researchChat = this.chat([{ role: "user", content: systemPrompt }], [{ functionDeclarations: TOOL_DEFINITIONS }], {
29767
30123
  onUsage: (record) => onProgress({ type: "usage", record })
29768
30124
  });
29769
- const result = await this.runResearchLoop(researchChat, firstMessage, fs28, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
30125
+ const result = await this.runResearchLoop(researchChat, firstMessage, fs29, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
29770
30126
  if (result.tasks) return { tasks: result.tasks, researchLog: result.researchLog, researchResults: result.researchResults };
29771
30127
  const fallback = await this.generatePlanFallback(userDescription, contextStr, result.researchResults, modelsByRunner, runners, onProgress, result.researchLog, runnerModes, autonomousDefault, signal, modes);
29772
30128
  return { tasks: fallback.tasks, researchLog: fallback.researchLog, researchResults: result.researchResults };
29773
30129
  }
29774
- async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs28, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30130
+ async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs29, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
29775
30131
  this.ensureInit();
29776
30132
  const { autonomousDefault } = modes;
29777
30133
  let ctx = "";
29778
- if (fs28) {
29779
- const collected = await new ContextCollector(fs28).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
30134
+ if (fs29) {
30135
+ const collected = await new ContextCollector(fs29).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
29780
30136
  if (collected.aiflowContext) ctx = `
29781
30137
  <aiflow_context>
29782
30138
  ${collected.aiflowContext}
@@ -30143,10 +30499,10 @@ ${buildResearchToolsPrompt()}` }
30143
30499
  }
30144
30500
  }
30145
30501
  // --- IAiService implementation ---
30146
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30502
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30147
30503
  this.ensureInit();
30148
30504
  const { autonomousDefault } = modes;
30149
- const contextStr = await BaseAiService.collectResearchContext(fs28, runners);
30505
+ const contextStr = await BaseAiService.collectResearchContext(fs29, runners);
30150
30506
  const systemPrompt = buildResearchPrompt(userDescription, contextStr, modelsByRunner, runners, runnerModes, modes);
30151
30507
  const userText = `User goal: ${userDescription}`;
30152
30508
  const firstMessage = `${buildResearchToolsPrompt()}
@@ -30166,17 +30522,17 @@ ${userText}`;
30166
30522
  onUsage: (record) => onProgress({ type: "usage", record }),
30167
30523
  budget: this.plannerBudget()
30168
30524
  });
30169
- const result = await this.runResearchLoop(researchChat, firstMessage, fs28, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
30525
+ const result = await this.runResearchLoop(researchChat, firstMessage, fs29, onProgress, runners, void 0, fetcher, userDescription, runnerModes, autonomousDefault, signal);
30170
30526
  if (result.tasks) return { tasks: result.tasks, researchLog: result.researchLog, researchResults: result.researchResults };
30171
30527
  const fallback = await this.generatePlanFallback(userDescription, contextStr, result.researchResults, modelsByRunner, runners, onProgress, result.researchLog, runnerModes, autonomousDefault, signal, modes);
30172
30528
  return { tasks: fallback.tasks, researchLog: fallback.researchLog, researchResults: result.researchResults };
30173
30529
  }
30174
- async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs28, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30530
+ async generatePlanDirect(userDescription, runners = [...DEFAULT_RUNNERS], modelsByRunner = {}, onToken, fs29, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
30175
30531
  this.ensureInit();
30176
30532
  const { autonomousDefault } = modes;
30177
30533
  let ctx = "";
30178
- if (fs28) {
30179
- const collected = await new ContextCollector(fs28).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
30534
+ if (fs29) {
30535
+ const collected = await new ContextCollector(fs29).collect(runners[0] ?? DEFAULT_RUNNERS[0]);
30180
30536
  if (collected.aiflowContext) ctx = `
30181
30537
  <aiflow_context>
30182
30538
  ${collected.aiflowContext}
@@ -31024,7 +31380,7 @@ var PlanEditError = class extends Error {
31024
31380
  };
31025
31381
 
31026
31382
  // src/services/sessionLease.ts
31027
- import * as fs18 from "fs";
31383
+ import * as fs19 from "fs";
31028
31384
  import * as path40 from "path";
31029
31385
  import { randomUUID as randomUUID6 } from "crypto";
31030
31386
  var LEASE_HEARTBEAT_MS = 1e4;
@@ -31093,7 +31449,7 @@ function isRecord6(value) {
31093
31449
  function readRecord(file) {
31094
31450
  let raw;
31095
31451
  try {
31096
- raw = fs18.readFileSync(file, "utf8");
31452
+ raw = fs19.readFileSync(file, "utf8");
31097
31453
  } catch (err) {
31098
31454
  if (err.code === "ENOENT") return null;
31099
31455
  throw err;
@@ -31225,9 +31581,9 @@ var LeaseHost = class {
31225
31581
  if (this.held.size === 0) this.stopHeartbeat();
31226
31582
  try {
31227
31583
  withFileLock(file, () => {
31228
- if (readRecord(file)?.hostId === this.id) fs18.rmSync(file, { force: true });
31584
+ if (readRecord(file)?.hostId === this.id) fs19.rmSync(file, { force: true });
31229
31585
  }, "release a session lease");
31230
- fs18.rmdirSync(path40.dirname(file));
31586
+ fs19.rmdirSync(path40.dirname(file));
31231
31587
  } catch {
31232
31588
  }
31233
31589
  }
@@ -31363,8 +31719,9 @@ function preservedNotice(kept) {
31363
31719
  const owner = first.task ? `Task "${first.task.title}"` : "A leftover task workspace no record accounted for";
31364
31720
  return `${owner} had work that never landed, so before its worktree was removed it was kept on branch ${first.branch}${where}. \`git log ${first.branch}\` shows it; merge or cherry-pick it to bring it back, and delete the branch once you no longer need it.`;
31365
31721
  }
31366
- function refusedNotice(worktree, reason, task2) {
31367
- return `Left ${task2 ? `the worktree of task "${task2.title}"` : "a leftover worktree"} in place at ${worktree}: it holds work Ordewell could not keep (${reason}). Save what you need from it, then remove it with \`git worktree remove --force ${worktree}\`.`;
31722
+ function refusedNotice(worktree, reason, task2, platform = process.platform) {
31723
+ 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}\``;
31724
+ return `Left ${task2 ? `the worktree of task "${task2.title}"` : "a leftover worktree"} in place at ${worktree}: it holds work Ordewell could not keep (${reason}). Save what you need from it, then ${remove}.`;
31368
31725
  }
31369
31726
  function sharedPathsNotice(run) {
31370
31727
  if (run.repos.some((r) => r.path === SELF_REPO)) {
@@ -32722,7 +33079,7 @@ import * as path45 from "path";
32722
33079
  // src/services/taskStartConfig.ts
32723
33080
  import * as path41 from "path";
32724
33081
  import { createHash as createHash4 } from "crypto";
32725
- import { existsSync as existsSync16, lstatSync as lstatSync4, readdirSync as readdirSync9, readFileSync as readFileSync15, statSync as statSync12 } from "fs";
33082
+ import { existsSync as existsSync16, lstatSync as lstatSync4, readdirSync as readdirSync9, readFileSync as readFileSync16, statSync as statSync12 } from "fs";
32726
33083
  var MAX_FILES = 2e3;
32727
33084
  var MAX_DEPTH = 8;
32728
33085
  function liveConfig(dir) {
@@ -32733,7 +33090,7 @@ function liveConfig(dir) {
32733
33090
  try {
32734
33091
  const info = statSync12(full);
32735
33092
  if (info.isFile()) {
32736
- found.set(rel, createHash4("sha1").update(readFileSync15(full)).digest("hex"));
33093
+ found.set(rel, createHash4("sha1").update(readFileSync16(full)).digest("hex"));
32737
33094
  } else if (info.isDirectory() && path41.basename(rel) !== "node_modules") {
32738
33095
  for (const name of readdirSync9(full)) visit(path41.posix.join(rel, name), depth + 1);
32739
33096
  }
@@ -32744,16 +33101,27 @@ function liveConfig(dir) {
32744
33101
  const selected = new Set(repositoryRunnerConfigPaths([...found.keys()]));
32745
33102
  return new Map([...found].filter(([name]) => selected.has(name)));
32746
33103
  }
32747
- function linkedRoots(dir) {
33104
+ function linkedRoots(dir, checkout) {
32748
33105
  const linked = /* @__PURE__ */ new Set();
32749
33106
  for (const root of RUNNER_CONFIG_ROOTS) {
32750
33107
  try {
32751
- if (lstatSync4(path41.join(dir, root)).isSymbolicLink()) linked.add(root);
33108
+ const here = lstatSync4(path41.join(dir, root), { bigint: true });
33109
+ if (here.isSymbolicLink() || here.isFile() && here.nlink > 1n && sameFile(here, statSync12(path41.join(checkout, root), { bigint: true }))) linked.add(root);
32752
33110
  } catch {
32753
33111
  }
32754
33112
  }
32755
33113
  return linked;
32756
33114
  }
33115
+ function sameFile(a, b) {
33116
+ return a.dev === b.dev && a.ino === b.ino;
33117
+ }
33118
+ function linksTo(link, target) {
33119
+ try {
33120
+ return lstatSync4(link).isSymbolicLink() && realPathOf(link) === realPathOf(target);
33121
+ } catch {
33122
+ return false;
33123
+ }
33124
+ }
32757
33125
  function readDirs(root) {
32758
33126
  const dirs = [{ dir: root, prefix: "" }];
32759
33127
  for (let dir = root, prefix = ""; !existsSync16(path41.join(dir, ".git")); ) {
@@ -32798,7 +33166,7 @@ var TaskStartConfig = class {
32798
33166
  */
32799
33167
  worktreeDifferences(id2, dir, root) {
32800
33168
  const now = liveConfig(dir);
32801
- const linked = linkedRoots(dir);
33169
+ const linked = linkedRoots(dir, root);
32802
33170
  const fromCheckout2 = (name) => linked.has(name.split("/")[0]);
32803
33171
  const key = `${id2}:worktree:${dir}`;
32804
33172
  let local = this.live.get(key);
@@ -32827,10 +33195,14 @@ var TaskStartConfig = class {
32827
33195
  if (!cwd || !repo.baseRef || !existsSync16(cwd)) continue;
32828
33196
  const prefix = repo.path === "." ? (await tryGit(invoker, repo.root, ["rev-parse", "--show-prefix"])).stdout.trim() : "";
32829
33197
  const roots = [...RUNNER_CONFIG_ROOTS, ...prefix ? RUNNER_CONFIG_ROOTS.map((r) => `${prefix}${r}`) : []];
33198
+ const top = path41.resolve(repo.root, ...prefix.split("/").filter(Boolean).map(() => ".."));
33199
+ const runnerRoots = prefix ? roots.filter((root) => root.startsWith(prefix)) : roots;
33200
+ const linked = runnerRoots.filter((root) => linksTo(path41.join(cwd, root), path41.join(top, root))).map((root) => `${root}/`);
32830
33201
  const diff = await tryGit(invoker, cwd, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "--diff-filter=ACMRTU", "-z", repo.baseRef, "--"]);
32831
33202
  const untracked = await tryGit(invoker, cwd, ["ls-files", "--others", "-z", "--", ...roots]);
32832
33203
  if (!diff.ok || !untracked.ok) continue;
32833
33204
  for (const name of [...diff.stdout.split("\0"), ...untracked.stdout.split("\0")]) {
33205
+ if (linked.some((root) => name.startsWith(root))) continue;
32834
33206
  const here = prefix && name.startsWith(prefix) ? name.slice(prefix.length) : void 0;
32835
33207
  if (repositoryRunnerConfigPaths([name]).length || here !== void 0 && repositoryRunnerConfigPaths([here]).length) {
32836
33208
  found.push(repo.path === "." ? name : path41.posix.join(repo.path, name));
@@ -32843,7 +33215,7 @@ var TaskStartConfig = class {
32843
33215
 
32844
33216
  // src/services/ScriptRunner.ts
32845
33217
  import { spawn as nodeSpawn2 } from "child_process";
32846
- import * as fs19 from "fs";
33218
+ import * as fs20 from "fs";
32847
33219
  import * as path42 from "path";
32848
33220
  import { EventEmitter as EventEmitter2 } from "events";
32849
33221
  import { StringDecoder as StringDecoder2 } from "string_decoder";
@@ -32929,8 +33301,8 @@ var ScriptSession = class extends AbstractRunnerSession {
32929
33301
  /** Aborted to end a sealed step, which has no process of its own here to signal. */
32930
33302
  sealedEnd = new AbortController();
32931
33303
  markGone;
32932
- gone = new Promise((resolve17) => {
32933
- this.markGone = resolve17;
33304
+ gone = new Promise((resolve18) => {
33305
+ this.markGone = resolve18;
32934
33306
  });
32935
33307
  /** Whoever spawned it attaches its listeners when the spawn resolves, so the body starts a macrotask later. */
32936
33308
  begin() {
@@ -33032,7 +33404,7 @@ var ScriptSession = class extends AbstractRunnerSession {
33032
33404
  return shell.file === null ? { file: step.script, args: [], shell: true } : { file: shell.file, args: [...shell.args, step.script], shell: false };
33033
33405
  }
33034
33406
  spawnStep(launch) {
33035
- return new Promise((resolve17) => {
33407
+ return new Promise((resolve18) => {
33036
33408
  let settled = false;
33037
33409
  const stdout = new StringDecoder2("utf8");
33038
33410
  const stderr = new StringDecoder2("utf8");
@@ -33044,7 +33416,7 @@ var ScriptSession = class extends AbstractRunnerSession {
33044
33416
  this.child = null;
33045
33417
  this.placed = null;
33046
33418
  launch.placed?.ended();
33047
- resolve17(status);
33419
+ resolve18(status);
33048
33420
  };
33049
33421
  this.placed = launch.placed ?? null;
33050
33422
  const child = spawnInOwnGroup((detached) => this.setup.spawn(launch.file, launch.args, {
@@ -33095,7 +33467,7 @@ var ScriptSession = class extends AbstractRunnerSession {
33095
33467
  openFullOutput() {
33096
33468
  const target = this.setup.fullOutput;
33097
33469
  if (!target) return;
33098
- const stream = fs19.createWriteStream(target.file);
33470
+ const stream = fs20.createWriteStream(target.file);
33099
33471
  const full = { file: target.file, stream, written: 0, dropped: 0, failed: false };
33100
33472
  stream.on("error", (err) => {
33101
33473
  if (!full.failed) console.error(`[ScriptSession] could not save the output of ${this.id} to ${target.file}:`, err);
@@ -33120,12 +33492,12 @@ var ScriptSession = class extends AbstractRunnerSession {
33120
33492
  if (!full.failed && full.dropped > 0) full.stream.write(`
33121
33493
  [Ordewell stopped saving output here: ${full.dropped} more characters were not saved]
33122
33494
  `);
33123
- await new Promise((resolve17) => {
33495
+ await new Promise((resolve18) => {
33124
33496
  if (full.stream.closed) {
33125
- resolve17();
33497
+ resolve18();
33126
33498
  return;
33127
33499
  }
33128
- full.stream.once("close", () => resolve17());
33500
+ full.stream.once("close", () => resolve18());
33129
33501
  full.stream.end();
33130
33502
  });
33131
33503
  return full.failed ? void 0 : { file: full.file, droppedChars: full.dropped };
@@ -33277,7 +33649,7 @@ function passed(status) {
33277
33649
 
33278
33650
  // src/services/PatchCapture.ts
33279
33651
  import { createHash as createHash5, randomBytes as randomBytes8 } from "crypto";
33280
- import * as fs20 from "fs";
33652
+ import * as fs21 from "fs";
33281
33653
  import * as os11 from "os";
33282
33654
  import * as path43 from "path";
33283
33655
 
@@ -33357,9 +33729,9 @@ var Subtree = class _Subtree {
33357
33729
  at(path52) {
33358
33730
  const { here } = this.source;
33359
33731
  const absolute = `${ROOT_NODE2}/${path52}`;
33360
- const relative21 = `${here}/${path52}`;
33732
+ const relative20 = `${here}/${path52}`;
33361
33733
  const nodes = this.nodes();
33362
- const found = (absolute !== here && isWithin(absolute, here) ? nodes.find((node) => node.path === absolute) : void 0) ?? nodes.find((node) => node.path === relative21);
33734
+ const found = (absolute !== here && isWithin(absolute, here) ? nodes.find((node) => node.path === absolute) : void 0) ?? nodes.find((node) => node.path === relative20);
33363
33735
  return found && this.planOf(found);
33364
33736
  }
33365
33737
  /** The same as a reference is pinned against it. */
@@ -33777,17 +34149,17 @@ function linkInPatch(patch) {
33777
34149
  function readOwn(scratch, name, max) {
33778
34150
  let fd;
33779
34151
  try {
33780
- fd = fs20.openSync(path43.join(scratch, name), fs20.constants.O_RDONLY | (fs20.constants.O_NOFOLLOW ?? 0));
34152
+ fd = fs21.openSync(path43.join(scratch, name), fs21.constants.O_RDONLY | (fs21.constants.O_NOFOLLOW ?? 0));
33781
34153
  } catch (err) {
33782
34154
  throw new Refusal(`the capture left no ${name.split(".").pop()} Ordewell could read (${err.code ?? String(err)})`);
33783
34155
  }
33784
34156
  try {
33785
- if (!fs20.fstatSync(fd).isFile()) throw new Refusal(`the capture's ${name.split(".").pop()} is not a file`);
34157
+ if (!fs21.fstatSync(fd).isFile()) throw new Refusal(`the capture's ${name.split(".").pop()} is not a file`);
33786
34158
  const chunks = [];
33787
34159
  let total = 0;
33788
34160
  for (; ; ) {
33789
34161
  const chunk = Buffer.alloc(Math.min(1024 * 1024, max + 1 - total));
33790
- const read2 = fs20.readSync(fd, chunk, 0, chunk.length, null);
34162
+ const read2 = fs21.readSync(fd, chunk, 0, chunk.length, null);
33791
34163
  if (read2 === 0) break;
33792
34164
  total += read2;
33793
34165
  chunks.push(chunk.subarray(0, read2));
@@ -33795,7 +34167,7 @@ function readOwn(scratch, name, max) {
33795
34167
  }
33796
34168
  return Buffer.concat(chunks);
33797
34169
  } finally {
33798
- fs20.closeSync(fd);
34170
+ fs21.closeSync(fd);
33799
34171
  }
33800
34172
  }
33801
34173
  function failure(step, outcome) {
@@ -33833,7 +34205,7 @@ async function captureHeld(runs, opts, signal) {
33833
34205
  if (clash) return { kind: "refused", reason: clash };
33834
34206
  const flags = [...flag("excluded", excluded.map((c) => c.name)), ...flag("dropped", dropped.map((p) => `${p.name} (${byteSize(p.size)})`))];
33835
34207
  if (kept.length === 0) return { kind: "empty", reason: "none of the worktree's changes is one a patch carries.", flags };
33836
- fs20.writeFileSync(`${stem}.revert`, revertRecords([...excluded, ...dropped.flatMap((p) => p.changes)]), { flag: "wx", mode: 384 });
34208
+ fs21.writeFileSync(`${stem}.revert`, revertRecords([...excluded, ...dropped.flatMap((p) => p.changes)]), { flag: "wx", mode: 384 });
33837
34209
  const exported = await runs.run(exportScript(stem), worktree);
33838
34210
  if (signal?.aborted) return { kind: "refused", reason: "the attempt ended while its changes were being captured." };
33839
34211
  if (!exported.success) return { kind: "refused", reason: failure("git could not write or replay the patch", exported) };
@@ -33859,8 +34231,8 @@ async function captureHeld(runs, opts, signal) {
33859
34231
  if (err instanceof Refusal) return { kind: "refused", reason: `${err.message}.` };
33860
34232
  throw err;
33861
34233
  } finally {
33862
- fs20.rmSync(`${stem}.d`, { recursive: true, force: true });
33863
- for (const suffix of ["base", "raw", "files", "sizes", "renames", "revert", "kept", "hashes", "patch", "tree", "replayed"]) fs20.rmSync(`${stem}.${suffix}`, { force: true });
34234
+ fs21.rmSync(`${stem}.d`, { recursive: true, force: true });
34235
+ for (const suffix of ["base", "raw", "files", "sizes", "renames", "revert", "kept", "hashes", "patch", "tree", "replayed"]) fs21.rmSync(`${stem}.${suffix}`, { force: true });
33864
34236
  }
33865
34237
  }
33866
34238
  async function capturePatch(shell, opts = {}, signal) {
@@ -33909,7 +34281,7 @@ async function indexEntries(invoker, worktree) {
33909
34281
  async function trialApply(invoker, worktree, patchFile, scratch) {
33910
34282
  const index = path43.resolve(worktree, (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--git-path", "index"])).trim());
33911
34283
  const copy = path43.join(scratch, "index");
33912
- fs20.copyFileSync(index, copy);
34284
+ fs21.copyFileSync(index, copy);
33913
34285
  const trial = { ...invoker, exec: (file, args, opts) => invoker.exec(file, args, { ...opts, env: { ...opts.env, GIT_INDEX_FILE: copy } }) };
33914
34286
  const tried = await tryGit(trial, worktree, [...APPLY_GIT, "apply", "--cached", "--3way", "--whitespace=nowarn", patchFile]);
33915
34287
  return { left: await indexEntries(trial, worktree), ...tried.ok ? {} : { failed: tried.stderr } };
@@ -33928,7 +34300,7 @@ function gitRefused(lead, stderr) {
33928
34300
  function onDisk3(worktree, names2) {
33929
34301
  return names2.map((name) => {
33930
34302
  try {
33931
- const stat = fs20.lstatSync(path43.join(worktree, name), { bigint: true, throwIfNoEntry: false });
34303
+ const stat = fs21.lstatSync(path43.join(worktree, name), { bigint: true, throwIfNoEntry: false });
33932
34304
  return stat ? `${stat.mode} ${stat.ino} ${stat.size} ${stat.mtimeNs} ${stat.ctimeNs}` : "none";
33933
34305
  } catch (err) {
33934
34306
  return err.code ?? "unreadable";
@@ -33969,12 +34341,12 @@ function leavesWorktree(worktree, names2, linked, held2, left) {
33969
34341
  return `the patch writes ${name}, under ${at}, a submodule, whose files are another repository's.`;
33970
34342
  }
33971
34343
  const full = path43.join(worktree, ...parts.slice(0, i));
33972
- const stat = fs20.lstatSync(full, { throwIfNoEntry: false });
34344
+ const stat = fs21.lstatSync(full, { throwIfNoEntry: false });
33973
34345
  if (!stat) break;
33974
34346
  const last = i === parts.length;
33975
34347
  if (stat.isSymbolicLink()) {
33976
34348
  if (last && held2.get(at)?.some((entry) => entry.mode === LINK)) break;
33977
- const target = fs20.readlinkSync(full);
34349
+ const target = fs21.readlinkSync(full);
33978
34350
  return `the patch writes ${name}, ${last ? `a link to ${target}` : `under ${at}, a link to ${target}`}, so git would write through it, outside your worktree.`;
33979
34351
  }
33980
34352
  if (last || stat.isDirectory()) continue;
@@ -33996,10 +34368,10 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
33996
34368
  if (link !== void 0) {
33997
34369
  return refused4(`the patch holds a link or a submodule (${JSON.stringify(link.slice(0, 80))}), which a saved patch never does, so it is not one that was saved.`);
33998
34370
  }
33999
- const dir = fs20.mkdtempSync(path43.join(os11.tmpdir(), "ordewell-apply-"));
34371
+ const dir = fs21.mkdtempSync(path43.join(os11.tmpdir(), "ordewell-apply-"));
34000
34372
  try {
34001
34373
  const toplevel = (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--show-toplevel"])).trim();
34002
- if (fs20.realpathSync(toplevel) !== fs20.realpathSync(worktree)) return refused4(`${worktree} is not the root of a worktree of its own.`);
34374
+ if (realPathOf(toplevel) !== realPathOf(worktree)) return refused4(`${worktree} is not the root of a worktree of its own.`);
34003
34375
  const head = (await git(invoker, worktree, [...APPLY_GIT, "rev-parse", "--verify", "HEAD^{commit}"])).trim();
34004
34376
  if (!(await tryGit(invoker, worktree, [...APPLY_GIT, "cat-file", "-e", `${saved.base}^{commit}`])).ok) {
34005
34377
  return refused4(`the commit the patch was taken against (${saved.base.slice(0, 12)}) is not in this repository, so there is nothing to merge it from.`);
@@ -34007,7 +34379,7 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
34007
34379
  const before = await unmergedPaths(invoker, worktree);
34008
34380
  if (before.length > 0) return refused4(`your worktree still has unresolved conflicts (${listed(before.slice(0, 10))}${before.length > 10 ? `, +${before.length - 10} more` : ""}). Resolve them and git add them, or undo them, then apply the patch.`);
34009
34381
  const file = path43.join(dir, "saved.patch");
34010
- fs20.writeFileSync(file, patch, { flag: "wx", mode: 384 });
34382
+ fs21.writeFileSync(file, patch, { flag: "wx", mode: 384 });
34011
34383
  const held2 = await indexEntries(invoker, worktree);
34012
34384
  const named3 = await pathsNamed(invoker, worktree, file);
34013
34385
  const { left, failed: failed2 } = await trialApply(invoker, worktree, file, dir);
@@ -34039,7 +34411,7 @@ async function applyPatch(invoker, worktree, patch, saved, opts = {}) {
34039
34411
  } catch (err) {
34040
34412
  return refused4(`git could not apply the patch (${err instanceof Error ? err.message : String(err)}).`);
34041
34413
  } finally {
34042
- fs20.rmSync(dir, { recursive: true, force: true });
34414
+ fs21.rmSync(dir, { recursive: true, force: true });
34043
34415
  }
34044
34416
  }
34045
34417
  function resolution(c) {
@@ -34106,17 +34478,17 @@ async function applySavedPatch(args, site) {
34106
34478
 
34107
34479
  // src/services/Board.ts
34108
34480
  import { createHash as createHash6 } from "crypto";
34109
- import * as fs21 from "fs";
34481
+ import * as fs22 from "fs";
34110
34482
  import * as path44 from "path";
34111
34483
  var BLOB_READ_MAX = 16 * 1024 * 1024;
34112
34484
  async function workBlob(cwd, file) {
34113
34485
  try {
34114
- const root = await fs21.promises.realpath(cwd);
34115
- const full = await fs21.promises.realpath(path44.join(root, file));
34486
+ const root = await fs22.promises.realpath(cwd);
34487
+ const full = await fs22.promises.realpath(path44.join(root, file));
34116
34488
  if (!full.startsWith(`${root}${path44.sep}`)) return void 0;
34117
- const stat = await fs21.promises.stat(full);
34489
+ const stat = await fs22.promises.stat(full);
34118
34490
  if (!stat.isFile() || stat.size > BLOB_READ_MAX) return void 0;
34119
- const bytes = await fs21.promises.readFile(full);
34491
+ const bytes = await fs22.promises.readFile(full);
34120
34492
  return createHash6("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
34121
34493
  } catch {
34122
34494
  return void 0;
@@ -35502,7 +35874,7 @@ function leasedIsolation(isolation, held2) {
35502
35874
  closeChanges: async () => {
35503
35875
  do {
35504
35876
  await Promise.all(underWay);
35505
- await new Promise((resolve17) => setImmediate(resolve17));
35877
+ await new Promise((resolve18) => setImmediate(resolve18));
35506
35878
  } while (underWay.size > 0);
35507
35879
  closed = true;
35508
35880
  }
@@ -35743,9 +36115,9 @@ var SlotPool = class {
35743
36115
  try {
35744
36116
  while (this.keptStarts.length > 0 && !this.full) {
35745
36117
  const node = this.keptStarts.shift();
35746
- await new Promise((resolve17) => {
35747
- this.taken = resolve17;
35748
- void node.tick().catch(() => void 0).finally(resolve17);
36118
+ await new Promise((resolve18) => {
36119
+ this.taken = resolve18;
36120
+ void node.tick().catch(() => void 0).finally(resolve18);
35749
36121
  });
35750
36122
  this.taken = null;
35751
36123
  }
@@ -38666,6 +39038,7 @@ var RunnerInstallation = class {
38666
39038
  env;
38667
39039
  workspace;
38668
39040
  authExec;
39041
+ launch;
38669
39042
  constructor(registry, execImpl = defaultExec4, now = Date.now, options = {}) {
38670
39043
  this.registry = registry;
38671
39044
  this.execImpl = execImpl;
@@ -38673,6 +39046,7 @@ var RunnerInstallation = class {
38673
39046
  this.env = options.env ?? (async () => ({}));
38674
39047
  this.workspace = options.workspace ?? (() => void 0);
38675
39048
  this.authExec = options.authExec;
39049
+ this.launch = options.launch ?? {};
38676
39050
  }
38677
39051
  /** True if the runner's CLI responds to `--version`. Cached per process. */
38678
39052
  async isInstalled(runner) {
@@ -38756,7 +39130,8 @@ var RunnerInstallation = class {
38756
39130
  try {
38757
39131
  return await readRunnerAuth(manifest, {
38758
39132
  ...this.authExec ? { exec: this.authExec } : {},
38759
- env: await this.env(workspace)
39133
+ env: await this.env(workspace),
39134
+ launch: this.launch
38760
39135
  });
38761
39136
  } catch {
38762
39137
  return { state: "unknown" };
@@ -38783,10 +39158,10 @@ var RunnerInstallation = class {
38783
39158
  * with `isInstalled` there.
38784
39159
  */
38785
39160
  async isSpawnable(command) {
38786
- if (process.platform !== "win32") return true;
39161
+ if ((this.launch.platform ?? process.platform) !== "win32") return true;
38787
39162
  try {
38788
- const plan = await planDirectLaunch(command, []);
38789
- return plan.file !== command;
39163
+ const plan = await planDirectLaunch(command, [], this.launch);
39164
+ return isExecutableResolved(command, plan, "", this.launch);
38790
39165
  } catch {
38791
39166
  return false;
38792
39167
  }
@@ -38976,10 +39351,10 @@ var AccountLimitMonitor = class {
38976
39351
  entry.inFlight = controller;
38977
39352
  entry.lastStartedAt = this.now();
38978
39353
  let deadline;
38979
- const abandoned = new Promise((resolve17) => {
39354
+ const abandoned = new Promise((resolve18) => {
38980
39355
  deadline = setTimeout(() => {
38981
39356
  controller.abort();
38982
- resolve17({ kind: "failed" });
39357
+ resolve18({ kind: "failed" });
38983
39358
  }, DEADLINE_MS);
38984
39359
  deadline.unref?.();
38985
39360
  });
@@ -39158,9 +39533,9 @@ async function readCodexAccountLimits(command, args, options, signal) {
39158
39533
  const initialized = await rpc.call("initialize", { clientInfo: APP_SERVER_CLIENT_INFO });
39159
39534
  if (!initialized.ok) return failed2();
39160
39535
  server4.notify("initialized", {});
39161
- const account = await new Promise((resolve17) => rpc.send("account/read", { refreshToken: false }, (response) => {
39536
+ const account = await new Promise((resolve18) => rpc.send("account/read", { refreshToken: false }, (response) => {
39162
39537
  accountRead = true;
39163
- resolve17(response);
39538
+ resolve18(response);
39164
39539
  }));
39165
39540
  if (!account.ok) return account.code === METHOD_NOT_FOUND ? { kind: "unsupported" } : failed2();
39166
39541
  const who = codexAccountOwner(account.result);
@@ -39178,7 +39553,7 @@ async function readCodexAccountLimits(command, args, options, signal) {
39178
39553
  ...followUp ? { followUp: true } : {}
39179
39554
  };
39180
39555
  })();
39181
- const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
39556
+ const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
39182
39557
  try {
39183
39558
  return await settleWithin(asked, {
39184
39559
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS4,
@@ -39235,7 +39610,7 @@ import { spawn as nodeSpawn3 } from "child_process";
39235
39610
  import { randomUUID as randomUUID7 } from "crypto";
39236
39611
  import { mkdtempSync as mkdtempSync5, rmSync as rmSync12 } from "fs";
39237
39612
  import { tmpdir as tmpdir6 } from "os";
39238
- import { join as join41 } from "path";
39613
+ import { join as join40 } from "path";
39239
39614
  var DEFAULT_TIMEOUT_MS5 = 2e4;
39240
39615
  var INITIALIZE_TIMEOUT_MS2 = 1e4;
39241
39616
  var USAGE_TIMEOUT_MS = 1e4;
@@ -39267,7 +39642,7 @@ function claudeAccountLimitCollector(options) {
39267
39642
  };
39268
39643
  }
39269
39644
  async function readClaudeAccountLimits(options, signal) {
39270
- const cwd = mkdtempSync5(join41(tmpdir6(), "ordewell-claude-limits-"));
39645
+ const cwd = mkdtempSync5(join40(tmpdir6(), "ordewell-claude-limits-"));
39271
39646
  const removeCwd = () => {
39272
39647
  try {
39273
39648
  rmSync12(cwd, { recursive: true, force: true });
@@ -39296,7 +39671,7 @@ async function readClaudeAccountLimits(options, signal) {
39296
39671
  if (usage.kind === "refused" && UNSUPPORTED_REQUEST.test(usage.error)) return { kind: "unsupported" };
39297
39672
  return claudeLimitReading(usage, owner, isRecord8(account) ? text3(account.subscriptionType) : void 0) ?? failed2();
39298
39673
  })().catch(failed2);
39299
- const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
39674
+ const cancelled2 = signal.aborted ? Promise.resolve() : new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
39300
39675
  try {
39301
39676
  return await settleWithin(asked, {
39302
39677
  timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS5,
@@ -39355,9 +39730,9 @@ import { homedir as homedir10 } from "os";
39355
39730
 
39356
39731
  // src/services/harness/openCodeCredentials.ts
39357
39732
  import { createHash as createHash7 } from "crypto";
39358
- import { promises as fs22 } from "fs";
39733
+ import { promises as fs23 } from "fs";
39359
39734
  import { homedir as osHomedir } from "os";
39360
- import { join as join42, resolve as resolve14 } from "path";
39735
+ import { join as join41, resolve as resolve15 } from "path";
39361
39736
  import { Worker } from "worker_threads";
39362
39737
  var DEFAULT_TIMEOUT_MS6 = 5e3;
39363
39738
  var BUSY_MS = 250;
@@ -39414,9 +39789,9 @@ parentPort.postMessage(select());
39414
39789
  var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
39415
39790
  var digest = (...parts) => createHash7("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
39416
39791
  function openCodeStorePaths(env, home) {
39417
- const data = join42(env.XDG_DATA_HOME || join42(home, ".local", "share"), "opencode");
39792
+ const data = join41(env.XDG_DATA_HOME || join41(home, ".local", "share"), "opencode");
39418
39793
  const file = env.OPENCODE_DB || "opencode.db";
39419
- return { db: file === ":memory:" ? null : resolve14(data, file), auth: join42(data, "auth.json") };
39794
+ return { db: file === ":memory:" ? null : resolve15(data, file), auth: join41(data, "auth.json") };
39420
39795
  }
39421
39796
  function openCodeGoLoginReader(deps = {}) {
39422
39797
  const homedir11 = deps.homedir ?? osHomedir;
@@ -39525,7 +39900,7 @@ function queryStore(path52, signal, deps) {
39525
39900
  }
39526
39901
  async function stamp(path52) {
39527
39902
  try {
39528
- const stat = await fs22.stat(path52);
39903
+ const stat = await fs23.stat(path52);
39529
39904
  return [stat.ino, stat.size, stat.mtimeMs];
39530
39905
  } catch {
39531
39906
  return null;
@@ -39533,9 +39908,9 @@ async function stamp(path52) {
39533
39908
  }
39534
39909
  async function readSmall(path52) {
39535
39910
  try {
39536
- const stat = await fs22.stat(path52);
39911
+ const stat = await fs23.stat(path52);
39537
39912
  if (!stat.isFile() || stat.size > MAX_AUTH_FILE_BYTES) return null;
39538
- return await fs22.readFile(path52, "utf8");
39913
+ return await fs23.readFile(path52, "utf8");
39539
39914
  } catch (err) {
39540
39915
  return err.code === "ENOENT" ? void 0 : null;
39541
39916
  }
@@ -39832,7 +40207,7 @@ function nativeShellOffer(input) {
39832
40207
  if (input.runner === "codex") {
39833
40208
  return {
39834
40209
  offered: false,
39835
- reason: "Codex already runs its own shell, read-only and without the network (ADR-0026), so this setting changes nothing for it."
40210
+ reason: platform === "win32" ? "On Windows Codex plans with its own shell off, since its sandbox there cannot keep a command off the network, and runs every command through Ordewell's (ADR-0010)." : "Codex already runs its own shell, read-only and without the network (ADR-0026), so this setting changes nothing for it."
39836
40211
  };
39837
40212
  }
39838
40213
  const checked = CHECKED[input.runner];
@@ -39992,6 +40367,11 @@ var CliAgentAiService = class {
39992
40367
  hasActiveConversation() {
39993
40368
  return this.session?.start != null;
39994
40369
  }
40370
+ /** On Windows, the shell `run_command` runs, which a coding agent there would take for PowerShell (ADR-0010). */
40371
+ researchShell() {
40372
+ if ((this.processDeps.platform ?? process.platform) !== "win32") return void 0;
40373
+ return resolveResearchShell().dialect === "cmd" ? "cmd" : "git-bash";
40374
+ }
39995
40375
  /**
39996
40376
  * False when the running agent process was spawned under a model/effort the
39997
40377
  * user has since changed in the picker. Unlike a vendor backend, the model
@@ -40053,13 +40433,14 @@ var CliAgentAiService = class {
40053
40433
  this.session = session;
40054
40434
  session.notice = req.notice;
40055
40435
  const contextStr = await collectResearchContext(req.fs, req.runners);
40436
+ const researchShell = this.researchShell();
40056
40437
  const systemPrompt = buildConversationSystemPrompt(
40057
40438
  req.goal,
40058
40439
  contextStr,
40059
40440
  req.modelsByRunner,
40060
40441
  req.runners,
40061
40442
  req.runnerModes,
40062
- { harness: true, runner: this.runner, isolatedExecution: req.isolatedExecution, skills: req.skills, execution: req.plannerTools !== void 0, autorun: req.autorun, delegation: req.delegation, subplanner: req.subplanner, ...req.plannerTools.noSubagents ? { subagents: false } : {} }
40443
+ { harness: true, runner: this.runner, isolatedExecution: req.isolatedExecution, skills: req.skills, execution: req.plannerTools !== void 0, autorun: req.autorun, delegation: req.delegation, subplanner: req.subplanner, ...req.plannerTools.noSubagents ? { subagents: false } : {}, ...researchShell ? { researchShell } : {} }
40063
40444
  );
40064
40445
  const fetcher = req.fetcher;
40065
40446
  const cwd = this.workspaceRoot();
@@ -40646,6 +41027,9 @@ ${corrective}`, catalog, onProgress, signal),
40646
41027
  };
40647
41028
  const tools = {
40648
41029
  sessionId: uuidv48(),
41030
+ // No session here runs a command, so the planner is not offered one: it
41031
+ // reads with its harness's own tools, and Codex keeps its shell for it.
41032
+ withheld: ["run_command"],
40649
41033
  handler: {
40650
41034
  listRunners: async () => ({ text: JSON.stringify({ runners: catalog.runners.map((id2) => ({ id: id2, readOnly: readOnlyMode(catalog.runnerModes?.[id2]) !== void 0 })) }) }),
40651
41035
  listModels: async ({ runner }) => ({ text: JSON.stringify({ runner, models: catalog.modelsByRunner?.[runner] ?? [] }) }),
@@ -40700,8 +41084,8 @@ Before submitting, call list_runners and list_models to check the available assi
40700
41084
  session.discard();
40701
41085
  }
40702
41086
  }
40703
- async researchAndPlan(userDescription, runners, modelsByRunner, fs28, onProgress, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
40704
- const contextStr = await collectResearchContext(fs28, runners);
41087
+ async researchAndPlan(userDescription, runners, modelsByRunner, fs29, onProgress, _fetcher, runnerModes, modes = DEFAULT_PLANNER_MODES, signal) {
41088
+ const contextStr = await collectResearchContext(fs29, runners);
40705
41089
  const prompt = buildPlanWithResults(userDescription, contextStr, "", modelsByRunner, runners, runnerModes, modes, true);
40706
41090
  const plan = await this.submittedPlan(prompt, oneShotCatalog(runners, modelsByRunner, runnerModes, modes), onProgress, signal);
40707
41091
  return {
@@ -40742,22 +41126,22 @@ function createAiService(config, deps) {
40742
41126
  import * as path49 from "path";
40743
41127
 
40744
41128
  // src/services/handoffReferences.ts
40745
- import * as fs23 from "fs";
41129
+ import * as fs24 from "fs";
40746
41130
  import * as path46 from "path";
40747
41131
  import { spawnSync as spawnSync2 } from "child_process";
40748
41132
  function resolveHandoffReferences(handoff, workspace) {
40749
41133
  const checked = /* @__PURE__ */ new Map();
40750
41134
  const contained = (candidate) => {
40751
41135
  try {
40752
- const root = fs23.realpathSync(workspace);
40753
- const resolved2 = fs23.realpathSync(path46.resolve(root, candidate));
40754
- const relative21 = path46.relative(root, resolved2);
40755
- return relative21 !== ".." && !relative21.startsWith(`..${path46.sep}`) && !path46.isAbsolute(relative21) ? resolved2 : void 0;
41136
+ const root = fs24.realpathSync(workspace);
41137
+ const resolved2 = fs24.realpathSync(path46.resolve(root, candidate));
41138
+ const relative20 = path46.relative(root, resolved2);
41139
+ return relative20 !== ".." && !relative20.startsWith(`..${path46.sep}`) && !path46.isAbsolute(relative20) ? resolved2 : void 0;
40756
41140
  } catch {
40757
41141
  return void 0;
40758
41142
  }
40759
41143
  };
40760
- const resolve17 = (ref2) => {
41144
+ const resolve18 = (ref2) => {
40761
41145
  if (ref2.kind !== "file" && ref2.kind !== "commit") return ref2;
40762
41146
  const key = JSON.stringify(ref2);
40763
41147
  const known = checked.get(key);
@@ -40767,13 +41151,13 @@ function resolveHandoffReferences(handoff, workspace) {
40767
41151
  const file = contained(ref2.path);
40768
41152
  if (file) {
40769
41153
  try {
40770
- resolved2 = fs23.statSync(file).isFile();
41154
+ resolved2 = fs24.statSync(file).isFile();
40771
41155
  } catch {
40772
41156
  }
40773
41157
  }
40774
41158
  } else if (/^[0-9a-fA-F]{4,64}$/.test(ref2.sha)) {
40775
41159
  const repo = contained(ref2.repo ?? ".");
40776
- if (repo && fs23.existsSync(path46.join(repo, ".git"))) {
41160
+ if (repo && fs24.existsSync(path46.join(repo, ".git"))) {
40777
41161
  const result2 = spawnSync2("git", ["--no-optional-locks", "--no-replace-objects", "cat-file", "-t", ref2.sha], {
40778
41162
  cwd: repo,
40779
41163
  encoding: "utf8",
@@ -40790,9 +41174,9 @@ function resolveHandoffReferences(handoff, workspace) {
40790
41174
  };
40791
41175
  return {
40792
41176
  ...handoff,
40793
- findings: handoff.findings.map((f) => ({ ...f, ...f.evidence ? { evidence: f.evidence.map(resolve17) } : {} })),
41177
+ findings: handoff.findings.map((f) => ({ ...f, ...f.evidence ? { evidence: f.evidence.map(resolve18) } : {} })),
40794
41178
  // A saved patch is Ordewell's own record, not a claim about a tree (ADR-0050).
40795
- ...handoff.artifacts ? { artifacts: handoff.artifacts.map((a) => a.kind === "patch" ? a : resolve17(a)) } : {}
41179
+ ...handoff.artifacts ? { artifacts: handoff.artifacts.map((a) => a.kind === "patch" ? a : resolve18(a)) } : {}
40796
41180
  };
40797
41181
  }
40798
41182
 
@@ -41458,8 +41842,8 @@ var PlanTurns = class {
41458
41842
  this.pump();
41459
41843
  return Promise.resolve(plan);
41460
41844
  }
41461
- const settled = new Promise((resolve17, reject) => {
41462
- this.waiters.set(entry.id, { resolve: resolve17, reject, signal: input.signal });
41845
+ const settled = new Promise((resolve18, reject) => {
41846
+ this.waiters.set(entry.id, { resolve: resolve18, reject, signal: input.signal });
41463
41847
  });
41464
41848
  this.pump();
41465
41849
  return settled;
@@ -42362,8 +42746,8 @@ var ChildPlanSession = class extends AbstractRunnerSession {
42362
42746
  counts;
42363
42747
  stopping = null;
42364
42748
  markGone;
42365
- gone = new Promise((resolve17) => {
42366
- this.markGone = resolve17;
42749
+ gone = new Promise((resolve18) => {
42750
+ this.markGone = resolve18;
42367
42751
  });
42368
42752
  /** Whoever spawned it attaches its listeners when the spawn resolves, so the child starts a macrotask later. */
42369
42753
  begin() {
@@ -43305,7 +43689,7 @@ var TreeLedger = class _TreeLedger {
43305
43689
  };
43306
43690
 
43307
43691
  // src/utils/treeEventLog.ts
43308
- import * as fs24 from "fs";
43692
+ import * as fs25 from "fs";
43309
43693
  import * as path47 from "path";
43310
43694
 
43311
43695
  // src/services/eventStore.ts
@@ -43326,7 +43710,7 @@ function treeEventLogFile(rootSessionId, baseDir) {
43326
43710
  return path47.join(sessionDataDir(rootSessionId, baseDir), LOG_FILE);
43327
43711
  }
43328
43712
  function hasTreeEventLog(rootSessionId, baseDir) {
43329
- return fs24.existsSync(treeEventLogFile(rootSessionId, baseDir));
43713
+ return fs25.existsSync(treeEventLogFile(rootSessionId, baseDir));
43330
43714
  }
43331
43715
  function batchOf(line) {
43332
43716
  try {
@@ -43339,8 +43723,8 @@ function batchOf(line) {
43339
43723
  async function* landed2(file) {
43340
43724
  let stream;
43341
43725
  try {
43342
- await fs24.promises.access(file);
43343
- stream = fs24.createReadStream(file);
43726
+ await fs25.promises.access(file);
43727
+ stream = fs25.createReadStream(file);
43344
43728
  } catch (err) {
43345
43729
  if (err.code === "ENOENT") return;
43346
43730
  throw err;
@@ -43375,15 +43759,15 @@ function jsonlEventStore(file) {
43375
43759
  let walked = null;
43376
43760
  let doubted = null;
43377
43761
  async function open() {
43378
- await fs24.promises.mkdir(path47.dirname(file), { recursive: true });
43379
- const size = await fs24.promises.stat(file).then(({ size: size2 }) => size2, () => 0);
43762
+ await fs25.promises.mkdir(path47.dirname(file), { recursive: true });
43763
+ const size = await fs25.promises.stat(file).then(({ size: size2 }) => size2, () => 0);
43380
43764
  let found = walked?.end === size ? walked : null;
43381
43765
  if (!found) {
43382
43766
  found = { end: 0, next: 1 };
43383
43767
  for await (const batch of landed2(file)) found = pastBatch(found, batch);
43384
43768
  }
43385
- if (size > found.end) await fs24.promises.truncate(file, found.end);
43386
- return { handle: await fs24.promises.open(file, "a"), next: found.next };
43769
+ if (size > found.end) await fs25.promises.truncate(file, found.end);
43770
+ return { handle: await fs25.promises.open(file, "a"), next: found.next };
43387
43771
  }
43388
43772
  async function write(events) {
43389
43773
  writer ??= await open();
@@ -43779,7 +44163,7 @@ var SessionEventRelay = class {
43779
44163
  };
43780
44164
 
43781
44165
  // src/utils/taskLogStore.ts
43782
- import * as fs25 from "fs";
44166
+ import * as fs26 from "fs";
43783
44167
  import * as path48 from "path";
43784
44168
  var EXTENSION = ".jsonl";
43785
44169
  function taskDir({ baseDir, sessionId, rootSessionId }, taskId) {
@@ -43788,7 +44172,7 @@ function taskDir({ baseDir, sessionId, rootSessionId }, taskId) {
43788
44172
  function listTaskLogAttempts(location, taskId) {
43789
44173
  let names2;
43790
44174
  try {
43791
- names2 = fs25.readdirSync(taskDir(location, taskId));
44175
+ names2 = fs26.readdirSync(taskDir(location, taskId));
43792
44176
  } catch {
43793
44177
  return [];
43794
44178
  }
@@ -43797,13 +44181,13 @@ function listTaskLogAttempts(location, taskId) {
43797
44181
  function openTaskLog(location, taskId, attempt) {
43798
44182
  ensureStateDirIgnored(location.baseDir);
43799
44183
  const dir = taskDir(location, taskId);
43800
- fs25.mkdirSync(dir, { recursive: true });
44184
+ fs26.mkdirSync(dir, { recursive: true });
43801
44185
  const next = (listTaskLogAttempts(location, taskId).pop() ?? 0) + 1;
43802
44186
  let number = attempt !== void 0 && Number.isInteger(attempt) && attempt >= 1 ? attempt : next;
43803
44187
  for (; ; ) {
43804
44188
  const file = path48.join(dir, `${number}${EXTENSION}`);
43805
44189
  try {
43806
- fs25.writeFileSync(file, "", { flag: "wx" });
44190
+ fs26.writeFileSync(file, "", { flag: "wx" });
43807
44191
  } catch (err) {
43808
44192
  if (err.code === "EEXIST") {
43809
44193
  number = Math.max(number + 1, next);
@@ -43815,7 +44199,7 @@ function openTaskLog(location, taskId, attempt) {
43815
44199
  attempt: number,
43816
44200
  append(events) {
43817
44201
  if (events.length === 0) return;
43818
- fs25.appendFileSync(file, events.map((e) => `${JSON.stringify(e)}
44202
+ fs26.appendFileSync(file, events.map((e) => `${JSON.stringify(e)}
43819
44203
  `).join(""));
43820
44204
  }
43821
44205
  };
@@ -43824,7 +44208,7 @@ function openTaskLog(location, taskId, attempt) {
43824
44208
  function prepareTaskOutputFile(location, taskId, attempt) {
43825
44209
  ensureStateDirIgnored(location.baseDir);
43826
44210
  const dir = taskDir(location, taskId);
43827
- fs25.mkdirSync(dir, { recursive: true });
44211
+ fs26.mkdirSync(dir, { recursive: true });
43828
44212
  return path48.join(dir, `${attempt}.output.txt`);
43829
44213
  }
43830
44214
  function taskPatchFile(location, taskId, attempt) {
@@ -43833,16 +44217,16 @@ function taskPatchFile(location, taskId, attempt) {
43833
44217
  function saveTaskPatch(location, taskId, attempt, patch) {
43834
44218
  ensureStateDirIgnored(location.baseDir);
43835
44219
  const file = taskPatchFile(location, taskId, attempt);
43836
- fs25.mkdirSync(path48.dirname(file), { recursive: true });
44220
+ fs26.mkdirSync(path48.dirname(file), { recursive: true });
43837
44221
  const partial = `${file}.${process.pid}-${Date.now()}.partial`;
43838
- fs25.writeFileSync(partial, patch, { flag: "wx" });
43839
- fs25.renameSync(partial, file);
44222
+ fs26.writeFileSync(partial, patch, { flag: "wx" });
44223
+ fs26.renameSync(partial, file);
43840
44224
  return file;
43841
44225
  }
43842
44226
  function readTaskPatch(location, taskId, attempt) {
43843
44227
  if (!Number.isInteger(attempt) || attempt < 1) return void 0;
43844
44228
  try {
43845
- return fs25.readFileSync(taskPatchFile(location, taskId, attempt));
44229
+ return fs26.readFileSync(taskPatchFile(location, taskId, attempt));
43846
44230
  } catch {
43847
44231
  return void 0;
43848
44232
  }
@@ -43854,7 +44238,7 @@ function readTaskLog(location, taskId, attempt) {
43854
44238
  if (!Number.isInteger(attempt) || attempt < 1) return [];
43855
44239
  let raw;
43856
44240
  try {
43857
- raw = fs25.readFileSync(path48.join(taskDir(location, taskId), `${attempt}${EXTENSION}`), "utf-8");
44241
+ raw = fs26.readFileSync(path48.join(taskDir(location, taskId), `${attempt}${EXTENSION}`), "utf-8");
43858
44242
  } catch {
43859
44243
  return [];
43860
44244
  }
@@ -44078,9 +44462,9 @@ function withTaskRunnerConfig(runner, setting) {
44078
44462
 
44079
44463
  // src/services/container/dockerLease.ts
44080
44464
  import { createHash as createHash11, randomBytes as randomBytes11 } from "crypto";
44081
- import { mkdtempSync as mkdtempSync8, readFileSync as readFileSync17, rmSync as rmSync15 } from "fs";
44465
+ import { mkdtempSync as mkdtempSync8, readFileSync as readFileSync18, rmSync as rmSync15 } from "fs";
44082
44466
  import { tmpdir as tmpdir9 } from "os";
44083
- import { basename as basename7, join as join48, posix as posix13, relative as relative19, sep as sep12 } from "path";
44467
+ import { basename as basename7, join as join47, posix as posix16, relative as relative18, sep as sep11 } from "path";
44084
44468
 
44085
44469
  // src/services/container/modelGateway.ts
44086
44470
  import { createHash as createHash8, randomBytes as randomBytes9, timingSafeEqual as timingSafeEqual2 } from "crypto";
@@ -44131,19 +44515,19 @@ var ModelGateway = class {
44131
44515
  api;
44132
44516
  /** The port it took on this host's loopback. */
44133
44517
  listen() {
44134
- return new Promise((resolve17, reject) => {
44518
+ return new Promise((resolve18, reject) => {
44135
44519
  this.server.once("error", reject);
44136
44520
  this.server.listen(0, "127.0.0.1", () => {
44137
44521
  const { port } = this.server.address();
44138
44522
  this.host = `127.0.0.1:${port}`;
44139
- resolve17(port);
44523
+ resolve18(port);
44140
44524
  });
44141
44525
  });
44142
44526
  }
44143
44527
  async close() {
44144
44528
  this.server.closeAllConnections();
44145
- await new Promise((resolve17) => {
44146
- this.server.close(() => resolve17());
44529
+ await new Promise((resolve18) => {
44530
+ this.server.close(() => resolve18());
44147
44531
  });
44148
44532
  }
44149
44533
  carries({ headers }) {
@@ -44253,7 +44637,7 @@ var CredentialBroker = class {
44253
44637
 
44254
44638
  // src/services/container/taskWorkspace.ts
44255
44639
  import { createHash as createHash9 } from "crypto";
44256
- import { posix as posix11 } from "path";
44640
+ import { posix as posix14 } from "path";
44257
44641
  var MIRROR_ROOT = "/mirror";
44258
44642
  var TASK_ROOT = "/task";
44259
44643
  var WORK_ROOT = `${TASK_ROOT}/work`;
@@ -44270,8 +44654,8 @@ printf %s "$kept" > ${mark}
44270
44654
  `;
44271
44655
  var SIGN_IN_COPY = `${TASK_ROOT}/login/claude`;
44272
44656
  var SIGN_IN_MARK = `${TASK_ROOT}/login/handed`;
44273
- var repoDir = (repo) => repo.path === SELF_REPO ? WORK_ROOT : posix11.join(WORK_ROOT, repo.path);
44274
- var mirrorDir2 = (repo) => posix11.join(MIRROR_ROOT, `${repo.path === SELF_REPO ? "self" : createHash9("sha256").update(repo.path).digest("hex").slice(0, 16)}.git`);
44657
+ var repoDir = (repo) => repo.path === SELF_REPO ? WORK_ROOT : posix14.join(WORK_ROOT, repo.path);
44658
+ var mirrorDir2 = (repo) => posix14.join(MIRROR_ROOT, `${repo.path === SELF_REPO ? "self" : createHash9("sha256").update(repo.path).digest("hex").slice(0, 16)}.git`);
44275
44659
  var exportRef = (attempt) => `refs/ordewell/export/${attempt}`;
44276
44660
  var receiveScript = (mirror) => `set -e; [ -d ${mirror} ] || git init -q --bare ${mirror}; cd ${mirror}; git config gc.auto 0; git config gc.pruneExpire never; git config receive.autogc false; exec git receive-pack .`;
44277
44661
  var extArgument = (arg) => arg.replace(/%/g, "%%").replace(/ /g, "% ");
@@ -44416,7 +44800,7 @@ function parseContainerSettings(raw) {
44416
44800
  }
44417
44801
 
44418
44802
  // src/services/container/containerRunners.ts
44419
- import { posix as posix12 } from "path";
44803
+ import { posix as posix15 } from "path";
44420
44804
  var LOGIN_VOLUME = "ordewell-login-claude-code";
44421
44805
  var CODEX_LOGIN_VOLUME = "ordewell-login-codex";
44422
44806
  var OPENCODE_LOGIN_VOLUME = "ordewell-login-opencode";
@@ -44469,7 +44853,7 @@ var CONTAINER_RUNNERS = [
44469
44853
  api: ANTHROPIC_API,
44470
44854
  unbrokered: { openai: OPENAI_API },
44471
44855
  // The copy is the runner's data directory, which `XDG_DATA_HOME` names the parent of.
44472
- signIn: { volume: OPENCODE_LOGIN_VOLUME, hosts: OPENCODE_HOSTS, copy: ["sh", "-c", COPY_OPENCODE_SIGN_IN], path: OPENCODE_SIGN_IN_COPY, env: { XDG_DATA_HOME: posix12.join(TASK_ROOT, "login") } },
44856
+ signIn: { volume: OPENCODE_LOGIN_VOLUME, hosts: OPENCODE_HOSTS, copy: ["sh", "-c", COPY_OPENCODE_SIGN_IN], path: OPENCODE_SIGN_IN_COPY, env: { XDG_DATA_HOME: posix15.join(TASK_ROOT, "login") } },
44473
44857
  args: (launch) => launch.args
44474
44858
  }
44475
44859
  ];
@@ -44632,7 +45016,7 @@ import { randomBytes as randomBytes10 } from "crypto";
44632
45016
  import { mkdtempSync as mkdtempSync6, realpathSync as realpathSync14, rmSync as rmSync13, writeFileSync as writeFileSync11 } from "fs";
44633
45017
  import { createServer as createServer3 } from "net";
44634
45018
  import { release, tmpdir as tmpdir7, type as osType } from "os";
44635
- import { join as join46 } from "path";
45019
+ import { join as join45 } from "path";
44636
45020
 
44637
45021
  // src/services/container/guaranteeProbe.ts
44638
45022
  var METADATA = "169.254.169.254:80";
@@ -44770,8 +45154,8 @@ var OUTSIDE = "1.1.1.1:443";
44770
45154
  var OUTSIDE_NAME = "example.com";
44771
45155
  var PROBE_MS = 12e4;
44772
45156
  function plantFile() {
44773
- const dir = mkdtempSync6(join46(realpathSync14(tmpdir7()), "ordewell-canary-"));
44774
- const file = join46(dir, "canary");
45157
+ const dir = mkdtempSync6(join45(realpathSync14(tmpdir7()), "ordewell-canary-"));
45158
+ const file = join45(dir, "canary");
44775
45159
  writeFileSync11(file, randomBytes10(16).toString("hex"));
44776
45160
  return { file, remove: () => rmSync13(dir, { recursive: true, force: true }) };
44777
45161
  }
@@ -44781,9 +45165,9 @@ function listenOnLoopback() {
44781
45165
  hits += 1;
44782
45166
  socket.destroy();
44783
45167
  });
44784
- return new Promise((resolve17, reject) => {
45168
+ return new Promise((resolve18, reject) => {
44785
45169
  server4.once("error", reject);
44786
- server4.listen(0, "127.0.0.1", () => resolve17({ port: server4.address().port, hits: () => hits, close: () => server4.close() }));
45170
+ server4.listen(0, "127.0.0.1", () => resolve18({ port: server4.address().port, hits: () => hits, close: () => server4.close() }));
44787
45171
  });
44788
45172
  }
44789
45173
  async function withCanaries(use) {
@@ -44847,7 +45231,7 @@ var SpawnedDockerCli = class {
44847
45231
  }
44848
45232
  async call(args, { input, env, timeoutMs = CALL_TIMEOUT_MS, stdoutTo } = {}) {
44849
45233
  const child = spawn2("docker", [...args], { env: await this.environment(env), stdio: ["pipe", "pipe", "pipe"] });
44850
- return new Promise((resolve17) => {
45234
+ return new Promise((resolve18) => {
44851
45235
  let stdout = "";
44852
45236
  let stderr = "";
44853
45237
  let written = 0;
@@ -44873,7 +45257,7 @@ var SpawnedDockerCli = class {
44873
45257
  child.stdin.end(input);
44874
45258
  const finish2 = (code) => {
44875
45259
  clearTimeout(timer);
44876
- const done = () => resolve17({ code, stdout, stderr, ...overflowed ? { overflowed: true } : {} });
45260
+ const done = () => resolve18({ code, stdout, stderr, ...overflowed ? { overflowed: true } : {} });
44877
45261
  if (sink) sink.end(done);
44878
45262
  else done();
44879
45263
  };
@@ -44978,8 +45362,8 @@ function listening(entry) {
44978
45362
  entry.stderr?.on("data", (chunk) => {
44979
45363
  said2 = (said2 + chunk.toString()).slice(-STDERR_TAIL_CHARS2);
44980
45364
  });
44981
- return new Promise((resolve17, reject) => {
44982
- entry.stdout?.once("data", () => resolve17());
45365
+ return new Promise((resolve18, reject) => {
45366
+ entry.stdout?.once("data", () => resolve18());
44983
45367
  entry.once("error", reject);
44984
45368
  entry.once("close", () => reject(new Error(`The egress sidecar ended before it listened${said2.trim() ? `: ${said2.trim()}` : "."}`)));
44985
45369
  });
@@ -45113,20 +45497,20 @@ send(READY, 0);
45113
45497
  var LeaseRelay = class {
45114
45498
  constructor(entry) {
45115
45499
  this.entry = entry;
45116
- this.ready = new Promise((resolve17, reject) => {
45117
- this.markReady = resolve17;
45500
+ this.ready = new Promise((resolve18, reject) => {
45501
+ this.markReady = resolve18;
45118
45502
  this.failReady = reject;
45119
45503
  });
45120
45504
  this.ready.catch(() => void 0);
45121
- this.ended = new Promise((resolve17) => {
45505
+ this.ended = new Promise((resolve18) => {
45122
45506
  entry.once("close", () => {
45123
45507
  this.gone();
45124
- resolve17();
45508
+ resolve18();
45125
45509
  });
45126
45510
  entry.once("error", (err) => {
45127
45511
  this.stderrTail += err.message;
45128
45512
  this.gone();
45129
- resolve17();
45513
+ resolve18();
45130
45514
  });
45131
45515
  });
45132
45516
  entry.stdin?.on("error", () => void 0);
@@ -45163,8 +45547,8 @@ var LeaseRelay = class {
45163
45547
  if (known) return known.listening;
45164
45548
  let heard;
45165
45549
  let failed2;
45166
- const listening2 = new Promise((resolve17, reject) => {
45167
- heard = resolve17;
45550
+ const listening2 = new Promise((resolve18, reject) => {
45551
+ heard = resolve18;
45168
45552
  failed2 = reject;
45169
45553
  });
45170
45554
  this.forwards.set(containerPort, { hostPort, listening: listening2, heard, failed: failed2 });
@@ -45199,9 +45583,9 @@ var LeaseRelay = class {
45199
45583
  this.send(CONNECT, conn, port);
45200
45584
  });
45201
45585
  this.exposed.add(server4);
45202
- await new Promise((resolve17, reject) => {
45586
+ await new Promise((resolve18, reject) => {
45203
45587
  server4.once("error", reject);
45204
- server4.listen(0, "127.0.0.1", () => resolve17());
45588
+ server4.listen(0, "127.0.0.1", () => resolve18());
45205
45589
  });
45206
45590
  return server4.address().port;
45207
45591
  }
@@ -45296,8 +45680,8 @@ async function tryVolume(cli, volume) {
45296
45680
  const removed = await cli.call(["volume", "rm", "-f", volume]);
45297
45681
  if (removed.code === 0) return null;
45298
45682
  if (tried === VOLUME_TRIES) return removed.stderr.trim();
45299
- await new Promise((resolve17) => {
45300
- setTimeout(resolve17, VOLUME_WAIT_MS);
45683
+ await new Promise((resolve18) => {
45684
+ setTimeout(resolve18, VOLUME_WAIT_MS);
45301
45685
  });
45302
45686
  }
45303
45687
  }
@@ -45362,9 +45746,9 @@ async function reclaimContainers(tree, raw, { cli = new SpawnedDockerCli(), tell
45362
45746
  }
45363
45747
 
45364
45748
  // src/services/container/pushGate.ts
45365
- import { accessSync, constants as constants2, mkdtempSync as mkdtempSync7, realpathSync as realpathSync15, rmSync as rmSync14 } from "fs";
45749
+ import { accessSync, constants as constants2, mkdtempSync as mkdtempSync7, rmSync as rmSync14 } from "fs";
45366
45750
  import { tmpdir as tmpdir8 } from "os";
45367
- import { isAbsolute as isAbsolute13, join as join47, relative as relative18, resolve as resolve16, sep as sep11 } from "path";
45751
+ import { isAbsolute as isAbsolute12, join as join46, relative as relative17, resolve as resolve17, sep as sep10 } from "path";
45368
45752
  var FSCK = ["-c", "transfer.fsckObjects=true", "-c", "fetch.fsckObjects=true"];
45369
45753
  var LANDING_HOOKS = ["pre-commit", "prepare-commit-msg", "commit-msg", "post-commit", "pre-merge-commit", "post-merge", "post-checkout", "post-rewrite", "reference-transaction", "post-index-change"];
45370
45754
  var PushRefused = class extends Error {
@@ -45396,8 +45780,8 @@ async function takeThroughGate(invoker, repo, bundle, { ref: ref2, base }) {
45396
45780
  async function hooksWritten(invoker, repo, base, snapshot) {
45397
45781
  const top = (await git(invoker, repo, ["rev-parse", "--show-toplevel"])).trim();
45398
45782
  const path52 = (await git(invoker, repo, ["rev-parse", "--git-path", "hooks"])).trim();
45399
- const given = resolve16(top, path52);
45400
- const folders = [.../* @__PURE__ */ new Set([given, realOf(given)])].map((dir) => relative18(top, dir).split(sep11).join("/").toLowerCase()).filter((dir) => dir !== ".." && !dir.startsWith("../") && !isAbsolute13(dir));
45783
+ const given = resolve17(top, path52);
45784
+ const folders = [.../* @__PURE__ */ new Set([given, realOf(given)])].map((dir) => relative17(top, dir).split(sep10).join("/").toLowerCase()).filter((dir) => dir !== ".." && !dir.startsWith("../") && !isAbsolute12(dir));
45401
45785
  if (folders.length === 0) return [];
45402
45786
  const changed = (await git(invoker, repo, ["diff-tree", "-r", "-z", "--name-only", "--no-renames", base, snapshot])).split("\0").filter(Boolean);
45403
45787
  return changed.filter((file) => {
@@ -45407,20 +45791,20 @@ async function hooksWritten(invoker, repo, base, snapshot) {
45407
45791
  }
45408
45792
  function realOf(path52) {
45409
45793
  try {
45410
- return realpathSync15(path52);
45794
+ return realPathOf(path52);
45411
45795
  } catch {
45412
45796
  return path52;
45413
45797
  }
45414
45798
  }
45415
45799
  async function checkObjects(invoker, repo, snapshot, base) {
45416
- const scratch = mkdtempSync7(join47(tmpdir8(), "ordewell-gate-"));
45800
+ const scratch = mkdtempSync7(join46(tmpdir8(), "ordewell-gate-"));
45417
45801
  try {
45418
- const prefix = join47(scratch, "taken");
45802
+ const prefix = join46(scratch, "taken");
45419
45803
  const packed = await tryGit(invoker, repo, ["pack-objects", "--revs", "-q", prefix], `${snapshot}
45420
45804
  ^${base}
45421
45805
  `);
45422
45806
  if (!packed.ok) throw new PushRefused(`git could not read what it holds (${packed.stderr.trim()})`);
45423
- const checked = await tryGit(invoker, repo, ["index-pack", "--strict", "-o", join47(scratch, "checked.idx"), `${prefix}-${packed.stdout.trim()}.pack`]);
45807
+ const checked = await tryGit(invoker, repo, ["index-pack", "--strict", "-o", join46(scratch, "checked.idx"), `${prefix}-${packed.stdout.trim()}.pack`]);
45424
45808
  if (!checked.ok) throw new PushRefused(`git would not take it (${checked.stderr.trim()})`);
45425
45809
  } finally {
45426
45810
  rmSync14(scratch, { recursive: true, force: true });
@@ -45435,10 +45819,10 @@ async function restoreSnapshot(invoker, worktree, snapshot, linked) {
45435
45819
  await run("reset", "-q");
45436
45820
  }
45437
45821
  async function hooksLandingWouldRun(invoker, worktree) {
45438
- const dir = resolve16(worktree, (await git(invoker, worktree, ["rev-parse", "--git-path", "hooks"])).trim());
45822
+ const dir = resolve17(worktree, (await git(invoker, worktree, ["rev-parse", "--git-path", "hooks"])).trim());
45439
45823
  return LANDING_HOOKS.filter((hook) => {
45440
45824
  try {
45441
- accessSync(resolve16(dir, hook), constants2.X_OK);
45825
+ accessSync(resolve17(dir, hook), constants2.X_OK);
45442
45826
  return true;
45443
45827
  } catch {
45444
45828
  return false;
@@ -45546,7 +45930,7 @@ var DockerExecutionBackend = class {
45546
45930
  */
45547
45931
  async preflight(runner, model) {
45548
45932
  const setupCommand = this.options.setupCommand?.();
45549
- const { problems, settings } = await inspectReadiness(this.options.settings, { cli: this.cli, broker: this.broker, agent: runner !== null, ...runner ? { runner } : {}, ...setupCommand ? { setupCommand } : {} });
45933
+ const { problems, settings } = await inspectReadiness(this.options.settings, { cli: this.cli, broker: this.broker, ...this.options.platform ? { platform: this.options.platform } : {}, agent: runner !== null, ...runner ? { runner } : {}, ...setupCommand ? { setupCommand } : {} });
45550
45934
  if (!settings) throw new Error(`This session runs tasks in containers, and this task cannot start in one. ${describeProblems(problems)}`);
45551
45935
  const refusal4 = runner && settings.login.kind === "broker" ? brokerRefusal(runner, model) : null;
45552
45936
  if (refusal4) throw new Error(`This session runs tasks in containers, and this task cannot start in one. ${refusal4}`);
@@ -45573,7 +45957,7 @@ var DockerExecutionBackend = class {
45573
45957
  }
45574
45958
  async workingDirectory(opened2) {
45575
45959
  const { worktree, writable, cwd } = opened2.workspace;
45576
- return posix13.join(WORK_ROOT, worktree ? relative19(writable ?? cwd, cwd).split(sep12).join("/") : await this.checkoutFolder(cwd));
45960
+ return posix16.join(WORK_ROOT, worktree ? relative18(writable ?? cwd, cwd).split(sep11).join("/") : await this.checkoutFolder(cwd));
45577
45961
  }
45578
45962
  async start({ runner, settings, spec, opened: opened2, repos }, signal) {
45579
45963
  const taskId = spec.task.id;
@@ -45811,7 +46195,7 @@ var DockerExecutionBackend = class {
45811
46195
  const moved = /* @__PURE__ */ new Map();
45812
46196
  for (const file of launch.files) {
45813
46197
  const inside2 = `/tmp/ordewell/${launchNumber}-${basename7(file)}`;
45814
- const wrote = await this.cli.call(["exec", "-i", box.name, "sh", "-c", 'umask 077; mkdir -p /tmp/ordewell; cat > "$0"', inside2], { input: readFileSync17(file) });
46198
+ const wrote = await this.cli.call(["exec", "-i", box.name, "sh", "-c", 'umask 077; mkdir -p /tmp/ordewell; cat > "$0"', inside2], { input: readFileSync18(file) });
45815
46199
  if (wrote.code !== 0) throw new Error(`Could not hand the runner its configuration: ${wrote.stderr.trim()}`);
45816
46200
  moved.set(file, inside2);
45817
46201
  }
@@ -45933,10 +46317,10 @@ var DockerExecutionBackend = class {
45933
46317
  */
45934
46318
  bringBack(box) {
45935
46319
  box.bringing ??= (async () => {
45936
- const dir = mkdtempSync8(join48(tmpdir9(), "ordewell-export-"));
46320
+ const dir = mkdtempSync8(join47(tmpdir9(), "ordewell-export-"));
45937
46321
  try {
45938
46322
  const taken = [];
45939
- for (const repo of box.repos) taken.push({ repo, snapshot: await this.take(box, repo, join48(dir, `${taken.length}.bundle`)) });
46323
+ for (const repo of box.repos) taken.push({ repo, snapshot: await this.take(box, repo, join47(dir, `${taken.length}.bundle`)) });
45940
46324
  for (const { repo, snapshot } of taken) await restoreSnapshot(this.git, repo.worktree, snapshot, repo.linked);
45941
46325
  } catch (err) {
45942
46326
  await this.cli.call(["volume", "create", ...this.labels(box.taskId), this.heldVolume(box.taskId)]);
@@ -49294,12 +49678,12 @@ var Session = class {
49294
49678
  return !task2 || reportEnded(task2) || task2.status !== "in_progress" && !this.orchestrator.getAttempt(taskId);
49295
49679
  };
49296
49680
  if (over() || signal?.aborted) return Promise.resolve();
49297
- return new Promise((resolve17) => {
49681
+ return new Promise((resolve18) => {
49298
49682
  const done = () => {
49299
49683
  clearTimeout(timer);
49300
49684
  unsubscribe();
49301
49685
  signal?.removeEventListener("abort", done);
49302
- resolve17();
49686
+ resolve18();
49303
49687
  };
49304
49688
  const timer = setTimeout(done, ms);
49305
49689
  const check2 = () => {
@@ -50495,7 +50879,7 @@ ${pins.join("\n")}` : goal;
50495
50879
  slotForTurn(signal) {
50496
50880
  if (this.turnRoom()) return null;
50497
50881
  if (signal?.aborted) return Promise.reject(new PlannerTurnStoppedError());
50498
- return new Promise((resolve17, reject) => {
50882
+ return new Promise((resolve18, reject) => {
50499
50883
  const onAbort = () => {
50500
50884
  if (this.openingsWaiting.delete(end)) end(new PlannerTurnStoppedError());
50501
50885
  };
@@ -50511,7 +50895,7 @@ ${pins.join("\n")}` : goal;
50511
50895
  this.roomWaiter = null;
50512
50896
  this.openingsWaiting.delete(end);
50513
50897
  signal?.removeEventListener("abort", onAbort);
50514
- resolve17();
50898
+ resolve18();
50515
50899
  return true;
50516
50900
  };
50517
50901
  });
@@ -50522,7 +50906,7 @@ ${pins.join("\n")}` : goal;
50522
50906
  return null;
50523
50907
  }
50524
50908
  if (signal?.aborted) return Promise.reject(new PlannerTurnStoppedError());
50525
- return new Promise((resolve17, reject) => {
50909
+ return new Promise((resolve18, reject) => {
50526
50910
  const onAbort = () => {
50527
50911
  if (this.openingsWaiting.delete(end)) end(new PlannerTurnStoppedError());
50528
50912
  };
@@ -50536,7 +50920,7 @@ ${pins.join("\n")}` : goal;
50536
50920
  if (!this.openingsWaiting.delete(end)) return;
50537
50921
  signal?.removeEventListener("abort", onAbort);
50538
50922
  this.assertPlannerReady();
50539
- }).then(resolve17, reject);
50923
+ }).then(resolve18, reject);
50540
50924
  });
50541
50925
  }
50542
50926
  /**
@@ -50716,8 +51100,8 @@ ${pins.join("\n")}` : goal;
50716
51100
  if (!pending) return null;
50717
51101
  const held2 = pending.held;
50718
51102
  if (!held2) return this.turns.follow(input, forced);
50719
- return new Promise((resolve17, reject) => {
50720
- held2.push({ input, forced, resolve: resolve17, reject });
51103
+ return new Promise((resolve18, reject) => {
51104
+ held2.push({ input, forced, resolve: resolve18, reject });
50721
51105
  });
50722
51106
  }
50723
51107
  /**
@@ -51967,8 +52351,8 @@ var StructuredSession = class extends AbstractRunnerSession {
51967
52351
  if (this.stopping) return this.stopping;
51968
52352
  if (this.exited) return Promise.resolve();
51969
52353
  let woundDown;
51970
- this.stopping = new Promise((resolve17) => {
51971
- woundDown = resolve17;
52354
+ this.stopping = new Promise((resolve18) => {
52355
+ woundDown = resolve18;
51972
52356
  });
51973
52357
  void this.windDown().catch(() => this.kill()).then(woundDown);
51974
52358
  return this.stopping;
@@ -51997,7 +52381,7 @@ var StructuredSession = class extends AbstractRunnerSession {
51997
52381
  }
51998
52382
  /** Whether `turn` closed within the deadline once interrupted. */
51999
52383
  async turnClosed(turn, adapter, deadline) {
52000
- const closed = new Promise((resolve17) => this.structuredEmitter.once("turnEnd", () => resolve17()));
52384
+ const closed = new Promise((resolve18) => this.structuredEmitter.once("turnEnd", () => resolve18()));
52001
52385
  adapter.interrupt(Math.max(0, deadline - Date.now())).catch(() => false);
52002
52386
  return await this.within(closed, deadline) && turn.ended;
52003
52387
  }
@@ -52008,7 +52392,7 @@ var StructuredSession = class extends AbstractRunnerSession {
52008
52392
  gone() {
52009
52393
  const { signal } = this.ended;
52010
52394
  if (signal.aborted) return Promise.resolve();
52011
- return new Promise((resolve17) => signal.addEventListener("abort", () => resolve17(), { once: true }));
52395
+ return new Promise((resolve18) => signal.addEventListener("abort", () => resolve18(), { once: true }));
52012
52396
  }
52013
52397
  turnState() {
52014
52398
  return this.state;
@@ -52160,7 +52544,7 @@ var StructuredSession = class extends AbstractRunnerSession {
52160
52544
  }
52161
52545
  async interruptTurn(turn, adapter) {
52162
52546
  const grace = this.launch.interruptGraceMs;
52163
- const ended2 = new Promise((resolve17) => this.structuredEmitter.once("turnEnd", () => resolve17()));
52547
+ const ended2 = new Promise((resolve18) => this.structuredEmitter.once("turnEnd", () => resolve18()));
52164
52548
  const acknowledged = await settleWithin(adapter.interrupt(grace).catch(() => false), { timeoutMs: grace, onTimeout: () => false });
52165
52549
  if (acknowledged) {
52166
52550
  const settled = await settleWithin(ended2.then(() => true), { timeoutMs: grace, onTimeout: () => false });
@@ -52592,11 +52976,11 @@ var RunnerRegistry = class {
52592
52976
  };
52593
52977
 
52594
52978
  // src/plugins/removedPluginNotice.ts
52595
- import * as fs26 from "fs";
52979
+ import * as fs27 from "fs";
52596
52980
  import * as path50 from "path";
52597
52981
  function isManifestFile(file) {
52598
52982
  try {
52599
- return fs26.statSync(file).isFile();
52983
+ return fs27.statSync(file).isFile();
52600
52984
  } catch {
52601
52985
  return false;
52602
52986
  }
@@ -52604,7 +52988,7 @@ function isManifestFile(file) {
52604
52988
  function removedPluginNotice(dataDir = globalDataDir()) {
52605
52989
  const directory = path50.join(dataDir, "plugins");
52606
52990
  try {
52607
- const hasManifest = isManifestFile(path50.join(directory, "manifest.json")) || fs26.readdirSync(directory, { withFileTypes: true }).some(
52991
+ const hasManifest = isManifestFile(path50.join(directory, "manifest.json")) || fs27.readdirSync(directory, { withFileTypes: true }).some(
52608
52992
  (entry) => (entry.isDirectory() || entry.isSymbolicLink()) && isManifestFile(path50.join(directory, entry.name, "manifest.json"))
52609
52993
  );
52610
52994
  if (hasManifest) return "Plugin runners were removed; manifests in ~/.ordewell/plugins/ are ignored. See the CHANGELOG.";
@@ -52615,7 +52999,7 @@ function removedPluginNotice(dataDir = globalDataDir()) {
52615
52999
  }
52616
53000
 
52617
53001
  // src/utils/stateStore.ts
52618
- import * as fs27 from "fs";
53002
+ import * as fs28 from "fs";
52619
53003
  import * as path51 from "path";
52620
53004
  var STATE_FILE2 = "state.json";
52621
53005
  function getStatePath(baseDir) {
@@ -52633,9 +53017,9 @@ function saveState(plan, baseDir, sessionId) {
52633
53017
  function loadState(baseDir, logger = defaultLogger) {
52634
53018
  const dir = baseDir ?? process.cwd();
52635
53019
  const statePath = getStatePath(dir);
52636
- if (!fs27.existsSync(statePath)) return null;
53020
+ if (!fs28.existsSync(statePath)) return null;
52637
53021
  try {
52638
- const raw = fs27.readFileSync(statePath, "utf-8");
53022
+ const raw = fs28.readFileSync(statePath, "utf-8");
52639
53023
  const parsed = JSON.parse(raw);
52640
53024
  if (!Array.isArray(parsed.runners)) {
52641
53025
  logger.warn("stateStore", `rejecting state from ${statePath}: old format (scalar "runner" instead of "runners" array). Please re-plan.`);
@@ -52659,11 +53043,11 @@ function loadState(baseDir, logger = defaultLogger) {
52659
53043
  function clearState(baseDir) {
52660
53044
  const dir = baseDir ?? process.cwd();
52661
53045
  const statePath = getStatePath(dir);
52662
- if (fs27.existsSync(statePath)) fs27.unlinkSync(statePath);
53046
+ if (fs28.existsSync(statePath)) fs28.unlinkSync(statePath);
52663
53047
  }
52664
53048
  function stateExists(baseDir) {
52665
53049
  const dir = baseDir ?? process.cwd();
52666
- return fs27.existsSync(getStatePath(dir));
53050
+ return fs28.existsSync(getStatePath(dir));
52667
53051
  }
52668
53052
 
52669
53053
  // src/services/selectPlanner.ts