@laoyuehanni/dsh-git-worktree 0.4.1 → 0.4.3-dsh-0.1.2-alpha.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
@@ -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.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * dsh-git-worktree host half. Owns the worktree storage-root settings section
3
3
  * (the `git-worktree` namespace in the dsh settings document, registered
4
- * through installSettingsSection with the composition entry as its base
4
+ * through SettingsProvider.installSection with the composition entry as its
5
+ * base
5
6
  * layer) and — while a webServer service exists — the HTTP routes the browser
6
7
  * half fetches. A stored root edit takes effect live: the routes read the
7
8
  * section source per request, so no restart and no route re-registration.
@@ -25,7 +26,7 @@ export interface Config {
25
26
  /** Reject stale or misspelled config keys before defaults can hide them. */
26
27
  export declare function validateConfig(config: Config): void;
27
28
  /** The settings namespace this plugin serves; its browser card spells the same string. */
28
- export declare const GIT_WORKTREE_NS: import("@deepseek-ai/dsh-settings").SettingsNamespace;
29
+ export declare const GIT_WORKTREE_NS = "git-worktree";
29
30
  /** The settings-facing subset of the config: the worktree storage root and the sidebar grouping switch. */
30
31
  export interface SectionConfig {
31
32
  /** Worktree storage root; absent/blank selects `$DSH_HOME/gitworktree`. */
package/lib/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * dsh-git-worktree host half. Owns the worktree storage-root settings section
3
3
  * (the `git-worktree` namespace in the dsh settings document, registered
4
- * through installSettingsSection with the composition entry as its base
4
+ * through SettingsProvider.installSection with the composition entry as its
5
+ * base
5
6
  * layer) and — while a webServer service exists — the HTTP routes the browser
6
7
  * half fetches. A stored root edit takes effect live: the routes read the
7
8
  * section source per request, so no restart and no route re-registration.
@@ -14,12 +15,11 @@
14
15
  */
15
16
  import { homedir } from 'node:os';
16
17
  import { rename } from 'node:fs/promises';
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. */
@@ -39,7 +39,7 @@ export function validateConfig(config) {
39
39
  validateRootDir(config.rootDir);
40
40
  }
41
41
  /** The settings namespace this plugin serves; its browser card spells the same string. */
42
- export const GIT_WORKTREE_NS = settingsNamespace('git-worktree');
42
+ export const GIT_WORKTREE_NS = 'git-worktree';
43
43
  /** Schema resolving the `git-worktree` settings section. */
44
44
  export const sectionSchema = z.object({
45
45
  rootDir: z.string(),
@@ -73,18 +73,25 @@ export function apply(ctx, config = {}) {
73
73
  home: () => homedir(),
74
74
  envHome: () => process.env.DSH_HOME,
75
75
  });
76
- installSettingsSection(ctx, GIT_WORKTREE_NS, sectionSchema, sectionOf(config), {
77
- validate: value => {
78
- validateRootDir(value.rootDir);
79
- if (value.groupSidebar !== undefined && typeof value.groupSidebar !== 'boolean') {
80
- throw new Error('groupSidebar must be a boolean');
81
- }
82
- },
83
- setSource: (source) => { sectionSource = source; },
84
- onChange: () => {
85
- // The storage root takes effect live: the routes read the section
86
- // source per request, so a committed edit needs no action here.
87
- },
76
+ // Host 0.1.2 hosts section installation on the provider itself: the same
77
+ // composition-entry base, validate, setSource, and onChange hooks ride
78
+ // `SettingsProvider.installSection`, reached through a settings injection.
79
+ // The registration is an effect on this plugin's fiber either way, so a
80
+ // late-attaching settings service is handled by the injection itself.
81
+ ctx.inject(['settings'], (settingsCtx) => {
82
+ settingsCtx.settings.installSection(ctx, GIT_WORKTREE_NS, sectionSchema, sectionOf(config), {
83
+ validate: value => {
84
+ validateRootDir(value.rootDir);
85
+ if (value.groupSidebar !== undefined && typeof value.groupSidebar !== 'boolean') {
86
+ throw new Error('groupSidebar must be a boolean');
87
+ }
88
+ },
89
+ setSource: (source) => { sectionSource = source; },
90
+ onChange: () => {
91
+ // The storage root takes effect live: the routes read the section
92
+ // source per request, so a committed edit needs no action here.
93
+ },
94
+ });
88
95
  });
89
96
  // One-shot legacy migration: the pre-0.3 plugin persisted its own
90
97
  // ~/.dsh/git-work-tree/settings.json. Registered after installSettingsSection
@@ -199,5 +206,37 @@ export function apply(ctx, config = {}) {
199
206
  send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
200
207
  }
201
208
  } }), 'git-worktree: update route');
209
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_INSPECT, handler: async (req, res) => {
210
+ try {
211
+ send(res, await handleInspectWorktree(deps(), await readJson(req)));
212
+ }
213
+ catch (error) {
214
+ send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
215
+ }
216
+ } }), 'git-worktree: inspect route');
217
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_REMOVE, handler: async (req, res) => {
218
+ try {
219
+ send(res, await handleRemoveWorktree(deps(), await readJson(req)));
220
+ }
221
+ catch (error) {
222
+ send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
223
+ }
224
+ } }), 'git-worktree: remove route');
225
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_EXISTS, handler: async (req, res) => {
226
+ try {
227
+ send(res, await handlePathExists(deps(), await readJson(req)));
228
+ }
229
+ catch (error) {
230
+ send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
231
+ }
232
+ } }), 'git-worktree: exists route');
233
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_ENSURE_DIRECTORY, handler: async (req, res) => {
234
+ try {
235
+ send(res, await handleEnsureDirectory(deps(), await readJson(req)));
236
+ }
237
+ catch (error) {
238
+ send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
239
+ }
240
+ } }), 'git-worktree: ensure-directory route');
202
241
  });
203
242
  }
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
+ }