dsh-git-scm 0.1.0 → 0.3.0

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/host/git.d.ts CHANGED
@@ -153,6 +153,33 @@ export interface Tag {
153
153
  /** Creation timestamp in Unix epoch milliseconds, or null. */
154
154
  date: number | null;
155
155
  }
156
+ /** One registered Git worktree of the repository. */
157
+ export interface WorktreeEntry {
158
+ /** Absolute checkout directory. */
159
+ path: string;
160
+ /** Base name of the checkout directory. */
161
+ name: string;
162
+ /** Short local branch name, or null for a detached or bare checkout. */
163
+ branch: string | null;
164
+ /** Abbreviated HEAD commit, or null for a bare checkout. */
165
+ head: string | null;
166
+ /** Whether the checkout is on a detached HEAD. */
167
+ detached: boolean;
168
+ /** Whether the entry is the bare repository itself. */
169
+ bare: boolean;
170
+ /** Whether the worktree is locked. */
171
+ locked: boolean;
172
+ /** Reason recorded with the lock, when one exists. */
173
+ lockReason: string | null;
174
+ /** Whether Git considers the registration prunable (its directory is gone). */
175
+ prunable: boolean;
176
+ /** Reason recorded with the prunable mark, when one exists. */
177
+ pruneReason: string | null;
178
+ /** Whether this worktree is the checkout the Session is looking at. */
179
+ current: boolean;
180
+ /** Whether this is the repository's main checkout (`git worktree list` first entry). */
181
+ main: boolean;
182
+ }
156
183
  /** The repository snapshot `gitSummary` answers. */
