@awebai/oats 0.50.0 → 0.52.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 (132) hide show
  1. package/README.md +1 -0
  2. package/bin/oats.mjs +153 -51
  3. package/docs/capabilities.md +11 -3
  4. package/docs/configuration.md +134 -88
  5. package/docs/desktop-cli-api.md +994 -71
  6. package/docs/desktop-instance-start.md +56 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +230 -59
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +73 -8
  12. package/docs/integrations.md +9 -8
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +43 -7
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/oats-local.schema.json +4 -3
  20. package/docs/official-catalog.md +4 -4
  21. package/docs/packages.md +14 -14
  22. package/docs/release-lane.md +15 -5
  23. package/docs/release-notes/v0.44.0.md +1 -1
  24. package/docs/release-notes/v0.51.0.md +156 -0
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/schedules.md +91 -4
  27. package/docs/servers.md +21 -2
  28. package/docs/souls-and-instances.md +113 -21
  29. package/docs/tui.md +152 -0
  30. package/docs/workspaces.md +2 -2
  31. package/lib/claim.mjs +266 -0
  32. package/lib/core.mjs +845 -166
  33. package/lib/errors.mjs +170 -0
  34. package/lib/harness-trust-write.mjs +68 -27
  35. package/lib/harness-trust.mjs +34 -16
  36. package/lib/instance-inspect.mjs +40 -11
  37. package/lib/instance-lifecycle.mjs +169 -47
  38. package/lib/launch-preference.mjs +16 -0
  39. package/lib/launch-prompt-completion.mjs +7 -43
  40. package/lib/launch-prompt-evidence.mjs +14 -7
  41. package/lib/launch-prompt-fixtures/README.md +86 -152
  42. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  43. package/lib/launch-prompt-fixtures.mjs +122 -109
  44. package/lib/launch-prompt-transport.mjs +2 -56
  45. package/lib/launch-prompts.mjs +102 -100
  46. package/lib/schedule-host.mjs +154 -22
  47. package/lib/schedule.mjs +73 -24
  48. package/lib/servers.mjs +20 -4
  49. package/lib/session-viewer.mjs +87 -10
  50. package/lib/system-tools.mjs +39 -0
  51. package/lib/tmux-server-scope.mjs +62 -0
  52. package/lib/triggers.mjs +4 -4
  53. package/lib/workspace.mjs +5 -11
  54. package/lib/worktree-hooks.mjs +116 -23
  55. package/lib/worktree.mjs +89 -102
  56. package/package-catalog.json +3 -3
  57. package/package.json +7 -2
  58. package/packages/client/capability-show-contract.mjs +230 -0
  59. package/packages/client/capability-warnings-contract.mjs +57 -0
  60. package/packages/client/cli-adapter.mjs +548 -0
  61. package/packages/client/cli-environment.mjs +53 -0
  62. package/packages/client/cli-locator.mjs +253 -0
  63. package/packages/client/cli-probe-contract.mjs +47 -0
  64. package/packages/client/client-terms.mjs +60 -0
  65. package/packages/client/deployment-contract.mjs +68 -0
  66. package/packages/client/deployment-data.mjs +483 -0
  67. package/packages/client/deployment-facts.mjs +34 -0
  68. package/packages/client/deployment-label.mjs +76 -0
  69. package/packages/client/deployment-observer.mjs +89 -0
  70. package/packages/client/deployment-panel.mjs +142 -0
  71. package/packages/client/deployment-read-cli.mjs +53 -0
  72. package/packages/client/display-text.mjs +44 -0
  73. package/packages/client/harness-names.mjs +30 -0
  74. package/packages/client/inspect-contract.mjs +62 -0
  75. package/packages/client/instance-acts.mjs +54 -0
  76. package/packages/client/instance-admission.mjs +45 -0
  77. package/packages/client/instance-events-contract.mjs +74 -0
  78. package/packages/client/instance-git-contract.mjs +80 -0
  79. package/packages/client/instance-presentation.mjs +22 -0
  80. package/packages/client/instance-tree.mjs +453 -0
  81. package/packages/client/kernel-environment.mjs +11 -0
  82. package/packages/client/launch-contract.mjs +51 -0
  83. package/packages/client/launch-prompt-outcome.mjs +165 -0
  84. package/packages/client/lifecycle-cli.mjs +61 -0
  85. package/packages/client/lifecycle-contract.mjs +372 -0
  86. package/packages/client/liveness-main.mjs +10 -0
  87. package/packages/client/liveness.mjs +35 -0
  88. package/packages/client/machine-contract.mjs +123 -0
  89. package/packages/client/own-environment.mjs +22 -0
  90. package/packages/client/panel-views.mjs +286 -0
  91. package/packages/client/readiness-contract.mjs +172 -0
  92. package/packages/client/refresh-loop.mjs +52 -0
  93. package/packages/client/remote-address.mjs +126 -0
  94. package/packages/client/remote-roster.mjs +67 -0
  95. package/packages/client/roster-sections.mjs +80 -0
  96. package/packages/client/spawn-apply-cli.mjs +104 -0
  97. package/packages/client/spawn-apply-contract.mjs +183 -0
  98. package/packages/client/spawn-decision.mjs +46 -0
  99. package/packages/client/spawn-messages.mjs +119 -0
  100. package/packages/client/spawn-preview-cli.mjs +32 -0
  101. package/packages/client/spawn-preview-contract.mjs +314 -0
  102. package/packages/client/team-members.mjs +41 -0
  103. package/packages/client/team-rows.mjs +45 -0
  104. package/packages/client/terminal-contract.mjs +57 -0
  105. package/packages/client/tmux-status.mjs +66 -0
  106. package/packages/client/waiting-on-you.mjs +88 -0
  107. package/packages/client/workspace-admission.mjs +45 -0
  108. package/packages/client/workspace-cli.mjs +142 -0
  109. package/packages/client/workspace-views.mjs +147 -0
  110. package/packages/tui/README.md +46 -0
  111. package/packages/tui/bin/tui.mjs +7 -0
  112. package/packages/tui/lib/actions.mjs +29 -0
  113. package/packages/tui/lib/client.mjs +4 -0
  114. package/packages/tui/lib/main.mjs +105 -0
  115. package/packages/tui/lib/term/keys.mjs +323 -0
  116. package/packages/tui/lib/term/screen.mjs +122 -0
  117. package/packages/tui/lib/term/style.mjs +43 -0
  118. package/packages/tui/lib/term/text.mjs +49 -0
  119. package/packages/tui/lib/term/tty.mjs +168 -0
  120. package/packages/tui/lib/term/width.mjs +124 -0
  121. package/packages/tui/lib/views/frame.mjs +62 -0
  122. package/packages/tui/lib/views/help.mjs +28 -0
  123. package/packages/tui/package.json +8 -0
  124. package/skills/oats-getting-started/SKILL.md +29 -22
  125. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  126. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  127. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  128. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  129. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  130. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  131. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  132. package/lib/launch-prompt-policy.mjs +0 -87
