@awebai/oats 0.52.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +2 -1
  2. package/bin/oats.mjs +314 -92
  3. package/docs/capabilities.md +66 -4
  4. package/docs/configuration.md +66 -3
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +3 -0
  6. package/docs/desktop-cli-api.md +696 -60
  7. package/docs/desktop-instance-start.md +25 -12
  8. package/docs/execution-targets.md +1 -0
  9. package/docs/implementation.md +184 -12
  10. package/docs/integrations.md +6 -3
  11. package/docs/knowledge.md +2 -2
  12. package/docs/macos-test-runs.md +246 -0
  13. package/docs/official-catalog.md +5 -5
  14. package/docs/packages.md +14 -14
  15. package/docs/release-lane.md +210 -6
  16. package/docs/release-notes/v0.53.0.md +1288 -0
  17. package/docs/release-notes/v0.54.0.md +142 -0
  18. package/docs/schedules.md +7 -1
  19. package/docs/souls-and-instances.md +239 -16
  20. package/docs/tui.md +453 -21
  21. package/docs/upgrading.md +310 -0
  22. package/docs/workspaces.md +123 -3
  23. package/lib/automations.mjs +22 -22
  24. package/lib/claim.mjs +93 -4
  25. package/lib/config-data.mjs +4 -1
  26. package/lib/core.mjs +569 -121
  27. package/lib/instance-events.mjs +19 -1
  28. package/lib/instance-git.mjs +39 -3
  29. package/lib/instance-inspect.mjs +5 -6
  30. package/lib/instance-lifecycle.mjs +145 -18
  31. package/lib/instance-resolution.mjs +59 -6
  32. package/lib/launch-preference.mjs +226 -15
  33. package/lib/local-edit.mjs +118 -0
  34. package/lib/packages.mjs +18 -5
  35. package/lib/pi-bridge.mjs +308 -0
  36. package/lib/refused-text.mjs +11 -0
  37. package/lib/remote.mjs +404 -60
  38. package/lib/resolve.mjs +2 -1
  39. package/lib/retained-after-retire.mjs +2 -2
  40. package/lib/retire-output.mjs +12 -1
  41. package/lib/schedule-host.mjs +6 -35
  42. package/lib/shell-word.mjs +13 -0
  43. package/lib/soul-launch-verbs.mjs +153 -0
  44. package/lib/stable-node.mjs +62 -0
  45. package/lib/teams-verbs.mjs +18 -46
  46. package/lib/workspace.mjs +75 -27
  47. package/package-catalog.json +4 -4
  48. package/package.json +2 -1
  49. package/packages/client/attach-exit.mjs +25 -0
  50. package/packages/client/cli-adapter.mjs +16 -3
  51. package/packages/client/cli-locator.mjs +2 -2
  52. package/packages/client/deployment-contract.mjs +4 -0
  53. package/packages/client/deployment-facts.mjs +71 -10
  54. package/packages/client/deployment-panel.mjs +49 -11
  55. package/packages/client/deployment-read-cli.mjs +7 -3
  56. package/packages/client/display-text.mjs +8 -2
  57. package/packages/client/instance-acts.mjs +46 -10
  58. package/packages/client/instance-events-contract.mjs +4 -2
  59. package/packages/client/instance-presentation.mjs +66 -2
  60. package/packages/client/instance-tree.mjs +23 -14
  61. package/packages/client/kernel-lines.mjs +31 -0
  62. package/packages/client/kernel-made.mjs +23 -0
  63. package/packages/client/launch-prompt-outcome.mjs +51 -16
  64. package/packages/client/lifecycle-contract.mjs +45 -4
  65. package/packages/client/liveness.mjs +14 -1
  66. package/packages/client/own-codes.mjs +31 -0
  67. package/packages/client/panel-views.mjs +18 -11
  68. package/packages/client/readiness-contract.mjs +3 -1
  69. package/packages/client/remote-address.mjs +34 -9
  70. package/packages/client/remote-identity-memory.mjs +94 -0
  71. package/packages/client/remote-roster.mjs +92 -6
  72. package/packages/client/session-attach.mjs +175 -0
  73. package/packages/client/spawn-apply-contract.mjs +16 -4
  74. package/packages/client/spawn-messages.mjs +26 -3
  75. package/packages/client/spawn-preview-cli.mjs +8 -2
  76. package/packages/client/spawn-preview-contract.mjs +5 -1
  77. package/packages/client/terminal-exec.mjs +21 -0
  78. package/packages/client/workspace-choices.mjs +95 -0
  79. package/packages/client/workspace-views.mjs +39 -3
  80. package/packages/record/README.md +21 -0
  81. package/packages/record/bin/setup.mjs +108 -15
  82. package/packages/tui/README.md +30 -12
  83. package/packages/tui/lib/actions.mjs +16 -1
  84. package/packages/tui/lib/client.mjs +32 -1
  85. package/packages/tui/lib/config.mjs +151 -0
  86. package/packages/tui/lib/main.mjs +117 -46
  87. package/packages/tui/lib/model.mjs +392 -0
  88. package/packages/tui/lib/read.mjs +473 -0
  89. package/packages/tui/lib/store.mjs +364 -0
  90. package/packages/tui/lib/term/keys.mjs +44 -0
  91. package/packages/tui/lib/term/screen.mjs +16 -4
  92. package/packages/tui/lib/term/text.mjs +60 -0
  93. package/packages/tui/lib/term/tty.mjs +13 -3
  94. package/packages/tui/lib/views/detail.mjs +46 -0
  95. package/packages/tui/lib/views/frame.mjs +230 -36
  96. package/packages/tui/lib/views/help.mjs +125 -13
  97. package/packages/tui/lib/views/instances.mjs +137 -0
  98. package/packages/tui/lib/views/scroll.mjs +19 -0
  99. package/packages/tui/lib/views/switcher.mjs +97 -0
  100. package/skills/oats-getting-started/SKILL.md +8 -2
