@awebai/oats 0.51.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/bin/oats.mjs +109 -37
- package/docs/capabilities.md +9 -2
- package/docs/configuration.md +134 -88
- package/docs/desktop-cli-api.md +927 -92
- package/docs/desktop-instance-start.md +56 -0
- package/docs/desktop.md +10 -7
- package/docs/execution-targets.md +144 -58
- package/docs/first-team.md +3 -1
- package/docs/harness-trust.md +50 -2
- package/docs/implementation.md +66 -9
- package/docs/integrations.md +9 -8
- package/docs/knowledge-reference/acceptance.md +1 -0
- package/docs/knowledge-reference/harvester.md +5 -3
- package/docs/knowledge-reference/model.md +5 -3
- package/docs/knowledge-theory.md +1 -1
- package/docs/knowledge.md +25 -2
- package/docs/launch-prompt-completion.md +50 -48
- package/docs/oats-local.schema.json +4 -3
- package/docs/official-catalog.md +4 -4
- package/docs/packages.md +14 -14
- package/docs/release-lane.md +15 -5
- package/docs/release-notes/v0.44.0.md +1 -1
- package/docs/release-notes/v0.52.0.md +933 -0
- package/docs/schedules.md +91 -4
- package/docs/souls-and-instances.md +95 -25
- package/docs/tui.md +152 -0
- package/docs/workspaces.md +2 -2
- package/lib/claim.mjs +186 -46
- package/lib/core.mjs +730 -185
- package/lib/errors.mjs +170 -0
- package/lib/harness-trust-write.mjs +68 -27
- package/lib/harness-trust.mjs +34 -16
- package/lib/instance-inspect.mjs +40 -11
- package/lib/instance-lifecycle.mjs +169 -47
- package/lib/launch-preference.mjs +16 -0
- package/lib/launch-prompt-completion.mjs +7 -43
- package/lib/launch-prompt-evidence.mjs +14 -7
- package/lib/launch-prompt-fixtures/README.md +86 -152
- package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
- package/lib/launch-prompt-fixtures.mjs +122 -109
- package/lib/launch-prompt-transport.mjs +2 -56
- package/lib/launch-prompts.mjs +102 -100
- package/lib/schedule-host.mjs +154 -22
- package/lib/schedule.mjs +73 -24
- package/lib/system-tools.mjs +39 -0
- package/lib/tmux-server-scope.mjs +62 -0
- package/lib/triggers.mjs +4 -4
- package/lib/workspace.mjs +5 -11
- package/lib/worktree-hooks.mjs +98 -20
- package/lib/worktree.mjs +83 -24
- package/package-catalog.json +3 -3
- package/package.json +7 -2
- package/packages/client/capability-show-contract.mjs +230 -0
- package/packages/client/capability-warnings-contract.mjs +57 -0
- package/packages/client/cli-adapter.mjs +548 -0
- package/packages/client/cli-environment.mjs +53 -0
- package/packages/client/cli-locator.mjs +253 -0
- package/packages/client/cli-probe-contract.mjs +47 -0
- package/packages/client/client-terms.mjs +60 -0
- package/packages/client/deployment-contract.mjs +68 -0
- package/packages/client/deployment-data.mjs +483 -0
- package/packages/client/deployment-facts.mjs +34 -0
- package/packages/client/deployment-label.mjs +76 -0
- package/packages/client/deployment-observer.mjs +89 -0
- package/packages/client/deployment-panel.mjs +142 -0
- package/packages/client/deployment-read-cli.mjs +53 -0
- package/packages/client/display-text.mjs +44 -0
- package/packages/client/harness-names.mjs +30 -0
- package/packages/client/inspect-contract.mjs +62 -0
- package/packages/client/instance-acts.mjs +54 -0
- package/packages/client/instance-admission.mjs +45 -0
- package/packages/client/instance-events-contract.mjs +74 -0
- package/packages/client/instance-git-contract.mjs +80 -0
- package/packages/client/instance-presentation.mjs +22 -0
- package/packages/client/instance-tree.mjs +453 -0
- package/packages/client/kernel-environment.mjs +11 -0
- package/packages/client/launch-contract.mjs +51 -0
- package/packages/client/launch-prompt-outcome.mjs +165 -0
- package/packages/client/lifecycle-cli.mjs +61 -0
- package/packages/client/lifecycle-contract.mjs +372 -0
- package/packages/client/liveness-main.mjs +10 -0
- package/packages/client/liveness.mjs +35 -0
- package/packages/client/machine-contract.mjs +123 -0
- package/packages/client/own-environment.mjs +22 -0
- package/packages/client/panel-views.mjs +286 -0
- package/packages/client/readiness-contract.mjs +172 -0
- package/packages/client/refresh-loop.mjs +52 -0
- package/packages/client/remote-address.mjs +126 -0
- package/packages/client/remote-roster.mjs +67 -0
- package/packages/client/roster-sections.mjs +80 -0
- package/packages/client/spawn-apply-cli.mjs +104 -0
- package/packages/client/spawn-apply-contract.mjs +183 -0
- package/packages/client/spawn-decision.mjs +46 -0
- package/packages/client/spawn-messages.mjs +119 -0
- package/packages/client/spawn-preview-cli.mjs +32 -0
- package/packages/client/spawn-preview-contract.mjs +314 -0
- package/packages/client/team-members.mjs +41 -0
- package/packages/client/team-rows.mjs +45 -0
- package/packages/client/terminal-contract.mjs +57 -0
- package/packages/client/tmux-status.mjs +66 -0
- package/packages/client/waiting-on-you.mjs +88 -0
- package/packages/client/workspace-admission.mjs +45 -0
- package/packages/client/workspace-cli.mjs +142 -0
- package/packages/client/workspace-views.mjs +147 -0
- package/packages/tui/README.md +46 -0
- package/packages/tui/bin/tui.mjs +7 -0
- package/packages/tui/lib/actions.mjs +29 -0
- package/packages/tui/lib/client.mjs +4 -0
- package/packages/tui/lib/main.mjs +105 -0
- package/packages/tui/lib/term/keys.mjs +323 -0
- package/packages/tui/lib/term/screen.mjs +122 -0
- package/packages/tui/lib/term/style.mjs +43 -0
- package/packages/tui/lib/term/text.mjs +49 -0
- package/packages/tui/lib/term/tty.mjs +168 -0
- package/packages/tui/lib/term/width.mjs +124 -0
- package/packages/tui/lib/views/frame.mjs +62 -0
- package/packages/tui/lib/views/help.mjs +28 -0
- package/packages/tui/package.json +8 -0
- package/skills/oats-getting-started/SKILL.md +29 -22
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
- package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
- package/lib/launch-prompt-policy.mjs +0 -87
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/** Diagnostic projection only: neither a retained target nor an audit receipt
|
|
2
|
+
* grants terminal authority. Bad additive data must never erase a retained home. */
|
|
3
|
+
import { record, absolute } from './spawn-preview-contract.mjs';
|
|
4
|
+
import { eventsUnsafe } from './instance-events-contract.mjs';
|
|
5
|
+
import { displayLine } from './display-text.mjs';
|
|
6
|
+
const safe = (v, max = 1024) => typeof v === 'string' && v.length <= max && !/[\x00-\x1f\x7f]/.test(v) && !eventsUnsafe.test(v);
|
|
7
|
+
/** The kernel's reasons, matched whole and shown as it wrote them: no prefix or suffix is matched, so the
|
|
8
|
+
* blocked reasons the kernel suffixes when its private evidence was not kept are entries of their own.
|
|
9
|
+
*
|
|
10
|
+
* Six no longer occur from OATS 0.52.0, which pins no pane geometry and reads no consent list: `blocked:
|
|
11
|
+
* launch geometry not pinned`, `blocked: prompt consent absent`, `launch prompt audit failed before geometry
|
|
12
|
+
* pin`, `launch prompt audit failed after geometry pin`, `launch prompt geometry pin failed` and `launch
|
|
13
|
+
* prompt geometry restoration incomplete`. They stay: kernels 0.44 to 0.51 are accepted, a routed host can
|
|
14
|
+
* run one, and a home keeps the outcome an older kernel recorded. */
|
|
15
|
+
const reasons = new Set([
|
|
16
|
+
'blocked: unexpected prompt', 'blocked: observation timeout', 'blocked: launch observation failed',
|
|
17
|
+
'blocked: invalid target', 'blocked: respawn ownership not proven', 'blocked: respawn geometry changed before fresh screen',
|
|
18
|
+
'blocked: launch geometry not pinned', 'blocked: repeated or unsupported prompt', 'blocked: prompt consent absent',
|
|
19
|
+
'blocked: prompt changed before input', 'blocked: launch authority already used',
|
|
20
|
+
'launch prompt audit failed', 'launch prompt audit failed after possible input',
|
|
21
|
+
'launch prompt audit failed before geometry pin', 'launch prompt audit failed after geometry pin',
|
|
22
|
+
'launch prompt geometry pin failed', 'launch prompt geometry restoration incomplete',
|
|
23
|
+
'launch prompt input failed', 'launch prompt input uncertain',
|
|
24
|
+
'launch prompt dispatch or recording incomplete', 'launch prompt metadata recording incomplete',
|
|
25
|
+
'launch prompt pending receipt incomplete', 'launch home identity changed; metadata retained at original home',
|
|
26
|
+
// The kernel's own evidence of the screen was not kept: alone when the launch had otherwise ended well,
|
|
27
|
+
// and as the suffix of each blocked reason whose screen the kernel keeps.
|
|
28
|
+
'private launch evidence retention failed',
|
|
29
|
+
'blocked: unexpected prompt; private launch evidence retention failed',
|
|
30
|
+
'blocked: repeated or unsupported prompt; private launch evidence retention failed',
|
|
31
|
+
'blocked: observation timeout; private launch evidence retention failed',
|
|
32
|
+
]);
|
|
33
|
+
export const LAUNCH_INSPECTION = 'Launch requires inspection';
|
|
34
|
+
export const LAUNCH_DIAGNOSTIC_BYTES = 32768;
|
|
35
|
+
/** The kernel's bound on each side of a difference, in UTF-16 units. */
|
|
36
|
+
const DIFFERED_UNITS = 40;
|
|
37
|
+
/** What a blocked launch's screen differed in from the confirmation the kernel answers (0.52.0), as
|
|
38
|
+
* `{nearest, index, expected, found}`, or undefined. The kernel sends `{nearest, firstDifference: {index,
|
|
39
|
+
* expected, found}}`: `nearest` the id of the nearest tolerance entry, `index` the first differing position
|
|
40
|
+
* of the two normalized texts, `expected` and `found` at most 40 UTF-16 units of each from there (either
|
|
41
|
+
* can be empty: that text ended). `found` is what a terminal showed and `expected` the kernel's own text:
|
|
42
|
+
* each is kept as one display line, null when there is nothing to show. For display only: never compared,
|
|
43
|
+
* parsed or acted on.
|
|
44
|
+
*
|
|
45
|
+
* Tolerant, unlike the outcome around it: anything else, in any part, is undefined, so a malformed value
|
|
46
|
+
* drops this one fact and never the outcome, the retained home or the read. Idempotent: this module's own
|
|
47
|
+
* answer decodes to itself (the renderer reads again what the server projected). */
|
|
48
|
+
export function launchPromptDiffered(v) {
|
|
49
|
+
if (!record(v) || !safe(v.nearest, 256) || !v.nearest) return undefined;
|
|
50
|
+
const own = !Object.hasOwn(v, 'firstDifference'), d = own ? v : v.firstDifference;
|
|
51
|
+
if (!record(d) || !Number.isSafeInteger(d.index) || d.index < 0) return undefined;
|
|
52
|
+
const sides = [d.expected, d.found];
|
|
53
|
+
// Only this module's answer holds null for a side with nothing to show.
|
|
54
|
+
if (!sides.every(s => typeof s === 'string' ? s.length <= DIFFERED_UNITS : own && s === null)) return undefined;
|
|
55
|
+
return { nearest: v.nearest, index: d.index, expected: displayLine(d.expected), found: displayLine(d.found) };
|
|
56
|
+
}
|
|
57
|
+
/** What differed, as data for a view: the Desktop's lead-in, then the two texts, each under a lead-in of
|
|
58
|
+
* its own that names whose text it is. `found` is what a terminal showed, so it is shown as an attributed
|
|
59
|
+
* quote and never inside one of the Desktop's sentences; `expected` is the kernel's own text and gets the
|
|
60
|
+
* same line, so the two read as a pair. A side with nothing to show has a `note` instead of a `text`.
|
|
61
|
+
* `detail` (the nearest entry and the position) is for Details, never part of a sentence. Null when there is
|
|
62
|
+
* nothing decodable to say. Nothing is interpreted: no client decides from the two texts what the prompt
|
|
63
|
+
* was, whether a key is safe, or what to press. */
|
|
64
|
+
export const DIFFERED_LEAD_IN = 'Where the screen first differed from the confirmation OATS answers:';
|
|
65
|
+
export const DIFFERED_NO_TEXT = '(no visible text)';
|
|
66
|
+
/** The background notice cannot hold an attributed quote: it says where one is. True whenever it shows:
|
|
67
|
+
* the kernel writes `differed` to the `launch-prompt` event in the step that puts it on the result. */
|
|
68
|
+
export const DIFFERED_IN_ACTIVITY = 'Its Activity shows what OATS expected and what the terminal showed.';
|
|
69
|
+
export function differedLines(v) {
|
|
70
|
+
const d = launchPromptDiffered(v);
|
|
71
|
+
if (!d) return null;
|
|
72
|
+
const line = (leadIn, text) => ({ leadIn, text, note: text === null ? DIFFERED_NO_TEXT : null });
|
|
73
|
+
return { leadIn: DIFFERED_LEAD_IN, lines: [line('OATS expected:', d.expected), line('The terminal showed:', d.found)],
|
|
74
|
+
detail: `Nearest entry ${displayLine(d.nearest)}, first difference at ${d.index}` };
|
|
75
|
+
}
|
|
76
|
+
const unknown = () => ({ status: 'unknown', answers: [], reason: LAUNCH_INSPECTION, receipt: [] });
|
|
77
|
+
const within = v => new TextEncoder().encode(JSON.stringify(v)).length <= LAUNCH_DIAGNOSTIC_BYTES;
|
|
78
|
+
export function launchPromptOutcome(v) {
|
|
79
|
+
// A failed audit can follow a possible key even with answers: []. Never
|
|
80
|
+
// translate missing diagnostics into “no input” or a recoverable spawn retry.
|
|
81
|
+
try {
|
|
82
|
+
if (!record(v) || !within(v) || !['blocked', 'incomplete', 'unknown'].includes(v.status)) return unknown();
|
|
83
|
+
const answers = Array.isArray(v.answers) && v.answers.length <= 8 ? v.answers.flatMap(a =>
|
|
84
|
+
record(a) && a.class === 'awebDevelopmentChannel' && a.status === 'submitted' && safe(a.signatureId, 256)
|
|
85
|
+
? [{ class: a.class, signatureId: a.signatureId, status: a.status }] : []) : [];
|
|
86
|
+
const receipt = Array.isArray(v.receipt) && v.receipt.length <= 16 ? v.receipt.flatMap(r => {
|
|
87
|
+
if (!record(r) || typeof r.ok !== 'boolean' || !Array.isArray(r.results) || r.results.length > 2) return [];
|
|
88
|
+
const results = r.results.flatMap(w => record(w) && typeof w.ok === 'boolean' && safe(w.path) && absolute(w.path)
|
|
89
|
+
? [{ path: w.path, ok: w.ok }] : []);
|
|
90
|
+
// Keep write outcomes and actual paths; raw event/OS diagnostic text is
|
|
91
|
+
// deliberately excluded. The Activity reader owns event-row projection.
|
|
92
|
+
return [{ ok: r.ok, results }];
|
|
93
|
+
}) : [];
|
|
94
|
+
// Only a blocked result says what differed (0.52.0), and not every one (an invalid target has no screen).
|
|
95
|
+
const differed = v.status === 'blocked' ? launchPromptDiffered(v.differed) : undefined;
|
|
96
|
+
const out = { status: v.status, answers, reason: reasons.has(v.reason) ? v.reason : LAUNCH_INSPECTION, receipt };
|
|
97
|
+
// The answer is held to the bound it was read under, so reading it again (the renderer does) gives it
|
|
98
|
+
// back. It can be longer than what was read: a withheld side, the generic reason. What differed is the
|
|
99
|
+
// one fact that goes first; an answer still over the bound is unknown here, as the next read would say.
|
|
100
|
+
if (differed && within({ ...out, differed })) return { ...out, differed };
|
|
101
|
+
return within(out) ? out : unknown();
|
|
102
|
+
} catch { return unknown(); }
|
|
103
|
+
}
|
|
104
|
+
export function retainedSpawnDetails(d) {
|
|
105
|
+
if (!record(d) || typeof d.instance !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/.test(d.instance)
|
|
106
|
+
|| !absolute(d.home) || ![false, 'unknown'].includes(d.launched)) return null;
|
|
107
|
+
const out = { instance: d.instance, home: d.home, launched: d.launched };
|
|
108
|
+
if (Object.hasOwn(d, 'launchPrompts')) {
|
|
109
|
+
out.launchPrompts = launchPromptOutcome(d.launchPrompts);
|
|
110
|
+
if (typeof d.parentLineageCommitted === 'boolean') out.parentLineageCommitted = d.parentLineageCommitted;
|
|
111
|
+
if (record(d.target)) {
|
|
112
|
+
out.target = {};
|
|
113
|
+
for (const key of ['socket', 'session', 'window', 'windowId', 'paneId']) if (safe(d.target[key])) out.target[key] = d.target[key];
|
|
114
|
+
if (d.target.backend === 'tmux') out.target.backend = 'tmux';
|
|
115
|
+
if (Number.isSafeInteger(d.target.pid) && d.target.pid > 0 || safe(d.target.pid, 32) && /^\d+$/.test(d.target.pid)) out.target.pid = d.target.pid;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** Whether input reached the pane, as far as the outcome says: a submitted answer, or an incomplete result
|
|
121
|
+
* (a failed audit can follow a possible key). One rule for a spawn and for a start. */
|
|
122
|
+
const inputNote = p => p.answers.length ? ' A launch-prompt answer was submitted; this does not confirm readiness.'
|
|
123
|
+
: p.status === 'incomplete' ? ' Input may already have been sent.' : '';
|
|
124
|
+
export function retainedSpawnMessage(d) {
|
|
125
|
+
if (!d.launchPrompts) return `${d.instance} was created but didn’t finish starting. Open it from the instance list instead of spawning again.`;
|
|
126
|
+
const p = launchPromptOutcome(d.launchPrompts);
|
|
127
|
+
return `${d.instance} was retained: ${p.reason}.${inputNote(p)} Inspect its existing pane, then use oats session start --home for this home. Do not spawn again.`;
|
|
128
|
+
}
|
|
129
|
+
/** A Start or Restart of an existing home that stopped at a launch prompt, in the Desktop's words: the
|
|
130
|
+
* kernel answers E_SPAWN_INCOMPLETE with the same retained details as a spawn. `instance` is the name the
|
|
131
|
+
* dialog started; `d` the decoded details. It claims the weaker thing for both statuses: a blocked start and
|
|
132
|
+
* one whose completion was not seen are both "not confirmed", never "failed" and never "started". */
|
|
133
|
+
export function retainedStartMessage(instance, d) {
|
|
134
|
+
const p = launchPromptOutcome(d?.launchPrompts);
|
|
135
|
+
return `OATS could not confirm that ${instance} finished starting: ${p.reason}.${inputNote(p)} Its session was kept. Refresh status, then open its terminal to read what it shows. Do not start it again before that.`;
|
|
136
|
+
}
|
|
137
|
+
/** A launch that worked while Claude Code ignored the channel option (0.52.0). The kernel's successful
|
|
138
|
+
* answer then carries `launchPrompts: {status: "flag-ignored", reason, signatureId, startId, at}` and its own
|
|
139
|
+
* words as one string among `warnings`, never as a field. This reader takes those two fields of an answer
|
|
140
|
+
* and knows nothing of the act that was answered. Its one caller is the start dialog, for a start's and a
|
|
141
|
+
* restart's answer; a spawn's answer carries `launchPrompts` too (0.52.0) and is not read yet. It stands
|
|
142
|
+
* beside the kept-session reader above, which reads a refusal's details and knows no such status.
|
|
143
|
+
* Tolerant: an answer that does not decode, or any other status, is null, and the launch reads as any
|
|
144
|
+
* launch that worked.
|
|
145
|
+
*
|
|
146
|
+
* `reason` is the one value the notice has a clause for, else null. `warnings` is every warning of that
|
|
147
|
+
* answer in the order given, each as one display line: the withheld marker for one the filter withholds,
|
|
148
|
+
* and no line for an entry with nothing to show. None is picked, matched or dropped by its words: no
|
|
149
|
+
* client looks for the kernel's sentence among them. */
|
|
150
|
+
export function launchFlagIgnored(answer) {
|
|
151
|
+
if (!record(answer) || !record(answer.launchPrompts) || answer.launchPrompts.status !== 'flag-ignored') return null;
|
|
152
|
+
const warnings = Array.isArray(answer.warnings) ? answer.warnings.map(w => displayLine(w)).filter(line => line !== null) : [];
|
|
153
|
+
return { reason: answer.launchPrompts.reason === 'channels-unavailable' ? 'channels-unavailable' : null, warnings };
|
|
154
|
+
}
|
|
155
|
+
/** The notice for it, `{headline, detail?}`, or null. `instance` is the name the caller launched. The launch
|
|
156
|
+
* worked: the headline never says "failed" or "could not confirm". The detail is the warnings under the
|
|
157
|
+
* Desktop's lead-in, one per line; there is none without a warning. */
|
|
158
|
+
export function flagIgnoredNotice(instance, answer) {
|
|
159
|
+
const d = launchFlagIgnored(answer);
|
|
160
|
+
if (!d) return null;
|
|
161
|
+
const headline = d.reason === 'channels-unavailable'
|
|
162
|
+
? `${instance} started. Claude Code reported that channels are not available and ignored the channel option, so mail and chat will not wake this instance.`
|
|
163
|
+
: `${instance} started. Claude Code ignored the channel option, so mail and chat will not wake this instance.`;
|
|
164
|
+
return d.warnings.length ? { headline, detail: ['OATS says:', ...d.warnings].join('\n') } : { headline };
|
|
165
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Fixed-argv installed-CLI K3 adapter. No kernel import, fallback or raw errors. */
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { isAbsolute } from 'node:path';
|
|
4
|
+
import { parseEnvelope, parseRetireEnvelope } from './cli-adapter.mjs';
|
|
5
|
+
import { object, lifecycleOptions, planRevision } from './lifecycle-contract.mjs';
|
|
6
|
+
const absolute = v => typeof v === 'string' && isAbsolute(v) && !v.includes('\0');
|
|
7
|
+
const key = v => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(v);
|
|
8
|
+
const failure = code => ({ schemaVersion: 1, ok: false, error: { code } });
|
|
9
|
+
const serverId = v => typeof v === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/.test(v);
|
|
10
|
+
/** Remote reads and plans: ssh's ConnectTimeout (15 s) plus the command. */
|
|
11
|
+
export const REMOTE_READ_TIMEOUT = 45_000;
|
|
12
|
+
/** A routed command (`server`) is addressed by `--server S --home H` and never carries `--dir`:
|
|
13
|
+
* the kernel sends the registered workspace. `context` is then only this machine's cwd. */
|
|
14
|
+
export function lifecycleArgv(options) {
|
|
15
|
+
if (!object(options) || Object.keys(options).some(k => !['operation', 'phase', 'instance', 'home', 'context', 'server', 'choices', 'revision', 'key'].includes(k))) return null;
|
|
16
|
+
const o = options, choices = lifecycleOptions(o.operation, o.choices);
|
|
17
|
+
if (!choices || !['plan', 'apply'].includes(o.phase) || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(o.instance || '')
|
|
18
|
+
|| !absolute(o.home) || !absolute(o.context) || (Object.hasOwn(o, 'server') && !serverId(o.server))) return null;
|
|
19
|
+
if (o.phase === 'plan' ? Object.hasOwn(o, 'revision') || Object.hasOwn(o, 'key') : !planRevision(o.revision) || !key(o.key)) return null;
|
|
20
|
+
const args = o.operation === 'stop' ? ['instance', 'stop', o.instance] : ['retire', o.instance];
|
|
21
|
+
if (o.phase === 'plan') args.push('--plan');
|
|
22
|
+
else {
|
|
23
|
+
if (o.operation === 'stop') args.push('--apply');
|
|
24
|
+
args.push('--plan-revision', o.revision, '--idempotency-key', o.key);
|
|
25
|
+
if (o.operation === 'retire' && choices.discardWorktree) args.push('--discard-worktree');
|
|
26
|
+
}
|
|
27
|
+
args.push('--home', o.home, ...(o.server ? ['--server', o.server] : ['--dir', o.context]));
|
|
28
|
+
if (o.operation === 'stop' && !choices.recursive) args.push('--no-recursive');
|
|
29
|
+
args.push('--json'); return args;
|
|
30
|
+
}
|
|
31
|
+
/** `exec` is a client's own `execFile` (the rule is at cli-adapter.mjs `runJson`). */
|
|
32
|
+
export function cliLifecycle(bin, options, { exec = execFile, timeout } = {}) {
|
|
33
|
+
const argv = lifecycleArgv(options);
|
|
34
|
+
if (!absolute(bin) || !argv) return Promise.resolve(failure('E_BAD_ARGS'));
|
|
35
|
+
const apply = options.phase === 'apply', limit = apply ? 600_000 : options.server ? REMOTE_READ_TIMEOUT : 30_000;
|
|
36
|
+
return new Promise(resolve => {
|
|
37
|
+
try {
|
|
38
|
+
exec(bin, argv, { cwd: options.context, encoding: 'utf8', shell: false,
|
|
39
|
+
timeout: Number.isFinite(timeout) && timeout > 0 ? Math.min(timeout, limit) : limit,
|
|
40
|
+
maxBuffer: (apply ? 4 : 1) * 1024 * 1024 }, (error, stdout) => {
|
|
41
|
+
if (error?.killed) return resolve(failure('E_CLI_TIMEOUT'));
|
|
42
|
+
if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return resolve(failure('E_CLI_OUTPUT_LIMIT'));
|
|
43
|
+
const printed = parseEnvelope(stdout), value = apply && options.operation === 'retire' ? parseRetireEnvelope(stdout) : printed;
|
|
44
|
+
if (!value) return resolve(failure('E_CLI_PROTOCOL'));
|
|
45
|
+
if (error && value.ok !== false) return resolve(failure('E_CLI_FAILED'));
|
|
46
|
+
// Only internal consumers see result/details. They validate/project all
|
|
47
|
+
// data against their admitted target. An error envelope's message is kept, for a
|
|
48
|
+
// local command and a routed one: the boundary shows it only through the display
|
|
49
|
+
// filter, as the refusal's detail. Stderr and the process error never leave here.
|
|
50
|
+
// `origin: 'kernel'`: the error is the one the installed CLI printed in its envelope, so the
|
|
51
|
+
// kernel answered. The adapter's own failures (`failure`) and the error it writes for a raw
|
|
52
|
+
// retire receipt that reports incomplete cleanup (parseRetireEnvelope) carry no origin, and
|
|
53
|
+
// unmarked reads as not the kernel's: a reader decides by where an answer came from, never
|
|
54
|
+
// by its shape.
|
|
55
|
+
if (value.ok) resolve({ schemaVersion: 1, ok: true, result: value.result });
|
|
56
|
+
else resolve({ schemaVersion: 1, ok: false, ...(printed?.ok === false ? { origin: 'kernel' } : {}), ...(value.result ? { result: value.result } : {}),
|
|
57
|
+
error: { code: value.error?.code, message: value.error?.message, details: value.error?.details } });
|
|
58
|
+
});
|
|
59
|
+
} catch { resolve(failure('E_CLI_FAILED')); }
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,372 @@
|
|
|
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
|
+
export function lifecycleChoicesApplicable(plan, choices) {
|
|
154
|
+
if (plan.action === 'stop') return true;
|
|
155
|
+
return !choices.discardWorktree || plan.facts.workMode === 'worktree';
|
|
156
|
+
}
|
|
157
|
+
export function lifecycleSession(v) {
|
|
158
|
+
if (!object(v) || !text(v.state, 128) || !v.state || typeof v.established !== 'boolean' || ![null, true, false].includes(v.present)
|
|
159
|
+
|| !nullable(v.backend) || (!v.established && (v.state !== 'unestablished' || v.present !== null))
|
|
160
|
+
|| (v.established && (v.present === null || v.state === 'unestablished'))) return null;
|
|
161
|
+
return { state: v.state, established: v.established, present: v.present, backend: v.backend,
|
|
162
|
+
...(!v.established ? { reason: text(v.reason, 256) ? v.reason : 'unavailable' } : {}) };
|
|
163
|
+
}
|
|
164
|
+
export function lifecycleWork(v) {
|
|
165
|
+
if (!object(v) || typeof v.observed !== 'boolean') return null;
|
|
166
|
+
if (!v.observed) return text(v.reason, 256) ? { observed: false, reason: v.reason } : null;
|
|
167
|
+
if (!gitRevision(v.revision) || !nullable(v.branch) || typeof v.detached !== 'boolean' || typeof v.drift !== 'boolean'
|
|
168
|
+
|| (v.detached && v.branch !== null) || !count(v.changed) || !count(v.untracked)) return null;
|
|
169
|
+
for (const c of [v.upstream, v.base]) if (!object(c) || !nullable(c.ref) || !numberOrNull(c.ahead) || !numberOrNull(c.behind)
|
|
170
|
+
|| (c.ref === null && (c.ahead !== null || c.behind !== null))) return null;
|
|
171
|
+
if (v.remote !== null && (!object(v.remote) || !nullable(v.remote.host) || !nullable(v.remote.path))) return null;
|
|
172
|
+
return { observed: true, revision: v.revision, branch: v.branch, detached: v.detached, drift: v.drift,
|
|
173
|
+
changed: v.changed, untracked: v.untracked,
|
|
174
|
+
upstream: { ref: v.upstream.ref, ahead: v.upstream.ahead, behind: v.upstream.behind },
|
|
175
|
+
base: { ref: v.base.ref, ahead: v.base.ahead, behind: v.base.behind },
|
|
176
|
+
remote: v.remote === null ? null : { host: v.remote.host, path: v.remote.path } };
|
|
177
|
+
}
|
|
178
|
+
function identity(v) {
|
|
179
|
+
return object(v) && text(v.instance, 255) && !!v.instance && text(v.agent, 255) && !!v.agent && absolute(v.home)
|
|
180
|
+
&& v.home.split('/').at(-1) === v.instance ? { instance: v.instance, agent: v.agent, home: v.home } : null;
|
|
181
|
+
}
|
|
182
|
+
function rows(value, project) {
|
|
183
|
+
if (!Array.isArray(value) || value.length > MAX_LIFECYCLE_TARGETS) return null;
|
|
184
|
+
const result = value.map(project);
|
|
185
|
+
return result.some(v => !v) || new Set(result.map(v => v.home)).size !== result.length ? null : result;
|
|
186
|
+
}
|
|
187
|
+
const excluded = v => { const i = identity(v); return i && text(v.reason) ? { ...i, reason: v.reason } : null; };
|
|
188
|
+
export function lifecyclePlan(v, target, operation, options) {
|
|
189
|
+
if (!object(v) || v.lifecycleApi !== 1 || v.action !== operation || v.instance !== target.instance || v.home !== target.home
|
|
190
|
+
|| !planRevision(v.planRevision) || !at(v.at) || !strings(v.notes)) return null;
|
|
191
|
+
const common = { lifecycleApi: 1, action: operation, instance: v.instance, home: v.home, planRevision: v.planRevision, at: v.at, notes: [...v.notes] };
|
|
192
|
+
if (operation === 'stop') {
|
|
193
|
+
if (v.recursive !== options.recursive) return null;
|
|
194
|
+
const targets = rows(v.targets, t => {
|
|
195
|
+
const i = identity(t), session = lifecycleSession(t?.session), work = lifecycleWork(t?.work);
|
|
196
|
+
return i && session && work && count(t.depth) && nullable(t.workMode) && typeof t.launched === 'boolean'
|
|
197
|
+
&& typeof t.retiring === 'boolean' && typeof t.stopPending === 'boolean' && [true, false, 'unknown'].includes(t.midTask)
|
|
198
|
+
? { ...i, depth: t.depth, workMode: t.workMode, launched: t.launched, session, work, retiring: t.retiring, stopPending: t.stopPending, midTask: t.midTask } : null;
|
|
199
|
+
});
|
|
200
|
+
const skipped = rows(v.skipped, excluded), ambiguous = rows(v.ambiguous, excluded);
|
|
201
|
+
if (!targets?.length || !skipped || !ambiguous || targets.length + skipped.length + ambiguous.length > MAX_LIFECYCLE_TARGETS
|
|
202
|
+
|| targets.at(-1).home !== target.home || targets.at(-1).agent !== target.agent || targets.at(-1).depth !== 0
|
|
203
|
+
|| targets.slice(0, -1).some(t => !t.depth) || (!options.recursive && targets.length !== 1)
|
|
204
|
+
|| (options.recursive && skipped.length) || [...skipped, ...ambiguous].some(t => targets.some(x => x.home === t.home))) return null;
|
|
205
|
+
return { ...common, recursive: v.recursive, targets, skipped, ambiguous };
|
|
206
|
+
}
|
|
207
|
+
const f = v.facts, d = v.defaults;
|
|
208
|
+
if (!object(f) || !object(d) || !nullable(f.workMode) || !(f.repo === null || absolute(f.repo)) || !nullable(f.recordedBranch) || f.pullRequest !== 'unknown'
|
|
209
|
+
|| typeof d.retainWorktree !== 'boolean' || !(d.deleteBranch === undefined || d.deleteBranch === false) || d.stopChildren !== true || d.retainChildren !== true) return null;
|
|
210
|
+
const session = lifecycleSession(f.session), work = lifecycleWork(f.work);
|
|
211
|
+
const children = rows(f.children, t => { const i = identity(t), s = lifecycleSession(t?.session); return i && s ? { ...i, session: s } : null; });
|
|
212
|
+
const ambiguous = rows(f.ambiguous, excluded);
|
|
213
|
+
if (!session || !work || !children || !ambiguous || children.length + ambiguous.length + 1 > MAX_LIFECYCLE_TARGETS
|
|
214
|
+
|| [...children, ...ambiguous].some(t => t.home === target.home) || ambiguous.some(t => children.some(c => c.home === t.home))) return null;
|
|
215
|
+
return { ...common, facts: { session, work, workMode: f.workMode, repo: f.repo, recordedBranch: f.recordedBranch,
|
|
216
|
+
children, ambiguous, pullRequest: 'unknown' }, defaults: { retainWorktree: d.retainWorktree, stopChildren: true, retainChildren: true } };
|
|
217
|
+
}
|
|
218
|
+
/** The kernel feature from which `stillRunning: []` in a failed row says the harness exited
|
|
219
|
+
* (docs/desktop-cli-api.md, #still-running). A kernel without it answers `[]` there for a session that was
|
|
220
|
+
* not seen to stop. */
|
|
221
|
+
const KERNEL_CODES_FEATURE = 'lifecycle-kernel-codes';
|
|
222
|
+
const PROBE_FEATURES_FEATURE = 'server-probe-features';
|
|
223
|
+
const names = (features, feature) => Array.isArray(features) && features.includes(feature);
|
|
224
|
+
/** The features of the kernel that answers a command, or null when they are not known. A local command
|
|
225
|
+
* (`routed: false`): the selected CLI's own list. A routed one (`routed: true`): the host's list, which is
|
|
226
|
+
* known only when this computer's CLI relays it (feature server-probe-features), the workspace's roster
|
|
227
|
+
* `group` was read (`probe.ok === true`) and `probe.features` is an array. Anything else is unknown, a
|
|
228
|
+
* missing `routed` too: never decided from a refusal, and never by probing. Pure: it keeps nothing. */
|
|
229
|
+
export function answeringFeatures({ cli, routed, group } = {}) {
|
|
230
|
+
if (cli?.ok !== true || !Array.isArray(cli.features)) return null;
|
|
231
|
+
if (routed === false) return [...cli.features];
|
|
232
|
+
const probe = group?.probe;
|
|
233
|
+
return routed === true && cli.features.includes(PROBE_FEATURES_FEATURE) && probe?.ok === true && Array.isArray(probe.features) ? [...probe.features] : null;
|
|
234
|
+
}
|
|
235
|
+
/** The rows of a stop's `results` or of a retire's `childrenStopped`. `decoded: false` reads a kernel's answer:
|
|
236
|
+
* a failed row's `stillRunning: []` is kept only when `features` (the answering kernel's, answeringFeatures)
|
|
237
|
+
* names lifecycle-kernel-codes, and is `null` otherwise, which is what that kernel's `[]` established.
|
|
238
|
+
* `decoded: true` validates rows a server already decoded, and keeps them as they are. A row's `message` is
|
|
239
|
+
* the kernel's text and is dropped, except under E_LIFECYCLE_BUSY, where it is kept as `detail`, through the
|
|
240
|
+
* display filter. */
|
|
241
|
+
function stoppedRows(value, expected, { withState = false, decoded = false, features = null } = {}) {
|
|
242
|
+
if (!Array.isArray(value) || value.length !== expected.length || value.length > MAX_LIFECYCLE_TARGETS) return null;
|
|
243
|
+
const exited = decoded || names(features, KERNEL_CODES_FEATURE);
|
|
244
|
+
const result = value.map((v, index) => {
|
|
245
|
+
if (!object(v) || v.home !== expected[index].home || v.instance !== expected[index].instance || typeof v.ok !== 'boolean') return null;
|
|
246
|
+
if (v.ok) return typeof v.stopped === 'boolean' && typeof v.alreadyIdle === 'boolean' && (!withState || text(v.state, 128))
|
|
247
|
+
? { instance: v.instance, home: v.home, ok: true, stopped: v.stopped, alreadyIdle: v.alreadyIdle, ...(withState ? { state: v.state } : {}) } : null;
|
|
248
|
+
if (v.stillRunning !== null && (!Array.isArray(v.stillRunning) || v.stillRunning.length > 128 || v.stillRunning.some(p => !Number.isSafeInteger(p) || p <= 0))) return null;
|
|
249
|
+
const code = lifecycleCode(v.code);
|
|
250
|
+
// The row's own sentence is kept for one code only: a child whose home could not be locked, where the
|
|
251
|
+
// sentence is the refusal of that child's stop and names what ends it. One display line, or nothing.
|
|
252
|
+
const detail = code !== 'E_LIFECYCLE_BUSY' ? null : decoded ? cleanLine(v.detail) ? v.detail : null : displayLine(v.message);
|
|
253
|
+
return { instance: v.instance, home: v.home, ok: false, code,
|
|
254
|
+
stillRunning: v.stillRunning === null || !v.stillRunning.length && !exited ? null : [...v.stillRunning], ...(detail ? { detail } : {}) };
|
|
255
|
+
});
|
|
256
|
+
return result.some(v => !v) ? null : result;
|
|
257
|
+
}
|
|
258
|
+
/** Decode the rows of a kernel's answer. `features`: the answering kernel's (answeringFeatures). Not given,
|
|
259
|
+
* null, or a list without lifecycle-kernel-codes all read a failed row's `[]` as `null`: a caller that
|
|
260
|
+
* forgets the argument makes the weaker claim. From here on `[]` in a failed row has one meaning: the
|
|
261
|
+
* harness exited, and what failed came after. */
|
|
262
|
+
export function stoppedTargets(value, expected, withState = false, { features = null } = {}) {
|
|
263
|
+
return stoppedRows(value, expected, { withState, features });
|
|
264
|
+
}
|
|
265
|
+
/** Validate rows a server already decoded (the reply's `childrenStopped`). Never for a kernel's answer. */
|
|
266
|
+
export function decodedStoppedTargets(value, expected) { return stoppedRows(value, expected, { decoded: true }); }
|
|
267
|
+
/** What a decoded row is, as data. The only place that reads a row for wording: every reader of a stop's
|
|
268
|
+
* result (a line, the sentence above the rows) decides from this.
|
|
269
|
+
* idle ok, the session was already stopped
|
|
270
|
+
* stopped ok
|
|
271
|
+
* retiring failed with E_INSTANCE_RETIRING: nothing was tried, a retire holds it
|
|
272
|
+
* locked failed with E_LIFECYCLE_BUSY: nothing was tried, its home's claim could not be taken
|
|
273
|
+
* running failed, and these signalled processes were seen alive after the wait
|
|
274
|
+
* unrecorded failed with `stillRunning: []`: the harness exited, and what failed came after
|
|
275
|
+
* unconfirmed failed with `stillRunning: null`: nothing is established
|
|
276
|
+
* The two codes decide before `stillRunning` does, and need no feature name: each means the same in every
|
|
277
|
+
* kernel that answers it, and the kernel answers both only before any effect. */
|
|
278
|
+
export function stoppedRowKind(row) {
|
|
279
|
+
if (row.ok) return row.alreadyIdle ? 'idle' : 'stopped';
|
|
280
|
+
if (row.code === 'E_INSTANCE_RETIRING') return 'retiring';
|
|
281
|
+
if (row.code === 'E_LIFECYCLE_BUSY') return 'locked';
|
|
282
|
+
return !Array.isArray(row.stillRunning) ? 'unconfirmed' : row.stillRunning.length ? 'running' : 'unrecorded';
|
|
283
|
+
}
|
|
284
|
+
/** A row's line, after its name. "Not stopped" for a row nothing was tried on; "Didn't stop" for one that
|
|
285
|
+
* was tried. The busy line says only what the code means: a row carries no holder, and the code covers
|
|
286
|
+
* causes where nobody runs. A `locked` row's own sentence (`detail`) is shown under the line, as a quote. */
|
|
287
|
+
export function stoppedRowText(row) {
|
|
288
|
+
const kind = stoppedRowKind(row);
|
|
289
|
+
return kind === 'idle' ? 'Was already stopped' : kind === 'stopped' ? 'Stopped'
|
|
290
|
+
: kind === 'retiring' ? 'Not stopped: it is being retired' : kind === 'locked' ? "Not stopped: OATS couldn't lock its home"
|
|
291
|
+
: kind === 'unrecorded' ? "Stopped, but OATS couldn't record it"
|
|
292
|
+
: kind === 'running' ? `Didn't stop (still running: ${row.stillRunning.join(', ')})` : "Didn't stop";
|
|
293
|
+
}
|
|
294
|
+
/** Some row failed, and every failed row is `unrecorded`: each session stopped, and OATS could not record all of it. */
|
|
295
|
+
const stoppedUnrecorded = rows => rows.some(r => !r.ok) && rows.every(r => r.ok || stoppedRowKind(r) === 'unrecorded');
|
|
296
|
+
/** How a stop's result that is not `ok` reads above its rows: `{ status, title }`. A reader words a stop's
|
|
297
|
+
* result from the rows, through this and childrenRefusedMessage, never from the reply's `reason.message`
|
|
298
|
+
* (a partial stop's reason stays E_SESSION_STOP_FAILED's sentence, whatever the rows say). */
|
|
299
|
+
export function stopResultWords(rows) {
|
|
300
|
+
if (!stoppedUnrecorded(rows)) return { status: 'Not every session stopped:', title: 'Not every session stopped' };
|
|
301
|
+
return { title: 'Stopped, but not recorded', status: rows.length === 1 ? `${rows[0].instance} stopped, but OATS couldn't record it.`
|
|
302
|
+
: "Every session stopped, but OATS couldn't record all of them:" };
|
|
303
|
+
}
|
|
304
|
+
const CHILDREN_UNRECORDED = "The child instances stopped, but OATS couldn't record it for all of them, so nothing was retired.";
|
|
305
|
+
/** The sentence for a retire refused with E_CHILDREN_RUNNING, chosen from its child rows. "Nothing was
|
|
306
|
+
* retired" rests on the code (an answer with no result, refused before the retire's own effects); "the
|
|
307
|
+
* child instances stopped" rests on the rows: every one is ok, or failed with `[]`. Like stopResultWords,
|
|
308
|
+
* a reader asks this, never the reply's `reason.message`. */
|
|
309
|
+
export const childrenRefusedMessage = rows => stoppedUnrecorded(rows) ? CHILDREN_UNRECORDED : messages.E_CHILDREN_RUNNING;
|
|
310
|
+
/** The one branch deletion a retire reports (feature `worktree-event`, 0.49.0): it finished the compensation of a
|
|
311
|
+
* spawn killed while its `worktree` hooks ran. `{branch, branchDeleted: true}`, or `{branch, branchDeleted: false,
|
|
312
|
+
* reason}`. Additive and read tolerantly: anything else is ignored (null), never a refused receipt. Its text is
|
|
313
|
+
* the kernel's, raw: shown only through displayLine. It is not retire's own `branchDeleted`, which stays refused. */
|
|
314
|
+
export function spawnCompensationOf(v) {
|
|
315
|
+
const label = (x, max) => typeof x === 'string' && !!x && x.length <= max;
|
|
316
|
+
if (!object(v) || !label(v.branch, 1024) || typeof v.branchDeleted !== 'boolean') return null;
|
|
317
|
+
if (v.branchDeleted) return { branch: v.branch, branchDeleted: true };
|
|
318
|
+
return label(v.reason, 4096) ? { branch: v.branch, branchDeleted: false, reason: v.reason } : null;
|
|
319
|
+
}
|
|
320
|
+
/** Decode a kernel's receipt. `server`: the request was routed there. The routed retire's result then may
|
|
321
|
+
* also carry `server` and `target` (its route); a local result carrying them is refused. `features`: the
|
|
322
|
+
* answering kernel's (answeringFeatures), for its rows (stoppedTargets).
|
|
323
|
+
* Desktop asks for no branch deletion, so a retire result that reports one, or a skipped one, is not the
|
|
324
|
+
* answer to its request and is refused whole, a deferred one too: nothing of it is projected. The kernel's one
|
|
325
|
+
* exception, an interrupted spawn's branch (`spawnCompensation`), is not such a report: it is projected. */
|
|
326
|
+
export function lifecycleReceipt(v, plan, key, { server = null, features = null } = {}) { return receipt(v, plan, key, { server, features }); }
|
|
327
|
+
function receipt(v, plan, key, { server = null, features = null, decoded = false } = {}) {
|
|
328
|
+
if (!object(v) || v.idempotencyKey !== key || v.planRevision !== plan.planRevision || typeof v.replayed !== 'boolean') return null;
|
|
329
|
+
if (!server ? Object.hasOwn(v, 'server') || Object.hasOwn(v, 'target')
|
|
330
|
+
: plan.action !== 'retire' && (Object.hasOwn(v, 'server') || Object.hasOwn(v, 'target'))
|
|
331
|
+
|| Object.hasOwn(v, 'server') && v.server !== server || Object.hasOwn(v, 'target') && !object(v.target)) return null;
|
|
332
|
+
if (plan.action === 'stop') {
|
|
333
|
+
const results = stoppedRows(v.results, plan.targets, { withState: true, decoded, features });
|
|
334
|
+
if (v.lifecycleApi !== 1 || v.action !== 'stop' || v.instance !== plan.instance || v.home !== plan.home || !at(v.at)
|
|
335
|
+
|| !results || v.ok !== results.every(r => r.ok) || !Array.isArray(v.retained)
|
|
336
|
+
|| JSON.stringify(v.retained) !== JSON.stringify(['home', 'work', 'transcript', 'launch'])) return null;
|
|
337
|
+
return { action: 'stop', instance: v.instance, home: v.home, planRevision: v.planRevision, replayed: v.replayed, at: v.at,
|
|
338
|
+
ok: v.ok, results, retained: [...v.retained] };
|
|
339
|
+
}
|
|
340
|
+
if (!(v.branchDeleted === undefined || v.branchDeleted === false)
|
|
341
|
+
|| object(v.retention) && (Object.hasOwn(v.retention, 'branchDeleted') || Object.hasOwn(v.retention, 'branchDeletionSkipped'))) return null;
|
|
342
|
+
if (v.retired === plan.instance && v.deferred === true) return { action: 'retire', instance: plan.instance, home: plan.home,
|
|
343
|
+
planRevision: v.planRevision, replayed: v.replayed, deferred: true };
|
|
344
|
+
if (v.retired !== plan.instance || typeof v.removedDir !== 'boolean' || typeof v.worktreeRemoved !== 'boolean'
|
|
345
|
+
|| (v.rollbackIncomplete !== undefined && !strings(v.rollbackIncomplete)) || !(v.retainedHome === undefined || v.retainedHome === plan.home)) return null;
|
|
346
|
+
const childrenStopped = stoppedRows(v.childrenStopped, plan.facts.children, { decoded, features });
|
|
347
|
+
if (!childrenStopped || childrenStopped.some(c => !c.ok)) return null;
|
|
348
|
+
let retention = null;
|
|
349
|
+
if (v.retention !== null) {
|
|
350
|
+
const r = v.retention;
|
|
351
|
+
if (!object(r) || !['retained', 'removed', 'absent'].includes(r.worktree) || !nullable(r.branch) || !nullable(r.recordedBranch)
|
|
352
|
+
|| (r.worktree === 'retained' && (!absolute(r.movedTo) || !nullable(r.detachedAt)))) return null;
|
|
353
|
+
retention = { worktree: r.worktree, branch: r.branch, recordedBranch: r.recordedBranch,
|
|
354
|
+
...(r.worktree === 'retained' ? { movedTo: r.movedTo, detachedAt: r.detachedAt } : {}) };
|
|
355
|
+
}
|
|
356
|
+
const recovery = v.workRecovery?.path, compensation = spawnCompensationOf(v.spawnCompensation);
|
|
357
|
+
return { action: 'retire', instance: plan.instance, home: plan.home, planRevision: v.planRevision, replayed: v.replayed,
|
|
358
|
+
removedDir: v.removedDir, worktreeRemoved: v.worktreeRemoved, retention, childrenStopped,
|
|
359
|
+
incomplete: !!v.rollbackIncomplete?.length, retainedHome: v.retainedHome ?? null,
|
|
360
|
+
recoveryPath: absolute(recovery) ? recovery : null, ...(compensation ? { spawnCompensation: compensation } : {}) };
|
|
361
|
+
}
|
|
362
|
+
/** Validate the public projection without exposing the server's private key. Its rows were decoded by
|
|
363
|
+
* the server and are kept as they are: this takes no features and never reads a kernel's own row. */
|
|
364
|
+
export function publicLifecycleReceipt(v, plan) {
|
|
365
|
+
if (!object(v) || v.action !== plan.action || v.instance !== plan.instance || v.home !== plan.home) return null;
|
|
366
|
+
if (v.action === 'stop') return receipt({ ...v, lifecycleApi: 1, idempotencyKey: 'public' }, plan, 'public', { decoded: true });
|
|
367
|
+
if (v.deferred !== true && (typeof v.incomplete !== 'boolean' || !(v.retainedHome === null || v.retainedHome === plan.home)
|
|
368
|
+
|| !(v.recoveryPath === null || absolute(v.recoveryPath)))) return null;
|
|
369
|
+
return receipt({ ...v, retired: v.instance, idempotencyKey: 'public',
|
|
370
|
+
retainedHome: v.retainedHome || undefined, rollbackIncomplete: v.incomplete ? ['reported incomplete cleanup'] : undefined,
|
|
371
|
+
workRecovery: v.recoveryPath ? { path: v.recoveryPath } : undefined }, plan, 'public', { decoded: true });
|
|
372
|
+
}
|
|
@@ -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")))));
|