@hy-sde-org/dsh-git 0.1.1-rc.2 → 0.1.5-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.
Files changed (64) hide show
  1. package/LICENSE +4 -5
  2. package/README.md +13 -3
  3. package/dist/conventional/commit-types-data.d.ts +23 -0
  4. package/dist/conventional/commit-types-data.d.ts.map +1 -0
  5. package/dist/conventional/commit-types-data.js +437 -0
  6. package/dist/conventional/commit-types-data.js.map +1 -0
  7. package/dist/conventional/commit-types.d.ts +63 -0
  8. package/dist/conventional/commit-types.d.ts.map +1 -0
  9. package/dist/conventional/commit-types.js +236 -0
  10. package/dist/conventional/commit-types.js.map +1 -0
  11. package/dist/conventional/index.d.ts +19 -0
  12. package/dist/conventional/index.d.ts.map +1 -0
  13. package/dist/conventional/index.js +19 -0
  14. package/dist/conventional/index.js.map +1 -0
  15. package/dist/conventional/normalization.d.ts +59 -0
  16. package/dist/conventional/normalization.d.ts.map +1 -0
  17. package/dist/conventional/normalization.js +355 -0
  18. package/dist/conventional/normalization.js.map +1 -0
  19. package/dist/conventional/text.d.ts +20 -0
  20. package/dist/conventional/text.d.ts.map +1 -0
  21. package/dist/conventional/text.js +51 -0
  22. package/dist/conventional/text.js.map +1 -0
  23. package/dist/conventional/types.d.ts +35 -0
  24. package/dist/conventional/types.d.ts.map +1 -0
  25. package/dist/conventional/types.js +8 -0
  26. package/dist/conventional/types.js.map +1 -0
  27. package/dist/conventional/validation-data.d.ts +22 -0
  28. package/dist/conventional/validation-data.d.ts.map +1 -0
  29. package/dist/conventional/validation-data.js +2543 -0
  30. package/dist/conventional/validation-data.js.map +1 -0
  31. package/dist/conventional/validation.d.ts +89 -0
  32. package/dist/conventional/validation.d.ts.map +1 -0
  33. package/dist/conventional/validation.js +343 -0
  34. package/dist/conventional/validation.js.map +1 -0
  35. package/dist/diff.d.ts +1 -1
  36. package/dist/diff.d.ts.map +1 -1
  37. package/dist/diff.js +18 -5
  38. package/dist/diff.js.map +1 -1
  39. package/dist/index.d.ts +5 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +5 -1
  42. package/dist/index.js.map +1 -1
  43. package/dist/repo-lock.d.ts +26 -0
  44. package/dist/repo-lock.d.ts.map +1 -0
  45. package/dist/repo-lock.js +53 -0
  46. package/dist/repo-lock.js.map +1 -0
  47. package/dist/service.d.ts +10 -3
  48. package/dist/service.d.ts.map +1 -1
  49. package/dist/service.js +27 -14
  50. package/dist/service.js.map +1 -1
  51. package/dist/types.d.ts +2 -2
  52. package/dist/types.d.ts.map +1 -1
  53. package/dist/types.js +1 -1
  54. package/dist/vcs.d.ts +149 -0
  55. package/dist/vcs.d.ts.map +1 -0
  56. package/dist/vcs.js +209 -0
  57. package/dist/vcs.js.map +1 -0
  58. package/dist/worktree.d.ts +269 -0
  59. package/dist/worktree.d.ts.map +1 -0
  60. package/dist/worktree.js +642 -0
  61. package/dist/worktree.js.map +1 -0
  62. package/examples/agent-preset/agent.cordis.yml +1 -1
  63. package/examples/agent-preset/preset.yml +1 -1
  64. package/package.json +32 -12
