@awebai/oats 0.51.0 → 0.52.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 (128) hide show
  1. package/README.md +1 -0
  2. package/bin/oats.mjs +109 -37
  3. package/docs/capabilities.md +9 -2
  4. package/docs/configuration.md +134 -88
  5. package/docs/desktop-cli-api.md +927 -92
  6. package/docs/desktop-instance-start.md +56 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +144 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +66 -9
  12. package/docs/integrations.md +9 -8
  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/oats-local.schema.json +4 -3
  20. package/docs/official-catalog.md +4 -4
  21. package/docs/packages.md +14 -14
  22. package/docs/release-lane.md +15 -5
  23. package/docs/release-notes/v0.44.0.md +1 -1
  24. package/docs/release-notes/v0.52.0.md +933 -0
  25. package/docs/schedules.md +91 -4
  26. package/docs/souls-and-instances.md +95 -25
  27. package/docs/tui.md +152 -0
  28. package/docs/workspaces.md +2 -2
  29. package/lib/claim.mjs +186 -46
  30. package/lib/core.mjs +730 -185
  31. package/lib/errors.mjs +170 -0
  32. package/lib/harness-trust-write.mjs +68 -27
  33. package/lib/harness-trust.mjs +34 -16
  34. package/lib/instance-inspect.mjs +40 -11
  35. package/lib/instance-lifecycle.mjs +169 -47
  36. package/lib/launch-preference.mjs +16 -0
  37. package/lib/launch-prompt-completion.mjs +7 -43
  38. package/lib/launch-prompt-evidence.mjs +14 -7
  39. package/lib/launch-prompt-fixtures/README.md +86 -152
  40. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  41. package/lib/launch-prompt-fixtures.mjs +122 -109
  42. package/lib/launch-prompt-transport.mjs +2 -56
  43. package/lib/launch-prompts.mjs +102 -100
  44. package/lib/schedule-host.mjs +154 -22
  45. package/lib/schedule.mjs +73 -24
  46. package/lib/system-tools.mjs +39 -0
  47. package/lib/tmux-server-scope.mjs +62 -0
  48. package/lib/triggers.mjs +4 -4
  49. package/lib/workspace.mjs +5 -11
  50. package/lib/worktree-hooks.mjs +98 -20
  51. package/lib/worktree.mjs +83 -24
  52. package/package-catalog.json +3 -3
  53. package/package.json +7 -2
  54. package/packages/client/capability-show-contract.mjs +230 -0
  55. package/packages/client/capability-warnings-contract.mjs +57 -0
  56. package/packages/client/cli-adapter.mjs +548 -0
  57. package/packages/client/cli-environment.mjs +53 -0
  58. package/packages/client/cli-locator.mjs +253 -0
  59. package/packages/client/cli-probe-contract.mjs +47 -0
  60. package/packages/client/client-terms.mjs +60 -0
  61. package/packages/client/deployment-contract.mjs +68 -0
  62. package/packages/client/deployment-data.mjs +483 -0
  63. package/packages/client/deployment-facts.mjs +34 -0
  64. package/packages/client/deployment-label.mjs +76 -0
  65. package/packages/client/deployment-observer.mjs +89 -0
  66. package/packages/client/deployment-panel.mjs +142 -0
  67. package/packages/client/deployment-read-cli.mjs +53 -0
  68. package/packages/client/display-text.mjs +44 -0
  69. package/packages/client/harness-names.mjs +30 -0
  70. package/packages/client/inspect-contract.mjs +62 -0
  71. package/packages/client/instance-acts.mjs +54 -0
  72. package/packages/client/instance-admission.mjs +45 -0
  73. package/packages/client/instance-events-contract.mjs +74 -0
  74. package/packages/client/instance-git-contract.mjs +80 -0
  75. package/packages/client/instance-presentation.mjs +22 -0
  76. package/packages/client/instance-tree.mjs +453 -0
  77. package/packages/client/kernel-environment.mjs +11 -0
  78. package/packages/client/launch-contract.mjs +51 -0
  79. package/packages/client/launch-prompt-outcome.mjs +165 -0
  80. package/packages/client/lifecycle-cli.mjs +61 -0
  81. package/packages/client/lifecycle-contract.mjs +372 -0
  82. package/packages/client/liveness-main.mjs +10 -0
  83. package/packages/client/liveness.mjs +35 -0
  84. package/packages/client/machine-contract.mjs +123 -0
  85. package/packages/client/own-environment.mjs +22 -0
  86. package/packages/client/panel-views.mjs +286 -0
  87. package/packages/client/readiness-contract.mjs +172 -0
  88. package/packages/client/refresh-loop.mjs +52 -0
  89. package/packages/client/remote-address.mjs +126 -0
  90. package/packages/client/remote-roster.mjs +67 -0
  91. package/packages/client/roster-sections.mjs +80 -0
  92. package/packages/client/spawn-apply-cli.mjs +104 -0
  93. package/packages/client/spawn-apply-contract.mjs +183 -0
  94. package/packages/client/spawn-decision.mjs +46 -0
  95. package/packages/client/spawn-messages.mjs +119 -0
  96. package/packages/client/spawn-preview-cli.mjs +32 -0
  97. package/packages/client/spawn-preview-contract.mjs +314 -0
  98. package/packages/client/team-members.mjs +41 -0
  99. package/packages/client/team-rows.mjs +45 -0
  100. package/packages/client/terminal-contract.mjs +57 -0
  101. package/packages/client/tmux-status.mjs +66 -0
  102. package/packages/client/waiting-on-you.mjs +88 -0
  103. package/packages/client/workspace-admission.mjs +45 -0
  104. package/packages/client/workspace-cli.mjs +142 -0
  105. package/packages/client/workspace-views.mjs +147 -0
  106. package/packages/tui/README.md +46 -0
  107. package/packages/tui/bin/tui.mjs +7 -0
  108. package/packages/tui/lib/actions.mjs +29 -0
  109. package/packages/tui/lib/client.mjs +4 -0
  110. package/packages/tui/lib/main.mjs +105 -0
  111. package/packages/tui/lib/term/keys.mjs +323 -0
  112. package/packages/tui/lib/term/screen.mjs +122 -0
  113. package/packages/tui/lib/term/style.mjs +43 -0
  114. package/packages/tui/lib/term/text.mjs +49 -0
  115. package/packages/tui/lib/term/tty.mjs +168 -0
  116. package/packages/tui/lib/term/width.mjs +124 -0
  117. package/packages/tui/lib/views/frame.mjs +62 -0
  118. package/packages/tui/lib/views/help.mjs +28 -0
  119. package/packages/tui/package.json +8 -0
  120. package/skills/oats-getting-started/SKILL.md +29 -22
  121. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  122. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  123. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  124. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  125. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  126. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  127. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  128. 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 {
@@ -50,13 +49,13 @@ import { inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
50
49
  import { appendEvent, liveWaiting, recordStartBoundary } from "./instance-events.mjs";
51
50
  import { killGroup } from "./process-group.mjs";
52
51
  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";
52
+ import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, readClaim, releaseClaim, removeGoneClaim, shownHolder } from "./claim.mjs";
54
53
  import { captureLoginEnvironment } from "./login-environment.mjs";
55
54
 
56
- import { oatsError, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
55
+ 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
56
  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";
57
+ import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchLayers, launchReport, selectionFrom } from "./launch-preference.mjs";
58
+ import { claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigDir } from "./harness-trust.mjs";
60
59
  async function materializePreparedDefault(prepared, home) { const m = await import("./instance-resolution.mjs"); return m.materializePrepared(prepared, home); }
61
60
  // Capability rows for a PREPARED spawn (workspace model): the one function that
62
61
  // turns a Resolution's modules into the row shape hooks/environment/requirements/
@@ -81,6 +80,8 @@ import { canonicalJson, lineAt, parseStrictJson } from "./canonical-json.mjs";
81
80
  import { readPortableBytes } from "./bounded-read.mjs";
82
81
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes } from "./tree-copy.mjs";
83
82
  import { assertSameWorktreeHead, gitRead, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
83
+ import { systemTool } from "./system-tools.mjs";
84
+ import { creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
84
85
  /** The package and capability id grammar (namespaced, lowercase): an id names a
85
86
  * directory (a home's module copy), so no path spelling fits it. */
86
87
  const PACKAGE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
@@ -172,7 +173,7 @@ export function legacyCapturedHomes(root) {
172
173
  }
173
174
  // The tmux session a new tmux instance opens its window in, when oats-local.yaml session.tmuxSession
174
175
  // 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.
176
+ // the same default in packages/client/tmux-status.mjs (it does not import lib/): change both.
176
177
  export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env.PI_AGENTS_TMUX_SESSION || "oats-agents";
177
178
  /**
178
179
  * The tmux session a NEW tmux launch opens its window in (0.31): the caller's, else the deployment's
@@ -590,7 +591,10 @@ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME
590
591
  // The test seams of #796, the same: a worktree hook's fixed timeout, the fetch timeout of
591
592
  // `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
592
593
  // 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"]);
594
+ "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS",
595
+ // The test seams of #915: the cgroup the kernel judges itself in, and the directories its systemd-run
596
+ // comes from (lib/tmux-server-scope.mjs, lib/system-tools.mjs).
597
+ "OATS_TEST_CGROUP", "OATS_TEST_SYSTEM_TOOL_DIRS"]);
594
598
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
595
599
  const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
596
600
  export function validateLaunchConfig(name, entry, where) {
@@ -639,27 +643,63 @@ function validateLaunchConfigs(map, file) {
639
643
  for (const [name, entry] of Object.entries(map)) validateLaunchConfig(name, entry, file);
640
644
  validateLaunchConfigDefaults(map, file);
641
645
  }
642
- export function launchPromptPolicyAt(deployment, home) {
646
+ /** The one-line statement a launch shows when it engages the development-channel
647
+ * confirmation: what it passes, what OATS does, and what stops it. */
648
+ 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).";
649
+ /** The warning of a start where Claude ignored the development-channel flag: the
650
+ * session runs, with no channel. It replaces DEV_CHANNEL_STATEMENT in that start's answer. */
651
+ 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.";
652
+ /** A start's warnings once Claude ignored the flag: the statement that OATS
653
+ * confirms the prompt is replaced by what the outcome means. */
654
+ const flagIgnoredWarnings = warnings => [...warnings.filter(w => w !== DEV_CHANNEL_STATEMENT), FLAG_IGNORED_WARNING];
655
+ /** Whether this launch engages the confirmation: decided from the rendered argv
656
+ * alone, never from provider settings. */
657
+ function devChannelEngaged(harness, command) {
658
+ return launchPromptEngages({ harness, argv: describeLaunchCommand(command).argv });
659
+ }
660
+ /** A start that does not engage the confirmation still records that, so the
661
+ * record always describes the last start. */
662
+ const notEngaged = startId => ({ status: "not-engaged", startId, at: new Date().toISOString() });
663
+ /** The record of a start where Claude ignored the flag: it asked nothing and
664
+ * runs, so nothing waits for a person. Its launch-prompt event holds the receipt. */
665
+ const channelsUnavailable = (startId, result) => ({ status: "flag-ignored", reason: "channels-unavailable", signatureId: result.signatureId, startId, at: new Date().toISOString() });
666
+ /** A started session is launched when the confirmation completed, or when Claude
667
+ * ignored the flag and showed none. */
668
+ const promptLaunched = status => status === "completed" || status === "flag-ignored";
669
+ /** The warning for a host `launchPromptAnswers` block the validator let through
670
+ * (only `true` entries, an empty block, `workspaceTrust`): it is ignored. */
671
+ export function launchPromptAnswersNotice(deployment) {
643
672
  let found;
644
673
  try { found = loadLocal(deployment); }
645
674
  catch (e) { if (e.code !== "E_LOCAL_MISSING") throw e; }
646
- return effectiveLaunchPromptPolicy(found?.local ?? {}, realPathOrNearest(home), found?.path ?? null);
675
+ if (!found?.local || typeof found.local !== "object" || !Object.hasOwn(found.local, "launchPromptAnswers")) return null;
676
+ 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.`;
677
+ }
678
+ /** What a start of `command` says before it runs: the ignored-key notice, then
679
+ * the development-channel statement when the argv engages the confirmation. */
680
+ export function launchStartNotices(deployment, harness, command) {
681
+ return [launchPromptAnswersNotice(deployment), devChannelEngaged(harness, command) ? DEV_CHANNEL_STATEMENT : null].filter(Boolean);
647
682
  }
648
- const promptOptedIn = policy => policy.awebDevelopmentChannel === true;
649
683
  function assertLaunchHome(home, expected) {
650
684
  const actual = directoryIdentity(home);
651
685
  if (!expected || actual.dev !== expected.dev || actual.ino !== expected.ino) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "launch home identity changed");
652
686
  }
653
- function promptController(home, startId, harness, policy, command, io, expectedHomeIdentity) {
687
+ function promptController(home, startId, command, io, expectedHomeIdentity) {
654
688
  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,
689
+ return createLaunchPromptController({ home: realPathOrNearest(home), startId, ...claudeVersionOf(describeLaunchCommand(command).executable), expectedHomeIdentity,
658
690
  transport: launchPromptTransport(io), audit: data => appendEvent(home, { kind: "launch-prompt", data }), retainFrame: retainLaunchPromptFrame,
659
691
  ...(io?.now ? { now: io.now } : {}), ...(io?.sleep ? { sleep: io.sleep } : {}) });
660
692
  }
661
693
  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.`), {
694
+ const hint = launchPrompts.claudeSessionShown ? ` ${CLAUDE_SESSION_HINT}` : "";
695
+ // A screen that never settled established no prompt: nothing to read and answer.
696
+ const enterSent = launchPrompts.answers?.some((a) => a.status === "submitted");
697
+ const advice = neverSettled(launchPrompts.reason)
698
+ ? (enterSent
699
+ ? "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."
700
+ : "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.")
701
+ : "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.";
702
+ 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
703
  instance, home, launched: "unknown",
664
704
  details: { retained: true, unconfirmed: true, instance, home, launched: "unknown", target, parentLineageCommitted, launchPrompts },
665
705
  });