package/lib/resolve.mjs CHANGED
@@ -227,7 +227,8 @@ export function parseVersion(text) {
227
227
  prerelease: m[4] ? m[4].split(".").map((p) => (/^\d+$/.test(p) ? Number(p) : p)) : [],
228
228
  };
229
229
  }
230
- function compareVersions(a, b) {
230
+ /** Two parsed versions (parseVersion) in semver order: negative, zero or positive. */
231
+ export function compareVersions(a, b) {
231
232
  for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
232
233
  if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0;
233
234
  if (a.prerelease.length === 0) return 1; // a release outranks any prerelease of the same triple
@@ -16,7 +16,7 @@
16
16
  * control characters escaped. */
17
17
  import { closeSync, constants as fsConstants, fstatSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync } from "node:fs";
18
18
  import { isAbsolute, join } from "node:path";
19
- import { instancesDirs, RECOVERABLE_GIT_ADMIN, retainedWorktreesRoot, retirementRecoveryRoot } from "./core.mjs";
19
+ import { gitOperationInProgress, instancesDirs, retainedWorktreesRoot, retirementRecoveryRoot } from "./core.mjs";
20
20
  import { gitRead, gitRepoRead } from "./instance-git.mjs";
21
21
  import { formatBytes } from "./retire-output.mjs";
22
22
  import { joinBytes } from "./tree-copy.mjs";
@@ -210,7 +210,7 @@ function uncommittedClasses(z) {
210
210
  * (`--ignore-submodules=dirty` compares only the commit a submodule is at). */
211
211
  function cleanFacts(path, gitDir) {
212
212
  const classes = [];
213
- if (RECOVERABLE_GIT_ADMIN.some((name) => typeof kindOf(join(gitDir, name)) === "string")) classes.push("an operation in progress");
213
+ if (gitOperationInProgress(gitDir, path)) classes.push("an operation in progress");
214
214
  const uncommitted = classes.length ? `; uncommitted: ${classes.join(", ")}` : "";
215
215
  const filters = contentFilters(path);
216
216
  if (filters.error) return [`clean: unknown (its configuration could not be read: ${shown(filters.error)})${uncommitted}`];
@@ -3,7 +3,8 @@
3
3
  * receipt's `workRecovery` (lib/core.mjs, retireInstance); another renders
4
4
  * its `extraWorktrees`. A receipt from an
5
5
  * older kernel, or a stored one, may carry `workRecoveries[]` instead: one
6
- * block is printed per entry. Dependency-free. */
6
+ * block is printed per entry. A third renders its `warnings`. Dependency-free. */
7
+ import { terminalText } from "./refused-text.mjs";
7
8
 
8
9
  export const formatBytes = (n) => n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`;
9
10
 
@@ -66,3 +67,13 @@ export function extraWorktreeLines(receipt, { host } = {}) {
66
67
  : `Extra worktree ${t.path} re-homed${host ? ` on ${host}` : ""} to ${t.movedTo} (${at}): ${t.reason}`;
67
68
  });
68
69
  }
70
+
71
+ /** The lines `oats retire` prints for a receipt's `warnings`, one per warning. A warning can hold
72
+ * text the kernel did not write: a path as the system resolves it (where a link at `work/` led,
73
+ * awebai/oats#973; the repository Git names for a tree), a hook's own words. Each goes to the
74
+ * terminal through terminalText (lib/refused-text.mjs), so that a name cannot clear the screen or
75
+ * write a line of its own. The receipt's JSON holds each warning as it is. */
76
+ export function warningLines(receipt) {
77
+ const warnings = Array.isArray(receipt?.warnings) ? receipt.warnings : [];
78
+ return warnings.map((w) => ` WARNING: ${terminalText(w)}`);
79
+ }
@@ -8,53 +8,24 @@ import { homedir, platform, userInfo } from "node:os";
8
8
  import { dirname, isAbsolute, join, resolve, sep } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { hostScheduleDir, scheduleError } from "./schedule.mjs";
11
+ import { stableNode as stableNodeRule, unitPathEntries } from "./stable-node.mjs";
11
12
 
12
13
  export const LAUNCHD_LABEL = "ai.oats.schedule-tick";
13
14
  export const SYSTEMD_UNIT = "oats-schedule-tick";
14
15
  const OATS_BIN = join(dirname(fileURLToPath(import.meta.url)), "..", "bin", "oats.mjs");
15
16
  /** The usual prefixes every unit PATH ends with, whether or not this host has them. */
16
17
  const FALLBACK_PATH = ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"];
17
- /** A versioned Homebrew keg: <prefix>/Cellar/<formula>/<version>/…, gone at the next upgrade. */
18
- const KEG = /^(.*)\/Cellar\/([^/]+)\/([^/]+)\//;
19
18
  const REINSTALL = "run `oats schedule host install` again from the operator's shell (not from an instance home)";
20
19
 
21
20
  function escapeXml(s) { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }
22
21
  function unescapeXml(s) { return String(s).replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&"); }
23
22
 
24
- /** The installer's PATH entries a unit may carry. Dropped: entries inside an
25
- * OATS instance home (an instance's `.oats/bin`, anything under
26
- * `instanceHome`), entries inside a versioned Homebrew keg, and relative or
27
- * empty entries. An entry missing today is kept: it may exist when the tick
28
- * runs, and status reports it while it does not. */
29
- export function unitPathEntries(envPath, { instanceHome = process.env.OATS_INSTANCE_HOME } = {}) {
30
- const home = instanceHome && isAbsolute(instanceHome) ? resolve(instanceHome) : null;
31
- const hazard = (entry) => {
32
- if (!entry || !isAbsolute(entry)) return true;
33
- const segments = entry.split(sep);
34
- if (segments.some((s, i) => s === ".oats" && segments[i + 1] === "bin")) return true;
35
- if (home && (resolve(entry) === home || resolve(entry).startsWith(home + sep))) return true;
36
- return KEG.test(entry.endsWith("/") ? entry : `${entry}/`);
37
- };
38
- return String(envPath || "").split(":").filter((entry) => !hazard(entry));
39
- }
40
-
23
+ export { unitPathEntries };
41
24
  function realpathOrNull(p) { try { return realpathSync(p); } catch { return null; } }
42
- /** The node a unit runs: one that survives a Homebrew upgrade. A keg's
43
- * `<prefix>/opt/<formula>/bin/node` when it is this node, else the first
44
- * `node` on the filtered PATH that is this node, else `execPath` with a
45
- * warning that the path is not stable. */
46
- export function stableNode({ execPath = process.execPath, envPath = process.env.PATH || "", instanceHome = process.env.OATS_INSTANCE_HOME } = {}) {
47
- const real = realpathOrNull(execPath);
48
- const keg = real && KEG.exec(real);
49
- if (keg) {
50
- const opt = join(keg[1], "opt", keg[2], "bin", "node");
51
- if (realpathOrNull(opt) === real) return { node: opt };
52
- }
53
- for (const entry of unitPathEntries(envPath, { instanceHome })) {
54
- const candidate = join(entry, "node");
55
- if (real && realpathOrNull(candidate) === real) return { node: candidate };
56
- }
57
- return { node: execPath, warning: `the node path ${execPath} is not stable (no Homebrew opt link and no node on PATH resolves to it): the timer stops when it goes away; install a node with a stable path and run \`oats schedule host install\` again` };
25
+ /** The node a unit runs: the rule of lib/stable-node.mjs, its warning worded
26
+ * for the timer. */
27
+ export function stableNode(o = {}) {
28
+ return stableNodeRule({ ...o, consequence: "the timer stops when it goes away", remedy: "run `oats schedule host install` again" });
58
29
  }
59
30
 
60
31
  /** launchd and systemd start units with a short PATH that has no Homebrew
@@ -0,0 +1,13 @@
1
+ /**
2
+ * A word of a command line the kernel prints for a person or an agent to paste into a shell. PURE: no
3
+ * I/O and no import, so a module lib/core.mjs imports (lib/launch-preference.mjs) can use the same rule
4
+ * as core, which re-exports both names.
5
+ */
6
+
7
+ /** `s` single-quoted for a POSIX shell. */
8
+ export function shq(s) { return `'${String(s).replace(/'/g, `'\\''`)}'`; }
9
+ /** One word of a command line that a person or an agent pastes into a shell: as it is when it holds
10
+ * only letters, digits and `_./:-`, single-quoted otherwise (an empty string too). The safe set is
11
+ * deliberately small: no `~` (an unquoted leading one expands), no `=` (zsh expands a leading
12
+ * `=word`). */
13
+ export function shellWord(s) { const word = String(s); return /^[A-Za-z0-9_.\/:-]+$/.test(word) ? word : shq(word); }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * `oats soul launch set|remove` (feature `soul-launch`, awebai/oats#990; docs/desktop-cli-api.md
3
+ * "`oats soul launch`"): the supported writer of oats-local.yaml `souls.launch`, a soul's launch preference
4
+ * on this machine (lib/launch-preference.mjs). It writes the key a soul has (soulKeyOf), so it cannot
5
+ * write a key that names no soul; `remove` also takes the exact text of a key in the file, the remedy
6
+ * for a key that names none, and that form works when the workspace's souls cannot be read.
7
+ * The file is rewritten through the path `oats teams` writes it by (lib/local-edit.mjs): one entry set
8
+ * or deleted in the parsed document, every other entry kept with its value and its comments.
9
+ */
10
+ import YAML from "yaml";
11
+ import { oatsError } from "./errors.mjs";
12
+ import { editLocal, readLocal } from "./local-edit.mjs";
13
+ import { LOCAL_FILE, launchKeyAt, launchKeysUnmatched, launchLayers, launchValueOf } from "./launch-preference.mjs";
14
+ import { findSoulEntry, qualifiedSoulName, soulCandidates, soulsOffered } from "./instance-resolution.mjs";
15
+ import { soulKeyOf } from "./teams.mjs";
16
+ import { LAUNCH_HARNESSES, launchConfigsAt, launchReportFor } from "./core.mjs";
17
+
18
+ export const SOUL_LAUNCH_API = 1;
19
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
20
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
21
+ function fail(code, message, details) { const e = oatsError(code, message, details); e.details = details; return e; }
22
+ const isRefusal = (e) => typeof e?.code === "string" && e.code.startsWith("E_");
23
+ const launchOf = (local) => (isObject(local?.souls?.launch) ? local.souls.launch : {});
24
+ const NAMED = 10;
25
+ const named = (list) => (list.length > NAMED ? [...list.slice(0, NAMED), `and ${list.length - NAMED} more`] : list).join(", ");
26
+
27
+ /** The entry `set` writes, from its flags: a launch configuration's name (`none` included), or the inline
28
+ * `{ harness, model? }`. Exactly one of `launchConfig` and `harness`; `model` only with `harness`. */
29
+ export function soulLaunchValue({ launchConfig, harness, model } = {}) {
30
+ if (launchConfig !== undefined && harness !== undefined) throw fail("E_BAD_ARGS", "oats soul launch set takes --launch-config <name>|none or --harness <h>, not both", { flags: ["--launch-config", "--harness"] });
31
+ if (launchConfig === undefined && harness === undefined) throw fail("E_BAD_ARGS", `oats soul launch set needs what to pin the soul to: --launch-config <name>|none, or --harness ${LAUNCH_HARNESSES.join("|")} [--model <id>]`, {});
32
+ if (launchConfig !== undefined) {
33
+ if (model !== undefined) throw fail("E_BAD_ARGS", "--model goes with --harness: a launch configuration carries its own model (oats launch-config set)", { flags: ["--launch-config", "--model"] });
34
+ return launchConfig;
35
+ }
36
+ if (!LAUNCH_HARNESSES.includes(harness)) throw fail("E_BAD_ARGS", `--harness must be one of ${LAUNCH_HARNESSES.join(", ")} (got ${JSON.stringify(harness)})`, { harness });
37
+ if (model !== undefined && !/^[^\s-][^\s]*$/.test(model)) throw fail("E_BAD_ARGS", `--model takes a model id: no whitespace, and no leading "-" (got ${JSON.stringify(model)})`, { model });
38
+ return { harness, ...(model !== undefined ? { model } : {}) };
39
+ }
40
+
41
+ /** Set or delete `souls.launch.<key>` in the document, and nothing else. A map left empty is removed
42
+ * (`souls.launch`, then `souls`). An entry that stays keeps its own key node, so its quoting and comment. */
43
+ function applyEntry(doc, key, value) {
44
+ if (value === null) {
45
+ doc.deleteIn(["souls", "launch", key]);
46
+ for (const path of [["souls", "launch"], ["souls"]]) {
47
+ const node = doc.getIn(path);
48
+ if (YAML.isMap(node) && node.items.length === 0) doc.deleteIn(path);
49
+ }
50
+ return;
51
+ }
52
+ // A key that holds no map (`souls:` with nothing under it) is replaced by the map the entry needs.
53
+ for (const path of [["souls"], ["souls", "launch"]]) if (doc.hasIn(path) && !YAML.isMap(doc.getIn(path))) doc.deleteIn(path);
54
+ doc.setIn(["souls", "launch", key], typeof value === "string" ? value : doc.createNode(value));
55
+ }
56
+ /** The local value this edit must read back as: `before` with the one entry set or deleted (value null). */
57
+ function expectedAfter(before, key, value) {
58
+ const next = structuredClone(before);
59
+ if (value === null) {
60
+ delete next.souls.launch[key];
61
+ if (Object.keys(next.souls.launch).length === 0) delete next.souls.launch;
62
+ if (Object.keys(next.souls).length === 0) delete next.souls;
63
+ return next;
64
+ }
65
+ if (!isObject(next.souls)) next.souls = {};
66
+ if (!isObject(next.souls.launch)) next.souls.launch = {};
67
+ next.souls.launch[key] = structuredClone(value);
68
+ return next;
69
+ }
70
+ /** Where two values differ, as JSON pointers (never the values: this file holds host paths). A map whose
71
+ * keys are the same in another order differs at the map. */
72
+ function differences(a, b, path = "", out = []) {
73
+ if (!isObject(a) || !isObject(b)) { if (!same(a, b)) out.push(path || "/"); return out; }
74
+ const ka = Object.keys(a), kb = Object.keys(b);
75
+ if (!same(ka, kb)) {
76
+ const stray = [...ka.filter((k) => !Object.hasOwn(b, k)), ...kb.filter((k) => !Object.hasOwn(a, k))];
77
+ if (stray.length) for (const k of stray) out.push(`${path}/${String(k).replace(/~/g, "~0").replace(/\//g, "~1")}`);
78
+ else out.push(path || "/");
79
+ }
80
+ for (const k of ka) if (Object.hasOwn(b, k)) differences(a[k], b[k], `${path}/${String(k).replace(/~/g, "~0").replace(/\//g, "~1")}`, out);
81
+ return out;
82
+ }
83
+
84
+ /**
85
+ * `oats soul launch set|remove`. `ctx`: { deployment, localPath }. `name`: the command's argument (a soul
86
+ * as a spawn names it, "*", or for `remove` the exact text of a key in the file). `value`: soulLaunchValue's
87
+ * (set only). `plan`: every check, nothing written. `readSouls()` reads the workspace → its discovery
88
+ * (discoverOrStandalone), and throws that read's own error.
89
+ * → the `soulLaunchApi: 1` answer. Every refusal is thrown before a byte of the file changes.
90
+ */
91
+ export async function soulLaunch(ctx, { action, name, value = null, plan = false }, { readSouls }) {
92
+ const star = name === "*";
93
+ // `remove` first tries its argument as the exact text of a key the file has now: that form needs no
94
+ // read of the workspace, so it goes on (and says so: `unread`) when the souls cannot be read.
95
+ const now = action === "remove" ? launchOf(readLocal(ctx.localPath).local) : {};
96
+ const exact = action === "remove" && Object.hasOwn(now, name);
97
+ if (action === "remove" && star && !exact) throw unknownEntry("*", now);
98
+ let discovery = null, unread = null;
99
+ try { discovery = await readSouls(); }
100
+ catch (e) { if (!exact || !isRefusal(e)) throw e; unread = { code: e.code, message: String(e.message) }; }
101
+ const entry = star || exact ? null : findSoulEntry(discovery, name);
102
+ const key = entry ? soulKeyOf(entry) : name;
103
+
104
+ let before = null;
105
+ const result = editLocal(ctx, { verb: `oats soul launch ${action}`, plan }, ({ doc, local }) => {
106
+ const entries = launchOf(local);
107
+ before = Object.hasOwn(entries, key) ? launchValueOf(entries[key]) : null;
108
+ if (action === "remove") { if (!Object.hasOwn(entries, key)) throw unknownEntry(key, entries); }
109
+ else {
110
+ // The same fact a spawn reports, said before the file holds it.
111
+ const configs = isObject(local?.["launch-configs"]) ? local["launch-configs"] : {};
112
+ if (typeof value === "string" && value !== "none" && !Object.hasOwn(configs, value)) {
113
+ throw fail("E_LAUNCH_CONFIG_UNKNOWN", `--launch-config ${JSON.stringify(value)} is no launch configuration ${LOCAL_FILE} declares (launch-configs:); oats launch-config list shows what is; nothing was written`, { name: value, from: star ? "local-default" : "local", at: launchKeyAt(key) });
114
+ }
115
+ if (Object.hasOwn(entries, key) && same(before, launchValueOf(value))) return null;
116
+ }
117
+ const written = action === "remove" ? null : value;
118
+ applyEntry(doc, key, written);
119
+ const expected = expectedAfter(local, key, written);
120
+ return { check: (next) => {
121
+ const differ = differences(expected, next);
122
+ if (differ.length) throw fail("E_WORKSPACE_SCHEMA", `the rewritten ${LOCAL_FILE} would not read back as this edit of souls.launch and nothing else (it differs at ${named(differ)}); nothing was written`, { path: ctx.localPath, reason: "read-back", differs: differ });
123
+ } };
124
+ });
125
+
126
+ const local = result.local;
127
+ const after = Object.hasOwn(launchOf(local), key) ? launchValueOf(launchOf(local)[key]) : null;
128
+ const answer = { soulLaunchApi: SOUL_LAUNCH_API, action, plan, key, souls: null, level: ctx.deployment, file: ctx.localPath, before, after, changed: result.changed, launch: null, unmatched: null, unread };
129
+ if (unread) return answer;
130
+ // What the entry applies to: every offered soul with that key (two members' souls of one bare name share it).
131
+ const applies = star ? [] : soulCandidates(discovery).map((c) => c.entry).filter((e) => soulKeyOf(e) === key)
132
+ .sort((a, b) => (qualifiedSoulName(a) < qualifiedSoulName(b) ? -1 : qualifiedSoulName(a) > qualifiedSoulName(b) ? 1 : 0));
133
+ if (!star) answer.souls = applies.map(qualifiedSoulName);
134
+ // The soul the command named; a key given by its exact text names the first soul it applies to.
135
+ const subject = entry ?? applies[0] ?? null;
136
+ const offered = soulsOffered(discovery);
137
+ if (subject) {
138
+ let launchConfigs = {};
139
+ try { launchConfigs = launchConfigsAt(ctx.deployment); } catch { launchConfigs = {}; }
140
+ // As a spawn of it would decide: a soul left on the fall-through beside a key that names no soul
141
+ // carries that refusal as the report's problem.
142
+ answer.launch = launchReportFor({ layers: launchLayers({ definition: subject.definition, entry: subject, key, local, offered }), launchConfigs, contextDir: ctx.deployment });
143
+ }
144
+ answer.unmatched = launchKeysUnmatched({ local, offered }).unmatched;
145
+ return answer;
146
+ }
147
+
148
+ /** E_LAUNCH_PREFERENCE_UNKNOWN: `remove` of an entry the file does not have. Never "done": a mistyped
149
+ * remove must not leave the entry its operator believes is gone. */
150
+ function unknownEntry(key, entries) {
151
+ const keys = Object.keys(entries).sort();
152
+ return fail("E_LAUNCH_PREFERENCE_UNKNOWN", `${LOCAL_FILE} souls.launch has no entry ${JSON.stringify(key)} (${keys.length ? `it has ${named(keys.map((k) => JSON.stringify(k)))}` : "it has none"}); nothing was written`, { key, keys });
153
+ }
@@ -0,0 +1,62 @@
1
+ /** The one rule for a node path that is written into something that outlives
2
+ * the process (a unit, a harness's settings): a path that survives an upgrade
3
+ * of Node. The host timer's unit (lib/schedule-host.mjs) and OATS_NODE_BIN,
4
+ * which every hook, provider check and dispatched command receives, are both
5
+ * this rule's answer. It imports nothing of the kernel, so any module can. */
6
+ import { realpathSync } from "node:fs";
7
+ import { isAbsolute, join, resolve, sep } from "node:path";
8
+
9
+ /** A versioned Homebrew keg: <prefix>/Cellar/<formula>/<version>/…, gone at the next upgrade. */
10
+ const KEG = /^(.*)\/Cellar\/([^/]+)\/([^/]+)\//;
11
+
12
+ /** The installer's PATH entries a unit may carry. Dropped: entries inside an
13
+ * OATS instance home (an instance's `.oats/bin`, anything under
14
+ * `instanceHome`), entries inside a versioned Homebrew keg, and relative or
15
+ * empty entries. An entry missing today is kept: it may exist when the tick
16
+ * runs, and status reports it while it does not. */
17
+ export function unitPathEntries(envPath, { instanceHome = process.env.OATS_INSTANCE_HOME } = {}) {
18
+ const home = instanceHome && isAbsolute(instanceHome) ? resolve(instanceHome) : null;
19
+ const hazard = (entry) => {
20
+ if (!entry || !isAbsolute(entry)) return true;
21
+ const segments = entry.split(sep);
22
+ if (segments.some((s, i) => s === ".oats" && segments[i + 1] === "bin")) return true;
23
+ if (home && (resolve(entry) === home || resolve(entry).startsWith(home + sep))) return true;
24
+ return KEG.test(entry.endsWith("/") ? entry : `${entry}/`);
25
+ };
26
+ return String(envPath || "").split(":").filter((entry) => !hazard(entry));
27
+ }
28
+
29
+ function realpathOrNull(p) { try { return realpathSync(p); } catch { return null; } }
30
+ /** A node path that survives a Homebrew upgrade. A keg's
31
+ * `<prefix>/opt/<formula>/bin/node` when it is this node, else the first
32
+ * `node` on the filtered PATH that is this node, else `execPath` with a
33
+ * warning that the path is not stable. The warning states the fact; the
34
+ * caller words what it loses (`consequence`) and what to do after installing
35
+ * a stable node (`remedy`). */
36
+ export function stableNode({ execPath = process.execPath, envPath = process.env.PATH || "", instanceHome = process.env.OATS_INSTANCE_HOME, consequence, remedy } = {}) {
37
+ const real = realpathOrNull(execPath);
38
+ const keg = real && KEG.exec(real);
39
+ if (keg) {
40
+ const opt = join(keg[1], "opt", keg[2], "bin", "node");
41
+ if (realpathOrNull(opt) === real) return { node: opt };
42
+ }
43
+ for (const entry of unitPathEntries(envPath, { instanceHome })) {
44
+ const candidate = join(entry, "node");
45
+ if (real && realpathOrNull(candidate) === real) return { node: candidate };
46
+ }
47
+ return { node: execPath, warning: `the node path ${execPath} is not stable (no Homebrew opt link and no node on PATH resolves to it)${consequence ? `: ${consequence}` : ""}${remedy ? `; install a node with a stable path and ${remedy}` : ""}` };
48
+ }
49
+
50
+ let kernel = null;
51
+ /** The rule's answer for the node running this kernel, on the kernel's own
52
+ * PATH: `node` is OATS_NODE_BIN, and `warning` (the third case only) is what a
53
+ * spawn and a start say, worded for a home's hooks. The rule reads the file
54
+ * system, so it is computed once for the node, PATH and instance home this
55
+ * process runs with, not once per hook. */
56
+ export function kernelNode() {
57
+ const key = [process.execPath, process.env.PATH || "", process.env.OATS_INSTANCE_HOME || ""].join("\0");
58
+ if (kernel?.key !== key) {
59
+ kernel = { key, answer: stableNode({ consequence: "what this home's hooks record with it stops working when it goes away", remedy: "restart the instance" }) };
60
+ }
61
+ return kernel.answer;
62
+ }
@@ -7,15 +7,11 @@
7
7
  * schema, and no label reference the write would leave unknown. A soul's teams are the workspace's
8
8
  * `souls:`, edited by a PR to that file: `oats soul teams` only reads them.
9
9
  */
10
- import { readFileSync } from "node:fs";
11
- import { join } from "node:path";
12
10
  import YAML from "yaml";
13
- import { parseConfigData } from "./config-data.mjs";
14
11
  import { oatsError } from "./errors.mjs";
15
- import { teamLabelProblem, validateLocal } from "./workspace.mjs";
12
+ import { teamLabelProblem } from "./workspace.mjs";
16
13
  import { TEAM_ID_RE, localTeamsClosed, soulTeams, teamModel, teamProblems, teamReferences } from "./teams.mjs";
17
- import { writeFileAtomic } from "./packages.mjs";
18
- import { withDirLock } from "./dir-lock.mjs";
14
+ import { editLocal } from "./local-edit.mjs";
19
15
 
20
16
  export const TEAMS_API = 2, SOUL_TEAMS_API = 2;
21
17
  const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -66,13 +62,6 @@ const modelOf = (ctx, local) => teamModel(ctx.workspace, local, { workspaceKey:
66
62
  const refusals = (ctx, local) => new Map(teamProblems(modelOf(ctx, local))
67
63
  .filter((p) => p.code === "E_TEAM_UNKNOWN").map((p) => [`${p.code} ${p.at}`, p]));
68
64
  const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
69
- const readLocal = (ctx) => {
70
- const text = readFileSync(ctx.localPath, "utf8");
71
- const doc = YAML.parseDocument(text, { keepSourceTokens: true });
72
- if (doc.errors?.length) throw fail("E_WORKSPACE_SCHEMA", `${ctx.localPath}: ${doc.errors[0].message}`, { path: ctx.localPath });
73
- return { text, doc, local: parseConfigData(text, { origin: { kind: "local", path: ctx.localPath } }).value };
74
- };
75
-
76
65
  /**
77
66
  * Edit `doc` from `before` to `next` SURGICALLY: only the entries that change are touched, so comments and
78
67
  * styles on everything else (inline comments on sibling entries) are kept. A map left empty is removed.
@@ -94,46 +83,29 @@ function applyState(doc, before, next) {
94
83
  }
95
84
 
96
85
  /**
97
- * Rewrite oats-local.yaml. `mutate(state, model)` edits the plain `state` (teamState) and may throw a
98
- * refusal; both come from the file AS IT IS NOW (re-read here, never the command's startup snapshot), so
99
- * two verbs running together cannot drop each other's change: the write is compare-and-swap — when the
100
- * file changed after this read, the edit is redone on the new content (a few times, then E_LOCAL_CHANGED).
86
+ * Rewrite oats-local.yaml through the shared edit path (lib/local-edit.mjs editLocal: the file as it is
87
+ * NOW, the deployment's local lock, compare-and-swap, the local schema). `mutate(state, model)` edits the
88
+ * plain `state` (teamState) and may throw a refusal; both come from the file as that path read it, so two
89
+ * verbs running together cannot drop each other's change, and a conditional write sees every earlier one.
101
90
  * `verb` names the command and `writes` the keys it adds, for the refusal where the workspace does not
102
91
  * allow local teams (local-teams-closed); a verb that only takes local teams away (`writes: null`) runs
103
92
  * there too, since it moves the file toward what the workspace allows. → { changed, local } (the value now).
104
- * The whole read-compare-write runs under the deployment's local lock (localLock), so among `oats teams`
105
- * writers the compare and the rename are one step: a conditional write sees every earlier one.
93
+ * A write is also refused when it would leave a label reference unknown that the file did not have.
106
94
  */
107
- function editLocal(ctx, { verb, writes }, mutate) {
108
- const lock = localLock(ctx);
109
- return withDirLock(lock, `${verb} on ${ctx.localPath}`, () => editLocalLocked(ctx, { verb, writes }, mutate), {
110
- retryMs: 5000,
111
- busy: (why) => fail("E_LOCAL_BUSY", `${ctx.localPath} is being edited by another oats process (the lock ${lock}: ${why}); if no oats teams command is running, remove ${lock} and retry; nothing was written`, { path: ctx.localPath, lock }),
112
- });
113
- }
114
- /** The lock every `oats teams` mutation holds: in the deployment's kernel state tree, never beside the files. */
115
- const localLock = (ctx) => join(ctx.deployment, ".agents", "locks", "local.lock");
116
- function editLocalLocked(ctx, { verb, writes }, mutate) {
117
- for (let attempt = 0; attempt < 5; attempt++) {
118
- const { text, doc, local: current } = readLocal(ctx);
95
+ function editTeams(ctx, { verb, writes }, mutate) {
96
+ return editLocal(ctx, { verb }, ({ doc, local: current }) => {
119
97
  const model = modelOf(ctx, current);
120
98
  if (model.localTeams === false && writes !== null) throw localTeamsClosed(writes, { verb });
121
99
  const before = teamState(current);
122
100
  const next = teamState(current);
123
101
  mutate(next, model);
124
- if (same(next, before)) return { changed: false, local: current };
102
+ if (same(next, before)) return null;
125
103
  applyState(doc, before, next);
126
- const out = doc.toString();
127
- const local = parseConfigData(out, { origin: { kind: "local", path: ctx.localPath } }).value;
128
- const problems = validateLocal(local);
129
- if (problems.length) throw fail("E_WORKSPACE_SCHEMA", `the rewritten oats-local.yaml would be invalid (${problems.map((p) => `${p.path || "/"}: ${p.message}`).join("; ")}); nothing was written`, { problems });
130
- const had = refusals(ctx, current);
131
- for (const [k, p] of refusals(ctx, local)) if (!had.has(k)) throw fail(p.code, `${p.message}; nothing was written`, Object.fromEntries(Object.entries(p).filter(([key]) => !["code", "severity", "message", "fix"].includes(key))));
132
- if (readFileSync(ctx.localPath, "utf8") !== text) continue; // changed under us: redo on the new content
133
- writeFileAtomic(ctx.localPath, out);
134
- return { changed: true, local };
135
- }
136
- throw fail("E_LOCAL_CHANGED", `${ctx.localPath} kept changing while this edit ran; nothing was written — run it again`, { path: ctx.localPath });
104
+ return { check: (local) => {
105
+ const had = refusals(ctx, current);
106
+ for (const [k, p] of refusals(ctx, local)) if (!had.has(k)) throw fail(p.code, `${p.message}; nothing was written`, Object.fromEntries(Object.entries(p).filter(([key]) => !["code", "severity", "message", "fix"].includes(key))));
107
+ } };
108
+ });
137
109
  }
138
110
 
139
111
  const assertLabel = (label) => {
@@ -149,7 +121,7 @@ export function teamsAdd(ctx, label, { team, description, noDefault = false } =
149
121
  if (typeof team !== "string" || !team.trim()) throw fail("E_BAD_ARGS", "oats teams add needs --team <provider team id>", { label });
150
122
  if (!TEAM_ID_RE.test(team.trim())) throw fail("E_BAD_ARGS", `${JSON.stringify(team)} is not a team id: it must match ${TEAM_ID_RE.source} (a letter or digit first; no whitespace or control characters; at most 256 characters)`, { label, team });
151
123
  let reused = false;
152
- const result = editLocal(ctx, { verb: "oats teams add", writes: ["teams"] }, (s, model) => {
124
+ const result = editTeams(ctx, { verb: "oats teams add", writes: ["teams"] }, (s, model) => {
153
125
  if (model.labels.has(label)) {
154
126
  const { from, team: existing } = model.labels.get(label);
155
127
  if (noDefault && existing === team.trim()) { reused = true; return; }
@@ -165,7 +137,7 @@ export function teamsAdd(ctx, label, { team, description, noDefault = false } =
165
137
  /** `oats teams remove <label>`: a LOCAL team nothing references (no cascade). Allowed where the workspace
166
138
  * does not allow local teams: removing them is the last step of committing them there. */
167
139
  export function teamsRemove(ctx, label) {
168
- return editLocal(ctx, { verb: "oats teams remove", writes: null }, (s, model) => {
140
+ return editTeams(ctx, { verb: "oats teams remove", writes: null }, (s, model) => {
169
141
  if (!model.local.has(label)) {
170
142
  if (model.shared.has(label)) throw fail("E_TEAM_SHARED", `team ${label} is shared (declared in oats-workspace.yaml): it is edited by a PR to that file, never removed here`, { label, at: model.shared.get(label).at });
171
143
  throw fail("E_TEAM_UNKNOWN", `team ${JSON.stringify(label)} is not declared`, { label });
@@ -192,7 +164,7 @@ function assertDefaultPrecondition(model, { ifAbsent, expect }) {
192
164
  * judged inside the edit, on the file as it is now (and again on every retry), after today's refusals. */
193
165
  export function teamsDefault(ctx, label, { ifAbsent = false, expect } = {}) {
194
166
  if (ifAbsent && expect !== undefined) throw fail("E_BAD_ARGS", "oats teams default takes --if-absent or --expect <label>, not both", { label });
195
- return editLocal(ctx, { verb: "oats teams default", writes: ["defaultTeam"] }, (s, model) => {
167
+ return editTeams(ctx, { verb: "oats teams default", writes: ["defaultTeam"] }, (s, model) => {
196
168
  if (!model.labels.has(label)) throw fail("E_TEAM_UNKNOWN", `team ${JSON.stringify(label)} is not declared: \`oats teams add\` it first`, { label });
197
169
  if (ifAbsent || expect !== undefined) assertDefaultPrecondition(model, { ifAbsent, expect });
198
170
  s.defaultTeam = label;