@awebai/oats 0.55.1 → 0.56.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 (78) hide show
  1. package/bin/oats.mjs +78 -62
  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 +317 -35
  5. package/docs/desktop-instance-start.md +105 -12
  6. package/docs/desktop.md +54 -7
  7. package/docs/execution-targets.md +184 -9
  8. package/docs/harness-trust.md +128 -11
  9. package/docs/implementation.md +54 -7
  10. package/docs/integrations.md +1 -1
  11. package/docs/knowledge.md +35 -16
  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/servers.md +21 -5
  17. package/docs/souls-and-instances.md +8 -4
  18. package/docs/tui.md +99 -26
  19. package/docs/upgrading.md +4 -1
  20. package/docs/workspaces.md +26 -6
  21. package/lib/automations.mjs +3 -4
  22. package/lib/bounded-read.mjs +18 -0
  23. package/lib/capability-show.mjs +13 -2
  24. package/lib/claim.mjs +3 -4
  25. package/lib/core.mjs +480 -152
  26. package/lib/errors.mjs +39 -0
  27. package/lib/harness-trust-write.mjs +119 -40
  28. package/lib/harness-trust.mjs +31 -18
  29. package/lib/instance-inspect.mjs +160 -11
  30. package/lib/instance-lifecycle.mjs +47 -30
  31. package/lib/packages.mjs +8 -5
  32. package/lib/pi-bridge.mjs +18 -19
  33. package/lib/remote.mjs +88 -51
  34. package/lib/retire-output.mjs +9 -4
  35. package/lib/schedule.mjs +3 -4
  36. package/lib/servers.mjs +39 -6
  37. package/lib/session-viewer.mjs +25 -1
  38. package/lib/triggers.mjs +3 -4
  39. package/lib/workspace.mjs +6 -6
  40. package/lib/worktree.mjs +10 -6
  41. package/lib/write-through-private-file.mjs +26 -0
  42. package/package-catalog.json +2 -2
  43. package/package.json +1 -1
  44. package/packages/client/cli-adapter.mjs +108 -13
  45. package/packages/client/cli-locator.mjs +16 -14
  46. package/packages/client/deployment-panel.mjs +4 -3
  47. package/packages/client/display-text.mjs +2 -1
  48. package/packages/client/instance-events-contract.mjs +4 -3
  49. package/packages/client/instance-lifecycle.mjs +228 -0
  50. package/packages/client/instance-presentation.mjs +9 -0
  51. package/packages/client/instance-tree.mjs +10 -8
  52. package/packages/client/kernel-lines.mjs +3 -3
  53. package/packages/client/launch-contract.mjs +11 -0
  54. package/packages/client/lifecycle-cli.mjs +12 -6
  55. package/packages/client/lifecycle-confirmation.mjs +407 -0
  56. package/packages/client/lifecycle-contract.mjs +6 -2
  57. package/packages/client/own-codes.mjs +1 -0
  58. package/packages/client/panel-views.mjs +39 -2
  59. package/packages/client/readiness-contract.mjs +2 -2
  60. package/packages/client/remote-roster.mjs +50 -5
  61. package/packages/client/roster-sections.mjs +3 -3
  62. package/packages/client/session-start.mjs +98 -0
  63. package/packages/client/start-gate.mjs +46 -0
  64. package/packages/client/start-messages.mjs +17 -0
  65. package/packages/client/workspace-views.mjs +2 -2
  66. package/packages/tui/README.md +10 -6
  67. package/packages/tui/lib/actions.mjs +4 -2
  68. package/packages/tui/lib/client.mjs +5 -2
  69. package/packages/tui/lib/config.mjs +39 -9
  70. package/packages/tui/lib/main.mjs +83 -13
  71. package/packages/tui/lib/model.mjs +116 -11
  72. package/packages/tui/lib/open.mjs +45 -0
  73. package/packages/tui/lib/read.mjs +46 -10
  74. package/packages/tui/lib/store.mjs +64 -9
  75. package/packages/tui/lib/term/tty.mjs +71 -12
  76. package/packages/tui/lib/views/frame.mjs +115 -33
  77. package/packages/tui/lib/views/help.mjs +37 -8
  78. 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,
