@laoyuehanni/dsh-git-worktree 0.4.4 → 0.4.6-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/lib/routes.js CHANGED
@@ -2,11 +2,25 @@
2
2
  * Route logic as pure functions: query/body in, status+body out. The HTTP
3
3
  * shell (index.ts) owns req/res mechanics; everything testable lives here.
4
4
  */
5
- import { dirname, join, resolve } from 'node:path';
6
- import { mkdir, stat } from 'node:fs/promises';
7
- import { GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, fetchAll, fsDirExists, inspectWorktree, isAbsoluteDir, probeRepo, probeWorkspaceGit, removeWorktree, switchBranch, updateBranch } from './git.js';
5
+ import { basename, dirname, join, resolve } from 'node:path';
6
+ import { mkdir, readdir, rm, stat } from 'node:fs/promises';
7
+ import { runPostCreateCopy } from './copy-files.js';
8
+ import { appendWorktreeExclude, fsExcludeSeams, GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, deleteBranch, fetchAll, fsDirExists, inspectWorktree, isAbsoluteDir, probeRepo, probeWorkspaceGit, removeWorktree, renameBranch, resolveBranch, switchBranch, updateBranch } from './git.js';
8
9
  import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
9
10
  import { resolveRootDir } from './settings.js';
11
+ /** Real fs-backed one-level directory listing (names only). Plain FILES are
12
+ * filtered out — the storage root can carry strays (a legacy settings.json
13
+ * was seen in the wild), and the scan lists worktree SLOTS, not entries. */
14
+ export async function fsListDir(path) {
15
+ try {
16
+ const dirents = await readdir(path, { withFileTypes: true });
17
+ return dirents.filter(entry => entry.isDirectory()).map(entry => entry.name);
18
+ }
19
+ catch {
20
+ // A missing storage root is the "no worktrees yet" answer, not an error.
21
+ return [];
22
+ }
23
+ }
10
24
  /** Real fs-backed directory probe: exists and is a directory. */
