@awebai/oats 0.68.1 → 0.69.2

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 (99) hide show
  1. package/bin/oats.mjs +180 -36
  2. package/docs/capabilities.md +73 -10
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/configuration.md +68 -2
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
  6. package/docs/design/2026-10-22-module-upgrade.md +1 -1
  7. package/docs/desktop-cli-api.md +600 -25
  8. package/docs/desktop-instance-start.md +59 -3
  9. package/docs/desktop.md +175 -10
  10. package/docs/execution-targets.md +536 -62
  11. package/docs/harness-trust.md +3 -1
  12. package/docs/implementation.md +33 -15
  13. package/docs/integrations.md +2 -2
  14. package/docs/knowledge.md +25 -16
  15. package/docs/oats-local.schema.json +2 -2
  16. package/docs/official-catalog.md +6 -5
  17. package/docs/packages.md +14 -14
  18. package/docs/release-notes/v0.69.0.md +658 -0
  19. package/docs/release-notes/v0.69.1.md +25 -0
  20. package/docs/release-notes/v0.69.2.md +259 -0
  21. package/docs/servers.md +51 -7
  22. package/docs/soul.schema.json +1 -0
  23. package/docs/souls-and-instances.md +46 -9
  24. package/docs/tui.md +177 -21
  25. package/docs/upgrading.md +16 -7
  26. package/docs/workspaces.md +2 -2
  27. package/injects/instance-boundary.md +19 -33
  28. package/injects/work-attached.md +8 -13
  29. package/injects/work-checkout.md +16 -30
  30. package/injects/work-directory.md +9 -15
  31. package/injects/work-workspace.md +8 -19
  32. package/injects/work-worktree.md +18 -33
  33. package/lib/capability-contract.mjs +2 -2
  34. package/lib/core.mjs +496 -127
  35. package/lib/file-pieces.mjs +49 -0
  36. package/lib/instance-background.mjs +54 -0
  37. package/lib/instance-events.mjs +25 -4
  38. package/lib/instance-inspect.mjs +3 -0
  39. package/lib/instance-lifecycle.mjs +35 -0
  40. package/lib/instance-resolution.mjs +3 -2
  41. package/lib/instance-same-work.mjs +67 -0
  42. package/lib/instance-upgrade.mjs +18 -0
  43. package/lib/launch-prompt-fixtures/README.md +62 -0
  44. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  45. package/lib/launch-prompt-fixtures.mjs +49 -0
  46. package/lib/launch-prompt-resume.mjs +55 -0
  47. package/lib/login-environment.mjs +27 -9
  48. package/lib/materialize.mjs +23 -2
  49. package/lib/resolve.mjs +32 -5
  50. package/lib/schedule.mjs +3 -3
  51. package/lib/servers.mjs +136 -27
  52. package/lib/session-end.mjs +82 -0
  53. package/lib/session-input.mjs +43 -9
  54. package/lib/session-resume-contract.mjs +33 -0
  55. package/lib/session-resume.mjs +337 -0
  56. package/lib/session-seen.mjs +163 -0
  57. package/lib/session-viewer.mjs +147 -44
  58. package/lib/soul-composition.mjs +15 -11
  59. package/lib/start-env.mjs +110 -0
  60. package/lib/tmux-server-scope.mjs +139 -14
  61. package/lib/workspace.mjs +41 -6
  62. package/package-catalog.json +11 -5
  63. package/package.json +1 -1
  64. package/packages/client/cli-adapter.mjs +39 -8
  65. package/packages/client/cli-locator.mjs +3 -2
  66. package/packages/client/deployment-data.mjs +16 -0
  67. package/packages/client/deployment-panel.mjs +7 -0
  68. package/packages/client/file-output-exec.mjs +98 -0
  69. package/packages/client/instance-tree.mjs +64 -14
  70. package/packages/client/launch-prompt-outcome.mjs +25 -13
  71. package/packages/client/own-codes.mjs +2 -0
  72. package/packages/client/panel-views.mjs +11 -3
  73. package/packages/client/remote-roster.mjs +5 -1
  74. package/packages/client/roster-sections.mjs +50 -6
  75. package/packages/client/same-work.mjs +49 -0
  76. package/packages/client/session-attach.mjs +35 -5
  77. package/packages/client/session-resume-cli.mjs +64 -0
  78. package/packages/client/session-resume-trigger.mjs +167 -0
  79. package/packages/client/session-resume.mjs +332 -0
  80. package/packages/client/soul-rows.mjs +2 -0
  81. package/packages/client/spawn-apply-contract.mjs +2 -1
  82. package/packages/client/spawn-decision.mjs +4 -1
  83. package/packages/client/spawn-preview-contract.mjs +12 -1
  84. package/packages/client/spawn-preview.mjs +2 -0
  85. package/packages/client/tmux-status.mjs +30 -7
  86. package/packages/client/waiting-on-you.mjs +11 -4
  87. package/packages/client/workspace-step.mjs +17 -5
  88. package/packages/record/lib/last-conversation.mjs +123 -0
  89. package/packages/record/lib/session-roots.mjs +10 -1
  90. package/packages/tui/README.md +2 -2
  91. package/packages/tui/lib/client.mjs +7 -3
  92. package/packages/tui/lib/main.mjs +49 -14
  93. package/packages/tui/lib/model.mjs +146 -55
  94. package/packages/tui/lib/store.mjs +84 -27
  95. package/packages/tui/lib/term/text.mjs +12 -9
  96. package/packages/tui/lib/views/frame.mjs +74 -7
  97. package/packages/tui/lib/views/help.mjs +10 -3
  98. package/packages/tui/lib/views/instances.mjs +41 -3
  99. 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,20 @@ 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 { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
99
+ import { SAME_WORK_FILE, sameWorkOf, writeSameWork } from "./instance-same-work.mjs";
100
+ import { readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
101
+ import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
102
+ import { recordSeen } from "./session-seen.mjs";
103
+ import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, fromEnvNames, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
104
+ import { watchResumeConfirmation } from "./launch-prompt-resume.mjs";
105
+ import { lastConversation } from "../packages/record/lib/last-conversation.mjs";
97
106
  /** The package and capability id grammar (namespaced, lowercase): an id names a
98
107
  * directory (a home's module copy), so no path spelling fits it. */
99
108
  const PACKAGE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
@@ -610,9 +619,10 @@ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME
610
619
  // `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
611
620
  // process's start time on a host with procfs, and the `ps` it runs (lib/worktree-hooks.mjs processStart).
612
621
  "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",
622
+ // The test seams of #915 and #1559: the cgroup the kernel judges itself in, whether the host was
623
+ // booted with systemd, and the directories its systemd-run comes from (lib/tmux-server-scope.mjs,
624
+ // lib/system-tools.mjs).
625
+ "OATS_TEST_CGROUP", "OATS_TEST_SYSTEMD_BOOTED", "OATS_TEST_SYSTEM_TOOL_DIRS",
616
626
  // The test seam of #1421 §3: the naming call's time limit (lib/instance-naming.mjs NAMING_TIMEOUT_MS).
617
627
  "OATS_TEST_NAMING_TIMEOUT_MS"]);
618
628
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
@@ -741,23 +751,46 @@ function incompleteLaunchPrompt(home, startId, target, reason, previous, expecte
741
751
  }
742
752
 
743
753
 
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. */
754
+ /** The machine's launch configurations file (awebai/oats#1506), beside the kernel's other per-user
755
+ * files: `$OATS_HOME_DIR/config/launch-configs.yaml`, else `~/.oats/config/launch-configs.yaml`. */
756
+ // The rule of schedule.mjs's oatsHomeDir, kept here as servers.mjs and deployments.mjs keep it:
757
+ // schedule.mjs imports this module, so importing it back would read its bindings before they exist.
758
+ const oatsHomeDir = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
759
+ export const machineLaunchConfigsFile = () => join(oatsHomeDir(), "config", "launch-configs.yaml");
760
+ /** The machine's launch configurations, validated as a deployment's are → `{ path, configs }`, or null
761
+ * when there is no file. A broken file throws E_LAUNCH_CONFIG_INVALID naming it. */
762
+ export function machineLaunchConfigs() {
763
+ const machine = loadMachineLaunchConfigs(machineLaunchConfigsFile());
764
+ if (machine) validateLaunchConfigs(machine.configs, machine.path);
765
+ return machine;
766
+ }
767
+
768
+ /** The launch configurations effective at `dir`, from two layers, each validated: the machine's
769
+ * (machineLaunchConfigsFile; a missing file is no layer) and the `launch-configs:` of the
770
+ * oats-local.yaml found walking up from `dir` (the deployment; none in reach, the machine's alone
771
+ * apply). A deployment entry replaces the machine's of the same name whole, and its `shadows` names
772
+ * the machine file. A deployment `default: true` for a harness wins: the machine entries of that
773
+ * harness are then not default. `source` is the directory the entry was declared in (a relative
774
+ * `executable` resolves against it). */
749
775
  export function launchConfigsAt(dir) {
750
776
  // Null-prototype: a configuration may legitimately be named constructor or
751
777
  // toString, and membership must never be an inherited property.
752
778
  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: [] };
779
+ const machine = machineLaunchConfigs();
780
+ let found = null;
781
+ try { found = loadLocal(dir); } catch (e) { if (e?.code !== "E_LOCAL_MISSING") throw e; }
782
+ const local = found?.local["launch-configs"];
783
+ if (found) validateLaunchConfigs(local, found.path);
784
+ const entryOf = (name, entry, file, { isDefault, shadows }) => {
785
+ if (!Object.hasOwn(entry, "harness")) noteRuntimeName(`launch-configs.${name}.runtime in ${file}`);
786
+ 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 };
787
+ };
788
+ const localDefaults = new Set(Object.values(local || {}).filter((entry) => entry.default === true).map(launchConfigHarness));
789
+ for (const [name, entry] of Object.entries(machine?.configs || {})) {
790
+ out[name] = entryOf(name, entry, machine.path, { isDefault: entry.default === true && !localDefaults.has(launchConfigHarness(entry)), shadows: [] });
791
+ }
792
+ for (const [name, entry] of Object.entries(local || {})) {
793
+ out[name] = entryOf(name, entry, found.path, { isDefault: entry.default === true, shadows: Object.hasOwn(machine?.configs || {}, name) ? [machine.path] : [] });
761
794
  }
762
795
  return out;
763
796
  }
