@awebai/oats 0.55.1 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/bin/oats.mjs +96 -72
  2. package/docs/capabilities.md +67 -3
  3. package/docs/design/2026-09-23-workspace-module-contracts.md +27 -3
  4. package/docs/desktop-cli-api.md +375 -37
  5. package/docs/desktop-instance-start.md +105 -12
  6. package/docs/desktop.md +65 -11
  7. package/docs/execution-targets.md +184 -9
  8. package/docs/harness-trust.md +128 -11
  9. package/docs/implementation.md +153 -11
  10. package/docs/integrations.md +5 -3
  11. package/docs/knowledge.md +117 -43
  12. package/docs/official-catalog.md +3 -3
  13. package/docs/packages.md +12 -12
  14. package/docs/release-lane.md +26 -1
  15. package/docs/release-notes/v0.56.0.md +699 -0
  16. package/docs/release-notes/v0.57.0.md +283 -0
  17. package/docs/schedules.md +8 -3
  18. package/docs/servers.md +21 -5
  19. package/docs/souls-and-instances.md +134 -19
  20. package/docs/tui.md +215 -31
  21. package/docs/upgrading.md +4 -1
  22. package/docs/workspaces.md +26 -6
  23. package/lib/automations.mjs +3 -4
  24. package/lib/bounded-read.mjs +18 -0
  25. package/lib/capability-show.mjs +13 -2
  26. package/lib/claim.mjs +3 -4
  27. package/lib/core.mjs +919 -278
  28. package/lib/errors.mjs +39 -0
  29. package/lib/harness-trust-write.mjs +119 -40
  30. package/lib/harness-trust.mjs +31 -18
  31. package/lib/instance-inspect.mjs +160 -11
  32. package/lib/instance-lifecycle.mjs +90 -37
  33. package/lib/packages.mjs +8 -5
  34. package/lib/pi-bridge.mjs +18 -19
  35. package/lib/remote.mjs +88 -51
  36. package/lib/retire-output.mjs +9 -4
  37. package/lib/schedule.mjs +3 -4
  38. package/lib/servers.mjs +39 -6
  39. package/lib/session-viewer.mjs +25 -1
  40. package/lib/triggers.mjs +3 -4
  41. package/lib/workspace.mjs +6 -6
  42. package/lib/worktree.mjs +33 -8
  43. package/lib/write-through-private-file.mjs +26 -0
  44. package/package-catalog.json +2 -2
  45. package/package.json +1 -1
  46. package/packages/client/cli-adapter.mjs +108 -13
  47. package/packages/client/cli-locator.mjs +16 -14
  48. package/packages/client/deployment-panel.mjs +4 -3
  49. package/packages/client/display-text.mjs +2 -1
  50. package/packages/client/instance-events-contract.mjs +4 -3
  51. package/packages/client/instance-lifecycle.mjs +235 -0
  52. package/packages/client/instance-presentation.mjs +9 -0
  53. package/packages/client/instance-tree.mjs +10 -8
  54. package/packages/client/kernel-lines.mjs +3 -3
  55. package/packages/client/launch-contract.mjs +11 -0
  56. package/packages/client/launch-prompt-outcome.mjs +1 -1
  57. package/packages/client/lifecycle-cli.mjs +12 -6
  58. package/packages/client/lifecycle-confirmation.mjs +407 -0
  59. package/packages/client/lifecycle-contract.mjs +6 -2
  60. package/packages/client/own-codes.mjs +1 -0
  61. package/packages/client/panel-views.mjs +39 -2
  62. package/packages/client/readiness-contract.mjs +2 -2
  63. package/packages/client/remote-roster.mjs +50 -5
  64. package/packages/client/roster-sections.mjs +3 -3
  65. package/packages/client/session-start.mjs +98 -0
  66. package/packages/client/start-gate.mjs +46 -0
  67. package/packages/client/start-messages.mjs +17 -0
  68. package/packages/client/workspace-views.mjs +2 -2
  69. package/packages/tui/README.md +21 -8
  70. package/packages/tui/lib/actions.mjs +11 -2
  71. package/packages/tui/lib/client.mjs +9 -2
  72. package/packages/tui/lib/config.mjs +39 -9
  73. package/packages/tui/lib/main.mjs +168 -20
  74. package/packages/tui/lib/model.mjs +315 -13
  75. package/packages/tui/lib/open.mjs +45 -0
  76. package/packages/tui/lib/read.mjs +171 -16
  77. package/packages/tui/lib/store.mjs +171 -10
  78. package/packages/tui/lib/term/tty.mjs +71 -12
  79. package/packages/tui/lib/views/act.mjs +85 -0
  80. package/packages/tui/lib/views/frame.mjs +145 -33
  81. package/packages/tui/lib/views/help.mjs +46 -11
  82. package/skills/oats-getting-started/SKILL.md +6 -3
package/lib/core.mjs CHANGED
@@ -57,7 +57,7 @@ import { oatsError, afterEndedSteps, afterFirstEffect, asKernelError, BEFORE_EFF
57
57
  import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
58
58
  import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchConfigUnknownFix, launchLayers, launchPreferenceUnmatched, launchPreferenceUnmatchedProblem, launchReport, selectionFrom } from "./launch-preference.mjs";
59
59
  import { shq, shellWord } from "./shell-word.mjs";
60
- import { claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigDir } from "./harness-trust.mjs";
60
+ import { CONFIG_DIR_VAR, HARNESS_FOLDER_VAR, claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigFolder } from "./harness-trust.mjs";
61
61
  async function materializePreparedDefault(prepared, home) { const m = await import("./instance-resolution.mjs"); return m.materializePrepared(prepared, home); }
62
62
  // Capability rows for a PREPARED spawn (workspace model): the one function that
63
63
  // turns a Resolution's modules into the row shape hooks/environment/requirements/
@@ -84,6 +84,7 @@ import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes } from "./tree-copy.
84
84
  import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
85
85
  import { systemTool } from "./system-tools.mjs";