@@ -2336,7 +2341,7 @@ function oatsWindowEnvironment() {
2336
2341
  * will open a window in: `{ server, present }` from the lookup and, when `session` is not on the
2337
2342
  * OATS server and this is no preview, `env`: the environment its creation needs, read now, so that a
2338
2343
  * 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
2344
+ * ensureOatsTmuxSession. It is also what the launch's checks first read (expectedPaneEnvironment). Not the
2340
2345
  * guarantee: ensureOatsTmuxSession decides by what it finds when it creates, and the harness is
2341
2346
  * looked up again on the session it returns; and an environment read for a running server is read
2342
2347
  * again there when that server has gone. undefined when this process has no tmux to run: the
@@ -2350,18 +2355,28 @@ function planOatsTmuxSession(session, io, { preview = false, missingSocket } = {
2350
2355
  if (present || preview) return { server, present };
2351
2356
  return { server, present, env: oatsSessionEnvironment(session, io, { startsServer: !server }), startsServer: !server };
2352
2357
  }
2358
+ /** The names a check of a launch reads from the pane the launch will run in, never from this
2359
+ * process: where its harness is looked up, the home directory, and the three variables that move a
2360
+ * harness's configuration folder (HARNESS_CONFIG_SELECTORS). For a selector "not set" is an answer:
2361
+ * the harness then reads its default folder under HOME. For PATH and HOME it is a problem. */
2362
+ const PANE_ENV_NAMES = ["PATH", "HOME", ...Object.values(HARNESS_FOLDER_VAR)];
2353
2363
  /**
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`.
2364
+ * The environment a pane created in `session` on `socket` starts with, for PANE_ENV_NAMES, read as
2365
+ * tmux decides it (spawn.c, environ.c), never computed from this process: for each name the
2366
+ * session's own entry when it has one, otherwise the server's global one. `session` null reads the
2367
+ * global one only (a session about to be created on a running server). One `show-environment` for
2368
+ * the session and one for the server answer every name: each is made when a name first needs it,
2369
+ * at most once, and read with the strict reader, as bytes.
2370
+ * → `{ of(name), cwd }`. `of(name)` is `{ value, source }`; `{ absent: true, source }` for a selector
2371
+ * that neither holds, or that the session clears (the server's is then not the pane's); or
2372
+ * `{ source, problem }` when the pane's value cannot be established: a read that failed, a value
2373
+ * the strict reader leaves out (unknown), and for PATH and HOME an explicit clear (`unset PATH;`:
2374
+ * the pane has none at all; never substituted by the global one or this process's) or a server with
2375
+ * none (for PATH tmux would fall back to a compiled-in default, which OATS does not assume).
2376
+ * `source` names where the value comes from; no value is ever in it or in `problem`. A problem
2377
+ * carries `remedy`: what would make that entry readable, as a tmux command on this socket.
2363
2378
  */
2364
- function panePath(socket, session, io, cwd) {
2379
+ function paneEnvironment(socket, session, io, cwd) {
2365
2380
  const read = (scope) => {
2366
2381
  const omitted = [], cleared = [];
2367
2382
  let env = null;
@@ -2371,43 +2386,181 @@ function panePath(socket, session, io, cwd) {
2371
2386
  } catch (e) { if (isKernelCode(e?.code)) throw e; }
2372
2387
  return { env, omitted, cleared };
2373
2388
  };
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)` };
2389
+ let own, global;
2390
+ const server = `the OATS tmux server (${socket})`;
2391
+ const tmuxAt = `tmux -S ${shellWord(socket)}`;
2392
+ const decide = ({ env, omitted, cleared }, name, source, holder, scope) => {
2393
+ const set = `give ${holder} a ${name} that OATS can read (${tmuxAt} set-environment ${scope} ${name} <value>)`;
2394
+ if (env === null) return { source, problem: `${source} could not be read`, remedy: `make \`${tmuxAt} show-environment ${scope} -s\` answer` };
2395
+ if (Object.hasOwn(env, name)) return { value: env[name], source };
2396
+ 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 };
2397
+ 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
2398
  return null;
2380
2399
  };
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;
2400
+ const answers = new Map();
2401
+ const of = (name) => {
2402
+ if (answers.has(name)) return answers.get(name);
2403
+ let answer = session ? decide(own ??= read(["-t", `=${session}`]), name, `the ${name} of tmux session ${session}`, `tmux session ${session}`, `-t ${shellWord(`=${session}`)}`) : null;
2404
+ if (!answer) {
2405
+ const source = `the global ${name} of ${server}`;
2406
+ answer = decide(global ??= read(["-g"]), name, source, server, "-g")
2407
+ ?? (HARNESS_CONFIG_SELECTORS.has(name) ? { absent: true, source: `${session ? `tmux session ${session} and ` : ""}${server}, which set${session ? "" : "s"} no ${name}` }
2408
+ : { 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>)` });
2409
+ }
2410
+ answers.set(name, answer);
2411
+ return answer;
2412
+ };
2413
+ return { of, cwd };
2414
+ }
2415
+ /** Why no prediction of a pane's environment is made, as the tail of "the pane's environment is not
2416
+ * established": no server runs and this command starts none (a preview, a readiness read); this
2417
+ * process could not read the server (no tmux for it, or a preview's read that failed); the spawn
2418
+ * launches nothing; the session a start would create was refused. A tmux that is there and could
2419
+ * not say whether a server runs is a read that failed, not a server known not to run:
2420
+ * previewPaneEnvironment carries that failure (`unread`) beside the reason, so that a command that
2421
+ * writes by this answer refuses instead of writing for this process's file (`oats harness trust`).
2422
+ * A process with no tmux on its PATH makes no read at all: no prediction, and no `unread`. */
2423
+ const NO_SERVER_YET = Object.freeze({ unestablished: " until a spawn starts the OATS tmux server (none runs)" });
2424
+ const NO_PANE_READ = Object.freeze({ unestablished: ": this process could not read the OATS tmux server" });
2425
+ const NO_TMUX = Object.freeze({ unestablished: ": this process has no tmux on its PATH to read the OATS tmux server with" });
2426
+ const NO_LAUNCH = Object.freeze({ unestablished: ": this spawn launches nothing (--no-launch), and a start reads its own session's" });
2427
+ const SESSION_REFUSED = Object.freeze({ unestablished: ": the session this start would create was refused" });
2428
+ const HOME_SESSION_UNREAD = Object.freeze({ unestablished: ": this home's session record could not be read" });
2429
+ /** The environment a launch's pane is expected to have (paneEnvironment's shape), from a plan
2430
+ * (planOatsTmuxSession): the session's or the server's when a server runs, else the environment the
2431
+ * server will be created with. `{ unestablished }`, with why, when that is not known (no plan, or a
2432
+ * preview with no server: a preview reads no creation environment, which would start the user's
2433
+ * login shell); the checks then read this process's values and say so, and the launch looks again
2434
+ * on the session it actually gets. */
2435
+ function expectedPaneEnvironment(plan, session, io, cwd) {
2436
+ // No plan: this process has no tmux to ask with, or a preview's question to tmux failed.
2437
+ if (!plan) return !io?.exec && !which("tmux") ? NO_TMUX : NO_PANE_READ;
2438
+ if (plan.server) return paneEnvironment(plan.server, plan.present ? session : null, io, cwd);
2439
+ if (!plan.env) return NO_SERVER_YET;
2440
+ const of = (name) => {
2441
+ const source = `the ${name} the OATS tmux server is created with`;
2442
+ if (plan.env[name] !== undefined) return { value: plan.env[name], source };
2443
+ if (HARNESS_CONFIG_SELECTORS.has(name)) return { absent: true, source: `the environment the OATS tmux server is created with, which sets no ${name}` };
2444
+ 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" };
2445
+ };
2446
+ return { of, cwd };
2447
+ }
2448
+ /**
2449
+ * The environment a launch will have, for PANE_ENV_NAMES: the one answer to "where will this launch
2450
+ * run", which every check of a launch reads (the harness lookup, folder trust, the package probe and
2451
+ * the remedy it prints) and none reads from this process in its place. For each name, by precedence:
2452
+ * 1. what the launch's command line sets: the launch configuration's `env` (a literal, or a
2453
+ * reference resolved from `env`, the spawning process: by design), over the capabilities' env
2454
+ * (`capabilities`: `{ env, owner(name) }`), which only a start's package probe is given: a
2455
+ * spawn's probe runs before its hooks, and the folder-trust check and the harness lookup do
2456
+ * not read it (awebai/oats#1041);
2457
+ * 2. a name the launch removes (`removed`: removedLaunchEnv): absent, with the launch as its
2458
+ * source, whatever the pane holds;
2459
+ * 3. the pane's (`pane`: paneEnvironment or expectedPaneEnvironment, or a function giving one,
2460
+ * called once and only when a name is not decided by 1 or 2; `pane()` on the result is that one
2461
+ * read, for a second answer over the same pane);
2462
+ * 4. no prediction (`pane` gives `{ unestablished }`, the reason as a clause): this process's
2463
+ * value, carried with that `unestablished`, so that a check that read it says so
2464
+ * (unestablishedNote) and never passes it off as the pane's; and with `unread` when the
2465
+ * reason is a read of the server that failed, which a caller that writes must refuse.
2466
+ * → `{ of(name), cwd, pane, removed }` (`removed` for launchEffectiveEnv, built on this answer);
2467
+ * `of(name)` is paneEnvironment's answer: `{ value, source }`,
2468
+ * `{ absent: true, source }` (a selector only; an empty one is not set, as the harnesses read it) or
2469
+ * `{ source, problem }`. A reference whose source is not set gives a problem marked `unresolved`:
2470
+ * the caller's own check of references refuses it (E_LAUNCH_ENV_MISSING), not a lookup.
2471
+ */
2472
+ export function launchEnvironment({ configEnv, configName, capabilities, removed = [], env = process.env, pane, cwd }) {
2473
+ let read;
2474
+ const paneAnswer = () => (read ??= { pane: (typeof pane === "function" ? pane() : pane) ?? NO_PANE_READ }).pane;
2475
+ const notThePanes = (answer) => ({ ...(answer.unestablished ? { unestablished: answer.unestablished } : {}), ...(answer.unread ? { unread: answer.unread } : {}) });
2476
+ // An empty selector is not set, as the harnesses read it; an empty HOME names no directory.
2477
+ const selector = (name, answer) => answer.value !== "" ? answer
2478
+ : HARNESS_CONFIG_SELECTORS.has(name) ? { absent: true, source: answer.source, ...notThePanes(answer) }
2479
+ : name === "HOME" ? { source: answer.source, problem: `${answer.source} is empty`, ...notThePanes(answer) } : answer;
2480
+ const of = (name) => {
2481
+ const own = Object.hasOwn(configEnv || {}, name) ? configEnv[name] : undefined;
2482
+ if (typeof own === "string") return selector(name, { value: own, source: `the ${name} of launch configuration ${configName}` });
2483
+ if (own && typeof own === "object" && own.fromEnv) {
2484
+ const source = `the ${name} of launch configuration ${configName} (from ${own.fromEnv})`;
2485
+ 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 });
2486
+ }
2487
+ 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` });
2488
+ // A selector the launch removes (a manifest may declare one under a namespace it names); PATH
2489
+ // and HOME are never removed (removableLaunchEnvName).
2490
+ 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)` };
2491
+ const from = paneAnswer();
2492
+ if (from.of) {
2493
+ const answer = selector(name, from.of(name));
2494
+ // A relative folder is the pane's own: read against its working directory, the home.
2495
+ return HARNESS_CONFIG_SELECTORS.has(name) && typeof answer.value === "string" && cwd && !isAbsolute(answer.value) && !answer.value.startsWith("~") ? { ...answer, value: resolve(cwd, answer.value) } : answer;
2496
+ }
2497
+ const source = `this process's ${name}`;
2498
+ const why = { unestablished: from.unestablished, ...(from.unread ? { unread: from.unread } : {}) };
2499
+ // What this process itself would read: its HOME, else its user's home directory.
2500
+ const value = name === "HOME" ? env.HOME || homedir() : env[name];
2501
+ if (value !== undefined) return selector(name, { value, source, ...why });
2502
+ return HARNESS_CONFIG_SELECTORS.has(name) ? { absent: true, source, ...why } : { source, problem: `${source} is not set`, ...why };
2503
+ };
2504
+ return { of, cwd, pane: paneAnswer, removed };
2505
+ }
2506
+ /** What a check says when `names`, which it read, were not all the pane's: that the pane's
2507
+ * environment is not established and why, and what it read instead, name by name (the launch
2508
+ * configuration's value when it sets one, else this process's). null when every one was established. */
2509
+ export function unestablishedNote(launchEnv, names) {
2510
+ const answers = names.map((name) => launchEnv.of(name));
2511
+ const why = answers.find((a) => a.unestablished)?.unestablished;
2512
+ if (!why) return null;
2513
+ return `the pane's environment is not established${why}; read instead: ${answers.map((a) => `${a.source}${a.absent ? " (not set)" : ""}`).join(", ")}`;
2514
+ }
2515
+ /**
2516
+ * The pane a launch would run in, for a command that only reads (a preview, readiness, `oats
2517
+ * harness trust`): expectedPaneEnvironment's shape, and never a creation environment, so never the
2518
+ * user's login shell. For a `home` whose recorded pane a start would reuse (running, or left as a
2519
+ * shell): that pane's session on its recorded server, as the start reads it. Otherwise the session
2520
+ * a launch would open its window in (the home's recorded one; without a home, `deployment`'s
2521
+ * session default) on the OATS server, when one runs. `{ unestablished }` when none runs, when
2522
+ * this process has no tmux on its PATH to ask with, when the home's session record cannot be read,
2523
+ * and when tmux could not say whether the server runs (a refused or cut-off `list-sessions`): that
2524
+ * last one with `unread`, the failure and what has to answer, because it is no evidence that no
2525
+ * server runs.
2526
+ */
2527
+ export function previewPaneEnvironment({ home = null, meta = null, deployment = null, io } = {}) {
2528
+ let session = DEFAULT_TMUX_SESSION;
2529
+ if (home) {
2530
+ let target;
2531
+ try { ({ target } = instanceSessionTarget(home)); } catch (e) { if (!isKernelCode(e?.code)) throw e; return HOME_SESSION_UNREAD; }
2532
+ if (target) {
2533
+ let state = null;
2534
+ 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 */ }
2535
+ if (state?.paneId && (state.present || state.state === "stopped")) return paneEnvironment(target.socket, target.session, io, home);
2536
+ }
2537
+ session = target?.session || meta?.tmux?.session || DEFAULT_TMUX_SESSION;
2538
+ } else if (deployment) {
2539
+ try { session = sessionDefaults(deployment).tmuxSession; } catch (e) { if (!isKernelCode(e?.code)) throw e; }
2540
+ }
2541
+ if (!io?.exec && !which("tmux")) return NO_TMUX;
2542
+ let found;
2543
+ try { found = oatsTmuxSessionSocket(session, io); }
2544
+ 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\`` }; }
2545
+ return expectedPaneEnvironment(found, session, io, home ?? undefined);
2546
+ }
2547
+ /** The one answer (launchEnvironment) for such a command: what the launch configuration sets
2548
+ * (`configEnv`), else what the launch removes (`removed`), else the pane previewPaneEnvironment
2549
+ * reads, read only when a name needs it. */
2550
+ export function previewLaunchEnvironment({ configEnv, configName, removed = [], env = process.env, home = null, meta = null, deployment = null, io } = {}) {
2551
+ return launchEnvironment({ configEnv, configName, removed, env, pane: () => previewPaneEnvironment({ home, meta, deployment, io }), cwd: home ?? undefined });
2552
+ }
2553
+ /** The PATH a launch's harness is looked up on, from the one answer (launchEnvironment): a PATH set
2554
+ * in the launch configuration is what the pane's command line applies, so the lookup uses it;
2555
+ * otherwise the pane's own. A declared absolute or relative executable is never looked up
2556
+ * (resolveLaunchExecutable). → `{ path, source, cwd }`, or `{ source, problem }` when the pane's PATH
2557
+ * cannot be established. undefined: no prediction is made (or a reference is not set, which its own
2558
+ * check refuses), and the lookup uses this process's PATH; the launch looks again on the session it
2559
+ * gets, and a preview says so (unestablishedNote). */
2560
+ function launchLookup(launchEnv) {
2561
+ const answer = launchEnv.of("PATH");
2562
+ if (answer.unestablished || answer.unresolved) return undefined;
2563
+ return answer.problem ? { source: answer.source, problem: answer.problem } : { path: answer.value, source: answer.source, cwd: launchEnv.cwd };
2411
2564
  }