@@ -1168,33 +1201,43 @@ export function materializedHookCommands(row, home) {
1168
1201
 
1169
1202
  /** Compose, but never mutate, an instance instruction view from canonical soul instructions.
1170
1203
  * `kind` tunes composition: "capability" suppresses the knowledge layer's injection (ephemeral service
1171
- * agents — reviewers, harvesters — carry no episodic memory by design). */
1172
- export function composeInstanceAgentsMd(soulDir, contextDir, soulName, workMode, kind, prepared = undefined) {
1204
+ * agents — reviewers, harvesters — carry no episodic memory by design).
1205
+ * → { text, body, blocks, resolved, oatsCoreDeclared }: `body` is the soul's AGENTS.md; `blocks` are the
1206
+ * capability blocks whose inject already exists (none before materialize), in the resolution's
1207
+ * instructionOrder, then the kernel's instance-boundary and work-mode blocks, last. */
1208
+ export function composeInstanceAgentsMd(soulDir, contextDir, soulName, workMode, kind, prepared = undefined, { launchConfigs = true } = {}) {
1173
1209
  const agentsMd = join(soulDir, "AGENTS.md");
1174
1210
  if (!existsSync(agentsMd)) throw new Error(`canonical soul instructions missing: ${agentsMd}`);
1175
1211
  // Workspace model only (lead decision c3-1): the capability set is the prepared
1176
1212
  // resolution's modules, materialized into the home by the caller. There is no
1177
1213
  // scope configuration to compose from.
1178
1214
  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);
1215
+ const resolved = resolvedFromPrepared(prepared, contextDir, { launchConfigs });
1180
1216
  const wanted = [];
1181
1217
  // Operational knowledge is a capability (oats.core / oats.setup) the resolution
1182
1218
  // carries like any other; the kernel composes no operational block of its own.
1183
1219
  const oatsCoreDeclared = (prepared.resolution?.modules || []).some((m) => m.name === "oats.core" || m.name === "oats.setup");
1184
- // The home/work boundary is runtime-neutral and mode-independent: every
1185
- // instance — including capability service agents in attached mode — needs to
1186
- // know which directory is its brain and which is the repository, and where
1187
- // `aw`/`oats` resolve their scope from. It precedes the mode block, which then
1188
- // adds only that mode's ownership and branch rules.
1220
+ // Capability injects first, in the resolution's instruction order (the soul's
1221
+ // listing, then the workspace defaults'), as materialize writes them.
1222
+ const order = Array.isArray(prepared.resolution?.instructionOrder) ? prepared.resolution.instructionOrder : [];
1223
+ const rank = (cap) => { const i = order.indexOf(cap.id); return i < 0 ? order.length : i; };
1224
+ const capabilities = resolved.capabilities.map((cap, i) => ({ cap, i })).sort((a, b) => rank(a.cap) - rank(b.cap) || a.i - b.i).map(({ cap }) => cap);
1225
+ for (const cap of capabilities) {
1226
+ if (cap.inject && existsSync(cap.inject)) wanted.push([`capability:${cap.id}`, cap.inject]);
1227
+ }
1228
+ // The kernel's blocks close the document. The home/work boundary is
1229
+ // runtime-neutral and mode-independent: every instance — including capability
1230
+ // service agents in attached mode — needs to know which directory is its
1231
+ // brain and which is the repository, and where `aw`/`oats` resolve their
1232
+ // scope from. It precedes the mode block, which then adds only that mode's
1233
+ // ownership and branch rules.
1189
1234
  const boundaryInject = packagedInject("instance-boundary");
1190
1235
  if (boundaryInject && existsSync(boundaryInject)) wanted.push(["kernel:instance-boundary", boundaryInject]);
1191
1236
  const workModeInject = packagedInject(`work-${workMode || "checkout"}`);
1192
1237
  if (workModeInject && existsSync(workModeInject)) wanted.push([`work-mode:${workMode || "checkout"}`, workModeInject]);
1193
- for (const cap of resolved.capabilities) {
1194
- if (cap.inject && existsSync(cap.inject)) wanted.push([`capability:${cap.id}`, cap.inject]);
1195
- }
1196
1238
  const blocks = wanted.map(([source, file]) => ({ source, file, content: readFileSync(file, "utf8").trim() }));
1197
- return { text: renderInstructionText(readFileSync(agentsMd, "utf8"), blocks), blocks, resolved, oatsCoreDeclared };
1239
+ const body = readFileSync(agentsMd, "utf8");
1240
+ return { text: renderInstructionText(body, blocks), body, blocks, resolved, oatsCoreDeclared };
1198
1241
  }
1199
1242
 
1200
1243
  /** Per slot `{ capability, from }` (from: "soul" | "workspace" | "team:<label>", the Desktop's
@@ -1207,15 +1250,16 @@ function layerRows(resolution) {
1207
1250
  * (manifest/settings/origin/trust known now; skills and inject paths point into
1208
1251
  * the home, which does not exist yet, and are rebuilt once materialize has
1209
1252
  * 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) {
1253
+ * configurations (left out with `launchConfigs: false`, for a composition that launches nothing).
1254
+ * `prepared.capabilityRows` is honoured only when non-empty. */
1255
+ export function resolvedFromPrepared(prepared, contextDir, { launchConfigs = true } = {}) {
1212
1256
  return {
1213
1257
  capabilities: Array.isArray(prepared.capabilityRows) && prepared.capabilityRows.length ? prepared.capabilityRows : plannedCapabilityRows(prepared.resolution),
1214
1258
  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
1259
  payloads: prepared.resolution.payloads ?? {},
1216
1260
  teams: prepared.resolution.teams ?? [], defaultTeam: prepared.resolution.defaultTeam ?? null, teamsSource: "live",
1217
1261
  layers: layerRows(prepared.resolution),
1218
- launchConfigs: launchConfigsAt(contextDir || prepared.deployment),
1262
+ ...(launchConfigs ? { launchConfigs: launchConfigsAt(contextDir || prepared.deployment) } : {}),
1219
1263
  };
1220
1264
  }
1221
1265
 
