@laoyuehanni/dsh-git-worktree 0.4.1 → 0.4.3

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
@@ -152,11 +152,53 @@ export interface UpdateOutcome {
152
152
  export declare function updateBranch(exec: Exec, cwd: string): Promise<UpdateOutcome>;
153
153
  /** Guard for route inputs: a non-empty absolute directory path. */
154
154
  export declare function isAbsoluteDir(value: string): boolean;
155
+ /** Pre-delete facts of one worktree directory, for the remove-confirm dialog. */
156
+ export interface WorktreeInspect {
157
+ /** Uncommitted-change file rows (`git status --porcelain` line count). */
158
+ dirty: number;
159
+ /** Commits ahead of the branch's upstream; undefined when no upstream. */
160
+ ahead: number | undefined;
161
+ }
162
+ /**
163
+ * Inspect one worktree directory for removal: how many files carry
164
+ * uncommitted changes (those ARE lost with the folder), and how many commits
165
+ * the checked-out branch leads its upstream by (informational only — the
166
+ * branch ref survives `worktree remove`, so those are kept).
167
+ * @param exec - executor seam.
168
+ * @param worktreePath - the worktree directory (absolute).
169
+ */
170
+ export declare function inspectWorktree(exec: Exec, worktreePath: string): Promise<WorktreeInspect>;
171
+ /**
172
+ * Remove one linked worktree: `git worktree remove` deletes the folder and
173
+ * the registration in one stroke. A stale registration (folder already gone
174
+ * behind git's back) resolves through `worktree prune` instead — the outcome
175
+ * the user asked for either way, which keeps the route idempotent.
176
+ * @param exec - executor seam.
177
+ * @param repoRoot - main worktree directory.
178
+ * @param worktreePath - the linked worktree directory to delete (absolute).
179
+ * @param force - pass `--force` past uncommitted changes.
180
+ * @param dirExists - existence seam for the stale-registration branch.
181
+ * @returns the path plus whether only a stale registration was pruned.
182
+ * @throws GitError for the main worktree, an unregistered path, or a refused
183
+ * removal (git's own stderr verbatim).
184
+ */
185
+ export declare function removeWorktree(exec: Exec, repoRoot: string, worktreePath: string, force: boolean, dirExists?: DirExists): Promise<{
186
+ path: string;
187
+ pruned: boolean;
188
+ }>;
155
189
  /**
156
190
  * Lightweight git belonging probe for ONE workspace directory: the three
157
191
  * facts the sidebar grouping needs and nothing else (no branch list, no
158
192
  * worktree list — {@link probeRepo} stays the full-facts path for the chip).
159
193
  *
194
+ * All three facts come from ONE `git rev-parse` invocation: the sidebar
195
+ * probes every registered workspace on each mount, and on Windows every git
196
+ * call is a process spawn, so three sequential spawns per directory made the
197
+ * startup probe cost scale with the workspace count directly. `rev-parse`
198
+ * evaluates each flag in turn and prints one line per answer, so
199
+ * `--show-toplevel`, `--git-common-dir`, and `--abbrev-ref HEAD` fold into a
200
+ * single process.
201
+ *
160
202
  * `repoRoot` — the grouping key — is derived from `--git-common-dir`, which
161
203
  * names the SHARED `<repo>/.git` from every worktree of the repository: the
162
204
  * main checkout reports it directly, a linked worktree reports the path back
@@ -164,8 +206,10 @@ export declare function isAbsoluteDir(value: string): boolean;
164
206
  * together, wherever the linked folder physically lives.
165
207
  * `main` is decided without `worktree list`: a directory is the main worktree
166
208
  * exactly when its own toplevel holds that shared .git.
167
- * `branch` normalizes detached/unborn HEAD to null HERE so no consumer
168
- * downstream ever string-compares against git's synthetic `'HEAD'`.
209
+ * `branch` uses `--abbrev-ref HEAD`, whose detached/unborn output is git's
210
+ * synthetic `HEAD` — normalized to null HERE so no consumer downstream ever
211
+ * string-compares against it (the same contract the old `branch
212
+ * --show-current` empty output mapped to).
169
213
  * @param exec - executor seam.
170
214
  * @param path - absolute directory the workspace reports.
171
215
  * @returns the facts, or undefined outside any git repository (a missing git
package/lib/git.js CHANGED
@@ -360,11 +360,69 @@ export async function updateBranch(exec, cwd) {
360
360
  export function isAbsoluteDir(value) {
361
361
  return value.trim() !== '' && isAbsolute(value);
362
362
  }
363
+ /**
364
+ * Inspect one worktree directory for removal: how many files carry
365
+ * uncommitted changes (those ARE lost with the folder), and how many commits
366
+ * the checked-out branch leads its upstream by (informational only — the
367
+ * branch ref survives `worktree remove`, so those are kept).
368
+ * @param exec - executor seam.
369
+ * @param worktreePath - the worktree directory (absolute).
370
+ */
371
+ export async function inspectWorktree(exec, worktreePath) {
372
+ const status = await git(exec, worktreePath, ['status', '--porcelain']);
373
+ const dirty = status.split('\n').filter(line => line.trim() !== '').length;
374
+ // No upstream (local-only branch) fails the rev-list — that is a normal
375
+ // answer, not an error: ahead stays undefined.
376
+ const aheadOut = await gitMaybe(exec, worktreePath, ['rev-list', '--count', '@{u}..HEAD']);
377
+ const parsed = aheadOut === undefined ? Number.NaN : Number(aheadOut.trim());
378
+ return { dirty, ahead: Number.isFinite(parsed) ? parsed : undefined };
379
+ }
380
+ /**
381
+ * Remove one linked worktree: `git worktree remove` deletes the folder and
382
+ * the registration in one stroke. A stale registration (folder already gone
383
+ * behind git's back) resolves through `worktree prune` instead — the outcome
384
+ * the user asked for either way, which keeps the route idempotent.
385
+ * @param exec - executor seam.
386
+ * @param repoRoot - main worktree directory.
387
+ * @param worktreePath - the linked worktree directory to delete (absolute).
388
+ * @param force - pass `--force` past uncommitted changes.
389
+ * @param dirExists - existence seam for the stale-registration branch.
390
+ * @returns the path plus whether only a stale registration was pruned.
391
+ * @throws GitError for the main worktree, an unregistered path, or a refused
392
+ * removal (git's own stderr verbatim).
393
+ */
394
+ export async function removeWorktree(exec, repoRoot, worktreePath, force, dirExists = fsDirExists) {
395
+ const target = normalize(worktreePath);
396
+ const worktrees = await listWorktrees(exec, repoRoot);
397
+ const registered = worktrees.find(w => w.path === target);
398
+ if (registered === undefined) {
399
+ throw new GitError(['worktree', 'remove'], 1, `"${target}" is not a registered worktree of this repository`);
400
+ }
401
+ if (registered.main) {
402
+ throw new GitError(['worktree', 'remove'], 1, 'cannot remove the main worktree');
403
+ }
404
+ if (!dirExists(target)) {
405
+ // Stale registration: the folder is already gone, so removal means
406
+ // clearing git's administrative record — exactly what prune does.
407
+ await git(exec, repoRoot, ['worktree', 'prune']);
408
+ return { path: target, pruned: true };
409
+ }
410
+ await git(exec, repoRoot, force ? ['worktree', 'remove', '--force', target] : ['worktree', 'remove', target]);
411
+ return { path: target, pruned: false };
412
+ }
363
413
  /**
364
414
  * Lightweight git belonging probe for ONE workspace directory: the three
365
415
  * facts the sidebar grouping needs and nothing else (no branch list, no
366
416
  * worktree list — {@link probeRepo} stays the full-facts path for the chip).
367
417
  *
418
+ * All three facts come from ONE `git rev-parse` invocation: the sidebar
419
+ * probes every registered workspace on each mount, and on Windows every git
420
+ * call is a process spawn, so three sequential spawns per directory made the
421
+ * startup probe cost scale with the workspace count directly. `rev-parse`
422
+ * evaluates each flag in turn and prints one line per answer, so
423
+ * `--show-toplevel`, `--git-common-dir`, and `--abbrev-ref HEAD` fold into a
424
+ * single process.
425
+ *
368
426
  * `repoRoot` — the grouping key — is derived from `--git-common-dir`, which
369
427
  * names the SHARED `<repo>/.git` from every worktree of the repository: the
370
428
  * main checkout reports it directly, a linked worktree reports the path back
@@ -372,29 +430,33 @@ export function isAbsoluteDir(value) {
372
430
  * together, wherever the linked folder physically lives.
373
431
  * `main` is decided without `worktree list`: a directory is the main worktree
374
432
  * exactly when its own toplevel holds that shared .git.
375
- * `branch` normalizes detached/unborn HEAD to null HERE so no consumer
376
- * downstream ever string-compares against git's synthetic `'HEAD'`.
433
+ * `branch` uses `--abbrev-ref HEAD`, whose detached/unborn output is git's
434
+ * synthetic `HEAD` — normalized to null HERE so no consumer downstream ever
435
+ * string-compares against it (the same contract the old `branch
436
+ * --show-current` empty output mapped to).
377
437
  * @param exec - executor seam.
378
438
  * @param path - absolute directory the workspace reports.
379
439
  * @returns the facts, or undefined outside any git repository (a missing git
380
440
  * binary surfaces the same way — a non-zero exit through the seam).
381
441
  */
382
442
  export async function probeWorkspaceGit(exec, path) {
383
- const top = await gitMaybe(exec, path, ['rev-parse', '--show-toplevel']);
384
- if (top === undefined || top.trim() === '')
443
+ const out = await gitMaybe(exec, path, ['rev-parse', '--show-toplevel', '--git-common-dir', '--abbrev-ref', 'HEAD']);
444
+ if (out === undefined)
385
445
  return undefined;
386
- const toplevel = normalize(top.trim());
387
- const commonDir = await gitMaybe(exec, path, ['rev-parse', '--git-common-dir']);
388
- if (commonDir === undefined || commonDir.trim() === '')
446
+ const lines = out.split('\n').map(line => line.trim());
447
+ const top = lines[0] ?? '';
448
+ const commonDir = lines[1] ?? '';
449
+ const branchName = lines[2] ?? '';
450
+ if (top === '' || commonDir === '')
389
451
  return undefined;
452
+ const toplevel = normalize(top);
390
453
  // Git outputs carry forward slashes on Windows — normalize every derived
391
454
  // path so consumers can compare against join()-built ones.
392
- const gitDir = normalize(resolve(path, commonDir.trim()));
393
- const branchName = (await gitMaybe(exec, path, ['branch', '--show-current']))?.trim() ?? '';
455
+ const gitDir = normalize(resolve(path, commonDir));
394
456
  return {
395
457
  repoRoot: dirname(gitDir),
396
458
  repoName: basename(dirname(gitDir)),
397
- branch: branchName === '' ? null : branchName,
459
+ branch: branchName === '' || branchName === 'HEAD' ? null : branchName,
398
460
  main: normalize(resolve(toplevel, '.git')) === gitDir,
399
461
  };
400
462
  }
package/lib/index.js CHANGED
@@ -17,9 +17,9 @@ import { rename } from 'node:fs/promises';
17
17
  import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings';
18
18
  import z from '@deepseek-ai/schemastery';
19
19
  import { childProcessExec } from './git.js';
20
- import { handleCreateBranch, handleCreateWorktree, handleFetch, handleGroupWorktrees, handleStatus, handleSwitch, handleUpdate, } from './routes.js';
20
+ import { handleCreateBranch, handleCreateWorktree, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleInspectWorktree, handlePathExists, handleRemoveWorktree, handleStatus, handleSwitch, handleUpdate, } from './routes.js';
21
21
  import { loadLegacySettings, migratedFileOf, planLegacyMigration, settingsFileOf, validateRootDir, } from './settings.js';
22
- import { ROUTE_BRANCH, ROUTE_FETCH, ROUTE_GROUP, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE } from './wire.js';
22
+ 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';
23
23
  export const name = 'dsh-git-worktree';
24
24
  export const inject = [];
25
25
  /** Largest accepted request body (bytes) — these payloads are a few strings. */
@@ -199,5 +199,37 @@ export function apply(ctx, config = {}) {
199
199
  send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
200
200
  }
201
201
  } }), 'git-worktree: update route');