@@ -679,7 +719,6 @@ function incompleteLaunchPrompt(home, startId, target, reason, previous, expecte
679
719
  return { status: "incomplete", answers: previous?.answers ?? [], reason: audit.ok === true ? reason : "launch prompt audit failed",
680
720
  receipt: [...(previous?.receipt ?? []), { ok: audit.ok === true, ...(audit.row ? { row: audit.row } : {}), results: audit.results ?? [] }] };
681
721
  }
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
722
 
684
723
 
685
724
  /** The launch configurations effective at `dir`: the `launch-configs:` of the
@@ -2010,8 +2049,8 @@ function tmuxOatsServer(args, io, options = {}) {
2010
2049
  return (io?.exec || execFileSync)("tmux", ["-u", "-L", OATS_TMUX_SERVER, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...options });
2011
2050
  }
2012
2051
  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_");
2052
+ /** A failed call in one line: the first line of its stderr, else how it ended. */
2053
+ 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
2054
  /** A failed call that ran to its own exit: it has a status, no signal ended it, and Node reports no
2016
2055
  * failure of its own. A timeout and an output overflow carry a code and keep what the call had
2017
2056
  * printed until then, so that text is not the call's answer. Anything else is not a completed call. */
@@ -2027,7 +2066,7 @@ function oatsTmuxSessionSocket(session, io, missingSocket) {
2027
2066
  let listed;
2028
2067
  try { listed = tmuxOatsServer(["list-sessions", "-F", "#{session_name}\t#{socket_path}"], io); }
2029
2068
  catch (e) {
2030
- if (oatsCoded(e)) throw e;
2069
+ if (isKernelCode(e?.code)) throw e;
2031
2070
  // A tmux that could not be run at all is the one failure a person can act on: say so.
2032
2071
  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
2072
  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 +2295,7 @@ function recordedServerEnvironment(caller, session, io) {
2256
2295
  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
2296
  let target;
2258
2297
  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})`) }; }
2298
+ 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
2299
  if (!target?.socket) return { read: null, error: refuse(`the home of ${basename(caller.home)} records no tmux server`) };
2261
2300
  // Bytes, not text; and nothing of a failed read (tmux's output, its error) goes into the refusal.
2262
2301
  let read = null;
@@ -2264,7 +2303,7 @@ function recordedServerEnvironment(caller, session, io) {
2264
2303
  try {
2265
2304
  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
2305
  read = parseTmuxShellEnvironment(Buffer.isBuffer(printed) ? printed : Buffer.from(String(printed)), omitted);
2267
- } catch (e) { if (oatsCoded(e)) throw e; }
2306
+ } catch (e) { if (isKernelCode(e?.code)) throw e; }
2268
2307
  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
2308
  // A variable the reader left out is never filled in from this process, and a server is never
2270
2309
  // started when the one left out decides which configuration it loads or which programs it runs.
@@ -2328,7 +2367,7 @@ function panePath(socket, session, io, cwd) {
2328
2367
  try {
2329
2368
  const printed = (io?.exec || execFileSync)("tmux", ["-u", "-S", socket, "show-environment", ...scope, "-s"], { timeout: 10000, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
2330
2369
  env = parseTmuxShellEnvironment(Buffer.isBuffer(printed) ? printed : Buffer.from(String(printed)), omitted, cleared);
2331
- } catch (e) { if (oatsCoded(e)) throw e; }
2370
+ } catch (e) { if (isKernelCode(e?.code)) throw e; }
2332
2371
  return { env, omitted, cleared };
2333
2372
  };
2334
2373
  const decide = ({ env, omitted, cleared }, source, unset) => {
@@ -2384,8 +2423,12 @@ function launchLookup(configEnv, env, pane, configName, cwd) {
2384
2423
  * its own PATH names no tmux to create it with (creatorTmux). `missingSocket` is a session start's
2385
2424
  * check of its home when the server's socket file is missing (oatsTmuxSessionSocket): with a reason,
2386
2425
  * E_SESSION_UNKNOWN and no server is created at that path.
2426
+ * A creator inside a systemd service on Linux starts the server in a scope of its own
2427
+ * (lib/tmux-server-scope.mjs, awebai/oats#915): the same tmux argv and environment, run by the
2428
+ * system's `systemd-run --user --scope`. When that cannot be done, the server starts as before and
2429
+ * `warnings` (the caller's answer's) says it lives inside that service.
2387
2430
  */
2388
- export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket) {
2431
+ export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket, warnings) {
2389
2432
  let { server: socket, present } = oatsTmuxSessionSocket(session, io, missingSocket);
2390
2433
  if (!present) {
2391
2434
  // The executable is chosen here, where the creation is about to run, and nowhere earlier: a
@@ -2395,10 +2438,38 @@ export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket) {
2395
2438
  // this call starts gets what a server start gets.
2396
2439
  const env = plan?.env && (plan.startsServer || socket) ? plan.env : oatsSessionEnvironment(session, io, { startsServer: !socket });
2397
2440
  const address = socket ? ["-S", socket] : ["-L", OATS_TMUX_SERVER];
2441
+ const args = ["-u", ...address, "new-session", "-d", "-s", session, "-n", "hq", "-c", hq, "-P", "-F", "#{socket_path}\t#{window_id}"];
2442
+ const options = { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], env };
2443
+ const run = (file, argv) => (io?.exec || execFileSync)(file, argv, options).trim();
2444
+ // Inside a service: the scope to start in, or the warning a start by this process carries.
2445
+ const scope = serverScopePlan(creatorPlacement(io));
2446
+ let wrapper = null, unscoped = scope.warn ? serverScopeWarning(scope.warn) : null;
2447
+ if (scope.wrap) {
2448
+ // The scope's own INVOCATION_ID, which systemd-run exports to what it runs, is removed by the
2449
+ // system's env, so the server starts with `env` less any INVOCATION_ID: without both tools, no scope.
2450
+ const where = io?.systemToolDirs ? { dirs: io.systemToolDirs } : {};
2451
+ const systemdRun = systemTool("systemd-run", where), clean = systemTool("env", where);
2452
+ if (systemdRun.file && clean.file) wrapper = [systemdRun.file, ["--user", "--scope", "--collect", "--quiet", "--unit", serverScopeUnit({ socket, env }), "--", clean.file, "-u", "INVOCATION_ID"]];
2453
+ else unscoped = serverScopeWarning({ unit: scope.unit, reason: systemdRun.reason ?? clean.reason });
2454
+ }
2455
+ /** Started by this process outside a scope: said once it has started. */
2456
+ const plain = () => { const out = run(tmux, args); if (unscoped) warnings?.push(unscoped); return out; };
2398
2457
  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(); }
2458
+ try {
2459
+ if (!wrapper) created = plain();
2460
+ else {
2461
+ try { created = run(wrapper[0], [...wrapper[1], tmux, ...args]); }
2462
+ catch (e) {
2463
+ if (isKernelCode(e?.code)) throw e;
2464
+ // Another creator's server (its scope already exists) answers: started, by it.
2465
+ const again = oatsTmuxSessionSocket(session, io, missingSocket);
2466
+ if (again.present) socket = again.server;
2467
+ else { unscoped = serverScopeWarning({ unit: scope.unit, reason: failureLine(e) }); created = plain(); }
2468
+ }
2469
+ }
2470
+ }
2400
2471
  catch (e) {
2401
- if (oatsCoded(e)) throw e;
2472
+ if (isKernelCode(e?.code)) throw e;
2402
2473
  const again = oatsTmuxSessionSocket(session, io, missingSocket);
2403
2474
  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
2475
  socket = again.server;
@@ -2431,7 +2502,7 @@ const paneCommand = (command) => `unset COLORFGBG; ${command}; exec "\${SHELL:-/
2431
2502
  function sizeWindow(socket, windowId, io) {
2432
2503
  if (!/^@\d+$/.test(windowId || "")) return;
2433
2504
  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; }
2505
+ try { tmuxOn(socket, ["set-option", "-w", "-t", windowId, option, value], io); } catch (e) { if (isKernelCode(e?.code)) throw e; }
2435
2506
  }
2436
2507
  }
2437
2508
  /** The agent window OATS just created, by the id new-window returned: showing the viewer's colours and
@@ -2669,6 +2740,57 @@ export function upgradeHomeMeta(meta, home) {
2669
2740
  const { runtime, ...rest } = meta;
2670
2741
  return { ...rest, ...(runtime !== undefined || meta.harness !== undefined ? { harness: meta.harness ?? runtime } : {}), ...(meta.launch !== undefined ? { launch: upgradeLaunchRecipe(meta.launch) } : {}) };
2671
2742
  }
2743
+ /** A home's record (`<home>/instance.json`) as it is on disk. Total: it never throws, so that one
2744
+ * home's record decides only for that home (awebai/oats#896). One of:
2745
+ * - `{ state: "record", path, meta }`: the JSON object the file holds, as written (a reader of
2746
+ * the home's harness passes it through upgradeHomeMeta);
2747
+ * - `{ state: "absent", path }`: no entry of that name, or a home this process cannot look into,
2748
+ * where whether there is one cannot be told (answered as a home without a record, as before);
2749
+ * - `{ state: "unreadable", path, reason }`: an entry is there and gives no JSON object: cut off,
2750
+ * empty, kept from this user, a directory, a link to nothing, or JSON that is not an object.
2751
+ * `reason` is the system's or the parser's, in words, without the path.
2752
+ * An unreadable record is never an absent one: the home may be a whole instance with work, and
2753
+ * "cannot read" is not "is not there". */
2754
+ export function readHomeRecord(home) {
2755
+ const path = join(home, "instance.json");
2756
+ const unreadable = (reason) => ({ state: "unreadable", path, reason });
2757
+ let text;
2758
+ try {
2759
+ // Only a regular file is read: a read of a directory fails, and one of a pipe would not return.
2760
+ const entry = statSync(path);
2761
+ if (!entry.isFile()) return unreadable(entry.isDirectory() ? "it is a directory" : "it is not a regular file");
2762
+ text = readFileSync(path, "utf8");
2763
+ } catch (e) {
2764
+ let entry;
2765
+ try { entry = lstatSync(path); } catch { return { state: "absent", path }; }
2766
+ if (entry.isSymbolicLink() && e?.code === "ENOENT") return unreadable("it is a symbolic link to nothing");
2767
+ // The system's words without the path, which the answer already names: `EACCES: permission denied`.
2768
+ return unreadable(String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, ""));
2769
+ }
2770
+ let value;
2771
+ try { value = JSON.parse(text); } catch (e) { return unreadable(String(e?.message ?? e)); }
2772
+ if (!isPlainObject(value)) return unreadable(`it holds ${value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`}, not a JSON object`);
2773
+ return { state: "record", path, meta: value };
2774
+ }
2775
+ /** What an answer says of a record that cannot be read (readHomeRecord): the file and the reason. */
2776
+ const unreadableRecordSaid = (record) => `${record.path} cannot be read (${record.reason})`;
2777
+ /** The refusal of a lifecycle verb (retire, stop, session start) for a home whose record is there
2778
+ * and cannot be read: E_UNIDENTIFIED_INSTANCE_HOME, with the file, the reason, `nothing` (what the
2779
+ * verb had done by then: nothing; a spawn that names the home says "nothing was spawned") and the
2780
+ * one remedy that exists. Every caller raises it before any effect: a client reads this code from
2781
+ * a stop or a retire as "refused, nothing happened". `--force` does not apply to it: it removes a
2782
+ * home that has NO record, never, blind, one whose record cannot be read. */
2783
+ function unreadableRecordRefusal(record, nothing = "nothing was done") {
2784
+ 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.`);
2785
+ }
2786
+ /** The one check a lifecycle verb makes when it has resolved its home, before it takes a claim or
2787
+ * reads anything of the home: a record that cannot be read refuses the verb (unreadableRecordRefusal).
2788
+ * → the record as read (readHomeRecord), a record or an absent one. */
2789
+ export function identifiedHomeRecord(home, nothing) {
2790
+ const record = readHomeRecord(home);
2791
+ if (record.state === "unreadable") throw unreadableRecordRefusal(record, nothing);
2792
+ return record;
2793
+ }
2672
2794
  const LAUNCH_PROMPT = { kind: "task-file", file: "TASK.md" };
2673
2795
  /** The fixed prompt a codex launch starts with: it names the task file, never its text (argv is
2674
2796
  * readable by every local user). Codex reads the file with a tool. */
