@awebai/oats 0.69.5 → 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 (48) hide show
  1. package/bin/oats.mjs +78 -320
  2. package/docs/design/2026-09-26-okf-knowledge-operations.md +2 -0
  3. package/docs/design/2026-10-29-warm-reader.md +261 -0
  4. package/docs/design/README.md +4 -0
  5. package/docs/desktop-cli-api.md +250 -12
  6. package/docs/execution-targets.md +11 -2
  7. package/docs/implementation.md +26 -8
  8. package/docs/integrations.md +1 -1
  9. package/docs/knowledge.md +14 -7
  10. package/docs/named-test-runs.md +4 -0
  11. package/docs/official-catalog.md +3 -3
  12. package/docs/packages.md +12 -12
  13. package/docs/release-notes/v0.69.6.md +165 -0
  14. package/docs/schedules.md +8 -1
  15. package/docs/tui.md +21 -4
  16. package/docs/upgrading.md +9 -5
  17. package/docs/workspaces.md +2 -2
  18. package/lib/argv.mjs +41 -0
  19. package/lib/automation-scope.mjs +6 -4
  20. package/lib/automations.mjs +61 -11
  21. package/lib/captured-context.mjs +12 -0
  22. package/lib/hot-reads.mjs +21 -15
  23. package/lib/install-stamp.mjs +61 -0
  24. package/lib/instance-events.mjs +8 -6
  25. package/lib/instance-listing.mjs +13 -5
  26. package/lib/kernel-features.mjs +10 -0
  27. package/lib/local-edit.mjs +1 -1
  28. package/lib/local-inputs.mjs +3 -0
  29. package/lib/member-clone.mjs +15 -11
  30. package/lib/read-call.mjs +143 -0
  31. package/lib/reader.mjs +203 -0
  32. package/lib/remote.mjs +47 -6
  33. package/lib/resolved-deployment.mjs +12 -4
  34. package/lib/roster-read.mjs +199 -0
  35. package/lib/session-input.mjs +35 -11
  36. package/lib/workspace-read.mjs +160 -0
  37. package/package-catalog.json +2 -2
  38. package/package.json +1 -1
  39. package/packages/client/cli-locator.mjs +1 -0
  40. package/packages/client/cli-probe-contract.mjs +4 -2
  41. package/packages/client/deployment-observer.mjs +8 -3
  42. package/packages/client/deployment-panel.mjs +17 -1
  43. package/packages/client/deployment-read-cli.mjs +48 -27
  44. package/packages/client/own-codes.mjs +3 -0
  45. package/packages/client/warm-reader.mjs +241 -0
  46. package/packages/tui/lib/client.mjs +2 -1
  47. package/packages/tui/lib/read.mjs +59 -11
  48. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -33,8 +33,8 @@
33
33
  * `oats automations refresh`, which the tick runs as a child when the snapshot is ten minutes
34
34
  * old), one list per kind, and the tick reads it. The run state stays local. */
35
35
  import { spawnSync } from "node:child_process";
36
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
37
- import { dirname, join } from "node:path";
36
+ import { accessSync, constants as fsConstants, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
37
+ import { dirname, join, resolve } from "node:path";
38
38
  import { recordLocalInput } from "./local-inputs.mjs";
39
39
  import YAML from "yaml";
40
40
  import { parseConfigData } from "./config-data.mjs";
@@ -272,32 +272,82 @@ export function staleTrust(host, automations) {
272
272
  const known = new Set(automations.map((a) => a.id));
273
273
  return [...host.trust].filter((id) => !known.has(id));
274
274
  }
275
- /** The account the host's `gh` is logged in as on one GitHub host (`gh api user`), memoized in
276
- * `cache` (one per tick). `io.gh(args)` is the seam. → { ok, login } | { ok: false, error } */
277
- export function ghLogin(ghHost, { io, cache } = {}) {
275
+ /** The file a spawn of `name` runs: the first executable regular file on `path`, each entry (an empty one is the
276
+ * directory itself) resolved against `cwd` as the child's lookup resolves it. null when there is none. */
277
+ function onPath(name, path, cwd) {
278
+ for (const dir of String(path ?? "").split(":")) {
279
+ const candidate = resolve(cwd, dir || ".", name);
280
+ try { accessSync(candidate, fsConstants.X_OK); if (statSync(candidate).isFile()) return candidate; } catch { /* not here */ }
281
+ }
282
+ return null;
283
+ }
284
+ /** The token variables gh reads. Only which of them are set is part of a login's context, never a value. */
285
+ const GH_TOKEN_VARS = ["GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"];
286
+ /** What `gh api user`'s answer depends on, besides GitHub itself: the context a reused login is reused under
287
+ * (`--max-age`, display only: ghLogin's `lookup`). It is
288
+ * - the GitHub host;
289
+ * - the gh this read would run: `PATH` resolved against `cwd`, as the spawn resolves it, by its path, real path
290
+ * and file (so another deployment's relative PATH entry, or a binary replaced in place, is another context);
291
+ * - the NAMES of the token variables that are set, never their values, not even a digest of them;
292
+ * - `GH_HOST`, and gh's config directory as `GH_CONFIG_DIR`, `XDG_CONFIG_HOME` or `HOME` locate it;
293
+ * - the file of the hosts.yml there, as stat sees it: a `gh auth login`, `logout` or `switch` rewrites it.
294
+ * null when the gh to run cannot be found: such a read is never reused. What it does not see (a token variable
295
+ * given another value, a token revoked server-side) reuses the login until the record is older than --max-age,
296
+ * as a head moved on the remote reads unmoved. */
297
+ export function ghLoginParts(ghHost, env = process.env, cwd = process.cwd()) {
298
+ const stamp = (p) => { const st = statSync(p); return `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`; };
299
+ const gh = onPath("gh", env.PATH, cwd);
300
+ let binary;
301
+ try { binary = gh && `${gh}\0${realpathSync(gh)}\0${stamp(gh)}`; } catch { binary = null; }
302
+ if (!binary) return null;
303
+ const config = resolve(cwd, env.GH_CONFIG_DIR || (env.XDG_CONFIG_HOME ? join(env.XDG_CONFIG_HOME, "gh") : join(env.HOME ?? "", ".config", "gh")));
304
+ let hosts = "absent";
305
+ try { hosts = stamp(join(config, "hosts.yml")); } catch { /* absent or unreadable: as such */ }
306
+ const tokens = GH_TOKEN_VARS.filter((v) => typeof env[v] === "string" && env[v] !== "");
307
+ return [ghHost, binary, `tokens=${tokens.join(",")}`, `GH_HOST=${env.GH_HOST ?? ""}`, `config=${config}`, `hosts=${hosts}`];
308
+ }
309
+ /** How long the live lookup waits for gh before it is a failure: an act that places or fires an automation
310
+ * (a schedule tick, a trigger poll, a run) waits as long as it always has. */
311
+ export const GH_LOGIN_TIMEOUT_MS = 30_000;
312
+ /** How long the lookup behind a status display waits (`workspace status`): gh's answer takes well under a second
313
+ * (one GitHub API round trip, ~0.2 s of gh start), so 5 s is far above it; a hung gh then costs a read, which
314
+ * a client may run every few seconds, 5 s instead of 30. The placement shown says why (owner-mismatch). */
315
+ export const GH_LOGIN_DISPLAY_TIMEOUT_MS = 5_000;
316
+ /** The account the host's `gh` is logged in as on one GitHub host (`gh api user`), memoized in `cache` (one per
317
+ * tick). `io.gh(args, { timeout })` is the seam. `lookup` is the display's (`workspace status`), never an act's:
318
+ * `{ observe(ghHost), timeoutMs }`, `observe` answering a lib/remote.mjs factObservation (under --max-age a
319
+ * successful login is recorded and reused while recent; a failed one is never recorded and ends that reuse) or
320
+ * null, `timeoutMs` the wait (GH_LOGIN_TIMEOUT_MS without it). → { ok, login } | { ok: false, error } */
321
+ export function ghLogin(ghHost, { io, cache, lookup } = {}) {
278
322
  if (cache?.has(ghHost)) return cache.get(ghHost);
323
+ const fact = lookup?.observe?.(ghHost) ?? null;
324
+ const timeout = lookup?.timeoutMs ?? GH_LOGIN_TIMEOUT_MS;
325
+ const reused = fact?.reuse();
326
+ if (typeof reused === "string" && reused) { const out = { ok: true, login: reused }; cache?.set(ghHost, out); return out; }
279
327
  const argv = ["api", "user", "--jq", ".login", ...(ghHost === "github.com" ? [] : ["--hostname", ghHost])];
280
328
  let r;
281
- if (io?.gh) r = io.gh(argv);
329
+ if (io?.gh) r = io.gh(argv, { timeout });
282
330
  else {
283
- const p = spawnSync("gh", argv, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000, env: { ...process.env, GH_PROMPT_DISABLED: "1" } });
331
+ const p = spawnSync("gh", argv, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout, env: { ...process.env, GH_PROMPT_DISABLED: "1" } });
284
332
  r = p.error ? { status: 127, stdout: "", stderr: p.error.code === "ENOENT" ? "gh is not installed on this host" : p.error.message } : p;
285
333
  }
286
334
  const login = String(r.stdout || "").trim();
287
335
  const out = r.status === 0 && login ? { ok: true, login } : { ok: false, error: String(r.stderr || r.stdout).split("\n").map((l) => l.trim()).find(Boolean) || `gh exited ${r.status}` };
336
+ // A failed answer is not recorded, and it ends the reuse of an earlier success: the next read asks again.
337
+ if (out.ok) fact?.record(login); else fact?.forget();
288
338
  cache?.set(ghHost, out);
289
339
  return out;
290
340
  }