86
86
  import { creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
87
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
87
88
  /** The package and capability id grammar (namespaced, lowercase): an id names a
88
89
  * directory (a home's module copy), so no path spelling fits it. */
89
90
  const PACKAGE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
@@ -1223,22 +1224,26 @@ export function resolvedFromHome(home, meta, { teams, defaultTeam, teamsSource }
1223
1224
  * Note `e.isDirectory()` is false for a symlinked child (readdir uses lstat
1224
1225
  * semantics), so a skill directory represented by a symlink contributes nothing.
1225
1226
  * That is deliberate and matches what actually gets copied; preflight reporting
1226
- * such a tree as empty is the point, not a gap. */
1227
- function skillEntriesIn(tree) {
1227
+ * such a tree as empty is the point, not a gap. `oats inspect --soul --skills`
1228
+ * (lib/instance-inspect.mjs soulSkills) lists a soul's skills by it too, with
1229
+ * `strict`: a marker that cannot be examined (EACCES, ELOOP, …) throws instead
1230
+ * of counting as absent, so "could not tell" never reads as "no skill". */
1231
+ export function skillEntriesIn(tree, { strict = false } = {}) {
1228
1232
  if (!tree || !existsSync(tree)) return [];
1229
- if (hasSkillDoc(tree)) return [{ name: basename(tree), src: tree }];
1233
+ if (hasSkillDoc(tree, strict)) return [{ name: basename(tree), src: tree }];
1230
1234
  const out = [];
1231
1235
  for (const e of readdirSync(tree, { withFileTypes: true })) {
1232
- if (e.isDirectory() && hasSkillDoc(join(tree, e.name))) out.push({ name: e.name, src: join(tree, e.name) });
1236
+ if (e.isDirectory() && hasSkillDoc(join(tree, e.name), strict)) out.push({ name: e.name, src: join(tree, e.name) });
1233
1237
  }
1234
1238
  return out;
1235
1239
  }
1236
1240
  /** Does this directory hold a READABLE skill document? `existsSync` is true for
1237
1241
  * a DIRECTORY named SKILL.md, which would let a tree pass every check and still
1238
1242
  * launch an instance with no readable skill (reviewer-d70bc8b). The marker must
1239
- * be a regular file. */
1240
- function hasSkillDoc(dir) {
1241
- try { return statSync(join(dir, "SKILL.md")).isFile(); } catch { return false; }
1243
+ * be a regular file. `strict`: only a missing marker is "no"; any other error throws. */
1244
+ function hasSkillDoc(dir, strict = false) {
1245
+ try { return statSync(join(dir, "SKILL.md")).isFile(); }
1246
+ catch (e) { if (strict && e?.code !== "ENOENT") throw e; return false; }
1242
1247
  }
1243
1248
 
1244
1249
  /** Enumerate every resource the resolved composition PROMISES this instance,
@@ -1871,21 +1876,76 @@ export function resolveRepo(root, repo) {
1871
1876
  return abs;
1872
1877
  }
1873
1878
 
1874
- /** The repository an attached work tree's OWNER recorded: `<owner home>/work` is the
1875
- * tree (the owner's own worktree or checkout). Undefined when the tree is not an
1876
- * instance's work/ (an integration worktree names its repository explicitly). */
1877
- function attachedOwnerRepo(workDir) {
1878
- if (typeof workDir !== "string" || !workDir) return undefined;
1879
- let tree;
1880
- try { tree = realpathSync(workDir); } catch { return undefined; }
1881
- for (const home of new Set([dirname(resolve(workDir)), dirname(tree)])) {
1879
+ /** Whose tree an attached spawn's work directory is, and of which repository: the one read both
1880
+ * questions are answered from (awebai/oats#958). An attached instance's repository is the
1881
+ * repository of the tree it is attached to, and the tree's owner is the instance in whose home it
1882
+ * is: the home's `work`, whose repository is the one that instance recorded, or one of the home's
1883
+ * extra trees, whose repository is the one extraWorktreesOf reads from Git (the test of an extra
1884
+ * tree is that function's, never the shape of the path).
1885
+ * → { owner: { name, home } | undefined, repo: string | undefined }. `owner` is the first home
1886
+ * under `root` that holds the tree: every agent dir is scanned, souls and capability-defined
1887
+ * agents alike, and the match is by path, never by name (instance names are only unique per
1888
+ * agent dir). Whether that name resolves back to that home is the caller's check. A tree in no
1889
+ * such home has no owner here; a `work` whose home is not one of them still gives the repository
1890
+ * that home recorded, as it always did. Read-only. */
1891
+ function attachedTreeOf(root, workDir) {
1892
+ const found = { owner: undefined, repo: undefined };
1893
+ if (typeof workDir !== "string" || !workDir) return found;
1894
+ const wd = resolve(workDir);
1895
+ let wdReal;
1896
+ try { wdReal = realpathSync(wd); } catch { return found; }
1897
+ // A home's work/: the repository its instance recorded. The home is the directory the path is in,
1898
+ // as given or as resolved.
1899
+ for (const home of new Set([dirname(wd), dirname(wdReal)])) {
1882
1900
  try {
1883
- if (realpathSync(join(home, "work")) !== tree) continue;
1901
+ if (realpathSync(join(home, "work")) !== wdReal) continue;
1884
1902
  const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
1885
- if (typeof meta?.repo === "string" && meta.repo) return meta.repo;
1903
+ if (typeof meta?.repo === "string" && meta.repo) { found.repo = meta.repo; break; }
1886
1904
  } catch { /* not an instance home */ }
1887
1905
  }
1888
- return undefined;
1906
+ // Lexical form of workDir with the HOME part canonicalized — checkout-mode
1907
+ // instances have work as a symlink to the shared repo, so realpath alone
1908
+ // would collide across every checkout instance; symlinked work trees only
1909
+ // match when workDir IS that home's work path.
1910
+ let wdLexical; try { wdLexical = join(realpathSync(dirname(wd)), basename(wd)); } catch { wdLexical = wd; }
1911
+ // An extra tree is compared as extraWorktreesOf compares paths, and looked for only in the home
1912
+ // the path is directly in: that function runs Git per `.work-*` entry of a home.
1913
+ const wdCanonical = canonicalHomePath(wd), treeHome = dirname(wdCanonical);
1914
+ let agentsRoot; try { agentsRoot = realpathSync(root); } catch { agentsRoot = root; }
1915
+ const hits = [];
1916
+ const candidate = (instHome, instName) => {
1917
+ let homeReal; try { homeReal = realpathSync(instHome); } catch { return; }
1918
+ try {
1919
+ if (join(homeReal, "work") === wdLexical) { hits.push({ home: instHome, name: instName }); return; }
1920
+ const wp = join(instHome, "work");
1921
+ if (!lstatSync(wp).isSymbolicLink() && realpathSync(wp) === wdReal) { hits.push({ home: instHome, name: instName }); return; }
1922
+ } catch { /* no work tree */ }
1923
+ if (hits.length || canonicalHomePath(instHome) !== treeHome) return;
1924
+ const tree = extraWorktreesOf(instHome).find((t) => canonicalHomePath(t.path) === wdCanonical);
1925
+ if (tree) hits.push({ home: instHome, name: instName, extraTreeRepo: tree.repo });
1926
+ };
1927
+ if (existsSync(agentsRoot)) {
1928
+ for (const ag of readdirSync(agentsRoot, { withFileTypes: true })) {
1929
+ if (!ag.isDirectory() || ag.name.startsWith(".")) continue;
1930
+ const dir = join(agentsRoot, ag.name, "instances");
1931
+ if (!existsSync(dir)) continue;
1932
+ for (const e of readdirSync(dir, { withFileTypes: true })) if (e.isDirectory()) candidate(join(dir, e.name), e.name);
1933
+ }
1934
+ }
1935
+ if (hits.length) {
1936
+ found.owner = { name: hits[0].name, home: hits[0].home };
1937
+ if (hits[0].extraTreeRepo !== undefined) found.repo = hits[0].extraTreeRepo;
1938
+ }
1939
+ return found;
1940
+ }
1941
+ /** The refusal of an attached spawn on a tree of no known instance: neither a home's `work` nor one
1942
+ * of its extra trees, so nothing is derived. One sentence names every flag still missing
1943
+ * (`parent`, `repo`), so one retry is enough. */
1944
+ function attachedTreeOfNoInstance(wd, { parent, repo }) {
1945
+ const what = `attached workDir ${wd} is not a known instance's <home>/work or an extra tree of a known instance's home (<home>/.work-<purpose>)`;
1946
+ if (parent && repo) return `${what}, so neither its owner nor its repository is derived — pass both: --parent <instance> (the owning instance) and --repo <repository>`;
1947
+ return parent ? `${what}, so its owner is not derived — name the owning instance explicitly (--parent <instance>)`
1948
+ : `${what}, so its repository is not derived — pass --repo <repository>`;
1889
1949
  }
1890
1950
  /** Only explicit directory execution relaxes the Git requirement. `repo` is
1891
1951
  * still the config/deployment context, never a directory we take ownership of. */
@@ -2336,7 +2396,7 @@ function oatsWindowEnvironment() {
2336
2396
  * will open a window in: `{ server, present }` from the lookup and, when `session` is not on the
2337
2397
  * OATS server and this is no preview, `env`: the environment its creation needs, read now, so that a
2338
2398
  * caller that cannot create it is refused with nothing left behind; the answer goes to
2339
- * ensureOatsTmuxSession. It is also where the harness is first looked up (expectedPanePath). Not the
2399
+ * ensureOatsTmuxSession. It is also what the launch's checks first read (expectedPaneEnvironment). Not the
2340
2400
  * guarantee: ensureOatsTmuxSession decides by what it finds when it creates, and the harness is
2341
2401
  * looked up again on the session it returns; and an environment read for a running server is read
2342
2402
  * again there when that server has gone. undefined when this process has no tmux to run: the
@@ -2350,18 +2410,28 @@ function planOatsTmuxSession(session, io, { preview = false, missingSocket } = {
2350
2410
  if (present || preview) return { server, present };
2351
2411
  return { server, present, env: oatsSessionEnvironment(session, io, { startsServer: !server }), startsServer: !server };
2352
2412
  }
2413
+ /** The names a check of a launch reads from the pane the launch will run in, never from this
2414
+ * process: where its harness is looked up, the home directory, and the three variables that move a
2415
+ * harness's configuration folder (HARNESS_CONFIG_SELECTORS). For a selector "not set" is an answer:
2416
+ * the harness then reads its default folder under HOME. For PATH and HOME it is a problem. */
2417
+ const PANE_ENV_NAMES = ["PATH", "HOME", ...Object.values(HARNESS_FOLDER_VAR)];
2353
2418
  /**
2354
- * The PATH a pane created in `session` on `socket` starts with, read as tmux decides it (spawn.c,
2355
- * environ.c), never computed from this process: the session's own entry when it has one, otherwise
2356
- * the server's global PATH. `session` null reads the global one only (a session about to be created
2357
- * on a running server). Both are read with the strict reader, as bytes.
2358
- * → `{ path, source }`, or `{ source, problem }` when the pane's PATH cannot be established: the
2359
- * session entry is an explicit clear (`unset PATH;`: the pane has no PATH at all; never substituted
2360
- * by the global one or this process's), a value the strict reader leaves out (unknown), a read that
2361
- * failed, or a server with no PATH (tmux would fall back to a compiled-in default, which OATS does not
2362
- * assume). `source` names where the PATH comes from; no value is ever in it or in `problem`.
2419
+ * The environment a pane created in `session` on `socket` starts with, for PANE_ENV_NAMES, read as
2420
+ * tmux decides it (spawn.c, environ.c), never computed from this process: for each name the
2421
+ * session's own entry when it has one, otherwise the server's global one. `session` null reads the
2422
+ * global one only (a session about to be created on a running server). One `show-environment` for
2423
+ * the session and one for the server answer every name: each is made when a name first needs it,
2424
+ * at most once, and read with the strict reader, as bytes.
2425
+ * → `{ of(name), cwd }`. `of(name)` is `{ value, source }`; `{ absent: true, source }` for a selector
2426
+ * that neither holds, or that the session clears (the server's is then not the pane's); or
2427
+ * `{ source, problem }` when the pane's value cannot be established: a read that failed, a value
2428
+ * the strict reader leaves out (unknown), and for PATH and HOME an explicit clear (`unset PATH;`:
2429
+ * the pane has none at all; never substituted by the global one or this process's) or a server with
2430
+ * none (for PATH tmux would fall back to a compiled-in default, which OATS does not assume).
2431
+ * `source` names where the value comes from; no value is ever in it or in `problem`. A problem
2432
+ * carries `remedy`: what would make that entry readable, as a tmux command on this socket.
2363
2433
  */
2364
- function panePath(socket, session, io, cwd) {
2434
+ function paneEnvironment(socket, session, io, cwd) {
2365
2435
  const read = (scope) => {
2366
2436
  const omitted = [], cleared = [];
2367
2437
  let env = null;
@@ -2371,43 +2441,181 @@ function panePath(socket, session, io, cwd) {
2371
2441
  } catch (e) { if (isKernelCode(e?.code)) throw e; }
2372
2442
  return { env, omitted, cleared };
2373
2443
  };
2374
- const decide = ({ env, omitted, cleared }, source, unset) => {
2375
- if (env === null) return { source, problem: `${source} could not be read` };
2376
- if (Object.hasOwn(env, "PATH")) return { path: env.PATH, source, cwd };
2377
- if (cleared.includes("PATH")) return { source, problem: unset };
2378
- if (omitted.includes("PATH")) return { source, problem: `${source} cannot be read as data (its value holds a $, a line break or a character tmux prints encoded)` };
2444
+ let own, global;
2445
+ const server = `the OATS tmux server (${socket})`;
2446
+ const tmuxAt = `tmux -S ${shellWord(socket)}`;
2447
+ const decide = ({ env, omitted, cleared }, name, source, holder, scope) => {
2448
+ const set = `give ${holder} a ${name} that OATS can read (${tmuxAt} set-environment ${scope} ${name} <value>)`;
2449
+ if (env === null) return { source, problem: `${source} could not be read`, remedy: `make \`${tmuxAt} show-environment ${scope} -s\` answer` };
2450
+ if (Object.hasOwn(env, name)) return { value: env[name], source };
2451
+ if (cleared.includes(name)) return HARNESS_CONFIG_SELECTORS.has(name) ? { absent: true, source: `${holder}, which clears ${name}` } : { source, problem: `${holder} clears ${name} (unset ${name}), so its panes start with no ${name} at all`, remedy: set };
2452
+ if (omitted.includes(name)) return { source, problem: `${source} cannot be read as data (its value holds a $, a line break or a character tmux prints encoded)`, remedy: HARNESS_CONFIG_SELECTORS.has(name) ? `${set}, or remove the entry (${tmuxAt} set-environment ${scope} -u ${name})` : set };
2379
2453
  return null;
2380
2454
  };
2381
- if (session) {
2382
- const own = decide(read(["-t", `=${session}`]), `the PATH of tmux session ${session}`, `tmux session ${session} clears PATH (unset PATH), so its panes start with no PATH at all`);
2383
- if (own) return own;
2384
- }
2385
- const source = `the global PATH of the OATS tmux server (${socket})`;
2386
- return decide(read(["-g"]), source, `the OATS tmux server (${socket}) clears PATH (unset PATH), so its panes start with no PATH at all`)
2387
- ?? { source, problem: `the OATS tmux server (${socket}) has no PATH, and tmux then gives a pane a compiled-in default that OATS does not assume` };
2388
- }
2389
- /** Where a launch's pane is expected to look its harness up, from a plan (planOatsTmuxSession): the
2390
- * session's or the server's PATH when a server runs, else the PATH of the environment the server
2391
- * will be created with. undefined when that is not known (no plan, or a preview with no server: a
2392
- * preview reads no creation environment); the lookup then uses this process's PATH, and the launch
2393
- * looks again on the session it actually gets. */
2394
- function expectedPanePath(plan, session, io, cwd) {
2395
- if (!plan) return undefined;
2396
- if (plan.server) return panePath(plan.server, plan.present ? session : null, io, cwd);
2397
- if (!plan.env) return undefined;
2398
- const source = "the PATH the OATS tmux server is created with";
2399
- return plan.env.PATH === undefined ? { source, problem: `${source} is not set, and tmux then gives a pane a compiled-in default that OATS does not assume` } : { path: plan.env.PATH, source, cwd };
2400
- }
2401
- /** The PATH a launch's harness is looked up on, by precedence: a PATH set in the launch
2402
- * configuration (a literal, or a reference resolved from `env`) is what the pane's command line
2403
- * applies, so the lookup uses it; otherwise the pane's own PATH (`pane`, from panePath or
2404
- * expectedPanePath; a function is called only when it is needed). A declared absolute or relative
2405
- * executable is never looked up (resolveLaunchExecutable). undefined: look up on this process's PATH. */
2406
- function launchLookup(configEnv, env, pane, configName, cwd) {
2407
- const own = configEnv?.PATH;
2408
- if (typeof own === "string") return { path: own, source: `the PATH of launch configuration ${configName}`, cwd };
2409
- if (own && typeof own === "object" && own.fromEnv) return env[own.fromEnv] === undefined ? undefined : { path: env[own.fromEnv], source: `the PATH of launch configuration ${configName} (from ${own.fromEnv})`, cwd };
2410
- return typeof pane === "function" ? pane() : pane;
2455
+ const answers = new Map();
2456
+ const of = (name) => {
2457
+ if (answers.has(name)) return answers.get(name);
2458
+ let answer = session ? decide(own ??= read(["-t", `=${session}`]), name, `the ${name} of tmux session ${session}`, `tmux session ${session}`, `-t ${shellWord(`=${session}`)}`) : null;
2459
+ if (!answer) {
2460
+ const source = `the global ${name} of ${server}`;
2461
+ answer = decide(global ??= read(["-g"]), name, source, server, "-g")
2462
+ ?? (HARNESS_CONFIG_SELECTORS.has(name) ? { absent: true, source: `${session ? `tmux session ${session} and ` : ""}${server}, which set${session ? "" : "s"} no ${name}` }
2463
+ : { source, problem: `${server} has no ${name}${name === "PATH" ? ", and tmux then gives a pane a compiled-in default that OATS does not assume" : ", so its panes start with none"}`, remedy: `give ${server} a ${name} (${tmuxAt} set-environment -g ${name} <value>)` });
2464
+ }
2465
+ answers.set(name, answer);
2466
+ return answer;
2467
+ };
2468
+ return { of, cwd };
2469
+ }
2470
+ /** Why no prediction of a pane's environment is made, as the tail of "the pane's environment is not
2471
+ * established": no server runs and this command starts none (a preview, a readiness read); this
2472
+ * process could not read the server (no tmux for it, or a preview's read that failed); the spawn
2473
+ * launches nothing; the session a start would create was refused. A tmux that is there and could
2474
+ * not say whether a server runs is a read that failed, not a server known not to run:
2475
+ * previewPaneEnvironment carries that failure (`unread`) beside the reason, so that a command that
2476
+ * writes by this answer refuses instead of writing for this process's file (`oats harness trust`).
2477
+ * A process with no tmux on its PATH makes no read at all: no prediction, and no `unread`. */
2478
+ const NO_SERVER_YET = Object.freeze({ unestablished: " until a spawn starts the OATS tmux server (none runs)" });
2479
+ const NO_PANE_READ = Object.freeze({ unestablished: ": this process could not read the OATS tmux server" });
2480
+ const NO_TMUX = Object.freeze({ unestablished: ": this process has no tmux on its PATH to read the OATS tmux server with" });
2481
+ const NO_LAUNCH = Object.freeze({ unestablished: ": this spawn launches nothing (--no-launch), and a start reads its own session's" });
2482
+ const SESSION_REFUSED = Object.freeze({ unestablished: ": the session this start would create was refused" });
2483
+ const HOME_SESSION_UNREAD = Object.freeze({ unestablished: ": this home's session record could not be read" });
2484
+ /** The environment a launch's pane is expected to have (paneEnvironment's shape), from a plan
2485
+ * (planOatsTmuxSession): the session's or the server's when a server runs, else the environment the
2486
+ * server will be created with. `{ unestablished }`, with why, when that is not known (no plan, or a
2487
+ * preview with no server: a preview reads no creation environment, which would start the user's
2488
+ * login shell); the checks then read this process's values and say so, and the launch looks again
2489
+ * on the session it actually gets. */
2490
+ function expectedPaneEnvironment(plan, session, io, cwd) {
2491
+ // No plan: this process has no tmux to ask with, or a preview's question to tmux failed.
2492
+ if (!plan) return !io?.exec && !which("tmux") ? NO_TMUX : NO_PANE_READ;
2493
+ if (plan.server) return paneEnvironment(plan.server, plan.present ? session : null, io, cwd);
2494
+ if (!plan.env) return NO_SERVER_YET;
2495
+ const of = (name) => {
2496
+ const source = `the ${name} the OATS tmux server is created with`;
2497
+ if (plan.env[name] !== undefined) return { value: plan.env[name], source };
2498
+ if (HARNESS_CONFIG_SELECTORS.has(name)) return { absent: true, source: `the environment the OATS tmux server is created with, which sets no ${name}` };
2499
+ return { source, problem: `${source} is not set${name === "PATH" ? ", and tmux then gives a pane a compiled-in default that OATS does not assume" : ", so its panes start with none"}`, remedy: "start the OATS tmux server from your own shell" };
2500
+ };
2501
+ return { of, cwd };
2502
+ }
2503
+ /**
2504
+ * The environment a launch will have, for PANE_ENV_NAMES: the one answer to "where will this launch
2505
+ * run", which every check of a launch reads (the harness lookup, folder trust, the package probe and
2506
+ * the remedy it prints) and none reads from this process in its place. For each name, by precedence:
2507
+ * 1. what the launch's command line sets: the launch configuration's `env` (a literal, or a
2508
+ * reference resolved from `env`, the spawning process: by design), over the capabilities' env
2509
+ * (`capabilities`: `{ env, owner(name) }`), which only a start's package probe is given: a
2510
+ * spawn's probe runs before its hooks, and the folder-trust check and the harness lookup do
2511
+ * not read it (awebai/oats#1041);
2512
+ * 2. a name the launch removes (`removed`: removedLaunchEnv): absent, with the launch as its
2513
+ * source, whatever the pane holds;
2514
+ * 3. the pane's (`pane`: paneEnvironment or expectedPaneEnvironment, or a function giving one,
2515
+ * called once and only when a name is not decided by 1 or 2; `pane()` on the result is that one
2516
+ * read, for a second answer over the same pane);
2517
+ * 4. no prediction (`pane` gives `{ unestablished }`, the reason as a clause): this process's
2518
+ * value, carried with that `unestablished`, so that a check that read it says so
2519
+ * (unestablishedNote) and never passes it off as the pane's; and with `unread` when the
2520
+ * reason is a read of the server that failed, which a caller that writes must refuse.
2521
+ * → `{ of(name), cwd, pane, removed }` (`removed` for launchEffectiveEnv, built on this answer);
2522
+ * `of(name)` is paneEnvironment's answer: `{ value, source }`,
2523
+ * `{ absent: true, source }` (a selector only; an empty one is not set, as the harnesses read it) or
2524
+ * `{ source, problem }`. A reference whose source is not set gives a problem marked `unresolved`:
2525
+ * the caller's own check of references refuses it (E_LAUNCH_ENV_MISSING), not a lookup.
2526
+ */
2527
+ export function launchEnvironment({ configEnv, configName, capabilities, removed = [], env = process.env, pane, cwd }) {
2528
+ let read;
2529
+ const paneAnswer = () => (read ??= { pane: (typeof pane === "function" ? pane() : pane) ?? NO_PANE_READ }).pane;
2530
+ const notThePanes = (answer) => ({ ...(answer.unestablished ? { unestablished: answer.unestablished } : {}), ...(answer.unread ? { unread: answer.unread } : {}) });
2531
+ // An empty selector is not set, as the harnesses read it; an empty HOME names no directory.
2532
+ const selector = (name, answer) => answer.value !== "" ? answer
2533
+ : HARNESS_CONFIG_SELECTORS.has(name) ? { absent: true, source: answer.source, ...notThePanes(answer) }
2534
+ : name === "HOME" ? { source: answer.source, problem: `${answer.source} is empty`, ...notThePanes(answer) } : answer;
2535
+ const of = (name) => {
2536
+ const own = Object.hasOwn(configEnv || {}, name) ? configEnv[name] : undefined;
2537
+ if (typeof own === "string") return selector(name, { value: own, source: `the ${name} of launch configuration ${configName}` });
2538
+ if (own && typeof own === "object" && own.fromEnv) {
2539
+ const source = `the ${name} of launch configuration ${configName} (from ${own.fromEnv})`;
2540
+ return env[own.fromEnv] === undefined ? { source, problem: `${name} references ${own.fromEnv}, not set on this host`, unresolved: true } : selector(name, { value: env[own.fromEnv], source });
2541
+ }
2542
+ if (capabilities?.env && Object.hasOwn(capabilities.env, name) && typeof capabilities.env[name] === "string") return selector(name, { value: capabilities.env[name], source: `the ${name} that ${capabilities.owner?.(name) || "a capability"} sets for this launch` });
2543
+ // A selector the launch removes (a manifest may declare one under a namespace it names); PATH
2544
+ // and HOME are never removed (removableLaunchEnvName).
2545
+ if (removed.includes(name) && HARNESS_CONFIG_SELECTORS.has(name)) return { absent: true, source: `this launch, which removes ${name} (a provider declares it and does not set it)` };
2546
+ const from = paneAnswer();
2547
+ if (from.of) {
2548
+ const answer = selector(name, from.of(name));
2549
+ // A relative folder is the pane's own: read against its working directory, the home.
2550
+ return HARNESS_CONFIG_SELECTORS.has(name) && typeof answer.value === "string" && cwd && !isAbsolute(answer.value) && !answer.value.startsWith("~") ? { ...answer, value: resolve(cwd, answer.value) } : answer;
2551
+ }
2552
+ const source = `this process's ${name}`;
2553
+ const why = { unestablished: from.unestablished, ...(from.unread ? { unread: from.unread } : {}) };
2554
+ // What this process itself would read: its HOME, else its user's home directory.
2555
+ const value = name === "HOME" ? env.HOME || homedir() : env[name];
2556
+ if (value !== undefined) return selector(name, { value, source, ...why });
2557
+ return HARNESS_CONFIG_SELECTORS.has(name) ? { absent: true, source, ...why } : { source, problem: `${source} is not set`, ...why };
2558
+ };
2559
+ return { of, cwd, pane: paneAnswer, removed };
2560
+ }
2561
+ /** What a check says when `names`, which it read, were not all the pane's: that the pane's
2562
+ * environment is not established and why, and what it read instead, name by name (the launch
2563
+ * configuration's value when it sets one, else this process's). null when every one was established. */
2564
+ export function unestablishedNote(launchEnv, names) {
2565
+ const answers = names.map((name) => launchEnv.of(name));
2566
+ const why = answers.find((a) => a.unestablished)?.unestablished;
2567
+ if (!why) return null;
2568
+ return `the pane's environment is not established${why}; read instead: ${answers.map((a) => `${a.source}${a.absent ? " (not set)" : ""}`).join(", ")}`;
2569
+ }
2570
+ /**
2571
+ * The pane a launch would run in, for a command that only reads (a preview, readiness, `oats
2572
+ * harness trust`): expectedPaneEnvironment's shape, and never a creation environment, so never the
2573
+ * user's login shell. For a `home` whose recorded pane a start would reuse (running, or left as a
2574
+ * shell): that pane's session on its recorded server, as the start reads it. Otherwise the session
2575
+ * a launch would open its window in (the home's recorded one; without a home, `deployment`'s
2576
+ * session default) on the OATS server, when one runs. `{ unestablished }` when none runs, when
2577
+ * this process has no tmux on its PATH to ask with, when the home's session record cannot be read,
2578
+ * and when tmux could not say whether the server runs (a refused or cut-off `list-sessions`): that
2579
+ * last one with `unread`, the failure and what has to answer, because it is no evidence that no
2580
+ * server runs.
2581
+ */
2582
+ export function previewPaneEnvironment({ home = null, meta = null, deployment = null, io } = {}) {
2583
+ let session = DEFAULT_TMUX_SESSION;
2584
+ if (home) {
2585
+ let target;
2586
+ try { ({ target } = instanceSessionTarget(home)); } catch (e) { if (!isKernelCode(e?.code)) throw e; return HOME_SESSION_UNREAD; }
2587
+ if (target) {
2588
+ let state = null;
2589
+ try { state = inspectSessionTarget(target, io); } catch (e) { if (isKernelCode(e?.code)) return HOME_SESSION_UNREAD; /* a server that has gone has no pane to reuse */ }
2590
+ if (state?.paneId && (state.present || state.state === "stopped")) return paneEnvironment(target.socket, target.session, io, home);
2591
+ }
2592
+ session = target?.session || meta?.tmux?.session || DEFAULT_TMUX_SESSION;
2593
+ } else if (deployment) {
2594
+ try { session = sessionDefaults(deployment).tmuxSession; } catch (e) { if (!isKernelCode(e?.code)) throw e; }
2595
+ }
2596
+ if (!io?.exec && !which("tmux")) return NO_TMUX;
2597
+ let found;
2598
+ try { found = oatsTmuxSessionSocket(session, io); }
2599
+ catch (e) { if (!isKernelCode(e?.code)) throw e; return { unestablished: NO_PANE_READ.unestablished, unread: `${e.message}. What has to answer, as this process: \`tmux -L ${OATS_TMUX_SERVER} list-sessions\`` }; }
2600
+ return expectedPaneEnvironment(found, session, io, home ?? undefined);
2601
+ }
2602
+ /** The one answer (launchEnvironment) for such a command: what the launch configuration sets
2603
+ * (`configEnv`), else what the launch removes (`removed`), else the pane previewPaneEnvironment
2604
+ * reads, read only when a name needs it. */
2605
+ export function previewLaunchEnvironment({ configEnv, configName, removed = [], env = process.env, home = null, meta = null, deployment = null, io } = {}) {
2606
+ return launchEnvironment({ configEnv, configName, removed, env, pane: () => previewPaneEnvironment({ home, meta, deployment, io }), cwd: home ?? undefined });
2607
+ }
2608
+ /** The PATH a launch's harness is looked up on, from the one answer (launchEnvironment): a PATH set
2609
+ * in the launch configuration is what the pane's command line applies, so the lookup uses it;
2610
+ * otherwise the pane's own. A declared absolute or relative executable is never looked up
2611
+ * (resolveLaunchExecutable). → `{ path, source, cwd }`, or `{ source, problem }` when the pane's PATH
2612
+ * cannot be established. undefined: no prediction is made (or a reference is not set, which its own
2613
+ * check refuses), and the lookup uses this process's PATH; the launch looks again on the session it
2614
+ * gets, and a preview says so (unestablishedNote). */
2615
+ function launchLookup(launchEnv) {
2616
+ const answer = launchEnv.of("PATH");
2617
+ if (answer.unestablished || answer.unresolved) return undefined;
2618
+ return answer.problem ? { source: answer.source, problem: answer.problem } : { path: answer.value, source: answer.source, cwd: launchEnv.cwd };
2411
2619
  }
2412
2620
  /**
2413
2621
  * Make sure `session` exists on the OATS server and return that server's absolute socket: the one
@@ -2494,10 +2702,13 @@ function oatsTmuxWindows(session) {
2494
2702
  try { return tmuxOatsServer(["list-windows", "-t", `=${session}`, "-F", "#{window_name}"]).split("\n").filter(Boolean); }
2495
2703
  catch { return []; }
2496
2704
  }
2497
- /** The harness's window command: no COLORFGBG in the pane, whatever the server's global environment
2498
- * holds. tmux runs the command with the server's `default-shell -c` (the user's shell: sh, bash and
2499
- * zsh all take `unset NAME;`), and the fallback shell it execs inherits the result. */
2500
- const paneCommand = (command) => `unset COLORFGBG; ${command}; exec "\${SHELL:-/bin/zsh}"`;
2705
+ /** The harness's window command: no COLORFGBG in the pane, and none of the names the launch
2706
+ * removes (`removed`: removedLaunchEnv, each a portable name), whatever the server's global or the
2707
+ * session's environment holds; the command's own prefix then sets what the launch sets. tmux runs
2708
+ * the command with the server's `default-shell -c` (the user's shell: sh, bash and zsh all take
2709
+ * `unset NAME…;`), and the fallback shell it execs inherits the result. Never persisted: the
2710
+ * recorded command (meta.command) is the launch command alone. */
2711
+ const paneCommand = (command, removed = []) => `unset ${["COLORFGBG", ...removed].join(" ")}; ${command}; exec "\${SHELL:-/bin/zsh}"`;
2501
2712
  /** The sizing options on one window, each best effort: this command's failure is ignored, nothing is
2502
2713
  * retried elsewhere and nothing global is written. */
2503
2714
  function sizeWindow(socket, windowId, io) {
@@ -2636,14 +2847,26 @@ export function requirementHarness(row) {
2636
2847
  return Object.hasOwn(row, "harness") ? row.harness : row.runtime;
2637
2848
  }
2638
2849
  function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {}) {
2639
- const probeEnv = env || process.env;
2850
+ // The probe's environment is the launch's (launchEffectiveEnv: the pane's PATH, HOME and
2851
+ // selectors, never this process's in their place), given as it is or as a function called at the
2852
+ // first requirement that applies: a launch with none reads nothing of its pane, and one whose
2853
+ // pane cannot be read is refused there (E_RUNTIME_ENDPOINT_UNKNOWN), before any probe. The
2854
+ // function may carry `note` (probeEnvironment): what the probe read in place of a pane's
2855
+ // environment that is not established, which a refusal for a missing package then says; and
2856
+ // `executable`, the program the launch's lookup selected, which the probe runs.
2857
+ let probeEnv;
2640
2858
  const found = [];
2641
2859
  const problems = [];
2642
2860
  // The session launches with the SELECTED executable (a configuration's,
2643
2861
  // the host's harness default included), so probing another binary would inspect a different
2644
2862
  // account's packages than the instance will actually use. The probe is the
2645
- // manager's controlled list subcommand; no launch argument is added to it.
2863
+ // manager's controlled list subcommand; no launch argument is added to it. A harness's own
2864
+ // name is run as the launch's lookup resolved it (`selected`), never looked up a second time by
2865
+ // the probe's exec: this process's working directory is not the pane's, so a relative entry of
2866
+ // the pane's PATH would name another program there. The remedy keeps the name as declared.
2646
2867
  const probeOpts = { context: contextDir, ...(bin ? { bin } : {}) };
2868
+ const selected = typeof env === "function" ? env.executable : undefined;
2869
+ const runOpts = bin || !selected ? probeOpts : { ...probeOpts, bin: selected };
2647
2870
  for (const cap of resolved.capabilities || []) {
2648
2871
  for (const raw of cap.manifest?.requires || []) {
2649
2872
  if (!raw || typeof raw !== "object") continue;
@@ -2657,14 +2880,18 @@ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {})
2657
2880
  const spec = raw.package;
2658
2881
  if (!safeHarnessPackageSpec(spec, harness)) { problems.push(`${cap.id}: ${harness} package spec is not a plain source token (${JSON.stringify(spec)})`); continue; }
2659
2882
  if (raw.marketplace !== undefined && !safeHarnessSourceRef(raw.marketplace)) { problems.push(`${cap.id}: marketplace is not a plain source reference (${JSON.stringify(raw.marketplace)})`); continue; }
2660
- const status = harnessPackageStatus(harness, spec, probeEnv, probeOpts);
2883
+ probeEnv ??= typeof env === "function" ? env() : env;
2884
+ const status = harnessPackageStatus(harness, spec, probeEnv, runOpts);
2661
2885
  const mgr = HARNESS_PACKAGE_MANAGERS[harness];
2662
2886
  const stepList = mgr?.steps ? mgr.steps(spec, raw, probeOpts) : [mgr?.argv(spec, raw, probeOpts) || []];
2663
2887
  // Keep the remedy in the same resource directory and selected wrapper as
2664
2888
  // the probe; quote argv, never turn a path or package selector into shell code.
2889
+ // It starts with the selector the launch will read, as the probe's environment has it (the
2890
+ // pane's, never this process's), so that running it fixes the account that starts: Claude's
2891
+ // only when the launch has one, pi's folder always (its default is under the launch's HOME).
2665
2892
  // Pi expands ~ against the launch HOME; relative selectors are anchored
2666
2893
  // to the probe cwd before the remedy changes to contextDir.
2667
- const piResourceDir = harness === "pi" ? piAgentDir(probeEnv).replace(/^~(?=$|\/)/, () => probeEnv.HOME || homedir()) : undefined;
2894
+ const piResourceDir = harness === "pi" ? piAgentDir(probeEnv).replace(/^~(?=$|\/)/, () => probeEnv.HOME) : undefined;
2668
2895
  const resourceEnv = harness === "pi" ? `PI_CODING_AGENT_DIR=${shq(resolve(piResourceDir))} `
2669
2896
  : harness === "claude" && probeEnv.CLAUDE_CONFIG_DIR ? `CLAUDE_CONFIG_DIR=${shq(resolve(probeEnv.CLAUDE_CONFIG_DIR))} ` : "";
2670
2897
  const direct = stepList.filter((a) => a.length).map((a) => resourceEnv + [bin || a[0], ...a.slice(1)].map(shq).join(" ")).join(" && ");
@@ -2707,7 +2934,8 @@ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {})
2707
2934
  }
2708
2935
  }
2709
2936
  if (problems.length) {
2710
- throw oatsError("E_HARNESS_RESOURCE_MISSING", `this instance runs on ${harness}, and its active capabilities require harness packages that are not installed:\n${problems.map((p) => ` ${p}`).join("\n")}`);
2937
+ const readInstead = typeof env === "function" ? env.note?.() : null;
2938
+ throw oatsError("E_HARNESS_RESOURCE_MISSING", `this instance runs on ${harness}, and its active capabilities require harness packages that are not installed:\n${problems.map((p) => ` ${p}`).join("\n")}${readInstead ? `\nThe account this probe read is not known to be the launch's: ${readInstead}` : ""}`);
2711
2939
  }
2712
2940
  const seen = new Set();
2713
2941
  return found.filter((x) => (seen.has(x.identity) ? false : seen.add(x.identity))).sort((a, b) => a.identity.localeCompare(b.identity));
@@ -3063,20 +3291,42 @@ function deploymentOfHome(home, meta) {
3063
3291
  }
3064
3292
  }
3065
3293
  /** Folder trust for a launch in `home` (lib/harness-trust.mjs, read-only), read from the file the
3066
- * launch's own env selects (the host `env` and the launch configuration's `configEnv`): `trustHome`
3067
- * — the codex launch trusts the home, because that file trusts its deployment root or an ancestor
3068
- * — `covered`, the `file` read (or the `problem` that keeps it unresolved) and the warning when
3069
- * folder trust is not established there. */
3070
- export function launchFolderTrust({ harness, home, meta, yolo, env = process.env, configEnv = {}, launchConfig = null }) {
3294
+ * launch itself will read: the one its selector names, else the default one under its HOME, both
3295
+ * from the one answer (`launch`: launchEnvironment), never from this process. `trustHome` — the
3296
+ * codex launch trusts the home, because that file trusts its deployment root or an ancestor —
3297
+ * `covered`, the `file` read and the warning when folder trust is not established there. `file`
3298
+ * is null with a `problem` when the launch configuration does not resolve it (`configEnv`, its
3299
+ * references read from `env`), and with `unreadable` when the pane's environment could not be
3300
+ * read: the check then warns that the file could not be established and says nothing about
3301
+ * trust, and codex's home is not trusted by a file nobody read. `note`: what was read in place of
3302
+ * a pane's environment that is not established (a readiness read with no server, a spawn that
3303
+ * launches nothing): the file read is then this process's and not known to be the launch's. The
3304
+ * warning says it, in place of where the file comes from, and readiness says it of a file that
3305
+ * does establish trust as well. A
3306
+ * codex launch under yolo trusts its home whatever a file says, so nothing of it rests on the
3307
+ * file: it carries no `note` and no `unreadable`. */
3308
+ export function launchFolderTrust({ harness, home, meta, yolo, launch, env = process.env, configEnv = {}, launchConfig = null }) {
3071
3309
  if (harness !== "codex" && harness !== "claude") return { trustHome: false, covered: false, file: null, warning: null };
3072
3310
  const root = deploymentOfHome(home, meta);
3073
- const unresolved = launchConfigDir(harness, configEnv, env)?.problem;
3074
- const launchEnv = launchEffectiveEnv({ base: env, configEnv });
3075
- const file = unresolved ? null : harnessConfigFile(harness, launchEnv);
3076
- const problem = unresolved && `launch configuration ${launchConfig || "(recorded)"}: ${unresolved}`;
3077
- const trustHome = !unresolved && harness === "codex" && codexTrustsRoot(root, { env: launchEnv });
3078
- const covered = harness === "codex" ? trustHome || yolo === true : !unresolved && claudeTrusts(home, { env: launchEnv });
3079
- return { trustHome, covered, file, ...(problem ? { problem } : {}), warning: harnessTrustWarning({ harness, root, file, problem, covered }) };
3311
+ const variable = CONFIG_DIR_VAR[harness];
3312
+ // Without a file, only codex under yolo is covered: its launch trusts the home whatever a file says.
3313
+ const yoloCovers = harness === "codex" && yolo === true;
3314
+ const unknown = (facts) => { const covered = yoloCovers; return { trustHome: false, covered, file: null, ...facts, warning: harnessTrustWarning({ harness, root, file: null, covered, ...facts }) }; };
3315
+ const unresolved = launchConfigFolder(variable, configEnv, env)?.problem;
3316
+ if (unresolved) return unknown({ problem: `launch configuration ${launchConfig || "(recorded)"}: ${unresolved}` });
3317
+ const selector = launch.of(variable);
3318
+ // The default file is under HOME: read only when the launch has no selector.
3319
+ const base = selector.absent ? launch.of("HOME") : null;
3320
+ const failed = selector.problem ? selector : base?.problem ? base : null;
3321
+ if (failed) return unknown(yoloCovers ? {} : { unreadable: `${failed.problem}${failed.remedy ? `: ${failed.remedy}` : ""}` });
3322
+ const read = base ? { HOME: base.value } : { [variable]: selector.value };
3323
+ const file = harnessConfigFile(harness, read);
3324
+ const trustHome = harness === "codex" && codexTrustsRoot(root, { env: read });
3325
+ const covered = harness === "codex" ? trustHome || yolo === true : claudeTrusts(home, { env: read });
3326
+ const names = base ? [variable, "HOME"] : [variable];
3327
+ const note = yoloCovers ? null : unestablishedNote(launch, names);
3328
+ const from = note ?? (base ? `under ${base.source}` : selector.source);
3329
+ return { trustHome, covered, file, ...(note ? { note } : {}), warning: harnessTrustWarning({ harness, root, file, from, covered }) };
3080
3330
  }
3081
3331
 
3082
3332
  /** The harness command line of a recipe. With no configuration the bytes
@@ -3186,8 +3436,11 @@ function requirementsWithArgsMessage(harness, providers, config) {
3186
3436
  * (OATS_LAUNCH_PREVIEW=1); the others run here for real when a start plans,
3187
3437
  * and not at all for a preview. A home
3188
3438
  * that records no launch recipe (an earlier kernel spawned it) is not planned:
3189
- * E_LAUNCH_LEGACY, re-spawn it from the deployment. */
3190
- export function planLaunch({ home, instance, meta, contextDir, agentLike, selection = {}, launchConfigs, resolvedCfg, env = process.env, preview = false, assertRoots, reselect = null, panePath: expectedPane }) {
3439
+ * E_LAUNCH_LEGACY, re-spawn it from the deployment. `pane`: the environment the launch's pane is
3440
+ * expected to have (paneEnvironment's shape, or a function giving it, called only when a check
3441
+ * needs a name the launch itself does not set); every check here reads it through the one answer
3442
+ * (launchEnvironment), and says so when it is not established. */
3443
+ export function planLaunch({ home, instance, meta, contextDir, agentLike, selection = {}, launchConfigs, resolvedCfg, env = process.env, preview = false, assertRoots, reselect = null, pane }) {
3191
3444
  assertRoots?.();
3192
3445
  const problems = [];
3193
3446
  const fail = (check, code, detail) => { if (!preview) throw oatsError(code, detail); problems.push({ check, ok: false, detail, code }); };
@@ -3213,12 +3466,16 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3213
3466
  // the default no longer decides (a bare --launch-config none, another harness).
3214
3467
  const frozenYolo = frozen && !(frozen.launchConfigDefault === true && !config?.frozen) ? frozen.yolo : undefined;
3215
3468
  const yolo = resolveYolo(selection.yolo ?? chosen.configuredYolo ?? (frozen ? frozenYolo : agentLike?.yolo ?? resolvedCfg?.yolo));
3469
+ // Where this launch will run (launchEnvironment): what its configuration sets, else its pane's.
3470
+ const launchEnv = launchEnvironment({ configEnv: config?.env, configName: config?.name, env, pane, cwd: home });
3216
3471
  // A frozen recipe keeps its recorded path. Otherwise a bare name is looked up where the pane will
3217
- // look it up (launchLookup: the configuration's PATH, else `expectedPane`, the start's expected
3472
+ // look it up (launchLookup: the configuration's PATH, else the pane's, the start's expected
3218
3473
  // session or server PATH; a start looks again on the session it gets).
3219
3474
  const executable = config?.frozen
3220
3475
  ? { path: config.executablePath, declared: frozen.executableDeclared ?? null, resolvedFrom: frozen.executableResolvedFrom || "recorded", missing: existsSync(config.executablePath) ? undefined : `${config.executablePath} (recorded) does not exist` }
3221
- : resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir, lookup: config?.executable?.includes("/") ? undefined : launchLookup(config?.env, env, expectedPane, config?.name, home) });
3476
+ : resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir, lookup: config?.executable?.includes("/") ? undefined : launchLookup(launchEnv) });
3477
+ // A bare name looked up on this process's PATH because the pane's is not established: said.
3478
+ const lookupNote = !config?.frozen && !config?.executable?.includes("/") && !executable.lookup ? unestablishedNote(launchEnv, ["PATH"]) : null;
3222
3479
  const notOnPane = !executable.path && executable.lookup ? executableNotOnPanePath(executable, { harness, config, from: launchChoice?.from, at: launchChoice?.at }) : null;
3223
3480
  if (notOnPane) {
3224
3481
  if (!preview) throw notOnPane;
@@ -3229,7 +3486,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3229
3486
  problems.push({ check: "executable", ok: false, detail: e.message, code: e.code });
3230
3487
  }
3231
3488
  const exeProblem = executable.path ? checkLaunchExecutable(executable.path) : notOnPane || (!config?.executable && launchChoice) ? null : executable.missing;
3232
- if (exeProblem) fail("executable", "E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${exeProblem}`); else if (!notOnPane) problems.push({ check: "executable", ok: true, detail: `${executable.path} (${executable.resolvedFrom})` });
3489
+ if (exeProblem) fail("executable", "E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${exeProblem}`); else if (!notOnPane) problems.push({ check: "executable", ok: true, detail: `${executable.path} (${executable.resolvedFrom})${lookupNote ? `; ${lookupNote}` : ""}` });
3233
3490
  // Capability contributions: recorded at spawn with provenance; a harness
3234
3491
  // switch needs the new harness's launch args from the same capabilities.
3235
3492
  let hooks = { launch: {}, env: {}, contributions: [], pending: true };
@@ -3256,6 +3513,11 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3256
3513
  } else problems.push({ check: "capabilities", ok: true, detail: "decided by the capabilities' spawn hooks" });
3257
3514
  // A configuration may not override environment a capability owns.
3258
3515
  const configEnv = config?.env || {};
3516
+ // What this launch removes (removedLaunchEnv): the names its providers declare that their payload and
3517
+ // the configuration leave out. Its checks read them as removed and its window command unsets them.
3518
+ // A plan with no recorded launch (meta null) has no payload yet: the spawn decides it.
3519
+ const declaredEnv = frozen ? homeDeclaredLaunchEnv(meta, frozen, launchManifestDir(home, meta) ? capabilityManifests(home) : {}) : [];
3520
+ const removedEnv = removedLaunchEnv({ declared: declaredEnv, hooksEnv: hooks.env, configEnv });
3259
3521
  const owned = Object.keys(configEnv).filter((n) => Object.hasOwn(hooks.env, n));
3260
3522
  if (owned.length) {
3261
3523
  const owner = (n) => hooks.contributions.find((c) => (c.env || []).includes(n))?.capability || "a capability";
@@ -3271,7 +3533,9 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3271
3533
  // probed under the launch's EFFECTIVE environment with the selected
3272
3534
  // executable, only when some requirement is declared for this harness and
3273
3535
  // every reference resolved. Configuration arguments cannot be applied to a
3274
- // package probe (it must never start a conversation), which is stated.
3536
+ // package probe (it must never start a conversation), which is stated. A pane
3537
+ // whose environment cannot be read is refused with its own code, and one that
3538
+ // is not established is probed with what the item names.
3275
3539
  if (executable.path && !missing.length && !owned.length) {
3276
3540
  const providers = frozen
3277
3541
  ? capturedProviders(meta, frozen).map((p) => { const dir = launchManifestDir(home, meta); const manifest = dir ? capabilityManifest(p.id, dir) : undefined; return manifest ? { id: p.id, manifest, settings: p.settings } : null; }).filter(Boolean)
@@ -3283,10 +3547,17 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3283
3547
  // reported verified: refused, truthfully, with the way out.
3284
3548
  fail("harness-packages", "E_LAUNCH_PROBE_UNSUPPORTED", requirementsWithArgsMessage(harness, providers, config));
3285
3549
  } else if (declared) {
3550
+ // The check fails with the code the gate refused with, never another name for it (#1047):
3551
+ // E_HARNESS_RESOURCE_MISSING, or E_RUNTIME_ENDPOINT_UNKNOWN for a pane whose environment it
3552
+ // cannot read (#993). Anything else it throws is a fault, not a missing package:
3553
+ // thrown on, as the capabilities check above does, for the command's door to answer.
3286
3554
  try {
3287
- verifyHarnessPackages(harness, { capabilities: providers }, contextDir, { ...(config?.executable || config?.frozen ? { bin: executable.path } : {}), env: launchEffectiveEnv({ base: env, hooksEnv: hooks.env, configEnv }) });
3288
- problems.push({ check: "harness-packages", ok: true, detail: `verified with ${executable.path}${(config?.args || []).length ? "; configuration arguments are not applied to the probe: native configuration the packages must see belongs in a wrapper or the environment" : ""}` });
3289
- } catch (e) { fail("harness-packages", "E_HARNESS_PACKAGE", e.message); }
3555
+ // The probe's answer also holds what the capabilities set, over the same read of the pane.
3556
+ const probeLaunch = launchEnvironment({ configEnv, configName: config?.name, capabilities: { env: hooks.env, owner: (name) => hooks.contributions.find((c) => (c.env || []).includes(name))?.capability }, removed: removedEnv, env, pane: launchEnv.pane, cwd: home });
3557
+ verifyHarnessPackages(harness, { capabilities: providers }, contextDir, { ...(config?.executable || config?.frozen ? { bin: executable.path } : {}), env: probeEnvironment(() => launchEffectiveEnv({ base: env, hooksEnv: hooks.env, configEnv, launch: probeLaunch, harness }), probeLaunch, harness, executable.path) });
3558
+ const probeNote = unestablishedNote(probeLaunch, probeNames(harness));
3559
+ problems.push({ check: "harness-packages", ok: true, detail: `verified with ${executable.path}${(config?.args || []).length ? "; configuration arguments are not applied to the probe: native configuration the packages must see belongs in a wrapper or the environment" : ""}${probeNote ? `; ${probeNote}` : ""}` });
3560
+ } catch (e) { if (!["E_HARNESS_RESOURCE_MISSING", "E_RUNTIME_ENDPOINT_UNKNOWN"].includes(e?.code)) throw e; fail("harness-packages", e.code, e.message); }
3290
3561
  } else problems.push({ check: "harness-packages", ok: true, detail: "no harness package requirement declared for this harness; nothing probed" });
3291
3562
  }
3292
3563
  const recipe = {
@@ -3297,26 +3568,84 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3297
3568
  ...(frozen?.legacy ? { legacy: { ...frozen.legacy, ...(hooks.refreshed?.length ? { replacedBy: hooks.refreshed } : {}) } } : {}),
3298
3569
  };
3299
3570
  const inst = instance || meta?.instance || basename(home);
3300
- const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, env, configEnv, launchConfig: config?.name });
3571
+ const trustLaunch = removedEnv.length ? launchEnvironment({ configEnv: config?.env, configName: config?.name, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) : launchEnv;
3572
+ const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, launch: trustLaunch, env, configEnv, launchConfig: config?.name });
3301
3573
  const command = renderLaunchRecipe(recipe, { home, instance: inst, trustHome });
3302
3574
  const selectionSource = frozen ? (config?.frozen || (!config && !selection.launchConfig && !selection.harness) ? "frozen" : "config") : "config";
3303
3575
  // A preview states what the start will do; the start states it in its own output.
3304
3576
  const previewNotices = preview ? launchStartNotices(dirname(dirname(dirname(dirname(home)))), harness, command) : [];
3305
- return { recipe, command, trustHome, harness, model: model || undefined, modelSource, yolo, config, executable, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: [...(hooks.warnings || []), ...previewNotices], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}) };
3306
- }
3307
- /** The environment a planned launch runs under: the host's base, the
3308
- * capabilities' validated env, the configuration's literals and its
3309
- * references resolved from the BASE (never from the prefix beside them).
3310
- * Package probes run under exactly this, so a CLAUDE_CONFIG_DIR or a
3311
- * credential reference selects the same account the launch will. */
3312
- export function launchEffectiveEnv({ base = process.env, hooksEnv = {}, configEnv = {} } = {}) {
3313
- const out = { ...base, ...hooksEnv };
3577
+ return { recipe, command, trustHome, declaredEnv, removedEnv, harness, model: model || undefined, modelSource, yolo, config, executable, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: [...(hooks.warnings || []), ...previewNotices], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}) };
3578
+ }
3579
+ /** The names a package probe of `harness` depends on: where its program is found and runs, the
3580
+ * home directory, and that harness's own selector. */
3581
+ const probeNames = (harness) => ["PATH", "HOME", ...(HARNESS_FOLDER_VAR[harness] ? [HARNESS_FOLDER_VAR[harness]] : [])];
3582
+ /** The package probe's environment as verifyHarnessPackages takes it: `make`, called at the first
3583
+ * requirement that applies, carrying `note`: what the probe read in place of a pane's environment
3584
+ * that is not established (unestablishedNote; null when every name is the pane's), and
3585
+ * `executable`: the absolute path the launch's lookup selected, which is the program the probe runs. */
3586
+ const probeEnvironment = (make, launchEnv, harness, executable) => Object.assign(make, { note: () => unestablishedNote(launchEnv, probeNames(harness)), executable });
3587
+ /** A PATH as a pane whose working directory is `cwd` reads it, for a process that runs elsewhere:
3588
+ * a relative entry, and an empty one, are `cwd` (lookupOnPath). Unchanged without a `cwd`. */
3589
+ const panePathFrom = (path, cwd) => cwd ? path.split(":").map((dir) => resolve(cwd, dir || ".")).join(":") : path;
3590
+ /** The environment a planned launch is judged under by what runs a program for it (the package
3591
+ * probe): this process's `base` without the names the launch removes (`launch.removed`:
3592
+ * removedLaunchEnv), the capabilities' validated env, the configuration's literals and
3593
+ * its references resolved from the BASE (never from the prefix beside them); and, for
3594
+ * PANE_ENV_NAMES, the one answer (`launch`: launchEnvironment) in place of this process's values:
3595
+ * each is set as the launch will have it, or removed when the launch will have none. So a probe
3596
+ * selects the account the launch will, and runs what its pane would. A name the probe depends on
3597
+ * (PATH, HOME, `harness`'s own selector) that cannot be established is refused
3598
+ * (E_RUNTIME_ENDPOINT_UNKNOWN: which name, where it was read, what makes it readable), never
3599
+ * answered from this process; another harness's selector in that state is left out. Every other
3600
+ * name stays this process's: only these five are read from the pane. The pane's PATH is given
3601
+ * with its relative entries resolved against the pane's working directory (panePathFrom). */
3602
+ export function launchEffectiveEnv({ base = process.env, hooksEnv = {}, configEnv = {}, launch, harness } = {}) {
3603
+ const out = { ...base };
3604
+ // What the launch removes (launch.removed: removedLaunchEnv) is not this process's either.
3605
+ for (const name of launch?.removed || []) delete out[name];
3606
+ Object.assign(out, hooksEnv);
3314
3607
  for (const [name, v] of Object.entries(configEnv || {})) {
3315
3608
  if (typeof v === "string") out[name] = v;
3316
3609
  else if (v && typeof v === "object" && v.fromEnv && base[v.fromEnv] !== undefined) out[name] = base[v.fromEnv];
3317
3610
  }
3611
+ for (const name of PANE_ENV_NAMES) {
3612
+ const answer = launch.of(name);
3613
+ if (answer.unresolved) continue; // a reference that is not set: the caller's own check refuses it
3614
+ // The pane's PATH, as the pane reads it: the probe and what it starts run in this process's
3615
+ // working directory, where a relative entry would name another directory than the pane's.
3616
+ if (!answer.problem) { if (answer.absent) delete out[name]; else out[name] = name === "PATH" && !answer.unestablished ? panePathFrom(answer.value, launch.cwd) : answer.value; continue; }
3617
+ if (probeNames(harness).includes(name)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot verify the harness packages this ${harness} launch requires: ${answer.problem}. The probe runs with the ${name} the launch's pane will have, never with this process's in its place; nothing was probed. To make it readable: set ${name} in the launch configuration (env)${answer.remedy ? `, or ${answer.remedy}` : ""}`);
3618
+ delete out[name];
3619
+ }
3318
3620
  return out;
3319
3621
  }
3622
+ /** A name a launch may remove: one a manifest could declare (the portable grammar, no core,
3623
+ * OATS_, PI_AGENT_ or process bootstrap name). A recorded list (instance.json) is read through it,
3624
+ * so no other name ever reaches the window's `unset`. */
3625
+ const removableLaunchEnvName = (name) => typeof name === "string" && PORTABLE_ENV_NAME_RE.test(name) && !CORE_LAUNCH_ENV.has(name) && !name.startsWith("OATS_") && !name.startsWith("PI_AGENT_")
3626
+ && !PROCESS_BOOTSTRAP_ENV.has(name) && !PROCESS_BOOTSTRAP_PREFIXES.some((reserved) => name.startsWith(reserved));
3627
+ /** The environment names `capabilities` declare (each one's manifest `environment`), united and sorted. */
3628
+ export const declaredLaunchEnv = (capabilities) => [...new Set((capabilities || []).flatMap((c) => Array.isArray(c?.environment) ? c.environment : []))].filter(removableLaunchEnvName).sort();
3629
+ /**
3630
+ * The names a launch removes from the environment its harness starts with (awebai/oats#1123): every
3631
+ * name a provider composed into the launch declares (`declared`: declaredLaunchEnv) that neither the
3632
+ * providers' merged payload (`hooksEnv`) nor the launch configuration (`configEnv`, the operator's
3633
+ * explicit setting on the launch's own command) sets. A declared name is its provider's to decide:
3634
+ * left out of the payload (a hook that answered without it, that failed, or none), the launch has
3635
+ * none, never a value the pane would inherit (the tmux server's or session's environment, a login
3636
+ * shell's, the Desktop's). Sorted. The window command unsets them (paneCommand), and the checks of
3637
+ * the launch read them as removed (launchEnvironment `removed`).
3638
+ */
3639
+ export function removedLaunchEnv({ declared = [], hooksEnv = {}, configEnv = {} } = {}) {
3640
+ return [...new Set(declared)].filter((name) => removableLaunchEnvName(name) && !Object.hasOwn(hooksEnv || {}, name) && !Object.hasOwn(configEnv || {}, name)).sort();
3641
+ }
3642
+ /** The names declared by the providers a home's launch composes (capturedProviders, as a start's
3643
+ * launch hooks run them): each one's manifest in the home's module copy (`manifests`:
3644
+ * capabilityManifests of the home), else the environment its spawn recorded (capabilityRuntime). */
3645
+ export function homeDeclaredLaunchEnv(meta, frozen, manifests = {}) {
3646
+ const recorded = new Map((Array.isArray(meta?.capabilityRuntime) ? meta.capabilityRuntime : []).map((b) => [b?.id, b]));
3647
+ return declaredLaunchEnv(capturedProviders(meta, frozen).map((p) => (Object.hasOwn(manifests || {}, p.id) ? manifests[p.id] : undefined) ?? recorded.get(p.id)));
3648
+ }
3320
3649
  /** argv (after the executable) and environment names of a rendered command,
3321
3650
  * from the parser: what a GUI shows, never the TASK body. */
3322
3651
  export function describeLaunchCommand(command) {
@@ -3403,11 +3732,20 @@ function* spawnBody(root, agent, o = {}) {
3403
3732
  const preparedDeployment = work === "workspace" && typeof o.prepared.deployment === "string" && o.prepared.deployment ? resolve(o.prepared.deployment) : undefined;
3404
3733
  if (preparedDeployment !== undefined && !(existsSync(preparedDeployment) && statSync(preparedDeployment).isDirectory())) throw oatsError("E_BAD_ARGS", `workspace mode: the deployment directory ${preparedDeployment} (where oats-local.yaml lives) is not a directory`);
3405
3734
  // A soul declares no repository (lead decision c3 Q6): the caller passes one, and an
3406
- // attached instance works in its owner's repository — the one the work tree's
3407
- // owning instance recorded.
3408
- const repoTarget = o.repo !== undefined ? o.repo : work === "attached" ? attachedOwnerRepo(o.workDir) : undefined;
3735
+ // attached instance's repository is the repository of the tree it is attached to
3736
+ // (attachedTreeOf, read once here: its owner is taken from the same read, below).
3737
+ const attachedTree = work === "attached" ? attachedTreeOf(root, o.workDir) : undefined;
3738
+ const repoTarget = o.repo !== undefined ? o.repo : attachedTree?.repo;
3409
3739
  const repoAbs = preparedDeployment ?? resolveExecutionContext(root, repoTarget, work);
3410
- if (!repoAbs) throw oatsError("E_BAD_ARGS", `${agent.name}: no repository for a ${work} instance — pass --repo${work === "attached" ? " (the work tree's owner records none)" : ""}`);
3740
+ if (!repoAbs) {
3741
+ // A tree of no known instance: the owner is not derived either, so a caller that named none
3742
+ // is told both at once (awebai/oats#958).
3743
+ if (work === "attached" && !attachedTree.owner) {
3744
+ const childOf = (typeof o.parent === "string" && o.parent.trim()) || (typeof o.relation === "string" && o.relation.trim() === "child" && typeof o.relativeTo === "string" && o.relativeTo.trim());
3745
+ throw oatsError("E_BAD_ARGS", attachedTreeOfNoInstance(typeof o.workDir === "string" ? resolve(o.workDir) : o.workDir, { parent: !childOf, repo: true }));
3746
+ }
3747
+ throw oatsError("E_BAD_ARGS", `${agent.name}: no repository for a ${work} instance — pass --repo${work === "attached" ? " (the work tree's owner records none)" : ""}`);
3748
+ }
3411
3749
  // Launch selection: a named configuration (explicit, or the soul's
3412
3750
  // launch-config default), or none; the harness and model follow from it.
3413
3751
  // K6b: a preview's native probes (model catalogue, harness packages) share
@@ -3525,56 +3863,28 @@ function* spawnBody(root, agent, o = {}) {
3525
3863
  if (relation === "unrelated") { relation = undefined; relativeTo = undefined; }
3526
3864
 
3527
3865
  // Attached = child of the work-tree owner, always (design decision). The
3528
- // owner is CANONICALLY resolved BY PATH: every instance home in the
3529
- // deployment (local root + team scope) is enumerated and matched on
3530
- // realpath(<home>/work) === realpath(workDir) — never by name, since
3866
+ // owner is CANONICALLY resolved BY PATH (attachedTreeOf, read above with the
3867
+ // repository): the instance in whose home the tree is, as that home's work
3868
+ // or as one of its extra trees — never by name, since
3531
3869
  // instance names are only unique per agent dir and a same-named local
3532
- // instance must not shadow the tree's true owner. For trees that are no
3533
- // instance's home/work (e.g. a coordinator's integration worktree), the
3870
+ // instance must not shadow the tree's true owner. For trees that are in no
3871
+ // instance's home (e.g. a coordinator's integration worktree), the
3534
3872
  // spawner must name the owner explicitly with a child relation — nothing
3535
3873
  // else can attach there.
3536
3874
  let attachedOwner;
3537
3875
  if (work === "attached" && o.workDir) {
3538
3876
  const wd = resolve(o.workDir);
3539
- let wdReal; try { wdReal = realpathSync(wd); } catch { wdReal = undefined; }
3540
3877
  let ownerName;
3541
- if (wdReal) {
3542
- // Every agent dir under the root: souls and capability-defined agents alike.
3543
- const scanInstances = (agentsRoot, cb) => {
3544
- if (!existsSync(agentsRoot)) return;
3545
- for (const ag of readdirSync(agentsRoot, { withFileTypes: true })) {
3546
- if (!ag.isDirectory() || ag.name.startsWith(".")) continue;
3547
- const dir = join(agentsRoot, ag.name, "instances");
3548
- if (!existsSync(dir)) continue;
3549
- for (const e of readdirSync(dir, { withFileTypes: true })) if (e.isDirectory()) cb(join(dir, e.name), e.name);
3550
- }
3551
- };
3552
- const ownerRoots = new Set();
3553
- try { ownerRoots.add(realpathSync(root)); } catch { ownerRoots.add(root); }
3554
- const hits = [];
3555
- // Lexical form of workDir with the HOME part canonicalized — checkout-mode
3556
- // instances have work as a symlink to the shared repo, so realpath alone
3557
- // would collide across every checkout instance; symlinked work trees only
3558
- // match when workDir IS that home's work path.
3559
- let wdLexical; try { wdLexical = join(realpathSync(dirname(wd)), basename(wd)); } catch { wdLexical = wd; }
3560
- for (const r2 of ownerRoots) scanInstances(r2, (instHome, instName) => {
3561
- const wp = join(instHome, "work");
3562
- try {
3563
- let homeReal; try { homeReal = realpathSync(instHome); } catch { return; }
3564
- if (join(homeReal, "work") === wdLexical) { hits.push({ home: instHome, name: instName }); return; }
3565
- if (!lstatSync(wp).isSymbolicLink() && realpathSync(wp) === wdReal) hits.push({ home: instHome, name: instName });
3566
- } catch { /* no work tree */ }
3567
- });
3568
- if (hits.length) {
3569
- ownerName = hits[0].name;
3570
- // The owner must be representable unambiguously from the CHILD's root:
3571
- // the recorded name, resolved like every other lineage edge, must land
3572
- // back on the matched home.
3573
- const check = findInstanceHome(root, ownerName);
3574
- let resolvesBack = false;
3575
- try { resolvesBack = !!check && realpathSync(check.home) === realpathSync(hits[0].home); } catch { /* not resolvable */ }
3576
- if (!resolvesBack) throw new Error(`attached workDir ${wd} belongs to instance "${ownerName}" (${hits[0].home}), but that name resolves to a different instance from this deployment root — the parent link would be ambiguous; retire/rename the shadowing instance or attach to a tree owned here`);
3577
- }
3878
+ const owner = attachedTree.owner;
3879
+ if (owner) {
3880
+ ownerName = owner.name;
3881
+ // The owner must be representable unambiguously from the CHILD's root:
3882
+ // the recorded name, resolved like every other lineage edge, must land
3883
+ // back on the matched home.
3884
+ const check = findInstanceHome(root, ownerName);
3885
+ let resolvesBack = false;
3886
+ try { resolvesBack = !!check && realpathSync(check.home) === realpathSync(owner.home); } catch { /* not resolvable */ }
3887
+ if (!resolvesBack) throw new Error(`attached workDir ${wd} belongs to instance "${ownerName}" (${owner.home}), but that name resolves to a different instance from this deployment root — the parent link would be ambiguous; retire/rename the shadowing instance or attach to a tree owned here`);
3578
3888
  }
3579
3889
  if (ownerName) {
3580
3890
  attachedOwner = ownerName;
@@ -3582,9 +3892,9 @@ function* spawnBody(root, agent, o = {}) {
3582
3892
  throw new Error(`attached agents are always children of the work-tree owner (${attachedOwner}) — drop the relation flags or use --work worktree for a different relation`);
3583
3893
  }
3584
3894
  } else {
3585
- // Path matches NO known instance's work tree: require an explicit,
3895
+ // The tree is in NO known instance's home: require an explicit,
3586
3896
  // validated child link so the "attached = child" invariant still holds.
3587
- if (!relation) throw new Error(`attached workDir ${wd} is not a known instance's <home>/work — name the owning instance explicitly (--parent <instance>)`);
3897
+ if (!relation) throw oatsError("E_BAD_ARGS", attachedTreeOfNoInstance(wd, { parent: true, repo: false }));
3588
3898
  if (relation !== "child") throw new Error(`attached agents are always children — only --parent <instance> (child) is valid for a non-instance work tree`);
3589
3899
  attachedOwner = relativeTo;
3590
3900
  }
@@ -3782,11 +4092,16 @@ function* spawnBody(root, agent, o = {}) {
3782
4092
  // reconciliation, so this spawn-time check is the authoritative one.
3783
4093
 
3784
4094
  // Prerequisites must fail before creating a home, worktree, or identity.
4095
+ // Where this launch will run (launchEnvironment): what its configuration sets, else its pane's.
4096
+ // `expectedEnv` is the preflight's answer, over the pane this plan expects; the launch reads the
4097
+ // session it actually gets (below). A spawn that launches nothing has no pane to read.
4098
+ const launchEnvOn = (pane, removed = []) => launchEnvironment({ configEnv: launchConfig?.env, configName: launchConfig?.name, removed, env: process.env, pane, cwd: home });
4099
+ const expectedEnv = launchEnvOn(launch ? () => expectedPaneEnvironment(tmuxSessionPlan, session, undefined, home) : NO_LAUNCH);
3785
4100
  // A launched harness is looked up where its pane will look it up (launchLookup): this is the
3786
4101
  // preflight against the expected PATH; the launch looks again on the session it gets. Without a
3787
4102
  // launch (or a known destination) the lookup is this process's PATH, as before.
3788
- const lookupFor = (pane) => launch && !launchConfig?.executable?.includes("/") ? launchLookup(launchConfig?.env, process.env, pane, launchConfig?.name, home) : undefined;
3789
- const executable = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, contextDir: repoAbs, lookup: lookupFor(() => expectedPanePath(tmuxSessionPlan, session, undefined, home)) });
4103
+ const lookupFor = (launchEnv) => launch && !launchConfig?.executable?.includes("/") ? launchLookup(launchEnv) : undefined;
4104
+ const executable = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, contextDir: repoAbs, lookup: lookupFor(expectedEnv) });
3790
4105
  if (!executable.path && executable.lookup) { previewPreflightBudget = null; throw executableNotOnPanePath(executable, { harness, config: launchConfig, from: launchChoice.from, at: launchChoice.at }); }
