@awebai/oats 0.50.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 (132) hide show
  1. package/README.md +1 -0
  2. package/bin/oats.mjs +153 -51
  3. package/docs/capabilities.md +11 -3
  4. package/docs/configuration.md +134 -88
  5. package/docs/desktop-cli-api.md +994 -71
  6. package/docs/desktop-instance-start.md +56 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +230 -59
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +73 -8
  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 +43 -7
  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.51.0.md +156 -0
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/schedules.md +91 -4
  27. package/docs/servers.md +21 -2
  28. package/docs/souls-and-instances.md +113 -21
  29. package/docs/tui.md +152 -0
  30. package/docs/workspaces.md +2 -2
  31. package/lib/claim.mjs +266 -0
  32. package/lib/core.mjs +845 -166
  33. package/lib/errors.mjs +170 -0
  34. package/lib/harness-trust-write.mjs +68 -27
  35. package/lib/harness-trust.mjs +34 -16
  36. package/lib/instance-inspect.mjs +40 -11
  37. package/lib/instance-lifecycle.mjs +169 -47
  38. package/lib/launch-preference.mjs +16 -0
  39. package/lib/launch-prompt-completion.mjs +7 -43
  40. package/lib/launch-prompt-evidence.mjs +14 -7
  41. package/lib/launch-prompt-fixtures/README.md +86 -152
  42. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  43. package/lib/launch-prompt-fixtures.mjs +122 -109
  44. package/lib/launch-prompt-transport.mjs +2 -56
  45. package/lib/launch-prompts.mjs +102 -100
  46. package/lib/schedule-host.mjs +154 -22
  47. package/lib/schedule.mjs +73 -24
  48. package/lib/servers.mjs +20 -4
  49. package/lib/session-viewer.mjs +87 -10
  50. package/lib/system-tools.mjs +39 -0
  51. package/lib/tmux-server-scope.mjs +62 -0
  52. package/lib/triggers.mjs +4 -4
  53. package/lib/workspace.mjs +5 -11
  54. package/lib/worktree-hooks.mjs +116 -23
  55. package/lib/worktree.mjs +89 -102
  56. package/package-catalog.json +3 -3
  57. package/package.json +7 -2
  58. package/packages/client/capability-show-contract.mjs +230 -0
  59. package/packages/client/capability-warnings-contract.mjs +57 -0
  60. package/packages/client/cli-adapter.mjs +548 -0
  61. package/packages/client/cli-environment.mjs +53 -0
  62. package/packages/client/cli-locator.mjs +253 -0
  63. package/packages/client/cli-probe-contract.mjs +47 -0
  64. package/packages/client/client-terms.mjs +60 -0
  65. package/packages/client/deployment-contract.mjs +68 -0
  66. package/packages/client/deployment-data.mjs +483 -0
  67. package/packages/client/deployment-facts.mjs +34 -0
  68. package/packages/client/deployment-label.mjs +76 -0
  69. package/packages/client/deployment-observer.mjs +89 -0
  70. package/packages/client/deployment-panel.mjs +142 -0
  71. package/packages/client/deployment-read-cli.mjs +53 -0
  72. package/packages/client/display-text.mjs +44 -0
  73. package/packages/client/harness-names.mjs +30 -0
  74. package/packages/client/inspect-contract.mjs +62 -0
  75. package/packages/client/instance-acts.mjs +54 -0
  76. package/packages/client/instance-admission.mjs +45 -0
  77. package/packages/client/instance-events-contract.mjs +74 -0
  78. package/packages/client/instance-git-contract.mjs +80 -0
  79. package/packages/client/instance-presentation.mjs +22 -0
  80. package/packages/client/instance-tree.mjs +453 -0
  81. package/packages/client/kernel-environment.mjs +11 -0
  82. package/packages/client/launch-contract.mjs +51 -0
  83. package/packages/client/launch-prompt-outcome.mjs +165 -0
  84. package/packages/client/lifecycle-cli.mjs +61 -0
  85. package/packages/client/lifecycle-contract.mjs +372 -0
  86. package/packages/client/liveness-main.mjs +10 -0
  87. package/packages/client/liveness.mjs +35 -0
  88. package/packages/client/machine-contract.mjs +123 -0
  89. package/packages/client/own-environment.mjs +22 -0
  90. package/packages/client/panel-views.mjs +286 -0
  91. package/packages/client/readiness-contract.mjs +172 -0
  92. package/packages/client/refresh-loop.mjs +52 -0
  93. package/packages/client/remote-address.mjs +126 -0
  94. package/packages/client/remote-roster.mjs +67 -0
  95. package/packages/client/roster-sections.mjs +80 -0
  96. package/packages/client/spawn-apply-cli.mjs +104 -0
  97. package/packages/client/spawn-apply-contract.mjs +183 -0
  98. package/packages/client/spawn-decision.mjs +46 -0
  99. package/packages/client/spawn-messages.mjs +119 -0
  100. package/packages/client/spawn-preview-cli.mjs +32 -0
  101. package/packages/client/spawn-preview-contract.mjs +314 -0
  102. package/packages/client/team-members.mjs +41 -0
  103. package/packages/client/team-rows.mjs +45 -0
  104. package/packages/client/terminal-contract.mjs +57 -0
  105. package/packages/client/tmux-status.mjs +66 -0
  106. package/packages/client/waiting-on-you.mjs +88 -0
  107. package/packages/client/workspace-admission.mjs +45 -0
  108. package/packages/client/workspace-cli.mjs +142 -0
  109. package/packages/client/workspace-views.mjs +147 -0
  110. package/packages/tui/README.md +46 -0
  111. package/packages/tui/bin/tui.mjs +7 -0
  112. package/packages/tui/lib/actions.mjs +29 -0
  113. package/packages/tui/lib/client.mjs +4 -0
  114. package/packages/tui/lib/main.mjs +105 -0
  115. package/packages/tui/lib/term/keys.mjs +323 -0
  116. package/packages/tui/lib/term/screen.mjs +122 -0
  117. package/packages/tui/lib/term/style.mjs +43 -0
  118. package/packages/tui/lib/term/text.mjs +49 -0
  119. package/packages/tui/lib/term/tty.mjs +168 -0
  120. package/packages/tui/lib/term/width.mjs +124 -0
  121. package/packages/tui/lib/views/frame.mjs +62 -0
  122. package/packages/tui/lib/views/help.mjs +28 -0
  123. package/packages/tui/package.json +8 -0
  124. package/skills/oats-getting-started/SKILL.md +29 -22
  125. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  126. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  127. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  128. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  129. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  130. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  131. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  132. 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 {
@@ -45,17 +44,18 @@ import { createHash, randomUUID } from "node:crypto";
45
44
  import { fileURLToPath } from "node:url";
46
45
  import { initializeNativeHistory, prepareNativeStart } from "../packages/record/lib/native-history.mjs";
47
46
  import { noteRuntimeName } from "./deprecation.mjs";
48
- import { attachSessionTarget } from "./session-viewer.mjs";
47
+ import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
49
48
  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";
52
+ import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, readClaim, releaseClaim, removeGoneClaim, shownHolder } from "./claim.mjs";
53
53
  import { captureLoginEnvironment } from "./login-environment.mjs";
54
54
 
55
- 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";
56
56
  import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
57
- import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigUnknown, launchLayers, launchReport, selectionFrom } from "./launch-preference.mjs";
58
- 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";
59
59
  async function materializePreparedDefault(prepared, home) { const m = await import("./instance-resolution.mjs"); return m.materializePrepared(prepared, home); }
60
60
  // Capability rows for a PREPARED spawn (workspace model): the one function that
61
61
  // turns a Resolution's modules into the row shape hooks/environment/requirements/
@@ -80,6 +80,8 @@ import { canonicalJson, lineAt, parseStrictJson } from "./canonical-json.mjs";
80
80
  import { readPortableBytes } from "./bounded-read.mjs";
81
81
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes } from "./tree-copy.mjs";
82
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";
83
85
  /** The package and capability id grammar (namespaced, lowercase): an id names a
84
86
  * directory (a home's module copy), so no path spelling fits it. */
85
87
  const PACKAGE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
@@ -171,7 +173,7 @@ export function legacyCapturedHomes(root) {
171
173
  }
