@awebai/oats 0.52.0 → 0.54.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 (100) hide show
  1. package/README.md +2 -1
  2. package/bin/oats.mjs +314 -92
  3. package/docs/capabilities.md +66 -4
  4. package/docs/configuration.md +66 -3
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +3 -0
  6. package/docs/desktop-cli-api.md +696 -60
  7. package/docs/desktop-instance-start.md +25 -12
  8. package/docs/execution-targets.md +1 -0
  9. package/docs/implementation.md +184 -12
  10. package/docs/integrations.md +6 -3
  11. package/docs/knowledge.md +2 -2
  12. package/docs/macos-test-runs.md +246 -0
  13. package/docs/official-catalog.md +5 -5
  14. package/docs/packages.md +14 -14
  15. package/docs/release-lane.md +210 -6
  16. package/docs/release-notes/v0.53.0.md +1288 -0
  17. package/docs/release-notes/v0.54.0.md +142 -0
  18. package/docs/schedules.md +7 -1
  19. package/docs/souls-and-instances.md +239 -16
  20. package/docs/tui.md +453 -21
  21. package/docs/upgrading.md +310 -0
  22. package/docs/workspaces.md +123 -3
  23. package/lib/automations.mjs +22 -22
  24. package/lib/claim.mjs +93 -4
  25. package/lib/config-data.mjs +4 -1
  26. package/lib/core.mjs +569 -121
  27. package/lib/instance-events.mjs +19 -1
  28. package/lib/instance-git.mjs +39 -3
  29. package/lib/instance-inspect.mjs +5 -6
  30. package/lib/instance-lifecycle.mjs +145 -18
  31. package/lib/instance-resolution.mjs +59 -6
  32. package/lib/launch-preference.mjs +226 -15
  33. package/lib/local-edit.mjs +118 -0
  34. package/lib/packages.mjs +18 -5
  35. package/lib/pi-bridge.mjs +308 -0
  36. package/lib/refused-text.mjs +11 -0
  37. package/lib/remote.mjs +404 -60
  38. package/lib/resolve.mjs +2 -1
  39. package/lib/retained-after-retire.mjs +2 -2
  40. package/lib/retire-output.mjs +12 -1
  41. package/lib/schedule-host.mjs +6 -35
  42. package/lib/shell-word.mjs +13 -0
  43. package/lib/soul-launch-verbs.mjs +153 -0
  44. package/lib/stable-node.mjs +62 -0
  45. package/lib/teams-verbs.mjs +18 -46
  46. package/lib/workspace.mjs +75 -27
  47. package/package-catalog.json +4 -4
  48. package/package.json +2 -1
  49. package/packages/client/attach-exit.mjs +25 -0
  50. package/packages/client/cli-adapter.mjs +16 -3
  51. package/packages/client/cli-locator.mjs +2 -2
  52. package/packages/client/deployment-contract.mjs +4 -0
  53. package/packages/client/deployment-facts.mjs +71 -10
  54. package/packages/client/deployment-panel.mjs +49 -11
  55. package/packages/client/deployment-read-cli.mjs +7 -3
  56. package/packages/client/display-text.mjs +8 -2
  57. package/packages/client/instance-acts.mjs +46 -10
  58. package/packages/client/instance-events-contract.mjs +4 -2
  59. package/packages/client/instance-presentation.mjs +66 -2
  60. package/packages/client/instance-tree.mjs +23 -14
  61. package/packages/client/kernel-lines.mjs +31 -0
  62. package/packages/client/kernel-made.mjs +23 -0
  63. package/packages/client/launch-prompt-outcome.mjs +51 -16
  64. package/packages/client/lifecycle-contract.mjs +45 -4
  65. package/packages/client/liveness.mjs +14 -1
  66. package/packages/client/own-codes.mjs +31 -0
  67. package/packages/client/panel-views.mjs +18 -11
  68. package/packages/client/readiness-contract.mjs +3 -1
  69. package/packages/client/remote-address.mjs +34 -9
  70. package/packages/client/remote-identity-memory.mjs +94 -0
  71. package/packages/client/remote-roster.mjs +92 -6
  72. package/packages/client/session-attach.mjs +175 -0
  73. package/packages/client/spawn-apply-contract.mjs +16 -4
  74. package/packages/client/spawn-messages.mjs +26 -3
  75. package/packages/client/spawn-preview-cli.mjs +8 -2
  76. package/packages/client/spawn-preview-contract.mjs +5 -1
  77. package/packages/client/terminal-exec.mjs +21 -0
  78. package/packages/client/workspace-choices.mjs +95 -0
  79. package/packages/client/workspace-views.mjs +39 -3
  80. package/packages/record/README.md +21 -0
  81. package/packages/record/bin/setup.mjs +108 -15
  82. package/packages/tui/README.md +30 -12
  83. package/packages/tui/lib/actions.mjs +16 -1
  84. package/packages/tui/lib/client.mjs +32 -1
  85. package/packages/tui/lib/config.mjs +151 -0
  86. package/packages/tui/lib/main.mjs +117 -46
  87. package/packages/tui/lib/model.mjs +392 -0
  88. package/packages/tui/lib/read.mjs +473 -0
  89. package/packages/tui/lib/store.mjs +364 -0
  90. package/packages/tui/lib/term/keys.mjs +44 -0
  91. package/packages/tui/lib/term/screen.mjs +16 -4
  92. package/packages/tui/lib/term/text.mjs +60 -0
  93. package/packages/tui/lib/term/tty.mjs +13 -3
  94. package/packages/tui/lib/views/detail.mjs +46 -0
  95. package/packages/tui/lib/views/frame.mjs +230 -36
  96. package/packages/tui/lib/views/help.mjs +125 -13
  97. package/packages/tui/lib/views/instances.mjs +137 -0
  98. package/packages/tui/lib/views/scroll.mjs +19 -0
  99. package/packages/tui/lib/views/switcher.mjs +97 -0
  100. package/skills/oats-getting-started/SKILL.md +8 -2
package/lib/core.mjs CHANGED
@@ -46,15 +46,17 @@ import { initializeNativeHistory, prepareNativeStart } from "../packages/record/
46
46
  import { noteRuntimeName } from "./deprecation.mjs";
47
47
  import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