@@ -2809,12 +2931,15 @@ export function homeLaunchLayers(realHome, meta) {
2809
2931
  /** A NEW launch selection (a spawn, or a start/restart that reselects) from the flags and the launch
2810
2932
  * layers (lib/launch-preference.mjs). → { launchSelection (resolveLaunchSelection's), launchChoice:
2811
2933
  * { 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 }) {
2934
+ * naming the layer. `refuseAmbiguous` (a spawn) refuses a launch that names no configuration among
2935
+ * several with no default (E_LAUNCH_CONFIG_AMBIGUOUS). Never reads a frozen recipe. */
2936
+ export function selectNewLaunch({ launchConfigs = {}, agent, flags = {}, layers = null, refuseAmbiguous = false }) {
2814
2937
  const choice = selectionFrom({ flags, layers });
2815
2938
  const named = choice.from !== "flag" && choice.selection.launchConfig !== undefined && choice.selection.launchConfig !== "none" ? choice.selection.launchConfig : null;
2816
2939
  if (named !== null && !Object.hasOwn(launchConfigs, named)) throw launchConfigUnknown({ name: named, from: choice.from, at: choice.at });
2817
2940
  const launchSelection = resolveLaunchSelection({ launchConfigs, agent: layers ? {} : agent, selection: choice.selection, preference: choice.preference });
2941
+ const ambiguous = refuseAmbiguous ? launchConfigAmbiguous({ launchConfigs, harness: launchSelection.harness, config: launchSelection.config, choice }) : null;
2942
+ if (ambiguous) throw ambiguous;
2818
2943
  return { launchSelection, launchChoice: { from: choice.from, at: choice.at, declared: layers?.declared ?? null } };
2819
2944
  }
2820
2945
  /** The `Launch` report (feature launch-preference) a spawn with no flags would decide HERE, for listings
@@ -2834,6 +2959,8 @@ export function launchReportFor({ layers, launchConfigs = {}, contextDir }) {
2834
2959
  } else if (choice.preference) { harness = choice.preference.harness; model = choice.preference.model ?? null; }
2835
2960
  // As a spawn: a layer naming "none" asks for the bare harness; otherwise no configuration is the harness default.
2836
2961
  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; }
2962
+ const ambiguous = launchConfigAmbiguous({ launchConfigs, harness, config, choice });
2963
+ if (ambiguous) return report(harness, model, null, { code: ambiguous.code, message: ambiguous.message, fix: ambiguous.details.fix });
2837
2964
  let exe;
2838
2965
  try { exe = resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir }); }
2839
2966
  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 +3046,21 @@ function deploymentOfHome(home, meta) {
2919
3046
  if (dirname(d) === d) return realPathOrNearest(dirname(dirname(dirname(dirname(resolve(home))))));
2920
3047
  }
2921
3048
  }
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 }) {
3049
+ /** Folder trust for a launch in `home` (lib/harness-trust.mjs, read-only), read from the file the
3050
+ * launch's own env selects (the host `env` and the launch configuration's `configEnv`): `trustHome`
3051
+ * — the codex launch trusts the home, because that file trusts its deployment root or an ancestor
3052
+ * — `covered`, the `file` read (or the `problem` that keeps it unresolved) and the warning when
3053
+ * folder trust is not established there. */
3054
+ export function launchFolderTrust({ harness, home, meta, yolo, env = process.env, configEnv = {}, launchConfig = null }) {
3055
+ if (harness !== "codex" && harness !== "claude") return { trustHome: false, covered: false, file: null, warning: null };
2926
3056
  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 };
3057
+ const unresolved = launchConfigDir(harness, configEnv, env)?.problem;
3058
+ const launchEnv = launchEffectiveEnv({ base: env, configEnv });
3059
+ const file = unresolved ? null : harnessConfigFile(harness, launchEnv);
3060
+ const problem = unresolved && `launch configuration ${launchConfig || "(recorded)"}: ${unresolved}`;
3061
+ const trustHome = !unresolved && harness === "codex" && codexTrustsRoot(root, { env: launchEnv });
3062
+ const covered = harness === "codex" ? trustHome || yolo === true : !unresolved && claudeTrusts(home, { env: launchEnv });
3063
+ return { trustHome, covered, file, ...(problem ? { problem } : {}), warning: harnessTrustWarning({ harness, root, file, problem, covered }) };
2933
3064
  }
2934
3065
 
2935
3066
  /** The harness command line of a recipe. With no configuration the bytes
@@ -3150,11 +3281,12 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3150
3281
  ...(frozen?.legacy ? { legacy: { ...frozen.legacy, ...(hooks.refreshed?.length ? { replacedBy: hooks.refreshed } : {}) } } : {}),
3151
3282
  };
3152
3283
  const inst = instance || meta?.instance || basename(home);
3153
- const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, env });
3284
+ const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, env, configEnv, launchConfig: config?.name });
3154
3285
  const command = renderLaunchRecipe(recipe, { home, instance: inst, trustHome });
3155
3286
  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 } : {}) };
3287
+ // A preview states what the start will do; the start states it in its own output.
3288
+ const previewNotices = preview ? launchStartNotices(dirname(dirname(dirname(dirname(home)))), harness, command) : [];
3289
+ 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
3290
  }
3159
3291
  /** The environment a planned launch runs under: the host's base, the
3160
3292
  * capabilities' validated env, the configuration's literals and its
@@ -3270,7 +3402,7 @@ function* spawnBody(root, agent, o = {}) {
3270
3402
  // Feature launch-preference: the flags, else the machine's souls.launch, else the soul's own launch,
3271
3403
  // else the host default — `launchChoice` says which layer decided (instance.json launchFrom/launchAt).
3272
3404
  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 })); }
3405
+ 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
3406
  catch (e) { previewPreflightBudget = null; throw e; }
3275
3407
  const launchConfig = launchSelection.config;
3276
3408
  const harness = launchSelection.harness;
@@ -3498,6 +3630,9 @@ function* spawnBody(root, agent, o = {}) {
3498
3630
  }
3499
3631
  }
3500
3632
  }
3633
+ // The anchor's record gives the lineage, and a parent's its child-spawn policy: one that is there
3634
+ // and cannot be read refuses the spawn, which would otherwise guess either (#896).
3635
+ if (anchorHome) identifiedHomeRecord(anchorHome, "nothing was spawned");
3501
3636
  const anchorMetaPath = anchorHome ? join(anchorHome, "instance.json") : undefined;
3502
3637
  const anchorOriginal = anchorMetaPath && existsSync(anchorMetaPath) ? readFileSync(anchorMetaPath, "utf8") : null;
3503
3638
  const anchorMeta = anchorOriginal === null ? undefined : JSON.parse(anchorOriginal);
@@ -3532,7 +3667,8 @@ function* spawnBody(root, agent, o = {}) {
3532
3667
  if (parentInstance && parentInstance !== instance) {
3533
3668
  const parentHome = parentInstance === relativeTo && anchorHome ? anchorHome
3534
3669
  : findInstanceHome(root, parentInstance)?.home;
3535
- const parentMeta = parentHome && existsSync(join(parentHome, "instance.json")) ? JSON.parse(readFileSync(join(parentHome, "instance.json"), "utf8")) : anchorMeta;
3670
+ const parentRecord = parentHome ? identifiedHomeRecord(parentHome, "nothing was spawned") : undefined;
3671
+ const parentMeta = parentRecord?.state === "record" ? parentRecord.meta : anchorMeta;
3536
3672
  const policy = childPolicyOf(parentMeta);
3537
3673
  if (policy.allowed === false) {
3538
3674
  // A preview touches nothing — not even the parent's event log; the
@@ -3699,7 +3835,7 @@ function* spawnBody(root, agent, o = {}) {
3699
3835
  d.revision = createHash("sha256").update(canonicalJson(d)).digest("hex").slice(0, 24);
3700
3836
  return d;
3701
3837
  };
3702
- const launchPromptAnswers = launchPromptPolicyAt(o.prepared.deployment || workspaceOf(root), home);
3838
+ const launchPromptNotice = launchPromptAnswersNotice(o.prepared.deployment || workspaceOf(root));
3703
3839
  if (o.preview === true) {
3704
3840
  const decision = buildDecision();
3705
3841
  // Workspace model (M3): the preview reports what APPLY will produce — every
@@ -3717,14 +3853,15 @@ function* spawnBody(root, agent, o = {}) {
3717
3853
  // Addendum 5: where each leaf of `settings.<cap>` came from (JSON pointer → { kind, at }):
3718
3854
  // manifest-default | workspace | soul | host | spawn, the last layer that set it.
3719
3855
  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))];
3856
+ // The preview's warnings are strings: the launchPromptAnswers notice, then what a module declares and this kernel ignores.
3857
+ // The development-channel statement is the apply's: no launch hook runs here, so the argv is unknown.
3858
+ const previewWarnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution))];
3722
3859
  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
3860
  return deliver({
3724
3861
  // Team model v2: the soul's teams here (unmapped rows included) and its default — the choice a
3725
3862
  // Desktop offers before anything is minted; joining any but the default is the provider's explicit act.
3726
3863
  ...{ 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,
3864
+ spawnPreviewApi: 2, preview: true, ...(previewWarnings.length ? { warnings: previewWarnings } : {}), agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
3728
3865
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
3729
3866
  decision, preflight,
3730
3867
  backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
@@ -4047,7 +4184,7 @@ function* spawnBody(root, agent, o = {}) {
4047
4184
  }
4048
4185
 
4049
4186
  // 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))];
4187
+ const warnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared?.resolution))];
4051
4188
 
4052
4189
  // Establish directory ownership while these are still the kernel's own roots.
4053
4190
  // A hook may replace either path; it must never mint authority for that target.
@@ -4381,7 +4518,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4381
4518
  prompt: LAUNCH_PROMPT, kernelBin: shimTarget,
4382
4519
  };
4383
4520
  if (triggerEventFile) recipe.env.OATS_TRIGGER_EVENT_FILE = triggerEventFile;
4384
- const folderTrust = launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo });
4521
+ const folderTrust = launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo, configEnv: launchConfig?.env, launchConfig: launchConfig?.name });
4385
4522
  if (folderTrust.warning) warnings.push(folderTrust.warning);
4386
4523
  let cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
4387
4524
 
@@ -4488,7 +4625,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4488
4625
  if (launch) {
4489
4626
  // The session on the OATS server, then everything on the one socket that answered: the collision
4490
4627
  // check, the records, the window and (in compensateSpawn) its removal.
4491
- const socket = ensureOatsTmuxSession(session, existsSync(root) ? root : workspaceOf(root), undefined, tmuxSessionPlan);
4628
+ const socket = ensureOatsTmuxSession(session, existsSync(root) ? root : workspaceOf(root), undefined, tmuxSessionPlan, undefined, spawnWarnings);
4492
4629
  // The harness looked up again on the PATH this window's pane will actually start with, whoever
4493
4630
  // created the session and with whatever environment (a race lost to another creator, a session
4494
4631
  // that overrides PATH). Not there: refused, and the spawn is compensated. Found elsewhere than
@@ -4510,6 +4647,10 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4510
4647
  if (present.includes(instance)) throw new Error(`tmux window "${instance}" already exists in session ${session}`);
4511
4648
  meta.tmux.socket = socket;
4512
4649
  meta.launched = true;
4650
+ promptStartId = randomUUID();
4651
+ const engaged = devChannelEngaged(harness, cmdline);
4652
+ if (engaged) warnings.push(DEV_CHANNEL_STATEMENT);
4653
+ else meta.launchPrompts = notEngaged(promptStartId);
4513
4654
  // Commit the final child metadata and its independent byte authority before
4514
4655
  // the managed harness can write. No child-home transition follows launch.
4515
4656
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n");
@@ -4520,13 +4661,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4520
4661
  const windowCmd = paneCommand(executionCommand);
4521
4662
  const paneEnvFlags = launchEnvRefs(recipe, process.env).flatMap((r) => ["-e", `${r.name}=${r.value}`]);
4522
4663
  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;
4664
+ // Only a launch that engages the confirmation needs lineage committed before
4665
+ // dispatch: its uncertain input outcome retains the new process and parent
4666
+ // link. Other launches keep their established post-launch commit/rollback.
4667
+ if (engaged) commitParentLineage();
4668
+ const controller = engaged ? promptController(home, promptStartId, cmdline, undefined, createdHomeIdentity) : null;
4530
4669
  windowMayExist = true;
4531
4670
  promptDispatched = !!controller;
4532
4671
  let windowId;
@@ -4538,10 +4677,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4538
4677
  catch (e) { throw launchFailed("set-option", "the new window's options were refused", e); }
4539
4678
  if (controller) {
4540
4679
  promptResult = controller.observeNew(promptTarget);
4541
- meta.launchPrompts = promptResult;
4680
+ if (promptResult.status === "flag-ignored") warnings.splice(0, warnings.length, ...flagIgnoredWarnings(warnings));
4681
+ meta.launchPrompts = promptResult.status === "flag-ignored" ? channelsUnavailable(promptStartId, promptResult) : promptResult;
4542
4682
  meta.launchPromptTarget = promptTarget;
4543
4683
  meta.parentLineageCommitted = parentLineageCommitted;
4544
- meta.launched = promptResult.status === "completed";
4684
+ meta.launched = promptLaunched(promptResult.status);
4545
4685
  assertLaunchHome(home, createdHomeIdentity);
4546
4686
  writeJsonAtomic(join(home, "instance.json"), meta);
4547
4687
  if (!meta.launched) throw retainedPromptError(home, instance, promptTarget, parentLineageCommitted, promptResult);
@@ -4553,8 +4693,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4553
4693
  clearSpawnInProgressMarker();
4554
4694
  }
4555
4695
 
4556
- // Ordinary launches and scaffolds commit here; opted-in launches already
4557
- // committed before dispatch so retained prompt failures keep their lineage.
4696
+ // Ordinary launches and scaffolds commit here; launches that engage the
4697
+ // development-channel confirmation already committed before dispatch, so
4698
+ // retained prompt failures keep their lineage.
4558
4699
  commitParentLineage();
4559
4700
 
4560
4701
  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 +4708,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4567
4708
  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
4709
  } catch (error) {
4569
4710
  if (promptDispatched) {
4570
- // Once opted-in launch dispatch occurred, uncertainty retains all effects.
4711
+ // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
4571
4712
  // The independent baseline remains launched:true: metadata is not proof of quiescence.
4572
4713
  let result = promptResult?.status === "blocked" || promptResult?.status === "incomplete" ? promptResult : incompleteLaunchPrompt(home, promptStartId, promptTarget ?? spawnTmux, "launch prompt dispatch or recording incomplete", promptResult, createdHomeIdentity);
4573
4714
  try {
@@ -4686,11 +4827,11 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
4686
4827
  return (existsSync(instancesDir) ? readdirSync(instancesDir, { withFileTypes: true }) : [])
4687
4828
  .filter((e) => e.isDirectory() && !e.name.startsWith("."))
4688
4829
  .map((e) => {
4689
- const metaPath = join(instancesDir, e.name, "instance.json");
4690
4830
  const home = join(instancesDir, e.name);
4691
- const meta = existsSync(metaPath)
4692
- ? upgradeHomeMeta(JSON.parse(readFileSync(metaPath, "utf8")), home)
4693
- : { instance: e.name, home };
4831
+ // The record decides for this home only: one that is there and cannot be read gives the
4832
+ // row of a home without a record, whose liveness says why (below), never a failed listing.
4833
+ const record = readHomeRecord(home);
4834
+ const meta = record.state === "record" ? upgradeHomeMeta(record.meta, home) : { instance: e.name, home };
4694
4835
  // A home retained by an incomplete rollback is NOT a live instance: it
4695
4836
  // is preserved state awaiting cleanup, and must read that way.
4696
4837
  const fallback = directoryRollbackPath(home);
@@ -4717,7 +4858,9 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
4717
4858
  catch { retirePending = { reason: "retire pending" }; }
4718
4859
  }
4719
4860
  // 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)))
4861
+ // A home whose record cannot be read is listed, never observed: where its session is, is in the record.
4862
+ const liveness = record.state === "unreadable" ? { running: null, runtimeState: "unreachable", runtimeError: `E_UNIDENTIFIED_INSTANCE_HOME: ${unreadableRecordSaid(record)}` }
4863
+ : recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(home)))
4721
4864
  ? { running: null, runtimeState: "unsupported", runtimeError: `E_HERDR_REMOVED: ${herdrInstanceRemoved(e.name).message}` }
4722
4865
  : tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name, scanOf(home),
4723
4866
  // A home that records no socket and no launch (--no-launch) reads the default server only
@@ -5907,6 +6050,8 @@ function instanceSessionTarget(home) {
5907
6050
  if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home);
5908
6051
  throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${e.message}`);
5909
6052
  }
6053
+ // A record that is JSON and no object gives no endpoint to compare the receipt with.
6054
+ if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${join(home, "instance.json")} holds no JSON object`);
5910
6055
  const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
5911
6056
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
5912
6057
  if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
@@ -5919,7 +6064,8 @@ export function inspectInstanceSession(home) {
5919
6064
  if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", waitingOnYou: null };
5920
6065
  let observed;
5921
6066
  try { observed = inspectSessionTarget(s.target); }
5922
- catch (e) { throw oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`); }
6067
+ // The tmux failure stays the cause: sessionServerGone judges it.
6068
+ catch (e) { throw Object.assign(oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`), { cause: e }); }
5923
6069
  // Feature waiting-on-you: beside `state`, whose enum is unchanged.
5924
6070
  return { home: s.home, ...observed, waitingOnYou: harnessRunning(observed) ? liveWaiting(s.home) : null };
5925
6071
  }
@@ -5940,6 +6086,15 @@ function tmuxServerAbsence(e) {
5940
6086
  return null;
5941
6087
  }
5942
6088
  function tmuxServerLost(e) { return tmuxServerAbsence(e) !== null; }
6089
+ /** Whether the tmux server of `home`'s recorded session is gone, judged from `error`, a failed tmux
6090
+ * call on its socket (#921). No server on the socket is gone. A missing socket file is gone only when
6091
+ * no process works in the home (#624); otherwise `why` says what is not established. Any other
6092
+ * failure is not gone, with no `why`. → { gone, why } */
6093
+ export function sessionServerGone(home, error, io) {
6094
+ const absence = tmuxServerAbsence(error);
6095
+ const why = absence === "missing-socket" ? missingSocketUnestablished(tmuxFailure(error, error.message), processesInHome(home, io)) : null;
6096
+ return { gone: absence !== null && !why, why };
6097
+ }
5943
6098
  /** tmux's own way back for a server that lost its socket file (tmux(1), `-S`). Named, never performed. */
