@awebai/oats 0.51.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +3 -1
  2. package/bin/oats.mjs +407 -123
  3. package/docs/capabilities.md +75 -6
  4. package/docs/configuration.md +200 -91
  5. package/docs/desktop-cli-api.md +1563 -113
  6. package/docs/desktop-instance-start.md +69 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +145 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +238 -17
  12. package/docs/integrations.md +13 -9
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +25 -2
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/macos-test-runs.md +246 -0
  20. package/docs/oats-local.schema.json +4 -3
  21. package/docs/official-catalog.md +5 -5
  22. package/docs/packages.md +14 -14
  23. package/docs/release-lane.md +225 -11
  24. package/docs/release-notes/v0.44.0.md +1 -1
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/release-notes/v0.53.0.md +1274 -0
  27. package/docs/schedules.md +97 -4
  28. package/docs/souls-and-instances.md +332 -40
  29. package/docs/tui.md +584 -0
  30. package/docs/upgrading.md +298 -0
  31. package/docs/workspaces.md +3 -3
  32. package/lib/automations.mjs +22 -22
  33. package/lib/claim.mjs +278 -49
  34. package/lib/config-data.mjs +4 -1
  35. package/lib/core.mjs +1282 -289
  36. package/lib/errors.mjs +170 -0
  37. package/lib/harness-trust-write.mjs +68 -27
  38. package/lib/harness-trust.mjs +34 -16
  39. package/lib/instance-events.mjs +19 -1
  40. package/lib/instance-git.mjs +39 -3
  41. package/lib/instance-inspect.mjs +45 -17
  42. package/lib/instance-lifecycle.mjs +306 -57
  43. package/lib/instance-resolution.mjs +59 -6
  44. package/lib/launch-preference.mjs +236 -9
  45. package/lib/launch-prompt-completion.mjs +7 -43
  46. package/lib/launch-prompt-evidence.mjs +14 -7
  47. package/lib/launch-prompt-fixtures/README.md +86 -152
  48. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  49. package/lib/launch-prompt-fixtures.mjs +122 -109
  50. package/lib/launch-prompt-transport.mjs +2 -56
  51. package/lib/launch-prompts.mjs +102 -100
  52. package/lib/local-edit.mjs +118 -0
  53. package/lib/packages.mjs +13 -4
  54. package/lib/pi-bridge.mjs +308 -0
  55. package/lib/refused-text.mjs +11 -0
  56. package/lib/remote.mjs +190 -25
  57. package/lib/resolve.mjs +2 -1
  58. package/lib/retained-after-retire.mjs +2 -2
  59. package/lib/retire-output.mjs +12 -1
  60. package/lib/schedule-host.mjs +125 -22
  61. package/lib/schedule.mjs +73 -24
  62. package/lib/shell-word.mjs +13 -0
  63. package/lib/soul-launch-verbs.mjs +153 -0
  64. package/lib/stable-node.mjs +62 -0
  65. package/lib/system-tools.mjs +39 -0
  66. package/lib/teams-verbs.mjs +18 -46
  67. package/lib/tmux-server-scope.mjs +62 -0
  68. package/lib/triggers.mjs +4 -4
  69. package/lib/workspace.mjs +54 -30
  70. package/lib/worktree-hooks.mjs +98 -20
  71. package/lib/worktree.mjs +83 -24
  72. package/package-catalog.json +4 -4
  73. package/package.json +8 -2
  74. package/packages/client/attach-exit.mjs +25 -0
  75. package/packages/client/capability-show-contract.mjs +230 -0
  76. package/packages/client/capability-warnings-contract.mjs +57 -0
  77. package/packages/client/cli-adapter.mjs +561 -0
  78. package/packages/client/cli-environment.mjs +53 -0
  79. package/packages/client/cli-locator.mjs +253 -0
  80. package/packages/client/cli-probe-contract.mjs +47 -0
  81. package/packages/client/client-terms.mjs +60 -0
  82. package/packages/client/deployment-contract.mjs +72 -0
  83. package/packages/client/deployment-data.mjs +483 -0
  84. package/packages/client/deployment-facts.mjs +95 -0
  85. package/packages/client/deployment-label.mjs +76 -0
  86. package/packages/client/deployment-observer.mjs +89 -0
  87. package/packages/client/deployment-panel.mjs +180 -0
  88. package/packages/client/deployment-read-cli.mjs +57 -0
  89. package/packages/client/display-text.mjs +50 -0
  90. package/packages/client/harness-names.mjs +30 -0
  91. package/packages/client/inspect-contract.mjs +62 -0
  92. package/packages/client/instance-acts.mjs +90 -0
  93. package/packages/client/instance-admission.mjs +45 -0
  94. package/packages/client/instance-events-contract.mjs +76 -0
  95. package/packages/client/instance-git-contract.mjs +80 -0
  96. package/packages/client/instance-presentation.mjs +86 -0
  97. package/packages/client/instance-tree.mjs +462 -0
  98. package/packages/client/kernel-environment.mjs +11 -0
  99. package/packages/client/kernel-lines.mjs +31 -0
  100. package/packages/client/kernel-made.mjs +23 -0
  101. package/packages/client/launch-contract.mjs +51 -0
  102. package/packages/client/launch-prompt-outcome.mjs +200 -0
  103. package/packages/client/lifecycle-cli.mjs +61 -0
  104. package/packages/client/lifecycle-contract.mjs +413 -0
  105. package/packages/client/liveness-main.mjs +10 -0
  106. package/packages/client/liveness.mjs +48 -0
  107. package/packages/client/machine-contract.mjs +123 -0
  108. package/packages/client/own-codes.mjs +31 -0
  109. package/packages/client/own-environment.mjs +22 -0
  110. package/packages/client/panel-views.mjs +293 -0
  111. package/packages/client/readiness-contract.mjs +174 -0
  112. package/packages/client/refresh-loop.mjs +52 -0
  113. package/packages/client/remote-address.mjs +151 -0
  114. package/packages/client/remote-identity-memory.mjs +94 -0
  115. package/packages/client/remote-roster.mjs +153 -0
  116. package/packages/client/roster-sections.mjs +80 -0
  117. package/packages/client/session-attach.mjs +175 -0
  118. package/packages/client/spawn-apply-cli.mjs +104 -0
  119. package/packages/client/spawn-apply-contract.mjs +195 -0
  120. package/packages/client/spawn-decision.mjs +46 -0
  121. package/packages/client/spawn-messages.mjs +142 -0
  122. package/packages/client/spawn-preview-cli.mjs +38 -0
  123. package/packages/client/spawn-preview-contract.mjs +318 -0
  124. package/packages/client/team-members.mjs +41 -0
  125. package/packages/client/team-rows.mjs +45 -0
  126. package/packages/client/terminal-contract.mjs +57 -0
  127. package/packages/client/terminal-exec.mjs +21 -0
  128. package/packages/client/tmux-status.mjs +66 -0
  129. package/packages/client/waiting-on-you.mjs +88 -0
  130. package/packages/client/workspace-admission.mjs +45 -0
  131. package/packages/client/workspace-choices.mjs +95 -0
  132. package/packages/client/workspace-cli.mjs +142 -0
  133. package/packages/client/workspace-views.mjs +183 -0
  134. package/packages/record/README.md +21 -0
  135. package/packages/record/bin/setup.mjs +108 -15
  136. package/packages/tui/README.md +64 -0
  137. package/packages/tui/bin/tui.mjs +7 -0
  138. package/packages/tui/lib/actions.mjs +44 -0
  139. package/packages/tui/lib/client.mjs +35 -0
  140. package/packages/tui/lib/config.mjs +151 -0
  141. package/packages/tui/lib/main.mjs +176 -0
  142. package/packages/tui/lib/model.mjs +392 -0
  143. package/packages/tui/lib/read.mjs +473 -0
  144. package/packages/tui/lib/store.mjs +364 -0
  145. package/packages/tui/lib/term/keys.mjs +367 -0
  146. package/packages/tui/lib/term/screen.mjs +134 -0
  147. package/packages/tui/lib/term/style.mjs +43 -0
  148. package/packages/tui/lib/term/text.mjs +109 -0
  149. package/packages/tui/lib/term/tty.mjs +178 -0
  150. package/packages/tui/lib/term/width.mjs +124 -0
  151. package/packages/tui/lib/views/detail.mjs +46 -0
  152. package/packages/tui/lib/views/frame.mjs +256 -0
  153. package/packages/tui/lib/views/help.mjs +140 -0
  154. package/packages/tui/lib/views/instances.mjs +137 -0
  155. package/packages/tui/lib/views/scroll.mjs +19 -0
  156. package/packages/tui/lib/views/switcher.mjs +97 -0
  157. package/packages/tui/package.json +8 -0
  158. package/skills/oats-getting-started/SKILL.md +30 -23
  159. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  160. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  161. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  162. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  163. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  164. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  165. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  166. package/lib/launch-prompt-policy.mjs +0 -87
package/lib/core.mjs CHANGED
@@ -27,11 +27,10 @@
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 { effectiveLaunchPromptPolicy } from "./launch-prompt-policy.mjs";
31
30
  import { canonicalHomePath, realPathOrNearest } from "./real-path.mjs";
32
- import { createLaunchPromptController } from "./launch-prompts.mjs";
31
+ import { createLaunchPromptController, neverSettled } from "./launch-prompts.mjs";
33
32
  import { retainLaunchPromptFrame } from "./launch-prompt-evidence.mjs";
34
- import { qualifyLaunchPromptFixtures } from "./launch-prompt-fixtures.mjs";
33
+ import { launchPromptEngages, claudeVersionOf, CLAUDE_SESSION_HINT } from "./launch-prompt-fixtures.mjs";
35
34
  import { LAUNCH_PANE_FORMAT, launchPaneTarget, launchPromptTransport } from "./launch-prompt-transport.mjs";
36
35
  import { execFileSync, execSync, spawn as spawnProcess, spawnSync } from "node:child_process";