@@ -1337,6 +1381,19 @@ export function planInstanceResources({ resolved, soulDir, agent, contextDir, co
1337
1381
  return expected;
1338
1382
  }
1339
1383
 
1384
+ /** Reorder `expected`'s instruction-block entries, in the slots they hold, to `blocks`' order
1385
+ * (the written AGENTS.md's), so the record lists them as the file has them; an entry `blocks`
1386
+ * does not name keeps its relative place after them. Mutates and returns `expected`. */
1387
+ export function orderInstructionBlocks(expected, blocks) {
1388
+ const key = (source, file) => `${source}\u0000${file}`;
1389
+ const rank = new Map(blocks.map((b, i) => [key(b.source, b.file), i]));
1390
+ const at = (r) => rank.get(key(r.source, r.declared)) ?? blocks.length;
1391
+ const slots = [], rows = [];
1392
+ expected.forEach((r, i) => { if (r.type === "instruction-block") { slots.push(i); rows.push({ r, i }); } });
1393
+ rows.sort((a, b) => at(a.r) - at(b.r) || a.i - b.i).forEach(({ r }, j) => { expected[slots[j]] = r; });
1394
+ return expected;
1395
+ }
1396
+
1340
1397
  // ---------- harness packages (satisfied by a harness's own package manager) ----------
1341
1398
 
1342
1399
  /** pi's config dir, officially relocatable via PI_CODING_AGENT_DIR (pi
@@ -2467,10 +2524,10 @@ function paneEnvironment(socket, session, io, cwd) {
2467
2524
  const tmuxAt = `tmux -S ${shellWord(socket)}`;
2468
2525
  const decide = ({ env, omitted, cleared }, name, source, holder, scope) => {
2469
2526
  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` };
2527
+ if (env === null) return { source, problem: `${source} could not be read`, unreadable: true, remedy: `make \`${tmuxAt} show-environment ${scope} -s\` answer` };
2471
2528
  if (Object.hasOwn(env, name)) return { value: env[name], source };
2472
2529
  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 };
2530
+ 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
2531
  return null;
2475
2532
  };
2476
2533
  const answers = new Map();
@@ -2729,7 +2786,14 @@ function oatsTmuxWindows(session) {
2729
2786
  * the command with the server's `default-shell -c` (the user's shell: sh, bash and zsh all take
2730
2787
  * `unset NAME…;`), and the fallback shell it execs inherits the result. Never persisted: the
2731
2788
  * recorded command (meta.command) is the launch command alone. */
2789
+ /** A launch's command followed by its exit marker (lib/session-end.mjs): the start id and the harness's
2790
+ * exit status, written when the harness ends, by spawn's window and start's alike. */
2791
+ const exitMarked = (command, startId, path) => `${command}; oats_start_status=$?; printf '{"startId":"%s","status":%d}\\n' ${shq(startId)} "$oats_start_status" > ${shq(path)}`;
2732
2792
  const paneCommand = (command, removed = []) => `unset ${["COLORFGBG", ...removed].join(" ")}; ${command}; exec "\${SHELL:-/bin/zsh}"`;
2793
+ /** The tail that marks the pane a launch creates (new-window: the new pane, tmux's current one after
2794
+ * it) or respawns (`paneId`) as the agent's (AGENT_PANE_OPTION), chained into the launch's own tmux
2795
+ * call. `-q`: a mark that cannot be set never fails the launch; readers then find the pane by id. */
2796
+ const markAgentPane = (name, paneId) => [";", "set-option", "-q", "-p", ...(paneId ? ["-t", paneId] : []), AGENT_PANE_OPTION, name];
2733
2797
  /** The sizing options on one window, each best effort: this command's failure is ignored, nothing is
2734
2798
  * retried elsewhere and nothing global is written. */
2735
2799
  function sizeWindow(socket, windowId, io) {
@@ -3048,6 +3112,10 @@ export const CODEX_TASK_PROMPT = "Read TASK.md in this directory first: it is yo
3048
3112
  /** The prompt each harness gets, so the task's text never travels in argv: Claude Code inlines an
3049
3113
  * `@file` mention; codex is pointed at the file. pi takes `@TASK.md` among its own arguments. */
3050
3114
  const TASK_PROMPT = Object.freeze({ claude: "@TASK.md", codex: CODEX_TASK_PROMPT });
3115
+ /** The prompt a resumed session gets in place of the task prompt (feature session-resume, R1): without
3116
+ * it, a harness cut off mid-turn would sit idle until someone types. It states only what holds for
3117
+ * every instance a resume brings back. */
3118
+ 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
3119
 
3052
3120
  /** The executable a launch uses: a configuration's declared one (a bare name
3053
3121
  * on PATH; a path against the deployment directory when relative) or the
@@ -3379,8 +3447,14 @@ export function launchFolderTrust({ harness, home, meta, yolo, launch, env = pro
3379
3447
  * deployment root or an ancestor in Codex's config (lib/harness-trust.mjs),
3380
3448
  * which Codex itself does not apply to the homes below it. Codex's own form
3381
3449
  * 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 }) {
3450
+ * honoured (codex-cli 0.157.1).
3451
+ *
3452
+ * `resume` ({ sessionId, prompt }, feature session-resume): the same launch continuing the harness's
3453
+ * own conversation. Claude takes `--resume <id>` among its own options, before contributed ones, and
3454
+ * the prompt after `--` in place of the task; pi takes `--session <id>`, and the prompt as the
3455
+ * positional where `@TASK.md` stands. Codex has none yet. Only the executed window command is rendered
3456
+ * so: what is persisted stays the ordinary launch. */
3457
+ export function renderLaunchRecipe(recipe, { home, instance, redact = false, trustHome = false, resume = null }) {
3384
3458
  const { harness, executable, model, yolo } = recipe;
3385
3459
  const cfgArgs = (recipe.args || []).map(shq).join(" ");
3386
3460
  const hookArgs = recipe.hooks?.launch?.[harness] || "";
@@ -3396,8 +3470,11 @@ export function renderLaunchRecipe(recipe, { home, instance, redact = false, tru
3396
3470
  }
3397
3471
  let cmdline;
3398
3472
  if (harness === "claude") {
3399
- cmdline = `${shq(executable)}${yolo ? " --dangerously-skip-permissions" : ""}${model ? ` --model ${shq(model)}` : ""}${tail} -- ${shq(TASK_PROMPT.claude)}`;
3473
+ 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
3474
  } else if (harness === "codex") {
3475
+ // No resume selector until a Codex resume is proven end to end on a signed-in host: start
3476
+ // --resume takes a Codex home's fresh path (resume-unproven) and never asks for one.
3477
+ if (resume) throw new Error("renderLaunchRecipe: codex has no resume rendering");
3401
3478
  // Codex compares the key with its own working directory, in its on-disk spelling.
3402
3479
  const codexTrust = `projects={${JSON.stringify(canonicalHomePath(home))}={trust_level="trusted"}}`;
3403
3480
  // Codex may run tool commands outside the session's process (its shared app-server daemon),
@@ -3411,7 +3488,7 @@ export function renderLaunchRecipe(recipe, { home, instance, redact = false, tru
3411
3488
  // .agents/skills up the tree, so the instance's copied capability skills are
3412
3489
  // found from cwd=home) and context files stay ambient. OATS contributes only
3413
3490
  // 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}`;
3491
+ 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
3492
  }
3416
3493
  return `${env.map((e) => e.reference ? `${e.name}="$${LAUNCH_REF_PREFIX}${e.name}"` : `${e.name}=${shq(e.value)}`).join(" ")} ${cmdline}`;
3417
3494
  }
@@ -3419,14 +3496,51 @@ export function renderLaunchRecipe(recipe, { home, instance, redact = false, tru
3419
3496
  /** Execution, not preview: mark pending before dispatch, then resolve native
3420
3497
  * storage inside the backend shell under the actual command environment.
3421
3498
  * 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) {
3499
+ * with the home's kernel shim first on PATH (every launch runs through here).
3500
+ * `start` is the launch's one native start (prepareNativeStart), prepared once and reused by every
3501
+ * render of that launch, so that the command dispatched is the only one with a pending receipt.
3502
+ * With `scope` (agentScopeOn's wrapper), that shell runs in a systemd scope of its own, named per
3503
+ * launch (lib/tmux-server-scope.mjs agentScope): execution only, like paneCommand's `unset`; the
3504
+ * persisted command, the recipe and the receipts never carry it. The wrapper is chosen only after
3505
+ * the probe started a scope in this pane's environment, so a failed systemd-run is not the
3506
+ * harness's exit. What remains is a race: systemd-run failing between the probe and the pane. The
3507
+ * pane's shell then reads exit status 1, the scope runner's: an ordinary exit (below 128, no
3508
+ * signal), which the start's exit marker (.oats-start-exited) reads as a harness that exited, never
3509
+ * one to relaunch, so the race cannot cause a spurious resume. No home file tells the two apart. */
3510
+ function nativeRecordCommand(command, home, harness, { start, scope } = {}) {
3424
3511
  const { tokens, binary } = parseLaunchCommand(command);
3425
3512
  const args = tokens.slice(binary + 1).map(t => t.value ?? t.text);
3426
- const id = prepareNativeStart(home, harness);
3513
+ const id = start ?? prepareNativeStart(home, harness);
3427
3514
  const recorder = join(PKG_ROOT, "packages", "record", "bin", "record-native-start.mjs");
3428
3515
  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)}`;
3516
+ const wrapper = scope ? agentScopeArgv(scope, agentScopeUnit({ home })).map(shq) : [];
3517
+ return `${[...shimPathPrefix(tokens, binary, home), ...wrapper].join(" ")} /bin/sh -c ${shq(inner)}`;
3518
+ }
3519
+ /** The agent's scope of the launch of `command` in a pane with `pane`'s environment (paneEnvironment)
3520
+ * → agentScope's answer. The values the probe gets for SCOPE_ENV_NAMES are the ones systemd-run
3521
+ * will run with: what the command's environment prefix sets (a literal, or a reference whose source
3522
+ * is one of `refs`, the pane's `-e` values, else the pane's own), else nothing for a name the launch
3523
+ * removes (paneCommand's `unset`), else the pane's. `io` is a test's (agentScope). */
3524
+ function agentScopeOn(command, { pane, removed = [], refs = [] }, io) {
3525
+ return agentScope({ io, paneEnv: () => {
3526
+ const { tokens, binary } = parseLaunchCommand(command);
3527
+ const prefix = tokens.slice(0, binary);
3528
+ const given = new Map(refs.map((r) => [r.name, r.value]));
3529
+ const ofPane = (name) => {
3530
+ if (removed.includes(name)) return {};
3531
+ const answer = pane.of(name);
3532
+ 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}`})` };
3533
+ return typeof answer.value === "string" ? { value: answer.value } : {};
3534
+ };
3535
+ const env = {};
3536
+ for (const name of SCOPE_ENV_NAMES) {
3537
+ const set = prefix.findLast((t) => t.name === name);
3538
+ const answer = !set ? ofPane(name) : set.kind === "env" ? { value: set.value } : given.has(set.source) ? { value: given.get(set.source) } : ofPane(set.source);
3539
+ if (answer.reason) return answer;
3540
+ if (answer.value) env[name] = answer.value;
3541
+ }
3542
+ return { env };
3543
+ } });
3430
3544
  }
3431
3545
 
3432
3546
 
@@ -3770,7 +3884,7 @@ export async function suggestSpawnName({ dir = process.cwd(), soul, task, harnes
3770
3884
  if (askedModel !== undefined && (typeof askedModel !== "string" || !askedModel)) throw oatsError("E_BAD_ARGS", "--model needs a model id");
3771
3885
  let deployment = null;
3772
3886
  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);
3887
+ const configs = launchConfigsAt(deployment ?? dir);
3774
3888
  let config = null;
3775
3889
  if (named !== undefined && named !== "none") {
3776
3890
  if (typeof named !== "string" || !Object.hasOwn(configs, named)) throw launchConfigUnknown({ name: named, from: "flag", at: "--launch-config" });
@@ -3947,7 +4061,7 @@ function* spawnBody(root, agent, o = {}) {
3947
4061
  if (prior.spawnCompleted !== true) throw unconfirmedSpawn(Object.assign(oatsError("E_SPAWN_INCOMPLETE", `${prior.instance} was created for this key but its spawn did not complete (launch or lineage unfinished); inspect it with oats session inspect --home ${prior.home} — do not spawn again`), { instance: prior.instance, home: prior.home, launched: prior.launched === true ? "unknown" : false }));
3948
4062
  // The receipt's warnings that are facts of the composition (a hook event this kernel ignores),
3949
4063
  // from the home's module copies: nothing runs again, and the captured composition is unchanged.
3950
- return { ...prior, replayed: true, launch: undefined, command: undefined, wake: prior.wake ?? { requested: null, saved: null, error: null }, warnings: replayedContractWarnings(prior.home) };
4064
+ return { ...prior, background: readInstanceBackground(prior.home), replayed: true, launch: undefined, command: undefined, wake: prior.wake ?? { requested: null, saved: null, error: null }, warnings: replayedContractWarnings(prior.home) };
3951
4065
  }
3952
4066
  }
3953
4067
 
@@ -3993,6 +4107,7 @@ function* spawnBody(root, agent, o = {}) {
3993
4107
  if (relation === "unrelated" && relativeTo) throw new Error(`relation "unrelated" takes no relativeTo`);
3994
4108
  if (relation && relation !== "unrelated" && !relativeTo) throw new Error(`relation "${relation}" needs a relative-to instance`);
3995
4109
  if (typeof o.relativeRoot === "string" && o.relativeRoot.trim() && !relativeTo && !legacyParent) throw new Error(`relativeRoot only qualifies relativeTo/parent`);
4110
+ if (o.sameWork !== undefined && typeof o.sameWork !== "boolean") throw oatsError("E_BAD_ARGS", "sameWork must be true or false");
3996
4111
  if (!relation && legacyParent) { relation = "child"; relativeTo = legacyParent; }
3997
4112
  if (relation === "unrelated") { relation = undefined; relativeTo = undefined; }
3998
4113
 
@@ -4123,6 +4238,12 @@ function* spawnBody(root, agent, o = {}) {
4123
4238
  if (anchorMeta?.siblingInstance) siblingInstance = anchorMeta.siblingInstance;
4124
4239
  }
4125
4240
  if (!relation && attachedOwner && attachedOwner !== instance) parentInstance = attachedOwner;
4241
+ // Feature instance-same-work: the flag binds the parent the new home records, whichever relation gave
4242
+ // it (child, a sibling of a non-root, --relation parent under a parented anchor, attached). None: refused
4243
+ // here, before any home, worktree or hook, a preview's included.
4244
+ if (o.sameWork === true && !(parentInstance && parentInstance !== instance)) {
4245
+ throw oatsError("E_BAD_ARGS", `--same-work needs a parent: ${instance} would record no parent instance${relation ? ` (relation ${relation}${relativeTo ? ` to ${relativeTo}` : ""})` : ""}; spawn it with --parent <instance>, or without --same-work; nothing was spawned`);
4246
+ }
4126
4247
  // K5 §4 — child-spawn permission is ENFORCED here, by the spawn route. The
4127
4248
  // parent's recorded policy (instance.json policy.childSpawns) says whether
4128
4249
  // it may have children; off refuses, attributed to that policy and its
@@ -4230,6 +4351,12 @@ function* spawnBody(root, agent, o = {}) {
4230
4351
  const composition = composeInstanceAgentsMd(soulDir, repoAbs, agent.name, work, agent.kind, o.prepared);
4231
4352
  const resolvedCfg = composition.resolved;
4232
4353
  const yolo = resolveYolo(o.yolo ?? launchSelection.configuredYolo);
4354
+ // Feature instance-background (#1579): the flag, else the soul's `background:`, else not background.
4355
+ // `backgroundFrom` names the layer that declared it, and is absent when neither did.
4356
+ if (o.background !== undefined && typeof o.background !== "boolean") throw oatsError("E_BAD_ARGS", "background must be true or false");
4357
+ const soulBackground = o.prepared?.soulEntry?.definition?.background;
4358
+ const backgroundFrom = o.background !== undefined ? "flag" : typeof soulBackground === "boolean" ? "soul" : null;
4359
+ const background = o.background ?? soulBackground === true;
4233
4360
  const expectedResources = planInstanceResources({ resolved: resolvedCfg, soulDir, agent, contextDir: repoAbs, composition, prepared: o.prepared });
4234
4361
  // Harness extensions selected by ACTIVE capabilities for THIS instance's
4235
4362
  // harness. Strict launch disables ambient extension discovery, so each one has
@@ -4350,7 +4477,9 @@ function* spawnBody(root, agent, o = {}) {
4350
4477
  const buildDecision = () => {
4351
4478
  const d = { instance, home, branch: plannedBranch, base: plannedBase,
4352
4479
  effective: { repo: repoAbs, work, harness, model: model || null, launchConfig: launchConfig?.name ?? null, yolo: yolo ?? null, backend, // backend regardless of --no-launch: the decision is what WOULD launch
4353
- childSpawns: ownChildPolicy.allowed, relation: relation ? { kind: relation, anchor: { instance: relativeTo ?? null, agentsRoot: anchorHome ? dirname(dirname(dirname(anchorHome))) : null } } : null } };
4480
+ childSpawns: ownChildPolicy.allowed, relation: relation ? { kind: relation, anchor: { instance: relativeTo ?? null, agentsRoot: anchorHome ? dirname(dirname(dirname(anchorHome))) : null } } : null,
4481
+ // Feature instance-background: bound only when true, so a decision without it keeps its revision.
4482
+ ...(background ? { background: true } : {}) } };
4354
4483
  // Workspace model: the decision binds WHAT WILL BE MATERIALIZED — the
4355
4484
  // resolution revision (member commits, package commits, payloads). A member
4356
4485
  // that moved between preview and apply changes it → E_DECISION_STALE.
@@ -4400,7 +4529,8 @@ function* spawnBody(root, agent, o = {}) {
4400
4529
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
4401
4530
  decision, preflight,
4402
4531
  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,
4532
+ harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigSource: launchConfig?.source ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
4533
+ background, ...(backgroundFrom ? { backgroundFrom } : {}),
4404
4534
  launch: launchReport({ declared: launchChoice.declared, harness, model, launchConfig: launchConfig?.name, from: launchChoice.from, at: launchChoice.at }),
4405
4535
  branch: plannedBranch, base: plannedBase, worktree: work === "worktree" ? join(home, "work") : null,
4406
4536
  // #796: the `worktree` hooks a worktree-mode spawn would fire, in the order they run; null in other modes.
@@ -4487,10 +4617,11 @@ function* spawnBody(root, agent, o = {}) {
4487
4617
  // and instance.json all read the rebuilt rows from here on.
4488
4618
  let materializeOutcome = null;
4489
4619
  if (o.prepared) {
4490
- // The kernel's composed text (soul AGENTS.md + kernel/work-mode injects) is
4491
- // the body materialize composes the capability injects onto.
4620
+ // The soul's AGENTS.md is the body materialize composes onto: the capability
4621
+ // injects in the resolution's instruction order, then the kernel's blocks.
4492
4622
  try {
4493
- materializeOutcome = yield () => (o.materialize ?? materializePreparedDefault)({ ...o.prepared, soulAgentsMd: composition.text, soulDir }, home);
4623
+ const kernelBlocks = composition.blocks.filter((b) => !b.source.startsWith("capability:"));
4624
+ materializeOutcome = yield () => (o.materialize ?? materializePreparedDefault)({ ...o.prepared, soulAgentsMd: composition.body, blocks: kernelBlocks, soulDir }, home);
4494
4625
  const rows = (typeof o.prepared.toCapabilityRows === "function" ? o.prepared.toCapabilityRows : toCapabilityRows)(o.prepared.resolution, home);
4495
4626
  if (!Array.isArray(rows)) throw new Error("toCapabilityRows returned no rows");
4496
4627
  for (const row of rows) row.hooks = materializedHookCommands(row, home);
@@ -4514,6 +4645,12 @@ function* spawnBody(root, agent, o = {}) {
4514
4645
  expectedResources.push({ type: "instruction-block", source, declared: file, path: file, materialized: true });
4515
4646
  known.add(`${source}\u0000${file}`);
4516
4647
  }
4648
+ // The record lists the blocks in the order the written file has them
4649
+ // (capability injects, then the kernel's); a block not found keeps its place after them.
4650
+ const bodyEnd = composition.body.replace(/\n*$/, "\n").length;
4651
+ const at = (b) => { const i = written.indexOf(`<!-- oats:${b.source} src=${b.file} -->\n`, bodyEnd); return i < 0 ? Infinity : i; };
4652
+ composition.blocks = composition.blocks.map((b, i) => ({ b, i, at: at(b) })).sort((x, y) => (x.at === y.at ? x.i - y.i : x.at < y.at ? -1 : 1)).map(({ b }) => b);
4653
+ orderInstructionBlocks(expectedResources, composition.blocks);
4517
4654
  // The expected resources deferred to materialize (module skills/injects)
4518
4655
  // are now resolvable: fill their paths so the record and the completeness
4519
4656
  // check compare promised against landed.
@@ -5039,6 +5176,9 @@ You are instance "${instance}" of agent "${agent.name}".
5039
5176
  - Work tree: ./work — ${workDesc}
5040
5177
  - Do all repository work inside ./work. Read ./work/AGENTS.md or ./work/CLAUDE.md first if present.${briefLines}${harness === "codex" ? "\n## Harness notification delivery\n\nNative Codex has no built-in messaging channel. Follow the explicit delivery briefing for this instance from your messaging capability, if present; it may arrange notification through this terminal. Shared channel instructions alone do not establish that delivery is configured. Without an instance delivery briefing, check your messaging capability's inbox and pending commands at task boundaries or when the operator asks; do not assume messages will wake this session.\n" : ""}
5041
5178
  ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spawn time — await instructions.\n"}`, { mode: 0o600 }); // human text: the owner's only
5179
+ // Feature instance-background: the home's record, beside its other files, so the spawn's rollback
5180
+ // (which removes the home) leaves nothing of it.
5181
+ if (background) writeInstanceBackground(home, true);
5042
5182
 
5043
5183
  // Launch command. Spawn IS session start: the recipe is persisted in
5044
5184
  // instance.json beside its rendering, which is executed in the instance's
@@ -5164,10 +5304,15 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5164
5304
  meta.defaultTeam = structuredClone(o.prepared.resolution.defaultTeam ?? null);
5165
5305
  }
5166
5306
  const spawnWarnings = warnings;
5307
+ // Feature instance-same-work: bound to the parent the home records, written before the launch so that
5308
+ // the instance's first status shows it; the home's removal on a rollback takes it with the rest.
5309
+ if (o.sameWork === true && meta.parentInstance) writeSameWork(home, meta.parentInstance);
5167
5310
 
5168
5311
  spawnTmux = meta.tmux;
5169
5312
  if (work === "directory") assertDirectoryRoots(home, homeReal);
5170
- let executionCommand = launch ? nativeRecordCommand(cmdline, home, harness) : null;
5313
+ // The launch's one native start, prepared before anything is created; every render below reuses it.
5314
+ const nativeStart = launch ? prepareNativeStart(home, harness) : null;
5315
+ let unscoped = null; // the harness's agent-scope warning, an event once the launch is recorded
5171
5316
  if (launch) {
5172
5317
  // The session on the OATS server, then everything on the one socket that answered: the collision
5173
5318
  // check, the records, the window and (in compensateSpawn) its removal.
@@ -5175,7 +5320,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5175
5320
  // The environment this window's pane will actually start with, whoever created the session and
5176
5321
  // with whatever environment (a race lost to another creator, a session that overrides a name):
5177
5322
  // 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);
5323
+ const pane = paneEnvironment(socket, session, undefined, home);
5324
+ const actualEnv = launchEnvOn(pane, removedEnv);
5179
5325
  // The harness looked up again on that PATH. Not there: refused, and the spawn is compensated.
5180
5326
  // Found elsewhere than the preflight found it: the launch runs that one.
5181
5327
  if (executable.lookup) {
@@ -5186,7 +5332,6 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5186
5332
  if (actual.path !== recipe.executable) {
5187
5333
  recipe.executable = actual.path;
5188
5334
  meta.command = cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
5189
- executionCommand = nativeRecordCommand(cmdline, home, harness);
5190
5335
  }
5191
5336
  }
5192
5337
  // The package gate judged the pane this spawn expected (`probed`). When the pane it got differs
@@ -5207,7 +5352,6 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5207
5352
  if (actualTrust.warning) spawnWarnings.push(actualTrust.warning);
5208
5353
  if (actualTrust.trustHome !== folderTrust.trustHome) {
5209
5354
  meta.command = cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: actualTrust.trustHome });
5210
- executionCommand = nativeRecordCommand(cmdline, home, harness);
5211
5355
  }
5212
5356
  folderTrust = actualTrust;
5213
5357
  let present;
@@ -5217,6 +5361,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5217
5361
  meta.tmux.socket = socket;
5218
5362
  meta.launched = true;
5219
5363
  promptStartId = randomUUID();
5364
+ // The spawn's launch is the home's first start: its id names it in the exit marker and a stop's
5365
+ // receipt (lib/session-end.mjs), as a start's does.
5366
+ meta.startId = promptStartId;
5220
5367
  const engaged = devChannelEngaged(harness, cmdline);
5221
5368
  if (engaged) warnings.push(DEV_CHANNEL_STATEMENT);
5222
5369
  else meta.launchPrompts = notEngaged(promptStartId);
@@ -5225,10 +5372,17 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5225
5372
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n");
5226
5373
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: true, tmux: meta.tmux });
5227
5374
  clearSpawnInProgressMarker();
