@awebai/oats 0.69.4 → 0.69.5

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 (46) hide show
  1. package/bin/oats.mjs +68 -49
  2. package/docs/configuration.md +12 -0
  3. package/docs/desktop-cli-api.md +8 -1
  4. package/docs/execution-targets.md +25 -3
  5. package/docs/implementation.md +10 -3
  6. package/docs/integrations.md +2 -2
  7. package/docs/knowledge.md +9 -6
  8. package/docs/official-catalog.md +5 -5
  9. package/docs/packages.md +14 -14
  10. package/docs/release-notes/v0.69.5.md +146 -0
  11. package/docs/tui.md +2 -1
  12. package/docs/upgrading.md +16 -5
  13. package/docs/workspaces.md +2 -2
  14. package/lib/agents-root.mjs +51 -0
  15. package/lib/automation-api.mjs +7 -0
  16. package/lib/automation-scope.mjs +35 -0
  17. package/lib/automations.mjs +2 -1
  18. package/lib/compile-cache.mjs +36 -0
  19. package/lib/core.mjs +39 -1348
  20. package/lib/deployment-path.mjs +127 -0
  21. package/lib/deployments.mjs +2 -2
  22. package/lib/drift.mjs +95 -0
  23. package/lib/hot-reads.mjs +131 -0
  24. package/lib/instance-address.mjs +21 -0
  25. package/lib/instance-lifecycle.mjs +4 -16
  26. package/lib/instance-listing.mjs +730 -0
  27. package/lib/instance-resolution.mjs +5 -166
  28. package/lib/materialize.mjs +2 -87
  29. package/lib/member-clone.mjs +188 -0
  30. package/lib/package-catalog.mjs +93 -0
  31. package/lib/packages.mjs +4 -24
  32. package/lib/reserved-launch-env.mjs +20 -0
  33. package/lib/resolved-deployment.mjs +1 -1
  34. package/lib/schedule.mjs +5 -29
  35. package/lib/semver.mjs +12 -0
  36. package/lib/servers.mjs +10 -12
  37. package/lib/session-end.mjs +3 -2
  38. package/lib/session-inspect.mjs +219 -0
  39. package/lib/soul-listing.mjs +216 -0
  40. package/lib/status-words.mjs +30 -0
  41. package/lib/version.mjs +9 -0
  42. package/lib/write-file-atomic.mjs +28 -0
  43. package/package-catalog.json +4 -4
  44. package/package.json +1 -1
  45. package/packages/tui/lib/store.mjs +7 -3
  46. package/skills/oats-getting-started/SKILL.md +3 -3
