@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
@@ -18,23 +18,21 @@
18
18
  * per-soul `source:` — those do not exist in this model. */
19
19
  import { existsSync, readFileSync, readdirSync, lstatSync, readlinkSync, realpathSync } from "node:fs";
20
20
  import { join, resolve as resolvePath, dirname, relative, isAbsolute, sep } from "node:path";
21
- import { oatsError } from "./errors.mjs";
22
- import { loadLocal, discoverWorkspace, discoverRepo, standaloneRepo, observeWorkspace } from "./workspace.mjs";
21
+ import { loadLocal, observeWorkspace } from "./workspace.mjs";
23
22
  import { resolveSoul, kernelCompatibility } from "./resolve.mjs";
24
23
  import { BY_TEAM_REMOVED, isRemovedTeamKeys, isTeamRefusal, memberNameOf, recordedTeams, reportRows, soulKeyOf, soulTeams, teamKeyOf, teamModel } from "./teams.mjs";
25
24
  import { launchLayers } from "./launch-preference.mjs";
26
25
  import { APPROVED_HOOKS, declaredSettings, locatedContractWarnings } from "./capability-contract.mjs";
27
26
  import { materialize, moduleSkills, MODULES_DIR, plannedModuleSkills, SKILLS_DIR } from "./materialize.mjs";
28
27
  import { contentDigest, fetchRemoteTree } from "./remote.mjs";
29
- import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync, symlinkSync, statSync } from "node:fs";
28
+ import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync, symlinkSync } from "node:fs";
30
29
  import { tmpdir } from "node:os";
31
- import { spawnSync } from "node:child_process";
32
30
  import { randomBytes } from "node:crypto";
33
- import { readLock, readLockIfPresent, LOCK_FILE, SOUL_ALIAS_SYMLINK } from "./packages.mjs";
34
- import * as defaultRemote from "./remote.mjs";
31
+ import { readLockIfPresent, SOUL_ALIAS_SYMLINK } from "./packages.mjs";
35
32
  import { parseRepoRef } from "./remote.mjs";
33
+ import { cloneRemotes, conventionCloneDir, discoverOrStandalone, err, resolveMemberClone, sameRepoKey } from "./member-clone.mjs";
34
+ export { canonicalCloneKey, conventionCloneDir, deploymentLock, discoverOrStandalone, memberCloneOf, resolveMemberClone, verifyMemberClone } from "./member-clone.mjs";
36
35
 
37
- function err(code, message, details) { const e = oatsError(code, message, details); e.details = details; return e; }
38
36
 
39
37
  /** Keys that would poison a payload's prototype (as own keys) or, as a CAPABILITY
40
38
  * name, address an inherited member of a plain `{}` (`constructor`, `toString`, …).
@@ -391,121 +389,18 @@ export async function ensureWorkspaceSoul(prepared, agentsRoot) {
391
389
  * and `oats sync` print (memberLabel). */
392
390
  export { memberNameOf };
393
391
 
394
- /** The convention path of a member's clone: `<deployment>/<member name>` — except a
395
- * member called `agents`, which is cloned as `agents-repo/` because `<deployment>/agents/`
396
- * is the instance root (design doc §4; matches onboard's cloneDirOf). */
397
- export function conventionCloneDir(deployment, key) {
398
- const name = memberNameOf(key);
399
- return join(deployment, name === "agents" ? "agents-repo" : name);
400
- }
401
392
 
402
- /** Normalise a key an operator may have WRITTEN in `clones:` — the canonical key
403
- * (`github.com/org/repo`), or any ref form parseRepoRef understands (`git:…`,
404
- * `https://…`, `git@host:…`, `/abs/bare.git`) — to the canonical key. A key that
405
- * parses no way is returned as written (it can then only match literally). */
406
- export function canonicalCloneKey(written) {
407
- const s = String(written).trim();
408
- if (s.startsWith("local/")) return s; // a local key is already canonical
409
- for (const candidate of [s, `git:${s}`]) {
410
- try { return parseRepoRef(candidate).key; } catch { /* next form */ }
411
- }
412
- return s;
413
- }
414
393
 