172
174
  // The tmux session a new tmux instance opens its window in, when oats-local.yaml session.tmuxSession
173
175
  // names none (0.31). PI_AGENTS_TMUX_SESSION is the pre-0.31 variable, still honoured. The Desktop keeps
174
- // 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.
175
177
  export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env.PI_AGENTS_TMUX_SESSION || "oats-agents";
176
178
  /**
177
179
  * The tmux session a NEW tmux launch opens its window in (0.31): the caller's, else the deployment's
@@ -588,8 +590,11 @@ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME
588
590
  "OATS_TEST_LOGIN_SHELL",
589
591
  // The test seams of #796, the same: a worktree hook's fixed timeout, the fetch timeout of
590
592
  // `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
591
- // process's start time on a host with procfs (lib/worktree-hooks.mjs processStart).
592
- "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS"]);
593
+ // process's start time on a host with procfs, and the `ps` it runs (lib/worktree-hooks.mjs processStart).
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"]);
593
598
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
594
599
  const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
595
600
  export function validateLaunchConfig(name, entry, where) {
@@ -638,27 +643,63 @@ function validateLaunchConfigs(map, file) {
638
643
  for (const [name, entry] of Object.entries(map)) validateLaunchConfig(name, entry, file);
639
644
  validateLaunchConfigDefaults(map, file);
640
645
  }
641
- 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) {
642
672
  let found;
643
673
  try { found = loadLocal(deployment); }
644
674
  catch (e) { if (e.code !== "E_LOCAL_MISSING") throw e; }
645
- 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);
646
682
  }
647
- const promptOptedIn = policy => policy.awebDevelopmentChannel === true;
648
683
  function assertLaunchHome(home, expected) {
649
684
  const actual = directoryIdentity(home);
650
685
  if (!expected || actual.dev !== expected.dev || actual.ino !== expected.ino) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "launch home identity changed");
651
686
  }
652
- function promptController(home, startId, harness, policy, command, io, expectedHomeIdentity) {
687
+ function promptController(home, startId, command, io, expectedHomeIdentity) {
653
688
  assertLaunchHome(home, expectedHomeIdentity);
654
- const described = describeLaunchCommand(command);
655
- const qualification = qualifyLaunchPromptFixtures({ home: realPathOrNearest(home), harness, executablePath: described.executable, argv: described.argv });
656
- return createLaunchPromptController({ home: realPathOrNearest(home), startId, ...qualification, policy, expectedHomeIdentity,
689
+ return createLaunchPromptController({ home: realPathOrNearest(home), startId, ...claudeVersionOf(describeLaunchCommand(command).executable), expectedHomeIdentity,
657
690
  transport: launchPromptTransport(io), audit: data => appendEvent(home, { kind: "launch-prompt", data }), retainFrame: retainLaunchPromptFrame,
658
691
  ...(io?.now ? { now: io.now } : {}), ...(io?.sleep ? { sleep: io.sleep } : {}) });
659
692
  }
660
693
  function retainedPromptError(home, instance, target, parentLineageCommitted, launchPrompts) {
661
- 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}`), {
662
703
  instance, home, launched: "unknown",
663
704
  details: { retained: true, unconfirmed: true, instance, home, launched: "unknown", target, parentLineageCommitted, launchPrompts },
664
705
  });
@@ -678,7 +719,6 @@ function incompleteLaunchPrompt(home, startId, target, reason, previous, expecte
678
719
  return { status: "incomplete", answers: previous?.answers ?? [], reason: audit.ok === true ? reason : "launch prompt audit failed",
679
720
  receipt: [...(previous?.receipt ?? []), { ok: audit.ok === true, ...(audit.row ? { row: audit.row } : {}), results: audit.results ?? [] }] };
680
721
  }
681
- 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.";
682
722
 
683
723
 
684
724
  /** The launch configurations effective at `dir`: the `launch-configs:` of the
@@ -2009,8 +2049,8 @@ function tmuxOatsServer(args, io, options = {}) {
2009
2049
  return (io?.exec || execFileSync)("tmux", ["-u", "-L", OATS_TMUX_SERVER, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...options });
2010
2050
  }
2011
2051
  const tmuxFailure = (e, fallback) => String(e?.stderr ?? e?.message ?? "").trim() || fallback;
2012
- /** An error OATS raised itself (a root guard under an injected exec), never one a tolerant read may absorb. */
2013
- 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"));
2014
2054
  /** A failed call that ran to its own exit: it has a status, no signal ended it, and Node reports no
2015
2055
  * failure of its own. A timeout and an output overflow carry a code and keep what the call had
2016
2056
  * printed until then, so that text is not the call's answer. Anything else is not a completed call. */
@@ -2026,7 +2066,7 @@ function oatsTmuxSessionSocket(session, io, missingSocket) {
2026
2066
  let listed;
2027
2067
  try { listed = tmuxOatsServer(["list-sessions", "-F", "#{session_name}\t#{socket_path}"], io); }
2028
2068
  catch (e) {
2029
- if (oatsCoded(e)) throw e;
2069
+ if (isKernelCode(e?.code)) throw e;
2030
2070
  // A tmux that could not be run at all is the one failure a person can act on: say so.
2031
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`);
2032
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"})`);
@@ -2255,7 +2295,7 @@ function recordedServerEnvironment(caller, session, io) {
2255
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`) };
2256
2296
  let target;
2257
2297
  try { target = instanceSessionTarget(caller.home).target; }
2258
- 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})`) }; }
2259
2299
  if (!target?.socket) return { read: null, error: refuse(`the home of ${basename(caller.home)} records no tmux server`) };
2260
2300
  // Bytes, not text; and nothing of a failed read (tmux's output, its error) goes into the refusal.
2261
2301
  let read = null;
@@ -2263,7 +2303,7 @@ function recordedServerEnvironment(caller, session, io) {
2263
2303
  try {
2264
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"] });
2265
2305
  read = parseTmuxShellEnvironment(Buffer.isBuffer(printed) ? printed : Buffer.from(String(printed)), omitted);
2266
- } catch (e) { if (oatsCoded(e)) throw e; }
2306
+ } catch (e) { if (isKernelCode(e?.code)) throw e; }
2267
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`) };
2268
2308
  // A variable the reader left out is never filled in from this process, and a server is never
2269
2309
  // started when the one left out decides which configuration it loads or which programs it runs.
@@ -2327,7 +2367,7 @@ function panePath(socket, session, io, cwd) {
2327
2367
  try {
2328
2368
  const printed = (io?.exec || execFileSync)("tmux", ["-u", "-S", socket, "show-environment", ...scope, "-s"], { timeout: 10000, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
2329
2369
  env = parseTmuxShellEnvironment(Buffer.isBuffer(printed) ? printed : Buffer.from(String(printed)), omitted, cleared);
2330
- } catch (e) { if (oatsCoded(e)) throw e; }
2370
+ } catch (e) { if (isKernelCode(e?.code)) throw e; }
2331
2371
  return { env, omitted, cleared };
2332
2372
  };
2333
2373
  const decide = ({ env, omitted, cleared }, source, unset) => {
@@ -2383,8 +2423,12 @@ function launchLookup(configEnv, env, pane, configName, cwd) {
2383
2423
  * its own PATH names no tmux to create it with (creatorTmux). `missingSocket` is a session start's
2384
2424
  * check of its home when the server's socket file is missing (oatsTmuxSessionSocket): with a reason,
2385
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.
2386
2430
  */
2387
- export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket) {
2431
+ export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket, warnings) {
2388
2432
  let { server: socket, present } = oatsTmuxSessionSocket(session, io, missingSocket);
2389
2433
  if (!present) {
2390
2434
  // The executable is chosen here, where the creation is about to run, and nowhere earlier: a
@@ -2394,10 +2438,38 @@ export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket) {
2394
2438
  // this call starts gets what a server start gets.
2395
2439
  const env = plan?.env && (plan.startsServer || socket) ? plan.env : oatsSessionEnvironment(session, io, { startsServer: !socket });
2396
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; };
2397
2457
  let created;
2398
- 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
+ }
2399
2471
  catch (e) {
2400
- if (oatsCoded(e)) throw e;
2472
+ if (isKernelCode(e?.code)) throw e;
2401
2473
  const again = oatsTmuxSessionSocket(session, io, missingSocket);
2402
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")}`);
2403
2475
  socket = again.server;