@@ -0,0 +1,127 @@
1
+ /** A deployment's canonical path: the one spelling of a deployment directory the kernel records and
2
+ * compares. A leaf (awebai/oats#1630): this computer's deployments list (deployments.mjs) reads it in
3
+ * the prelude of every command that lists its deployment, without loading core.mjs, which re-exports it. */
4
+ import { canonicalHomePath } from "./real-path.mjs";
5
+ import { execFileSync } from "node:child_process";
6
+ import { existsSync } from "node:fs";
7
+ import { resolve, dirname, relative, sep, isAbsolute, join } from "node:path";
8
+ import { oatsError } from "./errors.mjs";
9
+
10
+ /** Is there a Git marker (`.git` dir or worktree pointer file) at or above `dir`?
11
+ * Filesystem-only: it answers "does Git own this location" even when the git
12
+ * binary is missing, refuses the repo (dubious ownership), or cannot read its
13
+ * metadata — cases where a probe failure must NOT be read as "not a repo". */
14
+ function hasGitMarker(dir) {
15
+ let d = resolve(dir);
16
+ while (true) {
17
+ if (existsSync(join(d, ".git"))) return true;
18
+ const parent = dirname(d);
19
+ if (parent === d) return false;
20
+ d = parent;
21
+ }
22
+ }
23
+
24
+ /** Canonicalize any deployment path that determines where an instance HOME is
25
+ * created — the agents root, and the agent directory derived from it.
26
+ *
27
+ * findRoot() walks up from the INVOCATION directory, so the path can sit inside
28
+ * a LINKED git worktree: a human running `oats spawn` from a worktree, or (far
29
+ * more common) an agent that ran `cd ./work` first. Instance homes must live in
30
+ * the soul-owning repo's PRIMARY checkout — `agents/*​/instances/` is gitignored,
31
+ * so a home created in a linked worktree is invisible in status, and it dies
32
+ * with the tree that hosted it.
33
+ *
34
+ * Canonical identity comes from Git, never from a branch name: the FIRST record
35
+ * of `git worktree list --porcelain` is the main worktree. Probes are argv-based
36
+ * (paths may contain shell metacharacters) and read-only.
37
+ *
38
+ * Returns the path unchanged only when Git does not own the location, when it is
39
+ * already in the main worktree, or when it lies outside the work tree it was
40
+ * discovered from. Throws E_NO_CANONICAL_ROOT whenever Git DOES own the location
41
+ * but the primary checkout cannot be established — including a failed probe,
42
+ * which must never pass as "not a repo" (reviewer-2366d09): guessing recreates
43
+ * the very misplacement this exists to prevent.
44
+ *
45
+ * `self`: the path is a deployment directory, owned by the repository it sits
46
+ * in, that repository's root included (this computer's deployments list,
47
+ * lib/deployments.mjs). The probe starts at the directory itself rather than
48
+ * its parent, and the root of a linked worktree maps to the primary checkout's
49
+ * root. Without it (the agents roots), a path that is a work tree's root is left
50
+ * where it is.
51
+ */
52
+ export function canonicalDeploymentPath(p, { self = false } = {}) {
53
+ if (!p) return p;
54
+ const abs = resolve(p);
55
+ const probe = (argv) => {
56
+ try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
57
+ catch (e) { return { ok: false, err: String(e.stderr || e.message || "").trim() }; }
58
+ };
59
+ // The scope that owns the path. The directory itself may not exist yet
60
+ // (local-only scopes, an agent dir created on first use), so probe from the
61
+ // nearest existing ancestor.
62
+ let scope = self ? abs : dirname(abs);
63
+ while (!existsSync(scope) && dirname(scope) !== scope) scope = dirname(scope);
64
+ const top = probe(["git", "-C", scope, "rev-parse", "--show-toplevel"]);
65
+ if (!top.ok) {
66
+ // A failed probe is NOT evidence of a non-Git scope. Only the absence of any
67
+ // Git marker is — otherwise an unavailable/erroring git would silently let a
68
+ // linked worktree through, which is exactly the fail-open this prevents.
69
+ if (hasGitMarker(scope)) {
70
+ throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside a Git-owned location whose repository could not be read (${top.err || "git rev-parse failed"}) — instance homes must live in the soul-owning repo's primary checkout, and OATS cannot confirm this is it; fix the Git error or pass --dir <primary checkout>`);
71
+ }
72
+ return abs; // genuinely not a Git work tree
73
+ }
74
+ const toplevel = top.out.trim();
75
+ if (!toplevel) return abs;
76
+ // Git reports CANONICAL paths, so every comparison and every relative()
77
+ // below must be realpath-based: on macOS a temp/agents root reached through
78
+ // /var while Git reports /private/var would otherwise look "outside" the
79
+ // work tree and silently skip canonicalization. So would a root given in
80
+ // another letter case on a case-insensitive filesystem: Git's paths are in
81
+ // their on-disk spelling, and so are both sides here. The agents dir itself
82
+ // may not exist yet (local-only scopes), so resolve the nearest existing
83
+ // ancestor and re-append the remainder.
84
+ const realOf = canonicalHomePath;
85
+ const same = (a, b) => realOf(a) === realOf(b);
86
+ // Linked or main? `--git-dir` equals `--git-common-dir` in the MAIN worktree
87
+ // and points at <common>/worktrees/<name> in a linked one. This settles it
88
+ // without `git worktree list`, so the overwhelmingly common main-checkout
89
+ // path costs one probe and — crucially — cannot be failed by a hiccup in a
90
+ // command it does not need (a forced `worktree list` failure used to reject
91
+ // an ordinary main-checkout spawn).
92
+ const dirs = probe(["git", "-C", scope, "rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"]);
93
+ const [gitDir, commonDir] = dirs.ok
94
+ ? dirs.out.trim().split("\n").map((l) => l.trim())
95
+ // Pre-2.31 git has no --path-format: fall back to plain output, whose paths
96
+ // may be relative to the scope.
97
+ : (() => {
98
+ const plain = probe(["git", "-C", scope, "rev-parse", "--git-dir", "--git-common-dir"]);
99
+ if (!plain.ok) return [];
100
+ return plain.out.trim().split("\n").map((l) => resolve(scope, l.trim()));
101
+ })();
102
+ if (!gitDir || !commonDir) {
103
+ throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside the Git work tree ${toplevel}, but OATS could not tell a linked worktree from the primary checkout (${dirs.err || "git rev-parse --git-dir/--git-common-dir failed"}) — instance homes must live in the soul-owning repo's primary checkout; fix the Git error or pass --dir <primary checkout>`);
104
+ }
105
+ // Main checkout: the common case, and the one that must stay free — returned
106
+ // untouched, in the caller's own path form.
107
+ if (same(gitDir, commonDir)) return abs;
108
+ // Linked worktree from here on — the primary checkout is REQUIRED, not optional.
109
+ const list = probe(["git", "-C", scope, "worktree", "list", "--porcelain", "-z"]);
110
+ const mainWorktree = list.ok
111
+ ? (list.out.split("\0").find((f) => f.startsWith("worktree ")) || "").slice("worktree ".length)
112
+ : undefined;
113
+ if (!list.ok) throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside the linked Git worktree ${toplevel}, and the primary checkout could not be determined (${list.err || "git worktree list failed"}) — instance homes must live in the soul-owning repo's primary checkout; re-run from it or pass --dir <primary checkout>`);
114
+ if (!mainWorktree) throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside the linked Git worktree ${toplevel}, but \`git worktree list\` reported no main worktree — instance homes must live in the soul-owning repo's primary checkout; re-run from it or pass --dir <primary checkout>`);
115
+ if (!existsSync(mainWorktree)) throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside the linked Git worktree ${toplevel}, whose primary checkout ${mainWorktree} does not exist — instance homes must live in the soul-owning repo's primary checkout; restore it or pass --dir <primary checkout>`);
116
+ // Map the root's position within the linked tree onto the primary checkout.
117
+ // A root OUTSIDE the work tree (sibling agents/ beside the repo) is not a
118
+ // worktree artifact and is left exactly where it is.
119
+ const rel = relative(realOf(toplevel), realOf(abs));
120
+ if ((rel === "" && !self) || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return abs;
121
+ const canonical = join(realOf(mainWorktree), rel);
122
+ const back = relative(realOf(mainWorktree), canonical);
123
+ if (back === ".." || back.startsWith(`..${sep}`) || isAbsolute(back)) {
124
+ throw oatsError("E_NO_CANONICAL_ROOT", `canonical root for ${abs} would escape the primary checkout ${mainWorktree}`);
125
+ }
126
+ return canonical;
127
+ }
@@ -25,9 +25,9 @@
25
25
  import { closeSync, constants as fsConstants, fstatSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, statSync } from "node:fs";