37
36
  import {
@@ -47,16 +46,18 @@ import { initializeNativeHistory, prepareNativeStart } from "../packages/record/
47
46
  import { noteRuntimeName } from "./deprecation.mjs";
48
47
  import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
49
48
  import { inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
50
- import { appendEvent, liveWaiting, recordStartBoundary } from "./instance-events.mjs";
49
+ import { appendEvent, incarnationOf, liveWaiting, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
51
50
  import { killGroup } from "./process-group.mjs";
52
- import { interruptExitStatus, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
53
- import { CLAIM_WAIT_MS, acquireClaim, releaseClaim, removeGoneClaim } from "./claim.mjs";
51
+ 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
53
  import { captureLoginEnvironment } from "./login-environment.mjs";
54
+ import { kernelNode } from "./stable-node.mjs";
55
55
 
56
- import { oatsError, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
56
+ 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";
57
57
  import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
58
- import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigUnknown, launchLayers, launchReport, selectionFrom } from "./launch-preference.mjs";
59
- import { claudeTrusts, codexTrustsRoot, harnessTrustWarning } from "./harness-trust.mjs";
58
+ import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchConfigUnknownFix, launchLayers, launchPreferenceUnmatched, launchPreferenceUnmatchedProblem, launchReport, selectionFrom } from "./launch-preference.mjs";
59
+ import { shq, shellWord } from "./shell-word.mjs";
60
+ import { claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigDir } from "./harness-trust.mjs";
60
61
  async function materializePreparedDefault(prepared, home) { const m = await import("./instance-resolution.mjs"); return m.materializePrepared(prepared, home); }
61
62
  // Capability rows for a PREPARED spawn (workspace model): the one function that
62
63
  // turns a Resolution's modules into the row shape hooks/environment/requirements/
@@ -80,7 +81,9 @@ export { exactTreeDigest, fingerprintTree, KERNEL_HOME_RECEIPTS, storedTreeDiges
80
81
  import { canonicalJson, lineAt, parseStrictJson } from "./canonical-json.mjs";
81
82
  import { readPortableBytes } from "./bounded-read.mjs";
82
83
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes } from "./tree-copy.mjs";
83
- import { assertSameWorktreeHead, gitRead, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
84
+ import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
85
+ import { systemTool } from "./system-tools.mjs";
86
+ import { creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
84
87
  /** The package and capability id grammar (namespaced, lowercase): an id names a
85
88
  * directory (a home's module copy), so no path spelling fits it. */
86
89
  const PACKAGE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
@@ -172,7 +175,7 @@ export function legacyCapturedHomes(root) {
172
175
  }
173
176
  // The tmux session a new tmux instance opens its window in, when oats-local.yaml session.tmuxSession
174
177
  // names none (0.31). PI_AGENTS_TMUX_SESSION is the pre-0.31 variable, still honoured. The Desktop keeps
175
- // the same default in packages/desktop/server/tmux-status.mjs (it does not import lib/): change both.
178
+ // the same default in packages/client/tmux-status.mjs (it does not import lib/): change both.
176
179
  export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env.PI_AGENTS_TMUX_SESSION || "oats-agents";
177
180
  /**
178
181
  * The tmux session a NEW tmux launch opens its window in (0.31): the caller's, else the deployment's
@@ -228,12 +231,9 @@ function shIn(cwd, cmdline, timeout = 45000) {
228
231
  return execSync(cmdline, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout }).trim();
229
232
  }
230
233
  function shInTry(cwd, cmdline, timeout) { try { return shIn(cwd, cmdline, timeout); } catch { return undefined; } }
231
- export function shq(s) { return `'${String(s).replace(/'/g, `'\\''`)}'`; }
232
- /** One word of a command line that a person or an agent pastes into a shell: as it is when it holds
233
- * only letters, digits and `_./:-`, single-quoted otherwise (an empty string too). The safe set is
234
- * deliberately small: no `~` (an unquoted leading one expands), no `=` (zsh expands a leading
235
- * `=word`). */
236
- export function shellWord(s) { const word = String(s); return /^[A-Za-z0-9_.\/:-]+$/.test(word) ? word : shq(word); }
234
+ // The shell quoting of a printed command lives in lib/shell-word.mjs, which imports nothing, so that
235
+ // lib/launch-preference.mjs (imported here) quotes by the same rule.
236
+ export { shq, shellWord };
237
237
  export function slug(s) {
238
238
  const r = String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
239
239
  return r || "agent";
@@ -584,13 +584,16 @@ const LAUNCH_CONFIG_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
584
584
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
585
585
  /** Environment the kernel sets for every launch (identity, home, roots) and
586
586
  * its reference aliases: a configuration may not name them. */
587
- export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "OATS_AGENT", "OATS_SOUL", "OATS_SOUL_ID", "OATS_ROOT", "OATS_CONTEXT", "OATS_WORKSPACE", "OATS_EVENT", "OATS_SETTINGS", "OATS_SETTINGS_ORIGINS", "OATS_CLI_BIN", "PI_AGENT_INSTANCE", "PI_AGENT_HOME", "PI_AGENTS_ROOT",
587
+ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "OATS_AGENT", "OATS_SOUL", "OATS_SOUL_ID", "OATS_ROOT", "OATS_CONTEXT", "OATS_WORKSPACE", "OATS_EVENT", "OATS_SETTINGS", "OATS_SETTINGS_ORIGINS", "OATS_CLI_BIN", "OATS_NODE_BIN", "PI_AGENT_INSTANCE", "PI_AGENT_HOME", "PI_AGENTS_ROOT",
588
588
  // The test seam that replaces the login shell (lib/login-environment.mjs): never a launch's to set.
589
589
  "OATS_TEST_LOGIN_SHELL",
590
590
  // The test seams of #796, the same: a worktree hook's fixed timeout, the fetch timeout of
591
591
  // `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
592
592
  // process's start time on a host with procfs, and the `ps` it runs (lib/worktree-hooks.mjs processStart).
593
- "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS"]);
593
+ "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS",
594
+ // The test seams of #915: the cgroup the kernel judges itself in, and the directories its systemd-run
595
+ // comes from (lib/tmux-server-scope.mjs, lib/system-tools.mjs).
596
+ "OATS_TEST_CGROUP", "OATS_TEST_SYSTEM_TOOL_DIRS"]);
594
597
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
595
598
  const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
596
599
  export function validateLaunchConfig(name, entry, where) {
@@ -639,27 +642,63 @@ function validateLaunchConfigs(map, file) {
639
642
  for (const [name, entry] of Object.entries(map)) validateLaunchConfig(name, entry, file);
640
643
  validateLaunchConfigDefaults(map, file);
641
644
  }
642
- export function launchPromptPolicyAt(deployment, home) {
645
+ /** The one-line statement a launch shows when it engages the development-channel
646
+ * confirmation: what it passes, what OATS does, and what stops it. */
647
+ export const DEV_CHANNEL_STATEMENT = "This start passes --dangerously-load-development-channels plugin:aweb-channel@awebai-marketplace; OATS confirms Claude's development-channel prompt once. The messaging provider's delivery or channel-mode setting stops it (the provider's warning says where those settings are).";
648
+ /** The warning of a start where Claude ignored the development-channel flag: the
649
+ * session runs, with no channel. It replaces DEV_CHANNEL_STATEMENT in that start's answer. */
650
+ export const FLAG_IGNORED_WARNING = "Claude reported that channels are not currently available and ignored the development-channel flag, so this instance gets no channel delivery: mail and chat will not wake it. Check first for a telemetry opt-out in the launch environment (DISABLE_TELEMETRY, DO_NOT_TRACK or CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: Claude Code disables channels when one is set), then whether this Claude account offers channels; otherwise change the messaging provider's delivery (its readiness warning says where the setting is). See docs/configuration.md#the-development-channel-confirmation.";
651
+ /** A start's warnings once Claude ignored the flag: the statement that OATS
652
+ * confirms the prompt is replaced by what the outcome means. */
653
+ const flagIgnoredWarnings = warnings => [...warnings.filter(w => w !== DEV_CHANNEL_STATEMENT), FLAG_IGNORED_WARNING];
654
+ /** Whether this launch engages the confirmation: decided from the rendered argv
655
+ * alone, never from provider settings. */
656
+ function devChannelEngaged(harness, command) {
657
+ return launchPromptEngages({ harness, argv: describeLaunchCommand(command).argv });
658
+ }
659
+ /** A start that does not engage the confirmation still records that, so the
660
+ * record always describes the last start. */
661
+ const notEngaged = startId => ({ status: "not-engaged", startId, at: new Date().toISOString() });
662
+ /** The record of a start where Claude ignored the flag: it asked nothing and
663
+ * runs, so nothing waits for a person. Its launch-prompt event holds the receipt. */
664
+ const channelsUnavailable = (startId, result) => ({ status: "flag-ignored", reason: "channels-unavailable", signatureId: result.signatureId, startId, at: new Date().toISOString() });
665
+ /** A started session is launched when the confirmation completed, or when Claude
666
+ * ignored the flag and showed none. */
667
+ const promptLaunched = status => status === "completed" || status === "flag-ignored";
668
+ /** The warning for a host `launchPromptAnswers` block the validator let through
669
+ * (only `true` entries, an empty block, `workspaceTrust`): it is ignored. */
670
+ export function launchPromptAnswersNotice(deployment) {
643
671
  let found;
644
672
  try { found = loadLocal(deployment); }
645
673
  catch (e) { if (e.code !== "E_LOCAL_MISSING") throw e; }
646
- return effectiveLaunchPromptPolicy(found?.local ?? {}, realPathOrNearest(home), found?.path ?? null);
674
+ if (!found?.local || typeof found.local !== "object" || !Object.hasOwn(found.local, "launchPromptAnswers")) return null;
675
+ return `launchPromptAnswers in ${found.path} is ignored: remove it. OATS confirms Claude's development-channel prompt whenever it launches Claude with --dangerously-load-development-channels plugin:aweb-channel@awebai-marketplace; settings.oats.aweb.delivery: session or settings.oats.aweb.claudeChannelMode: approved keeps Claude from being launched that way.`;
676
+ }
677
+ /** What a start of `command` says before it runs: the ignored-key notice, then
678
+ * the development-channel statement when the argv engages the confirmation. */
679
+ export function launchStartNotices(deployment, harness, command) {
680
+ return [launchPromptAnswersNotice(deployment), devChannelEngaged(harness, command) ? DEV_CHANNEL_STATEMENT : null].filter(Boolean);
647
681
  }
648
- const promptOptedIn = policy => policy.awebDevelopmentChannel === true;
649
682
  function assertLaunchHome(home, expected) {
650
683
  const actual = directoryIdentity(home);
651
684
  if (!expected || actual.dev !== expected.dev || actual.ino !== expected.ino) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "launch home identity changed");
652
685
  }
653
- function promptController(home, startId, harness, policy, command, io, expectedHomeIdentity) {
686
+ function promptController(home, startId, command, io, expectedHomeIdentity) {
654
687
  assertLaunchHome(home, expectedHomeIdentity);
655
- const described = describeLaunchCommand(command);
656
- const qualification = qualifyLaunchPromptFixtures({ home: realPathOrNearest(home), harness, executablePath: described.executable, argv: described.argv });
657
- return createLaunchPromptController({ home: realPathOrNearest(home), startId, ...qualification, policy, expectedHomeIdentity,
688
+ return createLaunchPromptController({ home: realPathOrNearest(home), startId, ...claudeVersionOf(describeLaunchCommand(command).executable), expectedHomeIdentity,
658
689
  transport: launchPromptTransport(io), audit: data => appendEvent(home, { kind: "launch-prompt", data }), retainFrame: retainLaunchPromptFrame,
659
690
  ...(io?.now ? { now: io.now } : {}), ...(io?.sleep ? { sleep: io.sleep } : {}) });
660
691
  }
661
692
  function retainedPromptError(home, instance, target, parentLineageCommitted, launchPrompts) {
662
- return Object.assign(oatsError("E_SPAWN_INCOMPLETE", `${launchPrompts.reason}; home and pane retained: inspect ${home}, then use oats session start --home ${shellWord(home)}. If the harness changed, refresh its qualified prompt fixtures; never broaden the matcher.`), {
693
+ const hint = launchPrompts.claudeSessionShown ? ` ${CLAUDE_SESSION_HINT}` : "";
694
+ // A screen that never settled established no prompt: nothing to read and answer.
695
+ const enterSent = launchPrompts.answers?.some((a) => a.status === "submitted");
696
+ const advice = neverSettled(launchPrompts.reason)
697
+ ? (enterSent
698
+ ? "OATS sent one Enter to Claude's development-channel confirmation, and the screen then never settled into a session within the 30 s bound; no other key is sent: look at the pane, and if Claude's session is running, it started."
699
+ : "The screen never settled within the 30 s bound, so OATS established no prompt and sent no key: look at the pane, and if Claude's session is running, restart the instance.")
700
+ : "If Claude's development-channel confirmation changed, read the prompt and press Enter yourself, or add its captured wording as a tolerance entry in a reviewed change; never broaden the matcher.";
701
+ return Object.assign(oatsError("E_SPAWN_INCOMPLETE", `${launchPrompts.reason}; home and pane retained: inspect ${home}, then use oats session start --home ${shellWord(home)}. ${advice}${hint}`), {
663
702
  instance, home, launched: "unknown",
664
703
  details: { retained: true, unconfirmed: true, instance, home, launched: "unknown", target, parentLineageCommitted, launchPrompts },
665
704
  });
@@ -679,7 +718,6 @@ function incompleteLaunchPrompt(home, startId, target, reason, previous, expecte
679
718
  return { status: "incomplete", answers: previous?.answers ?? [], reason: audit.ok === true ? reason : "launch prompt audit failed",
680
719
  receipt: [...(previous?.receipt ?? []), { ok: audit.ok === true, ...(audit.row ? { row: audit.row } : {}), results: audit.results ?? [] }] };
681
720
  }
682
- export const LAUNCH_PROMPT_UPDATE_WARNING = "Launch prompt answers are opted in for this home. A harness update can block launch again (blocked: unexpected prompt); refresh qualified fixtures. No fallback key is sent.";
683
721
 
684
722
 
685
723
  /** The launch configurations effective at `dir`: the `launch-configs:` of the
@@ -1671,6 +1709,8 @@ export function lifecycleHookEnv(event, cap, { home, instance, agentName, soulDi
1671
1709
  // Author this from the running kernel, never PATH, ambient env or
1672
1710
  // a caller's extraEnv: those may point at a different executable.
1673
1711
  OATS_CLI_BIN: kernelBin(),
1712
+ // The node a capability writes into anything that outlives its hook (lib/stable-node.mjs).
1713
+ OATS_NODE_BIN: kernelNode().node,
1674
1714
  OATS_SETTINGS: JSON.stringify(cap.settings || {}),
1675
1715
  // Where each leaf of OATS_SETTINGS came from (JSON pointer → { kind, at }; kind is
1676
1716
  // manifest-default | workspace | soul | host | spawn | anchor), so a provider can tell a
@@ -2010,8 +2050,8 @@ function tmuxOatsServer(args, io, options = {}) {
2010
2050
  return (io?.exec || execFileSync)("tmux", ["-u", "-L", OATS_TMUX_SERVER, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...options });
2011
2051
  }
2012
2052
  const tmuxFailure = (e, fallback) => String(e?.stderr ?? e?.message ?? "").trim() || fallback;
2013
- /** An error OATS raised itself (a root guard under an injected exec), never one a tolerant read may absorb. */
2014
- const oatsCoded = (e) => typeof e?.code === "string" && e.code.startsWith("E_");
2053
+ /** A failed call in one line: the first line of its stderr, else how it ended. */
2054
+ const failureLine = (e) => String(e?.stderr ?? "").trim().split("\n")[0] || (Number.isInteger(e?.status) ? `exit ${e.status}` : e?.signal ? `signal ${e.signal}` : String(e?.message || "failed"));
2015
2055
  /** A failed call that ran to its own exit: it has a status, no signal ended it, and Node reports no
2016
2056
  * failure of its own. A timeout and an output overflow carry a code and keep what the call had
2017
2057
  * printed until then, so that text is not the call's answer. Anything else is not a completed call. */
@@ -2027,7 +2067,7 @@ function oatsTmuxSessionSocket(session, io, missingSocket) {
2027
2067
  let listed;
2028
2068
  try { listed = tmuxOatsServer(["list-sessions", "-F", "#{session_name}\t#{socket_path}"], io); }
2029
2069
  catch (e) {
2030
- if (oatsCoded(e)) throw e;
2070
+ if (isKernelCode(e?.code)) throw e;
2031
2071
  // A tmux that could not be run at all is the one failure a person can act on: say so.
2032
2072
  if (e?.code === "ENOENT") throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `could not read the OATS tmux server for session ${session}: tmux was not found through this process's PATH. Run this command with a PATH that holds tmux`);
2033
2073
  if (!exitedByItself(e)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `could not read the OATS tmux server for session ${session}: tmux list-sessions did not exit by itself (${typeof e?.code === "string" ? e.code : e?.signal || "no exit status"})`);
@@ -2256,7 +2296,7 @@ function recordedServerEnvironment(caller, session, io) {
2256
2296
  if (!caller.home) return { read: null, error: refuse(`this process carries an instance's identity (${caller.evidence}) and neither OATS_INSTANCE_HOME nor the working directory names its home`) };
2257
2297
  let target;
2258
2298
  try { target = instanceSessionTarget(caller.home).target; }
2259
- catch (e) { if (!oatsCoded(e)) throw e; return { read: null, error: refuse(`the session receipt of ${basename(caller.home)} could not be used (${e.code})`) }; }
2299
+ catch (e) { if (!isKernelCode(e?.code)) throw e; return { read: null, error: refuse(`the session receipt of ${basename(caller.home)} could not be used (${e.code})`) }; }
2260
2300
  if (!target?.socket) return { read: null, error: refuse(`the home of ${basename(caller.home)} records no tmux server`) };
2261
2301
  // Bytes, not text; and nothing of a failed read (tmux's output, its error) goes into the refusal.
2262
2302
  let read = null;
@@ -2264,7 +2304,7 @@ function recordedServerEnvironment(caller, session, io) {
2264
2304
  try {
2265
2305
  const printed = (io?.exec || execFileSync)("tmux", ["-u", "-S", target.socket, "show-environment", "-g", "-s"], { timeout: 10000, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
2266
2306
  read = parseTmuxShellEnvironment(Buffer.isBuffer(printed) ? printed : Buffer.from(String(printed)), omitted);
2267
- } catch (e) { if (oatsCoded(e)) throw e; }
2307
+ } catch (e) { if (isKernelCode(e?.code)) throw e; }
2268
2308
  if (read === null) return { read, error: refuse(`the environment of the tmux server that ${basename(caller.home)} is recorded on (${target.socket}) could not be read`) };
2269
2309
  // A variable the reader left out is never filled in from this process, and a server is never
2270
2310
  // started when the one left out decides which configuration it loads or which programs it runs.
@@ -2328,7 +2368,7 @@ function panePath(socket, session, io, cwd) {
2328
2368
  try {
2329
2369
  const printed = (io?.exec || execFileSync)("tmux", ["-u", "-S", socket, "show-environment", ...scope, "-s"], { timeout: 10000, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
2330
2370
  env = parseTmuxShellEnvironment(Buffer.isBuffer(printed) ? printed : Buffer.from(String(printed)), omitted, cleared);
2331
- } catch (e) { if (oatsCoded(e)) throw e; }
2371
+ } catch (e) { if (isKernelCode(e?.code)) throw e; }
2332
2372
  return { env, omitted, cleared };
2333
2373
  };
2334
2374
  const decide = ({ env, omitted, cleared }, source, unset) => {
@@ -2384,8 +2424,12 @@ function launchLookup(configEnv, env, pane, configName, cwd) {
2384
2424
  * its own PATH names no tmux to create it with (creatorTmux). `missingSocket` is a session start's
2385
2425
  * check of its home when the server's socket file is missing (oatsTmuxSessionSocket): with a reason,
2386
2426
  * E_SESSION_UNKNOWN and no server is created at that path.
2427
+ * A creator inside a systemd service on Linux starts the server in a scope of its own
2428
+ * (lib/tmux-server-scope.mjs, awebai/oats#915): the same tmux argv and environment, run by the
2429
+ * system's `systemd-run --user --scope`. When that cannot be done, the server starts as before and
2430
+ * `warnings` (the caller's answer's) says it lives inside that service.
2387
2431
  */
2388
- export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket) {
2432
+ export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket, warnings) {
2389
2433
  let { server: socket, present } = oatsTmuxSessionSocket(session, io, missingSocket);
2390
2434
  if (!present) {
2391
2435
  // The executable is chosen here, where the creation is about to run, and nowhere earlier: a
@@ -2395,10 +2439,38 @@ export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket) {
2395
2439
  // this call starts gets what a server start gets.
2396
2440
  const env = plan?.env && (plan.startsServer || socket) ? plan.env : oatsSessionEnvironment(session, io, { startsServer: !socket });
2397
2441
  const address = socket ? ["-S", socket] : ["-L", OATS_TMUX_SERVER];
2442
+ const args = ["-u", ...address, "new-session", "-d", "-s", session, "-n", "hq", "-c", hq, "-P", "-F", "#{socket_path}\t#{window_id}"];
2443
+ const options = { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], env };
2444
+ const run = (file, argv) => (io?.exec || execFileSync)(file, argv, options).trim();
2445
+ // Inside a service: the scope to start in, or the warning a start by this process carries.
2446
+ const scope = serverScopePlan(creatorPlacement(io));
2447
+ let wrapper = null, unscoped = scope.warn ? serverScopeWarning(scope.warn) : null;
2448
+ if (scope.wrap) {
2449
+ // The scope's own INVOCATION_ID, which systemd-run exports to what it runs, is removed by the
2450
+ // system's env, so the server starts with `env` less any INVOCATION_ID: without both tools, no scope.
2451
+ const where = io?.systemToolDirs ? { dirs: io.systemToolDirs } : {};
2452
+ const systemdRun = systemTool("systemd-run", where), clean = systemTool("env", where);
2453
+ if (systemdRun.file && clean.file) wrapper = [systemdRun.file, ["--user", "--scope", "--collect", "--quiet", "--unit", serverScopeUnit({ socket, env }), "--", clean.file, "-u", "INVOCATION_ID"]];
2454
+ else unscoped = serverScopeWarning({ unit: scope.unit, reason: systemdRun.reason ?? clean.reason });
2455
+ }
2456
+ /** Started by this process outside a scope: said once it has started. */
2457
+ const plain = () => { const out = run(tmux, args); if (unscoped) warnings?.push(unscoped); return out; };
2398
2458
  let created;
2399
- try { created = (io?.exec || execFileSync)(tmux, ["-u", ...address, "new-session", "-d", "-s", session, "-n", "hq", "-c", hq, "-P", "-F", "#{socket_path}\t#{window_id}"], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], env }).trim(); }
2459
+ try {
2460
+ if (!wrapper) created = plain();
2461
+ else {
2462
+ try { created = run(wrapper[0], [...wrapper[1], tmux, ...args]); }
2463
+ catch (e) {
2464
+ if (isKernelCode(e?.code)) throw e;
2465
+ // Another creator's server (its scope already exists) answers: started, by it.
2466
+ const again = oatsTmuxSessionSocket(session, io, missingSocket);
2467
+ if (again.present) socket = again.server;
2468
+ else { unscoped = serverScopeWarning({ unit: scope.unit, reason: failureLine(e) }); created = plain(); }
2469
+ }
2470
+ }
2471
+ }
2400
2472
  catch (e) {
2401
- if (oatsCoded(e)) throw e;
2473
+ if (isKernelCode(e?.code)) throw e;
2402
2474
  const again = oatsTmuxSessionSocket(session, io, missingSocket);
2403
2475
  if (!again.present) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `could not create tmux session ${session} on the OATS tmux server: ${tmuxFailure(e, "tmux new-session failed")}`);
2404
2476
  socket = again.server;
@@ -2431,7 +2503,7 @@ const paneCommand = (command) => `unset COLORFGBG; ${command}; exec "\${SHELL:-/
2431
2503
  function sizeWindow(socket, windowId, io) {
2432
2504
  if (!/^@\d+$/.test(windowId || "")) return;
2433
2505
  for (const [option, value] of OATS_WINDOW_SIZING) {
2434
- try { tmuxOn(socket, ["set-option", "-w", "-t", windowId, option, value], io); } catch (e) { if (oatsCoded(e)) throw e; }
2506
+ try { tmuxOn(socket, ["set-option", "-w", "-t", windowId, option, value], io); } catch (e) { if (isKernelCode(e?.code)) throw e; }
2435
2507
  }
2436
2508
  }
2437
2509
  /** The agent window OATS just created, by the id new-window returned: showing the viewer's colours and
@@ -2669,6 +2741,57 @@ export function upgradeHomeMeta(meta, home) {
2669
2741
  const { runtime, ...rest } = meta;
2670
2742
  return { ...rest, ...(runtime !== undefined || meta.harness !== undefined ? { harness: meta.harness ?? runtime } : {}), ...(meta.launch !== undefined ? { launch: upgradeLaunchRecipe(meta.launch) } : {}) };
2671
2743
  }
2744
+ /** A home's record (`<home>/instance.json`) as it is on disk. Total: it never throws, so that one
2745
+ * home's record decides only for that home (awebai/oats#896). One of:
2746
+ * - `{ state: "record", path, meta }`: the JSON object the file holds, as written (a reader of
2747
+ * the home's harness passes it through upgradeHomeMeta);
2748
+ * - `{ state: "absent", path }`: no entry of that name, or a home this process cannot look into,
2749
+ * where whether there is one cannot be told (answered as a home without a record, as before);
2750
+ * - `{ state: "unreadable", path, reason }`: an entry is there and gives no JSON object: cut off,
2751
+ * empty, kept from this user, a directory, a link to nothing, or JSON that is not an object.
2752
+ * `reason` is the system's or the parser's, in words, without the path.
2753
+ * An unreadable record is never an absent one: the home may be a whole instance with work, and
2754
+ * "cannot read" is not "is not there". */
2755
+ export function readHomeRecord(home) {
2756
+ const path = join(home, "instance.json");
2757
+ const unreadable = (reason) => ({ state: "unreadable", path, reason });
2758
+ let text;
2759
+ try {
2760
+ // Only a regular file is read: a read of a directory fails, and one of a pipe would not return.
2761
+ const entry = statSync(path);
2762
+ if (!entry.isFile()) return unreadable(entry.isDirectory() ? "it is a directory" : "it is not a regular file");
2763
+ text = readFileSync(path, "utf8");
2764
+ } catch (e) {
2765
+ let entry;
2766
+ try { entry = lstatSync(path); } catch { return { state: "absent", path }; }
2767
+ if (entry.isSymbolicLink() && e?.code === "ENOENT") return unreadable("it is a symbolic link to nothing");
2768
+ // The system's words without the path, which the answer already names: `EACCES: permission denied`.
2769
+ return unreadable(String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, ""));
2770
+ }
2771
+ let value;
2772
+ try { value = JSON.parse(text); } catch (e) { return unreadable(String(e?.message ?? e)); }
2773
+ if (!isPlainObject(value)) return unreadable(`it holds ${value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`}, not a JSON object`);
2774
+ return { state: "record", path, meta: value };
2775
+ }
2776
+ /** What an answer says of a record that cannot be read (readHomeRecord): the file and the reason. */
2777
+ const unreadableRecordSaid = (record) => `${record.path} cannot be read (${record.reason})`;
2778
+ /** The refusal of a lifecycle verb (retire, stop, session start) for a home whose record is there
2779
+ * and cannot be read: E_UNIDENTIFIED_INSTANCE_HOME, with the file, the reason, `nothing` (what the
2780
+ * verb had done by then: nothing; a spawn that names the home says "nothing was spawned") and the
2781
+ * one remedy that exists. Every caller raises it before any effect: a client reads this code from
2782
+ * a stop or a retire as "refused, nothing happened". `--force` does not apply to it: it removes a
2783
+ * home that has NO record, never, blind, one whose record cannot be read. */
2784
+ function unreadableRecordRefusal(record, nothing = "nothing was done") {
2785
+ return oatsError("E_UNIDENTIFIED_INSTANCE_HOME", `${unreadableRecordSaid(record)}; ${nothing}. Restoring the file from a copy makes the home usable again; removing such a home through OATS is not possible yet.`);
2786
+ }
2787
+ /** The one check a lifecycle verb makes when it has resolved its home, before it takes a claim or
2788
+ * reads anything of the home: a record that cannot be read refuses the verb (unreadableRecordRefusal).
2789
+ * → the record as read (readHomeRecord), a record or an absent one. */
2790
+ export function identifiedHomeRecord(home, nothing) {
2791
+ const record = readHomeRecord(home);
2792
+ if (record.state === "unreadable") throw unreadableRecordRefusal(record, nothing);
2793
+ return record;
2794
+ }
2672
2795
  const LAUNCH_PROMPT = { kind: "task-file", file: "TASK.md" };
2673
2796
  /** The fixed prompt a codex launch starts with: it names the task file, never its text (argv is
2674
2797
  * readable by every local user). Codex reads the file with a tool. */
@@ -2794,8 +2917,13 @@ export function harnessDefaultConfig(launchConfigs, harness) {
2794
2917
  return found ? { ...found, harnessDefault: true } : null;
2795
2918
  }
2796
2919
  /** A home's launch layers now (feature launch-preference; --reselect-launch and inspect's launchCurrent): its
2797
- * RECORDED soul's launch (the soul copy it runs) and its deployment's oats-local.yaml souls.launch. */
2798
- export function homeLaunchLayers(realHome, meta) {
2920
+ * RECORDED soul's launch (the soul copy it runs) and its deployment's oats-local.yaml souls.launch.
2921
+ * `offered` is the description of a read of the workspace (lib/instance-resolution.mjs soulsOffered),
2922
+ * which the layers need to say which keys of souls.launch name no soul: only when the home's soul has
2923
+ * no entry of its own and souls.launch holds a key besides "*" (`needsOffered` on the answer says so
2924
+ * when none was given). A start that selects again makes that read (startInstanceSession); inspect's
2925
+ * launchCurrent and readiness make none, and report the layers as they are. */
2926
+ export function homeLaunchLayers(realHome, meta, { offered = null } = {}) {
2799
2927
  const deployment = dirname(dirname(dirname(dirname(realHome))));
2800
2928
  const found = loadLocal(deployment);
2801
2929
  if (!found.path || resolve(dirname(found.path)) !== resolve(deployment)) throw oatsError("E_LOCAL_MISSING", `${deployment} has no oats-local.yaml: --reselect-launch reads its souls.launch`);
@@ -2804,36 +2932,51 @@ export function homeLaunchLayers(realHome, meta) {
2804
2932
  const file = soulDir ? join(soulDir, "soul.yaml") : null;
2805
2933
  const definition = file && existsSync(file) ? withConfigFile(file, () => parseYamlNested(readFileSync(file, "utf8"))) : null;
2806
2934
  const key = soul.package && typeof soul.qualifiedName === "string" ? soul.qualifiedName : meta.agent;
2807
- return launchLayers({ definition, entry: { repoKey: soul.repoKey ?? null, path: typeof soul.path === "string" ? soul.path : null, package: soul.package?.id ?? null }, key, local: found.local });
2935
+ const entries = isPlainObject(found.local?.souls?.launch) ? found.local.souls.launch : {};
2936
+ const needsOffered = !offered && !Object.hasOwn(entries, key) && Object.keys(entries).some((k) => k !== "*");
2937
+ return { ...launchLayers({ definition, entry: { repoKey: soul.repoKey ?? null, path: typeof soul.path === "string" ? soul.path : null, package: soul.package?.id ?? null }, key, local: found.local, offered }), needsOffered };
2808
2938
  }
2809
2939
  /** A NEW launch selection (a spawn, or a start/restart that reselects) from the flags and the launch
2810
2940
  * layers (lib/launch-preference.mjs). → { launchSelection (resolveLaunchSelection's), launchChoice:
2811
- * { from, at, declared } }. A configuration a layer names but the host lacks is E_LAUNCH_CONFIG_UNKNOWN
2812
- * naming the layer. Never reads a frozen recipe. */
2813
- export function selectNewLaunch({ launchConfigs = {}, agent, flags = {}, layers = null }) {
2941
+ * { from, at, declared } }. A selection the fall-through would decide while souls.launch holds a key that
2942
+ * names no soul is E_LAUNCH_PREFERENCE_UNMATCHED, before every other refusal here (for every new
2943
+ * selection: a spawn, and a start that reselects). A configuration a layer names but the host lacks is
2944
+ * E_LAUNCH_CONFIG_UNKNOWN naming the layer. `refuseAmbiguous` (a spawn) refuses a launch that names no
2945
+ * configuration among several with no default (E_LAUNCH_CONFIG_AMBIGUOUS). Never reads a frozen recipe. */
2946
+ export function selectNewLaunch({ launchConfigs = {}, agent, flags = {}, layers = null, refuseAmbiguous = false }) {
2814
2947
  const choice = selectionFrom({ flags, layers });
2948
+ const unmatched = launchPreferenceUnmatched({ choice, layers });
2949
+ if (unmatched) throw unmatched;
2815
2950
  const named = choice.from !== "flag" && choice.selection.launchConfig !== undefined && choice.selection.launchConfig !== "none" ? choice.selection.launchConfig : null;
2816
2951
  if (named !== null && !Object.hasOwn(launchConfigs, named)) throw launchConfigUnknown({ name: named, from: choice.from, at: choice.at });
2817
2952
  const launchSelection = resolveLaunchSelection({ launchConfigs, agent: layers ? {} : agent, selection: choice.selection, preference: choice.preference });
2953
+ const ambiguous = refuseAmbiguous ? launchConfigAmbiguous({ launchConfigs, harness: launchSelection.harness, config: launchSelection.config, choice }) : null;
2954
+ if (ambiguous) throw ambiguous;
2818
2955
  return { launchSelection, launchChoice: { from: choice.from, at: choice.at, declared: layers?.declared ?? null } };
2819
2956
  }
2820
2957
  /** The `Launch` report (feature launch-preference) a spawn with no flags would decide HERE, for listings
2821
2958
  * (`oats souls`, `inspect --soul`): the same layers as selectNewLaunch, but no model catalogue is probed
2822
2959
  * (`model` is the configured id) and a spawn's refusal becomes `problem` {code, message, fix}. `contextDir`
2823
- * is the deployment (where a harness executable resolves). */
2960
+ * is the deployment (where a harness executable resolves). A key of souls.launch that names no soul
2961
+ * (E_LAUNCH_PREFERENCE_UNMATCHED) is the problem before any other, as in a spawn; `effective` stays the
2962
+ * launch the fall-through would have given. */
2824
2963
  export function launchReportFor({ layers, launchConfigs = {}, contextDir }) {
2825
2964
  const choice = selectionFrom({ layers });
2826
- const report = (harness, model, launchConfig, problem = null) => launchReport({ declared: layers?.declared ?? null, harness, model, launchConfig, from: choice.from, at: choice.at, problem });
2965
+ const unmatched = launchPreferenceUnmatchedProblem({ choice, layers });
2966
+ const report = (harness, model, launchConfig, problem = null) => launchReport({ declared: layers?.declared ?? null, harness, model, launchConfig, from: choice.from, at: choice.at,
2967
+ problem: unmatched ?? problem });
2827
2968
  let harness = "pi", model = null, config = null;
2828
2969
  if (choice.selection.launchConfig !== undefined && choice.selection.launchConfig !== "none") {
2829
2970
  // An unknown configuration launches nothing (`problem`); `effective` stays a real launch — the host
2830
2971
  // default — so a reader's closed decoder never meets a null harness.
2831
2972
  const name = choice.selection.launchConfig;
2832
- if (!Object.hasOwn(launchConfigs, name)) { const e = launchConfigUnknown({ name, from: choice.from, at: choice.at }); return report("pi", null, null, { code: e.code, message: e.message, fix: `declare launch configuration ${name} (oats launch-config set), or change oats-local.yaml souls.launch` }); }
2973
+ if (!Object.hasOwn(launchConfigs, name)) { const e = launchConfigUnknown({ name, from: choice.from, at: choice.at }); return report("pi", null, null, { code: e.code, message: e.message, fix: launchConfigUnknownFix(name, choice.from) }); }
2833
2974
  config = launchConfigs[name]; harness = config.harness; model = typeof config.model === "string" && config.model ? config.model : null;
2834
2975
  } else if (choice.preference) { harness = choice.preference.harness; model = choice.preference.model ?? null; }
2835
2976
  // As a spawn: a layer naming "none" asks for the bare harness; otherwise no configuration is the harness default.
2836
2977
  if (!config && !(choice.selection.launchConfig === "none" && !choice.preference)) { config = harnessDefaultConfig(launchConfigs, harness); if (config && !model) model = typeof config.model === "string" && config.model ? config.model : null; }
2978
+ const ambiguous = launchConfigAmbiguous({ launchConfigs, harness, config, choice });
2979
+ if (ambiguous) return report(harness, model, null, { code: ambiguous.code, message: ambiguous.message, fix: ambiguous.details.fix });
2837
2980
  let exe;
2838
2981
  try { exe = resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir }); }
2839
2982
  catch (e) { if (e?.code !== "E_CLAUDE_CONFIG_REMOVED") throw e; return report(harness, model, config?.name, { code: e.code, message: e.message, fix: `declare a claude default launch configuration (oats launch-config set), then delete ${e.details.file}` }); }
@@ -2919,17 +3062,21 @@ function deploymentOfHome(home, meta) {
2919
3062
  if (dirname(d) === d) return realPathOrNearest(dirname(dirname(dirname(dirname(resolve(home))))));
2920
3063
  }
2921
3064
  }
2922
- /** Folder trust for a launch in `home` (lib/harness-trust.mjs, read-only): `trustHome` — the
2923
- * codex launch trusts the home, because the operator trusts its deployment root or an
2924
- * ancestor — and the warning when the session will stop at its harness's folder-trust prompt. */
2925
- export function launchFolderTrust({ harness, home, meta, yolo, env = process.env }) {
3065
+ /** Folder trust for a launch in `home` (lib/harness-trust.mjs, read-only), read from the file the
3066
+ * launch's own env selects (the host `env` and the launch configuration's `configEnv`): `trustHome`
3067
+ * — the codex launch trusts the home, because that file trusts its deployment root or an ancestor
3068
+ * — `covered`, the `file` read (or the `problem` that keeps it unresolved) and the warning when
3069
+ * folder trust is not established there. */
3070
+ export function launchFolderTrust({ harness, home, meta, yolo, env = process.env, configEnv = {}, launchConfig = null }) {
3071
+ if (harness !== "codex" && harness !== "claude") return { trustHome: false, covered: false, file: null, warning: null };
2926
3072
  const root = deploymentOfHome(home, meta);
2927
- if (harness === "codex") {
2928
- const trustHome = codexTrustsRoot(root, { env });
2929
- return { trustHome, warning: harnessTrustWarning({ harness, root, covered: trustHome || yolo === true }) };
2930
- }
2931
- if (harness === "claude") return { trustHome: false, warning: harnessTrustWarning({ harness, root, covered: claudeTrusts(home, { env }) }) };
2932
- return { trustHome: false, warning: null };
3073
+ const unresolved = launchConfigDir(harness, configEnv, env)?.problem;
3074
+ const launchEnv = launchEffectiveEnv({ base: env, configEnv });
3075
+ const file = unresolved ? null : harnessConfigFile(harness, launchEnv);
3076
+ const problem = unresolved && `launch configuration ${launchConfig || "(recorded)"}: ${unresolved}`;
3077
+ const trustHome = !unresolved && harness === "codex" && codexTrustsRoot(root, { env: launchEnv });
3078
+ const covered = harness === "codex" ? trustHome || yolo === true : !unresolved && claudeTrusts(home, { env: launchEnv });
3079
+ return { trustHome, covered, file, ...(problem ? { problem } : {}), warning: harnessTrustWarning({ harness, root, file, problem, covered }) };
2933
3080
  }
2934
3081
 
2935
3082
  /** The harness command line of a recipe. With no configuration the bytes
@@ -3150,11 +3297,12 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3150
3297
  ...(frozen?.legacy ? { legacy: { ...frozen.legacy, ...(hooks.refreshed?.length ? { replacedBy: hooks.refreshed } : {}) } } : {}),
3151
3298
  };
3152
3299
  const inst = instance || meta?.instance || basename(home);
3153
- const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, env });
3300
+ const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, env, configEnv, launchConfig: config?.name });
3154
3301
  const command = renderLaunchRecipe(recipe, { home, instance: inst, trustHome });
3155
3302
  const selectionSource = frozen ? (config?.frozen || (!config && !selection.launchConfig && !selection.harness) ? "frozen" : "config") : "config";
3156
- const launchPromptAnswers = preview ? launchPromptPolicyAt(dirname(dirname(dirname(dirname(home)))), home) : null;
3157
- return { ...(preview ? { launchPromptAnswers } : {}), recipe, command, trustHome, harness, model: model || undefined, modelSource, yolo, config, executable, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: [...(hooks.warnings || []), ...(launchPromptAnswers && promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : [])], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}) };
3303
+ // A preview states what the start will do; the start states it in its own output.
3304
+ const previewNotices = preview ? launchStartNotices(dirname(dirname(dirname(dirname(home)))), harness, command) : [];
3305
+ return { recipe, command, trustHome, harness, model: model || undefined, modelSource, yolo, config, executable, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: [...(hooks.warnings || []), ...previewNotices], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}) };
3158
3306
  }
3159
3307
  /** The environment a planned launch runs under: the host's base, the
3160
3308
  * capabilities' validated env, the configuration's literals and its
@@ -3270,7 +3418,7 @@ function* spawnBody(root, agent, o = {}) {
3270
3418
  // Feature launch-preference: the flags, else the machine's souls.launch, else the soul's own launch,
3271
3419
  // else the host default — `launchChoice` says which layer decided (instance.json launchFrom/launchAt).
3272
3420
  let launchSelection, launchChoice;
3273
- try { ({ launchSelection, launchChoice } = selectNewLaunch({ launchConfigs: launchConfigsAt(root), agent, flags: { launchConfig: o.launchConfig, harness: o.harness, model: o.model }, layers: o.prepared.launch })); }
3421
+ try { ({ launchSelection, launchChoice } = selectNewLaunch({ launchConfigs: launchConfigsAt(root), agent, flags: { launchConfig: o.launchConfig, harness: o.harness, model: o.model }, layers: o.prepared.launch, refuseAmbiguous: true })); }
3274
3422
  catch (e) { previewPreflightBudget = null; throw e; }
3275
3423
  const launchConfig = launchSelection.config;
3276
3424
  const harness = launchSelection.harness;
@@ -3498,6 +3646,9 @@ function* spawnBody(root, agent, o = {}) {
3498
3646
  }
3499
3647
  }
3500
3648
  }
3649
+ // The anchor's record gives the lineage, and a parent's its child-spawn policy: one that is there
3650
+ // and cannot be read refuses the spawn, which would otherwise guess either (#896).
3651
+ if (anchorHome) identifiedHomeRecord(anchorHome, "nothing was spawned");
3501
3652
  const anchorMetaPath = anchorHome ? join(anchorHome, "instance.json") : undefined;
3502
3653
  const anchorOriginal = anchorMetaPath && existsSync(anchorMetaPath) ? readFileSync(anchorMetaPath, "utf8") : null;
3503
3654
  const anchorMeta = anchorOriginal === null ? undefined : JSON.parse(anchorOriginal);
@@ -3532,7 +3683,8 @@ function* spawnBody(root, agent, o = {}) {
3532
3683
  if (parentInstance && parentInstance !== instance) {
3533
3684
  const parentHome = parentInstance === relativeTo && anchorHome ? anchorHome
3534
3685
  : findInstanceHome(root, parentInstance)?.home;
3535
- const parentMeta = parentHome && existsSync(join(parentHome, "instance.json")) ? JSON.parse(readFileSync(join(parentHome, "instance.json"), "utf8")) : anchorMeta;
3686
+ const parentRecord = parentHome ? identifiedHomeRecord(parentHome, "nothing was spawned") : undefined;
3687
+ const parentMeta = parentRecord?.state === "record" ? parentRecord.meta : anchorMeta;
3536
3688
  const policy = childPolicyOf(parentMeta);
3537
3689
  if (policy.allowed === false) {
3538
3690
  // A preview touches nothing — not even the parent's event log; the
@@ -3699,7 +3851,7 @@ function* spawnBody(root, agent, o = {}) {
3699
3851
  d.revision = createHash("sha256").update(canonicalJson(d)).digest("hex").slice(0, 24);
3700
3852
  return d;
3701
3853
  };
3702
- const launchPromptAnswers = launchPromptPolicyAt(o.prepared.deployment || workspaceOf(root), home);
3854
+ const launchPromptNotice = launchPromptAnswersNotice(o.prepared.deployment || workspaceOf(root));
3703
3855
  if (o.preview === true) {
3704
3856
  const decision = buildDecision();
3705
3857
  // Workspace model (M3): the preview reports what APPLY will produce — every
@@ -3717,14 +3869,15 @@ function* spawnBody(root, agent, o = {}) {
3717
3869
  // Addendum 5: where each leaf of `settings.<cap>` came from (JSON pointer → { kind, at }):
3718
3870
  // manifest-default | workspace | soul | host | spawn, the last layer that set it.
3719
3871
  const preparedSettingsOrigins = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloadOrigins?.[m.name] ?? {})]));
3720
- // The preview's warnings are strings: the launch-prompt notice, then what a module declares and this kernel ignores.
3721
- const previewWarnings = [...(promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution))];
3872
+ // The preview's warnings are strings: the launchPromptAnswers notice, then what a module declares and this kernel ignores.
3873
+ // The development-channel statement is the apply's: no launch hook runs here, so the argv is unknown.
3874
+ const previewWarnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution))];
3722
3875
  const preparedSettings = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloads?.[m.name] && typeof o.prepared.resolution.payloads[m.name] === "object" ? o.prepared.resolution.payloads[m.name] : {})]));
3723
3876
  return deliver({
3724
3877
  // Team model v2: the soul's teams here (unmapped rows included) and its default — the choice a
3725
3878
  // Desktop offers before anything is minted; joining any but the default is the provider's explicit act.
3726
3879
  ...{ modules: o.prepared.preview ?? null, teams: structuredClone(o.prepared.resolution.teams ?? []), defaultTeam: structuredClone(o.prepared.resolution.defaultTeam ?? null), resolution: o.prepared.resolution.revision, declRevision: o.prepared.resolution.declRevision ?? null, payloadRevision: o.prepared.resolution.payloadRevision ?? null, workspace: o.prepared.discovery?.key ?? null, standalone: o.prepared.discovery?.standalone === true, providers: preparedProviders, settings: preparedSettings, settingsOrigins: preparedSettingsOrigins },
3727
- spawnPreviewApi: 2, preview: true, launchPromptAnswers, ...(previewWarnings.length ? { warnings: previewWarnings } : {}), agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
3880
+ spawnPreviewApi: 2, preview: true, ...(previewWarnings.length ? { warnings: previewWarnings } : {}), agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
3728
3881
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
3729
3882
  decision, preflight,
3730
3883
  backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
@@ -4047,7 +4200,7 @@ function* spawnBody(root, agent, o = {}) {
4047
4200
  }
4048
4201
 
4049
4202
  // What the composed modules declare and this kernel ignores (an unknown hook event), as the preview said.
4050
- const warnings = [...(promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared?.resolution))];
4203
+ const warnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared?.resolution))];
4051
4204
 
4052
4205
  // Establish directory ownership while these are still the kernel's own roots.
4053
4206
  // A hook may replace either path; it must never mint authority for that target.
@@ -4077,6 +4230,7 @@ function* spawnBody(root, agent, o = {}) {
4077
4230
  extraEnv: { OATS_TASK: task, OATS_REPO: repoAbs, OATS_BRANCH: branch || "", OATS_WORK: work, OATS_HARNESS: harness, OATS_RUNTIME: harness, OATS_KIND: agent.kind || "persistent", ...(triggerEventFile ? { OATS_TRIGGER_EVENT_FILE: triggerEventFile } : {}) },
4078
4231
  });
4079
4232
  warnings.push(...hookRes.warnings);
4233
+ if (kernelNode().warning) warnings.push(kernelNode().warning);
4080
4234
  // Which capability hooks RAN (in order) and how each ended — recorded on the
4081
4235
  // `spawned` event below: the instance's event log is the auditable fact that
4082
4236
  // a capability configured itself, independent of whatever the hook printed.
@@ -4381,7 +4535,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4381
4535
  prompt: LAUNCH_PROMPT, kernelBin: shimTarget,
4382
4536
  };
4383
4537
  if (triggerEventFile) recipe.env.OATS_TRIGGER_EVENT_FILE = triggerEventFile;
4384
- const folderTrust = launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo });
4538
+ const folderTrust = launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo, configEnv: launchConfig?.env, launchConfig: launchConfig?.name });
4385
4539
  if (folderTrust.warning) warnings.push(folderTrust.warning);
4386
4540
  let cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
4387
4541
 
@@ -4488,7 +4642,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4488
4642
  if (launch) {
4489
4643
  // The session on the OATS server, then everything on the one socket that answered: the collision
4490
4644
  // check, the records, the window and (in compensateSpawn) its removal.
4491
- const socket = ensureOatsTmuxSession(session, existsSync(root) ? root : workspaceOf(root), undefined, tmuxSessionPlan);
4645
+ const socket = ensureOatsTmuxSession(session, existsSync(root) ? root : workspaceOf(root), undefined, tmuxSessionPlan, undefined, spawnWarnings);
4492
4646
  // The harness looked up again on the PATH this window's pane will actually start with, whoever
4493
4647
  // created the session and with whatever environment (a race lost to another creator, a session
4494
4648
  // that overrides PATH). Not there: refused, and the spawn is compensated. Found elsewhere than
@@ -4510,6 +4664,10 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4510
4664
  if (present.includes(instance)) throw new Error(`tmux window "${instance}" already exists in session ${session}`);
4511
4665
  meta.tmux.socket = socket;
4512
4666
  meta.launched = true;
4667
+ promptStartId = randomUUID();
4668
+ const engaged = devChannelEngaged(harness, cmdline);
4669
+ if (engaged) warnings.push(DEV_CHANNEL_STATEMENT);
4670
+ else meta.launchPrompts = notEngaged(promptStartId);
4513
4671
  // Commit the final child metadata and its independent byte authority before
4514
4672
  // the managed harness can write. No child-home transition follows launch.
4515
4673
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n");
@@ -4520,13 +4678,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4520
4678
  const windowCmd = paneCommand(executionCommand);
4521
4679
  const paneEnvFlags = launchEnvRefs(recipe, process.env).flatMap((r) => ["-e", `${r.name}=${r.value}`]);
4522
4680
  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`);
4523
- const policy = launchPromptPolicyAt(o.prepared.deployment || workspaceOf(root), home);
4524
- // Only a consented prompt launch needs lineage committed before dispatch:
4525
- // its uncertain input outcome retains the new process and parent link.
4526
- // Ordinary launches keep their established post-launch commit/rollback.
4527
- if (promptOptedIn(policy)) commitParentLineage();
4528
- promptStartId = randomUUID();
4529
- const controller = promptOptedIn(policy) ? promptController(home, promptStartId, harness, policy, cmdline, undefined, createdHomeIdentity) : null;
4681
+ // Only a launch that engages the confirmation needs lineage committed before
4682
+ // dispatch: its uncertain input outcome retains the new process and parent
4683
+ // link. Other launches keep their established post-launch commit/rollback.
4684
+ if (engaged) commitParentLineage();
4685
+ const controller = engaged ? promptController(home, promptStartId, cmdline, undefined, createdHomeIdentity) : null;
4530
4686
  windowMayExist = true;
4531
4687
  promptDispatched = !!controller;
4532
4688
  let windowId;
@@ -4538,10 +4694,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4538
4694
  catch (e) { throw launchFailed("set-option", "the new window's options were refused", e); }
4539
4695
  if (controller) {
4540
4696
  promptResult = controller.observeNew(promptTarget);
4541
- meta.launchPrompts = promptResult;
4697
+ if (promptResult.status === "flag-ignored") warnings.splice(0, warnings.length, ...flagIgnoredWarnings(warnings));
4698
+ meta.launchPrompts = promptResult.status === "flag-ignored" ? channelsUnavailable(promptStartId, promptResult) : promptResult;
4542
4699
  meta.launchPromptTarget = promptTarget;
4543
4700
  meta.parentLineageCommitted = parentLineageCommitted;
4544
- meta.launched = promptResult.status === "completed";
4701
+ meta.launched = promptLaunched(promptResult.status);
4545
4702
  assertLaunchHome(home, createdHomeIdentity);
4546
4703
  writeJsonAtomic(join(home, "instance.json"), meta);
4547
4704
  if (!meta.launched) throw retainedPromptError(home, instance, promptTarget, parentLineageCommitted, promptResult);
@@ -4553,8 +4710,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4553
4710
  clearSpawnInProgressMarker();
4554
4711
  }
4555
4712
 
4556
- // Ordinary launches and scaffolds commit here; opted-in launches already
4557
- // committed before dispatch so retained prompt failures keep their lineage.
4713
+ // Ordinary launches and scaffolds commit here; launches that engage the
4714
+ // development-channel confirmation already committed before dispatch, so
4715
+ // retained prompt failures keep their lineage.
4558
4716
  commitParentLineage();
4559
4717
 
4560
4718
  appendEvent(home, { kind: "spawned", data: { agent: agent.name, work, branch: branch ?? null, harness, model: model || null, parentInstance: meta.parentInstance ?? null, relation: relation ?? null, launched: launch, hooks: hookReceipt(hookRes), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}) } });
@@ -4567,7 +4725,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4567
4725
  return deliver({ ...meta, ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: launch ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(session)}` : `oats session attach --home ${shellWord(home)}`, warnings: spawnWarnings.length ? spawnWarnings : undefined });
4568
4726
  } catch (error) {
4569
4727
  if (promptDispatched) {
4570
- // Once opted-in launch dispatch occurred, uncertainty retains all effects.
4728
+ // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
4571
4729
  // The independent baseline remains launched:true: metadata is not proof of quiescence.
4572
4730
  let result = promptResult?.status === "blocked" || promptResult?.status === "incomplete" ? promptResult : incompleteLaunchPrompt(home, promptStartId, promptTarget ?? spawnTmux, "launch prompt dispatch or recording incomplete", promptResult, createdHomeIdentity);
4573
4731
  try {
@@ -4686,11 +4844,11 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
4686
4844
  return (existsSync(instancesDir) ? readdirSync(instancesDir, { withFileTypes: true }) : [])
4687
4845
  .filter((e) => e.isDirectory() && !e.name.startsWith("."))
4688
4846
  .map((e) => {
4689
- const metaPath = join(instancesDir, e.name, "instance.json");
4690
4847
  const home = join(instancesDir, e.name);
4691
- const meta = existsSync(metaPath)
4692
- ? upgradeHomeMeta(JSON.parse(readFileSync(metaPath, "utf8")), home)
4693
- : { instance: e.name, home };
4848
+ // The record decides for this home only: one that is there and cannot be read gives the
4849
+ // row of a home without a record, whose liveness says why (below), never a failed listing.
4850
+ const record = readHomeRecord(home);
4851
+ const meta = record.state === "record" ? upgradeHomeMeta(record.meta, home) : { instance: e.name, home };
4694
4852
  // A home retained by an incomplete rollback is NOT a live instance: it
4695
4853
  // is preserved state awaiting cleanup, and must read that way.
4696
4854
  const fallback = directoryRollbackPath(home);
@@ -4717,7 +4875,9 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
4717
4875
  catch { retirePending = { reason: "retire pending" }; }
4718
4876
  }
4719
4877
  // A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
4720
- const liveness = recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(home)))
4878
+ // A home whose record cannot be read is listed, never observed: where its session is, is in the record.
4879
+ const liveness = record.state === "unreadable" ? { running: null, runtimeState: "unreachable", runtimeError: `E_UNIDENTIFIED_INSTANCE_HOME: ${unreadableRecordSaid(record)}` }
4880
+ : recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(home)))
4721
4881
  ? { running: null, runtimeState: "unsupported", runtimeError: `E_HERDR_REMOVED: ${herdrInstanceRemoved(e.name).message}` }
4722
4882
  : tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name, scanOf(home),
4723
4883
  // A home that records no socket and no launch (--no-launch) reads the default server only
@@ -4895,6 +5055,40 @@ function assertDirectoryHome(home, canonicalHome = realPathOrNearest(home)) {
4895
5055
  }
4896
5056
  }
4897
5057
 
5058
+ /** A directory of the home (instanceWork) is still the real directory the retire read it as: a
5059
+ * retire hook, or anything else, may have exchanged it since. */
5060
+ function assertHomeDirectory(work) {
5061
+ let st;
5062
+ try { st = lstatSync(work); } catch { /* fail closed below */ }
5063
+ if (!st?.isDirectory() || st.isSymbolicLink()) {
5064
+ throw oatsError("E_WORK_INSPECTION_FAILED", `${work} was a real directory when this retire first read it and is not one now (it is missing, a link or another filesystem type), so what the retire would copy is not what it read; restore it, or remove what is there, before retrying`);
5065
+ }
5066
+ }
5067
+
5068
+ /** A link at work/ (instanceWork) is still a link, or gone: a retire hook, or anything else, may
5069
+ * have put a directory or a file there since. The home's copy leaves `work/` out and the home's
5070
+ * removal takes whatever is there, so what replaced the link would be removed uncopied (#973).
5071
+ * The refusal says what was there and what is there now, and how it ends, by what is there now.
5072
+ * A directory: the next retire reads the home as it is now, and the plan shows what it would do.
5073
+ * It promises no copy: that depends on the record as it is then and on the spawn's receipt (a
5074
+ * directory of the home is copied and removed with it; an own tree's directory has no admin entry
5075
+ * and is kept after the hooks ran, until a person moves it: #1019). A file, or an entry that is
5076
+ * none of the three: no retire removes it (under a record that says `worktree` it is kept after
5077
+ * the hooks ran, under another record the inspection refuses) and the plan does not say so, so
5078
+ * the refusal names the step and not the plan. An entry that cannot be read: nothing is known of
5079
+ * it but that the next retire reads it again. */
5080
+ function assertStillLink(work, instance) {
5081
+ let st;
5082
+ try { st = lstatSync(work); } catch (e) { if (e?.code === "ENOENT") return; /* else fail closed below */ }
5083
+ if (!st?.isSymbolicLink()) {
5084
+ const now = !st ? "an entry that cannot be read" : st.isDirectory() ? "a directory" : st.isFile() ? "a file" : "an entry that is neither a link, a directory nor a file";
5085
+ const next = !st ? "The retire reads it again when it is run again"
5086
+ : st.isDirectory() ? `\`oats retire ${instance} --plan\` shows what a retire would do with what is there now, and running the retire again does that`
5087
+ : "No retire removes it: move it out of the home or remove it, then run the retire again";
5088
+ throw oatsError("E_WORK_INSPECTION_FAILED", `${work} was a link when this retire first read the home, and ${now} is there now. The home is kept and nothing of it was removed. ${next}`);
5089
+ }
5090
+ }
5091
+
4898
5092
  function assertDirectoryRoots(home, canonicalHome) {
4899
5093
  assertDirectoryHome(home, canonicalHome);
4900
5094
  const work = join(home, "work");
@@ -5678,29 +5872,97 @@ function extraWorktreesOf(home) {
5678
5872
  try { names = readdirSync(home); } catch { return trees; }
5679
5873
  // Git reports paths in their on-disk spelling: the home and each tree are compared in it too.
5680
5874
  const realHome = canonicalHomePath(home);
5681
- const inHome = (p) => { const rel = relative(realHome, canonicalHomePath(p)); return rel === "" || !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)); };
5682
5875
  for (const name of names.sort(byCodeUnit)) {
5683
5876
  if (!name.startsWith(".work-")) continue;
5684
5877
  const path = join(home, name);
5685
- try {
5686
- if (!lstatSync(path).isDirectory() || !lstatSync(join(path, ".git")).isFile()) continue;
5687
- } catch { continue; }
5688
- const dirs = gitRead(path, ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir", "--show-toplevel"]);
5689
- if (!dirs.ok) continue;
5690
- const [gitDir, commonDir, toplevel] = dirs.out.split("\n");
5691
- if (!gitDir || !commonDir || !toplevel || realPathOrNearest(gitDir) === realPathOrNearest(commonDir)) continue;
5692
- const real = canonicalHomePath(path);
5693
- // A repository inside the home goes with the home: its trees are home bytes.
5694
- if (canonicalHomePath(toplevel) !== real || inHome(commonDir)) continue;
5695
- const list = gitRead(path, ["worktree", "list", "--porcelain", "-z"]);
5696
- if (!list.ok) continue;
5697
- const records = parseWorktreeList(list.out);
5698
- const self = records.find((r) => canonicalHomePath(r.worktree) === real);
5699
- if (!records.length || !self) continue;
5700
- trees.push({ name, path, repo: records[0].worktree, gitDir, commonDir: realPathOrNearest(commonDir), locked: self.locked });
5878
+ const tree = registeredLinkedWorktree(path, realHome);
5879
+ if (tree) trees.push({ name, path, ...tree });
5701
5880
  }
5702
5881
  return trees;
5703
5882
  }
5883
+ /** The kernel's test of a tree of a home, for `path` in the home whose
5884
+ * canonical spelling is `realHome`: a real directory (not a symlink) whose
5885
+ * `.git` is a regular file, and that Git confirms is a registered linked
5886
+ * worktree of a repository outside the home (extraWorktreesOf says how).
5887
+ * The one test of an extra tree and of `work/` (instanceWork). Read-only
5888
+ * probes (gitRead). → { repo, gitDir, commonDir, locked }, or undefined. */
5889
+ function registeredLinkedWorktree(path, realHome) {
5890
+ const inHome = (p) => { const rel = relative(realHome, canonicalHomePath(p)); return rel === "" || !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)); };
5891
+ try {
5892
+ if (!lstatSync(path).isDirectory() || !lstatSync(join(path, ".git")).isFile()) return undefined;
5893
+ } catch { return undefined; }
5894
+ const dirs = gitRead(path, ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir", "--show-toplevel"]);
5895
+ if (!dirs.ok) return undefined;
5896
+ const [gitDir, commonDir, toplevel] = dirs.out.split("\n");
5897
+ if (!gitDir || !commonDir || !toplevel || realPathOrNearest(gitDir) === realPathOrNearest(commonDir)) return undefined;
5898
+ const real = canonicalHomePath(path);
5899
+ // A repository inside the home goes with the home: its trees are home bytes.
5900
+ if (canonicalHomePath(toplevel) !== real || inHome(commonDir)) return undefined;
5901
+ const list = gitRead(path, ["worktree", "list", "--porcelain", "-z"]);
5902
+ if (!list.ok) return undefined;
5903
+ const records = parseWorktreeList(list.out);
5904
+ const self = records.find((r) => canonicalHomePath(r.worktree) === real);
5905
+ if (!records.length || !self) return undefined;
5906
+ return { repo: records[0].worktree, gitDir, commonDir: realPathOrNearest(commonDir), locked: self.locked };
5907
+ }
5908
+ /** What is at `<home>/work` (awebai/oats#962): the one answer the retire
5909
+ * (retireInstance) and its plan (planRetire) both read. `record` is the
5910
+ * home's record as the caller read it. → { path, at, is, tree }.
5911
+ *
5912
+ * `at` is the entry: "link", "directory" (a real one), "other" (any other
5913
+ * kind of entry) or "none". `is` is what it is to the instance:
5914
+ *
5915
+ * - "directory-mode": the record says `directory`. Whatever is there, the
5916
+ * retire holds it against the spawn's receipt (inspectRetirementWork).
5917
+ * - "own-tree": the instance's own work tree. The retire re-homes it, or
5918
+ * removes it through Git when told to.
5919
+ * - "home-directory": a real directory that is not that. It is bytes of the
5920
+ * home that the home's copy leaves out: the retire copies it to recovery,
5921
+ * checks the copy against what it inspected, and removes it with the
5922
+ * home. Never a Git removal, and never left out of the copy.
5923
+ * - "link": a symbolic link, whatever the record says (awebai/oats#973). A
5924
+ * link is never the instance's own tree: it goes with the home, and no
5925
+ * step reads what it leads to as a tree to copy, move or remove. Neither
5926
+ * the receipt nor Git is read for it.
5927
+ * - "none", "other": the entry, for a record that does not say `worktree`.
5928
+ * The retire reads an "other" entry (a file, say) as a worktree, and its
5929
+ * inspection refuses it. Under a record that says `worktree` such an
5930
+ * entry is the own tree, as nothing at `work/` is (below): the retire
5931
+ * then finds a work directory whose Git admin entry is missing, runs its
5932
+ * hooks, and keeps the entry and the home as an incomplete item.
5933
+ *
5934
+ * A real directory is the instance's own tree when the spawn's receipt (a
5935
+ * valid retirement baseline) holds what only a `worktree` spawn writes
5936
+ * (`generatedWorkFingerprint`). A valid receipt without it says the
5937
+ * instance was given no tree, whatever the record says now: the record is
5938
+ * the instance's to write, the receipt is not. With no valid receipt the
5939
+ * record decides: `worktree` is the own tree; `attached`, `checkout` and
5940
+ * `workspace` were given a link, so a directory there is the home's; and a
5941
+ * record with no work mode, or one this kernel does not know, has the own
5942
+ * tree exactly when Git confirms that the directory is a registered linked
5943
+ * worktree (`tree`, registeredLinkedWorktree).
5944
+ *
5945
+ * Nothing at `work/`, or an entry that is neither a link nor a directory, is
5946
+ * what the record says, as before this function: a `worktree` record's own
5947
+ * tree, else the entry. `tree` is set for a real directory Git confirms, in
5948
+ * either answer: the repository of an own tree whose record names none, and
5949
+ * what a directory of the home leaves registered in its repository. */
5950
+ export function instanceWork(home, record) {
5951
+ const path = join(home, "work");
5952
+ const mode = record?.work;
5953
+ let st;
5954
+ try { st = lstatSync(path); } catch { /* nothing that can be read is there */ }
5955
+ const at = !st ? "none" : st.isSymbolicLink() ? "link" : st.isDirectory() ? "directory" : "other";
5956
+ if (mode === "directory") return { path, at, is: "directory-mode", tree: undefined };
5957
+ // The record is the instance's to write; what a link leads to is not the instance's (#973).
5958
+ if (at === "link") return { path, at, is: "link", tree: undefined };
5959
+ if (at !== "directory") return { path, at, is: mode === "worktree" ? "own-tree" : at, tree: undefined };
5960
+ const baseline = readJsonOrUndefined(findRetirementBaseline(home));
5961
+ const tree = registeredLinkedWorktree(path, canonicalHomePath(home));
5962
+ const own = retirementBaselineValid(baseline, home) ? typeof baseline.generatedWorkFingerprint === "string"
5963
+ : mode === "worktree" || (!WORK_MODES.includes(mode) && !!tree);
5964
+ return { path, at, is: own ? "own-tree" : "home-directory", tree };
5965
+ }
5704
5966
  /** Where retire re-homes the worktrees it retains, one directory per repository under it. */
5705
5967
  export function retainedWorktreesRoot(workspace) {
5706
5968
  return join(workspace, ".agents", "worktrees");
@@ -5759,7 +6021,7 @@ function extraWorktreeRows(trees, root) {
5759
6021
  const status = gitRead(tree.path, ["status", "--porcelain", "-z", "--ignored", "--untracked-files=all", "--ignore-submodules=none"]);
5760
6022
  if (!status.ok) why.push(`its status could not be read (${status.err})`);
5761
6023
  else if (status.out.length) why.push("it holds uncommitted, untracked or ignored files");
5762
- if (RECOVERABLE_GIT_ADMIN.some((n) => existsSync(join(tree.gitDir, n)))) why.push("an operation is in progress in it");
6024
+ if (gitOperationInProgress(tree.gitDir, tree.path)) why.push("an operation is in progress in it");
5763
6025
  if (commit) {
5764
6026
  const reach = gitRepoRead(tree.commonDir, ["for-each-ref", "--contains", commit, "--count=1", "--format=%(objectname)"]);
5765
6027
  if (!reach.ok) why.push(`which refs reach its HEAD commit could not be read (${reach.err})`);
@@ -5907,6 +6169,8 @@ function instanceSessionTarget(home) {
5907
6169
  if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home);
5908
6170
  throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${e.message}`);
5909
6171
  }
6172
+ // A record that is JSON and no object gives no endpoint to compare the receipt with.
6173
+ if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${join(home, "instance.json")} holds no JSON object`);
5910
6174
  const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
5911
6175
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
5912
6176
  if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
@@ -5919,7 +6183,8 @@ export function inspectInstanceSession(home) {
5919
6183
  if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", waitingOnYou: null };
5920
6184
  let observed;
5921
6185
  try { observed = inspectSessionTarget(s.target); }
5922
- catch (e) { throw oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`); }
6186
+ // The tmux failure stays the cause: sessionServerGone judges it.
6187
+ catch (e) { throw Object.assign(oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`), { cause: e }); }
5923
6188
  // Feature waiting-on-you: beside `state`, whose enum is unchanged.
5924
6189
  return { home: s.home, ...observed, waitingOnYou: harnessRunning(observed) ? liveWaiting(s.home) : null };
5925
6190
  }
@@ -5940,6 +6205,15 @@ function tmuxServerAbsence(e) {
5940
6205
  return null;
5941
6206
  }
5942
6207
  function tmuxServerLost(e) { return tmuxServerAbsence(e) !== null; }
6208
+ /** Whether the tmux server of `home`'s recorded session is gone, judged from `error`, a failed tmux
6209
+ * call on its socket (#921). No server on the socket is gone. A missing socket file is gone only when
6210
+ * no process works in the home (#624); otherwise `why` says what is not established. Any other
6211
+ * failure is not gone, with no `why`. → { gone, why } */
6212
+ export function sessionServerGone(home, error, io) {
6213
+ const absence = tmuxServerAbsence(error);
6214
+ const why = absence === "missing-socket" ? missingSocketUnestablished(tmuxFailure(error, error.message), processesInHome(home, io)) : null;
6215
+ return { gone: absence !== null && !why, why };
6216
+ }
5943
6217
  /** tmux's own way back for a server that lost its socket file (tmux(1), `-S`). Named, never performed. */
5944
6218
  const TMUX_SOCKET_REMEDY = "tmux recreates a removed socket file when its server process receives SIGUSR1";
5945
6219
  /** Processes as a refusal names them: pid and program, at most five, then how many more. */
@@ -6116,35 +6390,106 @@ function recordedSessionAbsence(home, meta, io) {
6116
6390
  * file is idle only when no process works in the home (#624). */
6117
6391
  export function stopInstanceSession(home, o = {}) {
6118
6392
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session stop needs an absolute instance home");
6119
- if (o.graceMs !== undefined && (!Number.isSafeInteger(o.graceMs) || o.graceMs < 1 || o.graceMs > 300000)) throw oatsError("E_BAD_ARGS", "stop grace must be 1-300000 ms");
6393
+ requireStopGrace(o.graceMs);
6394
+ // Under the home's lifecycle claim, the caller's (STOP_UNDER_CLAIM: a stop apply holds the claim
6395
+ // of every target before it stops the first) or, for the span of this one stop, its own (a
6396
+ // retire stopping a recorded child): no retire inspects or removes a home this stop writes
6397
+ // into, and a holder is answered before anything is signalled (lifecycleClaimRefusals:
6398
+ // E_INSTANCE_RETIRING beside a retire, E_LIFECYCLE_BUSY beside a stop). A home that is not
6399
+ // there has no claim to take and nothing to stop: it answers as it always did.
6400
+ if (o[STOP_UNDER_CLAIM] || !existsSync(home)) return stopSessionClaimed(home, o);
6401
+ const held = claimHomeFor("stop", basename(home), home);
6402
+ try { return stopSessionClaimed(home, o); } finally { releaseHomeClaim(held); }
6403
+ }
6404
+ /** An option of stopInstanceSession: the caller holds the home's lifecycle claim (claimHomeFor)
6405
+ * for this stop. A symbol, so no caller can set it from parsed arguments or JSON. */
6406
+ export const STOP_UNDER_CLAIM = Symbol("oats.stopUnderClaim");
6407
+ /** Refuse a stop's grace that is not 1-300000 ms (undefined is the default): before any effect. */
6408
+ export function requireStopGrace(graceMs) {
6409
+ if (graceMs !== undefined && (!Number.isSafeInteger(graceMs) || graceMs < 1 || graceMs > 300000)) throw oatsError("E_BAD_ARGS", "stop grace must be 1-300000 ms");
6410
+ }
6411
+ /** The stop of stopInstanceSession, under the home's claim. The pending self-retire marker is read
6412
+ * here, under it: a `--self` retire writes the marker while it holds the claim. */
6413
+ function stopSessionClaimed(home, o) {
6120
6414
  const realHome = realPathOrNearest(home);
6121
- if (existsSync(retirePendingMarkerPath(realHome))) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired; nothing was stopped`);
6122
- const s = instanceSessionTarget(realHome);
6123
- if (!s.target) return { home: s.home, backend: null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
6124
- let before;
6125
- try { before = inspectSessionTarget(s.target); }
6126
- catch (e) {
6127
- const absence = tmuxServerAbsence(e);
6128
- const why = absence === "missing-socket" ? missingSocketUnestablished(tmuxFailure(e, e.message), processesInHome(realHome, o.io)) : null;
6129
- if (absence && !why) before = { present: false, state: "stopped" };
6130
- else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${why ?? e.message}`);
6131
- }
6132
- if (!before.present || before.state === "shell" || before.state === "stopped") return { home: s.home, backend: s.target.backend, stopped: false, alreadyIdle: true, state: before.state, receipt: null };
6133
- const receipt = stopHarness(s.target, { graceMs: o.graceMs ?? 20000, kill: o.io?.kill, sleep: o.io?.sleep });
6134
- writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: receipt, retained: ["home", "work", "transcript", "launch"] });
6135
- appendEvent(realHome, { kind: receipt.exited ? "stopped" : "stop-refused", data: { signal: receipt.signal, waitedMs: receipt.waitedMs, stillRunning: receipt.stillRunning ?? [], state: receipt.state } });
6136
- 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 });
6137
- return { home: s.home, backend: s.target.backend, stopped: true, alreadyIdle: false, state: receipt.state, receipt };
6138
- }
6415
+ // `signalling`: the stop reached the step that signals the harness; `receipt`: that step's answer.
6416
+ let signalling = false, receipt;
6417
+ try {
6418
+ if (existsSync(retirePendingMarkerPath(realHome))) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired; nothing was stopped`);
6419
+ const s = instanceSessionTarget(realHome);
6420
+ if (!s.target) return { home: s.home, backend: null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
6421
+ let before;
6422
+ try { before = inspectSessionTarget(s.target); }
6423
+ catch (e) {
6424
+ const lost = sessionServerGone(realHome, e, o.io);
6425
+ if (lost.gone) before = { present: false, state: "stopped" };
6426
+ else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${lost.why ?? e.message}`);
6427
+ }
6428
+ if (!before.present || before.state === "shell" || before.state === "stopped") return { home: s.home, backend: s.target.backend, stopped: false, alreadyIdle: true, state: before.state, receipt: null };
6429
+ signalling = true;
6430
+ receipt = stopHarness(s.target, { graceMs: o.graceMs ?? 20000, kill: o.io?.kill, sleep: o.io?.sleep });
6431
+ writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: receipt, retained: ["home", "work", "transcript", "launch"] });
6432
+ appendEvent(realHome, { kind: receipt.exited ? "stopped" : "stop-refused", data: { signal: receipt.signal, waitedMs: receipt.waitedMs, stillRunning: receipt.stillRunning ?? [], state: receipt.state } });
6433
+ 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 });
6434
+ return { home: s.home, backend: s.target.backend, stopped: true, alreadyIdle: false, state: receipt.state, receipt };
6435
+ } catch (e) {
6436
+ // An error that is not the kernel's (the home removed under the stop, a write refused) is a
6437
+ // stop that failed, never the system's code (awebai/oats#891): its text, and what is true of
6438
+ // the harness by then. The receipt goes with it, so the caller reports what it established.
6439
+ // A receipt alone is not a signal: stopHarness answers one for a harness it found idle, having
6440
+ // signalled nothing (`sentAt: null`), and names as "already gone" a process its signal missed.
6441
+ const reached = receipt?.sentAt != null && receipt.requested.some((r) => r.note !== "already gone");
6442
+ const harness = reached ? `its harness was signalled (${receipt.signal}) and ${receipt.exited ? "has exited" : "is still running"}`
6443
+ : receipt ? `no signal reached its harness, which ${receipt.exited ? "had already exited" : "was not seen to exit"}`
6444
+ : signalling ? "whether its harness was signalled is not known" : "its harness was not signalled";
6445
+ const failure = isAnswerCode(e?.code) ? e : Object.assign(asKernelError(e, "E_SESSION_STOP_FAILED", `${basename(realHome)}: ${e?.message ?? e}; ${harness}`), receipt ? { receipt } : {});
6446
+ if (signalling) stopsThatSignalled.add(failure);
6447
+ throw failure;
6448
+ }
6449
+ }
6450
+ /** What a failed stop (an error of stopInstanceSession) established of the processes it signalled,
6451
+ * for its row of results: [] only when its receipt says the harness exited; the pids its receipt
6452
+ * names as still alive; and null when nothing is established. That is a stop without a receipt,
6453
+ * and one whose receipt says "not exited" and names no live pid: every process it signalled is
6454
+ * gone but the session did not read as idle (stopHarness's last answer), so something still runs
6455
+ * there that the stop cannot name. A reader takes [] as "stopped", which that is not. */
6456
+ export function stillRunningOf(e) {
6457
+ const receipt = e?.receipt;
6458
+ if (!receipt) return null;
6459
+ if (receipt.exited) return [];
6460
+ return Array.isArray(receipt.stillRunning) && receipt.stillRunning.length ? receipt.stillRunning : null;
6461
+ }
6462
+ /** What a retire says of the recorded children that did not stop (`rows`, each `ok: false`). A
6463
+ * child is "still running" only where its stop established processes that run (`stillRunning`
6464
+ * lists them). Of any other nothing of the kind is known: its stop was refused before it began (a
6465
+ * claim held, a self-retire scheduled) or failed, and it is said with its row's code. */
6466
+ function childrenNotStopped(rows) {
6467
+ const established = (k) => Array.isArray(k.stillRunning) && k.stillRunning.length > 0;
6468
+ const running = rows.filter(established);
6469
+ return [...(running.length ? [`${running.map((k) => k.instance).join(", ")} ${running.length === 1 ? "is" : "are"} still running after a bounded stop`] : []),
6470
+ ...rows.filter((k) => !established(k)).map((k) => `${k.instance} could not be stopped (${k.code})`)].join("; ");
6471
+ }
6472
+
6473
+ /** The errors of stopInstanceSession thrown once it had reached the step that signals the harness:
6474
+ * whoever reports what a stop touched (a retire's `reached.sessionStopAttempted`) reads it here. */
6475
+ const stopsThatSignalled = new WeakSet();
6139
6476
 
6140
6477
  /** What a retire plan promises about recorded children, applied: each is stopped
6141
6478
  * (default grace, never escalated) in the order given (the plan's: deepest first)
6142
6479
  * and kept. Every outcome is collected, so a refusal names each child that is
6143
- * still running or whose stop could not be established. */
6144
- function stopRecordedChildren(children) {
6480
+ * still running or whose stop could not be established. `signalled` is called
6481
+ * for each child whose stop reached the step that signals its harness. */
6482
+ function stopRecordedChildren(children, signalled) {
6145
6483
  return children.map((kid) => {
6146
- try { const s = stopInstanceSession(kid.home, {}); return { instance: kid.instance, home: kid.home, ok: true, stopped: s.stopped, alreadyIdle: s.alreadyIdle }; }
6147
- catch (e) { return { instance: kid.instance, home: kid.home, ok: false, code: e.code || "E_SESSION_STOP_FAILED", message: e.message, stillRunning: e.receipt?.stillRunning ?? null }; }
6484
+ try {
6485
+ const s = stopInstanceSession(kid.home, {});
6486
+ if (s.stopped) signalled?.();
6487
+ return { instance: kid.instance, home: kid.home, ok: true, stopped: s.stopped, alreadyIdle: s.alreadyIdle };
6488
+ } catch (e) {
6489
+ if (stopsThatSignalled.has(e)) signalled?.();
6490
+ reportDefect(e); // the error becomes a row here: its stack would otherwise be lost
6491
+ return { instance: kid.instance, home: kid.home, ok: false, code: kernelCode(e, "E_SESSION_STOP_FAILED"), message: e.message, stillRunning: stillRunningOf(e) };
6492
+ }
6148
6493
  });
6149
6494
  }
6150
6495
 
@@ -6278,10 +6623,19 @@ function tmuxOn(socket, args, io, env) {
6278
6623
  return (io?.exec || execFileSync)(tmux, ["-u", "-S", socket, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...(env ? { env } : {}) });
6279
6624
  }
6280
6625
 
6626
+ /** Write `value` as JSON at `path` through a private file beside it, renamed over it. When the
6627
+ * write or the rename fails the private file is removed and the error thrown is that failure's:
6628
+ * a file system with no space makes the file and has no block for its bytes, and nothing else
6629
+ * would remove it (awebai/oats#963). The removal's own failure is not answered. */
6281
6630
  function writeJsonAtomic(path, value, mode) {
6282
6631
  const tmp = `${path}.tmp-${process.pid}`;
6283
- writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", mode !== undefined ? { mode } : undefined);
6284
- renameSync(tmp, path);
6632
+ try {
6633
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", mode !== undefined ? { mode } : undefined);
6634
+ renameSync(tmp, path);
6635
+ } catch (e) {
6636
+ try { rmSync(tmp, { force: true }); } catch { /* the first error is the one answered */ }
6637
+ throw e;
6638
+ }
6285
6639
  }
6286
6640
 
6287
6641
  // ---------- stopping a harness, selecting on an existing home ----------
@@ -6509,6 +6863,8 @@ export function preWorkspaceHome(home, what) {
6509
6863
  }
6510
6864
  export function startInstanceSession(home, o = {}) {
6511
6865
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session start needs an absolute instance home");
6866
+ // A home whose record is there and cannot be read is refused before anything of it is read (#896).
6867
+ identifiedHomeRecord(home);
6512
6868
  // A home opened in Herdr, or an earlier start that allocated a Herdr pane, is refused before any
6513
6869
  // guard or receipt reads it.
6514
6870
  refuseHerdrHome(realPathOrNearest(home));
@@ -6531,7 +6887,12 @@ export function startInstanceSession(home, o = {}) {
6531
6887
  const lock = join(realHome, ".oats-start.lock");
6532
6888
  const pendingPath = join(realHome, ".oats-start-pending.json");
6533
6889
  const exitedPath = join(realHome, ".oats-start-exited");
6534
- const readMeta = () => { try { return upgradeHomeMeta(JSON.parse(readFileSync(metaPath, "utf8")), realHome); } catch (e) { throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${metaPath}: ${e.message}`); } };
6890
+ // The same reader as the check above: a record that became unreadable since then refuses as there.
6891
+ const readMeta = () => {
6892
+ const record = identifiedHomeRecord(realHome);
6893
+ if (record.state !== "record") throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${metaPath}: it is no longer there`);
6894
+ return upgradeHomeMeta(record.meta, realHome);
6895
+ };
6535
6896
  // Workspace-model homes only (lead decision c3 Q2): a home an earlier kernel
6536
6897
  // spawned records no modules, and there is no scope configuration left to
6537
6898
  // re-resolve it against. Retire still works on it.
@@ -6542,9 +6903,8 @@ export function startInstanceSession(home, o = {}) {
6542
6903
  // passes), else `{ stopped: false, why }`: the check's reason, or null for another failure.
6543
6904
  const missingSocket = (detail) => missingSocketUnestablished(detail, processesInHome(realHome, rawIo));
6544
6905
  const lostServer = (e) => {
6545
- const absence = tmuxServerAbsence(e);
6546
- const why = absence === "missing-socket" ? missingSocket(tmuxFailure(e, e.message)) : null;
6547
- return absence && !why ? { stopped: true } : { stopped: false, why };
6906
+ const lost = sessionServerGone(realHome, e, rawIo);
6907
+ return lost.gone ? { stopped: true } : { stopped: false, why: lost.why };
6548
6908
  };
6549
6909
  const launchFailure = (error) => {
6550
6910
  // execFileSync errors embed argv (including capability environment) in
@@ -6577,9 +6937,11 @@ export function startInstanceSession(home, o = {}) {
6577
6937
  // Launch-hook meta lands per capability over the spawn's record; a hook
6578
6938
  // that answered without meta keeps its previous entry (retire reads it).
6579
6939
  ...(hookMeta ? { capabilityMeta: { ...(meta.capabilityMeta || {}), ...hookMeta } } : {}) };
6580
- if (launchPrompts) {
6940
+ // The record describes the last start, a start that did not engage the confirmation included.
6941
+ if (launchPrompts?.status === "not-engaged") { next.launchPrompts = launchPrompts; delete next.launchPromptTarget; }
6942
+ else if (launchPrompts) {
6581
6943
  next.launchPrompts = launchPrompts; next.launchPromptTarget = launchPromptTarget ?? target;
6582
- next.launched = launchPrompts.status === "completed";
6944
+ next.launched = promptLaunched(launchPrompts.status);
6583
6945
  } else { delete next.launchPrompts; delete next.launchPromptTarget; }
6584
6946
  next.tmux = { session: target.session, window: target.window, socket: resolve(target.socket) };
6585
6947
  writeJsonAtomic(metaPath, next);
@@ -6693,7 +7055,11 @@ export function startInstanceSession(home, o = {}) {
6693
7055
  // preflight happens here, before anything is observed or stopped.
6694
7056
  // --reselect-launch (feature launch-preference): apply the home's launch layers now (souls.launch,
6695
7057
  // the recorded soul's launch, the host default) instead of the frozen recipe.
6696
- const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta) : null;
7058
+ // `launchOffered`: the caller's read of the workspace's souls (homeSoulsOffered), which the layers need
7059
+ // to tell a key of souls.launch that names no soul. A selection the layers would decide never goes on
7060
+ // without it: a key that was not checked must not let the launch fall through.
7061
+ const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
7062
+ 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)`);
6697
7063
  // The session this start opens its window in when it has to create one, and what its creation
6698
7064
  // needs (planOatsTmuxSession), read at most once: by the plan's lookup or by the creation's preflight.
6699
7065
  const planSession = receipt.target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
@@ -6743,7 +7109,7 @@ export function startInstanceSession(home, o = {}) {
6743
7109
  if (recorded.error) return undefined; // the gate refuses below; the lookup does not decide it
6744
7110
  const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
6745
7111
  if (!preview || preview.server) return expectedPanePath(preview, planSession, o.io, realHome);
6746
- try { return expectedPanePath(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (oatsCoded(e)) return undefined; throw e; }
7112
+ try { return expectedPanePath(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return undefined; throw e; }
6747
7113
  };
6748
7114
  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,
6749
7115
  panePath: pane });
@@ -6839,8 +7205,9 @@ export function startInstanceSession(home, o = {}) {
6839
7205
  const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
6840
7206
  ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
6841
7207
  ...(hookMeta ? { hookMeta } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
6842
- const launchPromptAnswers = launchPromptPolicyAt(dirname(dirname(dirname(dirname(home)))), realHome);
6843
- if (promptOptedIn(launchPromptAnswers)) warnings.push(LAUNCH_PROMPT_UPDATE_WARNING);
7208
+ warnings.push(...launchStartNotices(dirname(dirname(dirname(dirname(home)))), launchPlan?.harness || harness, command));
7209
+ if (kernelNode().warning) warnings.push(kernelNode().warning);
7210
+ const engaged = devChannelEngaged(launchPlan?.harness || harness, command);
6844
7211
  let stopReceipt = null;
6845
7212
  if (state.present && state.state !== "shell") {
6846
7213
  // Restart: every preflight above passed, so ask the running harness to
@@ -6863,7 +7230,8 @@ export function startInstanceSession(home, o = {}) {
6863
7230
  writeKernelShim(realHome);
6864
7231
  const startedAt = new Date().toISOString();
6865
7232
  const id = randomUUID();
6866
- const makeLaunchController = () => promptOptedIn(launchPromptAnswers) ? promptController(realHome, id, launchPlan?.harness || harness, launchPromptAnswers, command, o.io, originalHomeIdentity) : null;
7233
+ if (!engaged) planExtra.launchPrompts = notEngaged(id);
7234
+ const makeLaunchController = () => engaged ? promptController(realHome, id, command, o.io, originalHomeIdentity) : null;
6867
7235
  let launchController;
6868
7236
  let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
6869
7237
  checkRoots();
@@ -6903,12 +7271,12 @@ export function startInstanceSession(home, o = {}) {
6903
7271
  // A replacement window (never launched, recorded window gone, recorded server gone) is created
6904
7272
  // on the OATS server, wherever the home was recorded: one socket from here to the record.
6905
7273
  const recordedSocket = socket ? resolve(socket) : null;
6906
- socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket);
7274
+ socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
6907
7275
  if (lookAgain(() => panePath(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
6908
7276
  let names;
6909
7277
  try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
6910
7278
  catch (e) {
6911
- if (oatsCoded(e)) throw e;
7279
+ if (isKernelCode(e?.code)) throw e;
6912
7280
  throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
6913
7281
  }
6914
7282
  if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
@@ -6926,6 +7294,7 @@ export function startInstanceSession(home, o = {}) {
6926
7294
  if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
6927
7295
  }
6928
7296
  if (launchController) launchPrompts = inPlace ? launchController.observeRespawn(launchPromptTarget, beforeRespawn) : launchController.observeNew(launchPromptTarget);
7297
+ if (launchPrompts?.status === "flag-ignored") { launchPrompts = channelsUnavailable(id, launchPrompts); warnings = flagIgnoredWarnings(warnings); }
6929
7298
  } catch (error) {
6930
7299
  if (!promptDispatched) throw error;
6931
7300
  launchPrompts = incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt dispatch or recording incomplete", launchPrompts, originalHomeIdentity);
@@ -6954,7 +7323,7 @@ export function startInstanceSession(home, o = {}) {
6954
7323
  if (e.code && String(e.code).startsWith("E_")) throw e;
6955
7324
  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`);
6956
7325
  }
6957
- if (launchPrompts && launchPrompts.status !== "completed") throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
7326
+ if (launchPrompts && !promptLaunched(launchPrompts.status)) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
6958
7327
  // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
6959
7328
  if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
6960
7329
  return { ...done, warnings: [...warnings, ...movedWarnings] };
@@ -7287,8 +7656,14 @@ function assertWorktreeTopLevel(work, disclosure) {
7287
7656
  }
7288
7657
  }
7289
7658
 
7290
- function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktreeRemoval, directory = false, orphanedWork = false, disclosure } = {}) {
7291
- if (directory) assertDirectoryRoots(home);
7659
+ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktreeRemoval, directory = false, directoryMode = directory, link = false, instance, orphanedWork = false, disclosure } = {}) {
7660
+ // `directory`: work/ is read, copied and checked as a directory's bytes. `directoryMode`: the
7661
+ // record says `directory`. They differ for a directory of the home (instanceWork, #962), which
7662
+ // is copied the same way and is no directory instance: it has no receipt of its roots.
7663
+ if (directoryMode) assertDirectoryRoots(home);
7664
+ else if (directory) assertHomeDirectory(work);
7665
+ // `link`: work/ was read as a link, which goes with the home. Nothing of what it leads to is read.
7666
+ else if (link) assertStillLink(work, instance);
7292
7667
  const classes = [];
7293
7668
  let baseline;
7294
7669
  const path = findRetirementBaseline(home);
@@ -7320,7 +7695,10 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
7320
7695
  }
7321
7696
  // A mutable mode must not turn owned directory bytes into an excluded shared
7322
7697
  // tree (or authorize Git deletion). Require the independent spawn authority.
7323
- if (directory !== (baselineValid && baseline.directoryWork === true)) {
7698
+ // It is the record's mode that is held against the receipt, as before #962:
7699
+ // a directory of the home passes it as any home that is not in directory
7700
+ // mode does, and what it then gets is a checked copy, never either of those.
7701
+ if (directoryMode !== (baselineValid && baseline.directoryWork === true)) {
7324
7702
  throw oatsError("E_WORK_INSPECTION_FAILED", "directory work mode disagrees with independent retirement authority");
7325
7703
  }
7326
7704
  let directoryFingerprint;
@@ -7330,8 +7708,9 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
7330
7708
  if (readdirSync(work).length) classes.push("directory work bytes");
7331
7709
  }
7332
7710
  // For a quarantine retry whose worktree is gone, whether the recorded branch
7333
- // is still there to copy. Every other retire takes it to be there.
7334
- const branchExists = !directory && recordedBranch && !existsSync(work) ? recordedBranchExists(recordedBranch.repo, recordedBranch.branch) : true;
7711
+ // is still there to copy. Every other retire takes it to be there. Not asked
7712
+ // for a link that leads nowhere: nothing is copied through a link (#973).
7713
+ const branchExists = !directory && !link && recordedBranch && !existsSync(work) ? recordedBranchExists(recordedBranch.repo, recordedBranch.branch) : true;
7335
7714
  // Before anything of the worktree is read: its status describes it, not another directory.
7336
7715
  if (!directory && isWorktree && existsSync(work)) assertWorktreeTopLevel(work, disclosure);
7337
7716
  // A retire that will remove the worktree asks whether a ref that outlives it
@@ -7430,11 +7809,79 @@ function mirrorTopLevel(source, dest) {
7430
7809
  for (const e of entriesAsBytes(source)) if (!e.name.equals(GIT_NAME)) copyTreeSafe(joinBytes(source, e.name), joinBytes(dest, e.name));
7431
7810
  }
7432
7811
 
7812
+ /** What a recovery's work copy takes from a worktree's own Git directory: the
7813
+ * state of an operation, and what an operation that ended left there. It is
7814
+ * the list of what is copied, never the test for "an operation is in
7815
+ * progress" (gitOperationInProgress). */
7433
7816
  export const RECOVERABLE_GIT_ADMIN = [
7434
7817
  "MERGE_HEAD", "MERGE_MSG", "AUTO_MERGE", "CHERRY_PICK_HEAD", "REVERT_HEAD", "REBASE_HEAD",
7435
7818
  "BISECT_LOG", "BISECT_START", "BISECT_NAMES", "rebase-apply", "rebase-merge", "sequencer",
7436
7819
  ];
7437
7820
 
7821
+ /** The entries of a worktree's own Git directory by which `git status` decides
7822
+ * that an operation is in progress there (Git's wt-status.c,
7823
+ * wt_status_get_state, and sequencer.c, sequencer_get_last_command):
7824
+ * - `rebase-apply`, else `rebase-merge`: a rebase, or `git am`;
7825
+ * - `MERGE_HEAD`: a merge;
7826
+ * - `CHERRY_PICK_HEAD`, `REVERT_HEAD`: a cherry-pick, a revert;
7827
+ * - `sequencer/todo`: a cherry-pick or a revert of several commits, between
7828
+ * two of them;
7829
+ * - `BISECT_LOG`: a bisect.
7830
+ * It is not the list of what a recovery copies (RECOVERABLE_GIT_ADMIN): Git
7831
+ * leaves `REBASE_HEAD`, `AUTO_MERGE` and `MERGE_MSG` behind operations that
7832
+ * ended, reads `BISECT_START` and `BISECT_NAMES` only during a bisect, and
7833
+ * reads nothing of a `sequencer` directory but its `todo`. None of them says
7834
+ * that an operation is in progress, and a copy still takes each. */
7835
+ export const GIT_OPERATION_ENTRIES = Object.freeze([
7836
+ "rebase-apply", "rebase-merge", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "sequencer/todo", "BISECT_LOG",
7837
+ ]);
7838
+ /** The two of them that are refs. In the files format a ref is a file of the
7839
+ * Git directory; in the reftable format it is not, and only Git can say
7840
+ * whether it is there. */
7841
+ const GIT_OPERATION_REFS = Object.freeze(["CHERRY_PICK_HEAD", "REVERT_HEAD"]);
7842
+
7843
+ /** Whether something is at `path`, a link not followed → true, false when it
7844
+ * is not there (ENOENT, ENOTDIR), null when it cannot be looked at. */
7845
+ function gitEntryAt(path) {
7846
+ try { lstatSync(path); return true; }
7847
+ catch (e) { return e?.code === "ENOENT" || e?.code === "ENOTDIR" ? false : null; }
7848
+ }
7849
+ /** Whether the repository of the worktree whose own Git directory is `gitDir`
7850
+ * may store its refs in the reftable format: a `reftable` entry in that
7851
+ * directory, which a linked worktree's has too, or in the common directory
7852
+ * its `commondir` file names. No Git command runs for it. What cannot be
7853
+ * read is not "no": then Git is asked. */
7854
+ function refsMayBeReftable(gitDir) {
7855
+ if (gitEntryAt(join(gitDir, "reftable")) !== false) return true;
7856
+ let common;
7857
+ try { common = readFileSync(join(gitDir, "commondir"), "utf8").trim(); }
7858
+ catch (e) { return !(e?.code === "ENOENT" || e?.code === "ENOTDIR"); }
7859
+ return gitEntryAt(join(resolve(gitDir, common), "reftable")) !== false;
7860
+ }
7861
+
7862
+ /** Whether a Git operation is in progress in the worktree at `tree` whose own
7863
+ * Git directory is `gitDir`: the one answer to that question, for a retire's
7864
+ * extra trees, for the recovery of its own tree and for the listing of what
7865
+ * retires retained. A tree is removed on this answer, so it differs from
7866
+ * Git's own where that keeps a tree:
7867
+ * - an entry counts when it exists, as whatever it is and without following
7868
+ * a link. Git also resolves the two refs and reads the todo's first word;
7869
+ * a `CHERRY_PICK_HEAD` that does not resolve and a todo Git cannot read
7870
+ * are operations here;
7871
+ * - an entry that cannot be looked at, for any reason but its absence
7872
+ * (ENOENT, ENOTDIR), is an operation.
7873
+ * The entries are files in every format but the two refs. In a repository
7874
+ * that stores its refs in the reftable format a cherry-pick or a revert left
7875
+ * open in a tree with no change leaves no entry at all, so there, and only
7876
+ * there, Git is asked for each of the two in the tree (gitRefPresence).
7877
+ * Whatever is not Git's plain "not there" is an operation: a failure, a
7878
+ * timeout, no Git, no `tree` to ask in. In the files format no Git command
7879
+ * runs. */
7880
+ export function gitOperationInProgress(gitDir, tree) {
7881
+ if (GIT_OPERATION_ENTRIES.some((entry) => gitEntryAt(join(gitDir, entry)) !== false)) return true;
7882
+ return refsMayBeReftable(gitDir) && GIT_OPERATION_REFS.some((name) => gitRefPresence(tree, name) !== "absent");
7883
+ }
7884
+
7438
7885
  /** The paths of a repository's Git directories that a recovery's work copy
7439
7886
  * takes by copying them, beside the clone, the files and the index: one
7440
7887
  * selection, read by the copier (restoreStandaloneGitState,
@@ -7442,7 +7889,7 @@ export const RECOVERABLE_GIT_ADMIN = [
7442
7889
  * (repositoryGitState), so that each copied path is compared by what its
7443
7890
  * copy carries (copiedGitPathDigest). `dir`: the repository's own Git
7444
7891
  * directory ("git") or its common directory ("common"). `copy`: copyTreeSafe
7445
- * ("tree") or copyFileSync ("file").
7892
+ * ("tree") or copyRegularFile ("file").
7446
7893
  * The index is copied whole and is not in the selection: it is compared by
7447
7894
  * its entries, its resolve-undo records and its mode, never by its bytes,
7448
7895
  * which hold a cache that a read-only Git command rewrites. That is a
@@ -7457,7 +7904,7 @@ const copiedGitPath = ({ dir, path }, gitDir, commonDir) => join(dir === "git" ?
7457
7904
  /** What the copy of one selected path carries, as a digest; null when the
7458
7905
  * path is not there. copyTreeSafe gives a copy the entry's kind, bytes or
7459
7906
  * target, and the bits of the entry and of everything under it: its exact
7460
- * digest. copyFileSync follows a link and gives the copy the bytes and the
7907
+ * digest. copyRegularFile follows a link and gives the copy the bytes and the
7461
7908
  * mode of what it reaches: those. Any failure but "not there" throws, as a
7462
7909
  * read of the Git state does, and so does a file path that is not a file. */
7463
7910
  function copiedGitPathDigest(entry, at) {
@@ -7559,6 +8006,52 @@ function carryNamedObjects(source, recovered, { commits = [], blobs = [] }) {
7559
8006
  }
7560
8007
  }
7561
8008
 
8009
+ /** Copy `source` to `dest` as one file: how the recovery's copier takes the
8010
+ * paths it copies "as a file" (the index, the entries of COPIED_GIT_PATHS
8011
+ * with copy "file", a nested repository's reflogs). The kernel decides what
8012
+ * is copied that way, never the file system: copyFileSync of an empty
8013
+ * directory fails on one (EISDIR) and writes an empty file on another, where
8014
+ * a directory's size is 0, so the same retire refused on one host and went
8015
+ * through on the other (awebai/oats#1029).
8016
+ * The look follows a link, as Git does at each of these paths (it reads the
8017
+ * index, info/attributes and a reflog through one) and as the comparison
8018
+ * does (copiedGitPathDigest): what Git reads there decides.
8019
+ * → true: a regular file is there, in place or at a link's end, and `dest`,
8020
+ * whose directory is made, now holds its bytes and mode as a plain file.
8021
+ * → false: nothing is there (ENOENT, ENOTDIR), also at the end of a link
8022
+ * that leads nowhere; nothing is written, and the caller does what it always
8023
+ * did for an absent path.
8024
+ * Anything else throws, naming the path and what is there in the kernel's
8025
+ * own words (notCopiedAsFile), never the system's message. `source` and
8026
+ * `dest` are strings or Buffers (a ref's log is named by its bytes). */
8027
+ export function copyRegularFile(source, dest) {
8028
+ const absent = (e) => e?.code === "ENOENT" || e?.code === "ENOTDIR";
8029
+ let st;
8030
+ try { st = lstatSync(source); }
8031
+ catch (e) {
8032
+ if (absent(e)) return false;
8033
+ throw notCopiedAsFile(source, "an entry that cannot be read");
8034
+ }
8035
+ const link = st.isSymbolicLink();
8036
+ if (link) {
8037
+ try { st = statSync(source); }
8038
+ catch (e) {
8039
+ if (absent(e)) return false;
8040
+ throw notCopiedAsFile(source, "a link that cannot be followed");
8041
+ }
8042
+ }
8043
+ if (!st.isFile()) {
8044
+ const what = st.isDirectory() ? "a directory" : "an entry that is neither a file nor a directory";
8045
+ throw notCopiedAsFile(source, link ? `a link to ${what}` : what);
8046
+ }
8047
+ mkdirSync(Buffer.isBuffer(dest) ? parentOf(dest) : dirname(dest), { recursive: true });
8048
+ copyFileSync(source, dest);
8049
+ return true;
8050
+ }
8051
+ /** The copier's refusal of a path it copies as a file. `what`: one of the
8052
+ * words copyRegularFile has for what is there. */
8053
+ const notCopiedAsFile = (path, what) => new Error(`the recovery copies ${Buffer.isBuffer(path) ? path.toString("utf8") : path} as a file, and ${what} is there`);
8054
+
7562
8055
  function restoreStandaloneGitState(sourceWork, recoveredRepo) {
7563
8056
  const sourceGit = copierGitDir(sourceWork);
7564
8057
  const recoveredGit = join(recoveredRepo, ".git");
@@ -7576,8 +8069,12 @@ function restoreStandaloneGitState(sourceWork, recoveredRepo) {
7576
8069
  ];
7577
8070
  carryNamedObjects(sourceWork, recoveredRepo, { blobs });
7578
8071
  // The index is the selection's one exception (COPIED_GIT_PATHS): copied
7579
- // whole, compared by its entries, resolve-undo records and mode.
7580
- copyFileSync(join(sourceGit, "index"), join(recoveredGit, "index"));
8072
+ // whole, compared by its entries, resolve-undo records and mode. A tree
8073
+ // with no index file (`git worktree add --no-checkout`, the file removed)
8074
+ // is carried as one: the index the clone's checkout wrote is removed, so
8075
+ // that the copy reads to Git as the source does, every committed file a
8076
+ // staged deletion (awebai/oats#1048).
8077
+ if (!copyRegularFile(join(sourceGit, "index"), join(recoveredGit, "index"))) rmSync(join(recoveredGit, "index"), { force: true });
7581
8078
  for (const entry of COPIED_GIT_PATHS.filter((e) => e.dir === "git")) {
7582
8079
  const source = copiedGitPath(entry, sourceGit);
7583
8080
  if (!existsSync(source)) continue;
@@ -7633,12 +8130,7 @@ function carryStatusConfig(sourceWork, recoveredRepo) {
7633
8130
  }
7634
8131
  const common = copierCommonDir(sourceWork);
7635
8132
  const attributes = copiedGitPath(GIT_ATTRIBUTES, null, common);
7636
- if (existsSync(attributes)) {
7637
- const dest = copiedGitPath(GIT_ATTRIBUTES, null, join(recoveredRepo, ".git"));
7638
- mkdirSync(dirname(dest), { recursive: true });
7639
- copyFileSync(attributes, dest);
7640
- carried.push({ kind: "info/attributes", path: attributes });
7641
- }
8133
+ if (copyRegularFile(attributes, copiedGitPath(GIT_ATTRIBUTES, null, join(recoveredRepo, ".git")))) carried.push({ kind: "info/attributes", path: attributes });
7642
8134
  return carried;
7643
8135
  }
7644
8136
 
@@ -7656,17 +8148,22 @@ function detachRecoveryClone(source, recovered, commits = []) {
7656
8148
  named.push(stash);
7657
8149
  const sourceCommon = copierCommonDir(source);
7658
8150
  const stashLog = copiedGitPath(GIT_STASH_LOG, null, sourceCommon);
7659
- if (existsSync(stashLog)) {
7660
- const recoveredLog = copiedGitPath(GIT_STASH_LOG, null, join(recovered, ".git"));
7661
- mkdirSync(dirname(recoveredLog), { recursive: true });
7662
- copyFileSync(stashLog, recoveredLog);
7663
- named.push(...reflogCommits(recoveredLog));
7664
- }
8151
+ const recoveredLog = copiedGitPath(GIT_STASH_LOG, null, join(recovered, ".git"));
8152
+ if (copyRegularFile(stashLog, recoveredLog)) named.push(...reflogCommits(recoveredLog));
7665
8153
  }
7666
8154
  carryNamedObjects(source, recovered, { commits: named });
7667
8155
  try { retireGit(recovered, ["remote", "remove", "origin"]); } catch { /* no remote is already independent */ }
7668
8156
  }
7669
8157
 
8158
+ /** The commit at a repository's HEAD as the copier reads it, or null when
8159
+ * its HEAD has none: a branch nobody has committed on (`git init` and no
8160
+ * commit, `git switch --orphan`). Only Git's own quiet answer (exit 1) is
8161
+ * "none"; any other failure of the read throws. */
8162
+ function copierHeadCommit(repo) {
8163
+ try { return retireGit(repo, ["rev-parse", "--verify", "--quiet", "HEAD"], { encoding: "utf8" }).trim(); }
8164
+ catch (e) { if (e.status === 1) return null; throw e; }
8165
+ }
8166
+
7670
8167
  /** A path under a Git directory for a ref name read as bytes: a branch name
7671
8168
  * need not be UTF-8, and the file Git keeps for it is named by its bytes. */
7672
8169
  const gitPathOf = (dir, ...parts) => Buffer.concat([Buffer.from(`${dir}${sep}`), ...parts]);
@@ -7676,7 +8173,10 @@ const parentOf = (path) => path.subarray(0, path.lastIndexOf(sep.charCodeAt(0)))
7676
8173
  * for recovering work (awebai/oats#657): every local branch under its name at
7677
8174
  * its commit, HEAD on the source's branch when the source is on one (`name`:
7678
8175
  * headName) and detached at `head` otherwise, and the source's reflogs of
7679
- * HEAD and of each branch, copied over the clone's own. The branches are the
8176
+ * HEAD and of each branch, copied over the clone's own. `head` is null when
8177
+ * the source's HEAD has no commit (copierHeadCommit: `git init` and nothing
8178
+ * committed, `git switch --orphan`): the copy's HEAD is then put on the same
8179
+ * branch and checked to have no commit either. The branches are the
7680
8180
  * source's own `refs/heads`, not the clone's `refs/remotes/origin/*`: those
7681
8181
  * are only what the source advertises, and its configuration can hide a
7682
8182
  * branch from a clone (`uploadpack.hideRefs`). A tip the clone lacks is
@@ -7707,16 +8207,17 @@ function carryNestedRefs(source, dest, name, head) {
7707
8207
  if (!retireGit(dest, BRANCHES).equals(listing)) throw new Error(`nested recovery ${dest} does not have the local branches of its source`);
7708
8208
  if (name.branch !== null) retireGit(dest, ["symbolic-ref", "HEAD", `refs/heads/${name.branch}`]);
7709
8209
  else retireGit(dest, ["checkout", "--quiet", "--detach", head]);
7710
- const recovered = retireGit(dest, ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
7711
- if (recovered !== head) throw new Error(`nested recovery ${dest} is at ${recovered}, not at the commit ${head} its source has checked out`);
8210
+ const recovered = copierHeadCommit(dest);
8211
+ if (head === null) {
8212
+ // No commit to be at: the copy's HEAD names the source's branch, and has no commit either.
8213
+ if (recovered !== null) throw new Error(`nested recovery ${dest} is at ${recovered}, and the HEAD of its source has no commit`);
8214
+ if (!headName(dest).ref?.equals(name.ref)) throw new Error(`nested recovery ${dest} is not on the branch the HEAD of its source names`);
8215
+ } else if (recovered !== head) throw new Error(`nested recovery ${dest} is at ${recovered ?? "no commit"}, not at the commit ${head} its source has checked out`);
7712
8216
  // The reflogs last, so that nothing above writes to them after the copy.
7713
8217
  const named = [];
7714
8218
  const carryLog = (from, to) => {
7715
- if (existsSync(from)) {
7716
- mkdirSync(parentOf(to), { recursive: true });
7717
- copyFileSync(from, to);
7718
- named.push(...reflogCommits(to));
7719
- } else rmSync(to, { force: true });
8219
+ if (copyRegularFile(from, to)) named.push(...reflogCommits(to));
8220
+ else rmSync(to, { force: true });
7720
8221
  };
7721
8222
  const destGit = join(dest, ".git");
7722
8223
  carryLog(gitPathOf(copierGitDir(source), Buffer.from("logs/HEAD")), gitPathOf(destGit, Buffer.from("logs/HEAD")));
@@ -7742,7 +8243,10 @@ function materializeNestedRepositories(sourceWork, recoveredRepo) {
7742
8243
  const rel = relative(sourceWork, source);
7743
8244
  const dest = join(recoveredRepo, rel);
7744
8245
  const name = headName(source);
7745
- const head = retireGit(source, ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
8246
+ const head = copierHeadCommit(source);
8247
+ // No commit to detach the copy at, and no branch to put it on. What its
8248
+ // HEAD holds is not said: it is a file's content, and need not be text.
8249
+ if (head === null && name.branch === null) throw new Error(`nested repository ${source} has no commit at its HEAD, and its HEAD names no local branch`);
7746
8250
  rmSync(dest, { recursive: true, force: true });
7747
8251
  retireGit(null, ["clone", "--no-local", "--quiet", source, dest]);
7748
8252
  detachRecoveryClone(source, dest, carryNestedRefs(source, dest, name, head));
@@ -7827,13 +8331,16 @@ function copyRecoveryHome(observation, dest) {
7827
8331
  * source bytes are the observation's (observedWorkBytes), so the verified
7828
8332
  * value is also its byte state. → { copied, branchDrift?, excludes?,
7829
8333
  * statusConfig? }; `copied` is false where neither applies (another work
7830
- * mode, or a worktree home with no recorded repo or branch). A HEAD that
8334
+ * mode, a worktree home with no repo, or one whose worktree is gone and
8335
+ * whose record holds no branch). A HEAD that
7831
8336
  * cannot be read is an inspection failure, not a failed copy: its error is
7832
8337
  * put in `unreadableHeads`, and the callers throw it as it is. */
7833
8338
  const unreadableHeads = new WeakSet();
7834
8339
  function copyRecoveryWork(observation, meta, parent) {
7835
8340
  let branchDrift, excludes, statusConfig, copied = false;
7836
- if (meta.work === "worktree" && meta.repo && meta.branch && (existsSync(observation.work) || observation.branchExists)) {
8341
+ // A worktree that is there is copied from itself: only one that is gone needs the recorded
8342
+ // branch, to be copied from the repository. (An own tree whose record holds no branch, #962.)
8343
+ if (meta.work === "worktree" && meta.repo && (existsSync(observation.work) || (meta.branch && observation.branchExists))) {
7837
8344
  const recoveredRepo = join(parent, "repo");
7838
8345
  // The branch is derived from the worktree while it exists: an instance
7839
8346
  // that legitimately switched branches during its task must still be
@@ -7843,7 +8350,7 @@ function copyRecoveryWork(observation, meta, parent) {
7843
8350
  let ref;
7844
8351
  try { ref = existsSync(observation.work) ? worktreeHead(observation.work) : { branch: meta.branch, commit: null }; }
7845
8352
  catch (e) { unreadableHeads.add(e); throw e; }
7846
- if (ref.branch !== meta.branch) branchDrift = { recordedBranch: meta.branch, worktreeBranch: ref.branch, detachedAt: ref.branch === null ? ref.commit : null };
8353
+ if (meta.branch && ref.branch !== meta.branch) branchDrift = { recordedBranch: meta.branch, worktreeBranch: ref.branch, detachedAt: ref.branch === null ? ref.commit : null };
7847
8354
  if (ref.branch !== null) retireGit(null, ["clone", "--no-local", "--quiet", "--branch", ref.branch, meta.repo, recoveredRepo]);
7848
8355
  else {
7849
8356
  retireGit(null, ["clone", "--no-local", "--quiet", "--no-checkout", meta.repo, recoveredRepo]);
@@ -7922,8 +8429,7 @@ function homeOnlyRecovery(observation, meta) {
7922
8429
  if (observation.orphanedWork === true) return true;
7923
8430
  if (observation.workProvable === false) return false;
7924
8431
  if (!(observation.classes.length === 1 && observation.classes[0] === "changed instance-home bytes" && meta.work === "worktree" && existsSync(observation.work))) return false;
7925
- const gitDir = copierGitDir(observation.work);
7926
- return !RECOVERABLE_GIT_ADMIN.some((name) => existsSync(join(gitDir, name)));
8432
+ return !gitOperationInProgress(copierGitDir(observation.work), observation.work);
7927
8433
  }
7928
8434
 
7929
8435
  /** Remove a recovery's staging directory, after a copy that failed or that had
@@ -8119,8 +8625,14 @@ export function deferredRetireResultPath(home) {
8119
8625
  return join(dirname(home), `.oats-retired-${basename(home)}.json`);
8120
8626
  }
8121
8627
 
8628
+ /** What the detached completion of a self-retire runs. Its intent is its own input: it takes the
8629
+ * variable out of its environment once it has read it, before the retire runs anything, so that
8630
+ * nothing it starts (a retire hook, Git, the stop of a child) inherits it. A hook's environment
8631
+ * is this process's, with what the kernel adds (lifecycleHookEnv). */
8122
8632
  const DEFERRED_RETIRE_SCRIPT = `import { completeDeferredRetirement } from ${JSON.stringify(import.meta.url)};
8123
- process.exitCode = completeDeferredRetirement(JSON.parse(process.env.OATS_RETIRE_INTENT)) ? 0 : 1;`;
8633
+ const intent = process.env.OATS_RETIRE_INTENT;
8634
+ delete process.env.OATS_RETIRE_INTENT;
8635
+ process.exitCode = completeDeferredRetirement(JSON.parse(intent)) ? 0 : 1;`;
8124
8636
 
8125
8637
  /** Self-retire (aweb-abep): persist intent, then hand the retirement to a
8126
8638
  * detached process that runs it as an ORDINARY external retirement after the
@@ -8153,7 +8665,13 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8153
8665
  // The recorded children as they were when the retirement was scheduled: the completion stops them first.
8154
8666
  ...(Array.isArray(o.children) ? { children: o.children.map((c) => ({ instance: c.instance, home: c.home })) } : {}) }, resultPath,
8155
8667
  };
8156
- const env = { ...process.env, OATS_RETIRE_INTENT: JSON.stringify(intent) };
8668
+ // The completion is told who scheduled it: this process, by pid and by the start token its
8669
+ // holding of the home's claim records (lib/claim.mjs takes both from the same reading). It is
8670
+ // told in its environment and nowhere else: the marker's format is as it was, and the completion
8671
+ // compares the claim against what it was given, never against what it reads later beside the
8672
+ // home (completeDeferredRetirement).
8673
+ const requestedByStart = processStartToken(process.pid);
8674
+ const env = { ...process.env, OATS_RETIRE_INTENT: JSON.stringify({ ...intent, ...(requestedByStart ? { requestedByStart } : {}) }) };
8157
8675
  for (const k of CORE_LAUNCH_ENV) delete env[k];
8158
8676
  rmSync(resultPath, { force: true });
8159
8677
  const scheduleFailed = (why) => oatsError("E_SELF_RETIRE_SCHEDULE_FAILED", `could not start the deferred retirement of ${name}: ${why}. Nothing was inspected, run, or removed; the instance is still live and can be retired externally with \`oats retire ${name} --home ${found.home}\``);
@@ -8168,37 +8686,69 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8168
8686
  rmSync(logPath, { force: true });
8169
8687
  throw scheduleFailed(e.message);
8170
8688
  }
8171
- closeSync(fd);
8172
- if (!child.pid) { rmSync(logPath, { force: true }); throw scheduleFailed("no process was created"); }
8173
- // A spawn failure Node reports asynchronously (EAGAIN, EMFILE) would arrive
8174
- // after this returns; record it as a failed outcome so status shows the
8175
- // debt instead of an uncaught exception behind a success message.
8176
- child.on("error", (e) => {
8177
- try {
8178
- writeFileSync(resultPath, JSON.stringify({ instance: name, agent: found.agent.name, requestedAt: intent.requestedAt, completedAt: new Date().toISOString(), ok: false, error: { code: e.code, message: `the deferred retirement could not start: ${e.message}` }, retry: `oats retire ${name} --home ${found.home}` }, null, 2) + "\n");
8179
- } catch { /* the marker alone then shows RETIRING; status names its age */ }
8180
- });
8181
- child.unref();
8182
- // The marker names its completion (pid and start time; the start is null when it cannot be read):
8183
- // while that process lives, any other retire of this home is refused (refusePendingCompletion).
8184
- writeFileSync(marker, JSON.stringify({ ...intent, completionPid: child.pid, completionStart: processStartToken(child.pid) }, null, 2) + "\n");
8689
+ // From here a completion process may exist. It acts only once its delay has passed and this
8690
+ // retire has released the home's claim (completeDeferredRetirement), so whatever fails before the
8691
+ // marker is written ends it first, under the claim: the handle's own SIGKILL, never a pid looked
8692
+ // up. A scheduling that fails therefore leaves no completion behind, and "nothing was
8693
+ // inspected, run, or removed" stays true after this call has answered.
8694
+ let wroteMarker = false;
8695
+ try {
8696
+ closeSync(fd);
8697
+ if (!child.pid) throw scheduleFailed("no process was created");
8698
+ // A spawn failure Node reports asynchronously (EAGAIN, EMFILE) would arrive
8699
+ // after this returns; record it as a failed outcome so status shows the
8700
+ // debt instead of an uncaught exception behind a success message.
8701
+ child.on("error", (e) => {
8702
+ try {
8703
+ writeFileSync(resultPath, JSON.stringify({ instance: name, agent: found.agent.name, requestedAt: intent.requestedAt, completedAt: new Date().toISOString(), ok: false, error: { code: kernelCode(e, "E_SELF_RETIRE_SCHEDULE_FAILED"), message: `the deferred retirement could not start: ${e.message}` }, retry: `oats retire ${name} --home ${found.home}` }, null, 2) + "\n");
8704
+ } catch { /* the marker alone then shows RETIRING; status names its age */ }
8705
+ });
8706
+ child.unref();
8707
+ // The marker names its completion (pid and start time; the start is null when it cannot be read):
8708
+ // while that process lives, any other retire of this home is refused (refusePendingCompletion).
8709
+ const completionStart = processStartToken(child.pid);
8710
+ writeFileSync(marker, JSON.stringify({ ...intent, completionPid: child.pid, completionStart }, null, 2) + "\n");
8711
+ wroteMarker = true;
8712
+ // The marker promises a completion that is on its way. One that has ended by now is not: it
8713
+ // looked for its marker before this call wrote one, and nothing would ever remove it. So the
8714
+ // scheduling failed. A completion does not start its retire while it reads the claim as this
8715
+ // call's, alive (completeDeferredRetirement). So one that has ended by now either did not read
8716
+ // it so (this call's liveness could not be read, and its retire answered for that) and left
8717
+ // its outcome at `resultPath` (this call removed any earlier one before it started it), or
8718
+ // left none: it was killed, or could not write it. Gone is what the kernel reads of a holder
8719
+ // that died (processLiveness); a completion whose liveness cannot be read is not gone, and is
8720
+ // scheduled.
8721
+ if (existsSync(resultPath)) throw scheduleFailed("its completion gave up waiting for this command and has ended");
8722
+ if (processLiveness({ pid: child.pid, processStart: completionStart }).state === "gone") throw scheduleFailed("its completion has ended and left no outcome");
8723
+ } catch (e) {
8724
+ // No outcome is recorded for a completion this call ends itself: the answer below is the outcome.
8725
+ child.removeAllListeners("error");
8726
+ child.on("error", () => {});
8727
+ if (child.pid) { try { child.kill("SIGKILL"); } catch { /* it never ran */ } }
8728
+ // Its log, and the outcome it may have recorded: a completion kept waiting for this retire's
8729
+ // claim past its own patience gives up and says so there, before the kill reaches it. Both
8730
+ // paths are this retire's own (it removed any earlier result before it started the completion),
8731
+ // so what is removed here can only be that completion's.
8732
+ // Not closed: Node cannot wait for a child synchronously, so a kill that lands inside the
8733
+ // completion's own write of that outcome could leave a result after this removal. It would say
8734
+ // E_LIFECYCLE_BUSY of a retire that has since answered, and a later `oats retire` removes it.
8735
+ // And the marker, when this call wrote it: it names a completion that is not running.
8736
+ for (const left of [logPath, resultPath, ...(wroteMarker ? [marker] : [])]) { try { rmSync(left, { force: true }); } catch { /* none is a debt of the instance */ } }
8737
+ // "is not running": killed here, or gone by itself before the kill.
8738
+ throw e?.code === "E_SELF_RETIRE_SCHEDULE_FAILED" ? e : scheduleFailed(`${e?.message ?? e}; the completion this command had started is not running`);
8739
+ }
8185
8740
  return {
8186
8741
  retired: name, agent: found.agent.name, deferred: true, pendingMarker: marker,
8187
8742
  resultPath, logPath, completesInSec: delaySec, completionPid: child.pid,
8188
8743
  };
8189
8744
  }
8190
8745
 
8191
- /** Run by the detached child: wait for the caller's window to be gone, then
8192
- * retire the instance as an ordinary external operator. Returns true only
8193
- * when the home is actually gone, and then leaves no file behind. A failure
8194
- * writes an explicit outcome beside the home and leaves the pending marker
8195
- * (and, after hooks ran, the usual quarantine) in place, so `oats status`
8196
- * shows the debt and `oats retire <name>` retries and clears it. Accepts the
8197
- * intent object (the child gets it in its env) or a marker path. */
8198
8746
  /** The item a quarantine retry reports while the branch its failed spawn created is still there. It
8199
8747
  * names no branch: the name is the receipt's `retention.recordedBranch`, or the retained home's
8200
8748
  * instance.json `branch`. */
8201
8749
  export const FAILED_SPAWN_BRANCH_LEFT = "the branch the failed spawn created is left: OATS does not delete it. Inspect it and delete it with Git if it is not wanted, then retry";
8750
+ /** What a `retire-refused` event says of a completion whose cleanup did not finish. It names no item. */
8751
+ const RETIRE_INCOMPLETE_SENTENCE = (instance) => `the retirement of ${instance} is incomplete: its cleanup did not finish, and the home is retained`;
8202
8752
  const OBSOLETE_DELETE_BRANCH_SENTENCE = "this self-retire was requested with --delete-branch by an older OATS; retirement no longer deletes branches, so the branch and the worktree were left";
8203
8753
  /** The one internal option that says the retirement completes such an intent.
8204
8754
  * A symbol, so no caller can set it from parsed arguments or JSON. */
@@ -8206,8 +8756,29 @@ const OBSOLETE_DELETE_BRANCH = Symbol("an older self-retire intent with --delete
8206
8756
  /** The one internal option that says the retirement is a deferred self-retire's completion
8207
8757
  * (completeDeferredRetirement). A symbol, so no caller can set it from parsed arguments or JSON. */
8208
8758
  const COMPLETES_DEFERRED = Symbol("the completion of a deferred self-retire");
8759
+ /** How long a self-retire's completion waits for the retire that scheduled it to release the
8760
+ * home's claim before it goes on without it (completeDeferredRetirement). Long beside the wait of
8761
+ * a retire for any other holder (CLAIM_WAIT_MS, lib/claim.mjs): the scheduling is this
8762
+ * completion's own, and what it is waited for is a few file writes on a host that may be slow. */
8763
+ export const SCHEDULING_WAIT_MS = 10 * 60 * 1000;
8764
+ /** How long a completion pauses between two looks at the claim its scheduling still holds. */
8765
+ const SCHEDULING_PAUSE_MS = 50;
8209
8766
  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.";
8210
8767
 
8768
+ /** Run by the detached child: wait for the caller's window to be gone, then
8769
+ * retire the instance as an ordinary external operator. Returns true only
8770
+ * when the home is actually gone, and then leaves no file behind. Accepts the
8771
+ * intent object (the child gets it in its env) or a marker path.
8772
+ *
8773
+ * A completion that does not complete (the retire threw, or its cleanup is incomplete) says so,
8774
+ * since nobody is at a terminal to read its answer (awebai/oats#954). It leaves its outcome beside
8775
+ * the home, which `oats status` lists and `oats retire <name>` retries and clears, and one
8776
+ * `retire-refused` event. Its pending marker follows how far the retire got: it stays when a retire
8777
+ * hook was started or the removal of the home began, because the home is then owed a retire (after
8778
+ * hooks ran, the usual quarantine stays too); otherwise it goes, and the instance is a stopped or
8779
+ * running instance like any other, not one that reads RETIRING for a retire that is not happening.
8780
+ * How far the retire got is read from what it answers (`details.reached`, retireFailure), never
8781
+ * from its code. */
8211
8782
  export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8212
8783
  let intent = intentOrMarkerPath;
8213
8784
  if (typeof intentOrMarkerPath === "string") {
@@ -8230,6 +8801,68 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8230
8801
  const obsoleteDeleteBranch = intent.options?.deleteBranch === true;
8231
8802
  const delayMs = Math.max(0, Number(opts.delaySec ?? intent.delaySec ?? 8) * 1000);
8232
8803
  if (delayMs) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delayMs);
8804
+ // The home this completion answers for is the one its intent names, as every scheduling records
8805
+ // it. For an intent that names none the retire finds the instance by its name, and the
8806
+ // completion touches no marker and writes no event: a name can stand for more than one home.
8807
+ const home = typeof intent.options?.home === "string" && intent.options.home ? intent.options.home : null;
8808
+ // The retire that scheduled this completion writes the pending marker last, under the home's
8809
+ // claim. Until it has released that claim the completion does not start its retire: it would be
8810
+ // refused by its own scheduling for nothing but slowness, and would look for a marker that is
8811
+ // not written yet. So it waits here, for exactly one reading of the claim: its holder is the
8812
+ // command that scheduled this completion, by pid AND by recorded start, and reads as alive.
8813
+ // Who that command is comes from the intent this process was started with, and from nothing it
8814
+ // reads later: the claim is only compared against it. An intent that does not say both (a marker
8815
+ // the completion is run from, an older kernel's, a start that could not be read) waits for
8816
+ // nobody. Every other reading is not waited for, and the retire below answers it as for every
8817
+ // retire: that holder gone (taken over), its liveness unreadable, another holder in any state, a
8818
+ // file that is no claim, no claim.
8819
+ // The wait ends when the scheduling does: it returned (the marker is written by then), it failed
8820
+ // (and ended this completion itself), or it died. It also ends at its bound (SCHEDULING_WAIT_MS;
8821
+ // `opts.schedulingWaitMs` for a test), and nothing is decided there: the completion goes on to
8822
+ // the retire below, which waits and answers for a holder that is still there as for every
8823
+ // retire. A scheduling that comes back after that finds its completion's outcome, or a
8824
+ // completion that is gone, and has failed (scheduleDeferredSelfRetirement).
8825
+ const scheduledBy = Number.isSafeInteger(intent.requestedByPid) && isStartToken(intent.requestedByStart) ? { pid: intent.requestedByPid, start: intent.requestedByStart } : null;
8826
+ const schedulingHoldsClaim = () => {
8827
+ const held = home && scheduledBy ? homeClaimHolder(home) : null;
8828
+ return held !== null && held.holder.pid === scheduledBy.pid && held.holder.processStart === scheduledBy.start && held.state === "alive";
8829
+ };
8830
+ for (const until = Date.now() + (opts.schedulingWaitMs ?? SCHEDULING_WAIT_MS); schedulingHoldsClaim() && Date.now() < until;) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, SCHEDULING_PAUSE_MS);
8831
+ // Read before the retire runs: instance.json may be gone when the event is written.
8832
+ const incarnation = home ? incarnationOf(home) : null;
8833
+ /** Remove the pending marker, and only this completion's own: the one of the scheduling it
8834
+ * completes (the same `requestedAt`), whose named completion is absent (an older kernel's
8835
+ * marker), this process, or a process that is verifiably gone (a completion run from the marker
8836
+ * for a scheduling whose own completion died). A marker a later `--self` wrote, one that names
8837
+ * a process that runs or whose liveness cannot be read, and one that cannot be read are left.
8838
+ * The retire has released the home's claim by now, so a `--self` that lands between this read
8839
+ * and the removal loses its marker until its own completion runs; that completion still runs,
8840
+ * under the claim. → whether it removed one. */
8841
+ const removeOwnMarker = () => {
8842
+ if (!home) return false;
8843
+ const path = retirePendingMarkerPath(home), marker = readJsonOrUndefined(path);
8844
+ if (!isPlainObject(marker) || typeof intent.requestedAt !== "string" || marker.requestedAt !== intent.requestedAt) return false;
8845
+ const pid = marker.completionPid;
8846
+ if (Number.isSafeInteger(pid) && pid !== process.pid && processLiveness({ pid, processStart: marker.completionStart }).state !== "gone") return false;
8847
+ try { rmSync(path); return true; }
8848
+ catch (e) { if (e?.code !== "ENOENT") console.error(`deferred retirement: cannot remove ${path}: ${e.message}`); return false; }
8849
+ };
8850
+ /** The one way out of a completion that did not complete → false. `payload` is its outcome as
8851
+ * the result file takes it; `homeChanged` is false when no retire hook was started and nothing
8852
+ * of the home was removed. In this order: the outcome is written before the marker goes, since
8853
+ * a second `--self` reads a marker without an outcome as "already scheduled"; the event is
8854
+ * last, and evidence only, so one that cannot be written is said in the log and nothing else
8855
+ * changes. The row goes to the workspace's log alone, whatever `homeChanged` is: the
8856
+ * completion holds no claim here, and another retire may be inspecting or removing the home,
8857
+ * so it writes nothing into it. */
8858
+ const notCompleted = (payload, { code, homeChanged, sentence }) => {
8859
+ record(payload);
8860
+ if (!homeChanged && removeOwnMarker()) console.error(`deferred retirement of ${intent.instance}: no retire hook was started and nothing of the home was removed, so its pending marker is removed; ${intent.instance} is not being retired`);
8861
+ if (!home) { console.error(`deferred retirement of ${intent.instance}: no retire-refused event was recorded: its intent names no home`); return false; }
8862
+ const written = appendEvent(home, { kind: "retire-refused", data: { code, homeChanged, reason: retireRefusedReason(sentence) } }, { workspaceOnly: true, incarnation });
8863
+ 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("; ")}`);
8864
+ return false;
8865
+ };
8233
8866
  let result;
8234
8867
  try {
8235
8868
  result = retireInstance(intent.root, intent.instance, {
@@ -8237,19 +8870,30 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8237
8870
  ...(Array.isArray(intent.options?.plannedExtraWorktrees) ? { plannedExtraWorktrees: intent.options.plannedExtraWorktrees } : {}),
8238
8871
  ...(Array.isArray(intent.options?.children) ? { children: intent.options.children } : {}),
8239
8872
  ...(obsoleteDeleteBranch ? { [OBSOLETE_DELETE_BRANCH]: true } : {}),
8240
- // The retire that scheduled this completion may still hold the home's claim, about to write
8241
- // the marker and return: it is waited for, so the two are ordered by the claim and never by
8242
- // which process is faster.
8873
+ // The retire that scheduled this completion was waited for above. Any other live holder of
8874
+ // the claim is waited for by the retire itself, for the time a completion's retire has
8875
+ // always waited, and then answers as for every retire.
8243
8876
  [COMPLETES_DEFERRED]: true,
8244
8877
  });
8245
8878
  } catch (e) {
8246
- record({ ok: false, error: { code: e.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}` : ""}` });
8879
+ const code = kernelCode(e, "E_LIFECYCLE_FAILED");
8880
+ // An answer without `reached` is one in which the retire of the home had not begun (retireInstance).
8881
+ const reached = e?.details?.reached;
8882
+ const homeChanged = isPlainObject(reached) && (reached.hooksStarted === true || reached.home !== "kept");
8883
+ 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}` : ""}` },
8884
+ { code, homeChanged, sentence: e.message });
8247
8885
  console.error(`deferred retirement of ${intent.instance} failed: ${e.message}`);
8886
+ // A defect's stack goes to the completion's log (lib/errors.mjs isDefect).
8887
+ reportDefect(e);
8248
8888
  return false;
8249
8889
  }
8250
8890
  if (obsoleteDeleteBranch) console.log(OBSOLETE_DELETE_BRANCH_SENTENCE);
8251
8891
  if (result.rollbackIncomplete) {
8252
- record({ ok: false, result, retry: `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}` });
8892
+ // A result and not an error, so it has no code. The retire worked on the home and left it
8893
+ // quarantined: the home is changed. The items are text of hooks and of Git, which the outcome
8894
+ // and the log hold and the event does not.
8895
+ notCompleted({ ok: false, result, retry: `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}` },
8896
+ { code: null, homeChanged: true, sentence: RETIRE_INCOMPLETE_SENTENCE(intent.instance) });
8253
8897
  console.error(`deferred retirement of ${intent.instance} is INCOMPLETE; the home is retained:\n ${result.rollbackIncomplete.join("\n ")}`);
8254
8898
  return false;
8255
8899
  }
@@ -8284,47 +8928,197 @@ export const RETIRE_UNDER_CLAIM = Symbol("oats.retireUnderClaim");
8284
8928
  * claim of the first (that one removed, a same-named home of another agent made, in between). */
8285
8929
  const RETIRE_CLAIM_RESTARTS = 2;
8286
8930
 
8287
- /** The claim file of a retire of `home`: `<instances>/.oats-retirement/claims/<name>.lock`. Beside
8288
- * the homes, never inside one: a home's bytes are what its retire observes, copies and removes. */
8289
- function retireClaimPath(home) {
8931
+ /** The lifecycle claim file of `home`: `<instances>/.oats-retirement/claims/<name>.lock`. Beside
8932
+ * the homes, never inside one: a home's bytes are what its retire observes, copies and removes.
8933
+ * One file for every verb that holds a home (a retire, a stop): its record names the holder's
8934
+ * verb (`action`) from the instant it exists (lib/claim.mjs `facts`). */
8935
+ export function retireClaimPath(home) {
8290
8936
  return join(instancesRetirementRoot(dirname(home)), "claims", `${basename(home)}.lock`);
8291
8937
  }
8292
8938
 
8293
- /** The refusals of a retire of `name` (home `home`) that cannot take its claim `lock`, as
8294
- * lib/claim.mjs asks for them. All E_LIFECYCLE_BUSY, one line, saying that nothing was done;
8295
- * `details.lock` is the file that names the holder. */
8296
- function retireClaimRefusals(name, home, lock) {
8297
- const refuse = (message, details) => Object.assign(oatsError("E_LIFECYCLE_BUSY", message), { details: { instance: name, home, ...details } });
8939
+ /** The verbs that take a home's lifecycle claim: what claimHomeFor accepts, and so every `action`
8940
+ * a claim of the kernel's names. */
8941
+ const CLAIM_VERBS = Object.freeze(["retire", "stop"]);
8942
+ /** The verb the holder of a home's claim recorded (`action`): one of CLAIM_VERBS, never the
8943
+ * record's text. A claim is read back as whatever is in its file, which other instances of the
8944
+ * deployment can write, and this goes into messages, remedies and `details` (lib/claim.mjs
8945
+ * shownHolder, the same rule for the holder's own fields). Anything else is a retire's, as a
8946
+ * record without one is: a kernel before feature `lifecycle-claim-stop` wrote none, and only its
8947
+ * retire took the claim. */
8948
+ const claimAction = (holder) => CLAIM_VERBS.includes(holder?.action) ? holder.action : "retire";
8949
+ /** The command that takes a home's claim for `action`, as a person types it. */
8950
+ const claimCommand = (action) => action === "stop" ? "oats instance stop" : `oats ${action}`;
8951
+ /** What each verb that meets a held claim says it did not do: the words its refusals end with,
8952
+ * before any effect. After a takeover ended a dead holder's step, every verb says the same
8953
+ * (lib/errors.mjs nothingAfter). */
8954
+ const CLAIM_NOTHING = { retire: "nothing was done", stop: "nothing was stopped", "worktree add": "no tree was made" };
8955
+
8956
+ /** The refusals of `arriving` ("retire", "stop", or "worktree add", which reads the claim and does
8957
+ * not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
8958
+ * for them: one builder for every pair (arriving verb, holder's verb), so that the pair table of
8959
+ * docs/desktop-cli-api.md has one source. One line each, saying what was not done, once.
8960
+ * - A live holder: E_INSTANCE_RETIRING when the holder is a retire and the arriving verb is not
8961
+ * one (the instance is on its way out: waiting does not make the stop or the tree possible);
8962
+ * E_LIFECYCLE_BUSY otherwise, `holder: "running"`. Live is what was established of the pid
8963
+ * and its start, not that the process is that command: both name, after the dash, the check
8964
+ * for a holder that does not end (lib/errors.mjs ifItDoesNotEnd), the second after the wait.
8965
+ * - A holder whose liveness cannot be read: E_LIFECYCLE_BUSY, `holder: "unknown"`, whatever the
8966
+ * two verbs are, with that same check as its step (checkHolderByHand).
8967
+ * `details` is `{ instance, home, lock, pid, since, action }`: `lock` is the file that names the
8968
+ * holder, `action` the HOLDER's verb (claimAction). The holder is named as lib/claim.mjs
8969
+ * shownHolder allows, in the message and in `details` alike: `pid` and `since` are null, and the
8970
+ * message says `?` or `none`, for a field that does not have the shape the kernel writes.
8971
+ * `ended`, the last argument of each, is what the claim's takeovers ended before the refusal
8972
+ * (lib/claim.mjs). With some, the sentence says "nothing else was done" and the answer is
8973
+ * E_LIFECYCLE_FAILED, what was ended first (lib/errors.mjs afterEndedSteps), with these details. */
8974
+ export function lifecycleClaimRefusals(arriving, name, home, lock) {
8975
+ const nothing = (ended) => nothingAfter(ended, CLAIM_NOTHING[arriving]);
8976
+ const own = { instance: name, home };
8977
+ const holders = "oats retire or oats instance stop";
8978
+ // The holder of `at`, as an answer names it: `shown` for the message, `details` beside it.
8979
+ const held = (holder, at) => {
8980
+ const shown = shownHolder(holder), action = claimAction(holder);
8981
+ return { shown, action, details: { ...own, lock: at, pid: shown.pid, since: shown.since, action } };
8982
+ };
8298
8983
  return {
8299
- busy: (holder, unknown, at = lock) => {
8300
- const details = { lock: at, pid: holder?.pid ?? null, since: holder?.at ?? null };
8301
- return unknown
8302
- ? refuse(`whether the retire of ${name} that holds ${at} (pid ${holder?.pid ?? "?"}, recorded start ${holder?.processStart ?? "none"}) still runs cannot be read (${unknown}); nothing was done — check that pid by hand, and if it is not an oats retire, remove ${at}, then retry`, { ...details, unknown })
8303
- : refuse(`a retire of ${name} is already running (pid ${holder?.pid ?? "?"}, since ${holder?.at ?? "?"}); nothing was done — wait for it to finish`, details);
8984
+ busy: (holder, unknown, at = lock, ended = []) => {
8985
+ const { shown, action, details } = held(holder, at);
8986
+ const command = `an ${claimCommand(action)}`;
8987
+ if (unknown) return lifecycleBusy("unknown", `whether the ${action} of ${name} that holds ${at} (pid ${shown.pid ?? "?"}, recorded start ${shown.start ?? "none"}) still runs cannot be read (${unknown}); ${nothing(ended)}`,
8988
+ checkHolderByHand(command, at), { ...details, unknown }, ended);
8989
+ // Alive is all that was established of the pid, never that it is that command: both
8990
+ // answers below name the check for a holder that does not end. A retire's holder is not
8991
+ // waited for by a verb that is not one (the instance is on its way out).
8992
+ if (action === "retire" && arriving !== "retire") return afterEndedSteps(ended, Object.assign(oatsError("E_INSTANCE_RETIRING", `${name} is being retired (pid ${shown.pid ?? "?"}, since ${shown.since ?? "?"}); ${nothing(ended)} — ${ifItDoesNotEnd(command, at)}`), { details }));
8993
+ return lifecycleBusy("running", `a ${action} of ${name} is already running (pid ${shown.pid ?? "?"}, since ${shown.since ?? "?"}); ${nothing(ended)}`, `wait for it to finish; ${ifItDoesNotEnd(command, at)}`, details, ended);
8304
8994
  },
8305
- ownStartUnreadable: (reason, at) => refuse(`this process's start time cannot be read (${reason}), so oats retire cannot hold ${at} verifiably; nothing was done`, { lock: at }),
8306
- unreadableClaim: (at) => refuse(`${at} is not a readable claim; inspect it and remove it if no oats retire holds it; nothing was done`, { lock: at }),
8995
+ // Nobody is running in the four below, so never the sentence above that says to wait
8996
+ // (awebai/oats#874). The first sends nobody to a pid of this process, which is gone when the
8997
+ // answer is read: its remedy is a check in the reader's own shell (the reason names the read
8998
+ // that failed, as the reader made it).
8999
+ ownStartUnreadable: (reason, at, ended = []) => lifecycleBusy("none", `this process's start time cannot be read (${reason}), so ${claimCommand(arriving)} cannot hold ${at} verifiably; ${nothing(ended)}`,
9000
+ OWN_START_REMEDY, { ...own, lock: at }, ended),
9001
+ unreadableClaim: (at, ended = []) => lifecycleBusy("unknown", `${at} is not a readable claim; ${nothing(ended)}`, `inspect it and remove it if no ${holders} holds it, then retry`, { ...own, lock: at }, ended),
9002
+ cannotTakeOver: (holder, at, why, ended = []) => lifecycleBusy("none", `the process that held ${at} (pid ${held(holder, at).shown.pid ?? "?"}) is gone, and this file is not a claim this kernel can take over (${why}); ${nothing(ended)}`,
9003
+ `inspect ${at} and remove it if no ${holders} holds it, then retry`, held(holder, at).details, ended),
9004
+ // Nothing is wrong with the file: each command that took the claim died, and this one came
9005
+ // after each of them. The next run takes over the one that is there.
9006
+ heldAgain: (holder, at, times, ended = []) => lifecycleBusy("none", `the claim ${at} was found without a live holder ${times} times and was taken again each time, the last time by a process that is gone (pid ${held(holder, at).shown.pid ?? "?"}); ${nothing(ended)}`,
9007
+ "run the command again", held(holder, at).details, ended),
8307
9008
  };
8308
9009
  }
9010
+ /** The refusals of a retire of `name` that cannot take its claim `lock` (lifecycleClaimRefusals).
9011
+ * Exported for its tests. */
9012
+ export function retireClaimRefusals(name, home, lock) {
9013
+ return lifecycleClaimRefusals("retire", name, home, lock);
9014
+ }
9015
+
9016
+ /** An option of claimHomeFor: when the claim cannot be WRITTEN, read it in its place, and answer
9017
+ * that nobody holds it when nobody does. Passed by a stop apply and by no other caller (a
9018
+ * retire, a retire's stop of a recorded child and every later verb need the claim): a stop is
9019
+ * what an operator reaches for when a disk is full, and a stop that leaves a session running
9020
+ * because it could not write a file protects nobody. A symbol, so no caller can set it from
9021
+ * parsed arguments or JSON. */
9022
+ export const READ_CLAIM_WHEN_UNWRITABLE = Symbol("oats.readClaimWhenUnwritable");
9023
+
9024
+ /** Take the lifecycle claim of `home` for `verb` ("retire", "stop") → the holding, for
9025
+ * releaseHomeClaim. The one way a verb takes it: the record carries the verb from the instant the
9026
+ * file exists, and a holder of any verb is refused at once (`waitMs: 0`; only a deferred
9027
+ * self-retire's completion waits, for the retire that scheduled it). The claim's directory is
9028
+ * made as retire makes it for its recovery copies; the claims are private. A directory that
9029
+ * cannot be made is a claim that cannot be taken: nothing was done (awebai/oats#874).
9030
+ *
9031
+ * → `{ lock, me }`, the holding. With READ_CLAIM_WHEN_UNWRITABLE, also
9032
+ * → `{ lock, me: null, unwritable, look }` (awebai/oats#946): the claim could not be written,
9033
+ * for the system's code `unwritable` (lib/claim.mjs CLAIM_UNWRITABLE_CODES) at one of its
9034
+ * writes, and it was read where it would have been taken: nobody holds it. Nothing is held,
9035
+ * so nothing excludes a command that takes the claim later; `look()` makes the same read
9036
+ * again and throws what it throws. A holder, or a file that is no claim, is refused as when
9037
+ * the claim can be written, by the same builder; a read that does not reach the path throws
9038
+ * the refusal of the write, as without the option (lib/claim.mjs claimUnheld).
9039
+ * What decides is the place of the failure and the system's code as it was thrown there
9040
+ * (claimWrite, unwritableCode): never the code, the words or the details of an answer. */
9041
+ export function claimHomeFor(verb, name, home, { waitMs = 0, [READ_CLAIM_WHEN_UNWRITABLE]: readInstead = false } = {}) {
9042
+ if (!CLAIM_VERBS.includes(verb)) throw new TypeError(`claimHomeFor: ${JSON.stringify(verb)} is not a verb that takes a home's claim (${CLAIM_VERBS.join(", ")})`);
9043
+ const lock = retireClaimPath(home);
9044
+ const refusals = lifecycleClaimRefusals(verb, name, home, lock);
9045
+ try {
9046
+ try {
9047
+ claimWrite(() => mkdirSync(instancesRetirementRoot(dirname(home)), { recursive: true }));
9048
+ claimWrite(() => mkdirSync(dirname(lock), { recursive: true, mode: 0o700 }));
9049
+ } catch (e) { throw claimUnavailable(lock, e); }
9050
+ return { lock, me: acquireClaim(lock, { ...refusals, facts: { action: verb }, waitMs }) };
9051
+ } catch (refusal) {
9052
+ const unwritable = readInstead ? unwritableCode(refusal) : undefined;
9053
+ if (!unwritable) throw refusal;
9054
+ const look = () => claimUnheld(lock, refusals, refusal);
9055
+ look();
9056
+ return { lock, me: null, unwritable, look };
9057
+ }
9058
+ }
9059
+ /** Release a holding of claimHomeFor, only while its file still names it. A claim that was only
9060
+ * read (READ_CLAIM_WHEN_UNWRITABLE) holds nothing to release. */
9061
+ export function releaseHomeClaim(holding) {
9062
+ if (holding.me) releaseClaim(holding.lock, holding.me);
9063
+ }
9064
+ /** Who holds the lifecycle claim of `home` now, read and not taken → `{ lock, holder, action,
9065
+ * state, reason? }` (`state` is processLiveness's: "alive", "unknown" with its `reason`, "gone"),
9066
+ * or null when there is no claim or the file does not read as one. For the readers that do not
9067
+ * take the claim: a stop plan's `retiring` and `stopPending`, and `oats worktree add`. */
9068
+ export function homeClaimHolder(home) {
9069
+ const lock = retireClaimPath(home);
9070
+ const holder = readClaim(lock);
9071
+ if (!holder || holder.unreadable) return null;
9072
+ const live = processLiveness(holder);
9073
+ return { lock, holder, action: claimAction(holder), state: live.state, ...(live.reason ? { reason: live.reason } : {}) };
9074
+ }
9075
+ /** Whether the claim path `lock` holds something that is no claim anybody can read: a file that
9076
+ * does not parse as one, or a path that is there and never reads (a dangling symbolic link, which
9077
+ * reads as absent: lib/claim.mjs readClaim). A verb that TAKES the claim learns the second from
9078
+ * its link, which says the path exists (takeClaim); a verb that only reads asks the path itself.
9079
+ * A claim made between the two reads here is read again, and is a claim. */
9080
+ function claimPathUnreadable(lock) {
9081
+ const read = readClaim(lock);
9082
+ if (read) return read.unreadable === true;
9083
+ let entry;
9084
+ try { entry = lstatSync(lock); } catch (e) { return e?.code !== "ENOENT"; }
9085
+ return entry.isSymbolicLink() ? readClaim(lock) === null : readClaim(lock)?.unreadable === true;
9086
+ }
9087
+ /** Refuse `arriving` ("worktree add"), a verb that reads the lifecycle claim of `home` and does
9088
+ * not take it, when a retire holds it: E_INSTANCE_RETIRING beside a live one, E_LIFECYCLE_BUSY
9089
+ * (`holder: "unknown"`) beside one whose liveness cannot be read, and beside a file that does not
9090
+ * read as a claim, with the words a stop and a retire have for that file: one file has one
9091
+ * reading, and this verb makes a tree in a home that may be going away. Nothing refuses for a
9092
+ * holder that is gone (whoever takes the claim next takes it over) or for a stop (a tree does
9093
+ * not depend on the session). */
9094
+ export function refuseBesideRetire(arriving, home) {
9095
+ const lock = retireClaimPath(home);
9096
+ const refusals = lifecycleClaimRefusals(arriving, basename(home), home, lock);
9097
+ if (claimPathUnreadable(lock)) throw refusals.unreadableClaim(lock);
9098
+ const held = homeClaimHolder(home);
9099
+ if (!held || held.action !== "retire" || held.state === "gone") return;
9100
+ throw refusals.busy(held.holder, held.state === "unknown" ? held.reason : null);
9101
+ }
8309
9102
 
8310
9103
  /** The homes `name` resolves to under `root`, and the one a retire acts on. Names are unique per
8311
9104
  * agent dir only: two agents can own an instance of the same name (dev --purpose foo-1 and agent
8312
9105
  * dev-foo). Retirement is destructive, so a name that resolves to several homes is refused unless
8313
9106
  * the caller says which home (--home), and a home is accepted only when it is one of that name's
8314
- * homes under this root. */
9107
+ * homes under this root. A home whose record is there and cannot be read is refused here
9108
+ * (identifiedHomeRecord), `--force` or not: before the claim, and again under it. */
8315
9109
  function resolveRetireHome(root, name, o) {
8316
9110
  const matches = findInstanceHomes(root, name);
8317
9111
  if (!matches.length) throw oatsError("E_SESSION_UNKNOWN", `no instance named "${name}"`);
8318
9112
  const sameHome = (a, b) => { try { return realpathSync(a) === realpathSync(b); } catch { return resolve(a) === resolve(b); } };
9113
+ let found = matches[0];
8319
9114
  if (o.home) {
8320
- const found = matches.find((m) => sameHome(m.home, o.home));
9115
+ found = matches.find((m) => sameHome(m.home, o.home));
8321
9116
  if (!found) throw oatsError("E_HOME_MISMATCH", `instance "${name}" has no home at ${o.home} under this agents root (its home${matches.length === 1 ? " is" : "s are"} ${matches.map((m) => m.home).join(", ")})`);
8322
- return found;
8323
- }
8324
- if (matches.length > 1) {
9117
+ } else if (matches.length > 1) {
8325
9118
  throw oatsError("E_AMBIGUOUS_INSTANCE", `"${name}" names ${matches.length} instances under this agents root (${matches.map((m) => `${m.agent.name}: ${m.home}`).join("; ")}); retire with --home <path> to say which`);
8326
9119
  }
8327
- return matches[0];
9120
+ identifiedHomeRecord(found.home);
9121
+ return found;
8328
9122
  }
8329
9123
 
8330
9124
  /** `name` has no home under `root`: remove a retire claim of that name whose holder is gone, in
@@ -8357,9 +9151,10 @@ function refusePendingCompletion(name, home) {
8357
9151
  const live = processLiveness({ pid, processStart: pending.completionStart });
8358
9152
  if (live.state === "gone") return;
8359
9153
  const start = typeof pending.completionStart === "string" ? pending.completionStart : "none";
8360
- const details = { instance: name, home, lock: marker, pid, since: pending.requestedAt ?? null };
8361
- if (live.state === "alive") throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `a retire of ${name} is already scheduled (its completion, pid ${pid}, requested at ${pending.requestedAt ?? "?"}); nothing was done — wait for it to finish`), { details });
8362
- throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `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 — check that pid by hand, and if it is not an oats retire, remove ${marker}, then retry`), { details: { ...details, unknown: live.reason } });
9154
+ const details = { instance: name, home, lock: marker, pid, since: pending.requestedAt ?? null, action: "retire" };
9155
+ 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);
9156
+ 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`,
9157
+ `check that pid by hand, and if it is not an oats retire, remove ${marker}, then retry`, { ...details, unknown: live.reason });
8363
9158
  }
8364
9159
 
8365
9160
  /** Retire one instance. One retire of a home at a time (awebai/oats#863): the home's claim
@@ -8369,6 +9164,13 @@ function refusePendingCompletion(name, home) {
8369
9164
  * not bypass it. A claim left by a killed retire is taken over. Every apply path runs this
8370
9165
  * function: the CLI, the deferred completion, and `--server` on the host. Synchronous. */
8371
9166
  export function retireInstance(root, name, o = {}) {
9167
+ // No answer of a retire carries a code that is not the kernel's (awebai/oats#892). The retire of
9168
+ // the home gives its own (retireClaimed); what fails before it (the resolution, the claim, the
9169
+ // plan the caller reads under it) has touched nothing of the instance.
9170
+ try { return retireUnderClaim(root, name, o); }
9171
+ catch (e) { throw isAnswerCode(e?.code) ? e : statedFailure(e, "E_LIFECYCLE_FAILED", `Nothing was done: ${name} is not retired.`); }
9172
+ }
9173
+ function retireUnderClaim(root, name, o) {
8372
9174
  if (o.deleteBranch) throw oatsError("E_BAD_ARGS", RETIRE_DELETE_BRANCH_REFUSED);
8373
9175
  let found;
8374
9176
  try { found = resolveRetireHome(root, name, o); }
@@ -8377,21 +9179,17 @@ export function retireInstance(root, name, o = {}) {
8377
9179
  throw e;
8378
9180
  }
8379
9181
  for (let restarts = 0; ; restarts++) {
8380
- const lock = retireClaimPath(found.home);
8381
- const refusals = retireClaimRefusals(name, found.home, lock);
8382
- // The retirement root as retire makes it for its recovery copies; the claims are private.
8383
- mkdirSync(instancesRetirementRoot(dirname(found.home)), { recursive: true });
8384
- mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
8385
- // No waiting: a live holder is refused at once. Only a deferred completion waits, for the
8386
- // retire that scheduled it to return.
8387
- const me = acquireClaim(lock, { ...refusals, waitMs: o[COMPLETES_DEFERRED] ? CLAIM_WAIT_MS : 0 });
9182
+ // No waiting: a live holder, a retire or a stop, is refused at once. Only a deferred completion
9183
+ // waits, for the retire that scheduled it to return.
9184
+ const held = claimHomeFor("retire", name, found.home, { waitMs: o[COMPLETES_DEFERRED] ? CLAIM_WAIT_MS : 0 });
9185
+ const { lock } = held;
8388
9186
  try {
8389
9187
  // Resolved again under the claim: another retire may have removed the home between the
8390
9188
  // first resolution and the claim. Gone is what a retire of a retired instance answers.
8391
9189
  const now = resolveRetireHome(root, name, o);
8392
9190
  if (retireClaimPath(now.home) !== lock) {
8393
9191
  // The name is another home's now, whose claim this does not hold: start over on that one.
8394
- if (restarts >= RETIRE_CLAIM_RESTARTS) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `the home of ${name} changed while its claim was being taken (it is now ${now.home}); nothing was done — retry`), { details: { instance: name, home: now.home, lock: retireClaimPath(now.home) } });
9192
+ if (restarts >= RETIRE_CLAIM_RESTARTS) throw lifecycleBusy("none", `the home of ${name} changed while its claim was being taken (it is now ${now.home}); nothing was done`, "retry", { instance: name, home: now.home, lock: retireClaimPath(now.home) });
8395
9193
  found = now;
8396
9194
  continue;
8397
9195
  }
@@ -8405,13 +9203,100 @@ export function retireInstance(root, name, o = {}) {
8405
9203
  const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}) } : o;
