@awebai/oats 0.68.1 → 0.69.2

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 (99) hide show
  1. package/bin/oats.mjs +180 -36
  2. package/docs/capabilities.md +73 -10
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/configuration.md +68 -2
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
  6. package/docs/design/2026-10-22-module-upgrade.md +1 -1
  7. package/docs/desktop-cli-api.md +600 -25
  8. package/docs/desktop-instance-start.md +59 -3
  9. package/docs/desktop.md +175 -10
  10. package/docs/execution-targets.md +536 -62
  11. package/docs/harness-trust.md +3 -1
  12. package/docs/implementation.md +33 -15
  13. package/docs/integrations.md +2 -2
  14. package/docs/knowledge.md +25 -16
  15. package/docs/oats-local.schema.json +2 -2
  16. package/docs/official-catalog.md +6 -5
  17. package/docs/packages.md +14 -14
  18. package/docs/release-notes/v0.69.0.md +658 -0
  19. package/docs/release-notes/v0.69.1.md +25 -0
  20. package/docs/release-notes/v0.69.2.md +259 -0
  21. package/docs/servers.md +51 -7
  22. package/docs/soul.schema.json +1 -0
  23. package/docs/souls-and-instances.md +46 -9
  24. package/docs/tui.md +177 -21
  25. package/docs/upgrading.md +16 -7
  26. package/docs/workspaces.md +2 -2
  27. package/injects/instance-boundary.md +19 -33
  28. package/injects/work-attached.md +8 -13
  29. package/injects/work-checkout.md +16 -30
  30. package/injects/work-directory.md +9 -15
  31. package/injects/work-workspace.md +8 -19
  32. package/injects/work-worktree.md +18 -33
  33. package/lib/capability-contract.mjs +2 -2
  34. package/lib/core.mjs +496 -127
  35. package/lib/file-pieces.mjs +49 -0
  36. package/lib/instance-background.mjs +54 -0
  37. package/lib/instance-events.mjs +25 -4
  38. package/lib/instance-inspect.mjs +3 -0
  39. package/lib/instance-lifecycle.mjs +35 -0
  40. package/lib/instance-resolution.mjs +3 -2
  41. package/lib/instance-same-work.mjs +67 -0
  42. package/lib/instance-upgrade.mjs +18 -0
  43. package/lib/launch-prompt-fixtures/README.md +62 -0
  44. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  45. package/lib/launch-prompt-fixtures.mjs +49 -0
  46. package/lib/launch-prompt-resume.mjs +55 -0
  47. package/lib/login-environment.mjs +27 -9
  48. package/lib/materialize.mjs +23 -2
  49. package/lib/resolve.mjs +32 -5
  50. package/lib/schedule.mjs +3 -3
  51. package/lib/servers.mjs +136 -27
  52. package/lib/session-end.mjs +82 -0
  53. package/lib/session-input.mjs +43 -9
  54. package/lib/session-resume-contract.mjs +33 -0
  55. package/lib/session-resume.mjs +337 -0
  56. package/lib/session-seen.mjs +163 -0
  57. package/lib/session-viewer.mjs +147 -44
  58. package/lib/soul-composition.mjs +15 -11
  59. package/lib/start-env.mjs +110 -0
  60. package/lib/tmux-server-scope.mjs +139 -14
  61. package/lib/workspace.mjs +41 -6
  62. package/package-catalog.json +11 -5
  63. package/package.json +1 -1
  64. package/packages/client/cli-adapter.mjs +39 -8
  65. package/packages/client/cli-locator.mjs +3 -2
  66. package/packages/client/deployment-data.mjs +16 -0
  67. package/packages/client/deployment-panel.mjs +7 -0
  68. package/packages/client/file-output-exec.mjs +98 -0
  69. package/packages/client/instance-tree.mjs +64 -14
  70. package/packages/client/launch-prompt-outcome.mjs +25 -13
  71. package/packages/client/own-codes.mjs +2 -0
  72. package/packages/client/panel-views.mjs +11 -3
  73. package/packages/client/remote-roster.mjs +5 -1
  74. package/packages/client/roster-sections.mjs +50 -6
  75. package/packages/client/same-work.mjs +49 -0
  76. package/packages/client/session-attach.mjs +35 -5
  77. package/packages/client/session-resume-cli.mjs +64 -0
  78. package/packages/client/session-resume-trigger.mjs +167 -0
  79. package/packages/client/session-resume.mjs +332 -0
  80. package/packages/client/soul-rows.mjs +2 -0
  81. package/packages/client/spawn-apply-contract.mjs +2 -1
  82. package/packages/client/spawn-decision.mjs +4 -1
  83. package/packages/client/spawn-preview-contract.mjs +12 -1
  84. package/packages/client/spawn-preview.mjs +2 -0
  85. package/packages/client/tmux-status.mjs +30 -7
  86. package/packages/client/waiting-on-you.mjs +11 -4
  87. package/packages/client/workspace-step.mjs +17 -5
  88. package/packages/record/lib/last-conversation.mjs +123 -0
  89. package/packages/record/lib/session-roots.mjs +10 -1
  90. package/packages/tui/README.md +2 -2
  91. package/packages/tui/lib/client.mjs +7 -3
  92. package/packages/tui/lib/main.mjs +49 -14
  93. package/packages/tui/lib/model.mjs +146 -55
  94. package/packages/tui/lib/store.mjs +84 -27
  95. package/packages/tui/lib/term/text.mjs +12 -9
  96. package/packages/tui/lib/views/frame.mjs +74 -7
  97. package/packages/tui/lib/views/help.mjs +10 -3
  98. package/packages/tui/lib/views/instances.mjs +41 -3
  99. package/skills/oats-getting-started/SKILL.md +117 -4
@@ -14,11 +14,35 @@ function tmux(target, args, { exec = execFileSync, input, timeout = 10000, killS
14
14
  stdio: ["pipe", "pipe", "pipe"],
15
15
  });
16
16
  }