5944
6099
  const TMUX_SOCKET_REMEDY = "tmux recreates a removed socket file when its server process receives SIGUSR1";
5945
6100
  /** Processes as a refusal names them: pid and program, at most five, then how many more. */
@@ -6116,35 +6271,106 @@ function recordedSessionAbsence(home, meta, io) {
6116
6271
  * file is idle only when no process works in the home (#624). */
6117
6272
  export function stopInstanceSession(home, o = {}) {
6118
6273
  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");
6274
+ requireStopGrace(o.graceMs);
6275
+ // Under the home's lifecycle claim, the caller's (STOP_UNDER_CLAIM: a stop apply holds the claim
6276
+ // of every target before it stops the first) or, for the span of this one stop, its own (a
6277
+ // retire stopping a recorded child): no retire inspects or removes a home this stop writes
6278
+ // into, and a holder is answered before anything is signalled (lifecycleClaimRefusals:
6279
+ // E_INSTANCE_RETIRING beside a retire, E_LIFECYCLE_BUSY beside a stop). A home that is not
6280
+ // there has no claim to take and nothing to stop: it answers as it always did.
6281
+ if (o[STOP_UNDER_CLAIM] || !existsSync(home)) return stopSessionClaimed(home, o);
6282
+ const held = claimHomeFor("stop", basename(home), home);
6283
+ try { return stopSessionClaimed(home, o); } finally { releaseHomeClaim(held); }
6284
+ }
6285
+ /** An option of stopInstanceSession: the caller holds the home's lifecycle claim (claimHomeFor)
6286
+ * for this stop. A symbol, so no caller can set it from parsed arguments or JSON. */
6287
+ export const STOP_UNDER_CLAIM = Symbol("oats.stopUnderClaim");
6288
+ /** Refuse a stop's grace that is not 1-300000 ms (undefined is the default): before any effect. */
6289
+ export function requireStopGrace(graceMs) {
6290
+ if (graceMs !== undefined && (!Number.isSafeInteger(graceMs) || graceMs < 1 || graceMs > 300000)) throw oatsError("E_BAD_ARGS", "stop grace must be 1-300000 ms");
6291
+ }
6292
+ /** The stop of stopInstanceSession, under the home's claim. The pending self-retire marker is read
6293
+ * here, under it: a `--self` retire writes the marker while it holds the claim. */
6294
+ function stopSessionClaimed(home, o) {
6120
6295
  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
- }
6296
+ // `signalling`: the stop reached the step that signals the harness; `receipt`: that step's answer.
6297
+ let signalling = false, receipt;
6298
+ try {
6299
+ if (existsSync(retirePendingMarkerPath(realHome))) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired; nothing was stopped`);
6300
+ const s = instanceSessionTarget(realHome);
6301
+ if (!s.target) return { home: s.home, backend: null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
6302
+ let before;
6303
+ try { before = inspectSessionTarget(s.target); }
6304
+ catch (e) {
6305
+ const lost = sessionServerGone(realHome, e, o.io);
6306
+ if (lost.gone) before = { present: false, state: "stopped" };
6307
+ else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${lost.why ?? e.message}`);
6308
+ }
6309
+ 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 };
6310
+ signalling = true;
6311
+ receipt = stopHarness(s.target, { graceMs: o.graceMs ?? 20000, kill: o.io?.kill, sleep: o.io?.sleep });
6312
+ writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: receipt, retained: ["home", "work", "transcript", "launch"] });
6313
+ appendEvent(realHome, { kind: receipt.exited ? "stopped" : "stop-refused", data: { signal: receipt.signal, waitedMs: receipt.waitedMs, stillRunning: receipt.stillRunning ?? [], state: receipt.state } });
6314
+ 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 });
6315
+ return { home: s.home, backend: s.target.backend, stopped: true, alreadyIdle: false, state: receipt.state, receipt };
6316
+ } catch (e) {
6317
+ // An error that is not the kernel's (the home removed under the stop, a write refused) is a
6318
+ // stop that failed, never the system's code (awebai/oats#891): its text, and what is true of
6319
+ // the harness by then. The receipt goes with it, so the caller reports what it established.
6320
+ // A receipt alone is not a signal: stopHarness answers one for a harness it found idle, having
6321
+ // signalled nothing (`sentAt: null`), and names as "already gone" a process its signal missed.
6322
+ const reached = receipt?.sentAt != null && receipt.requested.some((r) => r.note !== "already gone");
6323
+ const harness = reached ? `its harness was signalled (${receipt.signal}) and ${receipt.exited ? "has exited" : "is still running"}`
6324
+ : receipt ? `no signal reached its harness, which ${receipt.exited ? "had already exited" : "was not seen to exit"}`
6325
+ : signalling ? "whether its harness was signalled is not known" : "its harness was not signalled";
6326
+ const failure = isAnswerCode(e?.code) ? e : Object.assign(asKernelError(e, "E_SESSION_STOP_FAILED", `${basename(realHome)}: ${e?.message ?? e}; ${harness}`), receipt ? { receipt } : {});
6327
+ if (signalling) stopsThatSignalled.add(failure);
6328
+ throw failure;
6329
+ }
6330
+ }
6331
+ /** What a failed stop (an error of stopInstanceSession) established of the processes it signalled,
6332
+ * for its row of results: [] only when its receipt says the harness exited; the pids its receipt
6333
+ * names as still alive; and null when nothing is established. That is a stop without a receipt,
6334
+ * and one whose receipt says "not exited" and names no live pid: every process it signalled is
6335
+ * gone but the session did not read as idle (stopHarness's last answer), so something still runs
6336
+ * there that the stop cannot name. A reader takes [] as "stopped", which that is not. */
6337
+ export function stillRunningOf(e) {
6338
+ const receipt = e?.receipt;
6339
+ if (!receipt) return null;
6340
+ if (receipt.exited) return [];
6341
+ return Array.isArray(receipt.stillRunning) && receipt.stillRunning.length ? receipt.stillRunning : null;
6342
+ }
6343
+ /** What a retire says of the recorded children that did not stop (`rows`, each `ok: false`). A
6344
+ * child is "still running" only where its stop established processes that run (`stillRunning`
6345
+ * lists them). Of any other nothing of the kind is known: its stop was refused before it began (a
6346
+ * claim held, a self-retire scheduled) or failed, and it is said with its row's code. */
6347
+ function childrenNotStopped(rows) {
6348
+ const established = (k) => Array.isArray(k.stillRunning) && k.stillRunning.length > 0;
6349
+ const running = rows.filter(established);
6350
+ return [...(running.length ? [`${running.map((k) => k.instance).join(", ")} ${running.length === 1 ? "is" : "are"} still running after a bounded stop`] : []),
6351
+ ...rows.filter((k) => !established(k)).map((k) => `${k.instance} could not be stopped (${k.code})`)].join("; ");
6352
+ }
6353
+
6354
+ /** The errors of stopInstanceSession thrown once it had reached the step that signals the harness:
6355
+ * whoever reports what a stop touched (a retire's `reached.sessionStopAttempted`) reads it here. */
6356
+ const stopsThatSignalled = new WeakSet();
6139
6357
 
6140
6358
  /** What a retire plan promises about recorded children, applied: each is stopped
6141
6359
  * (default grace, never escalated) in the order given (the plan's: deepest first)
6142
6360
  * 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) {
6361
+ * still running or whose stop could not be established. `signalled` is called
6362
+ * for each child whose stop reached the step that signals its harness. */
6363
+ function stopRecordedChildren(children, signalled) {
6145
6364
  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 }; }