5375
+ // The first start's launch environment (lib/start-env.mjs), after the baseline, as a start records its own.
5376
+ recordStartEnv(home, promptStartId, fromEnvNames(recipe.env), process.env);
5228
5377
  // Wrap the command so the window drops into an interactive shell when the
5229
5378
  // 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}`]);
5379
+ const refs = launchEnvRefs(recipe, process.env);
5380
+ // On the same pane, for the command it runs: whether the harness runs in a scope of its own.
5381
+ const scope = agentScopeOn(cmdline, { pane, removed: removedEnv, refs });
5382
+ if (scope.warning) spawnWarnings.push(unscoped = scope.warning);
5383
+ // The exit marker records how this launch's harness ended (lib/session-end.mjs), as a start's does.
5384
+ const windowCmd = paneCommand(exitMarked(nativeRecordCommand(cmdline, home, harness, { start: nativeStart, scope: scope.wrapper }), promptStartId, join(home, START_EXITED_FILE)), removedEnv);
5385
+ const paneEnvFlags = refs.flatMap((r) => ["-e", `${r.name}=${r.value}`]);
5232
5386
  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
5387
  // Only a launch that engages the confirmation needs lineage committed before
5234
5388
  // dispatch: its uncertain input outcome retains the new process and parent
@@ -5239,7 +5393,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5239
5393
  promptDispatched = !!controller;
5240
5394
  let windowId;
5241
5395
 
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(); }
5396
+ 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
5397
  catch (e) { throw launchFailed("new-window", "the window command was refused", e); }
5244
5398
  if (controller) { promptTarget = { ...meta.tmux, ...launchPaneTarget(socket, windowId) }; windowId = promptTarget.windowId; }
5245
5399
  try { prepareAgentWindow(socket, windowId); }
@@ -5269,12 +5423,13 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5269
5423
 
5270
5424
  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
5425
  if (launch) appendEvent(home, { kind: "launched", data: { harness, backend, launchConfig: launchConfig?.name ?? null } });
5426
+ if (unscoped) appendEvent(home, { kind: "launch-warning", data: { message: unscoped } });
5272
5427
  if (o.idempotencyKey !== undefined) {
5273
5428
  // Only now is the spawn a finished receipt a same-key retry may replay.
5274
5429
  meta.spawnCompleted = true;
5275
5430
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n"); // a kernel-owned field: the baseline fingerprint ignores it
5276
5431
  }
5277
- return deliver({ ...meta, ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: launch ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(session)}` : `oats session attach --home ${shellWord(home)}`, warnings: spawnWarnings.length ? spawnWarnings : undefined, ...(naming ? { naming } : {}) });
5432
+ return deliver({ ...meta, background, ...(backgroundFrom ? { backgroundFrom } : {}), ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: launch ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(session)}` : `oats session attach --home ${shellWord(home)}`, warnings: spawnWarnings.length ? spawnWarnings : undefined, ...(naming ? { naming } : {}) });
5278
5433
  } catch (error) {
5279
5434
  if (promptDispatched) {
5280
5435
  // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
@@ -5365,14 +5520,16 @@ function recordedTmuxWindows(socket, session, io) {
5365
5520
  * be read, and, for a row whose server holds its endpoint (`endpoint`), when its socket file is
5366
5521
  * missing while a process works in the home or the scan (`scanHome()`, processesInHome's answer for
5367
5522
  * it) cannot tell (#624). */
5368
- function tmuxLiveness({ windows, error, missingSocket, panes }, window, scanHome, endpoint, inspectPanes) {
5523
+ function tmuxLiveness({ windows, error, missingSocket, panes, windowIds }, window, scanHome, endpoint, inspectPanes) {
5369
5524
  if (error) return { running: null, runtimeState: "unreachable", runtimeError: error };
5370
5525
  const running = windows.includes(window);
5371
5526
  const why = !running && missingSocket && endpoint ? missingSocketUnestablished(missingSocket, scanHome()) : null;
5372
5527
  if (why) return { running: null, runtimeState: "unreachable", runtimeError: why };
5373
5528
  if (!running) return { running: false };
5374
5529
  try {
5375
- const observed = inspectPanes(panes.get(window) ?? []);
5530
+ // Two windows of one name: tmux finds neither by name, so no session command reaches this one.
5531
+ if (windowIds?.get(window)?.size > 1) throw new Error(`the session has ${windowIds.get(window).size} windows named ${window}`);
5532
+ const observed = inspectPanes(panes.get(window) ?? [], { name: window });
5376
5533
  return { running: harnessRunning(observed), ...(observed.state === "shell" ? { runtimeState: "shell" } : {}) };
5377
5534
  } catch (e) { return { running: null, runtimeState: "unreachable", runtimeError: tmuxFailure(e, "tmux pane inspection failed") }; }
5378
5535
  }
@@ -5381,19 +5538,19 @@ function tmuxLiveness({ windows, error, missingSocket, panes }, window, scanHome
5381
5538
  function statusTmuxPanes(snapshot, socket, session, io) {
5382
5539
  if (!snapshot.windows?.length) return snapshot;
5383
5540
  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}"];
5541
+ 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
5542
  const output = socket ? tmuxOn(socket, args, io) : (io?.exec || execFileSync)("tmux", ["-u", ...args], {
5386
5543
  encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
5387
5544
  });
5388
- const panes = new Map();
5545
+ const panes = new Map(), windowIds = new Map();
5389
5546
  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));
5547
+ const [window, windowId, ...pane] = line.split("\t");
5548
+ if (!pane.length) throw new Error("invalid tmux pane response");
5549
+ if (!panes.has(window)) { panes.set(window, []); windowIds.set(window, new Set()); }
5550
+ panes.get(window).push(pane.join("\t"));
5551
+ windowIds.get(window).add(windowId);
5395
5552
  }
5396
- return { ...snapshot, panes };
5553
+ return { ...snapshot, panes, windowIds };
5397
5554
  } catch (e) { return { error: tmuxFailure(e, "tmux list-panes failed") }; }
5398
5555
  }
5399
5556
  export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
@@ -5448,12 +5605,7 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5448
5605
  // A self-retire that has been requested but not completed: the home is
5449
5606
  // owed a retirement, not live work. Read-only here — completion is the
5450
5607
  // detached child's or an operator's `oats retire`, never status.
5451
- const pending = retirePendingMarkerPath(home);
5452
- let retirePending, marker;
5453
- if (existsSync(pending)) {
5454
- try { retirePending = JSON.parse(readFileSync(pending, "utf8")); marker = { read: retirePending }; }
5455
- catch { retirePending = { reason: "retire pending" }; marker = { read: undefined }; }
5456
- }
5608
+ const { retirePending, marker } = readRetirePending(home);
5457
5609
  const retire = retireStateOf(home, marker);
5458
5610
  // A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
5459
5611
  // A home whose record cannot be read is listed, never observed: where its session is, is in the record.
@@ -5490,12 +5642,19 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5490
5642
  try { const s = instanceSessionTarget(home); if (!s.target) waitingOnYou = null; }
5491
5643
  catch { waitingOnYou = null; }
5492
5644
  }