17
+ /** The tmux pane option OATS sets on the agent's pane whenever it creates or respawns it, its value
18
+ * the instance's window name (the instance name). Internal: what OATS sets, not an API (#1569). */
19
+ export const AGENT_PANE_OPTION = "@oats-agent";
20
+ const paneNumber = (paneId) => Number(paneId.slice(1));
21
+ /** Which of a window's panes is the agent's (#1569), the one rule every reader applies (the client's
22
+ * tmux-status keeps a copy, held to this one by a parity test). `panes`: the window's panes, each
23
+ * `{ paneId: "%N", mark }` (`mark`: the pane's AGENT_PANE_OPTION, "" when unset; any other field is
24
+ * carried along); `name`: the instance's window name. One pane is the agent's, mark or not. Of
25
+ * several: the one marked with `name`; else, when none is, the unmarked pane with the lowest id
26
+ * (tmux's creation order: the window's own pane, before any split of it). A pane marked with another
27
+ * name is never the agent's. → `{ pane }` (the element itself, null for no panes), or `{ error }`
28
+ * when it cannot tell: the sentence every refusal and status's `runtimeError` carry. */
29
+ export function resolveAgentPane(panes, name) {
30
+ if (panes.length <= 1) return { pane: panes[0] ?? null };
31
+ const byId = [...panes].sort((a, b) => paneNumber(a.paneId) - paneNumber(b.paneId));
32
+ const ids = (list) => list.map((p) => p.paneId).join(", ");
33
+ const ours = byId.filter((p) => p.mark === name);
34
+ if (ours.length === 1) return { pane: ours[0] };
35
+ if (ours.length > 1) return { error: `the window has ${ours.length} panes marked as ${name}'s agent pane (${ids(ours)}); close all but the agent's with tmux kill-pane -t <id>, or close the window and start the instance` };
36
+ const unmarked = byId.find((p) => !p.mark);
37
+ if (unmarked) return { pane: unmarked };
38
+ return { error: `the window has ${byId.length} panes and none is ${name}'s agent pane (${ids(byId)}); close the panes that aren't, or close the window and start the instance` };
39
+ }
17
40
  // Public inspection opts into window geometry; input and other session operations
18
41
  // retain their existing transport result and do not depend on size parsing.