415
- /** The remotes a clone carries (any remote, not only origin), each with its url parsed
416
- * to a repo key: [{ name, key }]. Not a git repo → null. */
417
- function cloneRemotes(path) {
418
- const git = (argv) => spawnSync("git", ["-C", path, ...argv], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 10_000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
419
- const inside = git(["rev-parse", "--git-dir"]);
420
- if (inside.status !== 0) return null;
421
- // -z: each entry is `<key>\n<value>\0`, so a value holding a newline cannot read as another entry.
422
- const cfg = git(["config", "-z", "--get-regexp", "^remote\\..*\\.url$"]);
423
- const remotes = [];
424
- if (cfg.status === 0) {
425
- for (const entry of cfg.stdout.split("\0")) {
426
- const nl = entry.indexOf("\n");
427
- if (nl < 0) continue;
428
- const key = entry.slice(0, nl), url = entry.slice(nl + 1).trim();
429
- if (!url) continue;
430
- const name = key.slice("remote.".length, -".url".length);
431
- try { remotes.push({ name, key: parseRepoRef(url).key }); } catch { remotes.push({ name, key: `?/${url}` }); }
432
- }
433
- }
434
- return remotes;
435
- }
436
394
 
437
- /** The remote urls a clone carries, parsed to their repo keys. Not a git repo → null. */
438
- function cloneRemoteKeys(path) {
439
- return cloneRemotes(path)?.map((r) => r.key) ?? null;
440
- }
441
395
 
442
396
  /** The name of the clone's remote whose url names `key`, or null (no such remote, or not a git repo). */
443
397
  export function cloneRemoteFor(path, key) {
444
398
  return (cloneRemotes(path) || []).find((r) => sameRepoKey(r.key, key))?.name ?? null;
445
399
  }
446
400
 
447
- /** Two repo keys name the same repository. Hosted keys compare literally; `local/<abs>`
448
- * keys compare by realpath when the path exists (macOS tmpdir → /private/var…). */
449
- function sameRepoKey(a, b) {
450
- if (a === b) return true;
451
- if (!a.startsWith("local/") || !b.startsWith("local/")) return false;
452
- const real = (k) => { try { return realpathSync(k.slice("local/".length)); } catch { return k.slice("local/".length); } };
453
- return real(a) === real(b);
454
- }
455
401
 
456
- /** Verify `path` is the clone of `key`: it exists, is a directory, is a Git repo, and
457
- * one of its remotes parses to `key`. Anything else → E_CLONE_MISMATCH { path, expected,
458
- * found } — the operator pointed the kernel at the wrong place; it never works there. */
459
- export function verifyMemberClone(path, key, { via } = {}) {
460
- 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 });
461
- let st; try { st = statSync(path); } catch { throw mismatch(null, "the path does not exist"); }
462
- if (!st.isDirectory()) throw mismatch(null, "not a directory");
463
- const found = cloneRemoteKeys(path);
464
- if (found === null) throw mismatch(null, "not a Git repository");
465
- if (!found.some((k) => sameRepoKey(k, key))) throw mismatch(found, found.length ? "no remote names it" : "it has no remotes");
466
- return path;
467
- }
468
402
 
469
- /**
470
- * Where the work target of a PREPARED spawn lives — the member clone of the soul's
471
- * repo on this machine (design doc §4; decision 9: the work target is the only thing
472
- * that needs a clone). In order:
473
- * 1. `explicit` (`--repo`) — the operator's word; relative to the deployment; not
474
- * verified against the member (an explicit --repo may deliberately point elsewhere);
475
- * 2. `oats-local.yaml` `clones: { <repo key>: <path> }` — the key as written is
476
- * normalised through parseRepoRef so `git:…`, `https://…`, `git@…` spellings match;
477
- * 3. `<deployment>/<member name>` (`agents` → `agents-repo`);
478
- * 4. null — nothing on this machine.
479
- * A path found by (2) or (3) is VERIFIED: a directory, a Git repo, one remote parsing to
480
- * the member's key → else E_CLONE_MISMATCH. A `clones:` entry whose path is absent is a
481
- * mismatch too (the operator named it; "missing" would hide the typo).
482
- * Returns an absolute path or null.
483
- */
484
- export function resolveMemberClone(prepared, { explicit } = {}) {
485
- const deployment = resolvePath(prepared?.deployment ?? process.cwd());
486
- if (typeof explicit === "string" && explicit.trim()) return isAbsolute(explicit) ? resolvePath(explicit) : resolvePath(deployment, explicit);
487
- const key = prepared?.soulEntry?.repoKey;
488
- if (typeof key !== "string" || !key) return null;
489
- return memberCloneOf(deployment, prepared?.local, key).path;
490
- }
491
403
 
492
- /** Steps 2–4 of resolveMemberClone for one member, naming the rule that found it (feature desktop-facts):
493
- * → { path, rule: "clones" | "convention" } | { path: null, rule: null }; a named or conventional path that
494
- * is not the member's clone is E_CLONE_MISMATCH, as for a spawn. */
495
- export function memberCloneOf(deployment, local, key) {
496
- const clones = local?.clones;
497
- if (clones && typeof clones === "object") {
498
- for (const [written, value] of Object.entries(clones)) {
499
- if (!sameRepoKey(canonicalCloneKey(written), key)) continue;
500
- 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:" });
501
- const path = isAbsolute(value) ? resolvePath(value) : resolvePath(deployment, value);
502
- return { path: verifyMemberClone(path, key, { via: `oats-local.yaml clones: ${written}` }), rule: "clones" };
503
- }
504
- }
505
- const convention = conventionCloneDir(deployment, key);
506
- if (!existsSync(convention)) return { path: null, rule: null };
507
- return { path: verifyMemberClone(convention, key, { via: "convention path" }), rule: "convention" };
508
- }
509
404
 
510
405
  /** The clone url of the soul's member as the workspace names it (for remedies). */