2412
2565
  /**
2413
2566
  * Make sure `session` exists on the OATS server and return that server's absolute socket: the one
@@ -2494,10 +2647,13 @@ function oatsTmuxWindows(session) {
2494
2647
  try { return tmuxOatsServer(["list-windows", "-t", `=${session}`, "-F", "#{window_name}"]).split("\n").filter(Boolean); }
2495
2648
  catch { return []; }
2496
2649
  }
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}"`;
2650
+ /** The harness's window command: no COLORFGBG in the pane, and none of the names the launch
2651
+ * removes (`removed`: removedLaunchEnv, each a portable name), whatever the server's global or the
2652
+ * session's environment holds; the command's own prefix then sets what the launch sets. tmux runs
2653
+ * the command with the server's `default-shell -c` (the user's shell: sh, bash and zsh all take
2654
+ * `unset NAME…;`), and the fallback shell it execs inherits the result. Never persisted: the
2655
+ * recorded command (meta.command) is the launch command alone. */
2656
+ const paneCommand = (command, removed = []) => `unset ${["COLORFGBG", ...removed].join(" ")}; ${command}; exec "\${SHELL:-/bin/zsh}"`;
2501
2657
  /** The sizing options on one window, each best effort: this command's failure is ignored, nothing is
2502
2658
  * retried elsewhere and nothing global is written. */
2503
2659
  function sizeWindow(socket, windowId, io) {
@@ -2636,14 +2792,26 @@ export function requirementHarness(row) {
2636
2792
  return Object.hasOwn(row, "harness") ? row.harness : row.runtime;
2637
2793
  }
2638
2794
  function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {}) {
2639
- const probeEnv = env || process.env;
2795
+ // The probe's environment is the launch's (launchEffectiveEnv: the pane's PATH, HOME and
2796
+ // selectors, never this process's in their place), given as it is or as a function called at the
2797
+ // first requirement that applies: a launch with none reads nothing of its pane, and one whose
2798
+ // pane cannot be read is refused there (E_RUNTIME_ENDPOINT_UNKNOWN), before any probe. The
2799
+ // function may carry `note` (probeEnvironment): what the probe read in place of a pane's
2800
+ // environment that is not established, which a refusal for a missing package then says; and
2801
+ // `executable`, the program the launch's lookup selected, which the probe runs.
2802
+ let probeEnv;
2640
2803
  const found = [];
2641
2804
  const problems = [];
2642
2805
  // The session launches with the SELECTED executable (a configuration's,
2643
2806
  // the host's harness default included), so probing another binary would inspect a different
2644
2807
  // 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.
2808
+ // manager's controlled list subcommand; no launch argument is added to it. A harness's own
2809
+ // name is run as the launch's lookup resolved it (`selected`), never looked up a second time by
2810
+ // the probe's exec: this process's working directory is not the pane's, so a relative entry of
2811
+ // the pane's PATH would name another program there. The remedy keeps the name as declared.
2646
2812
  const probeOpts = { context: contextDir, ...(bin ? { bin } : {}) };
2813
+ const selected = typeof env === "function" ? env.executable : undefined;
2814
+ const runOpts = bin || !selected ? probeOpts : { ...probeOpts, bin: selected };
2647
2815
  for (const cap of resolved.capabilities || []) {
2648
2816
  for (const raw of cap.manifest?.requires || []) {
2649
2817
  if (!raw || typeof raw !== "object") continue;
@@ -2657,14 +2825,18 @@ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {})
2657
2825
  const spec = raw.package;
2658
2826
  if (!safeHarnessPackageSpec(spec, harness)) { problems.push(`${cap.id}: ${harness} package spec is not a plain source token (${JSON.stringify(spec)})`); continue; }
2659
2827
  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);
2828
+ probeEnv ??= typeof env === "function" ? env() : env;
2829
+ const status = harnessPackageStatus(harness, spec, probeEnv, runOpts);
2661
2830
  const mgr = HARNESS_PACKAGE_MANAGERS[harness];
2662
2831
  const stepList = mgr?.steps ? mgr.steps(spec, raw, probeOpts) : [mgr?.argv(spec, raw, probeOpts) || []];
2663
2832
  // Keep the remedy in the same resource directory and selected wrapper as
2664
2833
  // the probe; quote argv, never turn a path or package selector into shell code.
2834
+ // It starts with the selector the launch will read, as the probe's environment has it (the
2835
+ // pane's, never this process's), so that running it fixes the account that starts: Claude's
2836
+ // only when the launch has one, pi's folder always (its default is under the launch's HOME).
2665
2837
  // Pi expands ~ against the launch HOME; relative selectors are anchored
2666
2838
  // to the probe cwd before the remedy changes to contextDir.
2667
- const piResourceDir = harness === "pi" ? piAgentDir(probeEnv).replace(/^~(?=$|\/)/, () => probeEnv.HOME || homedir()) : undefined;
2839
+ const piResourceDir = harness === "pi" ? piAgentDir(probeEnv).replace(/^~(?=$|\/)/, () => probeEnv.HOME) : undefined;
2668
2840
  const resourceEnv = harness === "pi" ? `PI_CODING_AGENT_DIR=${shq(resolve(piResourceDir))} `
2669
2841
  : harness === "claude" && probeEnv.CLAUDE_CONFIG_DIR ? `CLAUDE_CONFIG_DIR=${shq(resolve(probeEnv.CLAUDE_CONFIG_DIR))} ` : "";
2670
2842
  const direct = stepList.filter((a) => a.length).map((a) => resourceEnv + [bin || a[0], ...a.slice(1)].map(shq).join(" ")).join(" && ");
@@ -2707,7 +2879,8 @@ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {})
2707
2879
  }
