@cjhyy/code-shell-core 0.6.0-rc.14 → 0.6.0-rc.15

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.
Files changed (81) hide show
  1. package/dist/capability-control/service.d.ts +2 -0
  2. package/dist/capability-control/service.js +4 -2
  3. package/dist/cc-orchestrator/codex-session-history.js +1 -1
  4. package/dist/cc-orchestrator/external-agent-bindings.js +1 -1
  5. package/dist/cc-orchestrator/external-agent-session-store.js +3 -1
  6. package/dist/cc-orchestrator/session-history.js +2 -2
  7. package/dist/cli/agent-server-stdio.js +7 -2
  8. package/dist/context/manager.d.ts +11 -2
  9. package/dist/context/manager.js +64 -3
  10. package/dist/credentials/inject-credential-tool.d.ts +3 -1
  11. package/dist/credentials/inject-credential-tool.js +29 -10
  12. package/dist/credentials/use-credential-tool.d.ts +1 -0
  13. package/dist/credentials/use-credential-tool.js +3 -0
  14. package/dist/engine/engine.d.ts +9 -0
  15. package/dist/engine/engine.js +96 -17
  16. package/dist/engine/turn-loop.d.ts +3 -1
  17. package/dist/engine/turn-loop.js +3 -1
  18. package/dist/engine/types.d.ts +8 -0
  19. package/dist/git/worktree/crud.d.ts +69 -0
  20. package/dist/git/worktree/crud.js +206 -0
  21. package/dist/git/worktree/diff.d.ts +14 -0
  22. package/dist/git/worktree/diff.js +82 -0
  23. package/dist/git/worktree/git-exec.d.ts +7 -0
  24. package/dist/git/worktree/git-exec.js +51 -0
  25. package/dist/git/worktree/index.d.ts +5 -0
  26. package/dist/git/worktree/index.js +5 -0
  27. package/dist/git/worktree/query.d.ts +42 -0
  28. package/dist/git/worktree/query.js +121 -0
  29. package/dist/git/worktree/slug.d.ts +11 -0
  30. package/dist/git/worktree/slug.js +58 -0
  31. package/dist/git/worktree.d.ts +1 -127
  32. package/dist/git/worktree.js +5 -464
  33. package/dist/index.d.ts +28 -27
  34. package/dist/index.js +24 -24
  35. package/dist/plugins/installer/checkUpdate.d.ts +4 -1
  36. package/dist/plugins/installer/checkUpdate.js +4 -2
  37. package/dist/plugins/installer/install.js +2 -0
  38. package/dist/plugins/installer/parseSource.d.ts +4 -1
  39. package/dist/plugins/installer/parseSource.js +28 -10
  40. package/dist/plugins/installer/update.d.ts +4 -1
  41. package/dist/plugins/installer/update.js +5 -3
  42. package/dist/plugins/parseMarketplaceInput.d.ts +4 -1
  43. package/dist/plugins/parseMarketplaceInput.js +4 -3
  44. package/dist/preset/index.d.ts +1 -0
  45. package/dist/preset/index.js +6 -0
  46. package/dist/prompt/sections/base.md +1 -1
  47. package/dist/protocol/chat-session-manager.js +7 -0
  48. package/dist/protocol/server.d.ts +10 -0
  49. package/dist/protocol/server.js +88 -4
  50. package/dist/protocol/types.d.ts +6 -0
  51. package/dist/protocol/types.js +2 -0
  52. package/dist/runtime/background-shell.js +2 -3
  53. package/dist/services/auto-dream.d.ts +15 -4
  54. package/dist/services/auto-dream.js +20 -20
  55. package/dist/services/dream-consolidation.d.ts +2 -3
  56. package/dist/services/dream-consolidation.js +65 -15
  57. package/dist/services/extract-memories.d.ts +14 -5
  58. package/dist/services/extract-memories.js +20 -3
  59. package/dist/services/global-dream-promotion.d.ts +23 -0
  60. package/dist/services/global-dream-promotion.js +112 -0
  61. package/dist/services/memory-orchestrator.js +347 -34
  62. package/dist/session/memory.d.ts +56 -17
  63. package/dist/session/memory.js +337 -78
  64. package/dist/session/session-manager.d.ts +1 -1
  65. package/dist/session/session-manager.js +6 -6
  66. package/dist/settings/manager.js +43 -12
  67. package/dist/settings/schema.d.ts +21 -0
  68. package/dist/settings/schema.js +12 -0
  69. package/dist/tool-system/builtin/index.js +18 -8
  70. package/dist/tool-system/builtin/memory.js +40 -8
  71. package/dist/tool-system/builtin/worktree.d.ts +2 -0
  72. package/dist/tool-system/builtin/worktree.js +59 -11
  73. package/dist/tool-system/context.d.ts +11 -1
  74. package/dist/tool-system/mcp-manager.d.ts +8 -5
  75. package/dist/tool-system/mcp-manager.js +85 -55
  76. package/dist/tool-system/path-policy.d.ts +2 -0
  77. package/dist/tool-system/path-policy.js +28 -12
  78. package/dist/tool-system/workspace-bridge.d.ts +11 -0
  79. package/dist/tool-system/workspace-bridge.js +1 -0
  80. package/dist/types.d.ts +14 -0
  81. package/package.json +1 -1