@@ -2430,7 +2502,7 @@ const paneCommand = (command) => `unset COLORFGBG; ${command}; exec "\${SHELL:-/
2430
2502
  function sizeWindow(socket, windowId, io) {
2431
2503
  if (!/^@\d+$/.test(windowId || "")) return;
2432
2504
  for (const [option, value] of OATS_WINDOW_SIZING) {
2433
- 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; }
2434
2506
  }
2435
2507
  }
2436
2508
  /** The agent window OATS just created, by the id new-window returned: showing the viewer's colours and
@@ -2668,6 +2740,57 @@ export function upgradeHomeMeta(meta, home) {
2668
2740
  const { runtime, ...rest } = meta;
2669
2741
  return { ...rest, ...(runtime !== undefined || meta.harness !== undefined ? { harness: meta.harness ?? runtime } : {}), ...(meta.launch !== undefined ? { launch: upgradeLaunchRecipe(meta.launch) } : {}) };
2670
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
+ }
2671
2794
  const LAUNCH_PROMPT = { kind: "task-file", file: "TASK.md" };
2672
2795
  /** The fixed prompt a codex launch starts with: it names the task file, never its text (argv is
2673
2796
  * readable by every local user). Codex reads the file with a tool. */
@@ -2808,12 +2931,15 @@ export function homeLaunchLayers(realHome, meta) {
2808
2931
  /** A NEW launch selection (a spawn, or a start/restart that reselects) from the flags and the launch
2809
2932
  * layers (lib/launch-preference.mjs). → { launchSelection (resolveLaunchSelection's), launchChoice:
2810
2933
  * { from, at, declared } }. A configuration a layer names but the host lacks is E_LAUNCH_CONFIG_UNKNOWN
2811
- * naming the layer. Never reads a frozen recipe. */
2812
- 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 }) {
2813
2937
  const choice = selectionFrom({ flags, layers });
2814
2938
  const named = choice.from !== "flag" && choice.selection.launchConfig !== undefined && choice.selection.launchConfig !== "none" ? choice.selection.launchConfig : null;
2815
2939
  if (named !== null && !Object.hasOwn(launchConfigs, named)) throw launchConfigUnknown({ name: named, from: choice.from, at: choice.at });
2816
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;
2817
2943
  return { launchSelection, launchChoice: { from: choice.from, at: choice.at, declared: layers?.declared ?? null } };
2818
2944
  }
2819
2945
  /** The `Launch` report (feature launch-preference) a spawn with no flags would decide HERE, for listings
@@ -2833,6 +2959,8 @@ export function launchReportFor({ layers, launchConfigs = {}, contextDir }) {
2833
2959
  } else if (choice.preference) { harness = choice.preference.harness; model = choice.preference.model ?? null; }
2834
2960
  // As a spawn: a layer naming "none" asks for the bare harness; otherwise no configuration is the harness default.
2835
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 });
2836
2964
  let exe;
2837
2965
  try { exe = resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir }); }
2838
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}` }); }
@@ -2918,17 +3046,21 @@ function deploymentOfHome(home, meta) {
2918
3046
  if (dirname(d) === d) return realPathOrNearest(dirname(dirname(dirname(dirname(resolve(home))))));
2919
3047
  }
2920
3048
  }
2921
- /** Folder trust for a launch in `home` (lib/harness-trust.mjs, read-only): `trustHome` — the
2922
- * codex launch trusts the home, because the operator trusts its deployment root or an
2923
- * ancestor — and the warning when the session will stop at its harness's folder-trust prompt. */
2924
- 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 };
2925
3056
  const root = deploymentOfHome(home, meta);
2926
- if (harness === "codex") {
2927
- const trustHome = codexTrustsRoot(root, { env });
2928
- return { trustHome, warning: harnessTrustWarning({ harness, root, covered: trustHome || yolo === true }) };
2929
- }
2930
- if (harness === "claude") return { trustHome: false, warning: harnessTrustWarning({ harness, root, covered: claudeTrusts(home, { env }) }) };
2931
- 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 }) };
2932
3064
  }
2933
3065
 
