@awebai/oats 0.69.4 → 0.69.5

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 (46) hide show
  1. package/bin/oats.mjs +68 -49
  2. package/docs/configuration.md +12 -0
  3. package/docs/desktop-cli-api.md +8 -1
  4. package/docs/execution-targets.md +25 -3
  5. package/docs/implementation.md +10 -3
  6. package/docs/integrations.md +2 -2
  7. package/docs/knowledge.md +9 -6
  8. package/docs/official-catalog.md +5 -5
  9. package/docs/packages.md +14 -14
  10. package/docs/release-notes/v0.69.5.md +146 -0
  11. package/docs/tui.md +2 -1
  12. package/docs/upgrading.md +16 -5
  13. package/docs/workspaces.md +2 -2
  14. package/lib/agents-root.mjs +51 -0
  15. package/lib/automation-api.mjs +7 -0
  16. package/lib/automation-scope.mjs +35 -0
  17. package/lib/automations.mjs +2 -1
  18. package/lib/compile-cache.mjs +36 -0
  19. package/lib/core.mjs +39 -1348
  20. package/lib/deployment-path.mjs +127 -0
  21. package/lib/deployments.mjs +2 -2
  22. package/lib/drift.mjs +95 -0
  23. package/lib/hot-reads.mjs +131 -0
  24. package/lib/instance-address.mjs +21 -0
  25. package/lib/instance-lifecycle.mjs +4 -16
  26. package/lib/instance-listing.mjs +730 -0
  27. package/lib/instance-resolution.mjs +5 -166
  28. package/lib/materialize.mjs +2 -87
  29. package/lib/member-clone.mjs +188 -0
  30. package/lib/package-catalog.mjs +93 -0
  31. package/lib/packages.mjs +4 -24
  32. package/lib/reserved-launch-env.mjs +20 -0
  33. package/lib/resolved-deployment.mjs +1 -1
  34. package/lib/schedule.mjs +5 -29
  35. package/lib/semver.mjs +12 -0
  36. package/lib/servers.mjs +10 -12
  37. package/lib/session-end.mjs +3 -2
  38. package/lib/session-inspect.mjs +219 -0
  39. package/lib/soul-listing.mjs +216 -0
  40. package/lib/status-words.mjs +30 -0
  41. package/lib/version.mjs +9 -0
  42. package/lib/write-file-atomic.mjs +28 -0
  43. package/package-catalog.json +4 -4
  44. package/package.json +1 -1
  45. package/packages/tui/lib/store.mjs +7 -3
  46. package/skills/oats-getting-started/SKILL.md +3 -3
package/lib/packages.mjs CHANGED
@@ -41,13 +41,15 @@
41
41
  * is exported below as a thin function throwing E_REMOVED so nothing breaks at
42
42
  * import time; callers are deleted in the next phase.
43
43
  */
44
- import { closeSync, existsSync, fchmodSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, lstatSync } from "node:fs";
44
+ import { existsSync, mkdtempSync, readFileSync, rmSync, lstatSync } from "node:fs";
45
45
  import { tmpdir } from "node:os";
46
- import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
46
+ import { isAbsolute, join, posix, relative, resolve, sep } from "node:path";
47
47
  import { recordLocalInput } from "./local-inputs.mjs";
48
48
  import { oatsError as baseOatsError } from "./errors.mjs";
49
49
  import * as defaultRemote from "./remote.mjs";
50
50
  import { manifestContractProblems } from "./capability-contract.mjs";
51
+ import { writeFileAtomic } from "./write-file-atomic.mjs";
52
+ export { writeFileAtomic } from "./write-file-atomic.mjs";
51
53
 
52
54
  export const LOCK_FILE = "oats-lock.json";
53
55
  export const LOCK_VERSION = 3;
@@ -98,28 +100,6 @@ export function assertNoSymlinkedParents(scopeDir, leafDir, what) {
98
100
  }
99
101
  }
100
102
 
