@awebai/oats 0.68.1 → 0.69.2

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 (99) hide show
  1. package/bin/oats.mjs +180 -36
  2. package/docs/capabilities.md +73 -10
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/configuration.md +68 -2
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
  6. package/docs/design/2026-10-22-module-upgrade.md +1 -1
  7. package/docs/desktop-cli-api.md +600 -25
  8. package/docs/desktop-instance-start.md +59 -3
  9. package/docs/desktop.md +175 -10
  10. package/docs/execution-targets.md +536 -62
  11. package/docs/harness-trust.md +3 -1
  12. package/docs/implementation.md +33 -15
  13. package/docs/integrations.md +2 -2
  14. package/docs/knowledge.md +25 -16
  15. package/docs/oats-local.schema.json +2 -2
  16. package/docs/official-catalog.md +6 -5
  17. package/docs/packages.md +14 -14
  18. package/docs/release-notes/v0.69.0.md +658 -0
  19. package/docs/release-notes/v0.69.1.md +25 -0
  20. package/docs/release-notes/v0.69.2.md +259 -0
  21. package/docs/servers.md +51 -7
  22. package/docs/soul.schema.json +1 -0
  23. package/docs/souls-and-instances.md +46 -9
  24. package/docs/tui.md +177 -21
  25. package/docs/upgrading.md +16 -7
  26. package/docs/workspaces.md +2 -2
  27. package/injects/instance-boundary.md +19 -33
  28. package/injects/work-attached.md +8 -13
  29. package/injects/work-checkout.md +16 -30
  30. package/injects/work-directory.md +9 -15
  31. package/injects/work-workspace.md +8 -19
  32. package/injects/work-worktree.md +18 -33
  33. package/lib/capability-contract.mjs +2 -2
  34. package/lib/core.mjs +496 -127
  35. package/lib/file-pieces.mjs +49 -0
  36. package/lib/instance-background.mjs +54 -0
  37. package/lib/instance-events.mjs +25 -4
  38. package/lib/instance-inspect.mjs +3 -0
  39. package/lib/instance-lifecycle.mjs +35 -0
  40. package/lib/instance-resolution.mjs +3 -2
  41. package/lib/instance-same-work.mjs +67 -0
  42. package/lib/instance-upgrade.mjs +18 -0
  43. package/lib/launch-prompt-fixtures/README.md +62 -0
  44. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  45. package/lib/launch-prompt-fixtures.mjs +49 -0
  46. package/lib/launch-prompt-resume.mjs +55 -0
  47. package/lib/login-environment.mjs +27 -9
  48. package/lib/materialize.mjs +23 -2
  49. package/lib/resolve.mjs +32 -5
  50. package/lib/schedule.mjs +3 -3
  51. package/lib/servers.mjs +136 -27
  52. package/lib/session-end.mjs +82 -0
  53. package/lib/session-input.mjs +43 -9
  54. package/lib/session-resume-contract.mjs +33 -0
  55. package/lib/session-resume.mjs +337 -0
  56. package/lib/session-seen.mjs +163 -0
  57. package/lib/session-viewer.mjs +147 -44
  58. package/lib/soul-composition.mjs +15 -11
  59. package/lib/start-env.mjs +110 -0
  60. package/lib/tmux-server-scope.mjs +139 -14
  61. package/lib/workspace.mjs +41 -6
  62. package/package-catalog.json +11 -5
  63. package/package.json +1 -1
  64. package/packages/client/cli-adapter.mjs +39 -8
  65. package/packages/client/cli-locator.mjs +3 -2
  66. package/packages/client/deployment-data.mjs +16 -0
  67. package/packages/client/deployment-panel.mjs +7 -0
  68. package/packages/client/file-output-exec.mjs +98 -0
  69. package/packages/client/instance-tree.mjs +64 -14
  70. package/packages/client/launch-prompt-outcome.mjs +25 -13
  71. package/packages/client/own-codes.mjs +2 -0
  72. package/packages/client/panel-views.mjs +11 -3
  73. package/packages/client/remote-roster.mjs +5 -1
  74. package/packages/client/roster-sections.mjs +50 -6
  75. package/packages/client/same-work.mjs +49 -0
  76. package/packages/client/session-attach.mjs +35 -5
  77. package/packages/client/session-resume-cli.mjs +64 -0
  78. package/packages/client/session-resume-trigger.mjs +167 -0
  79. package/packages/client/session-resume.mjs +332 -0
  80. package/packages/client/soul-rows.mjs +2 -0
  81. package/packages/client/spawn-apply-contract.mjs +2 -1
  82. package/packages/client/spawn-decision.mjs +4 -1
  83. package/packages/client/spawn-preview-contract.mjs +12 -1
  84. package/packages/client/spawn-preview.mjs +2 -0
  85. package/packages/client/tmux-status.mjs +30 -7
  86. package/packages/client/waiting-on-you.mjs +11 -4
  87. package/packages/client/workspace-step.mjs +17 -5
  88. package/packages/record/lib/last-conversation.mjs +123 -0
  89. package/packages/record/lib/session-roots.mjs +10 -1
  90. package/packages/tui/README.md +2 -2
  91. package/packages/tui/lib/client.mjs +7 -3
  92. package/packages/tui/lib/main.mjs +49 -14
  93. package/packages/tui/lib/model.mjs +146 -55
  94. package/packages/tui/lib/store.mjs +84 -27
  95. package/packages/tui/lib/term/text.mjs +12 -9
  96. package/packages/tui/lib/views/frame.mjs +74 -7
  97. package/packages/tui/lib/views/help.mjs +10 -3
  98. package/packages/tui/lib/views/instances.mjs +41 -3
  99. package/skills/oats-getting-started/SKILL.md +117 -4
@@ -6,6 +6,7 @@ import { waitingClaim } from './waiting-on-you.mjs';
6
6
  import { byRuntimeState } from './instance-presentation.mjs';
7
7
  import { retireData } from './retire-state.mjs';
8
8
  import { displayLine } from './display-text.mjs';
9
+ import { drawingFirst } from './same-work.mjs';
9
10
 
