@awebai/oats 0.58.0 → 0.59.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 (53) hide show
  1. package/bin/oats.mjs +1 -1
  2. package/docs/desktop-cli-api.md +68 -3
  3. package/docs/desktop.md +30 -3
  4. package/docs/execution-targets.md +11 -0
  5. package/docs/implementation.md +2 -0
  6. package/docs/integrations.md +2 -2
  7. package/docs/knowledge.md +4 -4
  8. package/docs/official-catalog.md +4 -4
  9. package/docs/packages.md +14 -14
  10. package/docs/release-notes/v0.59.0.md +288 -0
  11. package/docs/servers.md +4 -1
  12. package/docs/souls-and-instances.md +21 -0
  13. package/docs/tui.md +644 -118
  14. package/docs/workspaces.md +2 -2
  15. package/lib/core.mjs +216 -42
  16. package/lib/read-ahead-worker.mjs +119 -0
  17. package/lib/read-ahead.mjs +115 -0
  18. package/lib/retire-state.mjs +33 -0
  19. package/lib/servers.mjs +9 -1
  20. package/lib/session-input.mjs +14 -4
  21. package/package-catalog.json +3 -3
  22. package/package.json +1 -1
  23. package/packages/client/cli-locator.mjs +2 -2
  24. package/packages/client/deployment-data.mjs +4 -0
  25. package/packages/client/deployment-panel.mjs +3 -0
  26. package/packages/client/instance-acts.mjs +23 -8
  27. package/packages/client/instance-presentation.mjs +3 -2
  28. package/packages/client/instance-tree.mjs +84 -39
  29. package/packages/client/lifecycle-confirmation.mjs +9 -3
  30. package/packages/client/remote-roster.mjs +4 -1
  31. package/packages/client/retire-in-flight.mjs +65 -0
  32. package/packages/client/retire-state.mjs +30 -0
  33. package/packages/client/spawn-apply.mjs +13 -4
  34. package/packages/tui/README.md +23 -10
  35. package/packages/tui/lib/actions.mjs +63 -5
  36. package/packages/tui/lib/client.mjs +12 -1
  37. package/packages/tui/lib/config.mjs +7 -2
  38. package/packages/tui/lib/main.mjs +315 -82
  39. package/packages/tui/lib/model.mjs +523 -56
  40. package/packages/tui/lib/panel.mjs +436 -125
  41. package/packages/tui/lib/read.mjs +52 -26
  42. package/packages/tui/lib/store.mjs +908 -65
  43. package/packages/tui/lib/term/keys.mjs +9 -2
  44. package/packages/tui/lib/term/text.mjs +4 -0
  45. package/packages/tui/lib/term/through.mjs +12 -1
  46. package/packages/tui/lib/views/frame.mjs +394 -95
  47. package/packages/tui/lib/views/help.mjs +54 -13
  48. package/packages/tui/lib/views/instances.mjs +43 -25
  49. package/packages/tui/lib/views/palette.mjs +61 -0
  50. package/packages/tui/lib/views/souls.mjs +268 -0
  51. package/packages/tui/lib/views/spawn.mjs +299 -0
  52. package/packages/tui/lib/views/split.mjs +29 -0
  53. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -0,0 +1,115 @@
