@awebai/oats 0.69.4 → 0.69.6

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 (74) hide show
  1. package/bin/oats.mjs +141 -364
  2. package/docs/configuration.md +12 -0
  3. package/docs/design/2026-09-26-okf-knowledge-operations.md +2 -0
  4. package/docs/design/2026-10-29-warm-reader.md +261 -0
  5. package/docs/design/README.md +4 -0
  6. package/docs/desktop-cli-api.md +258 -13
  7. package/docs/execution-targets.md +36 -5
  8. package/docs/implementation.md +34 -9
  9. package/docs/integrations.md +2 -2
  10. package/docs/knowledge.md +18 -8
  11. package/docs/named-test-runs.md +4 -0
  12. package/docs/official-catalog.md +5 -5
  13. package/docs/packages.md +14 -14
  14. package/docs/release-notes/v0.69.5.md +146 -0
  15. package/docs/release-notes/v0.69.6.md +165 -0
  16. package/docs/schedules.md +8 -1
  17. package/docs/tui.md +23 -5
  18. package/docs/upgrading.md +20 -5
  19. package/docs/workspaces.md +2 -2
  20. package/lib/agents-root.mjs +51 -0
  21. package/lib/argv.mjs +41 -0
  22. package/lib/automation-api.mjs +7 -0
  23. package/lib/automation-scope.mjs +37 -0
  24. package/lib/automations.mjs +63 -12
  25. package/lib/captured-context.mjs +12 -0
  26. package/lib/compile-cache.mjs +36 -0
  27. package/lib/core.mjs +39 -1348
  28. package/lib/deployment-path.mjs +127 -0
  29. package/lib/deployments.mjs +2 -2
  30. package/lib/drift.mjs +95 -0
  31. package/lib/hot-reads.mjs +137 -0
  32. package/lib/install-stamp.mjs +61 -0
  33. package/lib/instance-address.mjs +21 -0
  34. package/lib/instance-events.mjs +8 -6
  35. package/lib/instance-lifecycle.mjs +4 -16
  36. package/lib/instance-listing.mjs +738 -0
  37. package/lib/instance-resolution.mjs +5 -166
  38. package/lib/kernel-features.mjs +10 -0
  39. package/lib/local-edit.mjs +1 -1
  40. package/lib/local-inputs.mjs +3 -0
  41. package/lib/materialize.mjs +2 -87
  42. package/lib/member-clone.mjs +192 -0
  43. package/lib/package-catalog.mjs +93 -0
  44. package/lib/packages.mjs +4 -24
  45. package/lib/read-call.mjs +143 -0
  46. package/lib/reader.mjs +203 -0
  47. package/lib/remote.mjs +47 -6
  48. package/lib/reserved-launch-env.mjs +20 -0
  49. package/lib/resolved-deployment.mjs +13 -5
  50. package/lib/roster-read.mjs +199 -0
  51. package/lib/schedule.mjs +5 -29
  52. package/lib/semver.mjs +12 -0
  53. package/lib/servers.mjs +10 -12
  54. package/lib/session-end.mjs +3 -2
  55. package/lib/session-input.mjs +35 -11
  56. package/lib/session-inspect.mjs +219 -0
  57. package/lib/soul-listing.mjs +216 -0
  58. package/lib/status-words.mjs +30 -0
  59. package/lib/version.mjs +9 -0
  60. package/lib/workspace-read.mjs +160 -0
  61. package/lib/write-file-atomic.mjs +28 -0
  62. package/package-catalog.json +4 -4
  63. package/package.json +1 -1
  64. package/packages/client/cli-locator.mjs +1 -0
  65. package/packages/client/cli-probe-contract.mjs +4 -2
  66. package/packages/client/deployment-observer.mjs +8 -3
  67. package/packages/client/deployment-panel.mjs +17 -1
  68. package/packages/client/deployment-read-cli.mjs +48 -27
  69. package/packages/client/own-codes.mjs +3 -0
  70. package/packages/client/warm-reader.mjs +241 -0
  71. package/packages/tui/lib/client.mjs +2 -1
  72. package/packages/tui/lib/read.mjs +59 -11
  73. package/packages/tui/lib/store.mjs +7 -3
  74. package/skills/oats-getting-started/SKILL.md +3 -3