5493
- // `retire` is only ever the value read above: a record that carries one (hand-edited, or
5494
- // copied from a row) never stands in for it.
5495
- const { retire: _recordedRetire, ...recorded } = meta;
5645
+ // `retire` is only ever the value read above, and `background` and `sameWork` the home's own records
5646
+ // (below): a record that carries any of them (hand-edited, or copied from a row) never stands in for it.
5647
+ const { retire: _recordedRetire, background: _recordedBackground, sameWork: _recordedSameWork, ...recorded } = meta;
5648
+ // Feature session-resume: how the last session of a launched home that does not run ended
5649
+ // (lib/session-end.mjs): lost, stopped or exited. Absent while it runs or reads unknown, for a
5650
+ // home never launched, and for one being set up, retired or quarantined.
5651
+ const sessionEnd = record.state === "record" && liveness.running === false && meta.launched === true && !rollbackIncomplete && !spawnInProgress && !retirePending ? sessionEndOf(home, meta) : null;
5496
5652
  // Feature instance-color: the home's own colour record (lib/instance-color.mjs), a palette name or
5497
5653
  // 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 } : {}) };
5654
+ // Feature instance-same-work: `sameWork: true` only while the home's flag is bound to the parent
5655
+ // its readable record names (lib/instance-same-work.mjs sameWorkOf); absent otherwise, never false.
5656
+ const sameWork = record.state === "record" && sameWorkOf(home, meta.parentInstance);
5657
+ return { ...recorded, ...claims, home, instance: e.name, ...facts, color: readInstanceColor(home), ...(readInstanceBackground(home) ? { background: true } : {}), ...(sameWork ? { sameWork: true } : {}), ...(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
5658
 
5500
5659
  });
5501
5660
  };
@@ -5536,6 +5695,9 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5536
5695
  out.push({ name, kind: "capability", capability: cap, description: cap ? `capability agent (${cap})` : "capability agent", dir, instances, ...(retireFailures.length ? { retireFailures } : {}) });
5537
5696
  seen.add(name);
5538
5697
  }
5698
+ // Feature session-resume: what this local listing saw of each home's session, for the sweep
5699
+ // (lib/session-seen.mjs). It never changes the listing, and never throws or prints.
5700
+ recordSeen(root, out.flatMap((a) => a.instances || []));
5539
5701
  return out;
5540
5702
  }
5541
5703
 
@@ -6044,9 +6206,15 @@ function retireGitProbe(repo, args, { encoding } = {}) {
6044
6206
  * MUST be added in the same change to the names a capability may not declare
6045
6207
  * as its own (`retirement.disposable.home`: KERNEL_HOME_NAMES and
6046
6208
  * KERNEL_HOME_NAME_PREFIXES in lib/capability-contract.mjs, and the schema). */
6047
- // `.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$/];
6209
+ // `.oats-color.json` (feature instance-color) and `.oats-background.json` (feature instance-background) are
6210
+ // presentation anyone may change at any time: never work.
6211
+ // `.oats-same-work.json` (feature instance-same-work) is kernel presentation of the same kind.
6212
+ // `.oats-start-exited` (lib/session-end.mjs) is the window's record of how the harness ended: every
6213
+ // launched home whose harness ever ended holds it.
6214
+ // `.oats-start-env.json` and its key (lib/start-env.mjs) are written at every start that renders a
6215
+ // recipe, after the spawn's baseline: every launched home holds them.
6216
+ const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json", ".oats-background.json", SAME_WORK_FILE, START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
6217
+ const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, START_ENV_TMP];
6050
6218
  /** Harness project settings in the home are configuration, not work: the
6051
6219
  * home's `.claude/` is harness layout the kernel already shapes (the skills
6052
6220
  * alias), and capabilities keep their own entries current in its
@@ -6092,7 +6260,9 @@ const GIT_NAME = Buffer.from(".git");
6092
6260
  * version `digestVersion` names (the baseline's own: baselineDigestVersion).
6093
6261
  * Both versions hold a home's `instance.json` without the fields the kernel
6094
6262
  * writes after spawn (kernelNeutralInstanceJson), so they read alike two
6095
- * `instance.json` files that parse to the same value.
6263
+ * `instance.json` files that parse to the same value; one over
6264
+ * NEUTRAL_INSTANCE_JSON_BYTES is held as its bytes, so a baseline taken
6265
+ * of its neutral form reads that home as changed.
6096
6266
  * - 1, the legacy digest: what a baseline without `digestVersion` holds,
6097
6267
  * written by a kernel before 0.49.0. It never changes: its framing (each
6098
6268
  * field followed by NUL, no lengths) and its order (the names as text,
@@ -6137,7 +6307,10 @@ const GIT_NAME = Buffer.from(".git");
6137
6307
  * reach, one inside another tap, and one that holds a path it passes over
6138
6308
  * (the caller does not ask for those; worktreeDigests).
6139
6309
  *
6140
- * The walk reads every byte it hashes itself, in this order. While it does,
6310
+ * The walk reads every byte it hashes itself, in this order, each file in
6311
+ * pieces of a fixed size (file-pieces.mjs); a home's `instance.json`, which
6312
+ * the stored digest takes in its neutral form, is read whole up to
6313
+ * NEUTRAL_INSTANCE_JSON_BYTES. While it does,
6141
6314
  * worker threads read the files it reads next into the page cache
6142
6315
  * (read-ahead.mjs), which changes nothing it computes or throws. */
