@hy-sde-org/dsh-git 0.1.1-rc.2 → 0.1.2-rc.1
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/LICENSE +4 -5
- package/README.md +13 -3
- package/dist/conventional/commit-types-data.d.ts +23 -0
- package/dist/conventional/commit-types-data.d.ts.map +1 -0
- package/dist/conventional/commit-types-data.js +437 -0
- package/dist/conventional/commit-types-data.js.map +1 -0
- package/dist/conventional/commit-types.d.ts +63 -0
- package/dist/conventional/commit-types.d.ts.map +1 -0
- package/dist/conventional/commit-types.js +236 -0
- package/dist/conventional/commit-types.js.map +1 -0
- package/dist/conventional/index.d.ts +19 -0
- package/dist/conventional/index.d.ts.map +1 -0
- package/dist/conventional/index.js +19 -0
- package/dist/conventional/index.js.map +1 -0
- package/dist/conventional/normalization.d.ts +59 -0
- package/dist/conventional/normalization.d.ts.map +1 -0
- package/dist/conventional/normalization.js +355 -0
- package/dist/conventional/normalization.js.map +1 -0
- package/dist/conventional/text.d.ts +20 -0
- package/dist/conventional/text.d.ts.map +1 -0
- package/dist/conventional/text.js +51 -0
- package/dist/conventional/text.js.map +1 -0
- package/dist/conventional/types.d.ts +35 -0
- package/dist/conventional/types.d.ts.map +1 -0
- package/dist/conventional/types.js +8 -0
- package/dist/conventional/types.js.map +1 -0
- package/dist/conventional/validation-data.d.ts +22 -0
- package/dist/conventional/validation-data.d.ts.map +1 -0
- package/dist/conventional/validation-data.js +2543 -0
- package/dist/conventional/validation-data.js.map +1 -0
- package/dist/conventional/validation.d.ts +89 -0
- package/dist/conventional/validation.d.ts.map +1 -0
- package/dist/conventional/validation.js +343 -0
- package/dist/conventional/validation.js.map +1 -0
- package/dist/diff.d.ts +1 -1
- package/dist/diff.d.ts.map +1 -1
- package/dist/diff.js +18 -5
- package/dist/diff.js.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/repo-lock.d.ts +26 -0
- package/dist/repo-lock.d.ts.map +1 -0
- package/dist/repo-lock.js +53 -0
- package/dist/repo-lock.js.map +1 -0
- package/dist/service.d.ts +10 -3
- package/dist/service.d.ts.map +1 -1
- package/dist/service.js +27 -14
- package/dist/service.js.map +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -1
- package/dist/vcs.d.ts +149 -0
- package/dist/vcs.d.ts.map +1 -0
- package/dist/vcs.js +209 -0
- package/dist/vcs.js.map +1 -0
- package/dist/worktree.d.ts +269 -0
- package/dist/worktree.d.ts.map +1 -0
- package/dist/worktree.js +642 -0
- package/dist/worktree.js.map +1 -0
- package/examples/agent-preset/agent.cordis.yml +1 -1
- package/examples/agent-preset/preset.yml +1 -1
- package/package.json +30 -11
package/dist/worktree.js
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worktree pool with durable leases for parallel agent work on one repository.
|
|
3
|
+
*
|
|
4
|
+
* Modeled on treehouse (MIT, https://github.com/kunchenguid/treehouse) `get
|
|
5
|
+
* --lease` semantics, reduced to what a pure-TS fork can express over the
|
|
6
|
+
* `ctx.git` subprocess seam:
|
|
7
|
+
*
|
|
8
|
+
* - A per-repository pool of git worktrees under a configurable root
|
|
9
|
+
* (default `~/.treehouse`), each slot cut at detached HEAD (treehouse
|
|
10
|
+
* default) or at a NAMED branch (DSH deviation D1: `tool-git commit_apply
|
|
11
|
+
* --push` runs `git push` on the current branch, which fails on a detached
|
|
12
|
+
* HEAD, so the PR path needs a branch).
|
|
13
|
+
* - DURABLE LEASES: `acquireWorktree` reserves a slot in persistent pool state
|
|
14
|
+
* with an immutable random lease id; a leased slot is never handed out again
|
|
15
|
+
* and never pruned until `releaseWorktree` clears it with the matching id —
|
|
16
|
+
* exactly treehouse's lease contract, and the property that makes a task's
|
|
17
|
+
* environment survive a host restart (D3: DSH children die with the host, so
|
|
18
|
+
* the lease — not a process — is the ownership record).
|
|
19
|
+
* - Safety is never inferred: a slot is only reused when it is provably idle
|
|
20
|
+
* (not leased), clean (`--untracked-files=all` so untracked files count) and
|
|
21
|
+
* its HEAD is already merged into the exact reset target; pruning and
|
|
22
|
+
* destroying default to dry-runs and refuse dirty/leased/unmerged work
|
|
23
|
+
* unless the caller passes the explicit flag.
|
|
24
|
+
* - DEVIATIONS vs treehouse (see the scope doc): named-branch support (D1), no
|
|
25
|
+
* process scan/termination in release (D2 — reports instead of killing),
|
|
26
|
+
* lease holder identifies the session/agent rather than a PID (D3), and the
|
|
27
|
+
* pool state file is this package's own `treehouse-state.json` with
|
|
28
|
+
* treehouse-compatible field names — no byte-level interop claim (D4).
|
|
29
|
+
*
|
|
30
|
+
* Concurrency: pool-state mutations are serialized cross-process with
|
|
31
|
+
* `@deepseek-ai/dsh-atomic-write`'s `writeFileAtomic` + `withFileLock` (the
|
|
32
|
+
* same temp-rename + lock treehouse implements with a flock), and git
|
|
33
|
+
* mutations additionally run under the in-process `withRepoLock` keyed on the
|
|
34
|
+
* PRIMARY repo root so worktrees of one repository share one queue.
|
|
35
|
+
* @module @hy-sde-org/dsh-git/worktree
|
|
36
|
+
*/
|
|
37
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
38
|
+
import { homedir } from 'node:os';
|
|
39
|
+
import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
40
|
+
import { mkdir, readdir, readFile, realpath, rm, stat } from 'node:fs/promises';
|
|
41
|
+
import { writeFileAtomic, withFileLock } from '@deepseek-ai/dsh-atomic-write';
|
|
42
|
+
import { withRepoLock } from "./repo-lock.js";
|
|
43
|
+
/** A typed worktree-pool failure: semantic codes for the tool layer to branch on. */
|
|
44
|
+
export class WorktreeError extends Error {
|
|
45
|
+
name = 'WorktreeError';
|
|
46
|
+
code;
|
|
47
|
+
/** The worktree or pool path involved, when one exists. */
|
|
48
|
+
path;
|
|
49
|
+
constructor(code, message, path) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.code = code;
|
|
52
|
+
this.path = path;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const STATE_FILE_NAME = 'treehouse-state.json';
|
|
56
|
+
const STATE_SCHEMA = 1;
|
|
57
|
+
const DEFAULT_ROOT = join(homedir(), '.treehouse');
|
|
58
|
+
const DEFAULT_LOCK_WAIT_MS = 30_000;
|
|
59
|
+
function fail(code, message, path) {
|
|
60
|
+
throw new WorktreeError(code, message, path);
|
|
61
|
+
}
|
|
62
|
+
/** Never throw for a missing file; returns undefined. */
|
|
63
|
+
async function readOptional(path) {
|
|
64
|
+
try {
|
|
65
|
+
return await readFile(path, 'utf8');
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error?.code === 'ENOENT')
|
|
69
|
+
return undefined;
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Run a git command via the service, requiring exit 0 (WorktreeError on a non-zero exit). */
|
|
74
|
+
async function gitChecked(git, argv, cwd, signal) {
|
|
75
|
+
const run = await git.run(argv, { cwd, signal });
|
|
76
|
+
if (run.exitCode !== 0) {
|
|
77
|
+
throw new WorktreeError('GitFailed', `git ${argv[0] ?? ''} failed (exit ${run.exitCode}): ${run.stderr.trim()}`, cwd);
|
|
78
|
+
}
|
|
79
|
+
return run.stdout;
|
|
80
|
+
}
|
|
81
|
+
/** Run a git command without throwing on a non-zero exit. */
|
|
82
|
+
async function gitMaybe(git, argv, cwd, signal) {
|
|
83
|
+
const run = await git.run(argv, { cwd, signal });
|
|
84
|
+
return { ok: run.exitCode === 0, stdout: run.stdout, stderr: run.stderr };
|
|
85
|
+
}
|
|
86
|
+
function abortGuard(signal) {
|
|
87
|
+
if (signal?.aborted) {
|
|
88
|
+
throw new WorktreeError('GitFailed', 'operation was aborted before it could start');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/* ── repository discovery ──────────────────────────────────────────────── */
|
|
92
|
+
/**
|
|
93
|
+
* The PRIMARY repository root (the main checkout) owning `cwd`, canonicalized
|
|
94
|
+
* through realpath so one repository — main checkout or any linked worktree —
|
|
95
|
+
* always resolves to one pool key, even across `/tmp` vs `/private/tmp`.
|
|
96
|
+
* @param git - the git service.
|
|
97
|
+
* @param cwd - a directory inside any checkout of the repository.
|
|
98
|
+
* @param signal - optional abort.
|
|
99
|
+
* @returns the canonical absolute primary root.
|
|
100
|
+
*/
|
|
101
|
+
export async function primaryRepoRoot(git, cwd, signal) {
|
|
102
|
+
const inside = await gitMaybe(git, ['rev-parse', '--is-inside-work-tree'], cwd, signal);
|
|
103
|
+
if (!inside.ok || inside.stdout.trim() !== 'true') {
|
|
104
|
+
fail('NotARepository', `not inside a git working tree: ${cwd}`, cwd);
|
|
105
|
+
}
|
|
106
|
+
const common = await git.run(['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd, signal });
|
|
107
|
+
if (common.exitCode !== 0) {
|
|
108
|
+
const fallback = await git.run(['rev-parse', '--git-common-dir'], { cwd, signal });
|
|
109
|
+
if (fallback.exitCode !== 0) {
|
|
110
|
+
fail('NotARepository', `cannot resolve the repository for ${cwd}: ${fallback.stderr.trim()}`, cwd);
|
|
111
|
+
}
|
|
112
|
+
let value = fallback.stdout.trim();
|
|
113
|
+
if (!isAbsolute(value))
|
|
114
|
+
value = resolve(cwd, value);
|
|
115
|
+
return realpath(dirname(value));
|
|
116
|
+
}
|
|
117
|
+
let value = common.stdout.trim();
|
|
118
|
+
if (!isAbsolute(value))
|
|
119
|
+
value = resolve(cwd, value);
|
|
120
|
+
if (basename(value) !== '.git') {
|
|
121
|
+
fail('UnsupportedRepository', `bare or non-standard repository (git dir ${value})`, cwd);
|
|
122
|
+
}
|
|
123
|
+
return realpath(dirname(value));
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The pool directory for one primary repository root: `<root>/<repo>-<hash6>`
|
|
127
|
+
* where the hash is the first 6 hex chars of sha256 over the canonical root
|
|
128
|
+
* (stable offline; a remote URL is not consulted, unlike treehouse — D4).
|
|
129
|
+
* @param settings - pool settings (root default `~/.treehouse`).
|
|
130
|
+
* @param primaryRoot - canonical primary repository root.
|
|
131
|
+
* @returns the absolute pool directory.
|
|
132
|
+
*/
|
|
133
|
+
export function resolveWorktreePoolRoot(settings, primaryRoot) {
|
|
134
|
+
const root = settings.root ?? DEFAULT_ROOT;
|
|
135
|
+
const repoName = basename(primaryRoot);
|
|
136
|
+
const hash = createHash('sha256').update(primaryRoot).digest('hex').slice(0, 6);
|
|
137
|
+
return join(root, `${repoName}-${hash}`);
|
|
138
|
+
}
|
|
139
|
+
function stateFilePath(poolRoot) {
|
|
140
|
+
return join(poolRoot, STATE_FILE_NAME);
|
|
141
|
+
}
|
|
142
|
+
/* ── state file ────────────────────────────────────────────────────────── */
|
|
143
|
+
function parseState(text) {
|
|
144
|
+
try {
|
|
145
|
+
const value = JSON.parse(text);
|
|
146
|
+
if (typeof value !== 'object' || value === null)
|
|
147
|
+
return null;
|
|
148
|
+
const record = value;
|
|
149
|
+
if (record.schema !== STATE_SCHEMA || !Array.isArray(record.worktrees))
|
|
150
|
+
return null;
|
|
151
|
+
return record;
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function serializeState(state) {
|
|
158
|
+
return `${JSON.stringify(state, null, 2)}\n`;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Rebuild pool entries from the git worktree registry after a corrupt or
|
|
162
|
+
* truncated state file (treehouse parity: entries are marked leased until a
|
|
163
|
+
* human verifies them with `status`). Only worktrees under `poolRoot` are
|
|
164
|
+
* adopted; everything else is left to git bookkeeping.
|
|
165
|
+
* @returns the rebuilt entries, or null when the registry itself is unreadable.
|
|
166
|
+
*/
|
|
167
|
+
async function recoverEntriesFromDisk(git, repoRoot, poolRoot, signal) {
|
|
168
|
+
const list = await git.run(['worktree', 'list', '--porcelain'], { cwd: repoRoot, signal });
|
|
169
|
+
if (list.exitCode !== 0)
|
|
170
|
+
return null;
|
|
171
|
+
const prefix = poolRoot.endsWith(sep) ? poolRoot : `${poolRoot}${sep}`;
|
|
172
|
+
const entries = [];
|
|
173
|
+
let current;
|
|
174
|
+
const flush = () => {
|
|
175
|
+
if (current?.path !== undefined && current.path.startsWith(prefix)) {
|
|
176
|
+
const slot = dirname(current.path);
|
|
177
|
+
entries.push({
|
|
178
|
+
name: basename(slot),
|
|
179
|
+
path: current.path,
|
|
180
|
+
createdAt: new Date().toISOString(),
|
|
181
|
+
leased: true,
|
|
182
|
+
baseBranch: '',
|
|
183
|
+
...current.branch !== undefined ? { branch: current.branch } : {},
|
|
184
|
+
recovered: true,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
current = undefined;
|
|
188
|
+
};
|
|
189
|
+
for (const line of list.stdout.split('\n')) {
|
|
190
|
+
if (line.startsWith('worktree ')) {
|
|
191
|
+
flush();
|
|
192
|
+
current = { path: line.slice('worktree '.length) };
|
|
193
|
+
}
|
|
194
|
+
else if (line.startsWith('branch ')) {
|
|
195
|
+
if (current !== undefined)
|
|
196
|
+
current.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '');
|
|
197
|
+
}
|
|
198
|
+
// A bare `detached` line is implied for detached slots; no extra state.
|
|
199
|
+
}
|
|
200
|
+
flush();
|
|
201
|
+
return entries;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Load pool state, recovering from a corrupt/truncated/foreign file by
|
|
205
|
+
* rebuilding from `git worktree list` (entries adopted as leased-unverified).
|
|
206
|
+
*/
|
|
207
|
+
async function loadState(git, repoRoot, poolRoot, signal) {
|
|
208
|
+
const text = await readOptional(stateFilePath(poolRoot));
|
|
209
|
+
if (text !== undefined && text.trim().length > 0) {
|
|
210
|
+
const parsed = parseState(text);
|
|
211
|
+
if (parsed !== null && parsed.repoRoot === repoRoot) {
|
|
212
|
+
return { state: parsed, recovered: false };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const rebuilt = (await recoverEntriesFromDisk(git, repoRoot, poolRoot, signal)) ?? [];
|
|
216
|
+
return { state: { schema: STATE_SCHEMA, repoRoot, worktrees: rebuilt }, recovered: true };
|
|
217
|
+
}
|
|
218
|
+
/* ── git predicates ────────────────────────────────────────────────────── */
|
|
219
|
+
/** True when the worktree has no tracked or untracked changes. */
|
|
220
|
+
async function isClean(git, worktreePath, signal) {
|
|
221
|
+
const probe = await git.run(['status', '--porcelain', '--untracked-files=all'], { cwd: worktreePath, signal });
|
|
222
|
+
return probe.exitCode === 0 && probe.stdout.trim().length === 0;
|
|
223
|
+
}
|
|
224
|
+
/** True when the worktree HEAD is an ancestor of `target`. */
|
|
225
|
+
async function isMergedInto(git, worktreePath, target, signal) {
|
|
226
|
+
const probe = await gitMaybe(git, ['merge-base', '--is-ancestor', 'HEAD', target], worktreePath, signal);
|
|
227
|
+
return probe.ok;
|
|
228
|
+
}
|
|
229
|
+
async function exists(path) {
|
|
230
|
+
try {
|
|
231
|
+
await stat(path);
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/** The repository's default branch: origin HEAD symbolic ref, then the current branch. */
|
|
239
|
+
async function inferDefaultBranch(git, repoRoot, signal) {
|
|
240
|
+
const originHead = await gitMaybe(git, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], repoRoot, signal);
|
|
241
|
+
if (originHead.ok) {
|
|
242
|
+
const ref = originHead.stdout.trim();
|
|
243
|
+
const prefix = 'refs/remotes/origin/';
|
|
244
|
+
if (ref.startsWith(prefix) && ref.length > prefix.length)
|
|
245
|
+
return ref.slice(prefix.length);
|
|
246
|
+
}
|
|
247
|
+
const head = await gitMaybe(git, ['symbolic-ref', '--quiet', 'HEAD'], repoRoot, signal);
|
|
248
|
+
if (head.ok) {
|
|
249
|
+
const ref = head.stdout.trim();
|
|
250
|
+
const prefix = 'refs/heads/';
|
|
251
|
+
if (ref.startsWith(prefix) && ref.length > prefix.length)
|
|
252
|
+
return ref.slice(prefix.length);
|
|
253
|
+
}
|
|
254
|
+
fail('DefaultBranchUnknown', `cannot infer the default branch of ${repoRoot}; set settings.baseBranch or pass base`);
|
|
255
|
+
}
|
|
256
|
+
async function resolveTarget(git, repoRoot, explicit, settings, signal) {
|
|
257
|
+
const base = explicit ?? settings.baseBranch;
|
|
258
|
+
if (base !== undefined && base.length > 0)
|
|
259
|
+
return base;
|
|
260
|
+
return inferDefaultBranch(git, repoRoot, signal);
|
|
261
|
+
}
|
|
262
|
+
/** The pool owning a worktree path: `<poolRoot>/<slot>/<repoName>` → `<poolRoot>`. */
|
|
263
|
+
function poolRootFromLeasePath(worktreePath) {
|
|
264
|
+
return dirname(dirname(worktreePath));
|
|
265
|
+
}
|
|
266
|
+
/* ── acquire ───────────────────────────────────────────────────────────── */
|
|
267
|
+
/**
|
|
268
|
+
* Acquire a durable lease on one clean worktree slot. Never hands out a slot
|
|
269
|
+
* that cannot be proven idle (unleased) and clean with its HEAD already merged
|
|
270
|
+
* into the reset target; otherwise a new slot is cut. Holding the pool-state
|
|
271
|
+
* file lock for the whole choose-cut-reset cycle makes concurrent acquires (in
|
|
272
|
+
* any process) serialize, and `withRepoLock` on the primary root serializes
|
|
273
|
+
* with other in-process git mutations of the same repository.
|
|
274
|
+
*
|
|
275
|
+
* The returned lease is the caller's durable ownership record:
|
|
276
|
+
* `releaseWorktree` requires the exact `leaseId`, so a stale caller can never
|
|
277
|
+
* release someone else's slot.
|
|
278
|
+
* @param git - the git service.
|
|
279
|
+
* @param cwd - any checkout (main or worktree) of the target repository.
|
|
280
|
+
* @param settings - pool settings (root, default branch, fetch behavior).
|
|
281
|
+
* @param options - per-acquire options (named branch, base, holder, noFetch, signal).
|
|
282
|
+
* @returns the lease.
|
|
283
|
+
*/
|
|
284
|
+
export async function acquireWorktree(git, cwd, settings = {}, options = {}) {
|
|
285
|
+
abortGuard(options.signal);
|
|
286
|
+
const repoRoot = await primaryRepoRoot(git, cwd, options.signal);
|
|
287
|
+
const poolRoot = resolveWorktreePoolRoot(settings, repoRoot);
|
|
288
|
+
await mkdir(poolRoot, { recursive: true });
|
|
289
|
+
const target = await resolveTarget(git, repoRoot, options.base, settings, options.signal);
|
|
290
|
+
return withFileLock(stateFilePath(poolRoot), async () => {
|
|
291
|
+
// Serialize git mutations against other in-process callers of this repo.
|
|
292
|
+
return withRepoLock(repoRoot, async () => {
|
|
293
|
+
if (settings.fetchBeforeAcquire !== false && options.noFetch !== true) {
|
|
294
|
+
const remote = await gitMaybe(git, ['remote', 'get-url', 'origin'], repoRoot, options.signal);
|
|
295
|
+
if (remote.ok) {
|
|
296
|
+
await gitChecked(git, ['fetch', 'origin'], repoRoot, options.signal);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const { state } = await loadState(git, repoRoot, poolRoot, options.signal);
|
|
300
|
+
const entries = state.worktrees;
|
|
301
|
+
const branch = options.branch;
|
|
302
|
+
// A reusable slot: unleased, unbroken, clean, and — critically — HEAD
|
|
303
|
+
// already merged into the exact reset target; named-branch slots only
|
|
304
|
+
// when the name matches (D5). Never reuse when safety is unprovable.
|
|
305
|
+
const reusable = entries.find((entry) => {
|
|
306
|
+
if (entry.leased || entry.recovered === true)
|
|
307
|
+
return false;
|
|
308
|
+
if (branch !== undefined && entry.branch !== branch)
|
|
309
|
+
return false;
|
|
310
|
+
return true;
|
|
311
|
+
});
|
|
312
|
+
const atCap = settings.maxSlots !== undefined && settings.maxSlots > 0
|
|
313
|
+
&& entries.length >= settings.maxSlots;
|
|
314
|
+
// A cap limits NEW slots only: provable reuse is always allowed.
|
|
315
|
+
const cutNew = () => {
|
|
316
|
+
if (atCap) {
|
|
317
|
+
throw new WorktreeError('MaxSlots', `pool "${poolRoot}" is at its maxSlots cap (${settings.maxSlots}): no new slot can be cut — release a lease, prune/destroy an idle slot, or raise maxSlots`, poolRoot);
|
|
318
|
+
}
|
|
319
|
+
return cutNewSlot(git, repoRoot, poolRoot, entries, target, branch, options.signal);
|
|
320
|
+
};
|
|
321
|
+
let entry;
|
|
322
|
+
if (reusable !== undefined) {
|
|
323
|
+
const clean = await isClean(git, reusable.path, options.signal);
|
|
324
|
+
const merged = await isMergedInto(git, reusable.path, target, options.signal);
|
|
325
|
+
const present = await exists(reusable.path);
|
|
326
|
+
if (clean && merged && present) {
|
|
327
|
+
// Proven reusable: park it at the target, then lease it below.
|
|
328
|
+
entry = await reuseSlot(git, reusable, target, branch, options.signal);
|
|
329
|
+
}
|
|
330
|
+
else {
|
|
331
|
+
// Safety unprovable: keep the slot untouched and cut a new one.
|
|
332
|
+
entry = await cutNew();
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
else {
|
|
336
|
+
entry = await cutNew();
|
|
337
|
+
}
|
|
338
|
+
const leasedAt = new Date().toISOString();
|
|
339
|
+
const leaseId = randomBytes(16).toString('hex');
|
|
340
|
+
const updated = {
|
|
341
|
+
...entry,
|
|
342
|
+
leased: true,
|
|
343
|
+
leaseId,
|
|
344
|
+
leaseHolder: options.holder ?? 'dsh',
|
|
345
|
+
leasedAt,
|
|
346
|
+
baseBranch: options.base ?? settings.baseBranch ?? target,
|
|
347
|
+
...branch !== undefined ? { branch } : {},
|
|
348
|
+
recovered: false,
|
|
349
|
+
};
|
|
350
|
+
state.worktrees = [
|
|
351
|
+
...state.worktrees.filter(item => !(item.name === updated.name && item.path === updated.path)),
|
|
352
|
+
updated,
|
|
353
|
+
];
|
|
354
|
+
await writeFileAtomic(stateFilePath(poolRoot), serializeState(state), { mode: 0o600 });
|
|
355
|
+
return {
|
|
356
|
+
path: updated.path,
|
|
357
|
+
leaseId,
|
|
358
|
+
leaseHolder: updated.leaseHolder ?? 'dsh',
|
|
359
|
+
leasedAt,
|
|
360
|
+
baseBranch: updated.baseBranch,
|
|
361
|
+
...branch !== undefined ? { branch } : {},
|
|
362
|
+
};
|
|
363
|
+
});
|
|
364
|
+
}, { waitMs: settings.lockWaitMs ?? DEFAULT_LOCK_WAIT_MS });
|
|
365
|
+
}
|
|
366
|
+
/** Park a proven-reusable slot at the reset target (named branch recreated — D5). */
|
|
367
|
+
async function reuseSlot(git, entry, target, branch, signal) {
|
|
368
|
+
if (branch !== undefined) {
|
|
369
|
+
await gitChecked(git, ['checkout', '-B', branch, target], entry.path, signal);
|
|
370
|
+
}
|
|
371
|
+
else {
|
|
372
|
+
await gitChecked(git, ['checkout', '--detach', target], entry.path, signal);
|
|
373
|
+
}
|
|
374
|
+
return { ...entry, ...branch !== undefined ? { branch } : {} };
|
|
375
|
+
}
|
|
376
|
+
/** Cut a fresh slot: self-heal stale bookkeeping, then `worktree add`. */
|
|
377
|
+
async function cutNewSlot(git, repoRoot, poolRoot, entries, target, branch, signal) {
|
|
378
|
+
await gitChecked(git, ['worktree', 'prune'], repoRoot, signal);
|
|
379
|
+
const used = new Set(entries.map(entry => entry.name));
|
|
380
|
+
let slot = 1;
|
|
381
|
+
while (used.has(String(slot)))
|
|
382
|
+
slot += 1;
|
|
383
|
+
const slotDir = join(poolRoot, String(slot));
|
|
384
|
+
const path = join(slotDir, basename(repoRoot));
|
|
385
|
+
if (branch !== undefined) {
|
|
386
|
+
await gitChecked(git, ['worktree', 'add', '-b', branch, path, target], repoRoot, signal);
|
|
387
|
+
}
|
|
388
|
+
else {
|
|
389
|
+
await gitChecked(git, ['worktree', 'add', '--detach', path, target], repoRoot, signal);
|
|
390
|
+
}
|
|
391
|
+
return {
|
|
392
|
+
name: String(slot),
|
|
393
|
+
path,
|
|
394
|
+
createdAt: new Date().toISOString(),
|
|
395
|
+
leased: false,
|
|
396
|
+
baseBranch: '',
|
|
397
|
+
...branch !== undefined ? { branch } : {},
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
/* ── release ───────────────────────────────────────────────────────────── */
|
|
401
|
+
/**
|
|
402
|
+
* Release a leased worktree, clearing only the lease whose id matches. The
|
|
403
|
+
* slot is parked: a non-forced release requires a clean tree (tracked AND
|
|
404
|
+
* untracked) and then resets HEAD to the recorded base (or the inferred
|
|
405
|
+
* default) at detached HEAD; `force` additionally runs `git clean -fdqx`.
|
|
406
|
+
* D2: this engine never kills processes — a busy slot surfaces as a
|
|
407
|
+
* {@link WorktreeError} with code `DirtyWorktree` instead.
|
|
408
|
+
* @param git - the git service.
|
|
409
|
+
* @param cwd - any checkout of the pool's repository (fallback pool resolution).
|
|
410
|
+
* @param lease - the exact lease to release (`path` + `leaseId` from {@link acquireWorktree}).
|
|
411
|
+
* @param options - `force`, `settings` (root), `signal`.
|
|
412
|
+
*/
|
|
413
|
+
export async function releaseWorktree(git, cwd, lease, options = {}) {
|
|
414
|
+
abortGuard(options.signal);
|
|
415
|
+
const repoRoot = await primaryRepoRoot(git, cwd, options.signal);
|
|
416
|
+
// Prefer the pool the lease actually came from (settings-independent), then
|
|
417
|
+
// fall back to the configured root so release still works after a restart
|
|
418
|
+
// with a different tool config.
|
|
419
|
+
let poolRoot = poolRootFromLeasePath(lease.path);
|
|
420
|
+
if (await readOptional(stateFilePath(poolRoot)) === undefined) {
|
|
421
|
+
poolRoot = resolveWorktreePoolRoot(options.settings ?? {}, repoRoot);
|
|
422
|
+
}
|
|
423
|
+
await mkdir(poolRoot, { recursive: true });
|
|
424
|
+
return withFileLock(stateFilePath(poolRoot), async () => {
|
|
425
|
+
const { state } = await loadState(git, repoRoot, poolRoot, options.signal);
|
|
426
|
+
const entry = state.worktrees.find(item => item.path === lease.path);
|
|
427
|
+
if (entry === undefined)
|
|
428
|
+
fail('UnknownWorktree', `no pooled worktree at ${lease.path}`, lease.path);
|
|
429
|
+
if (entry.leaseId !== lease.leaseId) {
|
|
430
|
+
fail('LeaseMismatch', `lease ${lease.leaseId} does not own ${lease.path} (held by ${entry.leaseId ?? 'nobody'})`, lease.path);
|
|
431
|
+
}
|
|
432
|
+
return withRepoLock(repoRoot, async () => {
|
|
433
|
+
if (!(await exists(lease.path))) {
|
|
434
|
+
// The worktree is gone (external removal): drop the entry and prune bookkeeping.
|
|
435
|
+
state.worktrees = state.worktrees.filter(item => item.path !== lease.path);
|
|
436
|
+
await gitChecked(git, ['worktree', 'prune'], repoRoot, options.signal);
|
|
437
|
+
await writeFileAtomic(stateFilePath(poolRoot), serializeState(state), { mode: 0o600 });
|
|
438
|
+
return { path: lease.path, released: true };
|
|
439
|
+
}
|
|
440
|
+
const clean = await isClean(git, lease.path, options.signal);
|
|
441
|
+
if (!clean && options.force !== true) {
|
|
442
|
+
fail('DirtyWorktree', `worktree ${lease.path} has uncommitted changes; commit them or pass force`, lease.path);
|
|
443
|
+
}
|
|
444
|
+
const target = entry.baseBranch.length > 0
|
|
445
|
+
? entry.baseBranch
|
|
446
|
+
: await resolveTarget(git, repoRoot, undefined, {}, options.signal);
|
|
447
|
+
await gitChecked(git, ['checkout', '--detach', target], lease.path, options.signal);
|
|
448
|
+
await gitChecked(git, ['reset', '--hard', target], lease.path, options.signal);
|
|
449
|
+
if (!clean && options.force === true) {
|
|
450
|
+
await gitChecked(git, ['clean', '-fdqx'], lease.path, options.signal);
|
|
451
|
+
}
|
|
452
|
+
state.worktrees = state.worktrees.map((item) => {
|
|
453
|
+
if (item.path !== lease.path)
|
|
454
|
+
return item;
|
|
455
|
+
const parked = { ...item, leased: false, recovered: false };
|
|
456
|
+
delete parked.leaseId;
|
|
457
|
+
delete parked.leaseHolder;
|
|
458
|
+
delete parked.leasedAt;
|
|
459
|
+
return parked;
|
|
460
|
+
});
|
|
461
|
+
await writeFileAtomic(stateFilePath(poolRoot), serializeState(state), { mode: 0o600 });
|
|
462
|
+
return { path: lease.path, released: true };
|
|
463
|
+
});
|
|
464
|
+
}, { waitMs: 30_000 });
|
|
465
|
+
}
|
|
466
|
+
/* ── list / prune / destroy ────────────────────────────────────────────── */
|
|
467
|
+
/**
|
|
468
|
+
* Report every slot of the pool owning `cwd`. Read-only; never mutates pool
|
|
469
|
+
* state. Status is computed live: `leased`, `idle` (clean + merged + present)
|
|
470
|
+
* or `damaged` (recovered/unverified, missing, or dirty).
|
|
471
|
+
*/
|
|
472
|
+
export async function listWorktrees(git, cwd, options = {}) {
|
|
473
|
+
abortGuard(options.signal);
|
|
474
|
+
const repoRoot = await primaryRepoRoot(git, cwd, options.signal);
|
|
475
|
+
const poolRoot = resolveWorktreePoolRoot(options.settings ?? {}, repoRoot);
|
|
476
|
+
const text = await readOptional(stateFilePath(poolRoot));
|
|
477
|
+
if (text === undefined)
|
|
478
|
+
return [];
|
|
479
|
+
let entries = parseState(text)?.worktrees;
|
|
480
|
+
if (entries === undefined) {
|
|
481
|
+
// Corrupt/truncated state: report a read-only rebuild so damage is visible.
|
|
482
|
+
entries = (await recoverEntriesFromDisk(git, repoRoot, poolRoot, options.signal)) ?? [];
|
|
483
|
+
}
|
|
484
|
+
const target = await resolveTarget(git, repoRoot, undefined, {}, options.signal).catch(() => '');
|
|
485
|
+
const result = [];
|
|
486
|
+
for (const entry of entries) {
|
|
487
|
+
const present = await exists(entry.path);
|
|
488
|
+
const dirty = present ? !(await isClean(git, entry.path, options.signal)) : true;
|
|
489
|
+
const merged = present && target.length > 0
|
|
490
|
+
? await isMergedInto(git, entry.path, target, options.signal)
|
|
491
|
+
: false;
|
|
492
|
+
let status;
|
|
493
|
+
if (entry.recovered === true || (entry.leased && entry.leaseId === undefined))
|
|
494
|
+
status = 'damaged';
|
|
495
|
+
else if (entry.leased)
|
|
496
|
+
status = 'leased';
|
|
497
|
+
else if (!present || dirty)
|
|
498
|
+
status = 'damaged';
|
|
499
|
+
else
|
|
500
|
+
status = 'idle';
|
|
501
|
+
result.push({
|
|
502
|
+
name: entry.name,
|
|
503
|
+
path: entry.path,
|
|
504
|
+
status,
|
|
505
|
+
leased: entry.leased,
|
|
506
|
+
...entry.leaseId !== undefined ? { leaseId: entry.leaseId } : {},
|
|
507
|
+
...entry.leaseHolder !== undefined ? { leaseHolder: entry.leaseHolder } : {},
|
|
508
|
+
...entry.leasedAt !== undefined ? { leasedAt: entry.leasedAt } : {},
|
|
509
|
+
baseBranch: entry.baseBranch,
|
|
510
|
+
...entry.branch !== undefined ? { branch: entry.branch } : {},
|
|
511
|
+
dirty,
|
|
512
|
+
merged,
|
|
513
|
+
exists: present,
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
return result;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Produce (and with `yes`, execute) a prune plan for the pool owning `cwd`:
|
|
520
|
+
* only unleased, clean slots whose HEAD is merged into the current reset target
|
|
521
|
+
* are candidates; everything else is reported as skipped *without* removal.
|
|
522
|
+
* `all` sweeps every pool under the configured root. Dry-run unless `yes`.
|
|
523
|
+
*/
|
|
524
|
+
export async function pruneWorktrees(git, cwd, options = {}) {
|
|
525
|
+
abortGuard(options.signal);
|
|
526
|
+
const settings = options.settings ?? {};
|
|
527
|
+
const repoRoot = await primaryRepoRoot(git, cwd, options.signal);
|
|
528
|
+
const defaultPool = resolveWorktreePoolRoot(settings, repoRoot);
|
|
529
|
+
const scopes = [{ repoRoot, poolRoot: defaultPool }];
|
|
530
|
+
if (options.all === true) {
|
|
531
|
+
const base = dirname(defaultPool);
|
|
532
|
+
let names = [];
|
|
533
|
+
try {
|
|
534
|
+
names = (await readdir(base, { withFileTypes: true }))
|
|
535
|
+
.filter(entry => entry.isDirectory())
|
|
536
|
+
.map(entry => entry.name);
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
names = [];
|
|
540
|
+
}
|
|
541
|
+
for (const name of names) {
|
|
542
|
+
const pool = join(base, name);
|
|
543
|
+
if (pool === defaultPool)
|
|
544
|
+
continue;
|
|
545
|
+
scopes.push({ repoRoot: '', poolRoot: pool });
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
const candidates = [];
|
|
549
|
+
const skipped = [];
|
|
550
|
+
const removed = [];
|
|
551
|
+
for (const scope of scopes) {
|
|
552
|
+
const text = await readOptional(stateFilePath(scope.poolRoot));
|
|
553
|
+
if (text === undefined)
|
|
554
|
+
continue;
|
|
555
|
+
const parsed = parseState(text);
|
|
556
|
+
if (parsed === null)
|
|
557
|
+
continue;
|
|
558
|
+
const target = await resolveTarget(git, parsed.repoRoot, undefined, {}, options.signal).catch(() => '');
|
|
559
|
+
let mutated = false;
|
|
560
|
+
for (const entry of [...parsed.worktrees]) {
|
|
561
|
+
if (entry.leased) {
|
|
562
|
+
skipped.push({ name: entry.name, path: entry.path, reason: 'leased' });
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
if (!(await exists(entry.path))) {
|
|
566
|
+
skipped.push({ name: entry.name, path: entry.path, reason: 'missing' });
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
const clean = await isClean(git, entry.path, options.signal);
|
|
570
|
+
const merged = target.length > 0
|
|
571
|
+
? await isMergedInto(git, entry.path, target, options.signal)
|
|
572
|
+
: false;
|
|
573
|
+
if (!clean) {
|
|
574
|
+
skipped.push({ name: entry.name, path: entry.path, reason: 'dirty' });
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
if (!merged) {
|
|
578
|
+
skipped.push({ name: entry.name, path: entry.path, reason: 'not merged' });
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
candidates.push({ name: entry.name, path: entry.path, reason: 'removable' });
|
|
582
|
+
if (options.yes === true) {
|
|
583
|
+
await withRepoLock(parsed.repoRoot, async () => {
|
|
584
|
+
await gitChecked(git, ['worktree', 'remove', '--force', entry.path], parsed.repoRoot, options.signal);
|
|
585
|
+
await rm(dirname(entry.path), { recursive: true, force: true });
|
|
586
|
+
});
|
|
587
|
+
removed.push(entry.path);
|
|
588
|
+
parsed.worktrees = parsed.worktrees.filter(item => item.path !== entry.path);
|
|
589
|
+
mutated = true;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (options.yes === true && mutated) {
|
|
593
|
+
await writeFileAtomic(stateFilePath(scope.poolRoot), serializeState(parsed), { mode: 0o600 });
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return { candidates, skipped, removed };
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Destroy one pooled slot. Dry-run unless `yes`. Defaults refuse leased slots
|
|
600
|
+
* (`includeLeased`) and dirty or unmerged work (`includeUnlanded`) — the same
|
|
601
|
+
* guards as treehouse, with the same irreversible-data-loss semantics for the
|
|
602
|
+
* unlanded case.
|
|
603
|
+
*/
|
|
604
|
+
export async function destroyWorktree(git, cwd, options) {
|
|
605
|
+
abortGuard(options.signal);
|
|
606
|
+
const repoRoot = await primaryRepoRoot(git, cwd, options.signal);
|
|
607
|
+
const poolRoot = resolveWorktreePoolRoot(options.settings ?? {}, repoRoot);
|
|
608
|
+
const { state } = await loadState(git, repoRoot, poolRoot, options.signal);
|
|
609
|
+
const entry = options.path !== undefined
|
|
610
|
+
? state.worktrees.find(item => item.path === options.path)
|
|
611
|
+
: options.name !== undefined
|
|
612
|
+
? state.worktrees.find(item => item.name === options.name)
|
|
613
|
+
: undefined;
|
|
614
|
+
if (entry === undefined)
|
|
615
|
+
fail('UnknownWorktree', `no pooled worktree named ${String(options.name ?? options.path)}`, options.path);
|
|
616
|
+
if (entry.leased && options.includeLeased !== true) {
|
|
617
|
+
fail('LeasedWorktree', `worktree ${entry.path} is leased (${entry.leaseId ?? 'unverified'}); pass includeLeased to destroy`, entry.path);
|
|
618
|
+
}
|
|
619
|
+
if (options.yes !== true) {
|
|
620
|
+
return { path: entry.path, removed: false };
|
|
621
|
+
}
|
|
622
|
+
return withFileLock(stateFilePath(poolRoot), async () => withRepoLock(repoRoot, async () => {
|
|
623
|
+
const clean = await isClean(git, entry.path, options.signal);
|
|
624
|
+
const target = await resolveTarget(git, repoRoot, undefined, {}, options.signal).catch(() => '');
|
|
625
|
+
const merged = target.length > 0
|
|
626
|
+
? await isMergedInto(git, entry.path, target, options.signal)
|
|
627
|
+
: clean;
|
|
628
|
+
if (!clean && options.includeUnlanded !== true) {
|
|
629
|
+
fail('UnlandedWorktree', `worktree ${entry.path} is dirty; pass includeUnlanded to discard (irreversible)`, entry.path);
|
|
630
|
+
}
|
|
631
|
+
if (!merged && !clean && options.includeUnlanded !== true) {
|
|
632
|
+
fail('UnlandedWorktree', `worktree ${entry.path} has unmerged work; pass includeUnlanded to discard (irreversible)`, entry.path);
|
|
633
|
+
}
|
|
634
|
+
await gitChecked(git, ['worktree', 'remove', '--force', entry.path], repoRoot, options.signal);
|
|
635
|
+
await rm(dirname(entry.path), { recursive: true, force: true });
|
|
636
|
+
const fresh = await loadState(git, repoRoot, poolRoot, options.signal);
|
|
637
|
+
fresh.state.worktrees = fresh.state.worktrees.filter(item => item.path !== entry.path);
|
|
638
|
+
await writeFileAtomic(stateFilePath(poolRoot), serializeState(fresh.state), { mode: 0o600 });
|
|
639
|
+
return { path: entry.path, removed: true };
|
|
640
|
+
}), { waitMs: 30_000 });
|
|
641
|
+
}
|
|
642
|
+
//# sourceMappingURL=worktree.js.map
|