8406
9204
  return retireClaimed(root, name, bound, now);
8407
9205
  } finally {
8408
- releaseClaim(lock, me);
9206
+ releaseHomeClaim(held);
8409
9207
  }
8410
9208
  }
8411
9209
  }
8412
9210
 
8413
- /** The retire of the home `found`, under its claim (retireInstance). */
9211
+ /** `e` as the answer of a retire at a point where it knows what it has done: a kernel error whose
9212
+ * message ends with `said`, the sentence of that point with its own full stop. One that has a
9213
+ * kernel code keeps its code, its details and its provenance; any other is wrapped as `fallback`
9214
+ * (asKernelError), its text after `lead` when one is given. A message that already ends with the
9215
+ * sentence is left as it is: it is said once. */
9216
+ function statedFailure(e, fallback, said, lead) {
9217
+ const kernel = asKernelError(e, fallback, lead ? `${lead}: ${e?.message ?? e}` : undefined);
9218
+ // A failure answered under its own name (an unsafe key in a document) keeps its own words too.
9219
+ if (OWN_NAME_FAILURES.has(kernel.code) || kernel.message.endsWith(said)) return kernel;
9220
+ const stated = oatsError(kernel.code, `${kernel.message.replace(/\.$/, "")}. ${said}`, kernel.provenance);
9221
+ if (kernel.details) stated.details = kernel.details;
9222
+ if (Object.hasOwn(kernel, "cause")) stated.cause = kernel.cause; // whatever was thrown, undefined included (defectOf)
9223
+ return stated;
9224
+ }
9225
+ /** A retire's recovery as it is on disk at `path` → { path, phase }, the phase its recovery.json
9226
+ * holds now; null without a path, or when the manifest cannot be read or holds another phase. */
9227
+ function recoveryOnDisk(path) {
9228
+ try {
9229
+ if (!path) return null;
9230
+ const phase = readJsonOrUndefined(join(path, "recovery.json"))?.phase;
9231
+ return phase === "before-hooks" || phase === "complete" ? { path, phase } : null;
9232
+ } catch { return null; } // total: a read that fails names no copy
9233
+ }
9234
+ /** What is at `home` now, for a retire whose removal began (`removing`): "kept" when it did not,
9235
+ * "removed" when nothing is there, "partial" when something is (or that cannot be told). */
9236
+ function homeOnDisk(home, removing) {
9237
+ if (!removing) return "kept";
9238
+ try { lstatSync(home); return "partial"; } catch (e) { return e?.code === "ENOENT" ? "removed" : "partial"; } // total
9239
+ }
9240
+
9241
+ /** The retire of the home `found`, under its claim (retireInstance). Whatever fails in it is
9242
+ * answered with a kernel code and with what the retire had done by then (awebai/oats#892):
9243
+ * `details.reached` on every error, and, on one that is not the kernel's, the sentence of that
9244
+ * point (`at.said`, kept current by retireSteps). Such an error is E_LIFECYCLE_FAILED; the steps
9245
+ * that inspect the home or the work give E_WORK_INSPECTION_FAILED themselves.
9246
+ *
9247
+ * `reached` is `{ phase, sessionStopAttempted, hooksStarted, home, recovery }`. `phase` is how
9248
+ * far the retire got: "before-effects" (nothing happened: never answered once a process may have
9249
+ * been signalled), "before-hooks" (from the step that stops its recorded children on, whether or
9250
+ * not it had anything to signal, or earlier, from the end of the hook group an interrupted spawn
9251
+ * left), "after-hooks" (from the call of the retire hooks on),
9252
+ * "removal" (from the removal of the home on). In the other fields the untouched value is a
9253
+ * guarantee, and the other value says only that the retire reached that step, which may not have
9254
+ * completed (docs/desktop-cli-api.md, `error.details.reached`: the shape is contract):
9255
+ * - `sessionStopAttempted: false`: it signalled neither the instance's session nor a child's
9256
+ * harness;
9257
+ * - `hooksStarted: false`: no retire hook was started;
9258
+ * - `home: "kept"`: the removal did not begin; else what is on disk now, "partial" or "removed";
9259
+ * - `recovery: null`: no copy of this retire whose manifest can be read; else its path and the
9260
+ * phase its recovery.json holds now ("before-hooks" or "complete"), read when the error is
9261
+ * answered. */
8414
9262
  function retireClaimed(root, name, o, found) {
9263
+ const at = { phase: "before-effects", sessionTouched: false, hooksStarted: false, removing: false, recoveryPath: null, said: () => "Nothing was stopped, run or removed", lead: null };
9264
+ try { return retireSteps(root, name, o, found, at); }
9265
+ catch (e) { throw retireFailure(e, at, found.home); }
9266
+ }
9267
+ /** The error a retire of `home` answers for `e`, thrown while the retire was at `at`
9268
+ * (retireClaimed): a kernel error that carries `details.reached`. It never throws, whatever `e` and
9269
+ * `at` are: an answer of a retire without `reached` says that the retire of the home had not
9270
+ * begun and that nothing was done (retireInstance), and no error from here may read so. `reached`
9271
+ * is made first, from the tracker and two reads that cannot fail; if the sentence of that point
9272
+ * cannot be made, or the error cannot carry details, the answer is the error's own message, with
9273
+ * `reached`. Exported for its test. */
9274
+ export function retireFailure(e, at, home) {
9275
+ const reached = { phase: at.phase, sessionStopAttempted: at.sessionTouched, hooksStarted: at.hooksStarted, home: homeOnDisk(home, at.removing), recovery: recoveryOnDisk(at.recoveryPath) };
9276
+ // A code this verb answers only before any effect (lib/errors.mjs BEFORE_EFFECT_CODES), raised
9277
+ // once the retire is past "before-effects": the same fact `reached.phase` states, never a second
9278
+ // record of how far the retire got. A net: no known place raises one there.
9279
+ const late = at.phase !== "before-effects";
9280
+ try {
9281
+ const answered = isAnswerCode(e?.code) ? e : statedFailure(e, "E_LIFECYCLE_FAILED", `${at.said()}.`, at.lead?.());
9282
+ const failure = late ? afterFirstEffect(answered, "retire", `phase ${at.phase}`) : answered;
9283
+ failure.details = { ...failure.details, reached };
9284
+ return failure;
9285
+ } catch (unsaid) {
9286
+ reportDefect(unsaid);
9287
+ // The net again, where its sentence could not be built: never the refusal's own code past the
9288
+ // first effect, nor its words alone, which say that nothing happened.
9289
+ const lateRefusal = late && BEFORE_EFFECT_CODES.retire.includes(e?.code);
9290
+ const plain = new Error(`${lateRefusal ? `oats retire answered ${e.code} after its first effect (phase ${at.phase}): ` : ""}${String(e?.message ?? e)}`, { cause: e });
9291
+ plain.code = lateRefusal ? "E_LIFECYCLE_FAILED" : kernelCode(e, "E_LIFECYCLE_FAILED");
9292
+ const cause = isAnswerCode(e?.code) ? undefined : errorCause(e);
9293
+ plain.details = { ...(isAnswerCode(e?.code) && isPlainObject(e.details) ? e.details : {}), ...(cause ? { cause } : {}), reached };
9294
+ return plain;
9295
+ }
9296
+ }
9297
+ /** The steps of a retire. `at` is where it is (retireClaimed): each step that changes what a
9298
+ * failure may truthfully say moves it first. */
9299
+ function retireSteps(root, name, o, found, at) {
8415
9300
  const session = o.tmuxSession || DEFAULT_TMUX_SESSION;
8416
9301
  // self-retire: the caller IS the instance. Without --keep-dir the whole
8417
9302
  // retirement is deferred to a detached external completion (below); with
@@ -8460,28 +9345,46 @@ function retireClaimed(root, name, o, found) {
8460
9345
  if (isPlainObject(rawMarker?.inProgress)) {
8461
9346
  const p = rawMarker.inProgress;
8462
9347
  const live = processLiveness(p);
8463
- if (live.state === "alive") throw oatsError("E_LIFECYCLE_BUSY", `${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`);
9348
+ 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");
8464
9349
  if (live.state === "unknown") {
8465
- if (!o.force) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `${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 — check that pid by hand, and if it is not that spawn, run \`oats retire ${name} --force\``), { details: { pid: p.pid, processStart: p.processStart ?? null, unknown: live.reason, remedy: `oats retire ${name} --force` } });
9350
+ 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`,
9351
+ `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` });
8466
9352
  inProgressUnverified = true;
8467
9353
  spawnGroupWarnings.push(`retired with --force although whether its spawn (pid ${p.pid}) still runs could not be read (${live.reason}); its branch is kept`);
8468
9354
  }
8469
9355
  }
9356
+ // The retire's own read of the record, with the same reader as the resolution: one that became
9357
+ // unreadable since then refuses as there. It comes before the first signal a retire can send
9358
+ // (below), so that E_UNIDENTIFIED_INSTANCE_HOME for an unreadable record is only ever answered
9359
+ // while nothing was done: `reached` is untouched ("before-effects").
9360
+ const liveMeta = identifiedHomeRecord(found.home).meta;
9361
+ // What this retire did to the hook group an interrupted spawn left, when it signalled it. Ending
9362
+ // that group is the first signal a retire can send: from that call on the retire is no longer
9363
+ // "before-effects", and no answer says that nothing was stopped.
9364
+ let spawnGroupSaid = null;
9365
+ const nothingYet = () => spawnGroupSaid ? `${spawnGroupSaid}; no session was stopped, no retire hook was run and nothing was removed` : "Nothing was stopped, run or removed";
9366
+ at.said = nothingYet;
8470
9367
  if (quarantine?.inProgress) {
8471
9368
  const p = quarantine.inProgress;
9369
+ const group = `The worktree hook process group ${p.hookPgid} that an interrupted spawn left`;
9370
+ at.phase = "before-hooks";
9371
+ spawnGroupSaid = `${group} was signalled and may still run`;
8472
9372
  const ended = terminateRecordedGroup(p);
8473
- if (ended === "survived") throw oatsError("E_LIFECYCLE_BUSY", `${name}: the worktree hook process group ${p.hookPgid} that an interrupted spawn left could not be ended (it survived SIGKILL); nothing was retired`);
9373
+ if (ended === "terminated" || ended === "killed") spawnGroupSaid = `${group} was ended`;
9374
+ else if (ended !== "survived") { spawnGroupSaid = null; at.phase = "before-effects"; } // nothing was signalled
9375
+ // Two signals were sent by now: never a code that says nothing happened (awebai/oats#895).
9376
+ if (ended === "survived") throw oatsError("E_RUNTIME_QUIESCE_FAILED", `${name}: the worktree hook process group ${p.hookPgid} that an interrupted spawn left could not be ended (it survived SIGTERM and SIGKILL, and still runs); no session was stopped, no retire hook was run and nothing was removed. End that group by hand (kill -KILL -- -${p.hookPgid}), then retire again.`);
8474
9377
  if (ended === "unverified") spawnGroupWarnings.push(unverifiedGroupWarning(p.hookPgid));
8475
9378
  // A group whose leader's start cannot be read may still be that spawn's hook: never signalled,
8476
9379
  // and refused like an unreadable spawn above, with the same way out.
8477
9380
  if (ended === "unknown") {
8478
9381
  const note = unknownGroupNote(p);
8479
- if (!o.force) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `${name}: the worktree hook ${note}; nothing was retired — check process group ${p.hookPgid} by hand: if it is that hook, end it (kill -TERM -- -${p.hookPgid}) and retire again; if it is not, run \`oats retire ${name} --force\``), { details: { hookPgid: p.hookPgid, hookStart: p.hookStart ?? null, remedy: `oats retire ${name} --force` } });
9382
+ if (!o.force) throw lifecycleBusy("unknown", `${name}: the worktree hook ${note}; nothing was retired`,
9383
+ `check process group ${p.hookPgid} by hand: if it is that hook, end it (kill -TERM -- -${p.hookPgid}) and retire again; if it is not, run \`oats retire ${name} --force\``, { hookPgid: p.hookPgid, hookStart: p.hookStart ?? null, remedy: `oats retire ${name} --force` });
8480
9384
  inProgressUnverified = true;