26
26
  import { homedir, tmpdir } from "node:os";
27
27
  import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
28
- import { canonicalDeploymentPath } from "./core.mjs";
28
+ import { canonicalDeploymentPath } from "./deployment-path.mjs";
29
29
  import { withDirLock } from "./dir-lock.mjs";
30
- import { writeFileAtomic } from "./packages.mjs";
30
+ import { writeFileAtomic } from "./write-file-atomic.mjs";
31
31
  import { canonicalHomePath } from "./real-path.mjs";
32
32
 
33
33
  export const DEPLOYMENTS_API = 1;
package/lib/drift.mjs ADDED
@@ -0,0 +1,95 @@
1
+ /** A home's drift: how each recorded module and the recorded soul compare with what the workspace offers
2
+ * now. A leaf (awebai/oats#1630): `oats status` reports drift without loading the home composer
3
+ * (materialize.mjs), which imports these helpers and re-exports what it exported. */
4
+ import { memberRowByKey } from "./workspace.mjs";
5
+
6
+ const plainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
7
+ const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
8
+
9
+ /**
10
+ * driftOf(instanceJson, discovery, { lock } = {})
11
+ * → [{ module, from, recorded: { repoKey, commit }, current: { commit } | null, status: "current"|"moved"|"missing", reason? }]
12
+ *
13
+ * Member modules: the confirmed member row for `repoKey` in `discovery.members` is the current
14
+ * state — unconfirmed/absent → "missing" (reason "unconfirmed"); the capability gone from the
15
+ * member → "missing" (reason "capability-absent"); a different commit → "moved"; else "current".
16
+ * Package modules are pinned by version: without a lock they are "current"; with one, the lock's
17
+ * entry decides — absent package or capability → "missing", another commit → "moved".
18
+ */
19
+ export function driftOf(instanceJson, discovery, { lock } = {}) {
20
+ const modules = plainObject(instanceJson?.modules) ? instanceJson.modules : {};
21
+ const members = Array.isArray(discovery?.members) ? discovery.members : [];
22
+ const rows = [];
23
+ for (const name of Object.keys(modules).sort()) {
24
+ const rec = modules[name] || {};
25
+ const from = plainObject(rec.from) ? rec.from : {};
26
+ const commit = typeof rec.commit === "string" ? rec.commit : (typeof from.commit === "string" ? from.commit : null);
27
+ if (from.kind === "package") {
28
+ const recorded = { repoKey: from.repoKey ?? null, package: from.package ?? null, version: from.version ?? null, commit };
29
+ if (!plainObject(lock?.packages)) { rows.push({ module: name, from: clone(from), recorded, current: commit ? { commit } : null, status: "current" }); continue; }
30
+ const entry = lock.packages[from.package];
31
+ if (!entry) { rows.push({ module: name, from: clone(from), recorded, current: null, status: "missing", reason: "package-absent" }); continue; }
32
+ if (Array.isArray(entry.capabilities) && !entry.capabilities.includes(name)) {
33
+ rows.push({ module: name, from: clone(from), recorded, current: { commit: entry.commit, version: entry.version }, status: "missing", reason: "capability-absent" }); continue;
34
+ }
35
+ rows.push({ module: name, from: clone(from), recorded, current: { commit: entry.commit, version: entry.version }, status: entry.commit === commit ? "current" : "moved" });
36
+ continue;
37
+ }
38
+ const repoKey = typeof from.repoKey === "string" ? from.repoKey : null;
39
+ const recorded = { repoKey, commit };
40
+ const member = repoKey ? memberRowByKey(members, repoKey) : null;
41
+ if (!member || !member.confirmed || typeof member.commit !== "string") {
42
+ rows.push({ module: name, from: clone(from), recorded, current: null, status: "missing", reason: member ? (member.reason || "unconfirmed") : "unconfirmed" });
43
+ continue;
44
+ }
45
+ const cap = Array.isArray(member.capabilities) ? member.capabilities.find((c) => c && c.name === name) : null;
46
+ if (!cap) { rows.push({ module: name, from: clone(from), recorded, current: { commit: member.commit }, status: "missing", reason: "capability-absent" }); continue; }
47
+ // `version` (feature desktop-facts): the member capability's manifest version now, beside the commit.
48
+ rows.push({ module: name, from: clone(from), recorded, current: { commit: member.commit, version: typeof cap.manifest?.version === "string" ? cap.manifest.version : null }, status: member.commit === commit ? "current" : "moved" });
49
+ }
50
+ return rows;
51
+ }
52
+
53
+ /**
54
+ * soulDriftOf(instanceJson, discovery)
55
+ * → { name, repoKey, commit, current: { commit } | null, status: "current"|"moved"|"missing", reason? } | null
56
+ *
57
+ * Decision 17 for the SOUL SOURCE: a workspace spawn records `instance.json.workspace.soul =
58
+ * { repoKey, commit }` (the member and commit the soul was fetched from). The member row
59
+ * for `repoKey` in `discovery.members` is the current state: a different commit → "moved", the
60
+ * soul gone from the member → "missing" (reason "soul-absent"), no usable row → "missing"
61
+ * (reason "unconfirmed" / the row's reason). A standalone view's own member row is unconfirmed
62
+ * by construction (reason "cannot-read") yet carries the repo's current commit — it is compared,
63
+ * not reported missing. Returns null for a home without a recorded workspace soul (classic).
64
+ * A PACKAGE soul (`workspace.soul.package`) is compared with the discovery's package souls: the
65
+ * pin moved → "moved"; the package no longer locked/declared → "missing" ("package-absent"); the
66
+ * soul no longer shipped by the package → "missing" ("soul-absent").
67
+ */
68
+ export function soulDriftOf(instanceJson, discovery) {
69
+ const soul = plainObject(instanceJson?.workspace) && plainObject(instanceJson.workspace.soul) ? instanceJson.workspace.soul : null;
70
+ if (!soul || typeof soul.repoKey !== "string") return null;
71
+ const name = typeof instanceJson.agent === "string" ? instanceJson.agent : (typeof instanceJson.soul === "string" ? instanceJson.soul : null);
72
+ const commit = typeof soul.commit === "string" ? soul.commit : null;
73
+ if (plainObject(soul.package) && typeof soul.package.id === "string") {
74
+ // A package soul: "moved" means the package pin moved (another version/commit is locked now).
75
+ const pkg = { package: soul.package.id, version: soul.package.version ?? null };
76
+ const soulName = typeof soul.name === "string" ? soul.name : name;
77
+ const base = { name: soulName, repoKey: soul.repoKey, commit, ...pkg };
78
+ const listed = Array.isArray(discovery?.packageSouls) ? discovery.packageSouls.filter((s) => s && s.package === soul.package.id) : [];
79
+ const now = listed.find((s) => s.name === soulName) || null;
80
+ if (!now) return { ...base, current: null, status: "missing", reason: listed.length ? "soul-absent" : "package-absent" };
81
+ return { ...base, current: { commit: now.commit, version: now.version }, status: now.commit === commit ? "current" : "moved" };
82
+ }
83
+ const members = Array.isArray(discovery?.members) ? discovery.members : [];
84
+ const member = memberRowByKey(members, soul.repoKey);
85
+ const standaloneOwn = discovery?.standalone === true && member && member.key === discovery.key && typeof member.commit === "string";
86
+ const base = { name, repoKey: soul.repoKey, commit };
87
+ if (!member || (!member.confirmed && !standaloneOwn) || typeof member.commit !== "string") {
88
+ return { ...base, current: null, status: "missing", reason: member ? (member.reason || "unconfirmed") : "unconfirmed" };
89
+ }
90
+ const present = name === null || (Array.isArray(member.souls) && member.souls.some((s) => s && s.name === name));
91
+ if (!present) return { ...base, current: { commit: member.commit }, status: "missing", reason: "soul-absent" };
92
+ return { ...base, current: { commit: member.commit }, status: member.commit === commit ? "current" : "moved" };
93
+ }
94
+
95
+ export { clone, plainObject };
@@ -0,0 +1,131 @@
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
3
+ * its imports; for a hot read, each of its import lines (`lib/<name>.mjs`) takes the leaves listed here
4
+ * for that name, the modules its names are defined in and re-exported from (hotImport). Every specifier
5
+ * is one string literal, here and in bin, so that a reader of the sources (test/client-boundary.test.mjs)
6
+ * sees every module the CLI can load. Every other command, and a
7
+ * hot read given anything but the words and flags listed here (help, an unknown flag, a missing value),
8
+ * imports every module as before.
9
+ *
10
+ * A list must hold every module the read's code can reach, its error paths included. A line a read
11
+ * does not list, or a name its leaves do not export, is a tripwire (standIn): taking it is free, and
12
+ * any use of it throws a HotReadUnlisted defect that names the read, the line and the name.
13
+ * test/cli-hot-reads.test.mjs runs each read and pins the modules it must not load. Kernel-private,
14
+ * not exported from `./core`. Dependency-free. */
15
+
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"] };
18
+ /** A read that lists its deployment (LISTS_ITS_DEPLOYMENT in bin/oats.mjs): the observer and the list. */
19
+ 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
+
23
+ const READS = {
24
+ version: { ...DISPATCH, core: ["version"], schedule: ["automation-api"], automations: ["automation-api"], "session-viewer": ["session-viewer"] },
25
+ "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"] },
27
+ "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"] },
29
+ "instance events": { ...DISPATCH, ...LISTS, core: ["agents-root"], "instance-events": ["instance-events"], "instance-lifecycle": ["instance-address"] },
30
+ "instance waiting clear": { ...DISPATCH, ...LISTS, core: ["soul-listing", "agents-root"], "instance-events": ["instance-events"], "instance-lifecycle": ["instance-address"] },
31
+ };
32
+
33
+ /** The leaves, each loaded by its own literal specifier. */
34
+ const LEAVES = {
35
+ "agents-root": () => import("./agents-root.mjs"),
36
+ "automation-api": () => import("./automation-api.mjs"),
37
+ "automation-scope": () => import("./automation-scope.mjs"),
38
+ automations: () => import("./automations.mjs"),
39
+ deployments: () => import("./deployments.mjs"),
40
+ deprecation: () => import("./deprecation.mjs"),
41
+ errors: () => import("./errors.mjs"),
42
+ "instance-address": () => import("./instance-address.mjs"),
43
+ "instance-events": () => import("./instance-events.mjs"),
44
+ "instance-listing": () => import("./instance-listing.mjs"),
45
+ "local-inputs": () => import("./local-inputs.mjs"),
46
+ "package-catalog": () => import("./package-catalog.mjs"),
47
+ packages: () => import("./packages.mjs"),
48
+ "refused-text": () => import("./refused-text.mjs"),
49
+ remote: () => import("./remote.mjs"),
50
+ "resolved-deployment": () => import("./resolved-deployment.mjs"),
51
+ servers: () => import("./servers.mjs"),
52
+ "session-inspect": () => import("./session-inspect.mjs"),
53
+ "session-resume-contract": () => import("./session-resume-contract.mjs"),
54
+ "session-viewer": () => import("./session-viewer.mjs"),
55
+ "soul-listing": () => import("./soul-listing.mjs"),
56
+ "status-words": () => import("./status-words.mjs"),
57
+ teams: () => import("./teams.mjs"),
58
+ version: () => import("./version.mjs"),
59
+ workspace: () => import("./workspace.mjs"),
60
+ };
61
+
62
+ /** Each hot read's form: its words (`<name>`: an instance name), the switches and the value flags it
63
+ * takes, and the value flags it requires. */
64
+ const FORMS = [
65
+ { read: "version", words: ["version"], switches: ["--json"] },
66
+ { read: "version", words: ["--version"], switches: ["--json"] },
67
+ { read: "version", words: ["-v"], switches: ["--json"] },
68
+ { read: "session inspect", words: ["session", "inspect"], switches: ["--json"], values: ["--home"] },
69
+ { read: "status", words: ["status"], switches: ["--json", "--team", "--verbose"], values: ["--dir", "--max-age"] },
70
+ { read: "status --server", words: ["status"], switches: ["--json"], values: ["--server"], requires: ["--server"] },
71
+ { read: "workspace status", words: ["workspace", "status"], switches: ["--json"], values: ["--dir", "--max-age"] },
72
+ { read: "instance events", words: ["instance", "events", "<name>"], switches: ["--json"], values: ["--home", "--dir", "--limit", "--since"] },
73
+ { read: "instance waiting clear", words: ["instance", "waiting", "clear"], switches: ["--json"], values: ["--producer", "--reason", "--message", "--home", "--dir"] },
74
+ ];
75
+
76
+ function matches(form, argv) {
77
+ if (argv.length < form.words.length) return false;
78
+ if (form.words.some((w, i) => (w === "<name>" ? !argv[i] || argv[i].startsWith("-") : argv[i] !== w))) return false;
79
+ const given = new Set();
80
+ for (let i = form.words.length; i < argv.length; i++) {
81
+ const a = argv[i], eq = a.indexOf("=");
82
+ if (form.switches.includes(a)) continue;
83
+ const name = a.startsWith("--") && eq > 2 ? a.slice(0, eq) : a;
84
+ if (!form.values?.includes(name)) return false;
85
+ if (name === a) { if (argv[i + 1] === undefined || argv[i + 1].startsWith("--")) return false; i++; }
86
+ given.add(name);
87
+ }
88
+ return (form.requires ?? []).every((f) => given.has(f));
89
+ }
90
+
91
+ /** argv's hot read, { form, lines: { <name>: [leaf names] } }, or null for any other command. Help is
92
+ * never one: the dispatch answers usage for `-h` or `--help` anywhere in argv as it expands it, a flag's
93
+ * value included (`--dir -h`, `--dir=-h`), and usage reads beyond any hot read's names. */
94
+ export function hotRead(argv) {
95
+ if (argv.some((a) => /(^|=)(-h|--help)$/.test(a))) return null;
96
+ const form = FORMS.find((f) => matches(f, argv));
97
+ return form ? { form: form.read, lines: READS[form.read] } : null;
98
+ }
99
+
100
+ /** The leaves a hot read loads in place of bin's import line of `lib/<name>.mjs` (or of `yaml`). */
101
+ export function hotLeaves(read, name) {
102
+ return read.lines[name] ?? [];
103
+ }
104
+
105
+ /** What bin's import line of `name` answers in a hot read: its leaves, loaded in order (standIn). */
106
+ export async function hotImport(read, name) {
107
+ const modules = [];
108
+ for (const leaf of hotLeaves(read, name)) modules.push(await LEAVES[leaf]());
109
+ return standIn(read, name, modules);
110
+ }
111
+
112
+ /** A hot read's use of a name it does not list: a mistake in this table, never an answer. Its name is on
113
+ * the prototype, so the kernel reports it as the defect it is (errors.mjs isDefect). */
114
+ export class HotReadUnlisted extends Error {}
115
+ HotReadUnlisted.prototype.name = "HotReadUnlisted";
116
+
117
+ /** What an import line answers in a hot read: the one leaf's namespace (read live), or the names of its
118
+ * leaves together, behind a proxy that answers any other name with a tripwire. `then` is never one: an
119
+ * `await` asks for it, and its absence is what makes the answer no promise. */
120
+ export function standIn(read, line, modules) {
121
+ const target = modules.length === 1 ? modules[0] : Object.assign(Object.create(null), ...modules);
122
+ return new Proxy(target, { get: (t, name) => (name in t ? t[name] : name === "then" ? undefined : tripwire(read, line, name)) });
123
+ }
124
+
125
+ function tripwire(read, line, name) {
126
+ const fail = () => {
127
+ throw new HotReadUnlisted(`oats ${read.form} is a hot read, and it used ${String(name)} of ${line === "yaml" ? line : `lib/${line}.mjs`}, which lib/hot-reads.mjs does not list for it: list the module that defines ${String(name)} under that line in the read's entry in lib/hot-reads.mjs`);
128
+ };
129
+ // A function target, so that a call and `new` reach their traps too.
130
+ return new Proxy(function unlisted() {}, { get: fail, set: fail, has: fail, ownKeys: fail, apply: fail, construct: fail, getOwnPropertyDescriptor: fail, defineProperty: fail, deleteProperty: fail, getPrototypeOf: fail });
131
+ }
@@ -0,0 +1,21 @@
1
+ /** resolveInstance: an instance name, and optionally the home claimed for it, resolved to exactly one
2
+ * home under an agents root. A leaf (awebai/oats#1630): `oats instance events` and `instance waiting`
3
+ * resolve their home without loading instance-lifecycle.mjs or core.mjs; instance-lifecycle.mjs
4
+ * re-exports it. */
5
+ import { findInstanceHomes } from "./soul-listing.mjs";
6
+ import { oatsError } from "./errors.mjs";
7
+
8
+ /** Resolve `<name>` under the deployment's agents root to exactly one home. */
9
+ export function resolveInstance(ctx, root, name, { home } = {}) {
10
+ const roots = [root];
11
+ const candidates = [];
12
+ for (const rt of roots) for (const hit of findInstanceHomes(rt, name)) candidates.push({ root: rt, agent: hit.agent?.name ?? null, home: hit.home });
13
+ if (home !== undefined) {
14
+ const found = candidates.find((c) => c.home === home);
15
+ if (!found) throw oatsError("E_HOME_MISMATCH", `--home ${home} is not a home of instance ${JSON.stringify(name)} under ${roots.join(", ")}`);
16
+ return found;
17
+ }
18
+ if (!candidates.length) throw oatsError("E_SESSION_UNKNOWN", `no instance ${JSON.stringify(name)} under ${roots.join(", ")}`);
19
+ if (candidates.length > 1) throw Object.assign(oatsError("E_AMBIGUOUS_INSTANCE", `instance ${JSON.stringify(name)} has ${candidates.length} homes; pass --home <abs>`), { candidates });
20
+ return candidates[0];
21
+ }
@@ -9,8 +9,8 @@
9
9
  * Unknown is reported as unknown — never as "clean" or "no children". */