6143
6316
  function fingerprintTrees(root, options = {}) {
@@ -6158,6 +6331,15 @@ function treeDigests(root, { excludeRoot = new Set(), excludePaths = [], instanc
6158
6331
  /** A field whose length is not fixed, in the exact digest or in version 2: its length, NUL, its bytes. */
6159
6332
  const sizedIn = (hash, bytes) => { hash.update(String(bytes.length)); hash.update("\0"); hash.update(bytes); };
6160
6333
  const sized = (bytes) => sizedIn(x, bytes);
6334
+ /** A file's bytes into the digests, read in pieces (readFilePieces): in each,
6335
+ * "file" and NUL, then in the legacy digest (`legacyHash`) its bytes, and in
6336
+ * each of `framed` its length, NUL and its bytes; the same stream as the
6337
+ * whole file read at once gives. */
6338
+ const fileInto = (path, legacyHash, framed) => {
6339
+ const hashes = [legacyHash, ...framed].filter(Boolean);
6340
+ for (const hash of hashes) hash.update("file\0");
6341
+ readAheadConsumed(readFilePieces(path, (size) => { for (const hash of framed) hash?.update(`${size}\0`); }, (bytes) => { for (const hash of hashes) hash.update(bytes); }));
6342
+ };
6161
6343
  const rootStat = lstatSync(root);
6162
6344
  if (!rootStat.isDirectory()) {
6163
6345
  const mode = String(rootStat.mode & 0o7777);
@@ -6165,7 +6347,7 @@ function treeDigests(root, { excludeRoot = new Set(), excludePaths = [], instanc
6165
6347
  v?.update("entry\0"); v?.update(mode); v?.update("\0");
6166
6348
  x?.update("entry\0"); x?.update(mode); x?.update("\0");
6167
6349
  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); } }
6350
+ else if (rootStat.isFile()) fileInto(root, s, [v, x]);
6169
6351
  else throw unsupportedEntry(String(root));
6170
6352
  return digests();
6171
6353
  }
@@ -6218,15 +6400,18 @@ function treeDigests(root, { excludeRoot = new Set(), excludePaths = [], instanc
6218
6400
  if (x) { x.update("link\0"); sized(target); }
6219
6401
  if (t) { t.update("link\0"); sizedIn(t, target); }
6220
6402
  } else if (st.isFile()) {
6221
- const bytes = readFileSync(path);
6222
- readAheadConsumed(bytes.length);
6223
6403
  // Kernel-field neutrality applies ONLY when the tree IS an instance home, and only to the
6224
6404
  // 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); }
6405
+ const bytes = (s || v) && instanceHome && !relText && name === "instance.json" ? readFileUpTo(path, NEUTRAL_INSTANCE_JSON_BYTES) : null;
6406
+ if (bytes) {
6407
+ readAheadConsumed(bytes.length);
6408
+ const storedBytes = kernelNeutralInstanceJson(bytes);
6409
+ s?.update("file\0"); s?.update(storedBytes);
6410
+ if (v) { v.update("file\0"); sizedIn(v, storedBytes); }
6411
+ if (x) { x.update("file\0"); sized(bytes); }
6412
+ if (t) { t.update("file\0"); sizedIn(t, bytes); }
6413
+ } else fileInto(path, s, [v, x, t]);
6414
+ s?.update("\0");
6230
6415
  } else if (st.isDirectory()) {
6231
6416
  s?.update("dir\0"); v?.update("dir\0"); x?.update("dir\0"); tap?.hash.update("dir\0");
6232
6417
  walk(path, childRel, childRelText, on, tap ?? (opens ? { hash: opens, at: childRel.length + PATH_SEPARATOR_BYTES.length } : null));
@@ -6469,6 +6654,8 @@ function retirementDisposableRoots(work, capabilities) {
6469
6654
  * is still recovered at retire. (Replaces a whole-home re-stamp that could
6470
6655
  * bless authored bytes written in the launch→completion interval.) */
6471
6656
  const KERNEL_POST_SPAWN_FIELDS = ["spawnCompleted", "wake", "launchPrompts", "launchPromptTarget", "parentLineageCommitted"];
6657
+ // What a digest holds of a home instance.json to take its neutral form (#617); a larger one is hashed raw, in pieces.
6658
+ const NEUTRAL_INSTANCE_JSON_BYTES = 16 * 1024 * 1024;
6472
6659
  function kernelNeutralInstanceJson(bytes) {
6473
6660
  try {
6474
6661
  // Bytes that are not UTF-8 would each read as the replacement character,
@@ -7207,6 +7394,29 @@ export const STOP_UNDER_CLAIM = Symbol("oats.stopUnderClaim");
7207
7394
  export function requireStopGrace(graceMs) {
7208
7395
  if (graceMs !== undefined && (!Number.isSafeInteger(graceMs) || graceMs < 1 || graceMs > 300000)) throw oatsError("E_BAD_ARGS", "stop grace must be 1-300000 ms");
7209
7396
  }
7397
+ /** The start a stop ends: the home's recorded `startId`, null when it records none (or cannot be read). */
7398
+ function stopStartId(home) {
7399
+ const id = readJsonOrUndefined(join(home, "instance.json"))?.startId;
7400
+ return typeof id === "string" && id ? id : null;
7401
+ }
7402
+ /** Record that OATS stopped the session of `home`'s current start (lib/session-end.mjs): the stop
7403
+ * receipt `.oats-stop.json`, `stop` being what was done to the harness (stopHarness's receipt, or
7404
+ * null when nothing was signalled). Its `startId` names the start, so the home reads `stopped`
7405
+ * and no resume brings that start back. The one writer of the receipt: a stop, an idle stop, and
7406
+ * a retire before it ends the session. Throws what the write throws. */
7407
+ function recordStop(home, stop) {
7408
+ writeJsonAtomic(join(home, STOP_RECEIPT_FILE), { instance: basename(home), at: new Date().toISOString(), stop, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(home) });
7409
+ }
7410
+ /** An explicit stop of a launched home found idle whose session reads `lost` (the host went down or
7411
+ * its tmux server died; or a home from before 0.69 whose harness ended): nothing is signalled, but
7412
+ * the stop is recorded (`stop: null`), so a resume does not bring the home back. Best effort: a
7413
+ * home that cannot be written (a full disk) answers as any idle stop, and stays `lost`. */
7414
+ function recordIdleStop(realHome) {
7415
+ const meta = readJsonOrUndefined(join(realHome, "instance.json"));
7416
+ if (meta?.launched !== true || sessionEndOf(realHome, meta) !== SESSION_END.LOST) return;
7417
+ try { recordStop(realHome, null); }
7418
+ catch { /* the idle stop's answer is unchanged: see above */ }
7419
+ }
7210
7420
  /** The stop of stopInstanceSession, under the home's claim. The pending self-retire marker is read
7211
7421
  * here, under it: a `--self` retire writes the marker while it holds the claim. */
7212
7422
  function stopSessionClaimed(home, o) {
@@ -7224,10 +7434,13 @@ function stopSessionClaimed(home, o) {
7224
7434
  if (lost.gone) before = { present: false, state: "stopped" };
7225
7435
  else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${lost.why ?? e.message}`);
7226
7436
  }
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 };
7437
+ if (!before.present || before.state === "shell" || before.state === "stopped") {
7438
+ recordIdleStop(realHome);
7439
+ return { home: s.home, backend: s.target.backend, stopped: false, alreadyIdle: true, state: before.state, receipt: null };
7440
+ }
7228
7441
  signalling = true;
7229
7442
  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"] });
7443
+ recordStop(realHome, receipt);
7231
7444
  appendEvent(realHome, { kind: receipt.exited ? "stopped" : "stop-refused", data: { signal: receipt.signal, waitedMs: receipt.waitedMs, stillRunning: receipt.stillRunning ?? [], state: receipt.state } });
7232
7445
  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
7446
  return { home: s.home, backend: s.target.backend, stopped: true, alreadyIdle: false, state: receipt.state, receipt };
@@ -7292,11 +7505,11 @@ function stopRecordedChildren(children, signalled) {
7292
7505
  });
7293
7506
  }
7294
7507
 
7295
- export async function attachInstanceSession(home, { detachKey, onSwept } = {}) {
7508
+ export async function attachInstanceSession(home, { detachKey, statusLine, onSwept } = {}) {
7296
7509
  if (detachKey !== undefined) requireDetachKey(detachKey);
7297
7510
  const s = instanceSessionTarget(home);
7298
7511
  if (!s.target) throw oatsError("E_SESSION_NOT_RUNNING", "instance was not launched");
7299
- return attachSessionTarget(s.target, { detachKey, onSwept });
7512
+ return attachSessionTarget(s.target, { detachKey, statusLine, onSwept });
7300
7513
  }
7301
7514
 
7302
7515
  export function inputInstanceSession(home, text) {
@@ -7432,18 +7645,25 @@ function writeJsonAtomic(path, value, mode) {
7432
7645
 
7433
7646
  // ---------- stopping a harness, selecting on an existing home ----------
7434
7647
  /** The harness processes under a tmux session target: EVERY descendant
7435
- * of the pane's launcher process (the launcher shell itself is left so
7648
+ * of the agent's pane's launcher process (`paneId`, when given, the pane the caller inspected) (the launcher shell itself is left so
7436
7649
  * that, once its command ends, it becomes the fallback shell the start
7437
7650
  * path recognizes); a wrapper that does not exec the harness, the harness
7438
7651
  * and their children are all included, topmost first. Each row:
7439
7652
  * { pid, ppid, pgid, comm, depth }. */
7440
- export function harnessProcesses(target, io) {
7653
+ export function harnessProcesses(target, io, { paneId } = {}) {
7441
7654
  const ps = () => ((io?.exec || execFileSync)("ps", ["-axo", "pid=,ppid=,pgid=,comm="], { encoding: "utf8", timeout: 10000, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }))
7442
7655
  .split("\n").map((l) => l.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.+)$/)).filter(Boolean)
7443
7656
  .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);
7657
+ // The agent's pane (resolveAgentPane), never the first one listed: a split's pane is never signalled.
7658
+ const panes = tmuxOn(target.socket, ["list-panes", "-t", `=${target.session}:=${target.window}`, "-F", `#{pane_id}\t#{pane_pid}\t#{${AGENT_PANE_OPTION}}`], io)
7659
+ .split("\n").filter(Boolean).map((line) => { const [id, pid, mark = ""] = line.split("\t"); return { paneId: id, pid, mark }; });
7660
+ if (!panes.every((p) => /^%\d+$/.test(p.paneId))) throw oatsError("E_SESSION_UNKNOWN", "invalid tmux pane response");
7661
+ const { pane, error } = resolveAgentPane(panes, target.window);
7662
+ if (error) throw oatsError("E_SESSION_UNKNOWN", `${error}; nothing was signalled`);
7663
+ // `paneId`: the pane the caller inspected. Another one now is no pane to signal on that reading.
7664
+ 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`);
7665
+ if (!/^\d+$/.test(pane?.pid || "")) throw oatsError("E_SESSION_UNKNOWN", "tmux returned no pane process id");
7666
+ const panePid = Number(pane.pid);
7447
7667
  const rows = ps();
7448
7668
  const byParent = new Map();
7449
7669
  for (const r of rows) { if (!byParent.has(r.ppid)) byParent.set(r.ppid, []); byParent.get(r.ppid).push(r); }
@@ -7467,7 +7687,7 @@ export function stopHarness(target, { graceMs = 20000, signal = "SIGTERM", io =
7467
7687
  const idle = (s) => !s.present || s.state === "shell" || s.state === "stopped";
7468
7688
  let before = inspectSessionTarget(target, io);
7469
7689
  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);
7690
+ const procs = harnessProcesses(target, io, { paneId: before.paneId });
7471
7691
  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
7692
  const requested = [];
7473
7693
  const sentAt = new Date().toISOString();
@@ -7654,8 +7874,53 @@ export function capturedHomeCapabilities(meta) {
7654
7874
  export function preWorkspaceHome(home, what) {
7655
7875
  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
7876
  }
7877
+ /** The conversation a resume of `home` continues (feature session-resume, design §4): the newest
7878
+ * transcript of this incarnation whose cwd is the home, in the locations its native-record receipts
7879
+ * name (packages/record lib/last-conversation.mjs), `since` its recorded `createdAt` (a reused name
7880
+ * reuses the path). → { harness, sessionId } or { harness, reason, warning? }: no conversation (R2)
7881
+ * is the ordinary fresh start on TASK.md. Codex is never resumed until a signed-in host proves it
7882
+ * end to end (`resume-unproven`). A lookup that fails is a fresh start too, and says why. */
7883
+ export function resumeConversation(home, meta) {
7884
+ const harness = meta.launch?.harness ?? meta.harness;
7885
+ if (harness === "codex") return { harness, reason: FRESH_REASON.RESUME_UNPROVEN };
7886
+ let found;
7887
+ try { found = lastConversation(home, { harness, since: meta.createdAt }); }
7888
+ 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` }; }
7889
+ return found?.sessionId ? { harness, sessionId: found.sessionId } : { harness, reason: found?.none === "no-receipts" ? FRESH_REASON.NO_RECEIPTS : FRESH_REASON.NO_CONVERSATION };
7890
+ }
7891
+ /** The `resume` object of a `session start --resume` answer (its one producer): what it continued
7892
+ * (resumeConversation's `resume`), and `waiting` when the start succeeded and waits for its human. */
7893
+ export function resumeAnswer(resume, waiting = null) {
7894
+ return { resumed: !!resume.sessionId, ...(resume.sessionId ? {} : { reason: resume.reason }), harness: resume.harness, ...(resume.sessionId ? { sessionId: resume.sessionId } : {}), ...(waiting ? { waiting } : {}) };
7895
+ }
7896
+ /** The pane a resumed launch runs in, from its creation's LAUNCH_PANE_FORMAT output; null when that
7897
+ * output cannot be read (the watch is then skipped: it only reports). */
7898
+ function resumePaneTarget(target, socket, output) {
7899
+ try { return { ...target, ...launchPaneTarget(socket, output) }; } catch { return null; }
7900
+ }
7657
7901
  export function startInstanceSession(home, o = {}) {
7658
7902
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session start needs an absolute instance home");
7903
+ if (o.resume !== true) return startSession(home, o);
7904
+ // --resume (feature session-resume) runs the recorded launch as it is: a launch choice cannot go with it.
7905
+ 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");
7906
+ 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);
7907
+ 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`);
7908
+ // A resume holds the home's lifecycle claim for the whole start, as a retire, a stop and an
7909
+ // upgrade do (claimHomeFor): none of them runs while it starts, and it starts nothing beside one
7910
+ // of them (lifecycleClaimRefusals: E_INSTANCE_RETIRING beside a retire, E_LIFECYCLE_BUSY beside
7911
+ // the others). What it reads under the claim (the retire it owes, whether its session is still
7912
+ // lost) is what it starts from. A home that is not there has no claim to take: it answers as it
7913
+ // always did. An ordinary start or restart does not take the claim. The claim is the one of the
7914
+ // home as it is on disk, through any link to the home itself, and the start runs on that path,
7915
+ // never on the spelling it was given again: a link changed after the claim was taken does not
7916
+ // move the start to a home whose claim it does not hold.
7917
+ if (!existsSync(home)) return startSession(home, o);
7918
+ const real = canonicalHomePath(home);
7919
+ const held = claimHomeFor("resume", basename(real), real);
7920
+ try { return startSession(real, o); } finally { releaseHomeClaim(held); }
7921
+ }
7922
+ /** The start of startInstanceSession, its arguments checked; a resume's under the home's claim. */
7923
+ function startSession(home, o) {
7659
7924
  // A home whose record is there and cannot be read is refused before anything of it is read (#896).
7660
7925
  identifiedHomeRecord(home);
7661
7926
  // A home opened in Herdr, or an earlier start that allocated a Herdr pane, is refused before any
@@ -7804,7 +8069,7 @@ export function startInstanceSession(home, o = {}) {
7804
8069
  // shell-script harness). Only its own completion marker proves this
7805
8070
  // is a fallback shell. Never respawn an accepted launch in that gap.
7806
8071
  if (st.present && st.state === "shell") {
7807
- const exited = existsSync(exitedPath) && readFileSync(exitedPath, "utf8").trim() === pending.id;
8072
+ const exited = readStartExited(realHome)?.startId === pending.id;
7808
8073
  if (!exited) throw oatsError("E_SESSION_START_BUSY", `${basename(realHome)} is still starting; refresh its status before retrying`);
7809
8074
  }
7810
8075
  const meta = readMeta();
@@ -7901,6 +8166,22 @@ export function startInstanceSession(home, o = {}) {
7901
8166
  const selected = reselect !== null || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined;
7902
8167
  const hasRecipe = meta.launch && typeof meta.launch === "object";
7903
8168
  let launchPlan = null, launchHooksPass = null, hookMeta, explicitModelFrom = null, warnings = [];
8169
+ // --resume: only a home whose session was lost, read here, under the lock, before any launch hook
8170
+ // runs. Then the conversation it continues, or the reason it starts fresh (resumeConversation).
8171
+ let resume = null;
8172
+ if (o.resume === true) {
8173
+ 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`);
8174
+ const observed = recordedState();
8175
+ 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}`); }
8176
+ if (observed.state.present && observed.state.state !== "shell") throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${observed.state.state}); nothing was started`);
8177
+ // A home whose retire runs, cannot be told, failed or was interrupted is owed it, never a
8178
+ // resume (read as its status row reads it, under the claim this resume holds).
8179
+ const owed = owedRetire(realHome);
8180
+ if (owed) throw oatsError("E_INSTANCE_RETIRING", `${owedRetireSaid(meta.instance, owed.state)}; nothing was started`);
8181
+ const end = meta.launched === true ? sessionEndOf(realHome, meta) : "never-launched";
8182
+ 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)`);
8183
+ resume = resumeConversation(realHome, meta);
8184
+ }
7904
8185
  if (selected || hasRecipe) {
7905
8186
  // Every start of a home with a recipe (ordinary, model-only, or under a
7906
8187
  // selection) goes through the one planner: recipe shape, the recorded
@@ -7951,7 +8232,16 @@ export function startInstanceSession(home, o = {}) {
7951
8232
  // References recorded for this home must resolve on this host on every
7952
8233
  // start path, and the source variables go to the pane, not the command.
7953
8234
  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`); }
