@awebai/oats 0.69.4 → 0.69.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/bin/oats.mjs +141 -364
  2. package/docs/configuration.md +12 -0
  3. package/docs/design/2026-09-26-okf-knowledge-operations.md +2 -0
  4. package/docs/design/2026-10-29-warm-reader.md +261 -0
  5. package/docs/design/README.md +4 -0
  6. package/docs/desktop-cli-api.md +258 -13
  7. package/docs/execution-targets.md +36 -5
  8. package/docs/implementation.md +34 -9
  9. package/docs/integrations.md +2 -2
  10. package/docs/knowledge.md +18 -8
  11. package/docs/named-test-runs.md +4 -0
  12. package/docs/official-catalog.md +5 -5
  13. package/docs/packages.md +14 -14
  14. package/docs/release-notes/v0.69.5.md +146 -0
  15. package/docs/release-notes/v0.69.6.md +165 -0
  16. package/docs/schedules.md +8 -1
  17. package/docs/tui.md +23 -5
  18. package/docs/upgrading.md +20 -5
  19. package/docs/workspaces.md +2 -2
  20. package/lib/agents-root.mjs +51 -0
  21. package/lib/argv.mjs +41 -0
  22. package/lib/automation-api.mjs +7 -0
  23. package/lib/automation-scope.mjs +37 -0
  24. package/lib/automations.mjs +63 -12
  25. package/lib/captured-context.mjs +12 -0
  26. package/lib/compile-cache.mjs +36 -0
  27. package/lib/core.mjs +39 -1348
  28. package/lib/deployment-path.mjs +127 -0
  29. package/lib/deployments.mjs +2 -2
  30. package/lib/drift.mjs +95 -0
  31. package/lib/hot-reads.mjs +137 -0
  32. package/lib/install-stamp.mjs +61 -0
  33. package/lib/instance-address.mjs +21 -0
  34. package/lib/instance-events.mjs +8 -6
  35. package/lib/instance-lifecycle.mjs +4 -16
  36. package/lib/instance-listing.mjs +738 -0
  37. package/lib/instance-resolution.mjs +5 -166
  38. package/lib/kernel-features.mjs +10 -0
  39. package/lib/local-edit.mjs +1 -1
  40. package/lib/local-inputs.mjs +3 -0
  41. package/lib/materialize.mjs +2 -87
  42. package/lib/member-clone.mjs +192 -0
  43. package/lib/package-catalog.mjs +93 -0
  44. package/lib/packages.mjs +4 -24
  45. package/lib/read-call.mjs +143 -0
  46. package/lib/reader.mjs +203 -0
  47. package/lib/remote.mjs +47 -6
  48. package/lib/reserved-launch-env.mjs +20 -0
  49. package/lib/resolved-deployment.mjs +13 -5
  50. package/lib/roster-read.mjs +199 -0
  51. package/lib/schedule.mjs +5 -29
  52. package/lib/semver.mjs +12 -0
  53. package/lib/servers.mjs +10 -12
  54. package/lib/session-end.mjs +3 -2
  55. package/lib/session-input.mjs +35 -11
  56. package/lib/session-inspect.mjs +219 -0
  57. package/lib/soul-listing.mjs +216 -0
  58. package/lib/status-words.mjs +30 -0
  59. package/lib/version.mjs +9 -0
  60. package/lib/workspace-read.mjs +160 -0
  61. package/lib/write-file-atomic.mjs +28 -0
  62. package/package-catalog.json +4 -4
  63. package/package.json +1 -1
  64. package/packages/client/cli-locator.mjs +1 -0
  65. package/packages/client/cli-probe-contract.mjs +4 -2
  66. package/packages/client/deployment-observer.mjs +8 -3
  67. package/packages/client/deployment-panel.mjs +17 -1
  68. package/packages/client/deployment-read-cli.mjs +48 -27
  69. package/packages/client/own-codes.mjs +3 -0
  70. package/packages/client/warm-reader.mjs +241 -0
  71. package/packages/tui/lib/client.mjs +2 -1
  72. package/packages/tui/lib/read.mjs +59 -11
  73. package/packages/tui/lib/store.mjs +7 -3
  74. package/skills/oats-getting-started/SKILL.md +3 -3
