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。

fix(task-copy): 只在 Git 仓库跳过托管 worktree 目录,统计在 lstat 前检查上限

Dash671b9a20285b
diff --git a/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts
index 60be7aeb0b..ed1856fe28 100644
--- a/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/estimateWorkspace.test.ts
@@ -1,4 +1,4 @@
-import { expect, it } from 'vitest';
+import { expect, it, vi } from 'vitest';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
@@ -23,7 +23,7 @@ it('counts hidden and nested files, skips root Git metadata and does not count d
}
});
-it("skips other tasks' managed worktrees only at the project root", async () => {
+it("skips other tasks' managed worktree directories only at a repository root", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'copy-estimate-'));
try {
for (const name of ['.cindy-worktrees', '.xdt-worktrees']) {
@@ -32,8 +32,32 @@ it("skips other tasks' managed worktrees only at the project root", async () =>
}
await fs.mkdir(path.join(root, 'sub', '.cindy-worktrees'), { recursive: true });
await fs.writeFile(path.join(root, 'sub', '.cindy-worktrees', 'file'), '1234');
+ // A plain directory never holds Cindy worktrees: same-named folders are user files.
+ expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 3, bytes: 24 });
+ await fs.mkdir(path.join(root, '.git'));
expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 1, bytes: 4 });
+ // Only directories are skipped; a same-named file is still project content.
+ await fs.rm(path.join(root, '.xdt-worktrees'), { recursive: true });
+ await fs.writeFile(path.join(root, '.xdt-worktrees'), '12');
+ expect(await estimateWorkspace(root, () => {})).toEqual({ fileCount: 2, bytes: 6 });
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ }
+});
+
+it('stops an oversized directory before statting its entries', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'copy-estimate-'));
+ const lstat = vi.spyOn(fs, 'lstat');
+ try {
+ await Promise.all(
+ Array.from({ length: 300 }, (_, i) => fs.writeFile(path.join(root, `f${i}`), '')),
+ );
+ lstat.mockClear();
+ await expect(estimateWorkspace(root, () => {}, 10)).rejects.toThrow('MIGRATION_TOO_MANY_FILES');
+ // Only the repository probe ran; none of the 300 files were statted.
+ expect(lstat.mock.calls.filter(([file]) => !String(file).endsWith('.git'))).toEqual([]);
} finally {
+ lstat.mockRestore();
await fs.rm(root, { recursive: true, force: true });
}
});
diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
index 7e6aa9bb39..5f99170e2b 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -207,6 +207,8 @@ vi.mock('../../session-share/sessionShareImport', () => ({
vi.mock('../workspace', async (original) => ({
isExcludedFromWorkspace: (await original<typeof import('../workspace')>())
.isExcludedFromWorkspace,
+ excludedRootDirectories: (await original<typeof import('../workspace')>())
+ .excludedRootDirectories,
estimateWorkspace: async (_root: string, _check: () => void, maxFiles: number) => {
state.estimateLimits.push(maxFiles);
return { fileCount: 1, bytes: 8 };
@@ -514,6 +516,7 @@ describe('resumable cross-computer copy', () => {
const cwd = rows.get('fork')!.workingDir as string;
const managed = path.join(cwd, '.cindy-worktrees', 'other');
await fs.mkdir(managed, { recursive: true });
+ await fs.mkdir(path.join(cwd, '.git'));
rows.get('sibling')!.workingDir = managed;
state.siblingRunning = true;
await start();
diff --git a/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts b/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
index 6046fefbe5..4825cd33e3 100644
--- a/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/workspace.git-integration.test.ts
@@ -108,8 +108,13 @@ describe('cross-machine project snapshots', () => {
expect(await git(linked, 'diff', '--cached')).toBe(staged);
expect(await fs.readFile(path.join(source, 'tracked'), 'utf8')).toBe('base\n');
}, 30_000);
- it("leaves other tasks' managed worktrees behind", async () => {
+ it("leaves other tasks' managed worktrees behind in a repository", async () => {
+ await git(source, 'init', '-b', 'main');
+ await git(source, 'config', 'user.name', 'Migration test');
+ await git(source, 'config', 'user.email', 'migration@localhost');
await fs.writeFile(path.join(source, 'draft'), 'mine\n');
+ await git(source, 'add', 'draft');
+ await git(source, 'commit', '-m', 'fixture');
for (const name of ['.cindy-worktrees', '.xdt-worktrees']) {
await fs.mkdir(path.join(source, name, 'other-task'), { recursive: true });
// Nested Git metadata would otherwise make the whole snapshot non-portable.
@@ -119,11 +124,20 @@ describe('cross-machine project snapshots', () => {
const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
expect(Object.keys(snapshot.archive.files)).toEqual(['draft']);
await restoreWorkspace(snapshot, artifacts, target);
- expect(await fs.readdir(target)).toEqual(['draft']);
+ expect((await fs.readdir(target)).sort()).toEqual(['.git', 'draft']);
expect(
await fs.readFile(path.join(source, '.cindy-worktrees', 'other-task', 'file'), 'utf8'),
).toBe('not mine\n');
});
+ it('keeps same-named folders of a plain directory', async () => {
+ await fs.mkdir(path.join(source, '.cindy-worktrees'));
+ await fs.writeFile(path.join(source, '.cindy-worktrees', 'notes'), 'user file\n');
+ const before = await inventoryWorktree(source);
+ const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
+ await restoreWorkspace(snapshot, artifacts, target);
+ expect(await inventoryWorktree(target)).toEqual(before);
+ expect(Object.keys(before)).toContain(path.join('.cindy-worktrees', 'notes'));
+ });
it('refuses to overwrite a destination directory', async () => {
await fs.writeFile(path.join(source, 'source'), 'copy');
const snapshot = await snapshotWorkspace(source, artifacts, randomUUID());
diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.ts
index c4446949bf..37c1855038 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -56,6 +56,7 @@ import {
restoreWorkspace,
estimateWorkspace,
isExcludedFromWorkspace,
+ excludedRootDirectories,
type PortableWorkspace,
} from './workspace';
@@ -296,6 +297,8 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
await Promise.all(members.map((member) => physicalWorktreeKey(member.workingDir))),
),
];
+ // A task inside another managed worktree under a copied root does not touch copied files.
+ const excluded = await Promise.all(sourceKeys.map(excludedRootDirectories));
for (const session of getMakerIfReady()?.listActiveSessions() ?? []) {
if (!session.isTurnRunning() && !sourceBoundary!.isBusy(session.id)) continue;
const row = await scope.db.queryOne<{
@@ -309,10 +312,10 @@ async function prepare(scope: Scope, record: MigrationHandoff) {
const key = await physicalWorktreeKey(row.workingDir);
if (
sourceKeys.some(
- (sourceKey) =>
+ (sourceKey, index) =>
key === sourceKey ||
(key.startsWith(sourceKey + path.sep) &&
- !isExcludedFromWorkspace(sourceKey, key)) ||
+ !isExcludedFromWorkspace(sourceKey, key, excluded[index])) ||
sourceKey.startsWith(key + path.sep),
)
)
diff --git a/apps/desktop/src/main/task-migration/workspace.ts b/apps/desktop/src/main/task-migration/workspace.ts
index 5703e0b346..78109488c9 100644
--- a/apps/desktop/src/main/task-migration/workspace.ts
+++ b/apps/desktop/src/main/task-migration/workspace.ts
@@ -11,15 +11,33 @@ import { gitExec, GitExecError } from '../worktree/gitExec';
import { assertDiskCapacity } from './resources';
import { MANAGED_WORKTREE_DIR_NAMES } from '../../shared/managedWorktreePaths';
-/** Other tasks' Cindy worktrees live under the repository root; a copy never carries them. */
-const EXCLUDED_ROOT_NAMES: readonly string[] = MANAGED_WORKTREE_DIR_NAMES;
const ESTIMATE_CONCURRENCY = 32;
+const STAT_BATCH = 64;
-/** Whether `file` lies in a top-level directory that copies of `root` leave behind. */
-export function isExcludedFromWorkspace(root: string, file: string): boolean {
+/**
+ * Top-level directory names a copy of `root` leaves behind: other tasks' Cindy worktrees.
+ * Cindy only creates them inside Git repositories, so a plain directory keeps same-named
+ * folders. Callers skip only directories with these names, never files.
+ */
+export async function excludedRootDirectories(root: string): Promise<string[]> {
+ try {
+ await fs.lstat(path.join(root, '.git'));
+ return [...MANAGED_WORKTREE_DIR_NAMES];
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+}
+
+/** Whether `file` lies in one of `root`'s `excluded` top-level directories. */
+export function isExcludedFromWorkspace(
+ root: string,
+ file: string,
+ excluded: readonly string[],
+): boolean {
const relative = path.relative(root, file);
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return false;
- return EXCLUDED_ROOT_NAMES.includes(relative.split(path.sep)[0]);
+ return excluded.includes(relative.split(path.sep)[0]);
}
export interface PortableWorkspace {
@@ -146,7 +164,7 @@ export async function snapshotWorkspace(
encryptedKey: '',
iv: randomBytes(12),
maxBytes: Math.floor((space.bavail * space.bsize) / 1.1),
- excludeRootNames: [...EXCLUDED_ROOT_NAMES],
+ excludeRootNames: await excludedRootDirectories(root),
});
archive.files = Object.fromEntries(
Object.entries(archive.files).map(([name, entry]) => [name.split(path.sep).join('/'), entry]),
@@ -266,27 +284,33 @@ export async function estimateWorkspace(
maxFiles = Number.POSITIVE_INFINITY,
): Promise<{ fileCount: number; bytes: number }> {
root = await fs.realpath(root);
+ const excluded = await excludedRootDirectories(root);
const result = { fileCount: 0, bytes: 0 };
const pending = [root];
const visit = async (directory: string): Promise<void> => {
const files: string[] = [];
for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
check();
- if (directory === root && (entry.name === '.git' || EXCLUDED_ROOT_NAMES.includes(entry.name)))
- continue;
+ if (directory === root && entry.name === '.git') continue;
const file = path.join(directory, entry.name);
- if (entry.isDirectory()) pending.push(file);
- else if (entry.isFile() || entry.isSymbolicLink()) files.push(file);
+ if (entry.isDirectory()) {
+ if (directory !== root || !excluded.includes(entry.name)) pending.push(file);
+ } else if (entry.isFile() || entry.isSymbolicLink()) files.push(file);
else throw new Error('MIGRATION_NONPORTABLE_PATH');
}
- for (const stat of await Promise.all(files.map((file) => fs.lstat(file)))) {
- result.fileCount++;
- result.bytes += stat.size;
- }
+ // Count before stat so an oversized directory stops without statting every entry.
+ result.fileCount += files.length;
if (result.fileCount > maxFiles) throw new Error('MIGRATION_TOO_MANY_FILES');
+ for (let index = 0; index < files.length; index += STAT_BATCH) {
+ check();
+ const stats = await Promise.all(
+ files.slice(index, index + STAT_BATCH).map((file) => fs.lstat(file)),
+ );
+ for (const stat of stats) result.bytes += stat.size;
+ }
};
- // A sequential walk of a dependency-heavy project takes minutes; unbounded recursion
- // would hold the whole tree in memory. Visit a bounded number of directories at once.
+ // A sequential walk of a dependency-heavy project takes minutes; unbounded fan-out would
+ // hold the whole tree in memory. At most ESTIMATE_CONCURRENCY × STAT_BATCH stats in flight.
await new Promise<void>((resolve, reject) => {
let active = 0;
let settled = false;
diff --git a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
index a2f3f88da3..3cfd1188a9 100644
--- a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
+++ b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts
@@ -25,15 +25,16 @@ function restorableMode(mode: number): number {
return mode & (process.platform === 'win32' ? 0o666 : 0o777);
}
-/** `excludeRootNames` skips extra top-level entries (task copy leaves other tasks' worktrees behind). */
+/** `excludeRootNames` skips top-level directories (never files) — task copy leaves other tasks' worktrees behind. */
export async function inventoryWorktree(root: string, maxBytes?: number, excludeRootNames: readonly string[] = []): Promise<Record<string, FileEvidence>> {
const files: Record<string, FileEvidence> = Object.create(null);
let bytes = 0;
const walk = async (directory: string): Promise<void> => {
for (const name of await fs.readdir(directory)) {
- if (directory === root && (name === '.git' || excludeRootNames.includes(name))) continue;
+ if (directory === root && name === '.git') continue;
const absolute = path.join(directory, name);
const stat = await fs.lstat(absolute);
+ if (directory === root && stat.isDirectory() && excludeRootNames.includes(name)) continue;
const relative = path.relative(root, absolute);
const mode = restorableMode(stat.mode);
if (stat.isSymbolicLink()) {
diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.md
index bf8092bbe3..9c2450ea10 100644
--- a/docs/product-rules/task-device-migration.md
+++ b/docs/product-rules/task-device-migration.md
@@ -17,8 +17,9 @@
不发布这次副本。该检查不冻结输入,也不承诺外部编辑器与数据库的跨进程原子快照。
复制是一次快照,不持续同步;源任务后续变化不会更新副本。快照遇到文件变化会失败并允许重试。
2. 复用任务分享导出、原生上下文恢复及 worktree 快照。包含未提交、未跟踪和忽略文件;
- 项目根目录下其它任务的 Cindy 托管 worktree(`.cindy-worktrees`,旧名 `.xdt-worktrees`)
- 不随副本复制,也不计入统计;在这些 worktree 里运行的任务不阻止复制。
+ Git 仓库根目录下其它任务的 Cindy 托管 worktree 目录(`.cindy-worktrees`,旧名 `.xdt-worktrees`)
+ 不随副本复制,也不计入统计;在这些 worktree 里运行的任务不阻止复制。非 Git 目录中的同名文件夹
+ 及任何同名文件照常复制。
Git 保留 HEAD、暂存区和工作文件差别,不复制本机 Git 配置、hooks 或凭证。
目标始终创建独立目录,不覆盖已有项目。整组共享物理目录只复制一份,独立目录分别创建。
3. 复用 peer 直传及 OSS 回退、冷却。按实时磁盘和可用内存预算准备、发送、接收及解包,