2934
3066
  /** The harness command line of a recipe. With no configuration the bytes
@@ -3149,11 +3281,12 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3149
3281
  ...(frozen?.legacy ? { legacy: { ...frozen.legacy, ...(hooks.refreshed?.length ? { replacedBy: hooks.refreshed } : {}) } } : {}),
3150
3282
  };
3151
3283
  const inst = instance || meta?.instance || basename(home);
3152
- 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 });
3153
3285
  const command = renderLaunchRecipe(recipe, { home, instance: inst, trustHome });
3154
3286
  const selectionSource = frozen ? (config?.frozen || (!config && !selection.launchConfig && !selection.harness) ? "frozen" : "config") : "config";
3155
- const launchPromptAnswers = preview ? launchPromptPolicyAt(dirname(dirname(dirname(dirname(home)))), home) : null;
3156
- 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 } : {}) };
3157
3290
  }
3158
3291
  /** The environment a planned launch runs under: the host's base, the
3159
3292
  * capabilities' validated env, the configuration's literals and its
@@ -3269,7 +3402,7 @@ function* spawnBody(root, agent, o = {}) {
3269
3402
  // Feature launch-preference: the flags, else the machine's souls.launch, else the soul's own launch,
3270
3403
  // else the host default — `launchChoice` says which layer decided (instance.json launchFrom/launchAt).
3271
3404
  let launchSelection, launchChoice;
3272
- 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 })); }
3273
3406
  catch (e) { previewPreflightBudget = null; throw e; }
3274
3407
  const launchConfig = launchSelection.config;
3275
3408
  const harness = launchSelection.harness;
@@ -3497,6 +3630,9 @@ function* spawnBody(root, agent, o = {}) {
3497
3630
  }
3498
3631
  }
3499
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");
3500
3636
  const anchorMetaPath = anchorHome ? join(anchorHome, "instance.json") : undefined;
3501
3637
  const anchorOriginal = anchorMetaPath && existsSync(anchorMetaPath) ? readFileSync(anchorMetaPath, "utf8") : null;
3502
3638
  const anchorMeta = anchorOriginal === null ? undefined : JSON.parse(anchorOriginal);
@@ -3531,7 +3667,8 @@ function* spawnBody(root, agent, o = {}) {
3531
3667
  if (parentInstance && parentInstance !== instance) {
3532
3668
  const parentHome = parentInstance === relativeTo && anchorHome ? anchorHome
3533
3669
  : findInstanceHome(root, parentInstance)?.home;
3534
- 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;
3535
3672
  const policy = childPolicyOf(parentMeta);
3536
3673
  if (policy.allowed === false) {
3537
3674
  // A preview touches nothing — not even the parent's event log; the
@@ -3698,7 +3835,7 @@ function* spawnBody(root, agent, o = {}) {
3698
3835
  d.revision = createHash("sha256").update(canonicalJson(d)).digest("hex").slice(0, 24);
3699
3836
  return d;
3700
3837
  };
3701
- const launchPromptAnswers = launchPromptPolicyAt(o.prepared.deployment || workspaceOf(root), home);
3838
+ const launchPromptNotice = launchPromptAnswersNotice(o.prepared.deployment || workspaceOf(root));
3702
3839
  if (o.preview === true) {
3703
3840
  const decision = buildDecision();
3704
3841
  // Workspace model (M3): the preview reports what APPLY will produce — every
@@ -3716,14 +3853,15 @@ function* spawnBody(root, agent, o = {}) {
3716
3853
  // Addendum 5: where each leaf of `settings.<cap>` came from (JSON pointer → { kind, at }):
3717
3854
  // manifest-default | workspace | soul | host | spawn, the last layer that set it.
3718
3855
  const preparedSettingsOrigins = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloadOrigins?.[m.name] ?? {})]));
3719
- // The preview's warnings are strings: the launch-prompt notice, then what a module declares and this kernel ignores.
3720
- 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))];
3721
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] : {})]));
3722
3860
  return deliver({
3723
3861
  // Team model v2: the soul's teams here (unmapped rows included) and its default — the choice a
3724
3862
  // Desktop offers before anything is minted; joining any but the default is the provider's explicit act.
3725
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 },
3726
- 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,
3727
3865
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
3728
3866
  decision, preflight,
3729
3867
  backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
@@ -4046,7 +4184,7 @@ function* spawnBody(root, agent, o = {}) {
4046
4184
  }
4047
4185
 
4048
4186
  // What the composed modules declare and this kernel ignores (an unknown hook event), as the preview said.
4049
- const warnings = [...(promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared?.resolution))];
4187
+ const warnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared?.resolution))];
4050
4188
 
4051
4189
  // Establish directory ownership while these are still the kernel's own roots.
4052
4190
  // A hook may replace either path; it must never mint authority for that target.
@@ -4380,7 +4518,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4380
4518
  prompt: LAUNCH_PROMPT, kernelBin: shimTarget,
4381
4519
  };
4382
4520
  if (triggerEventFile) recipe.env.OATS_TRIGGER_EVENT_FILE = triggerEventFile;
4383
- 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 });
4384
4522
  if (folderTrust.warning) warnings.push(folderTrust.warning);
4385
4523
  let cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
4386
4524
 
@@ -4487,7 +4625,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4487
4625
  if (launch) {
4488
4626
  // The session on the OATS server, then everything on the one socket that answered: the collision
4489
4627
  // check, the records, the window and (in compensateSpawn) its removal.
4490
- 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);
4491
4629
  // The harness looked up again on the PATH this window's pane will actually start with, whoever
4492
4630
  // created the session and with whatever environment (a race lost to another creator, a session
4493
4631
  // that overrides PATH). Not there: refused, and the spawn is compensated. Found elsewhere than
@@ -4509,6 +4647,10 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4509
4647
  if (present.includes(instance)) throw new Error(`tmux window "${instance}" already exists in session ${session}`);
4510
4648
  meta.tmux.socket = socket;
4511
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);
4512
4654
  // Commit the final child metadata and its independent byte authority before
4513
4655
  // the managed harness can write. No child-home transition follows launch.
4514
4656
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n");
@@ -4519,13 +4661,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4519
4661
  const windowCmd = paneCommand(executionCommand);
4520
4662
  const paneEnvFlags = launchEnvRefs(recipe, process.env).flatMap((r) => ["-e", `${r.name}=${r.value}`]);
4521
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`);
4522
- const policy = launchPromptPolicyAt(o.prepared.deployment || workspaceOf(root), home);
4523
- // Only a consented prompt launch needs lineage committed before dispatch:
4524
- // its uncertain input outcome retains the new process and parent link.
4525
- // Ordinary launches keep their established post-launch commit/rollback.
4526
- if (promptOptedIn(policy)) commitParentLineage();
4527
- promptStartId = randomUUID();
4528
- 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;
4529
4669
  windowMayExist = true;
4530
4670
  promptDispatched = !!controller;
4531
4671
  let windowId;
@@ -4537,10 +4677,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4537
4677
  catch (e) { throw launchFailed("set-option", "the new window's options were refused", e); }
4538
4678
  if (controller) {
4539
4679
  promptResult = controller.observeNew(promptTarget);
4540
- 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;
4541
4682
  meta.launchPromptTarget = promptTarget;
4542
4683
  meta.parentLineageCommitted = parentLineageCommitted;
4543
- meta.launched = promptResult.status === "completed";
4684
+ meta.launched = promptLaunched(promptResult.status);
4544
4685
  assertLaunchHome(home, createdHomeIdentity);
4545
4686
  writeJsonAtomic(join(home, "instance.json"), meta);
4546
4687
  if (!meta.launched) throw retainedPromptError(home, instance, promptTarget, parentLineageCommitted, promptResult);
@@ -4552,8 +4693,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4552
4693
  clearSpawnInProgressMarker();
4553
4694
  }
4554
4695
 
4555
- // Ordinary launches and scaffolds commit here; opted-in launches already
4556
- // 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.
4557
4699
  commitParentLineage();
4558
4700
 
4559
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 } : {}) } });
@@ -4566,7 +4708,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4566
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 });
4567
4709
  } catch (error) {
4568
4710
  if (promptDispatched) {
4569
- // Once opted-in launch dispatch occurred, uncertainty retains all effects.
4711
+ // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
4570
4712
  // The independent baseline remains launched:true: metadata is not proof of quiescence.
4571
4713
  let result = promptResult?.status === "blocked" || promptResult?.status === "incomplete" ? promptResult : incompleteLaunchPrompt(home, promptStartId, promptTarget ?? spawnTmux, "launch prompt dispatch or recording incomplete", promptResult, createdHomeIdentity);
4572
4714
  try {
@@ -4685,11 +4827,11 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
4685
4827
  return (existsSync(instancesDir) ? readdirSync(instancesDir, { withFileTypes: true }) : [])
4686
4828
  .filter((e) => e.isDirectory() && !e.name.startsWith("."))
4687
4829
  .map((e) => {
4688
- const metaPath = join(instancesDir, e.name, "instance.json");
4689
4830
  const home = join(instancesDir, e.name);
4690
- const meta = existsSync(metaPath)
4691
- ? upgradeHomeMeta(JSON.parse(readFileSync(metaPath, "utf8")), home)
4692
- : { 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 };
4693
4835
  // A home retained by an incomplete rollback is NOT a live instance: it
4694
4836
  // is preserved state awaiting cleanup, and must read that way.
4695
4837
  const fallback = directoryRollbackPath(home);
@@ -4716,7 +4858,9 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
4716
4858
  catch { retirePending = { reason: "retire pending" }; }
4717
4859
  }
4718
4860
  // A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
4719
- 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)))
4720
4864
  ? { running: null, runtimeState: "unsupported", runtimeError: `E_HERDR_REMOVED: ${herdrInstanceRemoved(e.name).message}` }
4721
4865
  : tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name, scanOf(home),
4722
4866
  // A home that records no socket and no launch (--no-launch) reads the default server only
@@ -5906,6 +6050,8 @@ function instanceSessionTarget(home) {
5906
6050
  if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home);
5907
6051
  throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${e.message}`);
5908
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`);
5909
6055
  const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
5910
6056
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
5911
6057
  if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
@@ -5918,7 +6064,8 @@ export function inspectInstanceSession(home) {
5918
6064
  if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", waitingOnYou: null };
5919
6065
  let observed;
5920
6066
  try { observed = inspectSessionTarget(s.target); }
5921
- 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 }); }
5922
6069
  // Feature waiting-on-you: beside `state`, whose enum is unchanged.
5923
6070
  return { home: s.home, ...observed, waitingOnYou: harnessRunning(observed) ? liveWaiting(s.home) : null };
5924
6071
  }
@@ -5939,6 +6086,15 @@ function tmuxServerAbsence(e) {
5939
6086
  return null;
5940
6087
  }
5941
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
+ }
5942
6098
  /** tmux's own way back for a server that lost its socket file (tmux(1), `-S`). Named, never performed. */
5943
6099
  const TMUX_SOCKET_REMEDY = "tmux recreates a removed socket file when its server process receives SIGUSR1";
5944
6100
  /** Processes as a refusal names them: pid and program, at most five, then how many more. */
@@ -6115,42 +6271,114 @@ function recordedSessionAbsence(home, meta, io) {
6115
6271
  * file is idle only when no process works in the home (#624). */
6116
6272
  export function stopInstanceSession(home, o = {}) {
6117
6273
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session stop needs an absolute instance home");
6118
- 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) {
6119
6295
  const realHome = realPathOrNearest(home);
6120
- if (existsSync(retirePendingMarkerPath(realHome))) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired; nothing was stopped`);
6121
- const s = instanceSessionTarget(realHome);
6122
- if (!s.target) return { home: s.home, backend: null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
6123
- let before;
6124
- try { before = inspectSessionTarget(s.target); }
6125
- catch (e) {
6126
- const absence = tmuxServerAbsence(e);
6127
- const why = absence === "missing-socket" ? missingSocketUnestablished(tmuxFailure(e, e.message), processesInHome(realHome, o.io)) : null;
6128
- if (absence && !why) before = { present: false, state: "stopped" };
6129
- else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${why ?? e.message}`);
6130
- }
6131
- 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 };
6132
- const receipt = stopHarness(s.target, { graceMs: o.graceMs ?? 20000, kill: o.io?.kill, sleep: o.io?.sleep });
6133
- writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: receipt, retained: ["home", "work", "transcript", "launch"] });
6134
- appendEvent(realHome, { kind: receipt.exited ? "stopped" : "stop-refused", data: { signal: receipt.signal, waitedMs: receipt.waitedMs, stillRunning: receipt.stillRunning ?? [], state: receipt.state } });
6135
- 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 });
6136
- return { home: s.home, backend: s.target.backend, stopped: true, alreadyIdle: false, state: receipt.state, receipt };
6137
- }
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();
6138
6357
 