8481
9385
  spawnGroupWarnings.push(`retired with --force although the worktree ${note}; its branch is kept`);
8482
9386
  }
8483
9387
  }
8484
- const liveMeta = existsSync(metaPath) ? JSON.parse(readFileSync(metaPath, "utf8")) : undefined;
8485
9388
  // A quarantined home may carry an instance.json that is NOT the spawn record:
8486
9389
  // module materialization writes a pre-hook stub ({ modules, providers,
8487
9390
  // resolutionRevision }) before the spawn hooks run, and a required-hook
@@ -8517,9 +9420,26 @@ function retireClaimed(root, name, o, found) {
8517
9420
  }
8518
9421
 
8519
9422
  const workPath = join(found.home, "work");
8520
- const directory = meta.work === "directory";
8521
- const isWorktree = !directory && (meta.work === "worktree" ||
8522
- (existsSync(workPath) && !lstatSync(workPath).isSymbolicLink()));
9423
+ // What work/ is, by the one function the plan reads too (instanceWork, #962). Read once, here.
9424
+ const workIs = instanceWork(found.home, meta);
9425
+ const directoryMode = workIs.is === "directory-mode";
9426
+ // A real directory that is not the instance's own tree is bytes of the home: inspected, copied to
9427
+ // recovery and checked as a directory instance's work is, and removed with the home. It never
9428
+ // reaches the worktree step, and no pass leaves it out of its copy.
9429
+ const homeDirectory = workIs.is === "home-directory";
9430
+ const directory = directoryMode || homeDirectory;
9431
+ const isWorktree = workIs.is === "own-tree" || workIs.is === "other";
9432
+ // A link is never the instance's own tree, whatever the record says (#973): it goes with the
9433
+ // home, and what it leads to is not copied, moved, removed or read through Git by any step.
9434
+ const link = workIs.is === "link";
9435
+ // The record as the work steps read it, never written anywhere: an own tree is a worktree's,
9436
+ // whatever work mode the record holds, and when the record names no repository its repository
9437
+ // is the one Git names for the tree. A directory of the home is no worktree, whatever it holds,
9438
+ // and neither is a link, under a record that says `worktree` too: every step that asks whether
9439
+ // this home is a worktree's (the recovery's writers, the rollback retry) asks this record.
9440
+ const repoFromGit = workIs.is === "own-tree" && !meta.repo ? workIs.tree?.repo : undefined;
9441
+ const workMeta = workIs.is === "own-tree" ? { ...meta, work: "worktree", repo: meta.repo || repoFromGit }
9442
+ : homeDirectory || link ? { ...meta, work: undefined } : meta;
8523
9443
  // A live harness cannot establish a stable final work inspection of itself,