6365
+ try {
6366
+ const s = stopInstanceSession(kid.home, {});
6367
+ if (s.stopped) signalled?.();
6368
+ return { instance: kid.instance, home: kid.home, ok: true, stopped: s.stopped, alreadyIdle: s.alreadyIdle };
6369
+ } catch (e) {
6370
+ if (stopsThatSignalled.has(e)) signalled?.();
6371
+ reportDefect(e); // the error becomes a row here: its stack would otherwise be lost
6372
+ return { instance: kid.instance, home: kid.home, ok: false, code: kernelCode(e, "E_SESSION_STOP_FAILED"), message: e.message, stillRunning: stillRunningOf(e) };
6373
+ }
6148
6374
  });
6149
6375
  }
6150
6376
 
@@ -6509,6 +6735,8 @@ export function preWorkspaceHome(home, what) {
6509
6735
  }
6510
6736
  export function startInstanceSession(home, o = {}) {
6511
6737
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session start needs an absolute instance home");
6738
+ // A home whose record is there and cannot be read is refused before anything of it is read (#896).
6739
+ identifiedHomeRecord(home);
6512
6740
  // A home opened in Herdr, or an earlier start that allocated a Herdr pane, is refused before any
6513
6741
  // guard or receipt reads it.
6514
6742
  refuseHerdrHome(realPathOrNearest(home));
@@ -6531,7 +6759,12 @@ export function startInstanceSession(home, o = {}) {
6531
6759
  const lock = join(realHome, ".oats-start.lock");
6532
6760
  const pendingPath = join(realHome, ".oats-start-pending.json");
6533
6761
  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}`); } };
6762
+ // The same reader as the check above: a record that became unreadable since then refuses as there.
6763
+ const readMeta = () => {
6764
+ const record = identifiedHomeRecord(realHome);
6765
+ if (record.state !== "record") throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${metaPath}: it is no longer there`);
6766
+ return upgradeHomeMeta(record.meta, realHome);
6767
+ };
6535
6768
  // Workspace-model homes only (lead decision c3 Q2): a home an earlier kernel
6536
6769
  // spawned records no modules, and there is no scope configuration left to
6537
6770
  // re-resolve it against. Retire still works on it.
@@ -6542,9 +6775,8 @@ export function startInstanceSession(home, o = {}) {
6542
6775
  // passes), else `{ stopped: false, why }`: the check's reason, or null for another failure.
6543
6776
  const missingSocket = (detail) => missingSocketUnestablished(detail, processesInHome(realHome, rawIo));
6544
6777
  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 };
6778
+ const lost = sessionServerGone(realHome, e, rawIo);
6779
+ return lost.gone ? { stopped: true } : { stopped: false, why: lost.why };
6548
6780
  };
6549
6781
  const launchFailure = (error) => {
6550
6782
  // execFileSync errors embed argv (including capability environment) in
@@ -6577,9 +6809,11 @@ export function startInstanceSession(home, o = {}) {
6577
6809
  // Launch-hook meta lands per capability over the spawn's record; a hook
6578
6810
  // that answered without meta keeps its previous entry (retire reads it).
6579
6811
  ...(hookMeta ? { capabilityMeta: { ...(meta.capabilityMeta || {}), ...hookMeta } } : {}) };
6580
- if (launchPrompts) {
6812
+ // The record describes the last start, a start that did not engage the confirmation included.
6813
+ if (launchPrompts?.status === "not-engaged") { next.launchPrompts = launchPrompts; delete next.launchPromptTarget; }
6814
+ else if (launchPrompts) {
6581
6815
  next.launchPrompts = launchPrompts; next.launchPromptTarget = launchPromptTarget ?? target;
6582
- next.launched = launchPrompts.status === "completed";
6816
+ next.launched = promptLaunched(launchPrompts.status);
6583
6817
  } else { delete next.launchPrompts; delete next.launchPromptTarget; }
6584
6818
  next.tmux = { session: target.session, window: target.window, socket: resolve(target.socket) };
6585
6819
  writeJsonAtomic(metaPath, next);
@@ -6743,7 +6977,7 @@ export function startInstanceSession(home, o = {}) {
6743
6977
  if (recorded.error) return undefined; // the gate refuses below; the lookup does not decide it
6744
6978
  const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
6745
6979
  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; }
6980
+ try { return expectedPanePath(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return undefined; throw e; }
6747
6981
  };
6748
6982
  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
6983
  panePath: pane });
@@ -6839,8 +7073,8 @@ export function startInstanceSession(home, o = {}) {
6839
7073
  const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
6840
7074
  ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
6841
7075
  ...(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);
7076
+ warnings.push(...launchStartNotices(dirname(dirname(dirname(dirname(home)))), launchPlan?.harness || harness, command));
7077
+ const engaged = devChannelEngaged(launchPlan?.harness || harness, command);
6844
7078
  let stopReceipt = null;
6845
7079
  if (state.present && state.state !== "shell") {
6846
7080
  // Restart: every preflight above passed, so ask the running harness to
@@ -6863,7 +7097,8 @@ export function startInstanceSession(home, o = {}) {
6863
7097
  writeKernelShim(realHome);
6864
7098
  const startedAt = new Date().toISOString();
6865
7099
  const id = randomUUID();
6866
- const makeLaunchController = () => promptOptedIn(launchPromptAnswers) ? promptController(realHome, id, launchPlan?.harness || harness, launchPromptAnswers, command, o.io, originalHomeIdentity) : null;
7100
+ if (!engaged) planExtra.launchPrompts = notEngaged(id);
7101
+ const makeLaunchController = () => engaged ? promptController(realHome, id, command, o.io, originalHomeIdentity) : null;
6867
7102
  let launchController;
6868
7103
  let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
6869
7104
  checkRoots();
@@ -6903,12 +7138,12 @@ export function startInstanceSession(home, o = {}) {
6903
7138
  // A replacement window (never launched, recorded window gone, recorded server gone) is created
6904
7139
  // on the OATS server, wherever the home was recorded: one socket from here to the record.
6905
7140
  const recordedSocket = socket ? resolve(socket) : null;
6906
- socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket);
7141
+ socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
6907
7142
  if (lookAgain(() => panePath(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
6908
7143
  let names;
6909
7144
  try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
6910
7145
  catch (e) {
6911
- if (oatsCoded(e)) throw e;
7146
+ if (isKernelCode(e?.code)) throw e;
6912
7147
  throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
6913
7148
  }
6914
7149
  if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
@@ -6926,6 +7161,7 @@ export function startInstanceSession(home, o = {}) {
6926
7161
  if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
6927
7162
  }
6928
7163
  if (launchController) launchPrompts = inPlace ? launchController.observeRespawn(launchPromptTarget, beforeRespawn) : launchController.observeNew(launchPromptTarget);
7164
+ if (launchPrompts?.status === "flag-ignored") { launchPrompts = channelsUnavailable(id, launchPrompts); warnings = flagIgnoredWarnings(warnings); }
6929
7165
  } catch (error) {
6930
7166
  if (!promptDispatched) throw error;
6931
7167
  launchPrompts = incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt dispatch or recording incomplete", launchPrompts, originalHomeIdentity);
@@ -6954,7 +7190,7 @@ export function startInstanceSession(home, o = {}) {
6954
7190
  if (e.code && String(e.code).startsWith("E_")) throw e;
6955
7191
  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
7192
  }
6957
- if (launchPrompts && launchPrompts.status !== "completed") throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
7193
+ if (launchPrompts && !promptLaunched(launchPrompts.status)) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
6958
7194
  // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
6959
7195
  if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
6960
7196
  return { ...done, warnings: [...warnings, ...movedWarnings] };
@@ -8168,20 +8404,42 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8168
8404
  rmSync(logPath, { force: true });
8169
8405
  throw scheduleFailed(e.message);
8170
8406
  }
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");
8407
+ // From here a completion process may exist. It acts only once its delay has passed and this
8408
+ // retire has released the home's claim (completeDeferredRetirement), so whatever fails before the
8409
+ // marker is written ends it first, under the claim: the handle's own SIGKILL, never a pid looked
8410
+ // up. A scheduling that fails therefore leaves no completion behind, and "nothing was
8411
+ // inspected, run, or removed" stays true after this call has answered.
8412
+ try {
8413
+ closeSync(fd);
8414
+ if (!child.pid) throw scheduleFailed("no process was created");
8415
+ // A spawn failure Node reports asynchronously (EAGAIN, EMFILE) would arrive
8416
+ // after this returns; record it as a failed outcome so status shows the
8417
+ // debt instead of an uncaught exception behind a success message.
8418
+ child.on("error", (e) => {
8419
+ try {
8420
+ 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");
8421
+ } catch { /* the marker alone then shows RETIRING; status names its age */ }
8422
+ });
8423
+ child.unref();
8424
+ // The marker names its completion (pid and start time; the start is null when it cannot be read):
8425
+ // while that process lives, any other retire of this home is refused (refusePendingCompletion).
8426
+ writeFileSync(marker, JSON.stringify({ ...intent, completionPid: child.pid, completionStart: processStartToken(child.pid) }, null, 2) + "\n");
8427
+ } catch (e) {
8428
+ // No outcome is recorded for a completion this call ends itself: the answer below is the outcome.
8429
+ child.removeAllListeners("error");
8430
+ child.on("error", () => {});
8431
+ if (child.pid) { try { child.kill("SIGKILL"); } catch { /* it never ran */ } }
8432
+ // Its log, and the outcome it may have recorded: a completion kept waiting for this retire's
8433
+ // claim past its own patience gives up and says so there, before the kill reaches it. Both
8434
+ // paths are this retire's own (it removed any earlier result before it started the completion),
8435
+ // so what is removed here can only be that completion's.
8436
+ // Not closed: Node cannot wait for a child synchronously, so a kill that lands inside the
8437
+ // completion's own write of that outcome could leave a result after this removal. It would say
8438
+ // E_LIFECYCLE_BUSY of a retire that has since answered, and a later `oats retire` removes it.
8439
+ for (const left of [logPath, resultPath]) { try { rmSync(left, { force: true }); } catch { /* neither is a debt of the instance */ } }
8440
+ // "is not running": killed here, or gone by itself before the kill.
8441
+ throw e?.code === "E_SELF_RETIRE_SCHEDULE_FAILED" ? e : scheduleFailed(`${e?.message ?? e}; the completion this command had started is not running`);
8442
+ }
8185
8443
  return {
8186
8444
  retired: name, agent: found.agent.name, deferred: true, pendingMarker: marker,
8187
8445
  resultPath, logPath, completesInSec: delaySec, completionPid: child.pid,
@@ -8243,8 +8501,10 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8243
8501
  [COMPLETES_DEFERRED]: true,
8244
8502
  });
8245
8503
  } 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}` : ""}` });
8504
+ record({ ok: false, error: { code: kernelCode(e, "E_LIFECYCLE_FAILED"), 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}` : ""}` });
8247
8505
  console.error(`deferred retirement of ${intent.instance} failed: ${e.message}`);
8506
+ // A defect's stack goes to the completion's log (lib/errors.mjs isDefect).
8507
+ reportDefect(e);
8248
8508
  return false;
8249
8509
  }
8250
8510
  if (obsoleteDeleteBranch) console.log(OBSOLETE_DELETE_BRANCH_SENTENCE);
@@ -8284,47 +8544,168 @@ export const RETIRE_UNDER_CLAIM = Symbol("oats.retireUnderClaim");
8284
8544
  * claim of the first (that one removed, a same-named home of another agent made, in between). */
8285
8545
  const RETIRE_CLAIM_RESTARTS = 2;
