@awebai/oats 0.47.0 → 0.49.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/bin/oats.mjs +293 -41
- package/docs/capabilities.md +264 -8
- package/docs/capability-manifest.schema.json +18 -5
- package/docs/configuration.md +7 -1
- package/docs/desktop-cli-api.md +439 -40
- package/docs/desktop.md +72 -5
- package/docs/execution-targets.md +19 -1
- package/docs/implementation.md +81 -1
- package/docs/integrations.md +7 -5
- package/docs/knowledge.md +167 -197
- package/docs/official-catalog.md +6 -5
- package/docs/packages.md +14 -14
- package/docs/release-notes/v0.48.0.md +106 -0
- package/docs/release-notes/v0.49.0.md +770 -0
- package/docs/schedules.md +62 -39
- package/docs/servers.md +7 -0
- package/docs/souls-and-instances.md +395 -52
- package/docs/workspaces.md +18 -3
- package/injects/work-checkout.md +17 -11
- package/injects/work-worktree.md +19 -13
- package/lib/capability-contract.mjs +100 -11
- package/lib/capability-show.mjs +5 -2
- package/lib/core.mjs +1147 -319
- package/lib/instance-events.mjs +6 -3
- package/lib/instance-git.mjs +11 -5
- package/lib/instance-inspect.mjs +14 -3
- package/lib/instance-lifecycle.mjs +106 -16
- package/lib/instance-resolution.mjs +15 -3
- package/lib/launch-prompt-policy.mjs +17 -3
- package/lib/packages.mjs +1 -0
- package/lib/real-path.mjs +27 -0
- package/lib/resolve.mjs +4 -4
- package/lib/retire-output.mjs +6 -1
- package/lib/schedule.mjs +1 -0
- package/lib/servers.mjs +32 -6
- package/lib/teams-verbs.mjs +40 -9
- package/lib/tree-copy.mjs +18 -7
- package/lib/triggers.mjs +201 -65
- package/lib/workspace.mjs +20 -5
- package/lib/worktree-hooks.mjs +392 -0
- package/lib/worktree.mjs +655 -0
- package/package-catalog.json +12 -5
- package/package.json +1 -1
- package/skills/oats-getting-started/SKILL.md +1 -1
package/lib/workspace.mjs
CHANGED
|
@@ -18,7 +18,7 @@ import { parseConfigData } from "./config-data.mjs";
|
|
|
18
18
|
import { oatsError } from "./errors.mjs";
|
|
19
19
|
import * as defaultRemote from "./remote.mjs";
|
|
20
20
|
import { bindRemote, classifyPackageValue, lockedPackageRef } from "./packages.mjs";
|
|
21
|
-
import { manifestContractProblems } from "./capability-contract.mjs";
|
|
21
|
+
import { manifestContractProblems, locatedContractWarnings } from "./capability-contract.mjs";
|
|
22
22
|
import YAML from "yaml";
|
|
23
23
|
import { BY_TEAM_REMOVED, TEAM_MEMBERSHIP_MOVED, soulsReplacement } from "./teams.mjs";
|
|
24
24
|
|
|
@@ -597,6 +597,7 @@ async function enumerateRepo(remote, ref, key, commit) {
|
|
|
597
597
|
}, manifest);
|
|
598
598
|
if (shape.length) { for (const p of shape) problem("E_WORKSPACE_SCHEMA", `${file}#${p.path}`, p.message); continue; }
|
|
599
599
|
// The kernel contract (launch environment, hooks): a manifest the kernel could not run is not listed.
|
|
600
|
+
// What it declares and this kernel ignores (an unknown hook event) is a warning (workspaceWarnings), not a problem.
|
|
600
601
|
const contract = manifestContractProblems(manifest);
|
|
601
602
|
if (contract.length) { for (const p of contract) problem("E_WORKSPACE_SCHEMA", `${file}#${p.pointer}`, p.message); continue; }
|
|
602
603
|
if (capNames.has(manifest.capability)) { problem("E_WORKSPACE_SCHEMA", `${file}#/capability`, `capability ${show(manifest.capability)} is already declared by ${capNames.get(manifest.capability)}; the second declaration is not listed`); continue; }
|
|
@@ -828,11 +829,25 @@ export function memberRowByKey(members, key) {
|
|
|
828
829
|
return index.get(key) ?? null;
|
|
829
830
|
}
|
|
830
831
|
|
|
831
|
-
/** The discovery's warnings: ignored `private:`, over every listed soul
|
|
832
|
-
*
|
|
832
|
+
/** The discovery's warnings: ignored `private:`, over every listed soul, then what a listed
|
|
833
|
+
* member capability declares and this kernel ignores (capabilityContractWarnings). (0.30
|
|
834
|
+
* removed the `unmapped-team-label` warning: an unmapped shared team is the readiness item
|
|
835
|
+
* `team-unmapped`.) */
|
|
833
836
|
const byCodepointOrder = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
834
837
|
export function workspaceWarnings(workspace, members, externalRows, packageSouls) {
|
|
835
|
-
|
|
838
|
+
const confirmed = members.filter((m) => m.confirmed);
|
|
839
|
+
return [
|
|
840
|
+
...privateSoulWarnings([...confirmed.flatMap((m) => m.souls), ...externalRows.map((e) => e.soul), ...(packageSouls || [])]),
|
|
841
|
+
...capabilityContractWarnings(confirmed.flatMap((m) => m.capabilities)),
|
|
842
|
+
];
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/** Listed member capabilities' contract warnings (lib/capability-contract.mjs: an unknown,
|
|
846
|
+
* non-required hook event), ONE per warning: { code, capability, path, message }, `path`
|
|
847
|
+
* `<repoKey>:<dir>/oats.json#<pointer>`, sorted by capability, then path. */
|
|
848
|
+
export function capabilityContractWarnings(capabilities) {
|
|
849
|
+
return capabilities.flatMap((c) => locatedContractWarnings(c.manifest, `${c.repoKey}:${c.path}/oats.json`))
|
|
850
|
+
.sort((a, b) => byCodepointOrder(a.capability, b.capability) || byCodepointOrder(a.path, b.path));
|
|
836
851
|
}
|
|
837
852
|
|
|
838
853
|
/** `private:` in a soul.yaml has no effect since 0.26.0 (human decision 2026-09-25): every soul of a
|
|
@@ -895,6 +910,6 @@ export function standaloneRepo(ref, commit, discovery, { remote: injected } = {}
|
|
|
895
910
|
return {
|
|
896
911
|
standalone: true, key, commit: source.commit ?? commit ?? null, workspace: null,
|
|
897
912
|
members: [{ key, commit: source.commit ?? commit ?? null, confirmed: false, reason: "cannot-read", detail: `workspace of ${key} cannot be read; standalone view`, souls, capabilities, publishes: source.publishes ?? null }],
|
|
898
|
-
external: [], problems, warnings: privateSoulWarnings(souls),
|
|
913
|
+
external: [], problems, warnings: [...privateSoulWarnings(souls), ...capabilityContractWarnings(capabilities)],
|
|
899
914
|
};
|
|
900
915
|
}
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
/** The `worktree` lifecycle event's runner (#796), and the process facts its
|
|
2
|
+
* recovery reads. Dependency-free; the caller (lib/core.mjs for a spawn,
|
|
3
|
+
* lib/worktree.mjs for `oats worktree add`) builds each hook's environment.
|
|
4
|
+
*
|
|
5
|
+
* Only this event runs this way. Every other hook keeps `runLifecycleHooks`
|
|
6
|
+
* (execSync, buffered, 120 s, cwd the home). A `worktree` hook installs
|
|
7
|
+
* dependencies, so it may run for minutes and print a lot:
|
|
8
|
+
* - its cwd is the new tree; stdin is /dev/null; it has no terminal;
|
|
9
|
+
* - it is spawned detached (its own session and process group), so a
|
|
10
|
+
* timeout or an interrupt ends the whole group (terminateGroup);
|
|
11
|
+
* - stdout and stderr go to `<home>/.oats/logs/worktree-<p|work>-<cap>.log`
|
|
12
|
+
* (0600, truncated per run) and, when asked (`oats worktree add`), to the
|
|
13
|
+
* kernel's stderr — never its stdout, which holds only the envelope;
|
|
14
|
+
* - the result is the exit status; of the last stdout line's JSON only
|
|
15
|
+
* `warning` is read, and `env` is a contract error (as at retire).
|
|
16
|
+
* The timeout is fixed (WORKTREE_HOOK_TIMEOUT_MS). OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS
|
|
17
|
+
* is a test seam, not a setting. */
|
|
18
|
+
import { spawn as spawnProcess, execFileSync, spawnSync } from "node:child_process";
|
|
19
|
+
import { closeSync, existsSync, fchmodSync, mkdirSync, openSync, readFileSync, realpathSync, writeSync } from "node:fs";
|
|
20
|
+
import { dirname, join } from "node:path";
|
|
21
|
+
import { terminateGroup, watchGroup, TERM_GRACE_MS } from "./process-group.mjs";
|
|
22
|
+
|
|
23
|
+
export const WORKTREE_HOOK_TIMEOUT_MS = 30 * 60 * 1000;
|
|
24
|
+
/** The fixed timeout, or the test seam's value (a positive integer of milliseconds). */
|
|
25
|
+
export function worktreeHookTimeoutMs(env = process.env) {
|
|
26
|
+
const seam = Number(env.OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS);
|
|
27
|
+
return Number.isSafeInteger(seam) && seam > 0 ? seam : WORKTREE_HOOK_TIMEOUT_MS;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The signals an interrupted parent receives (condition A); SIGKILL cannot be caught. */
|
|
31
|
+
export const INTERRUPT_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
32
|
+
const SIGNAL_NUMBERS = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 };
|
|
33
|
+
/** The exit status of a process ended by `signal`: 128 + its number. */
|
|
34
|
+
export const interruptExitStatus = (signal) => 128 + (SIGNAL_NUMBERS[signal] ?? 15);
|
|
35
|
+
|
|
36
|
+
// ---------- process identity: a pid is verified by its start time ----------
|
|
37
|
+
|
|
38
|
+
/** Where a start time is read: /proc when this host has procfs, else `ps`. The test seam
|
|
39
|
+
* OATS_TEST_PROCESS_START_PS=1 (not a setting) takes the `ps` path on a host with procfs. */
|
|
40
|
+
const readsProc = () => process.env.OATS_TEST_PROCESS_START_PS !== "1" && existsSync("/proc/self/stat");
|
|
41
|
+
/** `ps` runs with a fixed environment, nothing inherited: `lstart` is local time in the locale's
|
|
42
|
+
* format, and two readers with another TZ or LANG would otherwise read one live process's start
|
|
43
|
+
* differently, and take it for another. */
|
|
44
|
+
const psEnv = () => ({ PATH: process.env.PATH ?? "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" });
|
|
45
|
+
|
|
46
|
+
/** Whether `pid` exists, from the kernel itself: kill(pid, 0). ESRCH is gone; EPERM (another user's
|
|
47
|
+
* process) and success are "exists"; anything else is unknown. Never from how procfs or `ps`
|
|
48
|
+
* word an absence: macOS's `ps` answers a pid that does not exist with an error and exit 1, which
|
|
49
|
+
* says nothing a failing `ps` does not also say. */
|
|
50
|
+
function existence(pid) {
|
|
51
|
+
try { process.kill(pid, 0); return { state: "exists" }; }
|
|
52
|
+
catch (e) {
|
|
53
|
+
if (e.code === "ESRCH") return { state: "gone" };
|
|
54
|
+
if (e.code === "EPERM") return { state: "exists" };
|
|
55
|
+
return { state: "unknown", reason: `kill(${pid}, 0) failed (${e.code || e.message})` };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The start of a pid that exists: /proc/<pid>/stat field 22 (clock ticks since boot) on Linux,
|
|
60
|
+
* elsewhere `ps -o lstart=` in a fixed environment. → { state: "alive", token } | { state: "unknown", reason }. */
|
|
61
|
+
function readStart(pid) {
|
|
62
|
+
if (readsProc()) {
|
|
63
|
+
let stat;
|
|
64
|
+
try { stat = readFileSync(`/proc/${pid}/stat`, "utf8"); }
|
|
65
|
+
catch (e) { return { state: "unknown", reason: `/proc/${pid}/stat could not be read (${e.code || e.message})` }; }
|
|
66
|
+
// comm (field 2) is in parentheses and may hold spaces or parentheses itself.
|
|
67
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
68
|
+
const start = fields[19]; // field 22 overall: after pid, comm and the 19 before it
|
|
69
|
+
return /^[0-9]+$/.test(start ?? "") ? { state: "alive", token: `proc:${start}` } : { state: "unknown", reason: `/proc/${pid}/stat has no start time` };
|
|
70
|
+
}
|
|
71
|
+
const r = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: psEnv(), timeout: 10_000 });
|
|
72
|
+
const out = String(r.stdout ?? "").trim(), err = String(r.stderr ?? "").trim();
|
|
73
|
+
if (r.error) return { state: "unknown", reason: `ps could not be run (${r.error.code || r.error.message})` };
|
|
74
|
+
if (r.status === 0 && out) return { state: "alive", token: `ps:${out}` };
|
|
75
|
+
return { state: "unknown", reason: `ps -o lstart= -p ${pid} answered ${r.status === null ? `signal ${r.signal}` : `exit ${r.status}`}${err ? `: ${err.split("\n")[0]}` : out ? " with output" : " with no output"}` };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** When `pid` started, read three ways apart (lessons/observation-must-not-harm-the-observer.md:
|
|
79
|
+
* "absent" never collapses with "unreadable"). One rule on every host: whether the pid exists is
|
|
80
|
+
* the kernel's answer (existence), and only a pid that exists has its start read.
|
|
81
|
+
* → { state: "alive", token } — an opaque token for its start; two processes that held one pid at
|
|
82
|
+
* different times never share it, so a pid is only ever compared WITH its token;
|
|
83
|
+
* → { state: "gone" } — kill(pid, 0) answers ESRCH, before the read or (it exited in between)
|
|
84
|
+
* after a read that failed;
|
|
85
|
+
* → { state: "unknown", reason } — anything else: the pid exists and its start could not be read,
|
|
86
|
+
* or kill(pid, 0) failed otherwise. Every caller fails safe on it. */
|
|
87
|
+
export function processStart(pid) {
|
|
88
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return { state: "gone" };
|
|
89
|
+
const before = existence(pid);
|
|
90
|
+
if (before.state !== "exists") return before;
|
|
91
|
+
const read = readStart(pid);
|
|
92
|
+
if (read.state === "alive") return read;
|
|
93
|
+
return existence(pid).state === "gone" ? { state: "gone" } : read;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The token of `processStart(pid)` when it is running, else null: for recording a process. A
|
|
97
|
+
* liveness decision never uses this, since null merges "gone" with "unknown" (processLiveness). */
|
|
98
|
+
export function processStartToken(pid) {
|
|
99
|
+
const s = processStart(pid);
|
|
100
|
+
return s.state === "alive" ? s.token : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** This process, as a record names it: { pid, processStart } (null when its start cannot be read;
|
|
104
|
+
* the callers that need it refuse then). */
|
|
105
|
+
export function selfIdentity() {
|
|
106
|
+
return { pid: process.pid, processStart: processStartToken(process.pid) };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Whether the process a record names (`{ pid, processStart }`) still runs:
|
|
110
|
+
* → { state: "alive" } — its pid runs with the recorded start;
|
|
111
|
+
* → { state: "gone" } — its pid does not run, or runs with another start (a reused pid);
|
|
112
|
+
* → { state: "unknown", reason } — the start could not be read, or the record has none to
|
|
113
|
+
* compare while its pid runs. Every caller fails safe on it: nothing is taken over, rolled back,
|
|
114
|
+
* retired or signalled, and the refusal names the way out. */
|
|
115
|
+
export function processLiveness(record) {
|
|
116
|
+
const pid = record?.pid;
|
|
117
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return { state: "gone" };
|
|
118
|
+
const s = processStart(pid);
|
|
119
|
+
if (s.state !== "alive") return s;
|
|
120
|
+
if (typeof record.processStart !== "string" || !record.processStart) return { state: "unknown", reason: `pid ${pid} runs, and the record names no start time to compare it with` };
|
|
121
|
+
return s.token === record.processStart ? { state: "alive" } : { state: "gone" };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Whether a record's process is verifiably the one still running (processLiveness "alive"). */
|
|
125
|
+
export const verifiedAlive = (record) => processLiveness(record).state === "alive";
|
|
126
|
+
|
|
127
|
+
const sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
128
|
+
const groupHasMembers = (pgid) => { try { process.kill(-pgid, 0); return true; } catch (e) { return e.code === "EPERM"; } };
|
|
129
|
+
|
|
130
|
+
/** End a hook process group a killed parent left behind (`{ hookPgid, hookStart }`
|
|
131
|
+
* from its record), synchronously: SIGTERM, then SIGKILL after `graceMs`.
|
|
132
|
+
* The group is signalled only when its leader (pid = pgid) is alive with the
|
|
133
|
+
* recorded start token: that alone proves the pgid is still this run's. A
|
|
134
|
+
* group whose leader is gone is never signalled, members or not — the record
|
|
135
|
+
* may have outlived the group and its id been reused by an unrelated one
|
|
136
|
+
* (lessons/observation-must-not-harm-the-observer.md: verified pids only).
|
|
137
|
+
* A group with members whose leader's start cannot be read is not signalled either, and is
|
|
138
|
+
* "unknown", never "unverified": its leader may be this run's and still running, so callers keep
|
|
139
|
+
* what they hold and refuse (unknownGroupNote) instead of warning and going on. An empty group is
|
|
140
|
+
* "none", whatever its leader reads as: the kernel answers that, not procfs or ps.
|
|
141
|
+
* → "none" (nothing to end) | "terminated" | "killed" | "survived"
|
|
142
|
+
* | "foreign" (the leader is someone else) | "unverified" (leader gone, members left: not signalled)
|
|
143
|
+
* | "unknown" (members left, the leader's start unreadable: not signalled). */
|
|
144
|
+
export function terminateRecordedGroup(rec, graceMs = TERM_GRACE_MS) {
|
|
145
|
+
const pgid = rec?.hookPgid;
|
|
146
|
+
if (!Number.isSafeInteger(pgid) || pgid <= 1 || !groupHasMembers(pgid)) return "none";
|
|
147
|
+
const leader = processStart(pgid);
|
|
148
|
+
if (leader.state === "unknown") return "unknown";
|
|
149
|
+
if (leader.state === "gone") return groupHasMembers(pgid) ? "unverified" : "none";
|
|
150
|
+
if (leader.token !== rec.hookStart) return "foreign";
|
|
151
|
+
return endGroupSync(pgid, graceMs);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The warning a recovery reports for an "unverified" group (terminateRecordedGroup): a hook's, or a git step's. */
|
|
155
|
+
export const unverifiedGroupWarning = (pgid, what = "hook") =>
|
|
156
|
+
`${what} process group ${pgid} was not signalled: its leader exited, so the group cannot be proven to be this run's; end any leftover processes yourself`;
|
|
157
|
+
|
|
158
|
+
/** What a refusal says of an "unknown" group (terminateRecordedGroup): its id, the recorded start
|
|
159
|
+
* of its leader and why that start cannot be read now. The caller adds what it kept and the way out. */
|
|
160
|
+
export function unknownGroupNote(rec, what = "hook") {
|
|
161
|
+
const s = processStart(rec.hookPgid);
|
|
162
|
+
const reason = s.state === "unknown" ? s.reason : "its leader's start time could not be read";
|
|
163
|
+
return `${what} process group ${rec.hookPgid} (leader pid ${rec.hookPgid}, recorded start ${rec.hookStart ?? "none"}) still has members, and its leader's start cannot be read (${reason}), so whether it is still that ${what} cannot be told and it was not signalled`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** End the group of a hook this process is running, synchronously, once its leader has
|
|
167
|
+
* closed after a timeout or an interrupt (runOne). The group was this process's when
|
|
168
|
+
* it was signalled with the leader alive, and is probed without a gap from then on:
|
|
169
|
+
* no pid is allocated while it is a live group's id, so a group seen non-empty is
|
|
170
|
+
* still ours (process-group.mjs, terminateGroup, the same rule). Never for a group
|
|
171
|
+
* read back from a record: that is terminateRecordedGroup. */
|
|
172
|
+
export function endOwnGroupSync(pgid, graceMs = TERM_GRACE_MS) {
|
|
173
|
+
if (!Number.isSafeInteger(pgid) || pgid <= 1 || !groupHasMembers(pgid)) return "none";
|
|
174
|
+
return endGroupSync(pgid, graceMs);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function endGroupSync(pgid, graceMs) {
|
|
178
|
+
try { process.kill(-pgid, "SIGTERM"); } catch { /* gone in between */ }
|
|
179
|
+
const deadline = Date.now() + graceMs;
|
|
180
|
+
while (Date.now() < deadline) {
|
|
181
|
+
if (!groupHasMembers(pgid)) return "terminated";
|
|
182
|
+
sleepSync(50);
|
|
183
|
+
}
|
|
184
|
+
try { process.kill(-pgid, "SIGKILL"); } catch { /* gone */ }
|
|
185
|
+
for (let i = 0; i < 20 && groupHasMembers(pgid); i++) sleepSync(50);
|
|
186
|
+
return groupHasMembers(pgid) ? "survived" : "killed";
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ---------- the remote URL a hook and the records see ----------
|
|
190
|
+
|
|
191
|
+
/** `origin`'s URL without credentials (amendment A2). URL-style
|
|
192
|
+
* (`scheme://userinfo@host/...`): the whole userinfo goes. scp-style
|
|
193
|
+
* (`user@host:path`): the `user@` goes. A local path is kept as it is. The
|
|
194
|
+
* result names the repository and carries no secret; it is the only form the
|
|
195
|
+
* kernel ever records, prints, logs or hands a hook. */
|
|
196
|
+
export function scrubRemoteUrl(url) {
|
|
197
|
+
const s = String(url ?? "").trim();
|
|
198
|
+
const scheme = /^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)(.*)$/s.exec(s);
|
|
199
|
+
if (scheme) {
|
|
200
|
+
const [, prefix, authority, rest] = scheme;
|
|
201
|
+
const at = authority.lastIndexOf("@");
|
|
202
|
+
return `${prefix}${at >= 0 ? authority.slice(at + 1) : authority}${rest}`;
|
|
203
|
+
}
|
|
204
|
+
// scp-style: [user@]host:path, where the part before the first ':' has no '/'.
|
|
205
|
+
const colon = s.indexOf(":");
|
|
206
|
+
const slash = s.indexOf("/");
|
|
207
|
+
if (colon > 0 && (slash < 0 || colon < slash)) {
|
|
208
|
+
const hostPart = s.slice(0, colon);
|
|
209
|
+
const at = hostPart.lastIndexOf("@");
|
|
210
|
+
return at >= 0 ? `${hostPart.slice(at + 1)}${s.slice(colon)}` : s;
|
|
211
|
+
}
|
|
212
|
+
return s;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ---------- interrupts ----------
|
|
216
|
+
|
|
217
|
+
/** Hold SIGINT, SIGTERM and SIGHUP while `worktree` hooks and their rollback
|
|
218
|
+
* run: the first one is recorded (`signal`) and `onSignal` callbacks run; the
|
|
219
|
+
* process is not ended by it. `restore()` removes the handlers, giving the
|
|
220
|
+
* previous behaviour back. */
|
|
221
|
+
export function signalGuard() {
|
|
222
|
+
const listeners = new Set();
|
|
223
|
+
const guard = {
|
|
224
|
+
signal: null,
|
|
225
|
+
onSignal(cb) { listeners.add(cb); if (guard.signal) cb(guard.signal); return () => listeners.delete(cb); },
|
|
226
|
+
restore() { for (const [sig, fn] of handlers) process.removeListener(sig, fn); handlers.length = 0; },
|
|
227
|
+
};
|
|
228
|
+
const handlers = INTERRUPT_SIGNALS.map((sig) => [sig, () => {
|
|
229
|
+
if (!guard.signal) guard.signal = sig;
|
|
230
|
+
for (const cb of [...listeners]) { try { cb(sig); } catch { /* a callback never ends the guard */ } }
|
|
231
|
+
}]);
|
|
232
|
+
for (const [sig, fn] of handlers) process.on(sig, fn);
|
|
233
|
+
return guard;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ---------- the runner ----------
|
|
237
|
+
|
|
238
|
+
/** How long a hook's output is drained after the hook exits, when something it started holds the pipes. */
|
|
239
|
+
const OUTPUT_DRAIN_MS = 2_000;
|
|
240
|
+
const LOG_NAME_UNSAFE = /[^A-Za-z0-9._-]+/g;
|
|
241
|
+
/** `<home>/.oats/logs/worktree-<purpose|work>-<cap>.log`. */
|
|
242
|
+
export function worktreeHookLogPath(home, purpose, capability) {
|
|
243
|
+
return join(home, ".oats", "logs", `worktree-${purpose || "work"}-${String(capability).replace(LOG_NAME_UNSAFE, "-")}.log`);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The capabilities whose `worktree` hook fires, in capability-name order:
|
|
247
|
+
* [{ id, command, required }]. `caps` are capability rows (hooks rendered as
|
|
248
|
+
* shell strings, requiredHooks listing "worktree" when declared required). */
|
|
249
|
+
export function worktreeHooksOf(caps) {
|
|
250
|
+
return (caps || [])
|
|
251
|
+
.filter((cap) => typeof cap?.hooks?.worktree === "string" && cap.hooks.worktree.trim())
|
|
252
|
+
.map((cap) => ({ id: cap.id, command: cap.hooks.worktree, required: (cap.requiredHooks || []).includes("worktree"), cap }))
|
|
253
|
+
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Run each hook in `hooks` (worktreeHooksOf) in order, one at a time.
|
|
257
|
+
* - `envFor(cap)`: the hook's whole environment;
|
|
258
|
+
* - `cwd`: the new tree; `home`/`purpose`: where the logs go;
|
|
259
|
+
* - `stream`: also copy the hook's output to process.stderr. A caller that closes its end
|
|
260
|
+
* (EPIPE: a tool shell killed, Desktop gone) stops the copy for the rest of the run, and only
|
|
261
|
+
* the copy: the hooks run on, their logs stay whole, and the run ends as it would have;
|
|
262
|
+
* - `guard`: a signalGuard; a signal ends the running hook's group and stops
|
|
263
|
+
* the run (`interrupted`);
|
|
264
|
+
* - `onStart({ capability, pgid, hookStart })`: called once each hook's group
|
|
265
|
+
* exists, before it can do anything long, so a caller records it for a
|
|
266
|
+
* recovery after SIGKILL.
|
|
267
|
+
* → { receipt: [{ capability, ok, required, log, exitCode?, signal?, timedOut?, contract? }],
|
|
268
|
+
* failures: [{ capability, event, message, required, contract? }], warnings: [], interrupted: signal|null } */
|
|
269
|
+
export async function runWorktreeHooks(hooks, { envFor, cwd, home, purpose, stream = false, guard, onStart, timeoutMs = worktreeHookTimeoutMs() }) {
|
|
270
|
+
const out = { receipt: [], failures: [], warnings: [], interrupted: null };
|
|
271
|
+
// A write to a closed pipe is an "error" event on process.stderr, fatal while nobody listens for it.
|
|
272
|
+
const sink = { open: stream };
|
|
273
|
+
const closed = (e) => {
|
|
274
|
+
if (!sink.open) return;
|
|
275
|
+
sink.open = false;
|
|
276
|
+
out.warnings.push(`the caller's stderr closed while the worktree hooks ran (${e?.code || e?.message}); the rest of their output is in their logs only`);
|
|
277
|
+
};
|
|
278
|
+
if (stream) process.stderr.on("error", closed);
|
|
279
|
+
try {
|
|
280
|
+
for (const hook of hooks) {
|
|
281
|
+
if (guard?.signal) { out.interrupted = guard.signal; break; }
|
|
282
|
+
const log = worktreeHookLogPath(home, purpose, hook.id);
|
|
283
|
+
const one = await runOne(hook, { env: envFor(hook.cap), cwd, log, sink, closed, guard, onStart, timeoutMs });
|
|
284
|
+
out.receipt.push({ capability: hook.id, ok: one.ok, required: hook.required, log, ...one.facts });
|
|
285
|
+
out.warnings.push(...one.warnings);
|
|
286
|
+
if (!one.ok) {
|
|
287
|
+
// An env answer is a contract error, which fails closed like a required hook (spawn's rule).
|
|
288
|
+
out.failures.push({ capability: hook.id, event: "worktree", message: one.message, required: hook.required || one.facts.contract === "environment", ...(one.facts.contract ? { contract: one.facts.contract } : {}) });
|
|
289
|
+
}
|
|
290
|
+
if (one.facts.signal && guard?.signal) { out.interrupted = guard.signal; break; }
|
|
291
|
+
}
|
|
292
|
+
if (!out.interrupted && guard?.signal) out.interrupted = guard.signal;
|
|
293
|
+
return out;
|
|
294
|
+
} finally {
|
|
295
|
+
if (stream) process.stderr.off("error", closed);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function runOne(hook, { env, cwd, log, sink, closed, guard, onStart, timeoutMs }) {
|
|
300
|
+
return new Promise((resolve) => {
|
|
301
|
+
const warnings = [];
|
|
302
|
+
let fd = null, logBroken = false;
|
|
303
|
+
try {
|
|
304
|
+
mkdirSync(dirname(log), { recursive: true, mode: 0o700 });
|
|
305
|
+
fd = openSync(log, "w", 0o600);
|
|
306
|
+
fchmodSync(fd, 0o600); // a log left by an earlier run keeps its old mode otherwise
|
|
307
|
+
} catch (e) { logBroken = true; warnings.push(`${hook.id} worktree hook: its log ${log} could not be opened (${e.code || e.message}); the hook ran without it`); }
|
|
308
|
+
const toLog = (chunk) => {
|
|
309
|
+
if (fd === null || logBroken) return;
|
|
310
|
+
try { writeSync(fd, chunk); }
|
|
311
|
+
catch (e) { logBroken = true; warnings.push(`${hook.id} worktree hook: writing its log ${log} failed (${e.code || e.message}); the hook kept running, the rest of its output is not in the log`); }
|
|
312
|
+
};
|
|
313
|
+
let stdoutTail = "";
|
|
314
|
+
let child;
|
|
315
|
+
try {
|
|
316
|
+
child = spawnProcess(hook.command, { cwd, env, shell: true, detached: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
317
|
+
} catch (e) {
|
|
318
|
+
if (fd !== null) closeSync(fd);
|
|
319
|
+
resolve({ ok: false, message: `could not start: ${e.message}`, facts: {}, warnings });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
watchGroup(child);
|
|
323
|
+
let timedOut = false, signalled = null, settled = false, drain = null;
|
|
324
|
+
const end = () => terminateGroup(child);
|
|
325
|
+
const timer = setTimeout(() => { timedOut = true; end(); }, timeoutMs);
|
|
326
|
+
const unwatch = guard ? guard.onSignal((sig) => { signalled = sig; end(); }) : () => {};
|
|
327
|
+
const hookStart = child.pid ? processStartToken(child.pid) : null;
|
|
328
|
+
if (child.pid) onStart?.({ capability: hook.id, pgid: child.pid, hookStart });
|
|
329
|
+
const toCaller = (chunk) => {
|
|
330
|
+
if (!sink.open) return;
|
|
331
|
+
if (process.stderr.destroyed || process.stderr.writableEnded) return closed({ code: "ERR_STREAM_DESTROYED" });
|
|
332
|
+
try { process.stderr.write(chunk); } catch (e) { closed(e); }
|
|
333
|
+
};
|
|
334
|
+
child.stdout.on("data", (chunk) => {
|
|
335
|
+
toLog(chunk);
|
|
336
|
+
toCaller(chunk);
|
|
337
|
+
stdoutTail = (stdoutTail + chunk.toString("utf8")).slice(-65536);
|
|
338
|
+
});
|
|
339
|
+
child.stderr.on("data", (chunk) => { toLog(chunk); toCaller(chunk); });
|
|
340
|
+
const finish = (code, signal, spawnError) => {
|
|
341
|
+
if (settled) return; settled = true;
|
|
342
|
+
clearTimeout(timer); clearTimeout(drain); unwatch();
|
|
343
|
+
// An ended hook's group is ended for certain before the answer: terminateGroup's SIGKILL is a timer the
|
|
344
|
+
// process may exit before, and a member that ignores SIGTERM would outlive it.
|
|
345
|
+
if ((timedOut || signalled) && child.pid) endOwnGroupSync(child.pid);
|
|
346
|
+
if (fd !== null) { try { closeSync(fd); } catch { /* closed */ } }
|
|
347
|
+
const facts = { exitCode: code ?? null, ...(signal ? { signal } : {}), ...(timedOut ? { timedOut: true } : {}) };
|
|
348
|
+
if (signalled) facts.signal = signalled;
|
|
349
|
+
let answer = {};
|
|
350
|
+
const last = stdoutTail.split("\n").map((l) => l.trim()).filter(Boolean).pop();
|
|
351
|
+
if (last) { try { const o = JSON.parse(last); if (o && typeof o === "object" && !Array.isArray(o)) answer = o; } catch { /* non-JSON output is fine */ } }
|
|
352
|
+
if (typeof answer.warning === "string" && answer.warning.trim()) warnings.push(`${hook.id} worktree hook: ${answer.warning.trim()}`);
|
|
353
|
+
if (spawnError) return resolve({ ok: false, message: `could not start: ${spawnError.message}`, facts, warnings });
|
|
354
|
+
if (signalled) return resolve({ ok: false, message: `interrupted by ${signalled}; its process group was ended`, facts, warnings });
|
|
355
|
+
if (timedOut) return resolve({ ok: false, message: `timed out after ${Math.round(timeoutMs / 1000)} s; its process group was ended`, facts, warnings });
|
|
356
|
+
if (code !== 0) return resolve({ ok: false, message: `${typeof answer.warning === "string" && answer.warning.trim() ? `${answer.warning.trim()} — ` : ""}exited ${code ?? signal}`, facts, warnings });
|
|
357
|
+
if (answer.env !== undefined) return resolve({ ok: false, message: `returned env, which a worktree hook may not (only spawn and launch hooks hand environment back)`, facts: { ...facts, contract: "environment" }, warnings });
|
|
358
|
+
resolve({ ok: true, facts, warnings });
|
|
359
|
+
};
|
|
360
|
+
child.on("error", (e) => finish(null, null, e));
|
|
361
|
+
child.on("close", (code, signal) => finish(code, signal));
|
|
362
|
+
// A process the hook left running (in its group or escaped from it) may hold the output pipes open, and
|
|
363
|
+
// 'close' would then never come: once the hook itself has exited, its output is drained for a moment and
|
|
364
|
+
// the pipes are let go. The leftover process is not the kernel's to end; the warning names it.
|
|
365
|
+
child.on("exit", (code, signal) => {
|
|
366
|
+
drain = setTimeout(() => {
|
|
367
|
+
if (settled) return;
|
|
368
|
+
warnings.push(`${hook.id} worktree hook: it exited, but a process it started still holds its output; that process was left running`);
|
|
369
|
+
child.stdout.destroy(); child.stderr.destroy();
|
|
370
|
+
finish(code, signal);
|
|
371
|
+
}, OUTPUT_DRAIN_MS);
|
|
372
|
+
});
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ---------- git facts about a tree and its clone ----------
|
|
377
|
+
|
|
378
|
+
const gitOut = (argv) => { try { return execFileSync("git", argv, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 30_000 }).trim(); } catch { return null; } };
|
|
379
|
+
|
|
380
|
+
/** The clone's `origin` URL, scrubbed (scrubRemoteUrl); "" when it has no `origin`. */
|
|
381
|
+
export function originRemoteOf(clone) {
|
|
382
|
+
const url = gitOut(["-C", clone, "remote", "get-url", "--end-of-options", "origin"]);
|
|
383
|
+
return url ? scrubRemoteUrl(url) : "";
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Whether `tree` (canonical) is still a directory whose Git toplevel is itself:
|
|
387
|
+
* the check after the hooks, which may remove or move it. */
|
|
388
|
+
export function treeStillThere(tree) {
|
|
389
|
+
const top = gitOut(["-C", tree, "rev-parse", "--path-format=absolute", "--show-toplevel"]);
|
|
390
|
+
if (!top) return false;
|
|
391
|
+
try { return realpathSync(top) === tree; } catch { return false; }
|
|
392
|
+
}
|