8524
9444
  // so self-retire never inspects, runs hooks, or removes anything here. It
8525
9445
  // persists the intent and hands the whole retirement to a detached process
@@ -8529,12 +9449,16 @@ function retireClaimed(root, name, o, found) {
8529
9449
  // quarantined home's cleanup descriptor overrides the live record's endpoint: either may name it.
8530
9450
  const herdrHome = recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(found.home))) || recordsHerdr(liveMeta);
8531
9451
  if (self && (!o.keepDir || herdrHome)) {
9452
+ // scheduleDeferredSelfRetirement ends the completion it started before it throws, whatever fails.
9453
+ at.said = () => `${spawnGroupSaid ? `${spawnGroupSaid}. ` : ""}This command inspected, ran and removed nothing, and left no detached completion running`;
8532
9454
  return scheduleDeferredSelfRetirement(root, found, name, o, session);
8533
9455
  }
8534
9456
  // A worktree directory whose git admin entry is gone cannot be inspected, moved or removed through git, and
8535
9457
  // what it holds may exist nowhere else: it is never removed. Without --force the hooks still run and it is
8536
9458
  // an incomplete item; --force (which removes the home it sits in) refuses before anything runs.
8537
- const orphanedWork = meta.work === "worktree" && existsSync(workPath) && worktreeAdminMissing(workPath);
9459
+ // (An own tree: a directory of the home under a record that says `worktree` is no worktree that lost
9460
+ // its entry. It is copied and removed with the home, #962.)
9461
+ const orphanedWork = workIs.is === "own-tree" && meta.work === "worktree" && existsSync(workPath) && worktreeAdminMissing(workPath);
8538
9462
  if (orphanedWork && o.force) {
8539
9463
  throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the work directory ${workPath} has no git admin entry in ${meta.repo ?? "its repository"}, so retiring the home would delete it with whatever it holds; move it out or delete it by hand, then retire again; nothing was run or removed`);
8540
9464
  }
@@ -8545,8 +9469,23 @@ function retireClaimed(root, name, o, found) {
8545
9469
  const owesWorktree = !!quarantine && (quarantine.cleanup.outstanding?.git || []).includes("worktree");
8546
9470
  const recordedBranch = quarantine ? { repo: meta.repo, branch: meta.branch } : undefined;
8547
9471
  // Whether this retire removes the worktree, when it gets to that step.
8548
- const worktreeRemoval = { removes: !!(o.discardWorktree || owesWorktree), repo: meta.repo };
8549
- const initialObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure: "Nothing was stopped, run or removed" });
9472
+ const worktreeRemoval = { removes: !!(o.discardWorktree || owesWorktree), repo: workMeta.repo };
9473
+ // An inspection of the home and the work. Whatever fails in it, a walk that meets an entry it
9474
+ // cannot read or that is gone included, is an inspection that failed (E_WORK_INSPECTION_FAILED),
9475
+ // and says what the retire has and has not done by then (`disclosure`), once. Classified here,
9476
+ // at the retire's own calls: the digests' other callers do not answer that code for it.
9477
+ const inspect = (disclosure) => {
9478
+ try { return inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, directoryMode, link, instance: name, orphanedWork, disclosure }); }
9479
+ catch (e) { throw statedFailure(e, "E_WORK_INSPECTION_FAILED", `${disclosure}.`, `could not inspect the home of ${name} or its work`); }
9480
+ };
9481
+ const initialObservation = inspect(nothingYet());
9482
+ // An own tree with no repository, recorded or read from Git, has no step: the retire cannot re-home it,
9483
+ // and its copy needs the repository too. Removing the home would delete it uncopied, so it is refused
9484
+ // here, --force included (#962): after the inspection, whose own refusals of such a directory keep
9485
+ // their words, and before the session is stopped and before any retire hook runs.
9486
+ if (workIs.is === "own-tree" && workIs.at === "directory" && !workMeta.repo && !orphanedWork && !o.keepDir) {
9487
+ throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: ${workPath} is the instance's own work tree, but its record names no repository and Git does not read it as a registered worktree of one, so the retire can neither re-home it nor copy it, and retiring the home would delete it with whatever it holds; move it out or delete it by hand, then retire again; nothing was run or removed`);
9488
+ }
8550
9489
  // A locked extra tree is known from the home as it is now: Git will neither move nor remove it, so a retire that