8286
8546
 
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) {
8547
+ /** The lifecycle claim file of `home`: `<instances>/.oats-retirement/claims/<name>.lock`. Beside
8548
+ * the homes, never inside one: a home's bytes are what its retire observes, copies and removes.
8549
+ * One file for every verb that holds a home (a retire, a stop): its record names the holder's
8550
+ * verb (`action`) from the instant it exists (lib/claim.mjs `facts`). */
8551
+ export function retireClaimPath(home) {
8290
8552
  return join(instancesRetirementRoot(dirname(home)), "claims", `${basename(home)}.lock`);
8291
8553
  }
8292
8554
 
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 } });
8555
+ /** The verbs that take a home's lifecycle claim: what claimHomeFor accepts, and so every `action`
8556
+ * a claim of the kernel's names. */
8557
+ const CLAIM_VERBS = Object.freeze(["retire", "stop"]);
8558
+ /** The verb the holder of a home's claim recorded (`action`): one of CLAIM_VERBS, never the
8559
+ * record's text. A claim is read back as whatever is in its file, which other instances of the
8560
+ * deployment can write, and this goes into messages, remedies and `details` (lib/claim.mjs
8561
+ * shownHolder, the same rule for the holder's own fields). Anything else is a retire's, as a
8562
+ * record without one is: a kernel before feature `lifecycle-claim-stop` wrote none, and only its
8563
+ * retire took the claim. */
8564
+ const claimAction = (holder) => CLAIM_VERBS.includes(holder?.action) ? holder.action : "retire";
8565
+ /** The command that takes a home's claim for `action`, as a person types it. */
8566
+ const claimCommand = (action) => action === "stop" ? "oats instance stop" : `oats ${action}`;
8567
+ /** What each verb that meets a held claim says it did not do: the words its refusals end with,
8568
+ * before any effect. After a takeover ended a dead holder's step, every verb says the same
8569
+ * (lib/errors.mjs nothingAfter). */
8570
+ const CLAIM_NOTHING = { retire: "nothing was done", stop: "nothing was stopped", "worktree add": "no tree was made" };
8571
+
8572
+ /** The refusals of `arriving` ("retire", "stop", or "worktree add", which reads the claim and does
8573
+ * not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
8574
+ * for them: one builder for every pair (arriving verb, holder's verb), so that the pair table of
8575
+ * docs/desktop-cli-api.md has one source. One line each, saying what was not done, once.
8576
+ * - A live holder: E_INSTANCE_RETIRING when the holder is a retire and the arriving verb is not
8577
+ * one (the instance is on its way out: waiting does not make the stop or the tree possible);
8578
+ * E_LIFECYCLE_BUSY otherwise, `holder: "running"`. Live is what was established of the pid
8579
+ * and its start, not that the process is that command: both name, after the dash, the check
8580
+ * for a holder that does not end (lib/errors.mjs ifItDoesNotEnd), the second after the wait.
8581
+ * - A holder whose liveness cannot be read: E_LIFECYCLE_BUSY, `holder: "unknown"`, whatever the
8582
+ * two verbs are, with that same check as its step (checkHolderByHand).
8583
+ * `details` is `{ instance, home, lock, pid, since, action }`: `lock` is the file that names the
8584
+ * holder, `action` the HOLDER's verb (claimAction). The holder is named as lib/claim.mjs
8585
+ * shownHolder allows, in the message and in `details` alike: `pid` and `since` are null, and the
8586
+ * message says `?` or `none`, for a field that does not have the shape the kernel writes.
8587
+ * `ended`, the last argument of each, is what the claim's takeovers ended before the refusal
8588
+ * (lib/claim.mjs). With some, the sentence says "nothing else was done" and the answer is
8589
+ * E_LIFECYCLE_FAILED, what was ended first (lib/errors.mjs afterEndedSteps), with these details. */
8590
+ export function lifecycleClaimRefusals(arriving, name, home, lock) {
8591
+ const nothing = (ended) => nothingAfter(ended, CLAIM_NOTHING[arriving]);
8592
+ const own = { instance: name, home };
8593
+ const holders = "oats retire or oats instance stop";
8594
+ // The holder of `at`, as an answer names it: `shown` for the message, `details` beside it.
8595
+ const held = (holder, at) => {
8596
+ const shown = shownHolder(holder), action = claimAction(holder);
8597
+ return { shown, action, details: { ...own, lock: at, pid: shown.pid, since: shown.since, action } };
8598
+ };
8298
8599
  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);
8600
+ busy: (holder, unknown, at = lock, ended = []) => {
8601
+ const { shown, action, details } = held(holder, at);
8602
+ const command = `an ${claimCommand(action)}`;
8603
+ 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)}`,
8604
+ checkHolderByHand(command, at), { ...details, unknown }, ended);
8605
+ // Alive is all that was established of the pid, never that it is that command: both
8606
+ // answers below name the check for a holder that does not end. A retire's holder is not
8607
+ // waited for by a verb that is not one (the instance is on its way out).
8608
+ 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 }));
8609
+ 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
8610
  },
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 }),
8611
+ // Nobody is running in the four below, so never the sentence above that says to wait
8612
+ // (awebai/oats#874). The first sends nobody to a pid of this process, which is gone when the
8613
+ // answer is read: its remedy is a check in the reader's own shell (the reason names the read
8614
+ // that failed, as the reader made it).
8615
+ ownStartUnreadable: (reason, at, ended = []) => lifecycleBusy("none", `this process's start time cannot be read (${reason}), so ${claimCommand(arriving)} cannot hold ${at} verifiably; ${nothing(ended)}`,
8616
+ OWN_START_REMEDY, { ...own, lock: at }, ended),
8617
+ 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),
8618
+ 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)}`,
8619
+ `inspect ${at} and remove it if no ${holders} holds it, then retry`, held(holder, at).details, ended),
8620
+ // Nothing is wrong with the file: each command that took the claim died, and this one came
8621
+ // after each of them. The next run takes over the one that is there.
8622
+ 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)}`,
8623
+ "run the command again", held(holder, at).details, ended),
8307
8624
  };
8308
8625
  }
8626
+ /** The refusals of a retire of `name` that cannot take its claim `lock` (lifecycleClaimRefusals).
8627
+ * Exported for its tests. */
8628
+ export function retireClaimRefusals(name, home, lock) {
8629
+ return lifecycleClaimRefusals("retire", name, home, lock);
8630
+ }
8631
+
8632
+ /** Take the lifecycle claim of `home` for `verb` ("retire", "stop") → the holding, for
8633
+ * releaseHomeClaim. The one way a verb takes it: the record carries the verb from the instant the
8634
+ * file exists, and a holder of any verb is refused at once (`waitMs: 0`; only a deferred
8635
+ * self-retire's completion waits, for the retire that scheduled it). The claim's directory is
8636
+ * made as retire makes it for its recovery copies; the claims are private. A directory that
8637
+ * cannot be made is a claim that cannot be taken: nothing was done (awebai/oats#874). */
8638
+ export function claimHomeFor(verb, name, home, { waitMs = 0 } = {}) {
8639
+ 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(", ")})`);
8640
+ const lock = retireClaimPath(home);
8641
+ try {
8642
+ mkdirSync(instancesRetirementRoot(dirname(home)), { recursive: true });
8643
+ mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
8644
+ } catch (e) { throw claimUnavailable(lock, e); }
8645
+ return { lock, me: acquireClaim(lock, { ...lifecycleClaimRefusals(verb, name, home, lock), facts: { action: verb }, waitMs }) };
8646
+ }
8647
+ /** Release a holding of claimHomeFor, only while its file still names it. */
8648
+ export function releaseHomeClaim(holding) {
8649
+ releaseClaim(holding.lock, holding.me);
8650
+ }
8651
+ /** Who holds the lifecycle claim of `home` now, read and not taken → `{ lock, holder, action,
8652
+ * state, reason? }` (`state` is processLiveness's: "alive", "unknown" with its `reason`, "gone"),
8653
+ * or null when there is no claim or the file does not read as one. For the readers that do not
8654
+ * take the claim: a stop plan's `retiring` and `stopPending`, and `oats worktree add`. */
8655
+ export function homeClaimHolder(home) {
8656
+ const lock = retireClaimPath(home);
8657
+ const holder = readClaim(lock);
8658
+ if (!holder || holder.unreadable) return null;
8659
+ const live = processLiveness(holder);
8660
+ return { lock, holder, action: claimAction(holder), state: live.state, ...(live.reason ? { reason: live.reason } : {}) };
8661
+ }
8662
+ /** Whether the claim path `lock` holds something that is no claim anybody can read: a file that
8663
+ * does not parse as one, or a path that is there and never reads (a dangling symbolic link, which
8664
+ * reads as absent: lib/claim.mjs readClaim). A verb that TAKES the claim learns the second from
8665
+ * its link, which says the path exists (takeClaim); a verb that only reads asks the path itself.
8666
+ * A claim made between the two reads here is read again, and is a claim. */
8667
+ function claimPathUnreadable(lock) {
8668
+ const read = readClaim(lock);
8669
+ if (read) return read.unreadable === true;
8670
+ let entry;
8671
+ try { entry = lstatSync(lock); } catch (e) { return e?.code !== "ENOENT"; }
8672
+ return entry.isSymbolicLink() ? readClaim(lock) === null : readClaim(lock)?.unreadable === true;
8673
+ }
8674
+ /** Refuse `arriving` ("worktree add"), a verb that reads the lifecycle claim of `home` and does
8675
+ * not take it, when a retire holds it: E_INSTANCE_RETIRING beside a live one, E_LIFECYCLE_BUSY
8676
+ * (`holder: "unknown"`) beside one whose liveness cannot be read, and beside a file that does not
8677
+ * read as a claim, with the words a stop and a retire have for that file: one file has one
8678
+ * reading, and this verb makes a tree in a home that may be going away. Nothing refuses for a
8679
+ * holder that is gone (whoever takes the claim next takes it over) or for a stop (a tree does
8680
+ * not depend on the session). */
8681
+ export function refuseBesideRetire(arriving, home) {
8682
+ const lock = retireClaimPath(home);
8683
+ const refusals = lifecycleClaimRefusals(arriving, basename(home), home, lock);
8684
+ if (claimPathUnreadable(lock)) throw refusals.unreadableClaim(lock);
8685
+ const held = homeClaimHolder(home);
8686
+ if (!held || held.action !== "retire" || held.state === "gone") return;
8687
+ throw refusals.busy(held.holder, held.state === "unknown" ? held.reason : null);
8688
+ }
8309
8689
 
8310
8690
  /** The homes `name` resolves to under `root`, and the one a retire acts on. Names are unique per
8311
8691
  * agent dir only: two agents can own an instance of the same name (dev --purpose foo-1 and agent
8312
8692
  * dev-foo). Retirement is destructive, so a name that resolves to several homes is refused unless
8313
8693
  * 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. */
8694
+ * homes under this root. A home whose record is there and cannot be read is refused here
8695
+ * (identifiedHomeRecord), `--force` or not: before the claim, and again under it. */
8315
8696
  function resolveRetireHome(root, name, o) {
8316
8697
  const matches = findInstanceHomes(root, name);
8317
8698
  if (!matches.length) throw oatsError("E_SESSION_UNKNOWN", `no instance named "${name}"`);
8318
8699
  const sameHome = (a, b) => { try { return realpathSync(a) === realpathSync(b); } catch { return resolve(a) === resolve(b); } };
8700
+ let found = matches[0];
8319
8701
  if (o.home) {
8320
- const found = matches.find((m) => sameHome(m.home, o.home));
8702
+ found = matches.find((m) => sameHome(m.home, o.home));
8321
8703
  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) {
8704
+ } else if (matches.length > 1) {
8325
8705
  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
8706
  }
8327
- return matches[0];
8707
+ identifiedHomeRecord(found.home);
8708
+ return found;
8328
8709
  }
8329
8710
 
8330
8711
  /** `name` has no home under `root`: remove a retire claim of that name whose holder is gone, in
@@ -8357,9 +8738,10 @@ function refusePendingCompletion(name, home) {
8357
8738
  const live = processLiveness({ pid, processStart: pending.completionStart });
8358
8739
  if (live.state === "gone") return;
8359
8740
  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 } });
8741
+ const details = { instance: name, home, lock: marker, pid, since: pending.requestedAt ?? null, action: "retire" };
8742
+ 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);
8743
+ 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`,
8744
+ `check that pid by hand, and if it is not an oats retire, remove ${marker}, then retry`, { ...details, unknown: live.reason });
8363
8745
  }
8364
8746
 
8365
8747
  /** Retire one instance. One retire of a home at a time (awebai/oats#863): the home's claim
@@ -8369,6 +8751,13 @@ function refusePendingCompletion(name, home) {
8369
8751
  * not bypass it. A claim left by a killed retire is taken over. Every apply path runs this
8370
8752
  * function: the CLI, the deferred completion, and `--server` on the host. Synchronous. */
8371
8753
  export function retireInstance(root, name, o = {}) {
8754
+ // No answer of a retire carries a code that is not the kernel's (awebai/oats#892). The retire of
8755
+ // the home gives its own (retireClaimed); what fails before it (the resolution, the claim, the
8756
+ // plan the caller reads under it) has touched nothing of the instance.
8757
+ try { return retireUnderClaim(root, name, o); }
8758
+ catch (e) { throw isAnswerCode(e?.code) ? e : statedFailure(e, "E_LIFECYCLE_FAILED", `Nothing was done: ${name} is not retired.`); }
8759
+ }
8760
+ function retireUnderClaim(root, name, o) {
8372
8761
  if (o.deleteBranch) throw oatsError("E_BAD_ARGS", RETIRE_DELETE_BRANCH_REFUSED);
8373
8762
  let found;
8374
8763
  try { found = resolveRetireHome(root, name, o); }
@@ -8377,21 +8766,17 @@ export function retireInstance(root, name, o = {}) {
8377
8766
  throw e;
8378
8767
  }
8379
8768
  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 });
8769
+ // No waiting: a live holder, a retire or a stop, is refused at once. Only a deferred completion
8770
+ // waits, for the retire that scheduled it to return.
8771
+ const held = claimHomeFor("retire", name, found.home, { waitMs: o[COMPLETES_DEFERRED] ? CLAIM_WAIT_MS : 0 });
8772
+ const { lock } = held;
8388
8773
  try {
8389
8774
  // Resolved again under the claim: another retire may have removed the home between the
8390
8775
  // first resolution and the claim. Gone is what a retire of a retired instance answers.
8391
8776
  const now = resolveRetireHome(root, name, o);
8392
8777
  if (retireClaimPath(now.home) !== lock) {
8393
8778
  // 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) } });
8779
+ 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
8780
  found = now;
8396
8781
  continue;
8397
8782
  }
@@ -8405,13 +8790,100 @@ export function retireInstance(root, name, o = {}) {
8405
8790
  const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}) } : o;
8406
8791
  return retireClaimed(root, name, bound, now);
8407
8792
  } finally {
8408
- releaseClaim(lock, me);
8793
+ releaseHomeClaim(held);
8409
8794
  }
8410
8795
  }
8411
8796
  }
