@awebai/oats 0.52.0 → 0.53.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 (98) hide show
  1. package/README.md +2 -1
  2. package/bin/oats.mjs +304 -92
  3. package/docs/capabilities.md +66 -4
  4. package/docs/configuration.md +66 -3
  5. package/docs/desktop-cli-api.md +673 -58
  6. package/docs/desktop-instance-start.md +25 -12
  7. package/docs/execution-targets.md +1 -0
  8. package/docs/implementation.md +175 -11
  9. package/docs/integrations.md +6 -3
  10. package/docs/knowledge.md +2 -2
  11. package/docs/macos-test-runs.md +246 -0
  12. package/docs/official-catalog.md +5 -5
  13. package/docs/packages.md +14 -14
  14. package/docs/release-lane.md +210 -6
  15. package/docs/release-notes/v0.53.0.md +1274 -0
  16. package/docs/schedules.md +7 -1
  17. package/docs/souls-and-instances.md +237 -15
  18. package/docs/tui.md +453 -21
  19. package/docs/upgrading.md +298 -0
  20. package/docs/workspaces.md +3 -3
  21. package/lib/automations.mjs +22 -22
  22. package/lib/claim.mjs +93 -4
  23. package/lib/config-data.mjs +4 -1
  24. package/lib/core.mjs +569 -121
  25. package/lib/instance-events.mjs +19 -1
  26. package/lib/instance-git.mjs +39 -3
  27. package/lib/instance-inspect.mjs +5 -6
  28. package/lib/instance-lifecycle.mjs +145 -18
  29. package/lib/instance-resolution.mjs +59 -6
  30. package/lib/launch-preference.mjs +226 -15
  31. package/lib/local-edit.mjs +118 -0
  32. package/lib/packages.mjs +13 -4
  33. package/lib/pi-bridge.mjs +308 -0
  34. package/lib/refused-text.mjs +11 -0
  35. package/lib/remote.mjs +190 -25
  36. package/lib/resolve.mjs +2 -1
  37. package/lib/retained-after-retire.mjs +2 -2
  38. package/lib/retire-output.mjs +12 -1
  39. package/lib/schedule-host.mjs +6 -35
  40. package/lib/shell-word.mjs +13 -0
  41. package/lib/soul-launch-verbs.mjs +153 -0
  42. package/lib/stable-node.mjs +62 -0
  43. package/lib/teams-verbs.mjs +18 -46
  44. package/lib/workspace.mjs +49 -19
  45. package/package-catalog.json +4 -4
  46. package/package.json +2 -1
  47. package/packages/client/attach-exit.mjs +25 -0
  48. package/packages/client/cli-adapter.mjs +16 -3
  49. package/packages/client/cli-locator.mjs +2 -2
  50. package/packages/client/deployment-contract.mjs +4 -0
  51. package/packages/client/deployment-facts.mjs +71 -10
  52. package/packages/client/deployment-panel.mjs +49 -11
  53. package/packages/client/deployment-read-cli.mjs +7 -3
  54. package/packages/client/display-text.mjs +8 -2
  55. package/packages/client/instance-acts.mjs +46 -10
  56. package/packages/client/instance-events-contract.mjs +4 -2
  57. package/packages/client/instance-presentation.mjs +66 -2
  58. package/packages/client/instance-tree.mjs +23 -14
  59. package/packages/client/kernel-lines.mjs +31 -0
  60. package/packages/client/kernel-made.mjs +23 -0
  61. package/packages/client/launch-prompt-outcome.mjs +51 -16
  62. package/packages/client/lifecycle-contract.mjs +45 -4
  63. package/packages/client/liveness.mjs +14 -1
  64. package/packages/client/own-codes.mjs +31 -0
  65. package/packages/client/panel-views.mjs +18 -11
  66. package/packages/client/readiness-contract.mjs +3 -1
  67. package/packages/client/remote-address.mjs +34 -9
  68. package/packages/client/remote-identity-memory.mjs +94 -0
  69. package/packages/client/remote-roster.mjs +92 -6
  70. package/packages/client/session-attach.mjs +175 -0
  71. package/packages/client/spawn-apply-contract.mjs +16 -4
  72. package/packages/client/spawn-messages.mjs +26 -3
  73. package/packages/client/spawn-preview-cli.mjs +8 -2
  74. package/packages/client/spawn-preview-contract.mjs +5 -1
  75. package/packages/client/terminal-exec.mjs +21 -0
  76. package/packages/client/workspace-choices.mjs +95 -0
  77. package/packages/client/workspace-views.mjs +39 -3
  78. package/packages/record/README.md +21 -0
  79. package/packages/record/bin/setup.mjs +108 -15
  80. package/packages/tui/README.md +30 -12
  81. package/packages/tui/lib/actions.mjs +16 -1
  82. package/packages/tui/lib/client.mjs +32 -1
  83. package/packages/tui/lib/config.mjs +151 -0
  84. package/packages/tui/lib/main.mjs +117 -46
  85. package/packages/tui/lib/model.mjs +392 -0
  86. package/packages/tui/lib/read.mjs +473 -0
  87. package/packages/tui/lib/store.mjs +364 -0
  88. package/packages/tui/lib/term/keys.mjs +44 -0
  89. package/packages/tui/lib/term/screen.mjs +16 -4
  90. package/packages/tui/lib/term/text.mjs +60 -0
  91. package/packages/tui/lib/term/tty.mjs +13 -3
  92. package/packages/tui/lib/views/detail.mjs +46 -0
  93. package/packages/tui/lib/views/frame.mjs +230 -36
  94. package/packages/tui/lib/views/help.mjs +125 -13
  95. package/packages/tui/lib/views/instances.mjs +137 -0
  96. package/packages/tui/lib/views/scroll.mjs +19 -0
  97. package/packages/tui/lib/views/switcher.mjs +97 -0
  98. package/skills/oats-getting-started/SKILL.md +2 -2