3791
4106
  // No executable for the chosen harness (none declared by a configuration): E_HARNESS_UNAVAILABLE names the
3792
4107
  // layer that chose it and the fix. Never a fallback to another harness.
@@ -3798,11 +4113,30 @@ function* spawnBody(root, agent, o = {}) {
3798
4113
  if (missingRefs.length) throw oatsError("E_LAUNCH_ENV_MISSING", `launch configuration ${launchConfig.name} references ${missingRefs.join(", ")}, not set in this environment; nothing was created`);
3799
4114
  // A configuration's executable answers the package probe (without one the
3800
4115
  // context-selected name does, as before: its remedies name that command),
3801
- // under the configuration's environment (literals, references resolved
3802
- // from the base); the capabilities' own env is not known before their
3803
- // spawn hooks run, which happens after the home exists.
4116
+ // under the environment the launch will have (launchEffectiveEnv: the
4117
+ // configuration's, and its pane's PATH, HOME and selectors, never this
4118
+ // process's in their place); the capabilities' own env is not known before
4119
+ // their spawn hooks run, which happens after the home exists
4120
+ // (awebai/oats#1041). `probed` keeps what the gate judged (null: no
4121
+ // requirement applied, so nothing was probed and nothing of the pane was
4122
+ // read), to compare with the pane the spawn actually gets.
3804
4123
  if ((launchConfig?.args || []).length && applicableRequirements(harness, resolvedCfg.capabilities).length) throw oatsError("E_LAUNCH_PROBE_UNSUPPORTED", `${requirementsWithArgsMessage(harness, resolvedCfg.capabilities, launchConfig)}; nothing was created`);
3805
- const harnessPackages = verifyHarnessPackages(harness, resolvedCfg, repoAbs, { ...(launchConfig?.executable ? { bin } : {}), env: launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {} }) });
4124
+ let probed = null;
4125
+ const recordedHarnessPackages = (found) => found.map((x) => ({ capability: x.capability, harness: x.harness, package: x.package, dir: x.dir, filtered: x.filtered, loadedBy: "harness-discovery" }));
4126
+ const probeEnvOn = (launchEnv, selected = bin) => probeEnvironment(() => (probed = launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {}, launch: launchEnv, harness })), launchEnv, harness, selected);
4127
+ const harnessPackages = verifyHarnessPackages(harness, resolvedCfg, repoAbs, { ...(launchConfig?.executable ? { bin } : {}), env: probeEnvOn(expectedEnv) });
4128
+ // What a preview of a launch says when no pane's environment is established (no server runs, or
4129
+ // it could not be read): the checks that read this process's values in its place, in one line
4130
+ // that names every name read that way, PATH among them: the lookup of a bare name and the package
4131
+ // probe. A spawn that launches nothing says nothing here: its checks read this process by design,
4132
+ // a start checks again on its own session, and it says whose values it read only where it already
4133
+ // says something (the folder-trust warning, a refusal of the package gate).
4134
+ const previewReadWarning = () => {
4135
+ if (!launch) return null;
4136
+ const checks = [...(!launchConfig?.executable?.includes("/") && !executable.lookup ? [["the harness lookup", ["PATH"]]] : []), ...(probed ? [["the harness package check", probeNames(harness)]] : [])];
4137
+ const note = unestablishedNote(expectedEnv, [...new Set(checks.flatMap(([, names]) => names))]);
4138
+ return note ? `${checks.map(([what]) => what).join(", ")}: ${note}` : null;
4139
+ };
3806
4140
  if (o.preview === true) { preflight = { status: previewPreflightBudget?.exhausted ? "timeout" : "complete", budgetMs: preflightBudgetMs, elapsedMs: Date.now() - preflightStarted }; previewPreflightBudget = null; }
