Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(ios-simulator): keep borrowed worktree protection outside source
JiangJiahao5d30b8b12158
diff --git a/apps/desktop/src/main/__tests__/fixtures/linkedWorktree.ts b/apps/desktop/src/main/__tests__/fixtures/linkedWorktree.tsnew file mode 100644index 0000000000..cc2af83932--- /dev/null+++ b/apps/desktop/src/main/__tests__/fixtures/linkedWorktree.ts@@ -0,0 +1,13 @@+import fs from 'node:fs/promises';+import path from 'node:path';++/** Standard linked-worktree files for filesystem unit tests; no Git subprocess. */+export async function createLinkedWorktreeMetadata(worktree: string): Promise<string> {+ const root = await fs.realpath(worktree);+ const gitDir = path.join(path.dirname(path.dirname(root)), '.git', 'worktrees', path.basename(root));+ await fs.mkdir(gitDir, { recursive: true });+ await fs.writeFile(path.join(root, '.git'), `gitdir: ${gitDir}\n`);+ await fs.writeFile(path.join(gitDir, 'commondir'), '../..\n');+ await fs.writeFile(path.join(gitDir, 'gitdir'), `${path.join(root, '.git')}\n`);+ return path.join(gitDir, 'locked');+}diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.tsindex 1a7c50256b..bdfbda6792 100644--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts@@ -38,6 +38,7 @@ import { inventoryWorktree } from '../worktree/recoveryArchive';import { physicalWorktreeKey } from '../worktree/resourceLock';import { readWorktreeRuntimePaths } from '../worktree/runtimeLeases';import { acquireIOSSimulatorProjectUse } from '../mcp-integrations/ios-simulator-project-source';+import { createLinkedWorktreeMetadata } from './fixtures/linkedWorktree';describe('shared worktree recycling', () => {let meta: WorktreeMeta;@@ -47,7 +48,7 @@ describe('shared worktree recycling', () => {state.userData = '';meta = { sessionId: 'owner', generation: 'generation-one', name: 'one', path: path.join(state.root, 'repo', '.cindy-worktrees', 'one'), baseRepo: path.join(state.root, 'repo'), branch: 'cindy/one', sourceBranch: 'main', createdAt: '2026-09-08T00:00:00Z' };await fs.mkdir(meta.path, { recursive: true });- await fs.writeFile(path.join(meta.path, '.git'), 'gitdir: unused-test-link');+ await createLinkedWorktreeMetadata(meta.path);await fs.writeFile(path.join(meta.path, 'draft.txt'), 'uncommitted contents');state.registry.clear(); state.registry.set(meta.sessionId, meta);state.runtimes.clear();@@ -167,7 +168,6 @@ describe('shared worktree recycling', () => {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!();diff --git a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.tsindex 1c84411097..3b19aba3ac 100644--- a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts@@ -25,7 +25,11 @@ vi.mock('../worktree/worktreeStore', () => ({del: async (id: string) => { state.registry.delete(id); },}));vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ readLocalWorktreeReferences: async () => state.refs }) }));-vi.mock('../worktree/runtimeLeases', () => ({ readWorktreeRuntimePaths: async () => new Set() }));+vi.mock('../worktree/runtimeLeases', async (original) => ({+ ...await original<typeof import('../worktree/runtimeLeases')>(),+ // Model an old owner profile that cannot see the borrower's shared leases.+ readWorktreeRuntimePaths: async () => new Set(),+}));vi.mock('../worktree/gitExec', async (original) => {const actual = await original<typeof import('../worktree/gitExec')>();return { ...actual, gitExec: vi.fn<typeof actual.gitExec>((args, cwd, options) => actual.gitExec(args, cwd, {@@ -33,13 +37,14 @@ vi.mock('../worktree/gitExec', async (original) => {})) };});-import { recycleManagedWorktree } from '../worktree/managedRecycle';+import { checkpointWorktreeForReuse, recycleManagedWorktree } from '../worktree/managedRecycle';import { restoreRecordedWorktree } from '../worktree/restoreRecovery';import { readRecycleRecord, writeRecycleRecord } from '../worktree/recycleJournal';import { captureWorktreeContent } from '../worktree/contentSnapshot';import { GitExecError, gitExec } from '../worktree/gitExec';import { acquireWorktree, releaseWorktree, parkAll } from '../worktree/WorktreePool';import { extractRecoveryArchive } from '../worktree/recoveryArchive';+import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease } from '../worktree/runtimeLeases';const exec = promisify(execFile);describe('worktree recovery with real Git and encrypted archives', () => {@@ -48,7 +53,7 @@ describe('worktree recovery with real Git and encrypted archives', () => {cwd, windowsHide: true, env: { ...process.env, GIT_CONFIG_GLOBAL: path.join(state.root, 'git-global'), GIT_CONFIG_NOSYSTEM: '1' },})).stdout.trim();beforeAll(async () => {- state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-recovery-git-'));+ state.root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-recovery-git-')));repo = path.join(state.root, 'repo');await fs.mkdir(repo);await git(repo, 'init', '-b', 'main');@@ -71,6 +76,22 @@ describe('worktree recovery with real Git and encrypted archives', () => {return meta;};+ it('protects a borrowed source from old recyclers after build scripts clean the worktree', async () => {+ const meta = await createFixture('borrowed-clean');+ const lease = (await acquireWorktreeRuntimeLease('borrower', meta.path, { crossProfile: true }))!;+ try {+ await git(meta.path, 'clean', '-fdx');+ await expect(fs.stat(path.join(meta.path, 'draft.txt'))).rejects.toMatchObject({ code: 'ENOENT' });+ // Old pool reuse and deletion must both stop before changing source.+ await expect(checkpointWorktreeForReuse(meta)).rejects.toThrow('worktree is locked');+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(false);+ await expect(git(repo, 'worktree', 'remove', '--force', meta.path)).rejects.toThrow();+ expect(await fs.readFile(path.join(meta.path, 'tracked.txt'), 'utf8')).toBe('base\n');+ await releaseWorktreeRuntimeLease(lease);+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);+ } finally { await releaseWorktreeRuntimeLease(lease); }+ }, 30_000);+it('restores detached HEAD, staged-only bytes, unstaged files, ignored files and untracked files', async () => {const worktree = path.join(repo, '.cindy-worktrees', 'recover');await git(repo, 'worktree', 'add', '-b', 'cindy/recover', worktree, 'main');diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.tsindex 3cd7241f8c..671d1faf90 100644--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts@@ -15,16 +15,19 @@ vi.mock('../desktopProcessIdentity', async (importOriginal) => ({import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, readWorktreeRuntimePaths, retryPendingWorktreeRuntimeLeaseReleases } from '../worktree/runtimeLeases';import { physicalWorktreeKey, withWorktreeResourceLock } from '../worktree/resourceLock';-import { hasKeepSentinel } from '../worktree/safety';+import { createLinkedWorktreeMetadata } from './fixtures/linkedWorktree';describe('worktree runtime evidence and physical locks', () => {let worktree: string;+ let gitLock: string;+ const hasGitLock = () => fs.stat(gitLock).then(() => true, () => false);const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;beforeEach(async () => {state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-runtime-'));state.userData = '';worktree = path.join(state.root, 'repo', '.cindy-worktrees', 'one');await fs.mkdir(path.join(worktree, 'src'), { recursive: true });+ gitLock = await createLinkedWorktreeMetadata(worktree);await fs.mkdir(path.join(state.root, '.dev-instances'));notify.mockClear();readIdentity.mockReset().mockResolvedValue(null);@@ -132,18 +135,52 @@ 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');+ it.each(['file', 'directory'] as const)('preserves an existing user Git lock %s', async (kind) => {+ const file = gitLock;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);+ expect(await hasGitLock()).toBe(true);if (kind === 'file') expect(await fs.readFile(file, 'utf8')).toBe('user requested retention');else expect(await fs.readdir(file)).toEqual([]);});+ it.each(['missing link', 'malformed link', 'foreign backlink', 'metadata inside source'] as const)(+ 'rejects borrowing with %s before publishing an external Git lock', async (kind) => {+ const link = path.join(worktree, '.git');+ if (kind === 'missing link') await fs.unlink(link);+ else if (kind === 'malformed link') await fs.writeFile(link, 'not a Git worktree');+ else if (kind === 'foreign backlink') {+ await fs.writeFile(path.join(path.dirname(gitLock), 'gitdir'), path.join(state.root, 'other', '.git'));+ } else {+ const gitDir = path.join(worktree, 'metadata', 'worktrees', 'one');+ await fs.mkdir(gitDir, { recursive: true });+ await fs.writeFile(path.join(gitDir, 'commondir'), '../..');+ await fs.writeFile(path.join(gitDir, 'gitdir'), link);+ await fs.writeFile(link, `gitdir: ${gitDir}\n`);+ gitLock = path.join(gitDir, 'locked');+ }+ await expect(acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true })).rejects.toThrow();+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ expect(await hasGitLock()).toBe(false);+ },+ );++ it('accepts relative Git metadata links without creating a keep file in source', async () => {+ const root = await fs.realpath(worktree);+ const gitDir = path.dirname(gitLock);+ const link = path.join(root, '.git');+ await fs.writeFile(link, `gitdir: ${path.relative(root, gitDir)}\n`);+ await fs.writeFile(path.join(gitDir, 'gitdir'), `${path.relative(gitDir, link)}\n`);+ const lease = (await acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true }))!;+ expect(lease.keepSentinel?.file).toBe(await physicalWorktreeKey(gitLock));+ await expect(fs.stat(path.join(worktree, '.worktree-keep'))).rejects.toMatchObject({ code: 'ENOENT' });+ await releaseWorktreeRuntimeLease(lease);+ expect(await hasGitLock()).toBe(false);+ });+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');@@ -152,14 +189,14 @@ describe('worktree runtime evidence and physical locks', () => {expect(second.keepSentinel).toEqual(first.keepSentinel);await releaseWorktreeRuntimeLease(first);await releaseWorktreeRuntimeLease(first);- expect(hasKeepSentinel(worktree)).toBe(true);+ expect(await hasGitLock()).toBe(true);await releaseWorktreeRuntimeLease(second);- expect(hasKeepSentinel(worktree)).toBe(false);+ expect(await hasGitLock()).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' });+ const file = gitLock;+ const content = JSON.stringify({ kind: 'cindy-runtime-lock', 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();@@ -169,8 +206,8 @@ describe('worktree runtime evidence and physical locks', () => {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' });+ const file = gitLock;+ const content = JSON.stringify({ kind: 'cindy-runtime-lock', 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();@@ -181,7 +218,7 @@ describe('worktree runtime evidence and physical locks', () => {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');+ const file = gitLock;if (change === 'edited') await fs.writeFile(file, 'keep my checkout');else {// Keep the old inode alive so a replacement containing identical bytes@@ -190,7 +227,7 @@ describe('worktree runtime evidence and physical locks', () => {await fs.writeFile(file, lease.keepSentinel!.content);}await releaseWorktreeRuntimeLease(lease);- expect(hasKeepSentinel(worktree)).toBe(true);+ expect(await hasGitLock()).toBe(true);expect(await fs.readFile(file, 'utf8')).toBe(change === 'edited' ? 'keep my checkout' : lease.keepSentinel!.content);});@@ -202,44 +239,61 @@ describe('worktree runtime evidence and physical locks', () => {});await releaseWorktreeRuntimeLease(active);await retryPendingWorktreeRuntimeLeaseReleases();- expect(hasKeepSentinel(worktree)).toBe(true);+ expect(await hasGitLock()).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);+ expect(await hasGitLock()).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');+ const sentinel = await physicalWorktreeKey(gitLock);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);+ expect(await hasGitLock()).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');+ const sentinel = lease.keepSentinel!.file!;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 hasGitLock()).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);+ expect(await hasGitLock()).toBe(false);+ await expect(fs.stat(lease.sharedFile!)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(fs.stat(`${lease.sharedFile}.release`)).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('still cleans an owned in-tree marker from an older durable release receipt', async () => {+ const lease = (await acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true }))!;+ const marker = lease.keepSentinel!;+ const oldFile = path.join(worktree, '.worktree-keep');+ await fs.rename(marker.file!, oldFile);+ // Older receipts carried identity and content, with no explicit marker path.+ const keepSentinel = { identity: marker.identity, content: marker.content };+ await fs.writeFile(`${lease.sharedFile}.release`, JSON.stringify({+ version: 1, file: lease.sharedFile, path: lease.physicalPath, keepSentinel,+ }));+ expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(0);+ await expect(fs.stat(oldFile)).rejects.toMatchObject({ code: 'ENOENT' });await expect(fs.stat(lease.sharedFile!)).rejects.toMatchObject({ code: 'ENOENT' });await expect(fs.stat(`${lease.sharedFile}.release`)).rejects.toMatchObject({ code: 'ENOENT' });+ await releaseWorktreeRuntimeLease(lease);});it('cleans its own marker when publishing marker ownership fails', async () => {@@ -253,7 +307,7 @@ describe('worktree runtime evidence and physical locks', () => {});await expect(acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true })).rejects.toMatchObject({ code: 'EIO' });expect(await readWorktreeRuntimePaths()).toEqual(new Set());- expect(hasKeepSentinel(worktree)).toBe(false);+ expect(await hasGitLock()).toBe(false);});it('keeps legacy protection while another shared borrower record is unreadable', async () => {@@ -261,12 +315,12 @@ describe('worktree runtime evidence and physical locks', () => {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 hasGitLock()).toBe(true);expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(1);await releaseWorktreeRuntimeLease(second);- expect(hasKeepSentinel(worktree)).toBe(true);+ expect(await hasGitLock()).toBe(true);expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(0);- expect(hasKeepSentinel(worktree)).toBe(false);+ expect(await hasGitLock()).toBe(false);});it('preserves when another live instance cannot publish runtime evidence', async () => {diff --git a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.tsindex e9a33b63b7..c6939419f6 100644--- a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts@@ -716,9 +716,15 @@ describe('接管陈旧锁', () => {expect(fs.existsSync(lock)).toBe(true);});- it('bounds repeated successful stale takeovers by time and count', async () => {+ it.each([+ { takeoverMs: 100, expectedTakeovers: 3 },+ { takeoverMs: 2_500, expectedTakeovers: 1 },+ ])('bounds repeated successful stale takeovers by time and count ($takeoverMs ms)', async ({ takeoverMs, expectedTakeovers }) => {const lock = path.join(dir, 'lock');await writeStaleStrictLock(lock);+ // Exercise the protocol budget independently of Windows filesystem latency.+ let now = Date.now();+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now);const originalRename = fsp.rename;let takeovers = 0;const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (@@ -728,25 +734,29 @@ describe('接管陈旧锁', () => {const result = await (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {takeovers += 1;+ now += takeoverMs;await writeStaleStrictLock(lock);}return result;}) as typeof fsp.rename);try {- const started = performance.now();+ const started = Date.now();await expect(withCrossProcessLock(lock, { label: 'churn', waitMs: 2_000 }, async (s) => s),).resolves.toEqual({ held: false, reason: 'busy' });- expect(performance.now() - started).toBeLessThan(1_000);- expect(takeovers).toBe(3);+ expect(takeovers).toBe(expectedTakeovers);+ expect(Date.now() - started).toBe(takeoverMs * expectedTakeovers);} finally {spy.mockRestore();+ clock.mockRestore();}});it('publishes after the final stale takeover when the path stays empty', async () => {const lock = path.join(dir, 'lock');await writeStaleStrictLock(lock);+ let now = Date.now();+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now);const originalRename = fsp.rename;let takeovers = 0;const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (@@ -756,6 +766,7 @@ describe('接管陈旧锁', () => {const result = await (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {takeovers += 1;+ now += 100;if (takeovers < 3) await writeStaleStrictLock(lock);}return result;@@ -767,12 +778,15 @@ describe('接管陈旧锁', () => {expect(takeovers).toBe(3);} finally {spy.mockRestore();+ clock.mockRestore();}});it('retries publication after the final takeover when Windows still reports the path busy', async () => {const lock = path.join(dir, 'lock');await writeStaleStrictLock(lock);+ let now = Date.now();+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now);const originalRename = fsp.rename;const originalLink = fsp.link;let takeovers = 0;@@ -784,6 +798,7 @@ describe('接管陈旧锁', () => {const result = await (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {takeovers += 1;+ now += 100;if (takeovers < 3) await writeStaleStrictLock(lock);}return result;@@ -807,6 +822,7 @@ describe('接管陈旧锁', () => {} finally {renameSpy.mockRestore();linkSpy.mockRestore();+ clock.mockRestore();}});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.tsindex eb05659b9a..8a30e84181 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@@ -18,6 +18,7 @@ import path from 'node:path';import { app } from 'electron';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createLinkedWorktreeMetadata } from '../../__tests__/fixtures/linkedWorktree';const { mockFsCp } = vi.hoisted(() => ({ mockFsCp: vi.fn() }));@@ -333,6 +334,7 @@ describe('iOS Simulator host', () => {await mkdir(path.join(taskRoot, 'Demo.xcodeproj'), { recursive: true });await mkdir(path.join(otherTaskRoot, 'Demo.xcodeproj'), { recursive: true });await mkdir(path.join(projectRoot, 'Demo.xcodeproj'), { recursive: true });+ const projectGitLock = await createLinkedWorktreeMetadata(projectRoot);if (mobile) {const mobileRoot = path.join(projectRoot, 'apps', 'mobile');await mkdir(mobileRoot, { recursive: true });@@ -401,7 +403,7 @@ describe('iOS Simulator host', () => {generation: attachedInstance.generation, leaseId: attachedInstance.lease.id,});const route = { instanceId: instance.instanceId, generation: instance.generation, leaseId: instance.lease.id };- return { root, taskRoot, otherTaskRoot, projectRoot, secondDevice, actor, host, context, route, build, inspect, inspectArtifact, installExact, launchExact, validateLaunch, useProfile, close };+ return { root, taskRoot, otherTaskRoot, projectRoot, projectGitLock, secondDevice, actor, host, context, route, build, inspect, inspectArtifact, installExact, launchExact, validateLaunch, useProfile, close };} catch (error) {await close();throw error;@@ -438,7 +440,7 @@ describe('iOS Simulator host', () => {const h = await projectSelectionHarness(true);try {h.validateLaunch.mockImplementationOnce(async () => {- expect((await stat(path.join(h.projectRoot, '.worktree-keep'))).isFile()).toBe(true);+ expect((await stat(h.projectGitLock)).isFile()).toBe(true);return null;});const result = await h.host.callTool('build_app', { ...h.route, projectDir: path.relative(h.taskRoot, h.projectRoot) }, h.context);@@ -448,7 +450,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' });+ await expect(stat(h.projectGitLock)).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));@@ -621,6 +623,7 @@ describe('iOS Simulator host', () => {if (phase === 'replacement') {await fsp.rename(h.projectRoot, `${h.projectRoot}-old`);await mkdir(path.join(h.projectRoot, 'Demo.xcodeproj'), { recursive: true });+ await createLinkedWorktreeMetadata(h.projectRoot);}await h.useProfile('user-data');expect(await h.host.callTool('build_app', { ...h.route, projectDir: h.projectRoot }, h.context)).toMatchObject({ ok: true });@@ -657,12 +660,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);+ expect((await stat(h.projectGitLock)).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' });+ await expect(stat(h.projectGitLock)).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.tsindex 90b6d287f3..e326252a1e 100644--- a/apps/desktop/src/main/worktree/runtimeLeases.ts+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts@@ -37,6 +37,8 @@ const leaseNamePattern = /^\d+-[a-f0-9]{64}\.json$/;const releaseRequestPattern = /^\d+-[a-f0-9]{64}\.json\.release$/;interface RuntimeKeepSentinel {+ /** Older release receipts omit this and refer to the in-tree keep marker. */+ file?: string;content: string;identity: string;}@@ -65,8 +67,8 @@ export async function acquireWorktreeRuntimeLease(// Publish both under the deletion lock. Keep the original profile copy// readable by existing clients sharing this userData.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.+ // Older profiles already check Git's external worktree lock before+ // recycling or pool reset. Build-time git clean cannot remove this file.keepSentinel = await acquireRuntimeKeepSentinel(shared);if (keepSentinel) {// Ownership lives with a real borrower, not merely in a recognizable@@ -102,9 +104,26 @@ async function publishRuntimeLease(sessionId: string, physicalPath: string, direreturn lease;}+/** Validate Git's linked-worktree metadata before writing outside the source. */+async function runtimeGitLockFile(root: string): Promise<string> {+ const link = path.join(root, '.git');+ const linkStat = await fs.lstat(link);+ if (!linkStat.isFile() || linkStat.isSymbolicLink()) throw new Error('project requires a linked Git worktree');+ const match = /^gitdir: (.+)$/.exec((await fs.readFile(link, 'utf8')).trim());+ if (!match) throw new Error('invalid worktree Git link');+ const gitDir = await physicalWorktreeKey(path.resolve(root, match[1]!));+ const common = await physicalWorktreeKey(path.resolve(gitDir, (await fs.readFile(path.join(gitDir, 'commondir'), 'utf8')).trim()));+ const backlink = await physicalWorktreeKey(path.resolve(gitDir, (await fs.readFile(path.join(gitDir, 'gitdir'), 'utf8')).trim()));+ if (path.dirname(gitDir) !== path.join(common, 'worktrees') || backlink !== link+ || gitDir === root || gitDir.startsWith(`${root}${path.sep}`)) {+ throw new Error('worktree Git metadata must belong to the source and remain outside it');+ }+ return path.join(gitDir, 'locked');+}+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() });+ const file = await runtimeGitLockFile(lease.physicalPath);+ const newContent = JSON.stringify({ kind: 'cindy-runtime-lock', version: 1, nonce: randomUUID() });let created = false;try {await fs.writeFile(file, newContent, { flag: 'wx', mode: 0o600 });@@ -112,14 +131,13 @@ async function acquireRuntimeKeepSentinel(lease: WorktreeRuntimeLease): Promise<} 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.+ // Never overwrite a user's existing Git lock, 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}` };+ const marker = { file, 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)) {@@ -127,7 +145,7 @@ async function acquireRuntimeKeepSentinel(lease: WorktreeRuntimeLease): Promise<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+ if (other.path === lease.physicalPath && other.keepSentinel?.file === file && other.keepSentinel?.content === content&& other.keepSentinel?.identity === marker.identity) return marker;} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;@@ -140,7 +158,7 @@ async function acquireRuntimeKeepSentinel(lease: WorktreeRuntimeLease): Promise<async function releaseRuntimeKeepSentinel(lease: WorktreeRuntimeLease): Promise<void> {const marker = lease.keepSentinel;if (!marker) return;- const file = path.join(lease.physicalPath, '.worktree-keep');+ const file = marker.file ?? path.join(lease.physicalPath, '.worktree-keep');try {const identity = await fs.lstat(file);if (!identity.isFile() || identity.isSymbolicLink()@@ -229,7 +247,9 @@ async function retryPendingRuntimeLeaseReleasesIn(directory: string): Promise<nuif (request.version !== 1 || typeof request.file !== 'string' || typeof request.path !== 'string'|| 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'))) {+ || typeof request.keepSentinel.content !== 'string' || typeof request.keepSentinel.identity !== 'string'+ || (request.keepSentinel.file !== undefined && (typeof request.keepSentinel.file !== 'string'+ || !path.isAbsolute(request.keepSentinel.file) || path.basename(request.keepSentinel.file) !== 'locked'))))) {pending++;continue;}diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 7b9d105fb4..5c121494b7 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -71,7 +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` 中保留原文件身份,由现有维护重试 |+| 旧版 worktree 回收器兼容锁 | 验证 linked worktree 的 Git 元数据与反向链接后,在源目录外的 `<commonGitDir>/worktrees/<id>/locked` 创建 Git 标准锁,避免构建中的 `git clean` 删除保护;旧版删除/池化复用已识别此锁。不覆盖用户锁,仅当最后一个共享借用结束且自建文件身份和内容仍匹配时删除。清理失败在共享租约 `.release` 中保留路径及原文件身份,由现有维护重试;旧回执仍按原身份清理 `.worktree-keep` || 跨 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.mdindex d5d4df3e33..4f6c323301 100644--- a/docs/ios-simulator-integration-plan.md+++ b/docs/ios-simulator-integration-plan.md@@ -1034,10 +1034,13 @@ fingerprint 和相对 container 路径;该 fingerprint 不代表 Git revision在发布租约前拒绝构建/启动,避免使用残缺目录或阻挡 owner 恢复。完成的记录或旧目录身份不阻止新目录使用。日志监听启动时登记既有日志,写入新意图前也必须完成登记;共享索引只保存日志位置,不复制状态、不改变原 profile 的日志格式和恢复归属。-兼容尚未读取共享租约的旧版回收方:借用时还在资源锁内创建或沿用 `.worktree-keep`,-旧版删除与池化复用均已识别该哨兵。用户已有或后来修改/替换的标记不会被删除;Host 自建-标记只在最后一个共享借用者结束、文件身份与内容仍匹配时移除。发布失败则不开始源目录-I/O;清理失败通过共享 `.release` 回执重试,异常退出留下的租约继续保护旧版回收路径。+兼容尚未读取共享租约的旧版回收方:借用时还在资源锁内验证 linked worktree 的 Git+元数据和反向链接,并创建或沿用源目录外的 `<commonGitDir>/worktrees/<id>/locked`。+旧版删除与池化复用均已检查该 Git 标准锁;构建脚本在源目录内执行 `git clean -fdx`+不会移除保护。用户已有或后来修改/替换的锁不会被删除;Host 自建锁只在最后一个共享+借用者结束、文件身份与内容仍匹配时移除。元数据不匹配、位于源目录内或锁发布失败时,+不开始源目录 I/O;清理失败通过共享 `.release` 回执重试,旧回执仍按原身份清理旧标记,+异常退出留下的租约继续保护旧版回收路径。日志预检只读取已登记 profile 的原始日志;profile 内租约副本保留原读取协议。任务 A 结束时排空自己的操作,不因其构建了 B 就把 B 加入 A 的目录删除范围。这仍是工程选择与目录边界校验,不是对 Xcode build scripts 的文件系统沙箱。