6139
6358
  /** What a retire plan promises about recorded children, applied: each is stopped
6140
6359
  * (default grace, never escalated) in the order given (the plan's: deepest first)
6141
6360
  * and kept. Every outcome is collected, so a refusal names each child that is
6142
- * still running or whose stop could not be established. */
6143
- 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) {
6144
6364
  return children.map((kid) => {
6145
- try { const s = stopInstanceSession(kid.home, {}); return { instance: kid.instance, home: kid.home, ok: true, stopped: s.stopped, alreadyIdle: s.alreadyIdle }; }
6146
- 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
+ }
6147
6374
  });
6148
6375
  }
6149
6376
 
6150
- export async function attachInstanceSession(home) {
6377
+ export async function attachInstanceSession(home, { detachKey } = {}) {
6378
+ if (detachKey !== undefined) requireDetachKey(detachKey);
6151
6379
  const s = instanceSessionTarget(home);
6152
6380
  if (!s.target) throw oatsError("E_SESSION_NOT_RUNNING", "instance was not launched");
6153
- return attachSessionTarget(s.target);
6381
+ return attachSessionTarget(s.target, { detachKey });
6154
6382
  }
6155
6383
 
6156
6384
  export function inputInstanceSession(home, text) {
@@ -6507,6 +6735,8 @@ export function preWorkspaceHome(home, what) {
6507
6735
  }
6508
6736
  export function startInstanceSession(home, o = {}) {
6509
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);
6510
6740
  // A home opened in Herdr, or an earlier start that allocated a Herdr pane, is refused before any
6511
6741
  // guard or receipt reads it.
6512
6742
  refuseHerdrHome(realPathOrNearest(home));
@@ -6529,7 +6759,12 @@ export function startInstanceSession(home, o = {}) {
6529
6759
  const lock = join(realHome, ".oats-start.lock");
6530
6760
  const pendingPath = join(realHome, ".oats-start-pending.json");
6531
6761
  const exitedPath = join(realHome, ".oats-start-exited");
6532
- 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
+ };
6533
6768
  // Workspace-model homes only (lead decision c3 Q2): a home an earlier kernel
6534
6769
  // spawned records no modules, and there is no scope configuration left to
6535
6770
  // re-resolve it against. Retire still works on it.
@@ -6540,9 +6775,8 @@ export function startInstanceSession(home, o = {}) {
6540
6775
  // passes), else `{ stopped: false, why }`: the check's reason, or null for another failure.
6541
6776
  const missingSocket = (detail) => missingSocketUnestablished(detail, processesInHome(realHome, rawIo));
6542
6777
  const lostServer = (e) => {
6543
- const absence = tmuxServerAbsence(e);
6544
- const why = absence === "missing-socket" ? missingSocket(tmuxFailure(e, e.message)) : null;
6545
- 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 };
6546
6780
  };
6547
6781
  const launchFailure = (error) => {
6548
6782
  // execFileSync errors embed argv (including capability environment) in
@@ -6575,9 +6809,11 @@ export function startInstanceSession(home, o = {}) {
6575
6809
  // Launch-hook meta lands per capability over the spawn's record; a hook
6576
6810
  // that answered without meta keeps its previous entry (retire reads it).
6577
6811
  ...(hookMeta ? { capabilityMeta: { ...(meta.capabilityMeta || {}), ...hookMeta } } : {}) };
6578
- 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) {
6579
6815
  next.launchPrompts = launchPrompts; next.launchPromptTarget = launchPromptTarget ?? target;
6580
- next.launched = launchPrompts.status === "completed";
6816
+ next.launched = promptLaunched(launchPrompts.status);
6581
6817
  } else { delete next.launchPrompts; delete next.launchPromptTarget; }
6582
6818
  next.tmux = { session: target.session, window: target.window, socket: resolve(target.socket) };
6583
6819
  writeJsonAtomic(metaPath, next);
@@ -6741,7 +6977,7 @@ export function startInstanceSession(home, o = {}) {
6741
6977
  if (recorded.error) return undefined; // the gate refuses below; the lookup does not decide it
6742
6978
  const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
6743
6979
  if (!preview || preview.server) return expectedPanePath(preview, planSession, o.io, realHome);
6744
- 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; }
6745
6981
  };
6746
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,
6747
6983
  panePath: pane });