10
10
  import { createHash } from "node:crypto";
11
11
  import { existsSync, lstatSync, readFileSync, rmSync } from "node:fs";
12
- import { basename, join } from "node:path";
13
- import { attachedWorkLink, claimHomeFor, extraWorktreePlan, findInstanceHomes, homeClaimHolder, identifiedHomeRecord, refuseBesideRetire, inspectInstanceSession, instanceWork, listAgents, listInstances, observeSessionWithoutReceipt, readHomeRecord, READ_CLAIM_WHEN_UNWRITABLE, releaseHomeClaim, requireStopGrace, retireClaimPath, retirePendingMarkerPath, retirementRecoveryFacts, shq, stillRunningOf, stopInstanceSession, STOP_UNDER_CLAIM } from "./core.mjs";
12
+ import { join } from "node:path";
13
+ import { attachedWorkLink, claimHomeFor, extraWorktreePlan, homeClaimHolder, identifiedHomeRecord, refuseBesideRetire, inspectInstanceSession, instanceWork, listAgents, listInstances, observeSessionWithoutReceipt, readHomeRecord, READ_CLAIM_WHEN_UNWRITABLE, releaseHomeClaim, requireStopGrace, retireClaimPath, retirePendingMarkerPath, retirementRecoveryFacts, shq, stillRunningOf, stopInstanceSession, STOP_UNDER_CLAIM } from "./core.mjs";
14
14
  import { groupedByOwner } from "./retire-output.mjs";