package/dist/vcs.js ADDED
@@ -0,0 +1,209 @@
1
+ /**
2
+ * TS contract port of omp's native `pi-vcs` surface (see `@oh-my-pi/pi-natives/vcs`),
3
+ * reduced to what a pure-TS/Node fork can express: the {@link VcsError} taxonomy,
4
+ * repository discovery with feature-gated `require()`, newline-safe patch joining,
5
+ * and HEAD stat-poll watching. The 60-method `VcsGitRepo` handle is NOT ported —
6
+ * the fork already shells out through `GitService` (`ctx.git`) per call, so a
7
+ * handle would duplicate that seam; what pi-vcs adds is typed error branching
8
+ * and the small discovery/lock/watch vocabulary.
9
+ *
10
+ * The fork has no Rust/N-API pipeline and no Jujutsu support, so `jj`, `clone`,
11
+ * `detachGitDir` and the `gix`-backed read/write verbs are out of scope; the
12
+ * portable contract here is: `repo()/git()/gitInfo()` discovery, `require()` /
13
+ * `requireGit()` feature gates, the `VcsError` taxonomy with `isVcsError` /
14
+ * `isEmptyCherryPick`, `joinPatches` (newline-safe), and `watch()` /
15
+ * `HEAD_WATCH_INTERVAL_MS`. `withRepoLock` lives in `./repo-lock.ts` and keys on
16
+ * `repo(cwd).primaryRoot()`.
17
+ * @module @hy-sde-org/dsh-git/vcs
18
+ */
19
+ import { dirname, isAbsolute, join, normalize, sep } from 'node:path';
20
+ import { statSync, watchFile, unwatchFile } from 'node:fs';
21
+ /**
22
+ * A typed VCS failure: a real `Error` with `name: "VcsError"`, a
23
+ * machine-readable `code`, and CLI-result fields. Non-CLI failures synthesize
24
+ * `exitCode: 1` and mirror `message` into `stderr`. Identify with
25
+ * {@link isVcsError} — upstream constructs these on the JS thread so identity
26
+ * rides on `name`, and this port keeps that contract.
27
+ */
28
+ export class VcsError extends Error {
29
+ name = 'VcsError';
30
+ code;
31
+ exitCode;
32
+ stdout;
33
+ stderr;
34
+ constructor(code, message, fields = {}) {
35
+ super(message);
36
+ this.code = code;
37
+ this.exitCode = fields.exitCode ?? 1;
38
+ this.stdout = fields.stdout ?? '';
39
+ this.stderr = fields.stderr ?? message;
40
+ }
41
+ }
42
+ /**
43
+ * True when `error` is a VCS failure (identity rides on `name`, like upstream).
44
+ * @param error - the value to test.
45
+ * @returns true for a {@link VcsError} instance.
46
+ */
47
+ export function isVcsError(error) {
48
+ return error instanceof Error && error.name === 'VcsError';
49
+ }
50
+ /**
51
+ * True when a cherry-pick failed because the commit is already applied.
52
+ * @param error - the value to test.
53
+ * @returns true for an `EmptyCherryPick` {@link VcsError}.
54
+ */
55
+ export function isEmptyCherryPick(error) {
56
+ return isVcsError(error) && error.code === 'EmptyCherryPick';
57
+ }
58
+ /**
59
+ * Construct a {@link VcsError} (upstream `vcsError` factory).
60
+ * @param code - the machine-readable error code.
61
+ * @param message - the human-readable message.
62
+ * @param fields - optional `exitCode`/`stdout`/`stderr` fields.
63
+ * @returns the constructed error.
64
+ */
65
+ export function vcsError(code, message, fields = {}) {
66
+ return new VcsError(code, message, fields);
67
+ }
68
+ /* ── discovery ─────────────────────────────────────────────────────────── */
69
+ function looksLikeGitDir(dir) {
70
+ try {
71
+ // node:fs sync stat — `.git` is either a directory (normal repo) or a
72
+ // file (a worktree pointer `gitdir: <path>`); both are discoverable here.
73
+ statSync(dir);
74
+ return true;
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ /**
81
+ * Walk up from `dir` to the nearest ancestor holding a `.git` entry, or null.
82
+ * @param dir - the directory to start the walk from.
83
+ * @returns the repo info, or `null` when no `.git` ancestor exists.
84
+ */
85
+ export function gitInfo(dir) {
86
+ let current = normalize(dir);
87
+ const root = dirname(current);
88
+ for (;;) {
89
+ const candidate = join(current, '.git');
90
+ if (looksLikeGitDir(candidate)) {
91
+ return { root: current, gitDir: candidate };
92
+ }
93
+ if (current === root)
94
+ return null;
95
+ current = root;
96
+ }
97
+ }
98
+ /**
99
+ * Discover the repository owning `dir`; `null` outside any repository.
100
+ * Sync (cheap fs walk) for render paths; async callers that already shell out
101
+ * should prefer `GitService`.
102
+ * @param dir - the directory to discover in.
103
+ * @returns the repo handle, or `null` outside a repository.
104
+ */
105
+ export function repo(dir) {
106
+ const info = gitInfo(dir);
107
+ if (info === null)
108
+ return null;
109
+ return {
110
+ kind: 'git',
111
+ root: info.root,
112
+ gitDir: info.gitDir,
113
+ watchTarget: join(info.gitDir, 'HEAD'),
114
+ supports: () => true,
115
+ };
116
+ }
117
+ /**
118
+ * Like {@link repo}, asserting any requested backend capabilities.
119
+ * @param dir - the directory to discover in.
120
+ * @param features - zero or more capabilities to assert.
121
+ * @returns the repo handle (throws `NotARepository` outside a repository).
122
+ */
123
+ export function require(dir, ...features) {
124
+ const discovered = repo(dir);
125
+ if (!discovered) {
126
+ throw vcsError('NotARepository', `not a repository: ${dir}`);
127
+ }
128
+ for (const feature of features) {
129
+ if (!discovered.supports(feature)) {
130
+ throw vcsError('Unsupported', `\`${feature}\` is not supported on a ${discovered.kind} repository`);
131
+ }
132
+ }
133
+ return discovered;
134
+ }
135
+ /**
136
+ * Like `repo`, but throws a `NotARepository` {@link VcsError}.
137
+ * @param dir - the directory to discover in.
138
+ * @returns the repo handle.
139
+ */
140
+ export function requireGit(dir) {
141
+ const repository = repo(dir);
142
+ if (!repository) {
143
+ throw vcsError('NotARepository', `not a repository: ${dir}`);
144
+ }
145
+ return repository;
146
+ }
147
+ /**
148
+ * Whether the nearest VCS ancestor is jj, making git automation unsafe.
149
+ * @param _dir - the directory to inspect (unused; no jj backend in this fork).
150
+ * @returns always `false` in this port.
151
+ */
152
+ export function isPureJj(_dir) {
153
+ // The fork has no Jujutsu backend; always false.
154
+ return false;
155
+ }
156
+ /* ── patch joining ─────────────────────────────────────────────────────── */
157
+ /**
158
+ * Join patch fragments verbatim, adding one final newline only when absent.
159
+ * Mirrors pi-vcs `join_patches`: parts are NOT re-joined with separators and
160
+ * trailing newlines are NOT collapsed, so a `GIT binary patch` terminator
161
+ * (a blank line after the payload) survives byte-exact (#8899).
162
+ * @param parts - the patch fragments to join, in order.
163
+ * @returns the joined patch text.
164
+ */
165
+ export function joinPatches(parts) {
166
+ let joined = '';
167
+ for (const part of parts) {
168
+ joined += part;
169
+ if (!part.endsWith('\n')) {
170
+ joined += '\n';
171
+ }
172
+ }
173
+ return joined;
174
+ }
175
+ /* ── HEAD watching ─────────────────────────────────────────────────────── */
176
+ /** Stat-poll interval for {@link watch}. */
177
+ export const HEAD_WATCH_INTERVAL_MS = 1000;
178
+ /**
179
+ * Watch a repository for head changes; returns a disposer.
180
+ * Stat-polls via `fs.watchFile` instead of `fs.watch`: backends may atomically
181
+ * replace the watched entry, permanently silencing inotify-backed watchers.
182
+ * @param repo - the repository returned by {@link repo} / {@link require}.
183
+ * @param onChange - called whenever the repository head changes.
184
+ * @param intervalMs - stat-poll interval in ms.
185
+ * @returns a disposer that stops watching.
186
+ */
187
+ export function watch(repo, onChange, intervalMs = HEAD_WATCH_INTERVAL_MS) {
188
+ const target = repo.watchTarget;
189
+ const listener = (curr, prev) => {
190
+ if (curr.mtimeMs !== prev.mtimeMs || curr.ino !== prev.ino || curr.size !== prev.size)
191
+ onChange();
192
+ };
193
+ watchFile(target, { interval: intervalMs }, listener).unref();
194
+ return () => { unwatchFile(target, listener); };
195
+ }
196
+ /**
197
+ * Worktree-relative prefix of a directory (pi-vcs `prefixOf`); null outside.
198
+ * @param repo - the repository handle.
199
+ * @param dir - an absolute (or repo-relative) path inside the worktree.
200
+ * @returns the worktree-relative prefix, or `null` for the root/outside paths.
201
+ */
202
+ export function prefixOf(repo, dir) {
203
+ const abs = isAbsolute(dir) ? normalize(dir) : join(repo.root, dir);
204
+ const relative = abs.startsWith(`${repo.root}${sep}`) ? abs.slice(repo.root.length + sep.length) : null;
205
+ if (relative === null)
206
+ return null;
207
+ return relative.length === 0 ? null : relative;
208
+ }
209
+ //# sourceMappingURL=vcs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vcs.js","sourceRoot":"","sources":["../src/vcs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,WAAW,CAAA;AACrE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAc,MAAM,SAAS,CAAA;AAoBtE;;;;;;GAMG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAG,UAAmB,CAAA;IACnC,IAAI,CAAc;IAClB,QAAQ,CAAQ;IAChB,MAAM,CAAQ;IACd,MAAM,CAAQ;IAEvB,YAAY,IAAkB,EAAE,OAAe,EAAE,SAAkE,EAAE;QACnH,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,IAAI,CAAC,CAAA;QACpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,IAAI,EAAE,CAAA;QACjC,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AAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IACnE,MAAM,QAAQ,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACvG,IAAI,QAAQ,KAAK,IAAI;QAAE,OAAO,IAAI,CAAA;IAClC,OAAO,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAA;AAChD,CAAC"}
@@ -0,0 +1,269 @@
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 type { GitService } from './service.ts';
38
+ /** Machine-readable failure codes carried by {@link WorktreeError}. */
39
+ export type WorktreeErrorCode = 'NotARepository' | 'UnsupportedRepository' | 'DefaultBranchUnknown' | 'LeaseMismatch' | 'UnknownWorktree' | 'DirtyWorktree' | 'UnlandedWorktree' | 'LeasedWorktree' | 'GitFailed' | 'MaxSlots';
40
+ /** A typed worktree-pool failure: semantic codes for the tool layer to branch on. */
41
+ export declare class WorktreeError extends Error {
42
+ readonly name: "WorktreeError";
43
+ readonly code: WorktreeErrorCode;
44
+ /** The worktree or pool path involved, when one exists. */
45
+ readonly path: string | undefined;
46
+ constructor(code: WorktreeErrorCode, message: string, path?: string);
47
+ }
48
+ /** Pool-level settings (shareable as a tool config row). */
49
+ export interface WorktreeSettings {
50
+ /**
51
+ * Pool root directory holding one sub-directory per repository
52
+ * (default `~/.treehouse`). Treated as a literal path — unlike treehouse it
53
+ * is not treated as the parent of a `.treehouse` directory (documented
54
+ * deviation D4; keep it explicit so an operator can point both tools at the
55
+ * same root if interop ever matters).
56
+ */
57
+ root?: string;
58
+ /**
59
+ * Default branch worktrees are cut from (default: inferred from
60
+ * `refs/remotes/origin/HEAD`, then the current branch).
61
+ */
62
+ baseBranch?: string;
63
+ /** Fetch origin before acquiring (default true; skipped when no origin exists). */
64
+ fetchBeforeAcquire?: boolean;
65
+ /** Max ms to wait for the cross-process pool-state lock (default 30000). */
66
+ lockWaitMs?: number;
67
+ /**
68
+ * Cap on total pooled slots for one repository (default 0 = unlimited).
69
+ * `acquireWorktree` still reuses a provably-idle slot when the cap is
70
+ * reached; it refuses to CUT a new slot and fails with code `MaxSlots`,
71
+ * leaving release/prune/destroy (or raising the cap) as the fix.
72
+ */
73
+ maxSlots?: number;
74
+ }
75
+ /** Per-acquire options. */
76
+ export interface AcquireOptions {
77
+ /**
78
+ * Cut HEAD at a NEW named branch instead of detached (DSH deviation D1, for
79
+ * `commit_apply --push` / PR flows). The branch is created from the reset
80
+ * target; a slot previously cut at the same branch name is the only slot
81
+ * this option may reuse (D5).
82
+ */
83
+ branch?: string;
84
+ /** Cut from this branch, overriding `settings.baseBranch` and inference. */
85
+ base?: string;
86
+ /** Lease holder label recorded in pool state (default `dsh`). */
87
+ holder?: string;
88
+ /** Skip the origin fetch even when `settings.fetchBeforeAcquire` is true. */
89
+ noFetch?: boolean;
90
+ signal?: AbortSignal;
91
+ }
92
+ /** A completed lease acquisition (the caller's durable ownership record). */
93
+ export interface WorktreeLease {
94
+ /** Absolute path of the worktree. */
95
+ path: string;
96
+ /** Immutable per-acquisition identity; required to release this slot. */
97
+ leaseId: string;
98
+ leaseHolder: string;
99
+ /** ISO timestamp of the acquisition. */
100
+ leasedAt: string;
101
+ /** The branch this slot was cut from (explicit or inferred). */
102
+ baseBranch: string;
103
+ /** Present when the slot was cut at a named branch (D1). */
104
+ branch?: string;
105
+ }
106
+ /** One pool slot as reported by {@link listWorktrees}. */
107
+ export interface WorktreeStatus {
108
+ /** Pool-relative slot name (the numeric directory). */
109
+ name: string;
110
+ path: string;
111
+ /** `leased` — durably reserved; `idle` — pooled and reusable; `damaged` — needs verification. */
112
+ status: 'leased' | 'idle' | 'damaged';
113
+ leased: boolean;
114
+ leaseId?: string;
115
+ leaseHolder?: string;
116
+ leasedAt?: string;
117
+ baseBranch: string;
118
+ /** The named branch this slot was cut at (D1), when any. */
119
+ branch?: string;
120
+ /** True when `git status --porcelain --untracked-files=all` is non-empty. */
121
+ dirty: boolean;
122
+ /** True when the worktree HEAD is an ancestor of the current reset target. */
123
+ merged: boolean;
124
+ /** True when the worktree directory still exists. */
125
+ exists: boolean;
126
+ }
127
+ /** One prune candidate or skip item. */
128
+ export interface WorktreePruneItem {
129
+ name: string;
130
+ path: string;
131
+ /** Human-readable reason: `removable`, or the skip reason. */
132
+ reason: string;
133
+ }
134
+ /** Result of {@link pruneWorktrees}. */
135
+ export interface WorktreePruneResult {
136
+ candidates: WorktreePruneItem[];
137
+ skipped: WorktreePruneItem[];
138
+ /** Paths actually removed when `yes` was passed. */
139
+ removed: string[];
140
+ }
141
+ /** Result of {@link destroyWorktree}. */
142
+ export interface WorktreeDestroyResult {
143
+ path: string;
144
+ /** True when the slot was actually removed; false for a dry-run preview. */
145
+ removed: boolean;
146
+ }
147
+ /** Result of {@link releaseWorktree}. */
148
+ export interface WorktreeReleaseResult {
149
+ path: string;
150
+ released: boolean;
151
+ }
152
+ /** One entry of the on-disk pool state (treehouse-compatible field names, own file — D4). */
153
+ export interface WorktreeStateEntry {
154
+ name: string;
155
+ path: string;
156
+ createdAt: string;
157
+ leased: boolean;
158
+ leaseId?: string;
159
+ leaseHolder?: string;
160
+ leasedAt?: string;
161
+ /** Explicit cut branch only (treehouse parity); empty for inferred. */
162
+ baseBranch: string;
163
+ /** Named branch this slot was cut at (D1). */
164
+ branch?: string;
165
+ /** True when this entry was rebuilt from disk after a corrupt/missing state file. */
166
+ recovered?: boolean;
167
+ }
168
+ /** The pool state file shape. */
169
+ export interface WorktreeState {
170
+ schema: 1;
171
+ /** Canonical (realpath) primary repository root the pool belongs to. */
172
+ repoRoot: string;
173
+ worktrees: WorktreeStateEntry[];
174
+ }
175
+ /**
176
+ * The PRIMARY repository root (the main checkout) owning `cwd`, canonicalized
177
+ * through realpath so one repository — main checkout or any linked worktree —
178
+ * always resolves to one pool key, even across `/tmp` vs `/private/tmp`.
179
+ * @param git - the git service.
180
+ * @param cwd - a directory inside any checkout of the repository.
181
+ * @param signal - optional abort.
182
+ * @returns the canonical absolute primary root.
183
+ */
184
+ export declare function primaryRepoRoot(git: GitService, cwd: string, signal?: AbortSignal): Promise<string>;
185
+ /**
186
+ * The pool directory for one primary repository root: `<root>/<repo>-<hash6>`
187
+ * where the hash is the first 6 hex chars of sha256 over the canonical root
188
+ * (stable offline; a remote URL is not consulted, unlike treehouse — D4).
189
+ * @param settings - pool settings (root default `~/.treehouse`).
190
+ * @param primaryRoot - canonical primary repository root.
191
+ * @returns the absolute pool directory.
192
+ */
193
+ export declare function resolveWorktreePoolRoot(settings: WorktreeSettings, primaryRoot: string): string;
194
+ /**
195
+ * Acquire a durable lease on one clean worktree slot. Never hands out a slot
196
+ * that cannot be proven idle (unleased) and clean with its HEAD already merged
197
+ * into the reset target; otherwise a new slot is cut. Holding the pool-state
198
+ * file lock for the whole choose-cut-reset cycle makes concurrent acquires (in
199
+ * any process) serialize, and `withRepoLock` on the primary root serializes
200
+ * with other in-process git mutations of the same repository.
201
+ *
202
+ * The returned lease is the caller's durable ownership record:
203
+ * `releaseWorktree` requires the exact `leaseId`, so a stale caller can never
204
+ * release someone else's slot.
205
+ * @param git - the git service.
206
+ * @param cwd - any checkout (main or worktree) of the target repository.
207
+ * @param settings - pool settings (root, default branch, fetch behavior).
208
+ * @param options - per-acquire options (named branch, base, holder, noFetch, signal).
209
+ * @returns the lease.
210
+ */
211
+ export declare function acquireWorktree(git: GitService, cwd: string, settings?: WorktreeSettings, options?: AcquireOptions): Promise<WorktreeLease>;
212
+ /**
213
+ * Release a leased worktree, clearing only the lease whose id matches. The
214
+ * slot is parked: a non-forced release requires a clean tree (tracked AND
215
+ * untracked) and then resets HEAD to the recorded base (or the inferred
216
+ * default) at detached HEAD; `force` additionally runs `git clean -fdqx`.
217
+ * D2: this engine never kills processes — a busy slot surfaces as a
218
+ * {@link WorktreeError} with code `DirtyWorktree` instead.
219
+ * @param git - the git service.
220
+ * @param cwd - any checkout of the pool's repository (fallback pool resolution).
221
+ * @param lease - the exact lease to release (`path` + `leaseId` from {@link acquireWorktree}).
222
+ * @param options - `force`, `settings` (root), `signal`.
223
+ */
224
+ export declare function releaseWorktree(git: GitService, cwd: string, lease: {
225
+ path: string;
226
+ leaseId: string;
227
+ }, options?: {
228
+ force?: boolean;
229
+ settings?: WorktreeSettings;
230
+ signal?: AbortSignal;
231
+ }): Promise<WorktreeReleaseResult>;
232
+ /**
233
+ * Report every slot of the pool owning `cwd`. Read-only; never mutates pool
234
+ * state. Status is computed live: `leased`, `idle` (clean + merged + present)
235
+ * or `damaged` (recovered/unverified, missing, or dirty).
236
+ */
237
+ export declare function listWorktrees(git: GitService, cwd: string, options?: {
238
+ settings?: WorktreeSettings;
239
+ signal?: AbortSignal;
240
+ }): Promise<WorktreeStatus[]>;
241
+ /**
242
+ * Produce (and with `yes`, execute) a prune plan for the pool owning `cwd`:
243
+ * only unleased, clean slots whose HEAD is merged into the current reset target
244
+ * are candidates; everything else is reported as skipped *without* removal.
245
+ * `all` sweeps every pool under the configured root. Dry-run unless `yes`.
246
+ */
247
+ export declare function pruneWorktrees(git: GitService, cwd: string, options?: {
248
+ yes?: boolean;
249
+ all?: boolean;
250
+ settings?: WorktreeSettings;
251
+ signal?: AbortSignal;
252
+ }): Promise<WorktreePruneResult>;
253
+ /**
254
+ * Destroy one pooled slot. Dry-run unless `yes`. Defaults refuse leased slots
255
+ * (`includeLeased`) and dirty or unmerged work (`includeUnlanded`) — the same
256
+ * guards as treehouse, with the same irreversible-data-loss semantics for the
257
+ * unlanded case.
258
+ */
259
+ export declare function destroyWorktree(git: GitService, cwd: string, options: {
260
+ /** Slot name (pool-relative) or absolute path under the pool. */
261
+ name?: string;
262
+ path?: string;
263
+ yes?: boolean;
264
+ includeLeased?: boolean;
265
+ includeUnlanded?: boolean;
266
+ settings?: WorktreeSettings;
267
+ signal?: AbortSignal;
268
+ }): Promise<WorktreeDestroyResult>;
269
+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