157
184
  export interface Summary {
158
185
  /** Repository identity. */
@@ -165,6 +192,8 @@ export interface Summary {
165
192
  stashes: Stash[];
166
193
  /** Tags. */
167
194
  tags: Tag[];
195
+ /** Registered worktrees, the main checkout first. */
196
+ worktrees: WorktreeEntry[];
168
197
  }
169
198
  /** The light snapshot `gitStatus` answers. */
170
199
  export interface StatusSnapshot {
@@ -266,6 +295,10 @@ export interface ActionResult {
266
295
  changed?: RefChange[];
267
296
  /** `pullBranch` only: commits the fast-forward brought in. */
268
297
  commits?: number;
298
+ /** `worktreeAdd` only: the created or reused checkout directory. */
299
+ worktreePath?: string;
300
+ /** `worktreeAdd` only: the checked-out branch name. */
301
+ branch?: string;
269
302
  }
270
303
  /** Line counts of one changed file. */
271
304
  export interface LineCount {
@@ -283,6 +316,9 @@ export interface GitSummaryRequest {
283
316
  /** Overrides for the layer's default limits. */
284
317
  limits?: Partial<GitLimits> | undefined;
285
318
  }
319
+ /** Request of one registered-worktree list read. */
320
+ export interface GitWorktreesRequest extends GitSummaryRequest {
321
+ }
286
322
  /** Request of one working-tree patch read. */
287
323
  export interface GitDiffRequest extends GitSummaryRequest {
288
324
  /** Repository-relative path to diff. */
@@ -347,6 +383,13 @@ export declare const NETWORK_TIMEOUT_MS = 300000;
347
383
  * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.
348
384
  */
349
385
  export declare function gitSummary({ exec, cwd, limits }: GitSummaryRequest): Promise<Summary>;
386
+ /**
387
+ * Read the registered worktrees of the checkout, the main checkout first.
388
+ * @param request - `exec`, `cwd`, and `limits`.
389
+ * @returns the worktree list of the wire contract.
390
+ * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.
391
+ */
392
+ export declare function gitWorktrees({ exec, cwd, limits }: GitWorktreesRequest): Promise<WorktreeEntry[]>;
350
393
  /**
351
394
  * Read the repository identity and working-tree changes only, for polling.
352
395
  * @param request - `exec`, `cwd`, and `limits`.
@@ -70,6 +70,8 @@ export interface GitLimits {
70
70
  maxCommits: number;
71
71
  /** Maximum tags. */
72
72
  maxTags: number;
73
+ /** Maximum registered worktrees. */
74
+ maxWorktrees: number;
73
75
  /** Maximum changed files across all change lists. */
74
76
  maxFiles: number;
75
77
  /** Maximum characters of one returned diff. */
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readFile, stat, writeFile } from "node:fs/promises";
1
+ import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
2
2
  import { dirname, isAbsolute, join, normalize } from "node:path";
3
3
  // src/host/git.ts
4
4
  /**
@@ -65,6 +65,7 @@ var DEFAULT_LIMITS = Object.freeze({
65
65
  maxBranches: 500,
66
66
  maxCommits: 40,
67
67
  maxTags: 30,
68
+ maxWorktrees: 64,
68
69
  maxFiles: 3e3,
69
70
  maxDiffBytes: 409600
70
71
  });
@@ -73,6 +74,7 @@ var LIMIT_KEYS = [
73
74
  "maxBranches",
74
75
  "maxCommits",
75
76
  "maxTags",
77
+ "maxWorktrees",
76
78
  "maxFiles",
77
79
  "maxDiffBytes"
78
80
  ];
@@ -375,7 +377,7 @@ async function readChanges(exec, limits) {
375
377
  "status",
376
378
  "--porcelain=v2",
377
379
  "-z",
378
- "--untracked-files=normal"
380
+ "--untracked-files=all"
379
381
  ], "status")).stdout, limits.maxFiles);
380
382
  }
381
383
  /** Parse one `for-each-ref` record into a branch entry. */
@@ -483,6 +485,120 @@ async function readTags(exec, limits) {
483
485
  }
484
486
  return tags;
485
487
  }
488
+ /** The canonical form of a path, tolerant of a checkout that no longer exists. */
489
+ async function canonicalPath(path) {
490
+ try {
491
+ return await realpath(path);
492
+ } catch {
493
+ return normalize(path);
494
+ }
495
+ }
496
+ /** Whether a path exists in the filesystem. */
497
+ async function pathExists(path) {
498
+ try {
499
+ await stat(path);
500
+ return true;
501
+ } catch {
502
+ return false;
503
+ }
504
+ }
505
+ /** Turn one porcelain record into the wire entry. */
506
+ function worktreeEntry(record, main) {
507
+ const path = record.path ?? "";
508
+ const branch = typeof record.branch === "string" ? record.branch.replace(/^refs\/heads\//, "") : null;
509
+ return {
510
+ path,
511
+ name: path.split(/[\\/]/).filter((part) => part.length > 0).pop() ?? path,
512
+ branch,
513
+ head: typeof record.head === "string" && record.head.length > 0 ? record.head.slice(0, 7) : null,
514
+ detached: record.detached === true,
515
+ bare: record.bare === true,
516
+ locked: record.locked === true,
517
+ lockReason: record.lockReason ?? null,
518
+ prunable: record.prunable === true,
519
+ pruneReason: record.pruneReason ?? null,
520
+ current: false,
521
+ main
522
+ };
523
+ }
524
+ /** Registered worktrees of the checkout, the main checkout first. */
525
+ async function readWorktrees(exec, root, limits) {
526
+ if (limits.maxWorktrees === 0) return [];
527
+ const result = await run(exec, [
528
+ "worktree",
529
+ "list",
530
+ "--porcelain",
531
+ "-z"
532
+ ], "worktree list");
533
+ const records = [];
534
+ let record = null;
535
+ for (const field of result.stdout.split("\0")) {
536
+ if (field.length === 0) {
537
+ if (record !== null && record.path !== void 0) records.push(record);
538
+ record = null;
539
+ continue;
540
+ }
541
+ if (record === null) record = {};
542
+ const space = field.indexOf(" ");
543
+ const key = space === -1 ? field : field.slice(0, space);
544
+ const value = space === -1 ? "" : field.slice(space + 1);
545
+ switch (key) {
546
+ case "worktree":
547
+ record.path = value;
548
+ break;
549
+ case "HEAD":
550
+ record.head = value;
551
+ break;
552
+ case "branch":
553
+ record.branch = value;
554
+ break;
555
+ case "detached":
556
+ record.detached = true;
557
+ break;
558
+ case "bare":
559
+ record.bare = true;
560
+ break;
561
+ case "locked":
562
+ record.locked = true;
563
+ if (value.length > 0) record.lockReason = value;
564
+ break;
565
+ case "prunable":
566
+ record.prunable = true;
567
+ if (value.length > 0) record.pruneReason = value;
568
+ }
569
+ }
570
+ if (record !== null && record.path !== void 0) records.push(record);
571
+ const canonicalRoot = await canonicalPath(root);
572
+ const entries = [];
573
+ for (const [index, item] of records.slice(0, limits.maxWorktrees).entries()) {
574
+ const entry = worktreeEntry(item, index === 0);
575
+ entry.current = await canonicalPath(entry.path) === canonicalRoot;
576
+ entries.push(entry);
577
+ }
578
+ return entries;
579
+ }
580
+ /** Directory slug a branch name gets inside the repository's worktree pool. */
581
+ function worktreeSlug(branch) {
582
+ const slug = branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
583
+ if (slug.length === 0 || slug === "." || slug === "..") throw new GitError("INVALID", `"${branch}" has no usable worktree directory name`);
584
+ return slug;
585
+ }
586
+ /** Ensure the repository's worktree pool exists and stays out of Git's status output. */
587
+ async function prepareWorktreePool(root) {
588
+ const pool = join(root, ".agents", "worktrees");
589
+ await mkdir(pool, { recursive: true });
590
+ const ignore = join(pool, ".gitignore");
591
+ if (!await pathExists(ignore)) await writeFile(ignore, "*\n", "utf8");
592
+ return pool;
593
+ }
594
+ /** One registered worktree addressed by its exact directory path. */
595
+ async function registeredWorktree(exec, root, path) {
596
+ const value = typeof path === "string" ? path.trim() : "";
597
+ if (value.length === 0) throw new GitError("INVALID", "a worktree path is required");
598
+ const entry = (await readWorktrees(exec, root, DEFAULT_LIMITS)).find((candidate) => candidate.path === value);
599
+ if (entry === void 0) throw new GitError("INVALID", `"${value}" is not a registered worktree of this checkout`);
600
+ return entry;
601
+ }
486
602
  /** Current remote-tracking tips, keyed by short ref name. */
487
603
  async function readRemoteTips(exec) {
488
604
  const result = await run(exec, [
@@ -575,7 +691,7 @@ async function gitSummary({ exec, cwd, limits = {} }) {
575
691
  const bounds = resolveLimits(limits);
576
692
  const root = await repositoryRoot(exec, cwd);
577
693
  if (root === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
578
- const [{ repo, changes }, branches, stashes, tags] = await Promise.all([
694
+ const [{ repo, changes }, branches, stashes, tags, worktrees] = await Promise.all([
579
695
  readRepo({
580
696
  exec,
581
697
  root,
@@ -583,17 +699,31 @@ async function gitSummary({ exec, cwd, limits = {} }) {
583
699
  }),
584
700
  readBranches(exec, bounds),
585
701
  readStashes(exec),
586
- readTags(exec, bounds)
702
+ readTags(exec, bounds),
703
+ readWorktrees(exec, root, bounds)
587
704
  ]);
588
705
  return {
589
706
  repo,
590
707
  changes,
591
708
  branches,
592
709
  stashes,
593
- tags
710
+ tags,
711
+ worktrees
594
712
  };
595
713
  }
596
714
  /**
715
+ * Read the registered worktrees of the checkout, the main checkout first.
716
+ * @param request - `exec`, `cwd`, and `limits`.
717
+ * @returns the worktree list of the wire contract.
718
+ * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.
719
+ */
720
+ async function gitWorktrees({ exec, cwd, limits = {} }) {
721
+ const bounds = resolveLimits(limits);
722
+ const root = await repositoryRoot(exec, cwd);
723
+ if (root === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
724
+ return await readWorktrees(exec, root, bounds);
725
+ }
726
+ /**
597
727
  * Read the repository identity and working-tree changes only, for polling.
598
728
  * @param request - `exec`, `cwd`, and `limits`.
599
729
  * @returns the light snapshot.
@@ -1373,7 +1503,9 @@ async function gitAction({ exec, cwd, operation, params = {} }) {
1373
1503
  ], "reset");
1374
1504
  case "fetch": {
1375
1505
  const args = ["fetch", "--prune"];
1376
- if (params.all !== false) args.push("--all");
1506
+ const remote = params.remote === void 0 ? null : checkedRemoteName(params.remote);
1507
+ if (remote !== null) args.push(remote);
1508
+ else if (params.all !== false) args.push("--all");
1377
1509
  const before = await readRemoteTips(exec);
1378
1510
  const result = await mutate(exec, args, "fetch", network);
1379
1511
  const after = await readRemoteTips(exec);
@@ -1532,9 +1664,43 @@ async function gitAction({ exec, cwd, operation, params = {} }) {
1532
1664
  const remote = params.remote === void 0 ? await defaultRemote(exec) : checkedRemoteName(params.remote);
1533
1665
  if (remote === null) throw new GitError("INVALID", "the repository has no remote to publish to");
1534
1666
  args.push("--set-upstream", remote, branch);
1535
- }
1667
+ } else if (params.remote !== void 0) args.push(checkedRemoteName(params.remote), await requireBranch(exec));
1536
1668
  return await mutate(exec, args, "push", network);
1537
1669
  }
1670
+ case "worktreeAdd": {
1671
+ const branch = await checkBranchName(exec, params.branch);
1672
+ if (await isUnborn(exec)) throw new GitError("INVALID", "create the first commit before adding a worktree");
1673
+ const pool = await prepareWorktreePool(root);
1674
+ const path = join(pool, worktreeSlug(branch));
1675
+ if (await pathExists(path)) throw new GitError("INVALID", `the worktree directory already exists: ${path}`);
1676
+ return {
1677
+ ...await mutate(exec, await localBranchExists(exec, branch) ? [
1678
+ "worktree",
1679
+ "add",
1680
+ path,
1681
+ branch
1682
+ ] : [
1683
+ "worktree",
1684
+ "add",
1685
+ "-b",
1686
+ branch,
1687
+ path,
1688
+ checkedRef(params.base === void 0 ? "HEAD" : params.base)
1689
+ ], "worktree add"),
1690
+ worktreePath: path,
1691
+ branch
1692
+ };
1693
+ }
1694
+ case "worktreeRemove": {
1695
+ const worktree = await registeredWorktree(exec, root, params.path);
1696
+ if (worktree.current) throw new GitError("INVALID", "the worktree of the current checkout cannot be removed");
1697
+ if (worktree.main || worktree.bare) throw new GitError("INVALID", "the main checkout cannot be removed as a worktree");
1698
+ const args = ["worktree", "remove"];
1699
+ if (params.force === true) args.push("--force");
1700
+ args.push(worktree.path);
1701
+ return await mutate(exec, args, "worktree remove");
1702
+ }
1703
+ case "worktreePrune": return await mutate(exec, ["worktree", "prune"], "worktree prune");
1538
1704
  case "checkoutBranch": {
1539
1705
  const name = typeof params.name === "string" ? params.name : "";
1540
1706
  if (name.length === 0) throw new GitError("INVALID", "a branch name is required");
@@ -1714,7 +1880,10 @@ var OPERATIONS = Object.freeze([
1714
1880
  "tagDelete",
1715
1881
  "addToIgnore",
1716
1882
  "reveal",
1717
- "initRepository"
1883
+ "initRepository",
1884
+ "worktreeAdd",
1885
+ "worktreeRemove",
1886
+ "worktreePrune"
1718
1887
  ]);
1719
1888
  /** Set form of {@link WIRE_CODE_NAMES} used to recognize an already-coded failure. */
1720
1889
  var WIRE_CODES = /* @__PURE__ */ new Set([
@@ -1899,6 +2068,7 @@ var LIMITS = Object.freeze({
1899
2068
  maxBranches: 500,
1900
2069
  maxCommits: 40,
1901
2070
  maxTags: 30,
2071
+ maxWorktrees: 64,
1902
2072
  maxFiles: 3e3,
1903
2073
  maxDiffBytes: MAX_DIFF_BYTES,
1904
2074
  maxOutputBytes: MAX_OUTPUT_BYTES
@@ -2093,6 +2263,35 @@ function apply(ctx) {
2093
2263
  };
2094
2264
  }
2095
2265
  /**
2266
+ * Move one Session into a registered worktree of its current checkout.
2267
+ *
2268
+ * This is the one action that is not a Git command: it validates the target
2269
+ * against the checkout's own `git worktree list`, then commits the Session's
2270
+ * working directory through the host's working-directory service.
2271
+ * @param options - Session identity, checkout, action parameters, seam, and cancellation.
2272
+ * @returns the committed working directory.
2273
+ */
2274
+ async function switchWorktree({ sessionId, cwd, params, exec, signal }) {
2275
+ const target = requiredString(params.path, "params.path");
2276
+ const worktree = (await gitWorktrees({
2277
+ exec,
2278
+ cwd,
2279
+ limits: LIMITS
2280
+ })).find((entry) => entry.path === target);
2281
+ if (worktree === void 0) throw new RequestError("INVALID", `"${target}" is not a registered worktree of this checkout`);
2282
+ if (worktree.current) throw new RequestError("INVALID", "the Session already works in this worktree");
2283
+ if (worktree.prunable) throw new RequestError("INVALID", "the worktree directory is missing; prune the registration instead");
2284
+ const agents = ctx.get("agents");
2285
+ const workingDirectory = ctx.get("workingDirectory");
2286
+ if (agents === void 0 || workingDirectory === void 0) throw new RequestError("INVALID", "switching worktrees is unavailable in this profile");
2287
+ const agent = agents.get(sessionId);
2288
+ if (agent === void 0) throw new RequestError("NO_SESSION", "the Session has no live Agent to switch");
2289
+ return {
2290
+ message: "switched to the worktree",
2291
+ path: await workingDirectory.set(agent, worktree.path, signal)
2292
+ };
2293
+ }
2294
+ /**
2096
2295
  * Answer one decoded request with Git data.
2097
2296
  * @param body - the decoded body `{ sessionId, action, params }`.
2098
2297
  * @param signal - cancellation of the whole request.
@@ -2201,6 +2400,13 @@ function apply(ctx) {
2201
2400
  });
2202
2401
  case "action": {
2203
2402
  const operation = requiredString(fields.operation, "params.operation");
2403
+ if (operation === "switchWorktree") return await switchWorktree({
2404
+ sessionId,
2405
+ cwd,
2406
+ params: fields,
2407
+ exec,
2408
+ signal
2409
+ });
2204
2410
  if (!OPERATIONS.includes(operation)) throw new RequestError("INVALID_REQUEST", `unknown operation "${operation}"`);
2205
2411
  return await gitAction({
2206
2412
  exec,