package/lib/remote.mjs CHANGED
@@ -13,8 +13,12 @@
13
13
  * commit locally. `ensureCommit` does a shallow, partial
14
14
  * `git fetch --depth 1 --no-tags --filter=blob:limit=64k origin <oid>` into a
15
15
  * content-addressed BARE cache repo under `<cacheRoot>/<sha256(key)>/` and then
16
- * pins the commit with `refs/oats/commits/<oid>` so `gc` cannot prune it (the
17
- * pins are also what a later fetch advertises as `have`, so it is incremental).
16
+ * pins the commit with `refs/oats/commits/<oid>` so `gc` cannot prune it. The
17
+ * pins are also what a later fetch advertises as `have`, so it is incremental:
18
+ * a new head beside the last one arrives in a few kilobytes. An incremental pack
19
+ * may refer to a blob the filter left out of the cache, and git then cannot
20
+ * complete it; that fetch is made once more without negotiation, which brings
21
+ * the commit whole (fetchCommit, awebai/oats#1059).
18
22
  * The commit arrives with ALL its trees (every listing is complete) and the blobs
19
23
  * up to SMALL_BLOB_LIMIT: every file discovery reads, in one round trip.
20
24
  * 3. Reads are then local plumbing: `git ls-tree -r -t -l -z` for listing and
@@ -66,6 +70,12 @@
66
70
  * `error.overflowed`. A listing failure git does not explain is never a raw
67
71
  * Node error escaping this module: it is E_REMOTE_UNREADABLE { reason: "unknown" }.
68
72
  *
73
+ * UNKNOWN vs NETWORK (awebai/oats#1059): a failed git call whose text shows nothing the
74
+ * kernel recognises is `unknown`, never `network`: `network` is what the text shows to
75
+ * be the network (classifyText). The message of an `unknown` failure carries git's own
76
+ * line (the last for a remote call, the first for a listing) through one scrub
77
+ * (scrubGitLine): one line, bounded, no control characters, no url's user information.
78
+ *
69
79
  * TREE SAFETY: every entry name git reports is validated BEFORE anything touches
70
80
  * the disk. A component that is empty, `.`, `..`, `.git` (any case) or contains
71
81
  * `\` / NUL is E_REMOTE_TREE_UNSAFE { why: "path" } — a crafted tree object can
@@ -83,8 +93,12 @@
83
93
  * kernel's live write (retried briefly) or to a git that was killed: one older than the
84
94
  * longest fetch, inside the cache and a regular file, is removed (a session notice says
85
95
  * so) and the write made once more; any other is E_REMOTE_UNREADABLE { reason: "cache" }
86
- * naming it. git is ended with SIGTERM first (it removes its own locks), SIGKILL after a
87
- * grace unless its group is seen empty first (process-group.mjs terminateGroup, watchGroup).
96
+ * naming it. Every fetch first removes the temporary files of the object store that are
97
+ * older than the longest fetch (a failed fetch's pack, which git does not remove), and
98
+ * no younger one: it may be another git's (removeStaleTemporaryFiles; temporaryStaleMs
99
+ * says what the longest fetch is). git is ended with
100
+ * SIGTERM first (it removes its own locks), SIGKILL after a grace unless its
101
+ * group is seen empty first (process-group.mjs terminateGroup, watchGroup).
88
102
  *
89
103
  * CACHE PIN vs OBJECTS: the pin ref is the fast-path marker, but a wiped or
90
104
  * pruned object store is detected (`rev-parse <oid>^{commit}`) and refetched;
@@ -156,6 +170,7 @@ import { homedir } from "node:os";
156
170
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
157
171
  import { fileURLToPath } from "node:url";
158
172
  import { oatsError } from "./errors.mjs";
173
+ import { REFUSED_TEXT } from "./refused-text.mjs";
159
174
  import { killGroup, signalGroup, terminateGroup, watchGroup } from "./process-group.mjs";
160
175
 
161
176
  export const FILE_BUDGET = 4 * 1024 * 1024; // readRemoteFile: 4 MiB per file
@@ -417,30 +432,84 @@ function stderrText(error) {
417
432
  return Buffer.isBuffer(s) ? s.toString("utf8") : typeof s === "string" ? s : String(error?.message ?? "");
418
433
  }
419
434
 
420
- /** Classify a failed network git call into the contract's reasons. A `maxBuffer`
421
- * overflow is never a timeout (the child is killed in both cases; only the timeout kill
422
- * counts) — it falls through to the stderr text, else "network". A timeout is our own
423
- * timer's kill (`timedOut`), whatever signal it sent. A git lock still held by another
424
- * process (a lost race that outlived retryLockRace, or a dead process's stale lock) is
425
- * "cache": a local cache write failed, nothing about the remote. Any other signal exit is
426
- * "killed" (the system killed git, e.g. out of memory). */
435
+ /** Classify a failed git call into the contract's reasons. A `maxBuffer` overflow is never
436
+ * a timeout (the child is killed in both cases; only the timeout kill counts): it is what
437
+ * its stderr text shows. A timeout is our own timer's kill (`timedOut`), whatever signal it
438
+ * sent. A git lock still held by another process (a lost race that outlived retryLockRace,
439
+ * or a dead process's stale lock) is "cache": a local cache write failed, nothing about the
440
+ * remote. Any other signal exit is "killed" (the system killed git, e.g. out of memory).
441
+ * Otherwise the text decides, and a text that shows nothing the kernel recognises is
442
+ * "unknown" (awebai/oats#1059): "network" is only what the text shows to be the network. */
427
443
  export function classifyRemoteFailure(error) {
428
- if (error?.overflowed === true || error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return classifyText(error) ?? "network";
444
+ if (error?.overflowed === true || error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return classifyText(error) ?? "unknown";
429
445
  if (error?.timedOut) return "timeout";
430
446
  if (isLockRace(error) || isLocalWriteFailure(error)) return "cache";
431
447
  if (typeof error?.signal === "string" && error.signal) return "killed";
432
- return classifyText(error) ?? "network";
448
+ return classifyText(error) ?? "unknown";
433
449
  }
434
450
 
435
- /** The stderr-text half of classifyRemoteFailure; null when the text says nothing recognisable. */
451
+ /** An object id as git prints it (SHA-1 or SHA-256). */
452
+ const OBJECT_ID_RE = /\b[0-9a-f]{40}(?:[0-9a-f]{24})?\b/g;
453
+ /** The stderr-text half of classifyRemoteFailure; null when the text says nothing recognisable. The object
454
+ * ids git names are taken out first: an id is evidence of nothing, and one that holds `403` must not read
455
+ * as a refusal of the operator's credentials. The network texts are git's own and its transports' (libcurl's
456
+ * come after git's "unable to access"; ssh's and getaddrinfo's are named). */
436
457
  function classifyText(error) {
437
- const text = stderrText(error).toLowerCase();
458
+ const text = stderrText(error).toLowerCase().replace(OBJECT_ID_RE, "");
438
459
  if (/authentication failed|could not read username|could not read password|permission denied|publickey|403|forbidden|terminal prompts disabled|invalid username or password|access denied|unauthori[sz]ed/.test(text)) return "auth";
439
460
  if (/repository not found|repository '.*' not found|not found|does not appear to be a git repository|no such file or directory|not our ref|unadvertised object|couldn't find remote ref|remote ref .* not found|not a valid object name|not a tree object|bad object|is not a valid revision|no such ref/.test(text)) return "not-found";
440
- if (/could not resolve host|connection refused|connection timed out|network is unreachable|unable to access|early eof|remote end hung up|connection reset|ssl|tls|unable to connect/.test(text)) return "network";
461
+ if (/could not resolve host|could not resolve proxy|name or service not known|temporary failure in name resolution|connection refused|connection timed out|operation timed out|network is unreachable|no route to host|unable to access|early eof|remote end hung up|unexpected disconnect|connection reset|connection closed by|ssl|tls|unable to connect|failed to connect/.test(text)) return "network";
441
462
  return null;
442
463
  }
443
464
 
465
+ /** How much of one line of git's is printed in a message. */
466
+ export const GIT_LINE_MAX = 300;
467
+ const REFUSED_TEXT_ALL = new RegExp(REFUSED_TEXT.source, "gu");
468
+ /** A terminal's control sequence (a colour, a cursor move), which goes whole and not only its escape character. */
469
+ const ANSI_SEQUENCE_RE = /\x1b\[[0-9;?]*[ -\/]*[@-~]/g;
470
+ /** The user information of a url, wherever a text holds one: `scheme://user:secret@host` → `scheme://host`. */
471
+ const URL_USERINFO_RE = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s\/]*@/gi;
472
+ /**
473
+ * What a line about the fetch of `url` must not repeat, by the module's own rule of a url that carries a
474
+ * secret (CREDENTIAL_URL_RE): the user information, as written and decoded, and with it
475
+ * - on http(s), each of its parts: there the user alone is a secret (a forge token is put in a url as
476
+ * `https://<token>@host`, or as the user before a fixed password), so the whole of it goes whether or
477
+ * not it holds a colon;
478
+ * - on another scheme, its password alone, and nothing where it holds no colon: a user name alone
479
+ * (`ssh://git@host`) is no secret and stays.
480
+ * The longest first, so that no part of a secret is left by removing a shorter one inside it. The cost of
481
+ * removing each part: a user that is a common word goes from git's line wherever the line repeats it, and a
482
+ * mangled line is better than a printed token.
483
+ */
484
+ function urlSecrets(url) {
485
+ const m = typeof url === "string" ? /^([a-z][a-z0-9+.-]*):\/\/([^\s\/]*)@/i.exec(url) : null;
486
+ if (!m) return [];
487
+ const http = /^https?$/i.test(m[1]), info = m[2], colon = info.indexOf(":");
488
+ if (colon < 0 && !http) return [];
489
+ const parts = colon < 0 ? [] : http ? [info.slice(0, colon), info.slice(colon + 1)] : [info.slice(colon + 1)];
490
+ const forms = (text) => { try { return [text, decodeURIComponent(text)]; } catch { return [text]; } };
491
+ return [...new Set([info, ...parts].flatMap(forms))].filter(Boolean).sort((a, b) => b.length - a.length);
492
+ }
493
+ /**
494
+ * One line of git's own words, made fit to print in a message (a failure message is an output channel:
495
+ * the fetch url is on git's command line, may carry credentials, and git or its transport can echo it).
496
+ * The user information of every url in it is removed, and that of `url` (the fetch url) wherever it
497
+ * appears; a terminal's control sequences, control characters and the other characters the kernel never
498
+ * prints (lib/refused-text.mjs) are removed, runs of white space become one space, and the line is cut to
499
+ * GIT_LINE_MAX characters. "" when nothing is left.
500
+ */
501
+ export function scrubGitLine(line, url = null) {
502
+ let text = String(line ?? "").replace(URL_USERINFO_RE, "$1");
503
+ for (const secret of urlSecrets(url)) text = text.split(secret).join("");
504
+ const points = [...text.replace(ANSI_SEQUENCE_RE, "").replace(/\s+/g, " ").replace(REFUSED_TEXT_ALL, "").trim()];
505
+ return points.length > GIT_LINE_MAX ? `${points.slice(0, GIT_LINE_MAX - 1).join("")}…` : points.join("");
506
+ }
507
+ /** The last line git wrote that says anything (a progress line ends with a carriage return), scrubbed. */
508
+ function gitLastLine(error, url) {
509
+ const lines = stderrText(error).split(/[\r\n]+/).map((line) => scrubGitLine(line, url)).filter(Boolean);
510
+ return lines.length ? lines[lines.length - 1] : "";
511
+ }
512
+
444
513
  /** What to do when git on a macOS host cannot reach its keychain: the credentials git uses must live
445
514
  * somewhere a session without a terminal can read. */
446
515
  export const KEYCHAIN_REMEDY = "on macOS a session without a terminal (an ssh command, a background job) cannot open the login keychain where git's credential helper keeps the forge token; store git credentials outside the keychain (`gh auth login --insecure-storage`, then `gh auth setup-git`), or use an SSH key the session can reach: one without a passphrase, or the desktop login's ssh-agent (point SSH_AUTH_SOCK at it in the shell's startup file)";
@@ -453,11 +522,17 @@ export function keychainHint({ platform = process.platform, stdinIsTTY = process
453
522
  return !stdinIsTTY || !!env.SSH_CONNECTION ? "keychain-non-interactive" : null;
454
523
  }
455
524
 
525
+ /** A failed git call as E_REMOTE_UNREADABLE, by its reason (classifyRemoteFailure). The message prints the
526
+ * url as every message of the cache does, without its user information (redactUrl); `details.url` is the
527
+ * url as written. A failure the kernel cannot classify (`unknown`) carries git's own last line, scrubbed
528
+ * (scrubGitLine), so that the message shows what the kernel could not name; with no line, an output over
529
+ * its budget is said, and otherwise the message ends at the reason. */
456
530
  function unreadable(ref, error, extra = {}) {
457
531
  const reason = classifyRemoteFailure(error), killed = reason === "killed";
458
532
  if (reason === "cache") return cacheFailure(ref, error, extra);
459
533
  const hint = keychainHint({ reason });
460
- return fail("E_REMOTE_UNREADABLE", `cannot read remote ${ref.url} (${reason})${killed ? `: git was killed (signal ${error.signal})` : ""}${hint ? `: ${KEYCHAIN_REMEDY}` : ""}`,
534
+ const said = reason === "unknown" ? gitLastLine(error, ref.url) || (error?.overflowed === true ? "git's output exceeded its budget" : "") : "";
535
+ return fail("E_REMOTE_UNREADABLE", `cannot read remote ${redactUrl(ref.url)} (${reason})${killed ? `: git was killed (signal ${error.signal})` : ""}${said ? `: ${said}` : ""}${hint ? `: ${KEYCHAIN_REMEDY}` : ""}`,
461
536
  { url: ref.url, key: ref.key, reason, ...(killed ? { signal: error.signal } : {}), ...(hint ? { hint, remedy: KEYCHAIN_REMEDY } : {}), ...extra });
462
537
  }
463
538
 
@@ -703,7 +778,8 @@ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
703
778
  const cacheRootOf = (options) => options.cacheDir ?? defaultCacheRoot();
704
779
  const cacheDirOf = (root, ref) => join(root, sha256(ref.key));
705
780
 
706
- /** A url without its userinfo (`ssh://user:secret@host/…` → `ssh://host/…`): what may be written to disk. */
781
+ /** A url without its userinfo (`ssh://user:secret@host/…` → `ssh://host/…`): what may be written to disk,
782
+ * and how a message prints a url. The one function for it. */
707
783
  function redactUrl(url) {
708
784
  return typeof url === "string" ? url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]*@/i, "$1") : url;
709
785
  }
@@ -1216,7 +1292,7 @@ async function ensureCommit(ref, oid, options) {
1216
1292
  const mode = await fetchMode(repo)
1217
1293
  ?? (keepsPartialCache(version) ? await startPartialFetches(repo, ref) : await recordFullFetches(repo, ref, olderGitNotice(version, ref)));
1218
1294
  const filter = mode === "partial" ? [`--filter=${PARTIAL_FILTER}`] : ["--no-filter"];
1219
- const { stderr } = await fetchInto(repo, ref, ["fetch", "-q", "--depth", "1", "--no-tags", "--no-recurse-submodules", ...filter, "origin", oid], { what: oid, commit: oid });
1295
+ const { stderr } = await fetchCommit(repo, ref, ["fetch", "-q", "--depth", "1", "--no-tags", "--no-recurse-submodules", ...filter, "origin", oid], oid);
1220
1296
  // A server without filters says so and sends the whole tree: nothing is lost, the cache remembers.
1221
1297
  if (mode === "partial" && /filtering not recognized by server/i.test(stderr.toString("utf8"))) await recordFullFetches(repo, ref);
1222
1298
  const commit = await asReadTimeout(repo, peelCommit(repo, oid));
@@ -1232,6 +1308,32 @@ async function ensureCommit(ref, oid, options) {
1232
1308
  });
1233
1309
  }
