@awebai/oats 0.55.1 → 0.56.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 (78) hide show
  1. package/bin/oats.mjs +78 -62
  2. package/docs/capabilities.md +67 -3
  3. package/docs/design/2026-09-23-workspace-module-contracts.md +27 -3
  4. package/docs/desktop-cli-api.md +317 -35
  5. package/docs/desktop-instance-start.md +105 -12
  6. package/docs/desktop.md +54 -7
  7. package/docs/execution-targets.md +184 -9
  8. package/docs/harness-trust.md +128 -11
  9. package/docs/implementation.md +54 -7
  10. package/docs/integrations.md +1 -1
  11. package/docs/knowledge.md +35 -16
  12. package/docs/official-catalog.md +3 -3
  13. package/docs/packages.md +12 -12
  14. package/docs/release-lane.md +26 -1
  15. package/docs/release-notes/v0.56.0.md +699 -0
  16. package/docs/servers.md +21 -5
  17. package/docs/souls-and-instances.md +8 -4
  18. package/docs/tui.md +99 -26
  19. package/docs/upgrading.md +4 -1
  20. package/docs/workspaces.md +26 -6
  21. package/lib/automations.mjs +3 -4
  22. package/lib/bounded-read.mjs +18 -0
  23. package/lib/capability-show.mjs +13 -2
  24. package/lib/claim.mjs +3 -4
  25. package/lib/core.mjs +480 -152
  26. package/lib/errors.mjs +39 -0
  27. package/lib/harness-trust-write.mjs +119 -40
  28. package/lib/harness-trust.mjs +31 -18
  29. package/lib/instance-inspect.mjs +160 -11
  30. package/lib/instance-lifecycle.mjs +47 -30
  31. package/lib/packages.mjs +8 -5
  32. package/lib/pi-bridge.mjs +18 -19
  33. package/lib/remote.mjs +88 -51
  34. package/lib/retire-output.mjs +9 -4
  35. package/lib/schedule.mjs +3 -4
  36. package/lib/servers.mjs +39 -6
  37. package/lib/session-viewer.mjs +25 -1
  38. package/lib/triggers.mjs +3 -4
  39. package/lib/workspace.mjs +6 -6
  40. package/lib/worktree.mjs +10 -6
  41. package/lib/write-through-private-file.mjs +26 -0
  42. package/package-catalog.json +2 -2
  43. package/package.json +1 -1
  44. package/packages/client/cli-adapter.mjs +108 -13
  45. package/packages/client/cli-locator.mjs +16 -14
  46. package/packages/client/deployment-panel.mjs +4 -3
  47. package/packages/client/display-text.mjs +2 -1
  48. package/packages/client/instance-events-contract.mjs +4 -3
  49. package/packages/client/instance-lifecycle.mjs +228 -0
  50. package/packages/client/instance-presentation.mjs +9 -0
  51. package/packages/client/instance-tree.mjs +10 -8
  52. package/packages/client/kernel-lines.mjs +3 -3
  53. package/packages/client/launch-contract.mjs +11 -0
  54. package/packages/client/lifecycle-cli.mjs +12 -6
  55. package/packages/client/lifecycle-confirmation.mjs +407 -0
  56. package/packages/client/lifecycle-contract.mjs +6 -2
  57. package/packages/client/own-codes.mjs +1 -0
  58. package/packages/client/panel-views.mjs +39 -2
  59. package/packages/client/readiness-contract.mjs +2 -2
  60. package/packages/client/remote-roster.mjs +50 -5
  61. package/packages/client/roster-sections.mjs +3 -3
  62. package/packages/client/session-start.mjs +98 -0
  63. package/packages/client/start-gate.mjs +46 -0
  64. package/packages/client/start-messages.mjs +17 -0
  65. package/packages/client/workspace-views.mjs +2 -2
  66. package/packages/tui/README.md +10 -6
  67. package/packages/tui/lib/actions.mjs +4 -2
  68. package/packages/tui/lib/client.mjs +5 -2
  69. package/packages/tui/lib/config.mjs +39 -9
  70. package/packages/tui/lib/main.mjs +83 -13
  71. package/packages/tui/lib/model.mjs +116 -11
  72. package/packages/tui/lib/open.mjs +45 -0
  73. package/packages/tui/lib/read.mjs +46 -10
  74. package/packages/tui/lib/store.mjs +64 -9
  75. package/packages/tui/lib/term/tty.mjs +71 -12
  76. package/packages/tui/lib/views/frame.mjs +115 -33
  77. package/packages/tui/lib/views/help.mjs +37 -8
  78. package/skills/oats-getting-started/SKILL.md +6 -3
