@laoyuehanni/dsh-git-worktree 0.4.1 → 0.4.2

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,6 +152,40 @@ 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
package/lib/git.js CHANGED
@@ -360,6 +360,56 @@ 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
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,11 +2,24 @@
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 } };
@@ -84,7 +97,13 @@ function gitFailure(error) {
84
97
  // found`), so match its `branch "` shape — git's own "not found"
85
98
  // texts (a remote that vanished mid-fetch: `Repository '...' not
86
99
  // found`) carry no quoted branch and stay 500 host faults.
87
- || error.stderr.includes('branch "');
100
+ || error.stderr.includes('branch "')
101
+ // Removal refusals from git.ts are caller-side state the same way: the
102
+ // main worktree (git refuses it too, but the route answers a clean 400
103
+ // before ever spawning git) and a path the repository never registered
104
+ // (a stale sidebar row racing a terminal-side removal).
105
+ || error.stderr.includes('cannot remove the main worktree')
106
+ || error.stderr.includes('is not a registered worktree');
88
107
  return fail(usage ? 400 : 500, error.message);
89
108
  }
90
109
  /**
@@ -333,3 +352,153 @@ export async function handleUpdate(deps, body) {
333
352
  return fail(500, error instanceof Error ? error.message : String(error));
334
353
  }
335
354
  }
355
+ /**
356
+ * POST /inspect — pre-delete facts for one worktree directory: the
357
+ * uncommitted-file count (those die with the folder) and the checked-out
358
+ * branch's ahead count (kept — the branch ref survives the removal).
359
+ * Deliberately repo-wide neutral: any directory inside a repository answers,
360
+ * so the dialog data stays meaningful even for odd shapes.
361
+ * @param deps - host dependencies.
362
+ * @param body - parsed request body: `{ path }`.
363
+ */
364
+ export async function handleInspectWorktree(deps, body) {
365
+ const parsed = readBody(body, ['path']);
366
+ if (isOutcome(parsed))
367
+ return parsed;
368
+ const { path } = parsed;
369
+ if (!isAbsoluteDir(path))
370
+ return fail(400, '"path" must be an absolute directory');
371
+ try {
372
+ const facts = await probeRepo(deps.exec, path, deps.dirExists);
373
+ if (facts === undefined)
374
+ return fail(400, `"${path}" is not inside a git repository`);
375
+ const inspected = await inspectWorktree(deps.exec, path);
376
+ const result = { dirty: inspected.dirty, ...inspected.ahead === undefined ? {} : { ahead: inspected.ahead } };
377
+ return { status: 200, body: result };
378
+ }
379
+ catch (error) {
380
+ if (error instanceof GitError)
381
+ return gitFailure(error);
382
+ return fail(500, error instanceof Error ? error.message : String(error));
383
+ }
384
+ }
385
+ /**
386
+ * POST /remove — delete one linked worktree: git's registration plus the
387
+ * folder in one stroke (`worktree remove`, `--force` past uncommitted
388
+ * changes the dialog already showed). DSH-side cleanup (archiving the
389
+ * workspace's sessions, dropping the workspace registration) is the
390
+ * browser's follow-up, by design: git first, so a refused removal leaves
391
+ * the workspace world untouched.
392
+ * @param deps - host dependencies.
393
+ * @param body - parsed request body: `{ path, force? }`.
394
+ */
395
+ export async function handleRemoveWorktree(deps, body) {
396
+ const parsed = readBody(body, ['path'], ['force']);
397
+ if (isOutcome(parsed))
398
+ return parsed;
399
+ const { path, force } = parsed;
400
+ if (!isAbsoluteDir(path))
401
+ return fail(400, '"path" must be an absolute directory');
402
+ try {
403
+ const facts = await probeRepo(deps.exec, path, deps.dirExists);
404
+ if (facts === undefined)
405
+ return fail(400, `"${path}" is not inside a git repository`);
406
+ const result = await removeWorktree(deps.exec, facts.repoRoot, path, force === true, deps.dirExists);
407
+ return { status: 200, body: result };
408
+ }
409
+ catch (error) {
410
+ if (error instanceof GitError)
411
+ return gitFailure(error);
412
+ return fail(500, error instanceof Error ? error.message : String(error));
413
+ }
414
+ }
415
+ /**
416
+ * POST /exists — batch directory-existence probe over plain fs (no git): true
417
+ * per path that exists AND is a directory. The browser gates the
418
+ * register-as-workspace action on this, so a missing folder (deleted, moved,
419
+ * or a corrupted session-header cwd) is answered by THIS route — the DSH
420
+ * workspace API never sees an unregistrable path.
421
+ * @param deps - host dependencies.
422
+ * @param body - parsed request body: `{ paths }`.
423
+ */
424
+ export async function handlePathExists(deps, body) {
425
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
426
+ return fail(400, 'request body must be a JSON object');
427
+ const paths = body.paths;
428
+ if (!Array.isArray(paths))
429
+ return fail(400, 'body key "paths" must be an array of absolute directories');
430
+ const unknownKeys = Object.keys(body).filter(key => key !== 'paths');
431
+ if (unknownKeys.length > 0)
432
+ return fail(400, `unknown body key "${unknownKeys[0]}"`);
433
+ const distinct = [];
434
+ for (const candidate of paths) {
435
+ if (typeof candidate !== 'string' || !isAbsoluteDir(candidate))
436
+ return fail(400, 'body key "paths" must be an array of absolute directories');
437
+ if (!distinct.includes(candidate))
438
+ distinct.push(candidate);
439
+ }
440
+ if (distinct.length > GROUP_PATHS_LIMIT)
441
+ return fail(400, `body key "paths" accepts at most ${String(GROUP_PATHS_LIMIT)} distinct directories`);
442
+ const statDirectory = deps.statDirectory ?? fsStatDirectory;
443
+ const exists = {};
444
+ await Promise.all(distinct.map(async (path) => {
445
+ // One bad path must not sink the batch: a probe that throws reads as
446
+ // "not a directory" — exactly the gating answer the client needs.
447
+ exists[path] = await statDirectory(path).catch(() => false);
448
+ }));
449
+ // Rebuildability is a STORAGE-SLOT fact, not a general one: only a missing
450
+ // path sitting DIRECTLY inside the resolved worktree root is a slot this
451
+ // plugin planned, so recreating the empty directory is safe self-healing
452
+ // (its sessions reattach by realpath once the folder is back). Paths
453
+ // outside the root are the user's own territory — never rebuilt here.
454
+ const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
455
+ const rebuildable = {};
456
+ for (const path of distinct) {
457
+ if (exists[path])
458
+ continue;
459
+ rebuildable[path] = dirname(resolve(path)) === resolve(rootDir);
460
+ }
461
+ return { status: 200, body: { exists, ...Object.values(rebuildable).some(Boolean) ? { rebuildable } : {} } };
462
+ }
463
+ /**
464
+ * POST /ensure-directory — recreate a MISSING worktree storage slot
465
+ * (`mkdir -p`). Strictly gated to paths sitting DIRECTLY inside the resolved
466
+ * worktree storage root: those slots were planned and created by this plugin,
467
+ * so rebuilding the empty folder is self-healing (historical sessions
468
+ * reattach automatically once realpath matches again — DSH keeps the
469
+ * workspace accounting and filters membership by the session header's cwd).
470
+ * Anything else is outside this plugin's territory and is refused, so a
471
+ * corrupted session-header cwd can never be materialized as stray folders.
472
+ * @param deps - host dependencies.
473
+ * @param body - parsed request body: `{ path }`.
474
+ */
475
+ export async function handleEnsureDirectory(deps, body) {
476
+ const parsed = readBody(body, ['path']);
477
+ if (isOutcome(parsed))
478
+ return parsed;
479
+ const { path } = parsed;
480
+ if (!isAbsoluteDir(path))
481
+ return fail(400, '"path" must be an absolute directory');
482
+ const configured = deps.sectionRootDir()?.trim();
483
+ if (configured !== undefined && configured !== '' && !isAbsoluteConfigPath(configured)) {
484
+ return fail(400, `configured rootDir "${String(deps.sectionRootDir())}" is not an absolute path`);
485
+ }
486
+ const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
487
+ const canonical = resolve(path);
488
+ // Exactly one level below the root, compared on resolved forms so `..`
489
+ // and spelling drift cannot escape the slot boundary.
490
+ if (dirname(canonical) !== resolve(rootDir)) {
491
+ return fail(400, `"${canonical}" is outside the worktree storage root "${resolve(rootDir)}"`);
492
+ }
493
+ const mkdirRecursive = deps.mkdirRecursive ?? fsMkdirRecursive;
494
+ try {
495
+ const statDirectory = deps.statDirectory ?? fsStatDirectory;
496
+ if (await statDirectory(canonical))
497
+ return { status: 200, body: { created: true } };
498
+ await mkdirRecursive(canonical);
499
+ return { status: 200, body: { created: true } };
500
+ }
501
+ catch (error) {
502
+ return fail(500, error instanceof Error ? error.message : String(error));
503
+ }
504
+ }
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.2",
4
4
  "description": "DSH plugin: branch visibility and git worktree isolation for Web UI sessions",
5
5
  "keywords": [
6
6
  "dsh",