1
+ /** Read-ahead for the tree digests (fingerprintTrees): while a digest reads a
2
+ * tree, file by file, on the calling thread, worker threads read the files it
3
+ * will read next, several at once, so that its own reads come from the page
4
+ * cache. A digest of a cold tree of many small files is otherwise bound by
5
+ * the latency of one read at a time (#1247).
6
+ *
7
+ * It changes nothing the digest computes. The digest reads every byte it
8
+ * hashes itself, with the same calls, in the same order, and an error is the
9
+ * error its own read meets: the readers' results and errors are dropped. A
10
+ * recovery copy's verification therefore still reads the copy's own bytes.
11
+ * A read-ahead that cannot start, falls behind or stops costs speed only, and
12
+ * the caller never waits for it: it stays synchronous.
13
+ *
14
+ * Bounds: at most `readers` files are read at once (one per reader thread),
15
+ * each through one reused 1 MiB buffer, so the threads hold `readers` MiB.
16
+ * The planner never runs more than `windowKiB` of file bytes or
17
+ * `windowFiles` files ahead of what the digest has read, so what it brings
18
+ * into the cache is read soon after; a file larger than the window is left
19
+ * to the digest. The page cache is the kernel's, reclaimable, not this
20
+ * process's memory. */
21
+ import { availableParallelism } from "node:os";
22
+ import { Worker } from "node:worker_threads";
23
+
24
+ /** The shared counters (an Int32Array over a SharedArrayBuffer). */
25
+ export const CTL = { JOB: 0, CONSUMED_KIB: 1, CONSUMED_FILES: 2, IN_FLIGHT: 3, MAX_IN_FLIGHT: 4, MAX_AHEAD_KIB: 5, MAX_AHEAD_FILES: 6 };
26
+ const CTL_LENGTH = 7;
27
+
28
+ const defaults = () => ({ enabled: true, readers: Math.min(4, Math.max(2, availableParallelism())), windowKiB: 64 * 1024, windowFiles: 4096 });
29
+ let settings = defaults();
30
+ // undefined: not started yet; null: could not start, and is not tried again.
31
+ let pool;
32
+ let active = false;
33
+ let unnotifiedKiB = 0, unnotifiedFiles = 0;
34
+
35
+ function started() {
36
+ if (pool !== undefined) return pool;
37
+ try {
38
+ const ctl = new Int32Array(new SharedArrayBuffer(CTL_LENGTH * Int32Array.BYTES_PER_ELEMENT));
39
+ const planner = new Worker(new URL("./read-ahead-worker.mjs", import.meta.url), {
40
+ // Not the process's own flags (an --import preload, a profiler): the threads only read.
41
+ execArgv: [],
42
+ workerData: { role: "planner", ctl, readers: settings.readers, windowKiB: settings.windowKiB, windowFiles: settings.windowFiles },
43
+ });
44
+ planner.on("error", () => { if (pool?.planner === planner) pool = null; });
45
+ // Never what keeps the process alive.
46
+ planner.unref();
47
+ pool = { planner, ctl };
48
+ } catch {
49
+ pool = null;
50
+ }
51
+ return pool;
52
+ }
53
+
54
+ /** Run `fn` (a digest of `roots`, paths as text or bytes, read in this order)
55
+ * with the files of `roots` read ahead → what `fn` returns. The walk is the
56
+ * digest's: `order` "bytes" (the names' bytes) or "locale" (their text by
57
+ * localeCompare, the legacy stored digest), passing over `excludeRoot` (top-level
58
+ * names, as text) and `excludePaths` (paths under a root, as bytes). Inside
59
+ * another read-ahead, `fn` simply runs: that one already reads its files. */
60
+ export function readingAhead(roots, { order = "bytes", excludeRoot = [], excludePaths = [] } = {}, fn) {
61
+ if (active || !settings.enabled) return fn();
62
+ const p = started();
63
+ if (!p) return fn();
64
+ const { ctl, planner } = p;
65
+ for (const i of [CTL.CONSUMED_KIB, CTL.CONSUMED_FILES, CTL.MAX_IN_FLIGHT, CTL.MAX_AHEAD_KIB, CTL.MAX_AHEAD_FILES]) Atomics.store(ctl, i, 0);
66
+ const job = Atomics.add(ctl, CTL.JOB, 1) + 1;
67
+ try {
68
+ planner.postMessage({ job, roots: roots.map((root) => Buffer.from(root)), order, excludeRoot: [...excludeRoot], excludePaths: excludePaths.map((path) => Buffer.from(path).toString("hex")) });
69
+ } catch {
70
+ return fn();
71
+ }
72
+ active = true;
73
+ unnotifiedKiB = 0; unnotifiedFiles = 0;
74
+ try {
75
+ return fn();
76
+ } finally {
77
+ active = false;
78
+ // The job ends: the planner stops, and the readers drop what is queued.
79
+ Atomics.add(ctl, CTL.JOB, 1);
80
+ Atomics.notify(ctl, CTL.CONSUMED_KIB);
81
+ }
82
+ }
83
+
84
+ /** Tell the read-ahead that the digest has read a file of `bytes` bytes. */
85
+ export function readAheadConsumed(bytes) {
86
+ if (!active) return;
87
+ const { ctl } = pool;
88
+ const kib = Math.ceil(bytes / 1024);
89
+ Atomics.add(ctl, CTL.CONSUMED_KIB, kib);
90
+ Atomics.add(ctl, CTL.CONSUMED_FILES, 1);
91
+ // The planner is woken once per eighth of the window read, not per file: a
92
+ // wake costs the digest's thread more than a small file's read.
93
+ unnotifiedKiB += kib; unnotifiedFiles++;
94
+ if (unnotifiedKiB >= settings.windowKiB / 8 || unnotifiedFiles >= settings.windowFiles / 8) {
95
+ unnotifiedKiB = 0; unnotifiedFiles = 0;
96
+ Atomics.notify(ctl, CTL.CONSUMED_KIB);
97
+ }
98
+ }
99
+
100
+ /** For tests: the defaults with `options` over them (a new pool starts with
101
+ * them); with none, the defaults. */
102
+ export function configureReadAhead(options) {
103
+ settings = { ...defaults(), ...options };
104
+ if (pool) pool.planner.terminate().catch(() => {});
105
+ pool = undefined;
106
+ }
107
+
108
+ /** For tests: the highest number of files read at once, and the most the
109
+ * planner ran ahead of the digest (KiB and files), in the last read-ahead.
110
+ * → undefined when no read-ahead has run. */
111
+ export function readAheadStats() {
112
+ if (!pool) return undefined;
113
+ const { ctl } = pool;
114
+ return { maxInFlight: Atomics.load(ctl, CTL.MAX_IN_FLIGHT), maxAheadKiB: Atomics.load(ctl, CTL.MAX_AHEAD_KIB), maxAheadFiles: Atomics.load(ctl, CTL.MAX_AHEAD_FILES), readers: settings.readers, windowKiB: settings.windowKiB, windowFiles: settings.windowFiles };
115
+ }
@@ -0,0 +1,33 @@
1
+ /** A status row's `retire` (feature status-retire-state): whether a retire of the home runs, could
2
+ * not be told, failed or was interrupted. The kernel's row reads it from the facts beside the home
3
+ * (lib/core.mjs retireStateOf); a remote row relays the host's (lib/servers.mjs). Both go through
4
+ * readRetireState, so a value either shows as this module reads it or not at all. */
5
+ import { retireRefusedReason } from "./instance-events.mjs";
6
+
7
+ export const RETIRE_STATES = ["running", "unknown", "failed", "interrupted"];
8
+ /** The code a `failed` state may carry: a kernel code's shape. Any other is left out. */
9
+ export const RETIRE_STATE_CODE_RE = /^E_[A-Z0-9_]+$/;
10
+ const ISO_INSTANT = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/;
11
+ /** Whether `at` is an instant exactly as `toISOString()` gives it, and one that exists. */
12
+ export const isInstant = (at) => typeof at === "string" && ISO_INSTANT.test(at) && !Number.isNaN(Date.parse(at)) && new Date(at).toISOString() === at;
13
+
14
+ /** `value` as a row's `retire` → `{ state, since, self, code?, message? }`, or undefined when it is
15
+ * none: an object whose `state` is one of RETIRE_STATES, whose `since` is an instant as
16
+ * `toISOString()` gives it, and whose `self` is a boolean. `since` is required: the Desktop drops
17
+ * a value without one, and a failed retire would then read as one still running. `code` and
18
+ * `message` belong to `failed` only, and are strings or absent, never null: `code` when it has a
19
+ * kernel code's shape; `message` on one line and at most the length of a retire's one-line reason
20
+ * (retireRefusedReason), and left out when it is empty. */
21
+ export function readRetireState(value) {
22
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
23
+ const { state, since, self, code, message } = value;
24
+ if (!RETIRE_STATES.includes(state) || !isInstant(since) || typeof self !== "boolean") return undefined;
25
+ const line = state === "failed" && typeof message === "string" ? retireRefusedReason(message) : "";
26
+ return {
27
+ state,
28
+ since,
29
+ self,
30
+ ...(state === "failed" && typeof code === "string" && RETIRE_STATE_CODE_RE.test(code) ? { code } : {}),
31
+ ...(line ? { message: line } : {}),
32
+ };
33
+ }
package/lib/servers.mjs CHANGED
@@ -24,6 +24,7 @@ import { basename, join, resolve } from "node:path";
24
24
  import { parseStrictJson } from "./canonical-json.mjs";
