@awebai/oats 0.68.0 → 0.69.1

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 (72) hide show
  1. package/bin/oats.mjs +102 -22
  2. package/docs/capabilities.md +49 -5
  3. package/docs/configuration.md +68 -2
  4. package/docs/desktop-cli-api.md +355 -12
  5. package/docs/desktop-instance-start.md +88 -3
  6. package/docs/desktop.md +147 -13
  7. package/docs/execution-targets.md +514 -62
  8. package/docs/harness-trust.md +3 -1
  9. package/docs/implementation.md +28 -11
  10. package/docs/integrations.md +1 -1
  11. package/docs/oats-local.schema.json +2 -2
  12. package/docs/official-catalog.md +4 -3
  13. package/docs/packages.md +7 -7
  14. package/docs/release-notes/v0.68.1.md +102 -0
  15. package/docs/release-notes/v0.69.0.md +658 -0
  16. package/docs/release-notes/v0.69.1.md +25 -0
  17. package/docs/servers.md +44 -5
  18. package/docs/souls-and-instances.md +11 -7
  19. package/docs/tui.md +114 -31
  20. package/docs/upgrading.md +14 -5
  21. package/docs/workspaces.md +1 -1
  22. package/lib/core.mjs +345 -89
  23. package/lib/file-pieces.mjs +49 -0
  24. package/lib/instance-events.mjs +25 -4
  25. package/lib/launch-prompt-fixtures/README.md +62 -0
  26. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  27. package/lib/launch-prompt-fixtures.mjs +49 -0
  28. package/lib/launch-prompt-resume.mjs +55 -0
  29. package/lib/login-environment.mjs +27 -9
  30. package/lib/schedule.mjs +3 -3
  31. package/lib/servers.mjs +117 -23
  32. package/lib/session-end.mjs +82 -0
  33. package/lib/session-input.mjs +43 -9
  34. package/lib/session-resume-contract.mjs +32 -0
  35. package/lib/session-resume.mjs +310 -0
  36. package/lib/session-seen.mjs +163 -0
  37. package/lib/session-viewer.mjs +147 -44
  38. package/lib/soul-composition.mjs +2 -1
  39. package/lib/start-env.mjs +110 -0
  40. package/lib/tmux-server-scope.mjs +139 -14
  41. package/lib/workspace.mjs +38 -4
  42. package/package-catalog.json +10 -4
  43. package/package.json +1 -1
  44. package/packages/client/cli-adapter.mjs +9 -0
  45. package/packages/client/cli-locator.mjs +3 -2
  46. package/packages/client/deployment-data.mjs +7 -0
  47. package/packages/client/deployment-panel.mjs +3 -0
  48. package/packages/client/file-output-exec.mjs +98 -0
  49. package/packages/client/instance-display-name.mjs +18 -0
  50. package/packages/client/launch-prompt-outcome.mjs +25 -13
  51. package/packages/client/own-codes.mjs +2 -0
  52. package/packages/client/session-attach.mjs +35 -5
  53. package/packages/client/session-resume-cli.mjs +64 -0
  54. package/packages/client/session-resume-trigger.mjs +167 -0
  55. package/packages/client/session-resume.mjs +332 -0
  56. package/packages/client/tmux-status.mjs +30 -7
  57. package/packages/client/waiting-on-you.mjs +11 -4
  58. package/packages/client/workspace-step.mjs +17 -5
  59. package/packages/record/lib/last-conversation.mjs +123 -0
  60. package/packages/record/lib/session-roots.mjs +10 -1
  61. package/packages/tui/README.md +1 -1
  62. package/packages/tui/lib/client.mjs +2 -1
  63. package/packages/tui/lib/main.mjs +5 -3
  64. package/packages/tui/lib/model.mjs +57 -15
  65. package/packages/tui/lib/store.mjs +8 -7
  66. package/packages/tui/lib/term/text.mjs +12 -9
  67. package/packages/tui/lib/views/capabilities.mjs +6 -6
  68. package/packages/tui/lib/views/frame.mjs +72 -7
  69. package/packages/tui/lib/views/help.mjs +9 -4
  70. package/packages/tui/lib/views/instances.mjs +46 -29
  71. package/packages/tui/lib/views/souls.mjs +9 -8
  72. package/skills/oats-getting-started/SKILL.md +117 -4
package/lib/core.mjs CHANGED
@@ -47,7 +47,7 @@ import { initializeNativeHistory, prepareNativeStart } from "../packages/record/
47
47
  import { sameDirectory } from "../packages/record/lib/directory-identity.mjs";
48
48
  import { noteRuntimeName } from "./deprecation.mjs";
49
49
  import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