3807
4141
  const task = o.task ?? (o.taskFile ? readFileSync(o.taskFile, "utf8") : "");
3808
4142
 
@@ -3871,7 +4205,7 @@ function* spawnBody(root, agent, o = {}) {
3871
4205
  const preparedSettingsOrigins = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloadOrigins?.[m.name] ?? {})]));
3872
4206
  // The preview's warnings are strings: the launchPromptAnswers notice, then what a module declares and this kernel ignores.
3873
4207
  // The development-channel statement is the apply's: no launch hook runs here, so the argv is unknown.
3874
- const previewWarnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution))];
4208
+ const previewWarnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution)), ...[previewReadWarning()].filter(Boolean)];
3875
4209
  const preparedSettings = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloads?.[m.name] && typeof o.prepared.resolution.payloads[m.name] === "object" ? o.prepared.resolution.payloads[m.name] : {})]));
3876
4210
  return deliver({
3877
4211
  // Team model v2: the soul's teams here (unmapped rows included) and its default — the choice a
@@ -4535,8 +4869,16 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4535
4869
  prompt: LAUNCH_PROMPT, kernelBin: shimTarget,
4536
4870
  };
4537
4871
  if (triggerEventFile) recipe.env.OATS_TRIGGER_EVENT_FILE = triggerEventFile;
4538
- const folderTrust = launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo, configEnv: launchConfig?.env, launchConfig: launchConfig?.name });
4539
- if (folderTrust.warning) warnings.push(folderTrust.warning);
4872
+ // What this launch removes (removedLaunchEnv): the names the composed capabilities declare that
4873
+ // their spawn hooks' payload and the configuration leave out. Folder trust and the checks on the
4874
+ // pane the spawn gets read them as removed; the window command unsets them.
4875
+ const removedEnv = removedLaunchEnv({ declared: declaredLaunchEnv(resolvedCfg.capabilities), hooksEnv: hookRes.env, configEnv: recipe.env });
4876
+ // Folder trust, read on the pane this plan expects: the command is rendered from it. A launch
4877
+ // reads it again on the session it gets, and warns from that (below); a spawn that launches
4878
+ // nothing warns from this, and the warning says whose values were read.
4879
+ const folderTrustOn = (launchEnv) => launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo, launch: launchEnv, configEnv: launchConfig?.env, launchConfig: launchConfig?.name });
4880
+ let folderTrust = folderTrustOn(launchEnvOn(expectedEnv.pane, removedEnv));
4881
+ if (!launch && folderTrust.warning) warnings.push(folderTrust.warning);
4540
4882
  let cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