25
25
  import { noteRuntimeName } from "./deprecation.mjs";
26
26
  import { readWaitingClaim } from "./instance-events.mjs";
27
+ import { readRetireState } from "./retire-state.mjs";
27
28
  import { withDirLock } from "./dir-lock.mjs";
28
29
  import { shellWord } from "./core.mjs";
29
30
  import { DETACH_KEY_FEATURE, requireDetachKey } from "./session-viewer.mjs";
@@ -870,6 +871,13 @@ const rowFacts = (i = {}) => Object.fromEntries(REMOTE_ROW_FACTS.map((k) => [k,
870
871
  * omits it, and absent ("not reported") must stay distinct from null ("no claim"). The
871
872
  * value passes the kernel's own read rule again; anything it refuses is null. */
872
873
  const rowWaiting = (i) => (Object.hasOwn(i, "waitingOnYou") ? { waitingOnYou: readWaitingClaim(i.waitingOnYou) } : {});
874
+ /** `retire` (feature status-retire-state) the same way, relayed ONLY when the host's row has the
875
+ * key: a host whose kernel predates the feature omits it, and its rows say nothing. Absent is the
876
+ * only reading of "no retire", so a value the kernel's own read refuses is dropped, never null. */
877
+ const rowRetire = (i) => {
878
+ const retire = Object.hasOwn(i, "retire") ? readRetireState(i.retire) : undefined;
879
+ return retire ? { retire } : {};
880
+ };
873
881
 
874
882
  /** The bounds a host's `features` list must meet to be relayed (feature server-probe-features). */
875
883
  export const HOST_FEATURES_MAX = 256;
@@ -962,7 +970,7 @@ export async function rosterGroups({ server, workspaceKeys, io = {} } = {}) {
962
970
  harness: i.harness || i.runtime || null, backend: i.tmux ? "tmux" : null,
963
971
  ...(i.sessionTarget ? { sessionTarget: i.sessionTarget } : {}), ...(i.tmux ? { tmux: i.tmux } : {}),
964
972
  running: typeof i.running === "boolean" ? i.running : null, ...(i.runtimeError ? { runtimeError: i.runtimeError } : {}),
965
- ...rowFacts(i), ...rowWaiting(i),
973
+ ...rowFacts(i), ...rowWaiting(i), ...rowRetire(i),
966
974
  // Every row the host reports is addressed by its home, saved
967
975
  // route or not; savedRoute says only that it was spawned from here.
968
976
  retirePending: !!i.retirePending, rollbackIncomplete: !!i.rollbackIncomplete, savedRoute: !!snap, addressable: true, missingRemotely: false,
@@ -13,10 +13,16 @@ function tmux(target, args, { exec = execFileSync, input, timeout = 10000, killS
13
13
  stdio: ["pipe", "pipe", "pipe"],
14
14
  });
15
15
  }
16
- export function inspectSessionTarget(target, io) {
16
+ // Public inspection opts into window geometry; input and other session operations
17
+ // retain their existing transport result and do not depend on size parsing.
18
+ export function inspectSessionTarget(target, io, { includeSize = false } = {}) {
19
+ const format = "#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"
20
+ + (includeSize ? "\t#{window_width}\t#{window_height}" : "");
17
21
  let rows;
18
22
  try {
19
- rows = tmux(target, ["list-panes", "-t", `=${target.session}:=${target.window}`, "-F", "#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"], io).trim().split("\n").filter(Boolean);
23
+ const output = tmux(target, ["list-panes", "-t", `=${target.session}:=${target.window}`, "-F", format], io);
24
+ // Preserve dimension whitespace for validation, and the original parsing for other callers.
25
+ rows = (includeSize ? output : output.trim()).split("\n").filter(Boolean);
20
26
  } catch (e) {
21
27
  // A missing window on a reachable server is absence. A lost socket is not.
22
28
  if (/can't find (window|session)/i.test(String(e.stderr || ""))) return { backend: "tmux", present: false, state: "stopped" };
@@ -24,8 +30,11 @@ export function inspectSessionTarget(target, io) {
24
30
  }
25
31
  if (!rows.length) return { backend: "tmux", present: false, state: "stopped" };
26
32
  if (rows.length !== 1) throw new Error("session window has multiple panes; choose an unsplit agent window");
27
- const [paneId, dead, command, panePid] = rows[0].split("\t");
33
+ const [paneId, dead, command, panePid, cols, rowsCount] = rows[0].split("\t");
28
34
  if (!/^%\d+$/.test(paneId) || !["0", "1"].includes(dead)) throw new Error("invalid tmux pane response");
35
+ if (includeSize && ![cols, rowsCount].every(value => /^[1-9]\d*$/.test(value) && Number.isSafeInteger(Number(value)))) {
36
+ throw new Error("invalid tmux pane response");
37
+ }
29
38
  let state = dead === "1" ? "stopped" : "unknown";
30
39
  if (dead === "0" && shells.has(command)) {
31
40
  // macOS tmux can report the wrapper shell while the harness is its child.
@@ -48,7 +57,8 @@ export function inspectSessionTarget(target, io) {
48
57
  }
49
58
  state = active ? "unknown" : "shell";
50
59
  }
51
- return { backend: "tmux", present: dead === "0", state, paneId };
60
+ return { backend: "tmux", present: dead === "0", state, paneId,
61
+ ...(includeSize && dead === "0" ? { size: { cols: Number(cols), rows: Number(rowsCount) } } : {}) };
52
62
  }
53
63
  // Settling gives a large bracketed paste time before the single Enter. Screen
54
64
  // bytes are observations only: neither change nor silence proves acceptance
@@ -3,12 +3,12 @@
3
3
  "packages": {
4
4
  "oats.okf": {
5
5
  "url": "https://github.com/awebai/oats-okf.git",
6
- "ref": "v5.2.0",
6
+ "ref": "v5.2.1",
7
7
  "path": "oats-package"
8
8
  },
9
9
  "oats.aweb": {
10
10
  "url": "https://github.com/awebai/oats-aweb.git",
11
- "ref": "v1.27.3",
11
+ "ref": "v1.28.0",
12
12
  "path": "oats-package"
13
13
  },
14
14
  "oats.jira": {
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "oats.framework": {
45
45
  "url": "https://github.com/awebai/oats.git",
46
- "ref": "oats-framework/v1.12.0",
46
+ "ref": "oats-framework/v1.12.2",
47
47
  "path": "oats-package"
48
48
  }
49
49
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.58.0",
3
+ "version": "0.59.0",
4
4
  "description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
5
5
  "keywords": [
6
6
  "agents",
@@ -13,7 +13,7 @@
13
13
  // Every candidate is canonicalized to an absolute executable and accepted
14
14
  // ONLY if executable and `<bin> version --json` returns the v1 probe:
15
15
  // {"schemaVersion":1,"name":"@awebai/oats","version":"0.24.x","desktopApi":1}
16
- // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.59.0 (the band is
16
+ // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.60.0 (the band is
17
17
  // spelled ONCE, in ACCEPT_RANGE below — this line only paraphrases it).
18
18
  // API version — not source adjacency — is authoritative.
19
19
  //
@@ -52,7 +52,7 @@ export const DESKTOP_API = 1;
52
52
  // carry a `description` for every kind and `<kind> update <id> --description`
53
53
  // sets one (feature `automation-descriptions`, which gates the Desktop's
54
54
  // summary writes). The Desktop v1 surface is otherwise unchanged.
55
- export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 59, 0] };
55
+ export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 60, 0] };
56
56
  /** The band as humans read it — derived, never hand-spelled, so the probe
57
57
  * rejection reason, the backend's /api status and the degradation card can
58
58
  * never disagree with the numbers actually enforced above. */
@@ -8,6 +8,7 @@ import { teamRow, teamRowsOf, defaultTeamOf, TEAM_ID } from './team-rows.mjs';
8
8
  import { launchOf, REPORT_FROM } from './launch-contract.mjs';
9
9
  import { readIdentity } from './workspace-views.mjs';
10
10
  import { waitingOnYouData } from './waiting-on-you.mjs';
11
+ import { retireData } from './retire-state.mjs';
11
12
  const text = value => typeof value === 'string' && value.length <= 8192 && !value.includes('\0');
12
13
  const absolute = value => text(value) && isAbsolute(value) && resolve(value) === value;
13
14
  const own = (value, key) => Object.hasOwn(value, key);
@@ -209,6 +210,9 @@ export function deploymentStatusData(document, deployment) {
209
210
  if (own(instance, 'tmux')) row.tmux = instance.tmux === null ? null : fields(instance.tmux, ['session', 'window', 'socket']);
210
211
  if (own(instance, 'sessionTarget')) row.sessionTarget = sessionTarget(instance.sessionTarget);
211
212
  if (own(instance, 'retirePending')) row.retirePending = true;
213
+ // #1247 (feature status-retire-state): the retire that runs, or failed, or was interrupted. Validated, never
214
+ // check()ed: a value out of the contract is dropped and the row reads as if it had none.
215
+ if (own(instance, 'retire')) { const retire = retireData(instance.retire); if (retire) row.retire = retire; }
212
216
  if (own(instance, 'rollbackIncomplete')) row.rollbackIncomplete = true;
213
217
  // #802 (feature worktree-event): a spawn running its worktree hooks, verifiably alive. Boolean true only;
214
218
  // any other value is dropped, never checked: the row stays an ordinary one.
@@ -13,6 +13,7 @@
13
13
  import { dirname } from 'node:path';
14
14
  import { livenessOrigin } from './liveness.mjs';
15
15
  import { knownOrigin, hasRuntimeError, byRuntimeState } from './instance-presentation.mjs';
16
+ import { retireData } from './retire-state.mjs';
16
17
 
17
18
  const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
18
19
 
@@ -98,6 +99,8 @@ export function panelInstance(i) {
98
99
  ...(i.modelFrom !== undefined ? { modelFrom: i.modelFrom } : {}),
99
100
  ...(i.identityAddress !== undefined ? { identityAddress: i.identityAddress } : {}),
100
101
  ...(i.retirePending ? { retirePending: true } : {}),
102
+ // #1247: the retire's state, validated again here (retire-state.mjs): a value out of the contract is absent.
103
+ ...(retireData(i.retire) ? { retire: retireData(i.retire) } : {}),
101
104
  ...(i.rollbackIncomplete ? { rollbackIncomplete: true } : {}),
102
105
  // #802: a spawn setting up its worktree (deployment-data.mjs keeps it as true only).
103
106
  ...(i.spawnInProgress === true ? { spawnInProgress: true } : {}),
@@ -2,10 +2,11 @@
2
2
  * keys or its buttons from this answer: verbs and reasons, never a label, an icon or a key.
3
3
  *
4
4
  * instanceActs(instance) -> { blocked: Reason | null, limited: Reason | null, acts: Act[] }
5
- * Act = { verb, enabled, reason: Reason | null }
5
+ * Act = { verb, enabled, reason: Reason | null, secondary? }
6
6
  * Reason = { code, sentence } and, by code:
7
7
  * { code: 'unaddressable', key, sentence, origin? } key: the row reason's own (remote-address.mjs rowReason)
8
- * { code: 'held', kind, sentence } kind: 'spawning' | 'spawn-incomplete' | 'retire-incomplete'
8
+ * { code: 'held', kind, sentence, origin? } kind: instance-tree.mjs HELD_HOMES's: 'spawning' |
9
+ * 'spawn-incomplete' | 'retiring' | 'retire-failed' | 'retire-incomplete'
9
10
  * { code: 'unsupported-session', sentence, origin? }
10
11
  * { code: 'not-running', sentence } an `open` act's only (`openAct`)
11
12
  * { code: 'state-unknown', sentence } an `open` act's only
@@ -19,7 +20,8 @@
19
20
  * answer's `origin` is passed on as it is, never decided again here): "kernel", "terminal-probe" or
20
21
  * "roster-read" when the row names the speaker of its `runtimeError`, "unattributed" when the row's text
21
22
  * stands beside no speaker. It is absent on a sentence this home wrote and on the stand-in for an older
22
- * kernel's Herdr row, and a `held` reason never has one. A client shows a sentence with an `origin`
23
+ * kernel's Herdr row. A `held` reason has one ("kernel") only for a failed retire whose row carries the
24
+ * kernel's message or code (#1247, instance-tree.mjs heldHome `said`). A client shows a sentence with an `origin`
23
25
  * through its display filter, after instance-presentation.mjs `originLead`'s words when the value names
24
26
  * a speaker, and a sentence with none as written, as this home's own.
25
27
  *
@@ -29,10 +31,20 @@
29
31
  * `blocked` and `limited` are never both set. An act's own `reason` says why that one act is listed
30
32
  * and not enabled; the others stay as they are.
31
33
  *
34
+ * `secondary: true` (#1247; absent otherwise): the act stays listed and enabled, behind its usual
35
+ * confirmation, but it is not the row's default or primary affordance. A client keeps it where the row's
36
+ * acts are listed (the Desktop's row menu, the TUI's key) and draws no inline primary control for it,
37
+ * never makes it the default act (the menu's first focus, a key's default) and does not advertise it
38
+ * (the TUI's footer). Only Retire on a retiring row is secondary: a second retire is safe (the kernel
39
+ * refuses it while one runs: E_INSTANCE_RETIRING, E_LIFECYCLE_BUSY) and, while the holder can't be read,
40
+ * may be the only way on.
41
+ *
32
42
  * In order, the first that applies:
33
43
  * a remote row the kernel does not report addressable blocked (unaddressable); no acts
34
44
  * a home the kernel holds, spawning blocked (held); no acts
35
- * a home the kernel holds, spawn or retire incomplete limited (held); retire
45
+ * a home the kernel holds, retiring limited (held); retire (secondary)
46
+ * a home the kernel holds, spawn incomplete, limited (held); retire
47
+ * retire failed or incomplete
36
48
  * a session backend OATS no longer has inspect, start (not enabled, unsupported-session), stop, retire
37
49
  * running === true inspect, restart, stop, retire
38
50
  * running === false inspect, start, stop, retire
@@ -54,7 +66,7 @@ import { heldHome } from './instance-tree.mjs';
54
66
  import { unsupportedSession } from './instance-presentation.mjs';
55
67
  import { canAddressRemote, rowReason } from './remote-address.mjs';
56
68
 
57
- const act = (verb, reason = null) => ({ verb, enabled: !reason, reason });
69
+ const act = (verb, reason = null, secondary = false) => ({ verb, enabled: !reason, reason, ...(secondary ? { secondary: true } : {}) });
58
70
  // An `open` act's own two codes, and the one sentence both carry.
59
71
  const NOT_RUNNING = 'not-running', STATE_UNKNOWN = 'state-unknown';
60
72
  const NO_LIVE_TERMINAL = 'No live terminal is reported.';
@@ -65,11 +77,14 @@ export function instanceActs(instance) {
65
77
  return { blocked: { code: 'unaddressable', key, sentence, ...(origin !== undefined ? { origin } : {}) }, limited: null, acts: [] };
66
78
  }
67
79
  // #802: a home the kernel holds starts, stops and opens nothing. Retire only when a spawn or a retire left it
68
- // half cleaned (the kernel's retire completes it), nothing while its spawn sets up the worktree.
80
+ // half cleaned (the kernel's retire completes it), nothing while its spawn sets up the worktree; while a
81
+ // retire runs (#1247), Retire stays reachable but secondary.
69
82
  const held = heldHome(instance);
70
83
  if (held) {
71
- const reason = { code: 'held', kind: held.kind, sentence: held.sentence(instance.instance) };
72
- return held.retire ? { blocked: null, limited: reason, acts: [act('retire')] } : { blocked: reason, limited: null, acts: [] };
84
+ const { sentence, origin } = held.said;
85
+ const reason = { code: 'held', kind: held.kind, sentence, ...(origin !== undefined ? { origin } : {}) };
86
+ return held.retire ? { blocked: null, limited: reason, acts: [act('retire', null, held.retire === 'secondary')] }
87
+ : { blocked: reason, limited: null, acts: [] };
73
88
  }
74
89
  // A Herdr-recorded row cannot start or restart: Start stays listed, not enabled, with the kernel's reason.
75
90
  // Its sentence and its `origin` are the row reason's own (rowReason answers this reason first for such a row).
@@ -6,10 +6,11 @@ export function runtimeState(instance) {
6
6
  }
7
7
 
8
8
  const RUNTIME_ORDER = Object.freeze({ running: 0, unknown: 1, stopped: 2 });
9
- /** The roster's one order, a comparator for `sort`: running, then unknown (`running` null or anything not
9
+ /** The panel's runtime order, a comparator for `sort`: running, then unknown (`running` null or anything not
10
10
  * a boolean: it may be running, so it stands above the rows nobody needs to watch), then stopped; by name
11
11
  * within each. Each row's place depends on that row alone, so it is a total order whatever `running` holds.
12
- * Read by `clusterInstances` (instance-tree.mjs) and `panelInstances` (deployment-panel.mjs). */
12
+ * Read by `panelInstances` (deployment-panel.mjs). The sidebar's roster orders by name (instance-tree.mjs
13
+ * `rosterOrder`, #1262). */
13
14
  export function byRuntimeState(a, b) {
14
15
  return RUNTIME_ORDER[runtimeState(a)] - RUNTIME_ORDER[runtimeState(b)] || String(a.instance).localeCompare(String(b.instance));
15
16
  }
@@ -4,6 +4,8 @@
4
4
  * no element: a client draws from these answers with its own means. */
5
5
  import { waitingClaim } from './waiting-on-you.mjs';
6
6
  import { byRuntimeState } from './instance-presentation.mjs';
7
+ import { retireData } from './retire-state.mjs';
8
+ import { displayLine } from './display-text.mjs';
7
9
 
8
10
  export function collapseKey(workspace, instance) {
9
11
  return `${workspace || ""}\u0000${instance}`;
@@ -54,6 +56,15 @@ export function resolveLinkId(fromInstance, name, byName) {
54
56
  return sameRoot.length === 1 ? instanceId(sameRoot[0]) : null;
55
57
  }
56
58
 
59
+ /** The roster's order, a comparator for `sort`: by instance name, ties broken by `instanceId`, so it is total and
60
+ * deterministic. It ranks roots, siblings under one parent, and so clusters (by their first root). A start or a
61
+ * stop moves no row; only adding or removing one does (Pepe's decision on #1262, comment 6196531154, which
62
+ * replaces #1083's running-first order for the roster). The one place the roster's order is decided. */
63
+ function rosterOrder(a, b) {
64
+ const ia = instanceId(a), ib = instanceId(b);
65
+ return String(a.instance).localeCompare(String(b.instance)) || (ia < ib ? -1 : ia > ib ? 1 : 0);
66
+ }
67
+
57
68
  /** Group instances into agent CLUSTERS — connected components of the
58
69
  * undirected relation graph (parent/child spawn edges + sibling links).
59
70
  * Unrelated instances are single-node clusters. Within a cluster the
@@ -62,7 +73,9 @@ export function resolveLinkId(fromInstance, name, byName) {
62
73
  * Nodes are keyed by instanceId (composite identity), never bare name —
63
74
  * duplicate names across repos render as distinct nodes.
64
75
  * Returns [{ key, instances: [{...instance, depth}] }] with clusters ranked by
65
- * their first member in the roster's order (`byRuntimeState`), as the panel is. */
76
+ * their first ROOT in the roster's order (`rosterOrder`), never by another member (#1262): a bundle sits where
77
+ * its root sits, and gaining or losing a child, or a start or a stop, moves nothing. A cluster without a root
78
+ * (a malformed cycle) ranks by its first member in that order. */
66
79
  export function clusterInstances(instances, { links = instanceLinks } = {}) {
67
80
  const byId = new Map(instances.map((i) => [instanceId(i), i]));
68
81
  const byName = new Map();
@@ -86,7 +99,7 @@ export function clusterInstances(instances, { links = instanceLinks } = {}) {
86
99
  adj.get(oid).add(id);
87
100
  }
88
101
  }
89
- const rank = byRuntimeState;
102
+ const rank = rosterOrder;
90
103
  const seen = new Set();
91
104
  const clusters = [];
92
105
  for (const start of [...instances].sort(rank)) {
@@ -122,11 +135,12 @@ export function clusterInstances(instances, { links = instanceLinks } = {}) {
122
135
  // Deterministic cluster label: the lexically-smallest ROOT name —
123
136
  // independent of liveness, so the visible cluster name does not flip
124
137
  // when a different member starts/stops running (review f921f7d nit).
125
- // `rank` (running, unknown, stopped) still governs display ORDER within the cluster.
138
+ // `rank` (rosterOrder: by name) governs display ORDER within the cluster.
126
139
  const rootNames = (roots.length ? roots : members).map((i) => i.instance).sort();
127
- clusters.push({ key: rootNames[0], instances: ordered });
140
+ clusters.push({ key: rootNames[0], instances: ordered, head: roots[0] ?? [...members].sort(rank)[0] });
128
141
  }
129
- return clusters;
142
+ // Stable: clusters whose heads rank equal keep the order they were found in (the roster's order of members).
143
+ return clusters.sort((a, b) => rank(a.head, b.head)).map(({ head: _head, ...c }) => c);
130
144
  }
131
145
 
132
146
  /** Find the roster instance a UI reference means. References carry the
@@ -214,22 +228,52 @@ const HELD_HOMES = Object.freeze({
214
228
  sentence: name => `${name} is setting up its worktree. It can't be used until the spawn finishes.` },
215
229
  "spawn-incomplete": { state: "Spawn didn't finish", hint: "Retire it to clean up", status: "Spawn didn't finish", retire: true,
216
230
  sentence: name => `The spawn of ${name} didn't finish. Retire it to clean up.` },
231
+ // #1247: a retire that runs (or whose holder's liveness can't be read): Retire stays offered, secondary.
232
+ retiring: { state: "Retiring…", status: "Retiring…", retire: "secondary",
233
+ sentence: name => `${name} is being retired.` },
234
+ "retire-failed": { state: "Retire failed", hint: "Retire it again to finish", status: "Retire failed", retire: true,
235
+ sentence: name => `The retire of ${name} failed. Retire it again to finish.` },
217
236
  "retire-incomplete": { state: "Retire didn't finish", hint: "Retire it again to complete", status: "Retire didn't finish", retire: true,
218
237
  sentence: name => `The retire of ${name} didn't finish. Retire it again to complete.` },
219
238
  });
220
- /** What the kernel's roster row says holds this home, or null (#802): `spawning` while a spawn that
221
- * runs its worktree hooks is verifiably alive (`spawnInProgress: true`), `spawn-incomplete` when a
222
- * spawn left it for retire to clean up (`rollbackIncomplete`), `retire-incomplete` when a retire did
223
- * (`retirePending`). rollbackIncomplete wins over spawnInProgress (the spawn is gone, not live), and a
224
- * live spawn over retirePending (the kernel refuses to retire it). Every surface draws such a row from
225
- * this: a spawning one starts, stops, retires and splits nothing; a quarantined one (`retire`) offers
226
- * Retire only. `state` is the row's text, `hint` its muted line, `status` the hover card's Status.
227
- * `sentence` is every client's, so it promises no act of one client: a spawning home "can't be used
228
- * until the spawn finishes", whoever started the spawn and whether or not it ends finished. */
239
+ /** Which retire kind a row's kernel facts are (#1247), or null: the kernel's `retire` (retire-state.mjs, read
240
+ * again here: a value out of the contract is absent); a row with no `retire` but `retirePending` (a kernel or a
241
+ * host before `status-retire-state`) reads `retiring`. */
242
+ function retireKind(instance) {
243
+ const retire = retireData(instance.retire);
244
+ if (retire) return retire.state === "failed" ? "retire-failed" : retire.state === "interrupted" ? "retire-incomplete" : "retiring";
245
+ return instance.retirePending ? "retiring" : null;
246
+ }
247
+ /** What the kernel's roster row says holds this home, or null (#802, #1247): `spawning` while a spawn
248
+ * that runs its worktree hooks is verifiably alive (`spawnInProgress: true`), `spawn-incomplete` when a
249
+ * spawn left it for retire to clean up (`rollbackIncomplete`); then the retire kinds (`retireKind`):
250
+ * `retiring` while a retire runs, its holder can't be read, the row is an older kernel's `retirePending`
251
+ * or this client's own retire is in flight; `retire-failed` when a self-retire's completion recorded an
252
+ * error; `retire-incomplete` when a scheduled completion is gone without an outcome. A retire this client
253
+ * started and has not read the roster after (retire-in-flight.mjs `retireInFlight`) is `retiring` whatever
254
+ * the row says: it is the newest fact, and the kernel refuses it (letting the row go) where a live spawn
255
+ * holds the home. Of the kernel's facts, rollbackIncomplete wins over spawnInProgress (the spawn is gone,
256
+ * not live), and a live spawn over a retire (the kernel refuses to retire it). Every surface draws such a row from this: a spawning or retiring one starts,
257
+ * stops, restarts and opens nothing new; one with `retire` offers Retire only, and `retire: "secondary"`
258
+ * (retiring: a second retire is refused while one runs, and safe) offers it out of the way (instance-acts.mjs).
259
+ * `state` is the row's text, `hint` its muted line (none while retiring), `status` the hover card's Status.
260
+ * `sentence` is every client's, so it promises no act of one client: a spawning home "can't be used until
261
+ * the spawn finishes", whoever started the spawn and whether or not it ends finished. `said` is what the
262
+ * row's reason says (instance-acts.mjs): the sentence, or for a failed retire with a recorded message or code the
263
+ * kernel's words (`message`, `code`, or `message (code)`) with `origin: "kernel"`, shown only through the display
264
+ * filter. */
229
265
  export function heldHome(instance) {
230
- const kind = !instance ? null : instance.rollbackIncomplete ? "spawn-incomplete"
231
- : instance.spawnInProgress === true ? "spawning" : instance.retirePending ? "retire-incomplete" : null;
232
- return kind ? { kind, ...HELD_HOMES[kind] } : null;
266
+ const kind = !instance ? null : instance.retireInFlight === true ? "retiring" : instance.rollbackIncomplete ? "spawn-incomplete"
267
+ : instance.spawnInProgress === true ? "spawning" : retireKind(instance);
268
+ if (!kind) return null;
269
+ const held = HELD_HOMES[kind], retire = kind === "retire-failed" ? retireData(instance.retire) : null;
270
+ // The kernel's words, message or code, are said as the kernel's, and shown only through the display filter; one the
271
+ // filter reduces to nothing (blank) says nothing; one it withholds is said, and shown withheld. With neither, the row's own words stand.
272
+ const shown = text => (text && displayLine(text) !== null ? text : null);
273
+ const message = shown(retire?.message), code = shown(retire?.code);
274
+ const said = message || code ? { sentence: message && code ? `${message} (${code})` : message || code, origin: "kernel" }
275
+ : { sentence: held.sentence(instance.instance) };
276
+ return { kind, ...held, said };
233
277
  }
234
278
 
235
279
  /* ── roster grouping: repo → agent family (soul), with sort modes ── */
@@ -239,9 +283,8 @@ export const ROSTER_SORTS = Object.freeze([
239
283
  Object.freeze({ id: "name", label: "Name" }),
240
284
  ]);
241
285
 
242
- /** Comparator for one sibling level. "status" is the roster's one order
243
- * (`byRuntimeState`: running, unknown, stopped, then by name); "name" is purely
244
- * alphabetical. Unknown ids fall back to "status" so a stale persisted choice
286
+ /** Comparator for one sibling level. "status" is `byRuntimeState` (running, unknown, stopped, then by name:
287
+ * #1083's order, which the roster no longer uses, #1262); "name" is purely alphabetical. No client calls it. Unknown ids fall back to "status" so a stale persisted choice
245
288
  * can never break rendering. */
246
289
  export function rosterRank(sortBy) {
247
290
  const byName = (a, b) => String(a.instance).localeCompare(String(b.instance));
@@ -355,30 +398,32 @@ export function visibleClusters(allInstances, visibleInstances, { links = instan
355
398
  .filter((c) => c.instances.length);
356
399
  }
357
400
 
358
- /** The sidebar roster's groups (Redesign v3), shared with the command palette:
359
- * each multi-member relation cluster under its deterministic name, then every
360
- * unrelated instance under "independent". A cluster's group is decided on the
361
- * FULL roster: more than one member there is a group under the cluster's name,
362
- * exactly one goes under "independent". A filter or a collapse decides which
363
- * rows are listed and never moves a row to another group; a group with no
364
- * visible row is left out. Returns [{ key, label, clusters: [{ key, instances }] }]
365
- * in the full roster's cluster order, each cluster projected to its visible
366
- * members, which carry their tree depth. A group's key is unique even when two
367
- * roots share a name (other agents roots or hosts), and does not depend on what
368
- * is visible: the label is the name, the key adds the cluster's place among the
369
- * multi-member clusters of the full roster. */
401
+ /** The sidebar roster's groups (Redesign v3), shared with the command palette and the TUI: the full roster's
402
+ * clusters in their one order (#1262), each multi-member relation cluster a group under its deterministic name,
403
+ * and each RUN of consecutive single-instance clusters one "independent" group, in place. So an instance that
404
+ * gains its first child stays where it was and becomes a group there; losing its last child, it rejoins the run
405
+ * at the same place. A cluster's group is decided on the FULL roster: a filter or a collapse decides which rows
406
+ * are listed and never moves a row to another group; a group with no visible row is left out. Returns
407
+ * [{ key, label, clusters: [{ key, instances }] }], each cluster projected to its visible members, which carry
408
+ * their tree depth. A group's key is unique even when two roots share a name (other agents roots or hosts), and
409
+ * does not depend on what is visible: a cluster's is `cluster:<its place among the full roster's multi-member
410
+ * clusters>:<name>`, a run's `independent:<instanceId of its first member in the full roster>`. */
370
411
  export function rosterGroups(allInstances, visibleInstances, { links = instanceLinks } = {}) {
371
412
  const visibleIds = new Set(visibleInstances.map((i) => instanceId(i)));
372
- const named = [], independent = [];
373
- let place = 0;
413
+ const groups = [];
414
+ let place = 0, run = null;
374
415
  for (const c of clusterInstances(allInstances, { links })) {
375
- const at = c.instances.length > 1 ? place++ : -1;
376
416
  const shown = { ...c, instances: c.instances.filter((i) => visibleIds.has(instanceId(i))) };
377
- if (!shown.instances.length) continue;
378
- if (at < 0) independent.push(shown);
379
- else named.push({ key: `cluster:${at}:${c.key}`, label: c.key, clusters: [shown] });
417
+ if (c.instances.length > 1) {
418
+ run = null;
419
+ const at = place++;
420
+ if (shown.instances.length) groups.push({ key: `cluster:${at}:${c.key}`, label: c.key, clusters: [shown] });
421
+ continue;
422
+ }
423
+ if (!run) { run = { key: `independent:${instanceId(c.instances[0])}`, label: "independent", clusters: [] }; groups.push(run); }
424
+ if (shown.instances.length) run.clusters.push(shown);
380
425
  }
381
- return [...named, ...(independent.length ? [{ key: "independent", label: "independent", clusters: independent }] : [])];
426
+ return groups.filter((g) => g.clusters.length);
382
427
  }
383
428
 
384
429
  /** Whether an item remains visible under VS Code-style collapsed ancestors.