@awebai/oats 0.49.0 → 0.50.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.
package/lib/core.mjs CHANGED
@@ -126,6 +126,11 @@ export function legacyLocalAgents(root) {
126
126
  return { code: "legacy-local-agents", dirs, instances,
127
127
  message: `${instances.length} instance home${instances.length === 1 ? "" : "s"} under local-agents/ ${instances.length === 1 ? "is" : "are"} from OATS 0.25 and ${instances.length === 1 ? "is" : "are"} not managed by this kernel; retire ${instances.length === 1 ? "it" : "them"} with the 0.25 kernel or delete the directory once ${instances.length === 1 ? "it is" : "they are"} stopped${instances.length ? ` (${instances.join(", ")})` : ""}` };
128
128
  }
129
+ /** The instances directories under the agents root `root`: `<root>/<agent>/instances`, one per
130
+ * agent directory, whether or not it exists. */
131
+ export function instancesDirs(root) {
132
+ return subdirs(root).map((agent) => join(root, agent, "instances"));
133
+ }
129
134
  /** The instance homes under the agents root `root` (a directory <root>/<agent>/instances/<name>
130
135
  * whose instance.json records that name) that other users on the machine can read or enter (any
131
136
  * group or other permission bit): one `home-readable` problem naming them, with the exact chmod,
@@ -1966,12 +1971,22 @@ export function explicitInstanceName(name) {
1966
1971
  return name;
1967
1972
  }
1968
1973
 
1969
- function tmuxAlive(session) { return !!shTry(`tmux has-session -t ${shq(session)} 2>/dev/null && echo yes`); }
1970
1974
  /** The window names of `session` on the user's DEFAULT tmux server: only for a home that records no
1971
1975
  * socket (listInstances). OATS creates nothing there: new sessions live on the OATS server below. */