11
25
  export async function fsStatDirectory(path) {
12
26
  try {
@@ -31,6 +45,12 @@ const GROUP_PATHS_LIMIT = 256;
31
45
  * the batch can ride wider than the old three-spawn shape without stacking
32
46
  * an unreasonable number of concurrent git processes. */
33
47
  const GROUP_BATCH_SIZE = 16;
48
+ /** Upper bound on children one /worktrees-all scan probes. The storage root
49
+ * is this plugin's own slot directory, so a healthy one stays far below;
50
+ * the cap exists so a root pointed at something enormous (a misconfigured
51
+ * rootDir, a home directory) cannot turn one dialog open into thousands of
52
+ * git spawns. Past it the scan answers its first slice plus `truncated`. */
53
+ const SCAN_CHILDREN_LIMIT = 512;
34
54
  /**
35
55
  * POST /group — git belonging facts for a batch of workspace directories.
36
56
  * Deduplicates, validates, probes in bounded batches, and answers 200 with
@@ -76,6 +96,172 @@ export async function handleGroupWorktrees(deps, body) {
76
96
  }
77
97
  return { status: 200, body: { facts } };
78
98
  }
99
+ /** The project-internal layout directory name every repository uses. */
100
+ const PROJECT_LAYOUT_DIR = join('.dsh', 'gitworktree');
101
+ /**
102
+ * Whether `canonical` sits DIRECTLY inside a `<repo>/.dsh/gitworktree`
103
+ * layout root whose repository actually exists on disk. The layout names its
104
+ * own owner (two levels up must hold a `.git`), so no workspace list is
105
+ * needed to gate the plugin's territory — a plain fs probe decides.
106
+ */
107
+ function insideProjectLayout(canonical, dirExists) {
108
+ const layout = dirname(canonical);
109
+ if (basename(layout) !== 'gitworktree')
110
+ return false;
111
+ const dsh = dirname(layout);
112
+ if (basename(dsh) !== '.dsh')
113
+ return false;
114
+ return dirExists(join(dirname(dsh), '.git'));
115
+ }
116
+ /**
117
+ * POST /worktrees-all — git facts for every DIRECT child directory of the two
118
+ * storage locations the plugin has ever used, merged:
119
+ *
120
+ * - legacy: the resolved central storage root (today a read-only historical
121
+ * location — existing worktrees stay put, `rootDir` still resolves it);
122
+ * - project: `<repo>/.dsh/gitworktree` under every DISTINCT repository root
123
+ * derived from the caller's registered workspace paths (the current
124
+ * layout — its path prefix is what the workspace tree nests under).
125
+ *
126
+ * The management dialog's data source (and, through it, the lazy prune's):
127
+ * one scan answers for all repositories at once, orphan directories included
128
+ * (a child that probes as no git repository comes back with null facts
129
+ * rather than being dropped — the dialog shows it as unrecognized). Missing
130
+ * locations answer their half as an empty list; per-child probe failures
131
+ * degrade to null facts, never a 500 — the dialog must render, not error
132
+ * out. Each location that holds more than {@link SCAN_CHILDREN_LIMIT}
133
+ * children answers its first slice, and any truncation marks the whole
134
+ * response `truncated`, so a misconfigured location cannot turn one dialog
135
+ * open into thousands of git spawns.
136
+ * @param deps - host dependencies.
137
+ * @param body - parsed request body: `{ workspaces? }`.
138
+ */
139
+ export async function handleWorktreesAll(deps, body) {
140
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
141
+ return fail(400, 'request body must be a JSON object');
142
+ const workspacesRaw = body.workspaces ?? [];
143
+ if (!Array.isArray(workspacesRaw))
144
+ return fail(400, 'body key "workspaces" must be an array of absolute directories');
145
+ const unknownKeys = Object.keys(body).filter(key => key !== 'workspaces');
146
+ if (unknownKeys.length > 0)
147
+ return fail(400, `unknown body key "${unknownKeys[0]}"`);
148
+ const workspaces = [];
149
+ for (const candidate of workspacesRaw) {
150
+ if (typeof candidate !== 'string' || !isAbsoluteDir(candidate))
151
+ return fail(400, 'body key "workspaces" must be an array of absolute directories');
152
+ if (!workspaces.includes(candidate))
153
+ workspaces.push(candidate);
154
+ }
155
+ if (workspaces.length > GROUP_PATHS_LIMIT)
156
+ return fail(400, `body key "workspaces" accepts at most ${String(GROUP_PATHS_LIMIT)} distinct directories`);
157
+ const listDir = deps.listDir ?? fsListDir;
158
+ const facts = [];
159
+ let truncated = false;
160
+ const scanLocation = async (root, source) => {
161
+ const listed = await listDir(root);
162
+ if (listed.length > SCAN_CHILDREN_LIMIT) {
163
+ truncated = true;
164
+ listed.length = SCAN_CHILDREN_LIMIT;
165
+ }
166
+ for (let start = 0; start < listed.length; start += GROUP_BATCH_SIZE) {
167
+ const batch = listed.slice(start, start + GROUP_BATCH_SIZE);
168
+ const probed = await Promise.all(batch.map(async (child) => {
169
+ const path = join(root, child);
170
+ try {
171
+ const gitFacts = await probeWorkspaceGit(deps.exec, path);
172
+ return gitFacts === undefined
173
+ ? { path, repoName: null, branch: null, source }
174
+ : { path, repoName: gitFacts.repoName, branch: gitFacts.branch, source };
175
+ }
176
+ catch {
177
+ return { path, repoName: null, branch: null, source };
178
+ }
179
+ }));
180
+ facts.push(...probed);
181
+ }
182
+ };
183
+ const legacyRoot = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
184
+ await scanLocation(legacyRoot, 'legacy');
185
+ const statDirectory = deps.statDirectory ?? fsStatDirectory;
186
+ const legacyRootExists = await statDirectory(legacyRoot);
187
+ // Project half: one belonging probe per DISTINCT workspace path (bounded
188
+ // batches, same as /group), then one scan per DISTINCT repository root.
189
+ const repoRoots = new Set();
190
+ for (let start = 0; start < workspaces.length; start += GROUP_BATCH_SIZE) {
191
+ const batch = workspaces.slice(start, start + GROUP_BATCH_SIZE);
192
+ const probed = await Promise.all(batch.map(async (path) => {
193
+ try {
194
+ return await probeWorkspaceGit(deps.exec, path);
195
+ }
196
+ catch {
197
+ return undefined;
198
+ }
199
+ }));
200
+ for (const workspaceFacts of probed) {
201
+ if (workspaceFacts !== undefined)
202
+ repoRoots.add(workspaceFacts.repoRoot);
203
+ }
204
+ }
205
+ for (const repoRoot of repoRoots) {
206
+ await scanLocation(join(repoRoot, PROJECT_LAYOUT_DIR), 'project');
207
+ }
208
+ return { status: 200, body: { worktrees: facts, legacyRoot, legacyRootExists, ...truncated ? { truncated } : {} } };
209
+ }
210
+ /** Real fs-backed recursive force rm (Windows file-lock retries included). */
211
+ export async function fsRmRecursive(path) {
212
+ await rm(path, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });
213
+ }
214
+ /** Create the layout root through the deps seam (tests substitute a no-op). */
215
+ function mkdirSlot(deps, layoutRoot) {
216
+ const mkdirRecursive = deps.mkdirRecursive ?? fsMkdirRecursive;
217
+ return mkdirRecursive(layoutRoot);
218
+ }
219
+ /**
220
+ * POST /purge — delete a NON-git directory sitting DIRECTLY inside one of the
221
+ * plugin's two storage layouts: the legacy central root or a repository's
222
+ * `.dsh/gitworktree`. The orphaned leftover a half-failed `worktree remove`
223
+ * can leave behind (git registration and the .git file already gone,
224
+ * contents stranded on disk). Triple-gated: one level below a storage
225
+ * location (resolved forms, same slot boundary as /ensure-directory), a real
226
+ * directory, and NOT a git repository — anything git still recognizes must
227
+ * go through /remove, where the removal carries the session-archive and
228
+ * unregistration half. Deletion is a plain recursive force rm.
229
+ * @param deps - host dependencies.
230
+ * @param body - parsed request body: `{ path }`.
231
+ */
232
+ export async function handlePurgeDirectory(deps, body) {
233
+ const parsed = readBody(body, ['path']);
234
+ if (isOutcome(parsed))
235
+ return parsed;
236
+ const { path } = parsed;
237
+ if (!isAbsoluteDir(path))
238
+ return fail(400, '"path" must be an absolute directory');
239
+ const configured = deps.sectionRootDir()?.trim();
240
+ if (configured !== undefined && configured !== '' && !isAbsoluteConfigPath(configured)) {
241
+ return fail(400, `configured rootDir "${String(deps.sectionRootDir())}" is not an absolute path`);
242
+ }
243
+ const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
244
+ const canonical = resolve(path);
245
+ if (dirname(canonical) !== resolve(rootDir) && !insideProjectLayout(canonical, deps.dirExists ?? fsDirExists)) {
246
+ return fail(400, `"${canonical}" is outside the plugin's worktree storage locations`);
247
+ }
248
+ const statDirectory = deps.statDirectory ?? fsStatDirectory;
249
+ if (!(await statDirectory(canonical))) {
250
+ return fail(400, `"${canonical}" is not a directory`);
251
+ }
252
+ const gitFacts = await probeWorkspaceGit(deps.exec, canonical);
253
+ if (gitFacts !== undefined) {
254
+ return fail(400, `"${canonical}" is a git repository; remove it as a worktree instead`);
255
+ }
256
+ const rmRecursive = deps.rmRecursive ?? fsRmRecursive;
257
+ try {
258
+ await rmRecursive(canonical);
259
+ return { status: 200, body: { path: canonical, removed: true } };
260
+ }
261
+ catch (error) {
262
+ return fail(500, error instanceof Error ? error.message : String(error));
263
+ }
264
+ }
79
265
  /** GitError to outcome: usage-shaped failures are 400, the rest 500. */
80
266
  function gitFailure(error) {
81
267
  const usage = error.stderr.includes('usage:')
@@ -101,6 +287,11 @@ function gitFailure(error) {
101
287
  // texts (a remote that vanished mid-fetch: `Repository '...' not
102
288
  // found`) carry no quoted branch and stay 500 host faults.
103
289
  || error.stderr.includes('branch "')
290
+ // Deletion refusals from `git branch -d` are the user's repo state the
291
+ // same way: unmerged commits (the safe delete's whole point) and a
292
+ // branch checked out in some worktree.
293
+ || error.stderr.includes('is not fully merged')
294
+ || error.stderr.includes('Cannot delete branch')
104
295
  // Removal refusals from git.ts are caller-side state the same way: the
105
296
  // main worktree (git refuses it too, but the route answers a clean 400
106
297
  // before ever spawning git) and a path the repository never registered
@@ -127,6 +318,7 @@ export async function handleStatus(deps, path) {
127
318
  repo: true,
128
319
  repoName: facts.repoName,
129
320
  repoRoot: facts.repoRoot,
321
+ main: facts.main,
130
322
  currentBranch: facts.currentBranch,
131
323
  branches: facts.branches,
132
324
  worktrees: facts.worktrees,
@@ -167,9 +359,14 @@ function isOutcome(value) {
167
359
  return typeof value === 'object' && value !== null && 'status' in value && 'body' in value;
168
360
  }
169
361
  /**
170
- * POST /worktree 鈥?create or reuse the worktree for a branch, then report the
171
- * directory so the client can register it as a workspace. With `cutout: true`
172
- * the branch is the CURRENT checkout (occupied by the main worktree, so git
362
+ * POST /worktree — create or reuse the worktree for a branch, then report the
363
+ * directory so the client can register it as a workspace. The worktree lands
364
+ * at `<repo>/.dsh/gitworktree/<branch>` (path prefix = repository, so the
365
+ * native workspace tree nests it under its repository automatically); an
366
+ * existing registration for the branch ANYWHERE is reused first (the
367
+ * repository-wide worktree list is location-independent — legacy-central
368
+ * worktrees keep being returned, never duplicated). With `cutout: true` the
369
+ * branch is the CURRENT checkout (occupied by the main worktree, so git
173
370
  * refuses to add it): a new branch is cut out of it (`<branch>-wt`, first
174
371
  * free `-wt<N>` suffix) and isolated in the fresh worktree instead.
175
372
  * @param deps - host dependencies.
@@ -184,15 +381,39 @@ export async function handleCreateWorktree(deps, body) {
184
381
  return fail(400, '"repoPath" must be an absolute directory');
185
382
  if (branch.trim() === '')
186
383
  return fail(400, '"branch" must be non-empty');
187
- const configured = deps.sectionRootDir()?.trim();
188
- if (configured !== undefined && configured !== '' && !isAbsoluteConfigPath(configured)) {
189
- return fail(400, `configured rootDir "${String(deps.sectionRootDir())}" is not an absolute path`);
190
- }
191
384
  try {
192
385
  const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
193
386
  if (facts === undefined)
194
387
  return fail(400, `"${repoPath}" is not inside a git repository`);
195
- const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
388
+ // Local-ignore first, creation second: the rule is harmless when the
389
+ // creation later fails (the directory simply does not exist), while the
390
+ // reverse order leaves a created worktree visible as untracked on the
391
+ // next `git status` when the write fails. A write failure never blocks
392
+ // the creation — the worktree cannot be rolled back — it rides the
393
+ // successful response as `excludeWarning` for the client to toast.
394
+ const excludeWarning = await appendWorktreeExclude(deps.excludeSeams ?? fsExcludeSeams, facts.repoRoot);
395
+ const layoutRoot = join(facts.repoRoot, PROJECT_LAYOUT_DIR);
396
+ // Optional pre-create remote sync — but only when the branch actually
397
+ // consumes remote data: a LOCAL branch's worktree (or an existing twin)
398
+ // never reads the fetched refs, so the resolve runs first and the fetch
399
+ // fires just for the remote-only shape (the twin `worktree add -b`
400
+ // consumes it, the cutout's arbitrary base too). Deliberately NOT a
401
+ // gate: a network hiccup must not block the creation — the failure
402
+ // rides the successful response as `fetchWarning` for the client to
403
+ // toast.
404
+ let fetchWarning;
405
+ if (deps.sectionFetchBeforeCreate() === true) {
406
+ const resolved = await resolveBranch(deps.exec, facts.repoRoot, branch);
407
+ if (resolved?.remote !== undefined) {
408
+ try {
409
+ await fetchAll(deps.exec, facts.repoRoot);
410
+ }
411
+ catch (error) {
412
+ fetchWarning = error instanceof GitError ? error.stderr.trim() : error instanceof Error ? error.message : String(error);
413
+ }
414
+ }
415
+ }
416
+ const warnings = { ...fetchWarning === undefined ? {} : { fetchWarning }, ...excludeWarning === undefined ? {} : { excludeWarning } };
196
417
  if (cutout === true) {
197
418
  // An explicit name skips the `-wt` suffix walk and is used verbatim —
198
419
  // both for the branch and the storage folder. A leading dash would
@@ -202,31 +423,38 @@ export async function handleCreateWorktree(deps, body) {
202
423
  if (custom !== undefined && custom !== '') {
203
424
  if (custom.startsWith('-'))
204
425
  return fail(400, '"name" must not start with "-"');
205
- const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(custom)}`);
206
- await mkdir(rootDir, { recursive: true });
426
+ const target = join(layoutRoot, sanitizeBranchDir(custom));
427
+ await mkdirSlot(deps, layoutRoot);
207
428
  await addWorktreeCutout(deps.exec, facts.repoRoot, branch, custom, target);
208
- return { status: 200, body: { path: target, created: true } };
429
+ const copyWarning = await runPostCreateCopy(deps, facts.repoRoot, target);
430
+ const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
431
+ return { status: 200, body: { path: target, created: true, ...warnings, ...copyWarnObj } };
209
432
  }
210
433
  // The new branch name must be known before the folder name can be
211
- // computed: the folder carries `<repoName>-<NEW branch>`. The name
212
- // must be free in BOTH namespaces — the branch table and the storage
213
- // folder: a leftover folder of a since-deleted branch would otherwise
214
- // fail `worktree add` with a bare "already exists", so the suffix
215
- // walk probes the folder too.
434
+ // computed: the folder carries the NEW branch's directory name. The
435
+ // name must be free in BOTH namespaces — the branch table and the
436
+ // storage folder: a leftover folder of a since-deleted branch would
437
+ // otherwise fail `worktree add` with a bare "already exists", so the
438
+ // suffix walk probes the folder too.
216
439
  const dirExists = deps.dirExists ?? fsDirExists;
217
- const newBranch = await cutoutBranchName(deps.exec, facts.repoRoot, branch, (candidate) => dirExists(join(rootDir, `${facts.repoName}-${sanitizeBranchDir(candidate)}`)));
218
- const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(newBranch)}`);
219
- await mkdir(rootDir, { recursive: true });
440
+ const newBranch = await cutoutBranchName(deps.exec, facts.repoRoot, branch, (candidate) => dirExists(join(layoutRoot, sanitizeBranchDir(candidate))));
441
+ const target = join(layoutRoot, sanitizeBranchDir(newBranch));
442
+ await mkdirSlot(deps, layoutRoot);
220
443
  await addWorktreeCutout(deps.exec, facts.repoRoot, branch, newBranch, target);
221
- return { status: 200, body: { path: target, created: true } };
444
+ const copyWarning = await runPostCreateCopy(deps, facts.repoRoot, target);
445
+ const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
446
+ return { status: 200, body: { path: target, created: true, ...warnings, ...copyWarnObj } };
222
447
  }
223
- // The folder name carries the belonging itself: `<repoName>-<branch>` —
224
- // the sidebar group title (the folder basename) then reads as the parent
225
- // repository plus the branch instead of a bare branch word.
226
- const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(branch)}`);
227
- await mkdir(rootDir, { recursive: true });
448
+ // The folder name carries the branch: `<repo>/.dsh/gitworktree/<branch>`.
449
+ const target = join(layoutRoot, sanitizeBranchDir(branch));
450
+ await mkdirSlot(deps, layoutRoot);
228
451
  const result = await addWorktree(deps.exec, facts.repoRoot, branch, target, deps.dirExists);
229
- return { status: 200, body: result };
452
+ let copyWarning;
453
+ if (result.created) {
454
+ copyWarning = await runPostCreateCopy(deps, facts.repoRoot, result.path);
455
+ }
456
+ const copyWarnObj = copyWarning !== undefined ? { copyWarning } : {};
457
+ return { status: 200, body: { ...result, ...warnings, ...copyWarnObj } };
230
458
  }
231
459
  catch (error) {
232
460
  if (error instanceof GitError)
@@ -263,18 +491,23 @@ export async function handleSwitch(deps, body) {
263
491
  }
264
492
  }
265
493
  /**
266
- * POST /branch 鈥?create a NEW branch from the queried directory's current
267
- * checkout (whatever its HEAD points at, detached included) and check it out
268
- * in place. Git validates the name; the client pre-flights the same rules
494
+ * POST /branch — create a NEW branch. Without `from`, from the queried
495
+ * directory's current checkout (whatever its HEAD points at, detached
496
+ * included), checked out in place. With `from` (a local branch or a remote
497
+ * tracking ref): checked out here too when `checkout` is set
498
+ * (`git switch -c <name> <from>`), created with no checkout touched
499
+ * otherwise (`git branch`) — a create aimed at another branch must not
500
+ * silently move the session's HEAD unless the caller asked for exactly
501
+ * that. Git validates both names; the client pre-flights the same rules
269
502
  * and only sends names it already accepts.
270
503
  * @param deps - host dependencies.
271
504
  * @param body - parsed request body.
272
505
  */
273
506
  export async function handleCreateBranch(deps, body) {
274
- const parsed = readBody(body, ['repoPath', 'name']);
507
+ const parsed = readBody(body, ['repoPath', 'name'], ['checkout'], ['from']);
275
508
  if (isOutcome(parsed))
276
509
  return parsed;
277
- const { repoPath, name } = parsed;
510
+ const { repoPath, name, from, checkout } = parsed;
278
511
  if (!isAbsoluteDir(repoPath))
279
512
  return fail(400, '"repoPath" must be an absolute directory');
280
513
  if (name.trim() === '')
@@ -283,11 +516,25 @@ export async function handleCreateBranch(deps, body) {
283
516
  // exec, not as an "unknown switch" GitError.
284
517
  if (name.startsWith('-'))
285
518
  return fail(400, '"name" must not start with "-"');
519
+ // The same flag-ride guard for the start point, which lands on
520
+ // `git branch <name> <from>` verbatim (a remote ref like `origin/x` is
521
+ // the caller's legitimate shape — passed through untouched).
522
+ if (from !== undefined) {
523
+ if (from.trim() === '')
524
+ return fail(400, '"from" must be non-empty when present');
525
+ if (from.startsWith('-'))
526
+ return fail(400, '"from" must not start with "-"');
527
+ }
286
528
  try {
287
529
  const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
288
530
  if (facts === undefined)
289
531
  return fail(400, `"${repoPath}" is not inside a git repository`);
290
- const created = await createBranch(deps.exec, facts.repoRoot, name);
532
+ // The session's OWN worktree: the no-`from` shape cuts from — and checks
533
+ // out in — the queried directory's HEAD, and `from` + `checkout` checks
534
+ // out HERE. `repoRoot` would move the main checkout instead of the
535
+ // worktree the session sits in (identical directory when it IS the main
536
+ // checkout).
537
+ const created = await createBranch(deps.exec, facts.toplevel, name, from, checkout === true);
291
538
  const result = { branch: created };
292
539
  return { status: 200, body: result };
293
540
  }
@@ -297,6 +544,79 @@ export async function handleCreateBranch(deps, body) {
297
544
  return fail(500, error instanceof Error ? error.message : String(error));
298
545
  }
299
546
  }
547
+ /**
548
+ * POST /branch-rename — rename a LOCAL branch (`git branch -m`). Runs at the
549
+ * repository root: branch refs are repository-wide and worktree HEADs
550
+ * pointing at the old name follow the ref. Git validates the new name and
551
+ * refuses a target that already exists; both map to 400 through
552
+ * {@link gitFailure}.
553
+ * @param deps - host dependencies.
554
+ * @param body - parsed request body.
555
+ */
556
+ export async function handleRenameBranch(deps, body) {
557
+ const parsed = readBody(body, ['repoPath', 'name', 'newName']);
558
+ if (isOutcome(parsed))
559
+ return parsed;
560
+ const { repoPath, name, newName } = parsed;
561
+ if (!isAbsoluteDir(repoPath))
562
+ return fail(400, '"repoPath" must be an absolute directory');
563
+ if (name.trim() === '')
564
+ return fail(400, '"name" must be non-empty');
565
+ if (newName.trim() === '')
566
+ return fail(400, '"newName" must be non-empty');
567
+ // Same flag-ride guard as the create route: the new name lands on
568
+ // `git branch -m <name> <newName>` verbatim.
569
+ if (newName.startsWith('-'))
570
+ return fail(400, '"newName" must not start with "-"');
571
+ try {
572
+ const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
573
+ if (facts === undefined)
574
+ return fail(400, `"${repoPath}" is not inside a git repository`);
575
+ const renamed = await renameBranch(deps.exec, facts.repoRoot, name, newName);
576
+ const result = { branch: renamed };
577
+ return { status: 200, body: result };
578
+ }
579
+ catch (error) {
580
+ if (error instanceof GitError)
581
+ return gitFailure(error);
582
+ return fail(500, error instanceof Error ? error.message : String(error));
583
+ }
584
+ }
585
+ /**
586
+ * POST /branch-delete — delete a LOCAL branch with the SAFE form
587
+ * (`git branch -d`): git refuses unmerged commits and branches checked out
588
+ * in any worktree, both mapping to 400 through {@link gitFailure}. No
589
+ * force variant — a menu click must never discard commits.
590
+ * @param deps - host dependencies.
591
+ * @param body - parsed request body.
592
+ */
593
+ export async function handleDeleteBranch(deps, body) {
594
+ const parsed = readBody(body, ['repoPath', 'name']);
595
+ if (isOutcome(parsed))
596
+ return parsed;
597
+ const { repoPath, name } = parsed;
598
+ if (!isAbsoluteDir(repoPath))
599
+ return fail(400, '"repoPath" must be an absolute directory');
600
+ if (name.trim() === '')
601
+ return fail(400, '"name" must be non-empty');
602
+ // Same flag-ride guard as its sibling routes: the name lands on
603
+ // `git branch -d <name>` verbatim.
604
+ if (name.startsWith('-'))
605
+ return fail(400, '"name" must not start with "-"');
606
+ try {
607
+ const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
608
+ if (facts === undefined)
609
+ return fail(400, `"${repoPath}" is not inside a git repository`);
610
+ const deleted = await deleteBranch(deps.exec, facts.repoRoot, name);
611
+ const result = { branch: deleted };
612
+ return { status: 200, body: result };
613
+ }
614
+ catch (error) {
615
+ if (error instanceof GitError)
616
+ return gitFailure(error);
617
+ return fail(500, error instanceof Error ? error.message : String(error));
618
+ }
619
+ }
300
620
  /**
301
621
  * POST /fetch 鈥?sync remote-tracking refs for the repository: fetch every
302
622
  * remote and prune tracking branches the remotes no longer carry. Pure
@@ -345,7 +665,11 @@ export async function handleUpdate(deps, body) {
345
665
  const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
346
666
  if (facts === undefined)
347
667
  return fail(400, `"${repoPath}" is not inside a git repository`);
348
- const outcome = await updateBranch(deps.exec, facts.repoRoot);
668
+ // The session's OWN worktree, not the main checkout: in a linked-worktree
669
+ // session "update current branch" means the branch that worktree holds.
670
+ // `repoRoot` would fast-forward the main checkout behind the user's back
671
+ // (both are the same directory when the session IS the main checkout).
672
+ const outcome = await updateBranch(deps.exec, facts.toplevel);
349
673
  const result = { branch: outcome.branch, updated: outcome.updated };
350
674
  return { status: 200, body: result };
351
675
  }
@@ -450,23 +774,26 @@ export async function handlePathExists(deps, body) {
450
774
  exists[path] = await statDirectory(path).catch(() => false);
451
775
  }));
452
776
  // Rebuildability is a STORAGE-SLOT fact, not a general one: only a missing
453
- // path sitting DIRECTLY inside the resolved worktree root is a slot this
454
- // plugin planned, so recreating the empty directory is safe self-healing
455
- // (its sessions reattach by realpath once the folder is back). Paths
456
- // outside the root are the user's own territory — never rebuilt here.
777
+ // path sitting DIRECTLY inside one of the plugin's storage locations (the
778
+ // legacy root, or a repository's `.dsh/gitworktree`) is a slot this plugin
779
+ // planned, so recreating the empty directory is safe self-healing (its
780
+ // sessions reattach by realpath once the folder is back). Paths outside
781
+ // both are the user's own territory — never rebuilt here.
457
782
  const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
783
+ const dirExists = deps.dirExists ?? fsDirExists;
458
784
  const rebuildable = {};
459
785
  for (const path of distinct) {
460
786
  if (exists[path])
461
787
  continue;
462
- rebuildable[path] = dirname(resolve(path)) === resolve(rootDir);
788
+ rebuildable[path] = dirname(resolve(path)) === resolve(rootDir) || insideProjectLayout(resolve(path), dirExists);
463
789
  }
464
790
  return { status: 200, body: { exists, ...Object.values(rebuildable).some(Boolean) ? { rebuildable } : {} } };
465
791
  }
466
792
  /**
467
793
  * POST /ensure-directory — recreate a MISSING worktree storage slot
468
- * (`mkdir -p`). Strictly gated to paths sitting DIRECTLY inside the resolved
469
- * worktree storage root: those slots were planned and created by this plugin,
794
+ * (`mkdir -p`). Strictly gated to paths sitting DIRECTLY inside one of the
795
+ * plugin's two storage layouts (the legacy central root, or a repository's
796
+ * `.dsh/gitworktree`): those slots were planned and created by this plugin,
470
797
  * so rebuilding the empty folder is self-healing (historical sessions
471
798
  * reattach automatically once realpath matches again — DSH keeps the
472
799
  * workspace accounting and filters membership by the session header's cwd).
@@ -488,10 +815,10 @@ export async function handleEnsureDirectory(deps, body) {
488
815
  }
489
816
  const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
490
817
  const canonical = resolve(path);
491
- // Exactly one level below the root, compared on resolved forms so `..`
492
- // and spelling drift cannot escape the slot boundary.
493
- if (dirname(canonical) !== resolve(rootDir)) {
494
- return fail(400, `"${canonical}" is outside the worktree storage root "${resolve(rootDir)}"`);
818
+ // Exactly one level below a storage location, compared on resolved forms
819
+ // so `..` and spelling drift cannot escape the slot boundary.
820
+ if (dirname(canonical) !== resolve(rootDir) && !insideProjectLayout(canonical, deps.dirExists ?? fsDirExists)) {
821
+ return fail(400, `"${canonical}" is outside the plugin's worktree storage locations`);
495
822
  }
496
823
  const mkdirRecursive = deps.mkdirRecursive ?? fsMkdirRecursive;
497
824
  try {
package/lib/settings.d.ts CHANGED
@@ -6,11 +6,6 @@
6
6
  * the legacy file is read once at startup and its value migrated across (the
7
7
  * renamed file stays behind as a backup).
8
8
  */
9
- /** The persisted document shape the pre-0.3 plugin read and wrote on its own. */
10
- export interface LegacySettings {
11
- /** Worktree storage root; '' selected the default ~/.dsh/gitworktree. */
12
- rootDir: string;
13
- }
14
9
  /**
15
10
  * Resolve the effective worktree storage root: an explicit non-blank `rootDir`
16
11
  * wins; otherwise `$DSH_HOME/gitworktree` (a blank `$DSH_HOME` counts as
@@ -27,25 +22,3 @@ export declare function resolveRootDir(rootDir: string | undefined, home: string
27
22
  * @param rootDir - the resolved section value.
28
23
  */
29
24
  export declare function validateRootDir(rootDir: string | undefined): void;
30
- /**
31
- * Decide what a legacy-file migration should store, if anything: the legacy
32
- * root only crosses over when it names a directory (blank kept the default,
33
- * which the section's absence already expresses) and the user layer has not
34
- * recorded its own choice (key presence, not a value comparison — an override
35
- * equal to the legacy value is still the user's own doing and must not be
36
- * rewritten).
37
- * @param legacy - the legacy file's stored value.
38
- * @param userLayer - the namespace's raw user layer, when one exists.
39
- * @returns the rootDir to write, or undefined to leave the section alone.
40
- */
41
- export declare function planLegacyMigration(legacy: LegacySettings, userLayer: Record<string, unknown> | undefined): string | undefined;
42
- /**
43
- * Load the legacy settings document.
44
- * @param file - absolute settings file path.
45
- * @returns the stored value, or the default when absent/unreadable/invalid.
46
- */
47
- export declare function loadLegacySettings(file: string): Promise<LegacySettings>;
48
- /** Resolve the legacy settings file location for a home directory. */
49
- export declare function settingsFileOf(home: string): string;
50
- /** The backup name a migrated legacy file is renamed to (never deleted). */
51
- export declare function migratedFileOf(file: string): string;
package/lib/settings.js CHANGED
@@ -6,7 +6,6 @@
6
6
  * the legacy file is read once at startup and its value migrated across (the
7
7
  * renamed file stays behind as a backup).
8
8
  */
9
- import { readFile } from 'node:fs/promises';
10
9
  import { join } from 'node:path';
11
10
  import { isAbsoluteConfigPath } from './normalize.js';
12
11
  /**
@@ -40,52 +39,3 @@ export function validateRootDir(rootDir) {
40
39
  throw new Error(`rootDir "${rootDir}" is not an absolute path`);
41
40
  }
42
41
  }
43
- /**
44
- * Decide what a legacy-file migration should store, if anything: the legacy
45
- * root only crosses over when it names a directory (blank kept the default,
46
- * which the section's absence already expresses) and the user layer has not
47
- * recorded its own choice (key presence, not a value comparison — an override
48
- * equal to the legacy value is still the user's own doing and must not be
49
- * rewritten).
50
- * @param legacy - the legacy file's stored value.
51
- * @param userLayer - the namespace's raw user layer, when one exists.
52
- * @returns the rootDir to write, or undefined to leave the section alone.
53
- */
54
- export function planLegacyMigration(legacy, userLayer) {
55
- if (userLayer !== undefined && Object.hasOwn(userLayer, 'rootDir'))
56
- return undefined;
57
- const value = legacy.rootDir.trim();
58
- return value === '' ? undefined : value;
59
- }
60
- /**
61
- * Load the legacy settings document.
62
- * @param file - absolute settings file path.
63
- * @returns the stored value, or the default when absent/unreadable/invalid.
64
- */
65
- export async function loadLegacySettings(file) {
66
- let raw;
67
- try {
68
- raw = await readFile(file, 'utf8');
69
- }
70
- catch {
71
- return { rootDir: '' };
72
- }
73
- try {
74
- const parsed = JSON.parse(raw);
75
- if (typeof parsed !== 'object' || parsed === null)
76
- return { rootDir: '' };
77
- const rootDir = parsed.rootDir;
78
- return typeof rootDir === 'string' ? { rootDir } : { rootDir: '' };
79
- }
80
- catch {
81
- return { rootDir: '' };
82
- }
83
- }
84
- /** Resolve the legacy settings file location for a home directory. */
85
- export function settingsFileOf(home) {
86
- return join(home, '.dsh', 'git-worktree', 'settings.json');
87
- }
88
- /** The backup name a migrated legacy file is renamed to (never deleted). */
89
- export function migratedFileOf(file) {
90
- return `${file}.migrated`;
91
- }