101
- /** Sibling temp + rename: replaces the directory entry itself, never writing
102
- * THROUGH a pre-planted symlink at `file`. The new file's permission bits are the process's default
103
- * (its umask) unless `mode` gives them: then they are exactly `mode`, and in force before a byte of
104
- * `contents` is written, so a file kept private is never readable by others on the way. */
105
- export function writeFileAtomic(file, contents, { mode } = {}) {
106
- mkdirSync(dirname(file), { recursive: true });
107
- const tmp = join(dirname(file), `.${basename(file)}.oats-tmp-${process.pid}`);
108
- try {
109
- if (mode === undefined) writeFileSync(tmp, contents);
110
- else {
111
- // A new file (one left by a killed process of this pid goes first; "wx" opens nothing that is
112
- // there), created with no more than `mode` (the umask only takes bits away), then set to it exactly.
113
- rmSync(tmp, { force: true });
114
- const fd = openSync(tmp, "wx", mode);
115
- try { fchmodSync(fd, mode); writeFileSync(fd, contents); } finally { closeSync(fd); }
116
- }
117
- renameSync(tmp, file);
118
- } finally {
119
- // A failed removal is not answered: when the write or the rename failed, that error is (#1076).
120
- try { rmSync(tmp, { force: true }); } catch { /* the first error is the one answered */ }
121
- }
122
- }
123
103
 
124
104
  /** Exact copy via `writeFileAtomic` (copyFileSync would follow a destination symlink). */