2708
2880
  }
2709
2881
  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")}`);
2882
+ const readInstead = typeof env === "function" ? env.note?.() : null;
2883
+ 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
2884
  }
2712
2885
  const seen = new Set();
2713
2886
  return found.filter((x) => (seen.has(x.identity) ? false : seen.add(x.identity))).sort((a, b) => a.identity.localeCompare(b.identity));
@@ -3063,20 +3236,42 @@ function deploymentOfHome(home, meta) {
3063
3236
  }
3064
3237
  }
3065
3238
  /** 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 }) {
3239
+ * launch itself will read: the one its selector names, else the default one under its HOME, both
3240
+ * from the one answer (`launch`: launchEnvironment), never from this process. `trustHome` — the
3241
+ * codex launch trusts the home, because that file trusts its deployment root or an ancestor —
3242
+ * `covered`, the `file` read and the warning when folder trust is not established there. `file`
3243
+ * is null with a `problem` when the launch configuration does not resolve it (`configEnv`, its
3244
+ * references read from `env`), and with `unreadable` when the pane's environment could not be
3245
+ * read: the check then warns that the file could not be established and says nothing about
3246
+ * trust, and codex's home is not trusted by a file nobody read. `note`: what was read in place of
3247
+ * a pane's environment that is not established (a readiness read with no server, a spawn that
3248
+ * launches nothing): the file read is then this process's and not known to be the launch's. The
3249
+ * warning says it, in place of where the file comes from, and readiness says it of a file that
3250
+ * does establish trust as well. A
3251
+ * codex launch under yolo trusts its home whatever a file says, so nothing of it rests on the
3252
+ * file: it carries no `note` and no `unreadable`. */
3253
+ export function launchFolderTrust({ harness, home, meta, yolo, launch, env = process.env, configEnv = {}, launchConfig = null }) {
3071
3254
  if (harness !== "codex" && harness !== "claude") return { trustHome: false, covered: false, file: null, warning: null };
3072
3255
  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 }) };
3256
+ const variable = CONFIG_DIR_VAR[harness];
3257
+ // Without a file, only codex under yolo is covered: its launch trusts the home whatever a file says.
3258
+ const yoloCovers = harness === "codex" && yolo === true;
3259
+ const unknown = (facts) => { const covered = yoloCovers; return { trustHome: false, covered, file: null, ...facts, warning: harnessTrustWarning({ harness, root, file: null, covered, ...facts }) }; };
3260
+ const unresolved = launchConfigFolder(variable, configEnv, env)?.problem;
3261
+ if (unresolved) return unknown({ problem: `launch configuration ${launchConfig || "(recorded)"}: ${unresolved}` });
3262
+ const selector = launch.of(variable);
3263
+ // The default file is under HOME: read only when the launch has no selector.
3264
+ const base = selector.absent ? launch.of("HOME") : null;
3265
+ const failed = selector.problem ? selector : base?.problem ? base : null;
3266
+ if (failed) return unknown(yoloCovers ? {} : { unreadable: `${failed.problem}${failed.remedy ? `: ${failed.remedy}` : ""}` });
3267
+ const read = base ? { HOME: base.value } : { [variable]: selector.value };
3268
+ const file = harnessConfigFile(harness, read);
3269
+ const trustHome = harness === "codex" && codexTrustsRoot(root, { env: read });
3270
+ const covered = harness === "codex" ? trustHome || yolo === true : claudeTrusts(home, { env: read });
3271
+ const names = base ? [variable, "HOME"] : [variable];
3272
+ const note = yoloCovers ? null : unestablishedNote(launch, names);
3273
+ const from = note ?? (base ? `under ${base.source}` : selector.source);
3274
+ return { trustHome, covered, file, ...(note ? { note } : {}), warning: harnessTrustWarning({ harness, root, file, from, covered }) };
3080
3275
  }
3081
3276
 
3082
3277
  /** The harness command line of a recipe. With no configuration the bytes
@@ -3186,8 +3381,11 @@ function requirementsWithArgsMessage(harness, providers, config) {
3186
3381
  * (OATS_LAUNCH_PREVIEW=1); the others run here for real when a start plans,
3187
3382
  * and not at all for a preview. A home
3188
3383
  * 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 }) {
3384
+ * E_LAUNCH_LEGACY, re-spawn it from the deployment. `pane`: the environment the launch's pane is
3385
+ * expected to have (paneEnvironment's shape, or a function giving it, called only when a check
3386
+ * needs a name the launch itself does not set); every check here reads it through the one answer
3387
+ * (launchEnvironment), and says so when it is not established. */
3388
+ export function planLaunch({ home, instance, meta, contextDir, agentLike, selection = {}, launchConfigs, resolvedCfg, env = process.env, preview = false, assertRoots, reselect = null, pane }) {
3191
3389
  assertRoots?.();
3192
3390
  const problems = [];
3193
3391
  const fail = (check, code, detail) => { if (!preview) throw oatsError(code, detail); problems.push({ check, ok: false, detail, code }); };
@@ -3213,12 +3411,16 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3213
3411
  // the default no longer decides (a bare --launch-config none, another harness).
3214
3412
  const frozenYolo = frozen && !(frozen.launchConfigDefault === true && !config?.frozen) ? frozen.yolo : undefined;
3215
3413
  const yolo = resolveYolo(selection.yolo ?? chosen.configuredYolo ?? (frozen ? frozenYolo : agentLike?.yolo ?? resolvedCfg?.yolo));
3414
+ // Where this launch will run (launchEnvironment): what its configuration sets, else its pane's.
3415
+ const launchEnv = launchEnvironment({ configEnv: config?.env, configName: config?.name, env, pane, cwd: home });
3216
3416
  // 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
3417
+ // look it up (launchLookup: the configuration's PATH, else the pane's, the start's expected
3218
3418
  // session or server PATH; a start looks again on the session it gets).
3219
3419
  const executable = config?.frozen
3220
3420
  ? { 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) });