10
11
  export function collapseKey(workspace, instance) {
11
12
  return `${workspace || ""}\u0000${instance}`;
@@ -114,14 +115,21 @@ export function instanceSiblings(instances) {
114
115
  * cluster members related only by sibling links sit at depth 0.
115
116
  * Nodes are keyed by instanceId (composite identity), never bare name —
116
117
  * duplicate names across repos render as distinct nodes.
118
+ * Under one parent, the children that draw their parent line come first (same-work.mjs `drawingFirst`: on a
119
+ * host that declares instance-same-work, the flagged ones), each part in the roster's order (#1577). The product
120
+ * owner's contract (awebai/oats#1577, comment 6441606665) refines the name order (the Desktop expert's decision
121
+ * roster-name-order-preserves-recognition) inside one parent's children only: roots, clusters and groups keep it.
117
122
  * Returns [{ key, instances: [{...instance, depth}] }] with clusters ranked by
118
123
  * their first ROOT in the roster's order (`rosterOrder`), never by another member (#1262): a bundle sits where
119
124
  * its root sits, and gaining or losing a child, or a start or a stop, moves nothing. A cluster without a root
120
- * (a malformed cycle) ranks by its first member in that order. */
121
- export function clusterInstances(instances, { links = instanceLinks } = {}) {
125
+ * (a malformed cycle) ranks by its first member in that order.
126
+ * `roster` (optional): the full roster `instances` is a part of (#1579: one section of it). Names resolve over it,
127
+ * so a part never turns an ambiguous name into a false unique one, and a link that resolves to a row outside the
128
+ * part is no edge: such a row is a root of its part, as a row whose parent is gone. Without it, `instances`. */
129
+ export function clusterInstances(instances, { links = instanceLinks, roster = instances } = {}) {
122
130
  const byId = new Map(instances.map((i) => [instanceId(i), i]));
123
131
  const byName = new Map();
124
- for (const i of instances) {
132
+ for (const i of roster) {
125
133
  if (!byName.has(i.instance)) byName.set(i.instance, []);
126
134
  byName.get(i.instance).push(i);
127
135
  }
@@ -136,7 +144,7 @@ export function clusterInstances(instances, { links = instanceLinks } = {}) {
136
144
  }
137
145
  for (const other of links(i)) {
138
146
  const oid = resolveLinkId(i, other, byName);
139
- if (!oid || oid === id) continue;
147
+ if (!oid || oid === id || !adj.has(oid)) continue; // a link out of these rows draws nothing
140
148
  adj.get(id).add(oid);
141
149
  adj.get(oid).add(id);
142
150
  }
@@ -170,7 +178,7 @@ export function clusterInstances(instances, { links = instanceLinks } = {}) {
170
178
  if (placed.has(instanceId(i))) return;
171
179
  placed.add(instanceId(i));
172
180
  ordered.push({ ...i, depth });
173
- kids(i).sort(rank).forEach((k) => walk(k, depth + 1));
181
+ kids(i).sort((a, b) => drawingFirst(a, b) || rank(a, b)).forEach((k) => walk(k, depth + 1));
174
182
  };
175
183
  roots.forEach((r) => walk(r, 0));
176
184
  for (const i of [...members].sort(rank)) walk(i, 0); // malformed cycles must not hide members
@@ -191,7 +199,8 @@ export function clusterInstances(instances, { links = instanceLinks } = {}) {
191
199
  * recent first, and so is each set of nodes at one level of a cluster: its depth-0 roots, and the children of
192
200
  * each parent. Nodes without a key follow every node with one, in their input order (a stable sort), so an
193
201
  * empty record returns the input order. A child stays under its parent: each cluster is walked again in
194
- * pre-order, every depth unchanged. Parentage is read from the pre-order and the depths alone (a node's
202
+ * pre-order, every depth unchanged. A parent's children keep the roster's split (#1577): those that draw their
203
+ * parent line first (same-work.mjs `drawingFirst`), recency deciding within each part; roots are not split. Parentage is read from the pre-order and the depths alone (a node's
195
204
  * children are the following rows one level deeper, until a row at its depth or above), never from names: the
196
205
  * tree was built by identity, and a malformed cycle's depth-0 leftovers are roots like any other. Returns new
197
206
  * cluster objects over the same rows; the input is not mutated. */
@@ -219,12 +228,13 @@ export function recencyOrder(clusters, lastFocus) {
219
228
  return node.key;
220
229
  };
221
230
  const instances = [];
222
- const walk = (nodes) => {
223
- for (const node of [...nodes].sort(recentFirst)) { instances.push(node.inst); walk(node.kids); }
231
+ const childOrder = (a, b) => drawingFirst(a.inst, b.inst) || recentFirst(a, b);
232
+ const walk = (nodes, order) => {
233
+ for (const node of [...nodes].sort(order)) { instances.push(node.inst); walk(node.kids, childOrder); }
224
234
  };
225
235
  const top = { key: null, kids: roots };
226
236
  keyOf(top);
227
- walk(roots);
237
+ walk(roots, recentFirst);
228
238
  return { key: top.key, cluster: { ...cluster, instances } };
229
239
  });
230
240
  return ranked.sort(recentFirst).map(({ cluster }) => cluster);
@@ -381,7 +391,7 @@ export function rosterRank(sortBy) {
381
391
 
382
392
  /** Group a roster list repo → agent family (soul), each family's items in
383
393
  * lineage order (parents before children, depth annotated) with siblings
384
- * sorted by `sortBy`. Lineage links crossing family/repo boundaries are cut:
394
+ * sorted by `sortBy` (those that draw their parent line first, #1577). Lineage links crossing family/repo boundaries are cut:
385
395
  * such children render as roots of their own family group. Returns
386
396
  * Map<repoLabel, Map<familyName, item[]>> with deterministic group order:
387
397
  * repos and families alphabetical. */
@@ -412,7 +422,8 @@ export function groupRosterFamilies(list, sortBy = "status") {
412
422
  if (seen.has(i.instance)) return; // cycle-safe
413
423
  seen.add(i.instance);
414
424
  ordered.push({ ...i, depth });
415
- kids(i).sort(rank).forEach((k) => walk(k, depth + 1));
425
+ // #1577: children that draw their parent line first, as clusterInstances orders them.
426
+ kids(i).sort((a, b) => drawingFirst(a, b) || rank(a, b)).forEach((k) => walk(k, depth + 1));
416
427
  };
417
428
  roots.sort(rank).forEach((r) => walk(r, 0));
418
429
  for (const i of items) if (!seen.has(i.instance)) ordered.push({ ...i, depth: 0 });
@@ -498,12 +509,13 @@ export function visibleClusters(allInstances, visibleInstances, { links = instan
498
509
  * `lastFocus` (Map<instanceId, time>, optional; the command palette's, #1383): the full roster's clusters are
499
510
  * ordered by last focus (`recencyOrder`) before the groups form by the same rule, so a run is the consecutive
500
511
  * single clusters of that order, keyed by its first member there. What is visible still decides only which rows
501
- * are listed, never the order. Without it, the roster's own order (the sidebar's and the TUI's). */
502
- export function rosterGroups(allInstances, visibleInstances, { links = instanceLinks, lastFocus } = {}) {
512
+ * are listed, never the order. Without it, the roster's own order (the sidebar's and the TUI's).
513
+ * `roster` (optional): the full roster `allInstances` is a part of, as for `clusterInstances`. */
514
+ export function rosterGroups(allInstances, visibleInstances, { links = instanceLinks, lastFocus, roster = allInstances } = {}) {
503
515
  const visibleIds = new Set(visibleInstances.map((i) => instanceId(i)));
504
516
  const groups = [];
505
517
  let place = 0, run = null;
506
- const clusters = clusterInstances(allInstances, { links });
518
+ const clusters = clusterInstances(allInstances, { links, roster });
507
519
  for (const c of lastFocus instanceof Map ? recencyOrder(clusters, lastFocus) : clusters) {
508
520
  const shown = { ...c, instances: c.instances.filter((i) => visibleIds.has(instanceId(i))) };
509
521
  if (c.instances.length > 1) {
@@ -518,6 +530,44 @@ export function rosterGroups(allInstances, visibleInstances, { links = instanceL
518
530
  return groups.filter((g) => g.clusters.length);
519
531
  }
520
532
 
533
+ /** The kernel feature that reports a row's `background` (#1579). */
534
+ export const BACKGROUND_FEATURE = "instance-background";
535
+
536
+ /** The rows the Background section holds (#1579; Pepe, 2026-10-27): a row whose own `background` is exactly
537
+ * `true`, or one with such an ancestor in its `parentInstance` chain among the rows present (resolved by
538
+ * identity, resolveLinkId over the FULL roster, cycle-safe; a parent that resolves to nothing ends the chain).
539
+ * So a background row's children stay under it whatever their own value. Placement only: a row's own flag is
540
+ * read, never changed (no inheritance). `enabled`: the CLI lists `instance-background`; without it the set is
541
+ * empty whatever a row carries (a stray field is ignored). Returns Set<instanceId>. */
542
+ export function backgroundPlacement(instances, enabled) {
543
+ const out = new Set();
544
+ if (!enabled) return out;
545
+ const byId = new Map(instances.map((i) => [instanceId(i), i]));
546
+ const byName = new Map();
547
+ for (const i of instances) {
548
+ if (!byName.has(i.instance)) byName.set(i.instance, []);
549
+ byName.get(i.instance).push(i);
550
+ }
551
+ const known = new Map(); // instanceId -> placed in Background
552
+ for (const row of instances) {
553
+ // Walk up until a background row, a row already decided, the top, or a cycle; every row walked shares the answer.
554
+ const path = [], seen = new Set();
555
+ let cursor = row, placed = false;
556
+ while (cursor) {
557
+ const id = instanceId(cursor);
558
+ if (known.has(id)) { placed = known.get(id); break; }
559
+ if (seen.has(id)) break;
560
+ seen.add(id); path.push(id);
561
+ if (cursor.background === true) { placed = true; break; }
562
+ const pid = cursor.parentInstance ? resolveLinkId(cursor, cursor.parentInstance, byName) : null;
563
+ cursor = pid ? byId.get(pid) : null;
564
+ }
565
+ for (const id of path) known.set(id, placed);
566
+ }
567
+ for (const [id, placed] of known) if (placed) out.add(id);
568
+ return out;
569
+ }
570
+
521
571
  /** Whether an item remains visible under VS Code-style collapsed ancestors.
522
572
  * Filtering temporarily reveals matching paths without mutating the user's
523
573
  * persisted collapse state. Parent traversal is cycle-safe and
@@ -154,21 +154,38 @@ export const FLAG_IGNORED_BYTES = FLAG_IGNORED_UNITS * 6 + 256;
154
154
  * The fact is `{reason, warnings, omitted}`. `reason` is the one value the notice has a clause for, else
155
155
  * null. `warnings` is the answer's warnings in the order given, each as one display line: the withheld
156
156
  * marker for one the filter withholds, and no line for an entry with nothing to show. None is picked,
157
- * matched or dropped by its words: no client looks for the kernel's sentence among them. Lines are kept in
158
- * order while both bounds hold: FLAG_IGNORED_WARNINGS lines, FLAG_IGNORED_UNITS units in total. The first
159
- * line that does not fit and every line after it are left out, and no line is cut inside; the first line
160
- * always fits (a display line is at most MAX_DISPLAY_LINE units). `omitted` counts the lines left out, 0
161
- * when none. An entry with nothing to show was never a line and is not counted. */
157
+ * matched or dropped by its words: no client looks for the kernel's sentence among them. The cut is
158
+ * boundedWarnings's. */
162
159
  export function launchFlagIgnored(answer) {
163
160
  if (!record(answer) || !record(answer.launchPrompts) || answer.launchPrompts.status !== 'flag-ignored') return null;
164
- const lines = Array.isArray(answer.warnings) ? answer.warnings.map(w => displayLine(w)).filter(line => line !== null) : [];
161
+ return { reason: answer.launchPrompts.reason === 'channels-unavailable' ? 'channels-unavailable' : null, ...boundedWarnings(answer.warnings) };
162
+ }
163
+ /** An answer's raw `warnings` as `{warnings, omitted}`: one display line per entry, in order, the withheld
164
+ * marker for one the filter withholds and no line for an entry with nothing to show (not an array: no
165
+ * lines). Lines are kept in order while both bounds hold: FLAG_IGNORED_WARNINGS lines, FLAG_IGNORED_UNITS
166
+ * units in total. The first line that does not fit and every line after it are left out, and no line is cut
167
+ * inside; the first line always fits (a display line is at most MAX_DISPLAY_LINE units). `omitted` counts
168
+ * the lines left out, 0 when none; an entry with nothing to show was never a line and is not counted. By
169
+ * position only, never by words. Shared by launchFlagIgnored and the session-resume reader. */
170
+ export function boundedWarnings(raw) {
171
+ const lines = Array.isArray(raw) ? raw.map(w => displayLine(w)).filter(line => line !== null) : [];
165
172
  const warnings = [];
166
173
  let units = 0;
167
174
  for (const line of lines) {
168
175
  if (warnings.length === FLAG_IGNORED_WARNINGS || units + line.length > FLAG_IGNORED_UNITS) break;
169
176
  warnings.push(line); units += line.length;
170
177
  }
171
- return { reason: answer.launchPrompts.reason === 'channels-unavailable' ? 'channels-unavailable' : null, warnings, omitted: lines.length - warnings.length };
178
+ return { warnings, omitted: lines.length - warnings.length };
179
+ }
180
+ /** Whether `{warnings, omitted}` could be boundedWarnings's answer as it crossed a boundary: display lines
181
+ * within both bounds, `omitted` a non-negative safe integer, above 0 only where a cut can have happened
182
+ * (beside a full list, or beside lines that leave no room for another of MAX_DISPLAY_LINE units). */
183
+ export function boundedWarningsValid(warnings, omitted) {
184
+ if (!Array.isArray(warnings) || warnings.length > FLAG_IGNORED_WARNINGS || !warnings.every(cleanLine)
185
+ || !Number.isSafeInteger(omitted) || omitted < 0) return false;
186
+ const units = warnings.reduce((sum, line) => sum + line.length, 0);
187
+ return units <= FLAG_IGNORED_UNITS
188
+ && !(omitted > 0 && warnings.length < FLAG_IGNORED_WARNINGS && units <= FLAG_IGNORED_UNITS - MAX_DISPLAY_LINE);
172
189
  }
173
190
  /** The fact above as it crossed a boundary: the same fact, or undefined. Exactly the three keys; `reason`
174
191
  * the one known value or null; `warnings` display lines within both bounds; `omitted` a non-negative safe
@@ -177,12 +194,7 @@ export function launchFlagIgnored(answer) {
177
194
  * one fact and never what carried it. Idempotent: the reader's own answer decodes to itself. */
178
195
  export function flagIgnoredFact(v) {
179
196
  if (!record(v) || Object.keys(v).length !== 3 || !['reason', 'warnings', 'omitted'].every(k => Object.hasOwn(v, k))
180
- || v.reason !== null && v.reason !== 'channels-unavailable'
181
- || !Array.isArray(v.warnings) || v.warnings.length > FLAG_IGNORED_WARNINGS || !v.warnings.every(cleanLine)
182
- || !Number.isSafeInteger(v.omitted) || v.omitted < 0) return undefined;
183
- const units = v.warnings.reduce((sum, line) => sum + line.length, 0);
184
- if (units > FLAG_IGNORED_UNITS
185
- || v.omitted > 0 && v.warnings.length < FLAG_IGNORED_WARNINGS && units <= FLAG_IGNORED_UNITS - MAX_DISPLAY_LINE) return undefined;
197
+ || v.reason !== null && v.reason !== 'channels-unavailable' || !boundedWarningsValid(v.warnings, v.omitted)) return undefined;
186
198
  return { reason: v.reason, warnings: [...v.warnings], omitted: v.omitted };
187
199
  }
188
200
  /** The notice for the fact, `{headline, detail?}`, or null when `fact` is not one. `instance` is the name
@@ -16,6 +16,8 @@ export const CLIENT_OWN_CODES = Object.freeze([
16
16
  'E_REMOTE_ROSTER', 'E_WORKSPACE_FEATURE', 'E_WORKSPACE_UNKNOWN',
17
17
  // This computer's deployments list (#1390): a CLI without it.
18
18
  'E_DEPLOYMENTS_FEATURE',
19
+ // The machine's session resume sweep (#1559): a CLI without it.
20
+ 'E_RESUME_FEATURE',
19
21
  // A spawn: its preview, its apply and the wake saved with it; a suggest read a newer one ended (E_SUPERSEDED, #1421 §3).
20
22
  'E_APPLY_UNAVAILABLE', 'E_BACKEND_UNAVAILABLE', 'E_BUSY', 'E_FORBIDDEN_FRAME', 'E_INPUT_PREPARATION', 'E_INSTANCE_GONE',
21
23
  'E_INTENT_EXPIRED', 'E_OUTCOME_UNKNOWN', 'E_PREFLIGHT_INCOMPLETE', 'E_PREVIEW_UNAVAILABLE', 'E_SUPERSEDED', 'E_TARGET_CHANGED',
@@ -46,6 +46,7 @@ import { teamMembers } from './team-members.mjs';
46
46
  import { requireTerms } from './client-terms.mjs';
47
47
  import { ROSTER_WORKSPACE_KEY } from './cli-adapter.mjs';
48
48
  import { waitingClaim } from './waiting-on-you.mjs';
49
+ import { sameWorkDeclared, withSameWorkGate } from './same-work.mjs';
49
50
 
50
51
  /** Roots come ONLY from the kernel's observed `status.root`; before (or
51
52
  * without) an observation there is nothing to act on. No layout guess. */
@@ -309,13 +310,20 @@ export function deploymentEntry(info, primary) {
309
310
  ...(info.reason && info.fix?.length ? { fix: [...info.fix] } : {}), ...(info.note ? { note: info.note } : {}) };
310
311
  }
311
312
 
312
- /** One deployment's own panel, as served before views. */
313
+ /** One deployment's own panel, as served before views. Each row carries whether its host declares
314
+ * instance-same-work (#1577), stamped here and nowhere else (same-work.mjs `withSameWorkGate`): `held.cli` for
315
+ * this computer's rows, and the group's host too for another machine's. */
313
316
  export function deploymentPanel(held, ws) {
314
317
  // Another machine's panel never says who made its `error`: the key is removed here whatever the panel carried.
315
318
  // A kept group's panel is made at the time it was read (#1124): a filtered read never makes it look newer.
316
- if (ws?.remote) { const { errorOrigin: _sent, ...panel } = remotePanel(ws.group, held.keptReadAt?.get?.(ws.group.id) ?? held.at); return { ...panel, observedAt: null, refreshing: held.remoteCollecting }; }
319
+ if (ws?.remote) {
320
+ const { errorOrigin: _sent, ...panel } = remotePanel(ws.group, held.keptReadAt?.get?.(ws.group.id) ?? held.at);
321
+ const declared = sameWorkDeclared(held.cli, ws.group);
322
+ return { ...panel, instances: panel.instances.map((row) => withSameWorkGate(row, declared)), observedAt: null, refreshing: held.remoteCollecting };
323
+ }
317
324
  const observed = ws ? held.snapshot.byWs.get(ws.id) : null;
318
- const instances = observed?.instances || [], kept = keptFailure(observed);
325
+ const declared = sameWorkDeclared(held.cli);
326
+ const instances = (observed?.instances || []).map((row) => withSameWorkGate(row, declared)), kept = keptFailure(observed);
319
327
  return {
320
328
  workspace: ws ? { id: ws.id, name: ws.name, team: null } : null,
321
329
  team: null,
@@ -44,7 +44,8 @@ export function remotePanel(group, at) {
44
44
  // A row's soul subtitle: its own group's soul list only, a string as the host reported it, never synthesized.
45
45
  const described = name => { const soul = (group.souls || []).find((a) => a?.name === name); return typeof soul?.description === "string" ? soul.description : null; };
46
46
  // A Herdr-recorded row is unsupported whatever the host's probe said: it cannot open or start.
47
- const instances = (group.instances || []).map(({ runtime: _released, runtimeErrorOrigin: _sent, retire: sentRetire, ...i }) => {
47
+ const instances = (group.instances || []).map(({ runtime: _released, runtimeErrorOrigin: _sent, retire: sentRetire, sameWork: sentSameWork,
48
+ sameWorkKnown: _gate, ...i }) => {
48
49
  const unsupported = unsupportedSession(i);
49
50
  const origin = unsupported ? unsupportedSessionOrigin(i) : group.probe.ok || (group.probe.error?.message && madeByKernel(group.probe.error)) ? "kernel" : "roster-read";
50
51
  const row = {
@@ -61,6 +62,9 @@ export function remotePanel(group, at) {
61
62
  ...(Object.hasOwn(i, "waitingOnYou") ? { waitingOnYou: waitingOnYouData(i.waitingOnYou) } : {}),
62
63
  // #1247: the host's retire state, relayed unchanged when it is in the contract (retire-state.mjs), else absent.
63
64
  ...(retireData(sentRetire) ? { retire: retireData(sentRetire) } : {}),
65
+ // #1577: the host's same-work flag, true only (anything else reads unflagged). `sameWorkKnown` is this
66
+ // client's own field (same-work.mjs), never a host's: whatever a host sent under it is dropped.
67
+ ...(sentSameWork === true ? { sameWork: true } : {}),
64
68
  ...(unsupported ? { running: null, runtimeState: "unsupported", runtimeError: unsupported } : {}),
65
69
  };
66
70
  return hasRuntimeError(row) && origin ? { ...row, runtimeErrorOrigin: origin } : row;
@@ -6,6 +6,7 @@
6
6
  * and a row carries `deployment: { id }`. Nothing is derived from a host name or a path beyond the
7
7
  * display label. A view with one deployment has one section and no heading. */
8
8
  import { rosterGroups, instanceId } from './instance-tree.mjs';
9
+ import { waitingClaim } from './waiting-on-you.mjs';
9
10
  import { machineLabelParts } from './deployment-label.mjs';
10
11
  import { requireTerms } from './client-terms.mjs';
11
12
 
@@ -54,14 +55,17 @@ export const rowStale = (row, deployments) => {
54
55
  * `[{ deployment|null, label|null, groups }]`, a group being `{ key, label, clusters }` as before.
55
56
  * `lastFocus` (Map<instanceId, time>, optional; the command palette's, #1383): each section's groups follow
56
57
  * last focus (rosterGroups), and the sections are ordered by the latest focus over each one's full roster,
57
- * most recent first, then the panel's order. Without it, the panel's order (the sidebar's and the TUI's). */
58
- export function rosterSections(instances, visible, deployments, terms, { lastFocus } = {}) {
58
+ * most recent first, then the panel's order. Without it, the panel's order (the sidebar's and the TUI's).
59
+ * `roster` (optional; #1579): the full roster `instances` is a part of (the main tree's rows or the Background
60
+ * section's, `sidebarSections`). Names resolve over its rows of the same deployment, and a relation to a row outside
61
+ * `instances` is none: that row's relatives are roots here. Without it, `instances`. */
62
+ export function rosterSections(instances, visible, deployments, terms, { lastFocus, roster = instances } = {}) {
59
63
  requireTerms(terms, 'rosterSections');
60
64
  const recency = lastFocus instanceof Map ? { lastFocus } : {};
61
- const groupsOf = (all, shown) => rosterGroups(all, shown, recency); // the relation groups the palette lists too
62
- if (!isMultiDeployment(deployments)) return [{ deployment: null, label: null, groups: groupsOf(instances, visible) }];
65
+ const groupsOf = (all, shown, whole) => rosterGroups(all, shown, { ...recency, roster: whole }); // the relation groups the palette lists too
66
+ if (!isMultiDeployment(deployments)) return [{ deployment: null, label: null, groups: groupsOf(instances, visible, roster) }];
63
67
  const sectionOf = splitByDeployment(deployments);
64
- const all = sectionOf(instances), shown = sectionOf(visible), labels = machineLabelParts(deployments, terms);
68
+ const all = sectionOf(instances), shown = sectionOf(visible), whole = sectionOf(roster), labels = machineLabelParts(deployments, terms);
65
69
  const label = ({ machine, tail }) => (tail ? `${machine} · ${tail}` : machine);
66
70
  const sections = deployments.map(d => ({ deployment: d, parts: labels.get(d.id), all: all.get(d.id), shown: shown.get(d.id) }));
67
71
  if (recency.lastFocus) {
@@ -77,7 +81,47 @@ export function rosterSections(instances, visible, deployments, terms, { lastFoc
77
81
  });
78
82
  }
79
83
  return sections.filter(s => s.shown.length)
80
- .map(s => ({ deployment: s.deployment, label: label(s.parts), machine: s.parts.machine, tail: s.parts.tail, groups: groupsOf(s.all, s.shown) }));
84
+ .map(s => ({ deployment: s.deployment, label: label(s.parts), machine: s.parts.machine, tail: s.parts.tail, groups: groupsOf(s.all, s.shown, whole.get(s.deployment.id)) }));
85
+ }
86
+
87
+ /** The section a row is painted in (#482, #1579), as a key: its deployment's, in the main tree or in the
88
+ * Background section (`placement`: instance-tree.mjs `backgroundPlacement`). A collapse hides, and rolls up,
89
+ * only rows of its own section: give it as `section` to `instanceVisibleInTree` and `waitingRollup`. Two rows
90
+ * are in one section exactly when their keys are equal; the key says nothing else. */
91
+ export function rosterSectionKey(deployments, placement = new Set()) {
92
+ const ids = Array.isArray(deployments) ? new Set(deployments.map(d => d?.id)) : new Set();
93
+ const primary = primaryDeployment(deployments)?.id ?? null;
94
+ return row => {
95
+ const id = rowDeployment(row);
96
+ const deployment = isMultiDeployment(deployments) ? (id && ids.has(id) ? id : primary) : null;
97
+ return `${placement.has(instanceId(row)) ? 'background' : 'main'}\u0000${deployment ?? ''}`;
98
+ };
99
+ }
100
+
101
+ /** The sidebar's roster and the TUI's (#1579): the main tree's sections, then the Background section.
102
+ * `instances`: the full roster; `visible`: the rows a filter and a collapse leave (instanceVisibleInTree, given
103
+ * `rosterSectionKey` as its section); `placement`: instance-tree.mjs `backgroundPlacement`.
104
+ * Options: `open`, whether the Background section is drawn open (the client's stored state, or a filter that is
105
+ * on: a filter shows its matches without changing what is stored); `listed`, the rows the filter leaves (all rows
106
+ * when nothing is filtered), which the heading counts; `stale(row)`, the client's held-stale test.
107
+ * Returns `{ main, background }`. `main` is `rosterSections` over the rows outside the section. `background` is
108
+ * null when no listed row is in the section (no heading is drawn), else `{ count, open, waiting, sections }`:
109
+ * `count` the listed rows in it, `waiting` whether any row in it waits (waitingClaim; open or closed, a filtered
110
+ * one included), and `sections` its own tree, `rosterSections` over its rows (with the machine sub-headings in a
111
+ * view of two or more deployments), empty while closed. Each part is a tree of its own: a relation to a row of the
112
+ * other part is none (a background row whose parent is in the main tree is a root of the Background section), and
113
+ * names still resolve over the full roster. The palette never asks this: it lists every row. */
114
+ export function sidebarSections(instances, visible, deployments, terms, { placement = new Set(), open = false, listed = instances, stale = () => false } = {}) {
115
+ requireTerms(terms, 'sidebarSections');
116
+ const inside = row => placement.has(instanceId(row));
117
+ const main = rosterSections(instances.filter(r => !inside(r)), visible.filter(r => !inside(r)), deployments, terms, { roster: instances });
118
+ const rows = instances.filter(inside), count = listed.filter(inside).length;
119
+ if (!count) return { main, background: null };
120
+ return { main, background: {
121
+ count, open: !!open,
122
+ waiting: rows.some(row => waitingClaim(row, { stale: stale(row) }) !== null),
123
+ sections: open ? rosterSections(rows, visible.filter(inside), deployments, terms, { roster: instances }) : [],
124
+ } };
81
125
  }
82
126
 
83
127
  /** `rows → Map<deployment id, rows>` over the given deployments; an unknown or missing deployment
@@ -0,0 +1,49 @@
1
+ /** Which parent→child lines a roster draws, and so the order under one parent (awebai/oats#1577, the contract
2
+ * on comment 6441606665, item 7). The one rule, shared by the Desktop's sidebar and command palette and by the
3
+ * TUI; neither client keeps a copy.
4
+ *
5
+ * The kernel reports `sameWork: true` on a child row that does the same work as its current parent (feature
6
+ * instance-same-work), and leaves the key out otherwise. It has already bound the flag to the current parent:
7
+ * a client reads `sameWork === true` and nothing more, and never compares parents.
8
+ *
9
+ * The gate: whether a row's host declares the feature. A local row: this computer's CLI advertises it. A remote
10
+ * row: this CLI advertises it and relays the hosts' own lists (server-probe-features), and the row's group's
11
+ * host names it (composed-gate.mjs `hostAdvertises`). Unknown is not supported: an unread or failed probe keeps
12
+ * today's lines. panel-views.mjs `deploymentPanel` stamps the gate's answer on each row it serves as
13
+ * `sameWorkKnown: true` (`withSameWorkGate`), present only when the host declares the feature; it is the
14
+ * client's own field, never the kernel's.
15
+ *
16
+ * Pure: no DOM, no Node builtin, so a page loads it as it is. */
17
+ import { hostAdvertises, PROBE_FEATURES_FEATURE } from './composed-gate.mjs';
18
+
19
+ export const SAME_WORK_FEATURE = 'instance-same-work';
20
+
21
+ const advertises = (cli, feature) => !!cli?.ok && Array.isArray(cli.features) && cli.features.includes(feature);
22
+
23
+ /** Whether a host declares the feature: `group` null for this computer's rows, else the remote roster group the
24
+ * rows came from. */
25
+ export function sameWorkDeclared(cli, group = null) {
26
+ if (!advertises(cli, SAME_WORK_FEATURE)) return false;
27
+ return group === null || (advertises(cli, PROBE_FEATURES_FEATURE) && hostAdvertises(group, SAME_WORK_FEATURE));
28
+ }
29
+
30
+ /** A row with the gate's answer stamped: `sameWorkKnown: true` when `declared`, else no key. Whatever the row
31
+ * carried under that key is dropped first, so a host can never set it. */
32
+ export function withSameWorkGate(row, declared) {
33
+ const { sameWorkKnown: _carried, ...rest } = row;
34
+ return declared ? { ...rest, sameWorkKnown: true } : rest;
35
+ }
36
+
37
+ /** A row the client made itself (a pending spawn's) has no stamp: it takes its parent's, since a child is on its
38
+ * parent's host (instance-tree.mjs `resolveLinkId` never resolves across hosts). `parent` is the row its
39
+ * `parentInstance` resolves to, or null. */
40
+ export const withParentGate = (row, parent) => withSameWorkGate(row, parent?.sameWorkKnown === true);
41
+
42
+ /** Whether a row draws the line to its parent: always when its host does not declare the feature (today's
43
+ * lines), else only when the kernel flagged it. A root has no parent line to draw, whatever this says. */
44
+ export const drawsParentLine = (row) => row?.sameWorkKnown !== true || row.sameWork === true;
45
+
46
+ /** The order of one parent's children, a comparator for a stable sort or a first key before another: the
47
+ * children that draw their parent line first, then those that don't. So a parent's line ends at its last
48
+ * joined child and never passes a child it doesn't join. Within each part the caller's own order stands. */
49
+ export const drawingFirst = (a, b) => Number(!drawsParentLine(a)) - Number(!drawsParentLine(b));
@@ -28,6 +28,12 @@ import { HERDR_REMOVED, terminalFailure, terminalMessage } from './terminal-cont
28
28
 
29
29
  /** The kernel feature of `session attach --detach-key` (docs/desktop-cli-api.md). */
30
30
  export const DETACH_KEY_FEATURE = "session-attach-detach-key";
31
+ /** The kernel feature of `session attach --no-status-line` (lib/session-viewer.mjs, the same
32
+ * name): the viewer without its status line, for a client that shows the scroll keys itself. */
33
+ export const NO_STATUS_LINE_FEATURE = "session-attach-no-status-line";
34
+ /** The kernel feature of `sessionViewer.prefixScroll` (lib/session-viewer.mjs, the same name): a
35
+ * kernel that lists it has the viewer's own Shift+PageUp, and says whether its viewer takes C-b [. */
36
+ export const PREFIX_SCROLL_FEATURE = "session-attach-prefix-scroll";
31
37
  /** The kernel feature under which a roster group's `probe.features` is the host's own list
32
38
  * (docs/desktop-cli-api.md, `probe.features`). Without it that key says nothing. */
33
39
  const PROBE_FEATURES_FEATURE = "server-probe-features";
@@ -51,6 +57,26 @@ export function hostDetachKeySupported(cli, group) {
51
57
  && probe?.ok === true && Array.isArray(probe.features) && probe.features.includes(DETACH_KEY_FEATURE);
52
58
  }
53
59
 
60
+ /** The viewer's scroll keys a client may name for a tab, `{ shift, prefix }`, from what the tab's
61
+ * host's kernel says (docs/desktop-cli-api.md, `session-attach-prefix-scroll`): a kernel that lists
62
+ * the feature has Shift+PageUp, and C-b [ too where its `sessionViewer.prefixScroll` is true. A
63
+ * kernel without the feature, or one not known, has neither: an older viewer may pass Shift+PageUp
64
+ * to the agent. */
65
+ function scrollKeysOf(facts) {
66
+ const listed = Array.isArray(facts?.features) && facts.features.includes(PREFIX_SCROLL_FEATURE);
67
+ return { shift: listed, prefix: listed && facts.sessionViewer?.prefixScroll === true };
68
+ }
69
+ /** A tab of this machine: this machine's accepted probe (`cli`, lib/cli-locator.mjs cliRecord). */
70
+ export function localScrollKeys(cli) {
71
+ return scrollKeysOf(cli?.ok === true ? cli : null);
72
+ }
73
+ /** A tab of another machine: the group's last roster read, when this machine's CLI relays what each
74
+ * host lists about itself and that read succeeded; otherwise unknown, so neither key. */
75
+ export function hostScrollKeys(cli, group) {
76
+ const probe = group?.probe;
77
+ return scrollKeysOf(lists(cli, PROBE_FEATURES_FEATURE) && probe?.ok === true ? probe : null);
78
+ }
79
+
54
80
  const coded = (code, message) => Object.assign(new Error(message), { code });
55
81
  const herdrRemoved = message => coded('E_HERDR_REMOVED', message);
56
82
  const unreachable = () => coded('E_TERM_REMOTE_UNREACHABLE', 'the remote server could not be reached');
@@ -111,13 +137,16 @@ export function remoteTargetKey(remote) {
111
137
  * target { home } on this machine; { serverId, instance, home } on another (what
112
138
  * `remoteTargetKey` admits, and it refuses as it always did)
113
139
  * detachKey undefined for none; else a non-empty string, appended as `--detach-key <key>`
140
+ * statusLine false for a viewer without its status line, the scroll keys (`--no-status-line`),
141
+ * asked only of a CLI that advertises NO_STATUS_LINE_FEATURE: one without it
142
+ * shows the line whatever it is asked, so it is asked nothing
114
143
  *
115
144
  * The client holds no copy of the kernel's key grammar: a key the kernel does not accept is the
116
145
  * kernel's refusal. A key for a CLI that does not take one throws `unsupported-detach-key`: a
117
146
  * kernel without the feature ignores the flag and opens a viewer with no exit, so the flag is
118
147
  * never tried (docs/desktop-cli-api.md). Its message is for a developer; a client decides what it
119
148
  * offers with `detachKeySupported`. */
120
- export function sessionAttachArgv(cli, target, { detachKey } = {}) {
149
+ export function sessionAttachArgv(cli, target, { detachKey, statusLine = true } = {}) {
121
150
  let address;
122
151
  if (target?.serverId !== undefined) {
123
152
  remoteTargetKey(target);
@@ -126,10 +155,11 @@ export function sessionAttachArgv(cli, target, { detachKey } = {}) {
126
155
  if (typeof target?.home !== "string" || !target.home.startsWith("/") || target.home.includes("\0")) throw new Error("invalid session home");
127
156
  address = ["--home", target.home];
128
157
  }
129
- if (detachKey === undefined) return ["session", "attach", ...address];
158
+ const quiet = statusLine === false && Array.isArray(cli?.features) && cli.features.includes(NO_STATUS_LINE_FEATURE) ? ["--no-status-line"] : [];
159
+ if (detachKey === undefined) return ["session", "attach", ...address, ...quiet];
130
160
  if (typeof detachKey !== "string" || !detachKey) throw new TypeError("a detach key is a non-empty string");
131
161
  if (!detachKeySupported(cli)) throw Object.assign(new Error(`installed oats ${cli?.version || "unknown"} does not support session attach --detach-key; update the CLI`), { code: "unsupported-detach-key" });
132
- return ["session", "attach", ...address, "--detach-key", detachKey];
162
+ return ["session", "attach", ...address, "--detach-key", detachKey, ...quiet];
133
163
  }
134
164
  /** The preflight of an attach on another machine, and the viewer to start after it: { binary, args }.
135
165
  *
@@ -139,14 +169,14 @@ export function sessionAttachArgv(cli, target, { detachKey } = {}) {
139
169
  * detachKey as `sessionAttachArgv` takes it. The viewer's arguments are built before the
140
170
  * inspect runs, so a key that cannot be used starts no process; the inspect never
141
171
  * carries the key. */
142
- export async function prepareRemoteTerm(cli, remote, { exec, run = (binary, args, options) => runTerminalCommand(binary, args, options, exec), signal, current = () => true, detachKey } = {}) {
172
+ export async function prepareRemoteTerm(cli, remote, { exec, run = (binary, args, options) => runTerminalCommand(binary, args, options, exec), signal, current = () => true, detachKey, statusLine } = {}) {
143
173
  const check = () => { if (signal?.aborted || !current()) throw Object.assign(new Error('Terminal context changed'), { code: 'E_TERM_CONTEXT_CHANGED' }); };
144
174
  check();
145
175
  requireRemoteSupport(cli, "session");
146
176
  const bin = cli.bin;
147
177
  remoteTargetKey(remote);
148
178
  const address = ["--server", remote.serverId, "--home", remote.home];
149
- const args = sessionAttachArgv(cli, remote, { detachKey });
179
+ const args = sessionAttachArgv(cli, remote, { detachKey, statusLine });
150
180
  check(); // actual execution owner, not only IPC admission
151
181
  let stdout;
152
182
  try {
@@ -0,0 +1,64 @@
1
+ /** The kernel's machine sweep, `oats session resume --json`, run by a client at its launch: it resumes every
2
+ * lost session on every local deployment. The answer is read by session-resume.mjs; this home runs it and
3
+ * passes on only the kernel's JSON: its envelope, a refusal's code and message, or a code of its own.
4
+ * argv ['session', 'resume', '--json']: no `--deployment` and no `--plan` from a client.
5
+ * cwd '/': the kernel resolves no deployment from the client's working directory.
6
+ * env the client's, cleaned (cli-environment.mjs) and without the instance variables (kernel-environment.mjs):
7
+ * a client started inside an instance must not scope the sweep to it. OATS_HOME_DIR passes through.
8
+ * It needs a compatible CLI (`cli.ok`, an absolute `cli.bin`) and the probe's `session-resume` feature: without
9
+ * either it runs nothing, and nothing falls back. There is no client-side deadline: the sweep starts sessions,
10
+ * and a client waits as long as it runs; when the client is gone first, the answer is just not shown. */
11
+ import { cliEnvironment } from './cli-environment.mjs';
12
+ import { withoutInstanceVariables } from './kernel-environment.mjs';
13
+ import { parseEnvelope } from './cli-adapter.mjs';
14
+ import { kernelMade } from './kernel-made.mjs';
15
+ import { execFileToFiles } from './file-output-exec.mjs';
16
+
17
+ export const SESSION_RESUME_FEATURE = 'session-resume';
18
+ /** A row per instance of every local deployment, with the start answer's warnings: far below this. */
19
+ export const SESSION_RESUME_MAX_BUFFER = 4 * 1024 * 1024;
20
+ const ARGV = Object.freeze(['session', 'resume', '--json']);
21
+ const CODE = /^E_[A-Z0-9_]{1,64}$/;
22
+
23
+ const compatible = (cli) => cli?.ok === true && typeof cli.bin === 'string' && cli.bin.startsWith('/');
24
+ /** Whether a probe (`oats version --json`, accepted, with an absolute bin) declares the sweep. */
25
+ export const resumeSupported = (cli) => compatible(cli) && Array.isArray(cli.features) && cli.features.includes(SESSION_RESUME_FEATURE);
26
+
27
+ /** A failure this home writes itself: a code and nothing else (no message, no stderr, no thrown text). */
28
+ const failure = (code) => ({ schemaVersion: 1, ok: false, error: { code } });
29
+ /** The kernel's refusal, passed on as its code and, when a string, its message (kernel prose, marked the kernel's). */
30
+ function refusal(error) {
31
+ if (typeof error?.code !== 'string' || !CODE.test(error.code)) return failure('E_CLI_PROTOCOL');
32
+ return { schemaVersion: 1, ok: false, error: kernelMade({ code: error.code, ...(typeof error.message === 'string' ? { message: error.message } : {}) }) };
33
+ }
34
+
35
+ /**
36
+ * Run the sweep once. `cli` is the client's accepted probe (`{ ok, bin, features }`).
37
+ * `io.exec` is the caller's exec, with execFile's signature; it defaults to execFileToFiles. A caller's exec MUST
38
+ * start the child detached (a session of its own), give it files and never pipes for its output, and never
39
+ * signal it: the sweep outlives the client that started it (the TUI passes its `changeExec`). No `timeout` is
40
+ * given. `io.env` replaces process.env as the environment cleaned.
41
+ * Never rejects. Resolves the parsed `{ schemaVersion: 1, ok: true, result }` (exit 0 only); the kernel's refusal
42
+ * `{ schemaVersion: 1, ok: false, error: { code, message } }` whatever the exit (E_RESUME_BUSY exits 1); or
43
+ * `{ schemaVersion: 1, ok: false, error: { code } }`: E_CLI_UNAVAILABLE, E_RESUME_FEATURE (nothing ran),
44
+ * E_CLI_OUTPUT_LIMIT (over SESSION_RESUME_MAX_BUFFER), E_CLI_PROTOCOL (no envelope, or a refusal without a valid
45
+ * code), E_CLI_FAILED (a nonzero exit with no refusal, or an exec that threw).
46
+ */
47
+ export function runResumeSweep(cli, io = {}) {
48
+ if (!compatible(cli)) return Promise.resolve(failure('E_CLI_UNAVAILABLE'));
49
+ if (!resumeSupported(cli)) return Promise.resolve(failure('E_RESUME_FEATURE'));
50
+ const env = withoutInstanceVariables(cliEnvironment(io.env ?? process.env));
51
+ return new Promise((done) => {
52
+ const fail = (code) => done(failure(code));
53
+ try {
54
+ (io.exec ?? execFileToFiles)(cli.bin, [...ARGV], { cwd: '/', env, shell: false, encoding: 'utf8', maxBuffer: SESSION_RESUME_MAX_BUFFER }, (error, stdout) => {
55
+ if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return fail('E_CLI_OUTPUT_LIMIT');
56
+ const envelope = parseEnvelope(stdout);
57
+ if (!envelope) return fail(error ? 'E_CLI_FAILED' : 'E_CLI_PROTOCOL');
58
+ if (envelope.ok === false) return done(refusal(envelope.error));
59
+ if (error) return fail('E_CLI_FAILED'); // success is exit 0 only
60
+ done(envelope);
61
+ });
62
+ } catch { fail('E_CLI_FAILED'); }
63
+ });
64
+ }