8235
+ if (recipeForEnv) { const missing = missingLaunchEnvRefs(recipeForEnv.env, o.env || process.env); if (missing.length) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage(missing)); }
8236
+ // A resume starts only under the values the start it brings back recorded (lib/start-env.mjs): a
8237
+ // changed one refuses, after a missing one; a start with no record to check (an earlier kernel's,
8238
+ // or one that does not read) is resumed and says so once. Ordinary starts never compare.
8239
+ let envUnverified = null;
8240
+ if (resume && recipeForEnv) {
8241
+ const fit = checkStartEnv(realHome, meta.startId, fromEnvNames(recipeForEnv.env), o.env || process.env);
8242
+ if (fit.changed) throw oatsError("E_LAUNCH_ENV_CHANGED", launchEnvChangedMessage(fit.changed));
8243
+ if (fit.unverified) warnings.push(envUnverified = launchEnvUnverifiedWarning(meta.instance));
8244
+ }
7955
8245
  const paneEnv = recipeForEnv ? launchEnvRefs(recipeForEnv, o.env || process.env) : [];
7956
8246
  const paneEnvFlags = paneEnv.flatMap((r) => ["-e", `${r.name}=${r.value}`]);
7957
8247
  checkRoots(); // preparation has run; no backend has been changed
@@ -8021,6 +8311,7 @@ export function startInstanceSession(home, o = {}) {
8021
8311
  const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
8022
8312
  ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
8023
8313
  ...(hookMeta ? { hookMeta } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
8314
+ if (resume?.warning) { warnings.push(resume.warning); appendEvent(realHome, { kind: "launch-warning", data: { message: resume.warning } }); }
8024
8315
  warnings.push(...launchStartNotices(dirname(dirname(dirname(dirname(home)))), launchPlan?.harness || harness, command));
8025
8316
  if (kernelNode().warning) warnings.push(kernelNode().warning);
8026
8317
  const engaged = devChannelEngaged(launchPlan?.harness || harness, command);
@@ -8047,14 +8338,37 @@ export function startInstanceSession(home, o = {}) {
8047
8338
  const startedAt = new Date().toISOString();
8048
8339
  const id = randomUUID();
8049
8340
  if (!engaged) planExtra.launchPrompts = notEngaged(id);
8341
+ // This start's launch environment, recorded just before its pane is made (best effort: never a
8342
+ // refusal). A home without a recipe renders none and records nothing.
8343
+ const recordEnv = () => { if (recipeForEnv) recordStartEnv(realHome, id, fromEnvNames(recipeForEnv.env), o.env || process.env); };
8050
8344
  const makeLaunchController = () => engaged ? promptController(realHome, id, command, o.io, originalHomeIdentity) : null;
8051
8345
  let launchController;
8052
8346
  let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
8347
+ // A resumed Claude session is watched for its resume-cost dialog once it runs (after the record):
8348
+ // the pane's identity is read at its creation, as the controller reads it.
8349
+ const watchResume = !!resume?.sessionId && launchPlan.harness === "claude";
8350
+ let resumeTarget = null;
8053
8351
  checkRoots();
8054
8352
  // The names this launch removes, from the recipe it runs (a preview-aware hook's real run included).
8055
8353
  // A home without a recipe (an earlier kernel's) composes no providers at launch: nothing.
8056
8354
  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);
8355
+ // The launch's one native start; every render of its window command reuses it.
8356
+ const nativeStart = prepareNativeStart(realHome, launchPlan?.harness || harness);
8357
+ // What the window runs: the planned command, or, for a resume that found its conversation, the same
8358
+ // recipe rendered with the harness's resume selector and the resume notice. Only the window carries
8359
+ // it: instance.json, the pending receipt and the recipe keep the ordinary launch, so a later start
8360
+ // opens a fresh conversation (and the native-record roots never see a recorded --session).
8361
+ const executedCommand = () => resume?.sessionId ? renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome, resume: { sessionId: resume.sessionId, prompt: RESUME_NOTICE } }) : command;
8362
+ const windowCommand = (scope) => paneCommand(exitMarked(nativeRecordCommand(executedCommand(), realHome, launchPlan?.harness || harness, { start: nativeStart, scope }), id, exitedPath), removed);
8363
+ // Whether the harness runs in a scope of its own (nativeRecordCommand), judged on the pane it
8364
+ // will run in for the command it runs; a warning is said, and is an event once the start is recorded.
8365
+ let unscoped = null;
8366
+ const scopeOn = (pane) => {
8367
+ // The caller's own io (a test's), not the guarded one every start runs with.
8368
+ const scope = agentScopeOn(command, { pane, removed, refs: paneEnv }, rawIo);
8369
+ if (scope.warning) warnings.push(unscoped = scope.warning);
8370
+ return scope.wrapper;
8371
+ };
8058
8372
  let reused = "new";
8059
8373
  const session = target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
8060
8374
  const window = target?.window || meta.tmux?.window || meta.instance;