package/lib/worktree.mjs CHANGED
@@ -21,20 +21,20 @@
21
21
  import { execFileSync, spawn as spawnChild, spawnSync } from "node:child_process";
22
22
  import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
23
23
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
24
- import { oatsError } from "./errors.mjs";
24
+ import { checkHolderByHand, ifItDoesNotEnd, lifecycleBusy, nothingAfter, oatsError, OWN_START_REMEDY } from "./errors.mjs";
25
25
  import { appendEvent } from "./instance-events.mjs";
26
26
  import { recordedTeams } from "./teams.mjs";
27
27
  import { canonicalCloneKey, memberCloneOf } from "./instance-resolution.mjs";
28
28
  import { loadLocal } from "./workspace.mjs";
29
29
  import { GIT_FETCH_TIMEOUT_MS } from "./remote.mjs";
30
- import { randomBytes } from "node:crypto";
31
30
  import { terminateGroup, watchGroup } from "./process-group.mjs";
31
+ import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, recordInClaim, releaseClaim, shownHolder } from "./claim.mjs";
32
32
  import {
33
33
  cloneOfMember, instanceSoulDir, isCapturedHome, isWorkspaceHome, capturedHomeRefusal, preWorkspaceHome, lifecycleHookEnv,
34
- retirePendingMarkerPath, stableSoulId, workspaceOf,
34
+ refuseBesideRetire, retirePendingMarkerPath, stableSoulId, workspaceOf,
35
35
  } from "./core.mjs";
36
36
  import {
37
- endOwnGroupSync, interruptExitStatus, processStartToken, runWorktreeHooks, scrubRemoteUrl, selfIdentity, signalGuard, terminateRecordedGroup, treeStillThere,
37
+ endOwnGroupSync, interruptExitStatus, isStartToken, processStartToken, runWorktreeHooks, scrubRemoteUrl, selfIdentity, signalGuard, terminateRecordedGroup, treeStillThere,
38
38
  processLiveness, unknownGroupNote, unverifiedGroupWarning, verifiedAlive, worktreeHooksOf,
39
39
  } from "./worktree-hooks.mjs";
40
40
 
