@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
@@ -7,6 +7,8 @@
7
7
  * frozen: a plain start/restart never re-reads these layers (only --reselect-launch or a respawn does).
8
8
  */
9
9
  import { oatsError } from "./errors.mjs";
10
+ import { REFUSED_TEXT, safeText } from "./refused-text.mjs";
11
+ import { shellWord } from "./shell-word.mjs";
10
12
 
11
13
  export const LOCAL_FILE = "oats-local.yaml";
12
14
  const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -31,18 +33,22 @@ export function soulLaunchAt(entry) {
31
33
  * — the deciding one, `{ from: "local" | "local-default" | "soul", at, value }` (`value` a launch
32
34
  * configuration's name or `{harness, model}`) — or null (the host default).
33
35
  * `definition` is the soul.yaml content; `key` its soul key (soulKeyOf); `local` the oats-local.yaml value.
36
+ * `offered` describes a read of the workspace (lib/instance-resolution.mjs soulsOffered): with it the
37
+ * layers carry `unmatched`, the keys of souls.launch that name no soul (launchKeysUnmatched), so every
38
+ * caller that has layers has that fact and none computes it; without it (a caller that made no read)
39
+ * `unmatched` is empty. `key` travels too: a refusal names the soul it refused.
34
40
  */
35
- export function launchLayers({ definition, entry, key, local }) {
41
+ export function launchLayers({ definition, entry, key, local, offered = null }) {
36
42
  const declared = preferenceOf(definition?.launch);
37
43
  const byKey = isObject(local?.souls?.launch) ? local.souls.launch : {};
38
44
  const pick = (k, from) => {
39
45
  if (!Object.hasOwn(byKey, k)) return null;
40
46
  const v = byKey[k];
41
- return { from, at: `${LOCAL_FILE}#/souls/launch/${pointerKey(k)}`, value: typeof v === "string" ? v : preferenceOf(v) };
47
+ return { from, at: launchKeyAt(k), value: launchValueOf(v) };
42
48
  };
43
49
  const layer = (key !== undefined && key !== "*" ? pick(key, "local") : null) ?? pick("*", "local-default")
44
50
  ?? (declared ? { from: "soul", at: soulLaunchAt(entry), value: declared } : null);
45
- return { declared, layer };
51
+ return { declared, layer, key: key ?? null, unmatched: offered ? launchKeysUnmatched({ local, offered }).unmatched : [] };
46
52
  }
47
53
 
48
54
  /**
@@ -60,38 +66,243 @@ export function selectionFrom({ flags = {}, layers }) {
60
66
  return { selection: { ...selection, launchConfig: "none" }, preference: { ...layer.value, from: layer.from }, from: layer.from, at: layer.at };
61
67
  }
62
68
 
69
+ /** Where a key of souls.launch is: `oats-local.yaml#/souls/launch/<key>`, the key as a JSON pointer token. */
70
+ export const launchKeyAt = (key) => `${LOCAL_FILE}#/souls/launch/${pointerKey(key)}`;
71
+ /** An entry of souls.launch as an answer carries it: a launch configuration's name (or "none"), or
72
+ * `{harness, model}` (`model` null when it has none); null for no entry, or a value that is neither. */
73
+ export function launchValueOf(v) { return typeof v === "string" ? v : preferenceOf(v); }
74
+
75
+ const byCodepoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
76
+ const bareName = (key) => key.slice(key.lastIndexOf("/") + 1);
77
+ /** The edit distance between two names (insert, delete, replace), or `over` when it is more than `max`. */
78
+ function editDistance(a, b, max, over = max + 1) {
79
+ if (Math.abs(a.length - b.length) > max) return over;
80
+ let row = Array.from({ length: b.length + 1 }, (_, j) => j);
81
+ for (let i = 1; i <= a.length; i++) {
82
+ const next = [i];
83
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
84
+ row = next;
85
+ }
86
+ return row[b.length] > max ? over : row[b.length];
87
+ }
88
+ const SUGGESTIONS = 3, NEAR = 2;
89
+ /** The offered soul keys nearest to `key`, at most three: first those with its bare name (the part after
90
+ * the last `/`), then those whose bare name is within two edits, by distance then by code point. */
91
+ function nearestSoulKeys(key, offered) {
92
+ const bare = bareName(key);
93
+ const ranked = [];
94
+ for (const k of offered) { const d = editDistance(bareName(k), bare, NEAR); if (d <= NEAR) ranked.push([d, k]); }
95
+ return ranked.sort((a, b) => a[0] - b[0] || byCodepoint(a[1], b[1])).slice(0, SUGGESTIONS).map(([, k]) => k);
96
+ }
97
+
98
+ /**
99
+ * THE function that decides which keys of souls.launch name no soul (awebai/oats#989): every reader asks it
100
+ * and none computes the answer itself. `local` is the oats-local.yaml value. `offered` describes one read
101
+ * of the workspace (lib/instance-resolution.mjs soulsOffered): `keys`, the soul key of every soul it
102
+ * offers (a soul in souls.disabled included), and `unread`, what that read could not see:
103
+ * `all`: a reason when no key can be checked (the standalone view of a workspace whose host is unreadable);
104
+ * `bare`: a reason when a soul keyed by its bare name may be missing (a member unconfirmed, or a member
105
+ * or external soul skipped with a problem);
106
+ * `packages`: { <package id>: reason } for a package whose souls may be missing (declared and not
107
+ * locked, or locked with a soul skipped).
108
+ * What a read did not record, it did not establish: a description with no `unread` (or soulsOffered's
109
+ * "unrecorded", for a discovery that kept no record of what it skipped) leaves every key unchecked.
110
+ * A key other than "*" that is the key of no offered soul is UNCHECKED when the source that could hold its
111
+ * soul was not read, and UNMATCHED otherwise: `<member>/<soul>` among them, since a member's soul is keyed
112
+ * by its bare name, and a key under a package that is locked and read. "*" is in neither.
113
+ * → { unmatched: [{ key, at, value, suggestions }], unchecked: [{ key, at, value, reason }] }, by key.
114
+ */
115
+ export function launchKeysUnmatched({ local, offered }) {
116
+ const byKey = isObject(local?.souls?.launch) ? local.souls.launch : {};
117
+ const keys = new Set(offered?.keys ?? []);
118
+ const unread = isObject(offered?.unread) ? offered.unread : { all: "unrecorded" };
119
+ const unmatched = [], unchecked = [];
120
+ for (const key of Object.keys(byKey).sort(byCodepoint)) {
121
+ if (key === "*" || keys.has(key)) continue;
122
+ const row = { key, at: launchKeyAt(key), value: launchValueOf(byKey[key]) };
123
+ const slash = key.lastIndexOf("/");
124
+ const reason = unread.all ?? (slash < 0 ? unread.bare : Object.hasOwn(unread.packages ?? {}, key.slice(0, slash)) ? unread.packages[key.slice(0, slash)] : null) ?? null;
125
+ if (reason !== null) unchecked.push({ ...row, reason });
126
+ else unmatched.push({ ...row, suggestions: nearestSoulKeys(key, [...keys]) });
127
+ }
128
+ return { unmatched, unchecked };
129
+ }
130
+
131
+ /** Why a key of souls.launch was not checked, one sentence per reason launchKeysUnmatched can give
132
+ * (soulsOffered's): what `oats doctor` says after the key. */
133
+ export const LAUNCH_KEY_UNCHECKED = Object.freeze({
134
+ standalone: "this deployment sees a standalone view (the workspace's host could not be read), so the workspace's souls are not known",
135
+ unrecorded: "the read of the workspace kept no record of the souls it could not read, so it established nothing about this key",
136
+ "member-unconfirmed": "a member of the workspace is not confirmed, and the key may be a soul of it",
137
+ "soul-unread": "a member's or an external soul could not be read, and the key may be that soul's",
138
+ "package-unlocked": "its package is declared and not locked (oats sync)",
139
+ "package-soul-unread": "a soul of its package could not be read, and the key may be that soul's",
140
+ });
141
+
142
+ /** A key or a name from outside the kernel, as a sentence of a launch answer carries it: every character
143
+ * the kernel never prints (lib/refused-text.mjs REFUSED_TEXT) replaced. `safeText` and not `terminalText`:
144
+ * these sentences are put in an answer, which a client reads and refuses when it holds such a character;
145
+ * the exact key is the answer's data (`details.keys`, a row's `key`). A text the schemas admit is unchanged. */
146
+ const said = (text) => safeText(text, LAUNCH_PROBLEM_TEXT_MAX);
147
+ /** A key of souls.launch named in a sentence: quoted, through `said`. */
148
+ export const launchKeyQuoted = (key) => JSON.stringify(said(key));
149
+ /**
150
+ * THE place the command an answer suggests is rendered (awebai/oats#1049): `oats soul launch set …` and
151
+ * `oats soul launch remove …`, as a person pastes it. `set` pins `key`, or the placeholder `<soul>` when
152
+ * the answer does not know which soul; `launch: "config"` offers a launch configuration only (the answers
153
+ * about a configuration), otherwise a configuration or a harness. `remove` removes `key`, or `<key>`.
154
+ * A key is a shell word (lib/shell-word.mjs): `"*"` prints as `'*'`, and every other key the schema of
155
+ * oats-local.yaml admits prints as it is. The arguments in angle brackets are for the person to replace.
156
+ * A key that holds a character the kernel never prints cannot be written into a command line: quoted it
157
+ * would still carry the character, and with the character replaced the command would name another key.
158
+ * For such a key there is no command, and what comes back says so and names the key (launchKeyQuoted)
159
+ * and where it is removed by hand (awebai/oats#1064). The schema of oats-local.yaml admits no such key,
160
+ * so a file never brings one here; a caller that hands one over still gets a text it can print. So no
161
+ * sentence built with this function checks its key itself.
162
+ */
163
+ export function soulLaunchCommand(action, { key, launch = "any" } = {}) {
164
+ if (key !== undefined && REFUSED_TEXT.test(String(key))) {
165
+ return action === "remove" ? `no command can name ${launchKeyQuoted(key)}: delete that key from ${LOCAL_FILE} (souls.launch) by hand` : `no command can name ${launchKeyQuoted(key)}, and no soul has such a key`;
166
+ }
167
+ if (action === "remove") return `oats soul launch remove ${key === undefined ? "<key>" : shellWord(key)}`;
168
+ return `oats soul launch set ${key === undefined ? "<soul>" : shellWord(key)} --launch-config <name>${launch === "config" ? "" : " | --harness <h>"}`;
169
+ }
170
+ /** Whether souls.launch."*" is the layer that decided: the answers below then give its command first. */
171
+ const fromDefault = (from) => from === "local-default";
172
+
63
173
  /** A launch configuration the layer names but this oats-local.yaml does not declare. */
64
174
  export function launchConfigUnknown({ name, from, at }) {
65
175
  return fail("E_LAUNCH_CONFIG_UNKNOWN", `${at ?? "the launch preference"} names launch configuration ${JSON.stringify(name)}, which ${LOCAL_FILE} does not declare (launch-configs:); oats launch-config list shows what is`, { name, from, at });
66
176
  }
67
177
 
178
+ /** The fix for it, by the layer that named the configuration: a soul's own entry, or souls.launch."*". */
179
+ export function launchConfigUnknownFix(name, from) {
180
+ const declare = `declare launch configuration ${name} (oats launch-config set)`;
181
+ if (fromDefault(from)) return `${declare}, name another for every soul without an entry (${soulLaunchCommand("set", { key: "*", launch: "config" })}), or pin the soul to one (${soulLaunchCommand("set", { launch: "config" })})`;
182
+ return `${declare}, or pin the soul to another (${soulLaunchCommand("set", { launch: "config" })})`;
183
+ }
184
+
68
185
  const NAMED = 10;
69
186
  /** E_LAUNCH_CONFIG_AMBIGUOUS, or null: a new launch on `harness` that chose no configuration (`config`
70
187
  * null after the harness default was looked up) although this host declares several for it and marks
71
188
  * none `default: true`. A choice that asked for the bare harness (`--launch-config none`, or a
72
- * souls.launch "none") is a choice; an inline or soul preference and `--harness` alone are not. */
189
+ * souls.launch "none") is a choice; an inline or soul preference and `--harness` alone are not.
190
+ * Its fix names the flag and the pin of the soul; where souls.launch."*" chose the harness, the
191
+ * command for '*' too, before the soul's own. */
73
192
  export function launchConfigAmbiguous({ launchConfigs = {}, harness, config, choice }) {
74
193
  if (config || (choice.selection.launchConfig === "none" && !choice.preference)) return null;
75
194
  const configurations = Object.keys(launchConfigs).filter((name) => launchConfigs[name]?.harness === harness).sort();
76
195
  if (configurations.length < 2) return null;
77
- const fix = `name one with --launch-config <name> (or souls.launch in ${LOCAL_FILE}), or mark one default: true (oats launch-config set)`;
78
- // The message names at most NAMED configurations, so it stays within a reader's bound (the
79
- // Desktop refuses a problem message over 1024 characters); details keep the full list.
80
- const named = configurations.length > NAMED ? [...configurations.slice(0, NAMED), `and ${configurations.length - NAMED} more`] : configurations;
81
- return fail("E_LAUNCH_CONFIG_AMBIGUOUS", `${LOCAL_FILE} declares ${configurations.length} ${harness} launch configurations (${named.join(", ")}) and none is default: true, and this launch names none; ${fix}`, { harness, configurations, fix });
196
+ const fix = `name one with --launch-config <name>, ${fromDefault(choice.from) ? `name one for every soul without an entry (${soulLaunchCommand("set", { key: "*", launch: "config" })}), ` : ""}pin the soul to one (${soulLaunchCommand("set", { launch: "config" })}), or mark one default: true (oats launch-config set)`;
197
+ // The message names at most NAMED configurations, and fewer when it would otherwise pass a reader's
198
+ // bound (the Desktop refuses a problem message over LAUNCH_PROBLEM_TEXT_MAX characters); details keep
199
+ // the full list.
200
+ const message = (count) => {
201
+ const named = configurations.length > count ? [...configurations.slice(0, count), `and ${configurations.length - count} more`] : configurations;
202
+ return `${LOCAL_FILE} declares ${configurations.length} ${harness} launch configurations (${named.join(", ")}) and none is default: true, and this launch names none; ${fix}`;
203
+ };
204
+ let count = NAMED;
205
+ while (count > 1 && message(count).length > LAUNCH_PROBLEM_TEXT_MAX) count -= 1;
206
+ return fail("E_LAUNCH_CONFIG_AMBIGUOUS", message(count), { harness, configurations, fix });
207
+ }
208
+
209
+ /** The code of the refusal below, and of every row that reports one of its keys (`oats souls`, `oats doctor`). */
210
+ export const LAUNCH_PREFERENCE_UNMATCHED = "E_LAUNCH_PREFERENCE_UNMATCHED";
211
+ /** The bound, in characters, of that refusal's `message` and of its `fix`, each: a reader's bound on a
212
+ * problem's texts (the Desktop's `Launch` reader refuses a longer one). */
213
+ export const LAUNCH_PROBLEM_TEXT_MAX = 1024;
214
+ const UNMATCHED_NAMED = 3;
215
+ export const UNMATCHED_FIX = `pin the soul each key was meant for (oats soul launch set), then remove the key (${soulLaunchCommand("remove")}); or name this launch with --launch-config <name> or --harness <h>`;
216
+ /** The unmatched keys in a sentence: at most `count` of them, each with its nearest soul keys when
217
+ * `near`, then "and K more". */
218
+ function unmatchedNamed(keys, count, near) {
219
+ const shown = keys.slice(0, count).map((k) => `${launchKeyQuoted(k.key)}${near && k.suggestions.length ? ` (nearest: ${k.suggestions.map(said).join(", ")})` : ""}`);
220
+ if (!shown.length) return `${keys.length} keys`;
221
+ return keys.length > shown.length ? `${shown.join(", ")} and ${keys.length - shown.length} more` : shown.join(shown.length === 2 ? " and " : ", ");
222
+ }
223
+ /** The first of `render`'s wordings, from the fullest to the barest, that fits a reader's bound; the
224
+ * barest cut to it when a single name is longer than the bound allows. */
225
+ function boundedText(render) {
226
+ for (const [count, near] of [[UNMATCHED_NAMED, true], [UNMATCHED_NAMED, false], [2, false], [1, false], [0, false]]) {
227
+ const text = render(count, near);
228
+ if (text.length <= LAUNCH_PROBLEM_TEXT_MAX) return text;
229
+ }
230
+ return `${render(0, false).slice(0, LAUNCH_PROBLEM_TEXT_MAX - 1)}…`;
231
+ }
232
+ /** One unmatched key as a problem row says it, within the same bound: the key and the nearest soul keys.
233
+ * `oats souls` read the workspace itself, and its row ends with the two commands, in their order.
234
+ * `lastRead` is `oats doctor`'s row, which read this machine's cache: it says that it speaks about this
235
+ * machine's last read of the souls and that a spawn is the authority (its remedy is the row's own field). */
236
+ export function unmatchedKeyMessage(row, { lastRead = false } = {}) {
237
+ return boundedText((count, near) => {
238
+ const named = `${LOCAL_FILE} souls.launch names ${count ? unmatchedNamed([row], 1, near) : "a key"}`;
239
+ if (lastRead) return `${named}, which is no soul in this machine's last read of the souls this workspace offers. A spawn reads the workspace itself and is the authority: where it finds the same, a new launch of a soul with no entry of its own that names no launch is refused`;
240
+ return `${named}, which is no soul this workspace offers: a new launch of a soul with no entry of its own that names no launch is refused while it is there. Pin the soul it was meant for (${soulLaunchCommand("set")}), then remove the key (${soulLaunchCommand("remove", count ? { key: row.key } : {})})`;
241
+ });
242
+ }
243
+ /**
244
+ * E_LAUNCH_PREFERENCE_UNMATCHED, or null (awebai/oats#989): a new launch that the fall-through would
245
+ * decide (`choice.from` is neither the flags nor the soul's own souls.launch entry) while souls.launch
246
+ * holds a key that names no soul the workspace offers (`layers.unmatched`). The kernel cannot tell which
247
+ * soul such a key was meant to pin, so it cannot say that this launch is not the one: the launch is
248
+ * refused, before the launch-configuration and harness refusals, which describe a launch that must not
249
+ * be used at all. `--model` alone names no launch. `details`: { soul (the soul key refused), from, at
250
+ * (the layer that would have decided), keys (every unmatched key, launchKeysUnmatched's rows), fix }.
251
+ * The message names at most three keys and stays within LAUNCH_PROBLEM_TEXT_MAX, as `fix` does;
252
+ * `details.keys` is complete.
253
+ * The remedy's order is set, then remove: removing first leaves the soul on the fall-through.
254
+ */
255
+ export function launchPreferenceUnmatched({ choice, layers }) {
256
+ const keys = layers?.unmatched ?? [];
257
+ if (!keys.length || choice.from === "flag" || choice.from === "local") return null;
258
+ const message = unmatchedLaunchSaid({ choice, layers }, (count, one) => `it is refused, and nothing was created or started. Pin the soul ${one ? "it was" : "each was"} meant for (${soulLaunchCommand("set")}), then remove the key (${soulLaunchCommand("remove", count ? { key: keys[0].key } : {})}); or name this launch (--launch-config <name> or --harness <h>).`);
259
+ return fail(LAUNCH_PREFERENCE_UNMATCHED, message, { soul: layers.key ?? null, from: choice.from, at: choice.at ?? null, keys, fix: UNMATCHED_FIX });
260
+ }
261
+ /** What the refusal above and a report of it both say, to `ending(count, one)`: the keys, that they name
262
+ * no soul, and which layer would decide a new launch of this soul that names none. */
263
+ function unmatchedLaunchSaid({ choice, layers }, ending) {
264
+ const keys = layers.unmatched;
265
+ const soul = layers.key === null || layers.key === undefined ? "this soul" : said(layers.key);
266
+ const decider = choice.from === "local-default" ? `souls.launch."*"` : choice.from === "soul" ? "the soul's own launch" : "the host default";
267
+ const one = keys.length === 1;
268
+ return boundedText((count, near) => `${LOCAL_FILE} souls.launch names ${unmatchedNamed(keys, count, near)}, which ${one ? "is" : "are"} no soul this workspace offers. A new launch of ${count ? soul : "this soul"} that names no launch has no entry of its own, so ${decider} would decide it, and the kernel cannot tell which soul ${one ? "that key was" : "those keys were"} meant to pin: ${ending(count, one)}`);
269
+ }
270
+ /**
271
+ * The `problem` of a `Launch` report for that refusal, or null where it would not be thrown: `{ code,
272
+ * message, fix }`. A listing states the condition, where the refusal states what was refused: nobody
273
+ * asked for a launch, so the message says that a new launch of this soul that names none would be
274
+ * refused, in the refusal's own sentence up to there, and it does not end with the remedy, which is the
275
+ * report's `fix` (UNMATCHED_FIX). Within the same bound; being shorter, it may name a key the refusal's
276
+ * message had no room for.
277
+ */
278
+ export function launchPreferenceUnmatchedProblem({ choice, layers }) {
279
+ const refusal = launchPreferenceUnmatched({ choice, layers });
280
+ if (!refusal) return null;
281
+ return { code: refusal.code, message: unmatchedLaunchSaid({ choice, layers }, () => "it would be refused."), fix: refusal.details.fix };
82
282
  }
83
283
 
84
- /** The fix for a missing harness, by the layer that chose it. */
284
+ /** The fix for a missing harness, by the layer that chose it: the flags, the soul's own entry of
285
+ * souls.launch, souls.launch."*", or the soul's own launch or the host default. */
85
286
  export function harnessFix(harness, from) {
86
287
  if (from === "flag") return `install ${harness}, or choose another --harness / --launch-config`;
87
- if (from === "local" || from === "local-default") return `install ${harness}, or change ${LOCAL_FILE} souls.launch`;
88
- return `install ${harness}, or override it on this machine in ${LOCAL_FILE} souls.launch`;
288
+ if (from === "local") return `install ${harness}, or pin this soul to another launch (${soulLaunchCommand("set")})`;
289
+ if (fromDefault(from)) return `install ${harness}, name another launch for every soul without an entry (${soulLaunchCommand("set", { key: "*" })}), or pin this soul to its own (${soulLaunchCommand("set")})`;
290
+ return `install ${harness}, or pin this soul on this machine (${soulLaunchCommand("set")})`;
89
291
  }
90
- /** E_HARNESS_UNAVAILABLE: the chosen harness has no executable here. Never a fallback to another harness. */
292
+ /** The layer that chose a launch, in words, for a message that has no room for its location. */
293
+ const LAYER_NAMED = Object.freeze({ flag: "the spawn flags", host: "the host default", local: "the soul's own entry of souls.launch", "local-default": `souls.launch."*"`, soul: "the soul's own launch" });
294
+ /** E_HARNESS_UNAVAILABLE: the chosen harness has no executable here. Never a fallback to another harness.
295
+ * The message says why, names the layer's location (`at`) and ends with the fix, whole. It stays within
296
+ * LAUNCH_PROBLEM_TEXT_MAX: a location too long for it (a repository key and a path, or a soul key) gives
297
+ * way to the layer's name, and then the reason is cut; `details.at` keeps the location. */
91
298
  export function harnessUnavailable({ harness, from, at, why }) {
92
- const source = from === "flag" ? "the spawn flags" : from === "host" ? "the host default" : at ?? from;
93
299
  const fix = harnessFix(harness, from);
94
- return fail("E_HARNESS_UNAVAILABLE", `${harness} is not installed on this machine (${why}); ${source} chose it — ${fix}`, { harness, from, at: at ?? null, fix });
300
+ const named = LAYER_NAMED[from] ?? from;
301
+ const message = (reason, source) => `${harness} is not installed on this machine (${reason}); ${source} chose it — ${fix}`;
302
+ let text = message(why, from === "flag" || from === "host" ? named : at ?? from);
303
+ if (text.length > LAUNCH_PROBLEM_TEXT_MAX) text = message(why, named);
304
+ if (text.length > LAUNCH_PROBLEM_TEXT_MAX) text = message(`${String(why).slice(0, Math.max(0, LAUNCH_PROBLEM_TEXT_MAX - message("…", named).length))}…`, named);
305
+ return fail("E_HARNESS_UNAVAILABLE", text, { harness, from, at: at ?? null, fix });
95
306
  }
96
307
 
97
308
  /** What a person can do about a harness its pane would not find. */
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The one way a kernel command rewrites the deployment's oats-local.yaml in place: every command that
3
+ * does calls editLocal, and a new one does too (its callers are whatever imports it: no list is kept here).
4
+ * The file is read as it is NOW, edited (in the parsed document, comments and every other entry kept; or
5
+ * as text, by a command that has a writer of its own for its block), validated against the local schema
6
+ * and by the caller's own check, and renamed in, all under the deployment's local lock, so two writers
7
+ * never drop each other's change.
8
+ */
9
+ import { readFileSync, statSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import YAML from "yaml";
12
+ import { isJsonSource, parseConfigData } from "./config-data.mjs";
13
+ import { oatsError } from "./errors.mjs";
14
+ import { validateLocal } from "./workspace.mjs";
15
+ import { writeFileAtomic } from "./packages.mjs";
16
+ import { withDirLock } from "./dir-lock.mjs";
17
+
18
+ function fail(code, message, details) { const e = oatsError(code, message, details); e.details = details; return e; }
19
+
20
+ /** The lock every kernel writer of oats-local.yaml holds: in the deployment's kernel state tree, never
21
+ * beside the files. */
22
+ export const localLock = (deployment) => join(deployment, ".agents", "locks", "local.lock");
23
+
24
+ /** No line folding: a value past 80 columns stays on its line (the library's default width re-wraps it). */
25
+ const RENDER = { lineWidth: 0 };
26
+ /** `value` (a document's content, its mappings as Maps so that their keys keep the file's order: an object
27
+ * would move a key like "10" to the front) as two-space JSON. */
28
+ function jsonText(value, indent = "") {
29
+ const inner = `${indent} `;
30
+ const block = (open, close, rows) => (rows.length ? `${open}\n${rows.map((row) => `${inner}${row}`).join(",\n")}\n${indent}${close}` : `${open}${close}`);
31
+ if (value instanceof Map) return block("{", "}", [...value].map(([k, v]) => `${JSON.stringify(String(k))}: ${jsonText(v, inner)}`));
32
+ if (Array.isArray(value)) return block("[", "]", value.map((v) => jsonText(v, inner)));
33
+ return JSON.stringify(value ?? null);
34
+ }
35
+ /** The edited document as the text to write, in the syntax the file has. The kernel reader takes a file
36
+ * that opens with `{` as strict JSON (isJsonSource), and the library's rendering of an edited flow
37
+ * collection is not JSON (a new key comes out unquoted), so such a file is written as JSON. It has no
38
+ * comment to keep; it keeps the order of its keys and its final newline, or the absence of one, and its
39
+ * indentation becomes two spaces. */
40
+ const render = (doc, text) => (isJsonSource(text) ? `${jsonText(doc.toJS({ mapAsMap: true }))}${text.endsWith("\n") ? "\n" : ""}` : doc.toString(RENDER));
41
+
42
+ /** The kernel reader's value of `text`, or the reason it reads none: its decoder's refusals carry their own
43
+ * names, not an `E_` code, so they are caught here and never reach a command as a crash. */
44
+ function decode(text, localPath) {
45
+ try { return { value: parseConfigData(text, { origin: { kind: "local", path: localPath } }).value }; }
46
+ catch (e) { return { failure: String(e?.message ?? e) }; }
47
+ }
48
+
49
+ /** oats-local.yaml as it is now → { text, doc (the editable document), local (the kernel reader's value) }. */
50
+ export function readLocal(localPath) {
51
+ const text = readFileSync(localPath, "utf8");
52
+ const doc = YAML.parseDocument(text, { keepSourceTokens: true });
53
+ if (doc.errors?.length) throw fail("E_WORKSPACE_SCHEMA", `${localPath}: ${doc.errors[0].message}`, { path: localPath });
54
+ const read = decode(text, localPath);
55
+ if (read.failure) throw fail("E_WORKSPACE_SCHEMA", `cannot decode ${localPath}: ${read.failure}; nothing was written`, { path: localPath });
56
+ return { text, doc, local: read.value };
57
+ }
58
+
59
+ /**
60
+ * Rewrite oats-local.yaml. `edit({ text, doc, local })` gets the file AS IT IS NOW (re-read here, never the
61
+ * command's startup snapshot): it may throw a refusal, and it changes `doc` only where the verb's own
62
+ * entries are. It returns null when there is nothing to change, else `{ check? }`, where `check(next)`
63
+ * may refuse the rewritten value (`next`: the kernel reader's parse of the new text) before it is written.
64
+ * The write is compare-and-swap: when the file changed after this read, the edit is redone on the new
65
+ * content (a few times, then E_LOCAL_CHANGED). → { changed, local } (the value now, or as it would be).
66
+ * The edit runs with the lock held, and may run several times: it never ends the process, and what its
67
+ * caller keeps of it is what its last run left.
68
+ *
69
+ * `verb` names the command in the lock's owner record. `plan: true` runs every check and writes nothing:
70
+ * no lock is taken either, so a plan leaves no trace in the deployment.
71
+ *
72
+ * What is written is the YAML library's rendering of the edited document (RENDER): every entry the edit did
73
+ * not touch keeps its value and its comments. It is not a byte copy: the library pads a flow collection
74
+ * (`[a, b]` comes back `[ a, b ]`) and indents by two. A file written as JSON stays JSON (render).
75
+ * Text the kernel reader would not decode is never written: that is E_WORKSPACE_SCHEMA, as an invalid value is.
76
+ *
77
+ * An edit that has a writer of its own returns `{ text, check? }` instead, made from the `text` it was
78
+ * given: that text is written as it is and the document is not rendered, so every byte the edit left alone
79
+ * stays. It is held to the same loop (the kernel reader, the local schema, `check`, compare-and-swap, the
80
+ * rename), and the text it was given, returned, is nothing to write: `changed: false`.
81
+ *
82
+ * Without `plan` the whole read-compare-write runs under the deployment's local lock (localLock), so among
83
+ * its writers the compare and the rename are one step: a conditional write sees every earlier one.
84
+ *
85
+ * The write replaces the file (a sibling temporary file, renamed in): no reader sees half of it, and the
86
+ * new file has the permission bits of the one it replaces, from before its first byte is written. A link
87
+ * at that path is replaced too, by a regular file with its target's bits (writeFileAtomic never writes
88
+ * through one): the target is left as it was.
89
+ */
90
+ export function editLocal(ctx, { verb, plan = false }, edit) {
91
+ if (plan) return editLocalLocked(ctx, { plan }, edit);
92
+ const lock = localLock(ctx.deployment);
93
+ return withDirLock(lock, `${verb} on ${ctx.localPath}`, () => editLocalLocked(ctx, { plan }, edit), {
94
+ retryMs: 5000,
95
+ busy: (why) => fail("E_LOCAL_BUSY", `${ctx.localPath} is being edited by another oats process (the lock ${lock}: ${why}); if no oats command that edits this file is running, remove ${lock} and retry; nothing was written`, { path: ctx.localPath, lock }),
96
+ });
97
+ }
98
+ function editLocalLocked(ctx, { plan }, edit) {
99
+ for (let attempt = 0; attempt < 5; attempt++) {
100
+ const { text, doc, local: current } = readLocal(ctx.localPath);
101
+ const step = edit({ text, doc, local: current });
102
+ if (!step) return { changed: false, local: current };
103
+ const own = typeof step.text === "string";
104
+ const out = own ? step.text : render(doc, text);
105
+ const read = decode(out, ctx.localPath);
106
+ const local = read.value;
107
+ const problems = read.failure ? [{ path: "", message: `the kernel would not decode it: ${read.failure}` }] : validateLocal(local);
108
+ 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 });
109
+ step.check?.(local);
110
+ if (own && out === text) return { changed: false, local: current };
111
+ if (plan) return { changed: true, local };
112
+ if (readFileSync(ctx.localPath, "utf8") !== text) continue; // changed under us: redo on the new content
113
+ // The file that replaces it keeps its permission bits: one its operator made private stays private.
114
+ writeFileAtomic(ctx.localPath, out, { mode: statSync(ctx.localPath).mode & 0o7777 });
115
+ return { changed: true, local };
116
+ }
117
+ throw fail("E_LOCAL_CHANGED", `${ctx.localPath} kept changing while this edit ran; nothing was written — run it again`, { path: ctx.localPath });
118
+ }
package/lib/packages.mjs CHANGED
@@ -41,7 +41,7 @@
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 { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync, lstatSync } from "node:fs";
44
+ import { closeSync, existsSync, fchmodSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, lstatSync } from "node:fs";
45
45
  import { tmpdir } from "node:os";
46
46
  import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
47
47
  import { recordLocalInput } from "./local-inputs.mjs";
@@ -99,12 +99,21 @@ export function assertNoSymlinkedParents(scopeDir, leafDir, what) {
99
99
  }
100
100
 
101
101
  /** Sibling temp + rename: replaces the directory entry itself, never writing
102
- * THROUGH a pre-planted symlink at `file`. */
103
- export function writeFileAtomic(file, contents) {
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 } = {}) {
104
106
  mkdirSync(dirname(file), { recursive: true });
105
107
  const tmp = join(dirname(file), `.${basename(file)}.oats-tmp-${process.pid}`);
106
108
  try {
107
- writeFileSync(tmp, contents);
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
+ }
108
117
  renameSync(tmp, file);
109
118
  } finally { rmSync(tmp, { force: true }); }
110
119
  }
@@ -281,7 +290,11 @@ export function parsePackageRequest(id, value, catalog) {
281
290
  const c = classifyPackageValue(value);
282
291
  if (c.problem) {
283
292
  const code = typeof value === "string" && value.trim().startsWith("git:") ? "E_REPO_REF" : "E_WORKSPACE_SCHEMA";
284
- throw oatsError(code, `packages.${id}: ${c.problem}, got ${JSON.stringify(value)}`, { id, value, path: `/packages/${id}`, problems: [c.problem] });
293
+ const safe = { id, value: defaultRemote.redactUrl(value, null, { reference: true }), path: `/packages/${id}`,
294
+ problems: [defaultRemote.redactUrl(c.problem, value, { known: false })] };
295
+ const message = defaultRemote.redactUrl(`packages.${safe.id}: ${safe.problems[0]}, got ${JSON.stringify(safe.value)}`,
296
+ value, { known: false, refusal: true });
297
+ throw oatsError(code, message, safe);
285
298
  }
286
299
  if (c.kind === "git") return { kind: "git", remoteRef: c.repo, at: c.at, path: DEFAULT_PACKAGE_PATH };
287
300
  const text = value.trim();