3421
+ : resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir, lookup: config?.executable?.includes("/") ? undefined : launchLookup(launchEnv) });
3422
+ // A bare name looked up on this process's PATH because the pane's is not established: said.
3423
+ const lookupNote = !config?.frozen && !config?.executable?.includes("/") && !executable.lookup ? unestablishedNote(launchEnv, ["PATH"]) : null;
3222
3424
  const notOnPane = !executable.path && executable.lookup ? executableNotOnPanePath(executable, { harness, config, from: launchChoice?.from, at: launchChoice?.at }) : null;
3223
3425
  if (notOnPane) {
3224
3426
  if (!preview) throw notOnPane;
@@ -3229,7 +3431,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3229
3431
  problems.push({ check: "executable", ok: false, detail: e.message, code: e.code });
3230
3432
  }
3231
3433
  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})` });
3434
+ 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
3435
  // Capability contributions: recorded at spawn with provenance; a harness
3234
3436
  // switch needs the new harness's launch args from the same capabilities.
3235
3437
  let hooks = { launch: {}, env: {}, contributions: [], pending: true };
@@ -3256,6 +3458,11 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3256
3458
  } else problems.push({ check: "capabilities", ok: true, detail: "decided by the capabilities' spawn hooks" });
3257
3459
  // A configuration may not override environment a capability owns.
3258
3460
  const configEnv = config?.env || {};
3461
+ // What this launch removes (removedLaunchEnv): the names its providers declare that their payload and
3462
+ // the configuration leave out. Its checks read them as removed and its window command unsets them.
3463
+ // A plan with no recorded launch (meta null) has no payload yet: the spawn decides it.
3464
+ const declaredEnv = frozen ? homeDeclaredLaunchEnv(meta, frozen, launchManifestDir(home, meta) ? capabilityManifests(home) : {}) : [];
3465
+ const removedEnv = removedLaunchEnv({ declared: declaredEnv, hooksEnv: hooks.env, configEnv });
3259
3466
  const owned = Object.keys(configEnv).filter((n) => Object.hasOwn(hooks.env, n));
3260
3467
  if (owned.length) {
3261
3468
  const owner = (n) => hooks.contributions.find((c) => (c.env || []).includes(n))?.capability || "a capability";
@@ -3271,7 +3478,9 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3271
3478
  // probed under the launch's EFFECTIVE environment with the selected
3272
3479
  // executable, only when some requirement is declared for this harness and
3273
3480
  // every reference resolved. Configuration arguments cannot be applied to a
3274
- // package probe (it must never start a conversation), which is stated.
3481
+ // package probe (it must never start a conversation), which is stated. A pane
3482
+ // whose environment cannot be read is refused with its own code, and one that
3483
+ // is not established is probed with what the item names.
3275
3484
  if (executable.path && !missing.length && !owned.length) {
3276
3485
  const providers = frozen
3277
3486
  ? 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 +3492,17 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3283
3492
  // reported verified: refused, truthfully, with the way out.
3284
3493
  fail("harness-packages", "E_LAUNCH_PROBE_UNSUPPORTED", requirementsWithArgsMessage(harness, providers, config));
3285
3494
  } else if (declared) {
3495
+ // The check fails with the code the gate refused with, never another name for it (#1047):
3496
+ // E_HARNESS_RESOURCE_MISSING, or E_RUNTIME_ENDPOINT_UNKNOWN for a pane whose environment it
3497
+ // cannot read (#993). Anything else it throws is a fault, not a missing package:
3498
+ // thrown on, as the capabilities check above does, for the command's door to answer.
3286
3499
  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); }
3500
+ // The probe's answer also holds what the capabilities set, over the same read of the pane.
3501
+ 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 });
3502
+ 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) });
3503
+ const probeNote = unestablishedNote(probeLaunch, probeNames(harness));
3504
+ 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}` : ""}` });
3505
+ } catch (e) { if (!["E_HARNESS_RESOURCE_MISSING", "E_RUNTIME_ENDPOINT_UNKNOWN"].includes(e?.code)) throw e; fail("harness-packages", e.code, e.message); }
3290
3506
  } else problems.push({ check: "harness-packages", ok: true, detail: "no harness package requirement declared for this harness; nothing probed" });
3291
3507
  }
3292
3508
  const recipe = {
@@ -3297,26 +3513,84 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3297
3513
  ...(frozen?.legacy ? { legacy: { ...frozen.legacy, ...(hooks.refreshed?.length ? { replacedBy: hooks.refreshed } : {}) } } : {}),
3298
3514
  };
3299
3515
  const inst = instance || meta?.instance || basename(home);
3300
- const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, env, configEnv, launchConfig: config?.name });
3516
+ const trustLaunch = removedEnv.length ? launchEnvironment({ configEnv: config?.env, configName: config?.name, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) : launchEnv;
3517
+ const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, launch: trustLaunch, env, configEnv, launchConfig: config?.name });
3301
3518
  const command = renderLaunchRecipe(recipe, { home, instance: inst, trustHome });
3302
3519
  const selectionSource = frozen ? (config?.frozen || (!config && !selection.launchConfig && !selection.harness) ? "frozen" : "config") : "config";
3303
3520
  // A preview states what the start will do; the start states it in its own output.
3304
3521
  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 };
3522
+ 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 } : {}) };
3523
+ }
3524
+ /** The names a package probe of `harness` depends on: where its program is found and runs, the
3525
+ * home directory, and that harness's own selector. */
3526
+ const probeNames = (harness) => ["PATH", "HOME", ...(HARNESS_FOLDER_VAR[harness] ? [HARNESS_FOLDER_VAR[harness]] : [])];
3527
+ /** The package probe's environment as verifyHarnessPackages takes it: `make`, called at the first
3528
+ * requirement that applies, carrying `note`: what the probe read in place of a pane's environment
3529
+ * that is not established (unestablishedNote; null when every name is the pane's), and
3530
+ * `executable`: the absolute path the launch's lookup selected, which is the program the probe runs. */
3531
+ const probeEnvironment = (make, launchEnv, harness, executable) => Object.assign(make, { note: () => unestablishedNote(launchEnv, probeNames(harness)), executable });
3532
+ /** A PATH as a pane whose working directory is `cwd` reads it, for a process that runs elsewhere:
3533
+ * a relative entry, and an empty one, are `cwd` (lookupOnPath). Unchanged without a `cwd`. */
3534
+ const panePathFrom = (path, cwd) => cwd ? path.split(":").map((dir) => resolve(cwd, dir || ".")).join(":") : path;
3535
+ /** The environment a planned launch is judged under by what runs a program for it (the package
3536
+ * probe): this process's `base` without the names the launch removes (`launch.removed`:
3537
+ * removedLaunchEnv), the capabilities' validated env, the configuration's literals and
3538
+ * its references resolved from the BASE (never from the prefix beside them); and, for
3539
+ * PANE_ENV_NAMES, the one answer (`launch`: launchEnvironment) in place of this process's values:
3540
+ * each is set as the launch will have it, or removed when the launch will have none. So a probe
3541
+ * selects the account the launch will, and runs what its pane would. A name the probe depends on
3542
+ * (PATH, HOME, `harness`'s own selector) that cannot be established is refused
3543
+ * (E_RUNTIME_ENDPOINT_UNKNOWN: which name, where it was read, what makes it readable), never
3544
+ * answered from this process; another harness's selector in that state is left out. Every other
3545
+ * name stays this process's: only these five are read from the pane. The pane's PATH is given
3546
+ * with its relative entries resolved against the pane's working directory (panePathFrom). */
3547
+ export function launchEffectiveEnv({ base = process.env, hooksEnv = {}, configEnv = {}, launch, harness } = {}) {
3548
+ const out = { ...base };
3549
+ // What the launch removes (launch.removed: removedLaunchEnv) is not this process's either.
3550
+ for (const name of launch?.removed || []) delete out[name];
3551
+ Object.assign(out, hooksEnv);
3314
3552
  for (const [name, v] of Object.entries(configEnv || {})) {
3315
3553
  if (typeof v === "string") out[name] = v;
3316
3554
  else if (v && typeof v === "object" && v.fromEnv && base[v.fromEnv] !== undefined) out[name] = base[v.fromEnv];
3317
3555
  }
3556
+ for (const name of PANE_ENV_NAMES) {
3557
+ const answer = launch.of(name);
3558
+ if (answer.unresolved) continue; // a reference that is not set: the caller's own check refuses it
3559
+ // The pane's PATH, as the pane reads it: the probe and what it starts run in this process's
3560
+ // working directory, where a relative entry would name another directory than the pane's.
3561
+ if (!answer.problem) { if (answer.absent) delete out[name]; else out[name] = name === "PATH" && !answer.unestablished ? panePathFrom(answer.value, launch.cwd) : answer.value; continue; }
3562
+ 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}` : ""}`);
3563
+ delete out[name];
3564
+ }
3318
3565
  return out;
3319
3566
  }
3567
+ /** A name a launch may remove: one a manifest could declare (the portable grammar, no core,
3568
+ * OATS_, PI_AGENT_ or process bootstrap name). A recorded list (instance.json) is read through it,
3569
+ * so no other name ever reaches the window's `unset`. */
3570
+ const removableLaunchEnvName = (name) => typeof name === "string" && PORTABLE_ENV_NAME_RE.test(name) && !CORE_LAUNCH_ENV.has(name) && !name.startsWith("OATS_") && !name.startsWith("PI_AGENT_")
3571
+ && !PROCESS_BOOTSTRAP_ENV.has(name) && !PROCESS_BOOTSTRAP_PREFIXES.some((reserved) => name.startsWith(reserved));
3572
+ /** The environment names `capabilities` declare (each one's manifest `environment`), united and sorted. */
3573
+ export const declaredLaunchEnv = (capabilities) => [...new Set((capabilities || []).flatMap((c) => Array.isArray(c?.environment) ? c.environment : []))].filter(removableLaunchEnvName).sort();
3574
+ /**
3575
+ * The names a launch removes from the environment its harness starts with (awebai/oats#1123): every
3576
+ * name a provider composed into the launch declares (`declared`: declaredLaunchEnv) that neither the
3577
+ * providers' merged payload (`hooksEnv`) nor the launch configuration (`configEnv`, the operator's
3578
+ * explicit setting on the launch's own command) sets. A declared name is its provider's to decide:
3579
+ * left out of the payload (a hook that answered without it, that failed, or none), the launch has
3580
+ * none, never a value the pane would inherit (the tmux server's or session's environment, a login
3581
+ * shell's, the Desktop's). Sorted. The window command unsets them (paneCommand), and the checks of
3582
+ * the launch read them as removed (launchEnvironment `removed`).
3583
+ */
3584
+ export function removedLaunchEnv({ declared = [], hooksEnv = {}, configEnv = {} } = {}) {
3585
+ return [...new Set(declared)].filter((name) => removableLaunchEnvName(name) && !Object.hasOwn(hooksEnv || {}, name) && !Object.hasOwn(configEnv || {}, name)).sort();
3586
+ }
3587
+ /** The names declared by the providers a home's launch composes (capturedProviders, as a start's
3588
+ * launch hooks run them): each one's manifest in the home's module copy (`manifests`:
3589
+ * capabilityManifests of the home), else the environment its spawn recorded (capabilityRuntime). */
3590
+ export function homeDeclaredLaunchEnv(meta, frozen, manifests = {}) {
3591
+ const recorded = new Map((Array.isArray(meta?.capabilityRuntime) ? meta.capabilityRuntime : []).map((b) => [b?.id, b]));
3592
+ return declaredLaunchEnv(capturedProviders(meta, frozen).map((p) => (Object.hasOwn(manifests || {}, p.id) ? manifests[p.id] : undefined) ?? recorded.get(p.id)));
3593
+ }
3320
3594
  /** argv (after the executable) and environment names of a rendered command,
3321
3595
  * from the parser: what a GUI shows, never the TASK body. */
3322
3596
  export function describeLaunchCommand(command) {
@@ -3782,11 +4056,16 @@ function* spawnBody(root, agent, o = {}) {
3782
4056
  // reconciliation, so this spawn-time check is the authoritative one.
3783
4057
 
3784
4058
  // Prerequisites must fail before creating a home, worktree, or identity.
4059
+ // Where this launch will run (launchEnvironment): what its configuration sets, else its pane's.
4060
+ // `expectedEnv` is the preflight's answer, over the pane this plan expects; the launch reads the
4061
+ // session it actually gets (below). A spawn that launches nothing has no pane to read.
4062
+ const launchEnvOn = (pane, removed = []) => launchEnvironment({ configEnv: launchConfig?.env, configName: launchConfig?.name, removed, env: process.env, pane, cwd: home });
4063
+ const expectedEnv = launchEnvOn(launch ? () => expectedPaneEnvironment(tmuxSessionPlan, session, undefined, home) : NO_LAUNCH);
3785
4064
  // A launched harness is looked up where its pane will look it up (launchLookup): this is the
3786
4065
  // preflight against the expected PATH; the launch looks again on the session it gets. Without a
3787
4066
  // 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)) });
4067
+ const lookupFor = (launchEnv) => launch && !launchConfig?.executable?.includes("/") ? launchLookup(launchEnv) : undefined;
4068
+ const executable = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, contextDir: repoAbs, lookup: lookupFor(expectedEnv) });
3790
4069
  if (!executable.path && executable.lookup) { previewPreflightBudget = null; throw executableNotOnPanePath(executable, { harness, config: launchConfig, from: launchChoice.from, at: launchChoice.at }); }
3791
4070
  // No executable for the chosen harness (none declared by a configuration): E_HARNESS_UNAVAILABLE names the
3792
4071
  // layer that chose it and the fix. Never a fallback to another harness.
@@ -3798,11 +4077,30 @@ function* spawnBody(root, agent, o = {}) {
3798
4077
  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
4078
  // A configuration's executable answers the package probe (without one the
3800
4079
  // 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.
4080
+ // under the environment the launch will have (launchEffectiveEnv: the
4081
+ // configuration's, and its pane's PATH, HOME and selectors, never this
4082
+ // process's in their place); the capabilities' own env is not known before
4083
+ // their spawn hooks run, which happens after the home exists
4084
+ // (awebai/oats#1041). `probed` keeps what the gate judged (null: no
4085
+ // requirement applied, so nothing was probed and nothing of the pane was
4086
+ // read), to compare with the pane the spawn actually gets.
3804
4087
  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 || {} }) });
4088
+ let probed = null;
4089
+ const recordedHarnessPackages = (found) => found.map((x) => ({ capability: x.capability, harness: x.harness, package: x.package, dir: x.dir, filtered: x.filtered, loadedBy: "harness-discovery" }));
4090
+ const probeEnvOn = (launchEnv, selected = bin) => probeEnvironment(() => (probed = launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {}, launch: launchEnv, harness })), launchEnv, harness, selected);
4091
+ const harnessPackages = verifyHarnessPackages(harness, resolvedCfg, repoAbs, { ...(launchConfig?.executable ? { bin } : {}), env: probeEnvOn(expectedEnv) });
4092
+ // What a preview of a launch says when no pane's environment is established (no server runs, or
4093
+ // it could not be read): the checks that read this process's values in its place, in one line
4094
+ // that names every name read that way, PATH among them: the lookup of a bare name and the package
4095
+ // probe. A spawn that launches nothing says nothing here: its checks read this process by design,
4096
+ // a start checks again on its own session, and it says whose values it read only where it already
4097
+ // says something (the folder-trust warning, a refusal of the package gate).
4098
+ const previewReadWarning = () => {
4099
+ if (!launch) return null;
4100
+ const checks = [...(!launchConfig?.executable?.includes("/") && !executable.lookup ? [["the harness lookup", ["PATH"]]] : []), ...(probed ? [["the harness package check", probeNames(harness)]] : [])];
4101
+ const note = unestablishedNote(expectedEnv, [...new Set(checks.flatMap(([, names]) => names))]);
4102
+ return note ? `${checks.map(([what]) => what).join(", ")}: ${note}` : null;
4103
+ };
3806
4104
  if (o.preview === true) { preflight = { status: previewPreflightBudget?.exhausted ? "timeout" : "complete", budgetMs: preflightBudgetMs, elapsedMs: Date.now() - preflightStarted }; previewPreflightBudget = null; }
3807
4105
  const task = o.task ?? (o.taskFile ? readFileSync(o.taskFile, "utf8") : "");
3808
4106
 
@@ -3871,7 +4169,7 @@ function* spawnBody(root, agent, o = {}) {
3871
4169
  const preparedSettingsOrigins = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloadOrigins?.[m.name] ?? {})]));
3872
4170
  // The preview's warnings are strings: the launchPromptAnswers notice, then what a module declares and this kernel ignores.
3873
4171
  // 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))];
4172
+ const previewWarnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution)), ...[previewReadWarning()].filter(Boolean)];
3875
4173
  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
4174
  return deliver({
3877
4175
  // Team model v2: the soul's teams here (unmapped rows included) and its default — the choice a
@@ -4535,8 +4833,16 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4535
4833
  prompt: LAUNCH_PROMPT, kernelBin: shimTarget,
4536
4834
  };
4537
4835
  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);
4836
+ // What this launch removes (removedLaunchEnv): the names the composed capabilities declare that
4837
+ // their spawn hooks' payload and the configuration leave out. Folder trust and the checks on the
4838
+ // pane the spawn gets read them as removed; the window command unsets them.
4839
+ const removedEnv = removedLaunchEnv({ declared: declaredLaunchEnv(resolvedCfg.capabilities), hooksEnv: hookRes.env, configEnv: recipe.env });
4840
+ // Folder trust, read on the pane this plan expects: the command is rendered from it. A launch
4841
+ // reads it again on the session it gets, and warns from that (below); a spawn that launches
4842
+ // nothing warns from this, and the warning says whose values were read.
4843
+ const folderTrustOn = (launchEnv) => launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo, launch: launchEnv, configEnv: launchConfig?.env, launchConfig: launchConfig?.name });
4844
+ let folderTrust = folderTrustOn(launchEnvOn(expectedEnv.pane, removedEnv));
4845
+ if (!launch && folderTrust.warning) warnings.push(folderTrust.warning);
4540
4846
  let cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
4541
4847
 
4542
4848
  // Module skills as materialize landed them (flat, .agents/skills/<skill>/),
@@ -4587,7 +4893,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4587
4893
  // package's resources. A non-empty filter is a deliberate choice whose
4588
4894
  // glob semantics belong to the harness, so it is auditable here rather
4589
4895
  // 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" })),
4896
+ harnessPackages: recordedHarnessPackages(harnessPackages),
4591
4897
  // What this instance ACTUALLY sees beyond the OATS-composed set. Recorded
4592
4898
  // so the deviation from strict composition is auditable instead of
4593
4899
  // implied — the honest contract, not an aspiration.
@@ -4643,12 +4949,14 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4643
4949
  // The session on the OATS server, then everything on the one socket that answered: the collision
4644
4950
  // check, the records, the window and (in compensateSpawn) its removal.
4645
4951
  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.
4952
+ // The environment this window's pane will actually start with, whoever created the session and
4953
+ // with whatever environment (a race lost to another creator, a session that overrides a name):
4954
+ // one read of it answers the three checks below, each of which reads it only when it has to.
4955
+ const actualEnv = launchEnvOn(paneEnvironment(socket, session, undefined, home), removedEnv);
4956
+ // The harness looked up again on that PATH. Not there: refused, and the spawn is compensated.
4957
+ // Found elsewhere than the preflight found it: the launch runs that one.
4650
4958
  if (executable.lookup) {
4651
- const actual = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, lookup: lookupFor(() => panePath(socket, session, undefined, home)) });
4959
+ const actual = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, lookup: lookupFor(actualEnv) });
4652
4960
  if (!actual.path) throw executableNotOnPanePath(actual, { harness, config: launchConfig, from: launchChoice.from, at: launchChoice.at });
4653
4961
  const bad = checkLaunchExecutable(actual.path);
4654
4962
  if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig?.name || "(harness default)"}: ${bad}`);
