Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(worktree): 同时读取 Claude Code 的 .worktreeinclude (#6011)

Dash57169eb2fa5f
diff --git a/apps/desktop/src/main/__tests__/worktreeIncludePatternsEngine.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeIncludePatternsEngine.git-integration.test.ts
index 07829803be..70720ef621 100644
--- a/apps/desktop/src/main/__tests__/worktreeIncludePatternsEngine.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeIncludePatternsEngine.git-integration.test.ts
@@ -3,20 +3,21 @@
* tracked 分支差异场景使用临时 Git worktree 做真实集成验证。
*/
-import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
import {
+ applyWorktreeIncludeFile,
copyWorktreeIncludeFiles,
listChangedWorktreeIncludeFiles,
parseWorktreeIncludePatterns,
_internal,
} from '../worktree/includePatternsEngine';
-const { globToRegex, listAllFiles } = _internal;
+const { globToRegex, listAllFiles, gitignoreMatcher } = _internal;
function git(cwd: string, ...args: string[]): void {
execFileSync('git', args, { cwd, stdio: 'pipe' });
@@ -95,6 +96,140 @@ describe('globToRegex', () => {
});
});
+describe('gitignoreMatcher (.worktreeinclude)', () => {
+ it('matches a slash-less pattern at any depth', () => {
+ const matches = gitignoreMatcher(['.env']);
+ expect(matches('.env')).toBe(true);
+ expect(matches('apps/web/.env')).toBe(true);
+ expect(matches('.env.local')).toBe(false);
+ });
+
+ it('anchors patterns that contain a slash to the repo root', () => {
+ expect(gitignoreMatcher(['/.env'])('apps/.env')).toBe(false);
+ expect(gitignoreMatcher(['/.env'])('.env')).toBe(true);
+ const matches = gitignoreMatcher(['config/*.json']);
+ expect(matches('config/local.json')).toBe(true);
+ expect(matches('apps/config/local.json')).toBe(false);
+ });
+
+ it('selects every file under a matched directory', () => {
+ const dirOnly = gitignoreMatcher(['.vscode/']);
+ expect(dirOnly('.vscode/settings.json')).toBe(true);
+ expect(dirOnly('apps/.vscode/a/b.json')).toBe(true);
+ expect(dirOnly('.vscode')).toBe(false);
+ expect(gitignoreMatcher(['secrets'])('secrets/key.pem')).toBe(true);
+ });
+
+ it('lets a later negation override an earlier match', () => {
+ const matches = gitignoreMatcher(['.env*', '!.env.example']);
+ expect(matches('.env.local')).toBe(true);
+ expect(matches('.env.example')).toBe(false);
+ expect(gitignoreMatcher(['!.env.example', '.env*'])('.env.example')).toBe(true);
+ });
+
+ it('treats a lone /** as everything under the repo root', () => {
+ const matches = gitignoreMatcher(['/**', '!*.log']);
+ expect(matches('.env')).toBe(true);
+ expect(matches('apps/web/.env')).toBe(true);
+ expect(matches('apps/debug.log')).toBe(false);
+ });
+
+ it('only lets a whole-segment ** cross directories', () => {
+ const embedded = gitignoreMatcher(['secret**.json']);
+ expect(embedded('secret-a.json')).toBe(true);
+ expect(embedded('apps/secret-a.json')).toBe(true);
+ expect(embedded('secret/private/key.json')).toBe(false);
+ const middle = gitignoreMatcher(['a/**/b.txt']);
+ expect(middle('a/b.txt')).toBe(true);
+ expect(middle('a/x/y/b.txt')).toBe(true);
+ expect(middle('c/a/b.txt')).toBe(false);
+ const leading = gitignoreMatcher(['**/local/*.json']);
+ expect(leading('local/a.json')).toBe(true);
+ expect(leading('apps/web/local/a.json')).toBe(true);
+ expect(leading('apps/web/local/x/a.json')).toBe(false);
+ });
+
+ it('selects only directory contents for a trailing /**', () => {
+ const matches = gitignoreMatcher(['config/**']);
+ expect(matches('config/local.json')).toBe(true);
+ expect(matches('config/a/b.json')).toBe(true);
+ expect(matches('config')).toBe(false);
+ expect(matches('apps/config/local.json')).toBe(false);
+ });
+});
+
+describe('applyWorktreeIncludeFile', () => {
+ let tmpRoot: string;
+ let baseRepo: string;
+ let worktreePath: string;
+
+ beforeEach(() => {
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-include-apply-'));
+ baseRepo = path.join(tmpRoot, 'repo');
+ worktreePath = path.join(tmpRoot, 'worktree');
+ fs.mkdirSync(path.join(baseRepo, 'apps', 'web'), { recursive: true });
+ fs.mkdirSync(worktreePath, { recursive: true });
+ fs.writeFileSync(path.join(baseRepo, '.env'), 'ROOT=1\n');
+ fs.writeFileSync(path.join(baseRepo, 'apps', 'web', '.env'), 'WEB=1\n');
+ fs.writeFileSync(path.join(baseRepo, 'local.json'), '{}');
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ const copied = async () =>
+ (await applyWorktreeIncludeFile(baseRepo, worktreePath))
+ .filter((r) => r.status === 'copied')
+ .map((r) => r.relpath)
+ .sort();
+
+ it('reads Claude Code .worktreeinclude with .gitignore semantics', async () => {
+ fs.writeFileSync(path.join(baseRepo, '.worktreeinclude'), '.env\n');
+
+ await expect(copied()).resolves.toEqual(['.env', 'apps/web/.env']);
+ expect(fs.readFileSync(path.join(worktreePath, 'apps', 'web', '.env'), 'utf8')).toBe('WEB=1\n');
+ });
+
+ it('keeps repeated .worktreeinclude rules so a later rule re-includes a file', async () => {
+ fs.writeFileSync(path.join(baseRepo, '.worktreeinclude'), '/.env\n!/.env\n/.env\n');
+
+ await expect(copied()).resolves.toEqual(['.env']);
+ });
+
+ it('keeps .xdtworktreeinclude root-relative and merges both files', async () => {
+ fs.writeFileSync(path.join(baseRepo, '.xdtworktreeinclude'), '.env\n');
+ await expect(copied()).resolves.toEqual(['.env']);
+
+ fs.writeFileSync(path.join(baseRepo, '.worktreeinclude'), 'local.json\n');
+ await expect(copied()).resolves.toEqual(['.env', 'local.json']);
+ });
+
+ it('does not write through a symlinked directory that leads outside the worktree', async () => {
+ const outside = path.join(tmpRoot, 'outside');
+ fs.mkdirSync(outside);
+ fs.mkdirSync(path.join(baseRepo, 'config'));
+ fs.writeFileSync(path.join(baseRepo, 'config', 'local.env'), 'SECRET=1\n');
+ fs.symlinkSync(outside, path.join(worktreePath, 'config'), 'junction');
+ fs.writeFileSync(path.join(baseRepo, '.worktreeinclude'), 'config/**\n');
+
+ await expect(applyWorktreeIncludeFile(baseRepo, worktreePath)).resolves.toEqual([
+ { relpath: 'config/local.env', status: 'skipped-outside' },
+ ]);
+ expect(fs.existsSync(path.join(outside, 'local.env'))).toBe(false);
+ });
+
+ it('reports files changed under .worktreeinclude rules as dirty', async () => {
+ fs.writeFileSync(path.join(baseRepo, '.worktreeinclude'), '.env\n');
+ await applyWorktreeIncludeFile(baseRepo, worktreePath);
+ fs.writeFileSync(path.join(worktreePath, 'apps', 'web', '.env'), 'WEB=2\n');
+
+ await expect(listChangedWorktreeIncludeFiles(baseRepo, worktreePath)).resolves.toEqual([
+ { relpath: 'apps/web/.env', reason: 'content-differs' },
+ ]);
+ });
+});
+
describe('listAllFiles', () => {
let tmpRoot: string;
@@ -207,6 +342,111 @@ describe('listChangedWorktreeIncludeFiles', () => {
});
});
+describe('include files tracked on the worktree branch', () => {
+ it('neither overwrites nor reports a file the target branch already tracks', async () => {
+ const gitRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-include-branch-'));
+ const repo = path.join(gitRoot, 'repo');
+ const worktree = path.join(gitRoot, 'worktree');
+ fs.mkdirSync(repo, { recursive: true });
+ try {
+ git(repo, 'init');
+ git(repo, 'config', 'user.name', 'XDMaker Test');
+ git(repo, 'config', 'user.email', '[email protected]');
+ fs.writeFileSync(path.join(repo, '.worktreeinclude'), 'local.json\n');
+ git(repo, 'add', '.worktreeinclude');
+ git(repo, 'commit', '-m', 'init');
+ git(repo, 'branch', 'feature');
+ git(repo, 'worktree', 'add', worktree, 'feature');
+ fs.writeFileSync(path.join(worktree, 'local.json'), '{"branch":true}');
+ git(worktree, 'add', 'local.json');
+ git(worktree, 'commit', '-m', 'track local.json on feature');
+ fs.writeFileSync(path.join(repo, 'local.json'), '{"base":true}');
+
+ await expect(applyWorktreeIncludeFile(repo, worktree)).resolves.toEqual([
+ { relpath: 'local.json', status: 'skipped-tracked' },
+ ]);
+ expect(fs.readFileSync(path.join(worktree, 'local.json'), 'utf8')).toBe('{"branch":true}');
+ await expect(listChangedWorktreeIncludeFiles(repo, worktree)).resolves.toEqual([]);
+ } finally {
+ fs.rmSync(gitRoot, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('include files under a path the target branch tracks', () => {
+ it('skips files beneath a tracked symlink before checkout has written it', async () => {
+ const gitRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-include-link-'));
+ const repo = path.join(gitRoot, 'repo');
+ const worktree = path.join(gitRoot, 'worktree');
+ fs.mkdirSync(repo, { recursive: true });
+ try {
+ git(repo, 'init');
+ git(repo, 'config', 'user.name', 'XDMaker Test');
+ git(repo, 'config', 'user.email', '[email protected]');
+ fs.writeFileSync(path.join(repo, '.worktreeinclude'), 'config/**\n');
+ git(repo, 'add', '.worktreeinclude');
+ git(repo, 'commit', '-m', 'init');
+ // feature 分支以 120000 模式跟踪符号链接 config; 用底层命令建提交, 不切分支、
+ // 不依赖平台能否创建链接。
+ const run = (args: string[], input?: string, env?: NodeJS.ProcessEnv): string =>
+ execFileSync('git', args, { cwd: repo, input, env: { ...process.env, ...env } })
+ .toString()
+ .trim();
+ const indexEnv = { GIT_INDEX_FILE: path.join(gitRoot, 'feature.index') };
+ const blob = run(['hash-object', '-w', '--stdin'], '../outside');
+ run(['read-tree', 'HEAD'], undefined, indexEnv);
+ run(['update-index', '--add', '--cacheinfo', `120000,${blob},config`], undefined, indexEnv);
+ const tree = run(['write-tree'], undefined, indexEnv);
+ const commit = run(['commit-tree', tree, '-p', 'HEAD', '-m', 'track config as a symlink']);
+ git(repo, 'branch', 'feature', commit);
+ fs.mkdirSync(path.join(repo, 'config'));
+ fs.writeFileSync(path.join(repo, 'config', 'local.env'), 'A=1\n');
+ git(repo, 'worktree', 'add', '--no-checkout', worktree, 'feature');
+
+ await expect(applyWorktreeIncludeFile(repo, worktree)).resolves.toEqual([
+ { relpath: 'config/local.env', status: 'skipped-tracked' },
+ ]);
+ expect(fs.existsSync(path.join(worktree, 'config'))).toBe(false);
+ } finally {
+ fs.rmSync(gitRoot, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('include files that are an ancestor of a path the target branch tracks', () => {
+ it('skips a file whose name the target branch needs as a directory', async () => {
+ const gitRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-include-ancestor-'));
+ const repo = path.join(gitRoot, 'repo');
+ const worktree = path.join(gitRoot, 'worktree');
+ fs.mkdirSync(repo, { recursive: true });
+ try {
+ git(repo, 'init');
+ git(repo, 'config', 'user.name', 'XDMaker Test');
+ git(repo, 'config', 'user.email', '[email protected]');
+ fs.writeFileSync(path.join(repo, '.worktreeinclude'), '/config\n');
+ git(repo, 'add', '.worktreeinclude');
+ git(repo, 'commit', '-m', 'init');
+ git(repo, 'branch', 'feature');
+ git(repo, 'worktree', 'add', worktree, 'feature');
+ fs.mkdirSync(path.join(worktree, 'config'));
+ fs.writeFileSync(path.join(worktree, 'config', 'settings.json'), '{}');
+ git(worktree, 'add', 'config/settings.json');
+ git(worktree, 'commit', '-m', 'track config/settings.json');
+ git(repo, 'worktree', 'remove', '--force', worktree);
+ // base 里同名的 config 是未跟踪的普通文件; 目标分支需要 config 作为目录
+ fs.writeFileSync(path.join(repo, 'config'), 'LOCAL=1\n');
+ git(repo, 'worktree', 'add', '--no-checkout', worktree, 'feature');
+
+ await expect(applyWorktreeIncludeFile(repo, worktree)).resolves.toEqual([
+ { relpath: 'config', status: 'skipped-tracked' },
+ ]);
+ expect(fs.existsSync(path.join(worktree, 'config'))).toBe(false);
+ } finally {
+ fs.rmSync(gitRoot, { recursive: true, force: true });
+ }
+ });
+});
+
describe('copyWorktreeIncludeFiles restore mode', () => {
let tmpRoot: string;
let baseRepo: string;
diff --git a/apps/desktop/src/main/worktree/WorktreePool.ts b/apps/desktop/src/main/worktree/WorktreePool.ts
index 5e0d726b88..baaf41cfbf 100644
--- a/apps/desktop/src/main/worktree/WorktreePool.ts
+++ b/apps/desktop/src/main/worktree/WorktreePool.ts
@@ -235,7 +235,7 @@ async function resetWorktree(
// 5. 重新拷贝 .claude/.sivi(被 git clean 删掉了,池化路径跳过 stageCheckout 所以必须成功)
await copyClaudeSiviDirs(baseRepo, worktreePath);
- // 6. 重新拷贝 .xdtworktreeinclude 文件
+ // 6. 重新拷贝 .xdtworktreeinclude / .worktreeinclude 选中的文件
try {
await applyWorktreeIncludeFile(baseRepo, worktreePath);
} catch (err) {
diff --git a/apps/desktop/src/main/worktree/dirty.ts b/apps/desktop/src/main/worktree/dirty.ts
index f18c25df21..f35a6e0277 100644
--- a/apps/desktop/src/main/worktree/dirty.ts
+++ b/apps/desktop/src/main/worktree/dirty.ts
@@ -62,7 +62,7 @@ async function hasEquivalentFileAtBase(
* 列出 worktree 中 Git 忽略、且 base checkout 没有同路径同内容副本的文件。
*
* `git status --porcelain` 与非强制 `git worktree remove` 都不会保护 ignored 文件;
- * 预创建补偿回收必须显式探测。`.xdtworktreeinclude` 从 base 复制来的未变化 `.env`
+ * 预创建补偿回收必须显式探测。worktree include 文件从 base 复制来的未变化 `.env`
* 仍可安全回收,因为 base 中保留着逐字节等价副本;独有或已变化的 ignored 内容
* 一律返回给调用方保留整个 worktree。Git/文件读取失败会抛出,由调用方 fail closed。
*/
diff --git a/apps/desktop/src/main/worktree/includePatternsEngine.ts b/apps/desktop/src/main/worktree/includePatternsEngine.ts
index aa82833902..a2f507580a 100644
--- a/apps/desktop/src/main/worktree/includePatternsEngine.ts
+++ b/apps/desktop/src/main/worktree/includePatternsEngine.ts
@@ -1,9 +1,11 @@
/**
- * worktree-parallel-sessions: `.xdtworktreeinclude` 解析与拷贝引擎。
+ * worktree-parallel-sessions: worktree include 文件解析与拷贝引擎。
*
- * 文件位于 baseRepo 根目录, 内容是按行的 glob pattern。worktree 创建后, 把匹配
- * 的(且 git 不跟踪的)文件按相对路径复制到 worktree 路径下, 用于带过去
- * .env / 本地 build 产物 / IDE 配置等不入库的本地文件。
+ * 两个文件都位于 baseRepo 根目录, 规则合并生效(任一文件选中即复制):
+ * - `.xdtworktreeinclude`: Cindy 原有格式, 每行一个 glob, 相对 baseRepo 根目录
+ * - `.worktreeinclude`: Claude Code 的同名约定, 按 `.gitignore` 语法解析
+ * worktree 创建后, 把匹配的(且 git 不跟踪的)文件按相对路径复制到 worktree 路径下,
+ * 用于带过去 .env / 本地 build 产物 / IDE 配置等不入库的本地文件。
*
* 规则:
* - 每行 trim
@@ -59,19 +61,16 @@ export interface ChangedIncludeFile {
* 该函数不读文件——上层先 read 再传给本函数, 便于测试。
*/
export function parseWorktreeIncludePatterns(content: string): string[] {
+ return [...new Set(includeRuleLines(content))];
+}
+
+/** 去掉空行与 `#` 注释后的规则行, 保留重复与原始顺序(`.gitignore` 语法依赖顺序)。 */
+function includeRuleLines(content: string): string[] {
if (!content) return [];
- const lines = content.split(/\r?\n/);
- const out: string[] = [];
- const seen = new Set<string>();
- for (const raw of lines) {
- const trimmed = raw.trim();
- if (!trimmed) continue;
- if (trimmed.startsWith('#')) continue;
- if (seen.has(trimmed)) continue;
- seen.add(trimmed);
- out.push(trimmed);
- }
- return out;
+ return content
+ .split(/\r?\n/)
+ .map((raw) => raw.trim())
+ .filter((line) => line && !line.startsWith('#'));
}
/**
@@ -116,6 +115,97 @@ function globToRegex(glob: string): RegExp {
return new RegExp(`^${p}$`);
}
+/** 判断 baseRepo 相对路径(/ 分隔)是否被 include 规则选中。 */
+type IncludeMatcher = (relpath: string) => boolean;
+
+function globMatcher(patterns: readonly string[]): IncludeMatcher {
+ const regexes = patterns.map(globToRegex);
+ return (rel) => regexes.some((re) => re.test(rel));
+}
+
+/**
+ * `.gitignore` 语法的 glob → RegExp(与 `.xdtworktreeinclude` 的 globToRegex 分开):
+ * 只有独占一段的 `**` 跨目录(开头或中间的 `**` 段表示 0 或多级目录);
+ * 段内的 `**`(如 `secret**.json`)与 `*` 相同, 不跨 `/`。
+ */
+function gitignoreGlobToRegex(glob: string): RegExp {
+ const segments = glob.split('/');
+ let out = '';
+ segments.forEach((segment, i) => {
+ const last = i === segments.length - 1;
+ if (segment === '**') {
+ out += last ? '.*' : '(?:.*\\/)?';
+ return;
+ }
+ out += segment
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
+ .replace(/\*+/g, '[^/]*')
+ .replaceAll('?', '[^/]');
+ if (!last) out += '\\/';
+ });
+ return new RegExp(`^${out}$`);
+}
+
+/**
+ * 按 `.gitignore` 语法匹配(Claude Code 的 `.worktreeinclude` 约定):
+ * - 不含 `/` 的规则匹配任意层级; 含 `/`(或以 `/` 开头)时相对仓库根目录
+ * - 末尾 `/` 只匹配目录; 选中目录即包含其下全部文件; 末尾 `/**` 只选目录里的内容
+ * - `!` 取反, 后面的规则覆盖前面的(规则须保留重复与原始顺序)
+ * `[...]` 字符类与 `\` 转义不支持, 按字面处理。
+ */
+function gitignoreMatcher(patterns: readonly string[]): IncludeMatcher {
+ const rules: { re: RegExp; negate: boolean; dirOnly: boolean }[] = [];
+ for (const raw of patterns) {
+ const negate = raw.startsWith('!');
+ let p = negate ? raw.slice(1) : raw;
+ // `config/**` 等价于根目录下的 `config/`: 只选目录内容, 不选同名普通文件。
+ const contentsOnly = p.endsWith('/**');
+ if (contentsOnly) p = p.slice(0, -3);
+ const dirOnly = contentsOnly || p.endsWith('/');
+ if (p.endsWith('/')) p = p.slice(0, -1);
+ const anchored = contentsOnly || p.includes('/');
+ if (p.startsWith('/')) p = p.slice(1);
+ if (!p) {
+ // 单独的 `/**` 是仓库根目录里的全部内容。
+ if (contentsOnly) rules.push({ re: /^.+$/, negate, dirOnly: false });
+ continue;
+ }
+ rules.push({ re: gitignoreGlobToRegex(anchored ? p : `**/${p}`), negate, dirOnly });
+ }
+ return (rel) => {
+ const segments = rel.split('/');
+ const dirs = segments.slice(1).map((_, i) => segments.slice(0, i + 1).join('/'));
+ let included = false;
+ for (const rule of rules) {
+ const hit = (!rule.dirOnly && rule.re.test(rel)) || dirs.some((dir) => rule.re.test(dir));
+ if (hit) included = !rule.negate;
+ }
+ return included;
+ };
+}
+
+const INCLUDE_FILES = [
+ { name: '.xdtworktreeinclude', toMatcher: globMatcher },
+ { name: '.worktreeinclude', toMatcher: gitignoreMatcher },
+] as const;
+
+/** 读取 baseRepo 根目录的 include 文件并合并规则; 都没有有效规则时返回 null。 */
+function readIncludeMatcher(baseRepo: string): IncludeMatcher | null {
+ const matchers: IncludeMatcher[] = [];
+ for (const { name, toMatcher } of INCLUDE_FILES) {
+ let content: string;
+ try {
+ content = fs.readFileSync(path.join(baseRepo, name), 'utf8');
+ } catch {
+ continue;
+ }
+ const patterns = includeRuleLines(content);
+ if (patterns.length > 0) matchers.push(toMatcher(patterns));
+ }
+ if (matchers.length === 0) return null;
+ return (rel) => matchers.some((matches) => matches(rel));
+}
+
/**
* 递归列出 baseRepo 下的所有文件相对路径(用 / 分隔)。
* 跳过 .git/ + node_modules/ + Cindy 当前/历史托管 worktree 子树, 防止扫超量。
@@ -167,6 +257,42 @@ async function getTrackedFiles(baseRepo: string): Promise<Set<string>> {
}
}
+/**
+ * 目标 worktree HEAD 树(= sourceBranch)里的文件。base 未跟踪、sourceBranch 已跟踪的
+ * 同名文件不能用 base 的本地副本覆盖(与 WorktreeManager 的 listProtectedClaudeSiviPaths
+ * 同一口径)。查询失败按空集处理(fail-open)。
+ */
+async function getHeadTreeFiles(root: string): Promise<Set<string>> {
+ try {
+ const { stdout } = await gitExec(['ls-tree', '-r', '-z', '--name-only', 'HEAD'], root);
+ return new Set(stdout.split('\0').filter(Boolean));
+ } catch {
+ return new Set<string>();
+ }
+}
+
+/**
+ * 由受控路径集合得到冲突判定: rel 与任一受控路径相同、是其父级(受控文件或符号链接之下)、
+ * 或是其祖先目录(受控内容需要这个目录)时, 在 rel 写入都会顶掉受控内容或与后台 checkout
+ * 冲突。只看 Git 记录, 不依赖它是否已经落盘。
+ */
+function trackedPathConflict(tracked: Iterable<string>): (rel: string) => boolean {
+ const files = new Set(tracked);
+ const dirs = new Set<string>();
+ for (const file of files) {
+ for (let end = file.lastIndexOf('/'); end > 0; end = file.lastIndexOf('/', end - 1)) {
+ dirs.add(file.slice(0, end));
+ }
+ }
+ return (rel) => {
+ if (dirs.has(rel)) return true;
+ for (let end = rel.length; end > 0; end = rel.lastIndexOf('/', end - 1)) {
+ if (files.has(rel.slice(0, end))) return true;
+ }
+ return false;
+ };
+}
+
/**
* 把 baseRepo 下匹配 patterns 且未被 git tracked 的文件拷贝到 destRoot 下相同相对路径。
*
@@ -174,7 +300,7 @@ async function getTrackedFiles(baseRepo: string): Promise<Set<string>> {
*
* @param baseRepo 源 repo 根目录(绝对路径)
* @param destRoot 目标 worktree 路径(绝对路径)
- * @param patterns parseWorktreeIncludePatterns 的输出
+ * @param patterns parseWorktreeIncludePatterns 的输出(`.xdtworktreeinclude` glob 语法)
* @returns per-file 结果, 用于日志 / UI 展示
*/
export async function copyWorktreeIncludeFiles(
@@ -184,17 +310,48 @@ export async function copyWorktreeIncludeFiles(
options: CopyWorktreeIncludeOptions = {},
): Promise<IncludeFileResult[]> {
if (patterns.length === 0) return [];
- const regexes = patterns.map(globToRegex);
- const allFiles = listAllFiles(baseRepo);
- const matched: string[] = [];
- for (const rel of allFiles) {
- if (regexes.some((re) => re.test(rel))) {
- matched.push(rel);
+ return copyMatchedFiles(baseRepo, destRoot, globMatcher(patterns), options);
+}
+
+/**
+ * 写入 destAbs 时的实际落点是否仍在 destRoot 内: 取 destAbs 自身或最近一个已存在的
+ * 父级, 解析全部符号链接后比较; 悬空链接或无法解析时按越界处理。
+ */
+function landsInside(destRoot: string, destAbs: string): boolean {
+ let probe = destAbs;
+ for (;;) {
+ try {
+ fs.lstatSync(probe);
+ break;
+ } catch {
+ const parent = path.dirname(probe);
+ if (parent === probe) return false;
+ probe = parent;
}
}
+ try {
+ const realRoot = fs.realpathSync(destRoot);
+ const real = fs.realpathSync(probe);
+ return real === realRoot || real.startsWith(realRoot + path.sep);
+ } catch {
+ return false;
+ }
+}
+
+async function copyMatchedFiles(
+ baseRepo: string,
+ destRoot: string,
+ matches: IncludeMatcher,
+ options: CopyWorktreeIncludeOptions,
+): Promise<IncludeFileResult[]> {
+ const matched = listAllFiles(baseRepo).filter(matches);
if (matched.length === 0) return [];
- const tracked = await getTrackedFiles(baseRepo);
+ const [trackedInBase, trackedInDestHead] = await Promise.all([
+ getTrackedFiles(baseRepo),
+ getHeadTreeFiles(destRoot),
+ ]);
+ const conflictsWithTracked = trackedPathConflict([...trackedInBase, ...trackedInDestHead]);
const results: IncludeFileResult[] = [];
for (const rel of matched) {
@@ -217,11 +374,17 @@ export async function copyWorktreeIncludeFiles(
continue;
}
- if (tracked.has(rel)) {
+ if (conflictsWithTracked(rel)) {
results.push({ relpath: rel, status: 'skipped-tracked' });
continue;
}
+ // 词法检查看不到符号链接: 目标(或其父目录)若是指向外部的链接, 写入会落到 worktree 外。
+ if (!landsInside(destRoot, destAbs)) {
+ results.push({ relpath: rel, status: 'skipped-outside' });
+ continue;
+ }
+
try {
if (options.overwriteExisting === false) {
try {
@@ -262,28 +425,22 @@ export async function listChangedWorktreeIncludeFiles(
baseRepo: string,
destRoot: string,
): Promise<ChangedIncludeFile[]> {
- const includeFile = path.join(baseRepo, '.xdtworktreeinclude');
- let content: string;
- try {
- content = fs.readFileSync(includeFile, 'utf8');
- } catch {
- return [];
- }
- const patterns = parseWorktreeIncludePatterns(content);
- if (patterns.length === 0) return [];
+ const matches = readIncludeMatcher(baseRepo);
+ if (!matches) return [];
- const regexes = patterns.map(globToRegex);
const [trackedInBase, trackedInDest] = await Promise.all([
getTrackedFiles(baseRepo),
getTrackedFiles(destRoot),
]);
+ const conflictsWithTracked = trackedPathConflict([...trackedInBase, ...trackedInDest]);
const changed: ChangedIncludeFile[] = [];
const destRootResolved = path.resolve(destRoot);
const srcFiles = listAllFiles(baseRepo);
for (const rel of srcFiles) {
- if (!regexes.some((re) => re.test(rel))) continue;
- if (trackedInBase.has(rel)) continue;
+ if (!matches(rel)) continue;
+ // worktree 分支已跟踪的同名文件不是从 base 复制来的, 其改动由 git 自身的 dirty 检查负责。
+ if (conflictsWithTracked(rel)) continue;
const srcAbs = path.join(baseRepo, rel);
const destAbs = path.join(destRoot, rel);
@@ -341,7 +498,7 @@ export async function listChangedWorktreeIncludeFiles(
const srcSet = new Set(srcFiles);
for (const rel of listAllFiles(destRoot)) {
if (srcSet.has(rel)) continue;
- if (!regexes.some((re) => re.test(rel))) continue;
+ if (!matches(rel)) continue;
// base 与 worktree 可能位于不同分支;dest-only 文件是否已提交必须按
// worktree 自己的 index 判断,不能复用 base checkout 的 tracked 集合。
if (trackedInDest.has(rel)) continue;
@@ -360,24 +517,17 @@ export async function listChangedWorktreeIncludeFiles(
}
/**
- * 一站式: 读 .xdtworktreeinclude → 解析 → 拷贝。文件不存在则返回空。
+ * 一站式: 读 .xdtworktreeinclude / .worktreeinclude → 解析 → 拷贝。都不存在则返回空。
*/
export async function applyWorktreeIncludeFile(
baseRepo: string,
destRoot: string,
options: CopyWorktreeIncludeOptions = {},
): Promise<IncludeFileResult[]> {
- const includeFile = path.join(baseRepo, '.xdtworktreeinclude');
- let content: string;
- try {
- content = fs.readFileSync(includeFile, 'utf8');
- } catch {
- return [];
- }
- const patterns = parseWorktreeIncludePatterns(content);
- if (patterns.length === 0) return [];
- return copyWorktreeIncludeFiles(baseRepo, destRoot, patterns, options);
+ const matches = readIncludeMatcher(baseRepo);
+ if (!matches) return [];
+ return copyMatchedFiles(baseRepo, destRoot, matches, options);
}
// 仅供测试用
-export const _internal = { globToRegex, listAllFiles };
+export const _internal = { globToRegex, listAllFiles, gitignoreMatcher };
diff --git a/apps/desktop/src/main/worktree/restore.ts b/apps/desktop/src/main/worktree/restore.ts
index 496dd9e62e..f2f08cd14d 100644
--- a/apps/desktop/src/main/worktree/restore.ts
+++ b/apps/desktop/src/main/worktree/restore.ts
@@ -341,7 +341,7 @@ async function finishRestoredWorktree(
overwriteExisting: false,
}).catch((err) => {
log.warn(
- `[restore] apply .xdtworktreeinclude failed for ${worktreePath}:`,
+ `[restore] apply worktree include files failed for ${worktreePath}:`,
err instanceof Error ? err.message : String(err),
);
});
@@ -498,7 +498,7 @@ async function restoreWorktreeForSessionOnce(sessionId: string): Promise<Worktre
await ensureLocalBranchForRestore(parsed.baseRepo, branch);
await addRestoredWorktree(parsed.baseRepo, status.worktreePath, branch);
// 快照必须先于本地配置恢复:未跟踪文件可能同时命中 .claude/.sivi 或
- // .xdtworktreeinclude,提前拷贝会让 git stash apply 因目标已存在而失败。
+ // .xdtworktreeinclude / .worktreeinclude,提前拷贝会让 git stash apply 因目标已存在而失败。
snapshotApplied = await applyPendingSnapshot(
parsed.baseRepo,
status.worktreePath,