@awebai/oats 0.51.0 → 0.53.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 (166) hide show
  1. package/README.md +3 -1
  2. package/bin/oats.mjs +407 -123
  3. package/docs/capabilities.md +75 -6
  4. package/docs/configuration.md +200 -91
  5. package/docs/desktop-cli-api.md +1563 -113
  6. package/docs/desktop-instance-start.md +69 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +145 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +238 -17
  12. package/docs/integrations.md +13 -9
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +25 -2
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/macos-test-runs.md +246 -0
  20. package/docs/oats-local.schema.json +4 -3
  21. package/docs/official-catalog.md +5 -5
  22. package/docs/packages.md +14 -14
  23. package/docs/release-lane.md +225 -11
  24. package/docs/release-notes/v0.44.0.md +1 -1
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/release-notes/v0.53.0.md +1274 -0
  27. package/docs/schedules.md +97 -4
  28. package/docs/souls-and-instances.md +332 -40
  29. package/docs/tui.md +584 -0
  30. package/docs/upgrading.md +298 -0
  31. package/docs/workspaces.md +3 -3
  32. package/lib/automations.mjs +22 -22
  33. package/lib/claim.mjs +278 -49
  34. package/lib/config-data.mjs +4 -1
  35. package/lib/core.mjs +1282 -289
  36. package/lib/errors.mjs +170 -0
  37. package/lib/harness-trust-write.mjs +68 -27
  38. package/lib/harness-trust.mjs +34 -16
  39. package/lib/instance-events.mjs +19 -1
  40. package/lib/instance-git.mjs +39 -3
  41. package/lib/instance-inspect.mjs +45 -17
  42. package/lib/instance-lifecycle.mjs +306 -57
  43. package/lib/instance-resolution.mjs +59 -6
  44. package/lib/launch-preference.mjs +236 -9
  45. package/lib/launch-prompt-completion.mjs +7 -43
  46. package/lib/launch-prompt-evidence.mjs +14 -7
  47. package/lib/launch-prompt-fixtures/README.md +86 -152
  48. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  49. package/lib/launch-prompt-fixtures.mjs +122 -109
  50. package/lib/launch-prompt-transport.mjs +2 -56
  51. package/lib/launch-prompts.mjs +102 -100
  52. package/lib/local-edit.mjs +118 -0
  53. package/lib/packages.mjs +13 -4
  54. package/lib/pi-bridge.mjs +308 -0
  55. package/lib/refused-text.mjs +11 -0
  56. package/lib/remote.mjs +190 -25
  57. package/lib/resolve.mjs +2 -1
  58. package/lib/retained-after-retire.mjs +2 -2
  59. package/lib/retire-output.mjs +12 -1
  60. package/lib/schedule-host.mjs +125 -22
  61. package/lib/schedule.mjs +73 -24
  62. package/lib/shell-word.mjs +13 -0
  63. package/lib/soul-launch-verbs.mjs +153 -0
  64. package/lib/stable-node.mjs +62 -0
  65. package/lib/system-tools.mjs +39 -0
  66. package/lib/teams-verbs.mjs +18 -46
  67. package/lib/tmux-server-scope.mjs +62 -0
  68. package/lib/triggers.mjs +4 -4
  69. package/lib/workspace.mjs +54 -30
  70. package/lib/worktree-hooks.mjs +98 -20
  71. package/lib/worktree.mjs +83 -24
  72. package/package-catalog.json +4 -4
  73. package/package.json +8 -2
  74. package/packages/client/attach-exit.mjs +25 -0
  75. package/packages/client/capability-show-contract.mjs +230 -0
  76. package/packages/client/capability-warnings-contract.mjs +57 -0
  77. package/packages/client/cli-adapter.mjs +561 -0
  78. package/packages/client/cli-environment.mjs +53 -0
  79. package/packages/client/cli-locator.mjs +253 -0
  80. package/packages/client/cli-probe-contract.mjs +47 -0
  81. package/packages/client/client-terms.mjs +60 -0
  82. package/packages/client/deployment-contract.mjs +72 -0
  83. package/packages/client/deployment-data.mjs +483 -0
  84. package/packages/client/deployment-facts.mjs +95 -0
  85. package/packages/client/deployment-label.mjs +76 -0
  86. package/packages/client/deployment-observer.mjs +89 -0
  87. package/packages/client/deployment-panel.mjs +180 -0
  88. package/packages/client/deployment-read-cli.mjs +57 -0
  89. package/packages/client/display-text.mjs +50 -0
  90. package/packages/client/harness-names.mjs +30 -0
  91. package/packages/client/inspect-contract.mjs +62 -0
  92. package/packages/client/instance-acts.mjs +90 -0
  93. package/packages/client/instance-admission.mjs +45 -0
  94. package/packages/client/instance-events-contract.mjs +76 -0
  95. package/packages/client/instance-git-contract.mjs +80 -0
  96. package/packages/client/instance-presentation.mjs +86 -0
  97. package/packages/client/instance-tree.mjs +462 -0
  98. package/packages/client/kernel-environment.mjs +11 -0
  99. package/packages/client/kernel-lines.mjs +31 -0
  100. package/packages/client/kernel-made.mjs +23 -0
  101. package/packages/client/launch-contract.mjs +51 -0
  102. package/packages/client/launch-prompt-outcome.mjs +200 -0
  103. package/packages/client/lifecycle-cli.mjs +61 -0
  104. package/packages/client/lifecycle-contract.mjs +413 -0
  105. package/packages/client/liveness-main.mjs +10 -0
  106. package/packages/client/liveness.mjs +48 -0
  107. package/packages/client/machine-contract.mjs +123 -0
  108. package/packages/client/own-codes.mjs +31 -0
  109. package/packages/client/own-environment.mjs +22 -0
  110. package/packages/client/panel-views.mjs +293 -0
  111. package/packages/client/readiness-contract.mjs +174 -0
  112. package/packages/client/refresh-loop.mjs +52 -0
  113. package/packages/client/remote-address.mjs +151 -0
  114. package/packages/client/remote-identity-memory.mjs +94 -0
  115. package/packages/client/remote-roster.mjs +153 -0
  116. package/packages/client/roster-sections.mjs +80 -0
  117. package/packages/client/session-attach.mjs +175 -0
  118. package/packages/client/spawn-apply-cli.mjs +104 -0
  119. package/packages/client/spawn-apply-contract.mjs +195 -0
  120. package/packages/client/spawn-decision.mjs +46 -0
  121. package/packages/client/spawn-messages.mjs +142 -0
  122. package/packages/client/spawn-preview-cli.mjs +38 -0
  123. package/packages/client/spawn-preview-contract.mjs +318 -0
  124. package/packages/client/team-members.mjs +41 -0
  125. package/packages/client/team-rows.mjs +45 -0
  126. package/packages/client/terminal-contract.mjs +57 -0
  127. package/packages/client/terminal-exec.mjs +21 -0
  128. package/packages/client/tmux-status.mjs +66 -0
  129. package/packages/client/waiting-on-you.mjs +88 -0
  130. package/packages/client/workspace-admission.mjs +45 -0
  131. package/packages/client/workspace-choices.mjs +95 -0
  132. package/packages/client/workspace-cli.mjs +142 -0
  133. package/packages/client/workspace-views.mjs +183 -0
  134. package/packages/record/README.md +21 -0
  135. package/packages/record/bin/setup.mjs +108 -15
  136. package/packages/tui/README.md +64 -0
  137. package/packages/tui/bin/tui.mjs +7 -0
  138. package/packages/tui/lib/actions.mjs +44 -0
  139. package/packages/tui/lib/client.mjs +35 -0
  140. package/packages/tui/lib/config.mjs +151 -0
  141. package/packages/tui/lib/main.mjs +176 -0
  142. package/packages/tui/lib/model.mjs +392 -0
  143. package/packages/tui/lib/read.mjs +473 -0
  144. package/packages/tui/lib/store.mjs +364 -0
  145. package/packages/tui/lib/term/keys.mjs +367 -0
  146. package/packages/tui/lib/term/screen.mjs +134 -0
  147. package/packages/tui/lib/term/style.mjs +43 -0
  148. package/packages/tui/lib/term/text.mjs +109 -0
  149. package/packages/tui/lib/term/tty.mjs +178 -0
  150. package/packages/tui/lib/term/width.mjs +124 -0
  151. package/packages/tui/lib/views/detail.mjs +46 -0
  152. package/packages/tui/lib/views/frame.mjs +256 -0
  153. package/packages/tui/lib/views/help.mjs +140 -0
  154. package/packages/tui/lib/views/instances.mjs +137 -0
  155. package/packages/tui/lib/views/scroll.mjs +19 -0
  156. package/packages/tui/lib/views/switcher.mjs +97 -0
  157. package/packages/tui/package.json +8 -0
  158. package/skills/oats-getting-started/SKILL.md +30 -23
  159. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  160. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  161. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  162. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  163. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  164. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  165. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  166. package/lib/launch-prompt-policy.mjs +0 -87