@@ -4658,6 +4966,27 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4658
4966
  executionCommand = nativeRecordCommand(cmdline, home, harness);
4659
4967
  }
4660
4968
  }
4969
+ // The package gate judged the pane this spawn expected (`probed`). When the pane it got differs
4970
+ // in a name the probe depends on, or the lookup above found the harness elsewhere there, the gate
4971
+ // judges again, on that one and with that program: a pane that cannot be
4972
+ // read (E_RUNTIME_ENDPOINT_UNKNOWN) or whose account lacks a package
4973
+ // (E_HARNESS_RESOURCE_MISSING) is refused, and the spawn is compensated as for the lookup
4974
+ // above. Equal, as it is unless another creator won the server's creation: nothing more is probed.
4975
+ if (probed) {
4976
+ const judged = probed, actual = probeEnvOn(actualEnv)();
4977
+ if (recipe.executable !== bin || probeNames(harness).some((name) => judged[name] !== actual[name])) {
4978
+ meta.composition.materialized.harnessPackages = recordedHarnessPackages(verifyHarnessPackages(harness, resolvedCfg, repoAbs, { ...(launchConfig?.executable ? { bin: recipe.executable } : {}), env: probeEnvironment(() => actual, actualEnv, harness, recipe.executable) }));
4979
+ }
4980
+ }
4981
+ // Folder trust on the same pane: the warning is about the file this launch reads, and codex's
4982
+ // trust of the home follows that file.
4983
+ const actualTrust = folderTrustOn(actualEnv);
4984
+ if (actualTrust.warning) spawnWarnings.push(actualTrust.warning);
4985
+ if (actualTrust.trustHome !== folderTrust.trustHome) {
4986
+ meta.command = cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: actualTrust.trustHome });
4987
+ executionCommand = nativeRecordCommand(cmdline, home, harness);
4988
+ }
4989
+ folderTrust = actualTrust;
4661
4990
  let present;
