@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.
- package/README.md +3 -1
- package/bin/oats.mjs +407 -123
- package/docs/capabilities.md +75 -6
- package/docs/configuration.md +200 -91
- package/docs/desktop-cli-api.md +1563 -113
- package/docs/desktop-instance-start.md +69 -0
- package/docs/desktop.md +10 -7
- package/docs/execution-targets.md +145 -58
- package/docs/first-team.md +3 -1
- package/docs/harness-trust.md +50 -2
- package/docs/implementation.md +238 -17
- package/docs/integrations.md +13 -9
- 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/macos-test-runs.md +246 -0
- package/docs/oats-local.schema.json +4 -3
- package/docs/official-catalog.md +5 -5
- package/docs/packages.md +14 -14
- package/docs/release-lane.md +225 -11
- package/docs/release-notes/v0.44.0.md +1 -1
- package/docs/release-notes/v0.52.0.md +933 -0
- package/docs/release-notes/v0.53.0.md +1274 -0
- package/docs/schedules.md +97 -4
- package/docs/souls-and-instances.md +332 -40
- package/docs/tui.md +584 -0
- package/docs/upgrading.md +298 -0
- package/docs/workspaces.md +3 -3
- package/lib/automations.mjs +22 -22
- package/lib/claim.mjs +278 -49
- package/lib/config-data.mjs +4 -1
- package/lib/core.mjs +1282 -289
- package/lib/errors.mjs +170 -0
- package/lib/harness-trust-write.mjs +68 -27
- package/lib/harness-trust.mjs +34 -16
- package/lib/instance-events.mjs +19 -1
- package/lib/instance-git.mjs +39 -3
- package/lib/instance-inspect.mjs +45 -17
- package/lib/instance-lifecycle.mjs +306 -57
- package/lib/instance-resolution.mjs +59 -6
- package/lib/launch-preference.mjs +236 -9
- 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/local-edit.mjs +118 -0
- package/lib/packages.mjs +13 -4
- package/lib/pi-bridge.mjs +308 -0
- package/lib/refused-text.mjs +11 -0
- package/lib/remote.mjs +190 -25
- package/lib/resolve.mjs +2 -1
- package/lib/retained-after-retire.mjs +2 -2
- package/lib/retire-output.mjs +12 -1
- package/lib/schedule-host.mjs +125 -22
- package/lib/schedule.mjs +73 -24
- package/lib/shell-word.mjs +13 -0
- package/lib/soul-launch-verbs.mjs +153 -0
- package/lib/stable-node.mjs +62 -0
- package/lib/system-tools.mjs +39 -0
- package/lib/teams-verbs.mjs +18 -46
- package/lib/tmux-server-scope.mjs +62 -0
- package/lib/triggers.mjs +4 -4
- package/lib/workspace.mjs +54 -30
- package/lib/worktree-hooks.mjs +98 -20
- package/lib/worktree.mjs +83 -24
- package/package-catalog.json +4 -4
- package/package.json +8 -2
- package/packages/client/attach-exit.mjs +25 -0
- package/packages/client/capability-show-contract.mjs +230 -0
- package/packages/client/capability-warnings-contract.mjs +57 -0
- package/packages/client/cli-adapter.mjs +561 -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 +72 -0
- package/packages/client/deployment-data.mjs +483 -0
- package/packages/client/deployment-facts.mjs +95 -0
- package/packages/client/deployment-label.mjs +76 -0
- package/packages/client/deployment-observer.mjs +89 -0
- package/packages/client/deployment-panel.mjs +180 -0
- package/packages/client/deployment-read-cli.mjs +57 -0
- package/packages/client/display-text.mjs +50 -0
- package/packages/client/harness-names.mjs +30 -0
- package/packages/client/inspect-contract.mjs +62 -0
- package/packages/client/instance-acts.mjs +90 -0
- package/packages/client/instance-admission.mjs +45 -0
- package/packages/client/instance-events-contract.mjs +76 -0
- package/packages/client/instance-git-contract.mjs +80 -0
- package/packages/client/instance-presentation.mjs +86 -0
- package/packages/client/instance-tree.mjs +462 -0
- package/packages/client/kernel-environment.mjs +11 -0
- package/packages/client/kernel-lines.mjs +31 -0
- package/packages/client/kernel-made.mjs +23 -0
- package/packages/client/launch-contract.mjs +51 -0
- package/packages/client/launch-prompt-outcome.mjs +200 -0
- package/packages/client/lifecycle-cli.mjs +61 -0
- package/packages/client/lifecycle-contract.mjs +413 -0
- package/packages/client/liveness-main.mjs +10 -0
- package/packages/client/liveness.mjs +48 -0
- package/packages/client/machine-contract.mjs +123 -0
- package/packages/client/own-codes.mjs +31 -0
- package/packages/client/own-environment.mjs +22 -0
- package/packages/client/panel-views.mjs +293 -0
- package/packages/client/readiness-contract.mjs +174 -0
- package/packages/client/refresh-loop.mjs +52 -0
- package/packages/client/remote-address.mjs +151 -0
- package/packages/client/remote-identity-memory.mjs +94 -0
- package/packages/client/remote-roster.mjs +153 -0
- package/packages/client/roster-sections.mjs +80 -0
- package/packages/client/session-attach.mjs +175 -0
- package/packages/client/spawn-apply-cli.mjs +104 -0
- package/packages/client/spawn-apply-contract.mjs +195 -0
- package/packages/client/spawn-decision.mjs +46 -0
- package/packages/client/spawn-messages.mjs +142 -0
- package/packages/client/spawn-preview-cli.mjs +38 -0
- package/packages/client/spawn-preview-contract.mjs +318 -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/terminal-exec.mjs +21 -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-choices.mjs +95 -0
- package/packages/client/workspace-cli.mjs +142 -0
- package/packages/client/workspace-views.mjs +183 -0
- package/packages/record/README.md +21 -0
- package/packages/record/bin/setup.mjs +108 -15
- package/packages/tui/README.md +64 -0
- package/packages/tui/bin/tui.mjs +7 -0
- package/packages/tui/lib/actions.mjs +44 -0
- package/packages/tui/lib/client.mjs +35 -0
- package/packages/tui/lib/config.mjs +151 -0
- package/packages/tui/lib/main.mjs +176 -0
- package/packages/tui/lib/model.mjs +392 -0
- package/packages/tui/lib/read.mjs +473 -0
- package/packages/tui/lib/store.mjs +364 -0
- package/packages/tui/lib/term/keys.mjs +367 -0
- package/packages/tui/lib/term/screen.mjs +134 -0
- package/packages/tui/lib/term/style.mjs +43 -0
- package/packages/tui/lib/term/text.mjs +109 -0
- package/packages/tui/lib/term/tty.mjs +178 -0
- package/packages/tui/lib/term/width.mjs +124 -0
- package/packages/tui/lib/views/detail.mjs +46 -0
- package/packages/tui/lib/views/frame.mjs +256 -0
- package/packages/tui/lib/views/help.mjs +140 -0
- package/packages/tui/lib/views/instances.mjs +137 -0
- package/packages/tui/lib/views/scroll.mjs +19 -0
- package/packages/tui/lib/views/switcher.mjs +97 -0
- package/packages/tui/package.json +8 -0
- package/skills/oats-getting-started/SKILL.md +30 -23
- 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
package/lib/errors.mjs
CHANGED
|
@@ -6,6 +6,176 @@ export function oatsError(code, message, provenance) {
|
|
|
6
6
|
return e;
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
+
/** Whether `code` has the shape of a kernel code (`E_` and upper-case letters, digits and
|
|
10
|
+
* underscores): the only codes an answer of the kernel carries. It tests the shape, not a list of
|
|
11
|
+
* known codes, and that is enough: no dependency of the kernel gives an error whose code has that
|
|
12
|
+
* shape, and neither does the system (`ENOENT`) or Node (`ERR_…`). An allow-list on purpose: what
|
|
13
|
+
* is not a kernel code is wrapped (asKernelError), whatever it is, so the next unknown code does
|
|
14
|
+
* not pass. */
|
|
15
|
+
export function isKernelCode(code) {
|
|
16
|
+
return typeof code === "string" && /^E_[A-Z0-9_]+$/.test(code);
|
|
17
|
+
}
|
|
18
|
+
/** The two failures the kernel answers under their own names, which are not kernel codes: an OATS
|
|
19
|
+
* document with an unsafe mapping key, or value. Every command answers them so, and they are the
|
|
20
|
+
* one exception to the rule above: no door wraps them. */
|
|
21
|
+
export const OWN_NAME_FAILURES = new Set(["unsafe-config-key", "unsafe-config-value"]);
|
|
22
|
+
/** Whether `code` is one an answer carries as it is: a kernel code, or one of the two names. */
|
|
23
|
+
export function isAnswerCode(code) {
|
|
24
|
+
return isKernelCode(code) || OWN_NAME_FAILURES.has(code);
|
|
25
|
+
}
|
|
26
|
+
/** The code `e` is answered with: its own when an answer carries it (isAnswerCode), else `fallback`. */
|
|
27
|
+
export function kernelCode(e, fallback) {
|
|
28
|
+
return isAnswerCode(e?.code) ? e.code : fallback;
|
|
29
|
+
}
|
|
30
|
+
/** Whether `e` is a defect: something thrown by a mistake in the code, never written as an answer.
|
|
31
|
+
* It has no code, and it is one of the language's own error kinds, whose `name` is not "Error"
|
|
32
|
+
* (TypeError, ReferenceError, RangeError, SyntaxError…), or it is a thrown value that is no Error
|
|
33
|
+
* at all. A plain Error without a code is NOT one: the kernel writes many of its refusals that way,
|
|
34
|
+
* and a child process that exits non-zero (a tmux or git call) is reported that way too. */
|
|
35
|
+
export function isDefect(e) {
|
|
36
|
+
if (typeof e?.code === "string" && e.code) return false;
|
|
37
|
+
return !(e instanceof Error) || e.name !== "Error";
|
|
38
|
+
}
|
|
39
|
+
/** What an answer's `details.cause` says of an error that is not the kernel's: `{ code, syscall? }`
|
|
40
|
+
* for one that has a code (the system's, Node's, or one of the kernel's own names that is not a
|
|
41
|
+
* kernel code), `{ name }` for a defect (isDefect), and undefined for a plain Error without a
|
|
42
|
+
* code: a refusal has no cause to name, and its answer is the general code and its message alone. */
|
|
43
|
+
export function errorCause(e) {
|
|
44
|
+
if (typeof e?.code === "string" && e.code) return { code: e.code, ...(typeof e.syscall === "string" && e.syscall ? { syscall: e.syscall } : {}) };
|
|
45
|
+
if (!isDefect(e)) return undefined;
|
|
46
|
+
return { name: e instanceof Error && typeof e.name === "string" && e.name ? e.name : "Error" };
|
|
47
|
+
}
|
|
48
|
+
/** `e` as a kernel error. One whose code an answer carries (isAnswerCode) is returned as it is. Any other is wrapped:
|
|
49
|
+
* the code `fallback`, `message` (default: its own), `details.cause` when it has one (errorCause)
|
|
50
|
+
* and the error itself as `cause`, so that whoever prints the answer still has a defect's stack. */
|
|
51
|
+
export function asKernelError(e, fallback, message) {
|
|
52
|
+
if (isAnswerCode(e?.code)) return e;
|
|
53
|
+
const wrapped = new Error(message ?? String(e?.message ?? e), { cause: e });
|
|
54
|
+
wrapped.code = fallback;
|
|
55
|
+
const cause = errorCause(e);
|
|
56
|
+
if (cause) wrapped.details = { cause };
|
|
57
|
+
return wrapped;
|
|
58
|
+
}
|
|
59
|
+
/** The defect (isDefect) that `e` is or wraps (asKernelError), as `{ thrown }`, else undefined: the
|
|
60
|
+
* one error whose stack an answer must not swallow. It is boxed because anything can be thrown,
|
|
61
|
+
* `undefined`, `null`, `0` and `""` included: whether there is a defect is not whether its value
|
|
62
|
+
* is truthy. A wrapper holds what it wrapped as its own `cause`, whatever that value is. */
|
|
63
|
+
export function defectOf(e) {
|
|
64
|
+
const thrown = isKernelCode(e?.code) && e.details?.cause && Object.hasOwn(e, "cause") ? e.cause : e;
|
|
65
|
+
return isDefect(thrown) ? { thrown } : undefined;
|
|
66
|
+
}
|
|
67
|
+
/** Print on stderr the defect `e` is or wraps (defectOf), when there is one: its stack, or, for a
|
|
68
|
+
* thrown value that is no Error and so has none, a line that shows the value. For whoever ends an
|
|
69
|
+
* error's way up: the door that answers it, and a caller that turns it into data (a row of a
|
|
70
|
+
* stop's results), after which nobody else can print it. */
|
|
71
|
+
export function reportDefect(e) {
|
|
72
|
+
const defect = defectOf(e);
|
|
73
|
+
if (!defect) return;
|
|
74
|
+
const { thrown } = defect;
|
|
75
|
+
process.stderr.write(`${thrown instanceof Error ? thrown.stack || String(thrown) : `A value that is no Error was thrown: ${shownValue(thrown)}`}\n`);
|
|
76
|
+
}
|
|
77
|
+
/** A thrown value that is no Error, as one can read it in a log: a string quoted, anything else as
|
|
78
|
+
* the language prints it. */
|
|
79
|
+
function shownValue(value) {
|
|
80
|
+
try { return typeof value === "string" ? JSON.stringify(value) : String(value); } catch { return `a ${typeof value} that cannot be printed`; }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** What `error.details.holder` of an E_LIFECYCLE_BUSY says, a closed list (docs/desktop-cli-api.md):
|
|
84
|
+
* "running": the kernel established that a process with the recorded pid and start time is alive,
|
|
85
|
+
* and waiting ends it when that process is the `oats` command its file names (the kernel does
|
|
86
|
+
* not establish that it is: a claim's refusal says what to check when it does not end,
|
|
87
|
+
* ifItDoesNotEnd); "unknown": whether one still runs cannot be read; "none": nobody is running,
|
|
88
|
+
* and what a dead command left has to be dealt with. */
|
|
89
|
+
export const BUSY_HOLDERS = Object.freeze(["running", "unknown", "none"]);
|
|
90
|
+
/** What a refusal says it did not do once something was ended before it (afterEndedSteps): then
|
|
91
|
+
* the words of every verb, in place of its own ("nothing was done", "nothing was stopped", "no
|
|
92
|
+
* tree was made"), which are true only before any effect. */
|
|
93
|
+
export const NOTHING_ELSE = "nothing else was done";
|
|
94
|
+
/** What a refusal's sentence says was not done: `own`, the verb's words, before any effect, and
|
|
95
|
+
* NOTHING_ELSE when `ended` names what was ended first. Whoever writes the sentence asks here: no
|
|
96
|
+
* message is rewritten after it was made. */
|
|
97
|
+
export function nothingAfter(ended, own = "nothing was done") {
|
|
98
|
+
return ended?.length ? NOTHING_ELSE : own;
|
|
99
|
+
}
|
|
100
|
+
/** The answers afterEndedSteps made: one is never made twice. */
|
|
101
|
+
const answeredAfterEndedSteps = new WeakSet();
|
|
102
|
+
/** `refusal` as it is answered when `ended` names what was ended before it (clauses, in order: a
|
|
103
|
+
* takeover ends the step a dead holder recorded, lib/claim.mjs). With none, `refusal` as it is.
|
|
104
|
+
* With some it is no answer before any effect, whatever its code says: E_LIFECYCLE_FAILED, the
|
|
105
|
+
* clauses first, then `after that:` and the refusal's own sentence, with its details and its
|
|
106
|
+
* `cause`. Its sentence was written knowing `ended` (nothingAfter): nothing in it is replaced. */
|
|
107
|
+
export function afterEndedSteps(ended, refusal) {
|
|
108
|
+
if (!ended?.length || answeredAfterEndedSteps.has(refusal)) return refusal;
|
|
109
|
+
const failed = oatsError("E_LIFECYCLE_FAILED", `${ended.join("; ")}; after that: ${String(refusal?.message ?? refusal)}`);
|
|
110
|
+
if (refusal?.details) failed.details = refusal.details;
|
|
111
|
+
// Its own `cause`, whatever the value: a wrapper holds what it wrapped there, and a thrown
|
|
112
|
+
// `undefined` is a defect whose report (defectOf) reads it from that property.
|
|
113
|
+
if (refusal && Object.hasOwn(refusal, "cause")) failed.cause = refusal.cause;
|
|
114
|
+
answeredAfterEndedSteps.add(failed);
|
|
115
|
+
return failed;
|
|
116
|
+
}
|
|
117
|
+
/** E_LIFECYCLE_BUSY, the one way the kernel makes it (test/lifecycle-busy-holder.test.mjs pins that
|
|
118
|
+
* no site raises the code any other way): `said` is the refusal, one line that states its
|
|
119
|
+
* effects; `remedy` is the step that ends it, and the message is `<said> — <remedy>`. For
|
|
120
|
+
* "unknown" and "none" waiting ends nothing, so a remedy is required: the process to check, the
|
|
121
|
+
* file to inspect, the command to run. `details.holder` is `holder`, whatever `details` holds.
|
|
122
|
+
* `ended` is what was ended before this refusal, for the one caller that can have ended
|
|
123
|
+
* something (a claim's takeover): with it the code would say what is no longer true, and the
|
|
124
|
+
* answer is afterEndedSteps's, the same sentence and details after what was ended. `said` was
|
|
125
|
+
* written for it (nothingAfter). */
|
|
126
|
+
export function lifecycleBusy(holder, said, remedy, details, ended) {
|
|
127
|
+
if (!BUSY_HOLDERS.includes(holder)) throw new TypeError(`lifecycleBusy: holder is ${JSON.stringify(holder)}, not one of ${BUSY_HOLDERS.join(", ")}`);
|
|
128
|
+
const step = typeof remedy === "string" ? remedy.trim() : "";
|
|
129
|
+
if (!step && holder !== "running") throw new TypeError(`lifecycleBusy: an answer whose holder is "${holder}" names the step that ends it`);
|
|
130
|
+
return afterEndedSteps(ended, Object.assign(oatsError("E_LIFECYCLE_BUSY", step ? `${said} — ${step}` : said), { details: { ...details, holder } }));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The step that ends a refusal for "this process's start time cannot be read": the check a person
|
|
134
|
+
* runs in a shell, of the read the refusal's own reason names (lib/worktree-hooks.mjs readStart:
|
|
135
|
+
* /proc/<pid>/stat where there is a procfs, else the system `ps` with both columns). It sends
|
|
136
|
+
* nobody to the pid of the refused command, which is gone when the answer is read: `$$` is the
|
|
137
|
+
* reader's shell. */
|
|
138
|
+
export const OWN_START_REMEDY = "check by hand, in a shell on this host, the read that the reason names (`cat /proc/$$/stat` where there is a /proc; elsewhere `PATH=/usr/bin:/bin ps -o lstart= -o stat= -p $$`, which must print a start time and a state), then run the command again";
|
|
139
|
+
|
|
140
|
+
/** The check that ends a refusal naming, by its pid, the holder of the file `at`, when that process
|
|
141
|
+
* is not the command it is taken for (`what`, with its article: "an oats retire"). What the
|
|
142
|
+
* kernel establishes of a holder is that a process with the recorded pid and start time is alive,
|
|
143
|
+
* or that this cannot be read; never that the process is that command: the file can name any
|
|
144
|
+
* process. One text of the check: the whole step for a holder whose liveness cannot be read, and
|
|
145
|
+
* what follows for one that runs and does not end (ifItDoesNotEnd). */
|
|
146
|
+
export const checkHolderByHand = (what, at) => `check that pid by hand, and if it is not ${what}, remove ${at}, then retry`;
|
|
147
|
+
/** The step for a holder that runs, when waiting for it has not ended the refusal (checkHolderByHand). */
|
|
148
|
+
export const ifItDoesNotEnd = (what, at) => `if it does not end, ${checkHolderByHand(what, at)}`;
|
|
149
|
+
|
|
150
|
+
/** Per verb, the codes that verb answers only BEFORE any effect: a client reads each as "refused,
|
|
151
|
+
* nothing happened". The rule holds by construction, at the place of each verb that knows how far
|
|
152
|
+
* it got (lib/core.mjs retireFailure, lib/instance-lifecycle.mjs applyStop): a listed code raised
|
|
153
|
+
* after the verb's first effect is never answered (afterFirstEffect). The docs table of
|
|
154
|
+
* docs/desktop-cli-api.md is checked against this constant, and a client's own set must lie
|
|
155
|
+
* inside it (test/lifecycle-before-effect-codes.test.mjs). */
|
|
156
|
+
const BEFORE_EFFECT = Object.freeze(["E_BAD_ARGS", "E_PLAN_STALE", "E_INSTANCE_RETIRING", "E_LIFECYCLE_BUSY", "E_HOME_MISMATCH", "E_SESSION_UNKNOWN",
|
|
157
|
+
"E_AMBIGUOUS_INSTANCE", "E_UNIDENTIFIED_INSTANCE_HOME", "E_REMOTE_INCOMPATIBLE", "E_AMBIGUOUS", "E_SNAPSHOT_UNKNOWN"]);
|
|
158
|
+
export const BEFORE_EFFECT_CODES = Object.freeze({ "instance stop": BEFORE_EFFECT, retire: BEFORE_EFFECT });
|
|
159
|
+
/** The defect afterFirstEffect makes. Its name is on the prototype, so that it is in the stack's
|
|
160
|
+
* first line whenever the engine writes that line (some write it when the error is made). */
|
|
161
|
+
class LateRefusal extends Error {}
|
|
162
|
+
LateRefusal.prototype.name = "LateRefusal";
|
|
163
|
+
/** `e` as `verb` ("instance stop", "retire") answers it once its first effect has happened, at
|
|
164
|
+
* `point` (how far it got, in a few words). An error whose code the verb does not list is returned
|
|
165
|
+
* as it is. A listed one is a kernel defect: its own message says that nothing happened, which is
|
|
166
|
+
* no longer true. → E_LIFECYCLE_FAILED, `<verb> answered <code> after its first effect (<point>):
|
|
167
|
+
* <its message>`, its details kept and `details.cause: { name: "LateRefusal" }`. It is a defect
|
|
168
|
+
* like any other the kernel wraps (asKernelError): whoever ends its way up prints its stack, with
|
|
169
|
+
* the code it had, on stderr (reportDefect). A net, never an answer: every known place that would
|
|
170
|
+
* be late has a code of its own. */
|
|
171
|
+
export function afterFirstEffect(e, verb, point) {
|
|
172
|
+
if (!BEFORE_EFFECT_CODES[verb]?.includes(e?.code)) return e;
|
|
173
|
+
const late = new LateRefusal(`oats ${verb} answered ${e.code} after its first effect (${point}): ${e.message}`);
|
|
174
|
+
const failed = asKernelError(late, "E_LIFECYCLE_FAILED");
|
|
175
|
+
failed.details = { ...e.details, ...failed.details };
|
|
176
|
+
return failed;
|
|
177
|
+
}
|
|
178
|
+
|
|
9
179
|
/** Herdr was removed in 0.31.0: every place that meets it refuses with E_HERDR_REMOVED, this stem
|
|
10
180
|
* and what to do. */
|
|
11
181
|
export const HERDR_REMOVED = "Herdr is no longer supported by OATS (removed in 0.31.0); tmux is the only session backend.";
|
|
@@ -8,7 +8,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
8
8
|
import { execFileSync } from 'node:child_process';
|
|
9
9
|
import { editClaudeTrust } from './harness-trust-json.mjs';
|
|
10
10
|
import { editCodexTrust } from './harness-trust-toml.mjs';
|
|
11
|
-
import { claudeTrusts, codexTrustsRoot, codexTrustedDirs } from './harness-trust.mjs';
|
|
11
|
+
import { CONFIG_DIR_VAR, claudeTrusts, codexTrustsRoot, codexTrustedDirs, launchConfigDir } from './harness-trust.mjs';
|
|
12
12
|
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
13
13
|
const error = (code, message, details) => Object.assign(new Error(message), { code, details });
|
|
14
14
|
const broken = () => error('E_CONFIG_BROKEN', 'Native trust configuration is unreadable, unsafe, invalid, or outside the supported format; inspect the selected file before retrying.');
|
|
@@ -80,46 +80,86 @@ function ensureDirectory(path) {
|
|
|
80
80
|
if (stat(path)) { if (!fs.lstatSync(path).isDirectory() || fs.realpathSync.native(path) !== path) throw broken(); return; }
|
|
81
81
|
ensureDirectory(dirname(path)); fs.mkdirSync(path, { mode: 0o700 }); syncDirectory(dirname(path));
|
|
82
82
|
}
|
|
83
|
+
/** The configuration files `name` reads: the ambient one (the operator's env), then one per
|
|
84
|
+
* launch configuration whose env moves the harness's configuration directory, in name order,
|
|
85
|
+
* deduplicated by canonical directory. No configuration directory is ever created. A launch
|
|
86
|
+
* configuration's directory that cannot be resolved or does not exist is a target with a
|
|
87
|
+
* `problem`: refused. A missing ambient directory means the harness has not run as this user:
|
|
88
|
+
* `skipped` when every harness was asked for (`named` false), a `problem` when this one was named. */
|
|
89
|
+
function trustTargets(name, env, launchConfigs, named) {
|
|
90
|
+
const variable = CONFIG_DIR_VAR[name], targets = [], byFile = new Map();
|
|
91
|
+
const add = (target) => {
|
|
92
|
+
if (target.file && byFile.has(target.file)) { byFile.get(target.file).launchConfigs.push(...target.launchConfigs); return; }
|
|
93
|
+
if (target.file) byFile.set(target.file, target);
|
|
94
|
+
targets.push(target);
|
|
95
|
+
};
|
|
96
|
+
let ambientFile = null;
|
|
97
|
+
try { ambientFile = nativePath(name, env); } catch { /* refused below, as a broken file */ }
|
|
98
|
+
add({ env, ambient: true, launchConfigs: [], file: ambientFile });
|
|
99
|
+
for (const config of Object.values(launchConfigs).filter(c => c.harness === name).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
|
|
100
|
+
const resolved = launchConfigDir(name, config.env, env);
|
|
101
|
+
if (!resolved) continue;
|
|
102
|
+
const named = text => `launch configuration ${config.name}: ${text}`;
|
|
103
|
+
if (resolved.problem) { add({ ambient: false, launchConfigs: [config.name], file: null, problem: named(resolved.problem) }); continue; }
|
|
104
|
+
const targetEnv = { ...env, [variable]: resolved.dir };
|
|
105
|
+
let file; try { file = nativePath(name, targetEnv); } catch { add({ ambient: false, launchConfigs: [config.name], file: null, problem: named(`${variable} ${resolved.dir} is not a usable directory`) }); continue; }
|
|
106
|
+
add({ env: targetEnv, ambient: false, launchConfigs: [config.name], file, dir: resolved.dir });
|
|
107
|
+
}
|
|
108
|
+
for (const t of targets) if (t.file && !t.problem && !fs.existsSync(dirname(t.file))) {
|
|
109
|
+
if (t.launchConfigs.length) t.problem = `launch configuration ${t.launchConfigs[0]}: ${variable} ${t.dir ?? dirname(t.file)} does not exist; OATS never creates a harness configuration directory: create it, or start ${name} with it once, then rerun`;
|
|
110
|
+
else if (named) t.problem = `${dirname(t.file)} does not exist: ${name} has not run as this user; OATS never creates a harness configuration directory: start ${name} once, then rerun`;
|
|
111
|
+
else t.skipped = `${dirname(t.file)} does not exist: ${name} has not run as this user`;
|
|
112
|
+
}
|
|
113
|
+
for (const t of targets) t.launchConfigs.sort();
|
|
114
|
+
return targets;
|
|
115
|
+
}
|
|
83
116
|
/** Planning performs reads only, including when native directories do not exist. */
|
|
84
|
-
export function planHarnessTrust(root, { harness = 'all', env = process.env, metadataProbe = nativeSecurityContext } = {}) {
|
|
117
|
+
export function planHarnessTrust(root, { harness = 'all', env = process.env, launchConfigs = {}, metadataProbe = nativeSecurityContext } = {}) {
|
|
85
118
|
if (!['all', 'claude', 'codex'].includes(harness)) throw error('E_BAD_ARGS', '--harness must be claude, codex, or all');
|
|
86
119
|
// Native lookup preserves the on-disk casing on case-insensitive APFS; the
|
|
87
120
|
// JS realpath implementation can retain the caller's spelling as a wrong key.
|
|
88
121
|
root = fs.realpathSync.native(root);
|
|
89
122
|
const result = { operation: 'harness-trust', mode: 'plan', root, entries: [], audit: null, warnings: [] }, plans = [];
|
|
90
123
|
for (const name of harness === 'all' ? ['claude', 'codex'] : [harness]) {
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
124
|
+
for (const target of trustTargets(name, env, launchConfigs, harness !== 'all')) {
|
|
125
|
+
const key = ['projects', root, name === 'claude' ? 'hasTrustDialogAccepted' : 'trust_level'];
|
|
126
|
+
const entry = { harness: name, file: target.file, ambient: target.ambient, launchConfigs: target.launchConfigs, key, current: null, desired: name === 'claude' ? true : 'trusted', beforeDigest: null, afterDigest: null, status: 'refused', ...(target.problem ? { problem: target.problem } : {}) };
|
|
127
|
+
result.entries.push(entry);
|
|
128
|
+
if (target.skipped) { entry.status = 'skipped'; entry.reason = target.skipped; continue; }
|
|
129
|
+
if (target.problem || !target.file) continue;
|
|
130
|
+
try {
|
|
131
|
+
const file = target.file;
|
|
132
|
+
const before = snapshot(file, metadataProbe); entry.beforeDigest = before.digest;
|
|
133
|
+
const text = before.bytes?.toString('utf8') ?? (name === 'claude' ? '{}' : '');
|
|
134
|
+
if (before.bytes && !Buffer.from(text).equals(before.bytes)) throw broken();
|
|
135
|
+
const edited = (name === 'claude' ? editClaudeTrust : editCodexTrust)(text, root);
|
|
136
|
+
// Preflight the existing reader's supported representation as well as
|
|
137
|
+
// native syntax; never discover a known compatibility gap after writing.
|
|
138
|
+
if (name === 'codex' && !codexTrustedDirs(edited.text).has(root)) throw broken();
|
|
139
|
+
const after = Buffer.from(edited.text);
|
|
140
|
+
entry.current = edited.current; entry.afterDigest = digest(after);
|
|
141
|
+
entry.status = before.bytes?.equals(after) ? 'unchanged' : 'change';
|
|
142
|
+
plans.push({ entry, before, after, env: target.env });
|
|
143
|
+
const overrideKey = CONFIG_DIR_VAR[name];
|
|
144
|
+
if (target.ambient && env[overrideKey]) result.warnings.push(`${overrideKey} selects ${env[overrideKey]}; effective file ${file}`);
|
|
145
|
+
} catch { /* Per-file refusal; never echo native content or parser exceptions. */ }
|
|
146
|
+
}
|
|
110
147
|
}
|
|
111
|
-
|
|
148
|
+
const problems = result.entries.filter(e => e.problem).map(e => e.problem);
|
|
149
|
+
if (result.entries.some(e => e.status === 'refused')) throw error('E_CONFIG_BROKEN', problems.length ? `Harness trust targets cannot be resolved; nothing was written: ${problems.join('; ')}` : broken().message, result);
|
|
112
150
|
return { result, plans };
|
|
113
151
|
}
|
|
114
|
-
export function harnessTrust(root, { harness = 'all', plan = false, env = process.env, checkpoint = () => {}, metadataProbe = nativeSecurityContext } = {}) {
|
|
152
|
+
export function harnessTrust(root, { harness = 'all', plan = false, env = process.env, launchConfigs = {}, checkpoint = () => {}, metadataProbe = nativeSecurityContext } = {}) {
|
|
115
153
|
let prepared;
|
|
116
|
-
try { prepared = planHarnessTrust(root, { harness, env, metadataProbe }); }
|
|
154
|
+
try { prepared = planHarnessTrust(root, { harness, env, launchConfigs, metadataProbe }); }
|
|
117
155
|
catch (e) { if (e.details?.operation === 'harness-trust') e.details.mode = plan ? 'plan' : 'apply'; throw e; }
|
|
118
156
|
const { result, plans } = prepared;
|
|
119
157
|
if (plan) return result;
|
|
120
158
|
result.mode = 'apply'; const operationId = randomUUID(), auditPath = join(result.root, '.agents', 'harness-trust.jsonl');
|
|
121
159
|
const locks = [], temps = new Map(), parents = new Map(); let mayHaveChanged = false, currentMayHaveChanged = false, reason = 'audit', current = null, auditSnapshot, failure, acquiringLock;
|
|
122
160
|
result.audit = { path: auditPath, operationId, status: 'incomplete' };
|
|
161
|
+
// Each file is verified through the reader, under the env that selects that file.
|
|
162
|
+
const trusts = p => (p.entry.harness === 'claude' ? claudeTrusts : codexTrustsRoot)(result.root, { env: p.env });
|
|
123
163
|
const checkParent = file => {
|
|
124
164
|
const dir = dirname(file);
|
|
125
165
|
if (fs.realpathSync.native(dir) !== dir || identity(fs.statSync(dir)) !== parents.get(dir)) throw new Error('parent changed');
|
|
@@ -164,7 +204,7 @@ export function harnessTrust(root, { harness = 'all', plan = false, env = proces
|
|
|
164
204
|
current = p; currentMayHaveChanged = false; reason = 'audit';
|
|
165
205
|
if (p.entry.status === 'unchanged') {
|
|
166
206
|
reason = 'verify';
|
|
167
|
-
if (!(p
|
|
207
|
+
if (!trusts(p)) throw new Error('verification failed');
|
|
168
208
|
reason = 'audit'; append(p.entry, 'outcome', 'unchanged'); current = null; continue;
|
|
169
209
|
}
|
|
170
210
|
append(p.entry, 'intent', 'planned'); reason = 'write';
|
|
@@ -186,7 +226,7 @@ export function harnessTrust(root, { harness = 'all', plan = false, env = proces
|
|
|
186
226
|
reason = 'verify'; checkpoint('after-replace', { entry: p.entry });
|
|
187
227
|
const observed = snapshot(p.entry.file, metadataProbe);
|
|
188
228
|
const expectedDigest = p.entry.afterDigest; p.entry.afterDigest = observed.digest;
|
|
189
|
-
if (observed.securityContext !== candidate.securityContext || observed.digest !== expectedDigest || !(p
|
|
229
|
+
if (observed.securityContext !== candidate.securityContext || observed.digest !== expectedDigest || !trusts(p)) throw new Error('verification failed');
|
|
190
230
|
p.entry.status = 'applied'; reason = 'audit'; append(p.entry, 'outcome', 'applied'); current = null;
|
|
191
231
|
}
|
|
192
232
|
result.audit.status = 'recorded';
|
|
@@ -200,7 +240,8 @@ export function harnessTrust(root, { harness = 'all', plan = false, env = proces
|
|
|
200
240
|
if (reason !== 'audit') { try { append(current.entry, 'outcome', current.entry.status); result.audit.status = 'recorded'; } catch { result.audit.status = 'incomplete'; } }
|
|
201
241
|
}
|
|
202
242
|
for (const p of plans) if (p.entry.status === 'change') p.entry.status = 'not-attempted';
|
|
203
|
-
|
|
243
|
+
const failed = result.entries.filter(e => ['failed', 'incomplete'].includes(e.status)).map(e => e.file);
|
|
244
|
+
failure = error('E_HARNESS_TRUST_INCOMPLETE', `Harness trust ${reason} failed${reason === 'locked' && acquiringLock ? `; could not acquire lock ${acquiringLock}` : ''}${failed.length ? `; failed: ${failed.join(', ')}` : ''}; inspect native configuration and ${auditPath} before retrying. No rollback was attempted.`, { ...result, reason, mayHaveChanged });
|
|
204
245
|
} finally {
|
|
205
246
|
// Cleanup is part of the outcome. Do not silently succeed with a lock left
|
|
206
247
|
// behind, and never delete a path another writer replaced.
|
package/lib/harness-trust.mjs
CHANGED
|
@@ -16,12 +16,32 @@
|
|
|
16
16
|
* override does trust a home, so the kernel's codex launch adds one for the home when the
|
|
17
17
|
* operator trusts the deployment root or an ancestor of it (renderLaunchRecipe). */
|
|
18
18
|
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
19
|
-
import { dirname, join, resolve } from "node:path";
|
|
19
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
20
20
|
import { homedir } from "node:os";
|
|
21
21
|
|
|
22
22
|
const real = (p) => { try { return realpathSync.native(p); } catch { return resolve(p); } };
|
|
23
23
|
const userHome = (env) => env.HOME || homedir();
|
|
24
24
|
|
|
25
|
+
/** The variable that moves each harness's configuration directory. */
|
|
26
|
+
export const CONFIG_DIR_VAR = { claude: "CLAUDE_CONFIG_DIR", codex: "CODEX_HOME" };
|
|
27
|
+
/** The configuration file `harness` reads under `env`: $CLAUDE_CONFIG_DIR/.claude.json or
|
|
28
|
+
* ~/.claude.json; $CODEX_HOME/config.toml or ~/.codex/config.toml. */
|
|
29
|
+
export function harnessConfigFile(harness, env = process.env) {
|
|
30
|
+
if (harness === "claude") return join(env.CLAUDE_CONFIG_DIR || userHome(env), ".claude.json");
|
|
31
|
+
return join(env.CODEX_HOME || join(userHome(env), ".codex"), "config.toml");
|
|
32
|
+
}
|
|
33
|
+
/** The configuration directory a launch configuration's `env` gives `harness`: `{dir}` from a
|
|
34
|
+
* literal or a {fromEnv} resolved from the host `base`; `{problem}` when the reference is not set
|
|
35
|
+
* on this host or the path is not absolute; null when the configuration leaves it to the host. */
|
|
36
|
+
export function launchConfigDir(harness, configEnv = {}, base = process.env) {
|
|
37
|
+
const name = CONFIG_DIR_VAR[harness];
|
|
38
|
+
if (!name || !Object.hasOwn(configEnv || {}, name)) return null;
|
|
39
|
+
const v = configEnv[name];
|
|
40
|
+
const dir = typeof v === "string" ? v : base[v?.fromEnv];
|
|
41
|
+
if (dir === undefined) return { problem: `${name} references ${v?.fromEnv}, not set on this host` };
|
|
42
|
+
return isAbsolute(dir) ? { dir } : { problem: `${name} ${JSON.stringify(dir)} is not an absolute path` };
|
|
43
|
+
}
|
|
44
|
+
|
|
25
45
|
/** `dir` and its ancestors, nearest first. */
|
|
26
46
|
function* upwards(dir) {
|
|
27
47
|
for (let d = real(dir); ; d = dirname(d)) { yield d; if (dirname(d) === d) return; }
|
|
@@ -30,9 +50,8 @@ function* upwards(dir) {
|
|
|
30
50
|
/** Whether Claude Code trusts `home` without asking: an accepted trust entry for the home or
|
|
31
51
|
* an ancestor, up to and including the nearest git root. */
|
|
32
52
|
export function claudeTrusts(home, { env = process.env } = {}) {
|
|
33
|
-
const file = env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, ".claude.json") : join(userHome(env), ".claude.json");
|
|
34
53
|
let projects;
|
|
35
|
-
try { projects = JSON.parse(readFileSync(
|
|
54
|
+
try { projects = JSON.parse(readFileSync(harnessConfigFile("claude", env), "utf8"))?.projects; } catch { return false; }
|
|
36
55
|
if (!projects || typeof projects !== "object") return false;
|
|
37
56
|
for (const d of upwards(home)) {
|
|
38
57
|
if (Object.hasOwn(projects, d) && projects[d]?.hasTrustDialogAccepted === true) return true;
|
|
@@ -118,23 +137,22 @@ export function codexTrustedDirs(text) {
|
|
|
118
137
|
/** Whether Codex's config trusts the deployment `root` or one of its ancestors: the operator's
|
|
119
138
|
* one-time consent for the kernel to trust each new home under it at launch. */
|
|
120
139
|
export function codexTrustsRoot(root, { env = process.env } = {}) {
|
|
121
|
-
const file = join(env.CODEX_HOME || join(userHome(env), ".codex"), "config.toml");
|
|
122
140
|
let trusted;
|
|
123
|
-
try { trusted = codexTrustedDirs(readFileSync(
|
|
141
|
+
try { trusted = codexTrustedDirs(readFileSync(harnessConfigFile("codex", env), "utf8")); } catch { return false; }
|
|
124
142
|
for (const d of upwards(root)) if (trusted.has(d)) return true;
|
|
125
143
|
return false;
|
|
126
144
|
}
|
|
127
145
|
|
|
128
|
-
/**
|
|
129
|
-
const
|
|
130
|
-
const TRUST_STEP = Object.fromEntries(["claude", "codex"].map(harness => [harness, root => {
|
|
131
|
-
const command = `oats harness trust --dir ${quote(root)} --harness ${harness}`;
|
|
132
|
-
return `preview with \`${command} --plan\`, then apply with \`${command}\`; a nested Git boundary may still require operator inspection`;
|
|
133
|
-
}]));
|
|
146
|
+
/** The deployment path as one shell word: as is when it needs no quoting, else single-quoted. */
|
|
147
|
+
const shellWord = value => /^[A-Za-z0-9_\/.,:@%+=-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\"'\"'") + "'";
|
|
134
148
|
|
|
135
|
-
/** The spawn and readiness warning for a
|
|
136
|
-
*
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
149
|
+
/** The spawn and readiness warning for a launch whose harness configuration does not trust the
|
|
150
|
+
* deployment (`file`, the file the launch reads; `problem` when that file cannot be resolved);
|
|
151
|
+
* null when `covered`, or for a harness without folder trust. A missing root entry does not
|
|
152
|
+
* prove the harness will prompt (a native gate may skip it), so this says only what the file
|
|
153
|
+
* lacks, and the one operator command that writes it (never run by readiness or a launch). */
|
|
154
|
+
export function harnessTrustWarning({ harness, root, file, problem, covered }) {
|
|
155
|
+
if (covered || !Object.hasOwn(CONFIG_DIR_VAR, harness)) return null;
|
|
156
|
+
if (problem) return `${harness} folder trust is not established: ${problem}`;
|
|
157
|
+
return `${harness} folder trust is not established in ${file}: oats harness trust --dir ${shellWord(root)}`;
|
|
140
158
|
}
|
package/lib/instance-events.mjs
CHANGED
|
@@ -46,7 +46,25 @@ export const EVENTS_API = 2;
|
|
|
46
46
|
const HOME_LOG = ".oats-events.jsonl";
|
|
47
47
|
const MAX_BYTES = 4 * 1024 * 1024;
|
|
48
48
|
|
|
49
|
-
export const EVENT_KINDS = ["spawned", "launched", "restarted", "stopped", "stop-refused", "retire-planned", "retired", "worktree-retained", "worktree-removed", "worktree-added", "branch-deleted", "child-spawn-refused", "launch-warning", "launch-prompt", "recomposed", "waiting"];
|
|
49
|
+
export const EVENT_KINDS = ["spawned", "launched", "restarted", "stopped", "stop-refused", "retire-planned", "retired", "retire-refused", "worktree-retained", "worktree-removed", "worktree-added", "branch-deleted", "child-spawn-refused", "launch-warning", "launch-prompt", "recomposed", "waiting"];
|
|
50
|
+
|
|
51
|
+
/** The longest `reason` a `retire-refused` row carries, in UTF-16 code units. The bound is not the
|
|
52
|
+
* kernel's: the Desktop's events reader refuses a whole read that holds a longer detail
|
|
53
|
+
* (`eventsDetail`, packages/client/instance-events-contract.mjs), so the kernel writes none.
|
|
54
|
+
* test/retire-refused-reader.test.mjs pins the two together; nothing under lib/ reads that package. */
|
|
55
|
+
export const RETIRE_REFUSED_REASON_MAX = 2048;
|
|
56
|
+
/** The `reason` of a `retire-refused` row for the sentence a retire answered: on one line (each run
|
|
57
|
+
* of whitespace, newlines among them, is one space) and at most RETIRE_REFUSED_REASON_MAX code
|
|
58
|
+
* units. A longer one is cut and ends with `…`, the mark counted in the bound, and never through a
|
|
59
|
+
* surrogate pair. */
|
|
60
|
+
export function retireRefusedReason(sentence) {
|
|
61
|
+
const line = String(sentence).replace(/\s+/g, " ").trim();
|
|
62
|
+
if (line.length <= RETIRE_REFUSED_REASON_MAX) return line;
|
|
63
|
+
const cut = line.slice(0, RETIRE_REFUSED_REASON_MAX - 1);
|
|
64
|
+
const last = cut.charCodeAt(cut.length - 1);
|
|
65
|
+
// A high surrogate at the end was the first half of a pair the cut went through.
|
|
66
|
+
return `${last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut}…`;
|
|
67
|
+
}
|
|
50
68
|
|
|
51
69
|
/** Kernel rows that end or begin a session: a waiting claim older than the
|
|
52
70
|
* incarnation's latest one is not live. */
|
package/lib/instance-git.mjs
CHANGED
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
* against a tree that has since moved is refused, never served. */
|
|
9
9
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
10
10
|
import { createHash } from "node:crypto";
|
|
11
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
11
|
+
import { existsSync, lstatSync, readFileSync } from "node:fs";
|
|
12
12
|
import { join } from "node:path";
|
|
13
13
|
import { oatsError } from "./errors.mjs";
|
|
14
|
+
import { canonicalHomePath } from "./real-path.mjs";
|
|
14
15
|
|
|
15
16
|
const GIT_MAX_BUFFER = 64 * 1024 * 1024;
|
|
16
17
|
const DIFF_MAX_BYTES = 256 * 1024;
|
|
@@ -68,6 +69,26 @@ export function gitRepoRead(gitDir, argv, { input, encoding } = {}) { return git
|
|
|
68
69
|
export function gitRepoRun(gitDir, argv) {
|
|
69
70
|
return execFileSync("git", ["--git-dir", gitDir, ...READ_ONLY_GIT, ...argv], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 120_000, env: gitEnv() });
|
|
70
71
|
}
|
|
72
|
+
/** What the result of a `git rev-parse -q --verify <ref>` (spawnSync's) says
|
|
73
|
+
* of the ref → "there" (status 0), "absent" (status 1 and nothing printed),
|
|
74
|
+
* else "unknown". An error or a signal is "unknown" whatever the status: a
|
|
75
|
+
* Git that could not be started has none, and one that is ended at the
|
|
76
|
+
* timeout can still exit 1 and print nothing, when it handles the signal. */
|
|
77
|
+
export function gitRefPresenceOf(r) {
|
|
78
|
+
if (r.error || r.signal) return "unknown";
|
|
79
|
+
if (r.status === 0) return "there";
|
|
80
|
+
return r.status === 1 && !r.stdout && !r.stderr ? "absent" : "unknown";
|
|
81
|
+
}
|
|
82
|
+
/** Whether the ref `name` is there in the tree at `cwd`, asked of Git
|
|
83
|
+
* (`rev-parse -q --verify`), which answers for every format a repository
|
|
84
|
+
* stores its refs in → "there", "absent" or "unknown" (gitRefPresenceOf);
|
|
85
|
+
* "unknown" too with no tree to ask in. Never throws: the caller decides
|
|
86
|
+
* what "unknown" means. Read-only and helper-free, like the module's other
|
|
87
|
+
* reads. */
|
|
88
|
+
export function gitRefPresence(cwd, name) {
|
|
89
|
+
if (typeof cwd !== "string" || !cwd) return "unknown";
|
|
90
|
+
return gitRefPresenceOf(spawnSync("git", ["-C", cwd, ...READ_ONLY_GIT, "rev-parse", "-q", "--verify", name], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 30_000, env: gitEnv() }));
|
|
91
|
+
}
|
|
71
92
|
function gitProbe(where, argv, input, encoding = "utf8") {
|
|
72
93
|
const r = spawnSync("git", [...where, ...READ_ONLY_GIT, ...argv], { encoding, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input, maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 30_000, env: gitEnv() });
|
|
73
94
|
return !r.error && r.status === 0 ? { ok: true, out: r.stdout } : { ok: false, out: "", err: String(r.error?.message ?? r.stderr ?? "").trim() || `git ${argv[0]} exited with ${r.status}` };
|
|
@@ -147,7 +168,17 @@ export function worktreeHead(work) {
|
|
|
147
168
|
|
|
148
169
|
/** The instance's work tree, from its home. The home's instance.json names
|
|
149
170
|
* the work mode; the tree is `<home>/work` (a directory or a symlink to the
|
|
150
|
-
* shared checkout). Missing/retired → attributed refusal, never a crash.
|
|
171
|
+
* shared checkout). Missing/retired → attributed refusal, never a crash.
|
|
172
|
+
*
|
|
173
|
+
* A real directory at `work/` is the instance's work tree only when it is
|
|
174
|
+
* the top level Git names for it (awebai/oats#962). Git answers for any
|
|
175
|
+
* directory inside a work tree, so a plain directory in a home whose
|
|
176
|
+
* deployment is a checkout, or whose home was made a repository, would be
|
|
177
|
+
* read as that repository's: its branch and its files, none of them the
|
|
178
|
+
* instance's. That is E_NO_WORKTREE, in every work mode: the rule is the
|
|
179
|
+
* path. A `work/` that is a link is read as what it leads to, wherever
|
|
180
|
+
* that is (a workspace instance's leads to the deployment directory, which
|
|
181
|
+
* is above its home). */
|
|
151
182
|
export function instanceWorkTree(home) {
|
|
152
183
|
const metaFile = join(home, "instance.json");
|
|
153
184
|
if (!existsSync(metaFile)) throw oatsError("E_SESSION_UNKNOWN", `${home} is not an OATS instance home (no instance.json)`);
|
|
@@ -155,8 +186,13 @@ export function instanceWorkTree(home) {
|
|
|
155
186
|
try { meta = JSON.parse(readFileSync(metaFile, "utf8")); } catch (e) { throw oatsError("E_SESSION_UNKNOWN", `${metaFile}: ${e.message}`); }
|
|
156
187
|
const work = join(home, "work");
|
|
157
188
|
if (!existsSync(work)) throw oatsError("E_NO_WORKTREE", `${meta.instance ?? home} has no work tree at ${work} (retired, recovered, or never materialized)`);
|
|
158
|
-
|
|
189
|
+
// One read: whether Git answers for `work` at all, and the top level it names for it.
|
|
190
|
+
const [inside, ...rest] = (trim(git(work, ["rev-parse", "--is-inside-work-tree", "--show-toplevel"], { allowFail: true })) ?? "").split("\n");
|
|
159
191
|
if (inside !== "true") throw oatsError("E_NO_WORKTREE", `${work} is not inside a git work tree`);
|
|
192
|
+
const top = rest.join("\n");
|
|
193
|
+
if (!lstatSync(work).isSymbolicLink() && (!top || canonicalHomePath(top) !== canonicalHomePath(work))) {
|
|
194
|
+
throw oatsError("E_NO_WORKTREE", `${work} is not a git work tree of its own: Git reads it as a directory inside another work tree`);
|
|
195
|
+
}
|
|
160
196
|
return { meta, work, mode: meta.work ?? null };
|
|
161
197
|
}
|
|
162
198
|
|