8412
8797
 
8413
- /** The retire of the home `found`, under its claim (retireInstance). */
8798
+ /** `e` as the answer of a retire at a point where it knows what it has done: a kernel error whose
8799
+ * message ends with `said`, the sentence of that point with its own full stop. One that has a
8800
+ * kernel code keeps its code, its details and its provenance; any other is wrapped as `fallback`
8801
+ * (asKernelError), its text after `lead` when one is given. A message that already ends with the
8802
+ * sentence is left as it is: it is said once. */
8803
+ function statedFailure(e, fallback, said, lead) {
8804
+ const kernel = asKernelError(e, fallback, lead ? `${lead}: ${e?.message ?? e}` : undefined);
8805
+ // A failure answered under its own name (an unsafe key in a document) keeps its own words too.
8806
+ if (OWN_NAME_FAILURES.has(kernel.code) || kernel.message.endsWith(said)) return kernel;
8807
+ const stated = oatsError(kernel.code, `${kernel.message.replace(/\.$/, "")}. ${said}`, kernel.provenance);
8808
+ if (kernel.details) stated.details = kernel.details;
8809
+ if (Object.hasOwn(kernel, "cause")) stated.cause = kernel.cause; // whatever was thrown, undefined included (defectOf)
8810
+ return stated;
8811
+ }
8812
+ /** A retire's recovery as it is on disk at `path` → { path, phase }, the phase its recovery.json
8813
+ * holds now; null without a path, or when the manifest cannot be read or holds another phase. */
8814
+ function recoveryOnDisk(path) {
8815
+ try {
8816
+ if (!path) return null;
8817
+ const phase = readJsonOrUndefined(join(path, "recovery.json"))?.phase;
8818
+ return phase === "before-hooks" || phase === "complete" ? { path, phase } : null;
8819
+ } catch { return null; } // total: a read that fails names no copy
8820
+ }
8821
+ /** What is at `home` now, for a retire whose removal began (`removing`): "kept" when it did not,
8822
+ * "removed" when nothing is there, "partial" when something is (or that cannot be told). */
8823
+ function homeOnDisk(home, removing) {
8824
+ if (!removing) return "kept";
8825
+ try { lstatSync(home); return "partial"; } catch (e) { return e?.code === "ENOENT" ? "removed" : "partial"; } // total
8826
+ }
8827
+
8828
+ /** The retire of the home `found`, under its claim (retireInstance). Whatever fails in it is
8829
+ * answered with a kernel code and with what the retire had done by then (awebai/oats#892):
8830
+ * `details.reached` on every error, and, on one that is not the kernel's, the sentence of that
8831
+ * point (`at.said`, kept current by retireSteps). Such an error is E_LIFECYCLE_FAILED; the steps
8832
+ * that inspect the home or the work give E_WORK_INSPECTION_FAILED themselves.
8833
+ *
8834
+ * `reached` is `{ phase, sessionStopAttempted, hooksStarted, home, recovery }`. `phase` is how
8835
+ * far the retire got: "before-effects" (nothing happened: never answered once a process may have
8836
+ * been signalled), "before-hooks" (from the step that stops its recorded children on, whether or
8837
+ * not it had anything to signal, or earlier, from the end of the hook group an interrupted spawn
8838
+ * left), "after-hooks" (from the call of the retire hooks on),
8839
+ * "removal" (from the removal of the home on). In the other fields the untouched value is a
8840
+ * guarantee, and the other value says only that the retire reached that step, which may not have
8841
+ * completed (docs/desktop-cli-api.md, `error.details.reached`: the shape is contract):
8842
+ * - `sessionStopAttempted: false`: it signalled neither the instance's session nor a child's
8843
+ * harness;
8844
+ * - `hooksStarted: false`: no retire hook was started;
8845
+ * - `home: "kept"`: the removal did not begin; else what is on disk now, "partial" or "removed";
8846
+ * - `recovery: null`: no copy of this retire whose manifest can be read; else its path and the
8847
+ * phase its recovery.json holds now ("before-hooks" or "complete"), read when the error is
8848
+ * answered. */
8414
8849
  function retireClaimed(root, name, o, found) {
8850
+ const at = { phase: "before-effects", sessionTouched: false, hooksStarted: false, removing: false, recoveryPath: null, said: () => "Nothing was stopped, run or removed", lead: null };
8851
+ try { return retireSteps(root, name, o, found, at); }
8852
+ catch (e) { throw retireFailure(e, at, found.home); }
8853
+ }
8854
+ /** The error a retire of `home` answers for `e`, thrown while the retire was at `at`
8855
+ * (retireClaimed): a kernel error that carries `details.reached`. It never throws, whatever `e` and
8856
+ * `at` are: an answer of a retire without `reached` says that the retire of the home had not
8857
+ * begun and that nothing was done (retireInstance), and no error from here may read so. `reached`
8858
+ * is made first, from the tracker and two reads that cannot fail; if the sentence of that point
8859
+ * cannot be made, or the error cannot carry details, the answer is the error's own message, with
8860
+ * `reached`. Exported for its test. */
8861
+ export function retireFailure(e, at, home) {
8862
+ const reached = { phase: at.phase, sessionStopAttempted: at.sessionTouched, hooksStarted: at.hooksStarted, home: homeOnDisk(home, at.removing), recovery: recoveryOnDisk(at.recoveryPath) };
8863
+ // A code this verb answers only before any effect (lib/errors.mjs BEFORE_EFFECT_CODES), raised
8864
+ // once the retire is past "before-effects": the same fact `reached.phase` states, never a second
8865
+ // record of how far the retire got. A net: no known place raises one there.
8866
+ const late = at.phase !== "before-effects";
8867
+ try {
8868
+ const answered = isAnswerCode(e?.code) ? e : statedFailure(e, "E_LIFECYCLE_FAILED", `${at.said()}.`, at.lead?.());
8869
+ const failure = late ? afterFirstEffect(answered, "retire", `phase ${at.phase}`) : answered;
8870
+ failure.details = { ...failure.details, reached };
8871
+ return failure;
8872
+ } catch (unsaid) {
8873
+ reportDefect(unsaid);
8874
+ // The net again, where its sentence could not be built: never the refusal's own code past the
8875
+ // first effect, nor its words alone, which say that nothing happened.
8876
+ const lateRefusal = late && BEFORE_EFFECT_CODES.retire.includes(e?.code);
8877
+ const plain = new Error(`${lateRefusal ? `oats retire answered ${e.code} after its first effect (phase ${at.phase}): ` : ""}${String(e?.message ?? e)}`, { cause: e });
8878
+ plain.code = lateRefusal ? "E_LIFECYCLE_FAILED" : kernelCode(e, "E_LIFECYCLE_FAILED");
8879
+ const cause = isAnswerCode(e?.code) ? undefined : errorCause(e);
8880
+ plain.details = { ...(isAnswerCode(e?.code) && isPlainObject(e.details) ? e.details : {}), ...(cause ? { cause } : {}), reached };
8881
+ return plain;
8882
+ }
8883
+ }
8884
+ /** The steps of a retire. `at` is where it is (retireClaimed): each step that changes what a
8885
+ * failure may truthfully say moves it first. */
8886
+ function retireSteps(root, name, o, found, at) {
8415
8887
  const session = o.tmuxSession || DEFAULT_TMUX_SESSION;
8416
8888
  // self-retire: the caller IS the instance. Without --keep-dir the whole
8417
8889
  // retirement is deferred to a detached external completion (below); with
@@ -8460,28 +8932,46 @@ function retireClaimed(root, name, o, found) {
8460
8932
  if (isPlainObject(rawMarker?.inProgress)) {
8461
8933
  const p = rawMarker.inProgress;
8462
8934
  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`);
8935
+ 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
8936
  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` } });
8937
+ 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`,
8938
+ `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
8939
  inProgressUnverified = true;
8467
8940
  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
8941
  }
8469
8942
  }
8943
+ // The retire's own read of the record, with the same reader as the resolution: one that became
8944
+ // unreadable since then refuses as there. It comes before the first signal a retire can send
8945
+ // (below), so that E_UNIDENTIFIED_INSTANCE_HOME for an unreadable record is only ever answered
8946
+ // while nothing was done: `reached` is untouched ("before-effects").
8947
+ const liveMeta = identifiedHomeRecord(found.home).meta;
8948
+ // What this retire did to the hook group an interrupted spawn left, when it signalled it. Ending
8949
+ // that group is the first signal a retire can send: from that call on the retire is no longer
8950
+ // "before-effects", and no answer says that nothing was stopped.
8951
+ let spawnGroupSaid = null;
8952
+ const nothingYet = () => spawnGroupSaid ? `${spawnGroupSaid}; no session was stopped, no retire hook was run and nothing was removed` : "Nothing was stopped, run or removed";
8953
+ at.said = nothingYet;
8470
8954
  if (quarantine?.inProgress) {
8471
8955
  const p = quarantine.inProgress;
8956
+ const group = `The worktree hook process group ${p.hookPgid} that an interrupted spawn left`;
8957
+ at.phase = "before-hooks";
8958
+ spawnGroupSaid = `${group} was signalled and may still run`;
8472
8959
  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`);
8960
+ if (ended === "terminated" || ended === "killed") spawnGroupSaid = `${group} was ended`;
8961
+ else if (ended !== "survived") { spawnGroupSaid = null; at.phase = "before-effects"; } // nothing was signalled
8962
+ // Two signals were sent by now: never a code that says nothing happened (awebai/oats#895).
8963
+ 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
8964
  if (ended === "unverified") spawnGroupWarnings.push(unverifiedGroupWarning(p.hookPgid));
8475
8965
  // A group whose leader's start cannot be read may still be that spawn's hook: never signalled,
8476
8966
  // and refused like an unreadable spawn above, with the same way out.
8477
8967
  if (ended === "unknown") {
8478
8968
  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` } });
8969
+ if (!o.force) throw lifecycleBusy("unknown", `${name}: the worktree hook ${note}; nothing was retired`,
8970
+ `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
8971
  inProgressUnverified = true;
8481
8972
  spawnGroupWarnings.push(`retired with --force although the worktree ${note}; its branch is kept`);
8482
8973
  }
8483
8974
  }
8484
- const liveMeta = existsSync(metaPath) ? JSON.parse(readFileSync(metaPath, "utf8")) : undefined;
8485
8975
  // A quarantined home may carry an instance.json that is NOT the spawn record:
8486
8976
  // module materialization writes a pre-hook stub ({ modules, providers,
8487
8977
  // resolutionRevision }) before the spawn hooks run, and a required-hook
@@ -8529,6 +9019,8 @@ function retireClaimed(root, name, o, found) {
8529
9019
  // quarantined home's cleanup descriptor overrides the live record's endpoint: either may name it.
8530
9020
  const herdrHome = recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(found.home))) || recordsHerdr(liveMeta);
8531
9021
  if (self && (!o.keepDir || herdrHome)) {
9022
+ // scheduleDeferredSelfRetirement ends the completion it started before it throws, whatever fails.
9023
+ at.said = () => `${spawnGroupSaid ? `${spawnGroupSaid}. ` : ""}This command inspected, ran and removed nothing, and left no detached completion running`;
8532
9024
  return scheduleDeferredSelfRetirement(root, found, name, o, session);
8533
9025
  }
8534
9026
  // A worktree directory whose git admin entry is gone cannot be inspected, moved or removed through git, and
@@ -8546,7 +9038,15 @@ function retireClaimed(root, name, o, found) {
8546
9038
  const recordedBranch = quarantine ? { repo: meta.repo, branch: meta.branch } : undefined;
8547
9039
  // Whether this retire removes the worktree, when it gets to that step.
8548
9040
  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" });
9041
+ // An inspection of the home and the work. Whatever fails in it, a walk that meets an entry it
9042
+ // cannot read or that is gone included, is an inspection that failed (E_WORK_INSPECTION_FAILED),
9043
+ // and says what the retire has and has not done by then (`disclosure`), once. Classified here,
9044
+ // at the retire's own calls: the digests' other callers do not answer that code for it.
9045
+ const inspect = (disclosure) => {
9046
+ try { return inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure }); }
9047
+ catch (e) { throw statedFailure(e, "E_WORK_INSPECTION_FAILED", `${disclosure}.`, `could not inspect the home of ${name} or its work`); }
9048
+ };
9049
+ const initialObservation = inspect(nothingYet());
8550
9050
  // 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
9051
  // would remove the home refuses here, before the session is stopped and before any retire hook runs (the hooks
8552
9052
  // revoke identities a kept home would still need). The extra-tree step keeps its own check, for a lock that appears
@@ -8592,21 +9092,37 @@ function retireClaimed(root, name, o, found) {
8592
9092
  // retired, nothing is escalated, and --force does not bypass it. A child whose
8593
9093
  // instance.json is gone by now (a --self snapshot's child retired in between)
8594
9094
  // is no longer an instance, and the plan would not list it: it is not stopped.
9095
+ // What this retire did to the instance's own session: "unverified" once the kill is sent and
9096
+ // until the window is seen gone. `childStopReached`: a child's stop got to signal its harness.
9097
+ let ownSession = "untouched", childStopReached = false;
9098
+ const sessionSaid = () => ownSession === "stopped" ? "its session has been stopped"
9099
+ : ownSession === "unverified" ? "its session was asked to end, and whether it did was not established"
9100
+ : childStopReached ? `this retire stopped no session of ${name}; a stop of its recorded children was attempted`
9101
+ : "this retire stopped no session";
9102
+ // What a refusal before the hooks tells the operator about the retire so far.
9103
+ const soFar = (kept) => `${name} is not retired and ${kept}; ${sessionSaid()}`;
9104
+ const beforeHooks = () => `No retire hook has run and nothing was deleted: ${soFar("its home and work are kept")}`;
9105
+ // What a refusal after the hooks tells the operator about the retire so far.
9106
+ const hooksSaid = () => at.hooksStarted ? "The retire hooks have run" : "No retire hook was run";
9107
+ const afterHooks = () => `${hooksSaid()}; the home, its work and the pre-hook recovery (if any) are kept; ${sessionSaid()}`;
9108
+ at.phase = "before-hooks";
9109
+ at.said = beforeHooks;
8595
9110
  let childrenStopped;
8596
9111
  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 } });
9112
+ childrenStopped = stopRecordedChildren(o.children.filter((kid) => existsSync(join(kid.home, "instance.json"))), () => { at.sessionTouched = true; childStopReached = true; });
9113
+ const notStopped = childrenStopped.filter((k) => !k.ok);
9114
+ if (notStopped.length) throw Object.assign(oatsError("E_CHILDREN_RUNNING", `${childrenNotStopped(notStopped)}; nothing was retired and nothing was escalated`), { details: { childrenStopped } });
8600
9115
  }
8601
9116
  // `=` forces exact matching: tmux targets otherwise PREFIX-match window names.
8602
9117
  // A no-launch instance is already quiesced. A launched one must have exact
8603
9118
  // window absence established before recovery copying begins.
8604
- let sessionStopped = false;
8605
9119
  if (!self && runtimeAuthority?.launched) {
8606
9120
  const runtimeSession = runtimeAuthority.tmux.session;
8607
9121
  const runtimeWindow = runtimeAuthority.tmux.window;
8608
9122
  const runtimeSocket = runtimeAuthority.tmux.socket;
8609
9123
  const tmux = ["-S", runtimeSocket];
9124
+ at.sessionTouched = true;
9125
+ ownSession = "unverified";
8610
9126
  try { execFileSync("tmux", [...tmux, "kill-window", "-t", `=${runtimeSession}:=${runtimeWindow}`], { stdio: ["ignore", "pipe", "pipe"] }); } catch { /* verify the effect below */ }
8611
9127
  try {
8612
9128
  const windows = execFileSync("tmux", [...tmux, "list-windows", "-t", runtimeSession, "-F", "#{window_name}"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).split("\n").filter(Boolean);
@@ -8624,13 +9140,9 @@ function retireClaimed(root, name, o, found) {
8624
9140
  if (why) throw unestablished(why);
8625
9141
  }
8626
9142
  }
8627
- sessionStopped = true;
9143
+ ownSession = "stopped";
8628
9144
  }
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")}` });
9145
+ const stableObservation = inspect(beforeHooks());
8634
9146
  // The bytes of the worktree as they are before the hooks: after the hooks,