50
- import { createSessionPaneInspector, inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
50
+ import { AGENT_PANE_OPTION, createSessionPaneInspector, inspectSessionTarget, inputSessionTarget, resolveAgentPane } from "./session-input.mjs";
51
51
  import { appendEvent, incarnationOf, liveWaiting, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
52
52
  import { killGroup } from "./process-group.mjs";
53
53
  import { NAMING_CALLS, NAMING_TIMEOUT_MS, suggestInstanceName } from "./instance-naming.mjs";
@@ -73,7 +73,7 @@ async function plannedSkillsDefault(prepared) { const m = await import("./instan
73
73
  // import: instance-resolution.mjs does not depend on core.mjs (no cycle).
74
74
  import { cloneRemoteFor, deploymentLock, resolutionContractWarnings, toCapabilityRows, verifyMemberClone } from "./instance-resolution.mjs";
75
75
  import { GIT_FETCH_TIMEOUT_MS, GIT_TIMEOUT_MS, gitEnv } from "./remote.mjs";
76
- import { loadLocal } from "./workspace.mjs";
76
+ import { loadLocal, loadMachineLaunchConfigs } from "./workspace.mjs";
77
77
  import { parseConfigData } from "./config-data.mjs";
78
78
  import { renderInstructionText } from "./instruction-composition.mjs";
79
79
  import { APPROVED_HOOKS, PORTABLE_ENV_NAME_RE, CORE_LAUNCH_ENV, PROCESS_BOOTSTRAP_ENV, PROCESS_BOOTSTRAP_PREFIXES, manifestContractProblems, disposableHomeRootProblem, disposableHomeRootMatches, contractWarningMessages, locatedContractWarnings } from "./capability-contract.mjs";
@@ -89,11 +89,18 @@ import { canonicalJson, lineAt, parseStrictJson } from "./canonical-json.mjs";
89
89
  import { readPortableBytes } from "./bounded-read.mjs";
90
90
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes, treeDisagreement } from "./tree-copy.mjs";
91
91
  import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
92
+ import { hashFile, readFilePieces, readFileUpTo } from "./file-pieces.mjs";
92
93
  import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
93
94
  import { systemTool } from "./system-tools.mjs";
94
- import { creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
95
+ import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
95
96
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
96
97
  import { readInstanceColor } from "./instance-color.mjs";
98
+ import { readStartExited, sessionEndOf, START_EXITED_FILE } from "./session-end.mjs";
99
+ import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
100
+ import { recordSeen } from "./session-seen.mjs";
101
+ import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, fromEnvNames, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
102
+ import { watchResumeConfirmation } from "./launch-prompt-resume.mjs";
103
+ import { lastConversation } from "../packages/record/lib/last-conversation.mjs";
97
104
  /** The package and capability id grammar (namespaced, lowercase): an id names a
98
105
  * directory (a home's module copy), so no path spelling fits it. */
99
106
  const PACKAGE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
@@ -610,9 +617,10 @@ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME
610
617
  // `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
611
618
  // process's start time on a host with procfs, and the `ps` it runs (lib/worktree-hooks.mjs processStart).
612
619
  "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS",
613
- // The test seams of #915: the cgroup the kernel judges itself in, and the directories its systemd-run
614
- // comes from (lib/tmux-server-scope.mjs, lib/system-tools.mjs).
615
- "OATS_TEST_CGROUP", "OATS_TEST_SYSTEM_TOOL_DIRS",
620
+ // The test seams of #915 and #1559: the cgroup the kernel judges itself in, whether the host was
621
+ // booted with systemd, and the directories its systemd-run comes from (lib/tmux-server-scope.mjs,
622
+ // lib/system-tools.mjs).
623
+ "OATS_TEST_CGROUP", "OATS_TEST_SYSTEMD_BOOTED", "OATS_TEST_SYSTEM_TOOL_DIRS",
616
624
  // The test seam of #1421 §3: the naming call's time limit (lib/instance-naming.mjs NAMING_TIMEOUT_MS).
617
625
  "OATS_TEST_NAMING_TIMEOUT_MS"]);
618
626
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
@@ -741,23 +749,46 @@ function incompleteLaunchPrompt(home, startId, target, reason, previous, expecte
741
749
  }
742
750
 
743
751
 
744
- /** The launch configurations effective at `dir`: the `launch-configs:` of the
745
- * oats-local.yaml found walking up from it (the deployment), validated. None
746
- * when no deployment is in reach. `source` is the deployment directory (a
747
- * relative `executable` resolves against it); `shadows` stays for the answer's
748
- * shape and is always empty — there is one host file, no scope chain. */
752
+ /** The machine's launch configurations file (awebai/oats#1506), beside the kernel's other per-user
753
+ * files: `$OATS_HOME_DIR/config/launch-configs.yaml`, else `~/.oats/config/launch-configs.yaml`. */
754
+ // The rule of schedule.mjs's oatsHomeDir, kept here as servers.mjs and deployments.mjs keep it:
755
+ // schedule.mjs imports this module, so importing it back would read its bindings before they exist.
756
+ const oatsHomeDir = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
757
+ export const machineLaunchConfigsFile = () => join(oatsHomeDir(), "config", "launch-configs.yaml");
758
+ /** The machine's launch configurations, validated as a deployment's are → `{ path, configs }`, or null
759
+ * when there is no file. A broken file throws E_LAUNCH_CONFIG_INVALID naming it. */
760
+ export function machineLaunchConfigs() {
761
+ const machine = loadMachineLaunchConfigs(machineLaunchConfigsFile());
762
+ if (machine) validateLaunchConfigs(machine.configs, machine.path);
763
+ return machine;
764
+ }
765
+
766
+ /** The launch configurations effective at `dir`, from two layers, each validated: the machine's
767
+ * (machineLaunchConfigsFile; a missing file is no layer) and the `launch-configs:` of the
768
+ * oats-local.yaml found walking up from `dir` (the deployment; none in reach, the machine's alone
769
+ * apply). A deployment entry replaces the machine's of the same name whole, and its `shadows` names
770
+ * the machine file. A deployment `default: true` for a harness wins: the machine entries of that
771
+ * harness are then not default. `source` is the directory the entry was declared in (a relative
772
+ * `executable` resolves against it). */
749
773
  export function launchConfigsAt(dir) {
750
774
  // Null-prototype: a configuration may legitimately be named constructor or
751
775
  // toString, and membership must never be an inherited property.
752
776
  const out = Object.create(null);
753
- let found;
754
- try { found = loadLocal(dir); } catch (e) { if (e?.code === "E_LOCAL_MISSING") return out; throw e; }
755
- const map = found.local["launch-configs"];
756
- validateLaunchConfigs(map, found.path);
757
- const source = dirname(found.path);
758
- for (const [name, entry] of Object.entries(map || {})) {
759
- if (!Object.hasOwn(entry, "harness")) noteRuntimeName(`launch-configs.${name}.runtime in ${found.path}`);
760
- out[name] = { name, harness: launchConfigHarness(entry), ...(entry.executable !== undefined ? { executable: entry.executable } : {}), args: [...(entry.args || [])], env: { ...(entry.env || {}) }, ...(entry.model !== undefined ? { model: entry.model } : {}), ...(entry.yolo !== undefined ? { yolo: entry.yolo } : {}), ...(entry.default === true ? { default: true } : {}), source, shadows: [] };
777
+ const machine = machineLaunchConfigs();
778
+ let found = null;
779
+ try { found = loadLocal(dir); } catch (e) { if (e?.code !== "E_LOCAL_MISSING") throw e; }
780
+ const local = found?.local["launch-configs"];
781
+ if (found) validateLaunchConfigs(local, found.path);
782
+ const entryOf = (name, entry, file, { isDefault, shadows }) => {
783
+ if (!Object.hasOwn(entry, "harness")) noteRuntimeName(`launch-configs.${name}.runtime in ${file}`);
784
+ return { name, harness: launchConfigHarness(entry), ...(entry.executable !== undefined ? { executable: entry.executable } : {}), args: [...(entry.args || [])], env: { ...(entry.env || {}) }, ...(entry.model !== undefined ? { model: entry.model } : {}), ...(entry.yolo !== undefined ? { yolo: entry.yolo } : {}), ...(isDefault ? { default: true } : {}), source: dirname(file), shadows };
785
+ };
786
+ const localDefaults = new Set(Object.values(local || {}).filter((entry) => entry.default === true).map(launchConfigHarness));
787
+ for (const [name, entry] of Object.entries(machine?.configs || {})) {
788
+ out[name] = entryOf(name, entry, machine.path, { isDefault: entry.default === true && !localDefaults.has(launchConfigHarness(entry)), shadows: [] });
789
+ }
790
+ for (const [name, entry] of Object.entries(local || {})) {
791
+ out[name] = entryOf(name, entry, found.path, { isDefault: entry.default === true, shadows: Object.hasOwn(machine?.configs || {}, name) ? [machine.path] : [] });
761
792
  }
762
793
  return out;
763
794
  }
@@ -1169,14 +1200,14 @@ export function materializedHookCommands(row, home) {
1169
1200
  /** Compose, but never mutate, an instance instruction view from canonical soul instructions.
1170
1201
  * `kind` tunes composition: "capability" suppresses the knowledge layer's injection (ephemeral service
1171
1202
  * agents — reviewers, harvesters — carry no episodic memory by design). */
1172
- export function composeInstanceAgentsMd(soulDir, contextDir, soulName, workMode, kind, prepared = undefined) {
1203
+ export function composeInstanceAgentsMd(soulDir, contextDir, soulName, workMode, kind, prepared = undefined, { launchConfigs = true } = {}) {
1173
1204
  const agentsMd = join(soulDir, "AGENTS.md");
1174
1205
  if (!existsSync(agentsMd)) throw new Error(`canonical soul instructions missing: ${agentsMd}`);
1175
1206
  // Workspace model only (lead decision c3-1): the capability set is the prepared
1176
1207
  // resolution's modules, materialized into the home by the caller. There is no
1177
1208
  // scope configuration to compose from.
1178
1209
  if (!prepared) throw oatsError("E_LOCAL_MISSING", `composing ${soulName ?? basename(dirname(soulDir))} needs a workspace deployment (oats-local.yaml) — its capabilities are the workspace's resolution; \`oats onboard\` creates one`);
1179
- const resolved = resolvedFromPrepared(prepared, contextDir);
1210
+ const resolved = resolvedFromPrepared(prepared, contextDir, { launchConfigs });
1180
1211
  const wanted = [];
1181
1212
  // Operational knowledge is a capability (oats.core / oats.setup) the resolution
1182
1213
  // carries like any other; the kernel composes no operational block of its own.
@@ -1207,15 +1238,16 @@ function layerRows(resolution) {
1207
1238
  * (manifest/settings/origin/trust known now; skills and inject paths point into
1208
1239
  * the home, which does not exist yet, and are rebuilt once materialize has
1209
1240
  * landed), the workspace, payloads and slots, and the deployment's launch
1210
- * configurations. `prepared.capabilityRows` is honoured only when non-empty. */
1211
- export function resolvedFromPrepared(prepared, contextDir) {
1241
+ * configurations (left out with `launchConfigs: false`, for a composition that launches nothing).
1242
+ * `prepared.capabilityRows` is honoured only when non-empty. */
1243
+ export function resolvedFromPrepared(prepared, contextDir, { launchConfigs = true } = {}) {
1212
1244
  return {
1213
1245
  capabilities: Array.isArray(prepared.capabilityRows) && prepared.capabilityRows.length ? prepared.capabilityRows : plannedCapabilityRows(prepared.resolution),
1214
1246
  workspace: { key: prepared.discovery?.key ?? null, name: prepared.discovery?.workspace?.name ?? null, deployment: prepared.deployment ?? null, commit: prepared.discovery?.commit ?? null, standalone: prepared.discovery?.standalone === true, revision: prepared.resolution.revision, slots: prepared.resolution.slots },
1215
1247
  payloads: prepared.resolution.payloads ?? {},
1216
1248
  teams: prepared.resolution.teams ?? [], defaultTeam: prepared.resolution.defaultTeam ?? null, teamsSource: "live",
1217
1249
  layers: layerRows(prepared.resolution),
1218
- launchConfigs: launchConfigsAt(contextDir || prepared.deployment),
1250
+ ...(launchConfigs ? { launchConfigs: launchConfigsAt(contextDir || prepared.deployment) } : {}),
1219
1251
  };
1220
1252
  }
1221
1253
 
@@ -2467,10 +2499,10 @@ function paneEnvironment(socket, session, io, cwd) {
2467
2499
  const tmuxAt = `tmux -S ${shellWord(socket)}`;
2468
2500
  const decide = ({ env, omitted, cleared }, name, source, holder, scope) => {
2469
2501
  const set = `give ${holder} a ${name} that OATS can read (${tmuxAt} set-environment ${scope} ${name} <value>)`;
2470
- if (env === null) return { source, problem: `${source} could not be read`, remedy: `make \`${tmuxAt} show-environment ${scope} -s\` answer` };
2502
+ if (env === null) return { source, problem: `${source} could not be read`, unreadable: true, remedy: `make \`${tmuxAt} show-environment ${scope} -s\` answer` };
2471
2503
  if (Object.hasOwn(env, name)) return { value: env[name], source };
2472
2504
  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 };
2473
- 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 };
2505
+ 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)`, unreadable: true, remedy: HARNESS_CONFIG_SELECTORS.has(name) ? `${set}, or remove the entry (${tmuxAt} set-environment ${scope} -u ${name})` : set };
2474
2506
  return null;
2475
2507
  };
2476
2508
  const answers = new Map();
@@ -2729,7 +2761,14 @@ function oatsTmuxWindows(session) {
2729
2761
  * the command with the server's `default-shell -c` (the user's shell: sh, bash and zsh all take
2730
2762
  * `unset NAME…;`), and the fallback shell it execs inherits the result. Never persisted: the
2731
2763
  * recorded command (meta.command) is the launch command alone. */
2764
+ /** A launch's command followed by its exit marker (lib/session-end.mjs): the start id and the harness's
2765
+ * exit status, written when the harness ends, by spawn's window and start's alike. */
2766
+ const exitMarked = (command, startId, path) => `${command}; oats_start_status=$?; printf '{"startId":"%s","status":%d}\\n' ${shq(startId)} "$oats_start_status" > ${shq(path)}`;
2732
2767
  const paneCommand = (command, removed = []) => `unset ${["COLORFGBG", ...removed].join(" ")}; ${command}; exec "\${SHELL:-/bin/zsh}"`;
2768
+ /** The tail that marks the pane a launch creates (new-window: the new pane, tmux's current one after
2769
+ * it) or respawns (`paneId`) as the agent's (AGENT_PANE_OPTION), chained into the launch's own tmux
2770
+ * call. `-q`: a mark that cannot be set never fails the launch; readers then find the pane by id. */
2771
+ const markAgentPane = (name, paneId) => [";", "set-option", "-q", "-p", ...(paneId ? ["-t", paneId] : []), AGENT_PANE_OPTION, name];
2733
2772
  /** The sizing options on one window, each best effort: this command's failure is ignored, nothing is
2734
2773
  * retried elsewhere and nothing global is written. */
2735
2774
  function sizeWindow(socket, windowId, io) {
@@ -3048,6 +3087,10 @@ export const CODEX_TASK_PROMPT = "Read TASK.md in this directory first: it is yo
3048
3087
  /** The prompt each harness gets, so the task's text never travels in argv: Claude Code inlines an
3049
3088
  * `@file` mention; codex is pointed at the file. pi takes `@TASK.md` among its own arguments. */
3050
3089
  const TASK_PROMPT = Object.freeze({ claude: "@TASK.md", codex: CODEX_TASK_PROMPT });
3090
+ /** The prompt a resumed session gets in place of the task prompt (feature session-resume, R1): without
3091
+ * it, a harness cut off mid-turn would sit idle until someone types. It states only what holds for
3092
+ * every instance a resume brings back. */
3093
+ export const RESUME_NOTICE = "OATS resumed this session after it was lost (the host restarted or its terminal server ended). Continue from where you were.";
3051
3094
 
3052
3095
  /** The executable a launch uses: a configuration's declared one (a bare name
3053
3096
  * on PATH; a path against the deployment directory when relative) or the
@@ -3379,8 +3422,14 @@ export function launchFolderTrust({ harness, home, meta, yolo, launch, env = pro
3379
3422
  * deployment root or an ancestor in Codex's config (lib/harness-trust.mjs),
3380
3423
  * which Codex itself does not apply to the homes below it. Codex's own form
3381
3424
  * of the override is the inline table: a dotted projects."<home>" key is not
3382
- * honoured (codex-cli 0.157.1). */
3383
- export function renderLaunchRecipe(recipe, { home, instance, redact = false, trustHome = false }) {
3425
+ * honoured (codex-cli 0.157.1).
3426
+ *
3427
+ * `resume` ({ sessionId, prompt }, feature session-resume): the same launch continuing the harness's
3428
+ * own conversation. Claude takes `--resume <id>` among its own options, before contributed ones, and
3429
+ * the prompt after `--` in place of the task; pi takes `--session <id>`, and the prompt as the
3430
+ * positional where `@TASK.md` stands. Codex has none yet. Only the executed window command is rendered
3431
+ * so: what is persisted stays the ordinary launch. */
3432
+ export function renderLaunchRecipe(recipe, { home, instance, redact = false, trustHome = false, resume = null }) {
3384
3433
  const { harness, executable, model, yolo } = recipe;
3385
3434
  const cfgArgs = (recipe.args || []).map(shq).join(" ");
3386
3435
  const hookArgs = recipe.hooks?.launch?.[harness] || "";
@@ -3396,8 +3445,11 @@ export function renderLaunchRecipe(recipe, { home, instance, redact = false, tru
3396
3445
  }
3397
3446
  let cmdline;
3398
3447
  if (harness === "claude") {
3399
- cmdline = `${shq(executable)}${yolo ? " --dangerously-skip-permissions" : ""}${model ? ` --model ${shq(model)}` : ""}${tail} -- ${shq(TASK_PROMPT.claude)}`;
3448
+ cmdline = `${shq(executable)}${yolo ? " --dangerously-skip-permissions" : ""}${model ? ` --model ${shq(model)}` : ""}${resume ? ` --resume ${shq(resume.sessionId)}` : ""}${tail} -- ${shq(resume ? resume.prompt : TASK_PROMPT.claude)}`;
3400
3449
  } else if (harness === "codex") {
3450
+ // No resume selector until a Codex resume is proven end to end on a signed-in host: start
3451
+ // --resume takes a Codex home's fresh path (resume-unproven) and never asks for one.
3452
+ if (resume) throw new Error("renderLaunchRecipe: codex has no resume rendering");
3401
3453
  // Codex compares the key with its own working directory, in its on-disk spelling.
3402
3454
  const codexTrust = `projects={${JSON.stringify(canonicalHomePath(home))}={trust_level="trusted"}}`;
3403
3455
  // Codex may run tool commands outside the session's process (its shared app-server daemon),
@@ -3411,7 +3463,7 @@ export function renderLaunchRecipe(recipe, { home, instance, redact = false, tru
3411
3463
  // .agents/skills up the tree, so the instance's copied capability skills are
3412
3464
  // found from cwd=home) and context files stay ambient. OATS contributes only
3413
3465
  // the composed instructions.
3414
- cmdline = `${shq(executable)} --append-system-prompt ${shq(join(home, "AGENTS.md"))} --approve --name ${shq(instance)}${model ? ` --model ${shq(model)}` : ""} ${shq("@TASK.md")}${tail}`;
3466
+ cmdline = `${shq(executable)} --append-system-prompt ${shq(join(home, "AGENTS.md"))} --approve --name ${shq(instance)}${model ? ` --model ${shq(model)}` : ""}${resume ? ` --session ${shq(resume.sessionId)}` : ""} ${shq(resume ? resume.prompt : "@TASK.md")}${tail}`;
3415
3467
  }
3416
3468
  return `${env.map((e) => e.reference ? `${e.name}="$${LAUNCH_REF_PREFIX}${e.name}"` : `${e.name}=${shq(e.value)}`).join(" ")} ${cmdline}`;
3417
3469
  }
@@ -3419,14 +3471,51 @@ export function renderLaunchRecipe(recipe, { home, instance, redact = false, tru
3419
3471
  /** Execution, not preview: mark pending before dispatch, then resolve native
3420
3472
  * storage inside the backend shell under the actual command environment.
3421
3473
  * The original executable/argv is exec'd unchanged after recording succeeds,
3422
- * with the home's kernel shim first on PATH (every launch runs through here). */
3423
- function nativeRecordCommand(command, home, harness) {
3474
+ * with the home's kernel shim first on PATH (every launch runs through here).
3475
+ * `start` is the launch's one native start (prepareNativeStart), prepared once and reused by every
3476
+ * render of that launch, so that the command dispatched is the only one with a pending receipt.
3477
+ * With `scope` (agentScopeOn's wrapper), that shell runs in a systemd scope of its own, named per
3478
+ * launch (lib/tmux-server-scope.mjs agentScope): execution only, like paneCommand's `unset`; the
3479
+ * persisted command, the recipe and the receipts never carry it. The wrapper is chosen only after
3480
+ * the probe started a scope in this pane's environment, so a failed systemd-run is not the
3481
+ * harness's exit. What remains is a race: systemd-run failing between the probe and the pane. The
3482
+ * pane's shell then reads exit status 1, the scope runner's: an ordinary exit (below 128, no
3483
+ * signal), which the start's exit marker (.oats-start-exited) reads as a harness that exited, never
3484
+ * one to relaunch, so the race cannot cause a spurious resume. No home file tells the two apart. */
3485
+ function nativeRecordCommand(command, home, harness, { start, scope } = {}) {
3424
3486
  const { tokens, binary } = parseLaunchCommand(command);
3425
3487
  const args = tokens.slice(binary + 1).map(t => t.value ?? t.text);
3426
- const id = prepareNativeStart(home, harness);
3488
+ const id = start ?? prepareNativeStart(home, harness);
3427
3489
  const recorder = join(PKG_ROOT, "packages", "record", "bin", "record-native-start.mjs");
3428
3490
  const inner = `${shq(process.execPath)} ${shq(recorder)} ${shq(home)} ${shq(id)} ${shq(harness)} ${shq(JSON.stringify(args))} && exec ${executionArgv(tokens, binary, harness).join(" ")}`;
3429
- return `${shimPathPrefix(tokens, binary, home).join(" ")} /bin/sh -c ${shq(inner)}`;
3491
+ const wrapper = scope ? agentScopeArgv(scope, agentScopeUnit({ home })).map(shq) : [];
3492
+ return `${[...shimPathPrefix(tokens, binary, home), ...wrapper].join(" ")} /bin/sh -c ${shq(inner)}`;
3493
+ }
3494
+ /** The agent's scope of the launch of `command` in a pane with `pane`'s environment (paneEnvironment)
3495
+ * → agentScope's answer. The values the probe gets for SCOPE_ENV_NAMES are the ones systemd-run
3496
+ * will run with: what the command's environment prefix sets (a literal, or a reference whose source
3497
+ * is one of `refs`, the pane's `-e` values, else the pane's own), else nothing for a name the launch
3498
+ * removes (paneCommand's `unset`), else the pane's. `io` is a test's (agentScope). */
3499
+ function agentScopeOn(command, { pane, removed = [], refs = [] }, io) {
3500
+ return agentScope({ io, paneEnv: () => {
3501
+ const { tokens, binary } = parseLaunchCommand(command);
3502
+ const prefix = tokens.slice(0, binary);
3503
+ const given = new Map(refs.map((r) => [r.name, r.value]));
3504
+ const ofPane = (name) => {
3505
+ if (removed.includes(name)) return {};
3506
+ const answer = pane.of(name);
3507
+ if (answer.unestablished || answer.unreadable) return { reason: `the pane's ${name} cannot be read (${answer.problem || `the pane's environment is not established${answer.unestablished}`})` };
3508
+ return typeof answer.value === "string" ? { value: answer.value } : {};
3509
+ };
3510
+ const env = {};
3511
+ for (const name of SCOPE_ENV_NAMES) {
3512
+ const set = prefix.findLast((t) => t.name === name);
3513
+ const answer = !set ? ofPane(name) : set.kind === "env" ? { value: set.value } : given.has(set.source) ? { value: given.get(set.source) } : ofPane(set.source);
3514
+ if (answer.reason) return answer;
3515
+ if (answer.value) env[name] = answer.value;
3516
+ }
3517
+ return { env };
3518
+ } });
3430
3519
  }
3431
3520
 
3432
3521
 
@@ -3770,7 +3859,7 @@ export async function suggestSpawnName({ dir = process.cwd(), soul, task, harnes
3770
3859
  if (askedModel !== undefined && (typeof askedModel !== "string" || !askedModel)) throw oatsError("E_BAD_ARGS", "--model needs a model id");
3771
3860
  let deployment = null;
3772
3861
  try { deployment = dirname(loadLocal(dir).path); } catch (e) { if (e?.code !== "E_LOCAL_MISSING") throw e; }
3773
- const configs = deployment ? launchConfigsAt(deployment) : Object.create(null);
3862
+ const configs = launchConfigsAt(deployment ?? dir);
3774
3863
  let config = null;
3775
3864
  if (named !== undefined && named !== "none") {
3776
3865
  if (typeof named !== "string" || !Object.hasOwn(configs, named)) throw launchConfigUnknown({ name: named, from: "flag", at: "--launch-config" });
@@ -4400,7 +4489,7 @@ function* spawnBody(root, agent, o = {}) {
4400
4489
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
4401
4490
  decision, preflight,
4402
4491
  backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
4403
- harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
4492
+ harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigSource: launchConfig?.source ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
4404
4493
  launch: launchReport({ declared: launchChoice.declared, harness, model, launchConfig: launchConfig?.name, from: launchChoice.from, at: launchChoice.at }),
4405
4494
  branch: plannedBranch, base: plannedBase, worktree: work === "worktree" ? join(home, "work") : null,
4406
4495
  // #796: the `worktree` hooks a worktree-mode spawn would fire, in the order they run; null in other modes.
@@ -5167,7 +5256,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5167
5256
 
5168
5257
  spawnTmux = meta.tmux;
5169
5258
  if (work === "directory") assertDirectoryRoots(home, homeReal);
5170
- let executionCommand = launch ? nativeRecordCommand(cmdline, home, harness) : null;
5259
+ // The launch's one native start, prepared before anything is created; every render below reuses it.
5260
+ const nativeStart = launch ? prepareNativeStart(home, harness) : null;
5261
+ let unscoped = null; // the harness's agent-scope warning, an event once the launch is recorded
5171
5262
  if (launch) {
5172
5263
  // The session on the OATS server, then everything on the one socket that answered: the collision
5173
5264
  // check, the records, the window and (in compensateSpawn) its removal.
@@ -5175,7 +5266,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5175
5266
  // The environment this window's pane will actually start with, whoever created the session and
5176
5267
  // with whatever environment (a race lost to another creator, a session that overrides a name):
5177
5268
  // one read of it answers the three checks below, each of which reads it only when it has to.
5178
- const actualEnv = launchEnvOn(paneEnvironment(socket, session, undefined, home), removedEnv);
5269
+ const pane = paneEnvironment(socket, session, undefined, home);
5270
+ const actualEnv = launchEnvOn(pane, removedEnv);
5179
5271
  // The harness looked up again on that PATH. Not there: refused, and the spawn is compensated.
5180
5272
  // Found elsewhere than the preflight found it: the launch runs that one.
5181
5273
  if (executable.lookup) {
@@ -5186,7 +5278,6 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5186
5278
  if (actual.path !== recipe.executable) {
5187
5279
  recipe.executable = actual.path;
5188
5280
  meta.command = cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
5189
- executionCommand = nativeRecordCommand(cmdline, home, harness);
5190
5281
  }
5191
5282
  }
5192
5283
  // The package gate judged the pane this spawn expected (`probed`). When the pane it got differs
@@ -5207,7 +5298,6 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5207
5298
  if (actualTrust.warning) spawnWarnings.push(actualTrust.warning);
5208
5299
  if (actualTrust.trustHome !== folderTrust.trustHome) {
5209
5300
  meta.command = cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: actualTrust.trustHome });
5210
- executionCommand = nativeRecordCommand(cmdline, home, harness);
5211
5301
  }
5212
5302
  folderTrust = actualTrust;
5213
5303
  let present;
@@ -5217,6 +5307,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5217
5307
  meta.tmux.socket = socket;
5218
5308
  meta.launched = true;
5219
5309
  promptStartId = randomUUID();
5310
+ // The spawn's launch is the home's first start: its id names it in the exit marker and a stop's
5311
+ // receipt (lib/session-end.mjs), as a start's does.
5312
+ meta.startId = promptStartId;
5220
5313
  const engaged = devChannelEngaged(harness, cmdline);
5221
5314
  if (engaged) warnings.push(DEV_CHANNEL_STATEMENT);
5222
5315
  else meta.launchPrompts = notEngaged(promptStartId);
@@ -5225,10 +5318,17 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5225
5318
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n");
5226
5319
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: true, tmux: meta.tmux });
5227
5320
  clearSpawnInProgressMarker();
5321
+ // The first start's launch environment (lib/start-env.mjs), after the baseline, as a start records its own.
5322
+ recordStartEnv(home, promptStartId, fromEnvNames(recipe.env), process.env);
5228
5323
  // Wrap the command so the window drops into an interactive shell when the
5229
5324
  // agent exits (e.g. Ctrl-C) instead of tmux killing the window.
5230
- const windowCmd = paneCommand(executionCommand, removedEnv);
5231
- const paneEnvFlags = launchEnvRefs(recipe, process.env).flatMap((r) => ["-e", `${r.name}=${r.value}`]);
5325
+ const refs = launchEnvRefs(recipe, process.env);
5326
+ // On the same pane, for the command it runs: whether the harness runs in a scope of its own.
5327
+ const scope = agentScopeOn(cmdline, { pane, removed: removedEnv, refs });
5328
+ if (scope.warning) spawnWarnings.push(unscoped = scope.warning);
5329
+ // The exit marker records how this launch's harness ended (lib/session-end.mjs), as a start's does.
5330
+ const windowCmd = paneCommand(exitMarked(nativeRecordCommand(cmdline, home, harness, { start: nativeStart, scope: scope.wrapper }), promptStartId, join(home, START_EXITED_FILE)), removedEnv);
5331
+ const paneEnvFlags = refs.flatMap((r) => ["-e", `${r.name}=${r.value}`]);
5232
5332
  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`);
5233
5333
  // Only a launch that engages the confirmation needs lineage committed before
5234
5334
  // dispatch: its uncertain input outcome retains the new process and parent
@@ -5239,7 +5339,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5239
5339
  promptDispatched = !!controller;
5240
5340
  let windowId;
5241
5341
 
5242
- try { windowId = tmuxOn(socket, ["new-window", "-P", "-F", controller ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", instance, "-c", home, ...paneEnvFlags, windowCmd], undefined, oatsWindowEnvironment()).trim(); }
5342
+ try { windowId = tmuxOn(socket, ["new-window", "-P", "-F", controller ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", instance, "-c", home, ...paneEnvFlags, windowCmd, ...markAgentPane(instance)], undefined, oatsWindowEnvironment()).trim(); }
5243
5343
  catch (e) { throw launchFailed("new-window", "the window command was refused", e); }
5244
5344
  if (controller) { promptTarget = { ...meta.tmux, ...launchPaneTarget(socket, windowId) }; windowId = promptTarget.windowId; }
5245
5345
  try { prepareAgentWindow(socket, windowId); }
@@ -5269,6 +5369,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5269
5369
 
5270
5370
  appendEvent(home, { kind: "spawned", data: { agent: agent.name, work, branch: branch ?? null, harness, model: model || null, parentInstance: meta.parentInstance ?? null, relation: relation ?? null, launched: launch, hooks: hookReceipt(hookRes), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}) } });
5271
5371
  if (launch) appendEvent(home, { kind: "launched", data: { harness, backend, launchConfig: launchConfig?.name ?? null } });
5372
+ if (unscoped) appendEvent(home, { kind: "launch-warning", data: { message: unscoped } });
5272
5373
  if (o.idempotencyKey !== undefined) {
5273
5374
  // Only now is the spawn a finished receipt a same-key retry may replay.
5274
5375
  meta.spawnCompleted = true;
@@ -5365,14 +5466,16 @@ function recordedTmuxWindows(socket, session, io) {
5365
5466
  * be read, and, for a row whose server holds its endpoint (`endpoint`), when its socket file is
5366
5467
  * missing while a process works in the home or the scan (`scanHome()`, processesInHome's answer for
5367
5468
  * it) cannot tell (#624). */
5368
- function tmuxLiveness({ windows, error, missingSocket, panes }, window, scanHome, endpoint, inspectPanes) {
5469
+ function tmuxLiveness({ windows, error, missingSocket, panes, windowIds }, window, scanHome, endpoint, inspectPanes) {
5369
5470
  if (error) return { running: null, runtimeState: "unreachable", runtimeError: error };
5370
5471
  const running = windows.includes(window);
5371
5472
  const why = !running && missingSocket && endpoint ? missingSocketUnestablished(missingSocket, scanHome()) : null;
5372
5473
  if (why) return { running: null, runtimeState: "unreachable", runtimeError: why };
5373
5474
  if (!running) return { running: false };
5374
5475
  try {
5375
- const observed = inspectPanes(panes.get(window) ?? []);
5476
+ // Two windows of one name: tmux finds neither by name, so no session command reaches this one.
5477
+ if (windowIds?.get(window)?.size > 1) throw new Error(`the session has ${windowIds.get(window).size} windows named ${window}`);
5478
+ const observed = inspectPanes(panes.get(window) ?? [], { name: window });
5376
5479
  return { running: harnessRunning(observed), ...(observed.state === "shell" ? { runtimeState: "shell" } : {}) };
5377
5480
  } catch (e) { return { running: null, runtimeState: "unreachable", runtimeError: tmuxFailure(e, "tmux pane inspection failed") }; }
5378
5481
  }
@@ -5381,19 +5484,19 @@ function tmuxLiveness({ windows, error, missingSocket, panes }, window, scanHome
5381
5484
  function statusTmuxPanes(snapshot, socket, session, io) {
5382
5485
  if (!snapshot.windows?.length) return snapshot;
5383
5486
  try {
5384
- const args = ["list-panes", "-s", "-t", `=${session}`, "-F", "#{window_name}\t#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"];
5487
+ const args = ["list-panes", "-s", "-t", `=${session}`, "-F", `#{window_name}\t#{window_id}\t#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}\t#{${AGENT_PANE_OPTION}}`];
5385
5488
  const output = socket ? tmuxOn(socket, args, io) : (io?.exec || execFileSync)("tmux", ["-u", ...args], {
5386
5489
  encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
5387
5490
  });
5388
- const panes = new Map();
5491
+ const panes = new Map(), windowIds = new Map();
5389
5492
  for (const line of output.split("\n").filter(Boolean)) {
5390
- const tab = line.indexOf("\t");
5391
- if (tab < 0) throw new Error("invalid tmux pane response");
5392
- const window = line.slice(0, tab);
5393
- if (!panes.has(window)) panes.set(window, []);
5394
- panes.get(window).push(line.slice(tab + 1));
5493
+ const [window, windowId, ...pane] = line.split("\t");
5494
+ if (!pane.length) throw new Error("invalid tmux pane response");
5495
+ if (!panes.has(window)) { panes.set(window, []); windowIds.set(window, new Set()); }
5496
+ panes.get(window).push(pane.join("\t"));
5497
+ windowIds.get(window).add(windowId);
5395
5498
  }
5396
- return { ...snapshot, panes };
5499
+ return { ...snapshot, panes, windowIds };
5397
5500
  } catch (e) { return { error: tmuxFailure(e, "tmux list-panes failed") }; }
5398
5501
  }