@@ -0,0 +1,407 @@
1
+ /** What a Stop or Retire plan and its answer say, and the client's half of the transaction: decide, then build.
2
+ * No DOM and no IO: a client draws `planView`'s and `outcomeView`'s data its own way, and reaches its lifecycle
3
+ * boundary (instance-lifecycle.mjs) through the `request` it gives `createLifecycleConfirmation`.
4
+ *
5
+ * What happened is shared; what to do next is each client's. Every sentence here is a fact about the plan or
6
+ * its answer, or a next step that names an act every confirmation has (review again: `refresh`; check again:
7
+ * `check-again`; update OATS). A next step that names a client's own furniture (a window, a roster, a command
8
+ * line) is not here: a view names it by a code (`next`), and the client words it. Labels of controls are the
9
+ * client's too; which controls exist is `state().offers`, and which choices, `planView(…).choices`.
10
+ *
11
+ * A client switches on codes and kinds, never on the words. Every wording function takes the client's terms
12
+ * (client-terms.mjs) and refuses a call without them.
13
+ *
14
+ * planView(plan, { operation, choices, leftover }, terms)
15
+ * -> { question, happening, state, warning, choices, applicable, notice, targets, own, at }
16
+ * happening: [{ text, path?, tone?, title? }] tone: 'note' | 'attention'
17
+ * state: { rows: [{ label, value, title }], notes: [{ text, tone, title? }] }
18
+ * choices: [{ id, sentence, value, applies, offered }] one per option the plan can carry
19
+ * notice: null | { code: 'E_OPTION_UNAVAILABLE', sentence } when the choices do not apply
20
+ * outcomeView(result, { target, operation, choices, plan, leftover }, terms)
21
+ * -> { kind, title, status, blocks, uncertain, plan?, planRef?, running? }
22
+ * kind: 'stale' | 'pending' | 'complete' | 'partial' | 'refused' | 'unknown' | 'invalid'
23
+ * status: { headline, more: [{ text } | { quote }], next: null | 'retire-with-force' | 'check-roster', code? }
24
+ * blocks: what is shown under the status, in order:
25
+ * { type: 'details', reason, bare } a code and the kernel's line behind a disclosure
26
+ * { type: 'quote', text } the kernel's own line, quoted
27
+ * { type: 'note', text }
28
+ * { type: 'rows', rows: [{ text, quote? }] } a stop's results or a retire's children
29
+ * { type: 'lines', lines: [{ text, path? }] } what a retire did
30
+ * applyRunningSentence(running, terms) -> the sentence for an apply of this client that is still running
31
+ * createLifecycleConfirmation({ request, target, operation, terms, onSettled, onChange, label, leftover })
32
+ * -> { state(), view(), setChoice(id, value), refresh(), apply(), checkAgain(), close() }
33
+ */
34
+ import { lifecyclePlan, lifecycleOptions, planReference, lifecycleReason, lifecycleDetailCode, publicLifecycleReceipt, decodedStoppedTargets,
35
+ stoppedRowKind, stoppedRowText, stopResultWords, childrenRefusedMessage, busyRefusal, undescribedRefusal, lifecycleChoicesApplicable,
36
+ ownWorktreeOf } from './lifecycle-contract.mjs';
37
+ import { gitTargetKey } from './instance-git-contract.mjs';
38
+ import { remoteReason, readingFrom } from './remote-address.mjs';
39
+ import { cleanLine, displayLine } from './display-text.mjs';
40
+ import { requireTerms } from './client-terms.mjs';
41
+
42
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
43
+ const names = values => values.map(v => v.instance).join(', ');
44
+ /** What a person reads for a session: whether it runs, never the backend's raw state word. */
45
+ const sessionText = s => !s.established ? "Unknown (couldn't be checked)" : s.present ? 'Running' : 'Not running';
46
+ /** The kernel's reason for unobserved work is a code or a sentence for operators (E_NO_WORKTREE, a path):
47
+ * never inline, only in the row's title. */
48
+ const workText = w => !w.observed ? "Unknown (couldn't be checked)" : !w.changed && !w.untracked ? 'None'
49
+ : [w.changed && `${w.changed} changed`, w.untracked && `${w.untracked} untracked`].filter(Boolean).join(', ');
50
+ /** The worktree's branch as observed, else the one recorded at spawn; null when detached or unknown. Not asked
51
+ * for a tree the kernel's fact answers and that was not observed (treeOf `unchecked`): no branch is named there. */
52
+ const branchOf = f => f.work.observed ? f.work.branch : f.recordedBranch;
53
+ /** A retire the kernel refuses as busy for a home a spawn left (`rollbackIncomplete`): the spawn may still run.
54
+ * For a kernel that does not say who holds the claim. One that does (feature lifecycle-claim-stop) has its
55
+ * answer read by `details.holder`, and its own sentence names the check and the command: never this one.
56
+ * What to do next (`next: 'retire-with-force'`) is the client's to word. */
57
+ const LEFTOVER_HELD = "OATS can't confirm that the spawn which left this home has stopped, so it won't retire it yet.";
58
+ /** How a retire plan's tree reads, for the words about it. `own`: the tree at `work/` is the instance's
59
+ * (ownWorktreeOf), by the kernel's fact or, for a plan without one, by the record. The other two are for a
60
+ * plan with the fact alone; a plan without one is `own` or neither, by the record.
61
+ * unchecked the kernel says the tree is the instance's and `work/` was not observed. The fact is the
62
+ * reading's answer by the record where nothing, or a file, is at `work/`, so the words promise
63
+ * no tree and name no branch: the only branch known there is the record's. One wording for
64
+ * every reason of unobserved work; no code of `facts.work.reason` is read.
65
+ * notOwn the kernel says the tree is not the instance's: no worktree is kept or deleted, and
66
+ * `facts.work`, an observation through any link, is another's tree. */
67
+ const treeOf = value => { const whose = ownWorktreeOf(value), fact = whose.from === 'fact';
68
+ return { own: whose.own, unchecked: fact && whose.own && !value.facts.work.observed, notOwn: fact && !whose.own }; };
69
+ /** The worktree line of "What will happen" and the warning under the checked choice, for an own tree that
70
+ * could not be checked. They follow the line for a session that could not be checked. */
71
+ const KEEPS_UNCHECKED = "Keeps its worktree, moved aside, if there is one. It couldn't be checked.";
72
+ const DELETES_UNCHECKED = "Deletes its worktree, if there is one. It couldn't be checked.";
73
+ const WARNS_UNCHECKED = "Deletes the worktree folder, if there is one, with any uncommitted changes (a recovery copy is saved first). It couldn't be checked.";
74
+ /** In the place of the worktree line when the kernel says the tree is not the instance's. True of every such
75
+ * home: it names no owner and does not claim there is a link. What happens to what is at `work/` is the
76
+ * line above it (the recovery copy and the home). */
77
+ const NOT_ITS_OWN = 'It has no worktree of its own, so no worktree is kept or deleted. A tree it links to is not touched.';
78
+ const ambiguousText = v => `Not included: ${v.instance} (another instance has the same parent name, so OATS can't tell whose child it is).`;
79
+ /** The sentence of each choice a plan can carry, by the id lifecycleOptions reads. */
80
+ const CHOICES = Object.freeze({ stop: [['recursive', 'Include child instances']], retire: [['discardWorktree', 'Also delete the worktree']] });
81
+ const REPLAYED = 'This is the result already recorded for this confirmation; nothing ran again.';
82
+ const UNCONFIRMED = 'Result not confirmed';
83
+
84
+ /** Deleting the worktree keeps its branch, except on a leftover row: there the kernel deletes the branch the
85
+ * interrupted spawn created when it holds no work, so the plan's next line is the only word on branches. */
86
+ const stays = (b, leftover) => b && !leftover ? ` Branch ${b} stays in the repository.` : '';
87
+ const line = (text, path, tone) => ({ text, ...(path ? { path } : {}), ...(tone ? { tone } : {}) });
88
+ /** What will happen, in plain words, built from the plan; each line only when it applies. */
89
+ function happening(value, requested, leftover) {
90
+ const lines = [];
91
+ if (value.action === 'stop') {
92
+ const t = value.targets;
93
+ lines.push(line(value.recursive && t.length > 1 ? `Stops ${t.length} sessions, children first: ${names(t)}.` : `Stops the session of ${value.instance}.`));
94
+ lines.push(line('Nothing is deleted. Its home, worktree, transcript and launch settings are kept; you can start it again.'));
95
+ lines.push(line('A session that refuses to stop is left running; nothing is forced.', undefined, 'note'));
96
+ for (const x of t.filter(x => x.midTask === true)) lines.push(line(`${x.instance} reports it is in the middle of a task.`, undefined, 'attention'));
97
+ if (value.skipped.length) lines.push(line(`Not stopped: ${names(value.skipped)} (children not included).`, undefined, 'note'));
98
+ return lines;
99
+ }
100
+ const f = value.facts, tree = treeOf(value);
101
+ if (f.session.established && f.session.present) lines.push(line('Stops its session.'));
102
+ else if (!f.session.established) lines.push(line("Stops its session, if one is running (its state couldn't be checked)."));
103
+ if (f.children.length) lines.push({ ...line(`Stops its ${plural(f.children.length, 'child instance')} first: ${names(f.children)}. They are kept, with their homes.`),
104
+ title: f.children.map(c => c.home).join('\n') });
105
+ lines.push(line('Saves a recovery copy of any uncommitted work, then deletes its home folder.', value.home));
106
+ if (tree.notOwn) lines.push(line(NOT_ITS_OWN));
107
+ else if (tree.unchecked) lines.push(line(requested.discardWorktree ? DELETES_UNCHECKED : KEEPS_UNCHECKED));
108
+ else if (tree.own) { const b = branchOf(f); lines.push(line(requested.discardWorktree ? `Deletes its worktree.${stays(b, leftover)}`
109
+ : `Keeps its worktree, moved aside${b ? `, on branch ${b}` : ''}.`)); }
110
+ // A home a spawn left (rollbackIncomplete): retire finishes its compensation, which deletes the branch
111
+ // the spawn created when it holds no work (the result's spawnCompensation says which).
112
+ lines.push(line(leftover ? 'Branches and pull requests are not changed, except a branch an interrupted spawn left with no work, which is deleted.'
113
+ : 'Branches and pull requests are not changed.'));
114
+ if (f.children.length) lines.push(line("If a child won't stop, nothing is retired.", undefined, 'note'));
115
+ return lines;
116
+ }
117
+ /** Current state: plain values by label, then what is not included and why. */
118
+ function current(value) {
119
+ const rows = [], notes = [];
120
+ const row = (label, value, title = '') => rows.push({ label, value, title });
121
+ if (value.action === 'stop') {
122
+ for (const t of value.targets) row(t.instance, sessionText(t.session));
123
+ for (const v of value.ambiguous) notes.push({ text: ambiguousText(v), tone: 'note' });
124
+ } else {
125
+ const f = value.facts, tree = treeOf(value);
126
+ row('Session', sessionText(f.session));
127
+ // Without a worktree of its own there is no Git work to report: the recovery line under What will happen covers it.
128
+ // When the kernel says the tree is not the instance's, nothing of `facts.work` is shown: it is an observation
129
+ // through any link, so for an attached instance it is its owner's tree, which this retire does not touch.
130
+ // A plan with no fact keeps the rows it had: what was observed, whoever's it is.
131
+ if (!tree.notOwn) {
132
+ if (f.work.observed || tree.own) row('Uncommitted work', workText(f.work), f.work.observed ? '' : f.work.reason);
133
+ if (f.work.observed) row('Branch', f.work.detached ? 'Detached' : f.work.branch);
134
+ if (f.work.observed && f.work.drift) notes.push({ text: `The worktree is on ${f.work.detached ? 'a detached commit' : f.work.branch}, not the branch it was spawned on${f.recordedBranch ? ` (${f.recordedBranch})` : ''}.`, tone: 'attention' });
135
+ }
136
+ for (const v of f.ambiguous) notes.push({ text: ambiguousText(v), tone: 'note', title: v.home });
137
+ }
138
+ return { rows, notes };
139
+ }
140
+ /** The warning under a checked "Also delete the worktree": in words, not colour alone. None when the kernel
141
+ * says the tree is not the instance's: the choice then stays on screen only to be undone, the notice says
142
+ * that it cannot be confirmed, and a warning would count another tree's changes and promise their deletion. */
143
+ function discardWarning(value, leftover) {
144
+ const f = value.facts, tree = treeOf(value);
145
+ if (tree.notOwn) return '';
146
+ if (tree.unchecked) return WARNS_UNCHECKED;
147
+ const n = f.work.observed ? f.work.changed + f.work.untracked : null;
148
+ const including = n === null ? ', including uncommitted changes, if any (a recovery copy is saved first)'
149
+ : n ? `, including ${plural(n, 'uncommitted change')} (a recovery copy is saved first)` : '';
150
+ return `Deletes the worktree folder${including}.${stays(branchOf(f), leftover)}`;
151
+ }
152
+ const question = (operation, target) => `${operation === 'retire' ? 'Retire' : 'Stop'} ${target.instance}?`;
153
+
154
+ /** What a plan says, for review. `choices`: the ones this plan was read for. `leftover`: the row is a home a
155
+ * failed spawn left (`rollbackIncomplete`). A choice is `offered` when the plan offers it (deleting the
156
+ * worktree: only an instance's own tree); a client keeps a choice that is set on screen, so it can be undone. */
157
+ export function planView(plan, { operation = plan.action, choices, leftover = false } = {}, terms) {
158
+ requireTerms(terms, 'planView');
159
+ const own = plan.action === 'retire' ? treeOf(plan).own : true, applicable = lifecycleChoicesApplicable(plan, choices);
160
+ return { question: question(operation, plan), happening: happening(plan, choices, leftover), state: current(plan),
161
+ warning: plan.action === 'retire' && choices.discardWorktree ? discardWarning(plan, leftover) : '',
162
+ choices: CHOICES[plan.action].map(([id, sentence]) => ({ id, sentence, value: choices[id], applies: lifecycleChoicesApplicable(plan, { [id]: choices[id] }),
163
+ offered: plan.action === 'retire' ? own : true })),
164
+ applicable, notice: applicable ? null : { code: 'E_OPTION_UNAVAILABLE', sentence: lifecycleReason('E_OPTION_UNAVAILABLE', terms).message },
165
+ targets: plan.action === 'stop' ? plan.targets.length : 1, own, at: plan.at };
166
+ }
167
+
168
+ /** One line per row of a stop's results or of a retire's child list; what a row is, and its words, are the contract's.
169
+ * The kernel's own sentence for a child whose home it could not lock is its quote. */
170
+ const rowsOf = values => values.map(v => ({ text: `${v.instance}: ${stoppedRowText(v)}`,
171
+ ...(stoppedRowKind(v) === 'locked' && cleanLine(v.detail) ? { quote: v.detail } : {}) }));
172
+ /** The branch an interrupted spawn left, which this retire deleted or kept (spawnCompensation); else nothing. */
173
+ function compensated(c) {
174
+ const branch = displayLine(c?.branch);
175
+ if (!branch) return null;
176
+ return line(c.branchDeleted ? `Branch ${branch} deleted: an interrupted spawn left it, and it held no work.`
177
+ : `Branch ${branch} kept: ${displayLine(c.reason) ?? 'no reason given'}`);
178
+ }
179
+ /** What a retire receipt says happened, each fact on its own line; paths beside them. */
180
+ function retired(receipt, snapshot, complete) {
181
+ const r = receipt.retention, children = receipt.childrenStopped;
182
+ return [complete && snapshot.facts.session.present === true && line('Session stopped.'),
183
+ children.length && line(`${plural(children.length, 'child instance')} stopped and kept.`),
184
+ line(receipt.removedDir ? 'Home folder deleted.' : 'Home folder kept.', receipt.removedDir ? undefined : receipt.retainedHome ?? undefined),
185
+ r?.worktree === 'retained' && line('Worktree kept at', r.movedTo), r?.worktree === 'removed' && line('Worktree deleted.'),
186
+ receipt.recoveryPath && line('Recovery copy saved at', receipt.recoveryPath),
187
+ compensated(receipt.spawnCompensation),
188
+ receipt.incomplete && line("Cleanup didn't finish.")].filter(Boolean);
189
+ }
190
+ /** A local reason's code and the CLI's own message, re-validated here (a reply is relayed as it is), or null: a
191
+ * code that may show one (lifecycleDetailCode) and a detail that is already a display line. The headline stays
192
+ * the fixed sentence for the code; the detail is only ever shown behind a disclosure. */
193
+ const localDetail = reason => reason && typeof reason === 'object' && !Object.hasOwn(reason, 'remote')
194
+ && lifecycleDetailCode(reason.code) && cleanLine(reason.detail) ? { code: reason.code, detail: reason.detail } : null;
195
+ /** A refusal: a remote host's headline, else the fixed sentence for the code (the shared table's); the code and
196
+ * the kernel's message behind a disclosure when there is one to show. `plan`: the snapshot the refusal is about,
197
+ * when there is one. Every status it answers carries the reason's `code` (and the kernel's busy `holder` when it
198
+ * is read by it): a client switches on the code, never on the words, and words a code only it raises itself. */
199
+ function refusal(reason, plan, { operation, leftover }, terms) {
200
+ // The kernel's busy answer, read by who holds the claim: the headline, the target it is about when that
201
+ // is another one of this plan, and the kernel's own sentence as the main text when it names what ends it.
202
+ const busy = busyRefusal(reason, plan);
203
+ if (busy) {
204
+ const more = [busy.about, busy.lead].filter(Boolean).map(text => ({ text }));
205
+ if (busy.sentence) more.push({ quote: busy.sentence });
206
+ return { status: { headline: busy.headline, more, next: null, code: reason.code, holder: reason.holder }, blocks: busy.details ? [{ type: 'details', reason: busy.details, bare: false }] : [] };
207
+ }
208
+ // An error the kernel answered that has no sentence here: the fallback sentence, and its code behind the disclosure.
209
+ const remote = remoteReason(reason), undescribed = undescribedRefusal(remote || reason, terms), shown = remote || undescribed || localDetail(reason);
210
+ // The kernel's own busy refusal (it carries the kernel's message; a client's own busy does not) for a home
211
+ // a spawn left: its sentence, and the kernel's message, which names the process, quoted under it.
212
+ if (!remote && shown && reason.code === 'E_LIFECYCLE_BUSY' && operation === 'retire' && leftover)
213
+ return { status: { headline: LEFTOVER_HELD, more: [], next: 'retire-with-force', code: reason.code }, blocks: [{ type: 'quote', text: shown.detail }] };
214
+ // A reason with no code reads as the table's fallback, and says that fallback's code; a code only the client
215
+ // raises (one the table does not know) keeps its own, so the client can word it.
216
+ const table = lifecycleReason(reason?.code, terms), own = typeof reason?.code === 'string' && reason.code ? reason.code : table.code;
217
+ const status = remote ? { headline: remote.message, code: remote.code } : undescribed ? { headline: undescribed.message, code: reason.code }
218
+ : { headline: table.message, code: own };
219
+ return { status: { more: [], next: null, ...status }, blocks: shown ? [{ type: 'details', reason: shown, bare: !!undescribed }] : [] };
220
+ }
221
+ /** A reply's `running` (this client's own apply that is still running), re-validated, or null: a target that names
222
+ * an instance, the act, and when it started (ms since the epoch). Read only beside this client's own busy refusal
223
+ * or an unknown outcome; the kernel's busy answer never carries it, and one that names a holder is never read so. */
224
+ function runningOf(result) {
225
+ const r = result?.running;
226
+ return r && typeof r === 'object' && typeof r.target?.instance === 'string' && ['stop', 'retire'].includes(r.operation) && Number.isFinite(r.since)
227
+ ? { target: { ...r.target }, operation: r.operation, since: r.since } : null;
228
+ }
229
+ const validTarget = (result, target) => result?.lifecycleApi === 1 && !!result.target && gitTargetKey(result.target) === gitTargetKey(target);
230
+
231
+ /** What a plan read that did not give a plan says: `reason` is the reply's (`null`: no reply that names this
232
+ * target, read as a protocol failure). */
233
+ export function unavailableView(reason, { target, operation }, terms) {
234
+ requireTerms(terms, 'unavailableView');
235
+ const { status, blocks } = refusal(reason ?? { code: 'E_CLI_PROTOCOL' }, null, { operation, leftover: false }, terms);
236
+ return { kind: 'unavailable', title: `Couldn't check what ${operation === 'retire' ? 'retiring' : 'stopping'} ${target.instance} will do`,
237
+ status, blocks, uncertain: false };
238
+ }
239
+
240
+ /** What an apply's answer says. `plan`: the snapshot that was confirmed; `choices`: the client's current ones (a
241
+ * stale answer's fresh plan is read for them). Any answer that does not read whole (another target, a receipt
242
+ * whose status its fields do not imply, child rows that are not the plan's) is `invalid`, shown as "Result not
243
+ * confirmed": never a second apply. */
244
+ export function outcomeView(result, { target, operation, choices, plan, leftover = false }, terms) {
245
+ requireTerms(terms, 'outcomeView');
246
+ const invalid = { kind: 'invalid', title: UNCONFIRMED, status: { headline: lifecycleReason('E_OUTCOME_UNKNOWN', terms).message, more: [], next: null, code: 'E_OUTCOME_UNKNOWN' },
247
+ blocks: [], uncertain: true };
248
+ try { return read(); } catch { return invalid; }
249
+ function read() {
250
+ if (!validTarget(result, target)) return invalid;
251
+ const name = target.instance, retire = operation === 'retire', uncertain = ['unknown', 'pending'].includes(result.status);
252
+ if (result.status === 'stale') {
253
+ const fresh = lifecyclePlan(result.plan, target, operation, choices);
254
+ if (!fresh) return invalid;
255
+ return { kind: 'stale', plan: fresh, planRef: planReference(result.planRef) ? result.planRef : null,
256
+ notice: { code: 'E_PLAN_STALE', sentence: lifecycleReason('E_PLAN_STALE', terms).message }, uncertain: false };
257
+ }
258
+ if (result.receipt) {
259
+ const receipt = publicLifecycleReceipt(result.receipt, plan); if (!receipt) return invalid;
260
+ const expected = receipt.deferred ? 'pending' : (receipt.action === 'stop' ? receipt.ok : receipt.removedDir && !receipt.incomplete) ? 'complete' : 'partial';
261
+ if (result.status !== expected) return invalid;
262
+ const replay = receipt.replayed || result.repeated ? [{ type: 'note', text: REPLAYED }] : [];
263
+ if (receipt.deferred) return { kind: 'pending', title: 'Retirement accepted', uncertain,
264
+ status: { headline: 'Retirement was accepted and will finish in the background.', more: [], next: 'check-roster' }, blocks: replay };
265
+ const done = receipt.action === 'stop' ? { type: 'rows', rows: rowsOf(receipt.results) } : { type: 'lines', lines: retired(receipt, plan, expected === 'complete') };
266
+ if (expected === 'complete') {
267
+ const title = receipt.action === 'stop' && receipt.results.length > 1 ? `${receipt.results.length} sessions stopped` : `${name} ${retire ? 'retired' : 'stopped'}`;
268
+ return { kind: 'complete', title, status: { headline: `${title}.`, more: [], next: null }, blocks: [done, ...replay], uncertain };
269
+ }
270
+ // A stop that is not ok: the sentence above the rows is chosen from the rows, so it agrees with them.
271
+ const words = receipt.action === 'stop' ? stopResultWords(receipt.results) : { status: "Retirement didn't finish. Some steps ran:", title: "Retirement didn't finish" };
272
+ const code = result.reason?.code ?? (receipt.action === 'stop' ? 'E_SESSION_STOP_FAILED' : 'E_RETIRE_INCOMPLETE');
273
+ return { kind: 'partial', title: words.title, status: { headline: words.status, more: [], next: null, code }, blocks: [done, ...replay], uncertain };
274
+ }
275
+ // The rows are the server's, already decoded: validated here, never decoded again.
276
+ const children = result.childrenStopped ? decodedStoppedTargets(result.childrenStopped, plan.facts?.children || []) : null;
277
+ if (result.childrenStopped && !children) return invalid;
278
+ let { status, blocks } = refusal(result.reason?.code ? result.reason : { code: 'E_OUTCOME_UNKNOWN' }, plan, { operation, leftover }, terms);
279
+ // This client's own apply is running (its busy refusal, or the answer of an apply whose wait ended): which one
280
+ // is said, in place of the general sentence of the busy refusal. Never for the kernel's busy answer.
281
+ const running = runningOf(result), own = running && !Object.hasOwn(result.reason ?? {}, 'holder');
282
+ if (own && result.reason?.code === 'E_LIFECYCLE_BUSY') status = { headline: applyRunningSentence(running, terms), more: [], next: null, code: 'E_LIFECYCLE_BUSY' };
283
+ if (children && result.reason?.code === 'E_CHILDREN_RUNNING') status = { headline: childrenRefusedMessage(children), more: [], next: null, code: 'E_CHILDREN_RUNNING' };
284
+ // Why the outcome is unknown: a remote transport or host cause keeps its headline and its line; a
285
+ // local one says its fixed sentence, with the CLI's own message behind the disclosure when it carries one.
286
+ // An apply whose wait ended is still running: that is said in place of the timeout, which ended only the wait.
287
+ if (own && uncertain) return { kind: 'unknown', title: UNCONFIRMED, status, uncertain, running,
288
+ blocks: [...blocks, { type: 'note', text: `The ${running.operation === 'retire' ? 'removal' : 'stop'} of ${displayLine(running.target.instance) ?? 'this instance'} is still running. Check again to read its result.` }] };
289
+ const cause = result.cause && remoteReason(result.cause);
290
+ const undescribed = result.cause && undescribedRefusal(cause || result.cause, terms);
291
+ blocks = [...blocks];
292
+ if (cause) blocks.push({ type: 'note', text: cause.message }, { type: 'details', reason: cause, bare: !!undescribed });
293
+ else if (result.cause) {
294
+ blocks.push({ type: 'note', text: undescribed ? undescribed.message : lifecycleReason(result.cause.code, terms).message });
295
+ const local = undescribed || localDetail(result.cause); if (local) blocks.push({ type: 'details', reason: local, bare: !!undescribed });
296
+ }
297
+ if (children) blocks.push({ type: 'note', text: 'Child instances:' }, { type: 'rows', rows: rowsOf(children) });
298
+ return { kind: uncertain ? 'unknown' : 'refused', title: uncertain ? UNCONFIRMED : `${name} wasn't ${retire ? 'retired' : 'stopped'}`, status, blocks, uncertain,
299
+ ...(own ? { running } : {}) };
300
+ }
301
+ }
302
+
303
+ /** The sentence for this client's own apply that is still running (`running`: { target, operation, since }, on
304
+ * the client's own busy refusal and on the unknown answer of an apply whose wait ended). The name is shown
305
+ * through the display filter. When it started is `running.since`, a field: each client words a time its own way. */
306
+ export function applyRunningSentence(running, terms) {
307
+ requireTerms(terms, 'applyRunningSentence');
308
+ const name = displayLine(running?.target?.instance) ?? 'this instance';
309
+ return `The ${running?.operation === 'retire' ? 'removal' : 'stop'} of ${name} is still running. Wait for it to finish, then review again.`;
310
+ }
311
+
312
+ /** What each settled outcome offers, and no other (the table of #855's 5a): a key is one intent. "Check again"
313
+ * asks for the answer to the confirmation already sent, by the same reference; trying again is a new plan. */
314
+ const SETTLED_OFFERS = Object.freeze({ complete: ['close'], partial: ['refresh', 'close'], refused: ['refresh', 'close'],
315
+ unknown: ['check-again', 'close'], pending: ['check-again', 'close'], invalid: ['check-again', 'close'], unavailable: ['refresh', 'close'] });
316
+
317
+ /** One confirmation of one act on one row: the client's half of the transaction. `request(body)` is the client's
318
+ * way to its boundary. `onChange(event, detail)` is told every step, synchronously, so the client can draw it:
319
+ * 'reading' a plan is being read: { cause, kept, view } kept: the plan on screen stays until the new one
320
+ * 'plan' a plan to review: { plan, planRef, view }
321
+ * 'unavailable' the plan could not be read: { view }
322
+ * 'applying' the confirmation was sent: { view }
323
+ * 'stale' the plan changed: back to review with the fresh plan: { plan, planRef, view, notice }
324
+ * 'settled' an apply's answer: { view, result }
325
+ * `onSettled(result, target)` is called once for every apply answer that reads and is not a return to review;
326
+ * what it does or throws changes nothing here. `label`: the server's label for a routed row; `leftover`: the row
327
+ * is a home a failed spawn left. Each step carries this confirmation's latest-intent token: an answer to an
328
+ * earlier step, or one after close, changes nothing and is not told. Nothing is kept beyond the instance. */
329
+ export function createLifecycleConfirmation({ request, target, operation, terms, onSettled = () => {}, onChange = () => {}, label = null, leftover = false, choices: initial = null } = {}) {
330
+ requireTerms(terms, 'createLifecycleConfirmation');
331
+ if (typeof request !== 'function' || !target?.instance || !['stop', 'retire'].includes(operation)) throw new TypeError('createLifecycleConfirmation: a request, a target and an operation (stop or retire)');
332
+ let choices = lifecycleOptions(operation, initial) ?? (operation === 'stop' ? { recursive: true } : { discardWorktree: false });
333
+ let phase = 'reading', outcome = null, notice = null, plan = null, planRef = null, shown = null, submission = null, settledView = null, ticket = 0, closed = false, current = null;
334
+ const tell = (event, detail) => { try { onChange(event, detail); } catch { /* a client's drawing changes nothing here */ } };
335
+ const verb = operation === 'retire' ? 'retiring' : 'stopping';
336
+ const applicable = () => !!plan && lifecycleChoicesApplicable(plan, choices);
337
+ function offers() {
338
+ if (closed) return [];
339
+ if (phase === 'reading' || phase === 'applying') return ['close'];
340
+ if (phase === 'review') return [...(planRef && applicable() ? ['apply'] : []), 'refresh', 'close'];
341
+ return [...SETTLED_OFFERS[outcome]];
342
+ }
343
+ /** Read a plan. The reference on screen is revoked at once; the plan on screen stays while a new one is read
344
+ * only when it was under review (`kept`). */
345
+ async function read(cause) {
346
+ const mine = ++ticket, requested = { ...choices }, kept = !!shown && phase === 'review' || !!shown && phase === 'reading' && current?.kept;
347
+ plan = null; planRef = null; submission = null; notice = null; outcome = null; settledView = null; phase = 'reading';
348
+ if (!kept) shown = null;
349
+ current = { kind: 'reading', cause, kept, title: question(operation, target),
350
+ message: kept ? (cause === 'check' ? 'Checking again…' : 'Updating for this choice…') : label ? readingFrom(label) : `Checking what ${verb} ${target.instance} will do…` };
351
+ tell('reading', { cause, kept, view: current });
352
+ const failed = reason => {
353
+ if (mine !== ticket || closed) return;
354
+ phase = 'settled'; outcome = 'unavailable'; shown = null; settledView = current = unavailableView(reason, { target, operation }, terms);
355
+ tell('unavailable', { view: current });
356
+ };
357
+ try {
358
+ const result = await request({ action: 'plan', operation, selector: { instance: target.instance, agent: target.agent, agentsRoot: target.agentsRoot, server: target.server ?? null }, options: requested });
359
+ if (mine !== ticket || closed) return;
360
+ if (!validTarget(result, target) || result.status !== 'plan') { failed(validTarget(result, target) ? result.reason : { code: result?.reason?.code }); return; }
361
+ const value = lifecyclePlan(result.plan, target, operation, requested);
362
+ if (!value || !planReference(result.planRef) || JSON.stringify(lifecycleOptions(operation, result.options)) !== JSON.stringify(requested)) throw new Error('Invalid plan');
363
+ plan = value; planRef = result.planRef; shown = value; phase = 'review'; current = planView(value, { operation, choices: requested, leftover }, terms);
364
+ tell('plan', { plan, planRef, view: current });
365
+ } catch { failed({ code: 'E_CLI_PROTOCOL' }); }
366
+ }
367
+ /** Send the reference: the one under review (`apply`), or the one already sent (`checkAgain`). */
368
+ async function send(again) {
369
+ const mine = ++ticket, snapshot = again ? submission.plan : plan, reference = again ? submission.reference : planRef;
370
+ submission = { reference, plan: snapshot, uncertain: true };
371
+ phase = 'applying'; planRef = null; outcome = null; notice = null; settledView = null;
372
+ current = { kind: 'applying', title: `${operation === 'retire' ? 'Retiring' : 'Stopping'} ${target.instance}…`,
373
+ message: operation === 'retire' ? `Retiring ${target.instance}. This can take up to a minute while sessions stop.` : `Stopping ${target.instance}. This can take up to a minute.` };
374
+ tell('applying', { view: current });
375
+ let result = null, view;
376
+ try { result = await request({ action: 'apply', planRef: reference }); view = outcomeView(result, { target, operation, choices, plan: snapshot, leftover }, terms); }
377
+ catch { view = outcomeView(null, { target, operation, choices, plan: snapshot, leftover }, terms); }
378
+ if (mine !== ticket || closed) return;
379
+ if (view.kind === 'stale') {
380
+ plan = view.plan; planRef = view.planRef; shown = view.plan; notice = view.notice; phase = 'review';
381
+ current = planView(view.plan, { operation, choices, leftover }, terms);
382
+ tell('stale', { plan, planRef, view: current, notice });
383
+ return;
384
+ }
385
+ submission.uncertain = view.uncertain; phase = 'settled'; outcome = view.kind; settledView = current = view;
386
+ tell('settled', { view, result });
387
+ if (view.kind !== 'invalid') { try { Promise.resolve(onSettled(result, target)).catch(() => {}); } catch { /* a refresh cannot erase a recorded outcome */ } }
388
+ }
389
+ void read('open');
390
+ return {
391
+ /** `running`: this client's own apply that is still running, when the settled answer says so (when it
392
+ * started is `running.since`, ms since the epoch, for the client to word). */
393
+ state: () => ({ phase, outcome: phase === 'settled' ? outcome : null, notice, offers: offers(), running: phase === 'settled' && settledView?.running ? { ...settledView.running } : null }),
394
+ view: () => current,
395
+ /** Set one choice of the plan (an id of `planView(…).choices`) and read the plan for it: while a plan is read
396
+ * or reviewed, the latest choice wins. */
397
+ setChoice(id, value) {
398
+ if (closed || !['reading', 'review'].includes(phase) || !CHOICES[operation].some(([c]) => c === id) || typeof value !== 'boolean') return false;
399
+ choices = { [id]: value }; void read('option'); return true;
400
+ },
401
+ refresh(cause = 'review') { if (!offers().includes('refresh')) return false; void read(cause === 'check' ? 'check' : 'review'); return true; },
402
+ apply() { if (!offers().includes('apply')) return false; void send(false); return true; },
403
+ checkAgain() { if (!offers().includes('check-again') || !submission) return false; void send(true); return true; },
404
+ /** Closing cancels nothing that was sent: the answer is no longer told. */
405
+ close() { closed = true; ticket++; },
406
+ };
407
+ }
@@ -139,8 +139,12 @@ export function busyRefusal(reason, plan = null) {
139
139
  }