@@ -0,0 +1,413 @@
1
+ /** K3 projection/validation only. No IO, kernel decisions or executable paths. */
2
+ import { gitRevision } from './instance-git-contract.mjs';
3
+ import { displayLine, cleanLine, DETAIL_WITHHELD } from './display-text.mjs';
4
+ import { kernelCode } from './remote-address.mjs';
5
+ import { requireTerms } from './client-terms.mjs';
6
+ export const LIFECYCLE_API = 1;
7
+ export const MAX_LIFECYCLE_TARGETS = 128;
8
+ export const object = v => !!v && typeof v === 'object' && !Array.isArray(v);
9
+ export const text = (v, max = 4096) => typeof v === 'string' && v.length <= max && !v.includes('\0')
10
+ && !/(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{16,}|https?:\/\/[^/\s]+@/.test(v);
11
+ const nullable = v => v === null || text(v);
12
+ const absolute = v => text(v) && v.startsWith('/');
13
+ const count = v => Number.isSafeInteger(v) && v >= 0;
14
+ const numberOrNull = v => v === null || count(v);
15
+ export const planRevision = v => typeof v === 'string' && /^[a-f0-9]{24}$/.test(v);
16
+ export const planReference = v => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
17
+ const at = v => typeof v === 'string' && Number.isFinite(Date.parse(v));
18
+ const strings = v => Array.isArray(v) && v.length <= 64 && v.every(n => text(n));
19
+ const messages = {
20
+ E_BAD_ARGS: 'Invalid lifecycle request.', E_WORKSPACE_UNKNOWN: 'Choose an advertised workspace.',
21
+ E_SESSION_UNKNOWN: 'This instance is no longer in the current roster.', E_AMBIGUOUS_INSTANCE: 'Select an exact instance home.',
22
+ E_HOME_MISMATCH: 'The instance home no longer matches this selection.',
23
+ // The kernel's, for a home it cannot work from: a record that is there and cannot be read, a rollback
24
+ // marker that cannot drive a retry, or neither a record nor a cleanup descriptor. Answered only before any effect.
25
+ E_UNIDENTIFIED_INSTANCE_HOME: "OATS couldn't find or read what it needs in this instance's home folder, so nothing was done.",
26
+ 'cli-unavailable': 'Choose a compatible installed OATS CLI.',
27
+ E_LIFECYCLE_UNAVAILABLE: terms => `This OATS can't stop or retire instances from ${terms.name}. Update OATS.`,
28
+ 'unsupported-remote-operation': "This computer's OATS can't route this to the server. Update OATS here.",
29
+ E_PLAN_REQUIRED: 'Open a fresh Stop or Retire confirmation; unguarded retirement is unavailable.',
30
+ E_PLAN_EXPIRED: 'This confirmation expired. Review again to check the current state.',
31
+ E_PLAN_CHANGED: 'The instance or OATS changed. Review again before confirming.',
32
+ E_OPTION_UNAVAILABLE: 'Only an instance with its own worktree can delete it. Review the choice again.',
33
+ E_PLAN_STALE: 'Something changed since you opened this. Review it and confirm again.',
34
+ E_PLAN_LIMIT: terms => `This would act on more instances than ${terms.name} can show. Nothing was submitted.`,
35
+ E_LIFECYCLE_BUSY: 'Another stop or retire is already running. Wait for it to finish, then review again.',
36
+ E_INSTANCE_RETIRING: 'An instance in this plan is already being retired.',
37
+ E_CHILDREN_RUNNING: "A child instance wouldn't stop, so nothing was retired. Other children may already have stopped.",
38
+ E_SESSION_STOP_FAILED: "The session didn't stop in time. Nothing was forced.",
39
+ E_WORK_PRESERVATION_FAILED: "Its work couldn't be saved safely, so the home folder is kept. Earlier retirement steps may have run.",
40
+ E_WORK_INSPECTION_FAILED: "Retirement was refused: OATS couldn't inspect the instance's home or work. The home folder is kept; its session may already have been stopped, and earlier retirement steps may have run.",
41
+ E_RETIRE_INCOMPLETE: "Retirement didn't finish cleaning up. Check what was kept before trying again.",
42
+ // True of both things the kernel answers it for: a session window it could not show gone, and the hook
43
+ // group an interrupted spawn left that survived both signals. The outcome is unknown; this is its cause.
44
+ E_RUNTIME_QUIESCE_FAILED: "OATS tried to end a session or a process and couldn't confirm that it ended.",
45
+ E_CLI_TIMEOUT: "OATS didn't answer in time.", E_CLI_OUTPUT_LIMIT: terms => `OATS's answer was larger than ${terms.name} reads safely.`,
46
+ E_CLI_PROTOCOL: terms => `OATS answered in a form ${terms.name} can't read.`, E_CLI_FAILED: "OATS couldn't be run for this.",
47
+ E_OUTCOME_UNKNOWN: "OATS didn't confirm the result. Check again before assuming nothing happened.",
48
+ };
49
+ /** Every code the table has a sentence for. */
50
+ export const LIFECYCLE_CODES = Object.freeze(Object.keys(messages));
51
+ /** The code as the table knows it: itself, or `E_CLI_FAILED` for one it has no sentence for. Needs no terms. */
52
+ export const lifecycleCode = code => (Object.hasOwn(messages, code) ? code : 'E_CLI_FAILED');
53
+ /** The code and its sentence, in the client's terms (client-terms.mjs): a sentence that names the client is
54
+ * built from them. */
55
+ export function lifecycleReason(code, terms) {
56
+ requireTerms(terms, 'lifecycleReason');
57
+ const known = lifecycleCode(code), message = messages[known];
58
+ return { code: known, message: typeof message === 'function' ? message(terms) : message };
59
+ }
60
+ /** A kernel's error answer whose code has no sentence here. It says "OATS answered", so it is chosen only
61
+ * for a code read out of the kernel's own error envelope: by where the code came from, which only the caller
62
+ * knows, never by the code's shape. lifecycleReason is given codes of every origin and keeps E_CLI_FAILED
63
+ * ("OATS couldn't be run for this.") for one it does not know; that sentence is never shown for an answer
64
+ * the kernel gave. It names the client that has no description, by the client's own `name`. */
65
+ const undescribed = terms => `OATS answered with an error that ${terms.name} has no description for.`;
66
+ /** The reason for a code the KERNEL answered and no sentence describes: its own code and the fallback
67
+ * sentence, or null when the code has a sentence, or is not in the kernel's code shape (an older kernel's
68
+ * system code, `ENOENT`, which keeps E_CLI_FAILED's sentence). The caller vouches for the origin. */
69
+ export function undescribedAnswer(code, terms) {
70
+ requireTerms(terms, 'undescribedAnswer');
71
+ return kernelCode(code) && !Object.hasOwn(messages, code) ? { code, message: undescribed(terms) } : null;
72
+ }
73
+ /** Re-validate a relayed reason (server → main → renderer) that reads by the fallback sentence, or null:
74
+ * a kernel code without a sentence, the fixed fallback sentence, and a detail that is a display line (else
75
+ * none). The reply's sentence is the server's word that the kernel answered; nothing else of it is shown.
76
+ * `terms`: the reader's, which are the server's: the sentence compared is the one built from them. */
77
+ export function undescribedRefusal(reason, terms) {
78
+ const fallback = undescribed(requireTerms(terms, 'undescribedRefusal'));
79
+ return object(reason) && reason.message === fallback && undescribedAnswer(reason.code, terms)
80
+ ? { code: reason.code, message: fallback, detail: cleanLine(reason.detail) ? reason.detail : null } : null;
81
+ }
82
+ /** Codes only Desktop raises (its CLI adapter, its lifecycle boundary, main): the kernel never answers with
83
+ * one. A new entry of `messages` that the kernel does not raise is listed here too. */
84
+ const desktopCodes = new Set(['E_WORKSPACE_UNKNOWN', 'cli-unavailable', 'E_LIFECYCLE_UNAVAILABLE', 'unsupported-remote-operation',
85
+ 'E_PLAN_REQUIRED', 'E_PLAN_EXPIRED', 'E_PLAN_CHANGED', 'E_OPTION_UNAVAILABLE', 'E_PLAN_LIMIT',
86
+ 'E_CLI_TIMEOUT', 'E_CLI_OUTPUT_LIMIT', 'E_CLI_PROTOCOL', 'E_CLI_FAILED', 'E_OUTCOME_UNKNOWN']);
87
+ /** A code whose local failure may show the CLI's own message as a detail beside the fixed sentence: the
88
+ * code has its own sentence and the kernel raises it. Never one of Desktop's own, whatever came with it;
89
+ * a code without a sentence shows no CLI text either. */
90
+ export const lifecycleDetailCode = code => Object.hasOwn(messages, code) && !desktopCodes.has(code);
91
+ /** The kernel feature from which every E_LIFECYCLE_BUSY of a stop or a retire carries `error.details.holder`
92
+ * (docs/desktop-cli-api.md): whether waiting ends the refusal, as data. */
93
+ const CLAIM_STOP_FEATURE = 'lifecycle-claim-stop';
94
+ /** E_LIFECYCLE_BUSY by who holds the claim. `headline` is the status line. `lead` introduces the kernel's own
95
+ * sentence, shown under it as the main text: for these holders the kernel's message names the step that ends
96
+ * the refusal, and Desktop shows the whole line, never a part of it. `running` promises that waiting ends
97
+ * it, and is the only one that does; its kernel sentence stays in Details. `unstated`: the field is absent
98
+ * or holds a value outside the kernel's list, read as the weaker claim. */
99
+ const BUSY = {
100
+ running: { headline: 'Another OATS command is already running. Wait for it to finish, then review again.' },
101
+ unknown: { headline: "Nothing was done. OATS can't tell whether another command is still running.", lead: 'It says what to check:' },
102
+ none: { headline: 'Nothing was done, and there is no other command to wait for.', lead: 'OATS says what to do:' },
103
+ unstated: { headline: 'Nothing was done: OATS refused this as busy.', lead: 'It says:' },
104
+ };
105
+ const HOLDERS = ['running', 'unknown', 'none'];
106
+ /** How a kernel's E_LIFECYCLE_BUSY is read: one of BUSY's keys, or null when the rule does not apply and
107
+ * the code keeps its fixed sentence. For the kernel's own answer only (the caller says so; Desktop's own busy
108
+ * carries no details), under that code only (`details.holder` on any other code means nothing to a client),
109
+ * and only when `features` (the answering kernel's, answeringFeatures) names lifecycle-claim-stop: a kernel
110
+ * without it answers the code for a command that may be running. */
111
+ export function busyHolder(code, details, features) {
112
+ if (code !== 'E_LIFECYCLE_BUSY' || !names(features, CLAIM_STOP_FEATURE)) return null;
113
+ return object(details) && HOLDERS.includes(details.holder) ? details.holder : 'unstated';
114
+ }
115
+ export const busyHeadline = holder => BUSY[holder].headline;
116
+ /** The target of a stop plan that a home names, when it is not the instance acted on: `{instance, home}`,
117
+ * else null. The `details` of a stop's claim refusal are of the target whose claim refused, which in a
118
+ * recursive stop may be a child. Matched by home against the plan's own targets, so a name shown is always
119
+ * one the plan already showed. */
120
+ export function busyAbout(plan, home) {
121
+ if (!object(plan) || plan.action !== 'stop' || typeof home !== 'string' || home === plan.home) return null;
122
+ const target = plan.targets.find(t => t.home === home);
123
+ return target ? { instance: target.instance, home: target.home } : null;
124
+ }
125
+ /** Re-validate a relayed busy reason (server → main → renderer) that says who holds, or null: the reason then
126
+ * reads by its code's fixed sentence. `{ headline, about, lead, sentence, details }`, each a line or null,
127
+ * in the order they are shown: the headline; `about`, when the refusal is of another target of `plan` (the
128
+ * reader's own plan snapshot: a name that is not in it is not shown); then `lead` and the kernel's `sentence`
129
+ * as the main text. A sentence the display filter withheld, or one that is not there, is not introduced:
130
+ * no lead, and `details` holds what Details shows (the code and the filter's line), as for any other code.
131
+ * The headline is chosen here from `holder`; the reply's `message` is never shown. */
132
+ export function busyRefusal(reason, plan = null) {
133
+ if (!object(reason) || reason.code !== 'E_LIFECYCLE_BUSY' || !Object.hasOwn(reason, 'holder') || typeof reason.holder !== 'string' || !Object.hasOwn(BUSY, reason.holder)) return null;
134
+ const { headline, lead } = BUSY[reason.holder], detail = cleanLine(reason.detail) ? reason.detail : null;
135
+ const target = object(reason.about) ? busyAbout(plan, reason.about.home) : null;
136
+ const about = target && target.instance === reason.about.instance ? `This is about ${target.instance}, which is in this plan.` : null;
137
+ const main = !!lead && !!detail && detail !== DETAIL_WITHHELD;
138
+ return { headline, about, lead: main ? lead : null, sentence: main ? detail : null, details: !main && detail ? { code: reason.code, detail } : null };
139
+ }
140
+ export function lifecycleFailure(code, terms, extra = {}) {
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 };
144
+ }
145
+ export function lifecycleOptions(operation, v) {
146
+ if (!object(v)) return null;
147
+ if (operation === 'stop' && Object.keys(v).length === 1 && Object.hasOwn(v, 'recursive') && typeof v.recursive === 'boolean') return { recursive: v.recursive };
148
+ // Retire has one choice, the worktree. It never deletes a branch: any other key is refused.
149
+ if (operation === 'retire' && Object.keys(v).length === 1 && Object.hasOwn(v, 'discardWorktree')
150
+ && typeof v.discardWorktree === 'boolean') return { discardWorktree: v.discardWorktree };
151
+ return null;
152
+ }
153
+ /** Whether the choices made for `plan` apply to it. A stop's always do. Deleting the worktree applies only to
154
+ * an instance's own tree (ownWorktreeOf). */
155
+ export function lifecycleChoicesApplicable(plan, choices) {
156
+ if (plan.action === 'stop') return true;
157
+ return !choices.discardWorktree || ownWorktreeOf(plan).own;
158
+ }
159
+ /** The kernel feature from which a retire plan says as a fact whether `work/` is the instance's own work
160
+ * tree, the one the retire keeps or deletes: `facts.ownWorktree`, a boolean (docs/desktop-cli-api.md, the
161
+ * retire plan). A stop plan does not carry it. */
162
+ export const OWN_WORKTREE_FEATURE = 'retire-plan-own-worktree';
163
+ /** A retire plan's `facts.ownWorktree` as the answering kernel's `features` (answeringFeatures) have it read:
164
+ * `{ value }` when it is read, `{}` when the plan has none, `null` for a malformed plan.
165
+ * the kernel lists the feature the key is required and a boolean: anything else is no plan, as every
166
+ * other malformed fact (a plan authorizes a removal: no fallback to the record);
167
+ * it does not list it the key is not read, whatever it holds;
168
+ * its features are not known the key is read when it is there as a boolean, else the plan has none.
169
+ * "Not known" is anything but a list: null, nothing, and the renderer's second pass over a plan the server
170
+ * already read, which holds the key exactly when the server read it. */
171
+ function ownWorktreeFact(facts, features) {
172
+ const known = Array.isArray(features), listed = known && features.includes(OWN_WORKTREE_FEATURE);
173
+ if (known && !listed) return {};
174
+ if (typeof facts.ownWorktree === 'boolean') return { value: facts.ownWorktree };
175
+ return listed ? null : {};
176
+ }
177
+ /** Whether `work/` is the instance's own work tree, the one a retire keeps or deletes, from a retire plan
178
+ * that lifecyclePlan read: `{ own, from }`.
179
+ * from 'fact' the plan holds `facts.ownWorktree`, the kernel's answer of the one reading of `work/` its
180
+ * retire acts on. `own` is that boolean, whatever the record says.
181
+ * from 'record' the plan holds none (a kernel that does not list the feature), and the record's work mode
182
+ * answers. The record can disagree with what is at `work/` (a link or a directory of the
183
+ * home under a record that says the tree is the instance's), and such a plan cannot tell:
184
+ * a reader words it from the record alone.
185
+ * Every reader that asks whose tree it is asks this (lifecycleChoicesApplicable, the Remove dialog), and this
186
+ * is the one place a plan's work mode is compared with a word: packages/desktop/test/lifecycle-own-worktree.test.mjs
187
+ * holds that. Neither `defaults.retainWorktree` (the default of an option) nor a note is read for it. */
188
+ export function ownWorktreeOf(plan) {
189
+ const facts = plan.facts;
190
+ return typeof facts.ownWorktree === 'boolean' ? { own: facts.ownWorktree, from: 'fact' }
191
+ : { own: facts.workMode === 'worktree', from: 'record' };
192
+ }
193
+ export function lifecycleSession(v) {
194
+ if (!object(v) || !text(v.state, 128) || !v.state || typeof v.established !== 'boolean' || ![null, true, false].includes(v.present)
195
+ || !nullable(v.backend) || (!v.established && (v.state !== 'unestablished' || v.present !== null))
196
+ || (v.established && (v.present === null || v.state === 'unestablished'))) return null;
197
+ return { state: v.state, established: v.established, present: v.present, backend: v.backend,
198
+ ...(!v.established ? { reason: text(v.reason, 256) ? v.reason : 'unavailable' } : {}) };
199
+ }
200
+ export function lifecycleWork(v) {
201
+ if (!object(v) || typeof v.observed !== 'boolean') return null;
202
+ if (!v.observed) return text(v.reason, 256) ? { observed: false, reason: v.reason } : null;
203
+ if (!gitRevision(v.revision) || !nullable(v.branch) || typeof v.detached !== 'boolean' || typeof v.drift !== 'boolean'
204
+ || (v.detached && v.branch !== null) || !count(v.changed) || !count(v.untracked)) return null;
205
+ for (const c of [v.upstream, v.base]) if (!object(c) || !nullable(c.ref) || !numberOrNull(c.ahead) || !numberOrNull(c.behind)
206
+ || (c.ref === null && (c.ahead !== null || c.behind !== null))) return null;
207
+ if (v.remote !== null && (!object(v.remote) || !nullable(v.remote.host) || !nullable(v.remote.path))) return null;
208
+ return { observed: true, revision: v.revision, branch: v.branch, detached: v.detached, drift: v.drift,
209
+ changed: v.changed, untracked: v.untracked,
210
+ upstream: { ref: v.upstream.ref, ahead: v.upstream.ahead, behind: v.upstream.behind },
211
+ base: { ref: v.base.ref, ahead: v.base.ahead, behind: v.base.behind },
212
+ remote: v.remote === null ? null : { host: v.remote.host, path: v.remote.path } };
213
+ }
214
+ function identity(v) {
215
+ return object(v) && text(v.instance, 255) && !!v.instance && text(v.agent, 255) && !!v.agent && absolute(v.home)
216
+ && v.home.split('/').at(-1) === v.instance ? { instance: v.instance, agent: v.agent, home: v.home } : null;
217
+ }
218
+ function rows(value, project) {
219
+ if (!Array.isArray(value) || value.length > MAX_LIFECYCLE_TARGETS) return null;
220
+ const result = value.map(project);
221
+ return result.some(v => !v) || new Set(result.map(v => v.home)).size !== result.length ? null : result;
222
+ }
223
+ const excluded = v => { const i = identity(v); return i && text(v.reason) ? { ...i, reason: v.reason } : null; };
224
+ /** Read a plan: a kernel's own answer, or the server's projection of one. `features`: the answering kernel's
225
+ * (answeringFeatures), which decide how a retire plan's `facts.ownWorktree` is read (ownWorktreeFact). The
226
+ * server gives them, for a relayed plan its host's; the renderer, which reads the server's projection, gives
227
+ * none. The plan read holds the key only when it was read. */
228
+ export function lifecyclePlan(v, target, operation, options, { features = null } = {}) {
229
+ if (!object(v) || v.lifecycleApi !== 1 || v.action !== operation || v.instance !== target.instance || v.home !== target.home
230
+ || !planRevision(v.planRevision) || !at(v.at) || !strings(v.notes)) return null;
231
+ const common = { lifecycleApi: 1, action: operation, instance: v.instance, home: v.home, planRevision: v.planRevision, at: v.at, notes: [...v.notes] };
232
+ if (operation === 'stop') {
233
+ if (v.recursive !== options.recursive) return null;
234
+ const targets = rows(v.targets, t => {
235
+ const i = identity(t), session = lifecycleSession(t?.session), work = lifecycleWork(t?.work);
236
+ return i && session && work && count(t.depth) && nullable(t.workMode) && typeof t.launched === 'boolean'
237
+ && typeof t.retiring === 'boolean' && typeof t.stopPending === 'boolean' && [true, false, 'unknown'].includes(t.midTask)
238
+ ? { ...i, depth: t.depth, workMode: t.workMode, launched: t.launched, session, work, retiring: t.retiring, stopPending: t.stopPending, midTask: t.midTask } : null;
239
+ });
240
+ const skipped = rows(v.skipped, excluded), ambiguous = rows(v.ambiguous, excluded);
241
+ if (!targets?.length || !skipped || !ambiguous || targets.length + skipped.length + ambiguous.length > MAX_LIFECYCLE_TARGETS
242
+ || targets.at(-1).home !== target.home || targets.at(-1).agent !== target.agent || targets.at(-1).depth !== 0
243
+ || targets.slice(0, -1).some(t => !t.depth) || (!options.recursive && targets.length !== 1)
244
+ || (options.recursive && skipped.length) || [...skipped, ...ambiguous].some(t => targets.some(x => x.home === t.home))) return null;
245
+ return { ...common, recursive: v.recursive, targets, skipped, ambiguous };
246
+ }
247
+ const f = v.facts, d = v.defaults;
248
+ if (!object(f) || !object(d) || !nullable(f.workMode) || !(f.repo === null || absolute(f.repo)) || !nullable(f.recordedBranch) || f.pullRequest !== 'unknown'
249
+ || typeof d.retainWorktree !== 'boolean' || !(d.deleteBranch === undefined || d.deleteBranch === false) || d.stopChildren !== true || d.retainChildren !== true) return null;
250
+ const session = lifecycleSession(f.session), work = lifecycleWork(f.work);
251
+ const children = rows(f.children, t => { const i = identity(t), s = lifecycleSession(t?.session); return i && s ? { ...i, session: s } : null; });
252
+ const ambiguous = rows(f.ambiguous, excluded);
253
+ const own = ownWorktreeFact(f, features);
254
+ if (!session || !work || !own || !children || !ambiguous || children.length + ambiguous.length + 1 > MAX_LIFECYCLE_TARGETS
255
+ || [...children, ...ambiguous].some(t => t.home === target.home) || ambiguous.some(t => children.some(c => c.home === t.home))) return null;
256
+ return { ...common, facts: { session, work, workMode: f.workMode, ...(Object.hasOwn(own, 'value') ? { ownWorktree: own.value } : {}), repo: f.repo, recordedBranch: f.recordedBranch,
257
+ children, ambiguous, pullRequest: 'unknown' }, defaults: { retainWorktree: d.retainWorktree, stopChildren: true, retainChildren: true } };
258
+ }
259
+ /** The kernel feature from which `stillRunning: []` in a failed row says the harness exited
260
+ * (docs/desktop-cli-api.md, #still-running). A kernel without it answers `[]` there for a session that was
261
+ * not seen to stop. */
262
+ const KERNEL_CODES_FEATURE = 'lifecycle-kernel-codes';
263
+ const PROBE_FEATURES_FEATURE = 'server-probe-features';
264
+ const names = (features, feature) => Array.isArray(features) && features.includes(feature);
265
+ /** The features of the kernel that answers a command, or null when they are not known. A local command
266
+ * (`routed: false`): the selected CLI's own list. A routed one (`routed: true`): the host's list, which is
267
+ * known only when this computer's CLI relays it (feature server-probe-features), the workspace's roster
268
+ * `group` was read (`probe.ok === true`) and `probe.features` is an array. Anything else is unknown, a
269
+ * missing `routed` too: never decided from a refusal, and never by probing. Pure: it keeps nothing. */
270
+ export function answeringFeatures({ cli, routed, group } = {}) {
271
+ if (cli?.ok !== true || !Array.isArray(cli.features)) return null;
272
+ if (routed === false) return [...cli.features];
273
+ const probe = group?.probe;
274
+ return routed === true && cli.features.includes(PROBE_FEATURES_FEATURE) && probe?.ok === true && Array.isArray(probe.features) ? [...probe.features] : null;
275
+ }
276
+ /** The rows of a stop's `results` or of a retire's `childrenStopped`. `decoded: false` reads a kernel's answer:
277
+ * a failed row's `stillRunning: []` is kept only when `features` (the answering kernel's, answeringFeatures)
278
+ * names lifecycle-kernel-codes, and is `null` otherwise, which is what that kernel's `[]` established.
279
+ * `decoded: true` validates rows a server already decoded, and keeps them as they are. A row's `message` is
280
+ * the kernel's text and is dropped, except under E_LIFECYCLE_BUSY, where it is kept as `detail`, through the
281
+ * display filter. */
282
+ function stoppedRows(value, expected, { withState = false, decoded = false, features = null } = {}) {
283
+ if (!Array.isArray(value) || value.length !== expected.length || value.length > MAX_LIFECYCLE_TARGETS) return null;
284
+ const exited = decoded || names(features, KERNEL_CODES_FEATURE);
285
+ const result = value.map((v, index) => {
286
+ if (!object(v) || v.home !== expected[index].home || v.instance !== expected[index].instance || typeof v.ok !== 'boolean') return null;
287
+ if (v.ok) return typeof v.stopped === 'boolean' && typeof v.alreadyIdle === 'boolean' && (!withState || text(v.state, 128))
288
+ ? { instance: v.instance, home: v.home, ok: true, stopped: v.stopped, alreadyIdle: v.alreadyIdle, ...(withState ? { state: v.state } : {}) } : null;
289
+ if (v.stillRunning !== null && (!Array.isArray(v.stillRunning) || v.stillRunning.length > 128 || v.stillRunning.some(p => !Number.isSafeInteger(p) || p <= 0))) return null;
290
+ const code = lifecycleCode(v.code);
291
+ // The row's own sentence is kept for one code only: a child whose home could not be locked, where the
292
+ // sentence is the refusal of that child's stop and names what ends it. One display line, or nothing.
293
+ const detail = code !== 'E_LIFECYCLE_BUSY' ? null : decoded ? cleanLine(v.detail) ? v.detail : null : displayLine(v.message);
294
+ return { instance: v.instance, home: v.home, ok: false, code,
295
+ stillRunning: v.stillRunning === null || !v.stillRunning.length && !exited ? null : [...v.stillRunning], ...(detail ? { detail } : {}) };
296
+ });
297
+ return result.some(v => !v) ? null : result;
298
+ }
299
+ /** Decode the rows of a kernel's answer. `features`: the answering kernel's (answeringFeatures). Not given,
300
+ * null, or a list without lifecycle-kernel-codes all read a failed row's `[]` as `null`: a caller that
301
+ * forgets the argument makes the weaker claim. From here on `[]` in a failed row has one meaning: the
302
+ * harness exited, and what failed came after. */
303
+ export function stoppedTargets(value, expected, withState = false, { features = null } = {}) {
304
+ return stoppedRows(value, expected, { withState, features });
305
+ }
306
+ /** Validate rows a server already decoded (the reply's `childrenStopped`). Never for a kernel's answer. */
307
+ export function decodedStoppedTargets(value, expected) { return stoppedRows(value, expected, { decoded: true }); }
308
+ /** What a decoded row is, as data. The only place that reads a row for wording: every reader of a stop's
309
+ * result (a line, the sentence above the rows) decides from this.
310
+ * idle ok, the session was already stopped
311
+ * stopped ok
312
+ * retiring failed with E_INSTANCE_RETIRING: nothing was tried, a retire holds it
313
+ * locked failed with E_LIFECYCLE_BUSY: nothing was tried, its home's claim could not be taken
314
+ * running failed, and these signalled processes were seen alive after the wait
315
+ * unrecorded failed with `stillRunning: []`: the harness exited, and what failed came after
316
+ * unconfirmed failed with `stillRunning: null`: nothing is established
317
+ * The two codes decide before `stillRunning` does, and need no feature name: each means the same in every
318
+ * kernel that answers it, and the kernel answers both only before any effect. */
319
+ export function stoppedRowKind(row) {
320
+ if (row.ok) return row.alreadyIdle ? 'idle' : 'stopped';
321
+ if (row.code === 'E_INSTANCE_RETIRING') return 'retiring';
322
+ if (row.code === 'E_LIFECYCLE_BUSY') return 'locked';
323
+ return !Array.isArray(row.stillRunning) ? 'unconfirmed' : row.stillRunning.length ? 'running' : 'unrecorded';
324
+ }
325
+ /** A row's line, after its name. "Not stopped" for a row nothing was tried on; "Didn't stop" for one that
326
+ * was tried. The busy line says only what the code means: a row carries no holder, and the code covers
327
+ * causes where nobody runs. A `locked` row's own sentence (`detail`) is shown under the line, as a quote. */
328
+ export function stoppedRowText(row) {
329
+ const kind = stoppedRowKind(row);
330
+ return kind === 'idle' ? 'Was already stopped' : kind === 'stopped' ? 'Stopped'
331
+ : kind === 'retiring' ? 'Not stopped: it is being retired' : kind === 'locked' ? "Not stopped: OATS couldn't lock its home"
332
+ : kind === 'unrecorded' ? "Stopped, but OATS couldn't record it"
333
+ : kind === 'running' ? `Didn't stop (still running: ${row.stillRunning.join(', ')})` : "Didn't stop";
334
+ }
335
+ /** Some row failed, and every failed row is `unrecorded`: each session stopped, and OATS could not record all of it. */
336
+ const stoppedUnrecorded = rows => rows.some(r => !r.ok) && rows.every(r => r.ok || stoppedRowKind(r) === 'unrecorded');
337
+ /** How a stop's result that is not `ok` reads above its rows: `{ status, title }`. A reader words a stop's
338
+ * result from the rows, through this and childrenRefusedMessage, never from the reply's `reason.message`
339
+ * (a partial stop's reason stays E_SESSION_STOP_FAILED's sentence, whatever the rows say). */
340
+ export function stopResultWords(rows) {
341
+ if (!stoppedUnrecorded(rows)) return { status: 'Not every session stopped:', title: 'Not every session stopped' };
342
+ return { title: 'Stopped, but not recorded', status: rows.length === 1 ? `${rows[0].instance} stopped, but OATS couldn't record it.`
343
+ : "Every session stopped, but OATS couldn't record all of them:" };
344
+ }
345
+ const CHILDREN_UNRECORDED = "The child instances stopped, but OATS couldn't record it for all of them, so nothing was retired.";
346
+ /** The sentence for a retire refused with E_CHILDREN_RUNNING, chosen from its child rows. "Nothing was
347
+ * retired" rests on the code (an answer with no result, refused before the retire's own effects); "the
348
+ * child instances stopped" rests on the rows: every one is ok, or failed with `[]`. Like stopResultWords,
349
+ * a reader asks this, never the reply's `reason.message`. */
350
+ export const childrenRefusedMessage = rows => stoppedUnrecorded(rows) ? CHILDREN_UNRECORDED : messages.E_CHILDREN_RUNNING;
351
+ /** The one branch deletion a retire reports (feature `worktree-event`, 0.49.0): it finished the compensation of a
352
+ * spawn killed while its `worktree` hooks ran. `{branch, branchDeleted: true}`, or `{branch, branchDeleted: false,
353
+ * reason}`. Additive and read tolerantly: anything else is ignored (null), never a refused receipt. Its text is
354
+ * the kernel's, raw: shown only through displayLine. It is not retire's own `branchDeleted`, which stays refused. */
355
+ export function spawnCompensationOf(v) {
356
+ const label = (x, max) => typeof x === 'string' && !!x && x.length <= max;
357
+ if (!object(v) || !label(v.branch, 1024) || typeof v.branchDeleted !== 'boolean') return null;
358
+ if (v.branchDeleted) return { branch: v.branch, branchDeleted: true };
359
+ return label(v.reason, 4096) ? { branch: v.branch, branchDeleted: false, reason: v.reason } : null;
360
+ }
361
+ /** Decode a kernel's receipt. `server`: the request was routed there. The routed retire's result then may
362
+ * also carry `server` and `target` (its route); a local result carrying them is refused. `features`: the
363
+ * answering kernel's (answeringFeatures), for its rows (stoppedTargets).
364
+ * Desktop asks for no branch deletion, so a retire result that reports one, or a skipped one, is not the
365
+ * answer to its request and is refused whole, a deferred one too: nothing of it is projected. The kernel's one
366
+ * exception, an interrupted spawn's branch (`spawnCompensation`), is not such a report: it is projected. */
367
+ export function lifecycleReceipt(v, plan, key, { server = null, features = null } = {}) { return receipt(v, plan, key, { server, features }); }
368
+ function receipt(v, plan, key, { server = null, features = null, decoded = false } = {}) {
369
+ if (!object(v) || v.idempotencyKey !== key || v.planRevision !== plan.planRevision || typeof v.replayed !== 'boolean') return null;
370
+ if (!server ? Object.hasOwn(v, 'server') || Object.hasOwn(v, 'target')
371
+ : plan.action !== 'retire' && (Object.hasOwn(v, 'server') || Object.hasOwn(v, 'target'))
372
+ || Object.hasOwn(v, 'server') && v.server !== server || Object.hasOwn(v, 'target') && !object(v.target)) return null;
373
+ if (plan.action === 'stop') {
374
+ const results = stoppedRows(v.results, plan.targets, { withState: true, decoded, features });
375
+ if (v.lifecycleApi !== 1 || v.action !== 'stop' || v.instance !== plan.instance || v.home !== plan.home || !at(v.at)
376
+ || !results || v.ok !== results.every(r => r.ok) || !Array.isArray(v.retained)
377
+ || JSON.stringify(v.retained) !== JSON.stringify(['home', 'work', 'transcript', 'launch'])) return null;
378
+ return { action: 'stop', instance: v.instance, home: v.home, planRevision: v.planRevision, replayed: v.replayed, at: v.at,
379
+ ok: v.ok, results, retained: [...v.retained] };
380
+ }
381
+ if (!(v.branchDeleted === undefined || v.branchDeleted === false)
382
+ || object(v.retention) && (Object.hasOwn(v.retention, 'branchDeleted') || Object.hasOwn(v.retention, 'branchDeletionSkipped'))) return null;
383
+ if (v.retired === plan.instance && v.deferred === true) return { action: 'retire', instance: plan.instance, home: plan.home,
384
+ planRevision: v.planRevision, replayed: v.replayed, deferred: true };
385
+ if (v.retired !== plan.instance || typeof v.removedDir !== 'boolean' || typeof v.worktreeRemoved !== 'boolean'
386
+ || (v.rollbackIncomplete !== undefined && !strings(v.rollbackIncomplete)) || !(v.retainedHome === undefined || v.retainedHome === plan.home)) return null;
387
+ const childrenStopped = stoppedRows(v.childrenStopped, plan.facts.children, { decoded, features });
388
+ if (!childrenStopped || childrenStopped.some(c => !c.ok)) return null;
389
+ let retention = null;
390
+ if (v.retention !== null) {
391
+ const r = v.retention;
392
+ if (!object(r) || !['retained', 'removed', 'absent'].includes(r.worktree) || !nullable(r.branch) || !nullable(r.recordedBranch)
393
+ || (r.worktree === 'retained' && (!absolute(r.movedTo) || !nullable(r.detachedAt)))) return null;
394
+ retention = { worktree: r.worktree, branch: r.branch, recordedBranch: r.recordedBranch,
395
+ ...(r.worktree === 'retained' ? { movedTo: r.movedTo, detachedAt: r.detachedAt } : {}) };
396
+ }
397
+ const recovery = v.workRecovery?.path, compensation = spawnCompensationOf(v.spawnCompensation);
398
+ return { action: 'retire', instance: plan.instance, home: plan.home, planRevision: v.planRevision, replayed: v.replayed,
399
+ removedDir: v.removedDir, worktreeRemoved: v.worktreeRemoved, retention, childrenStopped,
400
+ incomplete: !!v.rollbackIncomplete?.length, retainedHome: v.retainedHome ?? null,
401
+ recoveryPath: absolute(recovery) ? recovery : null, ...(compensation ? { spawnCompensation: compensation } : {}) };
402
+ }
403
+ /** Validate the public projection without exposing the server's private key. Its rows were decoded by
404
+ * the server and are kept as they are: this takes no features and never reads a kernel's own row. */
405
+ export function publicLifecycleReceipt(v, plan) {
406
+ if (!object(v) || v.action !== plan.action || v.instance !== plan.instance || v.home !== plan.home) return null;
407
+ if (v.action === 'stop') return receipt({ ...v, lifecycleApi: 1, idempotencyKey: 'public' }, plan, 'public', { decoded: true });
408
+ if (v.deferred !== true && (typeof v.incomplete !== 'boolean' || !(v.retainedHome === null || v.retainedHome === plan.home)
409
+ || !(v.recoveryPath === null || absolute(v.recoveryPath)))) return null;
410
+ return receipt({ ...v, retired: v.instance, idempotencyKey: 'public',
411
+ retainedHome: v.retainedHome || undefined, rollbackIncomplete: v.incomplete ? ['reported incomplete cleanup'] : undefined,
412
+ workRecovery: v.recoveryPath ? { path: v.recoveryPath } : undefined }, plan, 'public', { decoded: true });
413
+ }
@@ -0,0 +1,10 @@
1
+ // The liveness collector as a program: rows on stdin, one liveness per row on stdout
2
+ // (liveness.mjs). The backend starts it out of its own process (packages/desktop/server/oats-web.mjs) so a slow
3
+ // terminal server cannot stall request handling. It runs as Node under the packaged executable,
4
+ // started with the environment the backend was started with, and it starts tmux itself: so its
5
+ // first import cleans its own environment (own-environment.mjs), and that import must stay first.
6
+ import "./own-environment.mjs";
7
+ import { readFileSync } from "node:fs";
8
+ import { observeLiveness } from "./liveness.mjs";
9
+
10
+ process.stdout.write(JSON.stringify(observeLiveness(JSON.parse(readFileSync(0, "utf8")))));
@@ -0,0 +1,48 @@
1
+ /** Terminal-target liveness for kernel-reported rows. This is unchanged,
2
+ * v2-agnostic terminal observation: it consults tmux for the exact recorded
3
+ * target, never deployment files. A library only: the program that runs it out
4
+ * of the serving process is liveness-main.mjs (see packages/desktop/server/oats-web.mjs), so a slow
5
+ * terminal server cannot stall request handling. */
6
+ import { createTmuxStatusReader, DEFAULT_TMUX_SESSION } from './tmux-status.mjs';
7
+ import { unsupportedSession, unsupportedSessionOrigin } from './instance-presentation.mjs';
8
+
9
+ export { DEFAULT_TMUX_SESSION };
10
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
11
+
12
+ /** rows: [{ instance, running?, tmux?, sessionTarget?, runtimeState?, runtimeError? }] in, one liveness
13
+ * per row out. A Herdr-recorded row is never probed: it is unsupported, with the kernel's reason.
14
+ *
15
+ * The probe refines a row only when the kernel answered `running` true or false. A row it answered
16
+ * `running: null` is not probed: its `running`, `runtimeState` and `runtimeError` stay the kernel's,
17
+ * and the answer carries no `tmux`, so the merged row keeps the kernel's own. The kernel answers
18
+ * unknown for a server it could not read, for a missing socket file while a process works in the
19
+ * home, and for a record that cannot be read. Only its `runtimeError` text tells them apart, which
20
+ * no client reads; for the last two a probe would say "stopped" and be wrong. The cost: a kernel
21
+ * read that failed once shows the row as unknown until the next roster read. A row without a
22
+ * `running` key (no kernel sends one) is probed. */
23
+ export function observeLiveness(rows, { tmuxReader = createTmuxStatusReader(), session = DEFAULT_TMUX_SESSION } = {}) {
24
+ if (!Array.isArray(rows) || rows.length > 10000) throw new Error('Invalid liveness request');
25
+ return rows.map(row => {
26
+ if (!record(row) || typeof row.instance !== 'string') return { running: null, runtimeState: 'unreachable', runtimeError: 'Invalid terminal target' };
27
+ const unsupported = unsupportedSession(row);
28
+ if (unsupported) return { running: null, runtimeState: 'unsupported', runtimeError: unsupported.slice(0, 300), tmux: null };
29
+ // After the unsupported check: an older kernel's Herdr row is `unreachable` with a sessionTarget, and reads unsupported.
30
+ if (row.running === null) return { running: null, runtimeState: row.runtimeState ?? 'unreachable', ...(row.runtimeError ? { runtimeError: String(row.runtimeError).slice(0, 300) } : {}) };
31
+ const tmux = record(row.tmux) ? row.tmux : undefined;
32
+ const { tmux: observed, running, runtimeState, runtimeError } = tmuxReader({ instance: row.instance, tmux }, session);
33
+ return { tmux: observed, running, runtimeState, ...(runtimeError ? { runtimeError: String(runtimeError).slice(0, 300) } : {}) };
34
+ });
35
+ }
36
+
37
+ /** Who makes the `runtimeError` of a row's answer, when the answer has one: "kernel", "terminal-probe",
38
+ * or null for the stand-in of an older kernel's Herdr row. By the order `observeLiveness` takes, which is
39
+ * a function of the row alone: an invalid row and a probed one are the terminal check's, a Herdr row's
40
+ * text is the kernel's or the stand-in, and a row the kernel answered `running: null` keeps the kernel's.
41
+ * The collector's answer crosses a process as JSON, so the speaker is not put on that wire: the reader of
42
+ * the answers asks here, of the row it sent (deployment-panel.mjs `livenessAnswers`). Not on the stable surface. */
43
+ export function livenessOrigin(row) {
44
+ if (!record(row) || typeof row.instance !== 'string') return 'terminal-probe';
45
+ if (unsupportedSession(row)) return unsupportedSessionOrigin(row);
46
+ if (row.running === null) return 'kernel';
47
+ return 'terminal-probe';
48
+ }
@@ -0,0 +1,123 @@
1
+ /* oats desktop — a workspace's own machines (#517): the gates, the Add a machine defaults and field
2
+ rules, and the step rows of `oats server connect --json` and `oats aweb connect --json` as the CLI
3
+ sends them (docs/desktop-cli-api.md; interface §2 and §4).
4
+
5
+ Step rows are data: `detail` and `remedy` are shown as the CLI words them, never rewritten. A row
6
+ the contract does not allow is dropped, never guessed.
7
+
8
+ Pure data; no node: imports so the renderer can share it with the server. */
9
+
10
+ /** The kernel's own rules (lib/servers.mjs): a registration id, and an OpenSSH host alias or name. */
11
+ export const MACHINE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
12
+ export const SSH_HOST = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
13
+ const FOLDER_MAX = 1024;
14
+
15
+ export const CONNECT_STEPS = Object.freeze(['ssh', 'oats', 'git', 'deployment', 'register', 'readiness']);
16
+ export const AWEB_STEPS = Object.freeze(['aw', 'invite', 'join', 'readiness']);
17
+ /** Each status, as its row says it. */
18
+ export const STEP_LABELS = Object.freeze({ ok: 'ok', done: 'done', 'needs-human': 'needs you', skipped: 'waiting', failed: 'failed' });
19
+
20
+ const text = value => typeof value === 'string' && value.length > 0;
21
+ const features = cli => (cli?.ok && Array.isArray(cli.features) ? cli.features : []);
22
+
23
+ /** A workspace's own machines and Add a machine: kernel features servers-per-workspace and server-connect. */
24
+ export function machinesGated(cli) {
25
+ const f = features(cli);
26
+ return f.includes('servers-per-workspace') && f.includes('server-connect');
27
+ }
28
+ /** The messaging step (`oats aweb connect`) also needs capability-route. */
29
+ export function awebConnectGated(cli) {
30
+ return machinesGated(cli) && features(cli).includes('capability-route');
31
+ }
32
+
33
+ const basename = dir => String(dir || '').replace(/\/+$/, '').split('/').pop() || '';
34
+ /** The default Name: `<host>-<this deployment dir basename>`, made a valid registration id. */
35
+ export function machineName(host, deploymentDir) {
36
+ if (!text(host)) return '';
37
+ return `${host}-${basename(deploymentDir)}`.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/-{2,}/g, '-')
38
+ .replace(/^-+/, '').slice(0, 64).replace(/-+$/, '');
39
+ }
40
+ /** The default Folder on that machine: `~/Agents/<this deployment dir basename>`. */
41
+ export function machineFolder(deploymentDir) {
42
+ return `~/Agents/${basename(deploymentDir)}`;
43
+ }
44
+
45
+ /** The first field that the kernel would refuse, as `{ field, text }`, or null. */
46
+ export function machineFieldProblem({ id, host, folder }) {
47
+ if (!text(host)) return { field: 'host', text: 'Type the machine\'s ssh host alias.' };
48
+ if (!SSH_HOST.test(host)) return { field: 'host', text: 'Use an ssh host alias or host name from your ssh config (no user@, no options).' };
49
+ if (!text(id)) return { field: 'id', text: 'Give the machine a name.' };
50
+ if (!MACHINE_ID.test(id)) return { field: 'id', text: 'A name is lowercase letters, digits and dashes, up to 64 characters.' };
51
+ if (!text(folder) || !(folder.startsWith('/') || folder.startsWith('~/')) || folder.length > FOLDER_MAX || /[\u0000-\u001f\u007f]/.test(folder)) {
52
+ return { field: 'folder', text: 'The folder is a path on that machine, starting with / or ~/.' };
53
+ }
54
+ return null;
55
+ }
56
+
57
+ const STATUSES = new Set(Object.keys(STEP_LABELS));
58
+ /** One step row, or null when the contract does not allow it. Optional text fields are kept only as text. */
59
+ function stepRow(row, names) {
60
+ if (!row || typeof row !== 'object' || !names.includes(row.step) || !STATUSES.has(row.status)) return null;
61
+ const out = { step: row.step, status: row.status };
62
+ for (const key of ['code', 'detail', 'remedy', 'hint']) if (text(row[key])) out[key] = row[key];
63
+ return out;
64
+ }
65
+ const stepRows = (value, names) => (Array.isArray(value) ? value.slice(0, 32) : []).map(row => stepRow(row, names)).filter(Boolean);
66
+
67
+ /** A connect envelope (`server connect` or `aweb connect`) as `{ ok, ready, id, steps, error }`.
68
+ * A failed run's steps are `error.details.steps` (the steps so far, the failed one last). */
69
+ export function connectOutcome(envelope, names = CONNECT_STEPS) {
70
+ if (envelope?.ok === true && envelope.result && typeof envelope.result === 'object') {
71
+ const r = envelope.result;
72
+ return { ok: true, ready: r.ready === true, id: text(r.id) ? r.id : text(r.server) ? r.server : null, steps: stepRows(r.steps, names), error: null };
73
+ }
74
+ const error = envelope?.error;
75
+ return { ok: false, ready: false, id: null, steps: stepRows(error?.details?.steps, names),
76
+ error: { code: text(error?.code) ? error.code : 'E_CLI_PROTOCOL', message: text(error?.message) ? error.message : 'oats did not answer as expected' } };
77
+ }
78
+
79
+ /** Whether connect reached `register` (it registered the machine, now or before). */
80
+ export function registerReached(steps) {
81
+ return (Array.isArray(steps) ? steps : []).some(s => s?.step === 'register' && (s.status === 'ok' || s.status === 'done'));
82
+ }
83
+
84
+ /** The commands a remedy names: its backticked spans, in order. */
85
+ export function stepCommands(remedy) {
86
+ if (!text(remedy)) return [];
87
+ return [...remedy.matchAll(/`([^`\n]+)`/g)].map(m => m[1].trim()).filter(Boolean);
88
+ }
89
+
90
+ /** Why a window offers no remote machine (`machineScope` in packages/desktop/server/oats-web.mjs), one line each. */
91
+ export const MACHINE_SCOPE_REASONS = Object.freeze({
92
+ 'no-key': 'This deployment reports no workspace key, so no other machine can be matched to it.',
93
+ 'no-local': 'This workspace has no deployment on this computer, so machines are added from one that does.',
94
+ });
95
+
96
+ /** How a consumer follows the server's backfill: the first re-read after BACKFILL_POLL_MS, each next one
97
+ * 1.5 times later, up to BACKFILL_POLL_MAX_MS apart. */
98
+ export const BACKFILL_POLL_MS = 2000;
99
+ export const BACKFILL_POLL_MAX_MS = 15_000;
100
+ /** Consecutive failed reads after which a consumer stops following (the server is gone or refusing). */
101
+ export const BACKFILL_READ_FAILURES = 5;
102
+ /** Read the list again while the server's answers say `backfilling` (packages/desktop/server/machines.mjs): `read()` answers
103
+ * the list, `use(answer)` takes each, `owns()` is the consumer's latest intent (false: stop, nothing used).
104
+ * It follows until an answer is settled: the backfill itself is bounded (each check has its own deadline),
105
+ * so the follow ends with it, at most one read per BACKFILL_POLL_MAX_MS. It stops early when the owner
106
+ * moves on, on stop(), or after BACKFILL_READ_FAILURES failed reads in a row. Returns stop(). */
107
+ export function followBackfill({ read, use, owns = () => true, delay = BACKFILL_POLL_MS, maxDelay = BACKFILL_POLL_MAX_MS, timers = globalThis }) {
108
+ let stopped = false, timer = null, wait = delay, failures = 0;
109
+ const next = () => {
110
+ if (stopped) return;
111
+ timer = timers.setTimeout(async () => {
112
+ timer = null;
113
+ let answer;
114
+ try { answer = await read(); failures = 0; }
115
+ catch { if (++failures < BACKFILL_READ_FAILURES) { wait = Math.min(maxDelay, wait * 1.5); next(); } return; }
116
+ if (stopped || !owns()) return;
117
+ use(answer);
118
+ if (answer?.backfilling === true) { wait = Math.min(maxDelay, wait * 1.5); next(); }
119
+ }, wait);
120
+ };
121
+ next();
122
+ return () => { stopped = true; if (timer !== null) timers.clearTimeout(timer); timer = null; };
123
+ }