@laoyuehanni/dsh-git-worktree 0.4.4 → 0.4.5

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/git.d.ts CHANGED
@@ -32,6 +32,17 @@ export interface RepoFacts {
32
32
  repoRoot: string;
33
33
  /** Main repository directory basename. */
34
34
  repoName: string;
35
+ /** The QUERIED directory's own toplevel — the worktree the session
36
+ * actually sits in. Repository-wide commands (branch refs, fetch,
37
+ * worktree registration) run at {@link RepoFacts.repoRoot}; commands that
38
+ * act on the session's own checkout (switch/update/create-and-check-out)
39
+ * run HERE, or a linked-worktree session would silently operate on the
40
+ * main checkout instead. */
41
+ toplevel: string;
42
+ /** Whether the QUERIED directory is the main worktree — see
43
+ * {@link isMainWorktree}. `repoRoot` cannot answer this: it names the main
44
+ * checkout from every worktree by construction. */
45
+ main: boolean;
35
46
  /** Branch checked out by the queried directory. */
36
47
  currentBranch: string;
37
48
  branches: BranchEntry[];
@@ -63,6 +74,18 @@ export declare function fsSweepDir(path: string): Promise<'gone' | 'empty' | 'oc
63
74
  * @param dirExists - existence seam for stale-registration filtering.
64
75
  */
65
76
  export declare function probeRepo(exec: Exec, path: string, dirExists?: DirExists): Promise<RepoFacts | undefined>;
77
+ /**
78
+ * Resolve a branch display name against the authoritative branch list of the
79
+ * repository. Exported for the /worktree route's fetch gate: the pre-create
80
+ * remote sync only earns its round trip when the display name is REMOTE-only
81
+ * (a local branch's worktree never consumes fetched refs).
82
+ * @returns the local name plus the tracking remote when the display name is
83
+ * remote-only, or undefined when neither shape exists.
84
+ */
85
+ export declare function resolveBranch(exec: Exec, repoRoot: string, branch: string): Promise<{
86
+ local: string;
87
+ remote: string | undefined;
88
+ } | undefined>;
66
89
  /**
67
90
  * Create (or reuse) the worktree for one branch.
68
91
  *
@@ -119,18 +142,53 @@ export declare function addWorktreeCutout(exec: Exec, repoRoot: string, base: st
119
142
  */
120
143
  export declare function switchBranch(exec: Exec, repoRoot: string, branch: string): Promise<string>;
121
144
  /**
122
- * Create a NEW branch from the current checkout and check it out in place
123
- * (`git switch -c`): the cut point is whatever the queried directory's HEAD
124
- * points at, so a detached or unborn checkout cuts from the current commit
125
- * too. Runs at the queried directory's own toplevel — a session inside a
126
- * linked worktree creates and checks out within that worktree, never the
127
- * main checkout (the same semantics as {@link switchBranch}).
145
+ * Create a NEW branch. Three shapes:
146
+ *
147
+ * - no `from`: cut from the current checkout and check it out in place
148
+ * (`git switch -c`) — the cut point is whatever the queried directory's
149
+ * HEAD points at, so a detached or unborn checkout cuts from the current
150
+ * commit too. Runs at the queried directory's own toplevel — a session
151
+ * inside a linked worktree creates and checks out within that worktree,
152
+ * never the main checkout (the same semantics as {@link switchBranch}).
153
+ * - `from` without `checkout`: create AT that start point WITHOUT touching
154
+ * any checkout (`git branch`) — a create aimed at another branch must
155
+ * not move this session's HEAD.
156
+ * - `from` with `checkout`: create at the start point AND check it out
157
+ * here in one stroke (`git switch -c <name> <from>`).
128
158
  * @param exec - executor seam.
129
159
  * @param cwd - directory whose HEAD the branch is cut from (worktree toplevel).
130
160
  * @param name - new branch name (git validates; failures raise GitError).
131
- * @returns the branch name now created and checked out.
161
+ * @param from - optional start point; absent keeps the in-place semantics.
162
+ * @param checkout - with `from`, also check the new branch out here.
163
+ * @returns the branch name now created (checked out unless created at a
164
+ * start point with `checkout` false).
165
+ */
166
+ export declare function createBranch(exec: Exec, cwd: string, name: string, from?: string, checkout?: boolean): Promise<string>;
167
+ /**
168
+ * Rename a LOCAL branch (`git branch -m`): branch refs are repository-wide,
169
+ * so the command runs at the repository root and every worktree HEAD pointing
170
+ * at the old name follows the ref. Git validates the new name and refuses a
171
+ * target that already exists; remote branches are not renameable (not ours).
172
+ * @param exec - executor seam.
173
+ * @param repoRoot - main worktree directory.
174
+ * @param name - branch to rename.
175
+ * @param newName - the new local name.
176
+ * @returns the new name.
177
+ */
178
+ export declare function renameBranch(exec: Exec, repoRoot: string, name: string, newName: string): Promise<string>;
179
+ /**
180
+ * Delete a LOCAL branch (`git branch -d`, the SAFE form): git refuses a
181
+ * branch with unmerged commits ("not fully merged") and one checked out in
182
+ * any worktree — both caller-side state, mapped to 400 by the route. No
183
+ * `-D` force variant on purpose: a menu click must never discard commits
184
+ * (the terminal is the place for deliberate force-deletes). Runs at the
185
+ * repository root; remote branches are not ours to delete.
186
+ * @param exec - executor seam.
187
+ * @param repoRoot - main worktree directory.
188
+ * @param name - branch to delete.
189
+ * @returns the name of the branch that was deleted.
132
190
  */
133
- export declare function createBranch(exec: Exec, cwd: string, name: string): Promise<string>;
191
+ export declare function deleteBranch(exec: Exec, repoRoot: string, name: string): Promise<string>;
134
192
  /**
135
193
  * Sync remote-tracking refs: fetch every remote and prune tracking branches
136
194
  * the remotes no longer carry (the CLI equivalent of IDEA's "synchronize
package/lib/git.js CHANGED
@@ -73,6 +73,27 @@ function isDirBusyGitError(error) {
73
73
  || /\bEACCES\b/i.test(text)
74
74
  || /\bEBUSY\b/i.test(text);
75
75
  }
76
+ /**
77
+ * Whether a directory IS the main worktree of its repository: exactly when
78
+ * its own toplevel holds the SHARED `.git` that `--git-common-dir` names.
79
+ * From a linked worktree that path resolves to the shared `<repo>/.git` too,
80
+ * but its toplevel is the linked folder — so the two differ and the answer
81
+ * is false.
82
+ *
83
+ * Deliberately NOT "is the first entry of `worktree list`": that list is
84
+ * filtered by directory existence downstream (a stale main registration
85
+ * would flip the answer), it costs a second git spawn, and its `main` flag
86
+ * describes a different question — which entry git considers main, not
87
+ * which directory was asked about. Same rule as {@link probeWorkspaceGit}
88
+ * applies for the sidebar's grouping, extracted here so both answers are the
89
+ * same answer.
90
+ * @param toplevel - the queried directory's own `--show-toplevel`.
91
+ * @param gitDir - the SHARED git dir (`--git-common-dir`) every worktree
92
+ * resolves back to.
93
+ */
94
+ function isMainWorktree(toplevel, gitDir) {
95
+ return normalize(resolve(toplevel, '.git')) === gitDir;
96
+ }
76
97
  /**
77
98
  * Resolve a directory to repository facts, or undefined outside any git
78
99
  * repository (including the `git` binary missing: ENOENT surfaces as a
@@ -102,6 +123,8 @@ export async function probeRepo(exec, path, dirExists = fsDirExists) {
102
123
  return {
103
124
  repoRoot,
104
125
  repoName: basename(dirname(gitDir)),
126
+ toplevel,
127
+ main: isMainWorktree(toplevel, gitDir),
105
128
  currentBranch: await currentBranch(exec, path),
106
129
  branches: await listBranches(exec, repoRoot),
107
130
  // A stale registration (directory removed behind git's back) must not
@@ -207,11 +230,13 @@ async function listWorktrees(exec, repoRoot) {
207
230
  }
208
231
  /**
209
232
  * Resolve a branch display name against the authoritative branch list of the
210
- * repository.
233
+ * repository. Exported for the /worktree route's fetch gate: the pre-create
234
+ * remote sync only earns its round trip when the display name is REMOTE-only
235
+ * (a local branch's worktree never consumes fetched refs).
211
236
  * @returns the local name plus the tracking remote when the display name is
212
237
  * remote-only, or undefined when neither shape exists.
213
238
  */
214
- async function resolveBranch(exec, repoRoot, branch) {
239
+ export async function resolveBranch(exec, repoRoot, branch) {
215
240
  const localsOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)']);
216
241
  const locals = localsOut.split('\n').map(l => l.trim()).filter(l => l !== '');
217
242
  if (locals.includes(branch))
@@ -341,19 +366,65 @@ export async function switchBranch(exec, repoRoot, branch) {
341
366
  return resolved.local;
342
367
  }
343
368
  /**
344
- * Create a NEW branch from the current checkout and check it out in place
345
- * (`git switch -c`): the cut point is whatever the queried directory's HEAD
346
- * points at, so a detached or unborn checkout cuts from the current commit
347
- * too. Runs at the queried directory's own toplevel — a session inside a
348
- * linked worktree creates and checks out within that worktree, never the
349
- * main checkout (the same semantics as {@link switchBranch}).
369
+ * Create a NEW branch. Three shapes:
370
+ *
371
+ * - no `from`: cut from the current checkout and check it out in place
372
+ * (`git switch -c`) — the cut point is whatever the queried directory's
373
+ * HEAD points at, so a detached or unborn checkout cuts from the current
374
+ * commit too. Runs at the queried directory's own toplevel — a session
375
+ * inside a linked worktree creates and checks out within that worktree,
376
+ * never the main checkout (the same semantics as {@link switchBranch}).
377
+ * - `from` without `checkout`: create AT that start point WITHOUT touching
378
+ * any checkout (`git branch`) — a create aimed at another branch must
379
+ * not move this session's HEAD.
380
+ * - `from` with `checkout`: create at the start point AND check it out
381
+ * here in one stroke (`git switch -c <name> <from>`).
350
382
  * @param exec - executor seam.
351
383
  * @param cwd - directory whose HEAD the branch is cut from (worktree toplevel).
352
384
  * @param name - new branch name (git validates; failures raise GitError).
353
- * @returns the branch name now created and checked out.
385
+ * @param from - optional start point; absent keeps the in-place semantics.
386
+ * @param checkout - with `from`, also check the new branch out here.
387
+ * @returns the branch name now created (checked out unless created at a
388
+ * start point with `checkout` false).
389
+ */
390
+ export async function createBranch(exec, cwd, name, from, checkout = false) {
391
+ if (from === undefined || checkout) {
392
+ const startPoint = from === undefined ? [] : [from];
393
+ await git(exec, cwd, ['switch', '-c', name, ...startPoint]);
394
+ return name;
395
+ }
396
+ await git(exec, cwd, ['branch', name, from]);
397
+ return name;
398
+ }
399
+ /**
400
+ * Rename a LOCAL branch (`git branch -m`): branch refs are repository-wide,
401
+ * so the command runs at the repository root and every worktree HEAD pointing
402
+ * at the old name follows the ref. Git validates the new name and refuses a
403
+ * target that already exists; remote branches are not renameable (not ours).
404
+ * @param exec - executor seam.
405
+ * @param repoRoot - main worktree directory.
406
+ * @param name - branch to rename.
407
+ * @param newName - the new local name.
408
+ * @returns the new name.
409
+ */
410
+ export async function renameBranch(exec, repoRoot, name, newName) {
411
+ await git(exec, repoRoot, ['branch', '-m', name, newName]);
412
+ return newName;
413
+ }
414
+ /**
415
+ * Delete a LOCAL branch (`git branch -d`, the SAFE form): git refuses a
416
+ * branch with unmerged commits ("not fully merged") and one checked out in
417
+ * any worktree — both caller-side state, mapped to 400 by the route. No
418
+ * `-D` force variant on purpose: a menu click must never discard commits
419
+ * (the terminal is the place for deliberate force-deletes). Runs at the
420
+ * repository root; remote branches are not ours to delete.
421
+ * @param exec - executor seam.
422
+ * @param repoRoot - main worktree directory.
423
+ * @param name - branch to delete.
424
+ * @returns the name of the branch that was deleted.
354
425
  */
355
- export async function createBranch(exec, cwd, name) {
356
- await git(exec, cwd, ['switch', '-c', name]);
426
+ export async function deleteBranch(exec, repoRoot, name) {
427
+ await git(exec, repoRoot, ['branch', '-d', name]);
357
428
  return name;
358
429
  }
359
430
  /**
@@ -517,6 +588,6 @@ export async function probeWorkspaceGit(exec, path) {
517
588
  repoRoot: dirname(gitDir),
518
589
  repoName: basename(dirname(gitDir)),
519
590
  branch: branchName === '' || branchName === 'HEAD' ? null : branchName,
520
- main: normalize(resolve(toplevel, '.git')) === gitDir,
591
+ main: isMainWorktree(toplevel, gitDir),
521
592
  };
522
593
  }
package/lib/index.d.ts CHANGED
@@ -21,6 +21,14 @@ export interface Config {
21
21
  rootDir?: string;
22
22
  /** Sidebar git grouping on/off; absent = on (the composition-entry layer's default). */
23
23
  groupSidebar?: boolean;
24
+ /** Fetch every remote before creating a worktree; absent = off. A failed
25
+ * fetch never blocks the creation (see the /worktree route). */
26
+ fetchBeforeCreate?: boolean;
27
+ /** Prune stale worktrees lazily after each creation; absent = off. */
28
+ autoPruneWorktrees?: boolean;
29
+ /** Global cap the lazy prune trims down to (valid git worktrees only);
30
+ * absent = 30. */
31
+ keepWorktrees?: number;
24
32
  }
25
33
  /**
26
34
  * Cordis resolves the composition entry's config through this schema before
@@ -34,18 +42,36 @@ export interface Config {
34
42
  export declare const Config: z<Config>;
35
43
  /** Reject stale or misspelled config keys before defaults can hide them. */
36
44
  export declare function validateConfig(config: Config): void;
45
+ /**
46
+ * The prune cap must be an integer >= 1: 0 would read as "create then
47
+ * immediately self-delete" (the fresh worktree is excluded, but every other
48
+ * one dies on the next creation), a fraction cannot count directories.
49
+ * Absent = the shipped default, which passes.
50
+ */
51
+ export declare function validateKeepWorktrees(value: number | undefined): void;
37
52
  /** The settings namespace this plugin serves; its browser card spells the same string. */
38
53
  export declare const GIT_WORKTREE_NS = "git-worktree";
39
- /** The settings-facing subset of the config: the worktree storage root and the sidebar grouping switch. */
54
+ /** The settings-facing subset of the config: the worktree storage root, the
55
+ * sidebar grouping switch, and the create/prune behavior switches. */
40
56
  export interface SectionConfig {
41
57
  /** Worktree storage root; absent/blank selects `$DSH_HOME/gitworktree`. */
42
58
  rootDir?: string;
43
59
  /** Whether the sidebar groups same-repository workspaces; absent = on. */
44
60
  groupSidebar?: boolean;
61
+ /** Fetch every remote before creating a worktree; absent = off. */
62
+ fetchBeforeCreate?: boolean;
63
+ /** Prune stale worktrees lazily after each creation; absent = off. */
64
+ autoPruneWorktrees?: boolean;
65
+ /** Global cap the lazy prune trims down to; absent = 30. */
66
+ keepWorktrees?: number;
45
67
  }
46
68
  /** Schema resolving the `git-worktree` settings section. */
47
69
  export declare const sectionSchema: z<SectionConfig>;
48
- /** The section-shaped view of a config: absent keys stay absent (`exactOptionalPropertyTypes`). */
70
+ /** The shipped prune cap (whole storage root, valid git worktrees only). */
71
+ export declare const KEEP_WORKTREES_DEFAULT = 30;
72
+ /** The section-shaped view of a config: absent keys stay absent
73
+ * (`exactOptionalPropertyTypes`) except the switches, which spell their
74
+ * shipped defaults so a user-layer unset can always fall back to them. */
49
75
  export declare function sectionOf(config: Config): SectionConfig;
50
76
  /**
51
77
  * Plugin apply: install the settings section, migrate any legacy stored root
package/lib/index.js CHANGED
@@ -16,9 +16,9 @@ import { homedir } from 'node:os';
16
16
  import { rename } from 'node:fs/promises';
17
17
  import z from '@deepseek-ai/schemastery';
18
18
  import { childProcessExec } from './git.js';
19
- import { handleCreateBranch, handleCreateWorktree, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleInspectWorktree, handlePathExists, handleRemoveWorktree, handleStatus, handleSwitch, handleUpdate, } from './routes.js';
19
+ import { handleCreateBranch, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleInspectWorktree, handlePathExists, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
20
20
  import { loadLegacySettings, migratedFileOf, planLegacyMigration, settingsFileOf, validateRootDir, } from './settings.js';
21
- import { ROUTE_BRANCH, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_INSPECT, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE } from './wire.js';
21
+ import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_INSPECT, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
22
22
  export const name = 'dsh-git-worktree';
23
23
  export const inject = [];
24
24
  /** Largest accepted request body (bytes) — these payloads are a few strings. */
@@ -35,10 +35,13 @@ const BODY_LIMIT = 64 * 1024;
35
35
  export const Config = z.object({
36
36
  rootDir: z.string(),
37
37
  groupSidebar: z.boolean().default(true),
38
+ fetchBeforeCreate: z.boolean().default(false),
39
+ autoPruneWorktrees: z.boolean().default(false),
40
+ keepWorktrees: z.number(),
38
41
  });
39
42
  /** Reject stale or misspelled config keys before defaults can hide them. */
40
43
  export function validateConfig(config) {
41
- const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar');
44
+ const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees');
42
45
  if (unknown !== undefined) {
43
46
  throw new Error(`GitWorktreeConfig: unknown key "${unknown}"`);
44
47
  }
@@ -48,22 +51,52 @@ export function validateConfig(config) {
48
51
  if (config.groupSidebar !== undefined && typeof config.groupSidebar !== 'boolean') {
49
52
  throw new Error('GitWorktreeConfig: "groupSidebar" must be a boolean');
50
53
  }
54
+ if (config.fetchBeforeCreate !== undefined && typeof config.fetchBeforeCreate !== 'boolean') {
55
+ throw new Error('GitWorktreeConfig: "fetchBeforeCreate" must be a boolean');
56
+ }
57
+ if (config.autoPruneWorktrees !== undefined && typeof config.autoPruneWorktrees !== 'boolean') {
58
+ throw new Error('GitWorktreeConfig: "autoPruneWorktrees" must be a boolean');
59
+ }
60
+ validateKeepWorktrees(config.keepWorktrees);
51
61
  validateRootDir(config.rootDir);
52
62
  }
63
+ /**
64
+ * The prune cap must be an integer >= 1: 0 would read as "create then
65
+ * immediately self-delete" (the fresh worktree is excluded, but every other
66
+ * one dies on the next creation), a fraction cannot count directories.
67
+ * Absent = the shipped default, which passes.
68
+ */
69
+ export function validateKeepWorktrees(value) {
70
+ if (value === undefined)
71
+ return;
72
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {
73
+ throw new Error('GitWorktreeConfig: "keepWorktrees" must be an integer >= 1');
74
+ }
75
+ }
53
76
  /** The settings namespace this plugin serves; its browser card spells the same string. */
54
77
  export const GIT_WORKTREE_NS = 'git-worktree';
55
78
  /** Schema resolving the `git-worktree` settings section. */
56
79
  export const sectionSchema = z.object({
57
80
  rootDir: z.string(),
58
81
  groupSidebar: z.boolean(),
82
+ fetchBeforeCreate: z.boolean(),
83
+ autoPruneWorktrees: z.boolean(),
84
+ keepWorktrees: z.number(),
59
85
  });
60
- /** The section-shaped view of a config: absent keys stay absent (`exactOptionalPropertyTypes`). */
86
+ /** The shipped prune cap (whole storage root, valid git worktrees only). */
87
+ export const KEEP_WORKTREES_DEFAULT = 30;
88
+ /** The section-shaped view of a config: absent keys stay absent
89
+ * (`exactOptionalPropertyTypes`) except the switches, which spell their
90
+ * shipped defaults so a user-layer unset can always fall back to them. */
61
91
  export function sectionOf(config) {
62
92
  return {
63
93
  ...(config.rootDir === undefined ? {} : { rootDir: config.rootDir }),
64
- // The composition layer spells the shipped default (grouping ON) so a
65
- // user-layer unset can always fall back to it.
94
+ // The composition layer spells the shipped defaults so a user-layer
95
+ // unset can always fall back to them.
66
96
  groupSidebar: config.groupSidebar ?? true,
97
+ fetchBeforeCreate: config.fetchBeforeCreate ?? false,
98
+ autoPruneWorktrees: config.autoPruneWorktrees ?? false,
99
+ keepWorktrees: config.keepWorktrees ?? KEEP_WORKTREES_DEFAULT,
67
100
  };
68
101
  }
69
102
  /**
@@ -82,6 +115,7 @@ export function apply(ctx, config = {}) {
82
115
  const deps = () => ({
83
116
  exec: childProcessExec,
84
117
  sectionRootDir: () => sectionSource().rootDir,
118
+ sectionFetchBeforeCreate: () => sectionSource().fetchBeforeCreate,
85
119
  home: () => homedir(),
86
120
  envHome: () => process.env.DSH_HOME,
87
121
  });
@@ -97,6 +131,13 @@ export function apply(ctx, config = {}) {
97
131
  if (value.groupSidebar !== undefined && typeof value.groupSidebar !== 'boolean') {
98
132
  throw new Error('groupSidebar must be a boolean');
99
133
  }
134
+ if (value.fetchBeforeCreate !== undefined && typeof value.fetchBeforeCreate !== 'boolean') {
135
+ throw new Error('fetchBeforeCreate must be a boolean');
136
+ }
137
+ if (value.autoPruneWorktrees !== undefined && typeof value.autoPruneWorktrees !== 'boolean') {
138
+ throw new Error('autoPruneWorktrees must be a boolean');
139
+ }
140
+ validateKeepWorktrees(value.keepWorktrees);
100
141
  },
101
142
  setSource: (source) => { sectionSource = source; },
102
143
  onChange: () => {
@@ -187,6 +228,8 @@ export function apply(ctx, config = {}) {
187
228
  postRoute(ROUTE_WORKTREE, 'worktree', handleCreateWorktree);
188
229
  postRoute(ROUTE_SWITCH, 'switch', handleSwitch);
189
230
  postRoute(ROUTE_BRANCH, 'branch', handleCreateBranch);
231
+ postRoute(ROUTE_BRANCH_RENAME, 'branch-rename', handleRenameBranch);
232
+ postRoute(ROUTE_BRANCH_DELETE, 'branch-delete', handleDeleteBranch);
190
233
  postRoute(ROUTE_FETCH, 'fetch', handleFetch);
191
234
  postRoute(ROUTE_GROUP, 'group', handleGroupWorktrees);
192
235
  postRoute(ROUTE_UPDATE, 'update', handleUpdate);
@@ -194,5 +237,7 @@ export function apply(ctx, config = {}) {
194
237
  postRoute(ROUTE_REMOVE, 'remove', handleRemoveWorktree);
195
238
  postRoute(ROUTE_EXISTS, 'exists', handlePathExists);
196
239
  postRoute(ROUTE_ENSURE_DIRECTORY, 'ensure-directory', handleEnsureDirectory);
240
+ postRoute(ROUTE_WORKTREES_ALL, 'worktrees-all', handleWorktreesAll);
241
+ postRoute(ROUTE_PURGE, 'purge', handlePurgeDirectory);
197
242
  });
198
243
  }
package/lib/routes.d.ts CHANGED
@@ -3,12 +3,14 @@
3
3
  * shell (index.ts) owns req/res mechanics; everything testable lives here.
4
4
  */
5
5
  import { type DirExists, type Exec } from './git.js';
6
- import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, InspectWorktreeResult, PathExistsResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, UpdateResult } from './wire.js';
6
+ import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, InspectWorktreeResult, PathExistsResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, UpdateResult, WorktreesAllResult } from './wire.js';
7
7
  /** Everything the handlers need from the host half. */
8
8
  export interface RouteDeps {
9
9
  exec: Exec;
10
10
  /** The settings-resolved rootDir (absent/blank = the default location). */
11
11
  sectionRootDir: () => string | undefined;
12
+ /** Whether a worktree creation syncs the remotes first (absent = off). */
13
+ sectionFetchBeforeCreate: () => boolean | undefined;
12
14
  /** User home directory seam. */
13
15
  home: () => string;
14
16
  /** `$DSH_HOME` environment value seam. */
@@ -20,7 +22,16 @@ export interface RouteDeps {
20
22
  statDirectory?: (path: string) => Promise<boolean>;
21
23
  /** Recursive mkdir seam (fs.mkdir recursive); tests substitute. */
22
24
  mkdirRecursive?: (path: string) => Promise<void>;
25
+ /** One-level directory listing seam (fs.readdir with dirents); tests
26
+ * substitute. */
27
+ listDir?: (path: string) => Promise<string[]>;
28
+ /** Recursive force rm seam (fs.rm with retries); tests substitute. */
29
+ rmRecursive?: (path: string) => Promise<void>;
23
30
  }
31
+ /** Real fs-backed one-level directory listing (names only). Plain FILES are
32
+ * filtered out — the storage root can carry strays (a legacy settings.json
33
+ * was seen in the wild), and the scan lists worktree SLOTS, not entries. */
34
+ export declare function fsListDir(path: string): Promise<string[]>;
24
35
  /** Real fs-backed directory probe: exists and is a directory. */
25
36
  export declare function fsStatDirectory(path: string): Promise<boolean>;
26
37
  /** Real fs-backed recursive mkdir. */
@@ -28,7 +39,7 @@ export declare function fsMkdirRecursive(path: string): Promise<void>;
28
39
  /** One route outcome: HTTP status plus the JSON body. */
29
40
  export interface RouteOutcome {
30
41
  status: number;
31
- body: RepoStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | RouteError;
42
+ body: RepoStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
32
43
  }
33
44
  /**
34
45
  * POST /group — git belonging facts for a batch of workspace directories.
@@ -40,6 +51,36 @@ export interface RouteOutcome {
40
51
  * @param body - parsed request body: `{ paths }`.
41
52
  */
42
53
  export declare function handleGroupWorktrees(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
54
+ /**
55
+ * POST /worktrees-all — git facts for every DIRECT child directory of the
56
+ * resolved worktree storage root (the slots this plugin plans as
57
+ * `<repoName>-<branch>`). The management dialog's data source: one scan
58
+ * answers for all repositories at once, orphan directories included (a
59
+ * child that probes as no git repository comes back with null facts rather
60
+ * than being dropped — the dialog shows it as unrecognized). A missing
61
+ * storage root answers an empty list; per-child probe failures degrade to
62
+ * null facts, never a 500 — the dialog must render, not error out. A root
63
+ * holding more than {@link SCAN_CHILDREN_LIMIT} children answers its first
64
+ * slice plus `truncated`, so a misconfigured rootDir cannot turn one dialog
65
+ * open into thousands of git spawns.
66
+ * @param deps - host dependencies.
67
+ */
68
+ export declare function handleWorktreesAll(deps: RouteDeps): Promise<RouteOutcome>;
69
+ /** Real fs-backed recursive force rm (Windows file-lock retries included). */
70
+ export declare function fsRmRecursive(path: string): Promise<void>;
71
+ /**
72
+ * POST /purge — delete a NON-git directory sitting DIRECTLY inside the
73
+ * resolved worktree storage root: the orphaned leftover a half-failed
74
+ * `worktree remove` can leave behind (git registration and the .git file
75
+ * already gone, contents stranded on disk). Triple-gated: one level below
76
+ * the root (resolved forms, same slot boundary as /ensure-directory), a
77
+ * real directory, and NOT a git repository — anything git still recognizes
78
+ * must go through /remove, where the removal carries the session-archive
79
+ * and unregistration half. Deletion is a plain recursive force rm.
80
+ * @param deps - host dependencies.
81
+ * @param body - parsed request body: `{ path }`.
82
+ */
83
+ export declare function handlePurgeDirectory(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
43
84
  /**
44
85
  * GET /status 鈥?repository facts for one directory.
45
86
  * @param deps - host dependencies.
@@ -63,14 +104,38 @@ export declare function handleCreateWorktree(deps: RouteDeps, body: unknown): Pr
63
104
  */
64
105
  export declare function handleSwitch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
65
106
  /**
66
- * POST /branch 鈥?create a NEW branch from the queried directory's current
67
- * checkout (whatever its HEAD points at, detached included) and check it out
68
- * in place. Git validates the name; the client pre-flights the same rules
107
+ * POST /branch — create a NEW branch. Without `from`, from the queried
108
+ * directory's current checkout (whatever its HEAD points at, detached
109
+ * included), checked out in place. With `from` (a local branch or a remote
110
+ * tracking ref): checked out here too when `checkout` is set
111
+ * (`git switch -c <name> <from>`), created with no checkout touched
112
+ * otherwise (`git branch`) — a create aimed at another branch must not
113
+ * silently move the session's HEAD unless the caller asked for exactly
114
+ * that. Git validates both names; the client pre-flights the same rules
69
115
  * and only sends names it already accepts.
70
116
  * @param deps - host dependencies.
71
117
  * @param body - parsed request body.
72
118
  */
73
119
  export declare function handleCreateBranch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
120
+ /**
121
+ * POST /branch-rename — rename a LOCAL branch (`git branch -m`). Runs at the
122
+ * repository root: branch refs are repository-wide and worktree HEADs
123
+ * pointing at the old name follow the ref. Git validates the new name and
124
+ * refuses a target that already exists; both map to 400 through
125
+ * {@link gitFailure}.
126
+ * @param deps - host dependencies.
127
+ * @param body - parsed request body.
128
+ */
129
+ export declare function handleRenameBranch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
130
+ /**
131
+ * POST /branch-delete — delete a LOCAL branch with the SAFE form
132
+ * (`git branch -d`): git refuses unmerged commits and branches checked out
133
+ * in any worktree, both mapping to 400 through {@link gitFailure}. No
134
+ * force variant — a menu click must never discard commits.
135
+ * @param deps - host dependencies.
136
+ * @param body - parsed request body.
137
+ */
138
+ export declare function handleDeleteBranch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
74
139
  /**
75
140
  * POST /fetch 鈥?sync remote-tracking refs for the repository: fetch every
76
141
  * remote and prune tracking branches the remotes no longer carry. Pure