@@ -0,0 +1,219 @@
1
+ /** inspectInstanceSession: what a home's tmux session is, read under the home's runtime authority (its
2
+ * recorded launch and receipts, the retirement baseline, the Herdr refusal) and the agent pane's
3
+ * liveness. A leaf (awebai/oats#1630): `oats session inspect` reads it without loading core.mjs, which
4
+ * imports these helpers and re-exports what it exported. */
5
+ import { realPathOrNearest, canonicalHomePath } from "./real-path.mjs";
6
+ import { existsSync, readFileSync, lstatSync } from "node:fs";
7
+ import { isAbsolute, join, resolve, dirname, basename } from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { inspectSessionTarget } from "./session-input.mjs";
10
+ import { liveWaiting } from "./instance-events.mjs";
11
+ import { oatsError, herdrInstanceRemoved } from "./errors.mjs";
12
+
13
+ /** A cleanup descriptor is usable only if it can DRIVE the retry, so it is checked
14
+ * as the strict contract its one producer writes — the rollback above — and to the
15
+ * depth the retry CONSUMES it. Three rounds of review landed on this: validating
16
+ * the outer shape only moved the failure from "unparseable" to "parseable and
17
+ * useless", and every tolerance ("field optional", "array is enough") turned into
18
+ * a retry that resolved nothing, reported no failures, and CLEARED the quarantine
19
+ * — deleting the credential while the external state it was holding survived.
20
+ *
21
+ * Required, because the producer always writes them and the retry needs each one:
22
+ * `version` (the contract), `repo` (resolves capabilities and reruns hooks),
23
+ * `work` + `branch`-when-worktree (the rollback-owned Git steps; an unrecognised
24
+ * mode silently skips them), `capabilityRuntime` (handed to runLifecycleHooks AS
25
+ * the capability set, so it must BE one and must contain every outstanding hook),
26
+ * and `outstanding.hooks` (what the retry has to prove it reran).
27
+ *
28
+ * Anything else reads as ABSENT — no more retryable than a missing marker — so the
29
+ * home fails closed by default and `--force` can clear it. */
30
+ function isPlainObject(v) { return !!v && typeof v === "object" && !Array.isArray(v); }
31
+
32
+ // The stored digests are versioned apart (`digestVersion`, BASELINE_DIGEST_VERSION): this version
33
+ // also gates runtime, directory-home and provider-exclusion authority, so a bump would refuse them all.
34
+ const RETIRE_BASELINE_VERSION = 2;
35
+
36
+ function retirementStateRoot(home) {
37
+ // Independent of the bytes it authenticates, but colocated with the agent's
38
+ // already instance-owned storage rather than the source repository or user
39
+ // config home. Retiring <instances>/<name> never removes this sibling.
40
+ return instancesRetirementRoot(dirname(home));
41
+ }
42
+ /** The retirement state of the homes in the instances directory `instances`. */
43
+ function instancesRetirementRoot(instances) {
44
+ return join(instances, ".oats-retirement");
45
+ }
46
+
47
+ /** A home's identity as a receipt records it: its on-disk spelling, own name included. A home that
48
+ * is a symlink is not followed: its parent's on-disk spelling and its name as given (a home
49
+ * exchanged for a symlink is not the home it points at). */
50
+ function receiptHomeIdentity(home) {
51
+ let st;
52
+ try { st = lstatSync(home); } catch { /* not there: spelled as the nearest existing ancestor */ }
53
+ return st && !st.isSymbolicLink() ? canonicalHomePath(home) : join(canonicalHomePath(dirname(home)), basename(home));
54
+ }
55
+
56
+ /** Whether a receipt's recorded home is this home, whatever spelling either was written in.
57
+ * `current` is the home as the caller resolves it for the comparison. */
58
+ function receiptRecordsHome(baseline, current) {
59
+ return typeof baseline?.home === "string" && receiptHomeIdentity(baseline.home) === current;
60
+ }
61
+
62
+ function retirementBaselineFile(identity) {
63
+ return join(retirementStateRoot(identity), "baselines", `${createHash("sha256").update(identity).digest("hex")}.json`);
64
+ }
65
+
66
+ /** Where a spawn writes a home's receipt: keyed by its canonical identity. */
67
+ export function retirementBaselinePath(home) {
68
+ return retirementBaselineFile(receiptHomeIdentity(home));
69
+ }
70
+
71
+ /** Where a kernel before 0.49.0 wrote it: keyed by the parent's realpath in the spawn's own
72
+ * spelling, which on a case-insensitive filesystem need not be the on-disk one. */
73
+ function legacyRetirementBaselinePath(home) {
74
+ return retirementBaselineFile(join(realPathOrNearest(dirname(home)), basename(home)));
75
+ }
76
+
77
+ /** The receipt every reader uses: the canonical one if it exists, else one an earlier kernel left
78
+ * under this caller's spelling, else the canonical path (absent). Read-only: a receipt found at the
79
+ * legacy key is used where it is, never moved, copied or rewritten elsewhere.
80
+ *
81
+ * Limits. A legacy receipt written under spelling S is found only from S, or from the canonical
82
+ * spelling when that is S: a third spelling of such a home misses it (address the home as
83
+ * `oats status` prints it, the spawn's spelling). Receipts outlive retire, so a reused name can
84
+ * leave an earlier incarnation's receipt behind; the canonical one wins, which is right for every
85
+ * home spawned from 0.49.0 on. It is wrong in one case: two incarnations of the same name, both
86
+ * spawned by a kernel before 0.49.0 under different spellings, the earlier one under the canonical
87
+ * spelling. The later home then reads the earlier one's receipt. Its stale endpoint disagrees with
88
+ * instance.json (E_RUNTIME_AUTHORITY_MISMATCH) unless the later incarnation sits at the same
89
+ * endpoint, where session control already targets the right session. Retire finds the home
90
+ * fingerprint changed and preserves the home, less the stale receipt's disposable roots; a
91
+ * directory-work disagreement is E_WORK_INSPECTION_FAILED; and a start's record rewrites the stale
92
+ * file, as a kernel before 0.49.0 already does when a caller's spelling matches an earlier
93
+ * incarnation's. */
94
+ export function findRetirementBaseline(home) {
95
+ const canonical = retirementBaselinePath(home);
96
+ if (existsSync(canonical)) return canonical;
97
+ const legacy = legacyRetirementBaselinePath(home);
98
+ return legacy !== canonical && existsSync(legacy) ? legacy : canonical;
99
+ }
100
+
101
+ /** Herdr (removed in 0.31.0) is recognised in a home only to refuse: its instance.json records a
102
+ * Herdr session target or `backend: "herdr"`, or its independent receipt records a session target
103
+ * (a tmux receipt never does). Either source is enough. */
104
+ function recordsHerdr(meta, baseline) {
105
+ return (isPlainObject(meta) && (meta.sessionTarget !== undefined || meta.backend === "herdr"))
106
+ || (isPlainObject(baseline?.runtime) && baseline.runtime.sessionTarget !== undefined);
107
+ }
108
+ function readJsonOrUndefined(path) { try { return JSON.parse(readFileSync(path, "utf8")); } catch { return undefined; } }
109
+ /** Refuse any session operation on a home opened in Herdr, from its files as they are (either may be
110
+ * missing or unreadable): before any receipt validation, so the refusal is never an endpoint error. */
111
+ function refuseHerdrHome(home) {
112
+ if (recordsHerdr(readJsonOrUndefined(join(home, "instance.json")), readJsonOrUndefined(findRetirementBaseline(home)))) throw herdrInstanceRemoved(basename(home));
113
+ }
114
+
115
+ function runtimeAuthorityOf(baseline) {
116
+ const runtime = baseline?.runtime;
117
+ if (!isPlainObject(runtime) || typeof runtime.launched !== "boolean") return undefined;
118
+ if (!runtime.launched) return { launched: false };
119
+ if (runtime.sessionTarget !== undefined) return undefined;
120
+ const tmux = runtime.tmux;
121
+ if (!isPlainObject(tmux) || ![tmux.session, tmux.window, tmux.socket].every((v) => typeof v === "string" && v.length > 0)) return undefined;
122
+ return { launched: true, tmux: { session: tmux.session, window: tmux.window, socket: resolve(tmux.socket) } };
123
+ }
124
+
125
+ /** The fields of instance.json's tmux endpoint that differ from the one the independent receipt
126
+ * authorises, as fixed labels in a fixed order: `tmux.session`, `tmux.window`, `tmux.socket`. */
127
+ function tmuxEndpointDifferences(meta, authority) {
128
+ return [
129
+ ...(meta.tmux?.session === authority.tmux?.session ? [] : ["tmux.session"]),
130
+ ...(meta.tmux?.window === authority.tmux?.window ? [] : ["tmux.window"]),
131
+ ...(resolve(meta.tmux?.socket || ".") === authority.tmux?.socket ? [] : ["tmux.socket"]),
132
+ ];
133
+ }
134
+ /** instance.json's tmux endpoint is the one the independent receipt authorises. */
135
+ function tmuxEndpointAgrees(meta, authority) { return tmuxEndpointDifferences(meta, authority).length === 0; }
136
+
137
+ /** Whether a blocked or incomplete launch prompt explains metadata's `launched: false` beside a
138
+ * launched receipt. */
139
+ function promptRetained(meta, authority) {
140
+ return authority.launched === true && meta.launched === false && ["blocked", "incomplete"].includes(meta.launchPrompts?.status);
141
+ }
142
+ /** A blocked prompt is a retained runtime, not evidence that no process exists.
143
+ * The independent launched receipt and exact endpoint agreement remain mandatory. */
144
+ function launchStateAgrees(meta, authority) {
145
+ return meta.launched === authority.launched || (promptRetained(meta, authority) && tmuxEndpointAgrees(meta, authority));
146
+ }
147
+
148
+ /** The refusal for instance.json that disagrees with the independent receipt. `details.fields` names
149
+ * what differs, from a fixed vocabulary in a fixed order: `launched` (unless a blocked or incomplete
150
+ * launch prompt explains metadata's `launched: false`), then, for a launched receipt, each differing
151
+ * tmux endpoint field. Labels only: never a path, a value or the receipt. Callers throw it only once
152
+ * their own comparison has refused, so these labels diagnose a refusal and never decide one. */
153
+ function authorityMismatch(message, meta, authority) {
154
+ const fields = [
155
+ ...(meta.launched === authority.launched || promptRetained(meta, authority) ? [] : ["launched"]),
156
+ ...(authority.launched ? tmuxEndpointDifferences(meta, authority) : []),
157
+ ];
158
+ return Object.assign(oatsError("E_RUNTIME_AUTHORITY_MISMATCH", message), { details: { fields } });
159
+ }
160
+
161
+ /** The refusal for a home whose session receipt is at neither key its path gives (findRetirementBaseline):
162
+ * the canonical one, and the one an earlier kernel used for this spelling when that differs. The
163
+ * receipt is keyed by the home's path, so a moved deployment looks elsewhere. */
164
+ function missingSessionReceipt(home) {
165
+ const canonical = retirementBaselinePath(home), legacy = legacyRetirementBaselinePath(home);
166
+ const where = legacy === canonical ? canonical : `${canonical} (nor at ${legacy}, where a kernel before 0.49.0 kept it for this spelling)`;
167
+ return oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `no session receipt for ${home} at ${where}. First address the home exactly as \`oats status\` prints it (a deployment directory moved since spawn looks for the receipt elsewhere, and so does a letter-case spelling other than the spawn's, for a home spawned before 0.49.0). Otherwise the home was copied, the .oats-retirement beside it was removed, or its creation did not finish: stop its session yourself if one runs, then \`oats retire ${basename(home)} --plan\` and \`oats retire ${basename(home)}\` (work is preserved), and respawn.`);
168
+ }
169
+
170
+ /** Why a file could not be read or parsed, in the system's or the parser's words, without the path
171
+ * the sentence already names: `EACCES: permission denied`; a missing file is "it is missing". */
172
+ const unreadableBecause = (e) => e?.code === "ENOENT" ? "it is missing" : String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, "");
173
+
174
+ /** Session control uses the independent endpoint receipt. The receipt and the record are read
175
+ * apart, so that a failure names the file that failed (#1092): one `catch` over both cannot know. */
176
+ function instanceSessionTarget(home, { absentMeta } = {}) {
177
+ if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session needs an absolute instance home");
178
+ home = realPathOrNearest(home);
179
+ refuseHerdrHome(home);
180
+ const receiptPath = findRetirementBaseline(home), recordPath = join(home, "instance.json");
181
+ let baseline, meta;
182
+ try { baseline = JSON.parse(readFileSync(receiptPath, "utf8")); } catch (e) {
183
+ if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home);
184
+ throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home} at ${receiptPath}: ${unreadableBecause(e)}`);
185
+ }
186
+ try { meta = JSON.parse(readFileSync(recordPath, "utf8")); }
187
+ catch (e) {
188
+ // Upgrade may be between the two metadata renames. Its durable journal
189
+ // supplies only the missing record; the independent endpoint still decides.
190
+ if (e.code === "ENOENT" && isPlainObject(absentMeta)) meta = absentMeta;
191
+ else throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: ${unreadableBecause(e)}`);
192
+ }
193
+ // A record that is JSON and no object gives no endpoint to compare the receipt with.
194
+ if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: it holds no JSON object`);
195
+ const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
196
+ if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
197
+ if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw authorityMismatch("instance metadata disagrees with independent session receipt", meta, authority);
198
+ return { home, target: authority.launched ? { backend: "tmux", ...authority.tmux } : undefined };
199
+ }
200
+
201
+ /** `io` (`{ exec }`) is the tmux and process-table seam inspectSessionTarget takes. */
202
+ export function inspectInstanceSession(home, { io, absentMeta } = {}) {
203
+ if (typeof home === "string" && isAbsolute(home) && !existsSync(home)) return { home: realPathOrNearest(home), backend: null, present: false, state: "stopped", running: false, waitingOnYou: null };
204
+ const s = instanceSessionTarget(home, { absentMeta });
205
+ if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", running: false, waitingOnYou: null };
206
+ let observed;
207
+ try { observed = inspectSessionTarget(s.target, io, { includeSize: true }); }
208
+ // The tmux failure stays the cause: sessionServerGone judges it.
209
+ catch (e) { throw Object.assign(oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`), { cause: e }); }
210
+ // Features session-inspect-running and waiting-on-you: beside `state`, whose enum is unchanged.
211
+ // `running` is status's own liveness predicate over this observation, never a second reading.
212
+ const running = harnessRunning(observed);
213
+ return { home: s.home, ...observed, running, waitingOnYou: running ? liveWaiting(s.home) : null };
214
+ }
215
+ /** Whether an observed session runs a harness: present, and neither a
216
+ * fallback shell nor a dead pane. Only such a session can be waiting on a human. */
217
+ function harnessRunning(observed) { return observed?.present === true && observed.state !== "shell" && observed.state !== "stopped"; }
218
+
219
+ export { RETIRE_BASELINE_VERSION, authorityMismatch, harnessRunning, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, runtimeAuthorityOf, tmuxEndpointAgrees };
@@ -0,0 +1,216 @@
1
+ /** The souls under an agents root and the homes of an instance name among them: listAgents reads each
2
+ * soul.yaml (the flat reader, and the YAML parser for a workspace-model soul), findInstanceHomes finds
3
+ * the homes contained in them. A leaf (awebai/oats#1630): `oats instance events` and `instance waiting`
4
+ * resolve a home without loading core.mjs, which re-exports these. */
5
+ import { existsSync, realpathSync, readdirSync, readFileSync } from "node:fs";
6
+ import { join, dirname, basename, resolve, isAbsolute } from "node:path";
7
+ import { oatsError } from "./errors.mjs";
8
+ import { parseConfigData } from "./config-data.mjs";
9
+
10
+ export const RESERVED = new Set(["bin"]);
11
+
12
+ /** The agent dirs directly under an agents root that hold no soul: capability-defined
13
+ * agents (their soul is read-only in a module; the dir holds only instances/). */
14
+ function capabilityAgentDirs(root) {
15
+ let entries; try { entries = readdirSync(root, { withFileTypes: true }); } catch { return []; }
16
+ return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".") && !RESERVED.has(e.name) && !existsSync(join(root, e.name, "soul", "soul.yaml")))
17
+ .map((e) => ({ name: e.name, dir: join(root, e.name) }));
18
+ }
19
+
20
+ // ---------- yaml-ish ----------
21
+ /** `__proto__` is never data in a plain-object mapping: assigning it REWRITES
22
+ * the parsed object's prototype, so the entry vanishes from `Object.keys` —
23
+ * past every key validator — while still answering property reads (a document
24
+ * could smuggle an unvalidated `name:` or `capabilities:` that way). No OATS
25
+ * document has a use for the key, so the readers refuse it rather than parse
26
+ * it: fail closed, never silently drop.
27
+ *
28
+ * THE single refusal, shared by the readers and by every WRITER that assigns an
29
+ * operator-supplied key into a config map — a write path that let the inherited
30
+ * setter swallow the entry and then reported success would be the same defect
31
+ * with a friendlier face. The readers parse strings and cannot name the
32
+ * document, so `where` is filled in by whoever holds the file
33
+ * (`withConfigFile`); the raw message therefore says "mapping key", not
34
+ * "oats-config key" — soul.yaml and skill frontmatter go through here too. */
35
+ export function assertSafeConfigKey(key, where) {
36
+ if (key === "__proto__") {
37
+ throw oatsError("unsafe-config-key", `unsupported mapping key "__proto__"${where ? ` in ${where}` : ""} — "__proto__" cannot be a mapping key in an OATS document (it rewrites the parsed object's prototype instead of becoming data)`, where ? [{ file: where }] : undefined);
38
+ }
39
+ return key;
40
+ }
41
+ /** Run a reader that may raise the typed key refusal and re-raise it naming the
42
+ * FILE. Every caller with a path in hand wraps its read — the readers parse
43
+ * strings and cannot name a document — so the CLI boundary can print one line
44
+ * the operator can act on.
45
+ *
46
+ * The insertion uses a REPLACER FUNCTION, never a replacement string: `$&`,
47
+ * `$'`, `` $` `` and `$1` are substitution syntax in `String.replace`, so a
48
+ * config path containing one of them (`/tmp/$&/oats-config.yaml` — legal on every
49
+ * POSIX filesystem) was expanded against the match and the reported filename
50
+ * came out corrupted. A function receives the path as data. */
51
+ export function withConfigFile(file, read) {
52
+ try { return read(); }
53
+ catch (e) {
54
+ if (e?.code !== "unsafe-config-key" || e.provenance) throw e;
55
+ throw oatsError(e.code, e.message.replace(" — ", () => ` in ${file} — `), [{ file }]);
56
+ }
57
+ }
58
+
59
+ const yamlKey = (key) => assertSafeConfigKey(key);
60
+ export function parseYamlFlat(text) {
61
+ const o = {};
62
+ for (const line of text.split("\n")) {
63
+ const m = line.match(/^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*?)\s*(#.*)?$/);
64
+ if (m) o[yamlKey(m[1])] = m[2].replace(/^["']|["']$/g, "");
65
+ }
66
+ return o;
67
+ }
68
+
69
+ /** The `_`-prefixed namespace on a parsed document belongs to the KERNEL: `_dir`,
70
+ * `_origin`, `_package`, `_capabilityLock`, `_soulDir` … are the
71
+ * kernel's own statements ABOUT an artifact — where it was found, which lock row
72
+ * governs it, whether it is trusted. They are internal annotations, so they must
73
+ * be unforgeable: an artifact that can write them into its own on-disk document
74
+ * asserts its own provenance. That was reachable — a capability whose `oats.json`
75
+ * declared `"_capabilityLock": {...}` spread straight through `{ ...m }` and
76
+ * silenced doctor's "in installed/ but has no lock entry" warning for an
77
+ * artifact nothing locks.
78
+ *
79
+ * So every parsed document that later RECEIVES annotations is stripped first.
80
+ * Stripping (rather than refusing) keeps the reader tolerant of documents that
81
+ * merely carry an unknown underscore key, while making the namespace
82
+ * unreachable from disk.
83
+ *
84
+ * `__proto__` starts with `_`, so a JSON document's own `__proto__` key is
85
+ * dropped here too rather than re-assigned through the inherited setter. */
86
+ /** A flat soul.yaml names its harness `harness:` (0.27.0) or, as released
87
+ * souls and capability-defined agents do (oats.aweb 1.13.1), `runtime:` —
88
+ * set both, read either until no released package writes `runtime`. Both,
89
+ * disagreeing, is refused. Returns the soul with `harness` only. */
90
+ export function soulHarnessField(soul, file) {
91
+ if (!soul || !Object.hasOwn(soul, "runtime")) return soul;
92
+ const { runtime, ...rest } = soul;
93
+ if (Object.hasOwn(soul, "harness") && soul.harness !== runtime) {
94
+ throw oatsError("E_BAD_MANIFEST", `${file} declares harness: ${soul.harness} and runtime: ${runtime}; \`runtime\` is the pre-0.27 name of \`harness\` — keep one`, { file, harness: soul.harness, runtime });
95
+ }
96
+ return { ...rest, harness: Object.hasOwn(soul, "harness") ? soul.harness : runtime };
97
+ }
98
+ export function stripInternalAnnotations(parsed) {
99
+ const out = {};
100
+ for (const key of Object.keys(parsed)) if (!key.startsWith("_")) out[key] = parsed[key];
101
+ return out;
102
+ }
103
+
104
+ // ---------- agents ----------
105
+ function soulOf(agentDir) { return join(agentDir, "soul"); }
106
+ function readSoul(agentDir, soulDir = soulOf(agentDir)) {
107
+ const p = join(soulDir, "soul.yaml");
108
+ if (!existsSync(p)) return undefined;
109
+ // Stripped before annotation: `_soulDir` is consumed as "the read-only soul
110
+ // inside a package" (spawn, roster) and `_dir` as the agent home, so a
111
+ // soul.yaml that could declare either would be describing itself to the
112
+ // kernel. See stripInternalAnnotations.
113
+ const text = readFileSync(p, "utf8");
114
+ const flat = withConfigFile(p, () => parseYamlFlat(text));
115
+ // A workspace-model soul.yaml (schemaVersion 2) nests maps (capabilities,
116
+ // knowledge …): the flat reader would turn them into "" and the version into a
117
+ // string. It is read with the real parser; a classic soul keeps the flat reader.
118
+ let parsed = flat;
119
+ if (flat.schemaVersion === "2") {
120
+ try { const v = parseConfigData(text, { format: "yaml" }).value; if (v && typeof v === "object" && !Array.isArray(v)) parsed = v; }
121
+ catch { /* unreadable as YAML: the flat view is what the classic readers saw */ }
122
+ }
123
+ const soul = soulHarnessField(stripInternalAnnotations(parsed), p);
124
+ soul._dir = agentDir;
125
+ // A package soul homes at <package>--<soul> (lib/workspace.mjs packageSoulAgentName): that
126
+ // directory, not the soul.yaml name, is its agent name, so its instances never share a
127
+ // member soul's name or roster row.
128
+ soul.name = basename(agentDir).includes("--") ? basename(agentDir) : (soul.name || basename(agentDir));
129
+ return soul;
130
+ }
131
+
132
+ export function listAgents(root) {
133
+ const agents = [];
134
+ const scan = (base, kind) => {
135
+ if (!existsSync(base)) return;
136
+ for (const e of readdirSync(base, { withFileTypes: true })) {
137
+ if (!e.isDirectory() || (kind === "persistent" && RESERVED.has(e.name))) continue;
138
+ const soul = readSoul(join(base, e.name));
139
+ if (soul) { soul.kind = soul.kind || kind; agents.push(soul); }
140
+ }
141
+ };
142
+ scan(root, "persistent");
143
+ return agents;
144
+ }
145
+
146
+ // Locate an instance home under an agents root, including capability-defined
147
+ // agents homing under <root>/<name>/ WITHOUT a soul there (listAgents cannot
148
+ // see those). Shared by retireInstance and `oats spawn --parent`.
149
+ // SECURITY: `name` is caller-controlled (CLI args, API bodies). It must be a
150
+ // plain instance name — reject path separators/dots up front, and verify the
151
+ // hit resolves to an IMMEDIATE child of an instances/ dir (realpath
152
+ // containment), or `oats retire ../../dev/soul` would existence-match and
153
+ // recursively delete a canonical soul.
154
+ const INSTANCE_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
155
+
156
+ /** ALL homes matching an instance name under one agents root. Spawn keeps names
157
+ * unique across the deployment since 0.26.0, but homes from earlier kernels (a
158
+ * generated-name collision like `dev --purpose foo-1` vs agent `dev-foo`) and
159
+ * direct kernel callers passing `instance` can still share one.
160
+ * Ambiguity-sensitive callers must use this, not first-match. Same
161
+ * containment/charset guarantees as findInstanceHome. */
162
+ export function findInstanceHomes(root, name) {
163
+ if (typeof name !== "string" || !INSTANCE_NAME_RE.test(name)) return [];
164
+ const contained = (agentDir) => {
165
+ const home = join(agentDir, "instances", name);
166
+ if (!existsSync(home)) return undefined;
167
+ try {
168
+ const real = realpathSync(home);
169
+ if (dirname(real) !== realpathSync(join(agentDir, "instances")) || basename(real) !== name) return undefined;
170
+ } catch { return undefined; }
171
+ return home;
172
+ };
173
+ const out = [];
174
+ const seen = new Set();
175
+ const push = (agent, home) => {
176
+ // Dedupe by canonical home so all-matches callers never see double hits.
177
+ let key; try { key = realpathSync(home); } catch { key = resolve(home); }
178
+ if (seen.has(key)) return;
179
+ seen.add(key);
180
+ out.push({ agent, home });
181
+ };
182
+ for (const a of listAgents(root)) {
183
+ const home = contained(a._dir);
184
+ if (home) push(a, home);
185
+ }
186
+ for (const { name: agentName, dir } of capabilityAgentDirs(root)) {
187
+ const home = contained(dir);
188
+ if (home) push({ name: agentName, kind: "capability", _dir: dir }, home);
189
+ }
190
+ return out;
191
+ }
192
+
193
+ /** The working directory as the shell names it: $PWD when it is the process's own directory, else
194
+ * the physical cwd. A path through a symlink (an attached instance's work/, which links into its
195
+ * owner's tree) then still belongs to the instance it was entered from. */
196
+ export function logicalCwd() {
197
+ const cwd = process.cwd(), pwd = process.env.PWD;
198
+ try { if (pwd && isAbsolute(pwd) && realpathSync(pwd) === realpathSync(cwd)) return pwd; } catch { /* a stale PWD */ }
199
+ return cwd;
200
+ }
201
+ /** The instance home enclosing `dir` (itself or its nearest such ancestor): a directory laid out
202
+ * as <agents-root>/<agent>/instances/<name> whose instance.json records `instance: <name>`.
203
+ * For a process whose harness strips the session env (Codex's shared app-server daemon runs
204
+ * tool commands outside the session); the caller validates the home as it does one named by
205
+ * OATS_INSTANCE_HOME. undefined when no such directory encloses `dir`. */
206
+ export function enclosingInstanceHome(dir) {
207
+ for (let d = resolve(dir); ; d = dirname(d)) {
208
+ if (basename(dirname(d)) === "instances" && INSTANCE_NAME_RE.test(basename(d))) {
209
+ try { if (JSON.parse(readFileSync(join(d, "instance.json"), "utf8"))?.instance === basename(d)) return d; }
210
+ catch { /* no readable instance.json: not a home */ }
211
+ }
212
+ if (dirname(d) === d) return undefined;
213
+ }
214
+ }
215
+
216
+ export { INSTANCE_NAME_RE, capabilityAgentDirs, readSoul, soulOf, yamlKey };
@@ -0,0 +1,30 @@
1
+ /** The word `oats status`, `oats status --server <id>` and `oats server roster` print for an instance
2
+ * row in text, and the way back they print under a row whose session was lost (#1617, #1628). Rows
3
+ * in, strings out: the row is a `status --json` instance row, this kernel's or a host's (the roster
4
+ * relays its `sessionEnd`), read as it is. A host on a kernel before `sessionEnd` (feature
5
+ * session-resume) sends none, and its rows read `idle` as before. The JSON is never changed here.
6
+ * Dependency-free. */
7
+ import { terminalText } from "./refused-text.mjs";
8
+ import { shellWord } from "./shell-word.mjs";
9
+ import { SESSION_END } from "./session-resume-contract.mjs";
10
+
11
+ const isLost = (i) => i.running === false && i.sessionEnd === SESSION_END.LOST;
12
+
13
+ /** `running` true is RUNNING; false is LOST when the session was lost (`sessionEnd: "lost"`, the
14
+ * judgement the resume sweep acts on), else idle (stopped, exited, never launched, or not said);
15
+ * null (a server that cannot be read, a Herdr home) is unknown, never idle. */
16
+ export const livenessWord = (i) => i.running === true ? "RUNNING" : i.running === false ? (isLost(i) ? "LOST" : "idle") : "unknown";
17
+
18
+ /** A row's word: a retire under way wins over its liveness. */
19
+ export const statusWord = (i) => i.retirePending ? "RETIRING" : livenessWord(i);
20
+
21
+ /** The one line under a LOST row that says how to bring it back, or null for any other row. Local:
22
+ * the resume by hand, or the next sweep. `host` (a `--server` or roster row): both refuse `--server`
23
+ * (E_BAD_ARGS), so the line says to run them on that host. */
24
+ export function lostLine(i, { host } = {}) {
25
+ if (i.retirePending || !isLost(i)) return null;
26
+ const start = typeof i.home === "string" && i.home ? `oats session start --resume --home ${shellWord(i.home)}` : null;
27
+ if (host !== undefined) return terminalText(`lost: on ${host}, run ${start ? `${start} there, or its next oats session resume` : "oats session resume there"}`);
28
+ const sweep = "the next oats session resume (run when OATS Desktop or oats tui opens)";
29
+ return terminalText(start ? `lost: ${start} brings it back; so does ${sweep} if it can vouch for the loss` : `lost: ${sweep} brings it back if it can vouch for the loss`);
30
+ }
@@ -0,0 +1,9 @@
1
+ /** The kernel's package root and version, read from package.json once at load. A leaf (awebai/oats#1630):
2
+ * `oats version` reads it without loading core.mjs, which re-exports both. Node built-ins only. */
3
+ import { readFileSync } from "node:fs";
4
+ import { join, dirname } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ /** Package root (this file lives in <pkg>/lib/). */
8
+ export const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
9
+ export const OATS_VERSION = JSON.parse(readFileSync(join(PKG_ROOT, "package.json"), "utf8")).version;
@@ -0,0 +1,160 @@
1
+ /** lib/workspace-read.mjs — `oats workspace status`, the workspace read (awebai/oats#1630): the
2
+ * membership table, the locked and declared packages, the automations placed on this host, and the
3
+ * desktop facts. One implementation behind the CLI (bin/oats.mjs workspaceCmd) and a process that answers
4
+ * it many times (lib/read-call.mjs, whose header describes the context and the answer).
5
+ * `workspaceStatusAnswer(ctx)` is the `--json` answer, an envelope; `workspaceStatusView(ctx)` the data
6
+ * bin's text renderer reads. Beside them, the rows `oats sync` reports too. A leaf a hot read loads
7
+ * (lib/hot-reads.mjs): never core.mjs. Kernel-private, not exported from `./core`. */
8
+ import { dirname, join } from "node:path";
9
+ import { scopeAutomations } from "./automation-scope.mjs";
10
+ import { GH_LOGIN_DISPLAY_TIMEOUT_MS, ghLoginParts, staleTrust, trustRemedy } from "./automations.mjs";
11
+ import { LAYERS, officialCapabilityAliases, officialCatalogFile, officialPackageCatalog } from "./package-catalog.mjs";
12
+ import { classifyPackageValue, LOCK_FILE, readLock } from "./packages.mjs";
13
+ import { answerWarnings, refuse, runRead } from "./read-call.mjs";
14
+ import { browseUrl, factObservation } from "./remote.mjs";
15
+ import { loadLocal } from "./workspace.mjs";
16
+
17
+ /** `oats workspace status --json`: → `{ exit, answer, stderr }` (lib/read-call.mjs), `answer` the envelope. */
18
+ export function workspaceStatusAnswer(ctx) {
19
+ return runRead(ctx, async (call) => {
20
+ const { result } = await workspaceStatusFacts(call, ctx);
21
+ return { answer: { schemaVersion: 1, ok: true, result: call.withObservation(result), ...answerWarnings() } };
22
+ });
23
+ }
24
+
25
+ /** `oats workspace status` in text mode: → `{ exit, answer, view, stderr }`, `view` `{ result, discovery,
26
+ * localPath }` when it did not refuse, `answer` the failure envelope when it did. */
27
+ export function workspaceStatusView(ctx) {
28
+ return runRead(ctx, async (call) => ({ view: await workspaceStatusFacts(call, ctx) }));
29
+ }
30
+
31
+ /** The facts of `oats workspace status` (contract §6) at the deployment `dir` names. */
32
+ async function workspaceStatusFacts(call, { dir }) {
33
+ let found;
34
+ try { found = loadLocal(dir); }
35
+ catch (e) { refuse(e.code || "E_LOCAL_MISSING", e.message, e.details); }
36
+ // `remotes`: each member clone's remotes, asked of git once for the whole read (lib/member-clone.mjs).
37
+ const ctx = { dir, localPath: found.path, local: found.local, deploymentDir: dirname(found.path), remoteOptions: call.remoteOptions(), remotes: new Map() };
38
+ // The standalone case (decisions 10/25) is a discovery too: the repo's own view
39
+ // plus the kernel's oats.core default — discoverOrStandalone decides.
40
+ let discovery;
41
+ try { const { discoverOrStandalone } = await import("./member-clone.mjs"); discovery = await discoverOrStandalone(ctx.local, { deployment: ctx.deploymentDir, remoteOptions: ctx.remoteOptions }); }
42
+ catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) refuse(e.code, e.message, e.details ?? e.provenance); throw e; }
43
+ let lock;
44
+ try { lock = readLock(ctx.deploymentDir); } catch (e) { refuse(e.code || "E_LOCK_SCHEMA", e.message, e.details); }
45
+ const members = memberRows(discovery);
46
+ const packages = packageRows(lock);
47
+ // Standalone (decision 10): there is no workspace file — the declared packages are the
48
+ // kernel's own default (decision 25) and there are no teams.
49
+ const standalone = discovery.standalone === true;
50
+ const declared = Object.keys(standalone ? standalonePackages(catalogForStatus()).packages : (discovery.workspace?.packages || {})).sort();
51
+ const locked = new Set(packages.map((p) => p.id));
52
+ const unsynced = declared.filter((id) => !locked.has(id));
53
+ const stale = packages.filter((p) => !declared.includes(p.id)).map((p) => p.id);
54
+ const result = { workspaceStatusApi: 1, standalone: standalone || undefined, workspace: { name: workspaceName(discovery), key: discovery.key, url: discovery.url, commit: discovery.commit, observedAt: discovery.observedAt, local: ctx.localPath, teams: sharedTeamRows(discovery) }, members, packages, declaredPackages: declared, unsynced, stale, external: (discovery.external || []).map((e) => ({ source: e.source, soul: e.soul.name })), problems: discovery.problems, warnings: [...(discovery.warnings ?? [])] };
55
+ // Workspace automations (0.29.0), from the snapshot `oats sync` took, placed on this host.
56
+ // A display: under --max-age the placement may reuse a recent gh login, as the read reuses heads, and a hung gh
57
+ // costs it GH_LOGIN_DISPLAY_TIMEOUT_MS. An act that places or fires an automation always asks gh live. Without
58
+ // --max-age the session reuses nothing (maxAge 0), but the lookup still records a login and, failing, ends the
59
+ // reuse of the one before it, as every live display does.
60
+ const lookup = {
61
+ timeoutMs: GH_LOGIN_DISPLAY_TIMEOUT_MS,
62
+ observe: (ghHost) => { const parts = ghLoginParts(ghHost); return parts ? factObservation(ctx.remoteOptions, "gh-login", parts) : null; },
63
+ };
64
+ const actx = scopeAutomations(ctx.deploymentDir, { remotes: ctx.remotes, lookup });
65
+ result.automations = { host: actx.host.name, snapshot: actx.snapshot ? { takenAt: actx.snapshot.takenAt, problems: actx.snapshot.problems.length } : null, rows: [...actx.triggers, ...actx.schedules].map((a) => ({ kind: a.kind, id: a.id, runsOn: a.runsOn, owner: a.owner, runsHere: a.placement.runsHere, reason: a.placement.reason, enabledHere: a.placement.enabledHere, origin: a.origin, ...(a.invalid ? { invalid: a.invalid } : {}) })) };
66
+ // Automation trust (0.30): a workspace automation placed here but not trusted, and a trust entry
67
+ // that names none, are warnings the operator acts on in oats-local.yaml.
68
+ for (const a of [...actx.triggers, ...actx.schedules].filter((x) => x.placement.reason === "untrusted")) {
69
+ result.warnings.push({ code: "automation-untrusted", kind: a.kind, id: a.id, message: `${a.kind} ${a.id} is declared for this host (${a.runsOn}, as ${a.owner}) but not trusted here, so it does not run`, remedy: trustRemedy(a.id) });
70
+ }
71
+ for (const entry of staleTrust(actx.host, [...actx.triggers, ...actx.schedules])) {
72
+ result.warnings.push({ code: "automation-trust-stale", entry, message: `oats-local.yaml automations.trust names ${entry}, which is no workspace trigger or schedule${actx.snapshot ? "" : " (no automations snapshot yet: run oats sync)"}; its member may not have synced yet` });
73
+ }
74
+ await desktopFacts(result, discovery, lock, ctx);
75
+ return { result, discovery, localPath: ctx.localPath };
76
+ }
77
+
78
+ /** The official catalog's package map (package-catalog.json; OATS_PACKAGE_CATALOG overrides). */
79
+ function catalogForStatus() {
80
+ try { return officialPackageCatalog(); }
81
+ catch (e) { refuse(e.code || "E_PACKAGE_MISSING", e.message); }
82
+ }
83
+
84
+ /** The committed (shared) teams as `workspace status` reports them: rows in label order (team model v2). */
85
+ function sharedTeamRows(discovery) {
86
+ const teams = discovery.standalone === true ? {} : discovery.workspace?.teams || {};
87
+ return Object.keys(teams).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).map((label) => ({ label, team: typeof teams[label]?.team === "string" ? teams[label].team : null, description: typeof teams[label]?.description === "string" ? teams[label].description : null }));
88
+ }
89
+
90
+ /** `oats workspace status` facts (feature desktop-facts): the workspace defaults as rows; this
91
+ * computer (member clones and the rule that found each, disabled souls, the lock); file locations with
92
+ * browsable urls; each catalog package's newer version, when the official catalog has one. */
93
+ async function desktopFacts(result, discovery, lock, ctx) {
94
+ const { memberCloneOf } = await import("./member-clone.mjs");
95
+ const defaults = discovery.standalone === true ? {} : (discovery.workspace?.defaults ?? {});
96
+ const rows = (entries) => Object.entries(entries && typeof entries === "object" ? entries : {}).map(([name, v]) => ({ name, from: v === "off" ? null : v?.from ?? null, off: v === "off" })).sort((a, b) => (a.name < b.name ? -1 : 1));
97
+ const slot = (d) => (d && typeof d === "object" ? Object.entries(d).map(([name, v]) => ({ name, from: v?.from ?? null }))[0] ?? null : d ?? null);
98
+ result.defaults = {
99
+ slots: Object.fromEntries(LAYERS.map((l) => [l, slot(defaults[l])])),
100
+ capabilities: rows(defaults.capabilities),
101
+ };
102
+ result.workspace.file = discovery.standalone === true ? null : { path: "oats-workspace.yaml", url: browseUrl(discovery.key, discovery.commit, "oats-workspace.yaml") };
103
+ for (const m of result.members) Object.assign(m, { url: browseUrl(m.key, m.commit), membershipFile: { path: "oats-membership.yaml", url: browseUrl(m.key, m.commit, "oats-membership.yaml") } });
104
+ result.clones = result.members.map((m) => {
105
+ try { return { key: m.key, name: m.name, ...memberCloneOf(ctx.deploymentDir, ctx.local, m.key, { remotes: ctx.remotes }) }; }
106
+ catch (e) { if (e?.code === "E_CLONE_MISMATCH") return { key: m.key, name: m.name, path: null, rule: null, problem: { code: e.code, message: e.message } }; throw e; }
107
+ });
108
+ result.disabledSouls = [...(Array.isArray(ctx.local?.souls?.disabled) ? ctx.local.souls.disabled : [])];
109
+ result.lock = { path: join(ctx.deploymentDir, LOCK_FILE), lockfileVersion: lock.lockfileVersion ?? null };
110
+ const { compareSemver } = await import("./semver.mjs");
111
+ let catalog = null; try { catalog = officialPackageCatalog(); } catch { catalog = null; }
112
+ const cat = catalog && typeof catalog === "object" ? (catalog.packages && typeof catalog.packages === "object" && !("url" in catalog.packages) ? catalog.packages : catalog) : {};
113
+ for (const p of result.packages) {
114
+ const ref = p.source === `catalog:${p.id}` ? cat[p.id]?.ref : undefined;
115
+ const tag = standaloneCatalogVersion(ref);
116
+ const version = tag ? tag.replace(/^v/, "") : null;
117
+ p.latest = version && typeof p.version === "string" && compareSemver(version, p.version) > 0 ? { version, ref } : null;
118
+ }
119
+ }
120
+
121
+ /** The package requests of a standalone view: the catalog's own pin of the package
122
+ * providing oats.core (decision 25) — nothing else, since the version list lives in
123
+ * the workspace file we cannot read. The request is written as resolvePackages
124
+ * expects a CATALOG entry: the bare version (`v1.1.3`), never the catalog's raw ref
125
+ * (`oats-framework/v1.1.3` is a tag PATH the one grammar refuses); parsePackageRequest
126
+ * recomposes the tag from the catalog's own convention.
127
+ * → { packages: { <id>: <version> }, problems: [ { code: "E_PACKAGE_MISSING", … } ] } */
128
+ export function standalonePackages(catalog) {
129
+ let id = "oats.framework";
130
+ const file = officialCatalogFile();
131
+ try { const alias = officialCapabilityAliases()["oats.core"]; id = (typeof alias === "string" ? alias : alias?.package) ?? id; } catch { /* the catalog is diagnosed below */ }
132
+ const version = standaloneCatalogVersion(catalog?.[id]?.ref);
133
+ if (version) return { packages: { [id]: version }, problems: [] };
134
+ const why = catalog?.[id] ? `its ref ${JSON.stringify(catalog[id].ref)} carries no version` : `it has no entry ${JSON.stringify(id)}`;
135
+ return { packages: {}, problems: [{ code: "E_PACKAGE_MISSING", id, reason: "no-catalog", catalog: file, path: `/packages/${id}`, message: `the catalog has no package providing oats.core (OATS_PACKAGE_CATALOG=${file}): ${why}; standalone spawns will be refused until it does` }] };
136
+ }
137
+ /** The bare version of a catalog ref: its LAST path segment when that is a version
138
+ * (`v1.1.3` → `v1.1.3`; `oats-framework/v1.1.3` → `v1.1.3`; `main` → null). */
139
+ export function standaloneCatalogVersion(ref) {
140
+ if (typeof ref !== "string" || !ref.trim()) return null;
141
+ const tail = ref.trim().split("/").filter(Boolean).pop() ?? "";
142
+ return classifyPackageValue(tail).kind === "catalog" ? tail : null;
143
+ }
144
+
145
+ /** Display name of a discovery: the workspace's name, or the standalone label (decision 10). */
146
+ export const workspaceName = (discovery) => discovery.workspace?.name ?? `standalone:${memberLabel(discovery.key)}`;
147
+ export const memberLabel = (key) => String(key).split("/").filter(Boolean).pop()?.replace(/\.git$/, "") || String(key);
148
+
149
+ /** Membership rows for `sync` / `workspace status`. */
150
+ export function memberRows(discovery) {
151
+ return discovery.members.map((m) => ({
152
+ key: m.key, name: memberLabel(m.key), commit: m.commit ?? null, confirmed: m.confirmed, status: m.confirmed ? "confirmed" : m.reason, detail: m.detail ?? null,
153
+ souls: m.souls.map((s) => s.name), capabilities: m.capabilities.map((c) => c.name), publishes: m.publishes ?? null,
154
+ }));
155
+ }
156
+
157
+ /** Package rows for `sync` / `workspace status` from the lock. */
158
+ export function packageRows(lock) {
159
+ return Object.entries(lock.packages).map(([id, p]) => ({ id, version: p.version, source: p.source, commit: p.commit, integrity: p.integrity, capabilities: p.capabilities, souls: (p.souls ?? []).map((x) => x.name) }));
160
+ }