@@ -90,7 +90,7 @@ export function trackedGit(argv, { track, timeout = 120_000 }) {
90
90
  // holds no pipe would outlive it. One that survives SIGKILL keeps its identity recorded, and the
91
91
  // command stops here (keepClaim: the claim holding it is not released).
92
92
  if (timedOut && tracked && endOwnGroupSync(child.pid) === "survived") {
93
- return fail(Object.assign(oatsError("E_LIFECYCLE_BUSY", `a git step that timed out could not be ended (process group ${child.pid} survived SIGKILL); it stays recorded, and nothing more was done — end that process, then retry`), { details: { gitPid: child.pid }, keepClaim: true }));
93
+ return fail(Object.assign(lifecycleBusy("none", `a git step that timed out could not be ended (process group ${child.pid} survived SIGKILL); it stays recorded, and nothing more was done`, "end that process, then retry", { gitPid: child.pid }), { keepClaim: true }));
94
94
  }
95
95
  if (!tracked) return done({ ok: false, out: "", err: `the git step was not run: ${trackError ? `its process could not be recorded (${trackError.message})` : "its start time could not be read"}`, status: null });
96
96
  try { track(null); } catch { /* the record or claim is gone: nothing left to clear */ }
@@ -101,8 +101,9 @@ export function trackedGit(argv, { track, timeout = 120_000 }) {
101
101
 
102
102
  /** End the git step a dead holder recorded (`{ gitPid, gitStart }`), only when its leader runs with
103
103
  * the recorded start time (terminateRecordedGroup): SIGTERM, which git answers by removing its lock
104
- * files, then SIGKILL. → { owed?, remedy?, warning? }: `owed` stops the caller, which keeps `at` (the
105
- * claim or record naming the step); `remedy` is the way out. A step whose leader's start cannot be
104
+ * files, then SIGKILL. → { owed?, remedy?, warning?, ended? }: `owed` stops the caller, which keeps `at` (the
105
+ * claim or record naming the step); `remedy` is the way out; `ended` says that the step was signalled and
106
+ * is gone, for a caller that then fails (lib/claim.mjs takeOver). A step whose leader's start cannot be
106
107
  * read is owed, never a warning: it may still be that git, about to change the tree or the branch. */
107
108
  function endRecordedGit(holder, at, otherwise = `remove ${at}`) {
108
109
  if (!holder?.gitPid) return {};
@@ -111,6 +112,7 @@ function endRecordedGit(holder, at, otherwise = `remove ${at}`) {
111
112
  if (ended === "survived") return { owed: `git process group ${holder.gitPid}, left running by a killed oats worktree command, survived SIGKILL`, remedy: "end that process, then retry" };
112
113
  if (ended === "unknown") return { owed: unknownGroupNote(rec, "git"), remedy: unknownGroupRemedy(holder.gitPid, "git", otherwise) };
113
114
  if (ended === "unverified") return { warning: unverifiedGroupWarning(holder.gitPid, "git") };
115
+ if (ended === "terminated" || ended === "killed") return { ended: `git process group ${holder.gitPid}, left running by a killed oats worktree command, was ended` };
114
116
  return {};
115
117
  }
116
118
 
@@ -164,6 +166,9 @@ export function readTreeHome(home) {
164
166
  if (!isWorkspaceHome(meta)) throw preWorkspaceHome(home, "no tree was made");
165
167
  if (existsSync(join(home, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${home} is a quarantined home (or a spawn still in progress); finish its retirement (oats retire) before making trees in it`);
166
168
  if (existsSync(retirePendingMarkerPath(home))) throw oatsError("E_INSTANCE_RETIRING", `${basename(home)} is being retired; no tree was made`);
169
+ // A retire in flight holds the home's lifecycle claim. Read, never taken: an add runs hooks for
170
+ // minutes and has its purpose's claim.
171
+ refuseBesideRetire("worktree add", home);
167
172
  return { home, meta };
168
173
  }
169
174
 
@@ -232,7 +237,9 @@ function createRecord(path, rec) {
232
237
  const tmp = `${path}.tmp-${process.pid}`;
233
238
  writeFileSync(tmp, JSON.stringify(rec, null, 2) + "\n", { mode: 0o600 });
234
239
  try { linkSync(tmp, path); }
235
- catch (e) { if (e.code === "EEXIST") throw oatsError("E_LIFECYCLE_BUSY", `another oats worktree add of purpose ${rec.purpose} started at the same moment; nothing was done`); throw e; }
240
+ // Reached only when a record appeared after this add, which holds the purpose's claim, read that
241
+ // there was none: whoever wrote it did not hold the claim, and whether it still runs was not read.
242
+ catch (e) { if (e.code === "EEXIST") throw lifecycleBusy("unknown", `another oats worktree add of purpose ${rec.purpose} wrote ${path} at the same moment; nothing was done`, `check whether the process that record names still runs (its \`pid\`), then run the command again`, { purpose: rec.purpose, record: path }); throw e; }
236
243
  finally { try { unlinkSync(tmp); } catch { /* gone */ } }
237
244
  }
238
245
 
@@ -334,120 +341,100 @@ const worktreeFields = (out, field) => out.split("\0").filter((f) => f.startsWit
334
341
  * recovery) is taken over, so a killed command can always be run again: the owner is named by
335
342
  * pid AND start time (processLiveness), never by a pid alone, and a holder whose start cannot be
336
343
  * read is never taken for gone. A claim held by a live process is
337
- * waited for up to `CLAIM_WAIT_MS`, then refused as E_LIFECYCLE_BUSY. The holder's git steps
344
+ * waited for up to `CLAIM_WAIT_MS`, then refused as E_LIFECYCLE_BUSY; so is, with its own sentence,
345
+ * a file at the claim's path that is no claim this kernel can read or take over. The holder's git steps
338
346
  * are recorded in the claim (trackedGit), and a takeover ends one still running first: a dead
339
- * holder's git never finishes late on a tree made after the takeover.
347
+ * holder's git never finishes late on a tree made after the takeover. A command that is refused the
348
+ * claim after its takeover ended such a step answers E_LIFECYCLE_FAILED, naming what it ended first:
349
+ * E_LIFECYCLE_BUSY says that nothing happened (lib/errors.mjs afterEndedSteps).
340
350
  * `fn({ track, warnings })`; → Promise of what `fn` returns. */
341
351
  function withPurposeClaim(home, purpose, fn) {
342
352
  const dir = join(home, ".oats", "trees");
343
- mkdirSync(dir, { recursive: true, mode: 0o700 });
344
353
  const lock = join(dir, `${purpose}.lock`);
345
- const busy = (holder, unknown, at = lock) => Object.assign(oatsError("E_LIFECYCLE_BUSY", unknown
346
- ? `whether pid ${holder?.pid ?? "?"} (recorded start ${holder?.processStart ?? "none"}), which holds ${at}, still runs cannot be read (${unknown}); nothing was done — check that pid by hand, and if it is not an oats worktree command, remove ${at}, then retry`
347
- : `another oats worktree add or remove of purpose ${purpose} is running (pid ${holder?.pid ?? "?"} holds ${at}); nothing was done — retry when it has finished`), { details: { purpose, lock: at, ...(holder?.pid ? { pid: holder.pid } : {}), ...(unknown ? { unknown } : {}) } });
348
- return withClaim(lock, fn, { busy });
354
+ // A directory that cannot be made is a claim that cannot be taken: nothing was done (#874).
355
+ try { mkdirSync(dir, { recursive: true, mode: 0o700 }); } catch (e) { throw claimUnavailable(lock, e); }
356
+ return withClaim(lock, fn, { busy: purposeClaimBusy(purpose, lock) });
349
357
  }
350
358
 
351
- const CLAIM_WAIT_MS = 3000;
352
- const CLAIM_MAX_DEPTH = 8;
353
- const pauseSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
354
- function readClaim(path) {
355
- try { const o = JSON.parse(readFileSync(path, "utf8")); return o && typeof o === "object" ? o : { unreadable: true }; }
356
- catch (e) { return e.code === "ENOENT" ? null : { unreadable: true }; }
359
+ /** The `busy` refusal of the claim `lock` of `purpose` (lib/claim.mjs): E_LIFECYCLE_BUSY, one line
360
+ * that says nothing was done; `details.lock` is the file that names the holder. The holder is
361
+ * named as lib/claim.mjs shownHolder allows, here and in every refusal made from this one
362
+ * (worktreeClaimRefusals): a pid or a start that is not the kernel's is `?` or `none` in the
363
+ * message, and `details` has no `pid`. A holder that runs is waited for; the step also says what
364
+ * to check when it does not end (lib/errors.mjs ifItDoesNotEnd): alive is all that was
365
+ * established of the pid, not that it is an oats worktree command. `ended` is what
366
+ * the claim's takeovers ended before it: then the line says "nothing else was done" and the answer
367
+ * is E_LIFECYCLE_FAILED, what was ended first (lib/errors.mjs afterEndedSteps). Exported for its tests. */
368
+ export function purposeClaimBusy(purpose, lock) {
369
+ return (holder, unknown, at = lock, ended = []) => {
370
+ const shown = shownHolder(holder);
371
+ const details = { purpose, lock: at, ...(shown.pid ? { pid: shown.pid } : {}) };
372
+ return unknown
373
+ ? lifecycleBusy("unknown", `whether pid ${shown.pid ?? "?"} (recorded start ${shown.start ?? "none"}), which holds ${at}, still runs cannot be read (${unknown}); ${nothingAfter(ended)}`, checkHolderByHand("an oats worktree command", at), { ...details, unknown }, ended)
374
+ : lifecycleBusy("running", `another oats worktree add or remove of purpose ${purpose} is running (pid ${shown.pid ?? "?"} holds ${at}); ${nothingAfter(ended)}`, `retry when it has finished; ${ifItDoesNotEnd("an oats worktree command", at)}`, details, ended);
375
+ };
376
+ }
377
+
378
+ /** The refusals of an `oats worktree` command that cannot take a claim, as lib/claim.mjs asks for
379
+ * them, each made from the caller's `busy` with its own sentence. Every one says "nothing was
380
+ * done", once; "nothing else was done" when `ended`, its last argument, names what the claim's
381
+ * takeovers ended before it. Exported for its tests. */
382
+ export function worktreeClaimRefusals(busy) {
383
+ // The caller's details (its purpose, the file, the holder's pid), with this refusal's own
384
+ // sentence, remedy and `holder`: in none of the four is anybody known to be running.
385
+ const refuse = (holder, at, value, said, remedy, ended) => lifecycleBusy(value, said, remedy, busy(holder, null, at).details, ended);
386
+ return {
387
+ busy,
388
+ ownStartUnreadable: (reason, at, ended = []) => refuse(null, at, "none", `this process's start time cannot be read (${reason}), so it cannot hold ${at} verifiably; ${nothingAfter(ended)}`,
389
+ OWN_START_REMEDY, ended),
390
+ unreadableClaim: (at, ended = []) => refuse(null, at, "unknown", `${at} is not a readable claim; ${nothingAfter(ended)}`, "inspect it and remove it if no oats worktree command holds it, then retry", ended),
391
+ cannotTakeOver: (holder, at, why, ended = []) => refuse(holder, at, "none", `the process that held ${at} (pid ${shownHolder(holder).pid ?? "?"}) is gone, and this file is not a claim this kernel can take over (${why}); ${nothingAfter(ended)}`,
392
+ `inspect ${at} and remove it if no oats worktree command holds it, then retry`, ended),
393
+ // Nothing is wrong with the file: each command that took the claim died, and this one came
394
+ // after each of them. The next run takes over the one that is there.
395
+ heldAgain: (holder, at, times, ended = []) => refuse(holder, at, "none", `the claim ${at} was found without a live holder ${times} times and was taken again each time, the last time by a process that is gone (pid ${shownHolder(holder).pid ?? "?"}); ${nothingAfter(ended)}`,
396
+ "run the command again", ended),
397
+ };
357
398
  }
358
399
 
359
- /** Run `fn` holding the claim file `path`. Exported for its tests.
400
+ /** Run `fn` holding the claim file `path` (lib/claim.mjs: how a claim is taken, taken over from a
401
+ * dead holder and released). Exported for its tests.
360
402
  *
361
- * - Taking it: the owner's facts `{ pid, processStart, nonce }` are written to a private file and
362
- * hard-linked to `path`, which fails if `path` exists. So a claim is never seen without its
363
- * owner, and the nonce makes each holding distinct, even for the same process.
364
- * - Its owner is gone (processLiveness "gone"; "unknown" is refused, never taken over): the claim
365
- * is removed under a second claim,
366
- * `<path>.reclaim-<owner nonce>`, taken by this same protocol. Its holder re-reads `path` and
367
- * removes it only if it still names that owner. Nothing else removes another's claim: its
368
- * owner never releases it, and a new acquirer cannot write over an existing file. Two takeovers
369
- * of one dead owner are therefore serialized, and neither removes a claim made after it read.
370
- * A takeover cut short leaves its own claim behind, which the next takeover takes over in
371
- * turn, up to CLAIM_MAX_DEPTH nested levels.
372
- * - The holder's running git step (`gitPid`, `gitStart`; trackedGit) is in the claim. A takeover
373
- * ends it first (endRecordedGit) and refuses, keeping the claim, if it cannot be ended.
374
- * - Released by unlinking `path`, only while it still names this holding.
375
- * - An unreadable claim file is never removed: the command is refused as busy, naming the file. */
403
+ * The holder's running git step (`gitPid`, `gitStart`; trackedGit) is in the claim. A takeover
404
+ * ends it first (endRecordedGit) and refuses, keeping the claim, if it cannot be ended.
405
+ * `fn({ track, warnings })`; → Promise of what `fn` returns. An error with `keepClaim` leaves the
406
+ * claim held, for the step it names. */
376
407
  export async function withClaim(path, fn, { busy, waitMs = CLAIM_WAIT_MS } = {}) {
377
408
  const warnings = [];
378
- const me = acquireClaim(path, { busy, waitMs, warnings }, 0);
409
+ const me = acquireClaim(path, {
410
+ ...worktreeClaimRefusals(busy), waitMs, warnings,
411
+ // A step that could not be ended refuses, and `at` is kept: `holder: "none"`, since the holder
412
+ // is gone and its git has to be ended by hand; the caller's details, with the step's (`gitPid`
413
+ // is an integer whenever a step is owed; `gitStart` is shown only as a token of the kernel's).
414
+ // `before` is what this acquisition's takeovers ended before this step.
415
+ endHolderStep: (holder, at, before = []) => {
416
+ const ended = endRecordedGit(holder, at);
417
+ return ended.owed ? { refusal: lifecycleBusy("none", `${ended.owed}; ${at} is kept and ${nothingAfter(before)}`, ended.remedy, { ...busy(holder).details, gitPid: holder.gitPid, gitStart: isStartToken(holder.gitStart) ? holder.gitStart : null }, before) } : ended;
418
+ },
419
+ });
379
420
  // Record (or clear) the holder's running git step in the claim; only its live holder writes it.
380
- const track = (gitStep) => {
381
- const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
382
- writeFileSync(tmp, JSON.stringify({ ...me, ...(gitStep ?? {}) }) + "\n", { mode: 0o600 });
383
- renameSync(tmp, path);
384
- };
421
+ const track = (gitStep) => recordInClaim(path, me, gitStep);
385
422
  let keep = false;
386
423
  try { return await fn({ track, warnings }); }
387
424
  catch (e) { keep = e?.keepClaim === true; throw e; }
388
425
  finally { if (!keep) releaseClaim(path, me); }
389
426
  }
390
427
 
391
- function acquireClaim(path, opts, depth) {
392
- const { busy, waitMs } = opts;
393
- const self = selfIdentity();
394
- if (!self.processStart) throw Object.assign(busy(null), { message: `this process's start time cannot be read, so it cannot hold ${path} verifiably; nothing was done` });
395
- const me = { ...self, nonce: randomBytes(16).toString("hex"), at: new Date().toISOString() };
396
- const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
397
- writeFileSync(tmp, JSON.stringify(me) + "\n", { mode: 0o600 });
398
- try {
399
- const deadline = Date.now() + waitMs;
400
- for (;;) {
401
- try { linkSync(tmp, path); return me; }
402
- catch (e) { if (e.code !== "EEXIST") throw e; }
403
- const holder = readClaim(path);
404
- if (holder === null) continue; // released in between
405
- if (holder.unreadable) throw Object.assign(busy(null), { message: `${path} is not a readable claim; inspect it and remove it if no oats worktree command holds it; nothing was done` });
406
- const live = processLiveness(holder);
407
- // Unreadable is never taken for gone: the claim is kept, and the refusal names the way out.
408
- if (live.state === "unknown") throw busy(holder, live.reason, path);
409
- if (live.state === "gone") {
410
- if (depth >= CLAIM_MAX_DEPTH || typeof holder.nonce !== "string" || !/^[0-9a-f]{32}$/.test(holder.nonce)) throw busy(holder, null, path);
411
- takeOver(path, holder, opts, depth);
412
- continue;
413
- }
414
- if (Date.now() >= deadline) throw busy(holder, null, path);
415
- pauseSync(50);
416
- }
417
- } finally {
418
- try { unlinkSync(tmp); } catch { /* gone */ }
419
- }
420
- }
421
-
422
- /** Remove `path`, held by the dead `holder`, under the claim that serializes takeovers of it. */
423
- function takeOver(path, holder, opts, depth) {
424
- const reclaim = `${path}.reclaim-${holder.nonce}`;
425
- const me = acquireClaim(reclaim, opts, depth + 1);
426
- try {
427
- const now = readClaim(path);
428
- if (now?.nonce === holder.nonce) {
429
- const ended = endRecordedGit(now, path);
430
- if (ended.owed) {
431
- const e = opts.busy(now);
432
- throw Object.assign(e, { message: `${ended.owed}; ${path} is kept and nothing was done — ${ended.remedy}`, details: { ...e.details, gitPid: now.gitPid, gitStart: now.gitStart ?? null } });
433
- }
434
- if (ended.warning) opts.warnings?.push(ended.warning);
435
- unlinkSync(path);
436
- }
437
- } finally {
438
- releaseClaim(reclaim, me);
439
- }
440
- }
441
-
442
- function releaseClaim(path, me) {
443
- if (readClaim(path)?.nonce === me.nonce) { try { unlinkSync(path); } catch { /* gone */ } }
444
- }
428
+ /** What ends an interrupted add's rollback that could not be completed: nobody is running, and
429
+ * what the message lists as owed has to be dealt with before the rollback can finish. */
430
+ const owedRollbackRemedy = (purpose) => `deal with what is listed (end the process group, or remove the tree or the branch with Git), then run \`oats worktree remove --purpose ${purpose}\`, which finishes the rollback`;
445
431
 
446
432
  /** A `creating` record whose adder may still run: its start cannot be read. Never rolled back on
447
433
  * that; the refusal names the pid and the record's exact path, the way out once the pid is
448
434
  * checked by hand. */
449
435
  function unknownAdderRefusal({ purpose, tree, recPath, rec, reason }) {
450
- return Object.assign(oatsError("E_LIFECYCLE_BUSY", `whether the oats worktree add of purpose ${purpose} (pid ${rec.pid}, recorded start ${rec.processStart ?? "none"}) still runs cannot be read (${reason}); nothing was done — check that pid by hand, and if it is not an oats worktree add, ${leftoverRemedy(recPath, tree, rec)} and retry`), { details: { purpose, path: tree, record: recPath, pid: rec.pid, unknown: reason } });
436
+ return lifecycleBusy("unknown", `whether the oats worktree add of purpose ${purpose} (pid ${rec.pid}, recorded start ${rec.processStart ?? "none"}) still runs cannot be read (${reason}); nothing was done`,
437
+ `check that pid by hand, and if it is not an oats worktree add, ${leftoverRemedy(recPath, tree, rec)} and retry`, { purpose, path: tree, record: recPath, pid: rec.pid, unknown: reason });
451
438
  }
452
439
 
453
440
  // ---------- add ----------
@@ -490,7 +477,7 @@ export async function worktreeAdd(homeArg, o = {}) {
490
477
  if (found?.state === "unreadable") throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${recPath} is not a readable tree record; inspect it (and the tree at ${tree}), remove what is not yours, then retry`), { details: { purpose, path: tree, record: recPath } });
491
478
  if (found?.state === "creating") {
492
479
  const live = processLiveness(found);
493
- if (live.state === "alive") throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `an oats worktree add of purpose ${purpose} is still running (pid ${found.pid}, since ${found.startedAt}); nothing was done`), { details: { purpose, path: tree, pid: found.pid } });
480
+ if (live.state === "alive") throw lifecycleBusy("running", `an oats worktree add of purpose ${purpose} is still running (pid ${found.pid}, since ${found.startedAt}); nothing was done`, null, { purpose, path: tree, pid: found.pid });
494
481
  if (live.state === "unknown") throw unknownAdder(found, live.reason);
495
482
  return { recover: found };
496
483
  }
@@ -527,7 +514,7 @@ export async function worktreeAdd(homeArg, o = {}) {
527
514
  if (d.recover) {
528
515
  const rb = await rollbackTree(home, d.recover, { track });
529
516
  recoveryWarnings.push(...rb.warnings);
530
- if (rb.owed.length) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `an earlier oats worktree add of purpose ${purpose} was interrupted and its rollback could not be completed: ${rb.owed.join("; ")}; nothing new was done`), { details: { purpose, path: tree, owed: rb.owed, ...(rb.warnings.length ? { warnings: rb.warnings } : {}) } });
517
+ if (rb.owed.length) throw lifecycleBusy("none", `an earlier oats worktree add of purpose ${purpose} was interrupted and its rollback could not be completed: ${rb.owed.join("; ")}; nothing new was done`, owedRollbackRemedy(purpose), { purpose, path: tree, owed: rb.owed, ...(rb.warnings.length ? { warnings: rb.warnings } : {}) });
531
518
  checkFresh("after the rollback of an interrupted add");
532
519
  }
533
520
  rec = { version: RECORD_VERSION, purpose, state: "creating", path: tree, clone, remote, member, branch, base, ...selfIdentity(), startedAt: new Date().toISOString() };
@@ -631,11 +618,11 @@ export async function worktreeRemove(homeArg, o = {}) {
631
618
  if (rec.state === "unreadable") throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${recPath} is not a readable tree record; inspect it and the tree at ${tree}`), { details: { purpose, path: tree, record: recPath } });
632
619
  if (rec.state === "creating") {
633
620
  const live = processLiveness(rec);
634
- if (live.state === "alive") throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `an oats worktree add of purpose ${purpose} is still running (pid ${rec.pid}); nothing was removed`), { details: { purpose, path: tree, pid: rec.pid } });
621
+ if (live.state === "alive") throw lifecycleBusy("running", `an oats worktree add of purpose ${purpose} is still running (pid ${rec.pid}); nothing was removed`, null, { purpose, path: tree, pid: rec.pid });
635
622
  if (live.state === "unknown") throw unknownAdderRefusal({ purpose, tree, recPath, rec, reason: live.reason });
636
623
  const rb = await rollbackTree(home, rec, { track });
637
624
  const warned = [...claimWarnings, ...rb.warnings];
638
- if (rb.owed.length) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `the rollback of an interrupted add of purpose ${purpose} could not be completed: ${rb.owed.join("; ")}`), { details: { purpose, path: tree, owed: rb.owed, ...(warned.length ? { warnings: warned } : {}) } });
625
+ if (rb.owed.length) throw lifecycleBusy("none", `the rollback of an interrupted add of purpose ${purpose} could not be completed: ${rb.owed.join("; ")}`, owedRollbackRemedy(purpose), { purpose, path: tree, owed: rb.owed, ...(warned.length ? { warnings: warned } : {}) });
639
626
  return { purpose, path: tree, removed: true, rolledBack: true, branch: rec.branch, branchKept: rb.branchKept, ...(rb.branchKeptReason ? { branchKeptReason: rb.branchKeptReason } : {}), ...(warned.length ? { warnings: warned } : {}) };
640
627
  }
641
628
  const clone = rec.clone;
@@ -3,12 +3,12 @@
3
3
  "packages": {
4
4
  "oats.okf": {
5
5
  "url": "https://github.com/awebai/oats-okf.git",
6
- "ref": "v5.0.0",
6
+ "ref": "v5.0.2",
7
7
  "path": "oats-package"
8
8
  },
9
9
  "oats.aweb": {
10
10
  "url": "https://github.com/awebai/oats-aweb.git",
11
- "ref": "v1.24.0",
11
+ "ref": "v1.27.0",
12
12
  "path": "oats-package"
13
13
  },
14
14
  "oats.jira": {
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "oats.framework": {
45
45
  "url": "https://github.com/awebai/oats.git",
46
- "ref": "oats-framework/v1.9.0",
46
+ "ref": "oats-framework/v1.9.3",
47
47
  "path": "oats-package"
48
48
  }
49
49
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.50.0",
3
+ "version": "0.52.0",
4
4
  "description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
5
5
  "keywords": [
6
6
  "agents",
@@ -39,7 +39,12 @@
39
39
  "packages/record/docs/",
40
40
  "packages/record/test/vectors/",
41
41
  "packages/record/README.md",
42
- "packages/record/package.json"
42
+ "packages/record/package.json",
43
+ "packages/client/",
44
+ "packages/tui/bin/",
45
+ "packages/tui/lib/",
46
+ "packages/tui/README.md",
47
+ "packages/tui/package.json"
43
48
  ],
44
49
  "dependencies": {
45
50
  "@awebai/pi": "^0.2.1",
@@ -0,0 +1,230 @@
1
+ /** `oats capabilities show <name> (--member <repoKey> | --package <id>) [--file <path>] --json`
2
+ * (feature `capability-show`, `capabilityShowApi: 1`): what a capability ships — its injected
3
+ * instructions and its skills' files — read at the commit the catalog reports. Shared by the
4
+ * zero-dependency server (it validates before caching) and the capability page's Contents reader.
5
+ *
6
+ * The decoder is strict and bounded: an unknown API version, a field of the wrong type, an
7
+ * oversize string or list, or a path that is not a plain relative POSIX path inside the
8
+ * capability refuses the WHOLE answer (null), never a partial render. Presentation-only: nothing
9
+ * here infers a file the kernel did not list. The tolerant fields: `warnings` (OATS 0.49.0), projected by
10
+ * capability-warnings-contract.mjs, and `triggerSources` / `triggerSourceProblems` (feature `trigger-sources`),
11
+ * projected below: never a reason to refuse the answer (an older kernel sends none). */
12
+ import { warningsOf } from './capability-warnings-contract.mjs';
13
+ import { requireTerms } from './client-terms.mjs';
14
+
15
+ export const CAPABILITY_SHOW_API = 1;
16
+ export const CAPABILITY_SHOW_FEATURE = 'capability-show';
17
+ /** What a kernel answer the client cannot read says (the failed state's message), in the client's terms
18
+ * (client-terms.mjs): here the client is the old one, so the sentence names what to update. */
19
+ export function capabilityShowUnreadable(terms) {
20
+ requireTerms(terms, 'capabilityShowUnreadable');
21
+ return `${terms.selfInitial} can't read what this OATS version reports about the capability. Update ${terms.update}.`;
22
+ }
23
+
24
+ /** Bounds. A file's text is at most 256 KiB (the kernel truncates there, `truncated: true`). */
25
+ export const FILE_TEXT_MAX_BYTES = 256 * 1024;
26
+ export const LIMITS = Object.freeze({ path: 1024, skills: 256, files: 200, description: 1024, problems: 64, message: 4096, code: 128, name: 128,
27
+ sources: 16, events: 16, event: 64 });
28
+
29
+ const record = v => !!v && typeof v === 'object' && !Array.isArray(v);
30
+ const CONTROL = /[\u0000-\u001f\u007f]/;
31
+ const CAPABILITY_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
32
+ const PACKAGE_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/; // the kernel's package-id grammar, bounded
33
+ const CODE = /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;
34
+ const COMMIT = /^[0-9a-f]{40}$/;
35
+
36
+ export const validCapabilityName = v => typeof v === 'string' && CAPABILITY_NAME.test(v);
37
+ export const validPackageId = v => typeof v === 'string' && PACKAGE_ID.test(v);
38
+ /** A repository key is the kernel's to parse; the Desktop refuses only what could not be one argv value. */
39
+ export const validRepoKey = v => typeof v === 'string' && v.length > 0 && v.length <= LIMITS.path && v.trim() === v && !CONTROL.test(v) && !v.startsWith('-');
40
+ /** A plain relative POSIX path inside the capability: no leading `/`, no `.`/`..`/empty segment,
41
+ * no backslash, no control character, not option-looking, bounded. */
42
+ export function validRelativePath(v) {
43
+ if (typeof v !== 'string' || !v || v.length > LIMITS.path || CONTROL.test(v) || v.includes('\\') || v.startsWith('-') || v.startsWith('/')) return false;
44
+ return v.split('/').every(part => part !== '' && part !== '.' && part !== '..');
45
+ }
46
+
47
+ /** The connected CLI can answer `capabilities show` (the feature AND the API integer; never a version number). */
48
+ export const capabilityShowSupported = cli => cli?.ok === true && Array.isArray(cli.features) && cli.features.includes(CAPABILITY_SHOW_FEATURE)
49
+ && cli.capabilityShowApi === CAPABILITY_SHOW_API;
50
+
51
+ /** The verb's selector for a catalog row: { name, kind: 'member', repoKey } | { name, kind: 'package', package };
52
+ * null for a row the verb cannot address (an external capability, a malformed row). */
53
+ export function capabilitySelector(row) {
54
+ if (!record(row) || !validCapabilityName(row.name)) return null;
55
+ if (row.kind === 'member' && validRepoKey(row.repoKey)) return { name: row.name, kind: 'member', repoKey: row.repoKey };
56
+ if (row.kind === 'package' && validPackageId(row.package)) return { name: row.name, kind: 'package', package: row.package };
57
+ return null;
58
+ }
59
+ /** The same selector, validated as a request body field (the server's half: exact keys only). */
60
+ export function selectorOf(v) {
61
+ if (!record(v)) return null;
62
+ const keys = Object.keys(v).sort().join(',');
63
+ if (v.kind === 'member' && keys === 'kind,name,repoKey') return capabilitySelector(v);
64
+ if (v.kind === 'package' && keys === 'kind,name,package') return capabilitySelector(v);
65
+ return null;
66
+ }
67
+ export const sameSelector = (a, b) => !!a && !!b && a.name === b.name && a.kind === b.kind && (a.kind === 'member' ? a.repoKey === b.repoKey : a.package === b.package);
68
+
69
+ /* ── the decoder ─────────────────────────────────────────────────────────── */
70
+ class Unreadable extends Error {}
71
+ const refuse = () => { throw new Unreadable(); };
72
+ const byteLength = s => new TextEncoder().encode(s).byteLength;
73
+ function str(v, max) { if (typeof v !== 'string' || v.length > max) refuse(); return v; }
74
+ function nullableStr(v, max) { return v === null ? null : str(v, max); }
75
+ function path(v) { if (!validRelativePath(v)) refuse(); return v; }
76
+ function bytes(v) { if (v === null) return null; if (!Number.isSafeInteger(v) || v < 0) refuse(); return v; }
77
+ function bool(v) { if (typeof v !== 'boolean') refuse(); return v; }
78
+
79
+ /** File = { path, bytes: number|null, text: string|null, binary, truncated }, the kernel's invariants: text is at
80
+ * most 256 KiB of UTF-8 (truncated or not); a binary file has no text and is never truncated; a truncated one has
81
+ * text. `text: null` on a text file (and `bytes: null`) happens only for an unreadable declared inject, which a
82
+ * problem names: never in a `--file` answer (`fileAnswer`). An inject's `path` is null when the manifest's value
83
+ * is not a safe relative path (a problem with `path: null` carries the raw value); then it has no content. */
84
+ function file(v, { fileAnswer = false, inject = false } = {}) {
85
+ if (!record(v)) refuse();
86
+ const out = { path: inject && v.path === null ? null : path(v.path), bytes: bytes(v.bytes), text: nullableStr(v.text, FILE_TEXT_MAX_BYTES), binary: bool(v.binary), truncated: bool(v.truncated) };
87
+ if (out.text !== null && byteLength(out.text) > FILE_TEXT_MAX_BYTES) refuse();
88
+ if (out.binary && (out.text !== null || out.truncated)) refuse();
89
+ if (out.truncated && out.text === null) refuse();
90
+ if (fileAnswer && (out.bytes === null || (!out.binary && out.text === null))) refuse();
91
+ if (out.path === null && (out.text !== null || out.binary || out.bytes !== null)) refuse();
92
+ return out;
93
+ }
94
+ /** A skill's `files` is null when its directory could not be listed (a problem names the skill's path; never
95
+ * truncated then); a listed skill always has at least its SKILL.md. */
96
+ function skill(v) {
97
+ if (!record(v)) refuse();
98
+ const files = v.files === null ? null : Array.isArray(v.files) && v.files.length > 0 && v.files.length <= LIMITS.files ? v.files : refuse();
99
+ const description = nullableStr(v.description ?? null, 4 * LIMITS.description);
100
+ if (description !== null && byteLength(description) > LIMITS.description) refuse();
101
+ const out = { name: str(v.name, LIMITS.name), path: path(v.path), description,
102
+ files: files && files.map(f => { if (!record(f)) refuse(); return { path: path(f.path), bytes: bytes(f.bytes) }; }), filesTruncated: bool(v.filesTruncated) };
103
+ if (!out.name || CONTROL.test(out.name)) refuse();
104
+ if (out.files === null) { if (out.filesTruncated) refuse(); return out; }
105
+ // Every path is relative to the capability directory: a skill's files sit under its own directory.
106
+ if (out.files.some(f => !f.path.startsWith(`${out.path}/`))) refuse();
107
+ if (new Set(out.files.map(f => f.path)).size !== out.files.length) refuse();
108
+ return out;
109
+ }
110
+ function problem(v) {
111
+ if (!record(v)) refuse();
112
+ const code = str(v.code, LIMITS.code);
113
+ if (!CODE.test(code)) refuse();
114
+ return { code, message: str(v.message, LIMITS.message), path: v.path === null || v.path === undefined ? null : path(v.path) };
115
+ }
116
+ function head(v, name) {
117
+ if (!record(v) || v.capabilityShowApi !== CAPABILITY_SHOW_API) refuse();
118
+ if (!validCapabilityName(v.name) || (name !== undefined && v.name !== name)) refuse();
119
+ if (!['member', 'package'].includes(v.kind)) refuse();
120
+ if (typeof v.commit !== 'string' || !COMMIT.test(v.commit)) refuse();
121
+ }
122
+
123
+ /* ── trigger sources (feature `trigger-sources`) ─────────────────────────── */
124
+ /** A string held to `max` UTF-16 units, cut there (never inside a surrogate pair): cutting twice equals cutting once. */
125
+ function cut(s, max) {
126
+ if (s.length <= max) return s;
127
+ const last = s.charCodeAt(max - 1);
128
+ return s.slice(0, last >= 0xD800 && last <= 0xDBFF ? max - 1 : max);
129
+ }
130
+ /** One declared source as far as the page shows it: { events, description? }, or null when the value is not that
131
+ * shape. `command`, `parameters`, `fields` and `urlHosts` are not shown, so they are not relayed. */
132
+ function triggerSourceOf(v) {
133
+ if (!record(v) || !Array.isArray(v.events)) return null;
134
+ const events = v.events.filter(e => typeof e === 'string').slice(0, LIMITS.events).map(e => cut(e, LIMITS.event));
135
+ return { events, ...(typeof v.description === 'string' ? { description: cut(v.description, LIMITS.description) } : {}) };
136
+ }
137
+ /** The manifest's `triggerSources`, which the kernel answers exactly as written, whatever its shape: null when it
138
+ * is not an object (declared, not readable; the raw value is not relayed), else its first LIMITS.sources entries in
139
+ * the kernel's order, each name bounded and each value a `triggerSourceOf`. Every string is the manifest's:
140
+ * untrusted, shown only as quoted text (packages/desktop/renderer/source-quote.mjs). Built from entries, never by assignment: a manifest key
141
+ * may be `__proto__`. Tolerant, bounded and idempotent, like `warningsOf`. */
142
+ export function triggerSourcesOf(v) {
143
+ if (!record(v)) return null;
144
+ return Object.fromEntries(Object.entries(v).slice(0, LIMITS.sources).map(([name, value]) => [cut(name, LIMITS.name), triggerSourceOf(value)]));
145
+ }
146
+ /** `triggerSourceProblems`: [{ source, pointer, message }], the kernel's text (what a trigger naming the source
147
+ * gets as E_TRIGGER_SOURCE). `source: null` is a top-level problem; `pointer` a JSON pointer into the manifest.
148
+ * An entry that is not an object or has no message is skipped; at most LIMITS.problems are kept. They are never
149
+ * `problems`: a malformed declaration does not fail the capability. */
150
+ export function triggerSourceProblemsOf(v) {
151
+ const out = [];
152
+ for (const entry of Array.isArray(v) ? v : []) {
153
+ if (!record(entry) || typeof entry.message !== 'string') continue;
154
+ out.push({ source: typeof entry.source === 'string' ? cut(entry.source, LIMITS.name) : null,
155
+ pointer: typeof entry.pointer === 'string' ? cut(entry.pointer, LIMITS.path) : null, message: cut(entry.message, LIMITS.message) });
156
+ if (out.length === LIMITS.problems) break;
157
+ }
158
+ return out;
159
+ }
160
+ /** What the capability page says about the declaration, from a projected answer (presentation-free):
161
+ * null — the manifest declares none (or an older kernel answered);
162
+ * { unreadable: [the kernel's messages] } — it is not an object, or a top-level problem (`source: null`) disables
163
+ * every source; the messages may be none;
164
+ * { sources: [{ name, events: [..] | null, description: string | null, problems: [the kernel's messages] }] } —
165
+ * the listed sources in the kernel's order, then every source a problem names that the listing does not hold,
166
+ * at most LIMITS.sources. A source with a problem, or with `events: null` (its value is not a source's shape),
167
+ * is declared but not usable. */
168
+ export function triggerSourcesView(show) {
169
+ if (!record(show) || !Object.hasOwn(show, 'triggerSources')) return null;
170
+ const declared = show.triggerSources, problems = Array.isArray(show.triggerSourceProblems) ? show.triggerSourceProblems.filter(record) : [];
171
+ const top = problems.filter(p => p.source === null);
172
+ if (!record(declared) || top.length) return { unreadable: (record(declared) ? top : problems).map(p => p.message) };
173
+ const sources = Object.entries(declared).map(([name, value]) => ({ name, events: Array.isArray(value?.events) ? value.events : null,
174
+ description: typeof value?.description === 'string' ? value.description : null, problems: [] }));
175
+ const named = new Map(sources.map(source => [source.name, source]));
176
+ for (const p of problems) {
177
+ if (!named.has(p.source)) { const source = { name: p.source, events: null, description: null, problems: [] }; named.set(p.source, source); sources.push(source); }
178
+ named.get(p.source).problems.push(p.message);
179
+ }
180
+ return { sources: sources.slice(0, LIMITS.sources) };
181
+ }
182
+
183
+ /** The show answer, normalized, or null when this Desktop cannot read it. `name` / `selector`: the capability
184
+ * asked for (an answer about another capability, or the same name from another member or package, is refused). Every path — the inject's, a skill's, a skill file's — is
185
+ * relative to the capability directory: what `--file` takes, verbatim. */
186
+ export function capabilityShowData(v, { selector, name = selector?.name } = {}) {
187
+ try {
188
+ head(v, name);
189
+ if (v.kind === 'member' ? !validRepoKey(v.repoKey) : !(validPackageId(v.package) && (v.repoKey === null || v.repoKey === undefined || validRepoKey(v.repoKey)))) refuse();
190
+ if (selector && (v.kind !== selector.kind || (v.kind === 'member' ? v.repoKey !== selector.repoKey : v.package !== selector.package))) refuse();
191
+ const skills = v.skills === null ? null : Array.isArray(v.skills) && v.skills.length <= LIMITS.skills ? v.skills.map(skill) : refuse();
192
+ if (skills && new Set(skills.map(s => s.path)).size !== skills.length) refuse();
193
+ const problems = Array.isArray(v.problems) && v.problems.length <= LIMITS.problems ? v.problems.map(problem) : refuse();
194
+ return {
195
+ capabilityShowApi: CAPABILITY_SHOW_API, name: v.name, kind: v.kind, repoKey: v.repoKey ?? null,
196
+ package: v.kind === 'package' ? v.package : null, version: v.version === null || v.version === undefined ? null : str(v.version, 64),
197
+ commit: v.commit, path: v.path === null || v.path === undefined ? null : str(v.path, LIMITS.path),
198
+ inject: v.inject === null ? null : file(v.inject, { inject: true }), skills, problems,
199
+ // Tolerant and idempotent: the server's projection, relayed, projects to itself in the renderer.
200
+ warnings: warningsOf(v.warnings),
201
+ // Only when the kernel answers them (feature `trigger-sources`: the manifest declares the key; the problems
202
+ // follow only when it has some), so an older kernel's answer projects as before. Never `problems`.
203
+ ...(Object.hasOwn(v, 'triggerSources') ? { triggerSources: triggerSourcesOf(v.triggerSources) } : {}),
204
+ ...(Array.isArray(v.triggerSourceProblems) ? { triggerSourceProblems: triggerSourceProblemsOf(v.triggerSourceProblems) } : {}),
205
+ };
206
+ } catch (error) { if (error instanceof Unreadable) return null; throw error; }
207
+ }
208
+ /** The `--file` answer, normalized, or null when unreadable or not about `name` / `path`. */
209
+ export function capabilityFileData(v, { selector, name = selector?.name, path: asked } = {}) {
210
+ try {
211
+ head(v, name);
212
+ if (selector && v.kind !== selector.kind) refuse();
213
+ const out = { capabilityShowApi: CAPABILITY_SHOW_API, name: v.name, kind: v.kind, commit: v.commit, file: file(v.file, { fileAnswer: true }) };
214
+ if (asked !== undefined && out.file.path !== asked) refuse();
215
+ return out;
216
+ } catch (error) { if (error instanceof Unreadable) return null; throw error; }
217
+ }
218
+
219
+ /** A skill file's path relative to the capability root (what `--file` takes): the kernel's, verbatim. */
220
+ export const skillFilePath = (skill, file) => file.path;
221
+ /** The same path relative to its skill's directory (what the navigation shows). */
222
+ export const skillRelativePath = (skill, file) => file.path.slice(skill.path.length + 1);
223
+ /** Every file the answer lists, by its path relative to the capability root (what `--file` may be asked for):
224
+ * the inject (when its path is safe), then each listed skill's files. */
225
+ export function listedFiles(show) {
226
+ const out = new Map();
227
+ if (show?.inject?.path) out.set(show.inject.path, { kind: 'inject', file: show.inject });
228
+ for (const skill of show?.skills || []) for (const f of skill.files || []) out.set(skillFilePath(skill, f), { kind: 'skill', skill, file: f });
229
+ return out;
230
+ }