8635
9147
  // "the work did not move" is then proven, never taken from a status text.
8636
9148
  // Read before the recovery is written, so that a worktree that cannot be
@@ -8645,7 +9157,7 @@ function retireClaimed(root, name, o, found) {
8645
9157
  if (stableObservation.classes.length && stableObservation.workProvable) {
8646
9158
  try { observedWorkBytes(stableObservation); }
8647
9159
  catch (e) {
8648
- throw oatsError(e.code, `${e.message}. No recovery was written and nothing was deleted: ${soFar("its home is kept")}`);
9160
+ throw statedFailure(e, "E_WORK_INSPECTION_FAILED", `No recovery was written and nothing was deleted: ${soFar("its home is kept")}`);
8649
9161
  }
8650
9162
  }
8651
9163
  // One recovery per retirement. The snapshot taken here, before the retire
@@ -8654,11 +9166,12 @@ function retireClaimed(root, name, o, found) {
8654
9166
  // cannot be made or verified refuses here, with the same disclosure.
8655
9167
  let preHookRecovery;
8656
9168
  if (stableObservation.classes.length) {
9169
+ // Whatever fails here, not only a copy that could not be verified, says the same.
8657
9170
  try { preHookRecovery = writeRetirementRecovery(stableObservation, meta, name, "before-hooks"); }
8658
9171
  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 } : {});
9172
+ 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
9173
  }
9174
+ at.recoveryPath = preHookRecovery.receipt.path;
8662
9175
  }
8663
9176
  let workRecovery = preHookRecovery?.receipt;
8664
9177
 
@@ -8674,6 +9187,10 @@ function retireClaimed(root, name, o, found) {
8674
9187
  // The soul this home was spawned from, as recorded (a workspace home records its
8675
9188
  // per-commit directory; agents/<name>/soul may since point elsewhere) — the same
8676
9189
  // value spawn's hook saw.
9190
+ // From the call on the hooks count as run: one that fails part-way has started some.
9191
+ at.phase = "after-hooks";
9192
+ at.hooksStarted = true;
9193
+ 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
9194
  hookResults = runLifecycleHooks("retire", {
8678
9195
  home: found.home, instance: name, agentName: found.agent.name,
8679
9196
  soulDir: instanceSoulDir(found.home, meta) || found.agent._soulDir || join(found.agent._dir, "soul"),
@@ -8681,6 +9198,8 @@ function retireClaimed(root, name, o, found) {
8681
9198
  contextDir: meta.repo, workspaceDir: workspaceOf(root), rootDir: root, resolved, priorMeta: meta.capabilityMeta || {},
8682
9199
  });
8683
9200
  }
9201
+ at.phase = "after-hooks";
9202
+ at.said = afterHooks;
8684
9203
 
8685
9204
  // ORDINARY retirement must not delete a home whose cleanup did not finish.
8686
9205
  // The failures were already collected above; until now they were read ONLY on
@@ -8746,16 +9265,16 @@ function retireClaimed(root, name, o, found) {
8746
9265
  // step and before the home is removed.
8747
9266
  // A refusal here says what has and has not happened, as one before the hooks
8748
9267
  // does: the hooks have run, and what is kept (#659).
8749
- const finalObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure: afterHooks() });
9268
+ const finalObservation = inspect(afterHooks());
8750
9269
  try {
8751
9270
  if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, meta);
8752
9271
  else if (finalObservation.classes.length) {
8753
9272
  workRecovery = preserveRetirementWork({ ...finalObservation, notCopied: unionNotCopied(stableObservation.notCopied, finalObservation.notCopied) }, meta, name);
8754
9273
  }
8755
9274
  } 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 } : {});
9275
+ throw statedFailure(e, "E_LIFECYCLE_FAILED", `${afterHooks()}.`);
8758
9276
  }
9277
+ if (workRecovery?.path) at.recoveryPath = workRecovery.path;
8759
9278
 
8760
9279
  // Lineage repair: any instance pointing at the retiree (parentInstance from a
8761
9280
  // child/parent relation, siblingInstance from a root-sibling link) would be
@@ -8780,9 +9299,10 @@ function retireClaimed(root, name, o, found) {
8780
9299
  try { return realpathSync(hit.home) === retireeHome; } catch { return false; }
8781
9300
  };
8782
9301
  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; }
9302
+ // Another home's record: one that is absent or cannot be read names no edge to repair.
9303
+ const record = readHomeRecord(instHome);
9304
+ if (record.state !== "record") return;
9305
+ const p = record.path, m = record.meta;
8786
9306
  if (m.parentInstance !== name && m.siblingInstance !== name) return;
8787
9307
  if (!edgeIsRetiree(orphanRoot, instHome)) return; // same NAME, different instance — leave it
8788
9308
  // Drop every edge to the retiree, then graft the retiree's own links —
@@ -8833,10 +9353,20 @@ function retireClaimed(root, name, o, found) {
8833
9353
  // (`plannedExtraWorktrees`) binds what is done: trees that no longer read
8834
9354
  // as planned refuse as stale before any of them is touched.
8835
9355
  let extraWorktrees;
9356
+ let retention = null;
9357
+ // From here on the retire removes and re-homes trees: a failure no longer says that the work is
9358
+ // kept, only what is still true, and which trees it has dealt with.
9359
+ const treesDone = () => {
9360
+ const done = [...(extraWorktrees || []).map((r) => r.outcome === "removed" ? `${r.path} removed` : `${r.path} re-homed to ${r.movedTo}`),
9361
+ ...(retention?.worktree === "removed" ? [`${workPath} removed`] : retention?.worktree === "retained" ? [`${workPath} re-homed to ${retention.movedTo}`] : [])];
9362
+ return done.length ? `. Already done in this retire: ${done.join(", ")}` : "";
9363
+ };
9364
+ at.said = () => `${hooksSaid()}; the home is kept, and so is any recovery the retire wrote; ${sessionSaid()}${treesDone()}`;
8836
9365
  if (!o.keepDir && !(outstandingBeforeWorktree.length > 0 && !o.force)) {
8837
9366
  const rows = extraWorktreeRows(finalObservation.extraTrees, root);
8838
9367
  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.`);
9368
+ // After the hooks: never E_PLAN_STALE, which says that nothing happened (awebai/oats#895).
9369
+ 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
9370
  }
8841
9371
  const refused = rows.filter((r) => r.disposition === "refuse");
8842
9372
  if (refused.length) {
@@ -8876,7 +9406,6 @@ function retireClaimed(root, name, o, found) {
8876
9406
  const worktreeStep = isWorktree && !!meta.repo && !orphanedWork;
8877
9407
  const worktreeDeferred = worktreeStep && existsSync(workPath) && outstandingBeforeWorktree.length > 0 && !o.force;
8878
9408
  const keptForRetry = worktreeDeferred ? `git worktree ${workPath}: kept for the retry; outstanding: ${outstandingBeforeWorktree.join("; ")}` : null;
8879
- let retention = null;
8880
9409
  // The repository of work/, by its common Git directory (awebai/oats#679), read once from meta.repo: the
8881
9410
  // step's commands and the quarantine's verification below run helper-free against it (gitRepoRun,
8882
9411
  // gitRepoRead), as the extra-tree step's do. A bare repository is named as its Git directory.
@@ -8928,7 +9457,7 @@ function retireClaimed(root, name, o, found) {
8928
9457
  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
9458
  } catch (e) {
8930
9459
  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.`);
9460
+ 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
9461
  }
8933
9462
  retention = { worktree: "removed", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
8934
9463
  }
@@ -8953,7 +9482,7 @@ function retireClaimed(root, name, o, found) {
8953
9482
  // receipt `spawned` carries, so the workspace log shows both halves of a
8954
9483
  // capability's lifecycle after the home is gone.
8955
9484
  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 });
9485
+ 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
9486
  // Retrying a quarantine only clears it if compensation ACTUALLY completed.
8958
9487
  // Otherwise the home — and the credentials in it — must survive again, or the
8959
9488
  // retry becomes the deletion the quarantine was preventing.
@@ -9096,7 +9625,22 @@ function retireClaimed(root, name, o, found) {
9096
9625
  // dead end the unusable-marker fixes closed, just reached from a valid one.
9097
9626
  const forced = !!(stillIncomplete && o.force);
9098
9627
  if (!o.keepDir && (!stillIncomplete || forced)) {
9628
+ // The removal. A failure in it (a directory that is written into, or that cannot be emptied)
9629
+ // says what the retire did and what is at the home now, as it is on disk when it is answered.
9630
+ at.phase = "removal";
9631
+ at.removing = true;
9632
+ at.said = () => {
9633
+ const recovery = recoveryOnDisk(at.recoveryPath);
9634
+ const home = homeOnDisk(found.home, true);
9635
+ return [hooksSaid(),
9636
+ recovery ? `its recovery (${recovery.phase}) is at ${recovery.path}` : at.recoveryPath ? `its recovery at ${at.recoveryPath} could not be read` : "it wrote no recovery",
9637
+ retiredEvent.ok ? "its retired event is recorded" : "its retired event could not be recorded",
9638
+ home === "removed" ? `nothing is left at ${found.home}` : `what is left at ${found.home} may not be a whole instance home`,
9639
+ sessionSaid()].join("; ") + treesDone();
9640
+ };
9641
+ at.lead = () => `${name}: the directory at ${found.home} could not be removed`;
9099
9642
  rmSync(found.home, { recursive: true, force: true });
9643
+ at.lead = () => `${name}: its home was removed, and a file the retire leaves beside it could not be`;
9100
9644
  rmSync(directoryFallbackPath, { force: true });
9101
9645
  // The owed retirement is paid: clear the pending marker, and the failed
9102
9646
  // outcome an earlier deferred attempt may have left beside the home; a
@@ -9104,6 +9648,7 @@ function retireClaimed(root, name, o, found) {
9104
9648
  rmSync(retirePendingMarkerPath(found.home), { force: true });
9105
9649
  rmSync(deferredRetireResultPath(found.home), { force: true });
9106
9650
  rmSync(deferredRetireResultPath(found.home).replace(/\.json$/, ".log"), { force: true });
9651
+ at.lead = null;
9107
9652
  }
9108
9653
 
9109
9654
  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: (() => {