202
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_INSPECT, handler: async (req, res) => {
203
+ try {
204
+ send(res, await handleInspectWorktree(deps(), await readJson(req)));
205
+ }
206
+ catch (error) {
207
+ send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
208
+ }
209
+ } }), 'git-worktree: inspect route');
210
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_REMOVE, handler: async (req, res) => {
211
+ try {
212
+ send(res, await handleRemoveWorktree(deps(), await readJson(req)));
213
+ }
214
+ catch (error) {
215
+ send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
216
+ }
217
+ } }), 'git-worktree: remove route');
218
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_EXISTS, handler: async (req, res) => {
219
+ try {
220
+ send(res, await handlePathExists(deps(), await readJson(req)));
221
+ }
222
+ catch (error) {
223
+ send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
224
+ }
225
+ } }), 'git-worktree: exists route');
226
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_ENSURE_DIRECTORY, handler: async (req, res) => {
227
+ try {
228
+ send(res, await handleEnsureDirectory(deps(), await readJson(req)));
229
+ }
230
+ catch (error) {
231
+ send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
232
+ }
233
+ } }), 'git-worktree: ensure-directory route');
202
234
  });
203
235
  }
package/lib/routes.d.ts CHANGED
@@ -3,7 +3,7 @@
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, FetchResult, GroupWorkspacesResult, RepoStatus, RouteError, SwitchResult, UpdateResult } from './wire.js';
6
+ import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, InspectWorktreeResult, PathExistsResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, UpdateResult } from './wire.js';
7
7
  /** Everything the handlers need from the host half. */