@@ -6837,8 +7073,8 @@ export function startInstanceSession(home, o = {}) {
6837
7073
  const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
6838
7074
  ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
6839
7075
  ...(hookMeta ? { hookMeta } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
6840
- const launchPromptAnswers = launchPromptPolicyAt(dirname(dirname(dirname(dirname(home)))), realHome);
6841
- 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);
6842
7078
  let stopReceipt = null;
6843
7079
  if (state.present && state.state !== "shell") {
6844
7080
  // Restart: every preflight above passed, so ask the running harness to
@@ -6861,7 +7097,8 @@ export function startInstanceSession(home, o = {}) {
6861
7097
  writeKernelShim(realHome);
6862
7098
  const startedAt = new Date().toISOString();
6863
7099
  const id = randomUUID();
6864
- 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;
6865
7102
  let launchController;
6866
7103
  let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
6867
7104
  checkRoots();
@@ -6901,12 +7138,12 @@ export function startInstanceSession(home, o = {}) {
6901
7138
  // A replacement window (never launched, recorded window gone, recorded server gone) is created
6902
7139
  // on the OATS server, wherever the home was recorded: one socket from here to the record.
6903
7140
  const recordedSocket = socket ? resolve(socket) : null;
6904
- socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket);
7141
+ socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
6905
7142
  if (lookAgain(() => panePath(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
6906
7143
  let names;
6907
7144
  try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
6908
7145
  catch (e) {
6909
- if (oatsCoded(e)) throw e;
7146
+ if (isKernelCode(e?.code)) throw e;
6910
7147
  throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
6911
7148
  }
6912
7149
  if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
@@ -6924,6 +7161,7 @@ export function startInstanceSession(home, o = {}) {
6924
7161
  if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
6925
7162
  }
6926
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); }
6927
7165
  } catch (error) {
6928
7166
  if (!promptDispatched) throw error;
6929
7167
  launchPrompts = incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt dispatch or recording incomplete", launchPrompts, originalHomeIdentity);
@@ -6952,7 +7190,7 @@ export function startInstanceSession(home, o = {}) {
6952
7190
  if (e.code && String(e.code).startsWith("E_")) throw e;
6953
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`);
6954
7192
  }
6955
- 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);
6956
7194
  // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
6957
7195
  if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
6958
7196
  return { ...done, warnings: [...warnings, ...movedWarnings] };
@@ -8166,18 +8404,42 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8166
8404
  rmSync(logPath, { force: true });
8167
8405
  throw scheduleFailed(e.message);
8168
8406
  }
8169
- closeSync(fd);
8170
- if (!child.pid) { rmSync(logPath, { force: true }); throw scheduleFailed("no process was created"); }
8171
- // A spawn failure Node reports asynchronously (EAGAIN, EMFILE) would arrive
8172
- // after this returns; record it as a failed outcome so status shows the
8173
- // debt instead of an uncaught exception behind a success message.
8174
- child.on("error", (e) => {
8175
- try {
8176
- 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");
8177
- } catch { /* the marker alone then shows RETIRING; status names its age */ }
8178
- });
8179
- child.unref();
8180
- writeFileSync(marker, JSON.stringify(intent, 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
+ }
8181
8443
  return {
8182
8444
  retired: name, agent: found.agent.name, deferred: true, pendingMarker: marker,
8183
8445
  resultPath, logPath, completesInSec: delaySec, completionPid: child.pid,
@@ -8199,6 +8461,9 @@ const OBSOLETE_DELETE_BRANCH_SENTENCE = "this self-retire was requested with --d
8199
8461
  /** The one internal option that says the retirement completes such an intent.
8200
8462
  * A symbol, so no caller can set it from parsed arguments or JSON. */
8201
8463
  const OBSOLETE_DELETE_BRANCH = Symbol("an older self-retire intent with --delete-branch");
8464
+ /** The one internal option that says the retirement is a deferred self-retire's completion
8465
+ * (completeDeferredRetirement). A symbol, so no caller can set it from parsed arguments or JSON. */
8466
+ const COMPLETES_DEFERRED = Symbol("the completion of a deferred self-retire");
8202
8467
  export const RETIRE_DELETE_BRANCH_REFUSED = "oats retire no longer deletes branches: --delete-branch is not accepted. Retire without it; the branch is left in the repository. Inspect it there and delete it with Git if it is no longer wanted.";
8203
8468
 
8204
8469
  export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
@@ -8230,10 +8495,16 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8230
8495
  ...(Array.isArray(intent.options?.plannedExtraWorktrees) ? { plannedExtraWorktrees: intent.options.plannedExtraWorktrees } : {}),
8231
8496
  ...(Array.isArray(intent.options?.children) ? { children: intent.options.children } : {}),
8232
8497
  ...(obsoleteDeleteBranch ? { [OBSOLETE_DELETE_BRANCH]: true } : {}),
8498
+ // The retire that scheduled this completion may still hold the home's claim, about to write
8499
+ // the marker and return: it is waited for, so the two are ordered by the claim and never by
8500
+ // which process is faster.
8501
+ [COMPLETES_DEFERRED]: true,
8233
8502
  });
8234
8503
  } catch (e) {
8235
- 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}` : ""}` });
8236
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);
8237
8508
  return false;
8238
8509
  }
8239
8510
  if (obsoleteDeleteBranch) console.log(OBSOLETE_DELETE_BRANCH_SENTENCE);
@@ -8259,30 +8530,365 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8259
8530
  * (awebai/oats#693): the CLI cleans that home's wake schedules. A symbol, so
8260
8531
  * the printed and JSON receipt, and a recorded one, do not carry it. */
8261
8532
  export const RETIRE_SELECTED_HOME = Symbol("oats.retireSelectedHome");
8262
- export function retireInstance(root, name, o = {}) {
8263
- if (o.deleteBranch) throw oatsError("E_BAD_ARGS", RETIRE_DELETE_BRANCH_REFUSED);
8264
- const session = o.tmuxSession || DEFAULT_TMUX_SESSION;
8265
- // self-retire: the caller IS the instance. Without --keep-dir the whole
8266
- // retirement is deferred to a detached external completion (below); with
8267
- // --keep-dir the old in-process path runs and kills the window LAST.
8268
- const self = o.self === true;
8269
- // Names are unique per agent dir only: two agents can own an instance of
8270
- // the same name (dev --purpose foo-1 and agent dev-foo). Retirement is
8271
- // destructive, so a name that resolves to several homes is refused unless
8272
- // the caller says which home (--home), and a home is accepted only when it
8273
- // is one of that name's homes under this root.
8533
+ /** An option of retireInstance: a function it calls once it holds the home's claim, has resolved
8534
+ * the home again and has found no pending self-retire, before it reads anything else. What the
8535
+ * function throws is the retire's answer, and nothing was done; what it returns, `{ children?,
8536
+ * plannedExtraWorktrees? }`, sets those two options. `oats retire` reads here what the retire
8537
+ * acts on, so that it is the state the retire starts from, never one another retire changed
8538
+ * afterwards: a guarded apply its plan, once, refusing a revision that is not the one shown
8539
+ * (E_PLAN_STALE); a plain or `--self` retire its recorded children. Against a retire in flight
8540
+ * the answer is that it is running, and neither is read. A symbol, so no caller can set it from
8541
+ * parsed arguments or JSON. */
8542
+ export const RETIRE_UNDER_CLAIM = Symbol("oats.retireUnderClaim");
8543
+ /** How many times a retire starts over because the name resolved to another home once it held the
8544
+ * claim of the first (that one removed, a same-named home of another agent made, in between). */
8545
+ const RETIRE_CLAIM_RESTARTS = 2;
8546
+
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) {
8552
+ return join(instancesRetirementRoot(dirname(home)), "claims", `${basename(home)}.lock`);
8553
+ }
8554
+
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
+ };
8599
+ return {
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);
8610
+ },
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),
8624
+ };
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
+ }
8689
+
8690
+ /** The homes `name` resolves to under `root`, and the one a retire acts on. Names are unique per
8691
+ * agent dir only: two agents can own an instance of the same name (dev --purpose foo-1 and agent
8692
+ * dev-foo). Retirement is destructive, so a name that resolves to several homes is refused unless
8693
+ * the caller says which home (--home), and a home is accepted only when it is one of that name's
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. */
8696
+ function resolveRetireHome(root, name, o) {
8274
8697
  const matches = findInstanceHomes(root, name);
8275
8698
  if (!matches.length) throw oatsError("E_SESSION_UNKNOWN", `no instance named "${name}"`);
8276
8699
  const sameHome = (a, b) => { try { return realpathSync(a) === realpathSync(b); } catch { return resolve(a) === resolve(b); } };
8277
- let found;
8700
+ let found = matches[0];
8278
8701
  if (o.home) {
8279
8702
  found = matches.find((m) => sameHome(m.home, o.home));
8280
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(", ")})`);
8281
8704
  } else if (matches.length > 1) {
8282
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`);
8283
- } else {
8284
- found = matches[0];
8285
8706
  }
8707
+ identifiedHomeRecord(found.home);
8708
+ return found;
8709
+ }
8710
+
8711
+ /** `name` has no home under `root`: remove a retire claim of that name whose holder is gone, in
8712
+ * each instances directory the lookup searches (a retire killed after it removed the home and
8713
+ * before it released). One whose holder is alive, unknown or unreadable is left as it is. `name`
8714
+ * is the caller's: no path is built from one outside the instance-name grammar. */
8715
+ function removeAbandonedRetireClaims(root, name) {
8716
+ if (typeof name !== "string" || !INSTANCE_NAME_RE.test(name)) return;
8717
+ const dirs = new Set([...listAgents(root).map((a) => a._dir), ...capabilityAgentDirs(root).map((c) => c.dir)]);
8718
+ for (const dir of dirs) {
8719
+ const home = join(dir, "instances", name);
8720
+ const lock = retireClaimPath(home);
8721
+ // Whatever stops the removal, the answer is the same: there is no such instance.
8722
+ try { removeGoneClaim(lock, { ...retireClaimRefusals(name, home, lock), waitMs: 0 }); } catch { /* left as it is */ }
8723
+ }
8724
+ }
8725
+
8726
+ /** A deferred self-retire is scheduled for `home` and its completion has not started: every other
8727
+ * retire of the home is refused while that completion lives. The pending marker
8728
+ * (scheduleDeferredSelfRetirement) names it. Nothing refuses when there is no marker, when the
8729
+ * completion left its outcome (it failed: this retire retries it), when the marker names no
8730
+ * completion (an older kernel wrote it), when this process is that completion, or when that
8731
+ * process is gone (it died: this retire does what it owed). */
8732
+ function refusePendingCompletion(name, home) {
8733
+ const marker = retirePendingMarkerPath(home);
8734
+ if (!existsSync(marker) || existsSync(deferredRetireResultPath(home))) return;
8735
+ const pending = readJsonOrUndefined(marker);
8736
+ const pid = pending?.completionPid;
8737
+ if (!Number.isSafeInteger(pid) || pid === process.pid) return;
8738
+ const live = processLiveness({ pid, processStart: pending.completionStart });
8739
+ if (live.state === "gone") return;
8740
+ const start = typeof pending.completionStart === "string" ? pending.completionStart : "none";
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 });
8745
+ }
8746
+
8747
+ /** Retire one instance. One retire of a home at a time (awebai/oats#863): the home's claim
8748
+ * (retireClaimPath; lib/claim.mjs) is taken as soon as the home is resolved, before anything the
8749
+ * retire acts on is read, and held until this returns or throws. Any other retire of that home
8750
+ * is refused at once (E_LIFECYCLE_BUSY) before it stops, copies or runs anything; `--force` does
8751
+ * not bypass it. A claim left by a killed retire is taken over. Every apply path runs this
8752
+ * function: the CLI, the deferred completion, and `--server` on the host. Synchronous. */
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) {
8761
+ if (o.deleteBranch) throw oatsError("E_BAD_ARGS", RETIRE_DELETE_BRANCH_REFUSED);
8762
+ let found;
8763
+ try { found = resolveRetireHome(root, name, o); }
8764
+ catch (e) {
8765
+ if (e.code === "E_SESSION_UNKNOWN") removeAbandonedRetireClaims(root, name);
8766
+ throw e;
8767
+ }
8768
+ for (let restarts = 0; ; restarts++) {
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;
8773
+ try {
8774
+ // Resolved again under the claim: another retire may have removed the home between the
8775
+ // first resolution and the claim. Gone is what a retire of a retired instance answers.
8776
+ const now = resolveRetireHome(root, name, o);
8777
+ if (retireClaimPath(now.home) !== lock) {
8778
+ // The name is another home's now, whose claim this does not hold: start over on that one.
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) });
8780
+ found = now;
8781
+ continue;
8782
+ }
8783
+ // Every retire that runs here, in this process: a `--self` that only schedules answers that
8784
+ // one is already scheduled (scheduleDeferredSelfRetirement).
8785
+ if (o.self !== true || o.keepDir) refusePendingCompletion(name, now.home);
8786
+ // What the caller confirms once nobody else can be retiring this home (a guarded apply reads
8787
+ // its plan and checks the revision): after the two answers above, before the retire reads
8788
+ // anything of the home. What it returns of the plan binds the retire.
8789
+ const confirmed = o[RETIRE_UNDER_CLAIM]?.();
8790
+ const bound = confirmed ? { ...o, ...(confirmed.children ? { children: confirmed.children } : {}), ...(confirmed.plannedExtraWorktrees ? { plannedExtraWorktrees: confirmed.plannedExtraWorktrees } : {}) } : o;
8791
+ return retireClaimed(root, name, bound, now);
8792
+ } finally {
8793
+ releaseHomeClaim(held);
8794
+ }
8795
+ }
8796
+ }
8797
+
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. */
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) {
8887
+ const session = o.tmuxSession || DEFAULT_TMUX_SESSION;
8888
+ // self-retire: the caller IS the instance. Without --keep-dir the whole
8889
+ // retirement is deferred to a detached external completion (below); with
8890
+ // --keep-dir the old in-process path runs and kills the window LAST.
8891
+ const self = o.self === true;
8286
8892
  const metaPath = join(found.home, "instance.json");
8287
8893
  // A QUARANTINED home (spawn failed after a required hook and compensation did
8288
8894
  // not finish) has no instance.json — it never got that far. Its marker carries
@@ -8326,28 +8932,46 @@ export function retireInstance(root, name, o = {}) {
8326
8932
  if (isPlainObject(rawMarker?.inProgress)) {
8327
8933
  const p = rawMarker.inProgress;
8328
8934
  const live = processLiveness(p);
8329
- 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");
8330
8936
  if (live.state === "unknown") {
8331
- 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` });
8332
8939
  inProgressUnverified = true;
8333
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`);
8334
8941
  }
8335
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;
8336
8954
  if (quarantine?.inProgress) {
8337
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`;
8338
8959
  const ended = terminateRecordedGroup(p);
8339
- 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.`);
8340
8964
  if (ended === "unverified") spawnGroupWarnings.push(unverifiedGroupWarning(p.hookPgid));
8341
8965
  // A group whose leader's start cannot be read may still be that spawn's hook: never signalled,
8342
8966
  // and refused like an unreadable spawn above, with the same way out.
8343
8967
  if (ended === "unknown") {
8344
8968
  const note = unknownGroupNote(p);
8345
- 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` });
8346
8971
  inProgressUnverified = true;