5399
5502
  export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
@@ -5493,9 +5596,13 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5493
5596
  // `retire` is only ever the value read above: a record that carries one (hand-edited, or
5494
5597
  // copied from a row) never stands in for it.
5495
5598
  const { retire: _recordedRetire, ...recorded } = meta;
5599
+ // Feature session-resume: how the last session of a launched home that does not run ended
5600
+ // (lib/session-end.mjs): lost, stopped or exited. Absent while it runs or reads unknown, for a
5601
+ // home never launched, and for one being set up, retired or quarantined.
5602
+ const sessionEnd = record.state === "record" && liveness.running === false && meta.launched === true && !rollbackIncomplete && !spawnInProgress && !retirePending ? sessionEndOf(home, meta) : null;
5496
5603
  // Feature instance-color: the home's own colour record (lib/instance-color.mjs), a palette name or
5497
5604
  // null, after the record so that nothing in instance.json stands in for it.
5498
- return { ...recorded, ...claims, home, instance: e.name, ...facts, color: readInstanceColor(home), ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
5605
+ return { ...recorded, ...claims, home, instance: e.name, ...facts, color: readInstanceColor(home), ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, ...(sessionEnd ? { sessionEnd } : {}), waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
5499
5606
 
5500
5607
  });
5501
5608
  };
