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: protect borrowed worktrees from legacy recyclers

JiangJiahaod135e78310e9
diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
index 8235ff2050..1a7c50256b 100644
--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
@@ -151,6 +151,29 @@ describe('shared worktree recycling', () => {
await release?.();
}
});
+ it('protects borrowed source when the owner still reads only profile-local leases', async () => {
+ const borrowerProfile = path.join(state.root, 'profile-a');
+ const ownerProfile = path.join(state.root, 'legacy-profile');
+ // Match the pre-change reader: the owner never scans the shared registry.
+ vi.mocked(readWorktreeRuntimePaths).mockImplementation(async () => {
+ const directory = path.join(state.userData, 'worktree-runtime-leases');
+ const names = await fs.readdir(directory).catch(() => [] as string[]);
+ return new Set(await Promise.all(names.filter((name) => name.endsWith('.json')).map(async (name) =>
+ JSON.parse(await fs.readFile(path.join(directory, name), 'utf8')).path as string)));
+ });
+ state.userData = borrowerProfile;
+ const release = await acquireIOSSimulatorProjectUse('borrower', meta.path, new AbortController());
+ try {
+ state.userData = ownerProfile;
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());
+ expect(await recycle()).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.reason).toBe('keep-sentinel');
+ expect(archive).not.toHaveBeenCalled();
+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('uncommitted contents');
+ await release!();
+ expect(await recycle()).toBe(true);
+ } finally { await release?.(); }
+ });
it('protects a borrower running in a subdirectory', async () => {
state.refs.push({ ...state.refs[0], id: 'borrower', status: 'active', workingDir: path.join(meta.path, 'src'), worktreePath: null });
expect(await recycle()).toBe(false);
diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
index cdd89b72e7..3cd7241f8c 100644
--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
@@ -15,6 +15,7 @@ vi.mock('../desktopProcessIdentity', async (importOriginal) => ({
import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, readWorktreeRuntimePaths, retryPendingWorktreeRuntimeLeaseReleases } from '../worktree/runtimeLeases';
import { physicalWorktreeKey, withWorktreeResourceLock } from '../worktree/resourceLock';
+import { hasKeepSentinel } from '../worktree/safety';
describe('worktree runtime evidence and physical locks', () => {
let worktree: string;
@@ -131,6 +132,143 @@ describe('worktree runtime evidence and physical locks', () => {
await releaseWorktreeRuntimeLease(oldLease);
});
+ it.each(['file', 'directory'] as const)('preserves an existing user keep %s', async (kind) => {
+ const file = path.join(worktree, '.worktree-keep');
+ if (kind === 'file') await fs.writeFile(file, 'user requested retention');
+ else await fs.mkdir(file);
+ const lease = (await acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true }))!;
+ expect(lease.keepSentinel).toBeUndefined();
+ await releaseWorktreeRuntimeLease(lease);
+ expect(hasKeepSentinel(worktree)).toBe(true);
+ if (kind === 'file') expect(await fs.readFile(file, 'utf8')).toBe('user requested retention');
+ else expect(await fs.readdir(file)).toEqual([]);
+ });
+
+ it('keeps legacy protection until the last borrower in either profile finishes', async () => {
+ const first = (await acquireWorktreeRuntimeLease('first', worktree, { crossProfile: true }))!;
+ state.userData = path.join(state.root, 'second-profile');
+ const second = (await acquireWorktreeRuntimeLease('second', worktree, { crossProfile: true }))!;
+ expect(first.keepSentinel).toBeDefined();
+ expect(second.keepSentinel).toEqual(first.keepSentinel);
+ await releaseWorktreeRuntimeLease(first);
+ await releaseWorktreeRuntimeLease(first);
+ expect(hasKeepSentinel(worktree)).toBe(true);
+ await releaseWorktreeRuntimeLease(second);
+ expect(hasKeepSentinel(worktree)).toBe(false);
+ });
+
+ it('does not adopt a user marker just because its contents resemble our format', async () => {
+ const file = path.join(worktree, '.worktree-keep');
+ const content = JSON.stringify({ kind: 'cindy-runtime-keep', version: 1, nonce: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' });
+ await fs.writeFile(file, content);
+ const lease = (await acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true }))!;
+ expect(lease.keepSentinel).toBeUndefined();
+ await releaseWorktreeRuntimeLease(lease);
+ expect(await fs.readFile(file, 'utf8')).toBe(content);
+ });
+
+ it('does not let a later borrower adopt a marker edited during an earlier borrow', async () => {
+ const first = (await acquireWorktreeRuntimeLease('first', worktree, { crossProfile: true }))!;
+ const file = path.join(worktree, '.worktree-keep');
+ const content = JSON.stringify({ kind: 'cindy-runtime-keep', version: 1, nonce: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' });
+ await fs.writeFile(file, content);
+ const second = (await acquireWorktreeRuntimeLease('second', worktree, { crossProfile: true }))!;
+ expect(second.keepSentinel).toBeUndefined();
+ await releaseWorktreeRuntimeLease(first);
+ await releaseWorktreeRuntimeLease(second);
+ expect(await fs.readFile(file, 'utf8')).toBe(content);
+ });
+
+ it.each(['edited', 'replaced'] as const)('preserves a runtime marker %s by the user', async (change) => {
+ const lease = (await acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true }))!;
+ const file = path.join(worktree, '.worktree-keep');
+ if (change === 'edited') await fs.writeFile(file, 'keep my checkout');
+ else {
+ // Keep the old inode alive so a replacement containing identical bytes
+ // cannot be confused with the marker this acquisition actually owns.
+ await fs.rename(file, `${file}.previous`);
+ await fs.writeFile(file, lease.keepSentinel!.content);
+ }
+ await releaseWorktreeRuntimeLease(lease);
+ expect(hasKeepSentinel(worktree)).toBe(true);
+ expect(await fs.readFile(file, 'utf8')).toBe(change === 'edited' ? 'keep my checkout' : lease.keepSentinel!.content);
+ });
+
+ it('does not remove legacy protection when another borrower crashes', async () => {
+ const crashed = (await acquireWorktreeRuntimeLease('crashed', worktree, { crossProfile: true }))!;
+ const active = (await acquireWorktreeRuntimeLease('active', worktree, { crossProfile: true }))!;
+ vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw Object.assign(new Error('owner is gone'), { code: 'ESRCH' });
+ });
+ await releaseWorktreeRuntimeLease(active);
+ await retryPendingWorktreeRuntimeLeaseReleases();
+ expect(hasKeepSentinel(worktree)).toBe(true);
+ expect(await fs.stat(crashed.sharedFile!)).toBeDefined();
+ // Only confirmed source I/O teardown authorizes the remaining release.
+ await releaseWorktreeRuntimeLease(crashed);
+ expect(hasKeepSentinel(worktree)).toBe(false);
+ });
+
+ it('fails acquisition before source I/O when legacy protection cannot be published', async () => {
+ const write = fs.writeFile.bind(fs);
+ const sentinel = path.join(await physicalWorktreeKey(worktree), '.worktree-keep');
+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {
+ if (args[0] === sentinel) throw Object.assign(new Error('read only'), { code: 'EACCES' });
+ return write(...args);
+ });
+ await expect(acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true })).rejects.toMatchObject({ code: 'EACCES' });
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());
+ expect(hasKeepSentinel(worktree)).toBe(false);
+ });
+
+ it('retries failed sentinel cleanup through the shared durable release intent', async () => {
+ const lease = (await acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true }))!;
+ const unlink = fs.unlink.bind(fs);
+ const sentinel = path.join(lease.physicalPath, '.worktree-keep');
+ let blocked = true;
+ vi.spyOn(fs, 'unlink').mockImplementation(async (file) => {
+ if (file === sentinel && blocked) throw Object.assign(new Error('busy'), { code: 'EBUSY' });
+ return unlink(file);
+ });
+ await expect(releaseWorktreeRuntimeLease(lease)).rejects.toMatchObject({ code: 'EBUSY' });
+ expect(hasKeepSentinel(worktree)).toBe(true);
+ expect(await fs.stat(lease.sharedFile!)).toBeDefined();
+ state.userData = path.join(state.root, 'maintenance-profile');
+ expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(1);
+ blocked = false;
+ expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(0);
+ expect(hasKeepSentinel(worktree)).toBe(false);
+ await expect(fs.stat(lease.sharedFile!)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.stat(`${lease.sharedFile}.release`)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('cleans its own marker when publishing marker ownership fails', async () => {
+ const write = fs.writeFile.bind(fs);
+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {
+ if (typeof args[1] === 'string' && args[1].includes('"keepSentinel"')) {
+ await write(args[0], '{');
+ throw Object.assign(new Error('ownership publication interrupted'), { code: 'EIO' });
+ }
+ return write(...args);
+ });
+ await expect(acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true })).rejects.toMatchObject({ code: 'EIO' });
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());
+ expect(hasKeepSentinel(worktree)).toBe(false);
+ });
+
+ it('keeps legacy protection while another shared borrower record is unreadable', async () => {
+ const first = (await acquireWorktreeRuntimeLease('first', worktree, { crossProfile: true }))!;
+ const second = (await acquireWorktreeRuntimeLease('second', worktree, { crossProfile: true }))!;
+ await fs.writeFile(second.sharedFile!, '{');
+ await expect(releaseWorktreeRuntimeLease(first)).rejects.toThrow();
+ expect(hasKeepSentinel(worktree)).toBe(true);
+ expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(1);
+ await releaseWorktreeRuntimeLease(second);
+ expect(hasKeepSentinel(worktree)).toBe(true);
+ expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(0);
+ expect(hasKeepSentinel(worktree)).toBe(false);
+ });
+
it('preserves when another live instance cannot publish runtime evidence', async () => {
vi.spyOn(process, 'kill').mockReturnValue(true);
await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'), JSON.stringify({ pid: 4242 }));
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index b9b3ca5373..eb05659b9a 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
@@ -437,6 +437,10 @@ describe('iOS Simulator host', () => {
it('installs the external artifact on task A and validates Cindy Mobile launch against B', async () => {
const h = await projectSelectionHarness(true);
try {
+ h.validateLaunch.mockImplementationOnce(async () => {
+ expect((await stat(path.join(h.projectRoot, '.worktree-keep'))).isFile()).toBe(true);
+ return null;
+ });
const result = await h.host.callTool('build_app', { ...h.route, projectDir: path.relative(h.taskRoot, h.projectRoot) }, h.context);
expect(result).toMatchObject({ ok: true });
const artifactId = (await h.inspectArtifact.mock.results[0]!.value).artifactId;
@@ -444,6 +448,7 @@ describe('iOS Simulator host', () => {
expect(installed, JSON.stringify(installed)).toMatchObject({ ok: true });
const launched = await h.host.callTool('launch_app', { ...h.route, artifactId, args: [] }, h.context);
expect(launched, JSON.stringify(launched)).toMatchObject({ ok: true });
+ await expect(stat(path.join(h.projectRoot, '.worktree-keep'))).rejects.toMatchObject({ code: 'ENOENT' });
expect(h.validateLaunch).toHaveBeenCalledWith(h.projectRoot, READY_REPORT.devices[0]!.udid, expect.any(AbortSignal));
expect(h.installExact).toHaveBeenCalledWith(READY_REPORT.devices[0]!.udid, expect.objectContaining({ artifactId, worktreeRoot: h.projectRoot }), expect.any(AbortSignal));
expect(h.launchExact).toHaveBeenCalledWith(READY_REPORT.devices[0]!.udid, expect.objectContaining({ artifactId, worktreeRoot: h.projectRoot }), [], expect.any(AbortSignal));
@@ -652,10 +657,12 @@ describe('iOS Simulator host', () => {
await vi.waitFor(() => expect(h.build.mock.calls[0]![0].signal!.aborted).toBe(true));
expect(cancelFinished).toBe(false);
expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(h.projectRoot)]));
+ expect((await stat(path.join(h.projectRoot, '.worktree-keep'))).isFile()).toBe(true);
unblock();
expect(await result).toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });
await cancelling;
expect(await readWorktreeRuntimePaths()).toEqual(new Set());
+ await expect(stat(path.join(h.projectRoot, '.worktree-keep'))).rejects.toMatchObject({ code: 'ENOENT' });
expect((await stat(h.projectRoot)).isDirectory()).toBe(true);
if (reason === 'source-recycle') {
expect(await h.host.callTool('build_app', { ...h.route, projectDir: h.projectRoot }, h.context)).toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });
diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.ts
index d99c48fb11..90b6d287f3 100644
--- a/apps/desktop/src/main/worktree/runtimeLeases.ts
+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts
@@ -36,11 +36,17 @@ function leaseFile(sessionId: string, directory: string): string {
const leaseNamePattern = /^\d+-[a-f0-9]{64}\.json$/;
const releaseRequestPattern = /^\d+-[a-f0-9]{64}\.json\.release$/;
+interface RuntimeKeepSentinel {
+ content: string;
+ identity: string;
+}
+
/** A startup owns its own file, even when the business task id is reused. */
export interface WorktreeRuntimeLease {
readonly file: string;
readonly physicalPath: string;
readonly sharedFile?: string;
+ readonly keepSentinel?: RuntimeKeepSentinel;
}
export async function acquireWorktreeRuntimeLease(
@@ -53,13 +59,26 @@ export async function acquireWorktreeRuntimeLease(
return withWorktreeResourceLock(root, async () => {
const lease = await publishRuntimeLease(sessionId, await physicalWorktreeKey(root), runtimeRoot());
if (!options.crossProfile) return lease;
+ let shared: WorktreeRuntimeLease | undefined;
+ let keepSentinel: RuntimeKeepSentinel | undefined;
try {
// Publish both under the deletion lock. Keep the original profile copy
// readable by existing clients sharing this userData.
- const shared = await publishRuntimeLease(sessionId, lease.physicalPath, sharedRuntimeRoot());
- return { ...lease, sharedFile: shared.file };
+ shared = await publishRuntimeLease(sessionId, lease.physicalPath, sharedRuntimeRoot());
+ // Older owner profiles only read their own leases, but already honor this
+ // sentinel before both recycling and pool reset. Publish under their lock.
+ keepSentinel = await acquireRuntimeKeepSentinel(shared);
+ if (keepSentinel) {
+ // Ownership lives with a real borrower, not merely in a recognizable
+ // marker body that a user could have copied or edited. Existing v1
+ // readers ignore the additional field; a partial write fails closed.
+ await fs.writeFile(shared.file, JSON.stringify({
+ version: 1, pid: process.pid, path: lease.physicalPath, keepSentinel,
+ }));
+ }
+ return { ...lease, sharedFile: shared.file, keepSentinel };
} catch (error) {
- await releaseWorktreeRuntimeLease(lease).catch(() => undefined);
+ await releaseWorktreeRuntimeLease({ ...lease, sharedFile: shared?.file, keepSentinel }).catch(() => undefined);
throw error;
}
});
@@ -83,15 +102,91 @@ async function publishRuntimeLease(sessionId: string, physicalPath: string, dire
return lease;
}
+async function acquireRuntimeKeepSentinel(lease: WorktreeRuntimeLease): Promise<RuntimeKeepSentinel | undefined> {
+ const file = path.join(lease.physicalPath, '.worktree-keep');
+ const newContent = JSON.stringify({ kind: 'cindy-runtime-keep', version: 1, nonce: randomUUID() });
+ let created = false;
+ try {
+ await fs.writeFile(file, newContent, { flag: 'wx', mode: 0o600 });
+ created = true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ }
+ // stat must also succeed: a dangling user symlink is invisible to old pool
+ // guards. Never overwrite an existing marker, including files/directories.
+ await fs.stat(file);
+ const identity = await fs.lstat(file);
+ if (!identity.isFile() || identity.isSymbolicLink()) return undefined;
+ let content: string;
+ try { content = await fs.readFile(file, 'utf8'); } catch { return undefined; }
+ const marker = { content, identity: `${identity.dev}:${identity.ino}:${identity.birthtimeMs}` };
+ if (created) return content === newContent ? marker : undefined;
+ const directory = path.dirname(lease.file);
+ for (const name of await fs.readdir(directory)) {
+ if (!leaseNamePattern.test(name) || name === path.basename(lease.file)) continue;
+ try {
+ const other = JSON.parse(await fs.readFile(path.join(directory, name), 'utf8'));
+ if (other.version !== 1 || typeof other.path !== 'string') throw new Error('unreadable worktree lease');
+ if (other.path === lease.physicalPath && other.keepSentinel?.content === content
+ && other.keepSentinel?.identity === marker.identity) return marker;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ return undefined;
+}
+
+/** Called under the same physical lock as acquisition and old owner recyclers. */
+async function releaseRuntimeKeepSentinel(lease: WorktreeRuntimeLease): Promise<void> {
+ const marker = lease.keepSentinel;
+ if (!marker) return;
+ const file = path.join(lease.physicalPath, '.worktree-keep');
+ try {
+ const identity = await fs.lstat(file);
+ if (!identity.isFile() || identity.isSymbolicLink()
+ || `${identity.dev}:${identity.ino}:${identity.birthtimeMs}` !== marker.identity
+ || await fs.readFile(file, 'utf8') !== marker.content) return;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw error;
+ }
+ // Every cross-profile borrower publishes here before creating/joining the
+ // sentinel. Crashed borrowers remain references until explicit I/O teardown.
+ const directory = path.dirname(lease.file);
+ for (const name of await fs.readdir(directory)) {
+ if (!leaseNamePattern.test(name) || name === path.basename(lease.file)) continue;
+ try {
+ const other = JSON.parse(await fs.readFile(path.join(directory, name), 'utf8'));
+ if (other.version !== 1 || typeof other.path !== 'string') throw new Error('unreadable worktree lease');
+ if (other.path === lease.physicalPath) return;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ await fs.unlink(file).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ });
+}
+
export async function releaseWorktreeRuntimeLease(lease: WorktreeRuntimeLease): Promise<void> {
- const files = [lease.file, ...(lease.sharedFile ? [lease.sharedFile] : [])];
- const results = await Promise.allSettled(files.map((file) => releaseRuntimeLeaseFile({ file, physicalPath: lease.physicalPath })));
+ const files: WorktreeRuntimeLease[] = [{ file: lease.file, physicalPath: lease.physicalPath }];
+ if (lease.sharedFile) files.push({ file: lease.sharedFile, physicalPath: lease.physicalPath, keepSentinel: lease.keepSentinel });
+ const results = await Promise.allSettled(files.map(releaseRuntimeLeaseFile));
const failure = results.find((result) => result.status === 'rejected');
if (failure?.status === 'rejected') throw failure.reason;
}
+async function removeRuntimeLeaseFile(lease: WorktreeRuntimeLease): Promise<void> {
+ if (lease.keepSentinel) {
+ await withWorktreeResourceLock(lease.physicalPath, async () => {
+ await releaseRuntimeKeepSentinel(lease);
+ await fs.unlink(lease.file);
+ });
+ } else await fs.unlink(lease.file);
+}
+
async function releaseRuntimeLeaseFile(lease: WorktreeRuntimeLease): Promise<void> {
- try { await fs.unlink(lease.file); } catch (error) {
+ try { await removeRuntimeLeaseFile(lease); } catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
await fs.unlink(`${lease.file}.release`).catch(() => undefined);
return;
@@ -100,7 +195,7 @@ async function releaseRuntimeLeaseFile(lease: WorktreeRuntimeLease): Promise<voi
// a later maintenance pass can prove that this terminal cleanup succeeded.
try {
await fs.mkdir(path.dirname(lease.file), { recursive: true });
- await fs.writeFile(`${lease.file}.release`, JSON.stringify({ version: 1, file: lease.file, path: lease.physicalPath }), { flag: 'wx', mode: 0o600 });
+ await fs.writeFile(`${lease.file}.release`, JSON.stringify({ version: 1, file: lease.file, path: lease.physicalPath, keepSentinel: lease.keepSentinel }), { flag: 'wx', mode: 0o600 });
} catch { /* preserving the lease is the safe fallback */ }
// Wake the event-driven maintenance loop; it will retry the durable intent
// while the still-present lease continues to protect the worktree.
@@ -130,13 +225,17 @@ async function retryPendingRuntimeLeaseReleasesIn(directory: string): Promise<nu
for (const name of names.filter((value) => releaseRequestPattern.test(value))) {
const requestFile = path.join(directory, name);
try {
- const request = JSON.parse(await fs.readFile(requestFile, 'utf8')) as { version?: number; file?: string; path?: string };
+ const request = JSON.parse(await fs.readFile(requestFile, 'utf8')) as { version?: number; file?: string; path?: string; keepSentinel?: RuntimeKeepSentinel };
if (request.version !== 1 || typeof request.file !== 'string' || typeof request.path !== 'string'
- || path.dirname(request.file) !== directory || !leaseNamePattern.test(path.basename(request.file))) {
+ || path.dirname(request.file) !== directory || !leaseNamePattern.test(path.basename(request.file))
+ || (request.keepSentinel !== undefined && (!request.keepSentinel
+ || typeof request.keepSentinel.content !== 'string' || typeof request.keepSentinel.identity !== 'string'))) {
pending++;
continue;
}
- try { await fs.unlink(request.file); } catch (error) {
+ try {
+ await removeRuntimeLeaseFile({ file: request.file, physicalPath: request.path, keepSentinel: request.keepSentinel });
+ } catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { pending++; continue; }
}
await fs.unlink(requestFile).catch((error) => {
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 45189ca82c..7b9d105fb4 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -71,6 +71,7 @@
| Skill 卸载清理回执 | `app.getPath('userData')/skillhub/uninstall-cleanups/<token>.json`,记录操作 owner、旧文件/注册/偏好身份与完成阶段;跨窗口和重启保留,当前 owner 重试完成后删除,不作为授权凭据 |
| 跨 profile 的共享 Skill 文件互斥 | `app.getPath('appData')/Cindy/shared-skill-mutation-locks`,仅存文件锁及未完成操作的 token/名称哈希,保证正式版/dev/isolated 共用;短期锁复用既有崩溃回收,持久屏障必须等对应清理完成后删除,读取损坏只阻止相关名称 |
| 跨 profile 的 worktree 借用租约 | `app.getPath('appData')/Cindy/shared-worktree-runtime-leases`,模拟器工程借用时在原 profile 租约之外发布共享副本;回收器同时读取两处,源目录 I/O 结束后显式释放,释放失败由现有 `.release` 回执重试;不能因进程退出就移除保护 |
+| 旧版 worktree 回收器兼容哨兵 | 借用源目录根的 `.worktree-keep`,复用旧版删除/池化复用已识别的保留协议;不覆盖用户标记,仅当最后一个共享借用结束且自建文件身份和内容仍匹配时删除。清理失败在共享租约 `.release` 中保留原文件身份,由现有维护重试 |
| 跨 profile 的 worktree 回收日志位置 | `app.getPath('appData')/Cindy/shared-worktree-recycle-journals`,按日志目录哈希登记原 profile 日志位置,启动日志监听和写入回收记录前原子发布;借用方只读目标资源的原始日志,不复制恢复状态、不代替 owner 执行恢复。索引跨重启保留,原日志不存在时不产生回收意图 |
| 用户明确导出的文件 | 用户选择或任务明确指定的目标路径 |
diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.md
index a57f2ba784..d5d4df3e33 100644
--- a/docs/ios-simulator-integration-plan.md
+++ b/docs/ios-simulator-integration-plan.md
@@ -1034,7 +1034,11 @@ fingerprint 和相对 container 路径;该 fingerprint 不代表 Git revision
在发布租约前拒绝构建/启动,避免使用残缺目录或阻挡 owner 恢复。完成的记录或旧目录身份
不阻止新目录使用。日志监听启动时登记既有日志,写入新意图前也必须完成登记;共享索引
只保存日志位置,不复制状态、不改变原 profile 的日志格式和恢复归属。
-跨 profile 借用要求回收方也运行包含共享租约读取及日志登记支持的版本;profile 内副本保留原读取协议。
+兼容尚未读取共享租约的旧版回收方:借用时还在资源锁内创建或沿用 `.worktree-keep`,
+旧版删除与池化复用均已识别该哨兵。用户已有或后来修改/替换的标记不会被删除;Host 自建
+标记只在最后一个共享借用者结束、文件身份与内容仍匹配时移除。发布失败则不开始源目录
+I/O;清理失败通过共享 `.release` 回执重试,异常退出留下的租约继续保护旧版回收路径。
+日志预检只读取已登记 profile 的原始日志;profile 内租约副本保留原读取协议。
任务 A 结束时排空自己的操作,不因其构建了 B 就把 B 加入 A 的目录删除范围。
这仍是工程选择与目录边界校验,不是对 Xcode build scripts 的文件系统沙箱。
diff --git a/scripts/__tests__/ensure-binary-fallback.test.mjs b/scripts/__tests__/ensure-binary-fallback.test.mjs
index 53cfc68a58..260f54f1dc 100644
--- a/scripts/__tests__/ensure-binary-fallback.test.mjs
+++ b/scripts/__tests__/ensure-binary-fallback.test.mjs
@@ -13,6 +13,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { ensureBinary } from '../ensure-agent-binaries.mjs';
+import { fetchReleaseAsset } from '../../tools/ripgrep/update.mjs';
const PLATFORM = 'test-fallback-platform'; // 假平台:上游立即抛 unknown,不打网络、不碰真实二进制
const CLAUDE_PIN = JSON.parse(fs.readFileSync('tools/claude/latest.json', 'utf8')).version;
@@ -84,3 +85,48 @@ test('ensureBinary(ripgrep): 上游失败 → 回退 CDN,落地正确二进制
const ver = fs.readFileSync(path.join(path.dirname(binPath), '.version'), 'utf8').trim();
assert.equal(ver, RIPGREP_PIN);
});
+
+// Official release asset retries, without network access or real timers.
+for (const suffix of ['.tar.gz', '.tar.gz.sha256']) {
+ test(`ripgrep retries transient asset failures for ${suffix}`, async () => {
+ const url = `https://github.com/BurntSushi/ripgrep/releases/download/15.1.0/test${suffix}`;
+ const statuses = [500, 502, 200];
+ const delays = [];
+ const failures = [];
+ const result = await fetchReleaseAsset(url, {
+ fetchImpl: async (requestedUrl) => {
+ assert.equal(requestedUrl, url);
+ const response = new Response('asset', { status: statuses.shift() });
+ if (!response.ok) failures.push(response);
+ return response;
+ },
+ wait: async (milliseconds) => { delays.push(milliseconds); },
+ });
+ assert.equal(await result.text(), 'asset');
+ assert.deepEqual(delays, [1_000, 2_000]);
+ assert.equal(statuses.length, 0);
+ assert.ok(failures.every((response) => response.bodyUsed));
+ });
+}
+
+test('ripgrep exhausts three attempts before preserving the upstream error', async () => {
+ let attempts = 0;
+ const delays = [];
+ await assert.rejects(fetchReleaseAsset('https://example.invalid/rg', {
+ fetchImpl: async () => { attempts++; return new Response('unavailable', { status: 503 }); },
+ wait: async (milliseconds) => { delays.push(milliseconds); },
+ }), /Download failed 503/);
+ assert.equal(attempts, 3);
+ assert.deepEqual(delays, [1_000, 2_000]);
+});
+
+for (const status of [401, 404]) {
+ test(`ripgrep does not retry HTTP ${status}`, async () => {
+ let attempts = 0;
+ await assert.rejects(fetchReleaseAsset('https://example.invalid/rg', {
+ fetchImpl: async () => { attempts++; return new Response('unavailable', { status }); },
+ wait: async () => { assert.fail('permanent errors must not retry'); },
+ }), new RegExp(`Download failed ${status}`));
+ assert.equal(attempts, 1);
+ });
+}
diff --git a/tools/ripgrep/update.mjs b/tools/ripgrep/update.mjs
index c7da3353ee..16f5d7d1fa 100644
--- a/tools/ripgrep/update.mjs
+++ b/tools/ripgrep/update.mjs
@@ -19,6 +19,7 @@ import os from 'node:os';
import path from 'node:path';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
+import { setTimeout as delay } from 'node:timers/promises';
import { fileURLToPath, pathToFileURL } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -199,15 +200,27 @@ function findAsset(meta, name) {
return asset;
}
+// A transient GitHub asset 5xx should not immediately send CI to a CDN that
+// may not contain this pin. Bound retries; permanent errors still fail normally.
+export async function fetchReleaseAsset(url, { fetchImpl = fetch, wait = delay } = {}) {
+ for (let attempt = 1; ; attempt++) {
+ const res = await fetchImpl(url, { headers: ghHeaders() });
+ if (res.ok) return res;
+ await res.body?.cancel();
+ if (res.status < 500 || res.status >= 600 || attempt >= 3) {
+ throw new Error(`Download failed ${res.status}: ${url}`);
+ }
+ await wait(attempt * 1_000);
+ }
+}
+
async function fetchText(url) {
- const res = await fetch(url, { headers: ghHeaders() });
- if (!res.ok) throw new Error(`Download failed ${res.status}: ${url}`);
+ const res = await fetchReleaseAsset(url);
return await res.text();
}
async function downloadFile(url, destPath) {
- const res = await fetch(url, { headers: ghHeaders() });
- if (!res.ok) throw new Error(`Download failed ${res.status}: ${url}`);
+ const res = await fetchReleaseAsset(url);
if (!res.body) throw new Error(`Download returned no body: ${url}`);
await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(destPath));
}