8
8
  export interface RouteDeps {
9
9
  exec: Exec;
@@ -15,11 +15,20 @@ export interface RouteDeps {
15
15
  envHome: () => string | undefined;
16
16
  /** Worktree-registration existence seam (tests substitute). */
17
17
  dirExists?: DirExists;
18
+ /** Directory probe seam over fs.stat (true = exists AND is a directory);
19
+ * tests substitute. */
20
+ statDirectory?: (path: string) => Promise<boolean>;
21
+ /** Recursive mkdir seam (fs.mkdir recursive); tests substitute. */
22
+ mkdirRecursive?: (path: string) => Promise<void>;
18
23
  }
24
+ /** Real fs-backed directory probe: exists and is a directory. */
25
+ export declare function fsStatDirectory(path: string): Promise<boolean>;
26
+ /** Real fs-backed recursive mkdir. */
27
+ export declare function fsMkdirRecursive(path: string): Promise<void>;
19
28
  /** One route outcome: HTTP status plus the JSON body. */
20
29
  export interface RouteOutcome {
21
30
  status: number;
22
- body: RepoStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | RouteError;
31
+ body: RepoStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | RouteError;
23
32
  }
24
33
  /**
25
34
  * POST /group — git belonging facts for a batch of workspace directories.
@@ -80,3 +89,47 @@ export declare function handleFetch(deps: RouteDeps, body: unknown): Promise<Rou
80
89
  * @param body - parsed request body.
81
90
  */
82
91
  export declare function handleUpdate(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
92
+ /**
93
+ * POST /inspect — pre-delete facts for one worktree directory: the
94
+ * uncommitted-file count (those die with the folder) and the checked-out
95
+ * branch's ahead count (kept — the branch ref survives the removal).
96
+ * Deliberately repo-wide neutral: any directory inside a repository answers,
97
+ * so the dialog data stays meaningful even for odd shapes.
98
+ * @param deps - host dependencies.
99
+ * @param body - parsed request body: `{ path }`.
100
+ */
101
+ export declare function handleInspectWorktree(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
102
+ /**
103
+ * POST /remove — delete one linked worktree: git's registration plus the
104
+ * folder in one stroke (`worktree remove`, `--force` past uncommitted
105
+ * changes the dialog already showed). DSH-side cleanup (archiving the
106
+ * workspace's sessions, dropping the workspace registration) is the
107
+ * browser's follow-up, by design: git first, so a refused removal leaves
108
+ * the workspace world untouched.
109
+ * @param deps - host dependencies.
110
+ * @param body - parsed request body: `{ path, force? }`.
111
+ */
112
+ export declare function handleRemoveWorktree(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
113
+ /**
114
+ * POST /exists — batch directory-existence probe over plain fs (no git): true
115
+ * per path that exists AND is a directory. The browser gates the
116
+ * register-as-workspace action on this, so a missing folder (deleted, moved,
117
+ * or a corrupted session-header cwd) is answered by THIS route — the DSH
118
+ * workspace API never sees an unregistrable path.
119
+ * @param deps - host dependencies.
120
+ * @param body - parsed request body: `{ paths }`.
121
+ */
122
+ export declare function handlePathExists(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
123
+ /**
124
+ * POST /ensure-directory — recreate a MISSING worktree storage slot
125
+ * (`mkdir -p`). Strictly gated to paths sitting DIRECTLY inside the resolved
126
+ * worktree storage root: those slots were planned and created by this plugin,
127
+ * so rebuilding the empty folder is self-healing (historical sessions
128
+ * reattach automatically once realpath matches again — DSH keeps the
129
+ * workspace accounting and filters membership by the session header's cwd).
130
+ * Anything else is outside this plugin's territory and is refused, so a
131
+ * corrupted session-header cwd can never be materialized as stray folders.
132
+ * @param deps - host dependencies.
133
+ * @param body - parsed request body: `{ path }`.
134
+ */
135
+ export declare function handleEnsureDirectory(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
package/lib/routes.js CHANGED
@@ -2,19 +2,35 @@
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 { join } from 'node:path';
6
- import { mkdir } from 'node:fs/promises';
7
- import { GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, fetchAll, fsDirExists, isAbsoluteDir, probeRepo, probeWorkspaceGit, switchBranch, updateBranch } from './git.js';
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';
8
8
  import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
9
9
  import { resolveRootDir } from './settings.js';
10
+ /** Real fs-backed directory probe: exists and is a directory. */
11
+ export async function fsStatDirectory(path) {
12
+ try {
13
+ return (await stat(path)).isDirectory();
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ /** Real fs-backed recursive mkdir. */
20
+ export async function fsMkdirRecursive(path) {
21
+ await mkdir(path, { recursive: true });
22
+ }
10
23
  /** Uniform failure envelope. */
11
24
  function fail(status, error) {
12
25
  return { status, body: { error } };
13
26
  }
14
27
  /** Upper bound on distinct paths one /group request may probe. */
15
28
  const GROUP_PATHS_LIMIT = 256;
16
- /** Probes per in-flight batch — polite on Windows, where each git call is a process spawn. */
17
- const GROUP_BATCH_SIZE = 8;
29
+ /** Probes per in-flight batch — polite on Windows, where each git call is a
30
+ * process spawn. The probe itself is a single `rev-parse` per directory, so
31
+ * the batch can ride wider than the old three-spawn shape without stacking
32
+ * an unreasonable number of concurrent git processes. */
33
+ const GROUP_BATCH_SIZE = 16;
18
34
  /**
19
35
  * POST /group — git belonging facts for a batch of workspace directories.
20
36
  * Deduplicates, validates, probes in bounded batches, and answers 200 with
@@ -84,7 +100,13 @@ function gitFailure(error) {
84
100
  // found`), so match its `branch "` shape — git's own "not found"
85
101
  // texts (a remote that vanished mid-fetch: `Repository '...' not
86
102
  // found`) carry no quoted branch and stay 500 host faults.
87
- || error.stderr.includes('branch "');
103
+ || error.stderr.includes('branch "')
104
+ // Removal refusals from git.ts are caller-side state the same way: the
105
+ // main worktree (git refuses it too, but the route answers a clean 400
106
+ // before ever spawning git) and a path the repository never registered
107
+ // (a stale sidebar row racing a terminal-side removal).
108
+ || error.stderr.includes('cannot remove the main worktree')
109
+ || error.stderr.includes('is not a registered worktree');
88
110
  return fail(usage ? 400 : 500, error.message);
89
111
  }
90
112
  /**
@@ -333,3 +355,153 @@ export async function handleUpdate(deps, body) {
333
355
  return fail(500, error instanceof Error ? error.message : String(error));
334
356
  }
335
357
  }
358
+ /**
359
+ * POST /inspect — pre-delete facts for one worktree directory: the
360
+ * uncommitted-file count (those die with the folder) and the checked-out
361
+ * branch's ahead count (kept — the branch ref survives the removal).
362
+ * Deliberately repo-wide neutral: any directory inside a repository answers,
363
+ * so the dialog data stays meaningful even for odd shapes.
364
+ * @param deps - host dependencies.
365
+ * @param body - parsed request body: `{ path }`.
366
+ */
367
+ export async function handleInspectWorktree(deps, body) {
368
+ const parsed = readBody(body, ['path']);
369
+ if (isOutcome(parsed))
370
+ return parsed;
371
+ const { path } = parsed;
372
+ if (!isAbsoluteDir(path))
373
+ return fail(400, '"path" must be an absolute directory');
374
+ try {
375
+ const facts = await probeRepo(deps.exec, path, deps.dirExists);
376
+ if (facts === undefined)
377
+ return fail(400, `"${path}" is not inside a git repository`);
378
+ const inspected = await inspectWorktree(deps.exec, path);
379
+ const result = { dirty: inspected.dirty, ...inspected.ahead === undefined ? {} : { ahead: inspected.ahead } };
380
+ return { status: 200, body: result };
381
+ }
382
+ catch (error) {
383
+ if (error instanceof GitError)
384
+ return gitFailure(error);
385
+ return fail(500, error instanceof Error ? error.message : String(error));
386
+ }
387
+ }
388
+ /**
389
+ * POST /remove — delete one linked worktree: git's registration plus the
390
+ * folder in one stroke (`worktree remove`, `--force` past uncommitted
391
+ * changes the dialog already showed). DSH-side cleanup (archiving the
392
+ * workspace's sessions, dropping the workspace registration) is the
393
+ * browser's follow-up, by design: git first, so a refused removal leaves
394
+ * the workspace world untouched.
395
+ * @param deps - host dependencies.
396
+ * @param body - parsed request body: `{ path, force? }`.
397
+ */
398
+ export async function handleRemoveWorktree(deps, body) {
399
+ const parsed = readBody(body, ['path'], ['force']);
400
+ if (isOutcome(parsed))
401
+ return parsed;
402
+ const { path, force } = parsed;
403
+ if (!isAbsoluteDir(path))
404
+ return fail(400, '"path" must be an absolute directory');
405
+ try {
406
+ const facts = await probeRepo(deps.exec, path, deps.dirExists);
407
+ if (facts === undefined)
408
+ return fail(400, `"${path}" is not inside a git repository`);
409
+ const result = await removeWorktree(deps.exec, facts.repoRoot, path, force === true, deps.dirExists);
410
+ return { status: 200, body: result };
411
+ }
412
+ catch (error) {
413
+ if (error instanceof GitError)
414
+ return gitFailure(error);
415
+ return fail(500, error instanceof Error ? error.message : String(error));
416
+ }
417
+ }
418
+ /**
419
+ * POST /exists — batch directory-existence probe over plain fs (no git): true
420
+ * per path that exists AND is a directory. The browser gates the
421
+ * register-as-workspace action on this, so a missing folder (deleted, moved,
422
+ * or a corrupted session-header cwd) is answered by THIS route — the DSH
423
+ * workspace API never sees an unregistrable path.
424
+ * @param deps - host dependencies.
425
+ * @param body - parsed request body: `{ paths }`.
426
+ */
427
+ export async function handlePathExists(deps, body) {
428
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
429
+ return fail(400, 'request body must be a JSON object');
430
+ const paths = body.paths;
431
+ if (!Array.isArray(paths))
432
+ return fail(400, 'body key "paths" must be an array of absolute directories');
433
+ const unknownKeys = Object.keys(body).filter(key => key !== 'paths');
434
+ if (unknownKeys.length > 0)
435
+ return fail(400, `unknown body key "${unknownKeys[0]}"`);
436
+ const distinct = [];
437
+ for (const candidate of paths) {
438
+ if (typeof candidate !== 'string' || !isAbsoluteDir(candidate))
439
+ return fail(400, 'body key "paths" must be an array of absolute directories');
440
+ if (!distinct.includes(candidate))
441
+ distinct.push(candidate);
442
+ }
443
+ if (distinct.length > GROUP_PATHS_LIMIT)
444
+ return fail(400, `body key "paths" accepts at most ${String(GROUP_PATHS_LIMIT)} distinct directories`);
445
+ const statDirectory = deps.statDirectory ?? fsStatDirectory;
446
+ const exists = {};
447
+ await Promise.all(distinct.map(async (path) => {
448
+ // One bad path must not sink the batch: a probe that throws reads as
449
+ // "not a directory" — exactly the gating answer the client needs.
450
+ exists[path] = await statDirectory(path).catch(() => false);
451
+ }));
452
+ // 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.
457
+ const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
458
+ const rebuildable = {};
459
+ for (const path of distinct) {
460
+ if (exists[path])
461
+ continue;
462
+ rebuildable[path] = dirname(resolve(path)) === resolve(rootDir);
463
+ }
464
+ return { status: 200, body: { exists, ...Object.values(rebuildable).some(Boolean) ? { rebuildable } : {} } };
465
+ }
466
+ /**
467
+ * 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,
470
+ * so rebuilding the empty folder is self-healing (historical sessions
471
+ * reattach automatically once realpath matches again — DSH keeps the
472
+ * workspace accounting and filters membership by the session header's cwd).
473
+ * Anything else is outside this plugin's territory and is refused, so a
474
+ * corrupted session-header cwd can never be materialized as stray folders.
475
+ * @param deps - host dependencies.
476
+ * @param body - parsed request body: `{ path }`.
477
+ */
478
+ export async function handleEnsureDirectory(deps, body) {
479
+ const parsed = readBody(body, ['path']);
480
+ if (isOutcome(parsed))
481
+ return parsed;
482
+ const { path } = parsed;
483
+ if (!isAbsoluteDir(path))
484
+ return fail(400, '"path" must be an absolute directory');
485
+ const configured = deps.sectionRootDir()?.trim();
486
+ if (configured !== undefined && configured !== '' && !isAbsoluteConfigPath(configured)) {
487
+ return fail(400, `configured rootDir "${String(deps.sectionRootDir())}" is not an absolute path`);
488
+ }
489
+ const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
490
+ 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)}"`);
495
+ }
496
+ const mkdirRecursive = deps.mkdirRecursive ?? fsMkdirRecursive;
497
+ try {
498
+ const statDirectory = deps.statDirectory ?? fsStatDirectory;
499
+ if (await statDirectory(canonical))
500
+ return { status: 200, body: { created: true } };
501
+ await mkdirRecursive(canonical);
502
+ return { status: 200, body: { created: true } };
503
+ }
504
+ catch (error) {
505
+ return fail(500, error instanceof Error ? error.message : String(error));
506
+ }
507
+ }
package/lib/wire.d.ts CHANGED
@@ -20,6 +20,14 @@ export declare const ROUTE_FETCH = "/plugin/git-worktree/fetch";
20
20
  export declare const ROUTE_UPDATE = "/plugin/git-worktree/update";
21
21
  /** POST ROUTE_PREFIX/group — git belonging facts for a batch of workspace paths. */
22
22
  export declare const ROUTE_GROUP = "/plugin/git-worktree/group";
23
+ /** POST ROUTE_PREFIX/inspect — pre-delete facts for one worktree directory. */
24
+ export declare const ROUTE_INSPECT = "/plugin/git-worktree/inspect";
25
+ /** POST ROUTE_PREFIX/remove — delete one linked worktree (git registration + folder). */
26
+ export declare const ROUTE_REMOVE = "/plugin/git-worktree/remove";
27
+ /** POST ROUTE_PREFIX/exists — batch directory-existence probe (fs, no git). */
28
+ export declare const ROUTE_EXISTS = "/plugin/git-worktree/exists";
29
+ /** POST ROUTE_PREFIX/ensure-directory — mkdir -p a missing worktree storage slot. */
30
+ export declare const ROUTE_ENSURE_DIRECTORY = "/plugin/git-worktree/ensure-directory";
23
31
  /** One selectable branch row. */
24
32
  export interface BranchEntry {
25
33
  /** Display name: a bare local name (`main`) or `<remote>/<name>`. */
@@ -156,3 +164,63 @@ export interface GroupWorkspacesResult {
156
164
  /** Git facts per path; null marks a path outside any git repository. */
157
165
  facts: Record<string, WorkspaceGitFacts | null>;
158
166
  }
167
+ /** POST inspect request body. */
168
+ export interface InspectWorktreeBody {
169
+ /** The worktree directory to inspect (absolute). */
170
+ path: string;
171
+ }
172
+ /** POST inspect response body — the facts the remove-confirm dialog shows. */
173
+ export interface InspectWorktreeResult {
174
+ /** Uncommitted changes in the directory (staged + unstaged + untracked
175
+ * file rows of `git status --porcelain`). */
176
+ dirty: number;
177
+ /** Commits the checked-out branch is ahead of its upstream; absent = no
178
+ * upstream. Purely informational: the branch ref survives the removal, so
179
+ * these commits are NOT lost. */
180
+ ahead?: number;
181
+ }
182
+ /** POST remove request body. */
183
+ export interface RemoveWorktreeBody {
184
+ /** The linked worktree directory to delete (absolute). */
185
+ path: string;
186
+ /** True: force past uncommitted changes (the confirm dialog already
187
+ * showed the dirty count). */
188
+ force?: boolean;
189
+ }
190
+ /** POST remove response body. */
191
+ export interface RemoveWorktreeResult {
192
+ /** The removed worktree directory. */
193
+ path: string;
194
+ /** True when only a stale registration was pruned (the directory was
195
+ * already gone); false when `git worktree remove` deleted a live folder. */
196
+ pruned: boolean;
197
+ }
198
+ /** POST exists request body. */
199
+ export interface PathExistsBody {
200
+ /** Absolute directories to probe (deduped server-side). */
201
+ paths: string[];
202
+ }
203
+ /** POST exists response body — one entry per DISTINCT requested path; true =
204
+ * the path exists AND is a directory. The client gates the register action on
205
+ * this, so a missing folder never reaches the DSH workspace API. */
206
+ export interface PathExistsResult {
207
+ exists: Record<string, boolean>;
208
+ /** Per MISSING path: true when it sits DIRECTLY inside the plugin's
209
+ * worktree storage root — a slot this plugin planned, so rebuilding the
210
+ * empty directory is safe (historical sessions reattach automatically once
211
+ * realpath matches again). Absent paths and directories outside the root
212
+ * never appear here. */
213
+ rebuildable?: Record<string, boolean>;
214
+ }
215
+ /** POST ensure-directory request body. */
216
+ export interface EnsureDirectoryBody {
217
+ /** The missing directory to create (absolute; must sit directly inside the
218
+ * worktree storage root). */
219
+ path: string;
220
+ }
221
+ /** POST ensure-directory response body. */
222
+ export interface EnsureDirectoryResult {
223
+ /** Always true on 200 — the directory now exists (created, or already
224
+ * present as a directory). */
225
+ created: boolean;
226
+ }
package/lib/wire.js CHANGED
@@ -20,3 +20,11 @@ export const ROUTE_FETCH = `${ROUTE_PREFIX}/fetch`;
20
20
  export const ROUTE_UPDATE = `${ROUTE_PREFIX}/update`;
21
21
  /** POST ROUTE_PREFIX/group — git belonging facts for a batch of workspace paths. */
22
22
  export const ROUTE_GROUP = `${ROUTE_PREFIX}/group`;
23
+ /** POST ROUTE_PREFIX/inspect — pre-delete facts for one worktree directory. */
24
+ export const ROUTE_INSPECT = `${ROUTE_PREFIX}/inspect`;
25
+ /** POST ROUTE_PREFIX/remove — delete one linked worktree (git registration + folder). */
26
+ export const ROUTE_REMOVE = `${ROUTE_PREFIX}/remove`;
27
+ /** POST ROUTE_PREFIX/exists — batch directory-existence probe (fs, no git). */
28
+ export const ROUTE_EXISTS = `${ROUTE_PREFIX}/exists`;
29
+ /** POST ROUTE_PREFIX/ensure-directory — mkdir -p a missing worktree storage slot. */
30
+ export const ROUTE_ENSURE_DIRECTORY = `${ROUTE_PREFIX}/ensure-directory`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@laoyuehanni/dsh-git-worktree",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "DSH plugin: branch visibility and git worktree isolation for Web UI sessions",
5
5
  "keywords": [
6
6
  "dsh",