511
406
  function memberUrlOf(prepared, key) {
@@ -593,65 +488,9 @@ export async function prepareFirstProviding(contextDir, provides, { remoteOption
593
488
  return { prepared: null, skipped };
594
489
  }
595
490
 
596
- /** E_REMOTE_UNREADABLE reasons (lib/remote.mjs classifyRemoteFailure) that mean "the
597
- * operator's access context cannot see this host" — the ONLY reasons that turn a
598
- * workspace spawn into the standalone view. `network` / `timeout` are transient: the
599
- * workspace exists and is ours; a spawn must not quietly degrade to a standalone one. */
600
- const ACCESS_REASONS = new Set(["auth", "not-found"]);
601
- const isAccessFailure = (e) => e?.code === "E_REMOTE_UNREADABLE" && ACCESS_REASONS.has(e?.details?.reason ?? e?.provenance?.reason);
602
491
 
603
- /** The deployment's lock, or null when it has none (an unreadable lock is E_LOCK_SCHEMA). */
604
- export function deploymentLock(deployment) {
605
- return readLockIfPresent(deployment);
606
- }
607
492
 
608
- /** Decision 10: a standalone view is a MEMBER whose workspace cannot be read — the
609
- * repo must declare that workspace (oats-membership.yaml). A lone repo with no
610
- * backlink is not a member of anything and never becomes a capability source. */
611
- function requireMembership(repo, ref) {
612
- if (repo.membership) return;
613
- throw err("E_MEMBERSHIP_UNCONFIRMED", `a standalone view is a MEMBER whose workspace cannot be read; ${repo.key} declares no workspace (no oats-membership.yaml at ${String(repo.commit).slice(0, 12)})`, { key: repo.key, commit: repo.commit, ref, reason: "no-backlink" });
614
- }
615
493
 
616
- /**
617
- * Discover the workspace named by oats-local.yaml — or, when that ref is a REPO
618
- * whose workspace cannot be read (decision 10, the standalone case: a public
619
- * member of a privately hosted workspace), fall back to the repo's own souls and
620
- * capabilities. `standalone: <repo ref>` in oats-local.yaml asks for the standalone
621
- * view explicitly (no workspace lookup at all) — the repo must still be a member
622
- * (carry oats-membership.yaml), exactly as on the fallback path.
623
- *
624
- * A standalone result carries `standalone: true` and `standaloneReason`:
625
- * "explicit" — oats-local.yaml said `standalone:`;
626
- * "unreadable-host" — `workspace:` named a member whose declared host is not
627
- * readable in this access context (auth / not-found).
628
- * A transient failure reading the host (network, timeout) is rethrown as-is.
629
- */
630
- export async function discoverOrStandalone(local, { lock, deployment, remoteOptions, remote } = {}) {
631
- const ro = { remoteOptions, remote };
632
- // Package souls are listed from the deployment's lock (the `lock` given, else `<deployment>/oats-lock.json`).
633
- if (lock === undefined) lock = typeof deployment === "string" ? deploymentLock(deployment) : null;
634
- if (typeof local.standalone === "string" && local.standalone) {
635
- const repo = await discoverRepo(local.standalone, ro);
636
- requireMembership(repo, local.standalone);
637
- return { ...standaloneRepo(local.standalone, repo.commit, repo, { remote }), standaloneReason: "explicit" };
638
- }
639
- try { return await discoverWorkspace(local.workspace, { local, lock, ...ro }); }
640
- catch (e) {
641
- if (e?.code !== "E_WORKSPACE_SCHEMA" || e?.details?.notAHost !== true) throw e;
642
- // The ref is a repository without oats-workspace.yaml: is it a member whose
643
- // workspace we cannot read? Then the standalone view is what the operator gets.
644
- const repo = await discoverRepo(local.workspace, ro);
645
- if (!repo.membership) throw e;
646
- try { return await discoverWorkspace(repo.membership.workspace, { local, lock, ...ro }); }
647
- catch (inner) {
648
- // Only an ACCESS failure on the host means "standalone"; anything else
649
- // (network, timeout, a broken workspace file) is the caller's to see.
650
- if (!isAccessFailure(inner)) throw inner;
651
- return { ...standaloneRepo(local.workspace, repo.commit, repo, { remote }), standaloneReason: "unreadable-host", hostFailure: { code: inner.code, reason: inner.details?.reason ?? inner.provenance?.reason ?? null, url: inner.details?.url ?? inner.provenance?.url ?? null } };
652
- }
653
- }
654
- }
655
494
 
656
495
  /** Materialize a prepared resolution into `home`. Called by spawnInstance after
657
496
  * the home directory exists and before the harness is launched. `prepared.blocks`
@@ -62,7 +62,8 @@ import { oatsError } from "./errors.mjs";
62
62
  import * as defaultRemote from "./remote.mjs";
63
63
  import { renderInstructionText } from "./instruction-composition.mjs";
64
64
  import { DEFAULT_PACKAGE_PATH, validateLock } from "./packages.mjs";
65
- import { memberRowByKey } from "./workspace.mjs";
65
+ import { clone, plainObject } from "./drift.mjs";
66
+ export { driftOf, soulDriftOf } from "./drift.mjs";
66
67
 
67
68
  export const MODULES_DIR = join(".oats", "modules");
68
69
  export const SKILLS_DIR = join(".agents", "skills");
@@ -78,8 +79,6 @@ function fail(code, message, details) {
78
79
  if (details) e.details = details;
79
80
  return e;
80
81
  }
81
- const plainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
82
- const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
83
82
 
84
83
  /* ───────────────────────────── validation ─────────────────────────────── */
85
84
 
@@ -761,91 +760,7 @@ function linkPresent(path) {
761
760
 
762
761
  /* ───────────────────────────── driftOf ─────────────────────────────── */
763
762
 
764
- /**
765
- * driftOf(instanceJson, discovery, { lock } = {})
766
- * → [{ module, from, recorded: { repoKey, commit }, current: { commit } | null, status: "current"|"moved"|"missing", reason? }]
767
- *
768
- * Member modules: the confirmed member row for `repoKey` in `discovery.members` is the current
769
- * state — unconfirmed/absent → "missing" (reason "unconfirmed"); the capability gone from the
770
- * member → "missing" (reason "capability-absent"); a different commit → "moved"; else "current".
771
- * Package modules are pinned by version: without a lock they are "current"; with one, the lock's
772
- * entry decides — absent package or capability → "missing", another commit → "moved".
773
- */
774
- export function driftOf(instanceJson, discovery, { lock } = {}) {
775
- const modules = plainObject(instanceJson?.modules) ? instanceJson.modules : {};
776
- const members = Array.isArray(discovery?.members) ? discovery.members : [];
777
- const rows = [];
778
- for (const name of Object.keys(modules).sort()) {
779
- const rec = modules[name] || {};
780
- const from = plainObject(rec.from) ? rec.from : {};
781
- const commit = typeof rec.commit === "string" ? rec.commit : (typeof from.commit === "string" ? from.commit : null);
782
- if (from.kind === "package") {
783
- const recorded = { repoKey: from.repoKey ?? null, package: from.package ?? null, version: from.version ?? null, commit };
784
- if (!plainObject(lock?.packages)) { rows.push({ module: name, from: clone(from), recorded, current: commit ? { commit } : null, status: "current" }); continue; }
785
- const entry = lock.packages[from.package];
786
- if (!entry) { rows.push({ module: name, from: clone(from), recorded, current: null, status: "missing", reason: "package-absent" }); continue; }
787
- if (Array.isArray(entry.capabilities) && !entry.capabilities.includes(name)) {
788
- rows.push({ module: name, from: clone(from), recorded, current: { commit: entry.commit, version: entry.version }, status: "missing", reason: "capability-absent" }); continue;
789
- }
790
- rows.push({ module: name, from: clone(from), recorded, current: { commit: entry.commit, version: entry.version }, status: entry.commit === commit ? "current" : "moved" });
791
- continue;
792
- }
793
- const repoKey = typeof from.repoKey === "string" ? from.repoKey : null;
794
- const recorded = { repoKey, commit };
795
- const member = repoKey ? memberRowByKey(members, repoKey) : null;
796
- if (!member || !member.confirmed || typeof member.commit !== "string") {
797
- rows.push({ module: name, from: clone(from), recorded, current: null, status: "missing", reason: member ? (member.reason || "unconfirmed") : "unconfirmed" });
798
- continue;
799
- }
800
- const cap = Array.isArray(member.capabilities) ? member.capabilities.find((c) => c && c.name === name) : null;
801
- if (!cap) { rows.push({ module: name, from: clone(from), recorded, current: { commit: member.commit }, status: "missing", reason: "capability-absent" }); continue; }
802
- // `version` (feature desktop-facts): the member capability's manifest version now, beside the commit.
803
- 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" });
804
- }
805
- return rows;
806
- }
807
763
 
808
- /**
809
- * soulDriftOf(instanceJson, discovery)
810
- * → { name, repoKey, commit, current: { commit } | null, status: "current"|"moved"|"missing", reason? } | null
811
- *
812
- * Decision 17 for the SOUL SOURCE: a workspace spawn records `instance.json.workspace.soul =
813
- * { repoKey, commit }` (the member and commit the soul was fetched from). The member row
814
- * for `repoKey` in `discovery.members` is the current state: a different commit → "moved", the
815
- * soul gone from the member → "missing" (reason "soul-absent"), no usable row → "missing"
816
- * (reason "unconfirmed" / the row's reason). A standalone view's own member row is unconfirmed
817
- * by construction (reason "cannot-read") yet carries the repo's current commit — it is compared,
818
- * not reported missing. Returns null for a home without a recorded workspace soul (classic).
819
- * A PACKAGE soul (`workspace.soul.package`) is compared with the discovery's package souls: the
820
- * pin moved → "moved"; the package no longer locked/declared → "missing" ("package-absent"); the
821
- * soul no longer shipped by the package → "missing" ("soul-absent").
822
- */
823
- export function soulDriftOf(instanceJson, discovery) {
824
- const soul = plainObject(instanceJson?.workspace) && plainObject(instanceJson.workspace.soul) ? instanceJson.workspace.soul : null;
825
- if (!soul || typeof soul.repoKey !== "string") return null;
826
- const name = typeof instanceJson.agent === "string" ? instanceJson.agent : (typeof instanceJson.soul === "string" ? instanceJson.soul : null);
827
- const commit = typeof soul.commit === "string" ? soul.commit : null;
828
- if (plainObject(soul.package) && typeof soul.package.id === "string") {
829
- // A package soul: "moved" means the package pin moved (another version/commit is locked now).
830
- const pkg = { package: soul.package.id, version: soul.package.version ?? null };
831
- const soulName = typeof soul.name === "string" ? soul.name : name;
832
- const base = { name: soulName, repoKey: soul.repoKey, commit, ...pkg };
833
- const listed = Array.isArray(discovery?.packageSouls) ? discovery.packageSouls.filter((s) => s && s.package === soul.package.id) : [];
834
- const now = listed.find((s) => s.name === soulName) || null;
835
- if (!now) return { ...base, current: null, status: "missing", reason: listed.length ? "soul-absent" : "package-absent" };
836
- return { ...base, current: { commit: now.commit, version: now.version }, status: now.commit === commit ? "current" : "moved" };
837
- }
838
- const members = Array.isArray(discovery?.members) ? discovery.members : [];
839
- const member = memberRowByKey(members, soul.repoKey);
840
- const standaloneOwn = discovery?.standalone === true && member && member.key === discovery.key && typeof member.commit === "string";
841
- const base = { name, repoKey: soul.repoKey, commit };
842
- if (!member || (!member.confirmed && !standaloneOwn) || typeof member.commit !== "string") {
843
- return { ...base, current: null, status: "missing", reason: member ? (member.reason || "unconfirmed") : "unconfirmed" };
844
- }
845
- const present = name === null || (Array.isArray(member.souls) && member.souls.some((s) => s && s.name === name));
846
- if (!present) return { ...base, current: { commit: member.commit }, status: "missing", reason: "soul-absent" };
847
- return { ...base, current: { commit: member.commit }, status: member.commit === commit ? "current" : "moved" };
848
- }
849
764
 
850
765
  /** Read the modules recorded in an instance home (→ {} when absent). */
851
766
  export function recordedModules(home) {
@@ -0,0 +1,188 @@
1
+ /** A deployment's discovery (its workspace, or a standalone repository) and the local clone of a
2
+ * member: found by convention or by `clones:`, verified against the member's remote. A leaf
3
+ * (awebai/oats#1630): `oats status` and `workspace status` read them without loading
4
+ * instance-resolution.mjs and the spawn machinery it brings; it imports what it still uses and
5
+ * re-exports what it exported. */
6
+ import { existsSync, statSync, realpathSync } from "node:fs";
7
+ import { resolve as resolvePath, isAbsolute, join } from "node:path";
8
+ import { oatsError } from "./errors.mjs";
9
+ import { discoverRepo, standaloneRepo, discoverWorkspace } from "./workspace.mjs";
10
+ import { memberNameOf } from "./teams.mjs";
11
+ import { parseRepoRef } from "./remote.mjs";
12
+ import { spawnSync } from "node:child_process";
13
+ import { readLockIfPresent } from "./packages.mjs";
14
+
15
+ function err(code, message, details) { const e = oatsError(code, message, details); e.details = details; return e; }
16
+
17
+ /** The convention path of a member's clone: `<deployment>/<member name>` — except a
18
+ * member called `agents`, which is cloned as `agents-repo/` because `<deployment>/agents/`
19
+ * is the instance root (design doc §4; matches onboard's cloneDirOf). */
20
+ export function conventionCloneDir(deployment, key) {
21
+ const name = memberNameOf(key);
22
+ return join(deployment, name === "agents" ? "agents-repo" : name);
23
+ }
24
+
25
+ /** Normalise a key an operator may have WRITTEN in `clones:` — the canonical key
26
+ * (`github.com/org/repo`), or any ref form parseRepoRef understands (`git:…`,
27
+ * `https://…`, `git@host:…`, `/abs/bare.git`) — to the canonical key. A key that
28
+ * parses no way is returned as written (it can then only match literally). */
29
+ export function canonicalCloneKey(written) {
30
+ const s = String(written).trim();
31
+ if (s.startsWith("local/")) return s; // a local key is already canonical
32
+ for (const candidate of [s, `git:${s}`]) {
33
+ try { return parseRepoRef(candidate).key; } catch { /* next form */ }
34
+ }
35
+ return s;
36
+ }
37
+
38
+ /** The remotes a clone carries (any remote, not only origin), each with its url parsed
39
+ * to a repo key: [{ name, key }]. Not a git repo → null. */
40
+ function cloneRemotes(path) {
41
+ const git = (argv) => spawnSync("git", ["-C", path, ...argv], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 10_000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
42
+ const inside = git(["rev-parse", "--git-dir"]);
43
+ if (inside.status !== 0) return null;
44
+ // -z: each entry is `<key>\n<value>\0`, so a value holding a newline cannot read as another entry.
45
+ const cfg = git(["config", "-z", "--get-regexp", "^remote\\..*\\.url$"]);
46
+ const remotes = [];
47
+ if (cfg.status === 0) {
48
+ for (const entry of cfg.stdout.split("\0")) {
49
+ const nl = entry.indexOf("\n");
50
+ if (nl < 0) continue;
51
+ const key = entry.slice(0, nl), url = entry.slice(nl + 1).trim();
52
+ if (!url) continue;
53
+ const name = key.slice("remote.".length, -".url".length);
54
+ try { remotes.push({ name, key: parseRepoRef(url).key }); } catch { remotes.push({ name, key: `?/${url}` }); }
55
+ }
56
+ }
57
+ return remotes;
58
+ }
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;
63
+ }
64
+
65
+ /** Two repo keys name the same repository. Hosted keys compare literally; `local/<abs>`
66
+ * keys compare by realpath when the path exists (macOS tmpdir → /private/var…). */
67
+ function sameRepoKey(a, b) {
68
+ if (a === b) return true;
69
+ if (!a.startsWith("local/") || !b.startsWith("local/")) return false;
70
+ const real = (k) => { try { return realpathSync(k.slice("local/".length)); } catch { return k.slice("local/".length); } };
71
+ return real(a) === real(b);
72
+ }
73
+
74
+ /** Verify `path` is the clone of `key`: it exists, is a directory, is a Git repo, and
75
+ * one of its remotes parses to `key`. Anything else → E_CLONE_MISMATCH { path, expected,
76
+ * found } — the operator pointed the kernel at the wrong place; it never works there. */
77
+ export function verifyMemberClone(path, key, { via } = {}) {
78
+ 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
+ let st; try { st = statSync(path); } catch { throw mismatch(null, "the path does not exist"); }
80
+ if (!st.isDirectory()) throw mismatch(null, "not a directory");
81
+ const found = cloneRemoteKeys(path);
82
+ if (found === null) throw mismatch(null, "not a Git repository");
83
+ if (!found.some((k) => sameRepoKey(k, key))) throw mismatch(found, found.length ? "no remote names it" : "it has no remotes");
84
+ return path;
85
+ }
86
+
87
+ /**
88
+ * Where the work target of a PREPARED spawn lives — the member clone of the soul's
89
+ * repo on this machine (design doc §4; decision 9: the work target is the only thing
90
+ * that needs a clone). In order:
91
+ * 1. `explicit` (`--repo`) — the operator's word; relative to the deployment; not
92
+ * verified against the member (an explicit --repo may deliberately point elsewhere);
93
+ * 2. `oats-local.yaml` `clones: { <repo key>: <path> }` — the key as written is
94
+ * normalised through parseRepoRef so `git:…`, `https://…`, `git@…` spellings match;
95
+ * 3. `<deployment>/<member name>` (`agents` → `agents-repo`);
96
+ * 4. null — nothing on this machine.
97
+ * A path found by (2) or (3) is VERIFIED: a directory, a Git repo, one remote parsing to
98
+ * the member's key → else E_CLONE_MISMATCH. A `clones:` entry whose path is absent is a
99
+ * mismatch too (the operator named it; "missing" would hide the typo).
100
+ * Returns an absolute path or null.
101
+ */
102
+ export function resolveMemberClone(prepared, { explicit } = {}) {
103
+ const deployment = resolvePath(prepared?.deployment ?? process.cwd());
104
+ if (typeof explicit === "string" && explicit.trim()) return isAbsolute(explicit) ? resolvePath(explicit) : resolvePath(deployment, explicit);
105
+ const key = prepared?.soulEntry?.repoKey;
106
+ if (typeof key !== "string" || !key) return null;
107
+ return memberCloneOf(deployment, prepared?.local, key).path;
108
+ }
109
+
110
+ /** Steps 2–4 of resolveMemberClone for one member, naming the rule that found it (feature desktop-facts):
111
+ * → { 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) {
114
+ const clones = local?.clones;
115
+ if (clones && typeof clones === "object") {
116
+ for (const [written, value] of Object.entries(clones)) {
117
+ if (!sameRepoKey(canonicalCloneKey(written), key)) continue;
118
+ 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
+ const path = isAbsolute(value) ? resolvePath(value) : resolvePath(deployment, value);
120
+ return { path: verifyMemberClone(path, key, { via: `oats-local.yaml clones: ${written}` }), rule: "clones" };
121
+ }
122
+ }
123
+ const convention = conventionCloneDir(deployment, key);
124
+ if (!existsSync(convention)) return { path: null, rule: null };
125
+ return { path: verifyMemberClone(convention, key, { via: "convention path" }), rule: "convention" };
126
+ }
127
+
128
+ /** E_REMOTE_UNREADABLE reasons (lib/remote.mjs classifyRemoteFailure) that mean "the
129
+ * operator's access context cannot see this host" — the ONLY reasons that turn a
130
+ * workspace spawn into the standalone view. `network` / `timeout` are transient: the
131
+ * workspace exists and is ours; a spawn must not quietly degrade to a standalone one. */
132
+ const ACCESS_REASONS = new Set(["auth", "not-found"]);
133
+ const isAccessFailure = (e) => e?.code === "E_REMOTE_UNREADABLE" && ACCESS_REASONS.has(e?.details?.reason ?? e?.provenance?.reason);
134
+
135
+ /** The deployment's lock, or null when it has none (an unreadable lock is E_LOCK_SCHEMA). */
136
+ export function deploymentLock(deployment) {
137
+ return readLockIfPresent(deployment);
138
+ }
139
+
140
+ /** Decision 10: a standalone view is a MEMBER whose workspace cannot be read — the
141
+ * repo must declare that workspace (oats-membership.yaml). A lone repo with no
142
+ * backlink is not a member of anything and never becomes a capability source. */
143
+ function requireMembership(repo, ref) {
144
+ if (repo.membership) return;
145
+ throw err("E_MEMBERSHIP_UNCONFIRMED", `a standalone view is a MEMBER whose workspace cannot be read; ${repo.key} declares no workspace (no oats-membership.yaml at ${String(repo.commit).slice(0, 12)})`, { key: repo.key, commit: repo.commit, ref, reason: "no-backlink" });
146
+ }
147
+
148
+ /**
149
+ * Discover the workspace named by oats-local.yaml — or, when that ref is a REPO
150
+ * whose workspace cannot be read (decision 10, the standalone case: a public
151
+ * member of a privately hosted workspace), fall back to the repo's own souls and
152
+ * capabilities. `standalone: <repo ref>` in oats-local.yaml asks for the standalone
153
+ * view explicitly (no workspace lookup at all) — the repo must still be a member
154
+ * (carry oats-membership.yaml), exactly as on the fallback path.
155
+ *
156
+ * A standalone result carries `standalone: true` and `standaloneReason`:
157
+ * "explicit" — oats-local.yaml said `standalone:`;
158
+ * "unreadable-host" — `workspace:` named a member whose declared host is not
159
+ * readable in this access context (auth / not-found).
160
+ * A transient failure reading the host (network, timeout) is rethrown as-is.
161
+ */
162
+ export async function discoverOrStandalone(local, { lock, deployment, remoteOptions, remote } = {}) {
163
+ const ro = { remoteOptions, remote };
164
+ // Package souls are listed from the deployment's lock (the `lock` given, else `<deployment>/oats-lock.json`).
165
+ if (lock === undefined) lock = typeof deployment === "string" ? deploymentLock(deployment) : null;
166
+ if (typeof local.standalone === "string" && local.standalone) {
167
+ const repo = await discoverRepo(local.standalone, ro);
168
+ requireMembership(repo, local.standalone);
169
+ return { ...standaloneRepo(local.standalone, repo.commit, repo, { remote }), standaloneReason: "explicit" };
170
+ }
171
+ try { return await discoverWorkspace(local.workspace, { local, lock, ...ro }); }
172
+ catch (e) {
173
+ if (e?.code !== "E_WORKSPACE_SCHEMA" || e?.details?.notAHost !== true) throw e;
174
+ // The ref is a repository without oats-workspace.yaml: is it a member whose
175
+ // workspace we cannot read? Then the standalone view is what the operator gets.
176
+ const repo = await discoverRepo(local.workspace, ro);
177
+ if (!repo.membership) throw e;
178
+ try { return await discoverWorkspace(repo.membership.workspace, { local, lock, ...ro }); }
179
+ catch (inner) {
180
+ // Only an ACCESS failure on the host means "standalone"; anything else
181
+ // (network, timeout, a broken workspace file) is the caller's to see.
182
+ if (!isAccessFailure(inner)) throw inner;
183
+ return { ...standaloneRepo(local.workspace, repo.commit, repo, { remote }), standaloneReason: "unreadable-host", hostFailure: { code: inner.code, reason: inner.details?.reason ?? inner.provenance?.reason ?? null, url: inner.details?.url ?? inner.provenance?.url ?? null } };
184
+ }
185
+ }
186
+ }
187
+
188
+ export { cloneRemotes, err, sameRepoKey };
@@ -0,0 +1,93 @@
1
+ /** The official package catalog (package-catalog.json, or the file OATS_PACKAGE_CATALOG names) and the slot names a
2
+ * soul's capabilities fill (LAYERS). A leaf (awebai/oats#1630): `oats workspace status` reads them
3
+ * without loading core.mjs, which imports what it still uses and re-exports what it exported. */
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { recordLocalInput } from "./local-inputs.mjs";
7
+ import { oatsError } from "./errors.mjs";
8
+ import { parseStrictJson, lineAt } from "./canonical-json.mjs";
9
+ import { PKG_ROOT } from "./version.mjs";
10
+
11
+ /** The package and capability id grammar (namespaced, lowercase): an id names a
12
+ * directory (a home's module copy), so no path spelling fits it. */
13
+ const PACKAGE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
14
+
15
+ // ---------- capability slots ----------
16
+ export const LAYERS = ["knowledge", "messaging", "tasks"];
17
+
18
+ /** Official package catalog: identity + discovery ONLY — resolving through it
19
+ * never advances a lock and never grants executable trust (contract §1).
20
+ * Workstream 3 seeds the kernel-bundled catalog; OATS_PACKAGE_CATALOG points
21
+ * tests/deployments at an alternate catalog JSON ({ packages: { <id>: { url, ref? } } }). */
22
+ export function officialPackageCatalog() {
23
+ return readCatalogFile().packages;
24
+ }
25
+ /** Parse the catalog file once: { packages: { <id>: { url, ref?, path? } },
26
+ * capabilities?: { <legacy capability id>: <package id> } }. Both maps are
27
+ * returned with a null prototype so inherited Object.prototype names can never
28
+ * impersonate a catalog entry. */
29
+ function readCatalogFile() {
30
+ const file = officialCatalogFile();
31
+ const empty = { packages: Object.create(null), capabilities: Object.create(null), file };
32
+ // An OATS_PACKAGE_CATALOG override is local configuration (observation.localRevision); the bundled
33
+ // catalog belongs to the kernel install.
34
+ const override = !!process.env.OATS_PACKAGE_CATALOG;
35
+ if (!existsSync(file)) { if (override) recordLocalInput(file, null); return empty; }
36
+ const text = readFileSync(file, "utf8");
37
+ if (override) recordLocalInput(file, text);
38
+ return parsePackageCatalog(text, file);
39
+ }
40
+ /** A package catalog's text, parsed and checked as the kernel reads it (named `file` in errors):
41
+ * { packages, capabilities, file }, both maps null-prototype; invalid-source when it is broken. */
42
+ export function parsePackageCatalog(text, file) {
43
+ let doc;
44
+ try { doc = JSON.parse(text); }
45
+ catch (e) {
46
+ // JSON.parse does not say where; the kernel's strict reader (same grammar) locates the error.
47
+ let line;
48
+ try { parseStrictJson(text, { maxBytes: 64 * 1024 * 1024 }); } catch (s) { if (Number.isInteger(s.provenance?.offset)) line = lineAt(text, s.provenance.offset); }
49
+ throw oatsError("invalid-source", `broken package catalog ${file}${line ? ` (line ${line})` : ""}: ${e.message}`);
50
+ }
51
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw oatsError("invalid-source", `broken package catalog ${file}: root must be a JSON object`);
52
+ const out = { packages: Object.create(null), capabilities: Object.create(null), file };
53
+ const packages = doc.packages;
54
+ if (packages !== undefined) {
55
+ if (packages === null || typeof packages !== "object" || Array.isArray(packages)) throw oatsError("invalid-source", `broken package catalog ${file}: "packages" must be an object map`);
56
+ for (const [id, entry] of Object.entries(packages)) out.packages[id] = entry;
57
+ }
58
+ // Capability aliases (0.19.1 migration contract): legacy capability id →
59
+ // official package id. Identity mappings (package id == capability id) need
60
+ // no entry; an alias exists for capabilities a package exports under another
61
+ // package identity (oats.developer is exported by package oats.engineering).
62
+ //
63
+ // The object form may also carry "capability": the id the package exports
64
+ // TODAY in place of the legacy id (a RENAMING alias, the oas.* → oats.*
65
+ // migration contract). A plain alias promises the package exports the legacy
66
+ // id itself; a renaming alias promises it exports the successor instead.
67
+ const aliases = doc.capabilities;
68
+ if (aliases !== undefined) {
69
+ if (aliases === null || typeof aliases !== "object" || Array.isArray(aliases)) throw oatsError("invalid-source", `broken package catalog ${file}: "capabilities" must be a map of capability id → package id`);
70
+ for (const [capId, target] of Object.entries(aliases)) {
71
+ const obj = typeof target === "string" ? { package: target } : (target && typeof target === "object" && !Array.isArray(target) ? target : undefined);
72
+ const pkgId = obj?.package;
73
+ if (typeof pkgId !== "string" || !PACKAGE_ID_RE.test(pkgId)) throw oatsError("invalid-source", `broken package catalog ${file}: capability alias "${capId}" must name a package id (string, or { "package": "<id>" })`);
74
+ if (!PACKAGE_ID_RE.test(capId)) throw oatsError("invalid-source", `broken package catalog ${file}: capability alias key "${capId}" is not a valid capability id`);
75
+ const renamed = obj.capability;
76
+ if (renamed !== undefined && (typeof renamed !== "string" || !PACKAGE_ID_RE.test(renamed))) throw oatsError("invalid-source", `broken package catalog ${file}: capability alias "${capId}" has an invalid "capability" rename target`);
77
+ out.capabilities[capId] = renamed && renamed !== capId ? { package: pkgId, capability: renamed } : pkgId;
78
+ }
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** The effective official catalog file: `OATS_PACKAGE_CATALOG`, else the bundled one. */
84
+ export function officialCatalogFile() {
85
+ return process.env.OATS_PACKAGE_CATALOG || join(PKG_ROOT, "package-catalog.json");
86
+ }
87
+
88
+ /** The catalog's legacy-capability → official-package aliases (null-prototype). */
89
+ export function officialCapabilityAliases() {
90
+ return readCatalogFile().capabilities;
91
+ }
92
+
93
+ export { PACKAGE_ID_RE, readCatalogFile };