125
105
  export function copyFileAtomic(from, to) {
@@ -0,0 +1,20 @@
1
+ /** The environment names the kernel sets for every launch: a launch configuration may not name them,
2
+ * and a scheduled job's environment drops them (automation-scope.mjs childEnv). A leaf
3
+ * (awebai/oats#1630): the automation scope reads it without loading core.mjs, which imports it and
4
+ * re-exports it. One instance, here. */
5
+
6
+ /** Environment the kernel sets for every launch (identity, home, roots) and
7
+ * its reference aliases: a configuration may not name them. */
8
+ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "OATS_AGENT", "OATS_SOUL", "OATS_SOUL_ID", "OATS_ROOT", "OATS_CONTEXT", "OATS_WORKSPACE", "OATS_EVENT", "OATS_SETTINGS", "OATS_SETTINGS_ORIGINS", "OATS_CLI_BIN", "OATS_NODE_BIN", "PI_AGENT_INSTANCE", "PI_AGENT_HOME", "PI_AGENTS_ROOT",
9
+ // The test seam that replaces the login shell (lib/login-environment.mjs): never a launch's to set.
10
+ "OATS_TEST_LOGIN_SHELL",
11
+ // The test seams of #796, the same: a worktree hook's fixed timeout, the fetch timeout of
12
+ // `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
13
+ // process's start time on a host with procfs, and the `ps` it runs (lib/worktree-hooks.mjs processStart).
14
+ "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS",
15
+ // The test seams of #915 and #1559: the cgroup the kernel judges itself in, whether the host was
16
+ // booted with systemd, and the directories its systemd-run comes from (lib/tmux-server-scope.mjs,
17
+ // lib/system-tools.mjs).
18
+ "OATS_TEST_CGROUP", "OATS_TEST_SYSTEMD_BOOTED", "OATS_TEST_SYSTEM_TOOL_DIRS",
19
+ // The test seam of #1421 §3: the naming call's time limit (lib/instance-naming.mjs NAMING_TIMEOUT_MS).
20
+ "OATS_TEST_NAMING_TIMEOUT_MS"]);
@@ -2,7 +2,7 @@
2
2
  * list (awebai/oats#1390; lib/deployments.mjs listResolved).
3
3
  *
4
4
  * The resolvers report the deployment directory they found: `loadLocal` (lib/workspace.mjs) the
5
- * directory of the oats-local.yaml its walk up found, as spelled; `ensureRoot` (lib/core.mjs) the
5
+ * directory of the oats-local.yaml its walk up found, as spelled; `ensureRoot` (lib/agents-root.mjs) the
6
6
  * directory of the canonical agents root, `canonical`. The observer is called once, when the
7
7
  * process exits, with the root the command settled on: the first canonical one reported, else the
8
8
  * first one, and whether it is canonical. So a command that resolves its canonical root is compared
package/lib/schedule.mjs CHANGED
@@ -33,14 +33,15 @@ import { noteRuntimeName } from "./deprecation.mjs";
33
33
  import { herdrSettingRemoved } from "./errors.mjs";
34
34
  import { withDirLock as withSharedDirLock } from "./dir-lock.mjs";
35
35
  import { pollSourced, tickTriggers } from "./triggers.mjs";
36
- import { resolveMemberClone } from "./instance-resolution.mjs";
37
- import { SCHEDULE_NAME_RE, HOST_NAME_RE, readSnapshot, hostOf, trusted, parseOwner, MODEL_RE, automationContext, automationError, baseRow, localEntry, localId, soulOriginOf, splitId, validateDescription } from "./automations.mjs";
38
- import { RESERVED_LAUNCH_ENV, MAX_INSTANCE_NAME, shq, shellWord, findAgent, findInstanceHomes, inspectInstanceSession, inputInstanceSession, sessionServerGone, startInstanceSession, retirePendingMarkerPath } from "./core.mjs";
36
+ import { SCHEDULE_NAME_RE, HOST_NAME_RE, readSnapshot, hostOf, trusted, parseOwner, MODEL_RE, automationError, baseRow, localEntry, localId, soulOriginOf, splitId, validateDescription } from "./automations.mjs";
37
+ import { MAX_INSTANCE_NAME, shq, shellWord, findAgent, findInstanceHomes, inspectInstanceSession, inputInstanceSession, sessionServerGone, startInstanceSession, retirePendingMarkerPath } from "./core.mjs";
39
38
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
40
39
  import { readStartExited } from "./session-end.mjs";
40
+ import { childEnv, scopeAutomations } from "./automation-scope.mjs";
41
+ export { SCHEDULE_API } from "./automation-api.mjs";
42
+ export { childEnv, scopeAutomations } from "./automation-scope.mjs";
41
43
 
42
44
  export const SCHEDULE_FILE = "oats-schedules.json";
43
- export const SCHEDULE_API = 2;
44
45
  const ID_RE = SCHEDULE_NAME_RE;
45
46
  const HARNESSES = new Set(["pi", "claude", "codex"]);
46
47
  const MESSAGE_MAX = 256 * 1024;
@@ -545,22 +546,6 @@ export function findHomesInScope(ws, instance) {
545
546
  function scheduleBlock(def, minute) {
546
547
  return `\n\n## Scheduled run\n\nThis instance was launched by OATS schedule "${def.workspace?.qid ?? def.id}" for ${minute.toISOString()} (cron "${def.cron}" in ${def.tz}). It is disposable: finish the task above, bring your memory files up to date, and end with \`oats retire --self\`.\n`;
547
548
  }
548
- /** The environment a scheduler-launched oats child runs with: the caller's
549
- * frozen instance identity and capability snapshot removed (a tick or run-now
550
- * may be invoked from inside an unrelated instance; dispatch belongs to the
551
- * job's cwd and explicit selectors, never to that caller), host configuration
552
- * such as OATS_HOME_DIR and credentials kept. Shared by command and spawn jobs. */
553
- export function childEnv() {
554
- const env = { ...process.env };
555
- for (const key of [...RESERVED_LAUNCH_ENV,
556
- "OATS_DEPLOYMENT", "OATS_RESOLUTION", "OATS_CAPABILITY", "OATS_LAYER", "OATS_LEVEL", "OATS_META", "OATS_OPERATION",
557
- "OATS_REPO", "OATS_BRANCH", "OATS_WORK", "OATS_KIND", "OATS_TASK",
558
- "OATS_HARNESS", "OATS_PREVIOUS_HARNESS", "OATS_RUNTIME", "OATS_PREVIOUS_RUNTIME", "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT",
559
- "OATS_TEAM_NAME", "OATS_TEAM_SCOPE", "OATS_TEAM_ID", "OATS_TEAM_LABEL", "OATS_TEAM_LABELS", "OATS_DEFAULT_TEAM", "OATS_DEFAULT_TEAM_ID", "OATS_DEFAULT_TEAM_FROM", "OATS_TEAMS", "OATS_TEAMS_SOURCE", "OATS_TRIGGER_EVENT_FILE",
560
- "OATS_TREE", "OATS_TREE_CLONE", "OATS_TREE_REMOTE", "OATS_TREE_MEMBER", "OATS_TREE_BASE", "OATS_TREE_BASE_OID", "OATS_PURPOSE", "OATS_TREE_ORIGIN",
561
- ]) delete env[key];
562
- return env;
563
- }
564
549
  /** The deployment a spawn job runs in (module contract §5, decision 7): the
565
550
  * scope's oats-local.yaml. An unreadable one is reported (E_WORKSPACE_SCHEMA)
566
551
  * by the spawn, never answered some other way. */
@@ -937,15 +922,6 @@ export function tickWorkspace(ws, { now = new Date(), firedAt = now, io, reg, ws
937
922
  return considered;
938
923
  }
939
924
 
940
- /** One scope's automations context (lib/automations.mjs automationContext) with its oats-local.yaml;
941
- * an unreadable oats-local.yaml means no workspace automations (the local jobs still run). */
942
- export function scopeAutomations(ws, { io, now = new Date(), refresh = false, cache = new Map() } = {}) {
943
- let local = null;
944
- try { local = loadLocal(ws).local; } catch { local = null; }
945
- const clonePathOf = (repoKey) => resolveMemberClone({ deployment: ws, soulEntry: { repoKey }, local });
946
- const ctx = automationContext(ws, { local, io: { ...(io || {}), childEnv }, now, refresh, cache, clonePathOf });
947
- return Object.assign(ctx, { ws, local });
948
- }
949
925
  /** A stored minute key as a time, or null when it is not one. */
950
926
  function minuteTime(key) {
951
927
  const t = typeof key === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(key) ? Date.parse(`${key}:00Z`) : NaN;
package/lib/semver.mjs ADDED
@@ -0,0 +1,12 @@
1
+ /** The order of two kernel or package versions. A leaf (awebai/oats#1630): `oats workspace status`
2
+ * compares versions without loading servers.mjs, which imports it and re-exports it. */
3
+
4
+ export function compareSemver(a, b) {
5
+ const pa = String(a).split(/[.-]/).map((x) => Number.parseInt(x, 10));
6
+ const pb = String(b).split(/[.-]/).map((x) => Number.parseInt(x, 10));
7
+ for (let i = 0; i < 3; i++) {
8
+ const d = (pa[i] || 0) - (pb[i] || 0);
9
+ if (d) return d;
10
+ }
11
+ return 0;
12
+ }
package/lib/servers.mjs CHANGED
@@ -25,11 +25,14 @@ import { parseStrictJson } from "./canonical-json.mjs";
25
25
  import { noteRuntimeName } from "./deprecation.mjs";
26
26
  import { readWaitingClaim } from "./instance-events.mjs";
27
27
  import { readRetireState } from "./retire-state.mjs";
28
+ import { SESSION_END } from "./session-resume-contract.mjs";
28
29
  import { paletteColor } from "./instance-color.mjs";
29
30
  import { withDirLock } from "./dir-lock.mjs";
30
- import { shellWord } from "./core.mjs";
31
+ import { shellWord } from "./shell-word.mjs";
31
32
  import { DETACH_KEY_FEATURE, requireDetachKey } from "./session-viewer.mjs";
32
33
  import { LOGIN_CAPTURE_MAX_BYTES, LOGIN_SHELLS, loginPathEmitter, quoteFor, readLoginFrame } from "./login-environment.mjs";
34
+ import { compareSemver } from "./semver.mjs";
35
+ export { compareSemver } from "./semver.mjs";
33
36
 
34
37
  const OATS_HOME_DIR = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
35
38
  export const SERVERS_FILE = () => join(OATS_HOME_DIR(), "servers.json");
@@ -529,16 +532,6 @@ export const SESSION_REMOTE_VERSION = "0.22.2";
529
532
  * moves to 0.22.2 with that release. */
530
533
  export const MIN_REMOTE_VERSION = "0.22.1";
531
534
 
532
- export function compareSemver(a, b) {
533
- const pa = String(a).split(/[.-]/).map((x) => Number.parseInt(x, 10));
534
- const pb = String(b).split(/[.-]/).map((x) => Number.parseInt(x, 10));
535
- for (let i = 0; i < 3; i++) {
536
- const d = (pa[i] || 0) - (pb[i] || 0);
537
- if (d) return d;
538
- }
539
- return 0;
540
- }
541
-
542
535
  // ---------------------------------------------------------------- snapshots
543
536
 
544
537
  export function snapshotPath(serverId, instance) {
@@ -913,6 +906,11 @@ const rowRetire = (i) => {
913
906
  /** `sameWork` (feature instance-same-work) as `background`: relayed ONLY when the host's row says
914
907
  * `sameWork: true`, the one value a row carries; anything else, and a host that omits it, is absent. */
915
908
  const rowSameWork = (i) => (i.sameWork === true ? { sameWork: true } : {});
909
+ /** `sessionEnd` (feature session-resume, #1628) as `retire` is: relayed ONLY when the host's row has the
910
+ * key, which a host whose kernel predates the feature never sends, so its rows say nothing. A value that
911
+ * is not one of the contract's (lib/session-resume-contract.mjs SESSION_END) drops the key. */
912
+ const SESSION_ENDS = new Set(Object.values(SESSION_END));
913
+ const rowSessionEnd = (i) => (SESSION_ENDS.has(i.sessionEnd) ? { sessionEnd: i.sessionEnd } : {});
916
914
 
917
915
  /** The bounds a host's `features` list must meet to be relayed (feature server-probe-features). */
918
916
  export const HOST_FEATURES_MAX = 256;
@@ -1015,7 +1013,7 @@ export async function rosterGroups({ server, workspaceKeys, io = {} } = {}) {
1015
1013
  harness: i.harness || i.runtime || null, backend: i.tmux ? "tmux" : null,
1016
1014
  ...(i.sessionTarget ? { sessionTarget: i.sessionTarget } : {}), ...(i.tmux ? { tmux: i.tmux } : {}),
1017
1015
  running: typeof i.running === "boolean" ? i.running : null, ...(i.runtimeError ? { runtimeError: i.runtimeError } : {}),
1018
- ...rowFacts(i), ...rowWaiting(i), ...rowRetire(i), ...rowBackground(i), ...rowSameWork(i),
1016
+ ...rowFacts(i), ...rowWaiting(i), ...rowRetire(i), ...rowBackground(i), ...rowSameWork(i), ...rowSessionEnd(i),
1019
1017
  // Every row the host reports is addressed by its home, saved
1020
1018
  // route or not; savedRoute says only that it was spawned from here.
1021
1019
  retirePending: !!i.retirePending, rollbackIncomplete: !!i.rollbackIncomplete, savedRoute: !!snap, addressable: true, missingRemotely: false,
@@ -4,8 +4,9 @@
4
4
  * - `.oats-start-exited`: the window a spawn or a start made writes it when the harness exits,
5
5
  * `{"startId":"<id>","status":<n>}` (the harness's exit status). A kernel before 0.69 wrote the
6
6
  * start id alone on one line, and only from a start's window.
7
- * - `.oats-stop.json`: `oats instance stop` / `oats session stop`, `{ instance, at, stop, retained,
8
- * startId }`; `startId` (0.69) is the start the stop ended, null when the home had none.
7
+ * - `.oats-stop.json`: `oats instance stop` / `oats session stop`, a retire and a restart (before
8
+ * they end the session), `{ instance, at, stop, retained, startId }`; `startId` (0.69) is the
9
+ * start the stop ended, null when the home had none.
9
10
  * A reboot or a killed tmux server leaves neither file for the start that was running: that is a
10
11
  * lost session, the one a resume brings back. Dependency-free: status, start --resume and the
11
12
  * schedule runner read the files through here. */
@@ -0,0 +1,219 @@
1
+ /** inspectInstanceSession: what a home's tmux session is, read under the home's runtime authority (its
2
+ * recorded launch and receipts, the retirement baseline, the Herdr refusal) and the agent pane's
3
+ * liveness. A leaf (awebai/oats#1630): `oats session inspect` reads it without loading core.mjs, which
4
+ * imports these helpers and re-exports what it exported. */
5
+ import { realPathOrNearest, canonicalHomePath } from "./real-path.mjs";
6
+ import { existsSync, readFileSync, lstatSync } from "node:fs";
7
+ import { isAbsolute, join, resolve, dirname, basename } from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { inspectSessionTarget } from "./session-input.mjs";
10
+ import { liveWaiting } from "./instance-events.mjs";
11
+ import { oatsError, herdrInstanceRemoved } from "./errors.mjs";
12
+
13
+ /** A cleanup descriptor is usable only if it can DRIVE the retry, so it is checked
14
+ * as the strict contract its one producer writes — the rollback above — and to the
15
+ * depth the retry CONSUMES it. Three rounds of review landed on this: validating
16
+ * the outer shape only moved the failure from "unparseable" to "parseable and
17
+ * useless", and every tolerance ("field optional", "array is enough") turned into
18
+ * a retry that resolved nothing, reported no failures, and CLEARED the quarantine
19
+ * — deleting the credential while the external state it was holding survived.
20
+ *
21
+ * Required, because the producer always writes them and the retry needs each one:
22
+ * `version` (the contract), `repo` (resolves capabilities and reruns hooks),
23
+ * `work` + `branch`-when-worktree (the rollback-owned Git steps; an unrecognised
24
+ * mode silently skips them), `capabilityRuntime` (handed to runLifecycleHooks AS
25
+ * the capability set, so it must BE one and must contain every outstanding hook),
26
+ * and `outstanding.hooks` (what the retry has to prove it reran).
27
+ *
28
+ * Anything else reads as ABSENT — no more retryable than a missing marker — so the
29
+ * home fails closed by default and `--force` can clear it. */
30
+ function isPlainObject(v) { return !!v && typeof v === "object" && !Array.isArray(v); }
31
+
32
+ // The stored digests are versioned apart (`digestVersion`, BASELINE_DIGEST_VERSION): this version
33
+ // also gates runtime, directory-home and provider-exclusion authority, so a bump would refuse them all.
34
+ const RETIRE_BASELINE_VERSION = 2;
35
+
36
+ function retirementStateRoot(home) {
37
+ // Independent of the bytes it authenticates, but colocated with the agent's
38
+ // already instance-owned storage rather than the source repository or user
39
+ // config home. Retiring <instances>/<name> never removes this sibling.
40
+ return instancesRetirementRoot(dirname(home));
41
+ }
42
+ /** The retirement state of the homes in the instances directory `instances`. */
43
+ function instancesRetirementRoot(instances) {
44
+ return join(instances, ".oats-retirement");
45
+ }
46
+
47
+ /** A home's identity as a receipt records it: its on-disk spelling, own name included. A home that
48
+ * is a symlink is not followed: its parent's on-disk spelling and its name as given (a home
49
+ * exchanged for a symlink is not the home it points at). */
50
+ function receiptHomeIdentity(home) {
51
+ let st;
52
+ try { st = lstatSync(home); } catch { /* not there: spelled as the nearest existing ancestor */ }
53
+ return st && !st.isSymbolicLink() ? canonicalHomePath(home) : join(canonicalHomePath(dirname(home)), basename(home));
54
+ }
55
+
56
+ /** Whether a receipt's recorded home is this home, whatever spelling either was written in.
57
+ * `current` is the home as the caller resolves it for the comparison. */
58
+ function receiptRecordsHome(baseline, current) {
59
+ return typeof baseline?.home === "string" && receiptHomeIdentity(baseline.home) === current;
60
+ }
61
+
62
+ function retirementBaselineFile(identity) {
63
+ return join(retirementStateRoot(identity), "baselines", `${createHash("sha256").update(identity).digest("hex")}.json`);
64
+ }
65
+
66
+ /** Where a spawn writes a home's receipt: keyed by its canonical identity. */
67
+ export function retirementBaselinePath(home) {
68
+ return retirementBaselineFile(receiptHomeIdentity(home));
69
+ }
70
+
71
+ /** Where a kernel before 0.49.0 wrote it: keyed by the parent's realpath in the spawn's own
72
+ * spelling, which on a case-insensitive filesystem need not be the on-disk one. */
73
+ function legacyRetirementBaselinePath(home) {
74
+ return retirementBaselineFile(join(realPathOrNearest(dirname(home)), basename(home)));
75
+ }
76
+
77
+ /** The receipt every reader uses: the canonical one if it exists, else one an earlier kernel left
78
+ * under this caller's spelling, else the canonical path (absent). Read-only: a receipt found at the
79
+ * legacy key is used where it is, never moved, copied or rewritten elsewhere.
80
+ *
81
+ * Limits. A legacy receipt written under spelling S is found only from S, or from the canonical
82
+ * spelling when that is S: a third spelling of such a home misses it (address the home as
83
+ * `oats status` prints it, the spawn's spelling). Receipts outlive retire, so a reused name can
84
+ * leave an earlier incarnation's receipt behind; the canonical one wins, which is right for every
85
+ * home spawned from 0.49.0 on. It is wrong in one case: two incarnations of the same name, both
86
+ * spawned by a kernel before 0.49.0 under different spellings, the earlier one under the canonical
87
+ * spelling. The later home then reads the earlier one's receipt. Its stale endpoint disagrees with
88
+ * instance.json (E_RUNTIME_AUTHORITY_MISMATCH) unless the later incarnation sits at the same
89
+ * endpoint, where session control already targets the right session. Retire finds the home
90
+ * fingerprint changed and preserves the home, less the stale receipt's disposable roots; a
91
+ * directory-work disagreement is E_WORK_INSPECTION_FAILED; and a start's record rewrites the stale
92
+ * file, as a kernel before 0.49.0 already does when a caller's spelling matches an earlier
93
+ * incarnation's. */
94
+ export function findRetirementBaseline(home) {
95
+ const canonical = retirementBaselinePath(home);
96
+ if (existsSync(canonical)) return canonical;
97
+ const legacy = legacyRetirementBaselinePath(home);
98
+ return legacy !== canonical && existsSync(legacy) ? legacy : canonical;
99
+ }
100
+
101
+ /** Herdr (removed in 0.31.0) is recognised in a home only to refuse: its instance.json records a
102
+ * Herdr session target or `backend: "herdr"`, or its independent receipt records a session target
103
+ * (a tmux receipt never does). Either source is enough. */
104
+ function recordsHerdr(meta, baseline) {
105
+ return (isPlainObject(meta) && (meta.sessionTarget !== undefined || meta.backend === "herdr"))
106
+ || (isPlainObject(baseline?.runtime) && baseline.runtime.sessionTarget !== undefined);
107
+ }
108
+ function readJsonOrUndefined(path) { try { return JSON.parse(readFileSync(path, "utf8")); } catch { return undefined; } }
109
+ /** Refuse any session operation on a home opened in Herdr, from its files as they are (either may be
110
+ * missing or unreadable): before any receipt validation, so the refusal is never an endpoint error. */
111
+ function refuseHerdrHome(home) {
112
+ if (recordsHerdr(readJsonOrUndefined(join(home, "instance.json")), readJsonOrUndefined(findRetirementBaseline(home)))) throw herdrInstanceRemoved(basename(home));
113
+ }
114
+
115
+ function runtimeAuthorityOf(baseline) {
116
+ const runtime = baseline?.runtime;
117
+ if (!isPlainObject(runtime) || typeof runtime.launched !== "boolean") return undefined;
118
+ if (!runtime.launched) return { launched: false };
119
+ if (runtime.sessionTarget !== undefined) return undefined;
120
+ const tmux = runtime.tmux;
121
+ if (!isPlainObject(tmux) || ![tmux.session, tmux.window, tmux.socket].every((v) => typeof v === "string" && v.length > 0)) return undefined;
122
+ return { launched: true, tmux: { session: tmux.session, window: tmux.window, socket: resolve(tmux.socket) } };
123
+ }
124
+
125
+ /** The fields of instance.json's tmux endpoint that differ from the one the independent receipt
126
+ * authorises, as fixed labels in a fixed order: `tmux.session`, `tmux.window`, `tmux.socket`. */
127
+ function tmuxEndpointDifferences(meta, authority) {
128
+ return [
129
+ ...(meta.tmux?.session === authority.tmux?.session ? [] : ["tmux.session"]),
130
+ ...(meta.tmux?.window === authority.tmux?.window ? [] : ["tmux.window"]),
131
+ ...(resolve(meta.tmux?.socket || ".") === authority.tmux?.socket ? [] : ["tmux.socket"]),
132
+ ];
133
+ }
134
+ /** instance.json's tmux endpoint is the one the independent receipt authorises. */
135
+ function tmuxEndpointAgrees(meta, authority) { return tmuxEndpointDifferences(meta, authority).length === 0; }
136
+
137
+ /** Whether a blocked or incomplete launch prompt explains metadata's `launched: false` beside a
138
+ * launched receipt. */
139
+ function promptRetained(meta, authority) {
140
+ return authority.launched === true && meta.launched === false && ["blocked", "incomplete"].includes(meta.launchPrompts?.status);
141
+ }
142
+ /** A blocked prompt is a retained runtime, not evidence that no process exists.
143
+ * The independent launched receipt and exact endpoint agreement remain mandatory. */
144
+ function launchStateAgrees(meta, authority) {
145
+ return meta.launched === authority.launched || (promptRetained(meta, authority) && tmuxEndpointAgrees(meta, authority));
146
+ }
147
+
148
+ /** The refusal for instance.json that disagrees with the independent receipt. `details.fields` names
149
+ * what differs, from a fixed vocabulary in a fixed order: `launched` (unless a blocked or incomplete
150
+ * launch prompt explains metadata's `launched: false`), then, for a launched receipt, each differing
151
+ * tmux endpoint field. Labels only: never a path, a value or the receipt. Callers throw it only once
152
+ * their own comparison has refused, so these labels diagnose a refusal and never decide one. */
153
+ function authorityMismatch(message, meta, authority) {
154
+ const fields = [
155
+ ...(meta.launched === authority.launched || promptRetained(meta, authority) ? [] : ["launched"]),
156
+ ...(authority.launched ? tmuxEndpointDifferences(meta, authority) : []),
157
+ ];
158
+ return Object.assign(oatsError("E_RUNTIME_AUTHORITY_MISMATCH", message), { details: { fields } });
159
+ }
160
+
161
+ /** The refusal for a home whose session receipt is at neither key its path gives (findRetirementBaseline):
162
+ * the canonical one, and the one an earlier kernel used for this spelling when that differs. The
163
+ * receipt is keyed by the home's path, so a moved deployment looks elsewhere. */
164
+ function missingSessionReceipt(home) {
165
+ const canonical = retirementBaselinePath(home), legacy = legacyRetirementBaselinePath(home);
166
+ const where = legacy === canonical ? canonical : `${canonical} (nor at ${legacy}, where a kernel before 0.49.0 kept it for this spelling)`;
167
+ return oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `no session receipt for ${home} at ${where}. First address the home exactly as \`oats status\` prints it (a deployment directory moved since spawn looks for the receipt elsewhere, and so does a letter-case spelling other than the spawn's, for a home spawned before 0.49.0). Otherwise the home was copied, the .oats-retirement beside it was removed, or its creation did not finish: stop its session yourself if one runs, then \`oats retire ${basename(home)} --plan\` and \`oats retire ${basename(home)}\` (work is preserved), and respawn.`);
168
+ }
169
+
170
+ /** Why a file could not be read or parsed, in the system's or the parser's words, without the path
171
+ * the sentence already names: `EACCES: permission denied`; a missing file is "it is missing". */
172
+ const unreadableBecause = (e) => e?.code === "ENOENT" ? "it is missing" : String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, "");
173
+
174
+ /** Session control uses the independent endpoint receipt. The receipt and the record are read
175
+ * apart, so that a failure names the file that failed (#1092): one `catch` over both cannot know. */
176
+ function instanceSessionTarget(home, { absentMeta } = {}) {
177
+ if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session needs an absolute instance home");
178
+ home = realPathOrNearest(home);
179
+ refuseHerdrHome(home);
180
+ const receiptPath = findRetirementBaseline(home), recordPath = join(home, "instance.json");
181
+ let baseline, meta;
182
+ try { baseline = JSON.parse(readFileSync(receiptPath, "utf8")); } catch (e) {
183
+ if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home);
184
+ throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home} at ${receiptPath}: ${unreadableBecause(e)}`);
185
+ }
186
+ try { meta = JSON.parse(readFileSync(recordPath, "utf8")); }
187
+ catch (e) {
188
+ // Upgrade may be between the two metadata renames. Its durable journal
189
+ // supplies only the missing record; the independent endpoint still decides.
190
+ if (e.code === "ENOENT" && isPlainObject(absentMeta)) meta = absentMeta;
191
+ else throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: ${unreadableBecause(e)}`);
192
+ }
193
+ // A record that is JSON and no object gives no endpoint to compare the receipt with.
194
+ if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: it holds no JSON object`);
195
+ const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
196
+ if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
197
+ if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw authorityMismatch("instance metadata disagrees with independent session receipt", meta, authority);
198
+ return { home, target: authority.launched ? { backend: "tmux", ...authority.tmux } : undefined };
199
+ }
200
+
201
+ /** `io` (`{ exec }`) is the tmux and process-table seam inspectSessionTarget takes. */
202
+ export function inspectInstanceSession(home, { io, absentMeta } = {}) {
203
+ if (typeof home === "string" && isAbsolute(home) && !existsSync(home)) return { home: realPathOrNearest(home), backend: null, present: false, state: "stopped", running: false, waitingOnYou: null };
204
+ const s = instanceSessionTarget(home, { absentMeta });
205
+ if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", running: false, waitingOnYou: null };
206
+ let observed;
207
+ try { observed = inspectSessionTarget(s.target, io, { includeSize: true }); }
208
+ // The tmux failure stays the cause: sessionServerGone judges it.
209
+ catch (e) { throw Object.assign(oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`), { cause: e }); }
210
+ // Features session-inspect-running and waiting-on-you: beside `state`, whose enum is unchanged.
211
+ // `running` is status's own liveness predicate over this observation, never a second reading.
212
+ const running = harnessRunning(observed);
213
+ return { home: s.home, ...observed, running, waitingOnYou: running ? liveWaiting(s.home) : null };
214
+ }
215
+ /** Whether an observed session runs a harness: present, and neither a
216
+ * fallback shell nor a dead pane. Only such a session can be waiting on a human. */
217
+ function harnessRunning(observed) { return observed?.present === true && observed.state !== "shell" && observed.state !== "stopped"; }
218
+
219
+ export { RETIRE_BASELINE_VERSION, authorityMismatch, harnessRunning, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, runtimeAuthorityOf, tmuxEndpointAgrees };