8347
8972
  spawnGroupWarnings.push(`retired with --force although the worktree ${note}; its branch is kept`);
8348
8973
  }
8349
8974
  }
8350
- const liveMeta = existsSync(metaPath) ? JSON.parse(readFileSync(metaPath, "utf8")) : undefined;
8351
8975
  // A quarantined home may carry an instance.json that is NOT the spawn record:
8352
8976
  // module materialization writes a pre-hook stub ({ modules, providers,
8353
8977
  // resolutionRevision }) before the spawn hooks run, and a required-hook
@@ -8395,6 +9019,8 @@ export function retireInstance(root, name, o = {}) {
8395
9019
  // quarantined home's cleanup descriptor overrides the live record's endpoint: either may name it.
8396
9020
  const herdrHome = recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(found.home))) || recordsHerdr(liveMeta);
8397
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`;
8398
9024
  return scheduleDeferredSelfRetirement(root, found, name, o, session);
8399
9025
  }
8400
9026
  // A worktree directory whose git admin entry is gone cannot be inspected, moved or removed through git, and
@@ -8412,7 +9038,15 @@ export function retireInstance(root, name, o = {}) {
8412
9038
  const recordedBranch = quarantine ? { repo: meta.repo, branch: meta.branch } : undefined;
8413
9039
  // Whether this retire removes the worktree, when it gets to that step.
8414
9040
  const worktreeRemoval = { removes: !!(o.discardWorktree || owesWorktree), repo: meta.repo };
8415
- 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());
8416
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
8417
9051
  // would remove the home refuses here, before the session is stopped and before any retire hook runs (the hooks
8418
9052
  // revoke identities a kept home would still need). The extra-tree step keeps its own check, for a lock that appears
@@ -8458,21 +9092,37 @@ export function retireInstance(root, name, o = {}) {
8458
9092
  // retired, nothing is escalated, and --force does not bypass it. A child whose
8459
9093
  // instance.json is gone by now (a --self snapshot's child retired in between)
8460
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;
8461
9110
  let childrenStopped;
8462
9111
  if (Array.isArray(o.children)) {
8463
- childrenStopped = stopRecordedChildren(o.children.filter((kid) => existsSync(join(kid.home, "instance.json"))));
8464
- const running = childrenStopped.filter((k) => !k.ok);
8465
- 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 } });
8466
9115
  }
8467
9116
  // `=` forces exact matching: tmux targets otherwise PREFIX-match window names.
8468
9117
  // A no-launch instance is already quiesced. A launched one must have exact
8469
9118
  // window absence established before recovery copying begins.
8470
- let sessionStopped = false;
8471
9119
  if (!self && runtimeAuthority?.launched) {
8472
9120
  const runtimeSession = runtimeAuthority.tmux.session;
8473
9121
  const runtimeWindow = runtimeAuthority.tmux.window;
8474
9122
  const runtimeSocket = runtimeAuthority.tmux.socket;
8475
9123
  const tmux = ["-S", runtimeSocket];
9124
+ at.sessionTouched = true;
9125
+ ownSession = "unverified";
8476
9126
  try { execFileSync("tmux", [...tmux, "kill-window", "-t", `=${runtimeSession}:=${runtimeWindow}`], { stdio: ["ignore", "pipe", "pipe"] }); } catch { /* verify the effect below */ }
8477
9127
  try {
8478
9128
  const windows = execFileSync("tmux", [...tmux, "list-windows", "-t", runtimeSession, "-F", "#{window_name}"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).split("\n").filter(Boolean);
@@ -8490,13 +9140,9 @@ export function retireInstance(root, name, o = {}) {
8490
9140
  if (why) throw unestablished(why);
8491
9141
  }
8492
9142
  }
8493
- sessionStopped = true;
9143
+ ownSession = "stopped";
8494
9144
  }
8495
- // What a refusal before the hooks tells the operator about the retire so far.
8496
- const soFar = (kept) => `${name} is not retired and ${kept}; ${sessionStopped ? "its session has been stopped" : "this retire stopped no session"}`;
8497
- // What a refusal after the hooks tells the operator about the retire so far.
8498
- 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"}`;
8499
- 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());
8500
9146
  // The bytes of the worktree as they are before the hooks: after the hooks,