@@ -5536,6 +5643,9 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5536
5643
  out.push({ name, kind: "capability", capability: cap, description: cap ? `capability agent (${cap})` : "capability agent", dir, instances, ...(retireFailures.length ? { retireFailures } : {}) });
5537
5644
  seen.add(name);
5538
5645
  }
5646
+ // Feature session-resume: what this local listing saw of each home's session, for the sweep
5647
+ // (lib/session-seen.mjs). It never changes the listing, and never throws or prints.
5648
+ recordSeen(root, out.flatMap((a) => a.instances || []));
5539
5649
  return out;
5540
5650
  }
5541
5651
 
@@ -6045,8 +6155,12 @@ function retireGitProbe(repo, args, { encoding } = {}) {
6045
6155
  * as its own (`retirement.disposable.home`: KERNEL_HOME_NAMES and
6046
6156
  * KERNEL_HOME_NAME_PREFIXES in lib/capability-contract.mjs, and the schema). */
6047
6157
  // `.oats-color.json` (feature instance-color) is presentation anyone may change at any time: never work.
6048
- const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json"]);
6049
- const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/];
6158
+ // `.oats-start-exited` (lib/session-end.mjs) is the window's record of how the harness ended: every
6159
+ // launched home whose harness ever ended holds it.
6160
+ // `.oats-start-env.json` and its key (lib/start-env.mjs) are written at every start that renders a
6161
+ // recipe, after the spawn's baseline: every launched home holds them.
6162
+ const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json", START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
6163
+ const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, START_ENV_TMP];
6050
6164
  /** Harness project settings in the home are configuration, not work: the
6051
6165
  * home's `.claude/` is harness layout the kernel already shapes (the skills
6052
6166
  * alias), and capabilities keep their own entries current in its
@@ -6092,7 +6206,9 @@ const GIT_NAME = Buffer.from(".git");
6092
6206
  * version `digestVersion` names (the baseline's own: baselineDigestVersion).
6093
6207
  * Both versions hold a home's `instance.json` without the fields the kernel
6094
6208
  * writes after spawn (kernelNeutralInstanceJson), so they read alike two
6095
- * `instance.json` files that parse to the same value.
6209
+ * `instance.json` files that parse to the same value; one over
6210
+ * NEUTRAL_INSTANCE_JSON_BYTES is held as its bytes, so a baseline taken
6211
+ * of its neutral form reads that home as changed.
6096
6212
  * - 1, the legacy digest: what a baseline without `digestVersion` holds,
6097
6213
  * written by a kernel before 0.49.0. It never changes: its framing (each
6098
6214
  * field followed by NUL, no lengths) and its order (the names as text,
@@ -6137,7 +6253,10 @@ const GIT_NAME = Buffer.from(".git");
6137
6253
  * reach, one inside another tap, and one that holds a path it passes over
6138
6254
  * (the caller does not ask for those; worktreeDigests).
6139
6255
  *
6140
- * The walk reads every byte it hashes itself, in this order. While it does,
6256
+ * The walk reads every byte it hashes itself, in this order, each file in
6257
+ * pieces of a fixed size (file-pieces.mjs); a home's `instance.json`, which
6258
+ * the stored digest takes in its neutral form, is read whole up to
6259
+ * NEUTRAL_INSTANCE_JSON_BYTES. While it does,
6141
6260
  * worker threads read the files it reads next into the page cache
6142
6261
  * (read-ahead.mjs), which changes nothing it computes or throws. */