4662
4991
  try { present = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"]).split("\n").filter(Boolean); }
4663
4992
  catch (e) { throw new Error(`could not list the windows of tmux session ${session} on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`); }
@@ -4675,7 +5004,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4675
5004
  clearSpawnInProgressMarker();
4676
5005
  // Wrap the command so the window drops into an interactive shell when the
4677
5006
  // agent exits (e.g. Ctrl-C) instead of tmux killing the window.
4678
- const windowCmd = paneCommand(executionCommand);
5007
+ const windowCmd = paneCommand(executionCommand, removedEnv);
4679
5008
  const paneEnvFlags = launchEnvRefs(recipe, process.env).flatMap((r) => ["-e", `${r.name}=${r.value}`]);
4680
5009
  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
5010
  // Only a launch that engages the confirmation needs lineage committed before
@@ -6155,22 +6484,26 @@ function missingSessionReceipt(home) {
6155
6484
  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
6485
  }
6157
6486
 
6158
- /** Session control uses the independent endpoint receipt. */
6487
+ /** Why a file could not be read or parsed, in the system's or the parser's words, without the path
6488
+ * the sentence already names: `EACCES: permission denied`; a missing file is "it is missing". */
6489
+ const unreadableBecause = (e) => e?.code === "ENOENT" ? "it is missing" : String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, "");
6490
+
6491
+ /** Session control uses the independent endpoint receipt. The receipt and the record are read
6492
+ * apart, so that a failure names the file that failed (#1092): one `catch` over both cannot know. */
6159
6493
  function instanceSessionTarget(home) {
6160
6494
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session needs an absolute instance home");
6161
6495
  home = realPathOrNearest(home);
6162
6496
  refuseHerdrHome(home);
6163
- const receiptPath = findRetirementBaseline(home);
6497
+ const receiptPath = findRetirementBaseline(home), recordPath = join(home, "instance.json");
6164
6498
  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) {
6499
+ try { baseline = JSON.parse(readFileSync(receiptPath, "utf8")); } catch (e) {
6169
6500
  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}`);
6501
+ throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home} at ${receiptPath}: ${unreadableBecause(e)}`);
6171
6502
  }
6503
+ try { meta = JSON.parse(readFileSync(recordPath, "utf8")); }
6504
+ catch (e) { throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: ${unreadableBecause(e)}`); }
6172
6505
  // 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`);