8501
9147
  // "the work did not move" is then proven, never taken from a status text.
8502
9148
  // Read before the recovery is written, so that a worktree that cannot be
@@ -8511,7 +9157,7 @@ export function retireInstance(root, name, o = {}) {
8511
9157
  if (stableObservation.classes.length && stableObservation.workProvable) {
8512
9158
  try { observedWorkBytes(stableObservation); }
8513
9159
  catch (e) {
8514
- 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")}`);
8515
9161
  }
8516
9162
  }
8517
9163
  // One recovery per retirement. The snapshot taken here, before the retire
@@ -8520,11 +9166,12 @@ export function retireInstance(root, name, o = {}) {
8520
9166
  // cannot be made or verified refuses here, with the same disclosure.
8521
9167
  let preHookRecovery;
8522
9168
  if (stableObservation.classes.length) {
9169
+ // Whatever fails here, not only a copy that could not be verified, says the same.
8523
9170
  try { preHookRecovery = writeRetirementRecovery(stableObservation, meta, name, "before-hooks"); }
8524
9171
  catch (e) {
8525
- if (e?.code !== "E_WORK_PRESERVATION_FAILED") throw e;
8526
- 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")}`);
8527
9173
  }
9174
+ at.recoveryPath = preHookRecovery.receipt.path;
8528
9175
  }
8529
9176
  let workRecovery = preHookRecovery?.receipt;
8530
9177
 
@@ -8540,6 +9187,10 @@ export function retireInstance(root, name, o = {}) {
8540
9187
  // The soul this home was spawned from, as recorded (a workspace home records its
8541
9188
  // per-commit directory; agents/<name>/soul may since point elsewhere) — the same
8542
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()}`;
8543
9194
  hookResults = runLifecycleHooks("retire", {
8544
9195
  home: found.home, instance: name, agentName: found.agent.name,
8545
9196
  soulDir: instanceSoulDir(found.home, meta) || found.agent._soulDir || join(found.agent._dir, "soul"),
@@ -8547,6 +9198,8 @@ export function retireInstance(root, name, o = {}) {
8547
9198
  contextDir: meta.repo, workspaceDir: workspaceOf(root), rootDir: root, resolved, priorMeta: meta.capabilityMeta || {},
8548
9199
  });
8549
9200
  }
9201
+ at.phase = "after-hooks";
9202
+ at.said = afterHooks;
8550
9203
 
8551
9204
  // ORDINARY retirement must not delete a home whose cleanup did not finish.
8552
9205
  // The failures were already collected above; until now they were read ONLY on
@@ -8612,16 +9265,16 @@ export function retireInstance(root, name, o = {}) {
8612
9265
  // step and before the home is removed.
8613
9266
  // A refusal here says what has and has not happened, as one before the hooks
8614
9267
  // does: the hooks have run, and what is kept (#659).
8615
- const finalObservation = inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure: afterHooks() });
9268
+ const finalObservation = inspect(afterHooks());
8616
9269
  try {
8617
9270
  if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, meta);
8618
9271
  else if (finalObservation.classes.length) {
8619
9272
  workRecovery = preserveRetirementWork({ ...finalObservation, notCopied: unionNotCopied(stableObservation.notCopied, finalObservation.notCopied) }, meta, name);
8620
9273
  }
8621
9274
  } catch (e) {
8622
- if (!e?.code) throw e;
8623
- throw Object.assign(oatsError(e.code, `${e.message}. ${afterHooks()}.`, e.provenance), e.details ? { details: e.details } : {});
9275
+ throw statedFailure(e, "E_LIFECYCLE_FAILED", `${afterHooks()}.`);
8624
9276
  }
9277
+ if (workRecovery?.path) at.recoveryPath = workRecovery.path;
8625
9278
 
8626
9279
  // Lineage repair: any instance pointing at the retiree (parentInstance from a
8627
9280
  // child/parent relation, siblingInstance from a root-sibling link) would be
@@ -8646,9 +9299,10 @@ export function retireInstance(root, name, o = {}) {
8646
9299
  try { return realpathSync(hit.home) === retireeHome; } catch { return false; }
8647
9300
  };
8648
9301
  const repair = (orphanRoot, instHome) => {
8649
- const p = join(instHome, "instance.json");
8650
- if (!existsSync(p)) return;
8651
- 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;
8652
9306
  if (m.parentInstance !== name && m.siblingInstance !== name) return;
8653
9307
  if (!edgeIsRetiree(orphanRoot, instHome)) return; // same NAME, different instance — leave it
8654
9308
  // Drop every edge to the retiree, then graft the retiree's own links —
@@ -8699,10 +9353,20 @@ export function retireInstance(root, name, o = {}) {
8699
9353
  // (`plannedExtraWorktrees`) binds what is done: trees that no longer read
8700
9354
  // as planned refuse as stale before any of them is touched.
8701
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()}`;
8702
9365
  if (!o.keepDir && !(outstandingBeforeWorktree.length > 0 && !o.force)) {
8703
9366
  const rows = extraWorktreeRows(finalObservation.extraTrees, root);
8704
9367
  if (o.plannedExtraWorktrees && JSON.stringify(rows) !== JSON.stringify(o.plannedExtraWorktrees)) {
8705
- 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.`);
8706
9370
  }
8707
9371
  const refused = rows.filter((r) => r.disposition === "refuse");
8708
9372
  if (refused.length) {
@@ -8742,7 +9406,6 @@ export function retireInstance(root, name, o = {}) {
8742
9406
  const worktreeStep = isWorktree && !!meta.repo && !orphanedWork;
8743
9407
  const worktreeDeferred = worktreeStep && existsSync(workPath) && outstandingBeforeWorktree.length > 0 && !o.force;
8744
9408
  const keptForRetry = worktreeDeferred ? `git worktree ${workPath}: kept for the retry; outstanding: ${outstandingBeforeWorktree.join("; ")}` : null;
8745
- let retention = null;
8746
9409
  // The repository of work/, by its common Git directory (awebai/oats#679), read once from meta.repo: the
8747
9410
  // step's commands and the quarantine's verification below run helper-free against it (gitRepoRun,
8748
9411
  // gitRepoRead), as the extra-tree step's do. A bare repository is named as its Git directory.
@@ -8794,7 +9457,7 @@ export function retireInstance(root, name, o = {}) {
8794
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`");
8795
9458
  } catch (e) {
8796
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(", ")}.` : "";
8797
- 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.`);
8798
9461
  }
8799
9462
  retention = { worktree: "removed", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
8800
9463
  }
@@ -8819,7 +9482,7 @@ export function retireInstance(root, name, o = {}) {
8819
9482
  // receipt `spawned` carries, so the workspace log shows both halves of a
8820
9483
  // capability's lifecycle after the home is gone.
8821
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) })); })();
8822
- 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 });
8823
9486
  // Retrying a quarantine only clears it if compensation ACTUALLY completed.
8824
9487
  // Otherwise the home — and the credentials in it — must survive again, or the
8825
9488
  // retry becomes the deletion the quarantine was preventing.
@@ -8962,7 +9625,22 @@ export function retireInstance(root, name, o = {}) {
8962
9625
  // dead end the unusable-marker fixes closed, just reached from a valid one.
8963
9626
  const forced = !!(stillIncomplete && o.force);
8964
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`;
8965
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`;
8966
9644
  rmSync(directoryFallbackPath, { force: true });
8967
9645
  // The owed retirement is paid: clear the pending marker, and the failed
8968
9646
  // outcome an earlier deferred attempt may have left beside the home; a
@@ -8970,6 +9648,7 @@ export function retireInstance(root, name, o = {}) {
8970
9648
  rmSync(retirePendingMarkerPath(found.home), { force: true });
8971
9649
  rmSync(deferredRetireResultPath(found.home), { force: true });
8972
9650
  rmSync(deferredRetireResultPath(found.home).replace(/\.json$/, ".log"), { force: true });
9651
+ at.lead = null;
8973
9652
  }
8974
9653
 
8975
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: (() => {