@awebai/oats 0.48.0 → 0.50.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 +326 -28
- package/docs/capabilities.md +425 -8
- package/docs/capability-manifest.schema.json +60 -5
- package/docs/configuration.md +103 -0
- package/docs/desktop-cli-api.md +542 -47
- package/docs/desktop.md +85 -5
- package/docs/execution-targets.md +50 -9
- package/docs/implementation.md +74 -1
- package/docs/integrations.md +7 -5
- package/docs/knowledge.md +167 -197
- package/docs/official-catalog.md +4 -4
- package/docs/packages.md +28 -14
- package/docs/release-lane.md +41 -0
- package/docs/release-notes/v0.49.0.md +770 -0
- package/docs/release-notes/v0.50.0.md +279 -0
- package/docs/schedules.md +289 -53
- package/docs/servers.md +7 -0
- package/docs/souls-and-instances.md +450 -60
- package/docs/workspaces.md +3 -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 +18 -2
- package/lib/core.mjs +1374 -394
- package/lib/instance-events.mjs +9 -10
- package/lib/instance-git.mjs +19 -10
- package/lib/instance-inspect.mjs +58 -18
- 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/refused-text.mjs +17 -0
- package/lib/resolve.mjs +4 -4
- package/lib/retained-after-retire.mjs +387 -0
- package/lib/retire-output.mjs +6 -1
- package/lib/schedule.mjs +9 -2
- package/lib/servers.mjs +32 -6
- package/lib/tree-copy.mjs +18 -7
- package/lib/trigger-sources.mjs +234 -0
- package/lib/triggers.mjs +705 -108
- package/lib/workspace.mjs +20 -5
- package/lib/worktree-hooks.mjs +392 -0
- package/lib/worktree.mjs +655 -0
- package/package-catalog.json +3 -3
- package/package.json +1 -1
- package/skills/oats-getting-started/SKILL.md +1 -1
package/lib/worktree.mjs
ADDED
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
/** `oats worktree add|remove` (#796): the extra trees an instance makes, created the
|
|
2
|
+
* way the work-mode briefing's raw-git recipe made them, plus the `worktree` event.
|
|
3
|
+
*
|
|
4
|
+
* A tree is `<home>/.work-<purpose>`. `add` runs, as argument vectors:
|
|
5
|
+
* git -C <clone> worktree add --detach <tree>
|
|
6
|
+
* git -C <tree> fetch --refmap= origin <base>
|
|
7
|
+
* git -C <tree> switch -c <branch> <fetched oid>
|
|
8
|
+
* so it moves no ref of the clone and starts from the remote's state, never the
|
|
9
|
+
* clone's checkout. Then it fires every composed capability's `worktree` hook
|
|
10
|
+
* (lib/worktree-hooks.mjs), records `<home>/.oats/trees/<purpose>.json` and appends
|
|
11
|
+
* a `worktree-added` event. To retirement the tree is like any raw-git extra tree.
|
|
12
|
+
*
|
|
13
|
+
* The record is the recovery marker. `creating` (with the adding process's pid and
|
|
14
|
+
* start time) until the tree is ready; a later `add` or `remove` that finds it with
|
|
15
|
+
* that process gone finishes the rollback first. `ready` makes `add` a no-op.
|
|
16
|
+
*
|
|
17
|
+
* Every user value is checked before any write (amendment A1): no leading `-`, a
|
|
18
|
+
* purpose in the instance-name grammar, the branch and base valid branch names; each
|
|
19
|
+
* is passed after `--end-of-options` where the git subcommand honours it. The
|
|
20
|
+
* remote URL is recorded, printed and handed to hooks without userinfo (A2). */
|
|
21
|
+
import { execFileSync, spawn as spawnChild, spawnSync } from "node:child_process";
|
|
22
|
+
import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
23
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
24
|
+
import { oatsError } from "./errors.mjs";
|
|
25
|
+
import { appendEvent } from "./instance-events.mjs";
|
|
26
|
+
import { recordedTeams } from "./teams.mjs";
|
|
27
|
+
import { canonicalCloneKey, memberCloneOf } from "./instance-resolution.mjs";
|
|
28
|
+
import { loadLocal } from "./workspace.mjs";
|
|
29
|
+
import { GIT_FETCH_TIMEOUT_MS } from "./remote.mjs";
|
|
30
|
+
import { randomBytes } from "node:crypto";
|
|
31
|
+
import { terminateGroup, watchGroup } from "./process-group.mjs";
|
|
32
|
+
import {
|
|
33
|
+
cloneOfMember, instanceSoulDir, isCapturedHome, isWorkspaceHome, capturedHomeRefusal, preWorkspaceHome, lifecycleHookEnv,
|
|
34
|
+
retirePendingMarkerPath, stableSoulId, workspaceOf,
|
|
35
|
+
} from "./core.mjs";
|
|
36
|
+
import {
|
|
37
|
+
endOwnGroupSync, interruptExitStatus, processStartToken, runWorktreeHooks, scrubRemoteUrl, selfIdentity, signalGuard, terminateRecordedGroup, treeStillThere,
|
|
38
|
+
processLiveness, unknownGroupNote, unverifiedGroupWarning, verifiedAlive, worktreeHooksOf,
|
|
39
|
+
} from "./worktree-hooks.mjs";
|
|
40
|
+
|
|
41
|
+
const PURPOSE_RE = /^[a-z0-9][a-z0-9-]*$/; // the instance-name grammar (lib/core.mjs INSTANCE_NAME_RE)
|
|
42
|
+
const PURPOSE_MAX = 64;
|
|
43
|
+
const RECORD_VERSION = 1;
|
|
44
|
+
|
|
45
|
+
/** The fetch's timeout: the kernel's (GIT_FETCH_TIMEOUT_MS, 10 minutes), or the test seam
|
|
46
|
+
* OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS (a positive integer of milliseconds; not a setting). */
|
|
47
|
+
export function worktreeFetchTimeoutMs(env = process.env) {
|
|
48
|
+
const seam = Number(env.OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS);
|
|
49
|
+
return Number.isSafeInteger(seam) && seam > 0 ? seam : GIT_FETCH_TIMEOUT_MS;
|
|
50
|
+
}
|
|
51
|
+
/** The git environment of every step: the invoker's, never prompting for credentials. */
|
|
52
|
+
const gitEnv = () => ({ ...process.env, GIT_TERMINAL_PROMPT: "0" });
|
|
53
|
+
/** Run git → { ok, out, err, status }. Never a shell. */
|
|
54
|
+
function git(argv, { timeout = 120_000 } = {}) {
|
|
55
|
+
const r = spawnSync("git", argv, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: gitEnv(), timeout, maxBuffer: 64 * 1024 * 1024 });
|
|
56
|
+
return { ok: r.status === 0 && !r.error, out: String(r.stdout ?? ""), err: String(r.stderr ?? "").trim() || r.error?.message || "", status: r.status };
|
|
57
|
+
}
|
|
58
|
+
/** Run a git step that changes something (a tree, a ref, the worktree list) as a recorded child:
|
|
59
|
+
* → Promise<{ ok, out, err, status }>. A parent killed outright does not take its git with it, and
|
|
60
|
+
* a recovery that went ahead while that git still ran could see it finish late, on the tree or
|
|
61
|
+
* branch the recovery just made. So the step starts in its own process group, held in
|
|
62
|
+
* `read` before git exists; `track({ gitPid, gitStart })` records it (in the purpose's claim or
|
|
63
|
+
* the tree record) and only then is it released to `exec git`. A parent killed before that
|
|
64
|
+
* closes the step's stdin, and git never runs. A recovery ends a recorded git that still runs
|
|
65
|
+
* (endRecordedGit) before it acts. `track(null)` clears it once git has exited and, after a
|
|
66
|
+
* timeout, once its whole group is verified gone; a group that survives SIGKILL rejects with
|
|
67
|
+
* E_LIFECYCLE_BUSY (`keepClaim`), leaving the identity recorded for the next command. Exported for its tests. */
|
|
68
|
+
export function trackedGit(argv, { track, timeout = 120_000 }) {
|
|
69
|
+
return new Promise((resolve, fail) => {
|
|
70
|
+
let child;
|
|
71
|
+
try {
|
|
72
|
+
child = spawnChild("/bin/sh", ["-c", 'read _ || exit 125; exec git "$@"', "oats-git", ...argv], { detached: true, stdio: ["pipe", "pipe", "pipe"], env: gitEnv() });
|
|
73
|
+
} catch (e) { resolve({ ok: false, out: "", err: `git could not be started: ${e.message}`, status: null }); return; }
|
|
74
|
+
watchGroup(child);
|
|
75
|
+
let out = "", err = "", tracked = false, timedOut = false, settled = false;
|
|
76
|
+
const done = (r) => { if (!settled) { settled = true; resolve(r); } };
|
|
77
|
+
child.stdout.on("data", (c) => { out += c; });
|
|
78
|
+
child.stderr.on("data", (c) => { err += c; });
|
|
79
|
+
child.stdin.on("error", () => { /* the step ended before reading */ });
|
|
80
|
+
child.on("error", (e) => done({ ok: false, out, err: `git could not be started: ${e.message}`, status: null }));
|
|
81
|
+
const gitStart = child.pid ? processStartToken(child.pid) : null;
|
|
82
|
+
let trackError = null;
|
|
83
|
+
if (gitStart) { try { track({ gitPid: child.pid, gitStart }); tracked = true; } catch (e) { trackError = e; } }
|
|
84
|
+
child.stdin.end(tracked ? "\n" : "");
|
|
85
|
+
const timer = setTimeout(() => { timedOut = true; terminateGroup(child); }, timeout);
|
|
86
|
+
child.on("close", (code, signal) => {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
// A timed-out step's group is ended for certain before its identity is cleared: terminateGroup's
|
|
89
|
+
// SIGKILL is an unref'd timer this process may exit before, and a member that ignores SIGTERM and
|
|
90
|
+
// holds no pipe would outlive it. One that survives SIGKILL keeps its identity recorded, and the
|
|
91
|
+
// command stops here (keepClaim: the claim holding it is not released).
|
|
92
|
+
if (timedOut && tracked && endOwnGroupSync(child.pid) === "survived") {
|
|
93
|
+
return fail(Object.assign(oatsError("E_LIFECYCLE_BUSY", `a git step that timed out could not be ended (process group ${child.pid} survived SIGKILL); it stays recorded, and nothing more was done — end that process, then retry`), { details: { gitPid: child.pid }, keepClaim: true }));
|
|
94
|
+
}
|
|
95
|
+
if (!tracked) return done({ ok: false, out: "", err: `the git step was not run: ${trackError ? `its process could not be recorded (${trackError.message})` : "its start time could not be read"}`, status: null });
|
|
96
|
+
try { track(null); } catch { /* the record or claim is gone: nothing left to clear */ }
|
|
97
|
+
done({ ok: code === 0, out, err: err.trim() || (timedOut ? `timed out after ${Math.round(timeout / 1000)} s` : signal ? `ended by ${signal}` : ""), status: code });
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** End the git step a dead holder recorded (`{ gitPid, gitStart }`), only when its leader runs with
|
|
103
|
+
* the recorded start time (terminateRecordedGroup): SIGTERM, which git answers by removing its lock
|
|
104
|
+
* files, then SIGKILL. → { owed?, remedy?, warning? }: `owed` stops the caller, which keeps `at` (the
|
|
105
|
+
* claim or record naming the step); `remedy` is the way out. A step whose leader's start cannot be
|
|
106
|
+
* read is owed, never a warning: it may still be that git, about to change the tree or the branch. */
|
|
107
|
+
function endRecordedGit(holder, at, otherwise = `remove ${at}`) {
|
|
108
|
+
if (!holder?.gitPid) return {};
|
|
109
|
+
const rec = { hookPgid: holder.gitPid, hookStart: holder.gitStart };
|
|
110
|
+
const ended = terminateRecordedGroup(rec);
|
|
111
|
+
if (ended === "survived") return { owed: `git process group ${holder.gitPid}, left running by a killed oats worktree command, survived SIGKILL`, remedy: "end that process, then retry" };
|
|
112
|
+
if (ended === "unknown") return { owed: unknownGroupNote(rec, "git"), remedy: unknownGroupRemedy(holder.gitPid, "git", otherwise) };
|
|
113
|
+
if (ended === "unverified") return { warning: unverifiedGroupWarning(holder.gitPid, "git") };
|
|
114
|
+
return {};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The way out of an "unknown" group: an existing one, by hand. */
|
|
118
|
+
const unknownGroupRemedy = (pgid, what, otherwise) =>
|
|
119
|
+
`check process group ${pgid} by hand: if it is that ${what}, end it (kill -TERM -- -${pgid}) and retry; if it is not, ${otherwise} and retry`;
|
|
120
|
+
|
|
121
|
+
/** What a record of an add whose state cannot be settled leaves to remove by hand. */
|
|
122
|
+
const leftoverRemedy = (recPath, tree, rec) =>
|
|
123
|
+
`remove ${recPath}, then what that add left (the tree ${tree}: git worktree remove --force ${tree}; the branch ${rec.branch}, if it holds nothing of yours)`;
|
|
124
|
+
|
|
125
|
+
const firstLine = (text) => String(text).split("\n").map((l) => l.trim()).find((l) => /^(fatal|error):/.test(l)) ?? String(text).split("\n").map((l) => l.trim()).find(Boolean) ?? "";
|
|
126
|
+
|
|
127
|
+
export const treeRecordPath = (home, purpose) => join(home, ".oats", "trees", `${purpose}.json`);
|
|
128
|
+
export const extraTreePath = (home, purpose) => join(home, `.work-${purpose}`);
|
|
129
|
+
|
|
130
|
+
// ---------- arguments ----------
|
|
131
|
+
|
|
132
|
+
function badArgs(message, details) { return Object.assign(oatsError("E_BAD_ARGS", message), details ? { details } : {}); }
|
|
133
|
+
|
|
134
|
+
/** A1: refuse what git could read as an option, and anything not a valid name, before any write. */
|
|
135
|
+
export function validateTreeArgs({ purpose, branch, base }, { forRemove = false } = {}) {
|
|
136
|
+
const check = (flag, value) => {
|
|
137
|
+
if (typeof value !== "string" || !value) throw badArgs(`--${flag} needs a value`);
|
|
138
|
+
if (value.startsWith("-")) throw badArgs(`--${flag} ${JSON.stringify(value)} starts with "-", which git would read as an option; nothing was done`, { flag: `--${flag}` });
|
|
139
|
+
};
|
|
140
|
+
check("purpose", purpose);
|
|
141
|
+
if (!PURPOSE_RE.test(purpose) || purpose.length > PURPOSE_MAX) throw badArgs(`--purpose ${JSON.stringify(purpose)} must be a slug: lowercase letters, digits and "-", starting with a letter or digit, at most ${PURPOSE_MAX} characters`, { flag: "--purpose" });
|
|
142
|
+
if (forRemove) return;
|
|
143
|
+
check("branch", branch);
|
|
144
|
+
check("base", base);
|
|
145
|
+
for (const [flag, value] of [["branch", branch], ["base", base]]) {
|
|
146
|
+
// `@{-N}` is a previous-branch shorthand check-ref-format --branch would expand: never a name here.
|
|
147
|
+
if (value.includes("@{")) throw badArgs(`--${flag} ${JSON.stringify(value)} is not a branch name`, { flag: `--${flag}` });
|
|
148
|
+
// check-ref-format honours no --end-of-options; the leading "-" refusal above is what keeps the value a value.
|
|
149
|
+
const r = git(["check-ref-format", "--branch", value]);
|
|
150
|
+
if (!r.ok) throw badArgs(`--${flag} ${JSON.stringify(value)} is not a valid branch name (git check-ref-format --branch)`, { flag: `--${flag}` });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ---------- the home ----------
|
|
155
|
+
|
|
156
|
+
/** The instance home `oats worktree` acts in, read and checked: a workspace-model home, not
|
|
157
|
+
* quarantined or being retired. → { home, meta }. */
|
|
158
|
+
export function readTreeHome(home) {
|
|
159
|
+
if (typeof home !== "string" || !isAbsolute(home)) throw badArgs("oats worktree runs from an instance home (in the home, or with $OATS_INSTANCE_HOME set to it)");
|
|
160
|
+
let meta;
|
|
161
|
+
try { meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); }
|
|
162
|
+
catch { throw badArgs(`${home} is not an instance home (no readable instance.json); oats worktree runs from an instance home`); }
|
|
163
|
+
if (isCapturedHome(meta)) throw capturedHomeRefusal(home, "no tree was made");
|
|
164
|
+
if (!isWorkspaceHome(meta)) throw preWorkspaceHome(home, "no tree was made");
|
|
165
|
+
if (existsSync(join(home, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${home} is a quarantined home (or a spawn still in progress); finish its retirement (oats retire) before making trees in it`);
|
|
166
|
+
if (existsSync(retirePendingMarkerPath(home))) throw oatsError("E_INSTANCE_RETIRING", `${basename(home)} is being retired; no tree was made`);
|
|
167
|
+
return { home, meta };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---------- the clone ----------
|
|
171
|
+
|
|
172
|
+
/** `--repo` → { clone (canonical, the main worktree or the bare repository), member (key or "") }.
|
|
173
|
+
* Default: the instance's repository. A key resolves through the kernel's clone lookup
|
|
174
|
+
* (oats-local.yaml clones:, then <deployment>/<member name>); a path through realpath. */
|
|
175
|
+
export function resolveTreeClone(meta, repo) {
|
|
176
|
+
let path, member = "";
|
|
177
|
+
if (repo === undefined) {
|
|
178
|
+
if (typeof meta.repo !== "string" || !meta.repo) throw oatsError("E_CLONE_MISSING", "this instance records no repository; pass --repo <member key|clone path>");
|
|
179
|
+
path = meta.repo;
|
|
180
|
+
const key = meta.workspace?.soul?.repoKey;
|
|
181
|
+
if (typeof key === "string" && key && cloneOfMember(path, key)) member = key;
|
|
182
|
+
} else if (isAbsolute(repo) || repo.startsWith(".") || repo.startsWith("~")) {
|
|
183
|
+
path = repo.startsWith("~") ? join(process.env.HOME ?? "", repo.slice(1)) : resolve(repo);
|
|
184
|
+
} else {
|
|
185
|
+
const key = canonicalCloneKey(repo);
|
|
186
|
+
const deployment = meta.workspace?.deployment;
|
|
187
|
+
if (typeof deployment !== "string" || !deployment) throw oatsError("E_CLONE_MISSING", `--repo ${repo}: this home records no deployment to look its clone up in; pass a clone path instead`);
|
|
188
|
+
let local = {};
|
|
189
|
+
try { local = loadLocal(deployment)?.local ?? {}; } catch (e) { throw Object.assign(oatsError(e.code || "E_CONFIG_BROKEN", e.message), { details: e.details }); }
|
|
190
|
+
const found = memberCloneOf(deployment, local, key);
|
|
191
|
+
if (!found.path) throw Object.assign(oatsError("E_CLONE_MISSING", `--repo ${repo}: this machine has no clone of ${key} — clone it to <deployment>/<member name> or name it in oats-local.yaml clones: { ${key}: <abs path> }; or pass a clone path`), { details: { repoKey: key, deployment } });
|
|
192
|
+
path = found.path;
|
|
193
|
+
member = key;
|
|
194
|
+
}
|
|
195
|
+
let real;
|
|
196
|
+
try { real = realpathSync(path); if (!statSync(real).isDirectory()) throw new Error("not a directory"); }
|
|
197
|
+
catch { throw Object.assign(oatsError("E_CLONE_MISSING", `${path} is not a Git repository (it does not exist or is not a directory); pass --repo <clone>`), { details: { path } }); }
|
|
198
|
+
const dirs = git(["-C", real, "rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir", "--is-bare-repository"]);
|
|
199
|
+
if (!dirs.ok) throw Object.assign(oatsError("E_CLONE_MISSING", `${real} is not a Git repository (${firstLine(dirs.err)})`), { details: { path: real } });
|
|
200
|
+
const [gitDir, commonDir, bare] = dirs.out.trim().split("\n");
|
|
201
|
+
if (realpathOr(gitDir) !== realpathOr(commonDir)) throw Object.assign(oatsError("E_CLONE_MISMATCH", `${real} is a linked worktree, not a clone; trees are added from the clone itself (its main worktree)`), { details: { path: real } });
|
|
202
|
+
let clone = realpathOr(commonDir);
|
|
203
|
+
if (bare !== "true") {
|
|
204
|
+
const top = git(["-C", real, "rev-parse", "--path-format=absolute", "--show-toplevel"]);
|
|
205
|
+
if (!top.ok) throw Object.assign(oatsError("E_CLONE_MISSING", `${real} is not a Git work tree (${firstLine(top.err)})`), { details: { path: real } });
|
|
206
|
+
clone = realpathOr(top.out.trim());
|
|
207
|
+
}
|
|
208
|
+
const origin = git(["-C", clone, "remote", "get-url", "--end-of-options", "origin"]);
|
|
209
|
+
if (!origin.ok || !origin.out.trim()) throw Object.assign(oatsError("E_CLONE_MISMATCH", `${clone} has no "origin" remote; a tree starts from origin's branch`), { details: { path: clone } });
|
|
210
|
+
return { clone, member, remote: scrubRemoteUrl(origin.out.trim()) };
|
|
211
|
+
}
|
|
212
|
+
const realpathOr = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
|
|
213
|
+
|
|
214
|
+
// ---------- the record ----------
|
|
215
|
+
|
|
216
|
+
function readRecord(path) {
|
|
217
|
+
if (!existsSync(path)) return null;
|
|
218
|
+
try {
|
|
219
|
+
const r = JSON.parse(readFileSync(path, "utf8"));
|
|
220
|
+
if (r && typeof r === "object" && ["creating", "ready"].includes(r.state)) return r;
|
|
221
|
+
} catch { /* below */ }
|
|
222
|
+
return { state: "unreadable" };
|
|
223
|
+
}
|
|
224
|
+
function writeRecord(path, rec) {
|
|
225
|
+
const tmp = `${path}.tmp-${process.pid}`;
|
|
226
|
+
writeFileSync(tmp, JSON.stringify(rec, null, 2) + "\n", { mode: 0o600 });
|
|
227
|
+
renameSync(tmp, path);
|
|
228
|
+
}
|
|
229
|
+
/** Create the record only if none exists (two concurrent adds: one wins, the other sees it). */
|
|
230
|
+
function createRecord(path, rec) {
|
|
231
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
232
|
+
const tmp = `${path}.tmp-${process.pid}`;
|
|
233
|
+
writeFileSync(tmp, JSON.stringify(rec, null, 2) + "\n", { mode: 0o600 });
|
|
234
|
+
try { linkSync(tmp, path); }
|
|
235
|
+
catch (e) { if (e.code === "EEXIST") throw oatsError("E_LIFECYCLE_BUSY", `another oats worktree add of purpose ${rec.purpose} started at the same moment; nothing was done`); throw e; }
|
|
236
|
+
finally { try { unlinkSync(tmp); } catch { /* gone */ } }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ---------- rollback ----------
|
|
240
|
+
|
|
241
|
+
/** Whether this add created its branch: the record says so (`branchCreated`, written as soon as
|
|
242
|
+
* `git switch -c` returned), or — for a kill in between — the tree itself is a worktree whose HEAD
|
|
243
|
+
* is that branch, which only this add's switch can have made it. A branch that matches `baseOid`
|
|
244
|
+
* proves nothing: another add may have created the same name at the same base. */
|
|
245
|
+
function addCreatedBranch(rec, tree) {
|
|
246
|
+
if (rec.branchCreated === true) return true;
|
|
247
|
+
if (!existsSync(tree)) return false;
|
|
248
|
+
const top = git(["-C", tree, "rev-parse", "--path-format=absolute", "--show-toplevel"]);
|
|
249
|
+
if (!top.ok || realpathOr(top.out.trim()) !== realpathOr(tree)) return false;
|
|
250
|
+
const head = git(["-C", tree, "symbolic-ref", "--quiet", "HEAD"]);
|
|
251
|
+
return head.ok && head.out.trim() === `refs/heads/${rec.branch}`;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Undo an add from its record: end a hook group a killed adder left (only when it is
|
|
255
|
+
* verifiably that group), remove the tree, prune, verify it is gone, delete the branch only
|
|
256
|
+
* when this add created it, nothing has it checked out and it still points where the add
|
|
257
|
+
* created it, and drop the record.
|
|
258
|
+
* Its own git steps are recorded through `track` (trackedGit): in the claim for a recovery, in the
|
|
259
|
+
* tree record for the adder's own rollback.
|
|
260
|
+
* → { owed, warnings, branchDeleted, branchKept, branchKeptReason? }: `owed` is [] when all of
|
|
261
|
+
* that is verified, else what is still owed (the record is then kept, so the next add or remove
|
|
262
|
+
* tries again); a branch kept on purpose is not owed. `branchKept`: the branch exists afterwards. */
|
|
263
|
+
export async function rollbackTree(home, rec, { track }) {
|
|
264
|
+
const owed = [], warnings = [];
|
|
265
|
+
const tree = extraTreePath(home, rec.purpose);
|
|
266
|
+
const otherwise = leftoverRemedy(treeRecordPath(home, rec.purpose), tree, rec);
|
|
267
|
+
if (rec.hookPgid) {
|
|
268
|
+
const ended = terminateRecordedGroup(rec);
|
|
269
|
+
if (ended === "survived") owed.push(`hook process group ${rec.hookPgid} survived SIGKILL`);
|
|
270
|
+
if (ended === "unverified") warnings.push(unverifiedGroupWarning(rec.hookPgid));
|
|
271
|
+
// A hook that may still run in the tree: nothing is touched, and the record is kept.
|
|
272
|
+
if (ended === "unknown") return { owed: [`${unknownGroupNote(rec)}; nothing was rolled back — ${unknownGroupRemedy(rec.hookPgid, "hook", otherwise)}`], warnings, branchDeleted: false };
|
|
273
|
+
}
|
|
274
|
+
// A git step the killed adder left running is ended before anything is touched; one that cannot be
|
|
275
|
+
// ended, or whose state cannot be read, stops the rollback, since it may still change the tree or the branch.
|
|
276
|
+
const git0 = endRecordedGit(rec, null, otherwise);
|
|
277
|
+
if (git0.warning) warnings.push(git0.warning);
|
|
278
|
+
if (git0.owed) return { owed: [`${git0.owed}; nothing was rolled back — ${git0.remedy}`], warnings, branchDeleted: false };
|
|
279
|
+
const ownsBranch = typeof rec.branch === "string" && rec.branch && addCreatedBranch(rec, tree);
|
|
280
|
+
const clone = rec.clone;
|
|
281
|
+
let registered = false, list = null;
|
|
282
|
+
if (typeof clone === "string" && clone) {
|
|
283
|
+
if (existsSync(tree)) await trackedGit(["-C", clone, "worktree", "remove", "--force", "--end-of-options", tree], { track });
|
|
284
|
+
await trackedGit(["-C", clone, "worktree", "prune"], { track });
|
|
285
|
+
list = git(["-C", clone, "worktree", "list", "--porcelain", "-z"]);
|
|
286
|
+
if (!list.ok) owed.push(`git worktree ${tree}: could not verify removal (${firstLine(list.err)})`);
|
|
287
|
+
else {
|
|
288
|
+
const treeReal = realpathOr(tree);
|
|
289
|
+
registered = worktreeFields(list.out, "worktree").map(realpathOr).includes(treeReal);
|
|
290
|
+
if (registered) owed.push(`git worktree ${tree}: still registered`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
// A directory left at the path while a `creating` record held it is this add's own (git worktree add
|
|
294
|
+
// made it, or failed half-way): never a symlink, which is not followed.
|
|
295
|
+
if (!registered) {
|
|
296
|
+
try { const st = lstatSync(tree); if (st.isDirectory()) rmSync(tree, { recursive: true, force: true }); } catch { /* not there */ }
|
|
297
|
+
if (existsSync(tree)) owed.push(`${tree}: still present`);
|
|
298
|
+
}
|
|
299
|
+
let branchDeleted = false, branchKept = false, branchKeptReason;
|
|
300
|
+
if (typeof rec.branch === "string" && rec.branch && typeof clone === "string" && clone) {
|
|
301
|
+
const ref = `refs/heads/${rec.branch}`;
|
|
302
|
+
const before = git(["-C", clone, "rev-parse", "--verify", "--quiet", "--end-of-options", ref]);
|
|
303
|
+
branchKept = true;
|
|
304
|
+
if (!before.ok && before.status === 1 && !before.err) branchKept = false; // never made, or already gone
|
|
305
|
+
else if (!before.ok) owed.push(`git branch ${rec.branch}: could not be read (${firstLine(before.err) || `exit ${before.status}`})`);
|
|
306
|
+
else if (!ownsBranch) branchKeptReason = "this add's creation of it is not proven (another add, or a kill inside git switch, may have made it)";
|
|
307
|
+
else if (typeof rec.baseOid !== "string" || !rec.baseOid) branchKeptReason = "the record names no base commit to compare it with";
|
|
308
|
+
else if (!list?.ok) branchKeptReason = "whether it is checked out could not be read";
|
|
309
|
+
else if (worktreeFields(list.out, "branch").includes(ref)) branchKeptReason = "it is checked out in a worktree";
|
|
310
|
+
else {
|
|
311
|
+
await trackedGit(["-C", clone, "update-ref", "-d", ref, rec.baseOid], { track });
|
|
312
|
+
const left = git(["-C", clone, "rev-parse", "--verify", "--quiet", "--end-of-options", ref]);
|
|
313
|
+
if (!left.ok && left.status === 1 && !left.err) { branchDeleted = true; branchKept = false; }
|
|
314
|
+
else if (!left.ok) owed.push(`git branch ${rec.branch}: could not verify deletion (${firstLine(left.err) || `exit ${left.status}`})`);
|
|
315
|
+
else if (left.out.trim() !== rec.baseOid) branchKeptReason = `its tip moved from ${rec.baseOid.slice(0, 12)}, where this add created it`;
|
|
316
|
+
else owed.push(`git branch ${rec.branch}: still exists`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (!owed.length) rmSync(treeRecordPath(home, rec.purpose), { force: true });
|
|
320
|
+
return { owed, warnings, branchDeleted, branchKept, ...(branchKept && branchKeptReason ? { branchKeptReason } : {}) };
|
|
321
|
+
}
|
|
322
|
+
/** The values of one field (`worktree`, `branch`) across `git worktree list --porcelain -z`. */
|
|
323
|
+
const worktreeFields = (out, field) => out.split("\0").filter((f) => f.startsWith(`${field} `)).map((f) => f.slice(field.length + 1));
|
|
324
|
+
|
|
325
|
+
// ---------- the claim ----------
|
|
326
|
+
|
|
327
|
+
/** Run `fn` holding the purpose's claim (`<home>/.oats/trees/<purpose>.lock`): every read of a
|
|
328
|
+
* record that may lead to recovering it, every rollback a recovery does, every record an add
|
|
329
|
+
* creates and every removal happens under it, so two recoveries never act on the same snapshot
|
|
330
|
+
* and a recovery never acts on a tree made after it read. A live adder's own record is left to it
|
|
331
|
+
* (others refuse it as busy), so the claim is not held while hooks run.
|
|
332
|
+
*
|
|
333
|
+
* Unlike lib/dir-lock.mjs, a claim left by a process that died (SIGKILL in the middle of a
|
|
334
|
+
* recovery) is taken over, so a killed command can always be run again: the owner is named by
|
|
335
|
+
* pid AND start time (processLiveness), never by a pid alone, and a holder whose start cannot be
|
|
336
|
+
* read is never taken for gone. A claim held by a live process is
|
|
337
|
+
* waited for up to `CLAIM_WAIT_MS`, then refused as E_LIFECYCLE_BUSY. The holder's git steps
|
|
338
|
+
* are recorded in the claim (trackedGit), and a takeover ends one still running first: a dead
|
|
339
|
+
* holder's git never finishes late on a tree made after the takeover.
|
|
340
|
+
* `fn({ track, warnings })`; → Promise of what `fn` returns. */
|
|
341
|
+
function withPurposeClaim(home, purpose, fn) {
|
|
342
|
+
const dir = join(home, ".oats", "trees");
|
|
343
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
344
|
+
const lock = join(dir, `${purpose}.lock`);
|
|
345
|
+
const busy = (holder, unknown, at = lock) => Object.assign(oatsError("E_LIFECYCLE_BUSY", unknown
|
|
346
|
+
? `whether pid ${holder?.pid ?? "?"} (recorded start ${holder?.processStart ?? "none"}), which holds ${at}, still runs cannot be read (${unknown}); nothing was done — check that pid by hand, and if it is not an oats worktree command, remove ${at}, then retry`
|
|
347
|
+
: `another oats worktree add or remove of purpose ${purpose} is running (pid ${holder?.pid ?? "?"} holds ${at}); nothing was done — retry when it has finished`), { details: { purpose, lock: at, ...(holder?.pid ? { pid: holder.pid } : {}), ...(unknown ? { unknown } : {}) } });
|
|
348
|
+
return withClaim(lock, fn, { busy });
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const CLAIM_WAIT_MS = 3000;
|
|
352
|
+
const CLAIM_MAX_DEPTH = 8;
|
|
353
|
+
const pauseSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
354
|
+
function readClaim(path) {
|
|
355
|
+
try { const o = JSON.parse(readFileSync(path, "utf8")); return o && typeof o === "object" ? o : { unreadable: true }; }
|
|
356
|
+
catch (e) { return e.code === "ENOENT" ? null : { unreadable: true }; }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Run `fn` holding the claim file `path`. Exported for its tests.
|
|
360
|
+
*
|
|
361
|
+
* - Taking it: the owner's facts `{ pid, processStart, nonce }` are written to a private file and
|
|
362
|
+
* hard-linked to `path`, which fails if `path` exists. So a claim is never seen without its
|
|
363
|
+
* owner, and the nonce makes each holding distinct, even for the same process.
|
|
364
|
+
* - Its owner is gone (processLiveness "gone"; "unknown" is refused, never taken over): the claim
|
|
365
|
+
* is removed under a second claim,
|
|
366
|
+
* `<path>.reclaim-<owner nonce>`, taken by this same protocol. Its holder re-reads `path` and
|
|
367
|
+
* removes it only if it still names that owner. Nothing else removes another's claim: its
|
|
368
|
+
* owner never releases it, and a new acquirer cannot write over an existing file. Two takeovers
|
|
369
|
+
* of one dead owner are therefore serialized, and neither removes a claim made after it read.
|
|
370
|
+
* A takeover cut short leaves its own claim behind, which the next takeover takes over in
|
|
371
|
+
* turn, up to CLAIM_MAX_DEPTH nested levels.
|
|
372
|
+
* - The holder's running git step (`gitPid`, `gitStart`; trackedGit) is in the claim. A takeover
|
|
373
|
+
* ends it first (endRecordedGit) and refuses, keeping the claim, if it cannot be ended.
|
|
374
|
+
* - Released by unlinking `path`, only while it still names this holding.
|
|
375
|
+
* - An unreadable claim file is never removed: the command is refused as busy, naming the file. */
|
|
376
|
+
export async function withClaim(path, fn, { busy, waitMs = CLAIM_WAIT_MS } = {}) {
|
|
377
|
+
const warnings = [];
|
|
378
|
+
const me = acquireClaim(path, { busy, waitMs, warnings }, 0);
|
|
379
|
+
// Record (or clear) the holder's running git step in the claim; only its live holder writes it.
|
|
380
|
+
const track = (gitStep) => {
|
|
381
|
+
const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
|
|
382
|
+
writeFileSync(tmp, JSON.stringify({ ...me, ...(gitStep ?? {}) }) + "\n", { mode: 0o600 });
|
|
383
|
+
renameSync(tmp, path);
|
|
384
|
+
};
|
|
385
|
+
let keep = false;
|
|
386
|
+
try { return await fn({ track, warnings }); }
|
|
387
|
+
catch (e) { keep = e?.keepClaim === true; throw e; }
|
|
388
|
+
finally { if (!keep) releaseClaim(path, me); }
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function acquireClaim(path, opts, depth) {
|
|
392
|
+
const { busy, waitMs } = opts;
|
|
393
|
+
const self = selfIdentity();
|
|
394
|
+
if (!self.processStart) throw Object.assign(busy(null), { message: `this process's start time cannot be read, so it cannot hold ${path} verifiably; nothing was done` });
|
|
395
|
+
const me = { ...self, nonce: randomBytes(16).toString("hex"), at: new Date().toISOString() };
|
|
396
|
+
const tmp = `${path}.tmp-${process.pid}-${me.nonce}`;
|
|
397
|
+
writeFileSync(tmp, JSON.stringify(me) + "\n", { mode: 0o600 });
|
|
398
|
+
try {
|
|
399
|
+
const deadline = Date.now() + waitMs;
|
|
400
|
+
for (;;) {
|
|
401
|
+
try { linkSync(tmp, path); return me; }
|
|
402
|
+
catch (e) { if (e.code !== "EEXIST") throw e; }
|
|
403
|
+
const holder = readClaim(path);
|
|
404
|
+
if (holder === null) continue; // released in between
|
|
405
|
+
if (holder.unreadable) throw Object.assign(busy(null), { message: `${path} is not a readable claim; inspect it and remove it if no oats worktree command holds it; nothing was done` });
|
|
406
|
+
const live = processLiveness(holder);
|
|
407
|
+
// Unreadable is never taken for gone: the claim is kept, and the refusal names the way out.
|
|
408
|
+
if (live.state === "unknown") throw busy(holder, live.reason, path);
|
|
409
|
+
if (live.state === "gone") {
|
|
410
|
+
if (depth >= CLAIM_MAX_DEPTH || typeof holder.nonce !== "string" || !/^[0-9a-f]{32}$/.test(holder.nonce)) throw busy(holder, null, path);
|
|
411
|
+
takeOver(path, holder, opts, depth);
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
if (Date.now() >= deadline) throw busy(holder, null, path);
|
|
415
|
+
pauseSync(50);
|
|
416
|
+
}
|
|
417
|
+
} finally {
|
|
418
|
+
try { unlinkSync(tmp); } catch { /* gone */ }
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Remove `path`, held by the dead `holder`, under the claim that serializes takeovers of it. */
|
|
423
|
+
function takeOver(path, holder, opts, depth) {
|
|
424
|
+
const reclaim = `${path}.reclaim-${holder.nonce}`;
|
|
425
|
+
const me = acquireClaim(reclaim, opts, depth + 1);
|
|
426
|
+
try {
|
|
427
|
+
const now = readClaim(path);
|
|
428
|
+
if (now?.nonce === holder.nonce) {
|
|
429
|
+
const ended = endRecordedGit(now, path);
|
|
430
|
+
if (ended.owed) {
|
|
431
|
+
const e = opts.busy(now);
|
|
432
|
+
throw Object.assign(e, { message: `${ended.owed}; ${path} is kept and nothing was done — ${ended.remedy}`, details: { ...e.details, gitPid: now.gitPid, gitStart: now.gitStart ?? null } });
|
|
433
|
+
}
|
|
434
|
+
if (ended.warning) opts.warnings?.push(ended.warning);
|
|
435
|
+
unlinkSync(path);
|
|
436
|
+
}
|
|
437
|
+
} finally {
|
|
438
|
+
releaseClaim(reclaim, me);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function releaseClaim(path, me) {
|
|
443
|
+
if (readClaim(path)?.nonce === me.nonce) { try { unlinkSync(path); } catch { /* gone */ } }
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** A `creating` record whose adder may still run: its start cannot be read. Never rolled back on
|
|
447
|
+
* that; the refusal names the pid and the record's exact path, the way out once the pid is
|
|
448
|
+
* checked by hand. */
|
|
449
|
+
function unknownAdderRefusal({ purpose, tree, recPath, rec, reason }) {
|
|
450
|
+
return Object.assign(oatsError("E_LIFECYCLE_BUSY", `whether the oats worktree add of purpose ${purpose} (pid ${rec.pid}, recorded start ${rec.processStart ?? "none"}) still runs cannot be read (${reason}); nothing was done — check that pid by hand, and if it is not an oats worktree add, ${leftoverRemedy(recPath, tree, rec)} and retry`), { details: { purpose, path: tree, record: recPath, pid: rec.pid, unknown: reason } });
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ---------- add ----------
|
|
454
|
+
|
|
455
|
+
/** The hook context of a home, as its other lifecycle hooks get it. */
|
|
456
|
+
function hookContext(home, meta) {
|
|
457
|
+
const root = dirname(dirname(dirname(home)));
|
|
458
|
+
const ws = meta.workspace && typeof meta.workspace === "object" ? meta.workspace : {};
|
|
459
|
+
const t = recordedTeams(meta);
|
|
460
|
+
const soulDir = instanceSoulDir(home, meta);
|
|
461
|
+
return {
|
|
462
|
+
home, instance: meta.instance ?? basename(home), agentName: meta.agent, soulDir,
|
|
463
|
+
soulId: stableSoulId({ home, soulDir, agentName: meta.agent }), contextDir: meta.repo ?? "", workspaceDir: workspaceOf(root), rootDir: root,
|
|
464
|
+
resolved: { workspace: { key: ws.key, name: ws.name, deployment: ws.deployment }, teams: t.teams, defaultTeam: t.defaultTeam, teamsSource: "recorded" },
|
|
465
|
+
priorMeta: meta.capabilityMeta && typeof meta.capabilityMeta === "object" ? meta.capabilityMeta : {},
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const sameRecordFields = (rec, want) => ["clone", "branch", "base"].filter((k) => rec[k] !== want[k]);
|
|
470
|
+
const publicReceipt = (rec, extra = {}) => ({
|
|
471
|
+
purpose: rec.purpose, path: rec.path, clone: rec.clone, remote: rec.remote, member: rec.member || null, branch: rec.branch, base: rec.base,
|
|
472
|
+
baseOid: rec.baseOid ?? null, state: rec.state, hooks: rec.hooks ?? [], ...(rec.treeMissing ? { treeMissing: true } : {}), record: extra.record, ...extra,
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
/** `oats worktree add`. `o`: { purpose, branch, base, repo?, preview?, stream? }.
|
|
476
|
+
* → the receipt ({ ..., resumed }) or, with preview, the plan. Throws typed errors. */
|
|
477
|
+
export async function worktreeAdd(homeArg, o = {}) {
|
|
478
|
+
validateTreeArgs(o);
|
|
479
|
+
const { home, meta } = readTreeHome(homeArg);
|
|
480
|
+
const { purpose, branch, base } = o;
|
|
481
|
+
const recPath = treeRecordPath(home, purpose);
|
|
482
|
+
const tree = extraTreePath(home, purpose);
|
|
483
|
+
const { clone, member, remote } = resolveTreeClone(meta, o.repo);
|
|
484
|
+
const hooks = worktreeHooksOf(meta.capabilityRuntime);
|
|
485
|
+
const want = { clone, branch, base };
|
|
486
|
+
const unknownAdder = (found, reason) => unknownAdderRefusal({ purpose, tree, recPath, rec: found, reason });
|
|
487
|
+
// What the record says, read under the claim when this add acts on it (the preview only reads).
|
|
488
|
+
const decide = () => {
|
|
489
|
+
const found = readRecord(recPath);
|
|
490
|
+
if (found?.state === "unreadable") throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${recPath} is not a readable tree record; inspect it (and the tree at ${tree}), remove what is not yours, then retry`), { details: { purpose, path: tree, record: recPath } });
|
|
491
|
+
if (found?.state === "creating") {
|
|
492
|
+
const live = processLiveness(found);
|
|
493
|
+
if (live.state === "alive") throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `an oats worktree add of purpose ${purpose} is still running (pid ${found.pid}, since ${found.startedAt}); nothing was done`), { details: { purpose, path: tree, pid: found.pid } });
|
|
494
|
+
if (live.state === "unknown") throw unknownAdder(found, live.reason);
|
|
495
|
+
return { recover: found };
|
|
496
|
+
}
|
|
497
|
+
if (found?.state === "ready") {
|
|
498
|
+
const differ = sameRecordFields(found, want);
|
|
499
|
+
if (differ.length) throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `the tree of purpose ${purpose} exists with a different ${differ.join(", ")} (${differ.map((k) => `${k}: ${found[k]}, asked ${want[k]}`).join("; ")}); use another --purpose, or \`oats worktree remove --purpose ${purpose}\` first`), { details: { purpose, path: tree, differ, record: recPath } });
|
|
500
|
+
return { ready: found };
|
|
501
|
+
}
|
|
502
|
+
checkFresh();
|
|
503
|
+
return {};
|
|
504
|
+
};
|
|
505
|
+
// A fresh add: the path is free and the branch does not exist.
|
|
506
|
+
const checkFresh = (after = "") => {
|
|
507
|
+
let st; try { st = lstatSync(tree); } catch { /* free */ }
|
|
508
|
+
if (st) throw Object.assign(oatsError("E_PLACEMENT_TAKEN", after ? `${tree} is still there ${after}; remove it yourself, then retry`
|
|
509
|
+
: st.isSymbolicLink() || !st.isDirectory()
|
|
510
|
+
? `${tree} exists and is ${st.isSymbolicLink() ? "a symbolic link" : "not a directory"}; it is never followed or replaced — use another --purpose`
|
|
511
|
+
: `${tree} exists and no oats worktree add made it (no record); use another --purpose, or remove that tree yourself (git worktree remove ${tree})`), { details: { purpose, path: tree } });
|
|
512
|
+
const exists = git(["-C", clone, "rev-parse", "--verify", "--quiet", "--end-of-options", `refs/heads/${branch}`]);
|
|
513
|
+
if (exists.ok) throw Object.assign(oatsError("E_BRANCH_EXISTS", `branch ${branch} already exists in ${clone}; a tree never reuses or resets a branch — name another, e.g. ${meta.instance ?? basename(home)}/${branch}`), { details: { branch, clone, remedy: `${meta.instance ?? basename(home)}/${branch}` } });
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
if (o.preview) {
|
|
517
|
+
const d = decide();
|
|
518
|
+
if (d.ready) return { preview: true, ...publicReceipt(d.ready, { record: recPath }), resume: "noop", hooksToRun: [] };
|
|
519
|
+
return { preview: true, purpose, path: tree, clone, remote, member: member || null, branch, base, record: recPath, resume: d.recover ? "recover" : null,
|
|
520
|
+
hooks: hooks.map((h) => ({ capability: h.id, required: h.required })) };
|
|
521
|
+
}
|
|
522
|
+
let rec;
|
|
523
|
+
const claimed = await withPurposeClaim(home, purpose, async ({ track, warnings: claimWarnings }) => {
|
|
524
|
+
const d = decide();
|
|
525
|
+
if (d.ready) return publicReceipt(d.ready, { record: recPath, resumed: true, warnings: existsSync(tree) ? [] : [`the recorded tree ${tree} is no longer there; \`oats worktree remove --purpose ${purpose}\` drops the record`] });
|
|
526
|
+
const recoveryWarnings = [...claimWarnings];
|
|
527
|
+
if (d.recover) {
|
|
528
|
+
const rb = await rollbackTree(home, d.recover, { track });
|
|
529
|
+
recoveryWarnings.push(...rb.warnings);
|
|
530
|
+
if (rb.owed.length) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `an earlier oats worktree add of purpose ${purpose} was interrupted and its rollback could not be completed: ${rb.owed.join("; ")}; nothing new was done`), { details: { purpose, path: tree, owed: rb.owed, ...(rb.warnings.length ? { warnings: rb.warnings } : {}) } });
|
|
531
|
+
checkFresh("after the rollback of an interrupted add");
|
|
532
|
+
}
|
|
533
|
+
rec = { version: RECORD_VERSION, purpose, state: "creating", path: tree, clone, remote, member, branch, base, ...selfIdentity(), startedAt: new Date().toISOString() };
|
|
534
|
+
createRecord(recPath, rec);
|
|
535
|
+
return { recoveryWarnings };
|
|
536
|
+
});
|
|
537
|
+
if (!claimed.recoveryWarnings) return claimed;
|
|
538
|
+
const { recoveryWarnings } = claimed;
|
|
539
|
+
// This add's own git steps are recorded in its record (trackedGit), for a recovery after a SIGKILL.
|
|
540
|
+
const track = (gitStep) => {
|
|
541
|
+
const { gitPid: _gp, gitStart: _gs, ...rest } = rec;
|
|
542
|
+
rec = gitStep ? { ...rest, ...gitStep } : rest;
|
|
543
|
+
writeRecord(recPath, rec);
|
|
544
|
+
};
|
|
545
|
+
const fail = async (code, message, details = {}) => {
|
|
546
|
+
const rb = await rollbackTree(home, rec, { track });
|
|
547
|
+
const kept = rb.branchKept ? `; branch ${branch} kept${rb.branchKeptReason ? ` (${rb.branchKeptReason})` : ""}` : "";
|
|
548
|
+
const note = rb.owed.length ? ` — rollback INCOMPLETE (${rb.owed.join("; ")}); the record ${recPath} is kept, and the next oats worktree add or remove of this purpose finishes it` : ` — the tree was removed${kept}`;
|
|
549
|
+
const warned = [...recoveryWarnings, ...rb.warnings];
|
|
550
|
+
return Object.assign(oatsError(code, `${message}${note}`), { details: { purpose, path: tree, rolledBack: rb.owed.length === 0, branchKept: rb.branchKept, ...(rb.branchKeptReason ? { branchKeptReason: rb.branchKeptReason } : {}), ...(rb.owed.length ? { owed: rb.owed } : {}), ...(warned.length ? { warnings: warned } : {}), ...details } });
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
const add = await trackedGit(["-C", clone, "worktree", "add", "--detach", "--end-of-options", tree], { track });
|
|
554
|
+
if (!add.ok) throw await fail("E_GIT_FAILED", `git worktree add failed in ${clone}: ${firstLine(add.err) || "unknown error"}`);
|
|
555
|
+
const treeReal = realpathOr(tree);
|
|
556
|
+
const fetch = await trackedGit(["-C", tree, "fetch", "--refmap=", "--end-of-options", "origin", base], { track, timeout: worktreeFetchTimeoutMs() });
|
|
557
|
+
if (!fetch.ok) throw await fail("E_REMOTE_UNREADABLE", `cannot fetch ${base} from origin (${remote}): ${firstLine(fetch.err) || "timeout"}`, { base, remote });
|
|
558
|
+
const fetched = git(["-C", tree, "rev-parse", "--verify", "--quiet", "FETCH_HEAD^{commit}"]);
|
|
559
|
+
const oid = fetched.out.trim();
|
|
560
|
+
if (!fetched.ok || !/^[0-9a-f]{40,64}$/.test(oid)) throw await fail("E_BASE_UNKNOWN", `the fetch of ${base} from origin left no commit in FETCH_HEAD`, { base });
|
|
561
|
+
rec = { ...rec, baseOid: oid };
|
|
562
|
+
writeRecord(recPath, rec); // before the branch exists: a rollback deletes it only at this oid, and only if this add made it
|
|
563
|
+
const sw = await trackedGit(["-C", tree, "switch", "--no-guess", "-c", branch, "--end-of-options", oid], { track });
|
|
564
|
+
if (!sw.ok) {
|
|
565
|
+
// Another add created the branch first (the precheck passed for both): that is E_BRANCH_EXISTS; any other failure is git's.
|
|
566
|
+
const taken = git(["-C", clone, "rev-parse", "--verify", "--quiet", "--end-of-options", `refs/heads/${branch}`]).ok;
|
|
567
|
+
if (taken) throw await fail("E_BRANCH_EXISTS", `git switch -c ${branch} failed: ${firstLine(sw.err)}`, { branch });
|
|
568
|
+
throw await fail("E_GIT_FAILED", `git switch failed in ${tree}: ${firstLine(sw.err) || "unknown error"}`, { branch });
|
|
569
|
+
}
|
|
570
|
+
rec = { ...rec, branchCreated: true };
|
|
571
|
+
writeRecord(recPath, rec); // a kill before this line is covered by the tree's own HEAD (addCreatedBranch)
|
|
572
|
+
const head = git(["-C", tree, "rev-parse", "--verify", "HEAD"]).out.trim();
|
|
573
|
+
if (head !== oid) throw await fail("E_BASE_UNKNOWN", `HEAD of the new tree is ${head || "unreadable"}, not the fetched commit ${oid} of ${base}`, { base, head: head || null, fetched: oid });
|
|
574
|
+
|
|
575
|
+
const env = { OATS_TREE: treeReal, OATS_TREE_CLONE: clone, OATS_TREE_REMOTE: remote, OATS_TREE_MEMBER: member, OATS_BRANCH: branch, OATS_TREE_BASE: base, OATS_TREE_BASE_OID: oid, OATS_PURPOSE: purpose, OATS_TREE_ORIGIN: "add" };
|
|
576
|
+
const ctx = hookContext(home, meta);
|
|
577
|
+
const warnings = [...recoveryWarnings];
|
|
578
|
+
let run = { receipt: [], failures: [], warnings: [], interrupted: null };
|
|
579
|
+
if (hooks.length) {
|
|
580
|
+
const guard = signalGuard();
|
|
581
|
+
try {
|
|
582
|
+
run = await runWorktreeHooks(hooks, {
|
|
583
|
+
envFor: (cap) => lifecycleHookEnv("worktree", cap, { ...ctx, extraEnv: env }),
|
|
584
|
+
cwd: treeReal, home, purpose, stream: o.stream !== false, guard,
|
|
585
|
+
onStart: ({ pgid, hookStart }) => { rec = { ...rec, hookPgid: pgid, hookStart }; writeRecord(recPath, rec); },
|
|
586
|
+
});
|
|
587
|
+
warnings.push(...run.warnings);
|
|
588
|
+
if (run.interrupted) {
|
|
589
|
+
throw Object.assign(await fail("E_INTERRUPTED", `oats worktree add was interrupted by ${run.interrupted} while the worktree hooks ran; the running hook's process group was ended`, { signal: run.interrupted, hooks: run.receipt }), { exitStatus: interruptExitStatus(run.interrupted) });
|
|
590
|
+
}
|
|
591
|
+
let treeMissing = false;
|
|
592
|
+
if (!treeStillThere(treeReal)) {
|
|
593
|
+
const msg = `the tree ${treeReal} is no longer there (or no longer a worktree) after the worktree hooks ran`;
|
|
594
|
+
if (hooks.some((h) => h.required)) run.failures.push({ capability: "oats.kernel", event: "worktree", message: msg, required: true });
|
|
595
|
+
else { warnings.push(msg); treeMissing = true; }
|
|
596
|
+
}
|
|
597
|
+
const required = run.failures.filter((f) => f.required);
|
|
598
|
+
const logOf = (id) => run.receipt.find((r) => r.capability === id)?.log;
|
|
599
|
+
for (const f of run.failures.filter((x) => !x.required)) warnings.push(`${f.capability} worktree hook failed (the tree is kept): ${f.message}${logOf(f.capability) ? ` (log: ${logOf(f.capability)})` : ""}`);
|
|
600
|
+
if (required.length) {
|
|
601
|
+
const detail = required.map((f) => `${f.capability}: ${f.message}${logOf(f.capability) ? ` (log: ${logOf(f.capability)})` : ""}`).join("; ");
|
|
602
|
+
throw await fail(required.some((f) => f.contract === "environment") ? "E_HOOK_ENVIRONMENT_CONTRACT" : "E_REQUIRED_HOOK_FAILED", `a required worktree hook failed: ${detail}`, { hooks: run.receipt });
|
|
603
|
+
}
|
|
604
|
+
if (treeMissing) rec = { ...rec, treeMissing: true };
|
|
605
|
+
} finally {
|
|
606
|
+
guard.restore();
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
const { pid: _pid, processStart: _ps, hookPgid: _pg, hookStart: _hs, branchCreated: _bc, gitPid: _gp, gitStart: _gs, ...kept } = rec;
|
|
610
|
+
rec = { ...kept, state: "ready", hooks: run.receipt, readyAt: new Date().toISOString() };
|
|
611
|
+
writeRecord(recPath, rec);
|
|
612
|
+
appendEvent(home, { kind: "worktree-added", data: { purpose, path: tree, branch, base, baseOid: oid, remote, member: member || null, hooks: run.receipt } });
|
|
613
|
+
return publicReceipt(rec, { record: recPath, resumed: false, warnings });
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// ---------- remove ----------
|
|
617
|
+
|
|
618
|
+
/** `oats worktree remove --purpose <p>`: `git worktree remove` (which refuses a dirty tree),
|
|
619
|
+
* the branch kept, no hook, the record dropped. A `creating` record whose adder is gone is
|
|
620
|
+
* rolled back instead. Only recorded trees: a hand-made one is git's to remove. */
|
|
621
|
+
export async function worktreeRemove(homeArg, o = {}) {
|
|
622
|
+
validateTreeArgs(o, { forRemove: true });
|
|
623
|
+
const home = homeArg;
|
|
624
|
+
if (typeof home !== "string" || !isAbsolute(home) || !existsSync(join(home, "instance.json"))) throw badArgs("oats worktree runs from an instance home (in the home, or with $OATS_INSTANCE_HOME set to it)");
|
|
625
|
+
const { purpose } = o;
|
|
626
|
+
const recPath = treeRecordPath(home, purpose);
|
|
627
|
+
const tree = extraTreePath(home, purpose);
|
|
628
|
+
return withPurposeClaim(home, purpose, async ({ track, warnings: claimWarnings }) => {
|
|
629
|
+
const rec = readRecord(recPath);
|
|
630
|
+
if (!rec) throw badArgs(`no tree of purpose ${purpose} was made by oats worktree add in this home (no ${recPath})${existsSync(tree) ? `; to remove a tree made another way: git worktree remove ${tree}` : ""}`, { purpose, path: tree });
|
|
631
|
+
if (rec.state === "unreadable") throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${recPath} is not a readable tree record; inspect it and the tree at ${tree}`), { details: { purpose, path: tree, record: recPath } });
|
|
632
|
+
if (rec.state === "creating") {
|
|
633
|
+
const live = processLiveness(rec);
|
|
634
|
+
if (live.state === "alive") throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `an oats worktree add of purpose ${purpose} is still running (pid ${rec.pid}); nothing was removed`), { details: { purpose, path: tree, pid: rec.pid } });
|
|
635
|
+
if (live.state === "unknown") throw unknownAdderRefusal({ purpose, tree, recPath, rec, reason: live.reason });
|
|
636
|
+
const rb = await rollbackTree(home, rec, { track });
|
|
637
|
+
const warned = [...claimWarnings, ...rb.warnings];
|
|
638
|
+
if (rb.owed.length) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `the rollback of an interrupted add of purpose ${purpose} could not be completed: ${rb.owed.join("; ")}`), { details: { purpose, path: tree, owed: rb.owed, ...(warned.length ? { warnings: warned } : {}) } });
|
|
639
|
+
return { purpose, path: tree, removed: true, rolledBack: true, branch: rec.branch, branchKept: rb.branchKept, ...(rb.branchKeptReason ? { branchKeptReason: rb.branchKeptReason } : {}), ...(warned.length ? { warnings: warned } : {}) };
|
|
640
|
+
}
|
|
641
|
+
const clone = rec.clone;
|
|
642
|
+
if (existsSync(tree)) {
|
|
643
|
+
const status = git(["-C", tree, "status", "--porcelain", "--ignore-submodules=none"]);
|
|
644
|
+
const r = await trackedGit(["-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
|
|
645
|
+
if (!r.ok) {
|
|
646
|
+
if (status.ok && status.out.trim()) throw Object.assign(oatsError("E_WORKTREE_DIRTY", `git refused to remove ${tree}: ${firstLine(r.err)}; commit and push its changes, or discard them, then retry (the record is kept)`), { details: { purpose, path: tree, git: r.err } });
|
|
647
|
+
throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `git refused to remove ${tree}: ${firstLine(r.err)}; nothing was removed (the record is kept)`), { details: { purpose, path: tree, git: r.err } });
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
await trackedGit(["-C", clone, "worktree", "prune"], { track });
|
|
651
|
+
if (existsSync(tree)) throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `${tree} is still there after git worktree remove; the record is kept`), { details: { purpose, path: tree } });
|
|
652
|
+
rmSync(recPath, { force: true });
|
|
653
|
+
return { purpose, path: tree, removed: true, rolledBack: false, branch: rec.branch, branchKept: true, ...(claimWarnings.length ? { warnings: claimWarnings } : {}) };
|
|
654
|
+
});
|
|
655
|
+
}
|