291
341
  /** Where a workspace trigger or schedule runs, from this host's point of view.
292
342
  * → { runsHere, reason: null | host-unnamed | assigned-elsewhere | owner-mismatch | untrusted, detail?, enabledHere } */
293
- export function placementOf(a, { host, io, cache }) {
343
+ export function placementOf(a, { host, io, cache, lookup }) {
294
344
  const enabledHere = a.enabled !== false && !host.disabled[a.kind]?.has(a.id);
295
345
  let reason = null, detail;
296
346
  if (!host.name) { reason = "host-unnamed"; detail = "this host has no host.name in oats-local.yaml"; }
297
347
  else if (a.runsOn !== host.name) { reason = "assigned-elsewhere"; detail = `runs on ${a.runsOn}; this host is ${host.name}`; }
298
348
  else {
299
349
  const owner = parseOwner(a.owner);
300
- const who = owner ? ghLogin(owner.host, { io, cache }) : { ok: false, error: "owner is not <host>/<login>" };
350
+ const who = owner ? ghLogin(owner.host, { io, cache, lookup }) : { ok: false, error: "owner is not <host>/<login>" };
301
351
  if (!who.ok) { reason = "owner-mismatch"; detail = `acts as ${a.owner}, but this host's gh is not logged in on ${owner?.host ?? "?"}: ${who.error}`; }
302
352
  else if (who.login.toLowerCase() !== owner.login.toLowerCase()) { reason = "owner-mismatch"; detail = `acts as ${a.owner}; this host's gh is logged in as ${owner.host}/${who.login}`; }
303
353
  else if (!trusted(host, a.id)) { reason = "untrusted"; detail = `declared for this host, not trusted here; to run it, ${trustRemedy(a.id)}`; }
@@ -314,7 +364,7 @@ export function localEntry(kind, def, { invalid = null, dep = null } = {}) {
314
364
  * and it is ten minutes old — at most one attempt per interval) and each workspace trigger and
315
365
  * schedule placed on this host, kept per kind.
316
366
  * → { snapshot, host, triggers: [entry + placement], schedules: [...], refresh: null | { ok, error? } } */
317
- export function automationContext(dep, { local, io, now = new Date(), refresh = false, cache = new Map(), clonePathOf = null } = {}) {
367
+ export function automationContext(dep, { local, io, now = new Date(), refresh = false, cache = new Map(), clonePathOf = null, lookup } = {}) {
318
368
  let snapshot = readSnapshot(dep);
319
369
  let refreshed = null;
320
370
  const realizesWorkspace = typeof local?.workspace === "string" && local?.standalone === undefined;
@@ -326,7 +376,7 @@ export function automationContext(dep, { local, io, now = new Date(), refresh =
326
376
  if (refreshed.ok) snapshot = readSnapshot(dep);
327
377
  }
328
378
  const host = hostOf(local);
329
- const place = (list) => (list || []).map((a) => ({ ...a, origin: { ...a.origin, ...originLinks(a.origin, clonePathOf) }, placement: placementOf(a, { host, io, cache }) }));
379
+ const place = (list) => (list || []).map((a) => ({ ...a, origin: { ...a.origin, ...originLinks(a.origin, clonePathOf) }, placement: placementOf(a, { host, io, cache, lookup }) }));
330
380
  const ctx = { snapshot, host, ...Object.fromEntries(KIND_NAMES.map((k) => [`${k}s`, place(snapshot?.[`${k}s`])])), refresh: refreshed };
331
381
  /** The login this host's gh is authenticated as on each GitHub host the listed items (and
332
382
  * `extraHosts`) name: { <host>: <login> | null }. Asked once per host (the tick's cache). */
@@ -0,0 +1,12 @@
1
+ /** lib/captured-context.mjs — the refusal of an inherited captured context (the captured/portable path was
2
+ * removed in 0.26): an environment that carries OATS_RESOLUTION or OATS_DEPLOYMENT runs no kernel command
3
+ * but `version`, never against the current context in its place. The CLI's dispatch asks it for every
4
+ * command; a process answering reads asks it for each request. Kernel-private, not exported from
5
+ * `./core`. Dependency-free. */
6
+
7
+ /** → null, or the refusal `{ code: "E_UNSUPPORTED_MODE", message, details: { inherited } }` of `env`. */
8
+ export function inheritedContextRefusal(env) {
9
+ const inherited = ["OATS_RESOLUTION", "OATS_DEPLOYMENT"].filter((k) => env[k]);
10
+ if (!inherited.length) return null;
11
+ return { code: "E_UNSUPPORTED_MODE", message: `this environment carries a captured context (${inherited.join(", ")}): the captured/portable path was removed in 0.26, and nothing is run against the current context in its place — retire the captured home and re-spawn it from the deployment`, details: { inherited } };
12
+ }
package/lib/hot-reads.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  /** The CLI's hot reads (awebai/oats#1630): the reads the Desktop, the TUI and agents' hooks run over and
2
- * over load only the modules they use, never core.mjs. `bin/oats.mjs` asks hotRead for its argv before
2
+ * over load only the modules they use, never core.mjs; so does the warm reader's start (`oats reader --stdio`,
3
+ * lib/reader.mjs), which loads the reads itself. `bin/oats.mjs` asks hotRead for its argv before
3
4
  * its imports; for a hot read, each of its import lines (`lib/<name>.mjs`) takes the leaves listed here
4
5
  * for that name, the modules its names are defined in and re-exported from (hotImport). Every specifier
5
6
  * is one string literal, here and in bin, so that a reader of the sources (test/client-boundary.test.mjs)
@@ -13,50 +14,54 @@
13
14
  * test/cli-hot-reads.test.mjs runs each read and pins the modules it must not load. Kernel-private,
14
15
  * not exported from `./core`. Dependency-free. */
15
16
 
16
- /** The dispatch's own modules: the deprecated-name warning, the typed failures, the resume feature. */
17
- const DISPATCH = { deprecation: ["deprecation"], errors: ["errors"], "session-resume-contract": ["session-resume-contract"] };
17
+ /** The dispatch's own modules: argv's `--flag=value` expansion, the deprecated-name warning, the typed failures,
18
+ * the resume feature, the inherited captured context's refusal. */
19
+ const DISPATCH = { argv: ["argv"], deprecation: ["deprecation"], errors: ["errors"], "session-resume-contract": ["session-resume-contract"], "captured-context": ["captured-context"] };
18
20
  /** A read that lists its deployment (LISTS_ITS_DEPLOYMENT in bin/oats.mjs): the observer and the list. */
19
21
  const LISTS = { "resolved-deployment": ["resolved-deployment"], deployments: ["deployments"] };
20
- /** `--max-age` (status and workspace status): the observation window and the local-input revision. */
21
- const OBSERVES = { remote: ["remote"], "local-inputs": ["local-inputs"] };
22
+ /** The deployment reads (status and workspace status): their call scope (lib/read-call.mjs: the remote budget,
23
+ * the read session, `--max-age`'s parse) and the local-input revision `--max-age` records. */
24
+ const OBSERVES = { "read-call": ["read-call"], "local-inputs": ["local-inputs"] };
22
25
 
23
26
  const READS = {
24
- version: { ...DISPATCH, core: ["version"], schedule: ["automation-api"], automations: ["automation-api"], "session-viewer": ["session-viewer"] },
27
+ version: { ...DISPATCH, core: ["version"], "kernel-features": ["kernel-features"], schedule: ["automation-api"], automations: ["automation-api"], "session-viewer": ["session-viewer"] },
25
28
  "session inspect": { ...DISPATCH, ...LISTS, "refused-text": ["refused-text"], core: ["session-inspect"] },
26
- status: { ...DISPATCH, ...LISTS, ...OBSERVES, core: ["agents-root", "instance-listing"], "session-viewer": ["session-viewer"], "status-words": ["status-words"], teams: ["teams"], workspace: ["workspace"], packages: ["packages"] },
29
+ status: { ...DISPATCH, ...LISTS, ...OBSERVES, "roster-read": ["roster-read"], "workspace-read": ["workspace-read"], core: ["instance-listing"], "status-words": ["status-words"] },
27
30
  "status --server": { ...DISPATCH, "status-words": ["status-words"], servers: ["servers"] },
28
- "workspace status": { ...DISPATCH, ...LISTS, ...OBSERVES, core: ["package-catalog"], packages: ["packages"], schedule: ["automation-scope"], automations: ["automations"], workspace: ["workspace"] },
31
+ "workspace status": { ...DISPATCH, ...LISTS, ...OBSERVES, "workspace-read": ["workspace-read"] },
29
32
  "instance events": { ...DISPATCH, ...LISTS, core: ["agents-root"], "instance-events": ["instance-events"], "instance-lifecycle": ["instance-address"] },
30
33
  "instance waiting clear": { ...DISPATCH, ...LISTS, core: ["soul-listing", "agents-root"], "instance-events": ["instance-events"], "instance-lifecycle": ["instance-address"] },
34
+ // The warm reader (lib/reader.mjs): bin's dispatch only. The reader imports the reads itself, PRELOAD included,
35
+ // before its hello, never through this table (docs/design/2026-10-29-warm-reader.md D4).
36
+ reader: { ...DISPATCH },
31
37
  };
32
38
 
33
39
  /** The leaves, each loaded by its own literal specifier. */
34
40
  const LEAVES = {
35
41
  "agents-root": () => import("./agents-root.mjs"),
42
+ argv: () => import("./argv.mjs"),
36
43
  "automation-api": () => import("./automation-api.mjs"),
37
- "automation-scope": () => import("./automation-scope.mjs"),
38
- automations: () => import("./automations.mjs"),
44
+ "captured-context": () => import("./captured-context.mjs"),
39
45
  deployments: () => import("./deployments.mjs"),
40
46
  deprecation: () => import("./deprecation.mjs"),
41
47
  errors: () => import("./errors.mjs"),
42
48
  "instance-address": () => import("./instance-address.mjs"),
43
49
  "instance-events": () => import("./instance-events.mjs"),
44
50
  "instance-listing": () => import("./instance-listing.mjs"),
51
+ "kernel-features": () => import("./kernel-features.mjs"),
45
52
  "local-inputs": () => import("./local-inputs.mjs"),
46
- "package-catalog": () => import("./package-catalog.mjs"),
47
- packages: () => import("./packages.mjs"),
53
+ "read-call": () => import("./read-call.mjs"),
48
54
  "refused-text": () => import("./refused-text.mjs"),
49
- remote: () => import("./remote.mjs"),
50
55
  "resolved-deployment": () => import("./resolved-deployment.mjs"),
56
+ "roster-read": () => import("./roster-read.mjs"),
51
57
  servers: () => import("./servers.mjs"),
52
58
  "session-inspect": () => import("./session-inspect.mjs"),
53
59
  "session-resume-contract": () => import("./session-resume-contract.mjs"),
54
60
  "session-viewer": () => import("./session-viewer.mjs"),
55
61
  "soul-listing": () => import("./soul-listing.mjs"),
56
62
  "status-words": () => import("./status-words.mjs"),
57
- teams: () => import("./teams.mjs"),
58
63
  version: () => import("./version.mjs"),
59
- workspace: () => import("./workspace.mjs"),
64
+ "workspace-read": () => import("./workspace-read.mjs"),
60
65
  };
61
66
 
62
67
  /** Each hot read's form: its words (`<name>`: an instance name), the switches and the value flags it
@@ -71,6 +76,7 @@ const FORMS = [
71
76
  { read: "workspace status", words: ["workspace", "status"], switches: ["--json"], values: ["--dir", "--max-age"] },
72
77
  { read: "instance events", words: ["instance", "events", "<name>"], switches: ["--json"], values: ["--home", "--dir", "--limit", "--since"] },
73
78
  { read: "instance waiting clear", words: ["instance", "waiting", "clear"], switches: ["--json"], values: ["--producer", "--reason", "--message", "--home", "--dir"] },
79
+ { read: "reader", words: ["reader"], switches: ["--stdio"] },
74
80
  ];
75
81
 
76
82
  function matches(form, argv) {
@@ -0,0 +1,61 @@
1
+ /** lib/install-stamp.mjs — the install stamp of the warm reader (lib/reader.mjs; docs/desktop-cli-api.md "The warm
2
+ * reader"): `stat` of what this kernel's code and data come from, as one string, equal for an unchanged install. A
3
+ * reader takes it first, before the kernel it answers with is loaded (bin/oats.mjs imports this module statically and
4
+ * takes the stamp before its kernel imports), so a change while the kernel loads is never part of its baseline; then
5
+ * again for every request. Node built-ins only: loading it loads no kernel code. Kernel-private, not exported from
6
+ * `./core`. */
7
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
8
+ import { dirname, join } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ /** The install root: the directory of package.json, bin/ and lib/. */
12
+ export const INSTALL_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
13
+
14
+ /** The stamp of the install at `root`. The root's (dev, ino); (dev, ino, size, mtimeMs) of package.json,
15
+ * bin/oats.mjs, package-catalog.json, every file under lib/, docs/*.schema.json, each runtime dependency's
16
+ * package.json where it resolves now (dependencyManifests: a dependency newly installed nearer the root moves it) and
17
+ * the Node binary (realpath'd); the mtime of each directory under lib/ and of docs/ (a file added or removed). A file
18
+ * gone, or one that cannot be read, is part of the stamp too. No hashing: a replaced install has new inodes, an
19
+ * edited file a new size or mtime. */
20
+ export function installStamp(root = INSTALL_ROOT) {
21
+ const lines = [];
22
+ const file = (s) => `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}`;
23
+ const add = (path, keys) => {
24
+ const s = statSync(path, { throwIfNoEntry: false });
25
+ lines.push(`${path}\0${s ? keys(s) : "absent"}`);
26
+ return s;
27
+ };
28
+ const tree = (dir) => {
29
+ if (!add(dir, (s) => `${s.mtimeMs}`)?.isDirectory()) return;
30
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
31
+ if (entry.isDirectory()) tree(join(dir, entry.name));
32
+ else add(join(dir, entry.name), file);
33
+ }
34
+ };
35
+ try {
36
+ add(root, (s) => `${s.dev}:${s.ino}`);
37
+ for (const name of ["package.json", join("bin", "oats.mjs"), "package-catalog.json"]) add(join(root, name), file);
38
+ tree(join(root, "lib"));
39
+ const docs = join(root, "docs");
40
+ if (add(docs, (s) => `${s.mtimeMs}`)?.isDirectory()) for (const name of readdirSync(docs).filter((n) => n.endsWith(".schema.json")).sort()) add(join(docs, name), file);
41
+ for (const manifest of dependencyManifests(root)) add(manifest, file);
42
+ add(realpathSync(process.execPath), file);
43
+ } catch (e) {
44
+ lines.push(`unreadable\0${e.code ?? e.message}`); // a half-written or vanishing install reads as changed
45
+ }
46
+ return lines.join("\n");
47
+ }
48
+
49
+ /** The package.json of each runtime dependency in the install's package.json, where Node resolves it from the
50
+ * install root now: the nearest node_modules above it that holds it. (One under lib/ is in the stamp's tree.) */
51
+ export function dependencyManifests(root = INSTALL_ROOT) {
52
+ let names = [];
53
+ try { names = Object.keys(JSON.parse(readFileSync(join(root, "package.json"), "utf8")).dependencies ?? {}).sort(); } catch { /* the stamp has package.json */ }
54
+ return names.map((name) => {
55
+ for (let dir = root; ; dir = dirname(dir)) {
56
+ const manifest = join(dir, "node_modules", name, "package.json");
57
+ if (existsSync(manifest)) return manifest;
58
+ if (dirname(dir) === dir) return join(root, "node_modules", name, "package.json");
59
+ }
60
+ });
61
+ }
@@ -158,10 +158,11 @@ function workspaceLogPath(given, home, meta) {
158
158
  }
159
159
 
160
160
  /** The one address of the home a caller named, in any spelling: the real home, its
161
- * instance name and incarnation, its two logs, and `asked`, the caller's spelling. */
162
- function addressOf(given) {
161
+ * instance name and incarnation, its two logs, and `asked`, the caller's spelling. `known`: the
162
+ * home's record as the caller already read it (a JSON object), else it is read here. */
163
+ function addressOf(given, known) {
163
164
  const home = realOrNearest(given);
164
- const meta = metaOf(home);
165
+ const meta = known !== undefined ? known : metaOf(home);
165
166
  let workspaceLog;
166
167
  return {
167
168
  home, asked: given, instance: basename(home), incarnation: incarnationIn(meta), homeLog: join(home, HOME_LOG),
@@ -338,9 +339,10 @@ export function readEvents(given, { limit = 200, since = null, asked } = {}) {
338
339
  * null: what `oats status` rows and `oats session inspect` carry. The same
339
340
  * bounded read and the same claim rule as readEvents, over the home log only
340
341
  * (the workspace log only when the home log is absent): every row a producer
341
- * or a session boundary writes goes to both. */
342
- export function liveWaiting(home) {
343
- const a = addressOf(home);
342
+ * or a session boundary writes goes to both. `meta`: the home's record, when the caller has just
343
+ * read it (lib/instance-listing.mjs listInstances), so that one read parses it once. */
344
+ export function liveWaiting(home, { meta } = {}) {
345
+ const a = addressOf(home, meta);
344
346
  if (a.incarnation === null) return null;
345
347
  let log = readLog(a.homeLog, "home");
346
348
  if (log.source.status === "absent") log = readLog(a.workspaceLog, "workspace");
@@ -52,13 +52,17 @@ export function legacyLocalAgents(root) {
52
52
 
53
53
  /** The captured homes (the 0.24–0.25 captured/portable path, removed in 0.26) under the
54
54
  * agents root `root`: one `legacy-captured-home` problem naming them, or null. They have
55
- * no 0.26 runtime (start, inspect and in-home commands refuse them); retire still works. */
56
- export function legacyCapturedHomes(root) {
55
+ * no 0.26 runtime (start, inspect and in-home commands refuse them); retire still works.
56
+ * `records`: the records listInstances read in this same read (its `records`), each home's
57
+ * instance.json parsed once per read; a home it holds no record for is read here. */
58
+ export function legacyCapturedHomes(root, { records } = {}) {
57
59
  if (!root) return null;
58
60
  const homes = [];
59
61
  for (const agent of subdirs(root)) for (const inst of subdirs(join(root, agent, "instances"))) {
60
62
  const home = join(root, agent, "instances", inst);
61
- let meta; try { meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); } catch { continue; }
63
+ let meta;
64
+ if (records?.has(home)) meta = records.get(home);
65
+ else try { meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); } catch { continue; }
62
66
  if (isCapturedHome(meta)) homes.push({ instance: inst, home });
63
67
  }
64
68
  if (!homes.length) return null;
@@ -244,7 +248,10 @@ function statusTmuxPanes(snapshot, socket, session, io) {
244
248
  return { ...snapshot, panes, windowIds };
245
249
  } catch (e) { return { error: tmuxFailure(e, "tmux list-panes failed") }; }
246
250
  }
247
- export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
251
+ /** `records`, when given, a Map the listing fills with each home's record as read (home → the JSON
252
+ * object its instance.json holds, before upgradeHomeMeta), for the rest of the same read to reuse
253
+ * instead of reading the file again (legacyCapturedHomes). */
254
+ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io, { records } = {}) {
248
255
  // Liveness reads each home's RECORDED endpoint (a pre-0.31 home records pi-agents): the recorded
249
256
  // socket, never the ambient $TMUX server: one window read and one pane read per socket/session,
250
257
  // plus one lazy process scan for shell descendants, independent of the number of homes.
@@ -276,6 +283,7 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
276
283
  // The record decides for this home only: one that is there and cannot be read gives the
277
284
  // row of a home without a record, whose liveness says why (below), never a failed listing.
278
285
  const record = readHomeRecord(home);
286
+ if (record.state === "record") records?.set(home, record.meta);
279
287
  const meta = record.state === "record" ? upgradeHomeMeta(record.meta, home) : { instance: e.name, home };
280
288
  // A home retained by an incomplete rollback is NOT a live instance: it
281
289
  // is preserved state awaiting cleanup, and must read that way.
@@ -328,7 +336,7 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
328
336
  // its home log); null otherwise, and null means unknown. Pane liveness is
329
337
  // already observed in the batch; still require the independent receipt
330
338
  // to agree before showing a claim, just as session inspect does.
331
- let waitingOnYou = liveness.running === true ? liveWaiting(home) : null;
339
+ let waitingOnYou = liveness.running === true ? liveWaiting(home, record.state === "record" ? { meta: record.meta } : {}) : null;
332
340
  if (waitingOnYou) {
333
341
  try { const s = instanceSessionTarget(home); if (!s.target) waitingOnYou = null; }
334
342
  catch { waitingOnYou = null; }
@@ -0,0 +1,10 @@
1
+ /** lib/kernel-features.mjs — the kernel features this binary implements: `features` in `version --json`
2
+ * (the Desktop API v1 probe) and in `status --json` (lib/roster-read.mjs), which a remote roster relays
3
+ * as the host's (feature server-probe-features, lib/servers.mjs hostFeatures). ONE list for both,
4
+ * emitted at output time, never stored, and frozen: an answer carries it by reference. A name must pass hostFeatures's check
5
+ * (test/cli-json-contract.test.mjs). Kernel-private, not exported from `./core`. Dependency-free. */
6
+ import { SESSION_RESUME_FEATURE } from "./session-resume-contract.mjs";
7
+
8
+ export const KERNEL_FEATURES = Object.freeze(["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event", "trigger-sources", "session-attach-detach-key", "lifecycle-kernel-codes", "schedule-run-warnings", "lifecycle-claim-stop", "launch-prompt-dev-channel", "soul-launch", "retire-plan-own-worktree", "spawn-kernel-codes", "soul-skills", "roster-workspace-key", "spawn-apply-max-age", "status-retire-state", "session-inspect-size", "session-inspect-running", "deployments-list", "soul-composed-skills", "instance-color", "spawn-suggest-name", "instance-upgrade", "session-attach-no-status-line", "session-attach-prefix-scroll", "instance-suggest-name", "spawn-apply-suggest-name", SESSION_RESUME_FEATURE, "instance-background", "instance-same-work", "warm-reader", "status-liveness"]);
9
+ /** The warm reader's protocol (`oats reader --stdio`, lib/reader.mjs): `readerApi` in the probe and in the reader's hello. */
10
+ export const READER_API = 1;
@@ -22,7 +22,7 @@ function fail(code, message, details) { const e = oatsError(code, message, detai
22
22
  export const localLock = (deployment) => join(deployment, ".agents", "locks", "local.lock");
23
23
 
24
24
  /** No line folding: a value past 80 columns stays on its line (the library's default width re-wraps it). */
25
- const RENDER = { lineWidth: 0 };
25
+ const RENDER = Object.freeze({ lineWidth: 0 });
26
26
  /** `value` (a document's content, its mappings as Maps so that their keys keep the file's order: an object
27
27
  * would move a key like "10" to the front) as two-space JSON. */
28
28
  function jsonText(value, indent = "") {
@@ -20,6 +20,9 @@ let inputs = null; // canonical path → sha256(bytes) | "absent", while active
20
20
 
21
21
  /** Start recording for this process (idempotent; clears nothing already recorded). */
22
22
  export function activateLocalInputs() { inputs ??= new Map(); }
23
+ /** Forget what was recorded and stop recording: a process that answers many reads (lib/read-call.mjs)
24
+ * starts each one here, then activates again when that read takes --max-age. */
25
+ export function resetLocalInputs() { inputs = null; }
23
26
 
24
27
  /** A file's canonical path: its realpath when it exists, else its directory's realpath plus its name
25
28
  * (else the resolved path), so a symlinked deployment gives one revision. */
@@ -57,9 +57,13 @@ function cloneRemotes(path) {
57
57
  return remotes;
58
58
  }
59
59
 
60
- /** The remote urls a clone carries, parsed to their repo keys. Not a git repo → null. */
61
- function cloneRemoteKeys(path) {
62
- return cloneRemotes(path)?.map((r) => r.key) ?? null;
60
+ /** The remote urls a clone carries, parsed to their repo keys. Not a git repo → null. `remotes`, when
61
+ * given, a Map (path → this answer) one read keeps for itself, so a clone it verifies twice runs git once. */
62
+ function cloneRemoteKeys(path, remotes) {
63
+ if (remotes?.has(path)) return remotes.get(path);
64
+ const keys = cloneRemotes(path)?.map((r) => r.key) ?? null;
65
+ remotes?.set(path, keys);
66
+ return keys;
63
67
  }
64
68
 
65
69
  /** Two repo keys name the same repository. Hosted keys compare literally; `local/<abs>`
@@ -74,11 +78,11 @@ function sameRepoKey(a, b) {
74
78
  /** Verify `path` is the clone of `key`: it exists, is a directory, is a Git repo, and
75
79
  * one of its remotes parses to `key`. Anything else → E_CLONE_MISMATCH { path, expected,
76
80
  * found } — the operator pointed the kernel at the wrong place; it never works there. */
77
- export function verifyMemberClone(path, key, { via } = {}) {
81
+ export function verifyMemberClone(path, key, { via, remotes } = {}) {
78
82
  const mismatch = (found, why) => err("E_CLONE_MISMATCH", `${via ? `${via}: ` : ""}${path} is not a clone of ${key}${why ? ` (${why})` : ""}${found && found.length ? ` — its remotes point at ${found.join(", ")}` : ""}`, { path, expected: key, found, via: via ?? null });
79
83
  let st; try { st = statSync(path); } catch { throw mismatch(null, "the path does not exist"); }
80
84
  if (!st.isDirectory()) throw mismatch(null, "not a directory");
81
- const found = cloneRemoteKeys(path);
85
+ const found = cloneRemoteKeys(path, remotes);
82
86
  if (found === null) throw mismatch(null, "not a Git repository");
83
87
  if (!found.some((k) => sameRepoKey(k, key))) throw mismatch(found, found.length ? "no remote names it" : "it has no remotes");
84
88
  return path;
@@ -99,30 +103,30 @@ export function verifyMemberClone(path, key, { via } = {}) {
99
103
  * mismatch too (the operator named it; "missing" would hide the typo).
100
104
  * Returns an absolute path or null.
101
105
  */
102
- export function resolveMemberClone(prepared, { explicit } = {}) {
106
+ export function resolveMemberClone(prepared, { explicit, remotes } = {}) {
103
107
  const deployment = resolvePath(prepared?.deployment ?? process.cwd());
104
108
  if (typeof explicit === "string" && explicit.trim()) return isAbsolute(explicit) ? resolvePath(explicit) : resolvePath(deployment, explicit);
105
109
  const key = prepared?.soulEntry?.repoKey;
106
110
  if (typeof key !== "string" || !key) return null;
107
- return memberCloneOf(deployment, prepared?.local, key).path;
111
+ return memberCloneOf(deployment, prepared?.local, key, { remotes }).path;
108
112
  }
109
113
 
110
114
  /** Steps 2–4 of resolveMemberClone for one member, naming the rule that found it (feature desktop-facts):
111
115
  * → { path, rule: "clones" | "convention" } | { path: null, rule: null }; a named or conventional path that
112
- * is not the member's clone is E_CLONE_MISMATCH, as for a spawn. */
113
- export function memberCloneOf(deployment, local, key) {
116
+ * is not the member's clone is E_CLONE_MISMATCH, as for a spawn. `remotes`: verifyMemberClone's. */
117
+ export function memberCloneOf(deployment, local, key, { remotes } = {}) {
114
118
  const clones = local?.clones;
115
119
  if (clones && typeof clones === "object") {
116
120
  for (const [written, value] of Object.entries(clones)) {
117
121
  if (!sameRepoKey(canonicalCloneKey(written), key)) continue;
118
122
  if (typeof value !== "string" || !value.trim()) throw err("E_CLONE_MISMATCH", `oats-local.yaml clones: ${written} must be a path`, { path: value, expected: key, found: null, via: "oats-local.yaml clones:" });
119
123
  const path = isAbsolute(value) ? resolvePath(value) : resolvePath(deployment, value);
120
- return { path: verifyMemberClone(path, key, { via: `oats-local.yaml clones: ${written}` }), rule: "clones" };
124
+ return { path: verifyMemberClone(path, key, { via: `oats-local.yaml clones: ${written}`, remotes }), rule: "clones" };
121
125
  }
122
126
  }
123
127
  const convention = conventionCloneDir(deployment, key);
124
128
  if (!existsSync(convention)) return { path: null, rule: null };
125
- return { path: verifyMemberClone(convention, key, { via: "convention path" }), rule: "convention" };
129
+ return { path: verifyMemberClone(convention, key, { via: "convention path", remotes }), rule: "convention" };
126
130
  }
127
131
 
128
132
  /** E_REMOTE_UNREADABLE reasons (lib/remote.mjs classifyRemoteFailure) that mean "the
@@ -0,0 +1,143 @@
1
+ /** lib/read-call.mjs — one call of a deployment read (awebai/oats#1630): the scope `oats status` and
2
+ * `oats workspace status` run in (lib/roster-read.mjs, lib/workspace-read.mjs), so that the CLI runs
3
+ * each once and a long-lived process answers them many times with the same code.
4
+ *
5
+ * In a one-shot CLI, process exit is what forgets a read's state. A call does that itself: it starts
6
+ * by resetting every piece of module-level state its reads can reach (READ_STATE, which
7
+ * test/read-call-state.test.mjs pins against a scan of the reads' import closure), and ends by draining
8
+ * what its read session found worth telling the operator. A read answers `{ exit, answer, stderr }`:
9
+ * `answer` the JSON value the CLI prints, every refusal an answer too (refuse); `stderr` the read
10
+ * session's notices, as the CLI says them. Each read has a data layer beside it (`…View`): `view`, what
11
+ * bin's text renderer reads, in place of `answer`, without the JSON-only work.
12
+ *
13
+ * The context: `dir` (absolute), `maxAge` (null, or the --max-age seconds: parseMaxAge), `session` (a
14
+ * function answering the caller's read session, created by callSession: the CLI's is created at its
15
+ * first remote read and carries the CLI's exit and signal listeners; a reader's is created at the start
16
+ * of the request), `cacheDir` (the remote cache, absolute, or none), and `deployments` (an observer of
17
+ * the deployment the call resolves, settled when the call ends; the CLI passes none and settles its own
18
+ * at exit, lib/resolved-deployment.mjs). A call registers no process listener and closes no session:
19
+ * the caller closes it. Nor does it read argv or the working directory: the caller owns the process's
20
+ * cwd, which still reaches the children the reads run by name (tmux, git: a relative or empty PATH entry
21
+ * is resolved against it), so a caller answering for a deployment runs the call with that deployment
22
+ * as its cwd, as the CLI does when run there. Kernel-private, not exported from `./core`. Dependency-free.
23
+ */
24
+ import { resetRuntimeNames, runtimeNameWarning } from "./deprecation.mjs";
25
+ import { OWN_NAME_FAILURES } from "./errors.mjs";
26
+ import { activateLocalInputs, localRevision, resetLocalInputs } from "./local-inputs.mjs";
27
+ import { createReadSession, MAX_AGE_LIMIT, READ_REMOTE_BUDGET_MS, resetGitProbes, resetSshCommand } from "./remote.mjs";
28
+ import { observeResolvedDeployment, resetResolvedDeployment, settleResolvedDeployment } from "./resolved-deployment.mjs";
29
+
30
+ /** Every module-level binding the reads' import closure writes, and what a call does with it: `reset`
31
+ * (forgotten at the start of each call), `scoped` (set and ended by the call itself) or `safe` (kept
32
+ * across calls, and why that cannot change an answer). A binding the scan finds that is not here fails
33
+ * test/read-call-state.test.mjs, by module and name. */
34
+ export const READ_STATE = [
35
+ { module: "lib/deprecation.mjs", binding: "sources", how: "reset", reset: resetRuntimeNames },
36
+ { module: "lib/local-inputs.mjs", binding: "inputs", how: "reset", reset: resetLocalInputs },
37
+ { module: "lib/remote.mjs", binding: "sshCommandCache", how: "reset", reset: resetSshCommand },
38
+ { module: "lib/remote.mjs", binding: "gitVersions", how: "reset", reset: resetGitProbes },
39
+ { module: "lib/remote.mjs", binding: "protocolPins", how: "reset", reset: resetGitProbes },
40
+ { module: "lib/resolved-deployment.mjs", binding: "reported", how: "reset", reset: resetResolvedDeployment },
41
+ { module: "lib/resolved-deployment.mjs", binding: "observer", how: "scoped", why: "set and settled by the call when it is given `deployments`; else the CLI's own, settled at exit" },
42
+ { module: "lib/remote.mjs", binding: "liveChildren", how: "safe", why: "a registry of live git process groups, each leaving on 'close': empty once a call's session is closed, never cleared (that would lose exit reaping)" },
43
+ { module: "lib/remote.mjs", binding: "cacheLocks", how: "safe", why: "an in-process mutex per cache repo; an entry is removed when its holder releases it" },
44
+ { module: "lib/remote.mjs", binding: "fingerprintMemo", how: "safe", why: "the kernel code's fingerprint, install data: a process that runs a changed install exits first (the warm reader's install stamp)" },
45
+ { module: "lib/session-seen.mjs", binding: "processBoot", how: "safe", why: "the boot id: a process never outlives its boot" },
46
+ { module: "lib/session-viewer.mjs", binding: "probed", how: "safe", why: "only an attach's preparation reads it; readSessionViewer asks tmux -V at every call" },
47
+ { module: "lib/session-viewer.mjs", binding: "onQuit", how: "safe", why: "only an attach (attachSessionTarget) sets it" },
48
+ { module: "lib/session-viewer.mjs", binding: "quitHeld", how: "safe", why: "only an attach (attachSessionTarget) sets it" },
49
+ { module: "lib/workspace.mjs", binding: "schemaCache", how: "safe", why: "compiled validators of the kernel's own schema files, install data: the warm reader's install stamp covers them" },
50
+ { module: "lib/workspace.mjs", binding: "regexCache", how: "safe", why: "compiled patterns: a pure function of the pattern text" },
51
+ { module: "lib/workspace.mjs", binding: "workspaceChecks", how: "safe", why: "a WeakMap keyed by a workspace value one call parsed: never reached by another call" },
52
+ { module: "lib/workspace.mjs", binding: "memberRowIndex", how: "safe", why: "a WeakMap keyed by a discovery's members array one call built: never reached by another call" },
53
+ { module: "lib/errors.mjs", binding: "answeredAfterEndedSteps", how: "safe", why: "a WeakSet of refusals one call made: never reached by another call" },
54
+ { module: "lib/process-group.mjs", binding: "closedGroups", how: "safe", why: "a WeakSet of child processes: each one call's own" },
55
+ ];
56
+
57
+ /** Forget the state of the last read: every `reset` row of READ_STATE, each reset once. */
58
+ export function resetReadState() {
59
+ for (const reset of new Set(READ_STATE.map((row) => row.reset).filter(Boolean))) reset();
60
+ }
61
+
62
+ /** `--max-age <raw>` as the read verbs take it: `raw` the flag's value (true when it has none). → `{ maxAge }`,
63
+ * or `{ refusal: { code, message } }`. Which commands take the flag is the CLI's allow-list. */
64
+ export function parseMaxAge(raw) {
65
+ if (raw === true) return { refusal: { code: "E_BAD_ARGS", message: `--max-age needs a value: whole seconds from 0 to ${MAX_AGE_LIMIT}` } };
66
+ if (!/^\d{1,5}$/.test(raw) || Number(raw) > MAX_AGE_LIMIT) return { refusal: { code: "E_BAD_ARGS", message: `--max-age takes whole seconds from 0 to ${MAX_AGE_LIMIT}, got ${JSON.stringify(raw)}` } };
67
+ return { maxAge: Number(raw) };
68
+ }
69
+
70
+ /** The remote budget of these reads (ms): READ_REMOTE_BUDGET_MS, or `OATS_READ_REMOTE_BUDGET_MS` from `env`
71
+ * when it is a positive integer (a test and ops override, not a contract). */
72
+ export function readBudget(env) {
73
+ const override = Number(env.OATS_READ_REMOTE_BUDGET_MS);
74
+ return Number.isSafeInteger(override) && override > 0 ? override : READ_REMOTE_BUDGET_MS;
75
+ }
76
+
77
+ /** The read session of one call: --max-age's reuse window (`maxAge`, null for none) and, with `budgetMs`, a
78
+ * deadline that far from now. */
79
+ export function callSession({ maxAge = null, budgetMs = null } = {}) {
80
+ return createReadSession({ maxAge: maxAge ?? 0, ...(budgetMs !== null ? { deadline: Date.now() + budgetMs } : {}) });
81
+ }
82
+
83
+ /** A refusal of a read: the call answers it as the CLI's JSON failure, `{ schemaVersion: 1, ok: false,
84
+ * error: { code, message, details? } }` with the deprecated-name warning, and exit 1. */
85
+ class ReadRefusal extends Error {}
86
+ export function refuse(code, message, details) {
87
+ throw Object.assign(new ReadRefusal(String(message)), { code, details });
88
+ }
89
+
90
+ /** The deprecated-name warning a JSON answer carries (lib/deprecation.mjs), as the envelope spreads it. */
91
+ export function answerWarnings() {
92
+ const w = runtimeNameWarning();
93
+ return w ? { warnings: [w] } : {};
94
+ }
95
+
96
+ /** Run one read: `body(call)` answers `{ answer }` or `{ view }`, or refuses (refuse). → `{ exit, answer,
97
+ * view?, stderr }`. A typed config-shape failure (lib/errors.mjs OWN_NAME_FAILURES) is answered as the
98
+ * CLI's dispatch answers it. Anything else is thrown, and the session's notices are left in it for the
99
+ * caller to say. */
100
+ export async function runRead(ctx, body) {
101
+ const call = openCall(ctx);
102
+ let result;
103
+ try {
104
+ result = { exit: 0, answer: null, ...(await body(call)) };
105
+ } catch (e) {
106
+ if (e instanceof ReadRefusal) result = { exit: 1, answer: failure(e.code, e.message, e.details) };
107
+ else if (OWN_NAME_FAILURES.has(e?.code)) result = { exit: 1, answer: failure(e.code, e.message, e.details?.unconfirmed === true ? e.details : undefined) };
108
+ else throw e;
109
+ } finally {
110
+ if (ctx.deployments) settleResolvedDeployment();
111
+ }
112
+ return { ...result, stderr: call.notices() };
113
+ }
114
+
115
+ /** A refusal answered before any read runs (a caller's own preamble: lib/reader.mjs), as runRead answers one. */
116
+ export function refusalAnswer(code, message, details) {
117
+ return { exit: 1, answer: failure(code, message, details), stderr: "" };
118
+ }
119
+
120
+ function failure(code, message, details) {
121
+ return { schemaVersion: 1, ok: false, error: { code, message: String(message), ...(details !== undefined ? { details } : {}) }, ...answerWarnings() };
122
+ }
123
+
124
+ function openCall({ maxAge = null, session, cacheDir, deployments }) {
125
+ resetReadState();
126
+ if (maxAge !== null) activateLocalInputs(); // observation.localRevision: every local config read from here on
127
+ if (deployments) observeResolvedDeployment(deployments, { atExit: false });
128
+ let used = null;
129
+ const call = {
130
+ maxAge,
131
+ /** The caller's read session, asked for where the read first needs it. */
132
+ session: () => (used ??= session()),
133
+ /** The options every remote read of the call takes. */
134
+ remoteOptions: () => ({ ...(cacheDir ? { cacheDir } : {}), session: call.session() }),
135
+ /** The observation block: the heads' oldest observedAt and reuse, and the local configuration's revision. */
136
+ observation: () => ({ ...call.session().observation(), localRevision: localRevision() }),
137
+ /** A read verb's JSON with the observation block, only when --max-age was given (0 included). */
138
+ withObservation: (doc) => (maxAge === null ? doc : { ...doc, observation: call.observation() }),
139
+ /** What the session found worth telling the operator, taken out of it, as the CLI says it on stderr. */
140
+ notices: () => (used?.notices.splice(0) ?? []).map((notice) => `oats: warning: ${notice}\n`).join(""),
141
+ };
142
+ return call;
143
+ }