4541
4883
 
4542
4884
  // Module skills as materialize landed them (flat, .agents/skills/<skill>/),
@@ -4587,7 +4929,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4587
4929
  // package's resources. A non-empty filter is a deliberate choice whose
4588
4930
  // glob semantics belong to the harness, so it is auditable here rather
4589
4931
  // than second-guessed at spawn.
4590
- harnessPackages: harnessPackages.map((x) => ({ capability: x.capability, harness: x.harness, package: x.package, dir: x.dir, filtered: x.filtered, loadedBy: "harness-discovery" })),
4932
+ harnessPackages: recordedHarnessPackages(harnessPackages),
4591
4933
  // What this instance ACTUALLY sees beyond the OATS-composed set. Recorded
4592
4934
  // so the deviation from strict composition is auditable instead of
4593
4935
  // implied — the honest contract, not an aspiration.
@@ -4643,12 +4985,14 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4643
4985
  // The session on the OATS server, then everything on the one socket that answered: the collision
4644
4986
  // check, the records, the window and (in compensateSpawn) its removal.
4645
4987
  const socket = ensureOatsTmuxSession(session, existsSync(root) ? root : workspaceOf(root), undefined, tmuxSessionPlan, undefined, spawnWarnings);
4646
- // The harness looked up again on the PATH this window's pane will actually start with, whoever
4647
- // created the session and with whatever environment (a race lost to another creator, a session
4648
- // that overrides PATH). Not there: refused, and the spawn is compensated. Found elsewhere than
4649
- // the preflight found it: the launch runs that one.
4988
+ // The environment this window's pane will actually start with, whoever created the session and
4989
+ // with whatever environment (a race lost to another creator, a session that overrides a name):
4990
+ // one read of it answers the three checks below, each of which reads it only when it has to.
4991
+ const actualEnv = launchEnvOn(paneEnvironment(socket, session, undefined, home), removedEnv);
4992
+ // The harness looked up again on that PATH. Not there: refused, and the spawn is compensated.
4993
+ // Found elsewhere than the preflight found it: the launch runs that one.
4650
4994
  if (executable.lookup) {
4651
- const actual = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, lookup: lookupFor(() => panePath(socket, session, undefined, home)) });
4995
+ const actual = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, lookup: lookupFor(actualEnv) });
4652
4996
  if (!actual.path) throw executableNotOnPanePath(actual, { harness, config: launchConfig, from: launchChoice.from, at: launchChoice.at });
4653
4997
  const bad = checkLaunchExecutable(actual.path);
4654
4998
  if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig?.name || "(harness default)"}: ${bad}`);
@@ -4658,6 +5002,27 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4658
5002
  executionCommand = nativeRecordCommand(cmdline, home, harness);
4659
5003
  }
4660
5004
  }
5005
+ // The package gate judged the pane this spawn expected (`probed`). When the pane it got differs
5006
+ // in a name the probe depends on, or the lookup above found the harness elsewhere there, the gate
5007
+ // judges again, on that one and with that program: a pane that cannot be
5008
+ // read (E_RUNTIME_ENDPOINT_UNKNOWN) or whose account lacks a package
5009
+ // (E_HARNESS_RESOURCE_MISSING) is refused, and the spawn is compensated as for the lookup
5010
+ // above. Equal, as it is unless another creator won the server's creation: nothing more is probed.
5011
+ if (probed) {
5012
+ const judged = probed, actual = probeEnvOn(actualEnv)();
5013
+ if (recipe.executable !== bin || probeNames(harness).some((name) => judged[name] !== actual[name])) {
5014
+ meta.composition.materialized.harnessPackages = recordedHarnessPackages(verifyHarnessPackages(harness, resolvedCfg, repoAbs, { ...(launchConfig?.executable ? { bin: recipe.executable } : {}), env: probeEnvironment(() => actual, actualEnv, harness, recipe.executable) }));
5015
+ }
5016
+ }
5017
+ // Folder trust on the same pane: the warning is about the file this launch reads, and codex's
5018
+ // trust of the home follows that file.
5019
+ const actualTrust = folderTrustOn(actualEnv);
5020
+ if (actualTrust.warning) spawnWarnings.push(actualTrust.warning);
5021
+ if (actualTrust.trustHome !== folderTrust.trustHome) {
5022
+ meta.command = cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: actualTrust.trustHome });
5023
+ executionCommand = nativeRecordCommand(cmdline, home, harness);
5024
+ }
5025
+ folderTrust = actualTrust;
4661
5026
  let present;
4662
5027
  try { present = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"]).split("\n").filter(Boolean); }
4663
5028
  catch (e) { throw new Error(`could not list the windows of tmux session ${session} on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`); }
@@ -4675,7 +5040,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4675
5040
  clearSpawnInProgressMarker();
4676
5041
  // Wrap the command so the window drops into an interactive shell when the
4677
5042
  // agent exits (e.g. Ctrl-C) instead of tmux killing the window.
4678
- const windowCmd = paneCommand(executionCommand);
5043
+ const windowCmd = paneCommand(executionCommand, removedEnv);
4679
5044
  const paneEnvFlags = launchEnvRefs(recipe, process.env).flatMap((r) => ["-e", `${r.name}=${r.value}`]);
4680
5045
  const launchFailed = (step, refused, e) => oatsError("E_SPAWN_LAUNCH_FAILED", `tmux ${step} failed for ${instance} (${e.code === "ENOENT" ? "tmux unavailable" : refused}); the command line and tmux's output are withheld from this message because they can carry reference values; run tmux -S ${shellWord(socket)} list-windows -t ${shellWord(session)} to inspect`);
4681
5046
  // Only a launch that engages the confirmation needs lineage committed before
@@ -5424,7 +5789,7 @@ const GIT_MAX_BUFFER = 512 * 1024 * 1024;
5424
5789
  * its .gitattributes select can still run during `git status`; turning it
5425
5790
  * off would change what status reports. */
5426
5791
  const RETIRE_GIT_FLAGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "diff.external="];
5427
- const RETIRE_GIT_DROPPED_ENV = new Set(["GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_WORK_TREE", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_INDEX_FILE", "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_PREFIX", "GIT_SHALLOW_FILE", "GIT_COMMON_DIR"]);
5792
+ const RETIRE_GIT_DROPPED_ENV = new Set(["GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_DEFAULT_REF_FORMAT", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_WORK_TREE", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_INDEX_FILE", "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_PREFIX", "GIT_SHALLOW_FILE", "GIT_COMMON_DIR"]);
5428
5793
  function retireGitEnv(env) {
5429
5794
  const out = {};
5430
5795
  for (const [key, value] of Object.entries(process.env)) {
@@ -6155,22 +6520,26 @@ function missingSessionReceipt(home) {
6155
6520
  return oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `no session receipt for ${home} at ${where}. First address the home exactly as \`oats status\` prints it (a deployment directory moved since spawn looks for the receipt elsewhere, and so does a letter-case spelling other than the spawn's, for a home spawned before 0.49.0). Otherwise the home was copied, the .oats-retirement beside it was removed, or its creation did not finish: stop its session yourself if one runs, then \`oats retire ${basename(home)} --plan\` and \`oats retire ${basename(home)}\` (work is preserved), and respawn.`);
6156
6521
  }
6157
6522
 
6158
- /** Session control uses the independent endpoint receipt. */
6523
+ /** Why a file could not be read or parsed, in the system's or the parser's words, without the path
6524
+ * the sentence already names: `EACCES: permission denied`; a missing file is "it is missing". */
6525
+ const unreadableBecause = (e) => e?.code === "ENOENT" ? "it is missing" : String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, "");
6526
+
6527
+ /** Session control uses the independent endpoint receipt. The receipt and the record are read
6528
+ * apart, so that a failure names the file that failed (#1092): one `catch` over both cannot know. */
6159
6529
  function instanceSessionTarget(home) {
6160
6530
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session needs an absolute instance home");
6161
6531
  home = realPathOrNearest(home);
6162
6532
  refuseHerdrHome(home);
6163
- const receiptPath = findRetirementBaseline(home);
6533
+ const receiptPath = findRetirementBaseline(home), recordPath = join(home, "instance.json");
6164
6534
  let baseline, meta;
6165
- try {
6166
- baseline = JSON.parse(readFileSync(receiptPath, "utf8"));
6167
- meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
6168
- } catch (e) {
6535
+ try { baseline = JSON.parse(readFileSync(receiptPath, "utf8")); } catch (e) {
6169
6536
  if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home);
6170
- throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${e.message}`);
6537
+ throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home} at ${receiptPath}: ${unreadableBecause(e)}`);
6171
6538
  }
6539
+ try { meta = JSON.parse(readFileSync(recordPath, "utf8")); }
6540
+ catch (e) { throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: ${unreadableBecause(e)}`); }
6172
6541
  // A record that is JSON and no object gives no endpoint to compare the receipt with.
6173
- if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${join(home, "instance.json")} holds no JSON object`);
6542
+ if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: it holds no JSON object`);
6174
6543
  const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
6175
6544
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
6176
6545
  if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
@@ -6623,19 +6992,12 @@ function tmuxOn(socket, args, io, env) {
6623
6992
  return (io?.exec || execFileSync)(tmux, ["-u", "-S", socket, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...(env ? { env } : {}) });
6624
6993
  }
6625
6994
 
6626
- /** Write `value` as JSON at `path` through a private file beside it, renamed over it. When the
6627
- * write or the rename fails the private file is removed and the error thrown is that failure's:
6628
- * a file system with no space makes the file and has no block for its bytes, and nothing else
6629
- * would remove it (awebai/oats#963). The removal's own failure is not answered. */
6995
+ /** Write `value` as JSON at `path` through a private file beside it (`<path>.tmp-<pid>`), renamed
6996
+ * over it, by the kernel's one such writer (lib/write-through-private-file.mjs): when the write or
6997
+ * the rename fails the private file is removed and the error thrown is that failure's
6998
+ * (awebai/oats#963, #1076). */
6630
6999
  function writeJsonAtomic(path, value, mode) {
6631
- const tmp = `${path}.tmp-${process.pid}`;
6632
- try {
6633
- writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", mode !== undefined ? { mode } : undefined);
6634
- renameSync(tmp, path);
6635
- } catch (e) {
6636
- try { rmSync(tmp, { force: true }); } catch { /* the first error is the one answered */ }
6637
- throw e;
6638
- }
7000
+ writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, JSON.stringify(value, null, 2) + "\n", mode);
6639
7001
  }
6640
7002
 
6641
7003
  // ---------- stopping a harness, selecting on an existing home ----------
@@ -6833,7 +7195,7 @@ export function prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, c
6833
7195
  }
6834
7196
  /** Environment that selects which configuration (account, packages) a
6835
7197
  * harness reads, under which the package probe inspects its packages. */
6836
- const HARNESS_CONFIG_SELECTORS = new Set(["CLAUDE_CONFIG_DIR", "CODEX_HOME", "PI_CODING_AGENT_DIR"]);
7198
+ const HARNESS_CONFIG_SELECTORS = new Set(Object.values(HARNESS_FOLDER_VAR));
6837
7199
 
6838
7200
 
6839
7201
  export function restartInstanceSession(home, o = {}) { return startInstanceSession(home, { ...o, restart: true }); }
@@ -7097,23 +7459,24 @@ export function startInstanceSession(home, o = {}) {
7097
7459
  // the launch hook re-checks joined memberships against them.
7098
7460
  const resolvedCfg = resolvedFromHome(realHome, meta, { teams: o.teams, defaultTeam: o.defaultTeam, teamsSource: o.teamsSource });
7099
7461
  let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
7100
- // Where the plan looks a harness up by name: a pane the start will reuse, on its own recorded
7101
- // session, whatever the OATS server holds; otherwise the session's or the server's PATH when a
7102
- // server runs; when none does, the PATH of the environment this start will create the server
7103
- // with (read once, here, for the plan and for the creation below). For a creator that may not
7104
- // create the server the plan looks on this process's PATH, and its refusal comes at the
7105
- // creation's own place, after the start's other preflights.
7462
+ // The environment the plan's checks read for this launch's pane (the harness lookup by name,
7463
+ // the package probe, folder trust): a pane the start will reuse, on its own recorded session,
7464
+ // whatever the OATS server holds; otherwise the session's or the server's when a server runs;
7465
+ // when none does, the environment this start will create the server with (read once, here,
7466
+ // for the plan and for the creation below). For a creator that may not create the server no
7467
+ // pane's environment is established: the plan's checks read this process's, and the refusal
7468
+ // comes at the creation's own place, after the start's other preflights.
7106
7469
  const pane = () => {
7107
7470
  const recorded = recordedState();
7108
- if (reusable(recorded.state)) return panePath(receipt.target.socket, receipt.target.session, o.io, realHome);
7109
- if (recorded.error) return undefined; // the gate refuses below; the lookup does not decide it
7471
+ if (reusable(recorded.state)) return paneEnvironment(receipt.target.socket, receipt.target.session, o.io, realHome);
7472
+ if (recorded.error) return NO_PANE_READ; // the gate refuses below; no check decides it
7110
7473
  const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
7111
- if (!preview || preview.server) return expectedPanePath(preview, planSession, o.io, realHome);
7112
- try { return expectedPanePath(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return undefined; throw e; }
7474
+ if (!preview || preview.server) return expectedPaneEnvironment(preview, planSession, o.io, realHome);
7475
+ try { return expectedPaneEnvironment(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return SESSION_REFUSED; throw e; }
7113
7476
  };
7114
7477
  const plan = planLaunch({ home: realHome, instance: meta.instance, meta, contextDir: context, agentLike: agent || { harness: meta.harness, model: meta.model, yolo: meta.yolo }, selection: { launchConfig: o.launchConfig, harness: o.harness, model: o.model, yolo: o.yolo }, reselect, resolvedCfg, env: o.env || process.env, assertRoots: checkRoots,
7115
- panePath: pane });
7116
- launchPlan = { recipe: plan.recipe, command: plan.command, harness: plan.harness, model: plan.model, yolo: plan.yolo, executable: plan.executable, config: plan.config, launchChoice: plan.launchChoice, trustHome: plan.trustHome, modelFrom: modelFromOf(plan.modelSource, { at: "start", prior: meta.modelFrom ?? null }),
7478
+ pane });
7479
+ launchPlan = { recipe: plan.recipe, command: plan.command, declaredEnv: plan.declaredEnv, harness: plan.harness, model: plan.model, yolo: plan.yolo, executable: plan.executable, config: plan.config, launchChoice: plan.launchChoice, trustHome: plan.trustHome, modelFrom: modelFromOf(plan.modelSource, { at: "start", prior: meta.modelFrom ?? null }),
7117
7480
  ...(plan.launchChoice ? { launchFrom: plan.launchChoice.from, launchAt: plan.launchChoice.at, launchDeclared: plan.launchChoice.declared } : {}) };
7118
7481
  // The plan ran preview-aware launch hooks as a preview: their real run, over the planned
7119
7482
  // contributions, waits for the rest of preflight.
@@ -7166,7 +7529,7 @@ export function startInstanceSession(home, o = {}) {
7166
7529
  const lookAgain = (pane) => {
7167
7530
  if (!launchPlan || launchPlan.config?.frozen || launchPlan.config?.executable?.includes("/")) return false;
7168
7531
  const { config, launchChoice } = launchPlan;
7169
- const actual = resolveLaunchExecutable({ harness: launchPlan.harness, declared: config?.executable, declaringDir: config?.source, lookup: launchLookup(config?.env, o.env || process.env, pane, config?.name, realHome) });
7532
+ const actual = resolveLaunchExecutable({ harness: launchPlan.harness, declared: config?.executable, declaringDir: config?.source, lookup: launchLookup(launchEnvironment({ configEnv: config?.env, configName: config?.name, env: o.env || process.env, pane, cwd: realHome })) });
7170
7533
  if (!actual.path) throw executableNotOnPanePath(actual, { harness: launchPlan.harness, config, from: launchChoice?.from, at: launchChoice?.at });
7171
7534
  const bad = checkLaunchExecutable(actual.path);
7172
7535
  if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${bad}; nothing was started`);
@@ -7175,7 +7538,7 @@ export function startInstanceSession(home, o = {}) {
7175
7538
  command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome });
7176
7539
  return true;
7177
7540
  };
7178
- lookAgain(retained ? () => panePath(target.socket, target.session, o.io, realHome) : () => expectedPanePath(tmuxSessionPlan, planSession, o.io, realHome));
7541
+ lookAgain(retained ? () => paneEnvironment(target.socket, target.session, o.io, realHome) : () => expectedPaneEnvironment(tmuxSessionPlan, planSession, o.io, realHome));
7179
7542
  // Every preflight has passed: the preview-aware launch hooks run for real
7180
7543
  // (they may register the home with their provider), before a restart's
7181
7544
  // stop, and must contribute exactly what they contributed as a preview,
@@ -7235,7 +7598,10 @@ export function startInstanceSession(home, o = {}) {
7235
7598
  let launchController;
7236
7599
  let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
7237
7600
  checkRoots();
7238
- const windowCommand = () => paneCommand(`${nativeRecordCommand(command, realHome, launchPlan?.harness || harness)}; oats_start_status=$?; printf '%s\\n' ${shq(id)} > ${shq(exitedPath)}`);
7601
+ // The names this launch removes, from the recipe it runs (a preview-aware hook's real run included).
7602
+ // A home without a recipe (an earlier kernel's) composes no providers at launch: nothing.
7603
+ const removed = launchPlan ? removedLaunchEnv({ declared: launchPlan.declaredEnv, hooksEnv: launchPlan.recipe.hooks?.env, configEnv: launchPlan.recipe.env }) : [];
7604
+ const windowCommand = () => paneCommand(`${nativeRecordCommand(command, realHome, launchPlan?.harness || harness)}; oats_start_status=$?; printf '%s\\n' ${shq(id)} > ${shq(exitedPath)}`, removed);
7239
7605
  let reused = "new";
7240
7606
  const session = target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
7241
7607
  const window = target?.window || meta.tmux?.window || meta.instance;
@@ -7272,7 +7638,7 @@ export function startInstanceSession(home, o = {}) {
7272
7638
  // on the OATS server, wherever the home was recorded: one socket from here to the record.
7273
7639
  const recordedSocket = socket ? resolve(socket) : null;
7274
7640
  socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
7275
- if (lookAgain(() => panePath(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
7641
+ if (lookAgain(() => paneEnvironment(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
7276
7642
  let names;
7277
7643
  try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
7278
7644
  catch (e) {
@@ -7370,6 +7736,18 @@ function inspectedEntryExists(path) {
7370
7736
  throw oatsError("E_WORK_INSPECTION_FAILED", `could not inspect ${path}: ${e.message}`);
7371
7737
  }
7372
7738
  }
7739
+ /** inspectedEntryExists with a link not followed: a link is there as itself,
7740
+ * also one that leads nowhere. What the copier asks of an entry it copies
7741
+ * with copyTreeSafe, which copies a link as a link, and what the comparison
7742
+ * asks of the same entry (copiedGitPathDigest), so both read one thing
7743
+ * (awebai/oats#1038). Absence is ENOENT alone, as there. */
7744
+ function inspectedEntryPresent(path) {
7745
+ try { lstatSync(path); return true; }
7746
+ catch (e) {
7747
+ if (e.code === "ENOENT") return false;
7748
+ throw oatsError("E_WORK_INSPECTION_FAILED", `could not inspect ${path}: ${e.message}`);
7749
+ }
7750
+ }
7373
7751
  /** How the recovery copier resolves what it reads from a repository, read by
7374
7752
  * the copier and by the comparison alike (repositoryGitState), so that the
7375
7753
  * comparison holds the files the copy carries, found where the copy finds
@@ -7497,6 +7875,8 @@ function repositoryGitState(repo, { status, cloneSource } = {}) {
7497
7875
  const copierGit = asCopier(copierGitDir), copierCommon = asCopier(copierCommonDir);
7498
7876
  const excludesFile = valueOf("config", "--path", "--get", "core.excludesFile");
7499
7877
  const excludesRead = asCopier(copierExcludesFile);
7878
+ const copied = COPIED_GIT_PATHS.map((entry) => copiedGitPathDigest(entry, copiedGitPath(entry, copierGit, copierCommon)));
7879
+ const stash = valueOf("rev-parse", "--verify", "--quiet", "refs/stash");
7500
7880
  return {
7501
7881
  paths: printed,
7502
7882
  status: (status ?? worktreeStatusBytes(repo)).toString("latin1"),
@@ -7507,9 +7887,14 @@ function repositoryGitState(repo, { status, cloneSource } = {}) {
7507
7887
  index: inspectGit(repo, ["ls-files", "-s", "-v", "-z"], { env: { GIT_INDEX_FILE: join(copierGit, "index") } }),
7508
7888
  resolveUndo: inspectGit(repo, ["ls-files", "--resolve-undo", "-z"], { env: { GIT_INDEX_FILE: join(copierGit, "index") } }),
7509
7889
  indexMode: modeOf(join(copierGit, "index")),
7510
- copied: COPIED_GIT_PATHS.map((entry) => copiedGitPathDigest(entry, copiedGitPath(entry, copierGit, copierCommon))),
7890
+ copied,
7891
+ // What the copy carries through Git rather than as files (awebai/oats#1038), read as the
7892
+ // copier reads it: the operation's refs it writes, and the stash's entries where its log
7893
+ // is not a file (stashEntries).
7894
+ operationRefs: asCopier(() => operationRefsWritten(repo, copierGit)),
7895
+ stashEntries: stash !== null && copied[COPIED_GIT_PATHS.indexOf(GIT_STASH_LOG)] === null ? asCopier(() => stashEntries(repo).map((e) => e.line)) : null,
7511
7896
  tags: inspectGit(repo, ["for-each-ref", "--format=%(objectname) %(refname)", "refs/tags"]),
7512
- stash: valueOf("rev-parse", "--verify", "--quiet", "refs/stash"),
7897
+ stash,
7513
7898
  excludesFile: excludesFile === null && excludesRead === null ? null : [excludesFile, excludesRead, excludesRead && bytesOf(excludesRead)],
7514
7899
  exclude: bytesOf(join(copierCommon, "info", "exclude")),
7515
7900
  statusConfig: STATUS_CONFIG.map((key) => valueOf("config", "--get", key)),
@@ -7905,10 +8290,12 @@ const copiedGitPath = ({ dir, path }, gitDir, commonDir) => join(dir === "git" ?
7905
8290
  * path is not there. copyTreeSafe gives a copy the entry's kind, bytes or
7906
8291
  * target, and the bits of the entry and of everything under it: its exact
7907
8292
  * digest. copyRegularFile follows a link and gives the copy the bytes and the
7908
- * mode of what it reaches: those. Any failure but "not there" throws, as a
8293
+ * mode of what it reaches: those. So a "tree" path is looked at as the copier
8294
+ * looks at it, a link not followed (inspectedEntryPresent): a link that leads
8295
+ * nowhere is there, as a link. Any failure but "not there" throws, as a
7909
8296
  * read of the Git state does, and so does a file path that is not a file. */
7910
8297
  function copiedGitPathDigest(entry, at) {
7911
- if (!inspectedEntryExists(at)) return null;
8298
+ if (!(entry.copy === "tree" ? inspectedEntryPresent(at) : inspectedEntryExists(at))) return null;
7912
8299
  try {
7913
8300
  if (entry.copy === "tree") return exactTreeDigest(at);
7914
8301
  const st = statSync(at);
@@ -7976,14 +8363,17 @@ function indexBlobs(rows) {
7976
8363
  * the copy lacks; the missing commits are fetched from `source` by id (one
7977
8364
  * fetch, with everything they reach), the missing blobs, which can be in no
7978
8365
  * commit (staged content, a resolved conflict's sides), are copied by
7979
- * content (`cat-file blob` → `hash-object -w`); then the whole set is
8366
+ * content (`cat-file blob` → `hash-object -w`), and so are the missing trees
8367
+ * (`cat-file tree` → `hash-object -t tree -w`: the tree AUTO_MERGE names
8368
+ * and the trees under it that hold a conflict's files, which no commit
8369
+ * reaches, awebai/oats#1038); then the whole set is
7980
8370
  * checked again. A fetch or a read that fails is not the failure itself:
7981
8371
  * whatever is still missing after the repair is, named by its id, and the
7982
8372
  * copy is refused (E_WORK_PRESERVATION_FAILED). That covers an object the
7983
8373
  * source itself lacks, which GIT_NO_LAZY_FETCH keeps the copier from
7984
8374
  * fetching from a promisor remote. */
7985
- function carryNamedObjects(source, recovered, { commits = [], blobs = [] }) {
7986
- const named = [...new Set([...commits, ...blobs])];
8375
+ function carryNamedObjects(source, recovered, { commits = [], blobs = [], trees = [] }) {
8376
+ const named = [...new Set([...commits, ...blobs, ...trees])];
7987
8377
  if (!named.length) return;
7988
8378
  const missing = new Set(missingGitObjects(recovered, named));
7989
8379
  const fetch = [...new Set(commits)].filter((oid) => missing.has(oid));
@@ -7991,13 +8381,15 @@ function carryNamedObjects(source, recovered, { commits = [], blobs = [] }) {
7991
8381
  try { copierFetch(recovered, source, ["--stdin"], { input: fetch.join("\n") + "\n" }); }
7992
8382
  catch { /* the re-measure names what the fetch did not bring */ }
7993
8383
  }
7994
- for (const oid of new Set(blobs)) {
7995
- if (!missing.has(oid)) continue;
7996
- let blob;
7997
- try { blob = retireGit(source, ["cat-file", "blob", oid]); }
7998
- catch { continue; /* the re-measure names it */ }
7999
- const restored = retireGit(recovered, ["hash-object", "-w", "--stdin"], { input: blob, encoding: "utf8" }).trim();
8000
- if (restored !== oid) throw new Error(`recovered Git object ${restored} did not match source ${oid}`);
8384
+ for (const [type, oids] of [["blob", blobs], ["tree", trees]]) {
8385
+ for (const oid of new Set(oids)) {
8386
+ if (!missing.has(oid)) continue;
8387
+ let content;
8388
+ try { content = retireGit(source, ["cat-file", type, oid]); }
8389
+ catch { continue; /* the re-measure names it */ }
8390
+ const restored = retireGit(recovered, ["hash-object", "-t", type, "-w", "--stdin"], { input: content, encoding: "utf8" }).trim();
8391
+ if (restored !== oid) throw new Error(`recovered Git object ${restored} did not match source ${oid}`);
8392
+ }
8001
8393
  }
8002
8394
  const stillMissing = missingGitObjects(recovered, named);
8003
8395
  if (stillMissing.length) {
@@ -8075,13 +8467,169 @@ function restoreStandaloneGitState(sourceWork, recoveredRepo) {
8075
8467
  // that the copy reads to Git as the source does, every committed file a
8076
8468
  // staged deletion (awebai/oats#1048).
8077
8469
  if (!copyRegularFile(join(sourceGit, "index"), join(recoveredGit, "index"))) rmSync(join(recoveredGit, "index"), { force: true });
8470
+ // A link at one of these names is copied as a link, also one that leads
8471
+ // nowhere: the look does not follow it (inspectedEntryPresent), and
8472
+ // copyTreeSafe copies a link as a link (awebai/oats#1038).
8078
8473
  for (const entry of COPIED_GIT_PATHS.filter((e) => e.dir === "git")) {
8079
8474
  const source = copiedGitPath(entry, sourceGit);
8080
- if (!existsSync(source)) continue;
8475
+ if (!inspectedEntryPresent(source)) continue;
8081
8476
  const dest = copiedGitPath(entry, recoveredGit);
8082
8477
  rmSync(dest, { recursive: true, force: true });
8083
8478
  copyTreeSafe(source, dest);
8084
8479
  }
8480
+ carryOperationRefs(sourceWork, recoveredRepo, sourceGit);
8481
+ }
8482
+
8483
+ /** The refs an operation leaves in a worktree's own Git directory that the
8484
+ * copy above takes as files where they are files. In the reftable format they
8485
+ * are refs, not files (awebai/oats#1038). A fixed list: no name is ever read
8486
+ * from the source. */
8487
+ const CARRIED_OPERATION_REFS = Object.freeze(["CHERRY_PICK_HEAD", "REVERT_HEAD", "REBASE_HEAD", "AUTO_MERGE"]);
8488
+ /** A full object id of `repo`'s object format, as a pattern. */
8489
+ function objectIdPattern(repo) {
8490
+ const format = retireGit(repo, ["rev-parse", "--show-object-format"], { encoding: "utf8" }).trim();
8491
+ if (format === "sha1") return /^[0-9a-f]{40}$/;
8492
+ if (format === "sha256") return /^[0-9a-f]{64}$/;
8493
+ throw new Error(`${repo} uses the object format ${JSON.stringify(format)}, which the recovery does not know`);
8494
+ }
8495
+ /** The object id the ref named exactly `name` holds in `repo`, or null when
8496
+ * there is no such ref. `show-ref --exists` takes the name as it is (a branch
8497
+ * or a tag of the same name, which `rev-parse` would find in its place, is not
8498
+ * that ref) and does not ask for the object; once the ref is there, `rev-parse`
8499
+ * reads it, the ref at the Git directory's top level coming first in its
8500
+ * order. Only Git's answer that the ref does not exist (exit 2) is "none";
8501
+ * any other failure throws. Asked only of a repository whose refs may be in
8502
+ * the reftable format, which needs a Git that has `--exists` (2.43). */
8503
+ function exactRefValue(repo, name) {
8504
+ try { retireGit(repo, ["show-ref", "--exists", name]); }
8505
+ catch (e) { if (e.status === 2) return null; throw e; }
8506
+ return retireGit(repo, ["rev-parse", "--verify", "--quiet", name], { encoding: "utf8" }).trim();
8507
+ }
8508
+ /** The trees and blobs under the tree `tree`, itself included, that
8509
+ * `recovered` lacks, read from `source`: one level at a time, and only below
8510
+ * a tree the copy lacks. A tree the clone holds came with what it reaches, so
8511
+ * AUTO_MERGE's tree, which is the whole worktree's, costs the trees on the
8512
+ * conflict's paths, not the whole tree's. Gitlinks name commits of other
8513
+ * repositories and are not followed. */
8514
+ function missingTreeObjects(source, recovered, tree) {
8515
+ const trees = [], blobs = [];
8516
+ for (let level = missingGitObjects(recovered, [tree]); level.length;) {
8517
+ trees.push(...level);
8518
+ const children = [];
8519
+ for (const t of level) {
8520
+ for (const row of retireGit(source, ["ls-tree", "-z", t]).toString("latin1").split("\0")) {
8521
+ const m = /^\d+ (blob|tree) ([0-9a-f]+)\t/.exec(row);
8522
+ if (m) children.push({ type: m[1], oid: m[2] });
8523
+ }
8524
+ }
8525
+ const missing = new Set(missingGitObjects(recovered, [...new Set(children.map((c) => c.oid))]));
8526
+ blobs.push(...new Set(children.filter((c) => c.type === "blob" && missing.has(c.oid)).map((c) => c.oid)));
8527
+ level = [...new Set(children.filter((c) => c.type === "tree" && missing.has(c.oid)).map((c) => c.oid))];
8528
+ }
8529
+ return { trees, blobs };
8530
+ }
8531
+ /** Clone into a recovery, `args` being what follows `git clone`, its last the
8532
+ * destination. A recovery's refs are files, whatever the operator's Git
8533
+ * configuration or environment makes a new repository: the copy takes an
8534
+ * operation's refs as files of the Git directory, which a repository whose
8535
+ * refs are in the reftable format does not read (awebai/oats#1038). So the
8536
+ * clone is told the files format (`init.defaultRefFormat`, which a Git older
8537
+ * than the reftable format ignores; GIT_DEFAULT_REF_FORMAT, which would come
8538
+ * first, is not passed to the retire's Git: retireGitEnv), and a clone whose
8539
+ * Git directory still holds `reftable` refuses the copy. */
8540
+ function cloneRecovery(args) {
8541
+ retireGit(null, ["-c", "init.defaultRefFormat=files", "clone", ...args]);
8542
+ if (gitEntryAt(join(args.at(-1), ".git", "reftable")) !== false) throw new Error(`the recovery clone ${args.at(-1)} does not store its refs as files`);
8543
+ }
8544
+ /** The refs of an operation whose objects the recovery carries, whichever way
8545
+ * the ref came: written by carryOperationRefs, or copied as a file of the Git
8546
+ * directory. MERGE_HEAD is a file in every format, and is never written. */
8547
+ const OPERATION_OBJECT_REFS = Object.freeze([...CARRIED_OPERATION_REFS, "MERGE_HEAD"]);
8548
+ /** The object ids the operation ref `name` names in the recovery, read after
8549
+ * the copy from the file at its name: Git writes each of these refs, in the
8550
+ * files format, as one id per line (a merge of several commits names one per
8551
+ * line in MERGE_HEAD, of which a Git read gives the first only), and Git
8552
+ * would refuse to read a ref whose object is not yet there. A link at the
8553
+ * name is carried as itself (restoreStandaloneGitState), and what it leads
8554
+ * to is not read: it names nothing here. */
8555
+ function recoveredOperationObjects(recoveredRepo, name) {
8556
+ const at = join(recoveredRepo, ".git", name);
8557
+ let st;
8558
+ try { st = lstatSync(at); }
8559
+ catch (e) { if (e.code === "ENOENT") return []; throw e; }
8560
+ if (!st.isFile()) return [];
8561
+ return readFileSync(at, "latin1").split("\n").filter((line) => line !== "");
8562
+ }
8563
+ /** The type of each of `oids` in `repo` (`cat-file --batch-check`), "missing"
8564
+ * for one it does not hold. */
8565
+ function gitObjectTypes(repo, oids) {
8566
+ const types = new Map();
8567
+ if (!oids.length) return types;
8568
+ const out = retireGit(repo, ["cat-file", "--batch-check=%(objectname) %(objecttype)"], { input: oids.join("\n") + "\n", encoding: "utf8" });
8569
+ for (const line of out.split("\n")) {
8570
+ const space = line.indexOf(" ");
8571
+ if (space > 0) types.set(line.slice(0, space), line.slice(space + 1));
8572
+ }
8573
+ return types;
8574
+ }
8575
+ /** The operation's refs that the copy writes through Git, as { name, oid }:
8576
+ * each of CARRIED_OPERATION_REFS that the source's Git holds by its exact
8577
+ * name and that has nothing at its name in the worktree's own Git directory
8578
+ * `gitDir`, which the copy of the Git directory's files therefore does not
8579
+ * take. Asked only where the refs may be in the reftable format
8580
+ * (refsMayBeReftable); in the files format each is a file. The one read for
8581
+ * the copier (carryOperationRefs) and for the comparison (repositoryGitState),
8582
+ * so that what the copy writes is what is compared. */
8583
+ function operationRefsWritten(work, gitDir) {
8584
+ if (!refsMayBeReftable(gitDir)) return [];
8585
+ const refs = [];
8586
+ for (const name of CARRIED_OPERATION_REFS) {
8587
+ if (inspectedEntryPresent(join(gitDir, name))) continue;
8588
+ const oid = exactRefValue(work, name);
8589
+ if (oid !== null) refs.push({ name, oid });
8590
+ }
8591
+ return refs;
8592
+ }
8593
+ /** Give the recovery the operation's refs and the objects they name
8594
+ * (awebai/oats#1038):
8595
+ * - each of CARRIED_OPERATION_REFS that the source's Git holds and that has
8596
+ * nothing at its name in the source's own Git directory, which the copy of
8597
+ * the Git directory's files therefore did not take, is written with `git
8598
+ * update-ref` at the same object id. Git is asked only where the refs may
8599
+ * be in the reftable format (refsMayBeReftable): in the files format each
8600
+ * of these refs is a file, and the copy took it;
8601
+ * - every object an operation ref of the recovery names (OPERATION_OBJECT_REFS,
8602
+ * written or copied) is carried before any ref is written, with
8603
+ * carryNamedObjects: a commit by id, a tree with what under it the copy
8604
+ * lacks (AUTO_MERGE's), a blob by content. Such an object is often in no
8605
+ * branch (a commit reset away, a conflict's tree), and a clone does not
8606
+ * bring it. One the source itself lacks is not carried: the recovery's ref
8607
+ * names nothing there either. Git refuses to write a ref whose object is
8608
+ * not there, so a reftable ref the source holds without its object refuses
8609
+ * the copy.
8610
+ * Every id is checked as a full object id of the repository's object format
8611
+ * before use: a written ref's that is not one refuses the copy; a line of a
8612
+ * copied file that is not one names nothing, as for Git, carries no object
8613
+ * and is not used. A Git step that fails throws, as a failed copy does. */
8614
+ function carryOperationRefs(sourceWork, recoveredRepo, sourceGit) {
8615
+ const written = operationRefsWritten(sourceWork, sourceGit);
8616
+ const copied = [];
8617
+ for (const name of OPERATION_OBJECT_REFS) if (!written.some((r) => r.name === name)) copied.push(...recoveredOperationObjects(recoveredRepo, name));
8618
+ if (!written.length && !copied.length) return;
8619
+ const full = objectIdPattern(sourceWork);
8620
+ for (const { name, oid } of written) if (!full.test(oid)) throw new Error(`${name} of ${sourceWork} holds ${JSON.stringify(oid)}, which is not a full object id of the repository's object format`);
8621
+ // A line of a copied file that is no full object id names no object: the copy holds the same
8622
+ // file, which Git reads as naming nothing there either, and the line reaches no Git command.
8623
+ const named = [...written.map((r) => r.oid), ...copied.filter((oid) => full.test(oid))];
8624
+ if (!named.length) return;
8625
+ const commits = [], trees = [], blobs = [];
8626
+ for (const [oid, type] of gitObjectTypes(sourceWork, [...new Set(named)])) {
8627
+ if (type === "tree") { const under = missingTreeObjects(sourceWork, recoveredRepo, oid); trees.push(...under.trees); blobs.push(...under.blobs); }
8628
+ else if (type === "blob") blobs.push(oid);
8629
+ else if (type !== "missing") commits.push(oid);
8630
+ }
8631
+ carryNamedObjects(sourceWork, recoveredRepo, { commits, trees, blobs });
8632
+ for (const { name, oid } of written) retireGit(recoveredRepo, ["update-ref", name, oid]);
8085
8633
  }
8086
8634
 
8087
8635
  /** Give a recovery clone the source's effective exclude rules, so the status comparison sees the same
@@ -8137,10 +8685,14 @@ function carryStatusConfig(sourceWork, recoveredRepo) {
8137
8685
  /** Make a recovery clone stand on its own: give it the source's stash (the
8138
8686
  * ref, its log, and every commit the copied log names: awebai/oats#654),
8139
8687
  * prove it holds those and `commits` (what the caller's carried metadata
8140
- * names) with carryNamedObjects, then remove the remote it was cloned from. */
8688
+ * names) with carryNamedObjects, then remove the remote it was cloned from.
8689
+ * The log is copied as a file where it is one. In the reftable format it is
8690
+ * not (awebai/oats#1038): its entries are read through Git (stashEntries) and
8691
+ * written back with `git stash store`, so that `git stash list` reads the
8692
+ * same in the copy. */
8141
8693
  function detachRecoveryClone(source, recovered, commits = []) {
8142
8694
  const named = [...commits];
8143
- let stash;
8695
+ let stash, entries = [];
8144
8696
  try { stash = retireGit(source, ["rev-parse", "--verify", "--quiet", "refs/stash"], { encoding: "utf8" }).trim(); }
8145
8697
  catch { stash = undefined; }
8146
8698
  if (stash) {
@@ -8150,10 +8702,56 @@ function detachRecoveryClone(source, recovered, commits = []) {
8150
8702
  const stashLog = copiedGitPath(GIT_STASH_LOG, null, sourceCommon);
8151
8703
  const recoveredLog = copiedGitPath(GIT_STASH_LOG, null, join(recovered, ".git"));
8152
8704
  if (copyRegularFile(stashLog, recoveredLog)) named.push(...reflogCommits(recoveredLog));
8705
+ else {
8706
+ entries = stashEntries(source);
8707
+ named.push(...entries.map((e) => e.oid));
8708
+ }
8153
8709
  }
8154
8710
  carryNamedObjects(source, recovered, { commits: named });
8711
+ if (entries.length) storeStashEntries(source, recovered, entries);
8155
8712
  try { retireGit(recovered, ["remote", "remove", "origin"]); } catch { /* no remote is already independent */ }
8156
8713
  }
8714
+ /** The stash's entries as Git reads them from its reflog, oldest first:
8715
+ * { oid, subject, line }, `subject` the entry's message (`%gs`), `line` its row
8716
+ * as read. Read only where the log is not a file (the reftable format). A
8717
+ * message that is not UTF-8 cannot be given back to Git as an argument: that
8718
+ * refuses the copy, as an object id that is not a full one does. */
8719
+ function stashEntries(source) {
8720
+ const full = objectIdPattern(source);
8721
+ const rows = retireGit(source, ["reflog", "show", "--format=%H %gs", "refs/stash", "--"]);
8722
+ const out = [];
8723
+ for (const bytes of splitLines(rows)) {
8724
+ const line = bytes.toString("utf8");
8725
+ if (!Buffer.from(line).equals(bytes)) throw new Error(`a stash entry of ${source} has a message that is not UTF-8, and Git cannot be given it back`);
8726
+ const space = line.indexOf(" ");
8727
+ const oid = space < 0 ? line : line.slice(0, space);
8728
+ if (!full.test(oid)) throw new Error(`a stash entry of ${source} names ${JSON.stringify(oid)}, which is not a full object id of the repository's object format`);
8729
+ out.push({ oid, subject: space < 0 ? "" : line.slice(space + 1), line });
8730
+ }
8731
+ return out.reverse();
8732
+ }
8733
+ /** Write `entries` (stashEntries) into the copy's stash, oldest first, over the
8734
+ * fetched ref and its empty log, then check that the copy's stash reads as the
8735
+ * source's, entry for entry. */
8736
+ function storeStashEntries(source, recovered, entries) {
8737
+ retireGit(recovered, ["update-ref", "-d", "refs/stash"]);
8738
+ for (const { oid, subject } of entries) retireGit(recovered, ["stash", "store", "-m", subject, oid]);
8739
+ const copied = splitLines(retireGit(recovered, ["reflog", "show", "--format=%H %gs", "refs/stash", "--"])).map((b) => b.toString("utf8")).reverse();
8740
+ if (copied.length !== entries.length || copied.some((line, i) => line !== entries[i].line)) {
8741
+ throw new Error(`the recovery's stash does not read as the stash of ${source}: ${entries.length} entries there, ${copied.length} written`);
8742
+ }
8743
+ }
8744
+ /** The lines of Git's output, each as bytes, without the line feed that ends it. */
8745
+ function splitLines(out) {
8746
+ const lines = [];
8747
+ for (let at = 0; at < out.length;) {
8748
+ let end = out.indexOf(10, at);
8749
+ if (end < 0) end = out.length;
8750
+ if (end > at) lines.push(out.subarray(at, end));
8751
+ at = end + 1;
8752
+ }
8753
+ return lines;
8754
+ }
8157
8755
 
8158
8756
  /** The commit at a repository's HEAD as the copier reads it, or null when
8159
8757
  * its HEAD has none: a branch nobody has committed on (`git init` and no
@@ -8248,7 +8846,7 @@ function materializeNestedRepositories(sourceWork, recoveredRepo) {
8248
8846
  // HEAD holds is not said: it is a file's content, and need not be text.
8249
8847
  if (head === null && name.branch === null) throw new Error(`nested repository ${source} has no commit at its HEAD, and its HEAD names no local branch`);
8250
8848
  rmSync(dest, { recursive: true, force: true });
8251
- retireGit(null, ["clone", "--no-local", "--quiet", source, dest]);
8849
+ cloneRecovery(["--no-local", "--quiet", source, dest]);
8252
8850
  detachRecoveryClone(source, dest, carryNestedRefs(source, dest, name, head));
8253
8851
  restoreStandaloneGitState(source, dest);
8254
8852
  for (const c of carryExcludes(source, dest)) excludes.push({ repo: rel, ...c });
@@ -8351,9 +8949,9 @@ function copyRecoveryWork(observation, meta, parent) {
8351
8949
  try { ref = existsSync(observation.work) ? worktreeHead(observation.work) : { branch: meta.branch, commit: null }; }
8352
8950
  catch (e) { unreadableHeads.add(e); throw e; }
8353
8951
  if (meta.branch && ref.branch !== meta.branch) branchDrift = { recordedBranch: meta.branch, worktreeBranch: ref.branch, detachedAt: ref.branch === null ? ref.commit : null };
8354
- if (ref.branch !== null) retireGit(null, ["clone", "--no-local", "--quiet", "--branch", ref.branch, meta.repo, recoveredRepo]);
8952
+ if (ref.branch !== null) cloneRecovery(["--no-local", "--quiet", "--branch", ref.branch, meta.repo, recoveredRepo]);
8355
8953
  else {
8356
- retireGit(null, ["clone", "--no-local", "--quiet", "--no-checkout", meta.repo, recoveredRepo]);
8954
+ cloneRecovery(["--no-local", "--quiet", "--no-checkout", meta.repo, recoveredRepo]);
8357
8955
  copierFetch(recoveredRepo, observation.work, [ref.commit]);
8358
8956
  retireGit(recoveredRepo, ["checkout", "--quiet", "--detach", ref.commit]);
8359
8957
  }
@@ -8537,7 +9135,7 @@ function completeRetirementRecovery({ receipt, manifest }, before, after, meta)
8537
9135
  try { owned = realpathSync(recovery) === join(realpathSync(dirname(after.home)), ".oats-retirement", "recovery", basename(recovery)); } catch { /* gone: not the owned storage */ }
8538
9136
  if (!owned) throw new Error("directory recovery storage was redirected");
8539
9137
  };
8540
- let staging, manifestStarted = false;
9138
+ let staging;
8541
9139
  try {
8542
9140
  assertOwnedStorage();
8543
9141
  // Work that is not proven unchanged is copied. So is work this recovery does
@@ -8571,36 +9169,40 @@ function completeRetirementRecovery({ receipt, manifest }, before, after, meta)
8571
9169
  const notCopied = unionNotCopied(receipt.notCopied, after.notCopied);
8572
9170
  const { notCopied: _before, ...rest } = manifest;
8573
9171
  assertOwnedStorage();
8574
- manifestStarted = true;
8575
- writeFileSync(manifestTmp, JSON.stringify({ ...rest, phase: "complete", classes, ...(notCopied.length ? { notCopied } : {}), ...(afterHooks ? { afterHooks } : {}) }, null, 2) + "\n", { mode: 0o600 });
8576
- renameSync(manifestTmp, manifestPath);
9172
+ // A failed write or rename removes its private file and throws its own error (#1076).
9173
+ writeThroughPrivateFile(manifestPath, manifestTmp, JSON.stringify({ ...rest, phase: "complete", classes, ...(notCopied.length ? { notCopied } : {}), ...(afterHooks ? { afterHooks } : {}) }, null, 2) + "\n", 0o600);
8577
9174
  const { notCopied: _was, ...kept } = receipt;
8578
9175
  return { ...kept, classes, bytes: treeBytes(recovery), ...(notCopied.length ? { notCopied } : {}), ...(afterHooks ? { afterHooks } : {}) };
8579
9176
  } catch (e) {
8580
9177
  const left = staging ? removeStaging(staging) : null;
8581
- if (manifestStarted) { try { rmSync(manifestTmp, { force: true }); } catch { /* the original error is the refusal */ } }
8582
9178
  if (unreadableHeads.has(e)) { if (left) e.message += left; throw e; }
8583
9179
  const details = e.statusDisagreement ? { home: after.home, statusDisagreement: e.statusDisagreement } : undefined;
8584
9180
  throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `retirement work remains at ${after.home}; recovery could not be verified: ${e.message}${left ?? ""}`, details), details ? { details } : {});
8585
9181
  }
8586
9182
  }
8587
9183
 
8588
- /** The `work` link of the instance at `kidHome` when it is attached to
8589
- * `home`'s work (#718), else null: instance.json says `work: "attached"`, and
8590
- * its `work` is a symbolic link that leads to `<home>/work`, as written (in
8591
- * any spelling of the home) or through other links (`--work-dir` given as an
8592
- * alias of the tree). The latter is seen only while `<home>/work` exists, so a
8593
- * retire asks before it re-homes the worktree. → the link's target as written:
8594
- * the evidence a later relink checks is still there. */
8595
- export function attachedWorkLink(kidHome, home) {
9184
+ /** The `work` link of the instance at `kidHome` when it is attached to the
9185
+ * tree at `tree` (#718, #964), else null. `tree` is a tree of a home: its
9186
+ * `<home>/work`, or an extra tree of it (`<home>/.work-<purpose>`). Attached:
9187
+ * instance.json says `work: "attached"`, and its `work` is a symbolic link
9188
+ * that leads to the tree, as written (in any spelling of the home) or
9189
+ * through other links (`--work-dir` given as an alias of the tree). The
9190
+ * latter is seen only while the tree exists, so whoever moves or removes the
9191
+ * tree asks first. The one test of who is attached to a tree: the retire,
9192
+ * its plan and `oats worktree remove` read it. → the link's target as
9193
+ * written: the evidence a later relink checks is still there. */
9194
+ export function attachedWorkLink(kidHome, tree) {
8596
9195
  if (readJsonOrUndefined(join(kidHome, "instance.json"))?.work !== "attached") return null;
8597
9196
  const link = join(kidHome, "work");
8598
9197
  let written;
8599
9198
  try { written = readlinkSync(link); } catch { return null; }
8600
- const target = resolve(kidHome, written);
8601
- if (target === join(resolve(home), "work")) return written;
8602
- try { if (basename(target) === "work" && realpathSync(dirname(target)) === realpathSync(home)) return written; } catch { /* below */ }
8603
- try { return realpathSync(link) === realpathSync(join(home, "work")) ? written : null; } catch { return null; }
9199
+ const target = resolve(kidHome, written), at = resolve(tree);
9200
+ if (target === at) return written;
9201
+ // Existing paths are compared in their one spelling on disk (realpathSync.native, as
9202
+ // canonicalHomePath): on a case-insensitive filesystem JS realpathSync keeps the caller's letter
9203
+ // case, so a tree named as `.WORK-X` and as `.work-x` would read as two trees.
9204
+ try { if (basename(target) === basename(at) && realpathSync.native(dirname(target)) === realpathSync.native(dirname(at))) return written; } catch { /* below */ }
9205
+ try { return realpathSync.native(link) === realpathSync.native(at) ? written : null; } catch { return null; }
8604
9206
  }
8605
9207
  /** Point an attached instance's `work` link at `to`, atomically: a new link
8606
9208
  * beside it is renamed over the old one, so the link is never missing. */
@@ -9200,7 +9802,7 @@ function retireUnderClaim(root, name, o) {
9200
9802
  // its plan and checks the revision): after the two answers above, before the retire reads
9201
9803
  // anything of the home. What it returns of the plan binds the retire.
9202
9804
  const confirmed = o[RETIRE_UNDER_CLAIM]?.();
9203
- const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}) } : o;
9805
+ const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}), ...(confirmed.ambiguous ? { ambiguous: confirmed.ambiguous } : {}) } : o;
9204
9806
  return retireClaimed(root, name, bound, now);
9205
9807
  } finally {
9206
9808
  releaseHomeClaim(held);
@@ -9793,14 +10395,65 @@ function retireSteps(root, name, o, found, at) {
9793
10395
  // as planned refuse as stale before any of them is touched.
9794
10396
  let extraWorktrees;
9795
10397
  let retention = null;
10398
+ // An attached child's `work` is a link to a tree of this home: to its work/ (#718) or to one of
10399
+ // its extra trees (#964). A tree the retire moves or removes would leave that link pointing at a
10400
+ // path that is gone. The children looked at are the recorded ones this retire stopped; each tree's
10401
+ // are found while the tree is still there (a link through an alias of the tree resolves only
10402
+ // then), each with its link as written. What the retire could not do for one, or leaves it with,
10403
+ // is a warning in the receipt: the retire is not undone.
10404
+ const relinkWarnings = [];
10405
+ const stoppedKids = (childrenStopped || []).filter((k) => k.ok);
10406
+ // The instances the plan lists under `ambiguous` (`o.ambiguous`, handed in with the children: this
10407
+ // function reads no lineage) are attached by their link as well. The retire does not act on them:
10408
+ // they are not stopped, and a write to an instance that may be running is not made. A tree that is
10409
+ // moved or removed leaves their link pointing at a path that is gone, and the receipt says so.
10410
+ const attachedTo = (tree) => [...stoppedKids, ...(Array.isArray(o.ambiguous) ? o.ambiguous.map((k) => ({ instance: k.instance, home: k.home, ambiguous: true })) : [])]
10411
+ .map((k) => ({ ...k, link: attachedWorkLink(k.home, tree) })).filter((k) => k.link !== null);
10412
+ const NOT_STOPPED = "it records this instance as its parent under a name that is not unique, so the retire did not stop it";
10413
+ // The attachment as it was found, still: attached, and the same link. One that changed is
10414
+ // someone else's now, and is left as it is.
10415
+ const stillAttached = (kid) => { try { return readJsonOrUndefined(join(kid.home, "instance.json"))?.work === "attached" && readlinkSync(join(kid.home, "work")) === kid.link; } catch { return false; } };
10416
+ /** Repoint each of `kids` to `to`, where the tree that was at `from` is retained. It is a write to
10417
+ * another instance, so it is made only once the move is done and seen done: the tree is at its
10418
+ * new path and nothing is left at the old one. The child's AGENTS.md still names the old path. */
10419
+ const repointAttached = (kids, from, to) => {
10420
+ const present = (p) => { try { lstatSync(p); return true; } catch { return false; } };
10421
+ const moved = kids.length > 0 && (() => { try { return lstatSync(to).isDirectory(); } catch { return false; } })() && !present(from);
10422
+ for (const kid of kids) {
10423
+ if (kid.ambiguous) {
10424
+ if (stillAttached(kid)) relinkWarnings.push(`${kid.instance}: its work was ${from}, which this retire re-homed to ${to}; its work link ${join(kid.home, "work")} was not repointed and now points at a path that is gone (${NOT_STOPPED}); to repoint it by hand: ln -sfn ${shq(to)} ${shq(join(kid.home, "work"))}`);
10425
+ continue;
10426
+ }
10427
+ if (!stillAttached(kid)) {
10428
+ relinkWarnings.push(`${kid.instance}: its attachment changed during the retire, so its work was left as it is now and not repointed to the retained worktree ${to}; inspect ${join(kid.home, "work")}`);
10429
+ continue;
10430
+ }
10431
+ try {
10432
+ if (!moved) throw new Error(`the worktree was not seen at ${to} with nothing left at ${from}`);
10433
+ relinkAttachedWork(kid.home, to);
10434
+ } catch (e) {
10435
+ relinkWarnings.push(`${kid.instance}: its work link could not be repointed to the retained worktree ${to} (${e.message}) and still points at ${kid.link}; repoint it by hand: ln -sfn ${shq(to)} ${shq(join(kid.home, "work"))}`);
10436
+ }
10437
+ }
10438
+ };
10439
+ /** Say of each of `kids` that the tree at `tree`, which this retire removed, was its work: its
10440
+ * link, when it is still the one that was found, now points at a path that is gone. */
10441
+ const leftWithoutWork = (kids, tree, why) => {
10442
+ for (const kid of kids) if (stillAttached(kid)) relinkWarnings.push(`${kid.instance}: its work was ${tree}, which this retire removed (${why}); its work link ${join(kid.home, "work")} now points at a path that is gone${kid.ambiguous ? ` (${NOT_STOPPED})` : ""}`);
10443
+ };
9796
10444
  // From here on the retire removes and re-homes trees: a failure no longer says that the work is
9797
- // kept, only what is still true, and which trees it has dealt with.
10445
+ // kept, only what is still true, which trees it has dealt with, and what that left an attached
10446
+ // child with.
10447
+ const attachedSaid = () => relinkWarnings.length ? `. Attached children: ${relinkWarnings.join("; ")}` : "";
9798
10448
  const treesDone = () => {
9799
10449
  const done = [...(extraWorktrees || []).map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`),
9800
10450
  ...(retention?.worktree === "removed" ? [`${workPath} removed`] : retention?.worktree === "retained" ? [`${workPath} re-homed to ${retention.movedTo}`] : [])];
9801
- return done.length ? `. Already done in this retire: ${done.join(", ")}` : "";
10451
+ return done.length ? `. Already done in this retire: ${done.join(", ")}${attachedSaid()}` : "";
9802
10452
  };
9803
10453
  at.said = () => `${hooksSaid()}; the home is kept, and so is any recovery the retire wrote; ${sessionSaid()}${treesDone()}`;
10454
+ // The same for a refusal that has its own sentence, once the extra-tree step has dealt with a
10455
+ // tree: the refusals of that step, and every one of the work/ step, which comes after it.
10456
+ const alreadyDone = () => extraWorktrees?.length ? ` Already done in this retire: ${extraWorktrees.map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`).join(", ")}${attachedSaid()}.` : "";
9804
10457
  if (!o.keepDir && !(outstandingBeforeWorktree.length > 0 && !o.force)) {
9805
10458
  const rows = extraWorktreeRows(finalObservation.extraTrees, root);
9806
10459
  if (o.plannedExtraWorktrees && JSON.stringify(rows) !== JSON.stringify(o.plannedExtraWorktrees)) {
@@ -9812,11 +10465,12 @@ function retireSteps(root, name, o, found, at) {
9812
10465
  throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: ${refused.map((r) => `the extra worktree ${r.path}: ${r.reason}`).join("; ")}. No extra worktree was moved or removed and work/ is untouched; the retire hooks have run and the home is kept so nothing is lost.`);
9813
10466
  }
9814
10467
  extraWorktrees = [];
9815
- const done = () => extraWorktrees.length ? ` Already done in this retire: ${extraWorktrees.map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`).join(", ")}.` : "";
10468
+ // Who is attached to each tree, asked before any of them is moved or removed.
10469
+ const attachedOf = new Map(rows.map((row) => [row.path, attachedTo(row.path)]));
9816
10470
  // Each row's repository, by its Git directory: the commands run helper-free (gitRepoRun).
9817
10471
  const gitDirOf = new Map(finalObservation.extraTrees.map((tree) => [tree.path, tree.commonDir]));
9818
10472
  const git = (row, argv) => gitRepoRun(gitDirOf.get(row.path), argv);
9819
- const failed = (row, what, e) => oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the extra worktree ${row.path} ${what} (${String(e?.stderr ?? e?.message ?? e ?? "").trim()}).${done()} work/ is untouched; the retire hooks have run and the home is kept so nothing is lost — resolve and retry.`);
10473
+ const failed = (row, what, e) => oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the extra worktree ${row.path} ${what} (${String(e?.stderr ?? e?.message ?? e ?? "").trim()}).${alreadyDone()} work/ is untouched; the retire hooks have run and the home is kept so nothing is lost — resolve and retry.`);
9820
10474
  for (const row of rows) {
9821
10475
  if (row.disposition === "remove") {
9822
10476
  try {
@@ -9827,6 +10481,7 @@ function retireSteps(root, name, o, found, at) {
9827
10481
  } catch (e) { throw failed(row, "could not be removed, or its removal could not be verified", e); }
9828
10482
  extraWorktrees.push({ ...row, outcome: "removed" });
9829
10483
  appendEvent(found.home, { kind: "worktree-removed", data: { branch: row.branch, extra: true, path: row.path } }, { workspaceOnly: true });
10484
+ leftWithoutWork(attachedOf.get(row.path), row.path, "an extra worktree of the retired instance, clean: its branch and commits stay in its repository");
9830
10485
  } else {
9831
10486
  try {
9832
10487
  mkdirSync(dirname(row.movedTo), { recursive: true });
@@ -9834,14 +10489,16 @@ function retireSteps(root, name, o, found, at) {
9834
10489
  } catch (e) { throw failed(row, `could not be re-homed to ${row.movedTo}`, e); }
9835
10490
  extraWorktrees.push({ ...row, outcome: "retained" });
9836
10491
  appendEvent(found.home, { kind: "worktree-retained", data: { movedTo: row.movedTo, branch: row.branch, recordedBranch: null, extra: true, path: row.path } }, { workspaceOnly: true });
10492
+ // Right after this tree's move, not at the end as for work/: the work/ step below can still
10493
+ // refuse and keep the home, and the tree has left it either way.
10494
+ repointAttached(attachedOf.get(row.path), row.path, row.movedTo);
9837
10495
  }
9838
10496
  }
9839
10497
  if (!extraWorktrees.length) extraWorktrees = undefined;
9840
10498
  }
9841
10499
  // The attached children this retire stopped whose work is this home's work/
9842
- // (#718), found while work/ is still here (a link through an alias of the
9843
- // tree resolves only then), each with its link as written.
9844
- const attachedKids = (childrenStopped || []).filter((k) => k.ok).map((k) => ({ ...k, link: attachedWorkLink(k.home, found.home) })).filter((k) => k.link !== null);
10500
+ // (#718), found while work/ is still here.
10501
+ const attachedKids = attachedTo(workPath);
9845
10502
  const worktreeStep = isWorktree && !!workMeta.repo && !orphanedWork;
9846
10503
  const worktreeDeferred = worktreeStep && existsSync(workPath) && outstandingBeforeWorktree.length > 0 && !o.force;
9847
10504
  const keptForRetry = worktreeDeferred ? `git worktree ${workPath}: kept for the retry; outstanding: ${outstandingBeforeWorktree.join("; ")}` : null;
@@ -9874,8 +10531,9 @@ function retireSteps(root, name, o, found, at) {
9874
10531
  if (existsSync(workPath)) {
9875
10532
  let now;
9876
10533
  try { now = worktreeHead(workPath); }
9877
- catch (e) { throw oatsError("E_WORK_INSPECTION_FAILED", `${e.message}. The worktree was not removed. The home and the worktree are kept, and so is any recovery the retire wrote; retry the retire.`); }
9878
- assertSameWorktreeHead(finalObservation.head, now);
10534
+ catch (e) { throw oatsError("E_WORK_INSPECTION_FAILED", `${e.message}. The worktree was not removed.${alreadyDone()} The home and the worktree are kept, and so is any recovery the retire wrote; retry the retire.`); }
10535
+ try { assertSameWorktreeHead(finalObservation.head, now); }
10536
+ catch (e) { throw oatsError(e.code, `${e.message}${alreadyDone()}`); }
9879
10537
  }
9880
10538
  // The removal is verified as the extra-tree step's is: nothing is at work/ and the repository's
9881
10539
  // worktree list does not name it. A removal that did not happen, or cannot be shown to have
@@ -9895,8 +10553,7 @@ function retireSteps(root, name, o, found, at) {
9895
10553
  gitRepoRun(gitDir.dir, ["worktree", "prune"]);
9896
10554
  if (entryAt(workPath) || parseWorktreeList(gitRepoRun(gitDir.dir, ["worktree", "list", "--porcelain", "-z"])).some((r) => canonicalHomePath(r.worktree) === real)) throw new Error("it is still there after `git worktree remove`");
9897
10555
  } catch (e) {
9898
- const done = extraWorktrees?.length ? ` Already done in this retire: ${extraWorktrees.map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`).join(", ")}.` : "";
9899
- throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be removed, or its removal could not be verified (${String(e?.stderr || e?.message || e || "").trim() || "unknown error"}).${done} The retire hooks have run; the home is kept, and so is any recovery the retire wrote; ${sessionSaid()}. Check what is left at ${workPath}, then retry the retire.`);
10556
+ throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be removed, or its removal could not be verified (${String(e?.stderr || e?.message || e || "").trim() || "unknown error"}).${alreadyDone()} The retire hooks have run; the home is kept, and so is any recovery the retire wrote; ${sessionSaid()}. Check what is left at ${workPath}, then retry the retire.`);
9900
10557
  }
9901
10558
  retention = { worktree: "removed", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
9902
10559
  }
@@ -9908,7 +10565,7 @@ function retireSteps(root, name, o, found, at) {
9908
10565
  if (gitDir.error) throw new Error(gitDir.error);
9909
10566
  gitRepoRun(gitDir.dir, ["worktree", "move", workPath, dest]);
9910
10567
  } catch (e) {
9911
- throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be re-homed to ${dest} (${String(e.stderr ?? e.message ?? "").trim()}); the home is kept so nothing is lost — resolve and retry, or pass --discard-worktree to remove the worktree instead`);
10568
+ throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be re-homed to ${dest} (${String(e.stderr ?? e.message ?? "").trim()})${alreadyDone() ? `.${alreadyDone()} The` : "; the"} home is kept so nothing is lost — resolve and retry, or pass --discard-worktree to remove the worktree instead`);
9912
10569
  }
9913
10570
  retention = { worktree: "retained", movedTo: dest, branch: verifiedBranch, detachedAt: verifiedBranch === null ? ref.commit : null, recordedBranch: meta.branch ?? null };
9914
10571
  } else retention = { worktree: "absent", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
@@ -10036,26 +10693,10 @@ function retireSteps(root, name, o, found, at) {
10036
10693
  // last, once the move is done and seen done: the worktree is at its new path
10037
10694
  // and nothing is left at work/. One that fails is a warning; the retire is
10038
10695
  // not undone. The child's AGENTS.md still names the old path.
10039
- const relinkWarnings = [];
10040
- if (retention?.worktree === "retained") {
10041
- const present = (p) => { try { lstatSync(p); return true; } catch { return false; } };
10042
- const moved = attachedKids.length > 0 && (() => { try { return lstatSync(retention.movedTo).isDirectory(); } catch { return false; } })() && !present(workPath);
10043
- for (const kid of attachedKids) {
10044
- // The attachment as it was found, still: attached, and the same link. One that changed is
10045
- // someone else's now, and is left as it is.
10046
- const still = (() => { try { return readJsonOrUndefined(join(kid.home, "instance.json"))?.work === "attached" && readlinkSync(join(kid.home, "work")) === kid.link; } catch { return false; } })();
10047
- if (!still) {
10048
- relinkWarnings.push(`${kid.instance}: its attachment changed during the retire, so its work was left as it is now and not repointed to the retained worktree ${retention.movedTo}; inspect ${join(kid.home, "work")}`);
10049
- continue;
10050
- }
10051
- try {
10052
- if (!moved) throw new Error(`the worktree was not seen at ${retention.movedTo} with nothing left at ${workPath}`);
10053
- relinkAttachedWork(kid.home, retention.movedTo);
10054
- } catch (e) {
10055
- relinkWarnings.push(`${kid.instance}: its work link could not be repointed to the retained worktree ${retention.movedTo} (${e.message}) and still points at ${kid.link}; repoint it by hand: ln -sfn ${shq(retention.movedTo)} ${shq(join(kid.home, "work"))}`);
10056
- }
10057
- }
10058
- }
10696
+ if (retention?.worktree === "retained") repointAttached(attachedKids, workPath, retention.movedTo);
10697
+ // A work/ this retire removed (--discard-worktree, or a failed spawn's quarantine that owed it)
10698
+ // leaves each of them with a link to a path that is gone (#964): said, by name.
10699
+ else if (retention?.worktree === "removed") leftWithoutWork(attachedKids, workPath, o.discardWorktree ? "--discard-worktree" : "the worktree of a spawn that failed");
10059
10700
  // Forcing is the operator overriding the fail-closed default with their eyes
10060
10701
  // open: the home goes, and what remains outstanding is reported rather than
10061
10702
  // swallowed. Without this, a quarantine whose cleanup can never succeed (a