6143
6262
  function fingerprintTrees(root, options = {}) {
@@ -6158,6 +6277,15 @@ function treeDigests(root, { excludeRoot = new Set(), excludePaths = [], instanc
6158
6277
  /** A field whose length is not fixed, in the exact digest or in version 2: its length, NUL, its bytes. */
6159
6278
  const sizedIn = (hash, bytes) => { hash.update(String(bytes.length)); hash.update("\0"); hash.update(bytes); };
6160
6279
  const sized = (bytes) => sizedIn(x, bytes);
6280
+ /** A file's bytes into the digests, read in pieces (readFilePieces): in each,
6281
+ * "file" and NUL, then in the legacy digest (`legacyHash`) its bytes, and in
6282
+ * each of `framed` its length, NUL and its bytes; the same stream as the
6283
+ * whole file read at once gives. */
6284
+ const fileInto = (path, legacyHash, framed) => {
6285
+ const hashes = [legacyHash, ...framed].filter(Boolean);
6286
+ for (const hash of hashes) hash.update("file\0");
6287
+ readAheadConsumed(readFilePieces(path, (size) => { for (const hash of framed) hash?.update(`${size}\0`); }, (bytes) => { for (const hash of hashes) hash.update(bytes); }));
6288
+ };
6161
6289
  const rootStat = lstatSync(root);
6162
6290
  if (!rootStat.isDirectory()) {
6163
6291
  const mode = String(rootStat.mode & 0o7777);
@@ -6165,7 +6293,7 @@ function treeDigests(root, { excludeRoot = new Set(), excludePaths = [], instanc
6165
6293
  v?.update("entry\0"); v?.update(mode); v?.update("\0");
6166
6294
  x?.update("entry\0"); x?.update(mode); x?.update("\0");
6167
6295
  if (rootStat.isSymbolicLink()) { const target = readlinkSync(root, "buffer"); s?.update("link\0"); s?.update(target); if (v) { v.update("link\0"); sizedIn(v, target); } if (x) { x.update("link\0"); sized(target); } }
6168
- else if (rootStat.isFile()) { const bytes = readFileSync(root); readAheadConsumed(bytes.length); s?.update("file\0"); s?.update(bytes); if (v) { v.update("file\0"); sizedIn(v, bytes); } if (x) { x.update("file\0"); sized(bytes); } }
6296
+ else if (rootStat.isFile()) fileInto(root, s, [v, x]);
6169
6297
  else throw unsupportedEntry(String(root));
6170
6298
  return digests();
6171
6299
  }
@@ -6218,15 +6346,18 @@ function treeDigests(root, { excludeRoot = new Set(), excludePaths = [], instanc
6218
6346
  if (x) { x.update("link\0"); sized(target); }
6219
6347
  if (t) { t.update("link\0"); sizedIn(t, target); }
6220
6348
  } else if (st.isFile()) {
6221
- const bytes = readFileSync(path);
6222
- readAheadConsumed(bytes.length);
6223
6349
  // Kernel-field neutrality applies ONLY when the tree IS an instance home, and only to the
6224
6350
  // stored digest; a work tree's instance.json is the agent's bytes.
6225
- const storedBytes = s || v ? (instanceHome && !relText && name === "instance.json" ? kernelNeutralInstanceJson(bytes) : bytes) : undefined;
6226
- s?.update("file\0"); s?.update(storedBytes); s?.update("\0");
6227
- if (v) { v.update("file\0"); sizedIn(v, storedBytes); }
6228
- if (x) { x.update("file\0"); sized(bytes); }
6229
- if (t) { t.update("file\0"); sizedIn(t, bytes); }
6351
+ const bytes = (s || v) && instanceHome && !relText && name === "instance.json" ? readFileUpTo(path, NEUTRAL_INSTANCE_JSON_BYTES) : null;
6352
+ if (bytes) {
6353
+ readAheadConsumed(bytes.length);
6354
+ const storedBytes = kernelNeutralInstanceJson(bytes);
6355
+ s?.update("file\0"); s?.update(storedBytes);
6356
+ if (v) { v.update("file\0"); sizedIn(v, storedBytes); }
6357
+ if (x) { x.update("file\0"); sized(bytes); }
6358
+ if (t) { t.update("file\0"); sizedIn(t, bytes); }
6359
+ } else fileInto(path, s, [v, x, t]);
6360
+ s?.update("\0");
6230
6361
  } else if (st.isDirectory()) {
6231
6362
  s?.update("dir\0"); v?.update("dir\0"); x?.update("dir\0"); tap?.hash.update("dir\0");
6232
6363
  walk(path, childRel, childRelText, on, tap ?? (opens ? { hash: opens, at: childRel.length + PATH_SEPARATOR_BYTES.length } : null));
@@ -6469,6 +6600,8 @@ function retirementDisposableRoots(work, capabilities) {
6469
6600
  * is still recovered at retire. (Replaces a whole-home re-stamp that could
6470
6601
  * bless authored bytes written in the launch→completion interval.) */
6471
6602
  const KERNEL_POST_SPAWN_FIELDS = ["spawnCompleted", "wake", "launchPrompts", "launchPromptTarget", "parentLineageCommitted"];
6603
+ // What a digest holds of a home instance.json to take its neutral form (#617); a larger one is hashed raw, in pieces.
6604
+ const NEUTRAL_INSTANCE_JSON_BYTES = 16 * 1024 * 1024;
6472
6605
  function kernelNeutralInstanceJson(bytes) {
6473
6606
  try {
6474
6607
  // Bytes that are not UTF-8 would each read as the replacement character,
@@ -7207,6 +7340,21 @@ export const STOP_UNDER_CLAIM = Symbol("oats.stopUnderClaim");
7207
7340
  export function requireStopGrace(graceMs) {
7208
7341
  if (graceMs !== undefined && (!Number.isSafeInteger(graceMs) || graceMs < 1 || graceMs > 300000)) throw oatsError("E_BAD_ARGS", "stop grace must be 1-300000 ms");
7209
7342
  }
7343
+ /** The start a stop ends: the home's recorded `startId`, null when it records none (or cannot be read). */
7344
+ function stopStartId(home) {
7345
+ const id = readJsonOrUndefined(join(home, "instance.json"))?.startId;
7346
+ return typeof id === "string" && id ? id : null;
7347
+ }
7348
+ /** An explicit stop of a launched home found idle whose session reads `lost` (the host went down or
7349
+ * its tmux server died; or a home from before 0.69 whose harness ended): nothing is signalled, but
7350
+ * the stop is recorded (`stop: null`), so a resume does not bring the home back. Best effort: a
7351
+ * home that cannot be written (a full disk) answers as any idle stop, and stays `lost`. */
7352
+ function recordIdleStop(realHome) {
7353
+ const meta = readJsonOrUndefined(join(realHome, "instance.json"));
7354
+ if (meta?.launched !== true || sessionEndOf(realHome, meta) !== SESSION_END.LOST) return;
7355
+ try { writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: null, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(realHome) }); }
7356
+ catch { /* the idle stop's answer is unchanged: see above */ }
7357
+ }
7210
7358
  /** The stop of stopInstanceSession, under the home's claim. The pending self-retire marker is read
7211
7359
  * here, under it: a `--self` retire writes the marker while it holds the claim. */
7212
7360
  function stopSessionClaimed(home, o) {
@@ -7224,10 +7372,14 @@ function stopSessionClaimed(home, o) {
7224
7372
  if (lost.gone) before = { present: false, state: "stopped" };
7225
7373
  else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${lost.why ?? e.message}`);
7226
7374
  }
7227
- if (!before.present || before.state === "shell" || before.state === "stopped") return { home: s.home, backend: s.target.backend, stopped: false, alreadyIdle: true, state: before.state, receipt: null };
7375
+ if (!before.present || before.state === "shell" || before.state === "stopped") {
7376
+ recordIdleStop(realHome);
7377
+ return { home: s.home, backend: s.target.backend, stopped: false, alreadyIdle: true, state: before.state, receipt: null };
7378
+ }
7228
7379
  signalling = true;
7229
7380
  receipt = stopHarness(s.target, { graceMs: o.graceMs ?? 20000, kill: o.io?.kill, sleep: o.io?.sleep });
7230
- writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: receipt, retained: ["home", "work", "transcript", "launch"] });
7381
+ // `startId` names the start this stop ended, so a resume never brings it back (lib/session-end.mjs).
7382
+ writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: receipt, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(realHome) });
7231
7383
  appendEvent(realHome, { kind: receipt.exited ? "stopped" : "stop-refused", data: { signal: receipt.signal, waitedMs: receipt.waitedMs, stillRunning: receipt.stillRunning ?? [], state: receipt.state } });
7232
7384
  if (!receipt.exited) throw Object.assign(oatsError("E_SESSION_STOP_FAILED", `${basename(realHome)} was asked to stop (${receipt.signal} to ${receipt.requested.map((r) => `${r.comm} pid ${r.pid}`).join(", ")}) and is still running after ${receipt.waitedMs} ms; nothing was escalated`), { receipt });
7233
7385
  return { home: s.home, backend: s.target.backend, stopped: true, alreadyIdle: false, state: receipt.state, receipt };
@@ -7292,11 +7444,11 @@ function stopRecordedChildren(children, signalled) {
7292
7444
  });
7293
7445
  }
7294
7446
 
7295
- export async function attachInstanceSession(home, { detachKey, onSwept } = {}) {
7447
+ export async function attachInstanceSession(home, { detachKey, statusLine, onSwept } = {}) {
7296
7448
  if (detachKey !== undefined) requireDetachKey(detachKey);
7297
7449
  const s = instanceSessionTarget(home);
7298
7450
  if (!s.target) throw oatsError("E_SESSION_NOT_RUNNING", "instance was not launched");
7299
- return attachSessionTarget(s.target, { detachKey, onSwept });
7451
+ return attachSessionTarget(s.target, { detachKey, statusLine, onSwept });
7300
7452
  }
7301
7453
 
7302
7454
  export function inputInstanceSession(home, text) {
@@ -7432,18 +7584,25 @@ function writeJsonAtomic(path, value, mode) {
7432
7584
 
7433
7585
  // ---------- stopping a harness, selecting on an existing home ----------
7434
7586
  /** The harness processes under a tmux session target: EVERY descendant
7435
- * of the pane's launcher process (the launcher shell itself is left so
7587
+ * of the agent's pane's launcher process (`paneId`, when given, the pane the caller inspected) (the launcher shell itself is left so
7436
7588
  * that, once its command ends, it becomes the fallback shell the start
7437
7589
  * path recognizes); a wrapper that does not exec the harness, the harness
7438
7590
  * and their children are all included, topmost first. Each row:
7439
7591
  * { pid, ppid, pgid, comm, depth }. */
7440
- export function harnessProcesses(target, io) {
7592
+ export function harnessProcesses(target, io, { paneId } = {}) {
7441
7593
  const ps = () => ((io?.exec || execFileSync)("ps", ["-axo", "pid=,ppid=,pgid=,comm="], { encoding: "utf8", timeout: 10000, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }))
7442
7594
  .split("\n").map((l) => l.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.+)$/)).filter(Boolean)
7443
7595
  .map(([, pid, ppid, pgid, comm]) => ({ pid: Number(pid), ppid: Number(ppid), pgid: Number(pgid), comm: basename(comm).replace(/^-/, "") }));
7444
- const row = tmuxOn(target.socket, ["list-panes", "-t", `=${target.session}:=${target.window}`, "-F", "#{pane_pid}"], io).trim().split("\n")[0];
7445
- if (!/^\d+$/.test(row || "")) throw oatsError("E_SESSION_UNKNOWN", "tmux returned no pane process id");
7446
- const panePid = Number(row);
7596
+ // The agent's pane (resolveAgentPane), never the first one listed: a split's pane is never signalled.
7597
+ const panes = tmuxOn(target.socket, ["list-panes", "-t", `=${target.session}:=${target.window}`, "-F", `#{pane_id}\t#{pane_pid}\t#{${AGENT_PANE_OPTION}}`], io)
7598
+ .split("\n").filter(Boolean).map((line) => { const [id, pid, mark = ""] = line.split("\t"); return { paneId: id, pid, mark }; });
7599
+ if (!panes.every((p) => /^%\d+$/.test(p.paneId))) throw oatsError("E_SESSION_UNKNOWN", "invalid tmux pane response");
7600
+ const { pane, error } = resolveAgentPane(panes, target.window);
7601
+ if (error) throw oatsError("E_SESSION_UNKNOWN", `${error}; nothing was signalled`);
7602
+ // `paneId`: the pane the caller inspected. Another one now is no pane to signal on that reading.
7603
+ if (paneId && pane?.paneId !== paneId) throw oatsError("E_SESSION_UNKNOWN", `the agent's pane was ${paneId} and is now ${pane?.paneId ?? "gone"}; nothing was signalled`);
7604
+ if (!/^\d+$/.test(pane?.pid || "")) throw oatsError("E_SESSION_UNKNOWN", "tmux returned no pane process id");
7605
+ const panePid = Number(pane.pid);
7447
7606
  const rows = ps();
7448
7607
  const byParent = new Map();
7449
7608
  for (const r of rows) { if (!byParent.has(r.ppid)) byParent.set(r.ppid, []); byParent.get(r.ppid).push(r); }
@@ -7467,7 +7626,7 @@ export function stopHarness(target, { graceMs = 20000, signal = "SIGTERM", io =
7467
7626
  const idle = (s) => !s.present || s.state === "shell" || s.state === "stopped";
7468
7627
  let before = inspectSessionTarget(target, io);
7469
7628
  if (idle(before)) { wait(250); const again = inspectSessionTarget(target, io); if (idle(again)) return { requested: [], signal, sentAt: null, observedAt: new Date().toISOString(), exited: true, waitedMs: 0, state: again.state, stillRunning: [] }; before = again; }
7470
- const procs = harnessProcesses(target, io);
7629
+ const procs = harnessProcesses(target, io, { paneId: before.paneId });
7471
7630
  if (!procs.length) throw oatsError("E_SESSION_UNKNOWN", `the session reads as ${before.state} but no harness process was found under its pane; nothing was signalled`);
7472
7631
  const requested = [];
7473
7632
  const sentAt = new Date().toISOString();
@@ -7654,8 +7813,38 @@ export function capturedHomeCapabilities(meta) {
7654
7813
  export function preWorkspaceHome(home, what) {
7655
7814
  return oatsError("E_UNSUPPORTED_MODE", `${home} is not a workspace-model home (it records no modules): it was spawned by an earlier kernel — re-spawn it from the deployment (\`oats retire\` still works on it); ${what}`);
7656
7815
  }
7816
+ /** The conversation a resume of `home` continues (feature session-resume, design §4): the newest
7817
+ * transcript of this incarnation whose cwd is the home, in the locations its native-record receipts
7818
+ * name (packages/record lib/last-conversation.mjs), `since` its recorded `createdAt` (a reused name
7819
+ * reuses the path). → { harness, sessionId } or { harness, reason, warning? }: no conversation (R2)
7820
+ * is the ordinary fresh start on TASK.md. Codex is never resumed until a signed-in host proves it
7821
+ * end to end (`resume-unproven`). A lookup that fails is a fresh start too, and says why. */
7822
+ export function resumeConversation(home, meta) {
7823
+ const harness = meta.launch?.harness ?? meta.harness;
7824
+ if (harness === "codex") return { harness, reason: FRESH_REASON.RESUME_UNPROVEN };
7825
+ let found;
7826
+ try { found = lastConversation(home, { harness, since: meta.createdAt }); }
7827
+ catch (e) { return { harness, reason: FRESH_REASON.NO_CONVERSATION, warning: `the last conversation of ${meta.instance} could not be looked up (${e?.message ?? e}): it starts a fresh conversation on TASK.md` }; }
7828
+ return found?.sessionId ? { harness, sessionId: found.sessionId } : { harness, reason: found?.none === "no-receipts" ? FRESH_REASON.NO_RECEIPTS : FRESH_REASON.NO_CONVERSATION };
7829
+ }
7830
+ /** The `resume` object of a `session start --resume` answer (its one producer): what it continued
7831
+ * (resumeConversation's `resume`), and `waiting` when the start succeeded and waits for its human. */
7832
+ export function resumeAnswer(resume, waiting = null) {
7833
+ return { resumed: !!resume.sessionId, ...(resume.sessionId ? {} : { reason: resume.reason }), harness: resume.harness, ...(resume.sessionId ? { sessionId: resume.sessionId } : {}), ...(waiting ? { waiting } : {}) };
7834
+ }
7835
+ /** The pane a resumed launch runs in, from its creation's LAUNCH_PANE_FORMAT output; null when that
7836
+ * output cannot be read (the watch is then skipped: it only reports). */
7837
+ function resumePaneTarget(target, socket, output) {
7838
+ try { return { ...target, ...launchPaneTarget(socket, output) }; } catch { return null; }
7839
+ }
7657
7840
  export function startInstanceSession(home, o = {}) {
7658
7841
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session start needs an absolute instance home");
7842
+ // --resume (feature session-resume) runs the recorded launch as it is: a launch choice cannot go with it.
7843
+ if (o.resume === true) {
7844
+ if (o.restart) throw oatsError("E_BAD_ARGS", "--resume brings back a session that was lost; it is not a restart: use session start --resume");
7845
+ const chosen = [[o.launchConfig !== undefined, "--launch-config"], [o.harness !== undefined, "--harness"], [o.model !== undefined && o.model !== null, "--model"], [o.yolo === true, "--yolo"], [o.yolo === false, "--no-yolo"], [o.reselectLaunch === true, "--reselect-launch"]].filter(([given]) => given).map(([, name]) => name);
7846
+ if (chosen.length) throw oatsError("E_BAD_ARGS", `--resume runs the launch this home recorded; it cannot be combined with ${chosen.join(", ")}; nothing was read or started`);
7847
+ }
7659
7848
  // A home whose record is there and cannot be read is refused before anything of it is read (#896).
7660
7849
  identifiedHomeRecord(home);
7661
7850
  // A home opened in Herdr, or an earlier start that allocated a Herdr pane, is refused before any
@@ -7804,7 +7993,7 @@ export function startInstanceSession(home, o = {}) {
7804
7993
  // shell-script harness). Only its own completion marker proves this
7805
7994
  // is a fallback shell. Never respawn an accepted launch in that gap.
7806
7995
  if (st.present && st.state === "shell") {
7807
- const exited = existsSync(exitedPath) && readFileSync(exitedPath, "utf8").trim() === pending.id;
7996
+ const exited = readStartExited(realHome)?.startId === pending.id;
7808
7997
  if (!exited) throw oatsError("E_SESSION_START_BUSY", `${basename(realHome)} is still starting; refresh its status before retrying`);
7809
7998
  }
7810
7999
  const meta = readMeta();
@@ -7901,6 +8090,18 @@ export function startInstanceSession(home, o = {}) {
7901
8090
  const selected = reselect !== null || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined;
7902
8091
  const hasRecipe = meta.launch && typeof meta.launch === "object";
7903
8092
  let launchPlan = null, launchHooksPass = null, hookMeta, explicitModelFrom = null, warnings = [];
8093
+ // --resume: only a home whose session was lost, read here, under the lock, before any launch hook
8094
+ // runs. Then the conversation it continues, or the reason it starts fresh (resumeConversation).
8095
+ let resume = null;
8096
+ if (o.resume === true) {
8097
+ if (!hasRecipe) throw oatsError("E_LAUNCH_LEGACY", `${meta.instance || realHome} records no launch recipe (an earlier kernel spawned it): re-spawn it from the deployment; nothing was changed`);
8098
+ const observed = recordedState();
8099
+ if (observed.error) { const e = observed.error; throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${meta.instance} is running, so nothing was started: ${String(e.stderr ?? e.message ?? "").trim() || e.message}`); }
8100
+ if (observed.state.present && observed.state.state !== "shell") throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${observed.state.state}); nothing was started`);
8101
+ const end = meta.launched === true ? sessionEndOf(realHome, meta) : "never-launched";
8102
+ if (end !== SESSION_END.LOST) throw oatsError("E_RESUME_NOT_LOST", `${meta.instance} did not lose its session (${end === "never-launched" ? "it was never launched" : `it ${end}`}); --resume brings back only a lost session; nothing was started (an ordinary session start opens a fresh conversation)`);
8103
+ resume = resumeConversation(realHome, meta);
8104
+ }
7904
8105
  if (selected || hasRecipe) {
7905
8106
  // Every start of a home with a recipe (ordinary, model-only, or under a
7906
8107
  // selection) goes through the one planner: recipe shape, the recorded
@@ -7951,7 +8152,16 @@ export function startInstanceSession(home, o = {}) {
7951
8152
  // References recorded for this home must resolve on this host on every
7952
8153
  // start path, and the source variables go to the pane, not the command.
7953
8154
  const recipeForEnv = launchPlan?.recipe || (meta.launch && typeof meta.launch === "object" ? meta.launch : null);
7954
- if (recipeForEnv) { const missing = missingLaunchEnvRefs(recipeForEnv.env, o.env || process.env); if (missing.length) throw oatsError("E_LAUNCH_ENV_MISSING", `this home's launch references ${missing.join(", ")}, not set on this host; nothing was started`); }
8155
+ if (recipeForEnv) { const missing = missingLaunchEnvRefs(recipeForEnv.env, o.env || process.env); if (missing.length) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage(missing)); }
8156
+ // A resume starts only under the values the start it brings back recorded (lib/start-env.mjs): a
8157
+ // changed one refuses, after a missing one; a start with no record to check (an earlier kernel's,
8158
+ // or one that does not read) is resumed and says so once. Ordinary starts never compare.
8159
+ let envUnverified = null;
8160
+ if (resume && recipeForEnv) {
8161
+ const fit = checkStartEnv(realHome, meta.startId, fromEnvNames(recipeForEnv.env), o.env || process.env);
8162
+ if (fit.changed) throw oatsError("E_LAUNCH_ENV_CHANGED", launchEnvChangedMessage(fit.changed));
8163
+ if (fit.unverified) warnings.push(envUnverified = launchEnvUnverifiedWarning(meta.instance));
8164
+ }
7955
8165
  const paneEnv = recipeForEnv ? launchEnvRefs(recipeForEnv, o.env || process.env) : [];
7956
8166
  const paneEnvFlags = paneEnv.flatMap((r) => ["-e", `${r.name}=${r.value}`]);
7957
8167
  checkRoots(); // preparation has run; no backend has been changed
@@ -8021,6 +8231,7 @@ export function startInstanceSession(home, o = {}) {
8021
8231
  const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
8022
8232
  ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
8023
8233
  ...(hookMeta ? { hookMeta } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
8234
+ if (resume?.warning) { warnings.push(resume.warning); appendEvent(realHome, { kind: "launch-warning", data: { message: resume.warning } }); }
8024
8235
  warnings.push(...launchStartNotices(dirname(dirname(dirname(dirname(home)))), launchPlan?.harness || harness, command));
8025
8236
  if (kernelNode().warning) warnings.push(kernelNode().warning);
8026
8237
  const engaged = devChannelEngaged(launchPlan?.harness || harness, command);
@@ -8047,14 +8258,37 @@ export function startInstanceSession(home, o = {}) {
8047
8258
  const startedAt = new Date().toISOString();
8048
8259
  const id = randomUUID();
8049
8260
  if (!engaged) planExtra.launchPrompts = notEngaged(id);
8261
+ // This start's launch environment, recorded just before its pane is made (best effort: never a
8262
+ // refusal). A home without a recipe renders none and records nothing.
8263
+ const recordEnv = () => { if (recipeForEnv) recordStartEnv(realHome, id, fromEnvNames(recipeForEnv.env), o.env || process.env); };
8050
8264
  const makeLaunchController = () => engaged ? promptController(realHome, id, command, o.io, originalHomeIdentity) : null;
8051
8265
  let launchController;
8052
8266
  let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
8267
+ // A resumed Claude session is watched for its resume-cost dialog once it runs (after the record):
8268
+ // the pane's identity is read at its creation, as the controller reads it.
8269
+ const watchResume = !!resume?.sessionId && launchPlan.harness === "claude";
8270
+ let resumeTarget = null;
8053
8271
  checkRoots();
8054
8272
  // The names this launch removes, from the recipe it runs (a preview-aware hook's real run included).
8055
8273
  // A home without a recipe (an earlier kernel's) composes no providers at launch: nothing.
8056
8274
  const removed = launchPlan ? removedLaunchEnv({ declared: launchPlan.declaredEnv, hooksEnv: launchPlan.recipe.hooks?.env, configEnv: launchPlan.recipe.env }) : [];
8057
- const windowCommand = () => paneCommand(`${nativeRecordCommand(command, realHome, launchPlan?.harness || harness)}; oats_start_status=$?; printf '%s\\n' ${shq(id)} > ${shq(exitedPath)}`, removed);
8275
+ // The launch's one native start; every render of its window command reuses it.
8276
+ const nativeStart = prepareNativeStart(realHome, launchPlan?.harness || harness);
8277
+ // What the window runs: the planned command, or, for a resume that found its conversation, the same
8278
+ // recipe rendered with the harness's resume selector and the resume notice. Only the window carries
8279
+ // it: instance.json, the pending receipt and the recipe keep the ordinary launch, so a later start
8280
+ // opens a fresh conversation (and the native-record roots never see a recorded --session).
8281
+ const executedCommand = () => resume?.sessionId ? renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome, resume: { sessionId: resume.sessionId, prompt: RESUME_NOTICE } }) : command;
8282
+ const windowCommand = (scope) => paneCommand(exitMarked(nativeRecordCommand(executedCommand(), realHome, launchPlan?.harness || harness, { start: nativeStart, scope }), id, exitedPath), removed);
8283
+ // Whether the harness runs in a scope of its own (nativeRecordCommand), judged on the pane it
8284
+ // will run in for the command it runs; a warning is said, and is an event once the start is recorded.
8285
+ let unscoped = null;
8286
+ const scopeOn = (pane) => {
8287
+ // The caller's own io (a test's), not the guarded one every start runs with.
8288
+ const scope = agentScopeOn(command, { pane, removed, refs: paneEnv }, rawIo);
8289
+ if (scope.warning) warnings.push(unscoped = scope.warning);
8290
+ return scope.wrapper;
8291
+ };
8058
8292
  let reused = "new";
8059
8293
  const session = target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
8060
8294
  const window = target?.window || meta.tmux?.window || meta.instance;
@@ -8062,11 +8296,14 @@ export function startInstanceSession(home, o = {}) {
8062
8296
  let windowCmd = windowCommand();
8063
8297
  let moved = null;
8064
8298
  // A fallback shell (no harness descendant) or a retained dead pane is
8065
- // the agent's own pane: the command runs there, on the server the home
8066
- // recorded, no other window touched and no option set.
8299
+ // the agent's own pane (resolveAgentPane): the command runs there, on the
8300
+ // server the home recorded, no other window or pane touched and no option
8301
+ // set but that pane's mark.
8067
8302
  const inPlace = state.paneId && (state.present || state.state === "stopped");
8068
8303
  try {
8069
8304
  if (inPlace) {
8305
+ const scope = scopeOn(paneEnvironment(socket, session, o.io, realHome));
8306
+ if (scope) windowCmd = windowCommand(scope);
8070
8307
  launchController = makeLaunchController();
8071
8308
  if (launchController) {
8072
8309
  try {
@@ -8075,11 +8312,13 @@ export function startInstanceSession(home, o = {}) {
8075
8312
  } catch { /* a missing prior capture can never authorize input */ }
8076
8313
  }
8077
8314
  checkRoots();
8315
+ recordEnv();
8078
8316
  writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
8079
8317
  promptDispatched = !!launchController;
8080
8318
  try {
8081
- const output = tmuxOn(socket, ["respawn-pane", "-k", "-t", state.paneId, "-c", realHome, ...paneEnvFlags, windowCmd, ...(launchController ? [";", "display-message", "-p", "-t", state.paneId, LAUNCH_PANE_FORMAT] : [])], o.io, oatsWindowEnvironment());
8319
+ const output = tmuxOn(socket, ["respawn-pane", "-k", "-t", state.paneId, "-c", realHome, ...paneEnvFlags, windowCmd, ...markAgentPane(window, state.paneId), ...(launchController || watchResume ? [";", "display-message", "-p", "-t", state.paneId, LAUNCH_PANE_FORMAT] : [])], o.io, oatsWindowEnvironment());
8082
8320
  if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
8321
+ if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
8083
8322
  }
8084
8323
  catch (e) { throw launchFailure(e); }
8085
8324
  reused = "pane";
@@ -8091,7 +8330,12 @@ export function startInstanceSession(home, o = {}) {
8091
8330
  // on the OATS server, wherever the home was recorded: one socket from here to the record.
8092
8331
  const recordedSocket = socket ? resolve(socket) : null;
8093
8332
  socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
8094
- if (lookAgain(() => paneEnvironment(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
8333
+ // One read of the pane's environment answers both: the executable and the scope.
8334
+ const pane = paneEnvironment(socket, session, o.io, realHome);
8335
+ const looked = lookAgain(() => pane);
8336
+ if (looked) planExtra.launch = launchPlan.recipe;
8337
+ const scope = scopeOn(pane);
8338
+ if (looked || scope) windowCmd = windowCommand(scope);
8095
8339
  let names;
8096
8340
  try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
8097
8341
  catch (e) {
@@ -8102,12 +8346,14 @@ export function startInstanceSession(home, o = {}) {
8102
8346
  target = { backend: "tmux", session, window, socket };
8103
8347
  launchController = makeLaunchController();
8104
8348
  checkRoots();
8349
+ recordEnv();
8105
8350
  writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
8106
8351
  promptDispatched = !!launchController;
8107
8352
  try {
8108
- const output = tmuxOn(socket, ["new-window", "-P", "-F", launchController ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", window, "-c", realHome, ...paneEnvFlags, windowCmd], o.io, oatsWindowEnvironment()).trim();
8353
+ const output = tmuxOn(socket, ["new-window", "-P", "-F", launchController || watchResume ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", window, "-c", realHome, ...paneEnvFlags, windowCmd, ...markAgentPane(window)], o.io, oatsWindowEnvironment()).trim();
8109
8354
  if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
8110
- prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : output, o.io);
8355
+ if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
8356
+ prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : watchResume ? output.split("\t")[0] : output, o.io);
8111
8357
  }
8112
8358
  catch (e) { throw launchFailure(e); }
8113
8359
  if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
@@ -8144,9 +8390,16 @@ export function startInstanceSession(home, o = {}) {
8144
8390
  throw oatsError("E_SESSION_START_INCOMPLETE", `${meta.instance} was started (tmux ${target.session}:${target.window} on ${target.socket}) but its metadata could not be recorded: ${e.message}; the actual target is kept in ${pendingPath} and the next start adopts it instead of allocating another`);
8145
8391
  }
8146
8392
  if (launchPrompts && !promptLaunched(launchPrompts.status)) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
8393
+ // As spawn says it once launched: a start refused before this point leaves no event.
8394
+ if (unscoped) appendEvent(realHome, { kind: "launch-warning", data: { message: unscoped } });
8395
+ if (envUnverified) appendEvent(realHome, { kind: "launch-warning", data: { message: envUnverified } });
8147
8396
  // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
8148
8397
  if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
8149
- return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings] };
8398
+ // A resume answers what it continued. A resumed Claude session that stops at its resume-cost dialog
8399
+ // is a start that succeeded and waits for its human: reported (`waiting`), never answered.
8400
+ const waiting = resumeTarget && watchResumeConfirmation({ transport: launchPromptTransport(o.io), target: resumeTarget, notice: RESUME_NOTICE, ...(o.io?.now ? { now: o.io.now } : {}), ...(o.io?.sleep ? { sleep: o.io.sleep } : {}) }).waiting === RESUME_WAITING.RESUME_CONFIRMATION ? RESUME_WAITING.RESUME_CONFIRMATION : null;
8401
+ const resumed = resume ? { resume: resumeAnswer(resume, waiting) } : {};
8402
+ return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings], ...resumed };
8150
8403
  } finally {
8151
8404
  // A hook may have replaced the home itself. Never follow that replacement
8152
8405
  // to remove a target's lock; keep the original retry state with its home.
@@ -8308,7 +8561,7 @@ function repositoryGitState(repo, { status, cloneSource } = {}) {
8308
8561
  }
8309
8562
  const [gitDir, commonDir] = paths;
8310
8563
  const bytesOf = (path) => {
8311
- try { return createHash("sha256").update(readFileSync(path)).digest("hex"); }
8564
+ try { return hashFile(createHash("sha256"), path).digest("hex"); }
8312
8565
  catch (e) {
8313
8566
  if (e.code === "ENOENT") return null;
8314
8567
  throw oatsError("E_WORK_INSPECTION_FAILED", `could not read ${path}: ${e.message}`);
@@ -8777,7 +9030,7 @@ function copiedGitPathDigest(entry, at) {
8777
9030
  if (entry.copy === "tree") return exactTreeDigest(at);
8778
9031
  const st = statSync(at);
8779
9032
  if (!st.isFile()) throw new Error("it is not a file");
8780
- return createHash("sha256").update(`${st.mode & 0o7777}\0`).update(readFileSync(at)).digest("hex");
9033
+ return hashFile(createHash("sha256").update(`${st.mode & 0o7777}\0`), at).digest("hex");
8781
9034
  } catch (e) {
8782
9035
  if (e?.code === "E_WORK_INSPECTION_FAILED") throw e;
8783
9036
  throw oatsError("E_WORK_INSPECTION_FAILED", `could not read ${at}: ${e.message}`);
@@ -9393,7 +9646,10 @@ function preservedOutputs(work, directory) {
9393
9646
  * the whole home: the stored digest also passes over the kernel's receipts
9394
9647
  * and the harness settings, and reads instance.json through a parse. */
9395
9648
  function copyRecoveryHome(observation, dest) {
9396
- const excludeRoot = observation.homeExclude || new Set(["work"]);
9649
+ // The launch environment's key and the digests made with it never leave the home
9650
+ // (lib/start-env.mjs): a recovery copy leaves them, and any temporary file of theirs, out.
9651
+ const excludeRoot = new Set(observation.homeExclude || ["work"]);
9652
+ for (const name of readdirSync(observation.home)) if (name === START_ENV_FILE || name === START_ENV_KEY_FILE || START_ENV_TMP.test(name)) excludeRoot.add(name);
9397
9653
  copyRecoveryTree(observation.home, dest, { excludeRoot });
9398
9654
  if (storedTreeDigest(observation.home, BASELINE_DIGEST_VERSION, { excludeRoot, instanceHome: true }) !== storedTreeDigest(dest, BASELINE_DIGEST_VERSION, { instanceHome: true })) {
9399
9655
  throw new Error("home recovery verification disagreed with the source");