@awebai/oats 0.51.0 → 0.52.0

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 (128) hide show
  1. package/README.md +1 -0
  2. package/bin/oats.mjs +109 -37
  3. package/docs/capabilities.md +9 -2
  4. package/docs/configuration.md +134 -88
  5. package/docs/desktop-cli-api.md +927 -92
  6. package/docs/desktop-instance-start.md +56 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +144 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +66 -9
  12. package/docs/integrations.md +9 -8
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +25 -2
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/oats-local.schema.json +4 -3
  20. package/docs/official-catalog.md +4 -4
  21. package/docs/packages.md +14 -14
  22. package/docs/release-lane.md +15 -5
  23. package/docs/release-notes/v0.44.0.md +1 -1
  24. package/docs/release-notes/v0.52.0.md +933 -0
  25. package/docs/schedules.md +91 -4
  26. package/docs/souls-and-instances.md +95 -25
  27. package/docs/tui.md +152 -0
  28. package/docs/workspaces.md +2 -2
  29. package/lib/claim.mjs +186 -46
  30. package/lib/core.mjs +730 -185
  31. package/lib/errors.mjs +170 -0
  32. package/lib/harness-trust-write.mjs +68 -27
  33. package/lib/harness-trust.mjs +34 -16
  34. package/lib/instance-inspect.mjs +40 -11
  35. package/lib/instance-lifecycle.mjs +169 -47
  36. package/lib/launch-preference.mjs +16 -0
  37. package/lib/launch-prompt-completion.mjs +7 -43
  38. package/lib/launch-prompt-evidence.mjs +14 -7
  39. package/lib/launch-prompt-fixtures/README.md +86 -152
  40. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  41. package/lib/launch-prompt-fixtures.mjs +122 -109
  42. package/lib/launch-prompt-transport.mjs +2 -56
  43. package/lib/launch-prompts.mjs +102 -100
  44. package/lib/schedule-host.mjs +154 -22
  45. package/lib/schedule.mjs +73 -24
  46. package/lib/system-tools.mjs +39 -0
  47. package/lib/tmux-server-scope.mjs +62 -0
  48. package/lib/triggers.mjs +4 -4
  49. package/lib/workspace.mjs +5 -11
  50. package/lib/worktree-hooks.mjs +98 -20
  51. package/lib/worktree.mjs +83 -24
  52. package/package-catalog.json +3 -3
  53. package/package.json +7 -2
  54. package/packages/client/capability-show-contract.mjs +230 -0
  55. package/packages/client/capability-warnings-contract.mjs +57 -0
  56. package/packages/client/cli-adapter.mjs +548 -0
  57. package/packages/client/cli-environment.mjs +53 -0
  58. package/packages/client/cli-locator.mjs +253 -0
  59. package/packages/client/cli-probe-contract.mjs +47 -0
  60. package/packages/client/client-terms.mjs +60 -0
  61. package/packages/client/deployment-contract.mjs +68 -0
  62. package/packages/client/deployment-data.mjs +483 -0
  63. package/packages/client/deployment-facts.mjs +34 -0
  64. package/packages/client/deployment-label.mjs +76 -0
  65. package/packages/client/deployment-observer.mjs +89 -0
  66. package/packages/client/deployment-panel.mjs +142 -0
  67. package/packages/client/deployment-read-cli.mjs +53 -0
  68. package/packages/client/display-text.mjs +44 -0
  69. package/packages/client/harness-names.mjs +30 -0
  70. package/packages/client/inspect-contract.mjs +62 -0
  71. package/packages/client/instance-acts.mjs +54 -0
  72. package/packages/client/instance-admission.mjs +45 -0
  73. package/packages/client/instance-events-contract.mjs +74 -0
  74. package/packages/client/instance-git-contract.mjs +80 -0
  75. package/packages/client/instance-presentation.mjs +22 -0
  76. package/packages/client/instance-tree.mjs +453 -0
  77. package/packages/client/kernel-environment.mjs +11 -0
  78. package/packages/client/launch-contract.mjs +51 -0
  79. package/packages/client/launch-prompt-outcome.mjs +165 -0
  80. package/packages/client/lifecycle-cli.mjs +61 -0
  81. package/packages/client/lifecycle-contract.mjs +372 -0
  82. package/packages/client/liveness-main.mjs +10 -0
  83. package/packages/client/liveness.mjs +35 -0
  84. package/packages/client/machine-contract.mjs +123 -0
  85. package/packages/client/own-environment.mjs +22 -0
  86. package/packages/client/panel-views.mjs +286 -0
  87. package/packages/client/readiness-contract.mjs +172 -0
  88. package/packages/client/refresh-loop.mjs +52 -0
  89. package/packages/client/remote-address.mjs +126 -0
  90. package/packages/client/remote-roster.mjs +67 -0
  91. package/packages/client/roster-sections.mjs +80 -0
  92. package/packages/client/spawn-apply-cli.mjs +104 -0
  93. package/packages/client/spawn-apply-contract.mjs +183 -0
  94. package/packages/client/spawn-decision.mjs +46 -0
  95. package/packages/client/spawn-messages.mjs +119 -0
  96. package/packages/client/spawn-preview-cli.mjs +32 -0
  97. package/packages/client/spawn-preview-contract.mjs +314 -0
  98. package/packages/client/team-members.mjs +41 -0
  99. package/packages/client/team-rows.mjs +45 -0
  100. package/packages/client/terminal-contract.mjs +57 -0
  101. package/packages/client/tmux-status.mjs +66 -0
  102. package/packages/client/waiting-on-you.mjs +88 -0
  103. package/packages/client/workspace-admission.mjs +45 -0
  104. package/packages/client/workspace-cli.mjs +142 -0
  105. package/packages/client/workspace-views.mjs +147 -0
  106. package/packages/tui/README.md +46 -0
  107. package/packages/tui/bin/tui.mjs +7 -0
  108. package/packages/tui/lib/actions.mjs +29 -0
  109. package/packages/tui/lib/client.mjs +4 -0
  110. package/packages/tui/lib/main.mjs +105 -0
  111. package/packages/tui/lib/term/keys.mjs +323 -0
  112. package/packages/tui/lib/term/screen.mjs +122 -0
  113. package/packages/tui/lib/term/style.mjs +43 -0
  114. package/packages/tui/lib/term/text.mjs +49 -0
  115. package/packages/tui/lib/term/tty.mjs +168 -0
  116. package/packages/tui/lib/term/width.mjs +124 -0
  117. package/packages/tui/lib/views/frame.mjs +62 -0
  118. package/packages/tui/lib/views/help.mjs +28 -0
  119. package/packages/tui/package.json +8 -0
  120. package/skills/oats-getting-started/SKILL.md +29 -22
  121. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  122. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  123. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  124. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  125. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  126. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  127. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  128. package/lib/launch-prompt-policy.mjs +0 -87