19
- export function inspectSessionTarget(target, io, { includeSize = false } = {}) {
42
+ // `includePanes` adds `panes`, the window's pane count (the viewer selects the agent's pane in a split window).
43
+ export function inspectSessionTarget(target, io, { includeSize = false, includePanes = false } = {}) {
20
44
  const format = "#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"
21
- + (includeSize ? "\t#{window_width}\t#{window_height}" : "");
45
+ + (includeSize ? "\t#{window_width}\t#{window_height}" : "") + `\t#{${AGENT_PANE_OPTION}}`;
22
46
  let rows;
23
47
  try {
24
48
  const output = tmux(target, ["list-panes", "-t", `=${target.session}:=${target.window}`, "-F", format], io);
@@ -29,10 +53,14 @@ export function inspectSessionTarget(target, io, { includeSize = false } = {}) {
29
53
  if (/can't find (window|session)/i.test(String(e.stderr || ""))) return { backend: "tmux", present: false, state: "stopped" };
30
54
  throw e;
31
55
  }
32
- return createSessionPaneInspector(io)(rows, { includeSize });
56
+ const state = createSessionPaneInspector(io)(rows, { includeSize, name: target.window });
57
+ return includePanes ? { ...state, panes: rows.length } : state;
33
58
  }
34
- /** Interpret one window's panes with the lifecycle's shell/descendant rule. A status read shares
35
- * one inspector across windows so both successful and failed process scans cost one child. */
59
+ /** Interpret one window's panes: resolve the agent's pane (resolveAgentPane, `name` the window's
60
+ * instance name), then judge that pane alone with the lifecycle's shell/descendant rule; the other
61
+ * panes never make it unknown. Each row is `id, dead, command, pid[, cols, rows], mark` (the mark may
62
+ * be missing). A status read shares one inspector across windows so both successful and failed
63
+ * process scans cost one child. */
36
64
  export function createSessionPaneInspector(io) {
37
65
  let processRead;
38
66
  const readProcesses = () => {
@@ -47,11 +75,17 @@ export function createSessionPaneInspector(io) {
47
75
  if (processRead.error) throw processRead.error;
48
76
  return processRead.rows;
49
77
  };
50
- return (rows, { includeSize = false } = {}) => {
78
+ return (rows, { includeSize = false, name } = {}) => {
51
79
  if (!rows.length) return { backend: "tmux", present: false, state: "stopped" };
52
- if (rows.length !== 1) throw new Error("session window has multiple panes; choose an unsplit agent window");
53
- const [paneId, dead, command, panePid, cols, rowsCount] = rows[0].split("\t");
54
- if (!/^%\d+$/.test(paneId) || !["0", "1"].includes(dead)) throw new Error("invalid tmux pane response");
80
+ const panes = rows.map((row) => {
81
+ const fields = row.split("\t");
82
+ if (!/^%\d+$/.test(fields[0])) throw new Error("invalid tmux pane response");
83
+ return { paneId: fields[0], mark: fields[includeSize ? 6 : 4] ?? "", fields };
84
+ });
85
+ const { pane, error } = resolveAgentPane(panes, name);
86
+ if (error) throw new Error(error);
87
+ const [paneId, dead, command, panePid, cols, rowsCount] = pane.fields;
88
+ if (!["0", "1"].includes(dead)) throw new Error("invalid tmux pane response");
55
89
  if (includeSize && ![cols, rowsCount].every(value => /^[1-9]\d*$/.test(value) && Number.isSafeInteger(Number(value)))) {
56
90
  throw new Error("invalid tmux pane response");
57
91
  }
@@ -0,0 +1,33 @@
1
+ /** The names of the session-resume contract (feature session-resume, #1559): the strings a client
2
+ * reads in `sessionEnd`, in a `session start --resume` answer's `resume` object and in the rows of
3
+ * `oats session resume` (docs/desktop-cli-api.md). Both product sides settle them together
4
+ * (awebai/oats#1567): every producer, reader, test and doc takes them from here, so a change is made
5
+ * in one place. Each shape has one producer: `sessionEnd` lib/session-end.mjs `sessionEndOf`; the
6
+ * start's `resume` object lib/core.mjs `resumeAnswer`; the sweep's rows lib/session-resume.mjs
7
+ * (`rowFromStart`, `predicted` and the rows it answers without a start). Dependency-free. */
8
+
9
+ export const SESSION_RESUME_FEATURE = "session-resume";
10
+
11
+ /** `sessionEnd` on an `oats status --json` row of a launched home that does not run. */
12
+ export const SESSION_END = Object.freeze({ LOST: "lost", STOPPED: "stopped", EXITED: "exited" });
13
+
14
+ /** `resume.reason` of a start that opened a fresh conversation instead of continuing one; a sweep
15
+ * row `fresh` carries it as its `reason`. */
16
+ export const FRESH_REASON = Object.freeze({ NO_CONVERSATION: "no-conversation", NO_RECEIPTS: "no-receipts", RESUME_UNPROVEN: "resume-unproven" });
17
+
18
+ /** `resume.waiting` of a start that succeeded and waits for its human. */
19
+ export const RESUME_WAITING = Object.freeze({ RESUME_CONFIRMATION: "resume-confirmation" });
20
+
21
+ /** A sweep row's `outcome`. */
22
+ export const OUTCOME = Object.freeze({ RESUMED: "resumed", FRESH: "fresh", ALREADY_RUNNING: "already-running", SKIPPED: "skipped", BLOCKED: "blocked", REFUSED: "refused" });
23
+
24
+ /** A sweep row's `reason`, beside FRESH_REASON's for `fresh`. */
25
+ export const ROW_REASON = Object.freeze({
26
+ UNKNOWN: "unknown", START_BUSY: "start-busy", NOT_LOST: "not-lost", NOT_SEEN_RECENTLY: "not-seen-recently",
27
+ RESUME_CONFIRMATION: RESUME_WAITING.RESUME_CONFIRMATION, LAUNCH_PROMPT: "launch-prompt",
28
+ START_REFUSED: "start-refused", REFUSED_THIS_BOOT: "refused-this-boot", KEEPS_GETTING_LOST: "keeps-getting-lost",
29
+ LIFECYCLE_BUSY: "lifecycle-busy",
30
+ });
31
+
32
+ /** `deployments[].reason` of a deployment the sweep did not sweep. */
33
+ export const NOT_SWEPT = Object.freeze({ NOT_OK: "not-ok", UNREADABLE: "unreadable" });
@@ -0,0 +1,337 @@
1
+ /** `oats session resume` (feature session-resume, #1559): the machine sweep. After a shutdown, a
2
+ * reboot or a crash, every launched instance home whose session was lost (status `sessionEnd: lost`)
3
+ * on every local deployment is started again with `session start --resume`, in its own harness
4
+ * conversation; running homes are left alone, stopped and exited ones stay stopped.
5
+ *
6
+ * - The machine's deployments come from the registry, read only (readDeploymentsDocument, never the
7
+ * first-use import that listDeployments may write); `deployment` narrows the sweep to one
8
+ * directory, registered or not. Nothing opts a deployment out: stopping an instance with OATS
9
+ * is what keeps it down.
10
+ * - Only a loss the kernel can vouch for is resumed (lib/session-seen.mjs resumeEligible, from what
11
+ * local listings recorded of the home): seen running for its current start, not judged by an
12
+ * earlier sweep, first seen lost less than 24 hours ago, and, within one boot, lost less than 24
13
+ * hours after it was last seen running. Any other is `skipped`, `not-seen-recently`. A sweep that
14
+ * is not a plan judges each lost home it answered (`judgedBy`), so it is answered once.
15
+ * - Each home starts as a child process of this kernel (`session start --resume --home <home>
16
+ * --json`, its cwd the home's deployment), so each start resolves its own deployment's scope; at
17
+ * most RESUME_CONCURRENCY at once. A per-home failure is a row, never the sweep's failure.
18
+ * - One sweep per machine: a mkdir lock under OATS_HOME_DIR (default ~/.oats) `session-resume/`,
19
+ * holding its pid and boot id; a lock whose pid is gone, or taken in another boot, is stale and
20
+ * taken over. A second sweep answers E_RESUME_BUSY.
21
+ * - No retry storm. A loss the sweep answered is judged (above) and not started again, whatever the
22
+ * boot; one note per boot (`note.json`) backs that: a refused resume is noted, and a later sweep
23
+ * in the same boot reports it again (`refused-this-boot`) without starting it, also when its
24
+ * judgement was lost (a home whose start id changed since is not matched); and a home is started by sweeps at most RESUME_LIMIT
25
+ * times in a boot (counted by home: each start makes a new start id), then reported
26
+ * `keeps-getting-lost` without a start. A start counts when it launched something (`resumed`,
27
+ * `fresh`, `blocked`), noted as soon as that start has answered, so a sweep that is killed while
28
+ * other starts run has counted the ones that answered. `session start --resume` run by hand is
29
+ * neither bounded nor counted.
30
+ * Without a boot id (neither Linux nor macOS) nothing is noted or counted: each sweep tries again.
31
+ * The lock and the note are kernel-private, not a contract. `plan` predicts from the note, starting
32
+ * nothing, taking no lock and writing no note. */
33
+ import { execFile } from "node:child_process";
34
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
35
+ import { join, resolve } from "node:path";
36
+ import { oatsError } from "./errors.mjs";
37
+ import { deploymentState, readDeploymentsDocument } from "./deployments.mjs";
38
+ import { homeClaimHolder, listInstances, missingLaunchEnvRefs, owedRetireSaid, resumeConversation } from "./core.mjs";
39
+ import { checkStartEnv, fromEnvNames, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning } from "./start-env.mjs";
40
+ import { FRESH_REASON, NOT_SWEPT, OUTCOME, RESUME_WAITING, ROW_REASON, SESSION_END } from "./session-resume-contract.mjs";
41
+ import { bootId, homeKey, judgeLosses, readSeen, resumeEligible, resumeStateDir } from "./session-seen.mjs";
42
+ import { isAgentScopeWarning } from "./tmux-server-scope.mjs";
43
+
44
+ export { bootId, resumeStateDir };
45
+
46
+ export const RESUME_SCHEMA = 1;
47
+ /** At most this many starts run at once. */
48
+ export const RESUME_CONCURRENCY = 4;
49
+ /** At most this many sweep starts of one home in one boot. */
50
+ export const RESUME_LIMIT = 3;
51
+ /** An acquirer's lock without an owner record yet is its own for this long (the gap between mkdir and
52
+ * the owner's write); older, it is a crashed acquirer's. */
53
+ const OWNERLESS_GRACE_MS = 60_000;
54
+
55
+ const lockDir = () => join(resumeStateDir(), "lock");
56
+ const notePath = () => join(resumeStateDir(), "note.json");
57
+
58
+ function pidAlive(pid) {
59
+ if (!Number.isSafeInteger(pid) || pid < 1) return false;
60
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; }
61
+ }
62
+ const readJson = (path) => { try { return JSON.parse(readFileSync(path, "utf8")); } catch { return undefined; } };
63
+
64
+ /** Take the machine's resume lock → its release function. Busy: E_RESUME_BUSY. A lock whose owner's
65
+ * pid is gone, whose owner was recorded in another boot, or that has had no owner for
66
+ * OWNERLESS_GRACE_MS is stale: it is taken over under a second mkdir (`lock.takeover`), so two
67
+ * sweeps that both find it stale cannot both take it. */
68
+ export function acquireResumeLock({ boot = bootId(), now = () => Date.now() } = {}) {
69
+ const dir = lockDir(), takeover = `${dir}.takeover`;
70
+ mkdirSync(resumeStateDir(), { recursive: true, mode: 0o700 });
71
+ const busy = (why) => oatsError("E_RESUME_BUSY", `another session resume on this machine holds ${dir} (${why}); nothing was started`);
72
+ const stale = () => {
73
+ const owner = readJson(join(dir, "owner.json"));
74
+ if (!owner) { try { return now() - statSync(dir).mtimeMs > OWNERLESS_GRACE_MS ? "no owner" : null; } catch { return "gone"; } }
75
+ if (boot && owner.bootId && owner.bootId !== boot) return `taken in another boot by pid ${owner.pid}`;
76
+ return pidAlive(owner.pid) ? null : `its owner pid ${owner.pid} is gone`;
77
+ };
78
+ const take = () => { mkdirSync(dir); writeFileSync(join(dir, "owner.json"), JSON.stringify({ pid: process.pid, bootId: boot, at: new Date(now()).toISOString() }) + "\n", { mode: 0o600 }); };
79
+ try { take(); }
80
+ catch (e) {
81
+ if (e.code !== "EEXIST") throw e;
82
+ if (!stale()) { const owner = readJson(join(dir, "owner.json")); throw busy(owner ? `pid ${owner.pid} holds it` : "its owner is not recorded yet"); }
83
+ try { mkdirSync(takeover); }
84
+ catch (t) {
85
+ if (t.code !== "EEXIST") throw t;
86
+ // A takeover that crashed leaves its directory: after the grace it is gone for good.
87
+ let old = false; try { old = now() - statSync(takeover).mtimeMs > OWNERLESS_GRACE_MS; } catch { /* removed meanwhile */ }
88
+ if (!old) throw busy("another sweep is taking over a stale lock");
89
+ rmSync(takeover, { recursive: true, force: true });
90
+ try { mkdirSync(takeover); } catch { throw busy("another sweep is taking over a stale lock"); }
91
+ }
92
+ try {
93
+ // Read again under the takeover: another sweep may have taken it meanwhile.
94
+ if (existsSync(dir) && !stale()) throw busy("another sweep took it over");
95
+ const aside = `${dir}.stale-${process.pid}-${now()}`;
96
+ try { renameSync(dir, aside); rmSync(aside, { recursive: true, force: true }); } catch (r) { if (r.code !== "ENOENT") throw r; }
97
+ take();
98
+ } finally { rmSync(takeover, { recursive: true, force: true }); }
99
+ }
100
+ return () => { try { if (readJson(join(dir, "owner.json"))?.pid === process.pid) rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } };
101
+ }
102
+
103
+ /** This boot's note: `{ bootId, refused: [{ home, startId, code, message, at }], resumes: { <home>: n } }`,
104
+ * each home by its real path (lib/session-seen.mjs homeKey);
105
+ * empty for another boot's note, an unreadable one, or no boot id. */
106
+ export function readBootNote(boot = bootId()) {
107
+ const note = boot ? readJson(notePath()) : undefined;
108
+ if (!note || note.bootId !== boot) return { bootId: boot, refused: [], resumes: {} };
109
+ const resumes = {};
110
+ if (note.resumes && typeof note.resumes === "object" && !Array.isArray(note.resumes)) {
111
+ for (const [home, n] of Object.entries(note.resumes)) if (Number.isSafeInteger(n) && n > 0) resumes[home] = n;
112
+ }
113
+ return { bootId: boot, refused: Array.isArray(note.refused) ? note.refused.filter((r) => r && typeof r.home === "string") : [], resumes };
114
+ }
115
+ /** Note a sweep's `refusals` (each replacing its home's earlier entry) and the `launched` homes (each
116
+ * counted once more) for this boot; another boot's note is replaced whole. Nothing is written
117
+ * without a boot id. */
118
+ export function noteSweep({ refusals = [], launched = [] }, boot = bootId()) {
119
+ if (!boot || (!refusals.length && !launched.length)) return;
120
+ const note = readBootNote(boot);
121
+ const homes = new Set(refusals.map((r) => r.home));
122
+ const resumes = { ...note.resumes };
123
+ for (const home of launched) resumes[home] = (resumes[home] ?? 0) + 1;
124
+ const path = notePath();
125
+ mkdirSync(resumeStateDir(), { recursive: true, mode: 0o700 });
126
+ const tmp = `${path}.${process.pid}.tmp`;
127
+ try {
128
+ writeFileSync(tmp, JSON.stringify({ bootId: boot, refused: [...note.refused.filter((r) => !homes.has(r.home)), ...refusals], resumes }, null, 2) + "\n", { mode: 0o600 });
129
+ renameSync(tmp, path);
130
+ } catch (e) { rmSync(tmp, { force: true }); throw e; }
131
+ }
132
+
133
+ /** The deployments a sweep considers: the one `deployment` names (E_BAD_ARGS when it is not a
134
+ * deployment directory), else the registry's live rows, sorted: a row `oats deployments remove` took
135
+ * out (a tombstone, `removed: true`) is never swept. Registry errors (E_DEPLOYMENTS_*) throw. */
136
+ function sweptDeployments(deployment) {
137
+ if (deployment !== undefined) {
138
+ const dir = resolve(deployment);
139
+ if (deploymentState(dir) !== "ok") throw oatsError("E_BAD_ARGS", `--deployment ${dir} is not a deployment directory (no oats-local.yaml there); nothing was started`);
140
+ return [dir];
141
+ }
142
+ return readDeploymentsDocument().deployments.filter((row) => row && row.removed !== true).map((row) => row.path).sort();
143
+ }
144
+
145
+ /** One deployment: its entry for `deployments[]` and, when it is swept, its homes' rows to act on. */
146
+ function readDeployment(dir) {
147
+ const state = deploymentState(dir);
148
+ if (state !== "ok") return { entry: { deployment: dir, state, swept: false, reason: NOT_SWEPT.NOT_OK } };
149
+ let rows;
150
+ try {
151
+ // The status rows `oats status --dir <deployment> --json` lists (listInstances), from the
152
+ // deployment's own instance root.
153
+ const root = join(dir, "agents");
154
+ rows = existsSync(root) ? listInstances(root).flatMap((a) => (a.instances || []).map((i) => ({ deployment: dir, ...i }))) : [];
155
+ } catch (e) {
156
+ return { entry: { deployment: dir, state, swept: false, reason: NOT_SWEPT.UNREADABLE, code: typeof e?.code === "string" && e.code.startsWith("E_") ? e.code : "E_RESUME_UNREADABLE", message: String(e?.message ?? e) } };
157
+ }
158
+ return { entry: { deployment: dir, state, swept: true }, rows };
159
+ }
160
+
161
+ /** The reasons of the rows a sweep answers without judging the loss, so that a later sweep may
162
+ * resume it: a home OATS was stopping, upgrading or retiring (`lifecycle-busy`), whose next state
163
+ * is that command's to decide. A loop guard's refusal (`keeps-getting-lost`) judges the loss like
164
+ * any refusal, and nothing brings it back automatically, a reboot included (decided for #1567);
165
+ * naming it here would let the next boot retry it. */
166
+ const NOT_JUDGED = new Set([ROW_REASON.LIFECYCLE_BUSY]);
167
+ /** The outcomes of a start that launched something: the ones RESUME_LIMIT counts. */
168
+ const LAUNCHED = new Set([OUTCOME.RESUMED, OUTCOME.FRESH, OUTCOME.BLOCKED]);
169
+ const base = (row) => ({ deployment: row.deployment, instance: row.instance, home: row.home });
170
+
171
+ /** A start's answered warnings, as strings. */
172
+ const startWarnings = (answer) => answer?.ok === true && Array.isArray(answer.result?.warnings) ? answer.result.warnings.filter((w) => typeof w === "string") : [];
173
+ /** The warnings of a start's answer that are said of the host, not of its home: today only the
174
+ * agent-scope warning (isAgentScopeWarning), which every start on a host that cannot scope repeats.
175
+ * The sweep says each once, in its own `warnings`; the rows leave them out (rowFromStart). */
176
+ export function hostWarnings(answer) {
177
+ return startWarnings(answer).filter(isAgentScopeWarning);
178
+ }
179
+
180
+ /** What a start's JSON answer means for the sweep's row: its warnings without the host's (hostWarnings). */
181
+ export function rowFromStart(row, answer) {
182
+ if (answer?.ok === true) {
183
+ const r = answer.result ?? {}, resume = r.resume ?? {};
184
+ const warnings = startWarnings(answer).filter((w) => !isAgentScopeWarning(w));
185
+ const extra = warnings.length ? { warnings } : {};
186
+ if (resume.resumed === true) {
187
+ if (resume.waiting === RESUME_WAITING.RESUME_CONFIRMATION) return { ...base(row), outcome: OUTCOME.BLOCKED, reason: ROW_REASON.RESUME_CONFIRMATION, ...(resume.sessionId ? { sessionId: resume.sessionId } : {}), ...extra };
188
+ return { ...base(row), outcome: OUTCOME.RESUMED, ...(resume.sessionId ? { sessionId: resume.sessionId } : {}), ...extra };
189
+ }
190
+ return { ...base(row), outcome: OUTCOME.FRESH, reason: resume.reason ?? FRESH_REASON.NO_CONVERSATION, ...extra };
191
+ }
192
+ const code = typeof answer?.error?.code === "string" ? answer.error.code : "E_SESSION_START_FAILED";
193
+ const message = String(answer?.error?.message ?? "the start gave no answer");
194
+ if (code === "E_SPAWN_INCOMPLETE") return { ...base(row), outcome: OUTCOME.BLOCKED, reason: ROW_REASON.LAUNCH_PROMPT, code, ...(answer.error.details?.launchPrompts ? { launchPrompts: answer.error.details.launchPrompts } : {}) };
195
+ if (code === "E_SESSION_START_BUSY") return { ...base(row), outcome: OUTCOME.SKIPPED, reason: ROW_REASON.START_BUSY, code };
196
+ // The home's lifecycle claim was held, or its retire is owed: whatever OATS is doing decides the
197
+ // home's next state. Not a refusal: none is noted, judged or counted against the loop guard.
198
+ if (code === "E_INSTANCE_RETIRING" || code === "E_LIFECYCLE_BUSY") return { ...base(row), outcome: OUTCOME.SKIPPED, reason: ROW_REASON.LIFECYCLE_BUSY, code, message };
199
+ if (code === "E_RESUME_NOT_LOST" || code === "E_SESSION_RUNNING") return { ...base(row), outcome: OUTCOME.SKIPPED, reason: ROW_REASON.NOT_LOST, code };
200
+ if (code === "E_SESSION_UNKNOWN") return { ...base(row), outcome: OUTCOME.SKIPPED, reason: ROW_REASON.UNKNOWN, code, message };
201
+ return { ...base(row), outcome: OUTCOME.REFUSED, reason: ROW_REASON.START_REFUSED, code, message };
202
+ }
203
+
204
+ /** The environment of a start the sweep runs: this one's, without an instance identity, so a sweep
205
+ * run from inside an instance starts each home as the home itself, in its deployment. */
206
+ function startEnvironment(env) {
207
+ const out = { ...env };
208
+ for (const k of ["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "PI_AGENT_INSTANCE", "PI_AGENT_HOME"]) delete out[k];
209
+ return out;
210
+ }
211
+ function runStart({ execPath, bin, env }, row) {
212
+ return new Promise((done) => {
213
+ execFile(execPath, [bin, "session", "start", "--resume", "--home", row.home, "--json"], { cwd: row.deployment, env: startEnvironment(env), encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }, (error, stdout) => {
214
+ let answer;
215
+ try { answer = JSON.parse(String(stdout).trim().split("\n").pop()); } catch { answer = undefined; }
216
+ if (!answer || typeof answer !== "object") answer = { ok: false, error: { code: "E_SESSION_START_FAILED", message: `the start exited${error?.code !== undefined ? ` with status ${error.code}` : ""}${error?.signal ? ` on ${error.signal}` : ""} without an answer` } };
217
+ done(answer);
218
+ });
219
+ });
220
+ }
221
+ /** `fn` over `items`, at most `limit` at once; once `stop()` holds no item is taken any more, and the
222
+ * answer waits for every one already taken. */
223
+ async function inBatches(items, limit, fn, stop = () => false) {
224
+ const out = new Array(items.length);
225
+ let next = 0;
226
+ const worker = async () => { while (!stop() && next < items.length) { const i = next++; out[i] = await fn(items[i]); } };
227
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
228
+ return out;
229
+ }
230
+
231
+ /** The sweep → `{ schemaVersion, plan, deployments, rows, warnings? }` (docs/desktop-cli-api.md):
232
+ * `warnings`, only when there is one, holds each distinct host-wide warning of its starts once. `kernel`:
233
+ * `{ execPath, bin }`, how a start is run; `env` the environment each start gets. `start` (tests):
234
+ * row → Promise of the start's JSON answer, in place of the child process. */
235
+ export async function resumeSessions({ deployment, plan = false, kernel, env = process.env, boot = bootId(), start = (row) => runStart({ ...kernel, env }, row) } = {}) {
236
+ const release = plan ? null : acquireResumeLock({ boot });
237
+ try {
238
+ const deployments = [], candidates = [], rows = [], seen = new Map();
239
+ for (const dir of sweptDeployments(deployment)) {
240
+ const { entry, rows: found } = readDeployment(dir);
241
+ deployments.push(entry);
242
+ // What the kernel has seen of each home (lib/session-seen.mjs), read after the deployment's own
243
+ // listing recorded what it saw now.
244
+ const { homes } = found ? readSeen(join(dir, "agents")) : { homes: {} };
245
+ for (const [home, record] of Object.entries(homes)) seen.set(home, record);
246
+ for (const row of found ?? []) {
247
+ if (row.running === true) rows.push({ ...base(row), outcome: OUTCOME.ALREADY_RUNNING });
248
+ else if (row.running === null) rows.push({ ...base(row), outcome: OUTCOME.SKIPPED, reason: ROW_REASON.UNKNOWN });
249
+ // A launched home that is owed a self-retire reads no sessionEnd (its marker withholds it):
250
+ // it is listed as the lost ones are, so that the sweep says it is skipped (lifecycleBusy).
251
+ else if (row.sessionEnd === SESSION_END.LOST || (row.retirePending && row.launched === true && row.running === false)) candidates.push(row);
252
+ }
253
+ }
254
+ const note = readBootNote(boot), now = Date.now();
255
+ const toStart = [];
256
+ // Precedence, the first that applies: not seen recently, refused this boot, keeps getting lost,
257
+ // started. The record and the note name a home by its real path (homeKey), whatever spelling the
258
+ // sweep was given; a row shows the path it listed.
259
+ // A home OATS is stopping, upgrading or retiring, or whose retire is owed, comes first: nothing
260
+ // is started there. This read is only a filter (the sweep is not atomic with it): the start's
261
+ // own claim is what keeps a resume off such a home (lib/core.mjs startInstanceSession).
262
+ for (const row of candidates) {
263
+ const startId = row.startId ?? null, key = homeKey(row.home);
264
+ const prior = note.refused.find((r) => r.home === key && (r.startId ?? null) === startId);
265
+ const fit = resumeEligible(seen.get(key), row, { now });
266
+ const busy = lifecycleBusy(row);
267
+ if (busy) rows.push({ ...base(row), outcome: OUTCOME.SKIPPED, reason: ROW_REASON.LIFECYCLE_BUSY, message: busy });
268
+ else if (!fit.eligible) rows.push({ ...base(row), outcome: OUTCOME.SKIPPED, reason: ROW_REASON.NOT_SEEN_RECENTLY, message: `${row.instance} is not resumed automatically: ${fit.why}; start it by hand (oats session start --resume --home ${row.home}) if it should run` });
269
+ else if (prior) rows.push({ ...base(row), outcome: OUTCOME.REFUSED, reason: ROW_REASON.REFUSED_THIS_BOOT, code: prior.code, message: prior.message });
270
+ else if ((note.resumes[key] ?? 0) >= RESUME_LIMIT) rows.push({ ...base(row), outcome: OUTCOME.REFUSED, reason: ROW_REASON.KEEPS_GETTING_LOST, message: `${row.instance} was resumed ${note.resumes[key]} times in this boot and was lost again each time; no sweep starts this loss again: start it by hand (oats session start --resume --home ${row.home})` });
271
+ else if (plan) rows.push(predicted(row, env));
272
+ else toStart.push(row);
273
+ }
274
+ // Each start's answer is noted as it comes, under the lock (noteSweep is synchronous: two answers
275
+ // never interleave in it), before the sweep waits on the others. A note that cannot be written
276
+ // takes no more home; the lock is held until every start already running has answered, and the
277
+ // failure is the sweep's after that.
278
+ let noteFailure = null;
279
+ const hostWide = new Set();
280
+ const started = (await inBatches(toStart, RESUME_CONCURRENCY, async (row) => {
281
+ const answer = await start(row);
282
+ for (const w of hostWarnings(answer)) hostWide.add(w);
283
+ // A home removed between the read and its start (a retire finished in between) is not lost:
284
+ // whatever its start answered.
285
+ const gone = answer?.ok !== true && !existsSync(row.home);
286
+ const answered = gone ? { ...base(row), outcome: OUTCOME.SKIPPED, reason: ROW_REASON.NOT_LOST, ...(typeof answer?.error?.code === "string" ? { code: answer.error.code } : {}) } : rowFromStart(row, answer);
287
+ const key = homeKey(row.home);
288
+ try {
289
+ noteSweep({
290
+ refusals: answered.outcome === OUTCOME.REFUSED ? [{ home: key, startId: row.startId ?? null, code: answered.code, message: answered.message, at: new Date().toISOString() }] : [],
291
+ launched: LAUNCHED.has(answered.outcome) ? [key] : [],
292
+ }, boot);
293
+ } catch (e) { noteFailure ??= e; }
294
+ return answered;
295
+ }, () => noteFailure !== null)).filter(Boolean);
296
+ rows.push(...started);
297
+ // Each lost home this sweep answered is judged: no later sweep resumes this loss (a status read
298
+ // never uses one up). A plan judges nothing.
299
+ if (!plan) {
300
+ const lost = new Set(candidates.map((c) => c.home)), byDeployment = new Map();
301
+ for (const r of rows) if (lost.has(r.home) && !NOT_JUDGED.has(r.reason)) byDeployment.set(r.deployment, [...(byDeployment.get(r.deployment) ?? []), { home: r.home, startId: candidates.find((c) => c.home === r.home).startId ?? null, outcome: r.outcome }]);
302
+ for (const [dir, judged] of byDeployment) judgeLosses(join(dir, "agents"), judged, { boot });
303
+ }
304
+ if (noteFailure) throw noteFailure;
305
+ rows.sort((a, b) => (a.deployment < b.deployment ? -1 : a.deployment > b.deployment ? 1 : a.home < b.home ? -1 : a.home > b.home ? 1 : 0));
306
+ return { schemaVersion: RESUME_SCHEMA, plan: !!plan, deployments, rows, ...(hostWide.size ? { warnings: [...hostWide].sort() } : {}) };
307
+ } finally { release?.(); }
308
+ }
309
+
310
+ /** Why a lost home's status row says OATS is stopping, upgrading or retiring it, or that its
311
+ * retire is owed, as one line; null when it says none of that. Read only: the row's `retire` (any
312
+ * value: running, unknown, failed, interrupted) or `retirePending`, then the holder of the home's lifecycle claim,
313
+ * alive or of a liveness that cannot be read (homeClaimHolder). A holder that is gone is not one:
314
+ * the start takes its claim over. */
315
+ function lifecycleBusy(row) {
316
+ if (row.retire || row.retirePending) return owedRetireSaid(row.instance, row.retire?.state ?? "unknown");
317
+ const held = homeClaimHolder(row.home);
318
+ if (!held || held.state === "gone") return null;
319
+ return `${row.instance} is held by ${held.state === "alive" ? "a" : "what may still be a"} ${held.action} (${held.lock}); that command decides what the home is next`;
320
+ }
321
+
322
+ /** `--plan`'s prediction for a lost home, from what its start would check, read only: refused for a
323
+ * home with no recipe, a reference not set in `env` (the environment each start gets) or one whose
324
+ * value changed since the start it would bring back (lib/start-env.mjs, the start's own check), else
325
+ * resumed or fresh as the conversation lookup reads now, with the start's warning when its launch
326
+ * environment has no record to check. */
327
+ function predicted(row, env) {
328
+ const refused = (code, message) => ({ ...base(row), outcome: OUTCOME.REFUSED, reason: ROW_REASON.START_REFUSED, code, message });
329
+ if (!(row.launch && typeof row.launch === "object")) return refused("E_LAUNCH_LEGACY", `${row.instance} records no launch recipe (an earlier kernel spawned it): re-spawn it from the deployment`);
330
+ const missing = missingLaunchEnvRefs(row.launch.env, env);
331
+ if (missing.length) return refused("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage(missing));
332
+ const fit = checkStartEnv(row.home, row.startId ?? null, fromEnvNames(row.launch.env), env);
333
+ if (fit.changed) return refused("E_LAUNCH_ENV_CHANGED", launchEnvChangedMessage(fit.changed));
334
+ const extra = fit.unverified ? { warnings: [launchEnvUnverifiedWarning(row.instance)] } : {};
335
+ const found = resumeConversation(row.home, row);
336
+ return found.sessionId ? { ...base(row), outcome: OUTCOME.RESUMED, sessionId: found.sessionId, ...extra } : { ...base(row), outcome: OUTCOME.FRESH, reason: found.reason, ...extra };
337
+ }
@@ -0,0 +1,163 @@
1
+ /** What the kernel has seen of each launched home's session (feature session-resume, #1559;
2
+ * awebai/oats#1567 item 3): the record the sweep reads so that it resumes only a loss it can vouch
3
+ * for. Kernel-private, not a contract, under OATS_HOME_DIR beside the per-boot note: one file per
4
+ * deployment, `session-resume/seen/<first 16 hex of sha256(instances root)>.json`,
5
+ * { deployment, root, homes: { <home's real path>: { startId, lastSeenRunningAt, lastSeenRunningBoot,
6
+ * firstNotRunningAt, firstNotRunningBoot, judgedBy } } }
7
+ * (times ISO; boots bootId's, null without one; `judgedBy` `{ at, boot, outcome }` or null).
8
+ *
9
+ * - Observations have one producer, a local `listInstances` (`oats status`, the sweep's own read
10
+ * and every other local listing): recordSeen. A status routed to another machine reads nothing
11
+ * here; a start writes nothing.
12
+ * - `judgedBy` has one writer, a sweep that is not a plan (judgeLosses), once its rows are known:
13
+ * a status read never uses up a loss.
14
+ * - Never in the way of what reads it: an unreadable file is an empty record (which resumes
15
+ * nothing), every write error is swallowed and nothing is printed. A write is one atomic rename
16
+ * of the whole file, made only when something changed; two writers race harmlessly (the last
17
+ * rename wins whole).
18
+ * - Whether a loss is resumed is one pure function, resumeEligible.
19
+ * Dependency-free. */
20
+ import { execFileSync } from "node:child_process";
21
+ import { createHash, randomBytes } from "node:crypto";
22
+ import { mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { dirname, join, resolve } from "node:path";
25
+
26
+ /** A loss first seen this long ago or more is not resumed. */
27
+ export const FIRST_SEEN_MAX_MS = 24 * 60 * 60_000;
28
+ /** Within one boot, a loss first seen this long or more after the last running look is not resumed. */
29
+ export const WITHIN_BOOT_GAP_MS = 24 * 60 * 60_000;
30
+ /** A running home's last running look is rewritten at most this often in one boot. */
31
+ export const RUNNING_REFRESH_MS = 10 * 60_000;
32
+
33
+ const oatsHomeDir = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
34
+ /** The kernel-private directory of the sweep's lock, its per-boot note and this record. */
35
+ export const resumeStateDir = () => join(oatsHomeDir(), "session-resume");
36
+
37
+ /** This boot's identity, or null where the kernel cannot read one: Linux's boot id, macOS's boot
38
+ * time (`sysctl -n kern.boottime`, its `sec`/`usec`). */
39
+ export function bootId({ platform = process.platform, read = (p) => readFileSync(p, "utf8"), sysctl = () => execFileSync("sysctl", ["-n", "kern.boottime"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }) } = {}) {
40
+ try {
41
+ if (platform === "linux") return read("/proc/sys/kernel/random/boot_id").trim() || null;
42
+ if (platform === "darwin") { const m = /sec = (\d+), usec = (\d+)/.exec(sysctl()); return m ? `${m[1]}.${m[2]}` : null; }
43
+ } catch { /* unknown */ }
44
+ return null;
45
+ }
46
+ let processBoot;
47
+ /** bootId, read once per process: a process never outlives its boot. */
48
+ export const thisBoot = () => (processBoot === undefined ? (processBoot = bootId()) : processBoot);
49
+
50
+ const realOrResolved = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
51
+ /** The key of `home` in a record: its real path, so a deployment reached through a symlink (an
52
+ * explicit `--deployment` spelled so, a cwd under one) reads and writes the same entry. */
53
+ export const homeKey = (home) => realOrResolved(home);
54
+ /** The record file of the deployment whose instances root is `root` (its real path, the same way). */
55
+ export function seenFile(root) {
56
+ return join(resumeStateDir(), "seen", `${createHash("sha256").update(realOrResolved(root)).digest("hex").slice(0, 16)}.json`);
57
+ }
58
+
59
+ /** The record of `root` → `{ homes, readable }`: no file is an empty, readable record; a file that
60
+ * cannot be read or parsed is an empty, unreadable one (rewritten whole by the next change). */
61
+ export function readSeen(root) {
62
+ let text;
63
+ try { text = readFileSync(seenFile(root), "utf8"); }
64
+ catch (e) { return { homes: {}, readable: e?.code === "ENOENT" }; }
65
+ try {
66
+ const doc = JSON.parse(text);
67
+ if (!doc || typeof doc !== "object" || !doc.homes || typeof doc.homes !== "object" || Array.isArray(doc.homes)) return { homes: {}, readable: false };
68
+ const homes = {};
69
+ for (const [home, r] of Object.entries(doc.homes)) if (r && typeof r === "object" && !Array.isArray(r)) homes[home] = r;
70
+ return { homes, readable: true };
71
+ } catch { return { homes: {}, readable: false }; }
72
+ }
73
+ function writeSeen(root, homes) {
74
+ const path = seenFile(root), tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
75
+ try {
76
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
77
+ const real = realOrResolved(root);
78
+ writeFileSync(tmp, JSON.stringify({ deployment: dirname(real), root: real, homes }, null, 2) + "\n", { mode: 0o600 });
79
+ renameSync(tmp, path);
80
+ } catch { try { rmSync(tmp, { force: true }); } catch { /* nothing to remove */ } }
81
+ }
82
+
83
+ const startIdOf = (row) => (typeof row?.startId === "string" && row.startId ? row.startId : null);
84
+
85
+ /** The record after one listing of `rows` (status rows) at `now` in `boot` → `{ homes, changed }`.
86
+ * Per row:
87
+ * - running, another start or no record: a new record, seen running now (a new start resets it);
88
+ * - running, the same start: its last running look moves to now when it is RUNNING_REFRESH_MS old
89
+ * or more, or from another boot;
90
+ * - not running, launched, the same start, no loss seen yet: the loss is first seen now (once);
91
+ * - running unknown (null): unchanged.
92
+ * A home no longer listed is dropped. Pure. */
93
+ export function nextSeen(homes, rows, { now, boot }) {
94
+ const at = new Date(now).toISOString(), out = {};
95
+ let changed = false;
96
+ for (const row of rows) {
97
+ if (typeof row?.home !== "string") continue;
98
+ const prior = homes[row.home], startId = startIdOf(row);
99
+ let next = prior;
100
+ if (row.running === true) {
101
+ if (!prior || prior.startId !== startId) next = { startId, lastSeenRunningAt: at, lastSeenRunningBoot: boot, firstNotRunningAt: null, firstNotRunningBoot: null, judgedBy: null };
102
+ else if (!(now - Date.parse(prior.lastSeenRunningAt) < RUNNING_REFRESH_MS) || prior.lastSeenRunningBoot !== boot) next = { ...prior, lastSeenRunningAt: at, lastSeenRunningBoot: boot };
103
+ } else if (row.running === false && row.launched === true && prior && prior.startId === startId && !prior.firstNotRunningAt) {
104
+ next = { ...prior, firstNotRunningAt: at, firstNotRunningBoot: boot };
105
+ }
106
+ if (next) out[row.home] = next;
107
+ if (next !== prior) changed = true;
108
+ }
109
+ if (Object.keys(homes).some((home) => !Object.hasOwn(out, home))) changed = true;
110
+ return { homes: out, changed };
111
+ }
112
+
113
+ /** Record one local listing of `root`'s homes (listInstances, its every row). Never throws, never
114
+ * prints: what reads the listing answers the same whatever happens here. */
115
+ export function recordSeen(root, rows, { now = Date.now(), boot = thisBoot() } = {}) {
116
+ try {
117
+ const before = readSeen(root);
118
+ const { homes, changed } = nextSeen(before.homes, rows.map((row) => ({ ...row, home: typeof row?.home === "string" ? homeKey(row.home) : row?.home })), { now, boot });
119
+ if (changed || !before.readable) writeSeen(root, homes);
120
+ } catch { /* the record is the sweep's, never the reader's problem */ }
121
+ }
122
+
123
+ /** A sweep's answers for the lost homes of `root` (`[{ home, startId, outcome }]`), written once
124
+ * into each home's record as `judgedBy`, when the record is of that start and not judged yet: the
125
+ * file is read again just before the write, so a status write in between is kept. A `judgedBy` lost
126
+ * to a status write that renames over this one is harmless: a resumed home has a new start id; a
127
+ * refused one is still held by the per-boot refusal note; a skipped or blocked one is judged the
128
+ * same again. Never throws. */
129
+ export function judgeLosses(root, judged, { now = Date.now(), boot = thisBoot() } = {}) {
130
+ try {
131
+ const { homes } = readSeen(root);
132
+ let changed = false;
133
+ for (const { home, startId, outcome } of judged) {
134
+ const key = homeKey(home), r = homes[key];
135
+ if (!r || r.startId !== (startId ?? null) || r.judgedBy) continue;
136
+ homes[key] = { ...r, judgedBy: { at: new Date(now).toISOString(), boot, outcome } };
137
+ changed = true;
138
+ }
139
+ if (changed) writeSeen(root, homes);
140
+ } catch { /* best effort: see above */ }
141
+ }
142
+
143
+ /** Whether the sweep resumes the lost home of `row` (a status row) on its `record`, at `now` in
144
+ * `boot` → `{ eligible: true }` or `{ eligible: false, why }`. All four must hold:
145
+ * 1. the record saw it running for its current start;
146
+ * 2. no earlier sweep judged this loss (`judgedBy`);
147
+ * 3. the loss was first seen less than FIRST_SEEN_MAX_MS ago;
148
+ * 4. within one boot (both looks in the same boot, or either without a boot id), the last running
149
+ * look is less than WITHIN_BOOT_GAP_MS before the first not-running look. Across a reboot it
150
+ * does not apply.
151
+ * The rule reads the boots the record holds, not this one's. Pure. */
152
+ export function resumeEligible(record, row, { now }) {
153
+ const no = (why) => ({ eligible: false, why });
154
+ const lastRunning = Date.parse(record?.lastSeenRunningAt);
155
+ if (!record || record.startId !== startIdOf(row) || !Number.isFinite(lastRunning)) return no("OATS never saw it running for its current start");
156
+ if (record.judgedBy) return no(`an earlier sweep already answered this loss (${record.judgedBy.outcome ?? "answered"}${record.judgedBy.at ? ` at ${record.judgedBy.at}` : ""})`);
157
+ const firstLost = Date.parse(record.firstNotRunningAt);
158
+ if (!Number.isFinite(firstLost)) return no("OATS has not seen it stop since it last saw it running");
159
+ if (now - firstLost >= FIRST_SEEN_MAX_MS) return no(`its loss was first seen ${record.firstNotRunningAt}, 24 hours ago or more`);
160
+ const oneBoot = !record.lastSeenRunningBoot || !record.firstNotRunningBoot || record.lastSeenRunningBoot === record.firstNotRunningBoot;
161
+ if (oneBoot && firstLost - lastRunning >= WITHIN_BOOT_GAP_MS) return no(`in the boot it was lost in, it was last seen running ${record.lastSeenRunningAt}, 24 hours or more before its loss was seen`);
162
+ return { eligible: true };
163
+ }