@awebai/oats 0.69.12 → 0.69.15

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 (92) hide show
  1. package/README.md +216 -178
  2. package/bin/oats.mjs +254 -201
  3. package/docs/capabilities.md +58 -13
  4. package/docs/configuration.md +63 -5
  5. package/docs/container.md +291 -0
  6. package/docs/design/2026-09-23-workspace-module-contracts.md +2 -0
  7. package/docs/desktop-cli-api.md +590 -55
  8. package/docs/desktop-instance-start.md +4 -1
  9. package/docs/desktop.md +58 -12
  10. package/docs/execution-targets.md +84 -9
  11. package/docs/first-team.md +4 -3
  12. package/docs/implementation.md +99 -32
  13. package/docs/integrations.md +3 -2
  14. package/docs/knowledge-and-learning.md +72 -0
  15. package/docs/oats-local.schema.json +11 -2
  16. package/docs/official-catalog.md +39 -5
  17. package/docs/packages.md +93 -14
  18. package/docs/release-lane.md +2 -1
  19. package/docs/release-notes/v0.69.13.md +767 -0
  20. package/docs/release-notes/v0.69.14.md +83 -0
  21. package/docs/release-notes/v0.69.15.md +444 -0
  22. package/docs/schedules.md +159 -5
  23. package/docs/servers.md +241 -7
  24. package/docs/souls-and-instances.md +223 -14
  25. package/docs/tui.md +1 -1
  26. package/docs/upgrading.md +36 -5
  27. package/docs/workspaces.md +31 -5
  28. package/lib/claim.mjs +20 -5
  29. package/lib/command-flags.mjs +240 -0
  30. package/lib/core.mjs +1004 -633
  31. package/lib/deployments.mjs +4 -3
  32. package/lib/dir-lock.mjs +145 -33
  33. package/lib/errors.mjs +3 -2
  34. package/lib/harness-token.mjs +110 -0
  35. package/lib/host-run.mjs +218 -0
  36. package/lib/host-stop-child.mjs +21 -0
  37. package/lib/hot-reads.mjs +4 -3
  38. package/lib/instance-events.mjs +28 -6
  39. package/lib/instance-git.mjs +165 -14
  40. package/lib/instance-inspect.mjs +6 -1
  41. package/lib/instance-lifecycle.mjs +4 -3
  42. package/lib/instance-listing.mjs +114 -43
  43. package/lib/instance-resolution.mjs +56 -3
  44. package/lib/instance-upgrade.mjs +16 -20
  45. package/lib/kernel-features.mjs +4 -1
  46. package/lib/launch-env-exec.sh +7 -0
  47. package/lib/launch-env.mjs +74 -0
  48. package/lib/launch-preference.mjs +19 -12
  49. package/lib/member-clone.mjs +7 -1
  50. package/lib/packages.mjs +74 -2
  51. package/lib/read-call.mjs +4 -1
  52. package/lib/reader.mjs +3 -2
  53. package/lib/refused-text.mjs +3 -2
  54. package/lib/remote.mjs +126 -31
  55. package/lib/retained-after-retire.mjs +2 -7
  56. package/lib/retire-git-forms.mjs +41 -0
  57. package/lib/retire-incomplete.mjs +96 -0
  58. package/lib/schedule.mjs +239 -21
  59. package/lib/servers.mjs +161 -28
  60. package/lib/session-end.mjs +28 -8
  61. package/lib/session-resume.mjs +63 -56
  62. package/lib/session-seen.mjs +3 -14
  63. package/lib/start-env.mjs +13 -7
  64. package/lib/status-words.mjs +11 -4
  65. package/lib/system-tools.mjs +1 -36
  66. package/lib/teams.mjs +11 -4
  67. package/lib/upgrade-state.mjs +13 -2
  68. package/lib/worktree-hooks.mjs +6 -175
  69. package/lib/worktree.mjs +68 -10
  70. package/package-catalog.json +1 -1
  71. package/package.json +5 -1
  72. package/packages/client/instance-lifecycle.mjs +1 -1
  73. package/packages/client/lifecycle-contract.mjs +3 -1
  74. package/packages/client/session-resume-cli.mjs +2 -1
  75. package/packages/client/session-start.mjs +10 -7
  76. package/packages/client/workspace-cli.mjs +5 -1
  77. package/packages/record/README.md +56 -21
  78. package/packages/record/docs/capture-service.md +8 -5
  79. package/packages/record/docs/turn-record-sot.md +9 -0
  80. package/packages/record/lib/capture-health.mjs +6 -4
  81. package/packages/record/lib/capture-lock.mjs +31 -27
  82. package/packages/record/lib/capture-retained-scratch.mjs +4 -3
  83. package/packages/record/lib/capture-scratch.mjs +2 -1
  84. package/packages/record/lib/derived-state.mjs +4 -2
  85. package/packages/record/lib/index-db.mjs +4 -2
  86. package/packages/record/lib/lock-holder.mjs +21 -0
  87. package/packages/record/lib/private-files.mjs +18 -0
  88. package/packages/record/lib/process-identity.mjs +310 -0
  89. package/packages/record/lib/store.mjs +31 -25
  90. package/share/oats-login-receive +204 -0
  91. package/skills/oats-getting-started/SKILL.md +93 -26
  92. package/lib/tmux-config.mjs +0 -35
package/lib/core.mjs CHANGED
@@ -27,6 +27,7 @@
27
27
  * work (worktree|checkout|attached|workspace|directory), harness (pi|claude|codex), model (pi model pattern, optional)
28
28
  * (attached as soul default is for service agents — spawn must supply workDir)
29
29
  */
30
+ import { isLaunchEnvReference, referenceSource, referenceValue, fileReferenceRemedy, launchEnvHandoff, LAUNCH_ENV_HANDOFF } from "./launch-env.mjs";
30
31
  import { canonicalHomePath, realPathOrNearest } from "./real-path.mjs";
31
32
  import { createLaunchPromptController, neverSettled } from "./launch-prompts.mjs";
32
33
  import { retainLaunchPromptFrame } from "./launch-prompt-evidence.mjs";
@@ -43,16 +44,17 @@ import { createHash, randomUUID } from "node:crypto";
43
44
  import { initializeNativeHistory, prepareNativeStart } from "../packages/record/lib/native-history.mjs";
44
45
  import { sameDirectory } from "../packages/record/lib/directory-identity.mjs";
45
46
  import { noteRuntimeName } from "./deprecation.mjs";
47
+ import { RETIRE_DELETE_BRANCH_REFUSED } from "./command-flags.mjs";
46
48
  import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
47
49
  import { AGENT_PANE_OPTION, inspectSessionTarget, inputSessionTarget, resolveAgentPane } from "./session-input.mjs";