@@ -8062,11 +8376,14 @@ export function startInstanceSession(home, o = {}) {
8062
8376
  let windowCmd = windowCommand();
8063
8377
  let moved = null;
8064
8378
  // 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.
8379
+ // the agent's own pane (resolveAgentPane): the command runs there, on the
8380
+ // server the home recorded, no other window or pane touched and no option
8381
+ // set but that pane's mark.
8067
8382
  const inPlace = state.paneId && (state.present || state.state === "stopped");
8068
8383
  try {
8069
8384
  if (inPlace) {
8385
+ const scope = scopeOn(paneEnvironment(socket, session, o.io, realHome));
8386
+ if (scope) windowCmd = windowCommand(scope);
8070
8387
  launchController = makeLaunchController();
8071
8388
  if (launchController) {
8072
8389
  try {
@@ -8075,11 +8392,13 @@ export function startInstanceSession(home, o = {}) {
8075
8392
  } catch { /* a missing prior capture can never authorize input */ }
8076
8393
  }
8077
8394
  checkRoots();
8395
+ recordEnv();
8078
8396
  writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
8079
8397
  promptDispatched = !!launchController;
8080
8398
  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());
8399
+ 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
8400
  if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
8401
+ if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
8083
8402
  }
8084
8403
  catch (e) { throw launchFailure(e); }
8085
8404
  reused = "pane";
@@ -8091,7 +8410,12 @@ export function startInstanceSession(home, o = {}) {
8091
8410
  // on the OATS server, wherever the home was recorded: one socket from here to the record.
8092
8411
  const recordedSocket = socket ? resolve(socket) : null;
8093
8412
  socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
8094
- if (lookAgain(() => paneEnvironment(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
8413
+ // One read of the pane's environment answers both: the executable and the scope.
8414
+ const pane = paneEnvironment(socket, session, o.io, realHome);
8415
+ const looked = lookAgain(() => pane);
8416
+ if (looked) planExtra.launch = launchPlan.recipe;
8417
+ const scope = scopeOn(pane);
8418
+ if (looked || scope) windowCmd = windowCommand(scope);
8095
8419
  let names;
8096
8420
  try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
8097
8421
  catch (e) {
@@ -8102,12 +8426,14 @@ export function startInstanceSession(home, o = {}) {
8102
8426
  target = { backend: "tmux", session, window, socket };
8103
8427
  launchController = makeLaunchController();
8104
8428
  checkRoots();
8429
+ recordEnv();
8105
8430
  writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
8106
8431
  promptDispatched = !!launchController;
8107
8432
  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();
8433
+ 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
8434
  if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
8110
- prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : output, o.io);
8435
+ if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
8436
+ prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : watchResume ? output.split("\t")[0] : output, o.io);
8111
8437
  }
8112
8438
  catch (e) { throw launchFailure(e); }
8113
8439
  if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
@@ -8144,9 +8470,16 @@ export function startInstanceSession(home, o = {}) {
8144
8470
  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
8471
  }
8146
8472
  if (launchPrompts && !promptLaunched(launchPrompts.status)) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
8473
+ // As spawn says it once launched: a start refused before this point leaves no event.
8474
+ if (unscoped) appendEvent(realHome, { kind: "launch-warning", data: { message: unscoped } });
8475
+ if (envUnverified) appendEvent(realHome, { kind: "launch-warning", data: { message: envUnverified } });
8147
8476
  // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
8148
8477
  if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
8149
- return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings] };
8478
+ // A resume answers what it continued. A resumed Claude session that stops at its resume-cost dialog
8479
+ // is a start that succeeded and waits for its human: reported (`waiting`), never answered.
8480
+ 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;
8481
+ const resumed = resume ? { resume: resumeAnswer(resume, waiting) } : {};
8482
+ return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings], ...resumed };
8150
8483
  } finally {
8151
8484
  // A hook may have replaced the home itself. Never follow that replacement
8152
8485
  // to remove a target's lock; keep the original retry state with its home.
@@ -8308,7 +8641,7 @@ function repositoryGitState(repo, { status, cloneSource } = {}) {
8308
8641
  }
8309
8642
  const [gitDir, commonDir] = paths;
8310
8643
  const bytesOf = (path) => {
8311
- try { return createHash("sha256").update(readFileSync(path)).digest("hex"); }
8644
+ try { return hashFile(createHash("sha256"), path).digest("hex"); }
8312
8645
  catch (e) {
8313
8646
  if (e.code === "ENOENT") return null;
8314
8647
  throw oatsError("E_WORK_INSPECTION_FAILED", `could not read ${path}: ${e.message}`);
@@ -8777,7 +9110,7 @@ function copiedGitPathDigest(entry, at) {
8777
9110
  if (entry.copy === "tree") return exactTreeDigest(at);
8778
9111
  const st = statSync(at);
8779
9112
  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");
9113
+ return hashFile(createHash("sha256").update(`${st.mode & 0o7777}\0`), at).digest("hex");
8781
9114
  } catch (e) {
8782
9115
  if (e?.code === "E_WORK_INSPECTION_FAILED") throw e;
8783
9116
  throw oatsError("E_WORK_INSPECTION_FAILED", `could not read ${at}: ${e.message}`);
@@ -9393,7 +9726,10 @@ function preservedOutputs(work, directory) {
9393
9726
  * the whole home: the stored digest also passes over the kernel's receipts
9394
9727
  * and the harness settings, and reads instance.json through a parse. */
9395
9728
  function copyRecoveryHome(observation, dest) {
9396
- const excludeRoot = observation.homeExclude || new Set(["work"]);
9729
+ // The launch environment's key and the digests made with it never leave the home
9730
+ // (lib/start-env.mjs): a recovery copy leaves them, and any temporary file of theirs, out.
9731
+ const excludeRoot = new Set(observation.homeExclude || ["work"]);
9732
+ 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
9733
  copyRecoveryTree(observation.home, dest, { excludeRoot });
9398
9734
  if (storedTreeDigest(observation.home, BASELINE_DIGEST_VERSION, { excludeRoot, instanceHome: true }) !== storedTreeDigest(dest, BASELINE_DIGEST_VERSION, { instanceHome: true })) {
9399
9735
  throw new Error("home recovery verification disagreed with the source");
@@ -9705,6 +10041,25 @@ export function retirePendingMarkerPath(home) {
9705
10041
  return join(dirname(home), `.oats-retire-pending-${basename(home)}.json`);
9706
10042
  }
9707
10043
 
10044
+ /** The retire-pending marker of `home` as a status row reads it → `{ retirePending, marker }`: both
10045
+ * undefined when there is none; `retirePending` what it parsed as (a placeholder when it did not
10046
+ * parse), `marker` what retireStateOf takes. */
10047
+ function readRetirePending(home) {
10048
+ const pending = retirePendingMarkerPath(home);
10049
+ if (!existsSync(pending)) return {};
10050
+ try { const read = JSON.parse(readFileSync(pending, "utf8")); return { retirePending: read, marker: { read } }; }
10051
+ catch { return { retirePending: { reason: "retire pending" }, marker: { read: undefined } }; }
10052
+ }
10053
+ /** The retire `home` owes, as a status row's `retire` reads it (retireStateOf), or undefined. */
10054
+ function owedRetire(home) {
10055
+ return retireStateOf(home, readRetirePending(home).marker);
10056
+ }
10057
+ /** Why `instance`, whose status row's `retire` has `state`, is not resumed: one clause. */
10058
+ export function owedRetireSaid(instance, state) {
10059
+ const said = { running: "is running", unknown: "cannot be told", failed: "failed", interrupted: "was interrupted" }[state] ?? "cannot be told";
10060
+ return `${instance} is owed a retire (its retire ${said}); a home OATS is retiring is never resumed`;
10061
+ }
10062
+
9708
10063
  /** A status row's `retire` (feature status-retire-state, lib/retire-state.mjs): whether a retire of
9709
10064
  * `home` runs, could not be told, failed or was interrupted, read from what is beside the home
9710
10065
  * (`marker`: `{ read }` when its retire marker is there, `read` what its file parsed as, undefined
@@ -10073,15 +10428,19 @@ const RETIRE_CLAIM_RESTARTS = 2;
10073
10428
 
10074
10429
  /** The lifecycle claim file of `home`: `<instances>/.oats-retirement/claims/<name>.lock`. Beside
10075
10430
  * the homes, never inside one: a home's bytes are what its retire observes, copies and removes.
10076
- * One file for every verb that holds a home (a retire, a stop): its record names the holder's
10077
- * verb (`action`) from the instant it exists (lib/claim.mjs `facts`). */
10431
+ * One file for every verb that holds a home (a retire, a stop, an upgrade, a resume): its record
10432
+ * names the holder's verb (`action`) from the instant it exists (lib/claim.mjs `facts`). One file
10433
+ * for every spelling of the home: `<instances>` is the instances directory's own spelling on disk
10434
+ * (canonicalHomePath), and `<name>` the home's name once `.` and `..` are resolved, so that
10435
+ * `H/.`, or `H` through a link to its deployment, names H's claim. */
10078
10436
  export function retireClaimPath(home) {
10079
- return join(instancesRetirementRoot(dirname(home)), "claims", `${basename(home)}.lock`);
10437
+ const at = resolve(home);
10438
+ return join(instancesRetirementRoot(canonicalHomePath(dirname(at))), "claims", `${basename(at)}.lock`);
10080
10439
  }
10081
10440
 
10082
10441
  /** The verbs that take a home's lifecycle claim: what claimHomeFor accepts, and so every `action`
10083
- * a claim of the kernel's names. */
10084
- const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade"]);
10442
+ * a claim of the kernel's names. `resume` is a `session start --resume`. */
10443
+ const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade", "resume"]);
10085
10444
  /** The verb the holder of a home's claim recorded (`action`): one of CLAIM_VERBS, never the
10086
10445
  * record's text. A claim is read back as whatever is in its file, which other instances of the
10087
10446
  * deployment can write, and this goes into messages, remedies and `details` (lib/claim.mjs
@@ -10090,14 +10449,14 @@ const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade"]);
10090
10449
  * retire took the claim. */
10091
10450
  const claimAction = (holder) => CLAIM_VERBS.includes(holder?.action) ? holder.action : "retire";
10092
10451
  /** The command that takes a home's claim for `action`, as a person types it. */
10093
- const claimCommand = (action) => ["stop", "upgrade"].includes(action) ? `oats instance ${action}` : `oats ${action}`;
10452
+ const claimCommand = (action) => action === "resume" ? "oats session start --resume" : ["stop", "upgrade"].includes(action) ? `oats instance ${action}` : `oats ${action}`;
10094
10453
  /** What each verb that meets a held claim says it did not do: the words its refusals end with,
10095
10454
  * before any effect. After a takeover ended a dead holder's step, every verb says the same
10096
10455
  * (lib/errors.mjs nothingAfter). */
10097
- const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", "worktree add": "no tree was made", "instance color": "the colour was not changed" };
10456
+ const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", resume: "nothing was started", "worktree add": "no tree was made", "instance color": "the colour was not changed", "instance same-work": "the flag was not changed", "instance background": "the background was not changed" };
10098
10457
 
10099
- /** The refusals of `arriving` ("retire", "stop", or "worktree add", which reads the claim and does
10100
- * not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
10458
+ /** The refusals of `arriving` ("retire", "stop", "upgrade", "resume", or "worktree add", which
10459
+ * reads the claim and does not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
10101
10460
  * for them: one builder for every pair (arriving verb, holder's verb), so that the pair table of
10102
10461
  * docs/desktop-cli-api.md has one source. One line each, saying what was not done, once.
10103
10462
  * - A live holder: E_INSTANCE_RETIRING when the holder is a retire and the arriving verb is not
@@ -10117,7 +10476,7 @@ const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing wa
10117
10476
  export function lifecycleClaimRefusals(arriving, name, home, lock) {
10118
10477
  const nothing = (ended) => nothingAfter(ended, CLAIM_NOTHING[arriving]);
10119
10478
  const own = { instance: name, home };
10120
- const holders = "oats retire, oats instance stop or oats instance upgrade";
10479
+ const holders = "oats retire, oats instance stop, oats instance upgrade or oats session start --resume";
10121
10480
  // The holder of `at`, as an answer names it: `shown` for the message, `details` beside it.
10122
10481
  const held = (holder, at) => {
10123
10482
  const shown = shownHolder(holder), action = claimAction(holder);
@@ -10164,7 +10523,7 @@ export function retireClaimRefusals(name, home, lock) {
10164
10523
  * parsed arguments or JSON. */
10165
10524
  export const READ_CLAIM_WHEN_UNWRITABLE = Symbol("oats.readClaimWhenUnwritable");
10166
10525
 
10167
- /** Take the lifecycle claim of `home` for `verb` ("retire", "stop") → the holding, for
10526
+ /** Take the lifecycle claim of `home` for `verb` (one of CLAIM_VERBS) → the holding, for
10168
10527
  * releaseHomeClaim. The one way a verb takes it: the record carries the verb from the instant the
10169
10528
  * file exists, and a holder of any verb is refused at once (`waitMs: 0`; only a deferred
10170
10529
  * self-retire's completion waits, for the retire that scheduled it). The claim's directory is
@@ -10187,7 +10546,7 @@ export function claimHomeFor(verb, name, home, { waitMs = 0, [READ_CLAIM_WHEN_UN
10187
10546
  const refusals = lifecycleClaimRefusals(verb, name, home, lock);
10188
10547
  try {
10189
10548
  try {
10190
- claimWrite(() => mkdirSync(instancesRetirementRoot(dirname(home)), { recursive: true }));
10549
+ claimWrite(() => mkdirSync(dirname(dirname(lock)), { recursive: true }));
10191
10550
  claimWrite(() => mkdirSync(dirname(lock), { recursive: true, mode: 0o700 }));
10192
10551
  } catch (e) { throw claimUnavailable(lock, e); }
10193
10552
  return { lock, me: acquireClaim(lock, { ...refusals, facts: { action: verb }, waitMs }) };
@@ -10707,6 +11066,13 @@ function retireSteps(root, name, o, found, at) {
10707
11066
  const tmux = ["-S", runtimeSocket];
10708
11067
  at.sessionTouched = true;
10709
11068
  ownSession = "unverified";
11069
+ // The stop is recorded before the window is ended, so that at no instant the window is gone
11070
+ // and the home reads `lost` (a resume would bring it back): a retire that fails after this
11071
+ // leaves a home that reads `stopped`. A record that cannot be written (a full disk) does not
11072
+ // fail the retire: the home reads lost, and this retire's claim keeps a resume off it while it
11073
+ // runs. Should the retire then fail too, nothing records that it was asked for, and the home
11074
+ // reads lost as it did before this record existed.
11075
+ try { recordStop(found.home, null); } catch { /* see above */ }
10710
11076
  try { execFileSync("tmux", [...tmux, "kill-window", "-t", `=${runtimeSession}:=${runtimeWindow}`], { stdio: ["ignore", "pipe", "pipe"] }); } catch { /* verify the effect below */ }
10711
11077
  try {
10712
11078
  const windows = execFileSync("tmux", [...tmux, "list-windows", "-t", runtimeSession, "-F", "#{window_name}"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).split("\n").filter(Boolean);
@@ -11311,6 +11677,9 @@ function retireSteps(root, name, o, found, at) {
11311
11677
  // literal # in the socket path is written ##.
11312
11678
  const killSocket = runtimeAuthority?.tmux?.socket || meta?.tmux?.socket;
11313
11679
  const killTarget = shq(`=${killSession}:=${killWindow}`);
11680
+ // The home `--keep-dir` keeps reads `stopped` once its window is gone, never `lost` (recordStop,
11681
+ // as above). A record that cannot be written stops nothing: the home then reads lost, as before.
11682
+ if (o.keepDir) { try { recordStop(found.home, null); } catch { /* see above */ } }
11314
11683
  if (typeof killSocket === "string" && killSocket) {
11315
11684
  const kill = `sleep ${o.selfKillDelaySec ?? 8}; tmux -u -S ${shq(killSocket)} kill-window -t ${killTarget} 2>/dev/null || true`;
11316
11685
  shTry(`tmux -u -S ${shq(killSocket)} run-shell -b ${shq(kill.replace(/#/g, "##"))}`);