8551
9490
  // would remove the home refuses here, before the session is stopped and before any retire hook runs (the hooks
8552
9491
  // revoke identities a kept home would still need). The extra-tree step keeps its own check, for a lock that appears
@@ -8592,21 +9531,37 @@ function retireClaimed(root, name, o, found) {
8592
9531
  // retired, nothing is escalated, and --force does not bypass it. A child whose
8593
9532
  // instance.json is gone by now (a --self snapshot's child retired in between)
8594
9533
  // is no longer an instance, and the plan would not list it: it is not stopped.
9534
+ // What this retire did to the instance's own session: "unverified" once the kill is sent and
9535
+ // until the window is seen gone. `childStopReached`: a child's stop got to signal its harness.
9536
+ let ownSession = "untouched", childStopReached = false;
9537
+ const sessionSaid = () => ownSession === "stopped" ? "its session has been stopped"
9538
+ : ownSession === "unverified" ? "its session was asked to end, and whether it did was not established"
9539
+ : childStopReached ? `this retire stopped no session of ${name}; a stop of its recorded children was attempted`
9540
+ : "this retire stopped no session";
9541
+ // What a refusal before the hooks tells the operator about the retire so far.
9542
+ const soFar = (kept) => `${name} is not retired and ${kept}; ${sessionSaid()}`;
9543
+ const beforeHooks = () => `No retire hook has run and nothing was deleted: ${soFar("its home and work are kept")}`;
9544
+ // What a refusal after the hooks tells the operator about the retire so far.
9545
+ const hooksSaid = () => at.hooksStarted ? "The retire hooks have run" : "No retire hook was run";
9546
+ const afterHooks = () => `${hooksSaid()}; the home, its work and the pre-hook recovery (if any) are kept; ${sessionSaid()}`;
9547
+ at.phase = "before-hooks";
9548
+ at.said = beforeHooks;
8595
9549
  let childrenStopped;
8596
9550
  if (Array.isArray(o.children)) {
8597
- childrenStopped = stopRecordedChildren(o.children.filter((kid) => existsSync(join(kid.home, "instance.json"))));
8598
- const running = childrenStopped.filter((k) => !k.ok);
8599
- if (running.length) throw Object.assign(oatsError("E_CHILDREN_RUNNING", `${running.map((k) => k.instance).join(", ")} ${running.length === 1 ? "is" : "are"} still running after a bounded stop; nothing was retired and nothing was escalated`), { details: { childrenStopped } });
9551
+ childrenStopped = stopRecordedChildren(o.children.filter((kid) => existsSync(join(kid.home, "instance.json"))), () => { at.sessionTouched = true; childStopReached = true; });
9552
+ const notStopped = childrenStopped.filter((k) => !k.ok);
9553
+ if (notStopped.length) throw Object.assign(oatsError("E_CHILDREN_RUNNING", `${childrenNotStopped(notStopped)}; nothing was retired and nothing was escalated`), { details: { childrenStopped } });
8600
9554
  }
8601
9555
  // `=` forces exact matching: tmux targets otherwise PREFIX-match window names.
8602
9556
  // A no-launch instance is already quiesced. A launched one must have exact
8603
9557
  // window absence established before recovery copying begins.
8604
- let sessionStopped = false;
8605
9558
  if (!self && runtimeAuthority?.launched) {
8606
9559
  const runtimeSession = runtimeAuthority.tmux.session;
8607
9560
  const runtimeWindow = runtimeAuthority.tmux.window;
8608
9561
  const runtimeSocket = runtimeAuthority.tmux.socket;
8609
9562
  const tmux = ["-S", runtimeSocket];
9563
+ at.sessionTouched = true;
9564
+ ownSession = "unverified";
8610
9565
  try { execFileSync("tmux", [...tmux, "kill-window", "-t", `=${runtimeSession}:=${runtimeWindow}`], { stdio: ["ignore", "pipe", "pipe"] }); } catch { /* verify the effect below */ }
8611
9566
  try {
8612
9567
  const windows = execFileSync("tmux", [...tmux, "list-windows", "-t", runtimeSession, "-F", "#{window_name}"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).split("\n").filter(Boolean);
@@ -8624,13 +9579,9 @@ function retireClaimed(root, name, o, found) {
8624
9579
  if (why) throw unestablished(why);
8625
9580
  }
8626
9581
  }
8627
- sessionStopped = true;
9582
+ ownSession = "stopped";
8628
9583
  }
8629
- // What a refusal before the hooks tells the operator about the retire so far.
8630
- const soFar = (kept) => `${name} is not retired and ${kept}; ${sessionStopped ? "its session has been stopped" : "this retire stopped no session"}`;
8631
- // What a refusal after the hooks tells the operator about the retire so far.
8632
- const afterHooks = () => `The retire hooks have run; the home, its work and the pre-hook recovery (if any) are kept; ${sessionStopped ? "its session has been stopped" : "this retire stopped no session"}`;
8633
- const stableObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure: `No retire hook has run and nothing was deleted: ${soFar("its home and work are kept")}` });
9584
+ const stableObservation = inspect(beforeHooks());
8634
9585
  // The bytes of the worktree as they are before the hooks: after the hooks,