1234
1310
 
1311
+ /**
1312
+ * The fetch of a commit into the cache (awebai/oats#1059). The fetch negotiates: git tells the server the
1313
+ * commits the cache holds (its pins), and the pack holds only what they lack, a few kilobytes for a new head
1314
+ * beside the last one. But the server may then send an object as a delta against one it takes the cache to
1315
+ * hold, and the cache does not hold the blobs its filter left out (nor, in a cache that turned to whole
1316
+ * trees, those of the commits fetched before): the pack cannot be completed, git may not fetch the missing
1317
+ * base on its own (GIT_NO_LAZY_FETCH), and the fetch dies with words the kernel cannot classify. `git fetch`
1318
+ * has no way to ask for a pack that is complete by itself while negotiating. So a fetch whose failure the
1319
+ * kernel cannot classify (`unknown`: never by git's wording) is made once more without negotiation
1320
+ * (`fetch.negotiationAlgorithm=noop`, as the fetch of blobs by id): the server is told nothing of what the
1321
+ * cache holds and sends the commit whole, which is complete whatever the cache holds. One second attempt,
1322
+ * never a third; if it fails, its failure is the answer. The first attempt's temporary pack stays in the
1323
+ * object store until a later fetch finds it old enough (removeStaleTemporaryFiles): one pack per commit that
1324
+ * needed its second attempt, since that commit is then present and never fetched again.
1325
+ * → { stdout, stderr } of the fetch that succeeded.
1326
+ */
1327
+ async function fetchCommit(repo, ref, args, oid) {
1328
+ try { return await fetchInto(repo, ref, args, { what: oid, commit: oid, raw: true }); }
1329
+ catch (error) {
1330
+ if (typeof error?.code === "string" && error.code.startsWith("E_")) throw error; // the fetch's timeout
1331
+ // A command that gave the read up is not asked again; neither is a failure the kernel can name.
1332
+ if (error?.code === "ABORT_ERR" || repo.session?.signal?.aborted || classifyRemoteFailure(error) !== "unknown") throw fetchFailure(repo, ref, error, oid);
1333
+ }
1334
+ return fetchInto(repo, ref, ["-c", "fetch.negotiationAlgorithm=noop", ...args], { what: oid, commit: oid });
1335
+ }
1336
+
1235
1337
  /** Pin `name` to `oid` in the cache repo. Two processes pinning one commit write the same value: a lost lock
1236
1338
  * race is retried, and a ref that already holds `oid` (another process's write) counts as written. */