@@ -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`
@@ -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. */
@@ -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,192 @@
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. `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;
67
+ }
68
+
69
+ /** Two repo keys name the same repository. Hosted keys compare literally; `local/<abs>`
70
+ * keys compare by realpath when the path exists (macOS tmpdir → /private/var…). */
71
+ function sameRepoKey(a, b) {
72
+ if (a === b) return true;
73
+ if (!a.startsWith("local/") || !b.startsWith("local/")) return false;
74
+ const real = (k) => { try { return realpathSync(k.slice("local/".length)); } catch { return k.slice("local/".length); } };
75
+ return real(a) === real(b);
76
+ }
77
+
78
+ /** Verify `path` is the clone of `key`: it exists, is a directory, is a Git repo, and
79
+ * one of its remotes parses to `key`. Anything else → E_CLONE_MISMATCH { path, expected,
80
+ * found } — the operator pointed the kernel at the wrong place; it never works there. */
81
+ export function verifyMemberClone(path, key, { via, remotes } = {}) {
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 });
83
+ let st; try { st = statSync(path); } catch { throw mismatch(null, "the path does not exist"); }
84
+ if (!st.isDirectory()) throw mismatch(null, "not a directory");
85
+ const found = cloneRemoteKeys(path, remotes);
86
+ if (found === null) throw mismatch(null, "not a Git repository");
87
+ if (!found.some((k) => sameRepoKey(k, key))) throw mismatch(found, found.length ? "no remote names it" : "it has no remotes");
88
+ return path;
89
+ }
90
+
91
+ /**
92
+ * Where the work target of a PREPARED spawn lives — the member clone of the soul's
93
+ * repo on this machine (design doc §4; decision 9: the work target is the only thing
94
+ * that needs a clone). In order:
95
+ * 1. `explicit` (`--repo`) — the operator's word; relative to the deployment; not
96
+ * verified against the member (an explicit --repo may deliberately point elsewhere);
97
+ * 2. `oats-local.yaml` `clones: { <repo key>: <path> }` — the key as written is
98
+ * normalised through parseRepoRef so `git:…`, `https://…`, `git@…` spellings match;
99
+ * 3. `<deployment>/<member name>` (`agents` → `agents-repo`);
100
+ * 4. null — nothing on this machine.
101
+ * A path found by (2) or (3) is VERIFIED: a directory, a Git repo, one remote parsing to
102
+ * the member's key → else E_CLONE_MISMATCH. A `clones:` entry whose path is absent is a
103
+ * mismatch too (the operator named it; "missing" would hide the typo).
104
+ * Returns an absolute path or null.
105
+ */
106
+ export function resolveMemberClone(prepared, { explicit, remotes } = {}) {
107
+ const deployment = resolvePath(prepared?.deployment ?? process.cwd());
108
+ if (typeof explicit === "string" && explicit.trim()) return isAbsolute(explicit) ? resolvePath(explicit) : resolvePath(deployment, explicit);
109
+ const key = prepared?.soulEntry?.repoKey;
110
+ if (typeof key !== "string" || !key) return null;
111
+ return memberCloneOf(deployment, prepared?.local, key, { remotes }).path;
112
+ }
113
+
114
+ /** Steps 2–4 of resolveMemberClone for one member, naming the rule that found it (feature desktop-facts):
115
+ * → { path, rule: "clones" | "convention" } | { path: null, rule: null }; a named or conventional path that
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 } = {}) {
118
+ const clones = local?.clones;
119
+ if (clones && typeof clones === "object") {
120
+ for (const [written, value] of Object.entries(clones)) {
121
+ if (!sameRepoKey(canonicalCloneKey(written), key)) continue;
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:" });
123
+ const path = isAbsolute(value) ? resolvePath(value) : resolvePath(deployment, value);
124
+ return { path: verifyMemberClone(path, key, { via: `oats-local.yaml clones: ${written}`, remotes }), rule: "clones" };
125
+ }
126
+ }
127
+ const convention = conventionCloneDir(deployment, key);
128
+ if (!existsSync(convention)) return { path: null, rule: null };
129
+ return { path: verifyMemberClone(convention, key, { via: "convention path", remotes }), rule: "convention" };
130
+ }
131
+
132
+ /** E_REMOTE_UNREADABLE reasons (lib/remote.mjs classifyRemoteFailure) that mean "the
133
+ * operator's access context cannot see this host" — the ONLY reasons that turn a
134
+ * workspace spawn into the standalone view. `network` / `timeout` are transient: the
135
+ * workspace exists and is ours; a spawn must not quietly degrade to a standalone one. */
136
+ const ACCESS_REASONS = new Set(["auth", "not-found"]);
137
+ const isAccessFailure = (e) => e?.code === "E_REMOTE_UNREADABLE" && ACCESS_REASONS.has(e?.details?.reason ?? e?.provenance?.reason);
138
+
139
+ /** The deployment's lock, or null when it has none (an unreadable lock is E_LOCK_SCHEMA). */
140
+ export function deploymentLock(deployment) {
141
+ return readLockIfPresent(deployment);
142
+ }
143
+
144
+ /** Decision 10: a standalone view is a MEMBER whose workspace cannot be read — the
145
+ * repo must declare that workspace (oats-membership.yaml). A lone repo with no
146
+ * backlink is not a member of anything and never becomes a capability source. */
147
+ function requireMembership(repo, ref) {
148
+ if (repo.membership) return;
149
+ 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" });
150
+ }
151
+
152
+ /**
153
+ * Discover the workspace named by oats-local.yaml — or, when that ref is a REPO
154
+ * whose workspace cannot be read (decision 10, the standalone case: a public
155
+ * member of a privately hosted workspace), fall back to the repo's own souls and
156
+ * capabilities. `standalone: <repo ref>` in oats-local.yaml asks for the standalone
157
+ * view explicitly (no workspace lookup at all) — the repo must still be a member
158
+ * (carry oats-membership.yaml), exactly as on the fallback path.
159
+ *
160
+ * A standalone result carries `standalone: true` and `standaloneReason`:
161
+ * "explicit" — oats-local.yaml said `standalone:`;
162
+ * "unreadable-host" — `workspace:` named a member whose declared host is not
163
+ * readable in this access context (auth / not-found).
164
+ * A transient failure reading the host (network, timeout) is rethrown as-is.
165
+ */
166
+ export async function discoverOrStandalone(local, { lock, deployment, remoteOptions, remote } = {}) {
167
+ const ro = { remoteOptions, remote };
168
+ // Package souls are listed from the deployment's lock (the `lock` given, else `<deployment>/oats-lock.json`).
169
+ if (lock === undefined) lock = typeof deployment === "string" ? deploymentLock(deployment) : null;
170
+ if (typeof local.standalone === "string" && local.standalone) {
171
+ const repo = await discoverRepo(local.standalone, ro);
172
+ requireMembership(repo, local.standalone);
173
+ return { ...standaloneRepo(local.standalone, repo.commit, repo, { remote }), standaloneReason: "explicit" };
174
+ }
175
+ try { return await discoverWorkspace(local.workspace, { local, lock, ...ro }); }
176
+ catch (e) {
177
+ if (e?.code !== "E_WORKSPACE_SCHEMA" || e?.details?.notAHost !== true) throw e;
178
+ // The ref is a repository without oats-workspace.yaml: is it a member whose
179
+ // workspace we cannot read? Then the standalone view is what the operator gets.
180
+ const repo = await discoverRepo(local.workspace, ro);
181
+ if (!repo.membership) throw e;
182
+ try { return await discoverWorkspace(repo.membership.workspace, { local, lock, ...ro }); }
183
+ catch (inner) {
184
+ // Only an ACCESS failure on the host means "standalone"; anything else
185
+ // (network, timeout, a broken workspace file) is the caller's to see.
186
+ if (!isAccessFailure(inner)) throw inner;
187
+ 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 } };
188
+ }
189
+ }
190
+ }
191
+
192
+ export { cloneRemotes, err, sameRepoKey };