15
15
  import { observeInstanceGit } from "./instance-git.mjs";
16
16
  import { appendEvent } from "./instance-events.mjs";
@@ -19,6 +19,8 @@ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
19
19
  import { INSTANCE_COLOR_API, INSTANCE_COLORS, writeInstanceColor } from "./instance-color.mjs";
20
20
  import { INSTANCE_BACKGROUND_API, writeInstanceBackground } from "./instance-background.mjs";
21
21
  import { sameWorkOf, writeSameWork } from "./instance-same-work.mjs";
22
+ import { resolveInstance } from "./instance-address.mjs";
23
+ export { resolveInstance } from "./instance-address.mjs";
22
24
 
23
25
  export const LIFECYCLE_API = 1;
24
26
  const KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -38,20 +40,6 @@ const stopReceiptPath = (home, key) => join(home, `.oats-stop-receipt.${key}.jso
38
40
  function readJson(path) { try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; } }
39
41
  function planRevision(facts) { return createHash("sha256").update(JSON.stringify(facts)).digest("hex").slice(0, 24); }
40
42
 
41
- /** Resolve `<name>` under the deployment's agents root to exactly one home. */
42
- export function resolveInstance(ctx, root, name, { home } = {}) {
43
- const roots = [root];
44
- const candidates = [];
45
- for (const rt of roots) for (const hit of findInstanceHomes(rt, name)) candidates.push({ root: rt, agent: hit.agent?.name ?? null, home: hit.home });
46
- if (home !== undefined) {
47
- const found = candidates.find((c) => c.home === home);
48
- if (!found) throw oatsError("E_HOME_MISMATCH", `--home ${home} is not a home of instance ${JSON.stringify(name)} under ${roots.join(", ")}`);
49
- return found;
50
- }
51
- if (!candidates.length) throw oatsError("E_SESSION_UNKNOWN", `no instance ${JSON.stringify(name)} under ${roots.join(", ")}`);
52
- if (candidates.length > 1) throw Object.assign(oatsError("E_AMBIGUOUS_INSTANCE", `instance ${JSON.stringify(name)} has ${candidates.length} homes; pass --home <abs>`), { candidates });
53
- return candidates[0];
54
- }
55
43
  /** The home a stop or a retire is about: resolved (resolveInstance), and refused when its record is
56
44
  * there and cannot be read (core identifiedHomeRecord), before a plan reads anything of it. */
57
45
  function resolveTarget(ctx, root, name, opts) {