@@ -0,0 +1,58 @@
1
+ export const DEFAULT_WORKTREE_BRANCH_PREFIX = "worktree/";
2
+ export const HISTORICAL_WORKTREE_BRANCH_PREFIX = "worktree/";
3
+ /**
4
+ * Validate worktree slug to prevent path traversal attacks.
5
+ */
6
+ export function validateWorktreeSlug(slug) {
7
+ if (slug.trim().length === 0)
8
+ throw new Error("Worktree slug cannot be empty");
9
+ if (slug.length > 64)
10
+ throw new Error("Worktree slug too long (max 64 chars)");
11
+ if (/[^a-zA-Z0-9._-]/.test(slug))
12
+ throw new Error("Worktree slug contains invalid characters");
13
+ if (slug.startsWith(".") || slug.includes(".."))
14
+ throw new Error("Worktree slug cannot start with '.' or contain '..'");
15
+ }
16
+ export function normalizeWorktreeBranchPrefix(prefix = DEFAULT_WORKTREE_BRANCH_PREFIX) {
17
+ const raw = (prefix ?? DEFAULT_WORKTREE_BRANCH_PREFIX).trim();
18
+ if (!isValidWorktreeBranchPrefix(raw)) {
19
+ throw new Error(`Invalid worktree branch prefix: ${prefix ?? ""}`);
20
+ }
21
+ return raw.endsWith("/") ? raw : `${raw}/`;
22
+ }
23
+ export function isValidWorktreeBranchPrefix(prefix) {
24
+ const raw = prefix.trim();
25
+ if (!raw)
26
+ return false;
27
+ if (raw.startsWith("/") || raw.includes("//"))
28
+ return false;
29
+ if (raw.includes("..") || raw.includes("@{"))
30
+ return false;
31
+ if (/[\x00-\x20~^:?*[\]\\]/.test(raw))
32
+ return false;
33
+ const withoutTrailingSlash = raw.endsWith("/") ? raw.slice(0, -1) : raw;
34
+ if (!withoutTrailingSlash)
35
+ return false;
36
+ return withoutTrailingSlash.split("/").every((part) => {
37
+ if (!part)
38
+ return false;
39
+ if (part.startsWith(".") || part.endsWith("."))
40
+ return false;
41
+ if (part.endsWith(".lock"))
42
+ return false;
43
+ return true;
44
+ });
45
+ }
46
+ export function applyPrefix(prefix, slug, sessionId) {
47
+ validateWorktreeSlug(slug);
48
+ return `${normalizeWorktreeBranchPrefix(prefix)}${slug}-${sessionId.slice(0, 8)}`;
49
+ }
50
+ export function managedBranchPrefixes(prefix) {
51
+ const configured = normalizeWorktreeBranchPrefix(prefix);
52
+ return configured === HISTORICAL_WORKTREE_BRANCH_PREFIX
53
+ ? [configured]
54
+ : [configured, HISTORICAL_WORKTREE_BRANCH_PREFIX];
55
+ }
56
+ export function isManagedWorktreeBranch(branch, prefix) {
57
+ return managedBranchPrefixes(prefix).some((candidate) => branch.startsWith(candidate));
58
+ }
@@ -1,127 +1 @@
1
- /**
2
- * Git worktree management — create/remove isolated worktrees for agents.
3
- */
4
- import type { SandboxBackend } from "../tool-system/sandbox/index.js";
5
- import type { SessionWorkspace } from "../types.js";
6
- export interface WorktreeSession {
7
- originalCwd: string;
8
- worktreePath: string;
9
- worktreeName: string;
10
- worktreeBranch: string;
11
- originalBranch?: string;
12
- sessionId: string;
13
- createdAt: number;
14
- }
15
- /** Per-platform setup/cleanup scripts (a project's localEnvironment). */
16
- export interface PlatformScripts {
17
- default?: string;
18
- macos?: string;
19
- linux?: string;
20
- windows?: string;
21
- }
22
- /**
23
- * Pick the setup/cleanup script for the running platform, falling back to
24
- * `default`. Empty/whitespace-only scripts are treated as absent so a project
25
- * can leave a platform key blank without spawning an empty shell. `platform`
26
- * defaults to `process.platform` so callers usually omit it; tests pass a
27
- * fixed value.
28
- */
29
- export declare function selectPlatformScript(scripts: PlatformScripts | undefined, platform?: NodeJS.Platform): string | undefined;
30
- /**
31
- * Validate worktree slug to prevent path traversal attacks.
32
- */
33
- export declare function validateWorktreeSlug(slug: string): void;
34
- /**
35
- * Find the canonical git root (resolves worktree → main repo).
36
- */
37
- export declare function findGitRoot(cwd: string): string;
38
- export declare function findMainWorktreeRoot(cwd: string): string;
39
- export declare function findWorktreeForBranch(cwd: string, branch: string): string | undefined;
40
- export declare function assertBranchNotCheckedOut(cwd: string, branch: string): void;
41
- export declare function branchExists(cwd: string, branch: string): boolean;
42
- export declare function isGitWorktreeRoot(cwd: string): boolean;
43
- export declare function currentBranch(cwd: string): string | undefined;
44
- /**
45
- * Create an isolated git worktree for an agent session.
46
- */
47
- export declare function createWorktree(cwd: string, slug: string, sessionId: string): WorktreeSession;
48
- export interface WorktreeSetupResult {
49
- /** True if no setup script was configured for this platform (nothing ran). */
50
- skipped: boolean;
51
- /** True if a script ran and exited 0. */
52
- ok: boolean;
53
- /** Combined stdout/stderr, for surfacing to the user on failure. */
54
- output: string;
55
- /** Exit code when a script ran; undefined when skipped. */
56
- exitCode?: number | null;
57
- }
58
- /**
59
- * Run a project's `localEnvironment.setupScripts` once, in the freshly-created
60
- * worktree's root, right after `git worktree add`. This mirrors Codex's
61
- * local-environment semantics: setup belongs to the *worktree* lifecycle, not
62
- * the conversation — it runs when the isolated copy is born so e.g. `bun
63
- * install` or `cp .env.example .env` happens before the agent works there.
64
- *
65
- * Failure is non-fatal by design (Beta decision 2026-06-08, "警告但继续"): a
66
- * broken setup script shouldn't strand the agent outside a worktree it already
67
- * created. The caller surfaces `output` as a warning and proceeds. cleanup
68
- * scripts are intentionally NOT auto-run on exit (same decision).
69
- *
70
- * Reuses the same sandbox + env primitives as the Bash tool so the setup
71
- * command sees the project's `localEnvironment.env` and runs under the same
72
- * isolation the agent's later commands will.
73
- */
74
- export declare function runWorktreeSetup(worktreePath: string, script: string | undefined, opts?: {
75
- sandbox?: SandboxBackend;
76
- shellEnv?: Record<string, string>;
77
- timeoutMs?: number;
78
- signal?: AbortSignal;
79
- }): Promise<WorktreeSetupResult>;
80
- export interface RemoveWorktreeResult {
81
- /** True once `git worktree remove` completed and the directory is gone. */
82
- dirRemoved: boolean;
83
- /** The branch targeted for deletion when removeBranch=true. */
84
- branch?: string;
85
- /** True when removeBranch=true and branch deletion completed. */
86
- branchDeleted?: boolean;
87
- /** Non-empty when the worktree directory is gone but branch deletion failed. */
88
- branchError?: string;
89
- }
90
- /**
91
- * Remove a worktree and optionally its branch.
92
- */
93
- export declare function removeWorktree(worktreePath: string, removeBranch?: boolean): RemoveWorktreeResult;
94
- export declare function worktreeHasUncommittedChanges(worktreePath: string): boolean;
95
- export declare function worktreeHasUncommittedOrAheadChanges(worktreePath: string, baseRef?: string): boolean;
96
- export interface WorktreeDiffSummary {
97
- /** Best-effort base used for the branch comparison, usually main/master. */
98
- baseRef?: string;
99
- /** Unique files changed either by commits ahead of base or by uncommitted changes. */
100
- changedFiles: number;
101
- /** Commits reachable from HEAD but not from baseRef. */
102
- aheadCommits: number;
103
- /** True when `git status --porcelain` reports local changes. */
104
- hasUncommittedChanges: boolean;
105
- }
106
- export interface WorktreeWorkspaceOwner {
107
- sessionId: string;
108
- workspace?: SessionWorkspace;
109
- }
110
- export interface ListWorktreesOptions {
111
- includeDiffSummary?: boolean;
112
- currentSessionId?: string;
113
- workspaceOwners?: WorktreeWorkspaceOwner[];
114
- }
115
- export interface WorktreeInfo {
116
- path: string;
117
- branch: string;
118
- head: string;
119
- isMain?: boolean;
120
- diff?: WorktreeDiffSummary;
121
- occupiedBySessionIds?: string[];
122
- occupiedByOtherSession?: boolean;
123
- }
124
- /**
125
- * List active worktrees.
126
- */
127
- export declare function listWorktrees(cwd: string, opts?: ListWorktreesOptions): WorktreeInfo[];
1
+ export * from "./worktree/index.js";
@@ -1,464 +1,5 @@
1
- /**
2
- * Git worktree management create/remove isolated worktrees for agents.
3
- */
4
- import { execFileSync } from "node:child_process";
5
- import { existsSync, symlinkSync, lstatSync } from "node:fs";
6
- import { join, resolve, dirname } from "node:path";
7
- import { safeSpawnShell } from "../runtime/safe-spawn.js";
8
- import { buildSandboxEnv, mergeShellEnv, defaultShellBinary } from "../runtime/spawn-common.js";
9
- import { resolveExecutable } from "../utils/exec.js";
10
- // git resolved via PATH×PATHEXT on Windows (.cmd/.exe shim); no-op on POSIX.
11
- const GIT_BIN = resolveExecutable("git");
12
- /**
13
- * Pick the setup/cleanup script for the running platform, falling back to
14
- * `default`. Empty/whitespace-only scripts are treated as absent so a project
15
- * can leave a platform key blank without spawning an empty shell. `platform`
16
- * defaults to `process.platform` so callers usually omit it; tests pass a
17
- * fixed value.
18
- */
19
- export function selectPlatformScript(scripts, platform = process.platform) {
20
- if (!scripts)
21
- return undefined;
22
- const key = platform === "darwin" ? "macos" : platform === "win32" ? "windows" : "linux";
23
- // A blank platform key shouldn't shadow a real `default` — fall through.
24
- const platformScript = scripts[key]?.trim() ? scripts[key] : undefined;
25
- const candidate = platformScript ?? scripts.default;
26
- const trimmed = candidate?.trim();
27
- return trimmed ? candidate : undefined;
28
- }
29
- /**
30
- * Validate worktree slug to prevent path traversal attacks.
31
- */
32
- export function validateWorktreeSlug(slug) {
33
- if (slug.trim().length === 0)
34
- throw new Error("Worktree slug cannot be empty");
35
- if (slug.length > 64)
36
- throw new Error("Worktree slug too long (max 64 chars)");
37
- if (/[^a-zA-Z0-9._-]/.test(slug))
38
- throw new Error("Worktree slug contains invalid characters");
39
- if (slug.startsWith(".") || slug.includes(".."))
40
- throw new Error("Worktree slug cannot start with '.' or contain '..'");
41
- }
42
- /**
43
- * Find the canonical git root (resolves worktree → main repo).
44
- */
45
- export function findGitRoot(cwd) {
46
- return findMainWorktreeRoot(cwd);
47
- }
48
- export function findMainWorktreeRoot(cwd) {
49
- const commonDir = execFileSync(GIT_BIN, ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
50
- cwd,
51
- encoding: "utf-8",
52
- timeout: 5000,
53
- }).trim();
54
- return dirname(commonDir);
55
- }
56
- export function findWorktreeForBranch(cwd, branch) {
57
- const normalized = normalizeBranchName(branch);
58
- return listWorktrees(cwd).find((entry) => entry.branch === normalized)?.path;
59
- }
60
- export function assertBranchNotCheckedOut(cwd, branch) {
61
- const existingPath = findWorktreeForBranch(cwd, branch);
62
- if (existingPath) {
63
- throw new Error(`branch ${normalizeBranchName(branch)} already checked out at ${existingPath}`);
64
- }
65
- }
66
- export function branchExists(cwd, branch) {
67
- try {
68
- return (execFileSync(GIT_BIN, ["branch", "--list", normalizeBranchName(branch)], {
69
- cwd,
70
- encoding: "utf-8",
71
- timeout: 10000,
72
- }).trim().length > 0);
73
- }
74
- catch {
75
- return false;
76
- }
77
- }
78
- export function isGitWorktreeRoot(cwd) {
79
- if (!existsSync(join(cwd, ".git")))
80
- return false;
81
- try {
82
- const inside = execFileSync(GIT_BIN, ["rev-parse", "--is-inside-work-tree"], {
83
- cwd,
84
- encoding: "utf-8",
85
- timeout: 5000,
86
- }).trim();
87
- if (inside !== "true")
88
- return false;
89
- const topLevel = execFileSync(GIT_BIN, ["rev-parse", "--path-format=absolute", "--show-toplevel"], {
90
- cwd,
91
- encoding: "utf-8",
92
- timeout: 5000,
93
- }).trim();
94
- return resolve(topLevel) === resolve(cwd);
95
- }
96
- catch {
97
- return false;
98
- }
99
- }
100
- export function currentBranch(cwd) {
101
- try {
102
- const branch = execFileSync(GIT_BIN, ["branch", "--show-current"], {
103
- cwd,
104
- encoding: "utf-8",
105
- timeout: 5000,
106
- }).trim();
107
- return branch || undefined;
108
- }
109
- catch {
110
- return undefined;
111
- }
112
- }
113
- /**
114
- * Create an isolated git worktree for an agent session.
115
- */
116
- export function createWorktree(cwd, slug, sessionId) {
117
- validateWorktreeSlug(slug);
118
- const gitRoot = findGitRoot(cwd);
119
- const branchName = `worktree/${slug}-${sessionId.slice(0, 8)}`;
120
- const worktreePath = resolve(gitRoot, "..", `.worktrees/${slug}-${sessionId.slice(0, 8)}`);
121
- assertBranchNotCheckedOut(gitRoot, branchName);
122
- // Get current branch for later reference
123
- let originalBranch;
124
- try {
125
- originalBranch = execFileSync(GIT_BIN, ["branch", "--show-current"], {
126
- cwd: gitRoot,
127
- encoding: "utf-8",
128
- timeout: 5000,
129
- }).trim();
130
- }
131
- catch {
132
- // Detached HEAD
133
- }
134
- // Create the worktree. Pre-fix this used a quoted command string; the argv
135
- // form keeps branchName/worktreePath as literal positional arguments even
136
- // if a future caller bypasses validateWorktreeSlug.
137
- execFileSync(GIT_BIN, ["worktree", "add", "-b", branchName, worktreePath], {
138
- cwd: gitRoot,
139
- timeout: 30000,
140
- });
141
- // Symlink large directories to avoid disk bloat
142
- symlinkLargeDirectories(gitRoot, worktreePath);
143
- return {
144
- originalCwd: cwd,
145
- worktreePath,
146
- worktreeName: slug,
147
- worktreeBranch: branchName,
148
- originalBranch,
149
- sessionId,
150
- createdAt: Date.now(),
151
- };
152
- }
153
- /**
154
- * Run a project's `localEnvironment.setupScripts` once, in the freshly-created
155
- * worktree's root, right after `git worktree add`. This mirrors Codex's
156
- * local-environment semantics: setup belongs to the *worktree* lifecycle, not
157
- * the conversation — it runs when the isolated copy is born so e.g. `bun
158
- * install` or `cp .env.example .env` happens before the agent works there.
159
- *
160
- * Failure is non-fatal by design (Beta decision 2026-06-08, "警告但继续"): a
161
- * broken setup script shouldn't strand the agent outside a worktree it already
162
- * created. The caller surfaces `output` as a warning and proceeds. cleanup
163
- * scripts are intentionally NOT auto-run on exit (same decision).
164
- *
165
- * Reuses the same sandbox + env primitives as the Bash tool so the setup
166
- * command sees the project's `localEnvironment.env` and runs under the same
167
- * isolation the agent's later commands will.
168
- */
169
- export async function runWorktreeSetup(worktreePath, script, opts = {}) {
170
- const trimmed = script?.trim();
171
- if (!trimmed)
172
- return { skipped: true, ok: true, output: "" };
173
- const shell = defaultShellBinary();
174
- const backend = opts.sandbox;
175
- const baseEnv = backend && backend.name !== "off" ? buildSandboxEnv() : { ...process.env };
176
- const env = mergeShellEnv(baseEnv, opts.shellEnv);
177
- const result = await safeSpawnShell(trimmed, {
178
- cwd: worktreePath,
179
- env,
180
- timeoutMs: opts.timeoutMs ?? 120_000,
181
- maxOutputBytes: 1024 * 1024,
182
- sandbox: backend,
183
- shell,
184
- signal: opts.signal,
185
- });
186
- const parts = [];
187
- if (result.stdout)
188
- parts.push(result.stdout);
189
- if (result.stderr)
190
- parts.push(result.stderr);
191
- const output = parts.join("\n").trim();
192
- if (result.aborted)
193
- return { skipped: false, ok: false, output: output || "setup aborted" };
194
- if (result.timedOut)
195
- return { skipped: false, ok: false, output: output || "setup timed out" };
196
- if (result.spawnFailed) {
197
- return { skipped: false, ok: false, output: result.error ?? "failed to spawn setup script" };
198
- }
199
- return { skipped: false, ok: result.exitCode === 0, output, exitCode: result.exitCode };
200
- }
201
- /**
202
- * Remove a worktree and optionally its branch.
203
- */
204
- export function removeWorktree(worktreePath, removeBranch = false) {
205
- // The MAIN repo root, not the worktree's own toplevel. `git rev-parse
206
- // --show-toplevel` from inside a worktree returns the worktree path, which
207
- // is about to be deleted; the branch-delete must run from the main repo,
208
- // which outlives the worktree. Derive it from the common git dir.
209
- let mainRoot;
210
- try {
211
- const commonDir = execFileSync(GIT_BIN, ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: worktreePath, encoding: "utf-8", timeout: 5000 }).trim();
212
- mainRoot = dirname(commonDir); // <main>/.git → <main>
213
- }
214
- catch (err) {
215
- throw new Error(`failed to inspect worktree ${worktreePath}: ${gitErrorMessage(err)}`);
216
- }
217
- // Capture the worktree's branch BEFORE removing the worktree — afterwards
218
- // the directory is gone and `git branch --show-current` in it would fail.
219
- let branch = "";
220
- if (removeBranch) {
221
- try {
222
- branch = execFileSync(GIT_BIN, ["branch", "--show-current"], {
223
- cwd: worktreePath,
224
- encoding: "utf-8",
225
- timeout: 5000,
226
- }).trim();
227
- }
228
- catch (err) {
229
- throw new Error(`failed to determine branch for worktree ${worktreePath}: ${gitErrorMessage(err)}`);
230
- }
231
- if (!branch) {
232
- throw new Error(`failed to determine branch for worktree ${worktreePath}`);
233
- }
234
- if (!branch.startsWith("worktree/")) {
235
- throw new Error(`refusing to delete non-CodeShell worktree branch ${branch}`);
236
- }
237
- }
238
- try {
239
- execFileSync(GIT_BIN, ["worktree", "remove", worktreePath, "--force"], {
240
- cwd: mainRoot,
241
- timeout: 30000,
242
- });
243
- }
244
- catch (err) {
245
- throw new Error(`failed to remove worktree ${worktreePath}: ${gitErrorMessage(err)}`);
246
- }
247
- if (removeBranch) {
248
- try {
249
- execFileSync(GIT_BIN, ["branch", "-D", branch], { cwd: mainRoot, timeout: 10000 });
250
- }
251
- catch (err) {
252
- return {
253
- dirRemoved: true,
254
- branch,
255
- branchDeleted: false,
256
- branchError: gitErrorMessage(err),
257
- };
258
- }
259
- }
260
- return removeBranch ? { dirRemoved: true, branch, branchDeleted: true } : { dirRemoved: true };
261
- }
262
- export function worktreeHasUncommittedChanges(worktreePath) {
263
- try {
264
- return (execFileSync(GIT_BIN, ["status", "--porcelain"], {
265
- cwd: worktreePath,
266
- encoding: "utf-8",
267
- timeout: 10000,
268
- }).trim().length > 0);
269
- }
270
- catch {
271
- return false;
272
- }
273
- }
274
- export function worktreeHasUncommittedOrAheadChanges(worktreePath, baseRef) {
275
- if (worktreeHasUncommittedChanges(worktreePath))
276
- return true;
277
- const comparisonBase = baseRef && commitRefExists(worktreePath, baseRef)
278
- ? baseRef
279
- : findComparisonBaseRef(worktreePath);
280
- return comparisonBase ? aheadCommitCount(worktreePath, comparisonBase) > 0 : false;
281
- }
282
- /**
283
- * List active worktrees.
284
- */
285
- export function listWorktrees(cwd, opts = {}) {
286
- const raw = execFileSync(GIT_BIN, ["worktree", "list", "--porcelain"], {
287
- cwd,
288
- encoding: "utf-8",
289
- timeout: 10000,
290
- }).trim();
291
- if (!raw)
292
- return [];
293
- const entries = [];
294
- let current = { path: "", branch: "", head: "" };
295
- for (const line of raw.split("\n")) {
296
- if (line.startsWith("worktree ")) {
297
- if (current.path)
298
- entries.push(current);
299
- current = { path: line.slice(9), branch: "", head: "" };
300
- }
301
- else if (line.startsWith("HEAD ")) {
302
- current.head = line.slice(5, 13);
303
- }
304
- else if (line.startsWith("branch ")) {
305
- current.branch = line.slice(7).replace("refs/heads/", "");
306
- }
307
- }
308
- if (current.path)
309
- entries.push(current);
310
- if (!opts.includeDiffSummary && !opts.workspaceOwners?.length)
311
- return entries;
312
- let mainRoot = "";
313
- try {
314
- mainRoot = findMainWorktreeRoot(cwd);
315
- }
316
- catch {
317
- mainRoot = entries[0]?.path ?? "";
318
- }
319
- const baseRef = opts.includeDiffSummary ? findComparisonBaseRef(mainRoot || cwd) : undefined;
320
- return entries.map((entry) => {
321
- const owners = ownersForWorktree(entry.path, opts.workspaceOwners ?? []);
322
- return {
323
- ...entry,
324
- ...(mainRoot ? { isMain: resolve(entry.path) === resolve(mainRoot) } : {}),
325
- ...(opts.includeDiffSummary ? { diff: diffSummary(entry.path, baseRef) } : {}),
326
- ...(owners.length > 0
327
- ? {
328
- occupiedBySessionIds: owners,
329
- occupiedByOtherSession: owners.some((id) => id !== opts.currentSessionId),
330
- }
331
- : {}),
332
- };
333
- });
334
- }
335
- function ownersForWorktree(path, owners) {
336
- const target = resolve(path);
337
- return owners
338
- .filter((owner) => {
339
- const workspace = owner.workspace;
340
- if (!workspace)
341
- return false;
342
- return resolve(workspace.root) === target;
343
- })
344
- .map((owner) => owner.sessionId);
345
- }
346
- function findComparisonBaseRef(cwd) {
347
- for (const ref of ["main", "master", "origin/main", "origin/master"]) {
348
- if (commitRefExists(cwd, ref))
349
- return ref;
350
- }
351
- return undefined;
352
- }
353
- function commitRefExists(cwd, ref) {
354
- try {
355
- execFileSync(GIT_BIN, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
356
- cwd,
357
- encoding: "utf-8",
358
- timeout: 5000,
359
- });
360
- return true;
361
- }
362
- catch {
363
- return false;
364
- }
365
- }
366
- function diffSummary(cwd, baseRef) {
367
- const dirtyFiles = statusFileSet(cwd);
368
- const committedFiles = baseRef ? changedFilesSinceBase(cwd, baseRef) : new Set();
369
- const changedFiles = new Set([...dirtyFiles, ...committedFiles]);
370
- return {
371
- ...(baseRef ? { baseRef } : {}),
372
- changedFiles: changedFiles.size,
373
- aheadCommits: baseRef ? aheadCommitCount(cwd, baseRef) : 0,
374
- hasUncommittedChanges: dirtyFiles.size > 0,
375
- };
376
- }
377
- function changedFilesSinceBase(cwd, baseRef) {
378
- const out = gitOutput(cwd, ["diff", "--name-only", `${baseRef}...HEAD`]);
379
- const raw = out ?? gitOutput(cwd, ["diff", "--name-only", `${baseRef}..HEAD`]) ?? "";
380
- return new Set(raw
381
- .split("\n")
382
- .map((line) => line.trim())
383
- .filter(Boolean));
384
- }
385
- function aheadCommitCount(cwd, baseRef) {
386
- const out = gitOutput(cwd, ["rev-list", "--count", `${baseRef}..HEAD`]);
387
- const n = Number.parseInt(out?.trim() ?? "0", 10);
388
- return Number.isFinite(n) ? n : 0;
389
- }
390
- function statusFileSet(cwd) {
391
- const raw = gitOutput(cwd, ["status", "--porcelain=v1"]) ?? "";
392
- const files = new Set();
393
- for (const line of raw.split("\n")) {
394
- if (!line.trim())
395
- continue;
396
- const path = line.slice(3).trim();
397
- if (!path)
398
- continue;
399
- const renameTarget = path.includes(" -> ") ? path.split(" -> ").at(-1) : path;
400
- if (renameTarget)
401
- files.add(unquoteGitPath(renameTarget));
402
- }
403
- return files;
404
- }
405
- function unquoteGitPath(path) {
406
- if (!path.startsWith('"') || !path.endsWith('"'))
407
- return path;
408
- try {
409
- return JSON.parse(path);
410
- }
411
- catch {
412
- return path.slice(1, -1);
413
- }
414
- }
415
- function gitOutput(cwd, args) {
416
- try {
417
- return execFileSync(GIT_BIN, args, {
418
- cwd,
419
- encoding: "utf-8",
420
- timeout: 10000,
421
- });
422
- }
423
- catch {
424
- return undefined;
425
- }
426
- }
427
- function gitErrorMessage(err) {
428
- const stderr = err.stderr;
429
- if (Buffer.isBuffer(stderr)) {
430
- const msg = stderr.toString("utf-8").trim();
431
- if (msg)
432
- return msg;
433
- }
434
- if (typeof stderr === "string" && stderr.trim())
435
- return stderr.trim();
436
- return err instanceof Error ? err.message : String(err);
437
- }
438
- function normalizeBranchName(branch) {
439
- return branch.replace(/^refs\/heads\//, "");
440
- }
441
- /**
442
- * Symlink large directories (node_modules, .venv, etc.) from main repo to worktree.
443
- */
444
- function symlinkLargeDirectories(sourceRoot, worktreePath) {
445
- const largeDirs = ["node_modules", ".venv", "vendor", ".pnpm-store"];
446
- // Windows directory symlinks need admin/Developer Mode and throw EPERM for a
447
- // normal user; NTFS junctions don't and behave the same for our purpose
448
- // (share node_modules into the worktree). Use "junction" on win32, "dir"
449
- // elsewhere. Failure stays non-fatal — the worktree just doesn't share dirs.
450
- const linkType = process.platform === "win32" ? "junction" : "dir";
451
- for (const dir of largeDirs) {
452
- const source = join(sourceRoot, dir);
453
- const target = join(worktreePath, dir);
454
- if (existsSync(source) && lstatSync(source).isDirectory() && !existsSync(target)) {
455
- try {
456
- symlinkSync(source, target, linkType);
457
- }
458
- catch {
459
- // Symlink/junction might fail on some systems — non-fatal, the
460
- // worktree just won't share this directory (more disk, still works).
461
- }
462
- }
463
- }
464
- }
1
+ // Compatibility barrel for the pre-split worktree module. The split made the
2
+ // query/create APIs async because they now share the async git executor; all
3
+ // in-repo callers await them, so this barrel intentionally does not add sync
4
+ // wrappers.
5
+ export * from "./worktree/index.js";