48
- import { appendEvent, incarnationOf, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
50
+ import { RETIRE_HOOK_WARNING_KIND, appendEvent, incarnationOf, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
49
51
  import { killGroup } from "./process-group.mjs";
50
52
  import { NAMING_CALLS, NAMING_TIMEOUT_MS, suggestInstanceName } from "./instance-naming.mjs";
51
53
  import { interruptExitStatus, isStartToken, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
52
- import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite, readClaim, releaseClaim, removeGoneClaim, shownHolder, unwritableCode } from "./claim.mjs";
54
+ import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite, readClaim, recordInClaim, releaseClaim, removeGoneClaim, shownHolder, unwritableCode } from "./claim.mjs";
53
55
  import { captureLoginEnvironment } from "./login-environment.mjs";
54
56
  import { kernelNode } from "./stable-node.mjs";
55
- import { assertNoPartialUpgrade, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
57
+ import { assertNoPartialUpgrade, packageRespawnWarning, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
56
58
 
57
59
  import { oatsError, afterEndedSteps, afterFirstEffect, asKernelError, BEFORE_EFFECT_CODES, checkHolderByHand, errorCause, ifItDoesNotEnd, isAnswerCode, isKernelCode, kernelCode, lifecycleBusy, nothingAfter, reportDefect, OWN_NAME_FAILURES, OWN_START_REMEDY, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
58
60
  import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
@@ -85,22 +87,24 @@ import { readPortableBytes } from "./bounded-read.mjs";
85
87
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes, treeDisagreement } from "./tree-copy.mjs";
86
88
  import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
87
89
  import { hashFile, readFilePieces, readFileUpTo } from "./file-pieces.mjs";
88
- import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
90
+ import { assertSameWorktreeHead, filterOverrides, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, workTreeOverrides, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
91
+ import { retireGitReadsNoWorkTreeFile, retireSubcommandAt } from "./retire-git-forms.mjs";
89
92
  import { systemTool } from "./system-tools.mjs";
90
93
  import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
91
94
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
92
95
  import { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
93
96
  import { SAME_WORK_FILE, writeSameWork } from "./instance-same-work.mjs";
94
- import { readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
97
+ import { HOST_STOP_REASON, readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
98
+ import { thisBoot } from "./session-seen.mjs";
95
99
  import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
96
- import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, fromEnvNames, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
100
+ import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
97
101
  import { watchResumeConfirmation } from "./launch-prompt-resume.mjs";
98
102
  import { lastConversation } from "../packages/record/lib/last-conversation.mjs";
99
103
  import { PKG_ROOT } from "./version.mjs";
100
104
  import { canonicalDeploymentPath } from "./deployment-path.mjs";
101
105
  import { INSTANCE_NAME_RE, RESERVED, capabilityAgentDirs, enclosingInstanceHome, findInstanceHomes, listAgents, logicalCwd, readSoul, soulOf, stripInternalAnnotations, withConfigFile, yamlKey } from "./soul-listing.mjs";
102
106
  import { RETIRE_BASELINE_VERSION, authorityMismatch, findRetirementBaseline, inspectInstanceSession, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, retirementBaselinePath, runtimeAuthorityOf, tmuxEndpointAgrees } from "./session-inspect.mjs";
103
- import { CLAIM_VERBS, DEFAULT_TMUX_SESSION, LAUNCH_RECIPE_VERSION, claimAction, defaultTmuxWindows, deferredRetireResultPath, directoryRollbackPath, hostProcesses, isCapturedHome, lookupOnPath, missingSocketUnestablished, namedProcesses, parseLaunchCommand, procReadable, processesWorkingIn, readHomeRecord, readRetirePending, redactLaunchCommand, redactLaunchRecipe, retireClaimPath, retirePendingMarkerPath, retireStateOf, subdirs, tmuxFailure, tmuxOn, tmuxServerAbsence, unreadableRecordSaid, upgradeHomeMeta, upgradeLaunchRecipe } from "./instance-listing.mjs";
107
+ import { CLAIM_VERBS, DEFAULT_TMUX_SESSION, LAUNCH_RECIPE_VERSION, claimAction, completionLiveness, defaultTmuxWindows, deferredRetireResultPath, directoryRollbackPath, hostProcesses, isCapturedHome, lookupOnPath, missingSocketUnestablished, namedProcesses, parseLaunchCommand, procReadable, processesWorkingIn, readHomeRecord, readRetirePending, redactLaunchCommand, redactLaunchRecipe, retireCarried, retireClaimPath, retirePendingMarkerPath, retireStateOf, subdirs, tmuxFailure, tmuxOn, tmuxServerAbsence, unreadableRecordSaid, upgradeHomeMeta, upgradeLaunchRecipe } from "./instance-listing.mjs";
104
108
  import { LAYERS, PACKAGE_ID_RE } from "./package-catalog.mjs";
105
109
  import { RESERVED_LAUNCH_ENV } from "./reserved-launch-env.mjs";
106
110
  import { workspaceOf } from "./agents-root.mjs";
@@ -348,6 +352,8 @@ export const LAUNCH_CONFIG_KEYS = new Set(["harness", "runtime", "executable", "
348
352
  export const launchConfigHarness = (entry) => (Object.hasOwn(entry, "harness") ? entry.harness : entry.runtime);
349
353
  const LAUNCH_CONFIG_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
350
354
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
355
+ const DIRECTORY_LAUNCH_ENV = new Set(["HOME", "PATH", ...Object.values(HARNESS_FOLDER_VAR), "PI_CODING_AGENT_SESSION_DIR"]);
356
+ const fileLocationMessage = (name) => `${name} is a directory location; give it as a literal or {fromEnv}. fromFile is for credential values.`;
351
357
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
352
358
  const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
353
359
  export function validateLaunchConfig(name, entry, where) {
@@ -365,12 +371,13 @@ export function validateLaunchConfig(name, entry, where) {
365
371
  for (const a of entry.args) if (typeof a !== "string" || a.includes("\0")) bad("args must be a list of strings");
366
372
  }
367
373
  if (entry.env !== undefined) {
368
- if (!entry.env || typeof entry.env !== "object" || Array.isArray(entry.env)) bad("env must be a map of NAME to a string or {fromEnv: NAME}");
374
+ if (!entry.env || typeof entry.env !== "object" || Array.isArray(entry.env)) bad("env must be a map of NAME to a string, {fromEnv: NAME}, or {fromFile: /absolute/path}");
369
375
  for (const [n, v] of Object.entries(entry.env)) {
370
376
  if (!ENV_NAME.test(n)) bad(`env name ${JSON.stringify(n)} is not a valid environment variable name`);
371
377
  if (reservedLaunchEnv(n)) bad(`env ${n} is set by the kernel for every launch and cannot be overridden`);
372
378
  if (typeof v === "string") { if (v.includes("\0")) bad(`env ${n} must be text`); continue; }
373
- if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).length !== 1 || typeof v.fromEnv !== "string" || !ENV_NAME.test(v.fromEnv)) bad(`env ${n} must be a string or {fromEnv: NAME}`);
379
+ if (!isLaunchEnvReference(v)) bad(`env ${n} must be a string or {fromEnv: NAME} or {fromFile: /absolute/path}`);
380
+ if (v.fromFile !== undefined && DIRECTORY_LAUNCH_ENV.has(n)) bad(fileLocationMessage(n));
374
381
  if (v && typeof v === "object" && v.fromEnv && v.fromEnv.startsWith(LAUNCH_REF_PREFIX)) bad(`env ${n} may not reference a ${LAUNCH_REF_PREFIX}* alias`);
375
382
  }
376
383
  }
@@ -1454,7 +1461,7 @@ function replacedDialogClaims(prior, ran) {
1454
1461
  function voidedDialogClaims(ran) {
1455
1462
  return ran && Object.fromEntries(Object.keys(ran).map((id) => [id, null]));
1456
1463
  }
1457
- export function runLifecycleHooks(event, { home, instance, agentName, soulDir, soulId, contextDir, workspaceDir, rootDir, resolved, priorMeta = {}, extraEnv = {}, assertRoots }) {
1464
+ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, soulId, contextDir, workspaceDir, rootDir, resolved, priorMeta = {}, extraEnv = {}, assertRoots, finished, onFinished }) {
1458
1465
  const results = { meta: {}, briefs: [], warnings: [], order: [], launch: {}, env: {}, failures: [], contributions: [], volatileEnv: {}, dialogClaims: {} };
1459
1466
  // OATS_SOUL is set for EVERY hook: a caller that does not name the soul (launch,
1460
1467
  // retire) gets the directory the home's spawn recorded.
@@ -1470,6 +1477,13 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1470
1477
  if (cap.executable && !cap.trust?.trusted) results.warnings.push(`${cap.id}: executable surface disabled — ${cap.trust?.reason || "not trusted"}`);
1471
1478
  const cmd = cap.hooks?.[event];
1472
1479
  if (!cmd) continue;
1480
+ // A hook that has ended already (`finished`: capability → the meta it answered, or undefined)
1481
+ // is not run: it is in the order, with that meta, as if this call had run it.
1482
+ if (finished?.has(cap.id)) {
1483
+ results.order.push(cap.id);
1484
+ if (finished.get(cap.id) !== undefined) results.meta[cap.id] = finished.get(cap.id);
1485
+ continue;
1486
+ }
1473
1487
  assertRoots?.();
1474
1488
  results.order.push(cap.id);
1475
1489
  if (event === "spawn" || event === "launch") results.dialogClaims[cap.id] = null;
@@ -1504,6 +1518,8 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1504
1518
  if (DIALOG_CLAIMS.includes(o.dialogClaims)) results.dialogClaims[cap.id] = o.dialogClaims;
1505
1519
  else results.warnings.push(`${cap.id} ${event} hook answered dialogClaims ${String(JSON.stringify(o.dialogClaims)).slice(0, 64)}, neither "reported" nor "none"; read as no answer`);
1506
1520
  }
1521
+ // The hook ended and its answer is taken: the caller is told, with the meta it answered.
1522
+ onFinished?.(cap.id, o.meta || undefined);
1507
1523
  } catch (e) {
1508
1524
  if (e instanceof HookEnvironmentContractError) {
1509
1525
  const detail = String(e.message || e).slice(0, 200);
@@ -2206,9 +2222,10 @@ export function launchEnvironment({ configEnv, configName, capabilities, removed
2206
2222
  const of = (name) => {
2207
2223
  const own = Object.hasOwn(configEnv || {}, name) ? configEnv[name] : undefined;
2208
2224
  if (typeof own === "string") return selector(name, { value: own, source: `the ${name} of launch configuration ${configName}` });
2209
- if (own && typeof own === "object" && own.fromEnv) {
2210
- const source = `the ${name} of launch configuration ${configName} (from ${own.fromEnv})`;
2211
- return env[own.fromEnv] === undefined ? { source, problem: `${name} references ${own.fromEnv}, not set on this host`, unresolved: true } : selector(name, { value: env[own.fromEnv], source });
2225
+ if (own && typeof own === "object" && (own.fromEnv || own.fromFile)) {
2226
+ const sourceName = referenceSource(own), value = referenceValue(own, env);
2227
+ const source = `the ${name} of launch configuration ${configName} (from ${sourceName})`;
2228
+ return value === undefined ? { source, problem: `${name} references ${sourceName}, not set on this host`, unresolved: true } : selector(name, { value, source });
2212
2229
  }
2213
2230
  if (capabilities?.env && Object.hasOwn(capabilities.env, name) && typeof capabilities.env[name] === "string") return selector(name, { value: capabilities.env[name], source: `the ${name} that ${capabilities.owner?.(name) || "a capability"} sets for this launch` });
2214
2231
  // A selector the launch removes (a manifest may declare one under a namespace it names); PATH
@@ -2376,8 +2393,9 @@ function oatsTmuxWindows(session) {
2376
2393
  /** The harness's window command: no COLORFGBG in the pane, none of the names only a hook is handed,
2377
2394
  * and none of the names the launch removes (`removed`: removedLaunchEnv, each a portable name),
2378
2395
  * whatever the server's global or the session's environment holds; the command's own prefix then sets what the launch sets. tmux runs
2379
- * the command with the server's `default-shell -c` (the user's shell: sh, bash and zsh all take
2380
- * `unset NAME…;`), and the fallback shell it execs inherits the result. Never persisted: the
2396
+ * the window command with its `default-shell -c`. A reference handoff then runs this pane
2397
+ * wrapper through /bin/sh; nativeRecordCommand already executes parsed harness argv through
2398
+ * /bin/sh for every launch. The fallback shell it execs inherits the result. Never persisted: the
2381
2399
  * recorded command (meta.command) is the launch command alone. */
2382
2400
  /** A launch's command followed by its exit marker (lib/session-end.mjs): the start id and the harness's
2383
2401
  * exit status, written when the harness ends, by spawn's window and start's alike. */
@@ -2686,9 +2704,24 @@ export function checkLaunchExecutable(path) {
2686
2704
  return null;
2687
2705
  } catch (e) { return `${path} ${e.code === "ENOENT" ? "does not exist" : e.code === "EACCES" ? "is not executable" : e.message}`; }
2688
2706
  }
2689
- /** Source names of {fromEnv} references absent from `env`. */
2707
+ /** Source names of host references that cannot be resolved. Status recipes redact literals
2708
+ * as objects too; only reference-shaped entries have a source to resolve. */
2690
2709
  export function missingLaunchEnvRefs(configEnv, env = process.env) {
2691
- return Object.values(configEnv || {}).filter((v) => v && typeof v === "object" && v.fromEnv && env[v.fromEnv] === undefined).map((v) => v.fromEnv).sort();
2710
+ return Object.values(configEnv || {}).filter((v) => isLaunchEnvReference(v) && referenceValue(v, env) === undefined).map(referenceSource).sort();
2711
+ }
2712
+ /** A /login credential belongs to the person's account. Only an OATS-set token selects
2713
+ * the token route: inherited pane values cannot make that decision for the operator. */
2714
+ function claudeLoginCredential({ harness, launch, configEnv = {}, hooksEnv = {} }) {
2715
+ if (harness !== "claude") return null;
2716
+ const selected = launch.of("CLAUDE_CONFIG_DIR");
2717
+ if (selected.problem || selected.unresolved) return null;
2718
+ const ownHome = selected.value ? null : launch.of("HOME");
2719
+ const dir = selected.value || (ownHome?.value ? join(ownHome.value, ".claude") : null);
2720
+ if (!dir || !existsSync(join(dir, ".credentials.json"))) return null;
2721
+ const token = Object.hasOwn(configEnv, "CLAUDE_CODE_OAUTH_TOKEN") || Object.hasOwn(hooksEnv, "CLAUDE_CODE_OAUTH_TOKEN");
2722
+ return token
2723
+ ? { code: "E_CLAUDE_LOGIN_CREDENTIAL", message: `Claude has a /login credential at ${join(dir, ".credentials.json")} alongside the token OATS sets. Remove that /login credential before starting. Use oats harness token set claude to provision an inference-only token.` }
2724
+ : null;
2692
2725
  }
2693
2726
  /** The selection a start makes: which configuration (explicit name, "none",
2694
2727
  * a frozen recipe's, or the soul's default), and from it the harness and
@@ -2837,10 +2870,16 @@ export function launchReportFor({ layers, launchConfigs = {}, contextDir }) {
2837
2870
  * name: the command says NAME="$OATS_LAUNCH_REF_NAME", so no source
2838
2871
  * variable is ever named in the command and no assignment in the same
2839
2872
  * prefix can shadow it (zsh evaluates a prefix's assignments in order).
2840
- * Each goes to the pane as a tmux `-e NAME=value` argument. */
2873
+ * Each goes to the pane through a private per-start handoff file. */
2841
2874
  export function launchEnvRefs(recipe, env = process.env) {
2842
- const out = [];
2843
- for (const [name, v] of Object.entries(recipe.env || {})) if (v && typeof v === "object" && v.fromEnv && env[v.fromEnv] !== undefined) out.push({ name: `${LAUNCH_REF_PREFIX}${name}`, value: env[v.fromEnv], target: name, source: v.fromEnv });
2875
+ const out = [], values = new Map();
2876
+ for (const [name, v] of Object.entries(recipe.env || {})) if (isLaunchEnvReference(v)) {
2877
+ const source = referenceSource(v);
2878
+ if (!values.has(source)) values.set(source, referenceValue(v, env));
2879
+ const value = values.get(source);
2880
+ if (value === undefined) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage([referenceSource(v)], recipe.harness));
2881
+ out.push({ name: `${LAUNCH_REF_PREFIX}${name}`, value, target: name, source: referenceSource(v) });
2882
+ }
2844
2883
  return out;
2845
2884
  }
2846
2885
 
@@ -3050,7 +3089,7 @@ function nativeRecordCommand(command, home, harness, { start, scope } = {}) {
3050
3089
  /** The agent's scope of the launch of `command` in a pane with `pane`'s environment (paneEnvironment)
3051
3090
  * → agentScope's answer. The values the probe gets for SCOPE_ENV_NAMES are the ones systemd-run
3052
3091
  * will run with: what the command's environment prefix sets (a literal, or a reference whose source
3053
- * is one of `refs`, the pane's `-e` values, else the pane's own), else nothing for a name the launch
3092
+ * is one of `refs`, the private handoff's values, else the pane's own), else nothing for a name the launch
3054
3093
  * removes (paneCommand's `unset`), else the pane's. `io` is a test's (agentScope). */
3055
3094
  function agentScopeOn(command, { pane, removed = [], refs = [] }, io) {
3056
3095
  return agentScope({ io, paneEnv: () => {
@@ -3086,7 +3125,10 @@ export function assertLaunchRecipe(recipe, what) {
3086
3125
  if (typeof recipe.executable !== "string" || !recipe.executable) bad("no executable");
3087
3126
  if (!Array.isArray(recipe.args) || recipe.args.some((a) => typeof a !== "string")) bad("args are not a list of strings");
3088
3127
  if (!recipe.env || typeof recipe.env !== "object" || Array.isArray(recipe.env)) bad("env is not a map");
3089
- for (const [n, v] of Object.entries(recipe.env)) if (!(typeof v === "string" || (v && typeof v === "object" && typeof v.fromEnv === "string"))) bad(`env ${n} is neither a string nor a reference`);
3128
+ for (const [n, v] of Object.entries(recipe.env)) {
3129
+ if (!(typeof v === "string" || isLaunchEnvReference(v))) bad(`env ${n} is neither a string nor a reference`);
3130
+ if (v?.fromFile !== undefined && DIRECTORY_LAUNCH_ENV.has(n)) bad(fileLocationMessage(n));
3131
+ }
3090
3132
  if (recipe.model !== null && recipe.model !== undefined && typeof recipe.model !== "string") bad("model is not text");
3091
3133
  if (recipe.yolo !== undefined && typeof recipe.yolo !== "boolean") bad("yolo is not a boolean");
3092
3134
  if (!recipe.hooks || typeof recipe.hooks !== "object") bad("no hooks record");
@@ -3203,8 +3245,10 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3203
3245
  fail("environment", "E_LAUNCH_ENV_CONFLICT", `${owned.map((n) => `${n} (set by ${owner(n)})`).join(", ")} cannot be overridden by launch configuration ${config?.name}; change the capability's setting instead`);
3204
3246
  }
3205
3247
  const missing = missingLaunchEnvRefs(configEnv, env);
3206
- if (missing.length) fail("environment", "E_LAUNCH_ENV_MISSING", `launch configuration ${config?.name} references ${missing.join(", ")}, not set on this host; nothing was stopped or started`);
3248
+ if (missing.length) fail("environment", "E_LAUNCH_ENV_MISSING", missing.some((name) => name.startsWith("file:")) ? launchEnvMissingMessage(missing, harness) : `launch configuration ${config?.name} references ${missing.join(", ")}, not set on this host; nothing was stopped or started${fileReferenceRemedy(missing, harness)}`);
3207
3249
  else if (!owned.length) problems.push({ check: "environment", ok: true, detail: `${Object.keys(configEnv).length} value(s), references resolved on the execution host at start` });
3250
+ const login = claudeLoginCredential({ harness, configEnv, hooksEnv: hooks.env, launch: launchEnvironment({ configEnv, capabilities: { env: hooks.env }, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) });
3251
+ if (login?.code) fail("credentials", login.code, login.message);
3208
3252
  problems.push({ check: "model", ok: true, detail: model ? `${model} (${modelSource})` : `native default (${modelSource})` });
3209
3253
  // Harness package requirements: the captured providers' (bindings united
3210
3254
  // with contributions, by id, current manifest, captured settings for
@@ -3285,7 +3329,7 @@ export function launchEffectiveEnv({ base = process.env, hooksEnv = {}, configEn
3285
3329
  Object.assign(out, hooksEnv);
3286
3330
  for (const [name, v] of Object.entries(configEnv || {})) {
3287
3331
  if (typeof v === "string") out[name] = v;
3288
- else if (v && typeof v === "object" && v.fromEnv && base[v.fromEnv] !== undefined) out[name] = base[v.fromEnv];
3332
+ else if (v && typeof v === "object") { const value = referenceValue(v, base); if (value !== undefined) out[name] = value; }
3289
3333
  }
3290
3334
  for (const name of PANE_ENV_NAMES) {
3291
3335
  const answer = launch.of(name);
@@ -3472,6 +3516,11 @@ export async function spawnInstanceAsync(root, agent, o = {}) {
3472
3516
  }
3473
3517
  return step.value;
3474
3518
  }
3519
+ /** The command a spawn's answer gives to attach to its instance: the tmux session of its window when
3520
+ * it was launched (`meta.tmux` then names the socket), else the session surface by home. */
3521
+ function spawnAttach(meta, launched) {
3522
+ return launched ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(meta.tmux.session)}` : `oats session attach --home ${shellWord(meta.home)}`;
3523
+ }
3475
3524
  /** The producer sets this only when dispatched effects or their compensation
3476
3525
  * cannot be confirmed. A diagnostic's wording or home path is not evidence. */
3477
3526
  function unconfirmedSpawn(error) {
@@ -3595,7 +3644,7 @@ function* spawnBody(root, agent, o = {}) {
3595
3644
  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 }));
3596
3645
  // The receipt's warnings that are facts of the composition (a hook event this kernel ignores),
3597
3646
  // from the home's module copies: nothing runs again, and the captured composition is unchanged.
3598
- 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) };
3647
+ return { ...prior, background: readInstanceBackground(prior.home), replayed: true, launch: undefined, command: undefined, attach: spawnAttach(prior, prior.launched === true && !!prior.tmux?.socket), wake: prior.wake ?? { requested: null, saved: null, error: null }, warnings: replayedContractWarnings(prior.home) };
3599
3648
  }
3600
3649
  }
3601
3650
 
@@ -3924,7 +3973,12 @@ function* spawnBody(root, agent, o = {}) {
3924
3973
  { const bad = checkLaunchExecutable(executable.path); if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig?.name || "(harness default)"}: ${bad}`); }
3925
3974
  const bin = executable.path;
3926
3975
  const missingRefs = missingLaunchEnvRefs(launchConfig?.env || {}, process.env);
3927
- if (missingRefs.length) throw oatsError("E_LAUNCH_ENV_MISSING", `launch configuration ${launchConfig.name} references ${missingRefs.join(", ")}, not set in this environment; nothing was created`);
3976
+ if (missingRefs.length) throw oatsError("E_LAUNCH_ENV_MISSING", missingRefs.some((name) => name.startsWith("file:")) ? launchEnvMissingMessage(missingRefs, harness) : `launch configuration ${launchConfig.name} references ${missingRefs.join(", ")}, not set in this environment; nothing was created${fileReferenceRemedy(missingRefs, harness)}`);
3977
+ const preflightRemoved = removedLaunchEnv({ declared: declaredLaunchEnv(resolvedCfg.capabilities), configEnv: launchConfig?.env });
3978
+ // A hook-owned selector has no value until hooks run; its final check remains below.
3979
+ const selectorPending = !Object.hasOwn(launchConfig?.env || {}, "CLAUDE_CONFIG_DIR") && resolvedCfg.capabilities.some((cap) => cap.environment?.includes("CLAUDE_CONFIG_DIR") && (cap.hooks?.spawn || cap.hooks?.launch));
3980
+ const loginPreflight = selectorPending ? null : claudeLoginCredential({ harness, configEnv: launchConfig?.env, launch: launchEnvOn(expectedEnv.pane, preflightRemoved) });
3981
+ if (loginPreflight?.code) throw oatsError(loginPreflight.code, loginPreflight.message);
3928
3982
  // A configuration's executable answers the package probe (without one the
3929
3983
  // context-selected name does, as before: its remedies name that command),
3930
3984
  // under the environment the launch will have (launchEffectiveEnv: the
@@ -4153,9 +4207,19 @@ function* spawnBody(root, agent, o = {}) {
4153
4207
  if (o.prepared) {
4154
4208
  // The soul's AGENTS.md is the body materialize composes onto: the capability
4155
4209
  // injects in the resolution's instruction order, then the kernel's blocks.
4210
+ // The copy is the one wait between the home's creation and its first hook. A SIGINT, SIGTERM
4211
+ // or SIGHUP that arrives during it is held (signalGuard, as while the worktree hooks run): the
4212
+ // process is not ended with a home that has no record. The copy ends, by itself or because the
4213
+ // signal closed what it read from, and the home is removed as for any failure here.
4214
+ const copyGuard = signalGuard();
4156
4215
  try {
4157
4216
  const kernelBlocks = composition.blocks.filter((b) => !b.source.startsWith("capability:"));
4158
- materializeOutcome = yield () => (o.materialize ?? materializePreparedDefault)({ ...o.prepared, soulAgentsMd: composition.body, blocks: kernelBlocks, soulDir }, home);
4217
+ try { materializeOutcome = yield () => (o.materialize ?? materializePreparedDefault)({ ...o.prepared, soulAgentsMd: composition.body, blocks: kernelBlocks, soulDir }, home); }
4218
+ catch (e) { if (!copyGuard.signal) throw e; }
4219
+ if (copyGuard.signal) {
4220
+ throw Object.assign(oatsError("E_INTERRUPTED", `the spawn was interrupted by ${copyGuard.signal} while its capabilities were copied into the home; no hook had run`),
4221
+ { exitStatus: interruptExitStatus(copyGuard.signal), details: { signal: copyGuard.signal, hooks: [] } });
4222
+ }
4159
4223
  const rows = (typeof o.prepared.toCapabilityRows === "function" ? o.prepared.toCapabilityRows : toCapabilityRows)(o.prepared.resolution, home);
4160
4224
  if (!Array.isArray(rows)) throw new Error("toCapabilityRows returned no rows");
4161
4225
  for (const row of rows) row.hooks = materializedHookCommands(row, home);
@@ -4204,6 +4268,7 @@ function* spawnBody(root, agent, o = {}) {
4204
4268
  }
4205
4269
  }
4206
4270
  } catch (e) { throw rollbackEmptyOrPreparedHome(e); }
4271
+ finally { copyGuard.restore(); }
4207
4272
  }
4208
4273
  initializeNativeHistory(home);
4209
4274
 
@@ -4327,9 +4392,21 @@ function* spawnBody(root, agent, o = {}) {
4327
4392
  if (work === "worktree") {
4328
4393
  branch = plannedBranch;
4329
4394
  const wt = join(home, "work");
4395
+ // The checkout writes the tree's files: no filter driver the repository's configuration
4396
+ // defines runs in it, nor the file monitor it names (lib/instance-git.mjs workTreeOverrides).
4397
+ // This Git reads the operator's own configuration, so a driver of a name that configuration
4398
+ // defines too runs with the operator's command. Nothing outside the home exists yet, so
4399
+ // removing the scaffold is the whole rollback.
4400
+ const filters = workTreeOverrides(["-C", repoAbs], process.env);
4401
+ if (!filters.ok) {
4402
+ let removal = " — spawn rolled back", removalFailed = false;
4403
+ try { rmSync(home, { recursive: true, force: true }); } catch (e) { removalFailed = true; removal = ` — rollback INCOMPLETE, remove ${home} manually: ${e.message}`; }
4404
+ const error = oatsError("E_WORK_INSPECTION_FAILED", `could not make the instance worktree: git worktree add was not run in ${repoAbs}: ${filters.err}${removal}`);
4405
+ throw removalFailed ? unconfirmedSpawn(error) : error;
4406
+ }
4330
4407
  let added = false;
4331
4408
  try {
4332
- execFileSync("git", ["-C", repoAbs, "worktree", "add", wt, "-b", branch, plannedBase.oid],
4409
+ execFileSync("git", [...filters.args, "-C", repoAbs, "worktree", "add", wt, "-b", branch, plannedBase.oid],
4333
4410
  { stdio: ["ignore", "pipe", "pipe"] });
4334
4411
  added = true;
4335
4412
  // Git registers a canonical path. Retain it now: compensation hooks can
@@ -4417,11 +4494,69 @@ function* spawnBody(root, agent, o = {}) {
4417
4494
  // soul), never the swappable agents/<name>/soul pointer: a provider that pins a
4418
4495
  // path must pin this instance's content, and OATS_SOUL_ID is what it keys on.
4419
4496
  const harnessExecutableHanded = harnessExecutableEnv(bin, !!(executable.lookup || launchConfig?.executable?.includes("/")));
4420
- const hookRes = runLifecycleHooks("spawn", {
4497
+ // What the record says of the workspace and the teams, for the final record and, before it, for
4498
+ // the marker written ahead of the spawn hooks: a retire's hooks read both from the record.
4499
+ // M5/3a: the workspace's name and the deployment directory are recorded, so a home
4500
+ // answers them (inspect/operation run --home, OATS_WORKSPACE_NAME) without discovery.
4501
+ // Team model v2: the teams at spawn, exactly as the providers received them (OATS_TEAMS: mapped
4502
+ // rows only) and the default, recorded as EVIDENCE beside `providers` (never inside that
4503
+ // capability-keyed map). A home's hooks and operations get the LIVE set (liveTeams); this is
4504
+ // what they fall back to when the workspace cannot answer.
4505
+ const workspaceRecord = o.prepared ? {
4506
+ workspace: { key: o.prepared.discovery?.key ?? null, name: o.prepared.discovery?.workspace?.name ?? null, deployment: o.prepared.deployment ?? null, commit: o.prepared.discovery?.commit ?? null, resolution: o.prepared.resolution.revision, standalone: o.prepared.discovery?.standalone === true, soul: { id: preparedSoulIdOf(o.prepared.soulEntry), repoKey: o.prepared.soulEntry.repoKey, commit: o.prepared.soulEntry.commit, ...(typeof o.prepared.soulEntry.package === "string" ? { name: o.prepared.soulEntry.name, qualifiedName: o.prepared.soulEntry.qualifiedName, package: { id: o.prepared.soulEntry.package, version: o.prepared.soulEntry.version, commit: o.prepared.soulEntry.commit, digest: o.prepared.soulEntry.digest, path: o.prepared.soulEntry.path } } : {}) }, layers: layerRows(o.prepared.resolution) },
4507
+ teams: envRows(o.prepared.resolution.teams ?? []),
4508
+ defaultTeam: structuredClone(o.prepared.resolution.defaultTeam ?? null),
4509
+ } : {};
4510
+ // #796: the `worktree` hooks this spawn fires (work: worktree only), their run, and the
4511
+ // in-progress marker that covers a parent killed while its spawn or worktree hooks run.
4512
+ const treeHooks = work === "worktree" ? worktreeHooksOf(resolvedCfg.capabilities) : [];
4513
+ let worktreeRun = null, treeGuard = null, inProgressMarker = false;
4514
+ let hookRes = null;
4515
+ const inProgressStartedAt = new Date().toISOString();
4516
+ /** `event`: the hooks the spawn is about to run, or runs, when it writes the marker ("spawn",
4517
+ * "worktree"). Until the spawn hooks have answered, each capability with a spawn hook may have
4518
+ * started: the retire hook of every one of them is owed, and there is no receipt of theirs yet. */
4519
+ const writeSpawnInProgressMarker = (event, hook) => {
4520
+ const attempted = hookRes ? hookRes.order || [] : resolvedCfg.capabilities.filter((c) => c.hooks?.spawn).map((c) => c.id);
4521
+ const retireOwed = new Set(attempted.filter((id) => resolvedCfg.capabilities.find((c) => c.id === id)?.hooks?.retire));
4522
+ // Never through a home a hook put in its place.
4523
+ if (work === "directory") assertDirectoryHome(home, homeReal);
4524
+ writeQuarantineMarker(home, buildQuarantineMarker({
4525
+ instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId,
4526
+ incomplete: [event === "worktree" ? "the spawn is running its worktree hooks; until its process is gone this home is a spawn in progress" : "the spawn has not written its record; until its process is gone this home is a spawn in progress"],
4527
+ failed: [{ capability: "oats.kernel", event }],
4528
+ outstandingHooks: retireOwed, outstandingGit: new Set(work !== "worktree" ? [] : branch ? ["worktree", "branch"] : ["worktree"]),
4529
+ repoAbs, work, branch, resolvedCfg, hookMeta: hookRes?.meta || {}, launched: false, tmux: { session, window: instance },
4530
+ reason: event === "worktree" ? "spawn interrupted while its worktree hooks ran" : "spawn interrupted before its record was written",
4531
+ workspaceRecord,
4532
+ }), { inProgress: { ...selfIdentity(), startedAt: inProgressStartedAt, branch, baseOid: plannedBase?.oid, ...hook } }, work === "directory" ? 0o600 : undefined);
4533
+ inProgressMarker = true;
4534
+ };
4535
+ // The spawn's commit point for the marker: the final instance.json is written. The marker goes
4536
+ // before the final baseline is taken: the baseline digests the home, and a home digested with
4537
+ // the marker in it would read as changed since spawn at every retire.
4538
+ const clearSpawnInProgressMarker = () => {
4539
+ if (!inProgressMarker) return;
4540
+ rmSync(join(home, ".oats-rollback-incomplete.json"), { force: true });
4541
+ inProgressMarker = false;
4542
+ };
4543
+ // Write-ahead: what a retire needs to run the retire hooks (the repository they come from, the
4544
+ // capabilities, the soul) is on disk before the first spawn hook runs. Until the final record
4545
+ // is written, instance.json is the stub lib/materialize.mjs wrote, which names none of it: a
4546
+ // spawn killed in between (SIGKILL, a container stop) would leave a home whose retire could run
4547
+ // no hook, with what its spawn hooks registered outside the home still there. Written only when
4548
+ // a spawn hook is about to run whose capability has a retire hook: nothing else is owed yet.
4549
+ if (resolvedCfg.capabilities.some((c) => c.hooks?.spawn && c.hooks?.retire)) writeSpawnInProgressMarker("spawn", {});
4550
+ hookRes = runLifecycleHooks("spawn", {
4421
4551
  home, instance, agentName: agent.name, soulDir: homeSoulTarget, soulId: preparedSoulId, contextDir: repoAbs,
4422
4552
  workspaceDir: workspaceOf(root), rootDir: root, resolved: resolvedCfg,
4423
4553
  extraEnv: { OATS_TASK: task, OATS_REPO: repoAbs, OATS_BRANCH: branch || "", OATS_WORK: work, OATS_HARNESS: harness, ...harnessExecutableHanded, OATS_RUNTIME: harness, OATS_KIND: agent.kind || "persistent", ...(triggerEventFile ? { OATS_TRIGGER_EVENT_FILE: triggerEventFile } : {}), ...(spawnedBy ? { OATS_SPAWNER_HOME: spawnedBy.home } : {}) },
4424
4554
  });
4555
+ // The spawn hooks' receipt (their `meta`), on disk as soon as there is one: a retire after a kill
4556
+ // from here on hands it to the retire hooks.
4557
+ if (inProgressMarker) {
4558
+ try { writeSpawnInProgressMarker("spawn", {}); } catch { /* the marker written before the hooks stands: it owes the same retire hooks, without the receipt */ }
4559
+ }
4425
4560
  warnings.push(...hookRes.warnings);
4426
4561
  if (kernelNode().warning) warnings.push(kernelNode().warning);
4427
4562
  // Which capability hooks RAN (in order) and how each ended — recorded on the
@@ -4451,32 +4586,6 @@ function* spawnBody(root, agent, o = {}) {
4451
4586
  throw new Error(`relation "parent": failed to re-point anchor "${relativeTo}" (${e.message})`);
4452
4587
  }
4453
4588
  };
4454
- // #796: the `worktree` hooks this spawn fires (work: worktree only), their run, and the
4455
- // in-progress marker that covers a parent killed while they run.
4456
- const treeHooks = work === "worktree" ? worktreeHooksOf(resolvedCfg.capabilities) : [];
4457
- let worktreeRun = null, treeGuard = null, inProgressMarker = false;
4458
- const writeSpawnInProgressMarker = (hook) => {
4459
- const retireOwed = new Set((hookRes.order || []).filter((id) => resolvedCfg.capabilities.find((c) => c.id === id)?.hooks?.retire));
4460
- writeQuarantineMarker(home, buildQuarantineMarker({
4461
- instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId,
4462
- incomplete: ["the spawn is running its worktree hooks; until its process is gone this home is a spawn in progress"],
4463
- failed: [{ capability: "oats.kernel", event: "worktree" }],
4464
- outstandingHooks: retireOwed, outstandingGit: new Set(branch ? ["worktree", "branch"] : ["worktree"]),
4465
- repoAbs, work, branch, resolvedCfg, hookMeta: hookRes.meta || {}, launched: false, tmux: { session, window: instance },
4466
- reason: "spawn interrupted while its worktree hooks ran",
4467
- }), { inProgress: { ...selfIdentity(), startedAt: inProgressStartedAt, branch, baseOid: plannedBase.oid, ...hook } });
4468
- if (!inProgressMarker) {
4469
- inProgressMarker = true;
4470
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: { session, window: instance } });
4471
- }
4472
- };
4473
- const inProgressStartedAt = new Date().toISOString();
4474
- // The spawn's commit point for the marker: the final instance.json and baseline are written.
4475
- const clearSpawnInProgressMarker = () => {
4476
- if (!inProgressMarker) return;
4477
- rmSync(join(home, ".oats-rollback-incomplete.json"), { force: true });
4478
- inProgressMarker = false;
4479
- };
4480
4589
  let promptDispatched = false, promptTarget, promptResult, promptStartId;
4481
4590
  let windowMayExist = false;
4482
4591
  let spawnTmux;
@@ -4649,7 +4758,8 @@ function* spawnBody(root, agent, o = {}) {
4649
4758
  // The marker names this process by pid and start; one whose start cannot be read could not be told
4650
4759
  // apart from a dead one after a kill, so the spawn does not run its worktree hooks without it.
4651
4760
  if (!processStartToken(process.pid)) throw oatsError("E_SPAWN_FAILED", `this process's start time cannot be read, so a spawn killed while its worktree hooks ran could not be recovered safely; no worktree hook ran`);
4652
- writeSpawnInProgressMarker({});
4761
+ writeSpawnInProgressMarker("worktree", {});
4762
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: { session, window: instance } });
4653
4763
  treeGuard = signalGuard();
4654
4764
  const treeEnv = {
4655
4765
  OATS_TREE: tree, OATS_TREE_CLONE: cloneReal, OATS_TREE_REMOTE: originRemoteOf(cloneReal),
@@ -4659,7 +4769,7 @@ function* spawnBody(root, agent, o = {}) {
4659
4769
  worktreeRun = yield () => runWorktreeHooks(treeHooks, {
4660
4770
  envFor: (cap) => lifecycleHookEnv("worktree", cap, { home, instance, agentName: agent.name, soulDir: homeSoulTarget, soulId: preparedSoulId, contextDir: repoAbs, workspaceDir: workspaceOf(root), rootDir: root, resolved: resolvedCfg, priorMeta: hookRes.meta || {}, extraEnv: treeEnv }),
4661
4771
  cwd: tree, home, purpose: "", guard: treeGuard,
4662
- onStart: ({ pgid, hookStart }) => writeSpawnInProgressMarker({ hookPgid: pgid, hookStart }),
4772
+ onStart: ({ pgid, hookStart }) => writeSpawnInProgressMarker("worktree", { hookPgid: pgid, hookStart }),
4663
4773
  });
4664
4774
  warnings.push(...worktreeRun.warnings);
4665
4775
  if (worktreeRun.interrupted) {
@@ -4832,15 +4942,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4832
4942
  // digests) in instance.json before this metadata is assembled — carry them.
4833
4943
  if (o.prepared) {
4834
4944
  try { const prior = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); if (prior.modules) meta.modules = prior.modules; if (prior.providers) meta.providers = prior.providers; } catch { /* materialize wrote it; absent means nothing to carry */ }
4835
- // M5/3a: the workspace's name and the deployment directory are recorded, so a home
4836
- // answers them (inspect/operation run --home, OATS_WORKSPACE_NAME) without discovery.
4837
- meta.workspace = { key: o.prepared.discovery?.key ?? null, name: o.prepared.discovery?.workspace?.name ?? null, deployment: o.prepared.deployment ?? null, commit: o.prepared.discovery?.commit ?? null, resolution: o.prepared.resolution.revision, standalone: o.prepared.discovery?.standalone === true, soul: { id: preparedSoulIdOf(o.prepared.soulEntry), repoKey: o.prepared.soulEntry.repoKey, commit: o.prepared.soulEntry.commit, ...(typeof o.prepared.soulEntry.package === "string" ? { name: o.prepared.soulEntry.name, qualifiedName: o.prepared.soulEntry.qualifiedName, package: { id: o.prepared.soulEntry.package, version: o.prepared.soulEntry.version, commit: o.prepared.soulEntry.commit, digest: o.prepared.soulEntry.digest, path: o.prepared.soulEntry.path } } : {}) }, layers: layerRows(o.prepared.resolution) };
4838
- // Team model v2: the teams at spawn, exactly as the providers received them (OATS_TEAMS: mapped
4839
- // rows only) and the default, recorded as EVIDENCE beside `providers` (never inside that
4840
- // capability-keyed map). A home's hooks and operations get the LIVE set (liveTeams); this is
4841
- // what they fall back to when the workspace cannot answer.
4842
- meta.teams = envRows(o.prepared.resolution.teams ?? []);
4843
- meta.defaultTeam = structuredClone(o.prepared.resolution.defaultTeam ?? null);
4945
+ Object.assign(meta, workspaceRecord);
4844
4946
  }
4845
4947
  const spawnWarnings = warnings;
4846
4948
  // Feature instance-same-work: bound to the parent the home records, written before the launch so that
@@ -4860,6 +4962,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4860
4962
  // with whatever environment (a race lost to another creator, a session that overrides a name):
4861
4963
  // one read of it answers the three checks below, each of which reads it only when it has to.
4862
4964
  const pane = paneEnvironment(socket, session, undefined, home);
4965
+ const login = claudeLoginCredential({ harness, configEnv: recipe.env, hooksEnv: hookRes.env, launch: launchEnvironment({ configEnv: recipe.env, capabilities: { env: hookRes.env }, removed: removedEnv, env: process.env, pane, cwd: home }) });
4966
+ if (login?.code) throw oatsError(login.code, login.message);
4863
4967
  const actualEnv = launchEnvOn(pane, removedEnv);
4864
4968
  // The harness looked up again on that PATH. Not there: refused, and the spawn is compensated.
4865
4969
  // Found elsewhere than the preflight found it: the launch runs that one.
@@ -4917,19 +5021,19 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4917
5021
  // Commit the final child metadata and its independent byte authority before
4918
5022
  // the managed harness can write. No child-home transition follows launch.
4919
5023
  writeHomeRecord(home, meta);
4920
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: true, tmux: meta.tmux });
4921
5024
  clearSpawnInProgressMarker();
5025
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: true, tmux: meta.tmux });
4922
5026
  // The first start's launch environment (lib/start-env.mjs), after the baseline, as a start records its own.
4923
- recordStartEnv(home, promptStartId, fromEnvNames(recipe.env), process.env);
5027
+ const refs = launchEnvRefs(recipe, process.env);
5028
+ recordStartEnv(home, promptStartId, refs.map((r) => r.source), Object.fromEntries(refs.map((r) => [r.source, r.value])));
4924
5029
  // Wrap the command so the window drops into an interactive shell when the
4925
5030
  // agent exits (e.g. Ctrl-C) instead of tmux killing the window.
4926
- const refs = launchEnvRefs(recipe, process.env);
4927
5031
  // On the same pane, for the command it runs: whether the harness runs in a scope of its own.
4928
5032
  const scope = agentScopeOn(cmdline, { pane, removed: removedEnv, refs });
4929
5033
  if (scope.warning) spawnWarnings.push(unscoped = scope.warning);
4930
5034
  // The exit marker records how this launch's harness ended (lib/session-end.mjs), as a start's does.
4931
5035
  const windowCmd = paneCommand(exitMarked(nativeRecordCommand(cmdline, home, harness, { start: nativeStart, scope: scope.wrapper }), promptStartId, join(home, START_EXITED_FILE)), removedEnv);
4932
- const paneEnvFlags = refs.flatMap((r) => ["-e", `${r.name}=${r.value}`]);
5036
+
4933
5037
  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`);
4934
5038
  // Only a launch that engages the confirmation needs lineage committed before
4935
5039
  // dispatch: its uncertain input outcome retains the new process and parent
@@ -4940,8 +5044,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4940
5044
  promptDispatched = !!controller;
4941
5045
  let windowId;
4942
5046
 
4943
- 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(); }
4944
- catch (e) { throw launchFailed("new-window", "the window command was refused", e); }
5047
+ const envHandoff = launchEnvHandoff(home, promptStartId, refs);
5048
+ try { windowId = tmuxOn(socket, ["new-window", "-P", "-F", controller ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", instance, "-c", home, envHandoff.wrap(windowCmd), ...markAgentPane(instance)], undefined, oatsWindowEnvironment()).trim(); }
5049
+ catch (e) { envHandoff.remove(); throw launchFailed("new-window", "the window command was refused", e); }
4945
5050
  if (controller) { promptTarget = { ...meta.tmux, ...launchPaneTarget(socket, windowId) }; windowId = promptTarget.windowId; }
4946
5051
  try { prepareAgentWindow(socket, windowId); }
4947
5052
  catch (e) { throw launchFailed("set-option", "the new window's options were refused", e); }
@@ -4959,8 +5064,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4959
5064
  } else {
4960
5065
  meta.launched = false;
4961
5066
  writeHomeRecord(home, meta);
4962
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: meta.tmux });
4963
5067
  clearSpawnInProgressMarker();
5068
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: meta.tmux });
4964
5069
  }
4965
5070
 
4966
5071
  // Ordinary launches and scaffolds commit here; launches that engage the
@@ -4976,7 +5081,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4976
5081
  meta.spawnCompleted = true;
4977
5082
  writeHomeRecord(home, meta); // a kernel-owned field: the baseline fingerprint ignores it
4978
5083
  }
4979
- 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 } : {}) });
5084
+ return deliver({ ...meta, background, ...(backgroundFrom ? { backgroundFrom } : {}), ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: spawnAttach(meta, launch), warnings: spawnWarnings.length ? spawnWarnings : undefined, ...(naming ? { naming } : {}) });
4980
5085
  } catch (error) {
4981
5086
  if (promptDispatched) {
4982
5087
  // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
@@ -5191,7 +5296,7 @@ function deleteBranchAsCreated(run, repoAbs, branch, oid) {
5191
5296
  /** The quarantine marker (`.oats-rollback-incomplete.json`) a rollback that cannot finish leaves:
5192
5297
  * the cleanup descriptor a retry consumes (usableCleanupDescriptor). One builder for the
5193
5298
  * rollback below and for a spawn's in-progress marker (#796), which adds `inProgress`. */
5194
- function buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, reason, directoryPreservation = false, orphanedWork = false }) {
5299
+ function buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, reason, directoryPreservation = false, orphanedWork = false, workspaceRecord = {} }) {
5195
5300
  return {
5196
5301
  // `reason` is optional and DEFAULTS to the spawn wording, so every existing
5197
5302
  // caller is byte-identical; only a caller that supplies one differs. The
@@ -5219,6 +5324,9 @@ function buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, f
5219
5324
  trust: cap.trust, executable: cap.executable,
5220
5325
  })),
5221
5326
  capabilityMeta: hookMeta || {},
5327
+ // A spawn's in-progress marker: the record's `workspace`, `teams` and `defaultTeam`, which
5328
+ // the retire hooks' team and workspace environment is read from and the stub does not hold.
5329
+ ...workspaceRecord,
5222
5330
  },
5223
5331
  createdAt: new Date().toISOString(),
5224
5332
  };
@@ -5351,9 +5459,31 @@ const GIT_MAX_BUFFER = 512 * 1024 * 1024;
5351
5459
  * attempt to every existing instance's retire. These flags leave a status as
5352
5460
  * it was. They are the operator's own; what the retire guards against is
5353
5461
  * configuration the retired agent could write.
5354
- * Known limit: a filter driver that the repository's configuration names and
5355
- * its .gitattributes select can still run during `git status`; turning it
5356
- * off would change what status reports. */
5462
+ *
5463
+ * Filter drivers (`filter.<name>.clean`, `.process`, `.smudge`): Git runs
5464
+ * one when a command reads or writes a work-tree file that carries the
5465
+ * `filter` attribute, and it has no switch that turns filters off. A command
5466
+ * that can do so (every form outside lib/retire-git-forms.mjs's:
5467
+ * `status`, and the `checkout` of a recovery) is preceded by one read of the
5468
+ * repository's own configuration, and every driver that read names is
5469
+ * overridden to no command (lib/instance-git.mjs filterOverrides, which
5470
+ * says what the read covers). A file with such an attribute is then compared
5471
+ * as its bytes are in the work tree: a status reads it by its recorded size
5472
+ * and times first, as always, and by those bytes when they differ. A driver
5473
+ * whose name `-c` cannot carry is not overridden: Git is not run, and the
5474
+ * command fails (retireGitArgv). A driver that the operator's global or
5475
+ * system configuration defines runs as it does for the operator's own Git:
5476
+ * one that only it defines is left alone, and one the repository defines
5477
+ * under the same name is overridden with the operator's values, so the
5478
+ * repository's command for it never runs.
5479
+ * What this does not cover:
5480
+ * - a driver added to the configuration between that read and the command;
5481
+ * - a submodule's own configuration: a status runs Git inside each populated
5482
+ * submodule, and the overrides name this repository's drivers, not the
5483
+ * submodule's;
5484
+ * - `clone` (cloneRecovery), which has no repository to read yet: the
5485
+ * recovery it makes starts with no local configuration, so its checkout
5486
+ * runs only what the operator's own configuration defines. */
5357
5487
  const RETIRE_GIT_FLAGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "diff.external="];
5358
5488
  const RETIRE_GIT_DROPPED_ENV = new Set(["GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_DEFAULT_REF_FORMAT", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_WORK_TREE", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_INDEX_FILE", "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_PREFIX", "GIT_SHALLOW_FILE", "GIT_COMMON_DIR"]);
5359
5489
  function retireGitEnv(env) {
@@ -5363,16 +5493,31 @@ function retireGitEnv(env) {
5363
5493
  }
5364
5494
  return { ...out, GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1", ...env };
5365
5495
  }
5496
+ /** The arguments of one retire Git command in `repo` (null for none): the
5497
+ * flags, the overrides of the filter drivers `repo`'s configuration defines
5498
+ * when the subcommand can read or write a work-tree file, `-C`, then `args`
5499
+ * (the subcommand, after any `-c <setting>` of its own). Throws, and Git is
5500
+ * not run, when the drivers cannot be read or one cannot be overridden: a
5501
+ * status that was not run is a status that failed, never a clean one. */
5502
+ function retireGitArgv(repo, args) {
5503
+ const filters = repo === null || retireGitReadsNoWorkTreeFile(args) ? { ok: true, args: [] } : filterOverrides(["-C", repo], { operatorEnv: retireGitEnv() });
5504
+ if (!filters.ok) throw new Error(`git ${args[retireSubcommandAt(args)]} was not run in ${repo}: ${filters.err}`);
5505
+ return [...RETIRE_GIT_FLAGS, ...filters.args, ...(repo === null ? [] : ["-C", repo]), ...args];
5506
+ }
5366
5507
  /** One retire Git command in `repo` (`-C`; null for none, as for a clone) →
5367
5508
  * its stdout (a Buffer, or text with `encoding`); throws what execFileSync
5368
- * throws. */
5509
+ * throws, or retireGitArgv's error. */
5369
5510
  function retireGit(repo, args, { env, input, encoding } = {}) {
5370
- return execFileSync("git", [...RETIRE_GIT_FLAGS, ...(repo === null ? [] : ["-C", repo]), ...args],
5511
+ return execFileSync("git", retireGitArgv(repo, args),
5371
5512
  { stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input, encoding, maxBuffer: GIT_MAX_BUFFER, shell: false, env: retireGitEnv(env) });
5372
5513
  }
5373
- /** retireGit that never throws → spawnSync's result, for a caller that reads the exit status. */
5514
+ /** retireGit that never throws → spawnSync's result, for a caller that reads the exit status;
5515
+ * a command retireGitArgv did not let run reads as one that could not be started (`error`). */
5374
5516
  function retireGitProbe(repo, args, { encoding } = {}) {
5375
- return spawnSync("git", [...RETIRE_GIT_FLAGS, "-C", repo, ...args], { stdio: ["ignore", "pipe", "pipe"], encoding, maxBuffer: GIT_MAX_BUFFER, shell: false, env: retireGitEnv() });
5517
+ let argv;
5518
+ try { argv = retireGitArgv(repo, args); }
5519
+ catch (error) { return { error, status: null, signal: null, stdout: "", stderr: error.message }; }
5520
+ return spawnSync("git", argv, { stdio: ["ignore", "pipe", "pipe"], encoding, maxBuffer: GIT_MAX_BUFFER, shell: false, env: retireGitEnv() });
5376
5521
  }
5377
5522
 
5378
5523
  /** Kernel-owned receipts the kernel itself appends to a home after the spawn
@@ -5395,7 +5540,7 @@ function retireGitProbe(repo, args, { encoding } = {}) {
5395
5540
  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]);
5396
5541
  // `instance.json.tmp-<pid>` is what a process killed between the two steps of writeJsonAtomic leaves
5397
5542
  // of the record: not a hidden name, so a capability cannot declare it (disposableHomeRootProblem).
5398
- const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, /^instance\.json\.tmp-\d+$/, START_ENV_TMP];
5543
+ const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, /^instance\.json\.tmp-\d+$/, START_ENV_TMP, LAUNCH_ENV_HANDOFF];
5399
5544
  /** Harness project settings in the home are configuration, not work: the
5400
5545
  * home's `.claude/` is harness layout the kernel already shapes (the skills
5401
5546
  * alias), and capabilities keep their own entries current in its
@@ -6333,7 +6478,11 @@ function recordedSessionAbsence(home, meta, io) {
6333
6478
  * (`instanceSessionTarget`), bounded and never escalated: a harness still
6334
6479
  * there after the grace is reported still running, nothing is killed harder.
6335
6480
  * A no-launch or already-idle instance is a no-op that says so. A missing socket
6336
- * file is idle only when no process works in the home (#624). */
6481
+ * file is idle only when no process works in the home (#624).
6482
+ * `withHost: true` is a stop with the host (`oats host run` when the host stops,
6483
+ * lib/host-run.mjs): the same stop, whose record asks for a resume and is written
6484
+ * before the harness is signalled (recordStop), so that the home reads `lost` and
6485
+ * the next start's sweep brings it back, also when the host is killed mid-stop. */
6337
6486
  export function stopInstanceSession(home, o = {}) {
6338
6487
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session stop needs an absolute instance home");
6339
6488
  requireStopGrace(o.graceMs);
@@ -6363,9 +6512,11 @@ function stopStartId(home) {
6363
6512
  * receipt `.oats-stop.json`, `stop` being what was done to the harness (stopHarness's receipt, or
6364
6513
  * null when nothing was signalled). Its `startId` names the start, so the home reads `stopped`
6365
6514
  * and no resume brings that start back. The one writer of the receipt: a stop, an idle stop, and
6366
- * a retire and a restart before they end the session. Throws what the write throws. */
6367
- function recordStop(home, stop) {
6368
- writeJsonAtomic(join(home, STOP_RECEIPT_FILE), { instance: basename(home), at: new Date().toISOString(), stop, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(home) });
6515
+ * a retire and a restart before they end the session. Throws what the write throws.
6516
+ * `withHost`: a stop with the host. Its record says `resume: true` and `reason: "host-stop"`, and
6517
+ * the home reads `lost` (lib/session-end.mjs): a resume brings that start back. */
6518
+ function recordStop(home, stop, { withHost = false } = {}) {
6519
+ writeJsonAtomic(join(home, STOP_RECEIPT_FILE), { instance: basename(home), at: new Date().toISOString(), stop, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(home), ...(withHost ? { resume: true, reason: HOST_STOP_REASON } : {}) });
6369
6520
  }
6370
6521
  /** An explicit stop of a launched home found idle whose session reads `lost` (the host went down or
6371
6522
  * its tmux server died; or a home from before 0.69 whose harness ended): nothing is signalled, but
@@ -6378,13 +6529,14 @@ function recordIdleStop(realHome) {
6378
6529
  catch { /* the idle stop's answer is unchanged: see above */ }
6379
6530
  }
6380
6531
  /** The stop of stopInstanceSession, under the home's claim. The pending self-retire marker is read
6381
- * here, under it: a `--self` retire writes the marker while it holds the claim. */
6532
+ * here, under it: a `--self` retire writes the marker while it holds the claim. A marker whose
6533
+ * completion is gone refuses nothing (retireCarried). */
6382
6534
  function stopSessionClaimed(home, o) {
6383
6535
  const realHome = realPathOrNearest(home);
6384
6536
  // `signalling`: the stop reached the step that signals the harness; `receipt`: that step's answer.
6385
6537
  let signalling = false, receipt;
6386
6538
  try {
6387
- if (existsSync(retirePendingMarkerPath(realHome))) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired; nothing was stopped`);
6539
+ if (retireCarried(realHome)) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired; nothing was stopped`);
6388
6540
  const s = instanceSessionTarget(realHome);
6389
6541
  if (!s.target) return { home: s.home, backend: null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
6390
6542
  let before;
@@ -6394,13 +6546,20 @@ function stopSessionClaimed(home, o) {
6394
6546
  if (lost.gone) before = { present: false, state: "stopped" };
6395
6547
  else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${lost.why ?? e.message}`);
6396
6548
  }
6549
+ const withHost = o.withHost === true;
6397
6550
  if (!before.present || before.state === "shell" || before.state === "stopped") {
6398
- recordIdleStop(realHome);
6551
+ // A stop with the host records nothing of a home it finds idle: one that reads `lost` stays
6552
+ // lost, for the sweep.
6553
+ if (!withHost) recordIdleStop(realHome);
6399
6554
  return { home: s.home, backend: s.target.backend, stopped: false, alreadyIdle: true, state: before.state, receipt: null };
6400
6555
  }
6556
+ // A stop with the host is recorded before the signal: a host killed while the harness ends
6557
+ // leaves a home that reads `lost`, never `exited`. A record that cannot be written stops
6558
+ // nothing: the harness is then ended by the host, with no record, which reads `lost` too.
6559
+ if (withHost) recordStop(realHome, null, { withHost });
6401
6560
  signalling = true;
6402
6561
  receipt = stopHarness(s.target, { graceMs: o.graceMs ?? 20000, kill: o.io?.kill, sleep: o.io?.sleep });
6403
- recordStop(realHome, receipt);
6562
+ recordStop(realHome, receipt, { withHost });
6404
6563
  appendEvent(realHome, { kind: receipt.exited ? "stopped" : "stop-refused", data: { signal: receipt.signal, waitedMs: receipt.waitedMs, stillRunning: receipt.stillRunning ?? [], state: receipt.state } });
6405
6564
  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 });
6406
6565
  return { home: s.home, backend: s.target.backend, stopped: true, alreadyIdle: false, state: receipt.state, receipt };
@@ -6885,7 +7044,7 @@ function startSession(home, o) {
6885
7044
  // spawned records no modules, and there is no scope configuration left to
6886
7045
  // re-resolve it against. Retire still works on it.
6887
7046
  if (!isWorkspaceHome(readMeta())) throw preWorkspaceHome(realHome, "nothing was started");
6888
- let drift; // Read under the start lock, so an upgrade cannot swap modules between reads.
7047
+ let drift; // Read under the home's claim, so an upgrade cannot swap modules between reads.
6889
7048
  let cleanupWarnings = [];
6890
7049
  // A missing socket file is a stopped server only when no process works in this home (#624): its
6891
7050
  // check, for a recorded session and for the OATS server lookup. A failed read of a recorded session
@@ -6942,512 +7101,540 @@ function startSession(home, o) {
6942
7101
  if (clearPending) { checkRoots(); rmSync(pendingPath, { force: true }); }
6943
7102
  return { ...(drift.length ? { drift } : {}), instance: meta.instance, agent: meta.agent, home: realHome, harness: next.harness, backend: "tmux", model: model ?? null, launchConfig: next.launch?.launchConfig ?? null, yolo: next.yolo ?? null, target, startedAt, restartCount: next.restartCount, reused, warnings: cleanupWarnings, ...(launchPrompts ? { launchPrompts } : {}), ...(nativeRecordId ? { nativeRecordId } : {}), ...(stop ? { stop } : {}) };
6944
7103
  };
6945
- try { mkdirSync(lock); }
6946
- catch (e) {
6947
- if (e.code === "EEXIST") {
6948
- const retry = upgradeMutexRetry(realHome);
6949
- if (retry) throw oatsError("E_SESSION_START_BUSY", `a package upgrade of ${basename(realHome)} holds the start mutex (${lock}); nothing was stopped or started. Retry ${retry} to finish the upgrade before starting`);
6950
- throw oatsError("E_SESSION_START_BUSY", `another start of ${basename(realHome)} is in progress (${lock}); if no start is running, remove that directory and retry`);
7104
+ refuseStartMutex(realHome, lock);
7105
+ // An upgrade holds the home's claim while it applies, and this start holds it now: what an
7106
+ // upgrade left is read from here on.
7107
+ assertNoPartialUpgrade(realHome);
7108
+ cleanupWarnings = upgradeCleanupWarnings(realHome);
7109
+ // Compare the frozen package copies with the local deployment lock; starting never moves them.
7110
+ const driftDeployment = dirname(dirname(dirname(dirname(realHome))));
7111
+ let driftLock;
7112
+ try { driftLock = deploymentLock(driftDeployment); }
7113
+ catch (error) {
7114
+ // Drift is advisory; an unreadable deployment lock cannot invalidate a frozen home's launch.
7115
+ cleanupWarnings.push(`package module drift could not be read from ${join(driftDeployment, "oats-lock.json")}: ${error.message}`);
7116
+ }
7117
+ drift = driftLock === undefined ? [] : packageUpgradeDrift(readMeta(), { lock: driftLock });
7118
+ // The package modules an upgrade cannot move (gone from the lock): one line naming the respawn.
7119
+ const respawn = driftLock === undefined ? null : packageRespawnWarning(readMeta(), { lock: driftLock });
7120
+ if (respawn !== null) cleanupWarnings.push(respawn);
7121
+ if (existsSync(join(realHome, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${realHome} is a quarantined home whose cleanup is incomplete; finish its retirement (oats retire) before starting anything there`);
7122
+ // A self-retirement leaves this marker while its detached teardown runs:
7123
+ // the home is about to disappear, so nothing is relaunched into it.
7124
+ // A marker whose completion is gone (the row's `retire` reads `interrupted`) promises a retire
7125
+ // that nothing carries out. The home is owed it, and a start would bring back a home that
7126
+ // retire may have half taken down: the refusal names the retire that finishes it.
7127
+ if (existsSync(retirePendingMarkerPath(realHome))) {
7128
+ throw oatsError("E_INSTANCE_RETIRING", owedRetire(realHome)?.state === "interrupted"
7129
+ ? `${basename(realHome)} is owed a retire (its retire was interrupted): finish it with \`oats retire ${basename(realHome)} --home ${realHome}\`; nothing was started`
7130
+ : `${basename(realHome)} is being retired (${retirePendingMarkerPath(realHome)} is present); nothing was started`);
7131
+ }
7132
+ // A start that leaves the server the home recorded says so: one line per move (see the docs'
7133
+ // "Existing instances"), in the answer and as a launch-warning event.
7134
+ const movedWarnings = [];
7135
+ // 1. Reconcile a pending receipt before the equality gate: it may be the
7136
+ // only record of a session an earlier start allocated.
7137
+ if (existsSync(pendingPath)) {
7138
+ let pending;
7139
+ try { pending = JSON.parse(readFileSync(pendingPath, "utf8")); } catch { pending = undefined; }
7140
+ const pt = pending?.target;
7141
+ const validTarget = pt?.backend === "tmux" && [pt.session, pt.window, pt.socket].every((v) => typeof v === "string" && v.length > 0) && isAbsolute(pt.socket);
7142
+ let validCommand = false;
7143
+ try { parseLaunchCommand(pending?.command); validCommand = true; } catch { /* preserve invalid receipt below */ }
7144
+ let validLaunch = true;
7145
+ if (pending?.launch !== undefined) { try { assertLaunchRecipe(pending.launch, "the pending start"); } catch { validLaunch = false; } }
7146
+ if (pending?.harness !== undefined && !LAUNCH_HARNESSES.includes(pending.harness)) validLaunch = false;
7147
+ if (pending?.yolo !== undefined && typeof pending.yolo !== "boolean") validLaunch = false;
7148
+ const validReceipt = validTarget && validCommand && validLaunch
7149
+ && typeof pending.id === "string" && /^[a-zA-Z0-9-]{1,80}$/.test(pending.id)
7150
+ && (pending.model === null || (typeof pending.model === "string" && !!pending.model.trim() && !pending.model.includes("\0")))
7151
+ && typeof pending.startedAt === "string" && Number.isFinite(Date.parse(pending.startedAt));
7152
+ if (!validReceipt) throw oatsError("E_SESSION_UNKNOWN", `an earlier start left an unreadable or invalid receipt at ${pendingPath}; inspect it before retrying; nothing was started`);
7153
+ let st;
7154
+ checkRoots();
7155
+ try { st = inspectSessionTarget(pending.target, o.io); }
7156
+ catch (e) {
7157
+ const lost = lostServer(e);
7158
+ if (lost.stopped) st = { present: false, state: "stopped" };
7159
+ else throw oatsError("E_SESSION_UNKNOWN", `an earlier start of ${basename(realHome)} recorded a session (tmux ${pending.target.session}:${pending.target.window} on ${pending.target.socket}) that cannot be observed now: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}; the receipt ${pendingPath} is kept and nothing was started`);
6951
7160
  }
6952
- throw e;
6953
- }
6954
- try {
6955
- // Upgrade holds this same start lock while applying; re-read after taking it.
6956
- assertNoPartialUpgrade(realHome);
6957
- cleanupWarnings = upgradeCleanupWarnings(realHome);
6958
- // Compare the frozen package copies with the local deployment lock; starting never moves them.
6959
- const driftDeployment = dirname(dirname(dirname(dirname(realHome))));
6960
- let driftLock;
6961
- try { driftLock = deploymentLock(driftDeployment); }
6962
- catch (error) {
6963
- // Drift is advisory; an unreadable deployment lock cannot invalidate a frozen home's launch.
6964
- cleanupWarnings.push(`package module drift could not be read from ${join(driftDeployment, "oats-lock.json")}: ${error.message}`);
6965
- }
6966
- drift = driftLock === undefined ? [] : packageUpgradeDrift(readMeta(), { lock: driftLock });
6967
- if (existsSync(join(realHome, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${realHome} is a quarantined home whose cleanup is incomplete; finish its retirement (oats retire) before starting anything there`);
6968
- // A self-retirement leaves this marker while its detached teardown runs:
6969
- // the home is about to disappear, so nothing is relaunched into it.
6970
- if (existsSync(retirePendingMarkerPath(realHome))) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired (${retirePendingMarkerPath(realHome)} is present); nothing was started`);
6971
- // A start that leaves the server the home recorded says so: one line per move (see the docs'
6972
- // "Existing instances"), in the answer and as a launch-warning event.
6973
- const movedWarnings = [];
6974
- // 1. Reconcile a pending receipt before the equality gate: it may be the
6975
- // only record of a session an earlier start allocated.
6976
- if (existsSync(pendingPath)) {
6977
- let pending;
6978
- try { pending = JSON.parse(readFileSync(pendingPath, "utf8")); } catch { pending = undefined; }
6979
- const pt = pending?.target;
6980
- const validTarget = pt?.backend === "tmux" && [pt.session, pt.window, pt.socket].every((v) => typeof v === "string" && v.length > 0) && isAbsolute(pt.socket);
6981
- let validCommand = false;
6982
- try { parseLaunchCommand(pending?.command); validCommand = true; } catch { /* preserve invalid receipt below */ }
6983
- let validLaunch = true;
6984
- if (pending?.launch !== undefined) { try { assertLaunchRecipe(pending.launch, "the pending start"); } catch { validLaunch = false; } }
6985
- if (pending?.harness !== undefined && !LAUNCH_HARNESSES.includes(pending.harness)) validLaunch = false;
6986
- if (pending?.yolo !== undefined && typeof pending.yolo !== "boolean") validLaunch = false;
6987
- const validReceipt = validTarget && validCommand && validLaunch
6988
- && typeof pending.id === "string" && /^[a-zA-Z0-9-]{1,80}$/.test(pending.id)
6989
- && (pending.model === null || (typeof pending.model === "string" && !!pending.model.trim() && !pending.model.includes("\0")))
6990
- && typeof pending.startedAt === "string" && Number.isFinite(Date.parse(pending.startedAt));
6991
- if (!validReceipt) throw oatsError("E_SESSION_UNKNOWN", `an earlier start left an unreadable or invalid receipt at ${pendingPath}; inspect it before retrying; nothing was started`);
6992
- let st;
6993
- checkRoots();
6994
- try { st = inspectSessionTarget(pending.target, o.io); }
6995
- catch (e) {
6996
- const lost = lostServer(e);
6997
- if (lost.stopped) st = { present: false, state: "stopped" };
6998
- else throw oatsError("E_SESSION_UNKNOWN", `an earlier start of ${basename(realHome)} recorded a session (tmux ${pending.target.session}:${pending.target.window} on ${pending.target.socket}) that cannot be observed now: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}; the receipt ${pendingPath} is kept and nothing was started`);
6999
- }
7000
- // A launch may still consist entirely of shells (startup files, a
7001
- // shell-script harness). Only its own completion marker proves this
7002
- // is a fallback shell. Never respawn an accepted launch in that gap.
7003
- if (st.present && st.state === "shell") {
7004
- const exited = readStartExited(realHome)?.startId === pending.id;
7005
- if (!exited) throw oatsError("E_SESSION_START_BUSY", `${basename(realHome)} is still starting; refresh its status before retrying`);
7161
+ // A launch may still consist entirely of shells (startup files, a
7162
+ // shell-script harness). Only its own completion marker proves this
7163
+ // is a fallback shell. Never respawn an accepted launch in that gap.
7164
+ if (st.present && st.state === "shell") {
7165
+ const exited = readStartExited(realHome)?.startId === pending.id;
7166
+ if (!exited) throw oatsError("E_SESSION_START_BUSY", `${basename(realHome)} is still starting; refresh its status before retrying`);
7167
+ }
7168
+ const meta = readMeta();
7169
+ // A completed start (#691): its receipt names the start instance.json already records, on the
7170
+ // target it records. The receipt is history then, never authority: nothing of it is recorded
7171
+ // again, so a newer launch recipe or provider metadata stays as it is.
7172
+ const rt = meta.tmux;
7173
+ const sameTarget = rt && rt.session === pt.session && rt.window === pt.window && typeof rt.socket === "string" && !!rt.socket && resolve(rt.socket) === resolve(pt.socket);
7174
+ const running = st.present && st.state !== "shell";
7175
+ // The same start on another target is ambiguous while that other target runs; a restart once it
7176
+ // no longer runs is the way out (the recorded target is instance.json's, the ordinary path's).
7177
+ if (meta.startId === pending.id && !sameTarget && (!o.restart || running)) {
7178
+ throw oatsError("E_SESSION_UNKNOWN", `the start ${pending.id} of ${meta.instance} is recorded on tmux ${rt?.session ?? "?"}:${rt?.window ?? "?"} on ${rt?.socket ?? "?"} (\`oats session inspect --home ${realHome}\` shows it), but its receipt ${pendingPath} names tmux ${pt.session}:${pt.window} on ${pt.socket}; the receipt is kept and nothing was started. If that other target is not this instance's session, stop it (\`tmux -S ${shq(pt.socket)} kill-window -t ${shq(`=${pt.session}:=${pt.window}`)}\`), then run \`oats session restart --home ${realHome}\``);
7179
+ }
7180
+ if (meta.startId === pending.id) {
7181
+ if (running && !o.restart) {
7182
+ const asked = (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), meta.harness) !== meta.model) || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined || o.reselectLaunch === true;
7183
+ throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running; nothing was started${asked ? "; the requested model, launch configuration, harness or yolo was not applied: use session restart" : ""}`);
7006
7184
  }
7007
- const meta = readMeta();
7008
- // A completed start (#691): its receipt names the start instance.json already records, on the
7009
- // target it records. The receipt is history then, never authority: nothing of it is recorded
7010
- // again, so a newer launch recipe or provider metadata stays as it is.
7011
- const rt = meta.tmux;
7012
- const sameTarget = rt && rt.session === pt.session && rt.window === pt.window && typeof rt.socket === "string" && !!rt.socket && resolve(rt.socket) === resolve(pt.socket);
7013
- const running = st.present && st.state !== "shell";
7014
- // The same start on another target is ambiguous while that other target runs; a restart once it
7015
- // no longer runs is the way out (the recorded target is instance.json's, the ordinary path's).
7016
- if (meta.startId === pending.id && !sameTarget && (!o.restart || running)) {
7017
- throw oatsError("E_SESSION_UNKNOWN", `the start ${pending.id} of ${meta.instance} is recorded on tmux ${rt?.session ?? "?"}:${rt?.window ?? "?"} on ${rt?.socket ?? "?"} (\`oats session inspect --home ${realHome}\` shows it), but its receipt ${pendingPath} names tmux ${pt.session}:${pt.window} on ${pt.socket}; the receipt is kept and nothing was started. If that other target is not this instance's session, stop it (\`tmux -S ${shq(pt.socket)} kill-window -t ${shq(`=${pt.session}:=${pt.window}`)}\`), then run \`oats session restart --home ${realHome}\``);
7185
+ // A restart, or a target that is gone or a harness that exited: the ordinary start below
7186
+ // reads instance.json as it is, and its own receipt replaces this one when it launches. A
7187
+ // start refused before that leaves this receipt as it was. The completed start recorded its
7188
+ // own session boundary; it is not recorded again.
7189
+ } else {
7190
+ // Reconcile even an exited target: the independent baseline may
7191
+ // already name it while metadata still names the old allocation.
7192
+ // The adopted start's session boundary, at its launch time, completed
7193
+ // in whichever log the interrupted start did not record it. The receipt's
7194
+ // recipe names its configuration (null: the bare harness); only a receipt
7195
+ // without a recipe falls back to the recorded one.
7196
+ recordStartBoundary(realHome, { startId: pending.id, startedAt: pending.startedAt, harness: pending.harness ?? meta.harness ?? null, backend: "tmux", launchConfig: (pending.launch ? pending.launch.launchConfig : meta.launch?.launchConfig) ?? null, phase: "recovered" });
7197
+ const done = record(meta, { ...pending, model: pending.model ?? undefined, reused: "adopted" }, !st.present || st.state === "shell");
7198
+ // The adopted target is on another server than the home recorded (the start that allocated it
7199
+ // could not record it): this adoption records it, and says so once, here.
7200
+ const recordedSocket = typeof meta.tmux?.socket === "string" && meta.tmux.socket ? resolve(meta.tmux.socket) : null;
7201
+ if (recordedSocket && recordedSocket !== resolve(pending.target.socket)) {
7202
+ const message = sessionMovedWarning(meta.instance, recordedSocket, resolve(pending.target.socket));
7203
+ appendEvent(realHome, { kind: "launch-warning", data: { message } });
7204
+ movedWarnings.push(message);
7018
7205
  }
7019
- if (meta.startId === pending.id) {
7020
- if (running && !o.restart) {
7021
- const asked = (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), meta.harness) !== meta.model) || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined || o.reselectLaunch === true;
7022
- throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running; nothing was started${asked ? "; the requested model, launch configuration, harness or yolo was not applied: use session restart" : ""}`);
7023
- }
7024
- // A restart, or a target that is gone or a harness that exited: the ordinary start below
7025
- // reads instance.json as it is, and its own receipt replaces this one when it launches. A
7026
- // start refused before that leaves this receipt as it was. The completed start recorded its
7027
- // own session boundary; it is not recorded again.
7028
- } else {
7029
- // Reconcile even an exited target: the independent baseline may
7030
- // already name it while metadata still names the old allocation.
7031
- // The adopted start's session boundary, at its launch time, completed
7032
- // in whichever log the interrupted start did not record it. The receipt's
7033
- // recipe names its configuration (null: the bare harness); only a receipt
7034
- // without a recipe falls back to the recorded one.
7035
- recordStartBoundary(realHome, { startId: pending.id, startedAt: pending.startedAt, harness: pending.harness ?? meta.harness ?? null, backend: "tmux", launchConfig: (pending.launch ? pending.launch.launchConfig : meta.launch?.launchConfig) ?? null, phase: "recovered" });
7036
- const done = record(meta, { ...pending, model: pending.model ?? undefined, reused: "adopted" }, !st.present || st.state === "shell");
7037
- // The adopted target is on another server than the home recorded (the start that allocated it
7038
- // could not record it): this adoption records it, and says so once, here.
7039
- const recordedSocket = typeof meta.tmux?.socket === "string" && meta.tmux.socket ? resolve(meta.tmux.socket) : null;
7040
- if (recordedSocket && recordedSocket !== resolve(pending.target.socket)) {
7041
- const message = sessionMovedWarning(meta.instance, recordedSocket, resolve(pending.target.socket));
7042
- appendEvent(realHome, { kind: "launch-warning", data: { message } });
7043
- movedWarnings.push(message);
7044
- }
7045
- if (st.present && st.state !== "shell") {
7046
- if (o.restart) { rmSync(pendingPath, { force: true }); }
7047
- else {
7048
- // The recovered target runs what the receipt says; a choice made
7049
- // now (model, configuration, harness, yolo) was not applied to it.
7050
- if (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), done.harness || meta.harness) !== done.model) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running with its previously requested model; its target was recovered, but the new model was not applied`);
7051
- if (o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running (its pending start was recovered); the requested launch configuration, harness or yolo was not applied; stop it, or use session restart`);
7052
- return { ...done, warnings: [...done.warnings, ...movedWarnings] };
7053
- }
7206
+ if (st.present && st.state !== "shell") {
7207
+ if (o.restart) { rmSync(pendingPath, { force: true }); }
7208
+ else {
7209
+ // The recovered target runs what the receipt says; a choice made
7210
+ // now (model, configuration, harness, yolo) was not applied to it.
7211
+ if (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), done.harness || meta.harness) !== done.model) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running with its previously requested model; its target was recovered, but the new model was not applied`);
7212
+ if (o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running (its pending start was recovered); the requested launch configuration, harness or yolo was not applied; stop it, or use session restart`);
7213
+ return { ...done, warnings: [...done.warnings, ...movedWarnings] };
7054
7214
  }
7055
7215
  }
7056
7216
  }
7057
- // 2. The ordinary gate and observation, all under the lock.
7058
- const receipt = instanceSessionTarget(realHome);
7059
- const meta = readMeta();
7060
- const harness = meta.harness;
7061
- if (!["pi", "claude", "codex"].includes(harness)) throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", `instance ${meta.instance || realHome} records harness ${JSON.stringify(harness)}, which this kernel cannot relaunch`);
7062
- let command = meta.command;
7063
- let model = meta.model || undefined;
7064
- // What this start launches: the frozen command (optionally with another
7065
- // model, re-rendered in place), or, under a selection, the recipe
7066
- // re-resolved against the home's current scoped configuration. Every
7067
- // preflight happens here, before anything is observed or stopped.
7068
- // --reselect-launch (feature launch-preference): apply the home's launch layers now (souls.launch,
7069
- // the recorded soul's launch, the host default) instead of the frozen recipe.
7070
- // `launchOffered`: the caller's read of the workspace's souls (homeSoulsOffered), which the layers need
7071
- // to tell a key of souls.launch that names no soul. A selection the layers would decide never goes on
7072
- // without it: a key that was not checked must not let the launch fall through.
7073
- const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
7074
- if (reselect?.needsOffered && o.launchConfig === undefined && o.harness === undefined) throw oatsError("E_BAD_ARGS", `--reselect-launch of ${meta.instance || realHome} needs a read of the workspace's souls: oats-local.yaml souls.launch holds a key besides "*" and this home's soul has no entry of its own (the caller passes that read as launchOffered: lib/instance-resolution.mjs homeSoulsOffered)`);
7075
- // The session this start opens its window in when it has to create one, and what its creation
7076
- // needs (planOatsTmuxSession), read at most once: by the plan's lookup or by the creation's preflight.
7077
- const planSession = receipt.target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
7078
- let sessionPlanRead;
7079
- const sessionPlan = () => {
7080
- if (!sessionPlanRead) { try { sessionPlanRead = { plan: planOatsTmuxSession(planSession, o.io, { missingSocket }) }; } catch (e) { sessionPlanRead = { error: e }; } }
7081
- if (sessionPlanRead.error) throw sessionPlanRead.error;
7082
- return sessionPlanRead.plan;
7217
+ }
7218
+ // 2. The ordinary gate and observation, all under the home's claim.
7219
+ const receipt = instanceSessionTarget(realHome);
7220
+ const meta = readMeta();
7221
+ const harness = meta.harness;
7222
+ if (!["pi", "claude", "codex"].includes(harness)) throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", `instance ${meta.instance || realHome} records harness ${JSON.stringify(harness)}, which this kernel cannot relaunch`);
7223
+ let command = meta.command;
7224
+ let model = meta.model || undefined;
7225
+ // What this start launches: the frozen command (optionally with another
7226
+ // model, re-rendered in place), or, under a selection, the recipe
7227
+ // re-resolved against the home's current scoped configuration. Every
7228
+ // preflight happens here, before anything is observed or stopped.
7229
+ // --reselect-launch (feature launch-preference): apply the home's launch layers now (souls.launch,
7230
+ // the recorded soul's launch, the host default) instead of the frozen recipe.
7231
+ // `launchOffered`: the caller's read of the workspace's souls (homeSoulsOffered), which the layers need
7232
+ // to tell a key of souls.launch that names no soul. A selection the layers would decide never goes on
7233
+ // without it: a key that was not checked must not let the launch fall through.
7234
+ const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
7235
+ if (reselect?.needsOffered && o.launchConfig === undefined && o.harness === undefined) throw oatsError("E_BAD_ARGS", `--reselect-launch of ${meta.instance || realHome} needs a read of the workspace's souls: oats-local.yaml souls.launch holds a key besides "*" and this home's soul has no entry of its own (the caller passes that read as launchOffered: lib/instance-resolution.mjs homeSoulsOffered)`);
7236
+ // The session this start opens its window in when it has to create one, and what its creation
7237
+ // needs (planOatsTmuxSession), read at most once: by the plan's lookup or by the creation's preflight.
7238
+ const planSession = receipt.target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
7239
+ let sessionPlanRead;
7240
+ const sessionPlan = () => {
7241
+ if (!sessionPlanRead) { try { sessionPlanRead = { plan: planOatsTmuxSession(planSession, o.io, { missingSocket }) }; } catch (e) { sessionPlanRead = { error: e }; } }
7242
+ if (sessionPlanRead.error) throw sessionPlanRead.error;
7243
+ return sessionPlanRead.plan;
7244
+ };
7245
+ // The recorded target, observed once: by the plan's lookup, which must know whether the pane will
7246
+ // be reused before it chooses where to look, or by the gate below. A lost server is a stopped one
7247
+ // (lostServer); any other failure is the gate's refusal (E_SESSION_UNKNOWN), and the lookup does
7248
+ // not decide it.
7249
+ let recordedRead;
7250
+ const recordedState = () => {
7251
+ if (!recordedRead) {
7252
+ try { recordedRead = { state: receipt.target ? inspectSessionTarget(receipt.target, o.io) : { present: false, state: "not-launched" } }; }
7253
+ catch (e) { const lost = lostServer(e); recordedRead = lost.stopped ? { state: { present: false, state: "stopped" } } : { error: lost.why ? new Error(lost.why) : e }; }
7254
+ }
7255
+ return recordedRead;
7256
+ };
7257
+ // A pane the start reuses where it is: one the recorded target shows, running or left as a shell.
7258
+ const reusable = (state) => !!(state?.paneId && (state.present || state.state === "stopped"));
7259
+ const selected = reselect !== null || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined;
7260
+ const hasRecipe = meta.launch && typeof meta.launch === "object";
7261
+ let launchPlan = null, launchHooksPass = null, handedExecutable, hookMeta, hookDialogClaims, explicitModelFrom = null, warnings = [];
7262
+ // --resume: only a home whose session was lost, read here, under the home's claim, before any launch hook
7263
+ // runs. Then the conversation it continues, or the reason it starts fresh (resumeConversation).
7264
+ let resume = null;
7265
+ if (o.resume === true) {
7266
+ 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`);
7267
+ const observed = recordedState();
7268
+ 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}`); }
7269
+ if (observed.state.present && observed.state.state !== "shell") throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${observed.state.state}); nothing was started`);
7270
+ // A home whose retire runs, cannot be told, failed or was interrupted is owed it, never a
7271
+ // resume (read as its status row reads it, under the claim this resume holds).
7272
+ const owed = owedRetire(realHome);
7273
+ if (owed) throw oatsError("E_INSTANCE_RETIRING", `${owedRetireSaid(meta.instance, owed.state)}; nothing was started`);
7274
+ const end = meta.launched === true ? sessionEndOf(realHome, meta) : "never-launched";
7275
+ 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)`);
7276
+ resume = resumeConversation(realHome, meta);
7277
+ }
7278
+ if (selected || hasRecipe) {
7279
+ // Every start of a home with a recipe (ordinary, model-only, or under a
7280
+ // selection) goes through the one planner: recipe shape, the recorded
7281
+ // or selected executable, references, capability contributions under
7282
+ // the captured settings and current trust. A home without a recipe that
7283
+ // is asked for a selection is refused (E_LAUNCH_LEGACY).
7284
+ const context = meta.repo && existsSync(meta.repo) ? resolve(meta.repo) : dirname(dirname(dirname(dirname(realHome))));
7285
+ // o.teams / o.defaultTeam: the home's LIVE teams, computed by an async caller (liveTeams) —
7286
+ // the launch hook re-checks joined memberships against them.
7287
+ const resolvedCfg = resolvedFromHome(realHome, meta, { teams: o.teams, defaultTeam: o.defaultTeam, teamsSource: o.teamsSource });
7288
+ let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
7289
+ // The environment the plan's checks read for this launch's pane (the harness lookup by name,
7290
+ // the package probe, folder trust): a pane the start will reuse, on its own recorded session,
7291
+ // whatever the OATS server holds; otherwise the session's or the server's when a server runs;
7292
+ // when none does, the environment this start will create the server with (read once, here,
7293
+ // for the plan and for the creation below). For a creator that may not create the server no
7294
+ // pane's environment is established: the plan's checks read this process's, and the refusal
7295
+ // comes at the creation's own place, after the start's other preflights.
7296
+ const pane = () => {
7297
+ const recorded = recordedState();
7298
+ if (reusable(recorded.state)) return paneEnvironment(receipt.target.socket, receipt.target.session, o.io, realHome);
7299
+ if (recorded.error) return NO_PANE_READ; // the gate refuses below; no check decides it
7300
+ const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
7301
+ if (!preview || preview.server) return expectedPaneEnvironment(preview, planSession, o.io, realHome);
7302
+ try { return expectedPaneEnvironment(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return SESSION_REFUSED; throw e; }
7083
7303
  };
7084
- // The recorded target, observed once: by the plan's lookup, which must know whether the pane will
7085
- // be reused before it chooses where to look, or by the gate below. A lost server is a stopped one
7086
- // (lostServer); any other failure is the gate's refusal (E_SESSION_UNKNOWN), and the lookup does
7087
- // not decide it.
7088
- let recordedRead;
7089
- const recordedState = () => {
7090
- if (!recordedRead) {
7091
- try { recordedRead = { state: receipt.target ? inspectSessionTarget(receipt.target, o.io) : { present: false, state: "not-launched" } }; }
7092
- catch (e) { const lost = lostServer(e); recordedRead = lost.stopped ? { state: { present: false, state: "stopped" } } : { error: lost.why ? new Error(lost.why) : e }; }
7304
+ const plan = planLaunch({ home: realHome, instance: meta.instance, meta, contextDir: context, agentLike: agent || { harness: meta.harness, model: meta.model, yolo: meta.yolo }, selection: { launchConfig: o.launchConfig, harness: o.harness, model: o.model, yolo: o.yolo }, reselect, resolvedCfg, env: o.env || process.env, assertRoots: checkRoots,
7305
+ pane });
7306
+ launchPlan = { recipe: plan.recipe, command: plan.command, declaredEnv: plan.declaredEnv, harness: plan.harness, model: plan.model, yolo: plan.yolo, executable: plan.executable, executablePaneSide: plan.executablePaneSide, config: plan.config, launchChoice: plan.launchChoice, trustHome: plan.trustHome, modelFrom: modelFromOf(plan.modelSource, { at: "start", prior: meta.modelFrom ?? null }),
7307
+ ...(plan.launchChoice ? { launchFrom: plan.launchChoice.from, launchAt: plan.launchChoice.at, launchDeclared: plan.launchChoice.declared } : {}) };
7308
+ // The plan ran preview-aware launch hooks as a preview: their real run, over the planned
7309
+ // contributions, waits for the rest of preflight.
7310
+ handedExecutable = harnessExecutableEnv(plan.executable.path, plan.executablePaneSide).OATS_HARNESS_EXECUTABLE;
7311
+ if (plan.previewedHooks.length) launchHooksPass = { frozen: { ...plan.frozen, hooks: plan.recipe.hooks }, harness: plan.harness, resolvedCfg, contextDir: context, previewed: plan.recipe.hooks, volatileEnv: plan.volatileEnv, trustHome: plan.trustHome };
7312
+ command = launchPlan.command; model = launchPlan.model;
7313
+ // The other launch hooks ran for real in the plan: their warnings are
7314
+ // events now, whatever the start does next, and the answer carries them.
7315
+ hookMeta = plan.hookMeta;
7316
+ hookDialogClaims = plan.hookDialogClaims;
7317
+ warnings = plan.warnings;
7318
+ for (const message of warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
7319
+ } else if (o.model !== undefined && o.model !== null && String(o.model).trim() !== "") {
7320
+ const resolved = resolveModelPreference(String(o.model), harness);
7321
+ if (!resolved) throw oatsError("E_MODEL_UNKNOWN", `model preference ${JSON.stringify(o.model)} has no entry usable by harness ${harness}; give a ${harness} model id`);
7322
+ command = withLaunchModel(command, resolved);
7323
+ model = resolved; explicitModelFrom = "start";
7324
+ } else parseLaunchCommand(command);
7325
+ // A recorded command starts, and is saved, with its harness's safe task prompt.
7326
+ if (!launchPlan) command = withSafeTaskPrompt(command, harness);
7327
+ // References recorded for this home must resolve on this host on every
7328
+ // start path, and the source variables go to the pane, not the command.
7329
+ const recipeForEnv = launchPlan?.recipe || (meta.launch && typeof meta.launch === "object" ? meta.launch : null);
7330
+ if (recipeForEnv) { const missing = missingLaunchEnvRefs(recipeForEnv.env, o.env || process.env); if (missing.length) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage(missing, recipeForEnv.harness)); }
7331
+ // A resume starts only under the values the start it brings back recorded (lib/start-env.mjs): a
7332
+ // changed one refuses, after a missing one; a start with no record to check (an earlier kernel's,
7333
+ // or one that does not read) is resumed and says so once. Ordinary starts never compare.
7334
+ const paneEnv = recipeForEnv ? launchEnvRefs(recipeForEnv, o.env || process.env) : [];
7335
+ const referenceNames = paneEnv.map((r) => r.source), referenceValues = Object.fromEntries(paneEnv.map((r) => [r.source, r.value]));
7336
+ let envUnverified = null;
7337
+ if (resume && recipeForEnv) {
7338
+ const fit = checkStartEnv(realHome, meta.startId, referenceNames, referenceValues);
7339
+ if (fit.changed) throw oatsError("E_LAUNCH_ENV_CHANGED", launchEnvChangedMessage(fit.changed));
7340
+ if (fit.unverified) warnings.push(envUnverified = launchEnvUnverifiedWarning(meta.instance));
7341
+ }
7342
+
7343
+ checkRoots(); // preparation has run; no backend has been changed
7344
+ let target = receipt.target;
7345
+ const recorded = recordedState();
7346
+ if (recorded.error) { const e = recorded.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}`); }
7347
+ let state = recorded.state;
7348
+ if (state.present && state.state !== "shell" && !o.restart) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${state.state}); nothing was started`);
7349
+ // A caller that will have to create the tmux session reads the environment for it here, unless
7350
+ // the plan's lookup read it already with no server running (an instance that cannot is refused
7351
+ // here either way): after the start's preflights and its planning,
7352
+ // so each of their refusals still answers first, and before the real run of preview-aware
7353
+ // launch hooks, a stop and any write of the home's launch state (record, receipt, pending
7354
+ // start). A launch hook that does not declare launchPreview has already run and its warnings
7355
+ // are already events (above), as before any other late refusal of a start (E_SESSION_RUNNING,
7356
+ // E_LAUNCH_ENV_MISSING); nothing undoes what it did, and the hook contract (above
7357
+ // prepareLaunchHooks) allows such a hook idempotent provider registration, which the next
7358
+ // start repeats. Only when this start will have to create a window: a retained pane is reused
7359
+ // where it is. A restart whose window goes away during its stop is decided at the creation.
7360
+ const retained = reusable(state);
7361
+ const tmuxSessionPlan = retained ? undefined : sessionPlan();
7362
+ // A harness the plan looked up by name is looked up again where its pane will look it up, before
7363
+ // anything is stopped: the retained pane's own session, or the session this start will create
7364
+ // its window in (as planned). Once more on the session ensureOatsTmuxSession returns (below).
7365
+ // Not there: refused. Found elsewhere: the launch runs that one, and records it. Every executable
7366
+ // named bare (the harness's name, a declared name) is looked up again, also one the plan could only
7367
+ // look up on this process's PATH; a recorded (frozen) or a declared path never is.
7368
+ const lookAgain = (pane) => {
7369
+ if (!launchPlan || launchPlan.config?.frozen || launchPlan.config?.executable?.includes("/")) return false;
7370
+ const { config, launchChoice } = launchPlan;
7371
+ const actual = resolveLaunchExecutable({ harness: launchPlan.harness, declared: config?.executable, declaringDir: config?.source, lookup: launchLookup(launchEnvironment({ configEnv: config?.env, configName: config?.name, env: o.env || process.env, pane, cwd: realHome })) });
7372
+ if (!actual.path) throw executableNotOnPanePath(actual, { harness: launchPlan.harness, config, from: launchChoice?.from, at: launchChoice?.at });
7373
+ const bad = checkLaunchExecutable(actual.path);
7374
+ if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${bad}; nothing was started`);
7375
+ launchPlan.executablePaneSide = !!actual.lookup;
7376
+ if (actual.path === launchPlan.recipe.executable) return false;
7377
+ launchPlan.recipe = { ...launchPlan.recipe, executable: actual.path };
7378
+ command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome });
7379
+ return true;
7380
+ };
7381
+ /** The launch runs another program than the hooks that have run were handed: said, and kept in the home. */
7382
+ const noteReplacedExecutable = () => {
7383
+ const replaced = replacedExecutableWarning(handedExecutable, launchPlan?.recipe.executable);
7384
+ if (!replaced) return;
7385
+ handedExecutable = undefined;
7386
+ hookDialogClaims = voidedDialogClaims(hookDialogClaims);
7387
+ warnings.push(replaced);
7388
+ appendEvent(realHome, { kind: "launch-warning", data: { message: replaced } });
7389
+ };
7390
+ lookAgain(retained ? () => paneEnvironment(target.socket, target.session, o.io, realHome) : () => expectedPaneEnvironment(tmuxSessionPlan, planSession, o.io, realHome));
7391
+ // Every preflight has passed: the preview-aware launch hooks run for real
7392
+ // (they may register the home with their provider), before a restart's
7393
+ // stop, and must contribute exactly what they contributed as a preview,
7394
+ // which is what the command was rendered and preflighted from, except the
7395
+ // values of the env their preview declared volatile: those come from this
7396
+ // run, and the command is rendered again with them.
7397
+ if (launchHooksPass) {
7398
+ const { previewed, volatileEnv, trustHome, ...pass } = launchHooksPass;
7399
+ // The looks above have settled what this start expects: that is what its real hooks are handed.
7400
+ const handed = harnessExecutableEnv(launchPlan.recipe.executable, launchPlan.executablePaneSide);
7401
+ // Hooks that ran for real in the plan were handed the plan's: their statements don't reach this one.
7402
+ if (handed.OATS_HARNESS_EXECUTABLE !== handedExecutable) hookDialogClaims = voidedDialogClaims(hookDialogClaims);
7403
+ handedExecutable = handed.OATS_HARNESS_EXECUTABLE;
7404
+ const real = prepareLaunchHooks({ ...pass, extraEnv: handed, home: realHome, meta, assertRoots: checkRoots, pass: "real" });
7405
+ const canon = (v) => canonicalJson(JSON.parse(JSON.stringify(v ?? null)));
7406
+ const stable = (h) => Object.fromEntries(Object.entries(h.env).filter(([n]) => !volatileEnv.includes(n)));
7407
+ if (canon({ launch: real.launch, env: stable(real), contributions: real.contributions }) !== canon({ launch: previewed.launch, env: stable(previewed), contributions: previewed.contributions })) {
7408
+ // A provider's row names its env; the values are in the merged env.
7409
+ const rowOf = (h, id) => { const row = h.contributions.find((c) => c.capability === id); return canon({ row, values: (row?.env || []).map((n) => volatileEnv.includes(n) ? null : h.env[n]) }); };
7410
+ const differing = [...new Set([...real.contributions, ...previewed.contributions].map((c) => c.capability))].filter((id) => rowOf(real, id) !== rowOf(previewed, id));
7411
+ throw oatsError("E_LAUNCH_PREPARATION", `the launch hook of ${differing.join(", ") || "a capability"} returned a contribution that differs from its preview contribution (a launch hook returns the same contribution under OATS_LAUNCH_PREVIEW, apart from the values of its volatileEnv); nothing was stopped or started`);
7412
+ }
7413
+ launchPlan.recipe = { ...launchPlan.recipe, hooks: { launch: real.launch, env: real.env, contributions: real.contributions } };
7414
+ command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome });
7415
+ if (real.meta) hookMeta = { ...(hookMeta || {}), ...real.meta };
7416
+ if (real.dialogClaims) hookDialogClaims = { ...(hookDialogClaims || {}), ...real.dialogClaims };
7417
+ // The real run's warnings are events now, whatever the start does next,
7418
+ // and the answer carries them.
7419
+ warnings = [...warnings, ...real.warnings];
7420
+ for (const message of real.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
7421
+ checkRoots();
7422
+ }
7423
+ // The names this launch removes, from the recipe it runs (a preview-aware hook's real run included).
7424
+ // A home without a recipe (an earlier kernel's) composes no providers at launch: nothing.
7425
+ const removed = launchPlan ? removedLaunchEnv({ declared: launchPlan.declaredEnv, hooksEnv: launchPlan.recipe.hooks?.env, configEnv: launchPlan.recipe.env }) : [];
7426
+ // Check the final hook contributions against the environment actually handed to this start.
7427
+ // Reference values below are the same snapshot the private launcher will receive.
7428
+ const loginOn = (pane) => {
7429
+ const r = launchPlan?.recipe || recipeForEnv;
7430
+ if (!r) return;
7431
+ const configEnv = Object.fromEntries(Object.entries(r.env || {}).map(([name, value]) => [name, typeof value === "string" ? value : paneEnv.find((ref) => ref.target === name)?.value]));
7432
+ const login = claudeLoginCredential({ harness: launchPlan?.harness || harness, configEnv, hooksEnv: r.hooks?.env, launch: launchEnvironment({ configEnv, capabilities: { env: r.hooks?.env }, removed, env: o.env || process.env, pane, cwd: realHome }) });
7433
+ if (login?.code) throw oatsError(login.code, login.message);
7434
+ };
7435
+ loginOn(retained ? () => paneEnvironment(target.socket, target.session, o.io, realHome) : () => expectedPaneEnvironment(tmuxSessionPlan, planSession, o.io, realHome));
7436
+ noteReplacedExecutable();
7437
+ const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
7438
+ ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
7439
+ ...(hookMeta ? { hookMeta } : {}), ...(hookDialogClaims ? { hookDialogClaims } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
7440
+ if (resume?.warning) { warnings.push(resume.warning); appendEvent(realHome, { kind: "launch-warning", data: { message: resume.warning } }); }
7441
+ warnings.push(...launchStartNotices(dirname(dirname(dirname(dirname(home)))), launchPlan?.harness || harness, command));
7442
+ if (kernelNode().warning) warnings.push(kernelNode().warning);
7443
+ const engaged = devChannelEngaged(launchPlan?.harness || harness, command);
7444
+ let stopReceipt = null;
7445
+ if (state.present && state.state !== "shell") {
7446
+ // Restart: every preflight above passed, so ask the running harness to
7447
+ // end and wait, bounded. A harness still there afterwards is reported
7448
+ // as running; nothing is escalated and nothing is launched.
7449
+ // The stop is recorded first, for the start instance.json still names (recordStop, as a
7450
+ // retire does), so a relaunch that fails, or a process that dies before it, leaves a home
7451
+ // that reads `stopped`, never `lost`: no resume brings back what was being restarted. The
7452
+ // relaunch records a new start, which the record does not name. A stop refused here leaves
7453
+ // the record with the harness running: should that harness die later, the home reads
7454
+ // `stopped`. A record that cannot be written (a full disk) does not block the restart.
7455
+ try { recordStop(realHome, null); } catch { /* see above */ }
7456
+ stopReceipt = stopHarness(target, { graceMs: o.stopGraceMs ?? 20000, io: o.io, kill: o.io?.kill, sleep: o.io?.sleep });
7457
+ writeJsonAtomic(join(realHome, ".oats-restart.json"), { instance: meta.instance, at: new Date().toISOString(), stop: stopReceipt, next: { harness: launchPlan?.harness || harness, launchConfig: launchPlan?.recipe.launchConfig ?? null, model: model ?? null } }, 0o600);
7458
+ appendEvent(realHome, { kind: stopReceipt.exited ? "restarted" : "stop-refused", data: { phase: "restart-stop", signal: stopReceipt.signal, waitedMs: stopReceipt.waitedMs, stillRunning: stopReceipt.stillRunning ?? [] } });
7459
+ if (!stopReceipt.exited) throw oatsError("E_SESSION_STOP_FAILED", `${meta.instance} was asked to stop (${stopReceipt.signal} to ${stopReceipt.requested.map((r) => `${r.comm} pid ${r.pid}`).join(", ")} at ${stopReceipt.sentAt}) and was still running after ${stopReceipt.waitedMs} ms (${stopReceipt.state}); nothing was escalated and nothing was started; stop it yourself, or retry with a longer --stop-grace. Receipt: ${join(realHome, ".oats-restart.json")}`);
7460
+ try { state = inspectSessionTarget(target, o.io); }
7461
+ catch (e) {
7462
+ const lost = lostServer(e);
7463
+ if (lost.stopped) state = { present: false, state: "stopped" };
7464
+ else throw oatsError("E_SESSION_UNKNOWN", `after the stop, cannot establish the state of ${meta.instance}, so nothing was started: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}`);
7465
+ }
7466
+ if (state.present && state.state !== "shell") throw oatsError("E_SESSION_UNKNOWN", `${meta.instance} read as stopped and then as ${state.state} again; nothing was started`);
7467
+ }
7468
+ // The kernel that launches the harness is the one the agent's plain `oats` runs.
7469
+ checkRoots();
7470
+ writeKernelShim(realHome);
7471
+ const startedAt = new Date().toISOString();
7472
+ const id = randomUUID();
7473
+ if (!engaged) planExtra.launchPrompts = notEngaged(id);
7474
+ // This start's launch environment, recorded just before its pane is made (best effort: never a
7475
+ // refusal). A home without a recipe renders none and records nothing.
7476
+ const recordEnv = () => { if (recipeForEnv) recordStartEnv(realHome, id, referenceNames, referenceValues); };
7477
+ const makeLaunchController = () => engaged ? promptController(realHome, id, command, o.io, originalHomeIdentity) : null;
7478
+ let launchController;
7479
+ let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
7480
+ // A resumed Claude session is watched for its resume-cost dialog once it runs (after the record):
7481
+ // the pane's identity is read at its creation, as the controller reads it.
7482
+ const watchResume = !!resume?.sessionId && launchPlan.harness === "claude";
7483
+ let resumeTarget = null;
7484
+ checkRoots();
7485
+ // The launch's one native start; every render of its window command reuses it.
7486
+ const nativeStart = prepareNativeStart(realHome, launchPlan?.harness || harness);
7487
+ // What the window runs: the planned command, or, for a resume that found its conversation, the same
7488
+ // recipe rendered with the harness's resume selector and the resume notice. Only the window carries
7489
+ // it: instance.json, the pending receipt and the recipe keep the ordinary launch, so a later start
7490
+ // opens a fresh conversation (and the native-record roots never see a recorded --session).
7491
+ const executedCommand = () => resume?.sessionId ? renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome, resume: { sessionId: resume.sessionId, prompt: RESUME_NOTICE } }) : command;
7492
+ const windowCommand = (scope) => paneCommand(exitMarked(nativeRecordCommand(executedCommand(), realHome, launchPlan?.harness || harness, { start: nativeStart, scope }), id, exitedPath), removed);
7493
+ // Whether the harness runs in a scope of its own (nativeRecordCommand), judged on the pane it
7494
+ // will run in for the command it runs; a warning is said, and is an event once the start is recorded.
7495
+ let unscoped = null;
7496
+ const scopeOn = (pane) => {
7497
+ // The caller's own io (a test's), not the guarded one every start runs with.
7498
+ const scope = agentScopeOn(command, { pane, removed, refs: paneEnv }, rawIo);
7499
+ if (scope.warning) warnings.push(unscoped = scope.warning);
7500
+ return scope.wrapper;
7501
+ };
7502
+ let envHandoff;
7503
+ const privateWindowCommand = (command) => { envHandoff = launchEnvHandoff(realHome, id, paneEnv); return envHandoff.wrap(command); };
7504
+ let reused = "new";
7505
+ const session = target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
7506
+ const window = target?.window || meta.tmux?.window || meta.instance;
7507
+ let socket = target?.socket || meta.tmux?.socket;
7508
+ let windowCmd = windowCommand();
7509
+ let moved = null;
7510
+ // A fallback shell (no harness descendant) or a retained dead pane is
7511
+ // the agent's own pane (resolveAgentPane): the command runs there, on the
7512
+ // server the home recorded, no other window or pane touched and no option
7513
+ // set but that pane's mark.
7514
+ const inPlace = state.paneId && (state.present || state.state === "stopped");
7515
+ try {
7516
+ if (inPlace) {
7517
+ const pane = paneEnvironment(socket, session, o.io, realHome);
7518
+ loginOn(pane);
7519
+ const scope = scopeOn(pane);
7520
+ if (scope) windowCmd = windowCommand(scope);
7521
+ launchController = makeLaunchController();
7522
+ if (launchController) {
7523
+ try {
7524
+ const oldTarget = launchPromptTransport(o.io).identity(socket, state.paneId);
7525
+ beforeRespawn = launchController.captureBeforeRespawn(oldTarget);
7526
+ } catch { /* a missing prior capture can never authorize input */ }
7093
7527
  }
7094
- return recordedRead;
7095
- };
7096
- // A pane the start reuses where it is: one the recorded target shows, running or left as a shell.
7097
- const reusable = (state) => !!(state?.paneId && (state.present || state.state === "stopped"));
7098
- const selected = reselect !== null || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined;
7099
- const hasRecipe = meta.launch && typeof meta.launch === "object";
7100
- let launchPlan = null, launchHooksPass = null, handedExecutable, hookMeta, hookDialogClaims, explicitModelFrom = null, warnings = [];
7101
- // --resume: only a home whose session was lost, read here, under the lock, before any launch hook
7102
- // runs. Then the conversation it continues, or the reason it starts fresh (resumeConversation).
7103
- let resume = null;
7104
- if (o.resume === true) {
7105
- 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`);
7106
- const observed = recordedState();
7107
- 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}`); }
7108
- if (observed.state.present && observed.state.state !== "shell") throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${observed.state.state}); nothing was started`);
7109
- // A home whose retire runs, cannot be told, failed or was interrupted is owed it, never a
7110
- // resume (read as its status row reads it, under the claim this resume holds).
7111
- const owed = owedRetire(realHome);
7112
- if (owed) throw oatsError("E_INSTANCE_RETIRING", `${owedRetireSaid(meta.instance, owed.state)}; nothing was started`);
7113
- const end = meta.launched === true ? sessionEndOf(realHome, meta) : "never-launched";
7114
- 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)`);
7115
- resume = resumeConversation(realHome, meta);
7116
- }
7117
- if (selected || hasRecipe) {
7118
- // Every start of a home with a recipe (ordinary, model-only, or under a
7119
- // selection) goes through the one planner: recipe shape, the recorded
7120
- // or selected executable, references, capability contributions under
7121
- // the captured settings and current trust. A home without a recipe that
7122
- // is asked for a selection is refused (E_LAUNCH_LEGACY).
7123
- const context = meta.repo && existsSync(meta.repo) ? resolve(meta.repo) : dirname(dirname(dirname(dirname(realHome))));
7124
- // o.teams / o.defaultTeam: the home's LIVE teams, computed by an async caller (liveTeams) —
7125
- // the launch hook re-checks joined memberships against them.
7126
- const resolvedCfg = resolvedFromHome(realHome, meta, { teams: o.teams, defaultTeam: o.defaultTeam, teamsSource: o.teamsSource });
7127
- let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
7128
- // The environment the plan's checks read for this launch's pane (the harness lookup by name,
7129
- // the package probe, folder trust): a pane the start will reuse, on its own recorded session,
7130
- // whatever the OATS server holds; otherwise the session's or the server's when a server runs;
7131
- // when none does, the environment this start will create the server with (read once, here,
7132
- // for the plan and for the creation below). For a creator that may not create the server no
7133
- // pane's environment is established: the plan's checks read this process's, and the refusal
7134
- // comes at the creation's own place, after the start's other preflights.
7135
- const pane = () => {
7136
- const recorded = recordedState();
7137
- if (reusable(recorded.state)) return paneEnvironment(receipt.target.socket, receipt.target.session, o.io, realHome);
7138
- if (recorded.error) return NO_PANE_READ; // the gate refuses below; no check decides it
7139
- const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
7140
- if (!preview || preview.server) return expectedPaneEnvironment(preview, planSession, o.io, realHome);
7141
- try { return expectedPaneEnvironment(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return SESSION_REFUSED; throw e; }
7142
- };
7143
- const plan = planLaunch({ home: realHome, instance: meta.instance, meta, contextDir: context, agentLike: agent || { harness: meta.harness, model: meta.model, yolo: meta.yolo }, selection: { launchConfig: o.launchConfig, harness: o.harness, model: o.model, yolo: o.yolo }, reselect, resolvedCfg, env: o.env || process.env, assertRoots: checkRoots,
7144
- pane });
7145
- launchPlan = { recipe: plan.recipe, command: plan.command, declaredEnv: plan.declaredEnv, harness: plan.harness, model: plan.model, yolo: plan.yolo, executable: plan.executable, executablePaneSide: plan.executablePaneSide, config: plan.config, launchChoice: plan.launchChoice, trustHome: plan.trustHome, modelFrom: modelFromOf(plan.modelSource, { at: "start", prior: meta.modelFrom ?? null }),
7146
- ...(plan.launchChoice ? { launchFrom: plan.launchChoice.from, launchAt: plan.launchChoice.at, launchDeclared: plan.launchChoice.declared } : {}) };
7147
- // The plan ran preview-aware launch hooks as a preview: their real run, over the planned
7148
- // contributions, waits for the rest of preflight.
7149
- handedExecutable = harnessExecutableEnv(plan.executable.path, plan.executablePaneSide).OATS_HARNESS_EXECUTABLE;
7150
- if (plan.previewedHooks.length) launchHooksPass = { frozen: { ...plan.frozen, hooks: plan.recipe.hooks }, harness: plan.harness, resolvedCfg, contextDir: context, previewed: plan.recipe.hooks, volatileEnv: plan.volatileEnv, trustHome: plan.trustHome };
7151
- command = launchPlan.command; model = launchPlan.model;
7152
- // The other launch hooks ran for real in the plan: their warnings are
7153
- // events now, whatever the start does next, and the answer carries them.
7154
- hookMeta = plan.hookMeta;
7155
- hookDialogClaims = plan.hookDialogClaims;
7156
- warnings = plan.warnings;
7157
- for (const message of warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
7158
- } else if (o.model !== undefined && o.model !== null && String(o.model).trim() !== "") {
7159
- const resolved = resolveModelPreference(String(o.model), harness);
7160
- if (!resolved) throw oatsError("E_MODEL_UNKNOWN", `model preference ${JSON.stringify(o.model)} has no entry usable by harness ${harness}; give a ${harness} model id`);
7161
- command = withLaunchModel(command, resolved);
7162
- model = resolved; explicitModelFrom = "start";
7163
- } else parseLaunchCommand(command);
7164
- // A recorded command starts, and is saved, with its harness's safe task prompt.
7165
- if (!launchPlan) command = withSafeTaskPrompt(command, harness);
7166
- // References recorded for this home must resolve on this host on every
7167
- // start path, and the source variables go to the pane, not the command.
7168
- const recipeForEnv = launchPlan?.recipe || (meta.launch && typeof meta.launch === "object" ? meta.launch : null);
7169
- if (recipeForEnv) { const missing = missingLaunchEnvRefs(recipeForEnv.env, o.env || process.env); if (missing.length) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage(missing)); }
7170
- // A resume starts only under the values the start it brings back recorded (lib/start-env.mjs): a
7171
- // changed one refuses, after a missing one; a start with no record to check (an earlier kernel's,
7172
- // or one that does not read) is resumed and says so once. Ordinary starts never compare.
7173
- let envUnverified = null;
7174
- if (resume && recipeForEnv) {
7175
- const fit = checkStartEnv(realHome, meta.startId, fromEnvNames(recipeForEnv.env), o.env || process.env);
7176
- if (fit.changed) throw oatsError("E_LAUNCH_ENV_CHANGED", launchEnvChangedMessage(fit.changed));
7177
- if (fit.unverified) warnings.push(envUnverified = launchEnvUnverifiedWarning(meta.instance));
7178
- }
7179
- const paneEnv = recipeForEnv ? launchEnvRefs(recipeForEnv, o.env || process.env) : [];
7180
- const paneEnvFlags = paneEnv.flatMap((r) => ["-e", `${r.name}=${r.value}`]);
7181
- checkRoots(); // preparation has run; no backend has been changed
7182
- let target = receipt.target;
7183
- const recorded = recordedState();
7184
- if (recorded.error) { const e = recorded.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}`); }
7185
- let state = recorded.state;
7186
- if (state.present && state.state !== "shell" && !o.restart) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${state.state}); nothing was started`);
7187
- // A caller that will have to create the tmux session reads the environment for it here, unless
7188
- // the plan's lookup read it already with no server running (an instance that cannot is refused
7189
- // here either way): after the start's preflights and its planning,
7190
- // so each of their refusals still answers first, and before the real run of preview-aware
7191
- // launch hooks, a stop and any write of the home's launch state (record, receipt, pending
7192
- // start). A launch hook that does not declare launchPreview has already run and its warnings
7193
- // are already events (above), as before any other late refusal of a start (E_SESSION_RUNNING,
7194
- // E_LAUNCH_ENV_MISSING); nothing undoes what it did, and the hook contract (above
7195
- // prepareLaunchHooks) allows such a hook idempotent provider registration, which the next
7196
- // start repeats. Only when this start will have to create a window: a retained pane is reused
7197
- // where it is. A restart whose window goes away during its stop is decided at the creation.
7198
- const retained = reusable(state);
7199
- const tmuxSessionPlan = retained ? undefined : sessionPlan();
7200
- // A harness the plan looked up by name is looked up again where its pane will look it up, before
7201
- // anything is stopped: the retained pane's own session, or the session this start will create
7202
- // its window in (as planned). Once more on the session ensureOatsTmuxSession returns (below).
7203
- // Not there: refused. Found elsewhere: the launch runs that one, and records it. Every executable
7204
- // named bare (the harness's name, a declared name) is looked up again, also one the plan could only
7205
- // look up on this process's PATH; a recorded (frozen) or a declared path never is.
7206
- const lookAgain = (pane) => {
7207
- if (!launchPlan || launchPlan.config?.frozen || launchPlan.config?.executable?.includes("/")) return false;
7208
- const { config, launchChoice } = launchPlan;
7209
- const actual = resolveLaunchExecutable({ harness: launchPlan.harness, declared: config?.executable, declaringDir: config?.source, lookup: launchLookup(launchEnvironment({ configEnv: config?.env, configName: config?.name, env: o.env || process.env, pane, cwd: realHome })) });
7210
- if (!actual.path) throw executableNotOnPanePath(actual, { harness: launchPlan.harness, config, from: launchChoice?.from, at: launchChoice?.at });
7211
- const bad = checkLaunchExecutable(actual.path);
7212
- if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${bad}; nothing was started`);
7213
- launchPlan.executablePaneSide = !!actual.lookup;
7214
- if (actual.path === launchPlan.recipe.executable) return false;
7215
- launchPlan.recipe = { ...launchPlan.recipe, executable: actual.path };
7216
- command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome });
7217
- return true;
7218
- };
7219
- /** The launch runs another program than the hooks that have run were handed: said, and kept in the home. */
7220
- const noteReplacedExecutable = () => {
7221
- const replaced = replacedExecutableWarning(handedExecutable, launchPlan?.recipe.executable);
7222
- if (!replaced) return;
7223
- handedExecutable = undefined;
7224
- hookDialogClaims = voidedDialogClaims(hookDialogClaims);
7225
- warnings.push(replaced);
7226
- appendEvent(realHome, { kind: "launch-warning", data: { message: replaced } });
7227
- };
7228
- lookAgain(retained ? () => paneEnvironment(target.socket, target.session, o.io, realHome) : () => expectedPaneEnvironment(tmuxSessionPlan, planSession, o.io, realHome));
7229
- // Every preflight has passed: the preview-aware launch hooks run for real
7230
- // (they may register the home with their provider), before a restart's
7231
- // stop, and must contribute exactly what they contributed as a preview,
7232
- // which is what the command was rendered and preflighted from, except the
7233
- // values of the env their preview declared volatile: those come from this
7234
- // run, and the command is rendered again with them.
7235
- if (launchHooksPass) {
7236
- const { previewed, volatileEnv, trustHome, ...pass } = launchHooksPass;
7237
- // The looks above have settled what this start expects: that is what its real hooks are handed.
7238
- const handed = harnessExecutableEnv(launchPlan.recipe.executable, launchPlan.executablePaneSide);
7239
- // Hooks that ran for real in the plan were handed the plan's: their statements don't reach this one.
7240
- if (handed.OATS_HARNESS_EXECUTABLE !== handedExecutable) hookDialogClaims = voidedDialogClaims(hookDialogClaims);
7241
- handedExecutable = handed.OATS_HARNESS_EXECUTABLE;
7242
- const real = prepareLaunchHooks({ ...pass, extraEnv: handed, home: realHome, meta, assertRoots: checkRoots, pass: "real" });
7243
- const canon = (v) => canonicalJson(JSON.parse(JSON.stringify(v ?? null)));
7244
- const stable = (h) => Object.fromEntries(Object.entries(h.env).filter(([n]) => !volatileEnv.includes(n)));
7245
- if (canon({ launch: real.launch, env: stable(real), contributions: real.contributions }) !== canon({ launch: previewed.launch, env: stable(previewed), contributions: previewed.contributions })) {
7246
- // A provider's row names its env; the values are in the merged env.
7247
- const rowOf = (h, id) => { const row = h.contributions.find((c) => c.capability === id); return canon({ row, values: (row?.env || []).map((n) => volatileEnv.includes(n) ? null : h.env[n]) }); };
7248
- const differing = [...new Set([...real.contributions, ...previewed.contributions].map((c) => c.capability))].filter((id) => rowOf(real, id) !== rowOf(previewed, id));
7249
- throw oatsError("E_LAUNCH_PREPARATION", `the launch hook of ${differing.join(", ") || "a capability"} returned a contribution that differs from its preview contribution (a launch hook returns the same contribution under OATS_LAUNCH_PREVIEW, apart from the values of its volatileEnv); nothing was stopped or started`);
7528
+ checkRoots();
7529
+ recordEnv();
7530
+ writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
7531
+ promptDispatched = !!launchController;
7532
+ try {
7533
+ const output = tmuxOn(socket, ["respawn-pane", "-k", "-t", state.paneId, "-c", realHome, privateWindowCommand(windowCmd), ...markAgentPane(window, state.paneId), ...(launchController || watchResume ? [";", "display-message", "-p", "-t", state.paneId, LAUNCH_PANE_FORMAT] : [])], o.io, oatsWindowEnvironment());
7534
+ if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
7535
+ if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
7250
7536
  }
7251
- launchPlan.recipe = { ...launchPlan.recipe, hooks: { launch: real.launch, env: real.env, contributions: real.contributions } };
7252
- command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome });
7253
- if (real.meta) hookMeta = { ...(hookMeta || {}), ...real.meta };
7254
- if (real.dialogClaims) hookDialogClaims = { ...(hookDialogClaims || {}), ...real.dialogClaims };
7255
- // The real run's warnings are events now, whatever the start does next,
7256
- // and the answer carries them.
7257
- warnings = [...warnings, ...real.warnings];
7258
- for (const message of real.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
7537
+ catch (e) { envHandoff?.remove(); throw launchFailure(e); }
7538
+ reused = "pane";
7539
+ } else {
7540
+ const instancesRoot = dirname(realHome);
7541
+ const hq = existsSync(dirname(dirname(instancesRoot))) ? dirname(dirname(instancesRoot)) : realHome;
7259
7542
  checkRoots();
7260
- }
7261
- noteReplacedExecutable();
7262
- const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
7263
- ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
7264
- ...(hookMeta ? { hookMeta } : {}), ...(hookDialogClaims ? { hookDialogClaims } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
7265
- if (resume?.warning) { warnings.push(resume.warning); appendEvent(realHome, { kind: "launch-warning", data: { message: resume.warning } }); }
7266
- warnings.push(...launchStartNotices(dirname(dirname(dirname(dirname(home)))), launchPlan?.harness || harness, command));
7267
- if (kernelNode().warning) warnings.push(kernelNode().warning);
7268
- const engaged = devChannelEngaged(launchPlan?.harness || harness, command);
7269
- let stopReceipt = null;
7270
- if (state.present && state.state !== "shell") {
7271
- // Restart: every preflight above passed, so ask the running harness to
7272
- // end and wait, bounded. A harness still there afterwards is reported
7273
- // as running; nothing is escalated and nothing is launched.
7274
- // The stop is recorded first, for the start instance.json still names (recordStop, as a
7275
- // retire does), so a relaunch that fails, or a process that dies before it, leaves a home
7276
- // that reads `stopped`, never `lost`: no resume brings back what was being restarted. The
7277
- // relaunch records a new start, which the record does not name. A stop refused here leaves
7278
- // the record with the harness running: should that harness die later, the home reads
7279
- // `stopped`. A record that cannot be written (a full disk) does not block the restart.
7280
- try { recordStop(realHome, null); } catch { /* see above */ }
7281
- stopReceipt = stopHarness(target, { graceMs: o.stopGraceMs ?? 20000, io: o.io, kill: o.io?.kill, sleep: o.io?.sleep });
7282
- writeJsonAtomic(join(realHome, ".oats-restart.json"), { instance: meta.instance, at: new Date().toISOString(), stop: stopReceipt, next: { harness: launchPlan?.harness || harness, launchConfig: launchPlan?.recipe.launchConfig ?? null, model: model ?? null } }, 0o600);
7283
- appendEvent(realHome, { kind: stopReceipt.exited ? "restarted" : "stop-refused", data: { phase: "restart-stop", signal: stopReceipt.signal, waitedMs: stopReceipt.waitedMs, stillRunning: stopReceipt.stillRunning ?? [] } });
7284
- if (!stopReceipt.exited) throw oatsError("E_SESSION_STOP_FAILED", `${meta.instance} was asked to stop (${stopReceipt.signal} to ${stopReceipt.requested.map((r) => `${r.comm} pid ${r.pid}`).join(", ")} at ${stopReceipt.sentAt}) and was still running after ${stopReceipt.waitedMs} ms (${stopReceipt.state}); nothing was escalated and nothing was started; stop it yourself, or retry with a longer --stop-grace. Receipt: ${join(realHome, ".oats-restart.json")}`);
7285
- try { state = inspectSessionTarget(target, o.io); }
7543
+ // A replacement window (never launched, recorded window gone, recorded server gone) is created
7544
+ // on the OATS server, wherever the home was recorded: one socket from here to the record.
7545
+ const recordedSocket = socket ? resolve(socket) : null;
7546
+ socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
7547
+ // One read of the pane's environment answers both: the executable and the scope.
7548
+ const pane = paneEnvironment(socket, session, o.io, realHome);
7549
+ loginOn(pane);
7550
+ const looked = lookAgain(() => pane);
7551
+ if (looked) planExtra.launch = launchPlan.recipe;
7552
+ noteReplacedExecutable();
7553
+ if (hookDialogClaims) planExtra.hookDialogClaims = hookDialogClaims;
7554
+ const scope = scopeOn(pane);
7555
+ if (looked || scope) windowCmd = windowCommand(scope);
7556
+ let names;
7557
+ try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
7286
7558
  catch (e) {
7287
- const lost = lostServer(e);
7288
- if (lost.stopped) state = { present: false, state: "stopped" };
7289
- else throw oatsError("E_SESSION_UNKNOWN", `after the stop, cannot establish the state of ${meta.instance}, so nothing was started: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}`);
7559
+ if (isKernelCode(e?.code)) throw e;
7560
+ throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
7290
7561
  }
7291
- if (state.present && state.state !== "shell") throw oatsError("E_SESSION_UNKNOWN", `${meta.instance} read as stopped and then as ${state.state} again; nothing was started`);
7292
- }
7293
- // The kernel that launches the harness is the one the agent's plain `oats` runs.
7294
- checkRoots();
7295
- writeKernelShim(realHome);
7296
- const startedAt = new Date().toISOString();
7297
- const id = randomUUID();
7298
- if (!engaged) planExtra.launchPrompts = notEngaged(id);
7299
- // This start's launch environment, recorded just before its pane is made (best effort: never a
7300
- // refusal). A home without a recipe renders none and records nothing.
7301
- const recordEnv = () => { if (recipeForEnv) recordStartEnv(realHome, id, fromEnvNames(recipeForEnv.env), o.env || process.env); };
7302
- const makeLaunchController = () => engaged ? promptController(realHome, id, command, o.io, originalHomeIdentity) : null;
7303
- let launchController;
7304
- let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
7305
- // A resumed Claude session is watched for its resume-cost dialog once it runs (after the record):
7306
- // the pane's identity is read at its creation, as the controller reads it.
7307
- const watchResume = !!resume?.sessionId && launchPlan.harness === "claude";
7308
- let resumeTarget = null;
7309
- checkRoots();
7310
- // The names this launch removes, from the recipe it runs (a preview-aware hook's real run included).
7311
- // A home without a recipe (an earlier kernel's) composes no providers at launch: nothing.
7312
- const removed = launchPlan ? removedLaunchEnv({ declared: launchPlan.declaredEnv, hooksEnv: launchPlan.recipe.hooks?.env, configEnv: launchPlan.recipe.env }) : [];
7313
- // The launch's one native start; every render of its window command reuses it.
7314
- const nativeStart = prepareNativeStart(realHome, launchPlan?.harness || harness);
7315
- // What the window runs: the planned command, or, for a resume that found its conversation, the same
7316
- // recipe rendered with the harness's resume selector and the resume notice. Only the window carries
7317
- // it: instance.json, the pending receipt and the recipe keep the ordinary launch, so a later start
7318
- // opens a fresh conversation (and the native-record roots never see a recorded --session).
7319
- const executedCommand = () => resume?.sessionId ? renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome, resume: { sessionId: resume.sessionId, prompt: RESUME_NOTICE } }) : command;
7320
- const windowCommand = (scope) => paneCommand(exitMarked(nativeRecordCommand(executedCommand(), realHome, launchPlan?.harness || harness, { start: nativeStart, scope }), id, exitedPath), removed);
7321
- // Whether the harness runs in a scope of its own (nativeRecordCommand), judged on the pane it
7322
- // will run in for the command it runs; a warning is said, and is an event once the start is recorded.
7323
- let unscoped = null;
7324
- const scopeOn = (pane) => {
7325
- // The caller's own io (a test's), not the guarded one every start runs with.
7326
- const scope = agentScopeOn(command, { pane, removed, refs: paneEnv }, rawIo);
7327
- if (scope.warning) warnings.push(unscoped = scope.warning);
7328
- return scope.wrapper;
7329
- };
7330
- let reused = "new";
7331
- const session = target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
7332
- const window = target?.window || meta.tmux?.window || meta.instance;
7333
- let socket = target?.socket || meta.tmux?.socket;
7334
- let windowCmd = windowCommand();
7335
- let moved = null;
7336
- // A fallback shell (no harness descendant) or a retained dead pane is
7337
- // the agent's own pane (resolveAgentPane): the command runs there, on the
7338
- // server the home recorded, no other window or pane touched and no option
7339
- // set but that pane's mark.
7340
- const inPlace = state.paneId && (state.present || state.state === "stopped");
7341
- try {
7342
- if (inPlace) {
7343
- const scope = scopeOn(paneEnvironment(socket, session, o.io, realHome));
7344
- if (scope) windowCmd = windowCommand(scope);
7345
- launchController = makeLaunchController();
7346
- if (launchController) {
7347
- try {
7348
- const oldTarget = launchPromptTransport(o.io).identity(socket, state.paneId);
7349
- beforeRespawn = launchController.captureBeforeRespawn(oldTarget);
7350
- } catch { /* a missing prior capture can never authorize input */ }
7351
- }
7352
- checkRoots();
7353
- recordEnv();
7354
- writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
7355
- promptDispatched = !!launchController;
7356
- try {
7357
- 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());
7358
- if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
7359
- if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
7360
- }
7361
- catch (e) { throw launchFailure(e); }
7362
- reused = "pane";
7363
- } else {
7364
- const instancesRoot = dirname(realHome);
7365
- const hq = existsSync(dirname(dirname(instancesRoot))) ? dirname(dirname(instancesRoot)) : realHome;
7366
- checkRoots();
7367
- // A replacement window (never launched, recorded window gone, recorded server gone) is created
7368
- // on the OATS server, wherever the home was recorded: one socket from here to the record.
7369
- const recordedSocket = socket ? resolve(socket) : null;
7370
- socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
7371
- // One read of the pane's environment answers both: the executable and the scope.
7372
- const pane = paneEnvironment(socket, session, o.io, realHome);
7373
- const looked = lookAgain(() => pane);
7374
- if (looked) planExtra.launch = launchPlan.recipe;
7375
- noteReplacedExecutable();
7376
- if (hookDialogClaims) planExtra.hookDialogClaims = hookDialogClaims;
7377
- const scope = scopeOn(pane);
7378
- if (looked || scope) windowCmd = windowCommand(scope);
7379
- let names;
7380
- try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
7381
- catch (e) {
7382
- if (isKernelCode(e?.code)) throw e;
7383
- throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
7384
- }
7385
- if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
7386
- target = { backend: "tmux", session, window, socket };
7387
- launchController = makeLaunchController();
7388
- checkRoots();
7389
- recordEnv();
7390
- writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
7391
- promptDispatched = !!launchController;
7392
- try {
7393
- 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();
7394
- if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
7395
- if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
7396
- prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : watchResume ? output.split("\t")[0] : output, o.io);
7397
- }
7398
- catch (e) { throw launchFailure(e); }
7399
- if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
7562
+ if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
7563
+ target = { backend: "tmux", session, window, socket };
7564
+ launchController = makeLaunchController();
7565
+ checkRoots();
7566
+ recordEnv();
7567
+ writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
7568
+ promptDispatched = !!launchController;
7569
+ try {
7570
+ const output = tmuxOn(socket, ["new-window", "-P", "-F", launchController || watchResume ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", window, "-c", realHome, privateWindowCommand(windowCmd), ...markAgentPane(window)], o.io, oatsWindowEnvironment()).trim();
7571
+ if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
7572
+ if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
7573
+ prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : watchResume ? output.split("\t")[0] : output, o.io);
7400
7574
  }
7401
- if (launchController) launchPrompts = inPlace ? launchController.observeRespawn(launchPromptTarget, beforeRespawn) : launchController.observeNew(launchPromptTarget);
7402
- if (launchPrompts?.status === "flag-ignored") { launchPrompts = channelsUnavailable(id, launchPrompts); warnings = flagIgnoredWarnings(warnings); }
7403
- } catch (error) {
7404
- if (!promptDispatched) throw error;
7405
- launchPrompts = incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt dispatch or recording incomplete", launchPrompts, originalHomeIdentity);
7406
- }
7407
- target = { backend: "tmux", session, window, socket: resolve(socket) };
7408
- if (launchPrompts) {
7409
- try { assertLaunchHome(realHome, originalHomeIdentity); }
7410
- catch { throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch home identity changed; metadata retained at original home", launchPrompts, originalHomeIdentity)); }
7411
- planExtra.launchPrompts = launchPrompts;
7412
- planExtra.launchPromptTarget = launchPromptTarget ?? target;
7413
- // Recovery retains evidence but never reconstructs this invocation's answer authority.
7414
- try { writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600); }
7415
- catch { throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt pending receipt incomplete", launchPrompts, originalHomeIdentity)); }
7416
- }
7417
- // The session exists: its boundary (lib/instance-events.mjs) is recorded
7418
- // now, before the metadata, so a start whose metadata write fails still
7419
- // voids the claims of the session it replaced; its adoption only completes a log it missed.
7420
- // The planned recipe names the configuration (null: the bare harness), never the recorded recipe's.
7421
- recordStartBoundary(realHome, { startId: id, startedAt, harness: launchPlan?.harness || harness, backend: "tmux", launchConfig: launchPlan?.recipe.launchConfig ?? null, phase: o.restart ? "restart" : "start" });
7422
- // Keep launch evidence until the command exits or the target disappears.
7423
- // A transient child (for example the native-start recorder) is not proof that startup
7424
- // has finished. A later start reconciles the receipt without a watcher.
7425
- let done;
7426
- try { done = record(meta, { id, target, model, command, startedAt, reused, ...planExtra, ...(stopReceipt ? { stop: stopReceipt } : {}) }, false); }
7427
- catch (e) {
7428
- if (launchPrompts) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt metadata recording incomplete", launchPrompts, originalHomeIdentity));
7429
- if (e.code && String(e.code).startsWith("E_")) throw e;
7430
- 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`);
7431
- }
7432
- if (launchPrompts && !promptLaunched(launchPrompts.status)) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
7433
- // As spawn says it once launched: a start refused before this point leaves no event.
7434
- if (unscoped) appendEvent(realHome, { kind: "launch-warning", data: { message: unscoped } });
7435
- if (envUnverified) appendEvent(realHome, { kind: "launch-warning", data: { message: envUnverified } });
7436
- // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
7437
- if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
7438
- // A resume answers what it continued. A resumed Claude session that stops at its resume-cost dialog
7439
- // is a start that succeeded and waits for its human: reported (`waiting`), never answered.
7440
- 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;
7441
- const resumed = resume ? { resume: resumeAnswer(resume, waiting) } : {};
7442
- return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings], ...resumed };
7443
- } finally {
7444
- // A hook may have replaced the home itself. Never follow that replacement
7445
- // to remove a target's lock; keep the original retry state with its home.
7446
- try {
7447
- const st = lstatSync(realHome);
7448
- if (st.isDirectory() && !st.isSymbolicLink() && st.dev === originalHomeIdentity?.dev && st.ino === originalHomeIdentity?.ino) rmSync(lock, { recursive: true, force: true });
7449
- } catch { /* retain retry state when its authority is lost */ }
7450
- }
7575
+ catch (e) { envHandoff?.remove(); throw launchFailure(e); }
7576
+ if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
7577
+ }
7578
+ if (launchController) launchPrompts = inPlace ? launchController.observeRespawn(launchPromptTarget, beforeRespawn) : launchController.observeNew(launchPromptTarget);
7579
+ if (launchPrompts?.status === "flag-ignored") { launchPrompts = channelsUnavailable(id, launchPrompts); warnings = flagIgnoredWarnings(warnings); }
7580
+ } catch (error) {
7581
+ if (!promptDispatched) throw error;
7582
+ launchPrompts = incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt dispatch or recording incomplete", launchPrompts, originalHomeIdentity);
7583
+ }
7584
+ target = { backend: "tmux", session, window, socket: resolve(socket) };
7585
+ if (launchPrompts) {
7586
+ try { assertLaunchHome(realHome, originalHomeIdentity); }
7587
+ catch { throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch home identity changed; metadata retained at original home", launchPrompts, originalHomeIdentity)); }
7588
+ planExtra.launchPrompts = launchPrompts;
7589
+ planExtra.launchPromptTarget = launchPromptTarget ?? target;
7590
+ // Recovery retains evidence but never reconstructs this invocation's answer authority.
7591
+ try { writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600); }
7592
+ catch { throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt pending receipt incomplete", launchPrompts, originalHomeIdentity)); }
7593
+ }
7594
+ // The session exists: its boundary (lib/instance-events.mjs) is recorded
7595
+ // now, before the metadata, so a start whose metadata write fails still
7596
+ // voids the claims of the session it replaced; its adoption only completes a log it missed.
7597
+ // The planned recipe names the configuration (null: the bare harness), never the recorded recipe's.
7598
+ recordStartBoundary(realHome, { startId: id, startedAt, harness: launchPlan?.harness || harness, backend: "tmux", launchConfig: launchPlan?.recipe.launchConfig ?? null, phase: o.restart ? "restart" : "start" });
7599
+ // Keep launch evidence until the command exits or the target disappears.
7600
+ // A transient child (for example the native-start recorder) is not proof that startup
7601
+ // has finished. A later start reconciles the receipt without a watcher.
7602
+ let done;
7603
+ try { done = record(meta, { id, target, model, command, startedAt, reused, ...planExtra, ...(stopReceipt ? { stop: stopReceipt } : {}) }, false); }
7604
+ catch (e) {
7605
+ if (launchPrompts) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt metadata recording incomplete", launchPrompts, originalHomeIdentity));
7606
+ if (e.code && String(e.code).startsWith("E_")) throw e;
7607
+ 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`);
7608
+ }
7609
+ if (launchPrompts && !promptLaunched(launchPrompts.status)) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
7610
+ // As spawn says it once launched: a start refused before this point leaves no event.
7611
+ if (unscoped) appendEvent(realHome, { kind: "launch-warning", data: { message: unscoped } });
7612
+ if (envUnverified) appendEvent(realHome, { kind: "launch-warning", data: { message: envUnverified } });
7613
+ // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
7614
+ if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
7615
+ // A resume answers what it continued. A resumed Claude session that stops at its resume-cost dialog
7616
+ // is a start that succeeded and waits for its human: reported (`waiting`), never answered.
7617
+ 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;
7618
+ const resumed = resume ? { resume: resumeAnswer(resume, waiting) } : {};
7619
+ return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings], ...resumed };
7620
+ }
7621
+ /** What a start, holding the home's lifecycle claim (startClaimed), refuses at `lock`, the home's
7622
+ * `.oats-start.lock`. Two starts exclude each other through that claim, and a start makes
7623
+ * nothing at this path. An upgrade writes its regular file there and keeps it until its final
7624
+ * receipt is persisted (lib/instance-upgrade.mjs), so a file is an upgrade that has not finished,
7625
+ * answered with its retry and never removed here. A directory is the start lock of an earlier
7626
+ * OATS, which made one for each start: refused, named, and never removed. Anything else there is
7627
+ * refused and named. Every refusal is before any effect: E_SESSION_START_BUSY for the upgrade,
7628
+ * which its retry ends, and E_SESSION_START_LOCK_STUCK for the rest, which only a person can
7629
+ * end, so that an unattended caller (a scheduled start, the resume sweep) never waits it out as
7630
+ * a start that runs. */
7631
+ function refuseStartMutex(home, lock) {
7632
+ let entry;
7633
+ try { entry = lstatSync(lock); } catch (e) { if (e.code === "ENOENT") return; throw e; }
7634
+ const retry = entry.isFile() ? upgradeMutexRetry(home) : null;
7635
+ if (retry) throw oatsError("E_SESSION_START_BUSY", `a package upgrade of ${basename(home)} holds the start mutex (${lock}); nothing was stopped or started. Retry ${retry} to finish the upgrade before starting`);
7636
+ if (entry.isDirectory()) throw oatsError("E_SESSION_START_LOCK_STUCK", `${lock} is the start lock directory of an earlier OATS; nothing was stopped or started. Once no earlier oats is running, remove that directory and retry`);
7637
+ throw oatsError("E_SESSION_START_LOCK_STUCK", `${lock} is neither a package upgrade's file nor an earlier OATS's start lock directory; nothing was stopped or started. Remove it and retry`);
7451
7638
  }
7452
7639
 
7453
7640
  /** One Git call of a retirement inspection → its stdout, as bytes: a text
@@ -8689,7 +8876,7 @@ function copyRecoveryHome(observation, dest) {
8689
8876
  // The launch environment's key and the digests made with it never leave the home
8690
8877
  // (lib/start-env.mjs): a recovery copy leaves them, and any temporary file of theirs, out.
8691
8878
  const excludeRoot = new Set(observation.homeExclude || ["work"]);
8692
- 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);
8879
+ for (const name of readdirSync(observation.home)) if (name === START_ENV_FILE || name === START_ENV_KEY_FILE || START_ENV_TMP.test(name) || LAUNCH_ENV_HANDOFF.test(name)) excludeRoot.add(name);
8693
8880
  copyRecoveryTree(observation.home, dest, { excludeRoot });
8694
8881
  if (storedTreeDigest(observation.home, BASELINE_DIGEST_VERSION, { excludeRoot, instanceHome: true }) !== storedTreeDigest(dest, BASELINE_DIGEST_VERSION, { instanceHome: true })) {
8695
8882
  throw new Error("home recovery verification disagreed with the source");
@@ -9048,7 +9235,7 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
9048
9235
  };
9049
9236
  // The completion is told who scheduled it: this process, by pid and by the start token its
9050
9237
  // holding of the home's claim records (lib/claim.mjs takes both from the same reading). It is
9051
- // told in its environment and nowhere else: the marker's format is as it was, and the completion
9238
+ // told in its environment and nowhere else: the marker does not record it, and the completion
9052
9239
  // compares the claim against what it was given, never against what it reads later beside the
9053
9240
  // home (completeDeferredRetirement).
9054
9241
  const requestedByStart = processStartToken(process.pid);
@@ -9085,10 +9272,11 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
9085
9272
  } catch { /* the marker alone then shows RETIRING; status names its age */ }
9086
9273
  });
9087
9274
  child.unref();
9088
- // The marker names its completion (pid and start time; the start is null when it cannot be read):
9089
- // while that process lives, any other retire of this home is refused (refusePendingCompletion).
9275
+ // The marker names its completion (pid, start time and boot; the start and the boot are null
9276
+ // when they cannot be read): while that process lives, any other retire of this home is
9277
+ // refused (refusePendingCompletion).
9090
9278
  const completionStart = processStartToken(child.pid);
9091
- writeFileSync(marker, JSON.stringify({ ...intent, completionPid: child.pid, completionStart }, null, 2) + "\n");
9279
+ writeFileSync(marker, JSON.stringify({ ...intent, completionPid: child.pid, completionStart, completionBoot: thisBoot() }, null, 2) + "\n");
9092
9280
  wroteMarker = true;
9093
9281
  // The marker promises a completion that is on its way. One that has ended by now is not: it
9094
9282
  // looked for its marker before this call wrote one, and nothing would ever remove it. So the
@@ -9144,7 +9332,8 @@ const COMPLETES_DEFERRED = Symbol("the completion of a deferred self-retire");
9144
9332
  export const SCHEDULING_WAIT_MS = 10 * 60 * 1000;
9145
9333
  /** How long a completion pauses between two looks at the claim its scheduling still holds. */
9146
9334
  const SCHEDULING_PAUSE_MS = 50;
9147
- export const RETIRE_DELETE_BRANCH_REFUSED = "oats retire no longer deletes branches: --delete-branch is not accepted. Retire without it; the branch is left in the repository. Inspect it there and delete it with Git if it is no longer wanted.";
9335
+ // The refusal of retire --delete-branch: the CLI's (lib/command-flags.mjs) and retireInstance's.
9336
+ export { RETIRE_DELETE_BRANCH_REFUSED };
9148
9337
 
9149
9338
  /** Run by the detached child: wait for the caller's window to be gone, then
9150
9339
  * retire the instance as an ordinary external operator. Returns true only
@@ -9159,7 +9348,11 @@ export const RETIRE_DELETE_BRANCH_REFUSED = "oats retire no longer deletes branc
9159
9348
  * hooks ran, the usual quarantine stays too); otherwise it goes, and the instance is a stopped or
9160
9349
  * running instance like any other, not one that reads RETIRING for a retire that is not happening.
9161
9350
  * How far the retire got is read from what it answers (`details.reached`, retireFailure), never
9162
- * from its code. */
9351
+ * from its code.
9352
+ *
9353
+ * A retire whose cleanup is left incomplete by retire hooks alone is tried again first, up to three
9354
+ * times (RETIRE_RETRY_DELAYS_MS; awebai/oats#1747), before that outcome is written, and then the
9355
+ * outcome says how many attempts ran (`attempts`). An outcome after no retry is as it was. */
9163
9356
  export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
9164
9357
  let intent = intentOrMarkerPath;
9165
9358
  if (typeof intentOrMarkerPath === "string") {
@@ -9224,7 +9417,7 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
9224
9417
  const path = retirePendingMarkerPath(home), marker = readJsonOrUndefined(path);
9225
9418
  if (!isPlainObject(marker) || typeof intent.requestedAt !== "string" || marker.requestedAt !== intent.requestedAt) return false;
9226
9419
  const pid = marker.completionPid;
9227
- if (Number.isSafeInteger(pid) && pid !== process.pid && processLiveness({ pid, processStart: marker.completionStart }).state !== "gone") return false;
9420
+ if (Number.isSafeInteger(pid) && pid !== process.pid && completionLiveness(marker).state !== "gone") return false;
9228
9421
  try { rmSync(path); return true; }
9229
9422
  catch (e) { if (e?.code !== "ENOENT") console.error(`deferred retirement: cannot remove ${path}: ${e.message}`); return false; }
9230
9423
  };
@@ -9244,40 +9437,110 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
9244
9437
  if (!written.ok) console.error(`deferred retirement of ${intent.instance}: its retire-refused event could not be written: ${written.reason ?? (written.results ?? []).map((r) => `${r.path}: ${r.reason}`).join("; ")}`);
9245
9438
  return false;
9246
9439
  };
9247
- let result;
9248
- try {
9249
- result = retireInstance(intent.root, intent.instance, {
9250
- home: intent.options?.home, keepDir: !!intent.options?.keepDir, tmuxSession: intent.options?.tmuxSession,
9251
- ...(Array.isArray(intent.options?.plannedExtraWorktrees) ? { plannedExtraWorktrees: intent.options.plannedExtraWorktrees } : {}),
9252
- ...(Array.isArray(intent.options?.children) ? { children: intent.options.children } : {}),
9253
- ...(obsoleteDeleteBranch ? { [OBSOLETE_DELETE_BRANCH]: true } : {}),
9254
- // The retire that scheduled this completion was waited for above. Any other live holder of
9255
- // the claim is waited for by the retire itself, for the time a completion's retire has
9256
- // always waited, and then answers as for every retire.
9257
- [COMPLETES_DEFERRED]: true,
9258
- });
9259
- } catch (e) {
9260
- const code = kernelCode(e, "E_LIFECYCLE_FAILED");
9261
- // An answer without `reached` is one in which the retire of the home had not begun (retireInstance).
9262
- const reached = e?.details?.reached;
9263
- const homeChanged = isPlainObject(reached) && (reached.hooksStarted === true || reached.home !== "kept");
9264
- notCompleted({ ok: false, error: { code, message: e.message }, ...(e.details?.childrenStopped ? { childrenStopped: e.details.childrenStopped } : {}), ...(obsoleteDeleteBranch ? { warnings: [OBSOLETE_DELETE_BRANCH_SENTENCE] } : {}), retry: `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}` },
9265
- { code, homeChanged, sentence: e.message });
9266
- console.error(`deferred retirement of ${intent.instance} failed: ${e.message}`);
9267
- // A defect's stack goes to the completion's log (lib/errors.mjs isDefect).
9268
- reportDefect(e);
9269
- return false;
9270
- }
9271
- if (obsoleteDeleteBranch) console.log(OBSOLETE_DELETE_BRANCH_SENTENCE);
9272
- if (result.rollbackIncomplete) {
9440
+ const retry = `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}`;
9441
+ const retireOnce = (underClaim) => retireInstance(intent.root, intent.instance, {
9442
+ home: intent.options?.home, keepDir: !!intent.options?.keepDir, tmuxSession: intent.options?.tmuxSession,
9443
+ ...(Array.isArray(intent.options?.plannedExtraWorktrees) ? { plannedExtraWorktrees: intent.options.plannedExtraWorktrees } : {}),
9444
+ ...(Array.isArray(intent.options?.children) ? { children: intent.options.children } : {}),
9445
+ ...(obsoleteDeleteBranch ? { [OBSOLETE_DELETE_BRANCH]: true } : {}),
9446
+ // The retire that scheduled this completion was waited for above. Any other live holder of
9447
+ // the claim is waited for by the retire itself, for the time a completion's retire has
9448
+ // always waited, and then answers as for every retire.
9449
+ [COMPLETES_DEFERRED]: true,
9450
+ ...(underClaim ? { [RETIRE_UNDER_CLAIM]: underClaim } : {}),
9451
+ });
9452
+ // A retire whose cleanup is incomplete with retire hooks alone owed (RETIRE_HOOK_DEBT_ONLY) is
9453
+ // tried again, after each delay of RETIRE_RETRY_DELAYS_MS (`opts.retryDelaysMs` for a test), as a
9454
+ // plain retire like the first: it takes the claim, and its quarantine retry clears only when the
9455
+ // hooks are shown to have run. Every attempt records its own `retired` row. The retries stop at the
9456
+ // first that answers an error or whose cleanup owes more than retire hooks, and before any retry
9457
+ // whose home is gone or whose pending marker is no longer this completion's (another `requestedAt`,
9458
+ // or none): that is checked after the wait, and again by the retry itself once it holds the home's
9459
+ // claim, before it reads or does anything. While it waits, the completion keeps its retry state at
9460
+ // retireRetryPath, which another retire's refusal reads (refusePendingCompletion); it removes that
9461
+ // file on every way out.
9462
+ const delays = (Array.isArray(opts.retryDelaysMs) ? opts.retryDelaysMs : RETIRE_RETRY_DELAYS_MS).map((ms) => Math.max(0, Number(ms) || 0));
9463
+ const attempts = 1 + delays.length;
9464
+ const retryPath = home ? retireRetryPath(home) : null;
9465
+ const dropRetryState = () => {
9466
+ if (!retryPath) return;
9467
+ try { rmSync(retryPath, { force: true }); } catch (e) { console.error(`deferred retirement: cannot remove ${retryPath}: ${e.message}`); }
9468
+ };
9469
+ /** Why the home may not be retried now, or null: it is there, and its pending marker is still the
9470
+ * one of this completion's scheduling. */
9471
+ const notOwed = () => {
9472
+ if (!home) return "its intent names no home";
9473
+ if (!existsSync(home)) return "its home is gone";
9474
+ const marker = readJsonOrUndefined(retirePendingMarkerPath(home));
9475
+ if (!isPlainObject(marker) || typeof intent.requestedAt !== "string" || marker.requestedAt !== intent.requestedAt) return "its pending marker is no longer this completion's";
9476
+ return null;
9477
+ };
9478
+ /** Why the retire whose attempt `attempt` left `result` is not tried again, or null when it is. */
9479
+ const notRetried = (attempt, result) => {
9480
+ if (!result[RETIRE_HOOK_DEBT_ONLY]) return "its cleanup owes more than retire hooks";
9481
+ if (attempt >= attempts) return "it was the last attempt";
9482
+ return notOwed();
9483
+ };
9484
+ const items = (result) => result.rollbackIncomplete.join("; ");
9485
+ /** The way out of a retire left incomplete after `run` attempts → false. `said` is the log's line
9486
+ * for it: none for a first attempt that owes more than hooks, which says what it said before. */
9487
+ const incomplete = (run, result, said) => {
9488
+ if (said) console.error(said);
9273
9489
  // A result and not an error, so it has no code. The retire worked on the home and left it
9274
9490
  // quarantined: the home is changed. The items are text of hooks and of Git, which the outcome
9275
9491
  // and the log hold and the event does not.
9276
- notCompleted({ ok: false, result, retry: `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}` },
9492
+ dropRetryState();
9493
+ notCompleted({ ok: false, result, retry, ...(run > 1 ? { attempts: run } : {}) },
9277
9494
  { code: null, homeChanged: true, sentence: RETIRE_INCOMPLETE_SENTENCE(intent.instance) });
9278
9495
  console.error(`deferred retirement of ${intent.instance} is INCOMPLETE; the home is retained:\n ${result.rollbackIncomplete.join("\n ")}`);
9279
9496
  return false;
9280
- }
9497
+ };
9498
+ /** What a retry throws under the home's claim when the home is no longer owed it: nothing was done.
9499
+ * Never answered as it is: the completion knows it by identity, and an answer code passes through
9500
+ * retireInstance unwrapped. */
9501
+ const cancelled = lifecycleBusy("none", `the retry of the retirement of ${intent.instance} was not started: its pending marker is no longer this completion's; nothing was done`,
9502
+ "nothing to do: the scheduling that marker names owns the retirement now", { instance: intent.instance, home });
9503
+ const ownStart = processStartToken(process.pid);
9504
+ let result;
9505
+ for (let attempt = 1; ; attempt++) {
9506
+ if (attempt > 1) {
9507
+ const why = notOwed();
9508
+ if (why) return incomplete(attempt - 1, result, `deferred retirement of ${intent.instance}: attempt ${attempt} of ${attempts} is not started: ${why}`);
9509
+ }
9510
+ const last = result;
9511
+ try {
9512
+ result = retireOnce(attempt > 1 ? () => { if (notOwed()) throw cancelled; } : undefined);
9513
+ } catch (e) {
9514
+ if (e === cancelled) return incomplete(attempt - 1, last, `deferred retirement of ${intent.instance}: attempt ${attempt} of ${attempts} is not started: ${notOwed() ?? "its pending marker was not this completion's under the home's claim"}`);
9515
+ const code = kernelCode(e, "E_LIFECYCLE_FAILED");
9516
+ // An answer without `reached` is one in which the retire of the home had not begun (retireInstance).
9517
+ // A retry's home was changed by the attempts before it: their hooks ran, and it is quarantined.
9518
+ const reached = e?.details?.reached;
9519
+ const homeChanged = attempt > 1 || (isPlainObject(reached) && (reached.hooksStarted === true || reached.home !== "kept"));
9520
+ dropRetryState();
9521
+ notCompleted({ ok: false, error: { code, message: e.message }, ...(e.details?.childrenStopped ? { childrenStopped: e.details.childrenStopped } : {}), ...(obsoleteDeleteBranch ? { warnings: [OBSOLETE_DELETE_BRANCH_SENTENCE] } : {}), retry, ...(attempt > 1 ? { attempts: attempt } : {}) },
9522
+ { code, homeChanged, sentence: e.message });
9523
+ console.error(`deferred retirement of ${intent.instance} failed${attempt > 1 ? ` on attempt ${attempt} of ${attempts}` : ""}: ${e.message}`);
9524
+ // A defect's stack goes to the completion's log (lib/errors.mjs isDefect).
9525
+ reportDefect(e);
9526
+ return false;
9527
+ }
9528
+ if (obsoleteDeleteBranch && attempt === 1) console.log(OBSOLETE_DELETE_BRANCH_SENTENCE);
9529
+ if (!result.rollbackIncomplete) break;
9530
+ const why = notRetried(attempt, result);
9531
+ // The first attempt of a retire that owes more than hooks says what it said before this rule.
9532
+ if (why) return incomplete(attempt, result, attempt > 1 || result[RETIRE_HOOK_DEBT_ONLY] ? `deferred retirement of ${intent.instance}: attempt ${attempt} of ${attempts} is incomplete (${items(result)}); it is not tried again: ${why}` : null);
9533
+ // When the next attempt starts, and the earliest the last one can: each wait follows the end of
9534
+ // the attempt before it, whose length cannot be known here.
9535
+ const now = Date.now(), wait = delays[attempt - 1];
9536
+ const nextAt = new Date(now + wait).toISOString(), lastAt = new Date(now + delays.slice(attempt - 1).reduce((a, b) => a + b, 0)).toISOString();
9537
+ console.error(`deferred retirement of ${intent.instance}: attempt ${attempt} of ${attempts} is incomplete (${items(result)}); attempt ${attempt + 1} runs at ${nextAt}`);
9538
+ // Without its file the retry still runs; a refusal meanwhile only says less.
9539
+ try { writeFileSync(retryPath, JSON.stringify({ requestedAt: intent.requestedAt, completionPid: process.pid, completionStart: ownStart, attempt: attempt + 1, attempts, nextAt, lastAt }, null, 2) + "\n"); }
9540
+ catch (e) { console.error(`deferred retirement: cannot write ${retryPath}: ${e.message}; it retries without it`); }
9541
+ if (wait) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, wait);
9542
+ }
9543
+ dropRetryState();
9281
9544
  if (intent.options?.keepDir) {
9282
9545
  // The kept home is the one the intent names, never a same-named twin.
9283
9546
  const retained = intent.options?.home ? { home: intent.options.home } : findInstanceHome(intent.root, intent.instance);
@@ -9295,6 +9558,21 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
9295
9558
  * (awebai/oats#693): the CLI cleans that home's wake schedules. A symbol, so
9296
9559
  * the printed and JSON receipt, and a recorded one, do not carry it. */
9297
9560
  export const RETIRE_SELECTED_HOME = Symbol("oats.retireSelectedHome");
9561
+ /** On retireInstance's result: true when its cleanup is incomplete and what it owes is retire hooks
9562
+ * and nothing else (no Git step, directory preservation, orphaned work directory, or item no rerun
9563
+ * of the hooks can clear). A deferred completion retries only such a retire
9564
+ * (completeDeferredRetirement). A symbol, so the printed and JSON receipts do not carry it. */
9565
+ const RETIRE_HOOK_DEBT_ONLY = Symbol("oats.retireHookDebtOnly");
9566
+ /** How long a deferred completion whose retire owes retire hooks alone waits after each failed
9567
+ * attempt before the next (completeDeferredRetirement): three retries, at about 1, 5 and 15 minutes. */
9568
+ export const RETIRE_RETRY_DELAYS_MS = Object.freeze([60 * 1000, 5 * 60 * 1000, 15 * 60 * 1000]);
9569
+ /** Where a deferred completion keeps its retry state while it waits between attempts, beside the
9570
+ * home: `{ requestedAt, completionPid, completionStart, attempt, attempts, nextAt, lastAt }`.
9571
+ * Kernel-internal. Read only by refusePendingCompletion, and only while the completion it names
9572
+ * is the live one the pending marker names; any retire that removes the home removes it too. */
9573
+ function retireRetryPath(home) {
9574
+ return join(dirname(home), `.oats-retire-retry-${basename(home)}.json`);
9575
+ }
9298
9576
  /** An option of retireInstance: a function it calls once it holds the home's claim, has resolved
9299
9577
  * the home again and has found no pending self-retire, before it reads anything else. What the
9300
9578
  * function throws is the retire's answer, and nothing was done; what it returns, `{ children?,
@@ -9305,6 +9583,31 @@ export const RETIRE_SELECTED_HOME = Symbol("oats.retireSelectedHome");
9305
9583
  * the answer is that it is running, and neither is read. A symbol, so no caller can set it from
9306
9584
  * parsed arguments or JSON. */
9307
9585
  export const RETIRE_UNDER_CLAIM = Symbol("oats.retireUnderClaim");
9586
+ /** The one internal option that hands a retire's steps the claim it runs under (claimHomeFor's
9587
+ * holding): where it records the retire hooks that ended, and what the gone holder it took over
9588
+ * from had recorded (finishedRetireHooks). A symbol, so no caller can set it. */
9589
+ const RETIRE_CLAIM = Symbol("oats.retireClaim");
9590
+ /** The retire hooks a gone retire had finished, as the claim it left says (`tookOver`: its record,
9591
+ * or null) → Map of capability → the meta that hook answered (undefined when it answered none).
9592
+ * A retire writes the list as it goes (`retireHooks: [{ capability, meta? }]`, with
9593
+ * `retireHooksFor`, the incarnation of the home), and the retire that takes its claim over does
9594
+ * not run those hooks again. The claim is a file others can write, read back as whatever is in
9595
+ * it: the list counts only when the record is a retire's and names this incarnation (`created`,
9596
+ * the home's `createdAt`), and of it only the entries whose capability has a retire hook in this
9597
+ * home (`caps`) and whose meta is an object or absent. Anything else names no hook, so that hook
9598
+ * runs: a claim without the list (an earlier kernel's) skips nothing. */
9599
+ function finishedRetireHooks(tookOver, created, caps) {
9600
+ const finished = new Map();
9601
+ if (!isPlainObject(tookOver) || claimAction(tookOver) !== "retire" || !Array.isArray(tookOver.retireHooks)) return finished;
9602
+ if (typeof created !== "string" || !created || tookOver.retireHooksFor !== created) return finished;
9603
+ const hooked = new Set(caps.filter((cap) => cap?.hooks?.retire).map((cap) => cap.id));
9604
+ for (const entry of tookOver.retireHooks) {
9605
+ if (!isPlainObject(entry) || !hooked.has(entry.capability)) continue;
9606
+ if (entry.meta !== undefined && !isPlainObject(entry.meta)) continue;
9607
+ finished.set(entry.capability, entry.meta);
9608
+ }
9609
+ return finished;
9610
+ }
9308
9611
  /** How many times a retire starts over because the name resolved to another home once it held the
9309
9612
  * claim of the first (that one removed, a same-named home of another agent made, in between). */
9310
9613
  const RETIRE_CLAIM_RESTARTS = 2;
@@ -9402,7 +9705,9 @@ export const READ_CLAIM_WHEN_UNWRITABLE = Symbol("oats.readClaimWhenUnwritable")
9402
9705
  * made as retire makes it for its recovery copies; the claims are private. A directory that
9403
9706
  * cannot be made is a claim that cannot be taken: nothing was done (awebai/oats#874).
9404
9707
  *
9405
- * → `{ lock, me }`, the holding. With READ_CLAIM_WHEN_UNWRITABLE, also
9708
+ * → `{ lock, me, tookOver }`, the holding; `tookOver` is the record of the gone holder whose claim
9709
+ * this one took over, as its file held it, or null when the claim was free (the last one, when
9710
+ * several were taken over in turn). With READ_CLAIM_WHEN_UNWRITABLE, also
9406
9711
  * → `{ lock, me: null, unwritable, look }` (awebai/oats#946): the claim could not be written,
9407
9712
  * for the system's code `unwritable` (lib/claim.mjs CLAIM_UNWRITABLE_CODES) at one of its
9408
9713
  * writes, and it was read where it would have been taken: nobody holds it. Nothing is held,
@@ -9421,7 +9726,11 @@ export function claimHomeFor(verb, name, home, { waitMs = 0, [READ_CLAIM_WHEN_UN
9421
9726
  claimWrite(() => mkdirSync(dirname(dirname(lock)), { recursive: true }));
9422
9727
  claimWrite(() => mkdirSync(dirname(lock), { recursive: true, mode: 0o700 }));
9423
9728
  } catch (e) { throw claimUnavailable(lock, e); }
9424
- return { lock, me: acquireClaim(lock, { ...refusals, facts: { action: verb }, waitMs }) };
9729
+ // The takeovers of this claim hand over what the gone holder's file held; those of the claims
9730
+ // that serialize a takeover (lib/claim.mjs takeOver) are of other files.
9731
+ let tookOver = null;
9732
+ const me = acquireClaim(lock, { ...refusals, facts: { action: verb }, waitMs, endHolderStep: (holder, at) => { if (at === lock) tookOver = holder; return {}; } });
9733
+ return { lock, me, tookOver };
9425
9734
  } catch (refusal) {
9426
9735
  const unwritable = readInstead ? unwritableCode(refusal) : undefined;
9427
9736
  if (!unwritable) throw refusal;
@@ -9522,22 +9831,34 @@ function removeAbandonedRetireClaims(root, name) {
9522
9831
  * (scheduleDeferredSelfRetirement) names it. Nothing refuses when there is no marker, when the
9523
9832
  * completion left its outcome (it failed: this retire retries it), when the marker names no
9524
9833
  * completion (an older kernel wrote it), when this process is that completion, or when that
9525
- * process is gone (it died: this retire does what it owed). */
9834
+ * process is gone (it died, or the marker was written in another boot: this retire does what it
9835
+ * owed; completionLiveness). */
9526
9836
  function refusePendingCompletion(name, home) {
9527
9837
  const marker = retirePendingMarkerPath(home);
9528
9838
  if (!existsSync(marker) || existsSync(deferredRetireResultPath(home))) return;
9529
9839
  const pending = readJsonOrUndefined(marker);
9530
9840
  const pid = pending?.completionPid;
9531
9841
  if (!Number.isSafeInteger(pid) || pid === process.pid) return;
9532
- const live = processLiveness({ pid, processStart: pending.completionStart });
9842
+ const live = completionLiveness(pending);
9533
9843
  if (live.state === "gone") return;
9534
9844
  const start = typeof pending.completionStart === "string" ? pending.completionStart : "none";
9535
9845
  const details = { instance: name, home, lock: marker, pid, since: pending.requestedAt ?? null, action: "retire" };
9536
- if (live.state === "alive") throw lifecycleBusy("running", `a retire of ${name} is already scheduled (its completion, pid ${pid}, requested at ${pending.requestedAt ?? "?"}); nothing was done`, "wait for it to finish", details);
9846
+ if (live.state === "alive") throw lifecycleBusy("running", `a retire of ${name} is already scheduled (its completion, pid ${pid}, requested at ${pending.requestedAt ?? "?"})${retryingSaid(home, pending)}; nothing was done`, "wait for it to finish", details);
9537
9847
  throw lifecycleBusy("unknown", `whether the completion of the scheduled retire of ${name} that ${marker} names (pid ${pid}, recorded start ${start}) still runs cannot be read (${live.reason}); nothing was done`,
9538
9848
  `check that pid by hand, and if it is not an oats retire, remove ${marker}, then retry`, { ...details, unknown: live.reason });
9539
9849
  }
9540
9850
 
9851
+ /** What a refusal adds while the completion `pending` names waits to retry a cleanup that did not
9852
+ * finish: the clause of its retry state (retireRetryPath) when that file names the same scheduling
9853
+ * and the same completion, else "". Its numbers and times are checked before they are said. */
9854
+ function retryingSaid(home, pending) {
9855
+ const r = readJsonOrUndefined(retireRetryPath(home));
9856
+ if (!isPlainObject(r) || r.requestedAt !== pending.requestedAt || r.completionPid !== pending.completionPid || r.completionStart !== (pending.completionStart ?? null)) return "";
9857
+ if (![r.attempt, r.attempts].every((n) => Number.isSafeInteger(n) && n > 0) || r.attempt > r.attempts) return "";
9858
+ if (![r.nextAt, r.lastAt].every((t) => typeof t === "string" && !Number.isNaN(Date.parse(t)) && new Date(Date.parse(t)).toISOString() === t)) return "";
9859
+ return `; it is retrying cleanup that did not finish: attempt ${r.attempt} of ${r.attempts} runs at ${r.nextAt}, the last no earlier than ${r.lastAt}`;
9860
+ }
9861
+
9541
9862
  /** Retire one instance. One retire of a home at a time (awebai/oats#863): the home's claim
9542
9863
  * (retireClaimPath; lib/claim.mjs) is taken as soon as the home is resolved, before anything the
9543
9864
  * retire acts on is read, and held until this returns or throws. Any other retire of that home
@@ -9582,7 +9903,7 @@ function retireUnderClaim(root, name, o) {
9582
9903
  // anything of the home. What it returns of the plan binds the retire.
9583
9904
  const confirmed = o[RETIRE_UNDER_CLAIM]?.();
9584
9905
  const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}), ...(confirmed.ambiguous ? { ambiguous: confirmed.ambiguous } : {}) } : o;
9585
- return retireClaimed(root, name, bound, now);
9906
+ return retireClaimed(root, name, { ...bound, [RETIRE_CLAIM]: held }, now);
9586
9907
  } finally {
9587
9908
  releaseHomeClaim(held);
9588
9909
  }
@@ -9712,7 +10033,7 @@ function retireSteps(root, name, o, found, at) {
9712
10033
  else markerUnusable = true;
9713
10034
  } catch { markerUnusable = true; }
9714
10035
  }
9715
- // #796: a marker a spawn wrote before its worktree hooks (`inProgress`). While that spawn's
10036
+ // #796: a marker a spawn wrote before its spawn or worktree hooks (`inProgress`). While that spawn's
9716
10037
  // process is verifiably alive it is a spawn in progress, never a quarantine to retry, --force
9717
10038
  // included. Once it is gone, the hook group it left is ended when its leader is alive at the
9718
10039
  // recorded start time; a group whose leader is gone is never signalled, only reported (its id may
@@ -9726,9 +10047,9 @@ function retireSteps(root, name, o, found, at) {
9726
10047
  if (isPlainObject(rawMarker?.inProgress)) {
9727
10048
  const p = rawMarker.inProgress;
9728
10049
  const live = processLiveness(p);
9729
- if (live.state === "alive") throw lifecycleBusy("running", `${name} is still being spawned (pid ${p.pid}, running its worktree hooks since ${p.startedAt ?? "?"}); nothing was retired`, "wait for the spawn to end, or stop that process, then retire");
10050
+ if (live.state === "alive") throw lifecycleBusy("running", `${name} is still being spawned (pid ${p.pid}, running its hooks since ${p.startedAt ?? "?"}); nothing was retired`, "wait for the spawn to end, or stop that process, then retire");
9730
10051
  if (live.state === "unknown") {
9731
- if (!o.force) throw lifecycleBusy("unknown", `${name}: whether its spawn (pid ${p.pid}, recorded start ${p.processStart ?? "none"}, running its worktree hooks since ${p.startedAt ?? "?"}) still runs cannot be read (${live.reason}); nothing was retired`,
10052
+ if (!o.force) throw lifecycleBusy("unknown", `${name}: whether its spawn (pid ${p.pid}, recorded start ${p.processStart ?? "none"}, running its hooks since ${p.startedAt ?? "?"}) still runs cannot be read (${live.reason}); nothing was retired`,
9732
10053
  `check that pid by hand, and if it is not that spawn, run \`oats retire ${name} --force\``, { pid: p.pid, processStart: p.processStart ?? null, unknown: live.reason, remedy: `oats retire ${name} --force` });
9733
10054
  inProgressUnverified = true;
9734
10055
  spawnGroupWarnings.push(`retired with --force although whether its spawn (pid ${p.pid}) still runs could not be read (${live.reason}); its branch is kept`);
@@ -9799,6 +10120,16 @@ function retireSteps(root, name, o, found, at) {
9799
10120
  if (!existsSync(metaPath) && !quarantine && !o.force) {
9800
10121
  throw oatsError("E_UNIDENTIFIED_INSTANCE_HOME", `${found.home} has no instance.json and no cleanup descriptor, so OATS cannot tell whether external state (identities, worktrees) still depends on it. Retiring it would delete whatever it holds without running any cleanup. Inspect it, then re-run with \`--force\` to remove it anyway.`);
9801
10122
  }
10123
+ // The retire hooks run from the record: the repository they are run for (`repo`) and the
10124
+ // capabilities with their hooks (`capabilityRuntime`). A record with no repository runs none.
10125
+ // That is a retire with nothing left out only when the record says that no capability has a
10126
+ // retire hook. One that does not say (the stub lib/materialize.mjs writes, left by a spawn that
10127
+ // was killed before its record and wrote no marker before its hooks) may stand for an identity
10128
+ // registered outside the home: removing the home would leave it there with nothing that knows
10129
+ // of it. Fail closed, as for a home with no record; `--force` is the same deliberate escape.
10130
+ if (!o.force && !nonEmptyString(meta.repo) && !(Array.isArray(meta.capabilityRuntime) && !meta.capabilityRuntime.some((cap) => cap?.hooks?.retire))) {
10131
+ throw oatsError("E_UNIDENTIFIED_INSTANCE_HOME", `${metaPath} records neither a repository nor its capabilities' hooks (a spawn that was interrupted before it wrote its record leaves such a file), so OATS cannot tell which retire hooks to run, and what the spawn's hooks registered outside the home (an identity, a seat) may still be there. Retiring it would remove the home without running any of them. Nothing was stopped, run or removed. Inspect the home, clean up by hand what its capabilities registered, then remove it with \`oats retire ${name} --force\`.`);
10132
+ }
9802
10133
 
9803
10134
  const workPath = join(found.home, "work");
9804
10135
  // What work/ is, by the one function the plan reads too (instanceWork, #962). Read once, here.
@@ -10022,12 +10353,29 @@ function retireSteps(root, name, o, found, at) {
10022
10353
  at.phase = "after-hooks";
10023
10354
  at.hooksStarted = true;
10024
10355
  at.said = () => `The retire hooks were started and may not all have run; the home, its work and the pre-hook recovery (if any) are kept; ${sessionSaid()}`;
10356
+ // The hooks that end are recorded in this retire's claim as they end, after those a gone
10357
+ // retire it took over from had recorded: a retire that takes this one's claim over does not
10358
+ // run them again (finishedRetireHooks). The claim is beside the home, so nothing is written
10359
+ // into the home; a record that cannot be written leaves the hook to be run again.
10360
+ const claim = o[RETIRE_CLAIM];
10361
+ const finished = finishedRetireHooks(claim?.tookOver, meta.createdAt, resolved.capabilities);
10362
+ const ended = [...finished].map(([capability, answered]) => ({ capability, ...(answered !== undefined ? { meta: answered } : {}) }));
10363
+ const recordEnded = () => {
10364
+ if (!claim?.me || typeof meta.createdAt !== "string" || !meta.createdAt) return;
10365
+ try { recordInClaim(claim.lock, claim.me, { retireHooks: ended, retireHooksFor: meta.createdAt }); } catch { /* that hook is run again by a take-over */ }
10366
+ };
10367
+ if (ended.length) recordEnded();
10025
10368
  hookResults = runLifecycleHooks("retire", {
10026
10369
  home: found.home, instance: name, agentName: found.agent.name,
10027
10370
  soulDir: instanceSoulDir(found.home, meta) || found.agent._soulDir || join(found.agent._dir, "soul"),
10028
10371
  ...(nonEmptyString(meta.soulId) ? { soulId: meta.soulId } : {}),
10029
10372
  contextDir: meta.repo, workspaceDir: workspaceOf(root), rootDir: root, resolved, priorMeta: meta.capabilityMeta || {},
10373
+ finished, onFinished: (capability, answered) => { ended.push({ capability, ...(isPlainObject(answered) ? { meta: answered } : {}) }); recordEnded(); },
10030
10374
  });
10375
+ // The hooks ran: their warnings are events now, whatever the retire does
10376
+ // next (a refusal, a quarantine), so an action a hook names outlives the
10377
+ // answer (#1749). Recorded as given, in the workspace log only.
10378
+ for (const message of hookResults.warnings || []) appendEvent(found.home, { kind: RETIRE_HOOK_WARNING_KIND, data: { message } }, { workspaceOnly: true });
10031
10379
  }
10032
10380
  at.phase = "after-hooks";
10033
10381
  at.said = afterHooks;
@@ -10060,6 +10408,9 @@ function retireSteps(root, name, o, found, at) {
10060
10408
  // A quarantine retry's outcome apart from Git: what the hooks it reran left undone, and what they owed and
10061
10409
  // did not run. Known before the worktree step, which waits for it.
10062
10410
  const retryFailures = [];
10411
+ // How many of them no rerun of the retire hooks can clear: a capability with no retire hook, hooks
10412
+ // that cannot be rerun, an orphaned work directory. The rest are hook debt (retireHookDebtOnly).
10413
+ let retryNonHook = 0;
10063
10414
  if (quarantine) {
10064
10415
  for (const f of hookResults?.failures || []) retryFailures.push(`retire hook ${f.capability}: ${f.message}`);
10065
10416
  for (const [capId, m] of Object.entries(hookResults?.meta || {})) {
@@ -10076,12 +10427,14 @@ function retireSteps(root, name, o, found, at) {
10076
10427
  for (const capId of quarantine.cleanup.outstanding?.hooks || []) {
10077
10428
  if (ran.has(capId)) continue;
10078
10429
  const cap = (meta.capabilityRuntime || []).find((c) => c.id === capId);
10079
- retryFailures.push(cap && !cap.hooks?.retire
10430
+ const noHook = !!cap && !cap.hooks?.retire;
10431
+ if (noHook) retryNonHook++;
10432
+ retryFailures.push(noHook
10080
10433
  ? `${capId}: declares no retire hook, so OATS cannot verify or undo what its failed spawn hook may have created — clean up by hand, then remove the home with \`oats retire ${name} --force\``
10081
10434
  : `retire hook ${capId}: did not run on this retry, so the cleanup it owed is unverified`);
10082
10435
  }
10083
- if (!hookResults) retryFailures.push("retire hooks could not be rerun (cleanup descriptor lost its context repo)");
10084
- if (orphanItem) retryFailures.push(orphanItem);
10436
+ if (!hookResults) { retryNonHook++; retryFailures.push("retire hooks could not be rerun (cleanup descriptor lost its context repo)"); }
10437
+ if (orphanItem) { retryNonHook++; retryFailures.push(orphanItem); }
10085
10438
  }
10086
10439
 
10087
10440
  // Hooks are allowed to mutate the inspected tree, so inspect again after
@@ -10382,6 +10735,10 @@ function retireSteps(root, name, o, found, at) {
10382
10735
  // Otherwise the home — and the credentials in it — must survive again, or the
10383
10736
  // retry becomes the deletion the quarantine was preventing.
10384
10737
  let stillIncomplete;
10738
+ // Whether what is still incomplete is retire hooks and nothing else (RETIRE_HOOK_DEBT_ONLY).
10739
+ // `keptForRetry` is not debt of its own: it is the worktree kept because of those items, and a
10740
+ // retry runs the worktree step once they clear.
10741
+ let hookDebtOnly = false;
10385
10742
  // Ordinary path: quarantine instead of deleting, using the SAME writer the
10386
10743
  // spawn rollback uses. Two copies of this logic is how a previous divergence
10387
10744
  // happened (see quarantineInstanceHome), so there is still exactly one.
@@ -10392,6 +10749,9 @@ function retireSteps(root, name, o, found, at) {
10392
10749
  for (const [capId, m] of Object.entries(hookResults?.meta || {})) {
10393
10750
  if (m && typeof m === "object" && m.retired === false && m.reason !== "nothing-to-delete") outstandingHooks.add(capId);
10394
10751
  }
10752
+ // What the writer adds to the items is debt of its own: a descriptor kept outside the home, or
10753
+ // one that could not be stored, owes a restoration no rerun of the hooks makes.
10754
+ const itemsBeforeQuarantine = ordinaryIncomplete.length;
10395
10755
  quarantineInstanceHome({
10396
10756
  home: found.home, instance: name, agent: found.agent,
10397
10757
  soulDir: instanceSoulDir(found.home, meta), soulId: nonEmptyString(meta.soulId) ? meta.soulId : undefined,
@@ -10404,11 +10764,14 @@ function retireSteps(root, name, o, found, at) {
10404
10764
  reason: outstandingHooks.size ? "retire hook reported incomplete cleanup" : "the work directory has no git admin entry",
10405
10765
  });
10406
10766
  stillIncomplete = ordinaryIncomplete;
10767
+ hookDebtOnly = outstandingHooks.size > 0 && !orphanItem && ordinaryIncomplete.length === itemsBeforeQuarantine;
10407
10768
  }
10408
10769
  let branchDeletedByRetry = false, branchKeptReason;
10409
10770
  if (quarantine) {
10410
10771
  const failures = [...retryFailures];
10411
10772
  if (keptForRetry) failures.push(keptForRetry);
10773
+ // What the hooks left, before the Git verification below adds its own items.
10774
+ const hookItems = failures.length;
10412
10775
  // The quarantine may exist BECAUSE Git cleanup failed, so a retry has to
10413
10776
  // redo those steps and verify them — not just rerun hooks. No retire deletes a branch.
10414
10777
  if (workMeta.work === "worktree" && workMeta.repo) {
@@ -10480,6 +10843,11 @@ function retireSteps(root, name, o, found, at) {
10480
10843
  }
10481
10844
  if (failures.length) {
10482
10845
  stillIncomplete = failures;
10846
+ // Hook debt alone: a retire hook is still owed, nothing no rerun can clear is, no Git step was
10847
+ // added by the verification above, and the marker owes no Git step, directory or orphaned work.
10848
+ const owed = quarantine.cleanup.outstanding;
10849
+ hookDebtOnly = retryFailures.length > 0 && retryNonHook === 0 && failures.length === hookItems
10850
+ && !owed?.git?.length && owed?.directory !== true && owed?.orphanedWork !== true;
10483
10851
  try {
10484
10852
  writeFileSync(quarantinePath, JSON.stringify({ ...quarantine, incomplete: failures, lastRetryAt: new Date().toISOString() }, null, 2) + "\n");
10485
10853
  } catch { /* the quarantine stands regardless */ }
@@ -10532,6 +10900,8 @@ function retireSteps(root, name, o, found, at) {
10532
10900
  rmSync(retirePendingMarkerPath(found.home), { force: true });
10533
10901
  rmSync(deferredRetireResultPath(found.home), { force: true });
10534
10902
  rmSync(deferredRetireResultPath(found.home).replace(/\.json$/, ".log"), { force: true });
10903
+ // And the retry state a completion that was killed while it waited may have left (retireRetryPath).
10904
+ rmSync(retireRetryPath(found.home), { force: true });
10535
10905
  at.lead = null;
10536
10906
  }
10537
10907
 
@@ -10552,6 +10922,7 @@ function retireSteps(root, name, o, found, at) {
10552
10922
  return w.length ? w : undefined;
10553
10923
  })() };
10554
10924
  result[RETIRE_SELECTED_HOME] = found.home;
10925
+ result[RETIRE_HOOK_DEBT_ONLY] = !!stillIncomplete && !forced && hookDebtOnly;
10555
10926
  if (self) {
10556
10927
  // The caller is the instance: its process lives in the window we are about to
10557
10928
  // kill. Detach the kill so this function can return and the caller can report