@@ -0,0 +1,80 @@
1
+ /** Public K1 DTO checks only; no Git parsing, filesystem reads or kernel imports.
2
+ * Shared by the Desktop read boundary and its inert renderer controller. */
3
+ export const INSTANCE_GIT_MINIMUM_VERSION = '0.24.7';
4
+ export const INSTANCE_DIFF_LIMIT = 256 * 1024;
5
+ export const gitKinds = ['changed', 'renamed', 'copied', 'unmerged', 'untracked'];
6
+ const object = v => !!v && typeof v === 'object' && !Array.isArray(v);
7
+ const text = v => typeof v === 'string' && v.length > 0 && !v.includes('\0');
8
+ const nullable = v => v === null || text(v);
9
+ const count = v => Number.isSafeInteger(v) && v >= 0;
10
+ const optionalCount = v => v === null || count(v);
11
+ export const gitFileId = v => typeof v === 'string' && /^[a-f0-9]{24}$/.test(v);
12
+ export const gitRevision = v => v === 'unborn' || typeof v === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v);
13
+ // An opaque producer fingerprint, NOT a Git tree object or a path.
14
+ export const gitIndexRevision = v => typeof v === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v);
15
+ export function gitObservation(v) {
16
+ if (!object(v) || !gitRevision(v.revision) || !gitIndexRevision(v.indexRevision)
17
+ || !text(v.at) || !Number.isFinite(Date.parse(v.at)) || !text(v.worktree) || !nullable(v.branch)
18
+ || typeof v.detached !== 'boolean' || typeof v.unborn !== 'boolean'
19
+ || v.unborn !== (v.revision === 'unborn') || (v.detached && (v.unborn || v.branch !== null))) return null;
20
+ return { revision: v.revision, indexRevision: v.indexRevision, at: v.at, worktree: v.worktree,
21
+ branch: v.branch, detached: v.detached, unborn: v.unborn };
22
+ }
23
+ export function gitTarget(v) {
24
+ if (!object(v) || !['workspace', 'instance', 'agent', 'agentsRoot', 'home'].every(k => text(v[k])) || !nullable(v.server)) return null;
25
+ return Object.fromEntries(['workspace', 'instance', 'agent', 'agentsRoot', 'home', 'server'].map(k => [k, v[k]]));
26
+ }
27
+ export const gitTargetKey = v => JSON.stringify([v.workspace, v.instance, v.agent, v.agentsRoot, v.home, v.server]);
28
+ /* Per-file line counts (kernel #238, 0.29.1): additions/deletions are non-negative integers or
29
+ null (unknown, NOT zero: binary, untracked, submodules); binary is a boolean or null. Absent on
30
+ older kernels, so absent here too. */
31
+ const lineCount = v => v === null || (Number.isSafeInteger(v) && v >= 0);
32
+ const lineCounts = v => ['additions', 'deletions'].every(k => v[k] === undefined || lineCount(v[k])) && (v.binary === undefined || v.binary === null || typeof v.binary === 'boolean');
33
+ const counted = v => Object.fromEntries(['additions', 'deletions', 'binary'].filter(k => v[k] !== undefined).map(k => [k, v[k]]));
34
+ export function gitFile(v, full = false) {
35
+ if (!object(v) || !gitFileId(v.id) || !gitKinds.includes(v.kind) || typeof v.xy !== 'string'
36
+ || !/^[.MADRCUT?!]{2}$/.test(v.xy) || !text(v.path) || !nullable(v.origPath)
37
+ || (['renamed', 'copied'].includes(v.kind) && !text(v.origPath))
38
+ || (full && typeof v.submodule !== 'boolean') || (v.score !== undefined && !text(v.score))
39
+ || (full && !lineCounts(v))) return null;
40
+ return { id: v.id, kind: v.kind, xy: v.xy, path: v.path, origPath: v.origPath,
41
+ ...(full ? { submodule: v.submodule, ...(v.score === undefined ? {} : { score: v.score }), ...counted(v) } : {}) };
42
+ }
43
+ export function gitState(v, target) {
44
+ const observation = gitObservation(v?.observation);
45
+ if (!object(v) || v.instanceGitApi !== 1 || !observation || !target
46
+ || v.home !== target.home || v.instance !== target.instance || v.agent !== target.agent || !nullable(v.workMode)
47
+ || !object(v.recorded) || !nullable(v.recorded.branch) || !nullable(v.recorded.repo) || typeof v.recorded.drift !== 'boolean'
48
+ || !object(v.upstream) || !nullable(v.upstream.ref) || !optionalCount(v.upstream.ahead) || !optionalCount(v.upstream.behind)
49
+ || !object(v.base) || !['ref', 'source', 'mergeBase'].every(k => nullable(v.base[k])) || !optionalCount(v.base.ahead) || !optionalCount(v.base.behind)
50
+ || !object(v.summary) || !gitKinds.every(k => count(v.summary[k]))
51
+ || !Array.isArray(v.files) || !Array.isArray(v.notes) || v.notes.some(n => typeof n !== 'string')) return null;
52
+ if (v.upstream.ref === null && (v.upstream.ahead !== null || v.upstream.behind !== null)) return null;
53
+ if (v.base.ref === null && (v.base.ahead !== null || v.base.behind !== null || v.base.mergeBase !== null)) return null;
54
+ const files = v.files.map(f => gitFile(f, true));
55
+ if (files.some(f => !f) || new Set(files.map(f => f.id)).size !== files.length
56
+ || gitKinds.some(k => files.filter(f => f.kind === k).length !== v.summary[k])) return null;
57
+ return { instanceGitApi: 1, instance: v.instance, agent: v.agent, home: v.home, workMode: v.workMode, observation,
58
+ recorded: { branch: v.recorded.branch, repo: v.recorded.repo, drift: v.recorded.drift },
59
+ upstream: { ref: v.upstream.ref, ahead: v.upstream.ahead, behind: v.upstream.behind },
60
+ base: { ref: v.base.ref, source: v.base.source, mergeBase: v.base.mergeBase, ahead: v.base.ahead, behind: v.base.behind },
61
+ summary: Object.fromEntries(gitKinds.map(k => [k, v.summary[k]])), files, notes: [...v.notes] };
62
+ }
63
+ export function gitDiff(v, { fileId, revision, indexRevision, observation: expected, file: selected } = {}) {
64
+ const observation = gitObservation(v?.observation), file = gitFile(v?.file);
65
+ if (!object(v) || v.instanceGitApi !== 1 || !observation || !file
66
+ || file.id !== fileId || observation.revision !== revision || observation.indexRevision !== indexRevision
67
+ || (expected && observation.worktree !== expected.worktree)
68
+ || (selected && ['id', 'path', 'origPath', 'kind', 'xy'].some(k => file[k] !== selected[k]))
69
+ || (file.kind !== 'untracked' && revision === 'unborn')
70
+ || v.against !== (file.kind === 'untracked' ? 'empty' : revision)
71
+ || typeof v.binary !== 'boolean' || typeof v.truncated !== 'boolean' || typeof v.patch !== 'string'
72
+ || !count(v.bytes) || v.limit !== INSTANCE_DIFF_LIMIT
73
+ || v.readOnly?.helpers !== 'disabled' || v.readOnly?.optionalLocks !== 'off' || v.readOnly?.objectsWritten !== 0) return null;
74
+ const length = new TextEncoder().encode(v.patch).length;
75
+ if (length > v.limit || (v.binary && (length || v.bytes || v.truncated))
76
+ || (!v.truncated && v.bytes !== length) || (v.truncated && v.bytes <= v.limit)) return null;
77
+ return { instanceGitApi: 1, observation, file, against: v.against, binary: v.binary, bytes: v.bytes,
78
+ truncated: v.truncated, limit: v.limit, patch: v.patch,
79
+ readOnly: { helpers: 'disabled', optionalLocks: 'off', objectsWritten: 0 } };
80
+ }
@@ -0,0 +1,22 @@
1
+ import { HERDR_REMOVED } from "./terminal-contract.mjs";
2
+
3
+ export function runtimeState(instance) {
4
+ return instance.running === true ? "running" : instance.running === false ? "stopped" : "unknown";
5
+ }
6
+
7
+ /** Why a kernel-reported row has no usable session, or null. A Herdr-recorded
8
+ * instance cannot open, start or restart; it can still retire. A 0.31 kernel
9
+ * reports it as runtimeState "unsupported" with its E_HERDR_REMOVED text; an
10
+ * older kernel only records a sessionTarget (local) or a herdr backend
11
+ * (remote), and its runtimeError is a Herdr probe's, so the stem stands in. */
12
+ export function unsupportedSession(instance) {
13
+ const stem = `E_HERDR_REMOVED: ${HERDR_REMOVED}`;
14
+ if (instance?.runtimeState === "unsupported") return typeof instance.runtimeError === "string" && instance.runtimeError ? instance.runtimeError : stem;
15
+ return (instance?.sessionTarget !== undefined && instance?.sessionTarget !== null) || instance?.backend === "herdr" ? stem : null;
16
+ }
17
+
18
+ export function runtimeCounts(instances) {
19
+ const counts = { running: 0, stopped: 0, unknown: 0 };
20
+ for (const instance of instances) counts[runtimeState(instance)]++;
21
+ return counts;
22
+ }
@@ -0,0 +1,453 @@
1
+ /** The roster as a tree, from the kernel's rows alone: who is who (instanceId), who relates to whom
2
+ * (the parent and sibling links, resolved by identity), which groups, in what order, what is visible
3
+ * under a filter or a collapse, who waits below a collapsed row, and what holds a home. No document,
4
+ * no element: a client draws from these answers with its own means. */
5
+ import { waitingClaim } from './waiting-on-you.mjs';
6
+
7
+ export function collapseKey(workspace, instance) {
8
+ return `${workspace || ""}\u0000${instance}`;
9
+ }
10
+
11
+ /** Names an instance is directly related to (undirected edge endpoints):
12
+ * its spawn parent plus its explicit sibling link. Kernel contract
13
+ * (feature/agent-relations, final): `parentInstance` and `siblingInstance`
14
+ * (string, only set when a sibling relation was declared against a ROOT
15
+ * instance — a sibling of a non-root simply shares the anchor's parent).
16
+ * Absent fields contribute no edges. */
17
+ export function instanceLinks(instance) {
18
+ const out = [];
19
+ if (instance.parentInstance) out.push(instance.parentInstance);
20
+ if (instance.siblingInstance) out.push(instance.siblingInstance);
21
+ return out.filter((name) => name && name !== instance.instance);
22
+ }
23
+
24
+ /** Stable identity for one roster instance. Instance NAMES are only unique
25
+ * within one agents root — the kernel permits duplicate names across agent
26
+ * dirs/team repos — so graph code must never key nodes by bare name (a
27
+ * duplicate would silently hide a live instance; merged-state review
28
+ * f7c5769). The canonical home path is unique per instance; agentsRoot+name
29
+ * is the fallback; bare name only when the roster carries neither. */
30
+ export function instanceId(instance) {
31
+ const local = instance.home ? String(instance.home)
32
+ : instance.agentsRoot ? `${instance.agentsRoot}\u0000${instance.instance}` : String(instance.instance);
33
+ // Canonical paths are unique only within a host. Preserve existing local keys.
34
+ return instance.server ? `server:${instance.server}\u0000${local}` : local;
35
+ }
36
+
37
+ /** Resolve one relation-edge NAME to the id of the instance it means.
38
+ * Relation names come from instance.json lineage, which is recorded within
39
+ * one deployment scope — so a name resolves to the same-agentsRoot instance
40
+ * first; a name that is globally unique resolves cross-root; an AMBIGUOUS
41
+ * name — no same-root candidate, or MORE THAN ONE same-root candidate
42
+ * (intra-root duplicates are legal and inherently ambiguous; merged-state
43
+ * review @7dd1e7b) — resolves to nothing (fail safe: two separate clusters,
44
+ * never a wrong merge, a false edge, or a hidden node).
45
+ * EXPORTED as the one shared resolver — the hierarchy and cluster maps
46
+ * must use the same semantics rather than re-implementing them.
47
+ * byName: Map<name, instance[]> over the same roster. */
48
+ export function resolveLinkId(fromInstance, name, byName) {
49
+ const candidates = byName.get(name)?.filter((i) => (i.server || "") === (fromInstance.server || ""));
50
+ if (!candidates || !candidates.length) return null;
51
+ if (candidates.length === 1) return instanceId(candidates[0]);
52
+ const sameRoot = candidates.filter((c) => c.agentsRoot && c.agentsRoot === fromInstance.agentsRoot);
53
+ return sameRoot.length === 1 ? instanceId(sameRoot[0]) : null;
54
+ }
55
+
56
+ /** Group instances into agent CLUSTERS — connected components of the
57
+ * undirected relation graph (parent/child spawn edges + sibling links).
58
+ * Unrelated instances are single-node clusters. Within a cluster the
59
+ * parent/child tree ordering is kept (parent-first walk with depth);
60
+ * cluster members related only by sibling links sit at depth 0.
61
+ * Nodes are keyed by instanceId (composite identity), never bare name —
62
+ * duplicate names across repos render as distinct nodes.
63
+ * Returns [{ key, instances: [{...instance, depth}] }] with clusters ranked
64
+ * running-first then by first member name, matching the roster sort. */
65
+ export function clusterInstances(instances, { links = instanceLinks } = {}) {
66
+ const byId = new Map(instances.map((i) => [instanceId(i), i]));
67
+ const byName = new Map();
68
+ for (const i of instances) {
69
+ if (!byName.has(i.instance)) byName.set(i.instance, []);
70
+ byName.get(i.instance).push(i);
71
+ }
72
+ // undirected adjacency over IDs — unresolvable/ambiguous edges are ignored
73
+ const adj = new Map(instances.map((i) => [instanceId(i), new Set()]));
74
+ const parentIdOf = new Map(); // id -> resolved parent id (tree ordering)
75
+ for (const i of instances) {
76
+ const id = instanceId(i);
77
+ if (i.parentInstance) {
78
+ const pid = resolveLinkId(i, i.parentInstance, byName);
79
+ if (pid && pid !== id) parentIdOf.set(id, pid);
80
+ }
81
+ for (const other of links(i)) {
82
+ const oid = resolveLinkId(i, other, byName);
83
+ if (!oid || oid === id) continue;
84
+ adj.get(id).add(oid);
85
+ adj.get(oid).add(id);
86
+ }
87
+ }
88
+ const rank = (a, b) => (a.running === b.running ? a.instance.localeCompare(b.instance) : a.running ? -1 : 1);
89
+ const seen = new Set();
90
+ const clusters = [];
91
+ for (const start of [...instances].sort(rank)) {
92
+ if (seen.has(instanceId(start))) continue;
93
+ // collect the component
94
+ const members = [];
95
+ const queue = [instanceId(start)];
96
+ seen.add(instanceId(start));
97
+ while (queue.length) {
98
+ const id = queue.shift();
99
+ members.push(byId.get(id));
100
+ for (const next of adj.get(id) || []) if (!seen.has(next)) { seen.add(next); queue.push(next); }
101
+ }
102
+ // parent-first tree order INSIDE the component (cycle-safe: the walk
103
+ // visits each member once; leftovers append at depth 0)
104
+ const memberIds = new Set(members.map(instanceId));
105
+ const kids = (p) => members.filter((i) => parentIdOf.get(instanceId(i)) === instanceId(p));
106
+ const roots = members.filter((i) => {
107
+ const pid = parentIdOf.get(instanceId(i));
108
+ return !pid || !memberIds.has(pid);
109
+ });
110
+ roots.sort(rank);
111
+ const ordered = [];
112
+ const placed = new Set();
113
+ const walk = (i, depth) => {
114
+ if (placed.has(instanceId(i))) return;
115
+ placed.add(instanceId(i));
116
+ ordered.push({ ...i, depth });
117
+ kids(i).sort(rank).forEach((k) => walk(k, depth + 1));
118
+ };
119
+ roots.forEach((r) => walk(r, 0));
120
+ for (const i of [...members].sort(rank)) walk(i, 0); // malformed cycles must not hide members
121
+ // Deterministic cluster label: the lexically-smallest ROOT name —
122
+ // independent of liveness, so the visible cluster name does not flip
123
+ // when a different member starts/stops running (review f921f7d nit).
124
+ // Running-first `rank` still governs display ORDER within the cluster.
125
+ const rootNames = (roots.length ? roots : members).map((i) => i.instance).sort();
126
+ clusters.push({ key: rootNames[0], instances: ordered });
127
+ }
128
+ return clusters;
129
+ }
130
+
131
+ /** Find the roster instance a UI reference means. References carry the
132
+ * display name plus whatever identity the caller knows (home/agentsRoot —
133
+ * sidebar rows know both; older callers pass a bare name). Identity match
134
+ * wins; bare names resolve only when unambiguous in the roster — an
135
+ * ambiguous bare name returns null rather than the first same-named match
136
+ * (which could open the WRONG agents root's tmux session; review 46f3fdc).
137
+ * Importable so the duplicate-name regression exercises this exact layer. */
138
+ export function findRosterInstance(instances, ref) {
139
+ const name = typeof ref === "string" ? ref : ref.instance;
140
+ const home = typeof ref === "string" ? undefined : ref.home;
141
+ const root = typeof ref === "string" ? undefined : ref.agentsRoot;
142
+ // An object reference names a host (absent server means local). A legacy
143
+ // bare name can still resolve across the roster, but only if unambiguous.
144
+ if (typeof ref !== "string") instances = instances.filter((i) => (i.server || "") === (ref.server || ""));
145
+ if (home) {
146
+ const byHome = instances.find((i) => i.home === home);
147
+ if (byHome) return byHome;
148
+ }
149
+ if (root) {
150
+ const byRoot = instances.find((i) => i.instance === name && i.agentsRoot === root);
151
+ if (byRoot) return byRoot;
152
+ }
153
+ const named = instances.filter((i) => i.instance === name);
154
+ return named.length === 1 ? named[0] : null;
155
+ }
156
+
157
+ /** Shortest DISTINGUISHING path suffixes for a set of agents roots.
158
+ * Duplicate instance names are told apart by where they home, but naive
159
+ * single-segment tags collide (/a/project/agents and /b/project/agents both
160
+ * render "project"). Grow each root's suffix segment-by-segment until it is
161
+ * unique within the set; fall back to the full root. Returns Map<root, tag>.
162
+ * (Review cbd5bb3: duplicate option labels must actually differ.) */
163
+ export function distinguishingRootTags(roots) {
164
+ const uniq = [...new Set(roots.filter(Boolean).map(String))];
165
+ const segs = new Map(uniq.map((r) => [r, r.split("/").filter(Boolean)]));
166
+ const tags = new Map();
167
+ for (const root of uniq) {
168
+ const mine = segs.get(root);
169
+ // skip the trailing "agents"-style leaf shared by every root: start the
170
+ // suffix ABOVE the leaf, then extend upward until unique
171
+ let take = 2; // leaf + one parent
172
+ let tag;
173
+ for (; take <= mine.length; take++) {
174
+ tag = mine.slice(-take, -1).join("/");
175
+ const clash = uniq.some((other) => other !== root
176
+ && segs.get(other).slice(-take, -1).join("/") === tag);
177
+ if (!clash) break;
178
+ }
179
+ tags.set(root, take > mine.length || !tag ? root : tag);
180
+ }
181
+ return tags;
182
+ }
183
+
184
+ /** Whether an instance has children IN ITS OWN identity — parent edges
185
+ * resolve through resolveLinkId, so a childless parent whose NAME is shared
186
+ * by a parent in another agents root gets no disclosure control (review
187
+ * 7d740f9). Accepts the full instance object; the legacy bare-name call
188
+ * shape (string) keeps name matching for rosters without identity fields. */
189
+ export function hasInstanceChildren(instances, instance) {
190
+ if (typeof instance === "string") {
191
+ return instances.some((candidate) => candidate.parentInstance === instance);
192
+ }
193
+ const byName = new Map();
194
+ for (const i of instances) {
195
+ if (!byName.has(i.instance)) byName.set(i.instance, []);
196
+ byName.get(i.instance).push(i);
197
+ }
198
+ const id = instanceId(instance);
199
+ return instances.some((candidate) => candidate.parentInstance
200
+ && resolveLinkId(candidate, candidate.parentInstance, byName) === id);
201
+ }
202
+
203
+ export function instanceRepoLabel(instance) {
204
+ if (instance.repoName) return String(instance.repoName);
205
+ const path = instance.repo || instance.workspace || "";
206
+ return String(path).split("/").filter(Boolean).at(-1) || "workspace";
207
+ }
208
+
209
+ /* ── homes the kernel holds (#802) ── */
210
+
211
+ const HELD_HOMES = Object.freeze({
212
+ spawning: { state: "Setting up worktree…", status: "Spawning (setting up worktree)", retire: false,
213
+ sentence: name => `${name} is setting up its worktree. It can't be used until the spawn finishes.` },
214
+ "spawn-incomplete": { state: "Spawn didn't finish", hint: "Retire it to clean up", status: "Spawn didn't finish", retire: true,
215
+ sentence: name => `The spawn of ${name} didn't finish. Retire it to clean up.` },
216
+ "retire-incomplete": { state: "Retire didn't finish", hint: "Retire it again to complete", status: "Retire didn't finish", retire: true,
217
+ sentence: name => `The retire of ${name} didn't finish. Retire it again to complete.` },
218
+ });
219
+ /** What the kernel's roster row says holds this home, or null (#802): `spawning` while a spawn that
220
+ * runs its worktree hooks is verifiably alive (`spawnInProgress: true`), `spawn-incomplete` when a
221
+ * spawn left it for retire to clean up (`rollbackIncomplete`), `retire-incomplete` when a retire did
222
+ * (`retirePending`). rollbackIncomplete wins over spawnInProgress (the spawn is gone, not live), and a
223
+ * live spawn over retirePending (the kernel refuses to retire it). Every surface draws such a row from
224
+ * this: a spawning one starts, stops, retires and splits nothing; a quarantined one (`retire`) offers
225
+ * Retire only. `state` is the row's text, `hint` its muted line, `status` the hover card's Status.
226
+ * `sentence` is every client's, so it promises no act of one client: a spawning home "can't be used
227
+ * until the spawn finishes", whoever started the spawn and whether or not it ends finished. */
228
+ export function heldHome(instance) {
229
+ const kind = !instance ? null : instance.rollbackIncomplete ? "spawn-incomplete"
230
+ : instance.spawnInProgress === true ? "spawning" : instance.retirePending ? "retire-incomplete" : null;
231
+ return kind ? { kind, ...HELD_HOMES[kind] } : null;
232
+ }
233
+
234
+ /* ── roster grouping: repo → agent family (soul), with sort modes ── */
235
+
236
+ export const ROSTER_SORTS = Object.freeze([
237
+ Object.freeze({ id: "status", label: "Status (running first)" }),
238
+ Object.freeze({ id: "name", label: "Name" }),
239
+ ]);
240
+
241
+ /** Comparator for one sibling level. "status" ranks running instances first,
242
+ * then by name; "name" is purely alphabetical. Unknown ids fall back to
243
+ * "status" so a stale persisted choice can never break rendering. */
244
+ export function rosterRank(sortBy) {
245
+ const byName = (a, b) => String(a.instance).localeCompare(String(b.instance));
246
+ if (sortBy === "name") return byName;
247
+ return (a, b) => (!!a.running === !!b.running ? byName(a, b) : a.running ? -1 : 1);
248
+ }
249
+
250
+ /** Group a roster list repo → agent family (soul), each family's items in
251
+ * lineage order (parents before children, depth annotated) with siblings
252
+ * sorted by `sortBy`. Lineage links crossing family/repo boundaries are cut:
253
+ * such children render as roots of their own family group. Returns
254
+ * Map<repoLabel, Map<familyName, item[]>> with deterministic group order:
255
+ * repos and families alphabetical. */
256
+ export function groupRosterFamilies(list, sortBy = "status") {
257
+ const rank = rosterRank(sortBy);
258
+ const repos = new Map();
259
+ for (const i of list) {
260
+ // instance.json is workspace-controlled: agent/repoName may arrive as
261
+ // non-strings through the reader. Coerce grouping keys so one malformed
262
+ // instance cannot throw in localeCompare and blank the whole roster.
263
+ const rName = String(instanceRepoLabel(i));
264
+ if (!repos.has(rName)) repos.set(rName, new Map());
265
+ const families = repos.get(rName);
266
+ const fName = String(i.agent || "?");
267
+ if (!families.has(fName)) families.set(fName, []);
268
+ families.get(fName).push(i);
269
+ }
270
+ const sortedRepos = new Map([...repos.entries()].sort(([a], [b]) => a.localeCompare(b)));
271
+ for (const [rName, families] of sortedRepos) {
272
+ const sortedFamilies = new Map([...families.entries()].sort(([a], [b]) => a.localeCompare(b)));
273
+ for (const [fName, items] of sortedFamilies) {
274
+ const byName = new Map(items.map((i) => [i.instance, i]));
275
+ const roots = items.filter((i) => !i.parentInstance || !byName.has(i.parentInstance));
276
+ const kids = (p) => items.filter((i) => i.parentInstance === p.instance);
277
+ const ordered = [];
278
+ const seen = new Set();
279
+ const walk = (i, depth) => {
280
+ if (seen.has(i.instance)) return; // cycle-safe
281
+ seen.add(i.instance);
282
+ ordered.push({ ...i, depth });
283
+ kids(i).sort(rank).forEach((k) => walk(k, depth + 1));
284
+ };
285
+ roots.sort(rank).forEach((r) => walk(r, 0));
286
+ for (const i of items) if (!seen.has(i.instance)) ordered.push({ ...i, depth: 0 });
287
+ sortedFamilies.set(fName, ordered);
288
+ }
289
+ sortedRepos.set(rName, sortedFamilies);
290
+ }
291
+ return sortedRepos;
292
+ }
293
+
294
+ /** Stable collapse key for a roster GROUP header (repo or repo+family),
295
+ * workspace-scoped like instance collapse keys. */
296
+ export function rosterGroupKey(workspace, ...parts) {
297
+ return [`g:${workspace || ""}`, ...parts].join("\u0000");
298
+ }
299
+
300
+ /** Whether an instance itself matches the roster filter (its name, soul, repo or task) — as
301
+ * opposed to an ancestor shown only to keep a match's tree path. */
302
+ export function instanceMatchesFilter(item, query) {
303
+ const needle = String(query || "").trim().toLowerCase();
304
+ if (!needle) return true;
305
+ return [item.instance, item.agent, item.repoName, item.task]
306
+ .some((value) => String(value || "").toLowerCase().includes(needle));
307
+ }
308
+
309
+ /** Include matching instances plus their ancestor paths, in source order.
310
+ * IDENTITY-aware (merged-state review @3e76616): inclusion keys by
311
+ * instanceId and ancestors resolve through resolveLinkId over the FULL
312
+ * roster — a same-named instance in another root never leaks into this
313
+ * one's filter results, and an ambiguous parent edge includes nothing.
314
+ * `matches` decides what matches (default: the sidebar's instanceMatchesFilter);
315
+ * the command palette passes its fuzzy matcher and shares the tree path. */
316
+ export function filterInstanceTree(instances, query, matches = null) {
317
+ const needle = String(query || "").trim().toLowerCase();
318
+ if (!needle) return instances;
319
+ const isMatch = matches || ((item) => instanceMatchesFilter(item, needle));
320
+ const byId = new Map(instances.map((item) => [instanceId(item), item]));
321
+ const byName = new Map();
322
+ for (const item of instances) {
323
+ if (!byName.has(item.instance)) byName.set(item.instance, []);
324
+ byName.get(item.instance).push(item);
325
+ }
326
+ const included = new Set();
327
+ for (const item of instances) {
328
+ if (!isMatch(item)) continue;
329
+ let cursor = item;
330
+ const seen = new Set();
331
+ while (cursor) {
332
+ const id = instanceId(cursor);
333
+ if (seen.has(id)) break;
334
+ included.add(id);
335
+ seen.add(id);
336
+ const pid = cursor.parentInstance ? resolveLinkId(cursor, cursor.parentInstance, byName) : null;
337
+ cursor = pid ? byId.get(pid) : null;
338
+ }
339
+ }
340
+ return instances.filter((item) => included.has(instanceId(item)));
341
+ }
342
+
343
+ /** Cluster the FULL roster, then project each cluster to its visible
344
+ * members — never cluster a filtered subset: dropping roster rows can turn
345
+ * a globally AMBIGUOUS relation edge into a false unique edge, silently
346
+ * re-linking nodes while the user types (merged-state review @3e76616).
347
+ * Cluster order and member depths come from the full-roster computation;
348
+ * clusters with no visible member disappear. */
349
+ export function visibleClusters(allInstances, visibleInstances, { links = instanceLinks } = {}) {
350
+ const visibleIds = new Set(visibleInstances.map((i) => instanceId(i)));
351
+ return clusterInstances(allInstances, { links })
352
+ .map((c) => ({ ...c, instances: c.instances.filter((i) => visibleIds.has(instanceId(i))) }))
353
+ .filter((c) => c.instances.length);
354
+ }
355
+
356
+ /** The sidebar roster's groups (Redesign v3), shared with the command palette:
357
+ * each multi-member relation cluster under its deterministic name, then every
358
+ * unrelated instance under "independent". Clusters come from the FULL roster,
359
+ * projected to the visible members (visibleClusters), so a group's size is
360
+ * what is shown. Returns [{ key, label, clusters: [{ key, instances }] }] in
361
+ * display order, members carrying their tree depth. A group's key is unique
362
+ * even when two roots share a name (other agents roots or hosts): the label is
363
+ * the name, the key adds its place in the order. */
364
+ export function rosterGroups(allInstances, visibleInstances, { links = instanceLinks } = {}) {
365
+ const clusters = visibleClusters(allInstances, visibleInstances, { links });
366
+ return [
367
+ ...clusters.filter((c) => c.instances.length > 1).map((c, i) => ({ key: `cluster:${i}:${c.key}`, label: c.key, clusters: [c] })),
368
+ ...(clusters.some((c) => c.instances.length === 1)
369
+ ? [{ key: "independent", label: "independent", clusters: clusters.filter((c) => c.instances.length === 1) }] : []),
370
+ ];
371
+ }
372
+
373
+ /** Whether an item remains visible under VS Code-style collapsed ancestors.
374
+ * Filtering temporarily reveals matching paths without mutating the user's
375
+ * persisted collapse state. Parent traversal is cycle-safe and
376
+ * IDENTITY-aware: collapse keys are minted from instanceId, and parent
377
+ * names resolve through resolveLinkId so a collapsed duplicate name in
378
+ * another agents root can never hide this root's subtree (review 46f3fdc).
379
+ * `section(row)` (optional): the roster section (deployment) a row is painted in. A collapse hides only
380
+ * rows of its own section: the walk stops at the first ancestor painted in another section, which does
381
+ * not hide the row (#551's visible symptom: resolveLinkId accepts a unique name from another agents root,
382
+ * and that parent is painted, and collapsed, in another section). Without it, sections are ignored. */
383
+ export function instanceVisibleInTree(instance, allInstances, collapsed, workspace, filtering = false, { section } = {}) {
384
+ if (filtering) return true;
385
+ const byId = new Map(allInstances.map((item) => [instanceId(item), item]));
386
+ const byName = new Map();
387
+ for (const item of allInstances) {
388
+ if (!byName.has(item.instance)) byName.set(item.instance, []);
389
+ byName.get(item.instance).push(item);
390
+ }
391
+ const seen = new Set([instanceId(instance)]);
392
+ let cursor = instance;
393
+ while (cursor?.parentInstance) {
394
+ const pid = resolveLinkId(cursor, cursor.parentInstance, byName);
395
+ if (!pid || seen.has(pid)) break;
396
+ const parent = byId.get(pid);
397
+ if (section && parent && section(parent) !== section(instance)) break;
398
+ if (collapsed.has(collapseKey(workspace, pid))) return false;
399
+ seen.add(pid);
400
+ cursor = parent;
401
+ }
402
+ return true;
403
+ }
404
+
405
+ /** Needs input (Spec D): waiting instances hidden by a collapse, attributed to their nearest visible ancestor:
406
+ * Map(instanceId(ancestor) → [waiting rows]). Computed over the full roster (as clustering is) by the
407
+ * parent relation only (resolveLinkId: never across a remote server), cycle-safe; a missing or cyclic
408
+ * parent chain degrades to no roll-up. `section(row)`: the roster section (deployment) a row is painted
409
+ * in; a chain that leaves the waiting row's section rolls up nowhere (resolveLinkId accepts a unique name
410
+ * from another agents root), and a collapse in another section does not hide it (instanceVisibleInTree,
411
+ * given the same `section`). Filtering on → nothing is collapsed → empty. `stale(row)`: the caller's
412
+ * held-stale test; a stale row contributes nothing. */
413
+ export function waitingRollup(instances, collapsed, workspace, { filtering = false, stale = () => false, section = () => null } = {}) {
414
+ const out = new Map();
415
+ if (filtering || !collapsed?.size) return out;
416
+ const byId = new Map(instances.map(i => [instanceId(i), i]));
417
+ const byName = new Map();
418
+ for (const i of instances) { if (!byName.has(i.instance)) byName.set(i.instance, []); byName.get(i.instance).push(i); }
419
+ for (const i of instances) {
420
+ if (!waitingClaim(i, { stale: stale(i) }) || instanceVisibleInTree(i, instances, collapsed, workspace, false, { section })) continue;
421
+ const seen = new Set([instanceId(i)]);
422
+ let cursor = i, owner = null;
423
+ while (cursor?.parentInstance) {
424
+ const pid = resolveLinkId(cursor, cursor.parentInstance, byName);
425
+ if (!pid || seen.has(pid)) break;
426
+ seen.add(pid); cursor = byId.get(pid);
427
+ if (!cursor || section(cursor) !== section(i)) break;
428
+ if (instanceVisibleInTree(cursor, instances, collapsed, workspace, false, { section })) { owner = pid; break; }
429
+ }
430
+ if (owner === null) continue;
431
+ if (!out.has(owner)) out.set(owner, []);
432
+ out.get(owner).push(i);
433
+ }
434
+ return out;
435
+ }
436
+
437
+ /** Resolve the roster keyboard handler's ArrowLeft target: the parent
438
+ * instanceId of the row whose data-tree-instance is `id`, or null.
439
+ * Identity-aware end to end (review 96b037b): the current row is found by
440
+ * instanceId — rows carry composite ids, so a bare-name lookup never
441
+ * matches — and the parent edge resolves through resolveLinkId, so a
442
+ * duplicate parent name in another root (or intra-root) can never steal
443
+ * focus: ambiguity yields null and the key is a no-op. */
444
+ export function rosterParentId(instances, id) {
445
+ const me = instances.find((i) => instanceId(i) === id);
446
+ if (!me?.parentInstance) return null;
447
+ const byName = new Map();
448
+ for (const i of instances) {
449
+ if (!byName.has(i.instance)) byName.set(i.instance, []);
450
+ byName.get(i.instance).push(i);
451
+ }
452
+ return resolveLinkId(me, me.parentInstance, byName);
453
+ }
@@ -0,0 +1,11 @@
1
+ /** The variables an OATS instance session carries. A client started from inside one (a terminal in
2
+ * an agent's pane) inherits them, and a kernel command that runs with them answers for that instance
3
+ * instead of the directory it was asked about. The reads that name their own deployment remove them. */
4
+ export const INSTANCE_VARIABLES = Object.freeze(['PI_AGENTS_ROOT', 'PI_AGENT_HOME', 'PI_AGENT_INSTANCE', 'OATS_HOME', 'OATS_INSTANCE_HOME', 'OATS_INSTANCE', 'OATS_DEPLOYMENT', 'OATS_RESOLUTION']);
5
+
6
+ /** A copy of `env` without the instance variables. `env` is never changed. */
7
+ export function withoutInstanceVariables(env) {
8
+ const out = { ...env };
9
+ for (const name of INSTANCE_VARIABLES) delete out[name];
10
+ return out;
11
+ }
@@ -0,0 +1,51 @@
1
+ /** Soul launch preferences (feature `launch-preference`, OATS 0.30; docs/desktop-cli-api.md
2
+ * "Soul launch preferences"). The kernel's closed Launch object, decoded once for every reader:
3
+ * `oats souls` rows and `inspect --soul` (what a spawn with no flags would decide), `spawn --preview`
4
+ * (flags applied) and `inspect --home` (the record, plus `launchCurrent`). A kernel without the
5
+ * feature emits none of these fields, so every reader treats `launch` as optional. */
6
+ import { HARNESSES } from './harness-names.mjs';
7
+
8
+ const record = v => v !== null && typeof v === 'object' && !Array.isArray(v);
9
+ const exact = (v, keys) => record(v) && Object.keys(v).length === keys.length && keys.every(k => Object.hasOwn(v, k));
10
+ const text = (v, max) => typeof v === 'string' && v.length > 0 && v.length <= max && !/[\x00-\x1f\x7f]/.test(v);
11
+ const model = v => v === null || text(v, 256);
12
+ const LAUNCH_CONFIG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
13
+ const CODE = /^E_[A-Z0-9_]{1,62}$/;
14
+
15
+ /** Where the effective launch came from, per document: a report never says `flag`; only a home's
16
+ * record says `recorded` (a home from before 0.30). */
17
+ export const REPORT_FROM = Object.freeze(['local', 'local-default', 'soul', 'host']);
18
+ export const PREVIEW_FROM = Object.freeze(['flag', ...REPORT_FROM]);
19
+ export const RECORD_FROM = Object.freeze([...PREVIEW_FROM, 'recorded']);
20
+
21
+ /** LaunchPreference `{harness, model}` (model a string or null), or null (none declared). */
22
+ function preference(v) {
23
+ if (v === null) return null;
24
+ if (!exact(v, ['harness', 'model']) || !HARNESSES.includes(v.harness) || !model(v.model)) return undefined;
25
+ return { harness: v.harness, model: v.model };
26
+ }
27
+
28
+ /** An effective launch `{harness, model|null, launchConfig|null}` (also readiness `launch-changed`'s
29
+ * `recorded`/`current`), or `undefined` when malformed. */
30
+ export function effectiveOf(e) {
31
+ if (!exact(e, ['harness', 'model', 'launchConfig']) || !HARNESSES.includes(e.harness) || !model(e.model)
32
+ || !(e.launchConfig === null || (typeof e.launchConfig === 'string' && LAUNCH_CONFIG.test(e.launchConfig)))) return undefined;
33
+ return { harness: e.harness, model: e.model, launchConfig: e.launchConfig };
34
+ }
35
+
36
+ /** The Launch object, closed, or `undefined` when malformed (the reader then refuses its document). */
37
+ export function launchOf(v, from = REPORT_FROM) {
38
+ if (!exact(v, ['declared', 'effective', 'from', 'at', 'problem'])) return undefined;
39
+ const declared = preference(v.declared);
40
+ const e = v.effective;
41
+ if (declared === undefined || !exact(e, ['harness', 'model', 'launchConfig']) || !HARNESSES.includes(e.harness) || !model(e.model)
42
+ || !(e.launchConfig === null || (typeof e.launchConfig === 'string' && LAUNCH_CONFIG.test(e.launchConfig)))) return undefined;
43
+ if (!from.includes(v.from) || !(v.at === null || text(v.at, 1024))) return undefined;
44
+ let problem = null;
45
+ if (v.problem !== null) {
46
+ const p = v.problem;
47
+ if (!exact(p, ['code', 'message', 'fix']) || !CODE.test(p.code) || !text(p.message, 1024) || !text(p.fix, 1024)) return undefined;
48
+ problem = { code: p.code, message: p.message, fix: p.fix };
49
+ }
50
+ return { declared, effective: { harness: e.harness, model: e.model, launchConfig: e.launchConfig }, from: v.from, at: v.at, problem };
51
+ }