6506
+ if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: it holds no JSON object`);
6174
6507
  const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
6175
6508
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
6176
6509
  if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
@@ -6623,19 +6956,12 @@ function tmuxOn(socket, args, io, env) {
6623
6956
  return (io?.exec || execFileSync)(tmux, ["-u", "-S", socket, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...(env ? { env } : {}) });
6624
6957
  }
6625
6958
 
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. */
6959
+ /** Write `value` as JSON at `path` through a private file beside it (`<path>.tmp-<pid>`), renamed
6960
+ * over it, by the kernel's one such writer (lib/write-through-private-file.mjs): when the write or
6961
+ * the rename fails the private file is removed and the error thrown is that failure's
6962
+ * (awebai/oats#963, #1076). */
6630
6963
  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
- }
6964
+ writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, JSON.stringify(value, null, 2) + "\n", mode);
6639
6965
  }
6640
6966
 
6641
6967
  // ---------- stopping a harness, selecting on an existing home ----------
@@ -6833,7 +7159,7 @@ export function prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, c
6833
7159
  }
6834
7160
  /** Environment that selects which configuration (account, packages) a
6835
7161
  * 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"]);
7162
+ const HARNESS_CONFIG_SELECTORS = new Set(Object.values(HARNESS_FOLDER_VAR));
6837
7163
 
6838
7164
 
6839
7165
  export function restartInstanceSession(home, o = {}) { return startInstanceSession(home, { ...o, restart: true }); }
@@ -7097,23 +7423,24 @@ export function startInstanceSession(home, o = {}) {
7097
7423
  // the launch hook re-checks joined memberships against them.
7098
7424
  const resolvedCfg = resolvedFromHome(realHome, meta, { teams: o.teams, defaultTeam: o.defaultTeam, teamsSource: o.teamsSource });
7099
7425
  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.
7426
+ // The environment the plan's checks read for this launch's pane (the harness lookup by name,
7427
+ // the package probe, folder trust): a pane the start will reuse, on its own recorded session,
7428
+ // whatever the OATS server holds; otherwise the session's or the server's when a server runs;
7429
+ // when none does, the environment this start will create the server with (read once, here,
7430
+ // for the plan and for the creation below). For a creator that may not create the server no
7431
+ // pane's environment is established: the plan's checks read this process's, and the refusal
7432
+ // comes at the creation's own place, after the start's other preflights.
7106
7433
  const pane = () => {
7107
7434
  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
7435
+ if (reusable(recorded.state)) return paneEnvironment(receipt.target.socket, receipt.target.session, o.io, realHome);
7436
+ if (recorded.error) return NO_PANE_READ; // the gate refuses below; no check decides it
7110
7437
  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; }
7438
+ if (!preview || preview.server) return expectedPaneEnvironment(preview, planSession, o.io, realHome);
7439
+ try { return expectedPaneEnvironment(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return SESSION_REFUSED; throw e; }
7113
7440
  };
7114
7441
  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 }),
7442
+ pane });
7443
+ 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
7444
  ...(plan.launchChoice ? { launchFrom: plan.launchChoice.from, launchAt: plan.launchChoice.at, launchDeclared: plan.launchChoice.declared } : {}) };
7118
7445
  // The plan ran preview-aware launch hooks as a preview: their real run, over the planned
7119
7446
  // contributions, waits for the rest of preflight.
@@ -7166,7 +7493,7 @@ export function startInstanceSession(home, o = {}) {
7166
7493
  const lookAgain = (pane) => {
7167
7494
  if (!launchPlan || launchPlan.config?.frozen || launchPlan.config?.executable?.includes("/")) return false;
7168
7495
  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) });
7496
+ 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
7497
  if (!actual.path) throw executableNotOnPanePath(actual, { harness: launchPlan.harness, config, from: launchChoice?.from, at: launchChoice?.at });
7171
7498
  const bad = checkLaunchExecutable(actual.path);
7172
7499
  if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${bad}; nothing was started`);
@@ -7175,7 +7502,7 @@ export function startInstanceSession(home, o = {}) {
7175
7502
  command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome });
7176
7503
  return true;
7177
7504
  };
7178
- lookAgain(retained ? () => panePath(target.socket, target.session, o.io, realHome) : () => expectedPanePath(tmuxSessionPlan, planSession, o.io, realHome));
7505
+ lookAgain(retained ? () => paneEnvironment(target.socket, target.session, o.io, realHome) : () => expectedPaneEnvironment(tmuxSessionPlan, planSession, o.io, realHome));
7179
7506
  // Every preflight has passed: the preview-aware launch hooks run for real
7180
7507
  // (they may register the home with their provider), before a restart's
7181
7508
  // stop, and must contribute exactly what they contributed as a preview,
@@ -7235,7 +7562,10 @@ export function startInstanceSession(home, o = {}) {
7235
7562
  let launchController;
7236
7563
  let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
7237
7564
  checkRoots();
7238
- const windowCommand = () => paneCommand(`${nativeRecordCommand(command, realHome, launchPlan?.harness || harness)}; oats_start_status=$?; printf '%s\\n' ${shq(id)} > ${shq(exitedPath)}`);
7565
+ // The names this launch removes, from the recipe it runs (a preview-aware hook's real run included).
7566
+ // A home without a recipe (an earlier kernel's) composes no providers at launch: nothing.
7567
+ const removed = launchPlan ? removedLaunchEnv({ declared: launchPlan.declaredEnv, hooksEnv: launchPlan.recipe.hooks?.env, configEnv: launchPlan.recipe.env }) : [];
7568
+ const windowCommand = () => paneCommand(`${nativeRecordCommand(command, realHome, launchPlan?.harness || harness)}; oats_start_status=$?; printf '%s\\n' ${shq(id)} > ${shq(exitedPath)}`, removed);
7239
7569
  let reused = "new";
7240
7570
  const session = target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
7241
7571
  const window = target?.window || meta.tmux?.window || meta.instance;
@@ -7272,7 +7602,7 @@ export function startInstanceSession(home, o = {}) {
7272
7602
  // on the OATS server, wherever the home was recorded: one socket from here to the record.
7273
7603
  const recordedSocket = socket ? resolve(socket) : null;
7274
7604
  socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
7275
- if (lookAgain(() => panePath(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
7605
+ if (lookAgain(() => paneEnvironment(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
7276
7606
  let names;
7277
7607
  try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
7278
7608
  catch (e) {
@@ -8537,7 +8867,7 @@ function completeRetirementRecovery({ receipt, manifest }, before, after, meta)
8537
8867
  try { owned = realpathSync(recovery) === join(realpathSync(dirname(after.home)), ".oats-retirement", "recovery", basename(recovery)); } catch { /* gone: not the owned storage */ }
8538
8868
  if (!owned) throw new Error("directory recovery storage was redirected");
8539
8869
  };
8540
- let staging, manifestStarted = false;
8870
+ let staging;
8541
8871
  try {
8542
8872
  assertOwnedStorage();
8543
8873
  // Work that is not proven unchanged is copied. So is work this recovery does
@@ -8571,14 +8901,12 @@ function completeRetirementRecovery({ receipt, manifest }, before, after, meta)
8571
8901
  const notCopied = unionNotCopied(receipt.notCopied, after.notCopied);
8572
8902
  const { notCopied: _before, ...rest } = manifest;
8573
8903
  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);
8904
+ // A failed write or rename removes its private file and throws its own error (#1076).
8905
+ writeThroughPrivateFile(manifestPath, manifestTmp, JSON.stringify({ ...rest, phase: "complete", classes, ...(notCopied.length ? { notCopied } : {}), ...(afterHooks ? { afterHooks } : {}) }, null, 2) + "\n", 0o600);
8577
8906
  const { notCopied: _was, ...kept } = receipt;
8578
8907
  return { ...kept, classes, bytes: treeBytes(recovery), ...(notCopied.length ? { notCopied } : {}), ...(afterHooks ? { afterHooks } : {}) };
8579
8908
  } catch (e) {
8580
8909
  const left = staging ? removeStaging(staging) : null;
8581
- if (manifestStarted) { try { rmSync(manifestTmp, { force: true }); } catch { /* the original error is the refusal */ } }
8582
8910
  if (unreadableHeads.has(e)) { if (left) e.message += left; throw e; }
8583
8911
  const details = e.statusDisagreement ? { home: after.home, statusDisagreement: e.statusDisagreement } : undefined;
8584
8912
  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 } : {});