48
48
  import { inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
49
- import { appendEvent, liveWaiting, recordStartBoundary } from "./instance-events.mjs";
49
+ import { appendEvent, incarnationOf, liveWaiting, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
50
50
  import { killGroup } from "./process-group.mjs";
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";
51
+ import { interruptExitStatus, isStartToken, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
52
+ import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite, readClaim, releaseClaim, removeGoneClaim, shownHolder, unwritableCode } from "./claim.mjs";
53
53
  import { captureLoginEnvironment } from "./login-environment.mjs";
54
+ import { kernelNode } from "./stable-node.mjs";
54
55
 
55
56
  import { oatsError, afterEndedSteps, afterFirstEffect, asKernelError, BEFORE_EFFECT_CODES, checkHolderByHand, errorCause, ifItDoesNotEnd, isAnswerCode, isKernelCode, kernelCode, lifecycleBusy, nothingAfter, reportDefect, OWN_NAME_FAILURES, OWN_START_REMEDY, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
56
57
  import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
57
- import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchLayers, launchReport, selectionFrom } from "./launch-preference.mjs";
58
+ import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchConfigUnknownFix, launchLayers, launchPreferenceUnmatched, launchPreferenceUnmatchedProblem, launchReport, selectionFrom } from "./launch-preference.mjs";
59
+ import { shq, shellWord } from "./shell-word.mjs";
58
60
  import { claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigDir } from "./harness-trust.mjs";
59
61
  async function materializePreparedDefault(prepared, home) { const m = await import("./instance-resolution.mjs"); return m.materializePrepared(prepared, home); }
60
62
  // Capability rows for a PREPARED spawn (workspace model): the one function that
@@ -79,7 +81,7 @@ export { exactTreeDigest, fingerprintTree, KERNEL_HOME_RECEIPTS, storedTreeDiges
79
81
  import { canonicalJson, lineAt, parseStrictJson } from "./canonical-json.mjs";
80
82
  import { readPortableBytes } from "./bounded-read.mjs";
81
83
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes } from "./tree-copy.mjs";
82
- import { assertSameWorktreeHead, gitRead, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
84
+ import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
83
85
  import { systemTool } from "./system-tools.mjs";
84
86
  import { creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
85
87
  /** The package and capability id grammar (namespaced, lowercase): an id names a
@@ -229,12 +231,9 @@ function shIn(cwd, cmdline, timeout = 45000) {
229
231
  return execSync(cmdline, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout }).trim();
230
232
  }
231
233
  function shInTry(cwd, cmdline, timeout) { try { return shIn(cwd, cmdline, timeout); } catch { return undefined; } }
232
- export function shq(s) { return `'${String(s).replace(/'/g, `'\\''`)}'`; }
233
- /** One word of a command line that a person or an agent pastes into a shell: as it is when it holds
234
- * only letters, digits and `_./:-`, single-quoted otherwise (an empty string too). The safe set is
235
- * deliberately small: no `~` (an unquoted leading one expands), no `=` (zsh expands a leading
236
- * `=word`). */
237
- export function shellWord(s) { const word = String(s); return /^[A-Za-z0-9_.\/:-]+$/.test(word) ? word : shq(word); }
234
+ // The shell quoting of a printed command lives in lib/shell-word.mjs, which imports nothing, so that
235
+ // lib/launch-preference.mjs (imported here) quotes by the same rule.
236
+ export { shq, shellWord };
238
237
  export function slug(s) {
239
238
  const r = String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
240
239
  return r || "agent";
@@ -585,7 +584,7 @@ const LAUNCH_CONFIG_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
585
584
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
586
585
  /** Environment the kernel sets for every launch (identity, home, roots) and
587
586
  * its reference aliases: a configuration may not name them. */
588
- export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "OATS_AGENT", "OATS_SOUL", "OATS_SOUL_ID", "OATS_ROOT", "OATS_CONTEXT", "OATS_WORKSPACE", "OATS_EVENT", "OATS_SETTINGS", "OATS_SETTINGS_ORIGINS", "OATS_CLI_BIN", "PI_AGENT_INSTANCE", "PI_AGENT_HOME", "PI_AGENTS_ROOT",
587
+ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "OATS_AGENT", "OATS_SOUL", "OATS_SOUL_ID", "OATS_ROOT", "OATS_CONTEXT", "OATS_WORKSPACE", "OATS_EVENT", "OATS_SETTINGS", "OATS_SETTINGS_ORIGINS", "OATS_CLI_BIN", "OATS_NODE_BIN", "PI_AGENT_INSTANCE", "PI_AGENT_HOME", "PI_AGENTS_ROOT",
589
588
  // The test seam that replaces the login shell (lib/login-environment.mjs): never a launch's to set.
590
589
  "OATS_TEST_LOGIN_SHELL",
591
590
  // The test seams of #796, the same: a worktree hook's fixed timeout, the fetch timeout of
@@ -1710,6 +1709,8 @@ export function lifecycleHookEnv(event, cap, { home, instance, agentName, soulDi
1710
1709
  // Author this from the running kernel, never PATH, ambient env or
1711
1710
  // a caller's extraEnv: those may point at a different executable.
1712
1711
  OATS_CLI_BIN: kernelBin(),
1712
+ // The node a capability writes into anything that outlives its hook (lib/stable-node.mjs).
1713
+ OATS_NODE_BIN: kernelNode().node,
1713
1714
  OATS_SETTINGS: JSON.stringify(cap.settings || {}),
1714
1715
  // Where each leaf of OATS_SETTINGS came from (JSON pointer → { kind, at }; kind is
1715
1716
  // manifest-default | workspace | soul | host | spawn | anchor), so a provider can tell a
@@ -2916,8 +2917,13 @@ export function harnessDefaultConfig(launchConfigs, harness) {
2916
2917
  return found ? { ...found, harnessDefault: true } : null;
2917
2918
  }
2918
2919
  /** A home's launch layers now (feature launch-preference; --reselect-launch and inspect's launchCurrent): its
2919
- * RECORDED soul's launch (the soul copy it runs) and its deployment's oats-local.yaml souls.launch. */
2920
- export function homeLaunchLayers(realHome, meta) {
2920
+ * RECORDED soul's launch (the soul copy it runs) and its deployment's oats-local.yaml souls.launch.
2921
+ * `offered` is the description of a read of the workspace (lib/instance-resolution.mjs soulsOffered),
2922
+ * which the layers need to say which keys of souls.launch name no soul: only when the home's soul has
2923
+ * no entry of its own and souls.launch holds a key besides "*" (`needsOffered` on the answer says so
2924
+ * when none was given). A start that selects again makes that read (startInstanceSession); inspect's
2925
+ * launchCurrent and readiness make none, and report the layers as they are. */
2926
+ export function homeLaunchLayers(realHome, meta, { offered = null } = {}) {
2921
2927
  const deployment = dirname(dirname(dirname(dirname(realHome))));
2922
2928
  const found = loadLocal(deployment);
2923
2929
  if (!found.path || resolve(dirname(found.path)) !== resolve(deployment)) throw oatsError("E_LOCAL_MISSING", `${deployment} has no oats-local.yaml: --reselect-launch reads its souls.launch`);
@@ -2926,15 +2932,21 @@ export function homeLaunchLayers(realHome, meta) {
2926
2932
  const file = soulDir ? join(soulDir, "soul.yaml") : null;
2927
2933
  const definition = file && existsSync(file) ? withConfigFile(file, () => parseYamlNested(readFileSync(file, "utf8"))) : null;
2928
2934
  const key = soul.package && typeof soul.qualifiedName === "string" ? soul.qualifiedName : meta.agent;
2929
- return launchLayers({ definition, entry: { repoKey: soul.repoKey ?? null, path: typeof soul.path === "string" ? soul.path : null, package: soul.package?.id ?? null }, key, local: found.local });
2935
+ const entries = isPlainObject(found.local?.souls?.launch) ? found.local.souls.launch : {};
2936
+ const needsOffered = !offered && !Object.hasOwn(entries, key) && Object.keys(entries).some((k) => k !== "*");
2937
+ return { ...launchLayers({ definition, entry: { repoKey: soul.repoKey ?? null, path: typeof soul.path === "string" ? soul.path : null, package: soul.package?.id ?? null }, key, local: found.local, offered }), needsOffered };
2930
2938
  }
2931
2939
  /** A NEW launch selection (a spawn, or a start/restart that reselects) from the flags and the launch
2932
2940
  * layers (lib/launch-preference.mjs). → { launchSelection (resolveLaunchSelection's), launchChoice:
2933
- * { from, at, declared } }. A configuration a layer names but the host lacks is E_LAUNCH_CONFIG_UNKNOWN
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. */
2941
+ * { from, at, declared } }. A selection the fall-through would decide while souls.launch holds a key that
2942
+ * names no soul is E_LAUNCH_PREFERENCE_UNMATCHED, before every other refusal here (for every new
2943
+ * selection: a spawn, and a start that reselects). A configuration a layer names but the host lacks is
2944
+ * E_LAUNCH_CONFIG_UNKNOWN naming the layer. `refuseAmbiguous` (a spawn) refuses a launch that names no
2945
+ * configuration among several with no default (E_LAUNCH_CONFIG_AMBIGUOUS). Never reads a frozen recipe. */
2936
2946
  export function selectNewLaunch({ launchConfigs = {}, agent, flags = {}, layers = null, refuseAmbiguous = false }) {
2937
2947
  const choice = selectionFrom({ flags, layers });
2948
+ const unmatched = launchPreferenceUnmatched({ choice, layers });
2949
+ if (unmatched) throw unmatched;
2938
2950
  const named = choice.from !== "flag" && choice.selection.launchConfig !== undefined && choice.selection.launchConfig !== "none" ? choice.selection.launchConfig : null;
2939
2951
  if (named !== null && !Object.hasOwn(launchConfigs, named)) throw launchConfigUnknown({ name: named, from: choice.from, at: choice.at });
2940
2952
  const launchSelection = resolveLaunchSelection({ launchConfigs, agent: layers ? {} : agent, selection: choice.selection, preference: choice.preference });
@@ -2945,16 +2957,20 @@ export function selectNewLaunch({ launchConfigs = {}, agent, flags = {}, layers
2945
2957
  /** The `Launch` report (feature launch-preference) a spawn with no flags would decide HERE, for listings
2946
2958
  * (`oats souls`, `inspect --soul`): the same layers as selectNewLaunch, but no model catalogue is probed
2947
2959
  * (`model` is the configured id) and a spawn's refusal becomes `problem` {code, message, fix}. `contextDir`
2948
- * is the deployment (where a harness executable resolves). */
2960
+ * is the deployment (where a harness executable resolves). A key of souls.launch that names no soul
2961
+ * (E_LAUNCH_PREFERENCE_UNMATCHED) is the problem before any other, as in a spawn; `effective` stays the
2962
+ * launch the fall-through would have given. */
2949
2963
  export function launchReportFor({ layers, launchConfigs = {}, contextDir }) {
2950
2964
  const choice = selectionFrom({ layers });
2951
- const report = (harness, model, launchConfig, problem = null) => launchReport({ declared: layers?.declared ?? null, harness, model, launchConfig, from: choice.from, at: choice.at, problem });
2965
+ const unmatched = launchPreferenceUnmatchedProblem({ choice, layers });
2966
+ const report = (harness, model, launchConfig, problem = null) => launchReport({ declared: layers?.declared ?? null, harness, model, launchConfig, from: choice.from, at: choice.at,
2967
+ problem: unmatched ?? problem });
2952
2968
  let harness = "pi", model = null, config = null;
2953
2969
  if (choice.selection.launchConfig !== undefined && choice.selection.launchConfig !== "none") {
2954
2970
  // An unknown configuration launches nothing (`problem`); `effective` stays a real launch — the host
2955
2971
  // default — so a reader's closed decoder never meets a null harness.
2956
2972
  const name = choice.selection.launchConfig;
2957
- if (!Object.hasOwn(launchConfigs, name)) { const e = launchConfigUnknown({ name, from: choice.from, at: choice.at }); return report("pi", null, null, { code: e.code, message: e.message, fix: `declare launch configuration ${name} (oats launch-config set), or change oats-local.yaml souls.launch` }); }
2973
+ if (!Object.hasOwn(launchConfigs, name)) { const e = launchConfigUnknown({ name, from: choice.from, at: choice.at }); return report("pi", null, null, { code: e.code, message: e.message, fix: launchConfigUnknownFix(name, choice.from) }); }
2958
2974
  config = launchConfigs[name]; harness = config.harness; model = typeof config.model === "string" && config.model ? config.model : null;
2959
2975
  } else if (choice.preference) { harness = choice.preference.harness; model = choice.preference.model ?? null; }
2960
2976
  // As a spawn: a layer naming "none" asks for the bare harness; otherwise no configuration is the harness default.
@@ -4214,6 +4230,7 @@ function* spawnBody(root, agent, o = {}) {
4214
4230
  extraEnv: { OATS_TASK: task, OATS_REPO: repoAbs, OATS_BRANCH: branch || "", OATS_WORK: work, OATS_HARNESS: harness, OATS_RUNTIME: harness, OATS_KIND: agent.kind || "persistent", ...(triggerEventFile ? { OATS_TRIGGER_EVENT_FILE: triggerEventFile } : {}) },
4215
4231
  });
4216
4232
  warnings.push(...hookRes.warnings);
4233
+ if (kernelNode().warning) warnings.push(kernelNode().warning);
4217
4234
  // Which capability hooks RAN (in order) and how each ended — recorded on the
4218
4235
  // `spawned` event below: the instance's event log is the auditable fact that
4219
4236
  // a capability configured itself, independent of whatever the hook printed.
@@ -5038,6 +5055,40 @@ function assertDirectoryHome(home, canonicalHome = realPathOrNearest(home)) {
5038
5055
  }
5039
5056
  }
5040
5057
 
5058
+ /** A directory of the home (instanceWork) is still the real directory the retire read it as: a
5059
+ * retire hook, or anything else, may have exchanged it since. */
5060
+ function assertHomeDirectory(work) {
5061
+ let st;
5062
+ try { st = lstatSync(work); } catch { /* fail closed below */ }
5063
+ if (!st?.isDirectory() || st.isSymbolicLink()) {
5064
+ throw oatsError("E_WORK_INSPECTION_FAILED", `${work} was a real directory when this retire first read it and is not one now (it is missing, a link or another filesystem type), so what the retire would copy is not what it read; restore it, or remove what is there, before retrying`);
5065
+ }
5066
+ }
5067
+
5068
+ /** A link at work/ (instanceWork) is still a link, or gone: a retire hook, or anything else, may
5069
+ * have put a directory or a file there since. The home's copy leaves `work/` out and the home's
5070
+ * removal takes whatever is there, so what replaced the link would be removed uncopied (#973).
5071
+ * The refusal says what was there and what is there now, and how it ends, by what is there now.
5072
+ * A directory: the next retire reads the home as it is now, and the plan shows what it would do.
5073
+ * It promises no copy: that depends on the record as it is then and on the spawn's receipt (a
5074
+ * directory of the home is copied and removed with it; an own tree's directory has no admin entry
5075
+ * and is kept after the hooks ran, until a person moves it: #1019). A file, or an entry that is
5076
+ * none of the three: no retire removes it (under a record that says `worktree` it is kept after
5077
+ * the hooks ran, under another record the inspection refuses) and the plan does not say so, so
5078
+ * the refusal names the step and not the plan. An entry that cannot be read: nothing is known of
5079
+ * it but that the next retire reads it again. */
5080
+ function assertStillLink(work, instance) {
5081
+ let st;
5082
+ try { st = lstatSync(work); } catch (e) { if (e?.code === "ENOENT") return; /* else fail closed below */ }
5083
+ if (!st?.isSymbolicLink()) {
5084
+ const now = !st ? "an entry that cannot be read" : st.isDirectory() ? "a directory" : st.isFile() ? "a file" : "an entry that is neither a link, a directory nor a file";
5085
+ const next = !st ? "The retire reads it again when it is run again"
5086
+ : st.isDirectory() ? `\`oats retire ${instance} --plan\` shows what a retire would do with what is there now, and running the retire again does that`
5087
+ : "No retire removes it: move it out of the home or remove it, then run the retire again";
5088
+ throw oatsError("E_WORK_INSPECTION_FAILED", `${work} was a link when this retire first read the home, and ${now} is there now. The home is kept and nothing of it was removed. ${next}`);
5089
+ }
5090
+ }
5091
+
5041
5092
  function assertDirectoryRoots(home, canonicalHome) {
5042
5093
  assertDirectoryHome(home, canonicalHome);
5043
5094
  const work = join(home, "work");
@@ -5821,29 +5872,97 @@ function extraWorktreesOf(home) {
5821
5872
  try { names = readdirSync(home); } catch { return trees; }
5822
5873
  // Git reports paths in their on-disk spelling: the home and each tree are compared in it too.
5823
5874
  const realHome = canonicalHomePath(home);
5824
- const inHome = (p) => { const rel = relative(realHome, canonicalHomePath(p)); return rel === "" || !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)); };
5825
5875
  for (const name of names.sort(byCodeUnit)) {
5826
5876
  if (!name.startsWith(".work-")) continue;
5827
5877
  const path = join(home, name);
5828
- try {
5829
- if (!lstatSync(path).isDirectory() || !lstatSync(join(path, ".git")).isFile()) continue;
5830
- } catch { continue; }
5831
- const dirs = gitRead(path, ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir", "--show-toplevel"]);
5832
- if (!dirs.ok) continue;
5833
- const [gitDir, commonDir, toplevel] = dirs.out.split("\n");
5834
- if (!gitDir || !commonDir || !toplevel || realPathOrNearest(gitDir) === realPathOrNearest(commonDir)) continue;
5835
- const real = canonicalHomePath(path);
5836
- // A repository inside the home goes with the home: its trees are home bytes.
5837
- if (canonicalHomePath(toplevel) !== real || inHome(commonDir)) continue;
5838
- const list = gitRead(path, ["worktree", "list", "--porcelain", "-z"]);
5839
- if (!list.ok) continue;
5840
- const records = parseWorktreeList(list.out);
5841
- const self = records.find((r) => canonicalHomePath(r.worktree) === real);
5842
- if (!records.length || !self) continue;
5843
- trees.push({ name, path, repo: records[0].worktree, gitDir, commonDir: realPathOrNearest(commonDir), locked: self.locked });
5878
+ const tree = registeredLinkedWorktree(path, realHome);
5879
+ if (tree) trees.push({ name, path, ...tree });
5844
5880
  }
5845
5881
  return trees;
5846
5882
  }
5883
+ /** The kernel's test of a tree of a home, for `path` in the home whose
5884
+ * canonical spelling is `realHome`: a real directory (not a symlink) whose
5885
+ * `.git` is a regular file, and that Git confirms is a registered linked
5886
+ * worktree of a repository outside the home (extraWorktreesOf says how).
5887
+ * The one test of an extra tree and of `work/` (instanceWork). Read-only
5888
+ * probes (gitRead). → { repo, gitDir, commonDir, locked }, or undefined. */
5889
+ function registeredLinkedWorktree(path, realHome) {
5890
+ const inHome = (p) => { const rel = relative(realHome, canonicalHomePath(p)); return rel === "" || !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)); };
5891
+ try {
5892
+ if (!lstatSync(path).isDirectory() || !lstatSync(join(path, ".git")).isFile()) return undefined;
5893
+ } catch { return undefined; }
5894
+ const dirs = gitRead(path, ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir", "--show-toplevel"]);
5895
+ if (!dirs.ok) return undefined;
5896
+ const [gitDir, commonDir, toplevel] = dirs.out.split("\n");
5897
+ if (!gitDir || !commonDir || !toplevel || realPathOrNearest(gitDir) === realPathOrNearest(commonDir)) return undefined;
5898
+ const real = canonicalHomePath(path);
5899
+ // A repository inside the home goes with the home: its trees are home bytes.
5900
+ if (canonicalHomePath(toplevel) !== real || inHome(commonDir)) return undefined;
5901
+ const list = gitRead(path, ["worktree", "list", "--porcelain", "-z"]);
5902
+ if (!list.ok) return undefined;
5903
+ const records = parseWorktreeList(list.out);
5904
+ const self = records.find((r) => canonicalHomePath(r.worktree) === real);
5905
+ if (!records.length || !self) return undefined;
5906
+ return { repo: records[0].worktree, gitDir, commonDir: realPathOrNearest(commonDir), locked: self.locked };
5907
+ }
5908
+ /** What is at `<home>/work` (awebai/oats#962): the one answer the retire
5909
+ * (retireInstance) and its plan (planRetire) both read. `record` is the
5910
+ * home's record as the caller read it. → { path, at, is, tree }.
5911
+ *
5912
+ * `at` is the entry: "link", "directory" (a real one), "other" (any other
5913
+ * kind of entry) or "none". `is` is what it is to the instance:
5914
+ *
5915
+ * - "directory-mode": the record says `directory`. Whatever is there, the
5916
+ * retire holds it against the spawn's receipt (inspectRetirementWork).
5917
+ * - "own-tree": the instance's own work tree. The retire re-homes it, or
5918
+ * removes it through Git when told to.
5919
+ * - "home-directory": a real directory that is not that. It is bytes of the
5920
+ * home that the home's copy leaves out: the retire copies it to recovery,
5921
+ * checks the copy against what it inspected, and removes it with the
5922
+ * home. Never a Git removal, and never left out of the copy.
5923
+ * - "link": a symbolic link, whatever the record says (awebai/oats#973). A
5924
+ * link is never the instance's own tree: it goes with the home, and no
5925
+ * step reads what it leads to as a tree to copy, move or remove. Neither
5926
+ * the receipt nor Git is read for it.
5927
+ * - "none", "other": the entry, for a record that does not say `worktree`.
5928
+ * The retire reads an "other" entry (a file, say) as a worktree, and its
5929
+ * inspection refuses it. Under a record that says `worktree` such an
5930
+ * entry is the own tree, as nothing at `work/` is (below): the retire
5931
+ * then finds a work directory whose Git admin entry is missing, runs its
5932
+ * hooks, and keeps the entry and the home as an incomplete item.
5933
+ *
5934
+ * A real directory is the instance's own tree when the spawn's receipt (a
5935
+ * valid retirement baseline) holds what only a `worktree` spawn writes
5936
+ * (`generatedWorkFingerprint`). A valid receipt without it says the
5937
+ * instance was given no tree, whatever the record says now: the record is
5938
+ * the instance's to write, the receipt is not. With no valid receipt the
5939
+ * record decides: `worktree` is the own tree; `attached`, `checkout` and
5940
+ * `workspace` were given a link, so a directory there is the home's; and a
5941
+ * record with no work mode, or one this kernel does not know, has the own
5942
+ * tree exactly when Git confirms that the directory is a registered linked
5943
+ * worktree (`tree`, registeredLinkedWorktree).
5944
+ *
5945
+ * Nothing at `work/`, or an entry that is neither a link nor a directory, is
5946
+ * what the record says, as before this function: a `worktree` record's own
5947
+ * tree, else the entry. `tree` is set for a real directory Git confirms, in
5948
+ * either answer: the repository of an own tree whose record names none, and
5949
+ * what a directory of the home leaves registered in its repository. */
5950
+ export function instanceWork(home, record) {
5951
+ const path = join(home, "work");
5952
+ const mode = record?.work;
5953
+ let st;
5954
+ try { st = lstatSync(path); } catch { /* nothing that can be read is there */ }
5955
+ const at = !st ? "none" : st.isSymbolicLink() ? "link" : st.isDirectory() ? "directory" : "other";
5956
+ if (mode === "directory") return { path, at, is: "directory-mode", tree: undefined };
5957
+ // The record is the instance's to write; what a link leads to is not the instance's (#973).
5958
+ if (at === "link") return { path, at, is: "link", tree: undefined };
5959
+ if (at !== "directory") return { path, at, is: mode === "worktree" ? "own-tree" : at, tree: undefined };
5960
+ const baseline = readJsonOrUndefined(findRetirementBaseline(home));
5961
+ const tree = registeredLinkedWorktree(path, canonicalHomePath(home));
5962
+ const own = retirementBaselineValid(baseline, home) ? typeof baseline.generatedWorkFingerprint === "string"
5963
+ : mode === "worktree" || (!WORK_MODES.includes(mode) && !!tree);
5964
+ return { path, at, is: own ? "own-tree" : "home-directory", tree };
5965
+ }
5847
5966
  /** Where retire re-homes the worktrees it retains, one directory per repository under it. */
5848
5967
  export function retainedWorktreesRoot(workspace) {
5849
5968
  return join(workspace, ".agents", "worktrees");
@@ -5902,7 +6021,7 @@ function extraWorktreeRows(trees, root) {
5902
6021
  const status = gitRead(tree.path, ["status", "--porcelain", "-z", "--ignored", "--untracked-files=all", "--ignore-submodules=none"]);
5903
6022
  if (!status.ok) why.push(`its status could not be read (${status.err})`);
5904
6023
  else if (status.out.length) why.push("it holds uncommitted, untracked or ignored files");
5905
- if (RECOVERABLE_GIT_ADMIN.some((n) => existsSync(join(tree.gitDir, n)))) why.push("an operation is in progress in it");
6024
+ if (gitOperationInProgress(tree.gitDir, tree.path)) why.push("an operation is in progress in it");
5906
6025
  if (commit) {
5907
6026
  const reach = gitRepoRead(tree.commonDir, ["for-each-ref", "--contains", commit, "--count=1", "--format=%(objectname)"]);
5908
6027
  if (!reach.ok) why.push(`which refs reach its HEAD commit could not be read (${reach.err})`);
@@ -6504,10 +6623,19 @@ function tmuxOn(socket, args, io, env) {
6504
6623
  return (io?.exec || execFileSync)(tmux, ["-u", "-S", socket, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...(env ? { env } : {}) });
6505
6624
  }
6506
6625
 
6626
+ /** Write `value` as JSON at `path` through a private file beside it, renamed over it. When the
6627
+ * write or the rename fails the private file is removed and the error thrown is that failure's:
6628
+ * a file system with no space makes the file and has no block for its bytes, and nothing else
6629
+ * would remove it (awebai/oats#963). The removal's own failure is not answered. */
6507
6630
  function writeJsonAtomic(path, value, mode) {
6508
6631
  const tmp = `${path}.tmp-${process.pid}`;
6509
- writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", mode !== undefined ? { mode } : undefined);
6510
- renameSync(tmp, path);
6632
+ try {
6633
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", mode !== undefined ? { mode } : undefined);
6634
+ renameSync(tmp, path);
6635
+ } catch (e) {
6636
+ try { rmSync(tmp, { force: true }); } catch { /* the first error is the one answered */ }
6637
+ throw e;
6638
+ }
6511
6639
  }
6512
6640
 
6513
6641
  // ---------- stopping a harness, selecting on an existing home ----------
@@ -6927,7 +7055,11 @@ export function startInstanceSession(home, o = {}) {
6927
7055
  // preflight happens here, before anything is observed or stopped.
6928
7056
  // --reselect-launch (feature launch-preference): apply the home's launch layers now (souls.launch,
6929
7057
  // the recorded soul's launch, the host default) instead of the frozen recipe.
6930
- const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta) : null;
7058
+ // `launchOffered`: the caller's read of the workspace's souls (homeSoulsOffered), which the layers need
7059
+ // to tell a key of souls.launch that names no soul. A selection the layers would decide never goes on
7060
+ // without it: a key that was not checked must not let the launch fall through.
7061
+ const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
7062
+ if (reselect?.needsOffered && o.launchConfig === undefined && o.harness === undefined) throw oatsError("E_BAD_ARGS", `--reselect-launch of ${meta.instance || realHome} needs a read of the workspace's souls: oats-local.yaml souls.launch holds a key besides "*" and this home's soul has no entry of its own (the caller passes that read as launchOffered: lib/instance-resolution.mjs homeSoulsOffered)`);
6931
7063
  // The session this start opens its window in when it has to create one, and what its creation
6932
7064
  // needs (planOatsTmuxSession), read at most once: by the plan's lookup or by the creation's preflight.
6933
7065
  const planSession = receipt.target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
@@ -7074,6 +7206,7 @@ export function startInstanceSession(home, o = {}) {
7074
7206
  ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
7075
7207
  ...(hookMeta ? { hookMeta } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
7076
7208
  warnings.push(...launchStartNotices(dirname(dirname(dirname(dirname(home)))), launchPlan?.harness || harness, command));
7209
+ if (kernelNode().warning) warnings.push(kernelNode().warning);
7077
7210
  const engaged = devChannelEngaged(launchPlan?.harness || harness, command);
7078
7211
  let stopReceipt = null;
7079
7212
  if (state.present && state.state !== "shell") {
@@ -7523,8 +7656,14 @@ function assertWorktreeTopLevel(work, disclosure) {
7523
7656
  }
7524
7657
  }
7525
7658
 
7526
- function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktreeRemoval, directory = false, orphanedWork = false, disclosure } = {}) {
7527
- if (directory) assertDirectoryRoots(home);
7659
+ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktreeRemoval, directory = false, directoryMode = directory, link = false, instance, orphanedWork = false, disclosure } = {}) {
7660
+ // `directory`: work/ is read, copied and checked as a directory's bytes. `directoryMode`: the
7661
+ // record says `directory`. They differ for a directory of the home (instanceWork, #962), which
7662
+ // is copied the same way and is no directory instance: it has no receipt of its roots.
7663
+ if (directoryMode) assertDirectoryRoots(home);
7664
+ else if (directory) assertHomeDirectory(work);
7665
+ // `link`: work/ was read as a link, which goes with the home. Nothing of what it leads to is read.
7666
+ else if (link) assertStillLink(work, instance);
7528
7667
  const classes = [];
7529
7668
  let baseline;
7530
7669
  const path = findRetirementBaseline(home);
@@ -7556,7 +7695,10 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
7556
7695
  }
7557
7696
  // A mutable mode must not turn owned directory bytes into an excluded shared
7558
7697
  // tree (or authorize Git deletion). Require the independent spawn authority.
7559
- if (directory !== (baselineValid && baseline.directoryWork === true)) {
7698
+ // It is the record's mode that is held against the receipt, as before #962:
7699
+ // a directory of the home passes it as any home that is not in directory
7700
+ // mode does, and what it then gets is a checked copy, never either of those.
7701
+ if (directoryMode !== (baselineValid && baseline.directoryWork === true)) {
7560
7702
  throw oatsError("E_WORK_INSPECTION_FAILED", "directory work mode disagrees with independent retirement authority");
7561
7703
  }
7562
7704
  let directoryFingerprint;
@@ -7566,8 +7708,9 @@ function inspectRetirementWork(home, work, isWorktree, { recordedBranch, worktre
7566
7708
  if (readdirSync(work).length) classes.push("directory work bytes");
7567
7709
  }
7568
7710
  // For a quarantine retry whose worktree is gone, whether the recorded branch
7569
- // is still there to copy. Every other retire takes it to be there.
7570
- const branchExists = !directory && recordedBranch && !existsSync(work) ? recordedBranchExists(recordedBranch.repo, recordedBranch.branch) : true;
7711
+ // is still there to copy. Every other retire takes it to be there. Not asked
7712
+ // for a link that leads nowhere: nothing is copied through a link (#973).
7713
+ const branchExists = !directory && !link && recordedBranch && !existsSync(work) ? recordedBranchExists(recordedBranch.repo, recordedBranch.branch) : true;
7571
7714
  // Before anything of the worktree is read: its status describes it, not another directory.
7572
7715
  if (!directory && isWorktree && existsSync(work)) assertWorktreeTopLevel(work, disclosure);
7573
7716
  // A retire that will remove the worktree asks whether a ref that outlives it
@@ -7666,11 +7809,79 @@ function mirrorTopLevel(source, dest) {
7666
7809
  for (const e of entriesAsBytes(source)) if (!e.name.equals(GIT_NAME)) copyTreeSafe(joinBytes(source, e.name), joinBytes(dest, e.name));
7667
7810
  }
7668
7811
 
7812
+ /** What a recovery's work copy takes from a worktree's own Git directory: the
7813
+ * state of an operation, and what an operation that ended left there. It is
7814
+ * the list of what is copied, never the test for "an operation is in
7815
+ * progress" (gitOperationInProgress). */
7669
7816
  export const RECOVERABLE_GIT_ADMIN = [
7670
7817
  "MERGE_HEAD", "MERGE_MSG", "AUTO_MERGE", "CHERRY_PICK_HEAD", "REVERT_HEAD", "REBASE_HEAD",
7671
7818
  "BISECT_LOG", "BISECT_START", "BISECT_NAMES", "rebase-apply", "rebase-merge", "sequencer",
7672
7819
  ];
7673
7820
 
7821
+ /** The entries of a worktree's own Git directory by which `git status` decides
7822
+ * that an operation is in progress there (Git's wt-status.c,
7823
+ * wt_status_get_state, and sequencer.c, sequencer_get_last_command):
7824
+ * - `rebase-apply`, else `rebase-merge`: a rebase, or `git am`;
7825
+ * - `MERGE_HEAD`: a merge;
7826
+ * - `CHERRY_PICK_HEAD`, `REVERT_HEAD`: a cherry-pick, a revert;
7827
+ * - `sequencer/todo`: a cherry-pick or a revert of several commits, between
7828
+ * two of them;
7829
+ * - `BISECT_LOG`: a bisect.
7830
+ * It is not the list of what a recovery copies (RECOVERABLE_GIT_ADMIN): Git
7831
+ * leaves `REBASE_HEAD`, `AUTO_MERGE` and `MERGE_MSG` behind operations that
7832
+ * ended, reads `BISECT_START` and `BISECT_NAMES` only during a bisect, and
7833
+ * reads nothing of a `sequencer` directory but its `todo`. None of them says
7834
+ * that an operation is in progress, and a copy still takes each. */
7835
+ export const GIT_OPERATION_ENTRIES = Object.freeze([
7836
+ "rebase-apply", "rebase-merge", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "sequencer/todo", "BISECT_LOG",
7837
+ ]);
7838
+ /** The two of them that are refs. In the files format a ref is a file of the
7839
+ * Git directory; in the reftable format it is not, and only Git can say
7840
+ * whether it is there. */
7841
+ const GIT_OPERATION_REFS = Object.freeze(["CHERRY_PICK_HEAD", "REVERT_HEAD"]);
7842
+
7843
+ /** Whether something is at `path`, a link not followed → true, false when it
7844
+ * is not there (ENOENT, ENOTDIR), null when it cannot be looked at. */
7845
+ function gitEntryAt(path) {
7846
+ try { lstatSync(path); return true; }
7847
+ catch (e) { return e?.code === "ENOENT" || e?.code === "ENOTDIR" ? false : null; }
7848
+ }
7849
+ /** Whether the repository of the worktree whose own Git directory is `gitDir`
7850
+ * may store its refs in the reftable format: a `reftable` entry in that
7851
+ * directory, which a linked worktree's has too, or in the common directory
7852
+ * its `commondir` file names. No Git command runs for it. What cannot be
7853
+ * read is not "no": then Git is asked. */
7854
+ function refsMayBeReftable(gitDir) {
7855
+ if (gitEntryAt(join(gitDir, "reftable")) !== false) return true;
7856
+ let common;
7857
+ try { common = readFileSync(join(gitDir, "commondir"), "utf8").trim(); }
7858
+ catch (e) { return !(e?.code === "ENOENT" || e?.code === "ENOTDIR"); }
7859
+ return gitEntryAt(join(resolve(gitDir, common), "reftable")) !== false;
7860
+ }
7861
+
7862
+ /** Whether a Git operation is in progress in the worktree at `tree` whose own
7863
+ * Git directory is `gitDir`: the one answer to that question, for a retire's
7864
+ * extra trees, for the recovery of its own tree and for the listing of what
7865
+ * retires retained. A tree is removed on this answer, so it differs from
7866
+ * Git's own where that keeps a tree:
7867
+ * - an entry counts when it exists, as whatever it is and without following
7868
+ * a link. Git also resolves the two refs and reads the todo's first word;
7869
+ * a `CHERRY_PICK_HEAD` that does not resolve and a todo Git cannot read
7870
+ * are operations here;
7871
+ * - an entry that cannot be looked at, for any reason but its absence
7872
+ * (ENOENT, ENOTDIR), is an operation.
7873
+ * The entries are files in every format but the two refs. In a repository
7874
+ * that stores its refs in the reftable format a cherry-pick or a revert left
7875
+ * open in a tree with no change leaves no entry at all, so there, and only
7876
+ * there, Git is asked for each of the two in the tree (gitRefPresence).
7877
+ * Whatever is not Git's plain "not there" is an operation: a failure, a
7878
+ * timeout, no Git, no `tree` to ask in. In the files format no Git command
7879
+ * runs. */
7880
+ export function gitOperationInProgress(gitDir, tree) {
7881
+ if (GIT_OPERATION_ENTRIES.some((entry) => gitEntryAt(join(gitDir, entry)) !== false)) return true;
7882
+ return refsMayBeReftable(gitDir) && GIT_OPERATION_REFS.some((name) => gitRefPresence(tree, name) !== "absent");
7883
+ }
7884
+
7674
7885
  /** The paths of a repository's Git directories that a recovery's work copy
7675
7886
  * takes by copying them, beside the clone, the files and the index: one
7676
7887
  * selection, read by the copier (restoreStandaloneGitState,
@@ -7678,7 +7889,7 @@ export const RECOVERABLE_GIT_ADMIN = [
7678
7889
  * (repositoryGitState), so that each copied path is compared by what its
7679
7890
  * copy carries (copiedGitPathDigest). `dir`: the repository's own Git
7680
7891
  * directory ("git") or its common directory ("common"). `copy`: copyTreeSafe
7681
- * ("tree") or copyFileSync ("file").
7892
+ * ("tree") or copyRegularFile ("file").
7682
7893
  * The index is copied whole and is not in the selection: it is compared by
7683
7894
  * its entries, its resolve-undo records and its mode, never by its bytes,
7684
7895
  * which hold a cache that a read-only Git command rewrites. That is a
@@ -7693,7 +7904,7 @@ const copiedGitPath = ({ dir, path }, gitDir, commonDir) => join(dir === "git" ?
7693
7904
  /** What the copy of one selected path carries, as a digest; null when the
7694
7905
  * path is not there. copyTreeSafe gives a copy the entry's kind, bytes or
7695
7906
  * target, and the bits of the entry and of everything under it: its exact
7696
- * digest. copyFileSync follows a link and gives the copy the bytes and the
7907
+ * digest. copyRegularFile follows a link and gives the copy the bytes and the
7697
7908
  * mode of what it reaches: those. Any failure but "not there" throws, as a
7698
7909
  * read of the Git state does, and so does a file path that is not a file. */
7699
7910
  function copiedGitPathDigest(entry, at) {
@@ -7795,6 +8006,52 @@ function carryNamedObjects(source, recovered, { commits = [], blobs = [] }) {
7795
8006
  }
7796
8007
  }
7797
8008
 
8009
+ /** Copy `source` to `dest` as one file: how the recovery's copier takes the
8010
+ * paths it copies "as a file" (the index, the entries of COPIED_GIT_PATHS
8011
+ * with copy "file", a nested repository's reflogs). The kernel decides what
8012
+ * is copied that way, never the file system: copyFileSync of an empty
8013
+ * directory fails on one (EISDIR) and writes an empty file on another, where
8014
+ * a directory's size is 0, so the same retire refused on one host and went
8015
+ * through on the other (awebai/oats#1029).
8016
+ * The look follows a link, as Git does at each of these paths (it reads the
8017
+ * index, info/attributes and a reflog through one) and as the comparison
8018
+ * does (copiedGitPathDigest): what Git reads there decides.
8019
+ * → true: a regular file is there, in place or at a link's end, and `dest`,
8020
+ * whose directory is made, now holds its bytes and mode as a plain file.
8021
+ * → false: nothing is there (ENOENT, ENOTDIR), also at the end of a link
8022
+ * that leads nowhere; nothing is written, and the caller does what it always
8023
+ * did for an absent path.
8024
+ * Anything else throws, naming the path and what is there in the kernel's
8025
+ * own words (notCopiedAsFile), never the system's message. `source` and
8026
+ * `dest` are strings or Buffers (a ref's log is named by its bytes). */
8027
+ export function copyRegularFile(source, dest) {
8028
+ const absent = (e) => e?.code === "ENOENT" || e?.code === "ENOTDIR";
8029
+ let st;
8030
+ try { st = lstatSync(source); }
8031
+ catch (e) {
8032
+ if (absent(e)) return false;
8033
+ throw notCopiedAsFile(source, "an entry that cannot be read");
8034
+ }
8035
+ const link = st.isSymbolicLink();
8036
+ if (link) {
8037
+ try { st = statSync(source); }
8038
+ catch (e) {
8039
+ if (absent(e)) return false;
8040
+ throw notCopiedAsFile(source, "a link that cannot be followed");
8041
+ }
8042
+ }
8043
+ if (!st.isFile()) {
8044
+ const what = st.isDirectory() ? "a directory" : "an entry that is neither a file nor a directory";
8045
+ throw notCopiedAsFile(source, link ? `a link to ${what}` : what);
8046
+ }
8047
+ mkdirSync(Buffer.isBuffer(dest) ? parentOf(dest) : dirname(dest), { recursive: true });
8048
+ copyFileSync(source, dest);
8049
+ return true;
8050
+ }
8051
+ /** The copier's refusal of a path it copies as a file. `what`: one of the
8052
+ * words copyRegularFile has for what is there. */
8053
+ const notCopiedAsFile = (path, what) => new Error(`the recovery copies ${Buffer.isBuffer(path) ? path.toString("utf8") : path} as a file, and ${what} is there`);
8054
+
7798
8055
  function restoreStandaloneGitState(sourceWork, recoveredRepo) {
7799
8056
  const sourceGit = copierGitDir(sourceWork);
7800
8057
  const recoveredGit = join(recoveredRepo, ".git");
@@ -7812,8 +8069,12 @@ function restoreStandaloneGitState(sourceWork, recoveredRepo) {
7812
8069
  ];
7813
8070
  carryNamedObjects(sourceWork, recoveredRepo, { blobs });
7814
8071
  // The index is the selection's one exception (COPIED_GIT_PATHS): copied
7815
- // whole, compared by its entries, resolve-undo records and mode.
7816
- copyFileSync(join(sourceGit, "index"), join(recoveredGit, "index"));
8072
+ // whole, compared by its entries, resolve-undo records and mode. A tree
8073
+ // with no index file (`git worktree add --no-checkout`, the file removed)
8074
+ // is carried as one: the index the clone's checkout wrote is removed, so
8075
+ // that the copy reads to Git as the source does, every committed file a
8076
+ // staged deletion (awebai/oats#1048).
8077
+ if (!copyRegularFile(join(sourceGit, "index"), join(recoveredGit, "index"))) rmSync(join(recoveredGit, "index"), { force: true });
7817
8078
  for (const entry of COPIED_GIT_PATHS.filter((e) => e.dir === "git")) {
7818
8079
  const source = copiedGitPath(entry, sourceGit);
7819
8080
  if (!existsSync(source)) continue;
@@ -7869,12 +8130,7 @@ function carryStatusConfig(sourceWork, recoveredRepo) {
7869
8130
  }
7870
8131
  const common = copierCommonDir(sourceWork);
7871
8132
  const attributes = copiedGitPath(GIT_ATTRIBUTES, null, common);
7872
- if (existsSync(attributes)) {
7873
- const dest = copiedGitPath(GIT_ATTRIBUTES, null, join(recoveredRepo, ".git"));
7874
- mkdirSync(dirname(dest), { recursive: true });
7875
- copyFileSync(attributes, dest);
7876
- carried.push({ kind: "info/attributes", path: attributes });
7877
- }
8133
+ if (copyRegularFile(attributes, copiedGitPath(GIT_ATTRIBUTES, null, join(recoveredRepo, ".git")))) carried.push({ kind: "info/attributes", path: attributes });
7878
8134
  return carried;
7879
8135
  }
7880
8136
 
@@ -7892,17 +8148,22 @@ function detachRecoveryClone(source, recovered, commits = []) {
7892
8148
  named.push(stash);
7893
8149
  const sourceCommon = copierCommonDir(source);
7894
8150
  const stashLog = copiedGitPath(GIT_STASH_LOG, null, sourceCommon);
7895
- if (existsSync(stashLog)) {
7896
- const recoveredLog = copiedGitPath(GIT_STASH_LOG, null, join(recovered, ".git"));
7897
- mkdirSync(dirname(recoveredLog), { recursive: true });
7898
- copyFileSync(stashLog, recoveredLog);
7899
- named.push(...reflogCommits(recoveredLog));
7900
- }
8151
+ const recoveredLog = copiedGitPath(GIT_STASH_LOG, null, join(recovered, ".git"));
8152
+ if (copyRegularFile(stashLog, recoveredLog)) named.push(...reflogCommits(recoveredLog));
7901
8153
  }
7902
8154
  carryNamedObjects(source, recovered, { commits: named });
7903
8155
  try { retireGit(recovered, ["remote", "remove", "origin"]); } catch { /* no remote is already independent */ }
7904
8156
  }
7905
8157
 
8158
+ /** The commit at a repository's HEAD as the copier reads it, or null when
8159
+ * its HEAD has none: a branch nobody has committed on (`git init` and no
8160
+ * commit, `git switch --orphan`). Only Git's own quiet answer (exit 1) is
8161
+ * "none"; any other failure of the read throws. */
8162
+ function copierHeadCommit(repo) {
8163
+ try { return retireGit(repo, ["rev-parse", "--verify", "--quiet", "HEAD"], { encoding: "utf8" }).trim(); }
8164
+ catch (e) { if (e.status === 1) return null; throw e; }
8165
+ }
8166
+
7906
8167
  /** A path under a Git directory for a ref name read as bytes: a branch name
7907
8168
  * need not be UTF-8, and the file Git keeps for it is named by its bytes. */
7908
8169
  const gitPathOf = (dir, ...parts) => Buffer.concat([Buffer.from(`${dir}${sep}`), ...parts]);
@@ -7912,7 +8173,10 @@ const parentOf = (path) => path.subarray(0, path.lastIndexOf(sep.charCodeAt(0)))
7912
8173
  * for recovering work (awebai/oats#657): every local branch under its name at
7913
8174
  * its commit, HEAD on the source's branch when the source is on one (`name`:
7914
8175
  * headName) and detached at `head` otherwise, and the source's reflogs of
7915
- * HEAD and of each branch, copied over the clone's own. The branches are the
8176
+ * HEAD and of each branch, copied over the clone's own. `head` is null when
8177
+ * the source's HEAD has no commit (copierHeadCommit: `git init` and nothing
8178
+ * committed, `git switch --orphan`): the copy's HEAD is then put on the same
8179
+ * branch and checked to have no commit either. The branches are the
7916
8180
  * source's own `refs/heads`, not the clone's `refs/remotes/origin/*`: those
7917
8181
  * are only what the source advertises, and its configuration can hide a
7918
8182
  * branch from a clone (`uploadpack.hideRefs`). A tip the clone lacks is
@@ -7943,16 +8207,17 @@ function carryNestedRefs(source, dest, name, head) {
7943
8207
  if (!retireGit(dest, BRANCHES).equals(listing)) throw new Error(`nested recovery ${dest} does not have the local branches of its source`);
7944
8208
  if (name.branch !== null) retireGit(dest, ["symbolic-ref", "HEAD", `refs/heads/${name.branch}`]);
7945
8209
  else retireGit(dest, ["checkout", "--quiet", "--detach", head]);
7946
- const recovered = retireGit(dest, ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
7947
- if (recovered !== head) throw new Error(`nested recovery ${dest} is at ${recovered}, not at the commit ${head} its source has checked out`);
8210
+ const recovered = copierHeadCommit(dest);
8211
+ if (head === null) {
8212
+ // No commit to be at: the copy's HEAD names the source's branch, and has no commit either.
8213
+ if (recovered !== null) throw new Error(`nested recovery ${dest} is at ${recovered}, and the HEAD of its source has no commit`);
8214
+ if (!headName(dest).ref?.equals(name.ref)) throw new Error(`nested recovery ${dest} is not on the branch the HEAD of its source names`);
8215
+ } else if (recovered !== head) throw new Error(`nested recovery ${dest} is at ${recovered ?? "no commit"}, not at the commit ${head} its source has checked out`);
7948
8216
  // The reflogs last, so that nothing above writes to them after the copy.
7949
8217
  const named = [];
7950
8218
  const carryLog = (from, to) => {
7951
- if (existsSync(from)) {
7952
- mkdirSync(parentOf(to), { recursive: true });
7953
- copyFileSync(from, to);
7954
- named.push(...reflogCommits(to));
7955
- } else rmSync(to, { force: true });
8219
+ if (copyRegularFile(from, to)) named.push(...reflogCommits(to));
8220
+ else rmSync(to, { force: true });
7956
8221
  };
7957
8222
  const destGit = join(dest, ".git");
7958
8223
  carryLog(gitPathOf(copierGitDir(source), Buffer.from("logs/HEAD")), gitPathOf(destGit, Buffer.from("logs/HEAD")));
@@ -7978,7 +8243,10 @@ function materializeNestedRepositories(sourceWork, recoveredRepo) {
7978
8243
  const rel = relative(sourceWork, source);
7979
8244
  const dest = join(recoveredRepo, rel);
7980
8245
  const name = headName(source);
7981
- const head = retireGit(source, ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
8246
+ const head = copierHeadCommit(source);
8247
+ // No commit to detach the copy at, and no branch to put it on. What its
8248
+ // HEAD holds is not said: it is a file's content, and need not be text.
8249
+ if (head === null && name.branch === null) throw new Error(`nested repository ${source} has no commit at its HEAD, and its HEAD names no local branch`);
7982
8250
  rmSync(dest, { recursive: true, force: true });
7983
8251
  retireGit(null, ["clone", "--no-local", "--quiet", source, dest]);
7984
8252
  detachRecoveryClone(source, dest, carryNestedRefs(source, dest, name, head));
@@ -8063,13 +8331,16 @@ function copyRecoveryHome(observation, dest) {
8063
8331
  * source bytes are the observation's (observedWorkBytes), so the verified
8064
8332
  * value is also its byte state. → { copied, branchDrift?, excludes?,
8065
8333
  * statusConfig? }; `copied` is false where neither applies (another work
8066
- * mode, or a worktree home with no recorded repo or branch). A HEAD that
8334
+ * mode, a worktree home with no repo, or one whose worktree is gone and
8335
+ * whose record holds no branch). A HEAD that
8067
8336
  * cannot be read is an inspection failure, not a failed copy: its error is
8068
8337
  * put in `unreadableHeads`, and the callers throw it as it is. */
8069
8338
  const unreadableHeads = new WeakSet();
8070
8339
  function copyRecoveryWork(observation, meta, parent) {
8071
8340
  let branchDrift, excludes, statusConfig, copied = false;
8072
- if (meta.work === "worktree" && meta.repo && meta.branch && (existsSync(observation.work) || observation.branchExists)) {
8341
+ // A worktree that is there is copied from itself: only one that is gone needs the recorded
8342
+ // branch, to be copied from the repository. (An own tree whose record holds no branch, #962.)
8343
+ if (meta.work === "worktree" && meta.repo && (existsSync(observation.work) || (meta.branch && observation.branchExists))) {
8073
8344
  const recoveredRepo = join(parent, "repo");
8074
8345
  // The branch is derived from the worktree while it exists: an instance
8075
8346
  // that legitimately switched branches during its task must still be
@@ -8079,7 +8350,7 @@ function copyRecoveryWork(observation, meta, parent) {
8079
8350
  let ref;
8080
8351
  try { ref = existsSync(observation.work) ? worktreeHead(observation.work) : { branch: meta.branch, commit: null }; }
8081
8352
  catch (e) { unreadableHeads.add(e); throw e; }
8082
- if (ref.branch !== meta.branch) branchDrift = { recordedBranch: meta.branch, worktreeBranch: ref.branch, detachedAt: ref.branch === null ? ref.commit : null };
8353
+ if (meta.branch && ref.branch !== meta.branch) branchDrift = { recordedBranch: meta.branch, worktreeBranch: ref.branch, detachedAt: ref.branch === null ? ref.commit : null };
8083
8354
  if (ref.branch !== null) retireGit(null, ["clone", "--no-local", "--quiet", "--branch", ref.branch, meta.repo, recoveredRepo]);
8084
8355
  else {
8085
8356
  retireGit(null, ["clone", "--no-local", "--quiet", "--no-checkout", meta.repo, recoveredRepo]);
@@ -8158,8 +8429,7 @@ function homeOnlyRecovery(observation, meta) {
8158
8429
  if (observation.orphanedWork === true) return true;
8159
8430
  if (observation.workProvable === false) return false;
8160
8431
  if (!(observation.classes.length === 1 && observation.classes[0] === "changed instance-home bytes" && meta.work === "worktree" && existsSync(observation.work))) return false;
8161
- const gitDir = copierGitDir(observation.work);
8162
- return !RECOVERABLE_GIT_ADMIN.some((name) => existsSync(join(gitDir, name)));
8432
+ return !gitOperationInProgress(copierGitDir(observation.work), observation.work);
8163
8433
  }
8164
8434
 
8165
8435
  /** Remove a recovery's staging directory, after a copy that failed or that had
@@ -8355,8 +8625,14 @@ export function deferredRetireResultPath(home) {
8355
8625
  return join(dirname(home), `.oats-retired-${basename(home)}.json`);
8356
8626
  }
8357
8627
 
8628
+ /** What the detached completion of a self-retire runs. Its intent is its own input: it takes the
8629
+ * variable out of its environment once it has read it, before the retire runs anything, so that
8630
+ * nothing it starts (a retire hook, Git, the stop of a child) inherits it. A hook's environment
8631
+ * is this process's, with what the kernel adds (lifecycleHookEnv). */
8358
8632
  const DEFERRED_RETIRE_SCRIPT = `import { completeDeferredRetirement } from ${JSON.stringify(import.meta.url)};
8359
- process.exitCode = completeDeferredRetirement(JSON.parse(process.env.OATS_RETIRE_INTENT)) ? 0 : 1;`;
8633
+ const intent = process.env.OATS_RETIRE_INTENT;
8634
+ delete process.env.OATS_RETIRE_INTENT;
8635
+ process.exitCode = completeDeferredRetirement(JSON.parse(intent)) ? 0 : 1;`;
8360
8636
 
8361
8637
  /** Self-retire (aweb-abep): persist intent, then hand the retirement to a
8362
8638
  * detached process that runs it as an ORDINARY external retirement after the
@@ -8389,7 +8665,13 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8389
8665
  // The recorded children as they were when the retirement was scheduled: the completion stops them first.
8390
8666
  ...(Array.isArray(o.children) ? { children: o.children.map((c) => ({ instance: c.instance, home: c.home })) } : {}) }, resultPath,
8391
8667
  };
8392
- const env = { ...process.env, OATS_RETIRE_INTENT: JSON.stringify(intent) };
8668
+ // The completion is told who scheduled it: this process, by pid and by the start token its
8669
+ // holding of the home's claim records (lib/claim.mjs takes both from the same reading). It is
8670
+ // told in its environment and nowhere else: the marker's format is as it was, and the completion
8671
+ // compares the claim against what it was given, never against what it reads later beside the
8672
+ // home (completeDeferredRetirement).
8673
+ const requestedByStart = processStartToken(process.pid);
8674
+ const env = { ...process.env, OATS_RETIRE_INTENT: JSON.stringify({ ...intent, ...(requestedByStart ? { requestedByStart } : {}) }) };
8393
8675
  for (const k of CORE_LAUNCH_ENV) delete env[k];
8394
8676
  rmSync(resultPath, { force: true });
8395
8677
  const scheduleFailed = (why) => oatsError("E_SELF_RETIRE_SCHEDULE_FAILED", `could not start the deferred retirement of ${name}: ${why}. Nothing was inspected, run, or removed; the instance is still live and can be retired externally with \`oats retire ${name} --home ${found.home}\``);
@@ -8409,6 +8691,7 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8409
8691
  // marker is written ends it first, under the claim: the handle's own SIGKILL, never a pid looked
8410
8692
  // up. A scheduling that fails therefore leaves no completion behind, and "nothing was
8411
8693
  // inspected, run, or removed" stays true after this call has answered.
8694
+ let wroteMarker = false;
8412
8695
  try {
8413
8696
  closeSync(fd);
8414
8697
  if (!child.pid) throw scheduleFailed("no process was created");
@@ -8423,7 +8706,20 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8423
8706
  child.unref();
8424
8707
  // The marker names its completion (pid and start time; the start is null when it cannot be read):
8425
8708
  // 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");
8709
+ const completionStart = processStartToken(child.pid);
8710
+ writeFileSync(marker, JSON.stringify({ ...intent, completionPid: child.pid, completionStart }, null, 2) + "\n");
8711
+ wroteMarker = true;
8712
+ // The marker promises a completion that is on its way. One that has ended by now is not: it
8713
+ // looked for its marker before this call wrote one, and nothing would ever remove it. So the
8714
+ // scheduling failed. A completion does not start its retire while it reads the claim as this
8715
+ // call's, alive (completeDeferredRetirement). So one that has ended by now either did not read
8716
+ // it so (this call's liveness could not be read, and its retire answered for that) and left
8717
+ // its outcome at `resultPath` (this call removed any earlier one before it started it), or
8718
+ // left none: it was killed, or could not write it. Gone is what the kernel reads of a holder
8719
+ // that died (processLiveness); a completion whose liveness cannot be read is not gone, and is
8720
+ // scheduled.
8721
+ if (existsSync(resultPath)) throw scheduleFailed("its completion gave up waiting for this command and has ended");
8722
+ if (processLiveness({ pid: child.pid, processStart: completionStart }).state === "gone") throw scheduleFailed("its completion has ended and left no outcome");
8427
8723
  } catch (e) {
8428
8724
  // No outcome is recorded for a completion this call ends itself: the answer below is the outcome.
8429
8725
  child.removeAllListeners("error");
@@ -8436,7 +8732,8 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8436
8732
  // Not closed: Node cannot wait for a child synchronously, so a kill that lands inside the
8437
8733
  // completion's own write of that outcome could leave a result after this removal. It would say
8438
8734
  // 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 */ } }
8735
+ // And the marker, when this call wrote it: it names a completion that is not running.
8736
+ for (const left of [logPath, resultPath, ...(wroteMarker ? [marker] : [])]) { try { rmSync(left, { force: true }); } catch { /* none is a debt of the instance */ } }
8440
8737
  // "is not running": killed here, or gone by itself before the kill.
8441
8738
  throw e?.code === "E_SELF_RETIRE_SCHEDULE_FAILED" ? e : scheduleFailed(`${e?.message ?? e}; the completion this command had started is not running`);
8442
8739
  }
@@ -8446,17 +8743,12 @@ function scheduleDeferredSelfRetirement(root, found, name, o, session) {
8446
8743
  };
8447
8744
  }
8448
8745
 
8449
- /** Run by the detached child: wait for the caller's window to be gone, then
8450
- * retire the instance as an ordinary external operator. Returns true only
8451
- * when the home is actually gone, and then leaves no file behind. A failure
8452
- * writes an explicit outcome beside the home and leaves the pending marker
8453
- * (and, after hooks ran, the usual quarantine) in place, so `oats status`
8454
- * shows the debt and `oats retire <name>` retries and clears it. Accepts the
8455
- * intent object (the child gets it in its env) or a marker path. */
8456
8746
  /** The item a quarantine retry reports while the branch its failed spawn created is still there. It
8457
8747
  * names no branch: the name is the receipt's `retention.recordedBranch`, or the retained home's
8458
8748
  * instance.json `branch`. */
8459
8749
  export const FAILED_SPAWN_BRANCH_LEFT = "the branch the failed spawn created is left: OATS does not delete it. Inspect it and delete it with Git if it is not wanted, then retry";
8750
+ /** What a `retire-refused` event says of a completion whose cleanup did not finish. It names no item. */
8751
+ const RETIRE_INCOMPLETE_SENTENCE = (instance) => `the retirement of ${instance} is incomplete: its cleanup did not finish, and the home is retained`;
8460
8752
  const OBSOLETE_DELETE_BRANCH_SENTENCE = "this self-retire was requested with --delete-branch by an older OATS; retirement no longer deletes branches, so the branch and the worktree were left";
8461
8753
  /** The one internal option that says the retirement completes such an intent.
8462
8754
  * A symbol, so no caller can set it from parsed arguments or JSON. */
@@ -8464,8 +8756,29 @@ const OBSOLETE_DELETE_BRANCH = Symbol("an older self-retire intent with --delete
8464
8756
  /** The one internal option that says the retirement is a deferred self-retire's completion
8465
8757
  * (completeDeferredRetirement). A symbol, so no caller can set it from parsed arguments or JSON. */
8466
8758
  const COMPLETES_DEFERRED = Symbol("the completion of a deferred self-retire");
8759
+ /** How long a self-retire's completion waits for the retire that scheduled it to release the
8760
+ * home's claim before it goes on without it (completeDeferredRetirement). Long beside the wait of
8761
+ * a retire for any other holder (CLAIM_WAIT_MS, lib/claim.mjs): the scheduling is this
8762
+ * completion's own, and what it is waited for is a few file writes on a host that may be slow. */
8763
+ export const SCHEDULING_WAIT_MS = 10 * 60 * 1000;
8764
+ /** How long a completion pauses between two looks at the claim its scheduling still holds. */
8765
+ const SCHEDULING_PAUSE_MS = 50;
8467
8766
  export const RETIRE_DELETE_BRANCH_REFUSED = "oats retire no longer deletes branches: --delete-branch is not accepted. Retire without it; the branch is left in the repository. Inspect it there and delete it with Git if it is no longer wanted.";
8468
8767
 
8768
+ /** Run by the detached child: wait for the caller's window to be gone, then
8769
+ * retire the instance as an ordinary external operator. Returns true only
8770
+ * when the home is actually gone, and then leaves no file behind. Accepts the
8771
+ * intent object (the child gets it in its env) or a marker path.
8772
+ *
8773
+ * A completion that does not complete (the retire threw, or its cleanup is incomplete) says so,
8774
+ * since nobody is at a terminal to read its answer (awebai/oats#954). It leaves its outcome beside
8775
+ * the home, which `oats status` lists and `oats retire <name>` retries and clears, and one
8776
+ * `retire-refused` event. Its pending marker follows how far the retire got: it stays when a retire
8777
+ * hook was started or the removal of the home began, because the home is then owed a retire (after
8778
+ * hooks ran, the usual quarantine stays too); otherwise it goes, and the instance is a stopped or
8779
+ * running instance like any other, not one that reads RETIRING for a retire that is not happening.
8780
+ * How far the retire got is read from what it answers (`details.reached`, retireFailure), never
8781
+ * from its code. */
8469
8782
  export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8470
8783
  let intent = intentOrMarkerPath;
8471
8784
  if (typeof intentOrMarkerPath === "string") {
@@ -8488,6 +8801,68 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8488
8801
  const obsoleteDeleteBranch = intent.options?.deleteBranch === true;
8489
8802
  const delayMs = Math.max(0, Number(opts.delaySec ?? intent.delaySec ?? 8) * 1000);
8490
8803
  if (delayMs) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delayMs);
8804
+ // The home this completion answers for is the one its intent names, as every scheduling records
8805
+ // it. For an intent that names none the retire finds the instance by its name, and the
8806
+ // completion touches no marker and writes no event: a name can stand for more than one home.
8807
+ const home = typeof intent.options?.home === "string" && intent.options.home ? intent.options.home : null;
8808
+ // The retire that scheduled this completion writes the pending marker last, under the home's
8809
+ // claim. Until it has released that claim the completion does not start its retire: it would be
8810
+ // refused by its own scheduling for nothing but slowness, and would look for a marker that is
8811
+ // not written yet. So it waits here, for exactly one reading of the claim: its holder is the
8812
+ // command that scheduled this completion, by pid AND by recorded start, and reads as alive.
8813
+ // Who that command is comes from the intent this process was started with, and from nothing it
8814
+ // reads later: the claim is only compared against it. An intent that does not say both (a marker
8815
+ // the completion is run from, an older kernel's, a start that could not be read) waits for
8816
+ // nobody. Every other reading is not waited for, and the retire below answers it as for every
8817
+ // retire: that holder gone (taken over), its liveness unreadable, another holder in any state, a
8818
+ // file that is no claim, no claim.
8819
+ // The wait ends when the scheduling does: it returned (the marker is written by then), it failed
8820
+ // (and ended this completion itself), or it died. It also ends at its bound (SCHEDULING_WAIT_MS;
8821
+ // `opts.schedulingWaitMs` for a test), and nothing is decided there: the completion goes on to
8822
+ // the retire below, which waits and answers for a holder that is still there as for every
8823
+ // retire. A scheduling that comes back after that finds its completion's outcome, or a
8824
+ // completion that is gone, and has failed (scheduleDeferredSelfRetirement).
8825
+ const scheduledBy = Number.isSafeInteger(intent.requestedByPid) && isStartToken(intent.requestedByStart) ? { pid: intent.requestedByPid, start: intent.requestedByStart } : null;
8826
+ const schedulingHoldsClaim = () => {
8827
+ const held = home && scheduledBy ? homeClaimHolder(home) : null;
8828
+ return held !== null && held.holder.pid === scheduledBy.pid && held.holder.processStart === scheduledBy.start && held.state === "alive";
8829
+ };
8830
+ for (const until = Date.now() + (opts.schedulingWaitMs ?? SCHEDULING_WAIT_MS); schedulingHoldsClaim() && Date.now() < until;) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, SCHEDULING_PAUSE_MS);
8831
+ // Read before the retire runs: instance.json may be gone when the event is written.
8832
+ const incarnation = home ? incarnationOf(home) : null;
8833
+ /** Remove the pending marker, and only this completion's own: the one of the scheduling it
8834
+ * completes (the same `requestedAt`), whose named completion is absent (an older kernel's
8835
+ * marker), this process, or a process that is verifiably gone (a completion run from the marker
8836
+ * for a scheduling whose own completion died). A marker a later `--self` wrote, one that names
8837
+ * a process that runs or whose liveness cannot be read, and one that cannot be read are left.
8838
+ * The retire has released the home's claim by now, so a `--self` that lands between this read
8839
+ * and the removal loses its marker until its own completion runs; that completion still runs,
8840
+ * under the claim. → whether it removed one. */
8841
+ const removeOwnMarker = () => {
8842
+ if (!home) return false;
8843
+ const path = retirePendingMarkerPath(home), marker = readJsonOrUndefined(path);
8844
+ if (!isPlainObject(marker) || typeof intent.requestedAt !== "string" || marker.requestedAt !== intent.requestedAt) return false;
8845
+ const pid = marker.completionPid;
8846
+ if (Number.isSafeInteger(pid) && pid !== process.pid && processLiveness({ pid, processStart: marker.completionStart }).state !== "gone") return false;
8847
+ try { rmSync(path); return true; }
8848
+ catch (e) { if (e?.code !== "ENOENT") console.error(`deferred retirement: cannot remove ${path}: ${e.message}`); return false; }
8849
+ };
8850
+ /** The one way out of a completion that did not complete → false. `payload` is its outcome as
8851
+ * the result file takes it; `homeChanged` is false when no retire hook was started and nothing
8852
+ * of the home was removed. In this order: the outcome is written before the marker goes, since
8853
+ * a second `--self` reads a marker without an outcome as "already scheduled"; the event is
8854
+ * last, and evidence only, so one that cannot be written is said in the log and nothing else
8855
+ * changes. The row goes to the workspace's log alone, whatever `homeChanged` is: the
8856
+ * completion holds no claim here, and another retire may be inspecting or removing the home,
8857
+ * so it writes nothing into it. */
8858
+ const notCompleted = (payload, { code, homeChanged, sentence }) => {
8859
+ record(payload);
8860
+ if (!homeChanged && removeOwnMarker()) console.error(`deferred retirement of ${intent.instance}: no retire hook was started and nothing of the home was removed, so its pending marker is removed; ${intent.instance} is not being retired`);
8861
+ if (!home) { console.error(`deferred retirement of ${intent.instance}: no retire-refused event was recorded: its intent names no home`); return false; }
8862
+ const written = appendEvent(home, { kind: "retire-refused", data: { code, homeChanged, reason: retireRefusedReason(sentence) } }, { workspaceOnly: true, incarnation });
8863
+ if (!written.ok) console.error(`deferred retirement of ${intent.instance}: its retire-refused event could not be written: ${written.reason ?? (written.results ?? []).map((r) => `${r.path}: ${r.reason}`).join("; ")}`);
8864
+ return false;
8865
+ };
8491
8866
  let result;
8492
8867
  try {
8493
8868
  result = retireInstance(intent.root, intent.instance, {
@@ -8495,13 +8870,18 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8495
8870
  ...(Array.isArray(intent.options?.plannedExtraWorktrees) ? { plannedExtraWorktrees: intent.options.plannedExtraWorktrees } : {}),
8496
8871
  ...(Array.isArray(intent.options?.children) ? { children: intent.options.children } : {}),
8497
8872
  ...(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.
8873
+ // The retire that scheduled this completion was waited for above. Any other live holder of
8874
+ // the claim is waited for by the retire itself, for the time a completion's retire has
8875
+ // always waited, and then answers as for every retire.
8501
8876
  [COMPLETES_DEFERRED]: true,
8502
8877
  });
8503
8878
  } catch (e) {
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}` : ""}` });
8879
+ const code = kernelCode(e, "E_LIFECYCLE_FAILED");
8880
+ // An answer without `reached` is one in which the retire of the home had not begun (retireInstance).
8881
+ const reached = e?.details?.reached;
8882
+ const homeChanged = isPlainObject(reached) && (reached.hooksStarted === true || reached.home !== "kept");
8883
+ notCompleted({ ok: false, error: { code, message: e.message }, ...(e.details?.childrenStopped ? { childrenStopped: e.details.childrenStopped } : {}), ...(obsoleteDeleteBranch ? { warnings: [OBSOLETE_DELETE_BRANCH_SENTENCE] } : {}), retry: `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}` },
8884
+ { code, homeChanged, sentence: e.message });
8505
8885
  console.error(`deferred retirement of ${intent.instance} failed: ${e.message}`);
8506
8886
  // A defect's stack goes to the completion's log (lib/errors.mjs isDefect).
8507
8887
  reportDefect(e);
@@ -8509,7 +8889,11 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
8509
8889
  }
8510
8890
  if (obsoleteDeleteBranch) console.log(OBSOLETE_DELETE_BRANCH_SENTENCE);
8511
8891
  if (result.rollbackIncomplete) {
8512
- record({ ok: false, result, retry: `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}` });
8892
+ // A result and not an error, so it has no code. The retire worked on the home and left it
8893
+ // quarantined: the home is changed. The items are text of hooks and of Git, which the outcome
8894
+ // and the log hold and the event does not.
8895
+ notCompleted({ ok: false, result, retry: `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}` },
8896
+ { code: null, homeChanged: true, sentence: RETIRE_INCOMPLETE_SENTENCE(intent.instance) });
8513
8897
  console.error(`deferred retirement of ${intent.instance} is INCOMPLETE; the home is retained:\n ${result.rollbackIncomplete.join("\n ")}`);
8514
8898
  return false;
8515
8899
  }
@@ -8629,24 +9013,53 @@ export function retireClaimRefusals(name, home, lock) {
8629
9013
  return lifecycleClaimRefusals("retire", name, home, lock);
8630
9014
  }
8631
9015
 
9016
+ /** An option of claimHomeFor: when the claim cannot be WRITTEN, read it in its place, and answer
9017
+ * that nobody holds it when nobody does. Passed by a stop apply and by no other caller (a
9018
+ * retire, a retire's stop of a recorded child and every later verb need the claim): a stop is
9019
+ * what an operator reaches for when a disk is full, and a stop that leaves a session running
9020
+ * because it could not write a file protects nobody. A symbol, so no caller can set it from
9021
+ * parsed arguments or JSON. */
9022
+ export const READ_CLAIM_WHEN_UNWRITABLE = Symbol("oats.readClaimWhenUnwritable");
9023
+
8632
9024
  /** Take the lifecycle claim of `home` for `verb` ("retire", "stop") → the holding, for
8633
9025
  * releaseHomeClaim. The one way a verb takes it: the record carries the verb from the instant the
8634
9026
  * file exists, and a holder of any verb is refused at once (`waitMs: 0`; only a deferred
8635
9027
  * self-retire's completion waits, for the retire that scheduled it). The claim's directory is
8636
9028
  * 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 } = {}) {
9029
+ * cannot be made is a claim that cannot be taken: nothing was done (awebai/oats#874).
9030
+ *
9031
+ * → `{ lock, me }`, the holding. With READ_CLAIM_WHEN_UNWRITABLE, also
9032
+ * → `{ lock, me: null, unwritable, look }` (awebai/oats#946): the claim could not be written,
9033
+ * for the system's code `unwritable` (lib/claim.mjs CLAIM_UNWRITABLE_CODES) at one of its
9034
+ * writes, and it was read where it would have been taken: nobody holds it. Nothing is held,
9035
+ * so nothing excludes a command that takes the claim later; `look()` makes the same read
9036
+ * again and throws what it throws. A holder, or a file that is no claim, is refused as when
9037
+ * the claim can be written, by the same builder; a read that does not reach the path throws
9038
+ * the refusal of the write, as without the option (lib/claim.mjs claimUnheld).
9039
+ * What decides is the place of the failure and the system's code as it was thrown there
9040
+ * (claimWrite, unwritableCode): never the code, the words or the details of an answer. */
9041
+ export function claimHomeFor(verb, name, home, { waitMs = 0, [READ_CLAIM_WHEN_UNWRITABLE]: readInstead = false } = {}) {
8639
9042
  if (!CLAIM_VERBS.includes(verb)) throw new TypeError(`claimHomeFor: ${JSON.stringify(verb)} is not a verb that takes a home's claim (${CLAIM_VERBS.join(", ")})`);
8640
9043
  const lock = retireClaimPath(home);
9044
+ const refusals = lifecycleClaimRefusals(verb, name, home, lock);
8641
9045
  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. */
9046
+ try {
9047
+ claimWrite(() => mkdirSync(instancesRetirementRoot(dirname(home)), { recursive: true }));
9048
+ claimWrite(() => mkdirSync(dirname(lock), { recursive: true, mode: 0o700 }));
9049
+ } catch (e) { throw claimUnavailable(lock, e); }
9050
+ return { lock, me: acquireClaim(lock, { ...refusals, facts: { action: verb }, waitMs }) };
9051
+ } catch (refusal) {
9052
+ const unwritable = readInstead ? unwritableCode(refusal) : undefined;
9053
+ if (!unwritable) throw refusal;
9054
+ const look = () => claimUnheld(lock, refusals, refusal);
9055
+ look();
9056
+ return { lock, me: null, unwritable, look };
9057
+ }
9058
+ }
9059
+ /** Release a holding of claimHomeFor, only while its file still names it. A claim that was only
9060
+ * read (READ_CLAIM_WHEN_UNWRITABLE) holds nothing to release. */
8648
9061
  export function releaseHomeClaim(holding) {
8649
- releaseClaim(holding.lock, holding.me);
9062
+ if (holding.me) releaseClaim(holding.lock, holding.me);
8650
9063
  }
8651
9064
  /** Who holds the lifecycle claim of `home` now, read and not taken → `{ lock, holder, action,
8652
9065
  * state, reason? }` (`state` is processLiveness's: "alive", "unknown" with its `reason`, "gone"),
@@ -9007,9 +9420,26 @@ function retireSteps(root, name, o, found, at) {
9007
9420
  }
9008
9421
 
9009
9422
  const workPath = join(found.home, "work");
9010
- const directory = meta.work === "directory";
9011
- const isWorktree = !directory && (meta.work === "worktree" ||
9012
- (existsSync(workPath) && !lstatSync(workPath).isSymbolicLink()));
9423
+ // What work/ is, by the one function the plan reads too (instanceWork, #962). Read once, here.
9424
+ const workIs = instanceWork(found.home, meta);
9425
+ const directoryMode = workIs.is === "directory-mode";
9426
+ // A real directory that is not the instance's own tree is bytes of the home: inspected, copied to
9427
+ // recovery and checked as a directory instance's work is, and removed with the home. It never
9428
+ // reaches the worktree step, and no pass leaves it out of its copy.
9429
+ const homeDirectory = workIs.is === "home-directory";
9430
+ const directory = directoryMode || homeDirectory;
9431
+ const isWorktree = workIs.is === "own-tree" || workIs.is === "other";
9432
+ // A link is never the instance's own tree, whatever the record says (#973): it goes with the
9433
+ // home, and what it leads to is not copied, moved, removed or read through Git by any step.
9434
+ const link = workIs.is === "link";
9435
+ // The record as the work steps read it, never written anywhere: an own tree is a worktree's,
9436
+ // whatever work mode the record holds, and when the record names no repository its repository
9437
+ // is the one Git names for the tree. A directory of the home is no worktree, whatever it holds,
9438
+ // and neither is a link, under a record that says `worktree` too: every step that asks whether
9439
+ // this home is a worktree's (the recovery's writers, the rollback retry) asks this record.
9440
+ const repoFromGit = workIs.is === "own-tree" && !meta.repo ? workIs.tree?.repo : undefined;
9441
+ const workMeta = workIs.is === "own-tree" ? { ...meta, work: "worktree", repo: meta.repo || repoFromGit }
9442
+ : homeDirectory || link ? { ...meta, work: undefined } : meta;
9013
9443
  // A live harness cannot establish a stable final work inspection of itself,
9014
9444
  // so self-retire never inspects, runs hooks, or removes anything here. It
9015
9445
  // persists the intent and hands the whole retirement to a detached process
@@ -9026,7 +9456,9 @@ function retireSteps(root, name, o, found, at) {
9026
9456
  // A worktree directory whose git admin entry is gone cannot be inspected, moved or removed through git, and
9027
9457
  // what it holds may exist nowhere else: it is never removed. Without --force the hooks still run and it is
9028
9458
  // an incomplete item; --force (which removes the home it sits in) refuses before anything runs.
9029
- const orphanedWork = meta.work === "worktree" && existsSync(workPath) && worktreeAdminMissing(workPath);
9459
+ // (An own tree: a directory of the home under a record that says `worktree` is no worktree that lost
9460
+ // its entry. It is copied and removed with the home, #962.)
9461
+ const orphanedWork = workIs.is === "own-tree" && meta.work === "worktree" && existsSync(workPath) && worktreeAdminMissing(workPath);
9030
9462
  if (orphanedWork && o.force) {
9031
9463
  throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: the work directory ${workPath} has no git admin entry in ${meta.repo ?? "its repository"}, so retiring the home would delete it with whatever it holds; move it out or delete it by hand, then retire again; nothing was run or removed`);
9032
9464
  }
@@ -9037,16 +9469,23 @@ function retireSteps(root, name, o, found, at) {
9037
9469
  const owesWorktree = !!quarantine && (quarantine.cleanup.outstanding?.git || []).includes("worktree");
9038
9470
  const recordedBranch = quarantine ? { repo: meta.repo, branch: meta.branch } : undefined;
9039
9471
  // Whether this retire removes the worktree, when it gets to that step.
9040
- const worktreeRemoval = { removes: !!(o.discardWorktree || owesWorktree), repo: meta.repo };
9472
+ const worktreeRemoval = { removes: !!(o.discardWorktree || owesWorktree), repo: workMeta.repo };
9041
9473
  // An inspection of the home and the work. Whatever fails in it, a walk that meets an entry it
9042
9474
  // cannot read or that is gone included, is an inspection that failed (E_WORK_INSPECTION_FAILED),
9043
9475
  // and says what the retire has and has not done by then (`disclosure`), once. Classified here,
9044
9476
  // at the retire's own calls: the digests' other callers do not answer that code for it.
9045
9477
  const inspect = (disclosure) => {
9046
- try { return inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, orphanedWork, disclosure }); }
9478
+ try { return inspectRetirementWork(found.home, workPath, inspectableWorktree, { recordedBranch, worktreeRemoval, directory, directoryMode, link, instance: name, orphanedWork, disclosure }); }
9047
9479
  catch (e) { throw statedFailure(e, "E_WORK_INSPECTION_FAILED", `${disclosure}.`, `could not inspect the home of ${name} or its work`); }
9048
9480
  };
9049
9481
  const initialObservation = inspect(nothingYet());
9482
+ // An own tree with no repository, recorded or read from Git, has no step: the retire cannot re-home it,
9483
+ // and its copy needs the repository too. Removing the home would delete it uncopied, so it is refused
9484
+ // here, --force included (#962): after the inspection, whose own refusals of such a directory keep
9485
+ // their words, and before the session is stopped and before any retire hook runs.
9486
+ if (workIs.is === "own-tree" && workIs.at === "directory" && !workMeta.repo && !orphanedWork && !o.keepDir) {
9487
+ throw oatsError("E_WORK_PRESERVATION_FAILED", `${name}: ${workPath} is the instance's own work tree, but its record names no repository and Git does not read it as a registered worktree of one, so the retire can neither re-home it nor copy it, and retiring the home would delete it with whatever it holds; move it out or delete it by hand, then retire again; nothing was run or removed`);
9488
+ }
9050
9489
  // A locked extra tree is known from the home as it is now: Git will neither move nor remove it, so a retire that
9051
9490
  // would remove the home refuses here, before the session is stopped and before any retire hook runs (the hooks
9052
9491
  // revoke identities a kept home would still need). The extra-tree step keeps its own check, for a lock that appears
@@ -9167,7 +9606,7 @@ function retireSteps(root, name, o, found, at) {
9167
9606
  let preHookRecovery;
9168
9607
  if (stableObservation.classes.length) {
9169
9608
  // Whatever fails here, not only a copy that could not be verified, says the same.
9170
- try { preHookRecovery = writeRetirementRecovery(stableObservation, meta, name, "before-hooks"); }
9609
+ try { preHookRecovery = writeRetirementRecovery(stableObservation, workMeta, name, "before-hooks"); }
9171
9610
  catch (e) {
9172
9611
  throw statedFailure(e, "E_LIFECYCLE_FAILED", `No retire hook has run, no recovery was written and nothing was deleted: ${soFar("its home and work are kept")}`);
9173
9612
  }
@@ -9267,9 +9706,9 @@ function retireSteps(root, name, o, found, at) {
9267
9706
  // does: the hooks have run, and what is kept (#659).
9268
9707
  const finalObservation = inspect(afterHooks());
9269
9708
  try {
9270
- if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, meta);
9709
+ if (preHookRecovery) workRecovery = completeRetirementRecovery(preHookRecovery, stableObservation, finalObservation, workMeta);
9271
9710
  else if (finalObservation.classes.length) {
9272
- workRecovery = preserveRetirementWork({ ...finalObservation, notCopied: unionNotCopied(stableObservation.notCopied, finalObservation.notCopied) }, meta, name);
9711
+ workRecovery = preserveRetirementWork({ ...finalObservation, notCopied: unionNotCopied(stableObservation.notCopied, finalObservation.notCopied) }, workMeta, name);
9273
9712
  }
9274
9713
  } catch (e) {
9275
9714
  throw statedFailure(e, "E_LIFECYCLE_FAILED", `${afterHooks()}.`);
@@ -9403,7 +9842,7 @@ function retireSteps(root, name, o, found, at) {
9403
9842
  // (#718), found while work/ is still here (a link through an alias of the
9404
9843
  // tree resolves only then), each with its link as written.
9405
9844
  const attachedKids = (childrenStopped || []).filter((k) => k.ok).map((k) => ({ ...k, link: attachedWorkLink(k.home, found.home) })).filter((k) => k.link !== null);
9406
- const worktreeStep = isWorktree && !!meta.repo && !orphanedWork;
9845
+ const worktreeStep = isWorktree && !!workMeta.repo && !orphanedWork;
9407
9846
  const worktreeDeferred = worktreeStep && existsSync(workPath) && outstandingBeforeWorktree.length > 0 && !o.force;
9408
9847
  const keptForRetry = worktreeDeferred ? `git worktree ${workPath}: kept for the retry; outstanding: ${outstandingBeforeWorktree.join("; ")}` : null;
9409
9848
  // The repository of work/, by its common Git directory (awebai/oats#679), read once from meta.repo: the
@@ -9414,10 +9853,10 @@ function retireSteps(root, name, o, found, at) {
9414
9853
  const workRepoGitDir = () => {
9415
9854
  if (workRepo) return workRepo;
9416
9855
  const args = ["rev-parse", "--path-format=absolute", "--git-common-dir"];
9417
- let r = gitRead(meta.repo, args);
9418
- if (!r.ok) { const asGitDir = gitRepoRead(meta.repo, args); if (asGitDir.ok) r = asGitDir; }
9856
+ let r = gitRead(workMeta.repo, args);
9857
+ if (!r.ok) { const asGitDir = gitRepoRead(workMeta.repo, args); if (asGitDir.ok) r = asGitDir; }
9419
9858
  const dir = r.ok ? r.out.replace(/\n$/, "") : "";
9420
- return (workRepo = dir && !dir.includes("\n") ? { dir: realPathOrNearest(dir) } : { error: r.ok ? `git rev-parse printed no single Git directory for ${meta.repo}` : r.err });
9859
+ return (workRepo = dir && !dir.includes("\n") ? { dir: realPathOrNearest(dir) } : { error: r.ok ? `git rev-parse printed no single Git directory for ${workMeta.repo}` : r.err });
9421
9860
  };
9422
9861
  // Whether an entry is at the path: lstat, so a dangling link is an entry; one that cannot be tested counts.
9423
9862
  const entryAt = (path) => { try { lstatSync(path); return true; } catch (e) { return e?.code !== "ENOENT"; } };
@@ -9462,7 +9901,7 @@ function retireSteps(root, name, o, found, at) {
9462
9901
  retention = { worktree: "removed", branch: verifiedBranch, recordedBranch: meta.branch ?? null };
9463
9902
  }
9464
9903
  } else if (existsSync(workPath)) {
9465
- const dest = retainedWorktreeDest(workspaceOf(root), meta.repo, verifiedBranch, ref.commit);
9904
+ const dest = retainedWorktreeDest(workspaceOf(root), workMeta.repo, verifiedBranch, ref.commit);
9466
9905
  mkdirSync(dirname(dest), { recursive: true });
9467
9906
  try {
9468
9907
  const gitDir = workRepoGitDir();
@@ -9516,7 +9955,7 @@ function retireSteps(root, name, o, found, at) {
9516
9955
  if (keptForRetry) failures.push(keptForRetry);
9517
9956
  // The quarantine may exist BECAUSE Git cleanup failed, so a retry has to
9518
9957
  // redo those steps and verify them — not just rerun hooks. No retire deletes a branch.
9519
- if (meta.work === "worktree" && meta.repo) {
9958
+ if (workMeta.work === "worktree" && workMeta.repo) {
9520
9959
  // A worktree this retry removed (the step above ran) must be verified gone; one it retained or kept for
9521
9960
  // the next retry stays registered by design. The removal is not attempted a second time here: only the
9522
9961
  // worktree step removes, after its check of HEAD, so a worktree it failed to remove is still registered
@@ -9553,8 +9992,8 @@ function retireSteps(root, name, o, found, at) {
9553
9992
  else if (owesBranch && meta.branch && ip && ip.branch === meta.branch && /^[0-9a-f]{40,64}$/.test(String(ip.baseOid ?? "")) && retention?.worktree === "removed" && !failures.length) {
9554
9993
  const ref = `refs/heads/${meta.branch}`;
9555
9994
  // Retire's Git, bounded and helper-free (retireGit, #809): two reads, then the one write.
9556
- const tip = retireGitProbe(meta.repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", ref], { encoding: "utf8" });
9557
- const list = retireGitProbe(meta.repo, ["worktree", "list", "--porcelain", "-z"], { encoding: "utf8" });
9995
+ const tip = retireGitProbe(workMeta.repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", ref], { encoding: "utf8" });
9996
+ const list = retireGitProbe(workMeta.repo, ["worktree", "list", "--porcelain", "-z"], { encoding: "utf8" });
9558
9997
  const listOk = !list.error && list.status === 0;
9559
9998
  const checkedOut = listOk && list.stdout.split("\0").includes(`branch ${ref}`);
9560
9999
  if (tip.error || tip.status !== 0 || tip.stderr.length) branchKeptReason = "the branch could not be read";
@@ -9562,7 +10001,7 @@ function retireSteps(root, name, o, found, at) {
9562
10001
  else if (!listOk) branchKeptReason = "whether it is checked out could not be read";
9563
10002
  else if (checkedOut) branchKeptReason = "it is checked out in a worktree";
9564
10003
  else {
9565
- const del = retireGitProbe(meta.repo, ["update-ref", "-d", ref, ip.baseOid], { encoding: "utf8" });
10004
+ const del = retireGitProbe(workMeta.repo, ["update-ref", "-d", ref, ip.baseOid], { encoding: "utf8" });
9566
10005
  if (del.error || del.status !== 0) branchKeptReason = `git refused to delete it (${String(del.stderr || del.error?.message || "").trim().split("\n")[0] || "update-ref failed"})`;
9567
10006
  else branchDeletedByRetry = true;
9568
10007
  }
@@ -9580,7 +10019,7 @@ function retireSteps(root, name, o, found, at) {
9580
10019
  }
9581
10020
  // Git debt is proven by the verification block above, which only runs for a
9582
10021
  // worktree in a known repo. If it could not run, the debt stands.
9583
- if (quarantine.cleanup.outstanding?.git?.length && !(meta.work === "worktree" && meta.repo)) {
10022
+ if (quarantine.cleanup.outstanding?.git?.length && !(workMeta.work === "worktree" && workMeta.repo)) {
9584
10023
  failures.push(`git ${quarantine.cleanup.outstanding.git.join(", ")}: not re-verified on this retry, so the cleanup they owed is unverified`);
9585
10024
  }
9586
10025
  if (failures.length) {
@@ -9624,6 +10063,11 @@ function retireSteps(root, name, o, found, at) {
9624
10063
  // unreachable remote) would be unremovable through OATS forever — the same
9625
10064
  // dead end the unusable-marker fixes closed, just reached from a valid one.
9626
10065
  const forced = !!(stillIncomplete && o.force);
10066
+ // Where a link under a record that says `worktree` leads, for the receipt (#973): once the home
10067
+ // is removed nothing else says it. The system's answer for the link, read here and only read:
10068
+ // never the text stored in the link, and no step acts on the path. null: it does not resolve.
10069
+ const linkLed = link && meta.work === "worktree" && !o.keepDir && (!stillIncomplete || forced)
10070
+ ? (() => { try { return { path: realpathSync(workPath) }; } catch { return { path: null }; } })() : undefined;
9627
10071
  if (!o.keepDir && (!stillIncomplete || forced)) {
9628
10072
  // The removal. A failure in it (a directory that is written into, or that cannot be emptied)
9629
10073
  // says what the retire did and what is at the home now, as it is on disk when it is answered.
@@ -9653,6 +10097,10 @@ function retireSteps(root, name, o, found, at) {
9653
10097
 
9654
10098
  const result = { retired: name, agent: found.agent.name, workRecovery, retention, extraWorktrees, worktreeRemoved: isWorktree && !!retention && retention.worktree !== "retained", branchDeleted: false, ...(branchDeletedByRetry || branchKeptReason ? { spawnCompensation: { branch: meta.branch, branchDeleted: branchDeletedByRetry, ...(branchKeptReason ? { reason: branchKeptReason } : {}) } } : {}), removedDir: !o.keepDir && (!stillIncomplete || forced), rollbackIncomplete: forced ? undefined : stillIncomplete, forcedIncomplete: forced ? stillIncomplete : undefined, retainedHome: stillIncomplete && !forced ? found.home : undefined, relinked: relinked.length ? relinked : undefined, childrenStopped, capabilityMeta: hookResults?.meta, warnings: (() => {
9655
10099
  const w = [...spawnGroupWarnings, ...(hookResults?.warnings || []), ...relinkWarnings];
10100
+ // What the retire read from Git about work/ where the record did not say it (#962).
10101
+ if (repoFromGit) w.push(`the record names no repository for the work tree at ${workPath}: the retire used the one Git names for it, ${repoFromGit}; the record was not changed`);
10102
+ if (homeDirectory && workIs.tree && !o.keepDir && (!stillIncomplete || forced)) w.push(`${workPath} was a registered worktree of ${workIs.tree.repo} and not this instance's own tree: it was copied to recovery and removed with the home as a directory of the home. Its entry stays in that repository until a prune (git -C ${shq(workIs.tree.repo)} worktree prune); its branch and commits are untouched`);
10103
+ if (linkLed) w.push(`${workPath} was a link though the record says work mode worktree: nothing was retained or removed as a work tree, and ${linkLed.path === null ? "it led nowhere that could be read" : `what it led to (${linkLed.path}) was not touched`}`);
9656
10104
  if (o[OBSOLETE_DELETE_BRANCH]) w.push(OBSOLETE_DELETE_BRANCH_SENTENCE);
9657
10105
  if (isCapturedHome(meta) && !quarantine) {
9658
10106
  // A captured home retires through the workspace path; its captured retire hooks do not