140
140
  export function lifecycleFailure(code, terms, extra = {}) {
141
141
  requireTerms(terms, 'lifecycleFailure');
142
- return { lifecycleApi: LIFECYCLE_API, status: 'unavailable', target: null, planRef: null, plan: null, receipt: null,
143
- reason: lifecycleReason(code, terms), ...extra };
142
+ return lifecycleFailureOf(lifecycleReason(code, terms), extra);
143
+ }
144
+ /** A lifecycle failure whose reason is ready: one a client words itself, for a code of its own that the shared
145
+ * table does not know (the Desktop's frame guard). It words nothing, so it takes no terms. */
146
+ export function lifecycleFailureOf(reason, extra = {}) {
147
+ return { lifecycleApi: LIFECYCLE_API, status: 'unavailable', target: null, planRef: null, plan: null, receipt: null, reason, ...extra };
144
148
  }
145
149
  export function lifecycleOptions(operation, v) {
146
150
  if (!object(v)) return null;
@@ -20,6 +20,7 @@ export const CLIENT_OWN_CODES = Object.freeze([
20
20
  'E_UNSUPPORTED_OPTION', 'E_WAKE_OUTCOME_UNKNOWN', 'E_WAKE_SAVE_FAILED',
21
21
  // Stop, start, restart and remove, and the plan a person confirms (a spawn's plan too).
22
22
  'E_LIFECYCLE_UNAVAILABLE', 'E_OPTION_UNAVAILABLE', 'E_PLAN_CHANGED', 'E_PLAN_EXPIRED', 'E_PLAN_LIMIT', 'E_PLAN_REQUIRED',
23
+ 'E_HOME_UNVERIFIED', 'E_START_UNCONFIRMED',
23
24
  // An instance's Activity.
24
25
  'E_EVENTS_UNAVAILABLE', 'E_NOT_IN_SCOPE',
25
26
  // A terminal.
@@ -41,6 +41,7 @@ import { deploymentUnavailableText, keptFailure } from './deployment-facts.mjs';
41
41
  import { publicDeployment } from './deployment-panel.mjs';
42
42
  import { teamMembers } from './team-members.mjs';
43
43
  import { requireTerms } from './client-terms.mjs';
44
+ import { ROSTER_WORKSPACE_KEY } from './cli-adapter.mjs';
44
45
 
45
46
  /** Roots come ONLY from the kernel's observed `status.root`; before (or
46
47
  * without) an observation there is nothing to act on. No layout guess. */
@@ -97,6 +98,9 @@ export function deploymentInfo(held, d, terms) {
97
98
  }
98
99
  const g = d.group, machine = g.label || g.server;
99
100
  const reached = g.probe?.ok === true;
101
+ // A group a filtered roster read kept as last read (#1124, `held.keptReadAt`: remote-roster.mjs `keptReadTimes`):
102
+ // a machine reached then is stale now, as this computer's deployment is after a failed re-read, never live.
103
+ const kept = reached && !!held.keptReadAt?.get?.(g.id);
100
104
  let read = reached ? (identityFeature(held) ? readIdentity(g.workspace) : { status: "feature" }) : { status: "none" };
101
105
  let identityFrom = read.status === "identity" ? "reported" : null;
102
106
  if (!reached && (g.remembered || held.remembered.get(g.id))) {
@@ -110,7 +114,7 @@ export function deploymentInfo(held, d, terms) {
110
114
  const moved = held.remembered.note(g.id);
111
115
  const standalone = attach.note === "standalone" ? deploymentReason({ local: false, attach: { unattached: "standalone" } }, terms) : null;
112
116
  return { id: d.id, local: false, machine, path: g.target?.workspace || "", label: shortPath(g.target?.workspace || ""), name: d.name,
113
- live: reached, reachable: reached, identityFrom, identity, attach, teamLabel: identity?.defaultTeam?.label ?? null,
117
+ live: reached && !kept, reachable: reached, ...(kept ? { stale: true } : {}), identityFrom, identity, attach, teamLabel: identity?.defaultTeam?.label ?? null,
114
118
  ...reason, note: [moved, standalone].filter(Boolean).join(" ") || null };
115
119
  }
116
120
  /** A reason's parts as a deployment's fields: `reason` (the full sentence), `short` and `fix` (UI spec, #482). */
@@ -209,6 +213,38 @@ export function machineScope(held, wsId, terms) {
209
213
  return { key: identity.key, deployment: local.id, messaging };
210
214
  }
211
215
 
216
+ /** The workspace keys the roster read asks for (#1124, the CLI's feature roster-workspace-key): one per
217
+ * distinct usable key of the views the open windows show (`windowViews`: each window's view id, or null
218
+ * for a window bound to none), sorted; or null for the unfiltered read. The key of a view:
219
+ *
220
+ * a matched view its key (every deployment of it reports that key)
221
+ * an unattached view its one deployment's key, reported or (a machine not reached)
222
+ * remembered, member-derived included: a registration records the
223
+ * key the host reports, whatever its keyFrom
224
+ *
225
+ * A key that is null, or one the kernel would refuse (cli-adapter.mjs `ROSTER_WORKSPACE_KEY`), is no
226
+ * registration's: a view without a usable key adds none, and when that view holds another machine's
227
+ * deployment, whose registration then cannot be named, the read is unfiltered so that machine is still
228
+ * read. Unfiltered too: no window set yet (`windowViews` not an array), no roster answer yet (the first
229
+ * read holds every machine), a window showing the switcher (it lists every workspace), and a view id
230
+ * no view has (a window ahead of what is served). No window, or no usable key: `[]`, which a caller
231
+ * reads unfiltered as well. */
232
+ export function rosterWorkspaceKeys(held, windowViews, terms) {
233
+ requireTerms(terms, 'rosterWorkspaceKeys');
234
+ if (!Array.isArray(windowViews) || !held.rosterAnswered) return null;
235
+ const model = viewModel(held, terms);
236
+ const keys = new Set();
237
+ for (const id of windowViews) {
238
+ if (id === null) return null;
239
+ const view = model.views.find((v) => v.id === id);
240
+ if (!view) return null;
241
+ const key = view.key ?? model.infos.get(view.primary)?.identity?.key ?? null;
242
+ if (typeof key === 'string' && ROSTER_WORKSPACE_KEY.test(key)) keys.add(key);
243
+ else if (view.deployments.some((d) => !model.infos.get(d)?.local)) return null;
244
+ }
245
+ return [...keys].sort();
246
+ }
247
+
212
248
  /** A deployment as the panel and the rows name it. */
213
249
  export const deploymentTag = (info) => ({ id: info.id, machine: info.machine, path: info.path });
214
250
  /** A deployment's entry in the panel's `deployments` list (roster-sections.mjs `deploymentState` reads one). */
@@ -222,7 +258,8 @@ export function deploymentEntry(info, primary) {
222
258
  /** One deployment's own panel, as served before views. */
223
259
  export function deploymentPanel(held, ws) {
224
260
  // Another machine's panel never says who made its `error`: the key is removed here whatever the panel carried.
225
- if (ws?.remote) { const { errorOrigin: _sent, ...panel } = remotePanel(ws.group, held.at); return { ...panel, observedAt: null, refreshing: held.remoteCollecting }; }
261
+ // A kept group's panel is made at the time it was read (#1124): a filtered read never makes it look newer.
262
+ 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 }; }
226
263
  const observed = ws ? held.snapshot.byWs.get(ws.id) : null;
227
264
  const instances = observed?.instances || [], kept = keptFailure(observed);
228
265
  return {
@@ -6,7 +6,7 @@ import { effectiveOf, REPORT_FROM } from './launch-contract.mjs';
6
6
  import { defaultTeamOf } from './team-rows.mjs';
7
7
  import { remoteReason } from './remote-address.mjs';
8
8
  import { warningsOf } from './capability-warnings-contract.mjs';
9
- import { displayLine } from './display-text.mjs';
9
+ import { displayLine, DETAIL_WITHHELD } from './display-text.mjs';
10
10
  export const READINESS_API = 2;
11
11
  export const CHECKS = ['installed', 'configured', 'member', 'providers'];
12
12
  export const record = v => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -17,7 +17,7 @@ const states = ['pass', 'fail', 'unknown', 'not-applicable'];
17
17
  // The URL alternative finds `://` first and looks behind it for the scheme, as display-text.mjs `UNSAFE`
18
18
  // does and for its reason: time that grows with the length of the text, not with the square of a run.
19
19
  const unsafe = /[\x00-\x08\x0b-\x1f\x7f]|:\/\/(?<=[a-z][a-z0-9+.-]*:\/\/)[^\s/]*@|(?:token|authorization|password|secret|api[_ -]?key)\s*[:=]\s*\S+/i;
20
- function text(v, max = 1024) { if (typeof v !== 'string' || v.length > max) throw Error(); return unsafe.test(v) ? '[Detail withheld]' : v; }
20
+ function text(v, max = 1024) { if (typeof v !== 'string' || v.length > max) throw Error(); return unsafe.test(v) ? DETAIL_WITHHELD : v; }
21
21
  const nullable = v => v == null ? null : text(v);
22
22
  export function readinessSelector(v) {
23
23
  if (!record(v)) return null;