8635
9586
  // "the work did not move" is then proven, never taken from a status text.
8636
9587
  // Read before the recovery is written, so that a worktree that cannot be
@@ -8645,7 +9596,7 @@ function retireClaimed(root, name, o, found) {
8645
9596
  if (stableObservation.classes.length && stableObservation.workProvable) {
8646
9597
  try { observedWorkBytes(stableObservation); }
8647
9598
  catch (e) {
8648
- throw oatsError(e.code, `${e.message}. No recovery was written and nothing was deleted: ${soFar("its home is kept")}`);
9599
+ throw statedFailure(e, "E_WORK_INSPECTION_FAILED", `No recovery was written and nothing was deleted: ${soFar("its home is kept")}`);
8649
9600
  }
8650
9601
  }
8651
9602
  // One recovery per retirement. The snapshot taken here, before the retire
@@ -8654,11 +9605,12 @@ function retireClaimed(root, name, o, found) {
8654
9605
  // cannot be made or verified refuses here, with the same disclosure.
8655
9606
  let preHookRecovery;
8656
9607
  if (stableObservation.classes.length) {
8657
- try { preHookRecovery = writeRetirementRecovery(stableObservation, meta, name, "before-hooks"); }
9608
+ // Whatever fails here, not only a copy that could not be verified, says the same.
9609
+ try { preHookRecovery = writeRetirementRecovery(stableObservation, workMeta, name, "before-hooks"); }
8658
9610
  catch (e) {
8659
- if (e?.code !== "E_WORK_PRESERVATION_FAILED") throw e;
8660
- throw Object.assign(oatsError(e.code, `${e.message}. No retire hook has run, no recovery was written and nothing was deleted: ${soFar("its home and work are kept")}`, e.provenance), e.details ? { details: e.details } : {});
9611
+ throw statedFailure(e, "E_LIFECYCLE_FAILED", `No retire hook has run, no recovery was written and nothing was deleted: ${soFar("its home and work are kept")}`);
8661
9612
  }
9613
+ at.recoveryPath = preHookRecovery.receipt.path;
8662
9614
  }
8663
9615
  let workRecovery = preHookRecovery?.receipt;
8664
9616
 
@@ -8674,6 +9626,10 @@ function retireClaimed(root, name, o, found) {
8674
9626
  // The soul this home was spawned from, as recorded (a workspace home records its
8675
9627
  // per-commit directory; agents/<name>/soul may since point elsewhere) — the same
8676
9628
  // value spawn's hook saw.
9629
+ // From the call on the hooks count as run: one that fails part-way has started some.
9630
+ at.phase = "after-hooks";
9631
+ at.hooksStarted = true;
9632
+ 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()}`;
8677
9633
  hookResults = runLifecycleHooks("retire", {
8678
9634
  home: found.home, instance: name, agentName: found.agent.name,
8679
9635
  soulDir: instanceSoulDir(found.home, meta) || found.agent._soulDir || join(found.agent._dir, "soul"),
@@ -8681,6 +9637,8 @@ function retireClaimed(root, name, o, found) {
8681
9637
  contextDir: meta.repo, workspaceDir: workspaceOf(root), rootDir: root, resolved, priorMeta: meta.capabilityMeta || {},
8682
9638
  });
8683
9639
  }
9640
+ at.phase = "after-hooks";
9641
+ at.said = afterHooks;
8684
9642
 
8685
9643
  // ORDINARY retirement must not delete a home whose cleanup did not finish.
8686
9644
  // The failures were already collected above; until now they were read ONLY on
@@ -8746,16 +9704,16 @@ function retireClaimed(root, name, o, found) {
8746
9704
  // step and before the home is removed.
8747
9705
  // A refusal here says what has and has not happened, as one before the hooks
8748
9706
  // does: the hooks have run, and what is kept (#659).
8749
- const finalObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure: afterHooks() });
9707
+ const finalObservation = inspect(afterHooks());
8750
9708
  try {
8751
- if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, meta);
9709
+ if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, workMeta);
8752
9710
  else if (finalObservation.classes.length) {
8753
- workRecovery = preserveRetirementWork({ ...finalObservation, notCopied: unionNotCopied(stableObservation.notCopied, finalObservation.notCopied) }, meta, name);
9711
+ workRecovery = preserveRetirementWork({ ...finalObservation, notCopied: unionNotCopied(stableObservation.notCopied, finalObservation.notCopied) }, workMeta, name);
8754
9712
  }
8755
9713
  } catch (e) {
8756
- if (!e?.code) throw e;
8757
- throw Object.assign(oatsError(e.code, `${e.message}. ${afterHooks()}.`, e.provenance), e.details ? { details: e.details } : {});
9714
+ throw statedFailure(e, "E_LIFECYCLE_FAILED", `${afterHooks()}.`);
8758
9715
  }
9716
+ if (workRecovery?.path) at.recoveryPath = workRecovery.path;
8759
9717
 
8760
9718
  // Lineage repair: any instance pointing at the retiree (parentInstance from a
8761
9719
  // child/parent relation, siblingInstance from a root-sibling link) would be
@@ -8780,9 +9738,10 @@ function retireClaimed(root, name, o, found) {
8780
9738
  try { return realpathSync(hit.home) === retireeHome; } catch { return false; }
8781
9739
  };
8782
9740
  const repair = (orphanRoot, instHome) => {
8783
- const p = join(instHome, "instance.json");
8784
- if (!existsSync(p)) return;
8785
- let m; try { m = JSON.parse(readFileSync(p, "utf8")); } catch { return; }
9741
+ // Another home's record: one that is absent or cannot be read names no edge to repair.
9742
+ const record = readHomeRecord(instHome);
9743
+ if (record.state !== "record") return;
9744
+ const p = record.path, m = record.meta;
8786
9745
  if (m.parentInstance !== name && m.siblingInstance !== name) return;
8787
9746
  if (!edgeIsRetiree(orphanRoot, instHome)) return; // same NAME, different instance — leave it
8788
9747
  // Drop every edge to the retiree, then graft the retiree's own links —
@@ -8833,10 +9792,20 @@ function retireClaimed(root, name, o, found) {
8833
9792
  // (`plannedExtraWorktrees`) binds what is done: trees that no longer read
8834
9793
  // as planned refuse as stale before any of them is touched.
8835
9794
  let extraWorktrees;
9795
+ let retention = null;
9796
+ // From here on the retire removes and re-homes trees: a failure no longer says that the work is
9797
+ // kept, only what is still true, and which trees it has dealt with.
9798
+ const treesDone = () => {
9799
+ const done = [...(extraWorktrees || []).map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`),
9800
+ ...(retention?.worktree === "removed" ? [`${workPath} removed`] : retention?.worktree === "retained" ? [`${workPath} re-homed to ${retention.movedTo}`] : [])];
9801
+ return done.length ? `. Already done in this retire: ${done.join(", ")}` : "";
9802
+ };
9803
+ at.said = () => `${hooksSaid()}; the home is kept, and so is any recovery the retire wrote; ${sessionSaid()}${treesDone()}`;
8836
9804
  if (!o.keepDir && !(outstandingBeforeWorktree.length > 0 && !o.force)) {
8837
9805
  const rows = extraWorktreeRows(finalObservation.extraTrees, root);
8838
9806
  if (o.plannedExtraWorktrees && JSON.stringify(rows) !== JSON.stringify(o.plannedExtraWorktrees)) {
8839
- throw oatsError("E_PLAN_STALE", `${name}: the home's extra worktrees changed since the retire plan was shown, so none of them was moved or removed. The retire hooks have run; the home and its work are kept. Review the fresh plan (\`oats retire ${name} --plan\`) and apply it again.`);
9807
+ // After the hooks: never E_PLAN_STALE, which says that nothing happened (awebai/oats#895).
9808
+ throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the home's extra worktrees changed since the retire plan was shown, so none of them was moved or removed. The retire hooks have run; the home and its work are kept. Review the fresh plan (\`oats retire ${name} --plan\`) and apply it again.`);
8840
9809
  }
8841
9810
  const refused = rows.filter((r) => r.disposition === "refuse");
8842
9811
  if (refused.length) {
@@ -8873,10 +9842,9 @@ function retireClaimed(root, name, o, found) {
8873
9842
  // (#718), found while work/ is still here (a link through an alias of the
8874
9843
  // tree resolves only then), each with its link as written.
8875
9844
  const attachedKids = (childrenStopped || []).filter((k) => k.ok).map((k) => ({ ...k, link: attachedWorkLink(k.home, found.home) })).filter((k) => k.link !== null);
8876
- const worktreeStep = isWorktree && !!meta.repo && !orphanedWork;
9845
+ const worktreeStep = isWorktree && !!workMeta.repo && !orphanedWork;
8877
9846
  const worktreeDeferred = worktreeStep && existsSync(workPath) && outstandingBeforeWorktree.length > 0 && !o.force;
8878
9847
  const keptForRetry = worktreeDeferred ? `git worktree ${workPath}: kept for the retry; outstanding: ${outstandingBeforeWorktree.join("; ")}` : null;
8879
- let retention = null;
8880
9848
  // The repository of work/, by its common Git directory (awebai/oats#679), read once from meta.repo: the
8881
9849
  // step's commands and the quarantine's verification below run helper-free against it (gitRepoRun,
8882
9850
  // gitRepoRead), as the extra-tree step's do. A bare repository is named as its Git directory.
@@ -8885,10 +9853,10 @@ function retireClaimed(root, name, o, found) {
8885
9853
  const workRepoGitDir = () => {
8886
9854
  if (workRepo) return workRepo;
8887
9855
  const args = ["rev-parse", "--path-format=absolute", "--git-common-dir"];
8888
- let r = gitRead(meta.repo, args);
8889
- if (!r.ok) { const asGitDir = gitRepoRead(meta.repo, args); if (asGitDir.ok) r = asGitDir; }
9856
+ let r = gitRead(workMeta.repo, args);
9857
+ if (!r.ok) { const asGitDir = gitRepoRead(workMeta.repo, args); if (asGitDir.ok) r = asGitDir; }
8890
9858
  const dir = r.ok ? r.out.replace(/\n$/, "") : "";
8891
- return (workRepo = dir && !dir.includes("\n") ? { dir: realPathOrNearest(dir) } : { error: r.ok ? `git rev-parse printed no single Git directory for ${meta.repo}` : r.err });
9859
+ return (workRepo = dir && !dir.includes("\n") ? { dir: realPathOrNearest(dir) } : { error: r.ok ? `git rev-parse printed no single Git directory for ${workMeta.repo}` : r.err });
8892
9860
  };
8893
9861
  // Whether an entry is at the path: lstat, so a dangling link is an entry; one that cannot be tested counts.
8894
9862
  const entryAt = (path) => { try { lstatSync(path); return true; } catch (e) { return e?.code !== "ENOENT"; } };
@@ -8928,12 +9896,12 @@ function retireClaimed(root, name, o, found) {
8928
9896
  if (entryAt(workPath) || parseWorktreeList(gitRepoRun(gitDir.dir, ["worktree", "list", "--porcelain", "-z"])).some((r) => canonicalHomePath(r.worktree) === real)) throw new Error("it is still there after `git worktree remove`");
8929
9897
  } catch (e) {
8930
9898
  const done = extraWorktrees?.length ? ` Already done in this retire: ${extraWorktrees.map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`).join(", ")}.` : "";
8931
- throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be removed, or its removal could not be verified (${String(e?.stderr || e?.message || e || "").trim() || "unknown error"}).${done} The retire hooks have run; the home is kept, and so is any recovery the retire wrote; ${sessionStopped ? "its session has been stopped" : "this retire stopped no session"}. Check what is left at ${workPath}, then retry the retire.`);
9899
+ throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the worktree at ${workPath} could not be removed, or its removal could not be verified (${String(e?.stderr || e?.message || e || "").trim() || "unknown error"}).${done} The retire hooks have run; the home is kept, and so is any recovery the retire wrote; ${sessionSaid()}. Check what is left at ${workPath}, then retry the retire.`);
8932
9900
  }
8933
9901
  retention = { worktree: "removed", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
8934
9902
  }
8935
9903
  } else if (existsSync(workPath)) {
8936
- const dest = retainedWorktreeDest(workspaceOf(root), meta.repo, verifiedBranch, ref.commit);
9904
+ const dest = retainedWorktreeDest(workspaceOf(root), workMeta.repo, verifiedBranch, ref.commit);
8937
9905
  mkdirSync(dirname(dest), { recursive: true });
8938
9906
  try {
8939
9907
  const gitDir = workRepoGitDir();
@@ -8953,7 +9921,7 @@ function retireClaimed(root, name, o, found) {
8953
9921
  // receipt `spawned` carries, so the workspace log shows both halves of a
8954
9922
  // capability's lifecycle after the home is gone.
8955
9923
  const retireHookReceipt = (() => { const res = hookResults || {}; const failedBy = new Map((res.failures || []).map((f) => [f.capability, f])); return (res.order || []).map((id) => ({ capability: id, ok: !failedBy.has(id), meta: Object.hasOwn(res.meta || {}, id) })); })();
8956
- appendEvent(found.home, { kind: "retired", data: { agent: found.agent.name, keepDir: !!o.keepDir, self, quarantine: !!quarantine, workRecovery: workRecovery?.path ?? null, hooks: retireHookReceipt, ...(o[OBSOLETE_DELETE_BRANCH] ? { reason: OBSOLETE_DELETE_BRANCH_SENTENCE } : {}) } }, { workspaceOnly: true });
9924
+ const retiredEvent = appendEvent(found.home, { kind: "retired", data: { agent: found.agent.name, keepDir: !!o.keepDir, self, quarantine: !!quarantine, workRecovery: workRecovery?.path ?? null, hooks: retireHookReceipt, ...(o[OBSOLETE_DELETE_BRANCH] ? { reason: OBSOLETE_DELETE_BRANCH_SENTENCE } : {}) } }, { workspaceOnly: true });
8957
9925
  // Retrying a quarantine only clears it if compensation ACTUALLY completed.
8958
9926
  // Otherwise the home — and the credentials in it — must survive again, or the
8959
9927
  // retry becomes the deletion the quarantine was preventing.
@@ -8987,7 +9955,7 @@ function retireClaimed(root, name, o, found) {
8987
9955
  if (keptForRetry) failures.push(keptForRetry);
8988
9956
  // The quarantine may exist BECAUSE Git cleanup failed, so a retry has to
8989
9957
  // redo those steps and verify them — not just rerun hooks. No retire deletes a branch.
8990
- if (meta.work === "worktree" && meta.repo) {
9958
+ if (workMeta.work === "worktree" && workMeta.repo) {
8991
9959
  // A worktree this retry removed (the step above ran) must be verified gone; one it retained or kept for
8992
9960
  // the next retry stays registered by design. The removal is not attempted a second time here: only the
8993
9961
  // worktree step removes, after its check of HEAD, so a worktree it failed to remove is still registered
@@ -9024,8 +9992,8 @@ function retireClaimed(root, name, o, found) {
9024
9992
  else if (owesBranch && meta.branch && ip && ip.branch === meta.branch && /^[0-9a-f]{40,64}$/.test(String(ip.baseOid ?? "")) && retention?.worktree === "removed" && !failures.length) {
9025
9993
  const ref = `refs/heads/${meta.branch}`;
9026
9994
  // Retire's Git, bounded and helper-free (retireGit, #809): two reads, then the one write.
9027
- const tip = retireGitProbe(meta.repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", ref], { encoding: "utf8" });
9028
- const list = retireGitProbe(meta.repo, ["worktree", "list", "--porcelain", "-z"], { encoding: "utf8" });
9995
+ const tip = retireGitProbe(workMeta.repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", ref], { encoding: "utf8" });
9996
+ const list = retireGitProbe(workMeta.repo, ["worktree", "list", "--porcelain", "-z"], { encoding: "utf8" });
9029
9997
  const listOk = !list.error && list.status === 0;
9030
9998
  const checkedOut = listOk && list.stdout.split("\0").includes(`branch ${ref}`);
9031
9999
  if (tip.error || tip.status !== 0 || tip.stderr.length) branchKeptReason = "the branch could not be read";
@@ -9033,7 +10001,7 @@ function retireClaimed(root, name, o, found) {
9033
10001
  else if (!listOk) branchKeptReason = "whether it is checked out could not be read";
9034
10002
  else if (checkedOut) branchKeptReason = "it is checked out in a worktree";
9035
10003
  else {
9036
- const del = retireGitProbe(meta.repo, ["update-ref", "-d", ref, ip.baseOid], { encoding: "utf8" });
10004
+ const del = retireGitProbe(workMeta.repo, ["update-ref", "-d", ref, ip.baseOid], { encoding: "utf8" });
9037
10005
  if (del.error || del.status !== 0) branchKeptReason = `git refused to delete it (${String(del.stderr || del.error?.message || "").trim().split("\n")[0] || "update-ref failed"})`;
9038
10006
  else branchDeletedByRetry = true;
9039
10007
  }
@@ -9051,7 +10019,7 @@ function retireClaimed(root, name, o, found) {
9051
10019
  }
9052
10020
  // Git debt is proven by the verification block above, which only runs for a
9053
10021
  // worktree in a known repo. If it could not run, the debt stands.
9054
- if (quarantine.cleanup.outstanding?.git?.length && !(meta.work === "worktree" && meta.repo)) {
10022
+ if (quarantine.cleanup.outstanding?.git?.length && !(workMeta.work === "worktree" && workMeta.repo)) {
9055
10023
  failures.push(`git ${quarantine.cleanup.outstanding.git.join(", ")}: not re-verified on this retry, so the cleanup they owed is unverified`);
9056
10024
  }
9057
10025
  if (failures.length) {
@@ -9095,8 +10063,28 @@ function retireClaimed(root, name, o, found) {
9095
10063
  // unreachable remote) would be unremovable through OATS forever — the same
9096
10064
  // dead end the unusable-marker fixes closed, just reached from a valid one.
9097
10065
  const forced = !!(stillIncomplete && o.force);
10066
+ // Where a link under a record that says `worktree` leads, for the receipt (#973): once the home
10067
+ // is removed nothing else says it. The system's answer for the link, read here and only read:
10068
+ // never the text stored in the link, and no step acts on the path. null: it does not resolve.
10069
+ const linkLed = link && meta.work === "worktree" && !o.keepDir && (!stillIncomplete || forced)
10070
+ ? (() => { try { return { path: realpathSync(workPath) }; } catch { return { path: null }; } })() : undefined;
9098
10071
  if (!o.keepDir && (!stillIncomplete || forced)) {
10072
+ // The removal. A failure in it (a directory that is written into, or that cannot be emptied)
10073
+ // says what the retire did and what is at the home now, as it is on disk when it is answered.
10074
+ at.phase = "removal";
10075
+ at.removing = true;
10076
+ at.said = () => {
10077
+ const recovery = recoveryOnDisk(at.recoveryPath);
10078
+ const home = homeOnDisk(found.home, true);
10079
+ return [hooksSaid(),
10080
+ recovery ? `its recovery (${recovery.phase}) is at ${recovery.path}` : at.recoveryPath ? `its recovery at ${at.recoveryPath} could not be read` : "it wrote no recovery",
10081
+ retiredEvent.ok ? "its retired event is recorded" : "its retired event could not be recorded",
10082
+ home === "removed" ? `nothing is left at ${found.home}` : `what is left at ${found.home} may not be a whole instance home`,
10083
+ sessionSaid()].join("; ") + treesDone();
10084
+ };
10085
+ at.lead = () => `${name}: the directory at ${found.home} could not be removed`;
9099
10086
  rmSync(found.home, { recursive: true, force: true });
10087
+ at.lead = () => `${name}: its home was removed, and a file the retire leaves beside it could not be`;
9100
10088
  rmSync(directoryFallbackPath, { force: true });
9101
10089
  // The owed retirement is paid: clear the pending marker, and the failed
9102
10090
  // outcome an earlier deferred attempt may have left beside the home; a
@@ -9104,10 +10092,15 @@ function retireClaimed(root, name, o, found) {
9104
10092
  rmSync(retirePendingMarkerPath(found.home), { force: true });
9105
10093
  rmSync(deferredRetireResultPath(found.home), { force: true });
9106
10094
  rmSync(deferredRetireResultPath(found.home).replace(/\.json$/, ".log"), { force: true });
10095
+ at.lead = null;
9107
10096
  }
9108
10097
 
9109
10098
  const result = { retired: name, agent: found.agent.name, workRecovery, retention, extraWorktrees, worktreeRemoved: isWorktree && !!retention && retention.worktree !== "retained", branchDeleted: false, ...(branchDeletedByRetry || branchKeptReason ? { spawnCompensation: { branch: meta.branch, branchDeleted: branchDeletedByRetry, ...(branchKeptReason ? { reason: branchKeptReason } : {}) } } : {}), removedDir: !o.keepDir && (!stillIncomplete || forced), rollbackIncomplete: forced ? undefined : stillIncomplete, forcedIncomplete: forced ? stillIncomplete : undefined, retainedHome: stillIncomplete && !forced ? found.home : undefined, relinked: relinked.length ? relinked : undefined, childrenStopped, capabilityMeta: hookResults?.meta, warnings: (() => {
9110
10099
  const w = [...spawnGroupWarnings, ...(hookResults?.warnings || []), ...relinkWarnings];
10100
+ // What the retire read from Git about work/ where the record did not say it (#962).
10101
+ if (repoFromGit) w.push(`the record names no repository for the work tree at ${workPath}: the retire used the one Git names for it, ${repoFromGit}; the record was not changed`);
10102
+ if (homeDirectory && workIs.tree && !o.keepDir && (!stillIncomplete || forced)) w.push(`${workPath} was a registered worktree of ${workIs.tree.repo} and not this instance's own tree: it was copied to recovery and removed with the home as a directory of the home. Its entry stays in that repository until a prune (git -C ${shq(workIs.tree.repo)} worktree prune); its branch and commits are untouched`);
10103
+ if (linkLed) w.push(`${workPath} was a link though the record says work mode worktree: nothing was retained or removed as a work tree, and ${linkLed.path === null ? "it led nowhere that could be read" : `what it led to (${linkLed.path}) was not touched`}`);
9111
10104
  if (o[OBSOLETE_DELETE_BRANCH]) w.push(OBSOLETE_DELETE_BRANCH_SENTENCE);
9112
10105
  if (isCapturedHome(meta) && !quarantine) {
9113
10106
  // A captured home retires through the workspace path; its captured retire hooks do not