1237
1339
  async function writePin(repo, ref, name, oid, commit) {
@@ -1362,11 +1464,73 @@ function markCacheDamaged(repo, why) {
1362
1464
  /** The repository carries a damage mark this session did not set: the next fetch rebuilds it first. */
1363
1465
  const toRebuild = (dir, session) => existsSync(join(dir, DAMAGED_MARK)) && !session?.damaged.has(dir);
1364
1466
 
1365
- /** `git fetch` from the remote into the cache (args start at the subcommand and name the remote "origin"):
1366
- * a lost on-disk `.lock` race is retried, a timeout names the fetch (`what`) and how long it ran, any other
1367
- * failure is E_REMOTE_UNREADABLE (`raw`: the git error itself, for a caller that reads its stderr). → { stdout, stderr } */
1467
+ /**
1468
+ * THE LONGEST FETCH, the age past which a fetch may remove a temporary file of git's: 11 minutes, which is the
1469
+ * 10 minutes any kernel gives the fetch of a commit (GIT_FETCH_TIMEOUT_MS) and one minute of margin, the
1470
+ * constant a stale git lock is judged by (GIT_LOCK_STALE_MS); or, when the session making this fetch was given
1471
+ * a longer fetch timeout of its own, that timeout and the same minute (`fetchTimeoutMs`; no caller in the
1472
+ * kernel gives one). No fetch a kernel started can still be writing a file that old: git is ended at the
1473
+ * timeout, and an older kernel's fetch, which takes no write lock, has the same 10 minutes.
1474
+ */
1475
+ const temporaryStaleMs = (session) => Math.max(GIT_LOCK_STALE_MS, (session?.fetchTimeoutMs ?? 0) + 60_000);
1476
+ /**
1477
+ * The temporary files git has in the cache's object store: → Map path → mtimeMs. A fetch receives
1478
+ * its pack into `objects/pack/tmp_pack_*` (index-pack; its index and reverse index are written as
1479
+ * `tmp_idx_*` and `tmp_rev_*` there), and a pack small enough to be unpacked writes each object as
1480
+ * `objects/<xx>/tmp_obj_*` first; git's own `prune` looks for `tmp_*` in `objects`, `objects/pack` and those
1481
+ * directories, and so does this. index-pack does not remove its file when it dies, and nothing else in the
1482
+ * cache ever would (it runs no gc). Regular files only, and only inside the cache entry: no symbolic link
1483
+ * is followed below it (the rule of reclaimGitLock), so a directory that is one, or that lies behind one,
1484
+ * holds none, as does a directory that cannot be read.
1485
+ */
1486
+ function gitTemporaryFiles(repo) {
1487
+ const found = new Map();
1488
+ let root;
1489
+ try { root = realpathSync(repo.dir); } catch { return found; }
1490
+ const scan = (...below) => {
1491
+ const dir = join(root, ...below);
1492
+ let names;
1493
+ try {
1494
+ if (!lstatSync(dir).isDirectory() || realpathSync(dir) !== dir) return [];
1495
+ names = readdirSync(dir);
1496
+ } catch { return []; }
1497
+ for (const name of names) {
1498
+ if (!name.startsWith("tmp_")) continue;
1499
+ try { const st = lstatSync(join(dir, name)); if (st.isFile()) found.set(join(dir, name), st.mtimeMs); } catch { /* gone meanwhile */ }
1500
+ }
1501
+ return names;
1502
+ };
1503
+ for (const name of scan("objects")) if (/^[0-9a-f]{2}$/.test(name)) scan("objects", name);
1504
+ scan("objects", "pack");
1505
+ return found;
1506
+ }
1507
+ /**
1508
+ * Before a fetch, under the cache's write lock: remove the temporary files of the object store that are older
1509
+ * than the longest fetch (temporaryStaleMs says what that is). That is the only rule, for a failed fetch's own leftovers too:
1510
+ * a file that appeared during a fetch cannot be told from one another git is writing (an older kernel's fetch
1511
+ * takes no write lock, git names its pack file itself, and nothing says who holds a file open), so none is
1512
+ * removed for having appeared; git's own `prune` goes by age for the same reason. A failed fetch's pack
1513
+ * therefore stays until a fetch into this entry finds it old enough.
1514
+ */
1515
+ function removeStaleTemporaryFiles(repo) {
1516
+ const staleMs = temporaryStaleMs(repo.session), now = Date.now();
1517
+ for (const [file, mtimeMs] of gitTemporaryFiles(repo)) {
1518
+ if (now - mtimeMs <= staleMs) continue;
1519
+ try { unlinkSync(file); } catch { /* a later fetch finds it again */ }
1520
+ }
1521
+ }
1522
+
1523
+ /** A failed fetch as E_REMOTE_UNREADABLE: a failed write of the cache says where and at which stage. */
1524
+ const fetchFailure = (repo, ref, error, commit) => unreadable(ref, error, { commit, ...(classifyRemoteFailure(error) === "cache" ? { cacheDir: repo.dir, stage: "fetch" } : {}) });
1525
+
1526
+ /** `git fetch` from the remote into the cache (args start at the subcommand and name the remote "origin"),
1527
+ * made under the cache's write lock: a lost on-disk `.lock` race is retried, a timeout names the fetch
1528
+ * (`what`) and how long it ran, any other failure is E_REMOTE_UNREADABLE (`raw`: the git error itself, for
1529
+ * a caller that reads it). Every fetch first removes the temporary files earlier fetches left in the object
1530
+ * store, by their age (removeStaleTemporaryFiles). → { stdout, stderr } */
1368
1531
  async function fetchInto(repo, ref, args, { what, commit, input, raw = false } = {}) {
1369
1532
  const started = Date.now();
1533
+ removeStaleTemporaryFiles(repo);
1370
1534
  let lastError;
1371
1535
  try { return await cacheGit(repo, ["-c", `remote.origin.url=${ref.url}`, ...args], { timeout: repo.session?.fetchTimeoutMs ?? GIT_FETCH_TIMEOUT_MS, ...(input !== undefined ? { input } : {}) }); }
1372
1536
  catch (error) { lastError = error; }
@@ -1375,7 +1539,7 @@ async function fetchInto(repo, ref, args, { what, commit, input, raw = false } =
1375
1539
  throw fail("E_REMOTE_UNREADABLE", `cannot read remote ${ref.url} (timeout): git fetch of ${what} timed out after ${Math.round(elapsedMs / 1000)} s`,
1376
1540
  { url: ref.url, key: ref.key, reason: "timeout", commit, operation: "fetch", elapsedMs });
1377
1541
  }
1378
- throw raw ? lastError : unreadable(ref, lastError, { commit, ...(classifyRemoteFailure(lastError) === "cache" ? { cacheDir: repo.dir, stage: "fetch" } : {}) });
1542
+ throw raw ? lastError : fetchFailure(repo, ref, lastError, commit);
1379
1543
  }
1380
1544
 
1381
1545
  /** The sizes of `oids` in the cache, one `cat-file --batch-check`: → Map oid → size, null when the cache lacks it. */
@@ -1419,7 +1583,7 @@ async function ensureBlobs(repo, ref, commit, entries) {
1419
1583
  { what, commit, input: wanted.map((o) => `${o}\n`).join(""), raw: true });
1420
1584
  } catch (error) {
1421
1585
  if (typeof error?.code === "string" && error.code.startsWith("E_")) throw error;
1422
- if (!isRefusedWant(error)) throw unreadable(ref, error, { commit, ...(classifyRemoteFailure(error) === "cache" ? { cacheDir: repo.dir, stage: "fetch" } : {}) });
1586
+ if (!isRefusedWant(error)) throw fetchFailure(repo, ref, error, commit);
1423
1587
  await refetch();
1424
1588
  await recordFullFetches(repo, ref);
1425
1589
  }
@@ -1788,7 +1952,8 @@ function listingUnreadable(error, { repo, spec, path, ref, commit }) {
1788
1952
  if (missingObject) markCacheDamaged(repo, `${spec}: ${text.trim().split("\n")[0]}`);
1789
1953
  const killed = !error?.timedOut && !error?.overflowed && typeof error?.signal === "string" && error.signal !== "";
1790
1954
  const reason = error?.timedOut ? "timeout" : killed ? "killed" : missingObject ? "cache" : "unknown";
1791
- const why = error?.overflowed ? "listing exceeded the output budget" : killed ? `git was killed (signal ${error.signal})` : (text.trim().split("\n")[0] || error?.code || error?.message || "git ls-tree failed");
1955
+ // git's first line, as before, through the one scrub (scrubGitLine); a message of Node's when git said nothing.
1956
+ const why = error?.overflowed ? "listing exceeded the output budget" : killed ? `git was killed (signal ${error.signal})` : (scrubGitLine(text.trim().split("\n")[0], ref?.url) || error?.code || scrubGitLine(error?.message, ref?.url) || "git ls-tree failed");
1792
1957
  return fail("E_REMOTE_UNREADABLE", `cannot list ${spec}${path !== undefined ? ` -- ${path}` : ""} in ${ref?.key ?? repo.dir} (${reason}: ${why})`, { url: ref?.url ?? null, key: ref?.key ?? null, reason, commit: commit ?? null, spec, path: path ?? null, cause: error?.code ?? null, overflowed: error?.overflowed === true, ...(killed ? { signal: error.signal } : {}) });
1793
1958
  }
1794
1959
 
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
+ }