1972
- export function tmuxWindows(session = DEFAULT_TMUX_SESSION) {
1973
- if (!tmuxAlive(session)) return [];
1974
- return (shTry(`tmux list-windows -t ${shq(session)} -F '#{window_name}'`) || "").split("\n").filter(Boolean);
1976
+ export function tmuxWindows(session = DEFAULT_TMUX_SESSION) { return defaultTmuxWindows(session).windows; }
1977
+ /** tmuxWindows' read, keeping a missing socket file apart (#624): `{ windows }`, with `missingSocket`
1978
+ * (tmux's words) when the default server's socket file is missing. Any other failure reads as no
1979
+ * session. `has-session` first, as ever: it is the read-only probe a caller may expect for a home
1980
+ * that records no socket, and it words a missing socket file as list-windows does. */
1981
+ function defaultTmuxWindows(session) {
1982
+ const run = (args) => execFileSync("tmux", args, { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
1983
+ try {
1984
+ run(["has-session", "-t", session]);
1985
+ return { windows: run(["list-windows", "-t", session, "-F", "#{window_name}"]).split("\n").filter(Boolean) };
1986
+ } catch (e) {
1987
+ // Either read: the socket file can go between the two.
1988
+ return tmuxServerAbsence(e) === "missing-socket" ? { windows: [], missingSocket: tmuxFailure(e, "tmux failed") } : { windows: [] };
1989
+ }
1975
1990
  }
1976
1991
 
1977
1992
  // ---------- the OATS tmux server ----------
@@ -2003,8 +2018,11 @@ const exitedByItself = (e) => Number.isInteger(e?.status) && e.signal == null &&
2003
2018
  /** What the OATS server holds, as `list-sessions` answers: whether it runs, its socket (any session
2004
2019
  * names it), and whether a session named exactly `session` is there. No server and no such session
2005
2020
  * are the only answers that mean absent, and "no server" is read only from a call that exited by
2006
- * itself: a line a cut-off call left behind is not tmux's answer. Any other failure is not absence. */
2007
- function oatsTmuxSessionSocket(session, io) {
2021
+ * itself: a line a cut-off call left behind is not tmux's answer. Any other failure is not absence.
2022
+ * A missing socket file is absence only when `missingSocket(detail)` (a session start's check of its
2023
+ * home, missingSocketUnestablished) answers null; its reason refuses the start (#624). Without it, as
2024
+ * today. */
2025
+ function oatsTmuxSessionSocket(session, io, missingSocket) {
2008
2026
  let listed;
2009
2027
  try { listed = tmuxOatsServer(["list-sessions", "-F", "#{session_name}\t#{socket_path}"], io); }
2010
2028
  catch (e) {
@@ -2012,7 +2030,10 @@ function oatsTmuxSessionSocket(session, io) {
2012
2030
  // A tmux that could not be run at all is the one failure a person can act on: say so.
2013
2031
  if (e?.code === "ENOENT") throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `could not read the OATS tmux server for session ${session}: tmux was not found through this process's PATH. Run this command with a PATH that holds tmux`);
2014
2032
  if (!exitedByItself(e)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `could not read the OATS tmux server for session ${session}: tmux list-sessions did not exit by itself (${typeof e?.code === "string" ? e.code : e?.signal || "no exit status"})`);
2015
- if (tmuxServerLost(e)) return { server: null, present: false };
2033
+ const absence = tmuxServerAbsence(e);
2034
+ const why = absence === "missing-socket" && missingSocket ? missingSocket(tmuxFailure(e, "tmux list-sessions failed")) : null;
2035
+ if (why) throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether the OATS tmux server for session ${session} is running, so nothing was started: ${why}`);
2036
+ if (absence) return { server: null, present: false };
2016
2037
  throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `could not read the OATS tmux server for session ${session}: ${tmuxFailure(e, "tmux list-sessions failed")}`);
2017
2038
  }
2018
2039
  let server = null, present = false;
@@ -2280,10 +2301,10 @@ function oatsWindowEnvironment() {
2280
2301
  * again there when that server has gone. undefined when this process has no tmux to run: the
2281
2302
  * caller's backend check refuses that.
2282
2303
  */
2283
- function planOatsTmuxSession(session, io, { preview = false } = {}) {
2304
+ function planOatsTmuxSession(session, io, { preview = false, missingSocket } = {}) {
2284
2305
  if (!io?.exec && !which("tmux")) return undefined;
2285
2306
  let server, present;
2286
- try { ({ server, present } = oatsTmuxSessionSocket(session, io)); }
2307
+ try { ({ server, present } = oatsTmuxSessionSocket(session, io, missingSocket)); }
2287
2308
  catch (e) { if (preview) return undefined; throw e; } // a preview reports, it does not refuse on a read
2288
2309
  if (present || preview) return { server, present };
2289
2310
  return { server, present, env: oatsSessionEnvironment(session, io, { startsServer: !server }), startsServer: !server };
@@ -2359,10 +2380,12 @@ function launchLookup(configEnv, env, pane, configName, cwd) {
2359
2380
  * second lookup. tmux starts a server once: the first successful creator determines its initial
2360
2381
  * environment, and nothing here changes a running server's. E_RUNTIME_ENDPOINT_UNKNOWN when the
2361
2382
  * server cannot be read or names no socket, when this caller may not create the session, or when
2362
- * its own PATH names no tmux to create it with (creatorTmux).
2383
+ * its own PATH names no tmux to create it with (creatorTmux). `missingSocket` is a session start's
2384
+ * check of its home when the server's socket file is missing (oatsTmuxSessionSocket): with a reason,
2385
+ * E_SESSION_UNKNOWN and no server is created at that path.
2363
2386
  */
2364
- export function ensureOatsTmuxSession(session, hq, io, plan) {
2365
- let { server: socket, present } = oatsTmuxSessionSocket(session, io);
2387
+ export function ensureOatsTmuxSession(session, hq, io, plan, missingSocket) {
2388
+ let { server: socket, present } = oatsTmuxSessionSocket(session, io, missingSocket);
2366
2389
  if (!present) {
2367
2390
  // The executable is chosen here, where the creation is about to run, and nowhere earlier: a
2368
2391
  // session that exists needs none, so nothing is refused for it.
@@ -2375,7 +2398,7 @@ export function ensureOatsTmuxSession(session, hq, io, plan) {
2375
2398
  try { created = (io?.exec || execFileSync)(tmux, ["-u", ...address, "new-session", "-d", "-s", session, "-n", "hq", "-c", hq, "-P", "-F", "#{socket_path}\t#{window_id}"], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], env }).trim(); }
2376
2399
  catch (e) {
2377
2400
  if (oatsCoded(e)) throw e;
2378
- const again = oatsTmuxSessionSocket(session, io);
2401
+ const again = oatsTmuxSessionSocket(session, io, missingSocket);
2379
2402
  if (!again.present) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `could not create tmux session ${session} on the OATS tmux server: ${tmuxFailure(e, "tmux new-session failed")}`);
2380
2403
  socket = again.server;
2381
2404
  }
@@ -4377,7 +4400,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4377
4400
  relativeTo: relation ? relativeTo : undefined,
4378
4401
  spawnOrigin: relation || (parentInstance && parentInstance !== instance) ? "instance" : "operator",
4379
4402
  policy: { childSpawns: ownChildPolicy },
4380
- ...(triggerEventFile ? { trigger: { id: o.triggerEvent.trigger, key: o.triggerEvent.key ?? null, source: o.triggerEvent.source, repo: o.triggerEvent.repo, number: o.triggerEvent.number, subject: o.triggerEvent.subject ?? null, url: o.triggerEvent.url ?? null, event: o.triggerEvent.event, headSha: o.triggerEvent.headSha ?? null, observedAt: o.triggerEvent.observedAt ?? null, eventFile: triggerEventFile } } : {}),
4403
+ ...(triggerEventFile ? { trigger: { id: o.triggerEvent.trigger, key: o.triggerEvent.key ?? null, source: o.triggerEvent.source, repo: o.triggerEvent.repo ?? null, number: o.triggerEvent.number ?? null, subject: o.triggerEvent.subject ?? null, url: o.triggerEvent.url ?? null, event: o.triggerEvent.event, headSha: o.triggerEvent.headSha ?? null, observedAt: o.triggerEvent.observedAt ?? null, eventFile: triggerEventFile,
4404
+ // A capability source's event carries its declared fields (a pull request's never does).
4405
+ ...(o.triggerEvent.fields && typeof o.triggerEvent.fields === "object" ? { fields: o.triggerEvent.fields } : {}) } } : {}),
4381
4406
  // K6c: a decision-bound spawn records what bound it, so a retry with the
4382
4407
  // same key replays this receipt instead of spawning again.
4383
4408
  // The FULL bound decision (placement + effective), exactly as the fence
@@ -4614,26 +4639,42 @@ export function servedIdentityLine(identity) {
4614
4639
  return `alias ${identity.alias || "?"} on ${identity.team || "?"}`;
4615
4640
  }
4616
4641
  /** The window names of `session` on the tmux server at `socket`: `{ windows }`, empty when the server
4617
- * or the session is gone; `{ error }` when the server could not be read. */
4642
+ * or the session is gone, with `missingSocket` (tmux's words) when the socket file is missing, which
4643
+ * alone does not say the server is gone (#624); `{ error }` when the server could not be read. */
4618
4644
  function recordedTmuxWindows(socket, session) {
4619
4645
  try { return { windows: tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"]).split("\n").filter(Boolean) }; }
4620
4646
  catch (e) {
4621
- if (tmuxServerLost(e) || /can't find session/i.test(String(e.stderr ?? ""))) return { windows: [] };
4647
+ const absence = tmuxServerAbsence(e);
4648
+ if (absence === "missing-socket") return { windows: [], missingSocket: tmuxFailure(e, "tmux list-windows failed") };
4649
+ if (absence || /can't find session/i.test(String(e.stderr ?? ""))) return { windows: [] };
4622
4650
  return { error: String(e.stderr ?? e.message ?? "").trim() || "tmux list-windows failed" };
4623
4651
  }
4624
4652
  }
4625
- /** A status row's liveness from its session's windows: unknown (not false) when the server could not be read. */
4626
- function tmuxLiveness({ windows, error }, window) {
4627
- return error ? { running: null, runtimeState: "unreachable", runtimeError: error } : { running: windows.includes(window) };
4653
+ /** A status row's liveness from its session's windows: unknown (not false) when the server could not
4654
+ * be read, and, for a row whose server holds its endpoint (`endpoint`), when its socket file is
4655
+ * missing while a process works in the home or the scan (`scanHome()`, processesInHome's answer for
4656
+ * it) cannot tell (#624). */
4657
+ function tmuxLiveness({ windows, error, missingSocket }, window, scanHome, endpoint) {
4658
+ if (error) return { running: null, runtimeState: "unreachable", runtimeError: error };
4659
+ const running = windows.includes(window);
4660
+ const why = !running && missingSocket && endpoint ? missingSocketUnestablished(missingSocket, scanHome()) : null;
4661
+ return why ? { running: null, runtimeState: "unreachable", runtimeError: why } : { running };
4628
4662
  }
4629
- export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION) {
4663
+ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
4630
4664
  // Liveness reads each home's RECORDED endpoint (a pre-0.31 home records pi-agents): the recorded
4631
4665
  // socket, never the ambient $TMUX server, once per socket and session per call, so status costs no
4632
4666
  // more child processes as homes grow. A home without a recorded socket reads the default server.
4667
+ // A row whose socket file is missing is checked against one process scan of the host, made the
4668
+ // first time a row needs it and shared by every row (`io` reaches it: processesInHome).
4669
+ let hostScan;
4670
+ const scanOf = (home) => () => {
4671
+ hostScan ??= hostProcesses(io);
4672
+ return hostScan.ok ? { ok: true, processes: processesWorkingIn(hostScan.processes, home) } : hostScan;
4673
+ };
4633
4674
  const tmuxByEndpoint = new Map();
4634
4675
  const windowsOf = (session, socket) => {
4635
4676
  const key = JSON.stringify([socket ?? null, session]);
4636
- if (!tmuxByEndpoint.has(key)) tmuxByEndpoint.set(key, socket ? recordedTmuxWindows(socket, session) : { windows: tmuxWindows(session) });
4677
+ if (!tmuxByEndpoint.has(key)) tmuxByEndpoint.set(key, socket ? recordedTmuxWindows(socket, session) : defaultTmuxWindows(session));
4637
4678
  return tmuxByEndpoint.get(key);
4638
4679
  };
4639
4680
  const readInstancesOf = (agentDir) => {
@@ -4677,7 +4718,10 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION) {
4677
4718
  // A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
4678
4719
  const liveness = recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(home)))
4679
4720
  ? { running: null, runtimeState: "unsupported", runtimeError: `E_HERDR_REMOVED: ${herdrInstanceRemoved(e.name).message}` }
4680
- : tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name);
4721
+ : tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name, scanOf(home),
4722
+ // A home that records no socket and no launch (--no-launch) reads the default server only
4723
+ // by default: that server's missing socket says nothing about it, and stays "not running".
4724
+ !!meta.tmux?.socket || meta.launched === true);
4681
4725
  const identity = servedIdentityOf(meta);
4682
4726
  // Feature desktop-facts: `startedAt` — the last session start or restart (the receipt's restarts[]),
4683
4727
  // else the spawn's own launch (createdAt), else null (never launched); `identityAddress` — the
@@ -5084,7 +5128,15 @@ function retirementStateRoot(home) {
5084
5128
  // Independent of the bytes it authenticates, but colocated with the agent's
5085
5129
  // already instance-owned storage rather than the source repository or user
5086
5130
  // config home. Retiring <instances>/<name> never removes this sibling.
5087
- return join(dirname(home), ".oats-retirement");
5131
+ return instancesRetirementRoot(dirname(home));
5132
+ }
5133
+ /** The retirement state of the homes in the instances directory `instances`. */
5134
+ function instancesRetirementRoot(instances) {
5135
+ return join(instances, ".oats-retirement");
5136
+ }
5137
+ /** Where retire writes the recovery copies of the homes in the instances directory `instances`. */
5138
+ export function retirementRecoveryRoot(instances) {
5139
+ return join(instancesRetirementRoot(instances), "recovery");
5088
5140
  }
5089
5141
 
5090
5142
  /** A home's identity as a receipt records it: its on-disk spelling, own name included. A home that
@@ -5648,16 +5700,38 @@ function extraWorktreesOf(home) {
5648
5700
  }
5649
5701
  return trees;
5650
5702
  }
5703
+ /** Where retire re-homes the worktrees it retains, one directory per repository under it. */
5704
+ export function retainedWorktreesRoot(workspace) {
5705
+ return join(workspace, ".agents", "worktrees");
5706
+ }
5707
+ /** The longest retained-worktree leaf before its `-N` suffix, in bytes (awebai/oats#821). The
5708
+ * leaf is one path component, so it must fit NAME_MAX (255 on the usual filesystems). 16 bytes
5709
+ * are kept as a margin, as the test fixtures keep: nothing appends to the leaf's name today
5710
+ * (`git worktree move` renames to the path it is given, which does not exist, and adds nothing),
5711
+ * so the margin is headroom only. 8 more are kept for the `-N` suffix (`-` and up to seven
5712
+ * digits). A leaf is then at most 231 bytes, and at most 239 with its suffix. */
5713
+ export const RETAINED_LEAF_MAX = 255 - 16 - 8;
5651
5714
  /** Where a retired worktree is re-homed: `<workspace>/.agents/worktrees/<repoName>/<leaf>`,
5652
- * the leaf being the branch, else `detached-<commit>`; when that exists (or
5653
- * `taken` holds it), `<leaf>-2`, `-3`, … The one naming rule of work/ and of
5654
- * the extra trees. Creates nothing. */
5715
+ * the leaf being the branch, else `detached-<commit>`, with every run of characters outside
5716
+ * `[A-Za-z0-9._-]` made `-`; when that exists (or `taken` holds it), `<leaf>-2`, `-3`, … A leaf
5717
+ * over RETAINED_LEAF_MAX is cut to fit, its trailing `-` trimmed, and followed by `-` and 6 hex
5718
+ * of the SHA-256 of the full branch name: deterministic, readable, and one per branch. The
5719
+ * character class keeps the leaf ASCII, so its length in characters is its length in bytes;
5720
+ * widen the class and the bound must measure bytes. The one naming rule of work/ and of the
5721
+ * extra trees, the plan's `movedTo` and the apply's alike. Creates nothing. */
5655
5722
  function retainedWorktreeDest(workspace, repo, branch, commit, taken = new Set()) {
5656
5723
  const repoName = basename(realPathOrNearest(repo)).replace(/\.git$/, "") || "repo";
5657
- const leaf = (branch ?? `detached-${(commit || "unknown").slice(0, 12)}`).replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "work";
5658
- const retainedRoot = join(workspace, ".agents", "worktrees", repoName);
5659
- let dest = join(retainedRoot, leaf);
5660
- for (let n = 2; existsSync(dest) || taken.has(dest); n++) dest = join(retainedRoot, `${leaf}-${n}`);
5724
+ const name = branch ?? `detached-${(commit || "unknown").slice(0, 12)}`;
5725
+ const flat = name.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "work";
5726
+ const hash = () => createHash("sha256").update(name, "utf8").digest("hex").slice(0, 6);
5727
+ /** The leaf in `room` bytes: as it is when it fits, else cut and hashed. */
5728
+ const fit = (room) => flat.length <= room ? flat : `${flat.slice(0, room - 7).replace(/-+$/, "")}-${hash()}`;
5729
+ const retainedRoot = join(retainedWorktreesRoot(workspace), repoName);
5730
+ let dest = join(retainedRoot, fit(RETAINED_LEAF_MAX));
5731
+ // The 8 bytes kept for `-N` hold `-2` to `-9999999`; a longer suffix takes its extra bytes from
5732
+ // the leaf's readable part, never its hash, so a leaf with its suffix never passes
5733
+ // RETAINED_LEAF_MAX + 8.
5734
+ for (let n = 2; existsSync(dest) || taken.has(dest); n++) dest = join(retainedRoot, `${fit(Math.min(RETAINED_LEAF_MAX, RETAINED_LEAF_MAX + 7 - String(n).length))}-${n}`);
5661
5735
  taken.add(dest);
5662
5736
  return dest;
5663
5737
  }
@@ -5712,7 +5786,7 @@ function retirementBaselineValid(baseline, home) {
5712
5786
  * as not copied (none without a valid baseline). */
5713
5787
  export function retirementRecoveryFacts(home) {
5714
5788
  const baseline = readJsonOrUndefined(findRetirementBaseline(home));
5715
- return { recoveryRoot: join(retirementStateRoot(home), "recovery"), disposableHome: retirementBaselineValid(baseline, home) ? baselineDisposableHome(baseline) : [] };
5789
+ return { recoveryRoot: retirementRecoveryRoot(dirname(home)), disposableHome: retirementBaselineValid(baseline, home) ? baselineDisposableHome(baseline) : [] };
5716
5790
  }
5717
5791
  function writeRetirementBaseline(home, work, mode, capabilities, runtime, { exclusive = false, incarnationId, executionBinding } = {}) {
5718
5792
  if (mode === "directory") assertDirectoryRoots(home);
@@ -5852,21 +5926,104 @@ export function inspectInstanceSession(home) {
5852
5926
  * fallback shell nor a dead pane. Only such a session can be waiting on a human. */
5853
5927
  function harnessRunning(observed) { return observed?.present === true && observed.state !== "shell" && observed.state !== "stopped"; }
5854
5928
 
5855
- /** K3: quiesce one instance's session and RETAIN everything else — home,
5856
- * worktree, transcript, launch configuration — so `restart` can bring it back.
5857
- * Exactly restart's stop half under the same independent endpoint authority
5858
- * (`instanceSessionTarget`), bounded and never escalated: a harness still
5859
- * there after the grace is reported still running, nothing is killed harder.
5860
- * A no-launch or already-idle instance is a no-op that says so. */
5861
- function tmuxServerLost(e) { return /no server running on |(?:error connecting to|failed to connect to) .*(?:No such file or directory|Connection refused)/i.test(String(e.stderr ?? e.message ?? "")); }
5929
+ /** How a failed tmux call reads the server it addressed (#624). "gone": no server listens on the
5930
+ * socket (`no server running on`, or a refused connection), which is definitive. "missing-socket":
5931
+ * the socket file is not there (`No such file or directory`). After a reboot the server is gone,
5932
+ * but a tmux server outlives its removed socket file, so that alone establishes nothing: a caller
5933
+ * concludes stopped from it only when no process works in the home (missingSocketUnestablished).
5934
+ * null: anything else. */
5935
+ function tmuxServerAbsence(e) {
5936
+ const text = String(e?.stderr ?? e?.message ?? "");
5937
+ if (/no server running on |(?:error connecting to|failed to connect to) .*Connection refused/i.test(text)) return "gone";
5938
+ if (/(?:error connecting to|failed to connect to) .*No such file or directory/i.test(text)) return "missing-socket";
5939
+ return null;
5940
+ }
5941
+ function tmuxServerLost(e) { return tmuxServerAbsence(e) !== null; }
5942
+ /** tmux's own way back for a server that lost its socket file (tmux(1), `-S`). Named, never performed. */
5943
+ const TMUX_SOCKET_REMEDY = "tmux recreates a removed socket file when its server process receives SIGUSR1";
5944
+ /** Processes as a refusal names them: pid and program, at most five, then how many more. */
5945
+ function namedProcesses(processes) {
5946
+ return `${processes.slice(0, 5).map((p) => `pid ${p.pid} ${p.command}`).join(", ")}${processes.length > 5 ? `, and ${processes.length - 5} more` : ""}`;
5947
+ }
5948
+ /** A missing socket file (`detail`, tmux's words) checked against `scan`, processesInHome's answer
5949
+ * for the home (#624): null when it ran and found no process there, so the server is taken as gone,
5950
+ * as after a reboot; otherwise why the state is not established. Any process working in the home
5951
+ * counts, a person's shell included: the words name it, so the person can act on it. */
5952
+ function missingSocketUnestablished(detail, scan) {
5953
+ if (!scan.ok) return `${detail}; whether a process still works in this home could not be established (${scan.error})`;
5954
+ if (scan.processes.length) return `${detail}; a process still works in this home (${namedProcesses(scan.processes)}), so its tmux server may still be running without its socket file: ${TMUX_SOCKET_REMEDY}`;
5955
+ return null;
5956
+ }
5957
+ /** Whether this host's /proc can be read: Linux, and this process's own `cwd` link resolves. */
5958
+ function procReadable() {
5959
+ if (process.platform !== "linux") return { ok: false, error: "this host has no /proc to read (it is not Linux)" };
5960
+ try { readlinkSync("/proc/self/cwd"); return { ok: true }; }
5961
+ catch (e) { return { ok: false, error: `/proc/self/cwd cannot be read (${e.code || e.message})` }; }
5962
+ }
5963
+ /** Which process scan this host offers, checked cheaply and without scanning (doctor reports it):
5964
+ * /proc on Linux, else lsof when it is on PATH. → { mechanism: "proc" | "lsof" } | { mechanism: null, error } */
5965
+ export function processScanAvailability() {
5966
+ const proc = procReadable();
5967
+ if (proc.ok) return { mechanism: "proc" };
5968
+ if (process.env.PATH !== undefined && lookupOnPath("lsof", process.env.PATH)) return { mechanism: "lsof" };
5969
+ return { mechanism: null, error: `${proc.error}, and lsof is not on PATH` };
5970
+ }
5971
+ /** Doctor's information line when this host has no process scan (`availability`, from
5972
+ * processScanAvailability); none when it has one. */
5973
+ export function processScanInformation(availability = processScanAvailability()) {
5974
+ if (availability.mechanism) return [];
5975
+ return [`process-scan-unavailable: ${availability.error}; retire refuses where it must rule out a live process in an instance home (a home without its session receipt, a missing recorded tmux socket, a Herdr home), and session start/stop refuse when a recorded tmux socket is missing; install lsof`];
5976
+ }
5862
5977
  /**
5863
- * The live processes (other than this one and its children) whose working
5864
- * directory is inside `home`: `lsof -a -d cwd` over the host, one call.
5865
- * → { ok: true, processes: [{pid, command}] } | { ok: false, error } (the scan
5866
- * could not run, did not complete or listed no process: a caller must treat
5867
- * that as unknown, never as none).
5978
+ * Every live process on the host (other than this one and its direct children) with its working
5979
+ * directory, from one scan: /proc on Linux (`io.procRoot` names another root), else one `lsof -a -d
5980
+ * cwd` listing; an injected `io.exec` stands in for the host's commands, so it is lsof's. Each cwd
5981
+ * is kept in its on-disk spelling (canonicalHomePath); one the kernel reports deleted (`<path>
5982
+ * (deleted)`) is kept as both spellings. A process this user may not inspect (another user's, or a
5983
+ * non-dumpable one) is not seen by either mechanism.
5984
+ * → { ok: true, processes: [{pid, command, cwds}] } | { ok: false, error }
5868
5985
  */
5869
- export function processesInHome(home, io) {
5986
+ function hostProcesses(io) {
5987
+ const rows = typeof io?.procRoot === "string" ? procRows(io.procRoot)
5988
+ : !io?.exec && procReadable().ok ? procRows("/proc")
5989
+ : lsofRows(io);
5990
+ if (!rows.ok) return rows;
5991
+ const processes = [];
5992
+ for (const { pid, ppid, command, cwd } of rows.rows) {
5993
+ if (!pid || pid === process.pid || ppid === process.pid || typeof cwd !== "string") continue;
5994
+ const spellings = cwd.endsWith(" (deleted)") ? [cwd, cwd.slice(0, -" (deleted)".length)] : [cwd];
5995
+ processes.push({ pid, command: command ?? "?", cwds: spellings.map((p) => canonicalHomePath(p)) });
5996
+ }
5997
+ return { ok: true, processes };
5998
+ }
5999
+ /** The processes of a hostProcesses listing that work in `home`, compared in its on-disk spelling. */
6000
+ function processesWorkingIn(processes, home) {
6001
+ const realHome = canonicalHomePath(home);
6002
+ return processes.filter((p) => p.cwds.some((cwd) => cwd === realHome || cwd.startsWith(`${realHome}/`))).map(({ pid, command }) => ({ pid, command }));
6003
+ }
6004
+ /** /proc read as a scan: each numeric entry's `cwd` link, `comm` and `stat` (its ppid is the second
6005
+ * field after the last `)`, which ends the command). A pid that cannot be read (it ended meanwhile,
6006
+ * this user may not inspect it, or any other failure on that one pid) is not seen. A root that
6007
+ * cannot be listed, or one that lists no readable process, is a failed scan, never an empty one. */
6008
+ function procRows(root) {
6009
+ let names;
6010
+ try { names = readdirSync(root); }
6011
+ catch (e) { return { ok: false, error: `${root} cannot be read (${e.code || e.message})` }; }
6012
+ const rows = [];
6013
+ for (const name of names) {
6014
+ if (!/^\d+$/.test(name)) continue;
6015
+ try {
6016
+ const cwd = readlinkSync(join(root, name, "cwd"));
6017
+ const command = readFileSync(join(root, name, "comm"), "utf8").replace(/\n$/, "");
6018
+ const stat = readFileSync(join(root, name, "stat"), "utf8");
6019
+ rows.push({ pid: Number(name), ppid: Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]), command, cwd });
6020
+ } catch { /* not seen */ }
6021
+ }
6022
+ // A real /proc always lists at least this process.
6023
+ if (!rows.length) return { ok: false, error: `${root} listed no process` };
6024
+ return { ok: true, rows };
6025
+ }
6026
+ function lsofRows(io) {
5870
6027
  let out;
5871
6028
  try { out = (io?.exec || execFileSync)("lsof", ["-a", "-d", "cwd", "-F", "pRcn", "-w"], { encoding: "utf8", timeout: 20000, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }); }
5872
6029
  catch (e) {
@@ -5877,7 +6034,7 @@ export function processesInHome(home, io) {
5877
6034
  // listing.
5878
6035
  const completed = e?.status === 1 && e.signal == null && e.code === undefined;
5879
6036
  if (completed && typeof e.stdout === "string") out = e.stdout;
5880
- else return { ok: false, error: e?.code === "ENOENT" ? "lsof is not on PATH"
6037
+ else return { ok: false, error: e?.code === "ENOENT" ? "lsof is not on PATH; install lsof"
5881
6038
  : e?.code === "ETIMEDOUT" ? "lsof timed out"
5882
6039
  : e?.code === "ENOBUFS" ? "lsof printed more output than the scan reads"
5883
6040
  : e?.signal ? `lsof was ended by ${e.signal}`
@@ -5885,21 +6042,27 @@ export function processesInHome(home, io) {
5885
6042
  }
5886
6043
  // A listing holds at least one process (lsof and its caller are always in it), whichever exit it came with.
5887
6044
  if (!/^p\d+$/m.test(String(out))) return { ok: false, error: "lsof listed no process" };
5888
- // lsof reports each cwd in its on-disk spelling: the home is compared in it too.
5889
- const realHome = canonicalHomePath(home);
5890
- const processes = [];
6045
+ const rows = [];
5891
6046
  let cur = {};
5892
6047
  for (const line of String(out).split("\n")) {
5893
6048
  const tag = line[0], value = line.slice(1);
5894
- if (tag === "p") cur = { pid: Number(value) };
6049
+ if (tag === "p") { cur = { pid: Number(value) }; rows.push(cur); }
5895
6050
  else if (tag === "R") cur.ppid = Number(value);
5896
6051
  else if (tag === "c") cur.command = value;
5897
- else if (tag === "n" && cur.pid && cur.pid !== process.pid && cur.ppid !== process.pid) {
5898
- const cwd = canonicalHomePath(value);
5899
- if (cwd === realHome || cwd.startsWith(`${realHome}/`)) processes.push({ pid: cur.pid, command: cur.command ?? "?" });
5900
- }
6052
+ else if (tag === "n") cur.cwd = value;
5901
6053
  }
5902
- return { ok: true, processes };
6054
+ return { ok: true, rows };
6055
+ }
6056
+ /**
6057
+ * The live processes (other than this one and its direct children) whose working directory is
6058
+ * inside `home`, from one scan of the host (hostProcesses: /proc on Linux, else lsof). A pid and a
6059
+ * program name, never an argument list.
6060
+ * → { ok: true, processes: [{pid, command}] } | { ok: false, error } (the scan could not run, did
6061
+ * not complete or listed no process: a caller must treat that as unknown, never as none).
6062
+ */
6063
+ export function processesInHome(home, io) {
6064
+ const scan = hostProcesses(io);
6065
+ return scan.ok ? { ok: true, processes: processesWorkingIn(scan.processes, home) } : scan;
5903
6066
  }
5904
6067
 
5905
6068
  /**
@@ -5920,7 +6083,7 @@ export function observeSessionWithoutReceipt(home, meta, io) {
5920
6083
  if (!recorded.absent) return recorded;
5921
6084
  const scan = processesInHome(home, io);
5922
6085
  if (!scan.ok) return { absent: false, backend: recorded.backend, note: `could not scan for a process working in this home (${scan.error})` };
5923
- if (scan.processes.length) return { absent: false, backend: recorded.backend, note: `a process works in this home (${scan.processes.slice(0, 5).map((p) => `pid ${p.pid} ${p.command}`).join(", ")}${scan.processes.length > 5 ? `, and ${scan.processes.length - 5} more` : ""}); stop it, then retire` };
6086
+ if (scan.processes.length) return { absent: false, backend: recorded.backend, note: `a process works in this home (${namedProcesses(scan.processes)}); stop it, then retire` };
5924
6087
  return recorded;
5925
6088
  }
5926
6089
  function recordedSessionAbsence(home, meta, io) {
@@ -5943,6 +6106,13 @@ function recordedSessionAbsence(home, meta, io) {
5943
6106
  if (inHome) return { absent: false, backend: "tmux", note: `a tmux pane (${inHome[0]}:${inHome[1]}) on ${tmux.socket} works in this home` };
5944
6107
  return { absent: true, backend: "tmux", note: `no session receipt (a home from before 0.25.9); the recorded window ${where} is gone` };
5945
6108
  }
6109
+ /** K3: quiesce one instance's session and RETAIN everything else — home,
6110
+ * worktree, transcript, launch configuration — so `restart` can bring it back.
6111
+ * Exactly restart's stop half under the same independent endpoint authority
6112
+ * (`instanceSessionTarget`), bounded and never escalated: a harness still
6113
+ * there after the grace is reported still running, nothing is killed harder.
6114
+ * A no-launch or already-idle instance is a no-op that says so. A missing socket
6115
+ * file is idle only when no process works in the home (#624). */
5946
6116
  export function stopInstanceSession(home, o = {}) {
5947
6117
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session stop needs an absolute instance home");
5948
6118
  if (o.graceMs !== undefined && (!Number.isSafeInteger(o.graceMs) || o.graceMs < 1 || o.graceMs > 300000)) throw oatsError("E_BAD_ARGS", "stop grace must be 1-300000 ms");
@@ -5952,7 +6122,12 @@ export function stopInstanceSession(home, o = {}) {
5952
6122
  if (!s.target) return { home: s.home, backend: null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
5953
6123
  let before;
5954
6124
  try { before = inspectSessionTarget(s.target); }
5955
- catch (e) { if (tmuxServerLost(e)) before = { present: false, state: "stopped" }; else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${e.message}`); }
6125
+ catch (e) {
6126
+ const absence = tmuxServerAbsence(e);
6127
+ const why = absence === "missing-socket" ? missingSocketUnestablished(tmuxFailure(e, e.message), processesInHome(realHome, o.io)) : null;
6128
+ if (absence && !why) before = { present: false, state: "stopped" };
6129
+ else throw oatsError("E_SESSION_UNAVAILABLE", `cannot establish whether ${basename(realHome)} is running, so nothing was stopped: ${why ?? e.message}`);
6130
+ }
5956
6131
  if (!before.present || before.state === "shell" || before.state === "stopped") return { home: s.home, backend: s.target.backend, stopped: false, alreadyIdle: true, state: before.state, receipt: null };
5957
6132
  const receipt = stopHarness(s.target, { graceMs: o.graceMs ?? 20000, kill: o.io?.kill, sleep: o.io?.sleep });
5958
6133
  writeJsonAtomic(join(realHome, ".oats-stop.json"), { instance: basename(realHome), at: new Date().toISOString(), stop: receipt, retained: ["home", "work", "transcript", "launch"] });
@@ -6359,7 +6534,16 @@ export function startInstanceSession(home, o = {}) {
6359
6534
  // spawned records no modules, and there is no scope configuration left to
6360
6535
  // re-resolve it against. Retire still works on it.
6361
6536
  if (!isWorkspaceHome(readMeta())) throw preWorkspaceHome(realHome, "nothing was started");
6362
- const lostTmuxServer = tmuxServerLost;
6537
+ // A missing socket file is a stopped server only when no process works in this home (#624): its
6538
+ // check, for a recorded session and for the OATS server lookup. A failed read of a recorded session
6539
+ // is `{ stopped: true }` when its server is gone (or its socket file is missing and that check
6540
+ // passes), else `{ stopped: false, why }`: the check's reason, or null for another failure.
6541
+ const missingSocket = (detail) => missingSocketUnestablished(detail, processesInHome(realHome, rawIo));
6542
+ const lostServer = (e) => {
6543
+ const absence = tmuxServerAbsence(e);
6544
+ const why = absence === "missing-socket" ? missingSocket(tmuxFailure(e, e.message)) : null;
6545
+ return absence && !why ? { stopped: true } : { stopped: false, why };
6546
+ };
6363
6547
  const launchFailure = (error) => {
6364
6548
  // execFileSync errors embed argv (including capability environment) in
6365
6549
  // message; backend stderr can echo it too. Neither belongs in the API.
@@ -6435,8 +6619,9 @@ export function startInstanceSession(home, o = {}) {
6435
6619
  checkRoots();
6436
6620
  try { st = inspectSessionTarget(pending.target, o.io); }
6437
6621
  catch (e) {
6438
- if (lostTmuxServer(e)) st = { present: false, state: "stopped" };
6439
- else throw oatsError("E_SESSION_UNKNOWN", `an earlier start of ${basename(realHome)} recorded a session (tmux ${pending.target.session}:${pending.target.window} on ${pending.target.socket}) that cannot be observed now: ${String(e.stderr ?? e.message ?? "").trim() || e.message}; the receipt ${pendingPath} is kept and nothing was started`);
6622
+ const lost = lostServer(e);
6623
+ if (lost.stopped) st = { present: false, state: "stopped" };
6624
+ else throw oatsError("E_SESSION_UNKNOWN", `an earlier start of ${basename(realHome)} recorded a session (tmux ${pending.target.session}:${pending.target.window} on ${pending.target.socket}) that cannot be observed now: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}; the receipt ${pendingPath} is kept and nothing was started`);
6440
6625
  }
6441
6626
  // A launch may still consist entirely of shells (startup files, a
6442
6627
  // shell-script harness). Only its own completion marker proves this
@@ -6512,18 +6697,19 @@ export function startInstanceSession(home, o = {}) {
6512
6697
  const planSession = receipt.target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
6513
6698
  let sessionPlanRead;
6514
6699
  const sessionPlan = () => {
6515
- if (!sessionPlanRead) { try { sessionPlanRead = { plan: planOatsTmuxSession(planSession, o.io) }; } catch (e) { sessionPlanRead = { error: e }; } }
6700
+ if (!sessionPlanRead) { try { sessionPlanRead = { plan: planOatsTmuxSession(planSession, o.io, { missingSocket }) }; } catch (e) { sessionPlanRead = { error: e }; } }
6516
6701
  if (sessionPlanRead.error) throw sessionPlanRead.error;
6517
6702
  return sessionPlanRead.plan;
6518
6703
  };
6519
6704
  // The recorded target, observed once: by the plan's lookup, which must know whether the pane will
6520
- // be reused before it chooses where to look, or by the gate below. A lost server is a stopped one;
6521
- // any other failure is the gate's refusal (E_SESSION_UNKNOWN), and the lookup does not decide it.
6705
+ // be reused before it chooses where to look, or by the gate below. A lost server is a stopped one
6706
+ // (lostServer); any other failure is the gate's refusal (E_SESSION_UNKNOWN), and the lookup does
6707
+ // not decide it.
6522
6708
  let recordedRead;
6523
6709
  const recordedState = () => {
6524
6710
  if (!recordedRead) {
6525
6711
  try { recordedRead = { state: receipt.target ? inspectSessionTarget(receipt.target, o.io) : { present: false, state: "not-launched" } }; }
6526
- catch (e) { recordedRead = lostTmuxServer(e) ? { state: { present: false, state: "stopped" } } : { error: e }; }
6712
+ catch (e) { const lost = lostServer(e); recordedRead = lost.stopped ? { state: { present: false, state: "stopped" } } : { error: lost.why ? new Error(lost.why) : e }; }
6527
6713
  }
6528
6714
  return recordedRead;
6529
6715
  };
@@ -6553,7 +6739,7 @@ export function startInstanceSession(home, o = {}) {
6553
6739
  const recorded = recordedState();
6554
6740
  if (reusable(recorded.state)) return panePath(receipt.target.socket, receipt.target.session, o.io, realHome);
6555
6741
  if (recorded.error) return undefined; // the gate refuses below; the lookup does not decide it
6556
- const preview = planOatsTmuxSession(planSession, o.io, { preview: true });
6742
+ const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
6557
6743
  if (!preview || preview.server) return expectedPanePath(preview, planSession, o.io, realHome);
6558
6744
  try { return expectedPanePath(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (oatsCoded(e)) return undefined; throw e; }
6559
6745
  };
@@ -6662,7 +6848,12 @@ export function startInstanceSession(home, o = {}) {
6662
6848
  writeJsonAtomic(join(realHome, ".oats-restart.json"), { instance: meta.instance, at: new Date().toISOString(), stop: stopReceipt, next: { harness: launchPlan?.harness || harness, launchConfig: launchPlan?.recipe?.launchConfig ?? meta.launch?.launchConfig ?? null, model: model ?? null } }, 0o600);
6663
6849
  appendEvent(realHome, { kind: stopReceipt.exited ? "restarted" : "stop-refused", data: { phase: "restart-stop", signal: stopReceipt.signal, waitedMs: stopReceipt.waitedMs, stillRunning: stopReceipt.stillRunning ?? [] } });
6664
6850
  if (!stopReceipt.exited) throw oatsError("E_SESSION_STOP_FAILED", `${meta.instance} was asked to stop (${stopReceipt.signal} to ${stopReceipt.requested.map((r) => `${r.comm} pid ${r.pid}`).join(", ")} at ${stopReceipt.sentAt}) and was still running after ${stopReceipt.waitedMs} ms (${stopReceipt.state}); nothing was escalated and nothing was started; stop it yourself, or retry with a longer --stop-grace. Receipt: ${join(realHome, ".oats-restart.json")}`);
6665
- try { state = inspectSessionTarget(target, o.io); } catch (e) { if (lostTmuxServer(e)) state = { present: false, state: "stopped" }; else throw oatsError("E_SESSION_UNKNOWN", `after the stop, cannot establish the state of ${meta.instance}: ${String(e.stderr ?? e.message ?? "").trim() || e.message}`); }
6851
+ try { state = inspectSessionTarget(target, o.io); }
6852
+ catch (e) {
6853
+ const lost = lostServer(e);
6854
+ if (lost.stopped) state = { present: false, state: "stopped" };
6855
+ else throw oatsError("E_SESSION_UNKNOWN", `after the stop, cannot establish the state of ${meta.instance}, so nothing was started: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}`);
6856
+ }
6666
6857
  if (state.present && state.state !== "shell") throw oatsError("E_SESSION_UNKNOWN", `${meta.instance} read as stopped and then as ${state.state} again; nothing was started`);
6667
6858
  }
6668
6859
  // The kernel that launches the harness is the one the agent's plain `oats` runs.
@@ -6710,7 +6901,7 @@ export function startInstanceSession(home, o = {}) {
6710
6901
  // A replacement window (never launched, recorded window gone, recorded server gone) is created
6711
6902
  // on the OATS server, wherever the home was recorded: one socket from here to the record.
6712
6903
  const recordedSocket = socket ? resolve(socket) : null;
6713
- socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan);
6904
+ socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket);
6714
6905
  if (lookAgain(() => panePath(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
6715
6906
  let names;
6716
6907
  try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
@@ -7237,7 +7428,7 @@ function mirrorTopLevel(source, dest) {
7237
7428
  for (const e of entriesAsBytes(source)) if (!e.name.equals(GIT_NAME)) copyTreeSafe(joinBytes(source, e.name), joinBytes(dest, e.name));
7238
7429
  }
7239
7430
 
7240
- const RECOVERABLE_GIT_ADMIN = [
7431
+ export const RECOVERABLE_GIT_ADMIN = [
7241
7432
  "MERGE_HEAD", "MERGE_MSG", "AUTO_MERGE", "CHERRY_PICK_HEAD", "REVERT_HEAD", "REBASE_HEAD",
7242
7433
  "BISECT_LOG", "BISECT_START", "BISECT_NAMES", "rebase-apply", "rebase-merge", "sequencer",
7243
7434
  ];
@@ -7738,7 +7929,9 @@ function homeOnlyRecovery(observation, meta) {
7738
7929
  * (tree-copy.mjs), and a read-only one (a Go module cache, 0555) keeps
7739
7930
  * rmSync from unlinking what is in it: each directory is made u+rwx first,
7740
7931
  * before it is read (an unreadable one could not be listed), symbolic links
7741
- * are never followed, and then the tree is removed. Never throws: a cleanup
7932
+ * are never followed, and then the tree is removed. Names are listed and
7933
+ * joined as bytes, as the copier writes them, so a directory whose name is
7934
+ * not UTF-8 is reached too (#827). Never throws: a cleanup
7742
7935
  * must not replace the error that made it (#659). → null when the staging is
7743
7936
  * gone, else the clause a refusal adds to name what is left. */
7744
7937
  function removeStaging(staging) {
@@ -7748,9 +7941,9 @@ function removeStaging(staging) {
7748
7941
  const st = lstatSync(dir);
7749
7942
  if (!st.isDirectory()) return;
7750
7943
  if ((st.mode & 0o700) !== 0o700) chmodSync(dir, (st.mode & 0o7777) | 0o700);
7751
- names = readdirSync(dir);
7944
+ names = entriesAsBytes(dir).map((e) => e.name);
7752
7945
  } catch { return; }
7753
- for (const name of names) open(join(dir, name));
7946
+ for (const name of names) open(joinBytes(dir, name));
7754
7947
  };
7755
7948
  try { open(staging); rmSync(staging, { recursive: true, force: true }); } catch { /* named below */ }
7756
7949
  try { lstatSync(staging); } catch (e) { if (e?.code === "ENOENT") return null; }
@@ -7764,7 +7957,7 @@ function removeStaging(staging) {
7764
7957
  * will add to. → { receipt, manifest }: the receipt retire reports, and
7765
7958
  * recovery.json as written. */
7766
7959
  function writeRetirementRecovery(observation, meta, instance, phase) {
7767
- const recoveryRoot = join(retirementStateRoot(observation.home), "recovery");
7960
+ const recoveryRoot = retirementRecoveryRoot(dirname(observation.home));
7768
7961
  mkdirSync(recoveryRoot, { recursive: true });
7769
7962
  if (observation.directory && realpathSync(recoveryRoot) !== join(realpathSync(dirname(observation.home)), ".oats-retirement", "recovery")) {
7770
7963
  throw oatsError("E_WORK_PRESERVATION_FAILED", "directory recovery storage was redirected; retain the source home rather than copying into an unowned or disposable location");
@@ -8287,15 +8480,14 @@ export function retireInstance(root, name, o = {}) {
8287
8480
  } catch (e) {
8288
8481
  const detail = String(e.stderr ?? e.message ?? "").trim();
8289
8482
  const unestablished = (why) => oatsError("E_RUNTIME_QUIESCE_FAILED", `could not establish that ${runtimeSession}:${runtimeWindow} stopped on ${runtimeSocket}: ${why}`);
8290
- if (!/no server running|failed to connect|can't find session|no sessions/i.test(detail)) {
8291
- if (!tmuxServerLost(e)) throw unestablished(detail || "tmux inspection failed");
8292
- // A server that cannot be reached, typically because its socket file is missing (a reboot clears
8293
- // tmux's socket directory). A server outlives its socket file, so that alone does not say the
8294
- // window is gone: it is taken as gone only when no process works in the home, as for a home
8295
- // without its receipt.
8296
- const scan = processesInHome(found.home);
8297
- if (!scan.ok) throw unestablished(`${detail}; whether a process still works in this home could not be established (${scan.error})`);
8298
- if (scan.processes.length) throw unestablished(`${detail}; a process still works in this home (${scan.processes.slice(0, 5).map((p) => `pid ${p.pid} ${p.command}`).join(", ")}${scan.processes.length > 5 ? `, and ${scan.processes.length - 5} more` : ""})`);
8483
+ if (!/no server running|can't find session|no sessions/i.test(detail)) {
8484
+ const absence = tmuxServerAbsence(e);
8485
+ if (!absence) throw unestablished(detail || "tmux inspection failed");
8486
+ // A missing socket file, in any tmux's words (a reboot clears tmux's socket directory). A server
8487
+ // outlives its socket file, so that alone does not say the window is gone: it is taken as gone
8488
+ // only when no process works in the home, as for a home without its receipt (#624).
8489
+ const why = absence === "missing-socket" ? missingSocketUnestablished(detail, processesInHome(found.home)) : null;
8490
+ if (why) throw unestablished(why);
8299
8491
  }
8300
8492
  }
8301
8493
  sessionStopped = true;