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(desktop): make worktree recycling durable and reference-aware

DavidShene8676a1c7b14
diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
new file mode 100644
index 0000000000..7fc9a37dc6
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts
@@ -0,0 +1,222 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { WorktreeMeta } from '../worktree/types';
+import type { LocalWorktreeReference } from '../localDb/worker/worktreeReferences';
+
+const state = vi.hoisted(() => ({ root: '', refs: [] as LocalWorktreeReference[], runtimes: new Set<string>(), registry: new Map<string, WorktreeMeta>() }));
+const snapshot = vi.hoisted(() => vi.fn());
+const baselineMatches = vi.hoisted(() => vi.fn());
+const archive = vi.hoisted(() => vi.fn());
+const query = vi.hoisted(() => vi.fn());
+const git = vi.hoisted(() => vi.fn());
+
+vi.mock('electron', () => ({ app: { getPath: () => state.root } }));
+vi.mock('../worktree/worktreeStore', () => ({
+ get: (id: string) => state.registry.get(id) ?? null,
+ getAll: () => [...state.registry.values()], getAllPaths: () => [...state.registry.values()].map((m) => m.path),
+ set: async (id: string, meta: WorktreeMeta) => { state.registry.set(id, meta); },
+ del: async (id: string) => { state.registry.delete(id); },
+}));
+vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ readLocalWorktreeReferences: query }) }));
+vi.mock('../worktree/runtimeLeases', () => ({ readWorktreeRuntimePaths: async () => state.runtimes }));
+vi.mock('../worktree/contentSnapshot', () => ({ captureWorktreeContent: snapshot, worktreeContentBaselineMatches: baselineMatches }));
+vi.mock('../worktree/gitExec', () => ({ gitExec: git }));
+vi.mock('../worktree/recoveryArchive', async (original) => ({
+ ...await original<typeof import('../worktree/recoveryArchive')>(),
+ createRecoveryArchive: archive, verifyRecoveryArchive: async () => {},
+}));
+
+import { recycleManagedWorktree, requestWorktreeRecycle } from '../worktree/managedRecycle';
+import { readRecycleRecord } from '../worktree/recycleJournal';
+import { inventoryWorktree } from '../worktree/recoveryArchive';
+import { physicalWorktreeKey } from '../worktree/resourceLock';
+
+describe('shared worktree recycling', () => {
+ let meta: WorktreeMeta;
+ let removable: boolean;
+ beforeEach(async () => {
+ state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-recycle-test-'));
+ 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 fs.writeFile(path.join(meta.path, 'draft.txt'), 'uncommitted contents');
+ state.registry.clear(); state.registry.set(meta.sessionId, meta);
+ state.runtimes.clear();
+ state.refs = [{ id: meta.sessionId, status: 'archived', source: 'desktop', workingDir: meta.path, worktreePath: meta.path, currentDatabase: true }];
+ removable = true;
+ query.mockReset().mockImplementation(async () => state.refs);
+ snapshot.mockReset().mockResolvedValue({ head: 'actual-head', tree: 'file-tree', indexTree: 'index-tree', commit: 'saved-commit', ref: 'saved-ref' });
+ baselineMatches.mockReset().mockResolvedValue(true);
+ archive.mockReset().mockImplementation(async () => ({ file: 'archive.tar.gz.enc', files: await inventoryWorktree(meta.path) }));
+ git.mockReset().mockImplementation(async (args: string[]) => {
+ if (args.includes('--show-toplevel')) return { stdout: meta.path };
+ if (args.includes('--git-common-dir')) return { stdout: path.join(meta.baseRepo, '.git') };
+ if (args.includes('--git-dir')) return { stdout: path.join(meta.baseRepo, '.git', 'worktrees', 'one') };
+ if (args.includes('remove')) await fs.rm(meta.path, { recursive: true });
+ return { stdout: '' };
+ });
+ });
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await fs.rm(state.root, { recursive: true, force: true });
+ });
+ const recycle = () => recycleManagedWorktree(meta, { canRemove: async () => removable });
+
+ it('keeps content recoverable and drops registration only after the directory is gone', async () => {
+ const order: string[] = [];
+ archive.mockImplementation(async () => { order.push('archive'); return { files: await inventoryWorktree(meta.path) }; });
+ snapshot.mockImplementation(async () => { order.push('snapshot'); return { head: 'head', tree: 'tree', indexTree: 'index', commit: 'commit', ref: 'ref' }; });
+ expect(await recycle()).toBe(true);
+ expect(order).toEqual(['archive', 'snapshot']);
+ expect(state.registry.has(meta.sessionId)).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.phase).toBe('removed');
+ });
+ it.each(['active', null, 'unknown'])('protects a %s reference in another local database', async (status) => {
+ state.refs.push({ ...state.refs[0], id: 'borrower', status, currentDatabase: false });
+ expect(await recycle()).toBe(false);
+ expect(snapshot).not.toHaveBeenCalled();
+ expect(state.registry.has(meta.sessionId)).toBe(true);
+ });
+ it('does not exclude an identical task id in another database', async () => {
+ state.refs.push({ ...state.refs[0], status: 'active', currentDatabase: false });
+ expect(await recycle()).toBe(false);
+ });
+ it('terminal references release the shared resource once all runtimes have stopped', async () => {
+ state.refs.push({ ...state.refs[0], id: 'borrower', currentDatabase: false });
+ expect(await recycle()).toBe(true);
+ });
+ it('protects a terminal task with an active runtime lease', async () => {
+ state.runtimes.add(await physicalWorktreeKey(meta.path));
+ expect(await recycle()).toBe(false);
+ expect(archive).not.toHaveBeenCalled();
+ });
+ 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);
+ });
+ it('preserves when any local reference source is unreadable', async () => {
+ query.mockRejectedValue(new Error('database locked'));
+ expect(await recycle()).toBe(false);
+ expect(archive).not.toHaveBeenCalled();
+ });
+ it('keeps the sentinel outside the snapshot/removal flow', async () => {
+ await fs.writeFile(path.join(meta.path, '.worktree-keep'), '');
+ expect(await recycle()).toBe(false);
+ expect(archive).not.toHaveBeenCalled();
+ });
+ it('never snapshots the parent repository when .git is missing', async () => {
+ await fs.rm(path.join(meta.path, '.git'));
+ expect(await recycle()).toBe(false);
+ expect(snapshot).not.toHaveBeenCalled();
+ });
+ it('keeps files and registration when the archive cannot be encrypted', async () => {
+ archive.mockRejectedValue(new Error('key store unavailable'));
+ expect(await recycle()).toBe(false);
+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('uncommitted contents');
+ expect(state.registry.has(meta.sessionId)).toBe(true);
+ });
+ it('keeps the live index/files when Git snapshot creation fails', async () => {
+ snapshot.mockRejectedValue(new Error('unmerged index'));
+ expect(await recycle()).toBe(false);
+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('uncommitted contents');
+ });
+ it('cancels without reapplying a stash when the task becomes active during snapshotting', async () => {
+ snapshot.mockImplementation(async () => { removable = false; return { head: 'head' }; });
+ expect(await recycle()).toBe(false);
+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('uncommitted contents');
+ expect(git.mock.calls.some(([args]) => args.includes('stash'))).toBe(false);
+ });
+ it('rechecks a newly active borrower after the snapshot', async () => {
+ snapshot.mockImplementation(async () => { state.refs.push({ ...state.refs[0], id: 'new', status: 'active' }); return { head: 'head' }; });
+ expect(await recycle()).toBe(false);
+ });
+ it('preserves edits made during snapshot creation', async () => {
+ snapshot.mockImplementation(async () => { await fs.writeFile(path.join(meta.path, 'new.txt'), 'new work'); return { head: 'head' }; });
+ expect(await recycle()).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.reason).toBe('files-changed');
+ });
+ it('supports a changed branch or detached HEAD by recording the actual content baseline', async () => {
+ meta.branch = 'cindy/old-name';
+ expect(await recycle()).toBe(true);
+ expect((await readRecycleRecord(meta.path))?.snapshot?.head).toBe('actual-head');
+ });
+ it('records the request before removal and survives re-reading the journal', async () => {
+ await requestWorktreeRecycle(meta.sessionId);
+ expect((await readRecycleRecord(meta.path))?.phase).toBe('pending');
+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('uncommitted contents');
+ });
+ it('old requests cannot replace a newer generation journal', async () => {
+ const old = meta;
+ meta = { ...meta, generation: 'successor' }; state.registry.set(meta.sessionId, meta);
+ await requestWorktreeRecycle(meta.sessionId);
+ expect(await recycleManagedWorktree(old, { canRemove: async () => true })).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.generation).toBe('successor');
+ });
+ it('a recreated directory at the same path does not satisfy an old request', async () => {
+ await requestWorktreeRecycle(meta.sessionId);
+ await fs.rename(meta.path, `${meta.path}-old`);
+ await fs.mkdir(meta.path);
+ await fs.writeFile(path.join(meta.path, 'replacement.txt'), 'keep');
+ expect(await recycle()).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.reason).toBe('directory-replaced');
+ });
+ it('partial EBUSY deletion retains evidence and retries only unchanged surviving bytes', async () => {
+ const rm = fs.rm;
+ const fail = vi.spyOn(fs, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === meta.path) throw Object.assign(new Error('locked'), { code: 'EBUSY' });
+ return rm(target, options);
+ });
+ git.mockImplementation(async (args: string[]) => {
+ if (args.includes('--show-toplevel')) return { stdout: meta.path };
+ if (args.includes('--git-common-dir')) return { stdout: path.join(meta.baseRepo, '.git') };
+ if (args.includes('--git-dir')) return { stdout: path.join(meta.baseRepo, '.git', 'worktrees', 'one') };
+ if (args.includes('remove')) { await rm(path.join(meta.path, '.git'), { force: true }); throw new Error('EBUSY'); }
+ return { stdout: '' };
+ });
+ expect(await recycle()).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.phase).toBe('removing');
+ expect(state.registry.has(meta.sessionId)).toBe(true);
+ fail.mockRestore();
+ expect(await recycle()).toBe(true);
+ expect(snapshot).toHaveBeenCalledTimes(1);
+ });
+ it('does not report success when Git returns success but the directory remains', async () => {
+ const originalGit = git.getMockImplementation()!;
+ git.mockImplementation(async (args: string[]) => args.includes('remove') ? { stdout: '' } : originalGit(args));
+ expect(await recycle()).toBe(false);
+ expect(state.registry.has(meta.sessionId)).toBe(true);
+ expect((await readRecycleRecord(meta.path))?.reason).toBe('directory-still-present');
+ });
+ it('retains a new HEAD or staged change arriving after snapshotting', async () => {
+ baselineMatches.mockResolvedValue(false);
+ expect(await recycle()).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.reason).toBe('git-baseline-changed');
+ expect(git.mock.calls.some(([args]) => args.includes('remove'))).toBe(false);
+ });
+ it('persists a shared owner request before the last borrower status write', async () => {
+ await requestWorktreeRecycle('borrower', [meta.path]);
+ expect((await readRecycleRecord(meta.path))?.meta.sessionId).toBe(meta.sessionId);
+ });
+ it('protects an unknown registration sharing the physical directory', async () => {
+ state.registry.set('unknown', { ...meta, sessionId: 'unknown' });
+ expect(await recycle()).toBe(false);
+ expect(archive).not.toHaveBeenCalled();
+ });
+ it('preserves an externally locked Git worktree', async () => {
+ const gitDir = path.join(meta.baseRepo, '.git', 'worktrees', 'one');
+ await fs.mkdir(gitDir, { recursive: true });
+ await fs.writeFile(path.join(gitDir, 'locked'), 'external use');
+ expect(await recycle()).toBe(false);
+ expect(archive).not.toHaveBeenCalled();
+ });
+ it('rejects a Git link pointing at another repository', async () => {
+ const originalGit = git.getMockImplementation()!;
+ git.mockImplementation(async (args: string[], cwd: string) => args.includes('--git-common-dir') && cwd === meta.path
+ ? { stdout: path.join(state.root, 'different-repo', '.git') } : originalGit(args, cwd));
+ expect(await recycle()).toBe(false);
+ expect(archive).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index 2a10b3ff4d..46c4cedff1 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -33,6 +33,8 @@ const h = vi.hoisted(() => ({
recycleWorktreeForRemovedSession: vi.fn(),
isOwnerScopeCurrent: vi.fn(),
drizzle: {},
+ readBindings: vi.fn(),
+ requestRecycle: vi.fn(),
userDataPath: '',
agentIslandService: {
handleSessionMetadataPatch: vi.fn(),
@@ -79,6 +81,7 @@ vi.mock('../worktree/sessionRemovalRecycle.js', () => ({
hasRegisteredWorktreeForSession: h.hasRegisteredWorktreeForSession,
recycleWorktreeForRemovedSession: h.recycleWorktreeForRemovedSession,
}));
+vi.mock('../worktree/managedRecycle', () => ({ requestWorktreeRecycle: h.requestRecycle }));
import {
recycleSessionWorktreeForStatusChange,
setSessionRemovalCancelOperations,
@@ -100,6 +103,9 @@ beforeEach(() => {
h.hasRegisteredWorktreeForSession.mockReturnValue(true);
h.recycleWorktreeForRemovedSession.mockResolvedValue(undefined);
h.isOwnerScopeCurrent.mockReturnValue(true);
+ h.readBindings.mockReset().mockResolvedValue([]);
+ h.requestRecycle.mockReset().mockResolvedValue(undefined);
+ Object.assign(h.drizzle, { select: () => ({ from: () => ({ where: () => ({ limit: h.readBindings }) }) }) });
setSessionRemovalCancelOperations(h.cancelSessionOperations);
setSessionRemovalCleanup(h.cleanupRemovedSession);
setSessionRuntimeCleanup(h.runtimeCleanup);
@@ -115,6 +121,31 @@ afterEach(() => {
});
describe('setSessionsStatusInDb', () => {
+ it('persists shared resource intent before the terminal transaction', async () => {
+ const worktree = path.join(h.userDataPath, 'repo', '.cindy-worktrees', 'one');
+ h.readBindings.mockResolvedValue([{ workingDir: path.join(worktree, 'src'), worktreePath: null, remoteHostId: null }]);
+ const order: string[] = [];
+ h.requestRecycle.mockImplementation(async (_id, resources) => {
+ expect(resources).toEqual([worktree]);
+ order.push('request');
+ });
+ h.tx.mockImplementationOnce(async () => { order.push('status'); return []; });
+ await setSessionsStatusInDb(['borrower'], 'archived');
+ expect(order).toEqual(['request', 'status']);
+ });
+
+ it('preserves task status when recovery intent cannot be persisted', async () => {
+ h.requestRecycle.mockRejectedValue(new Error('private internal path'));
+ await expect(setSessionsStatusInDb(['owner'], 'archived')).rejects.toThrow('PRECONDITION_FAILED');
+ expect(h.tx).not.toHaveBeenCalled();
+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();
+ });
+
+ it('does not treat an unreadable reference query as an empty binding', async () => {
+ h.readBindings.mockRejectedValue(new Error('database unavailable'));
+ await expect(setSessionsStatusInDb(['owner'], 'archived')).rejects.toThrow('PRECONDITION_FAILED');
+ expect(h.tx).not.toHaveBeenCalled();
+ });
it('runs one sessions.setStatus tx and broadcasts per session after commit', async () => {
h.tx.mockResolvedValueOnce([
{
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
index a2d9f7751c..9deb9d757f 100644
--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
@@ -1,3 +1,9 @@
+// Normal archive/deletion coverage moved to managedWorktreeRecycle.test.ts:
+// non-mutating content snapshots replace the former stash/reapply contract.
+vi.mock('../worktree/runtimeLeases', () => ({
+ readWorktreeRuntimePaths: async () => new Set(),
+ acquireWorktreeRuntimeLease: async () => {}, releaseWorktreeRuntimeLease: async () => {},
+}));
/**
* removeWorktreeForSession / discardPrecreatedWorktree 删除守卫回归:
* - live-ref 守卫:其它 live 会话仍引用路径 → 保留;终态引用需确认 runtime 已关闭
@@ -84,6 +90,10 @@ vi.mock('../worktree/worktreeStore', () => ({
vi.mock('../localDb/client/current', () => ({
getDbClient: () => ({
+ readLocalWorktreeReferences: async () => {
+ if (liveSessionLookupError) throw liveSessionLookupError;
+ return liveSessionRows.map((row) => ({ ...row, source: 'desktop', currentDatabase: true }));
+ },
drizzle: {
select: () => ({
from: () => ({
@@ -158,18 +168,13 @@ describe('removeWorktreeForSession', () => {
expect(gitExecMock).not.toHaveBeenCalled();
});
- it('reads and recycles a historical auto-* worktree without renaming it', async () => {
- const meta = makeMeta('legacy-auto', 'auto-abc123');
+ it('a no-options compensation call cannot remove a registered active task', async () => {
+ const meta = makeMeta('active');
storeMap.set(meta.sessionId, meta);
-
- expect(manager.getForSession(meta.sessionId)).toEqual(meta);
+ liveSessionRows.push({ id: meta.sessionId, status: 'active', workingDir: meta.path, worktreePath: meta.path });
await manager.removeWorktreeForSession(meta.sessionId);
-
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has(meta.sessionId)).toBe(false);
+ expect(gitExecMock.mock.calls.some(([args]) => args.includes('remove'))).toBe(false);
+ expect(storeMap.get(meta.sessionId)).toEqual(meta);
});
it('suggestName reserves current and legacy names from local and origin branches', async () => {
@@ -267,554 +272,6 @@ describe('removeWorktreeForSession', () => {
);
});
- it('preserves worktree still referenced by another live session', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionRows.push({
- id: 'other',
- status: 'active',
- workingDir: meta.path,
- worktreePath: null,
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('archived session references block recycle without runtime observer', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionRows.push({
- id: 'other',
- status: 'archived',
- workingDir: meta.path,
- worktreePath: null,
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('deleted session references do not block recycle without runtime observer', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionRows.push({
- id: 'other',
- status: 'deleted',
- workingDir: meta.path,
- worktreePath: null,
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(false);
- });
-
- it('terminal session reference still blocks when its runtime is alive', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionRows.push({
- id: 'other',
- status: 'archived',
- workingDir: meta.path,
- worktreePath: null,
- });
-
- await manager.removeWorktreeForSession('s1', {
- isSessionRuntimeAlive: (sessionId) => sessionId === 'other',
- });
-
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it.each(['archived', 'deleted'])(
- '%s session reference stops blocking after its runtime is closed',
- async (status) => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionRows.push({ id: 'other', status, workingDir: meta.path, worktreePath: null });
-
- await manager.removeWorktreeForSession('s1', {
- isSessionRuntimeAlive: () => false,
- });
-
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(false);
- },
- );
-
- it.each([
- ['NULL', null],
- ['unknown', 'paused'],
- ])('%s session status conservatively keeps its reference live', async (_label, status) => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionRows.push({ id: 'other', status, workingDir: meta.path, worktreePath: null });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('preserves a clean worktree whose attached branch differs from Store metadata', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- gitExecMock.mockImplementation(async (args: string[]) => {
- if (args[0] === 'symbolic-ref') {
- return { stdout: 'refs/heads/feature/manual-switch\n', stderr: '' };
- }
- return { stdout: '', stderr: '' };
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
- expect(autoStashMock).not.toHaveBeenCalled();
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('preserves a dirty worktree before snapshotting when its branch changed', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValue(true);
- gitExecMock.mockImplementation(async (args: string[]) => {
- if (args[0] === 'symbolic-ref') {
- return { stdout: 'refs/heads/feature/manual-switch\n', stderr: '' };
- }
- return { stdout: '', stderr: '' };
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
- expect(autoStashMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('preserves detached or unreadable HEAD state', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- gitExecMock.mockImplementation(async (args: string[]) => {
- if (args[0] === 'symbolic-ref') throw new Error('detached HEAD');
- return { stdout: '', stderr: '' };
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
- expect(autoStashMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('preserves a worktree whose registered branch is outside its managed candidates', async () => {
- const meta = { ...makeMeta('s1'), branch: 'feature/manual-switch' };
- storeMap.set('s1', meta);
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).not.toHaveBeenCalled();
- expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
- expect(autoStashMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('owning session row does not block its own recycle (archived owner)', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- // owning session 自己的路径必须被排除,否则其终态回收永远无法推进
- liveSessionRows.push({
- id: 's1',
- status: 'archived',
- workingDir: null,
- worktreePath: meta.path,
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(false);
- });
-
- it('live-ref lookup failure → conservative preserve', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionLookupError = new Error('db closed');
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('dirty + stash failure → preserve', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValue(true);
- autoStashMock.mockResolvedValue(false);
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('changed local include files → preserve before dirty/stash/remove', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- changedIncludeFilesMock.mockResolvedValue([{ relpath: '.env', reason: 'content-differs' }]);
- isWorktreeDirtyMock.mockResolvedValue(true);
-
- await manager.removeWorktreeForSession('s1');
-
- expect(changedIncludeFilesMock).toHaveBeenCalledWith(BASE_REPO, meta.path);
- expect(isWorktreeDirtyMock).not.toHaveBeenCalled();
- expect(autoStashMock).not.toHaveBeenCalled();
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('dirty + stash success → removed', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValue(true);
- autoStashMock.mockResolvedValue(true);
-
- await manager.removeWorktreeForSession('s1');
-
- expect(autoStashMock).toHaveBeenCalledWith(meta.path, 's1');
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(false);
- });
-
- it('rechecks removal guard after snapshot and restores content if session became active', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValue(true);
- autoStashMock.mockResolvedValue(true);
- const canRemove = vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false);
-
- await manager.removeWorktreeForSession('s1', { canRemove });
-
- expect(canRemove).toHaveBeenCalledTimes(2);
- expect(autoStashMock).toHaveBeenCalledWith(meta.path, 's1');
- expect(restoreAutoStashMock).toHaveBeenCalledWith(meta.path, 's1');
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(true);
- expect(storeSetMock).toHaveBeenCalledWith('s1', meta);
- });
-
- it('rechecks borrower references before removing a clean owner worktree', async () => {
- const meta = makeMeta('owner');
- storeMap.set('owner', meta);
- const borrower = {
- id: 'borrower',
- status: 'archived',
- workingDir: meta.path,
- worktreePath: meta.path,
- };
- liveSessionRows.push(borrower);
- const isSessionRuntimeAlive = vi.fn(() => false);
- const canRemove = vi.fn().mockImplementation(async () => {
- if (canRemove.mock.calls.length === 2) borrower.status = 'active';
- return true;
- });
-
- await manager.removeWorktreeForSession('owner', { canRemove, isSessionRuntimeAlive });
-
- expect(canRemove).toHaveBeenCalledTimes(2);
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('owner')).toBe(true);
- });
-
- it('restores a dirty owner snapshot when a borrower becomes active before removal', async () => {
- const meta = makeMeta('owner');
- storeMap.set('owner', meta);
- isWorktreeDirtyMock.mockResolvedValue(true);
- const borrower = {
- id: 'borrower',
- status: 'archived',
- workingDir: meta.path,
- worktreePath: meta.path,
- };
- liveSessionRows.push(borrower);
- const isSessionRuntimeAlive = vi.fn(() => false);
- const canRemove = vi.fn().mockImplementation(async () => {
- if (canRemove.mock.calls.length === 2) borrower.status = 'active';
- return true;
- });
-
- await manager.removeWorktreeForSession('owner', { canRemove, isSessionRuntimeAlive });
-
- expect(canRemove).toHaveBeenCalledTimes(2);
- expect(autoStashMock).toHaveBeenCalledWith(meta.path, 'owner');
- expect(restoreAutoStashMock).toHaveBeenCalledWith(meta.path, 'owner');
- expect(gitExecMock).not.toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('owner')).toBe(true);
- expect(storeSetMock).toHaveBeenCalledWith('owner', meta);
- });
-
- it('keeps a preserved worktree unregistered when cancelled snapshot reapply fails', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValue(true);
- autoStashMock.mockResolvedValue(true);
- restoreAutoStashMock.mockResolvedValue(false);
- const canRemove = vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false);
-
- await manager.removeWorktreeForSession('s1', { canRemove });
-
- expect(restoreAutoStashMock).toHaveBeenCalledWith(meta.path, 's1');
- expect(storeSetMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(false);
- });
-
- it('serializes cancelled-recycle reapply before a SEND restore mutation', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValue(true);
- autoStashMock.mockResolvedValue(true);
- const canRemove = vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false);
- let releaseReapply!: () => void;
- restoreAutoStashMock.mockImplementationOnce(
- () =>
- new Promise<boolean>((resolve) => {
- releaseReapply = () => resolve(true);
- }),
- );
-
- const removal = manager.removeWorktreeForSession('s1', { canRemove });
- await vi.waitFor(() => {
- expect(restoreAutoStashMock).toHaveBeenCalledWith(meta.path, 's1');
- });
-
- let sendRestoreStarted = false;
- const sendRestore = withWorktreeRestoreMutation('s1', async () => {
- sendRestoreStarted = true;
- });
- await Promise.resolve();
- expect(sendRestoreStarted).toBe(false);
-
- releaseReapply();
- await Promise.all([removal, sendRestore]);
- expect(sendRestoreStarted).toBe(true);
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('reapplies and re-registers a snapshot when worktree removal fails', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValue(true);
- autoStashMock.mockResolvedValue(true);
- gitExecMock.mockImplementation(async (args: string[]) => {
- if (args[0] === 'symbolic-ref') {
- return { stdout: `refs/heads/${meta.branch}\n`, stderr: '' };
- }
- if (args[0] === 'worktree' && args[1] === 'remove') {
- throw new Error('worktree locked');
- }
- return { stdout: '', stderr: '' };
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(restoreAutoStashMock).toHaveBeenCalledWith(meta.path, 's1');
- expect(storeSetMock).toHaveBeenCalledWith('s1', meta);
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('preserves worktree containing another live session cwd', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionRows.push({
- id: 'other',
- status: 'active',
- workingDir: path.join(meta.path, 'packages', 'app'),
- worktreePath: null,
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- });
-
- it('.worktree-keep sentinel → preserved unconditionally (before dirty/stash)', async () => {
- // 哨兵检查走真实 fs,用 tmp 目录构造
- const tmpRoot = fsSync.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-sentinel-'));
- try {
- const base = path.join(tmpRoot, 'repo');
- const wt = path.join(base, '.xdt-worktrees', 's1');
- fsSync.mkdirSync(wt, { recursive: true });
- fsSync.writeFileSync(path.join(wt, '.worktree-keep'), '');
- const meta: WorktreeMeta = {
- sessionId: 's1',
- name: 's1',
- path: wt,
- baseRepo: base,
- branch: 'xdt/s1',
- sourceBranch: 'main',
- createdAt: '2026-07-01T00:00:00.000Z',
- };
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValue(true); // dirty 也不该走到 stash
-
- await manager.removeWorktreeForSession('s1');
-
- expect(autoStashMock).not.toHaveBeenCalled();
- expect(gitExecMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
- } finally {
- fsSync.rmSync(tmpRoot, { recursive: true, force: true });
- }
- });
-
- it('clean + unreferenced → removed and store entry dropped', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- liveSessionRows.push({
- id: 'other',
- status: 'active',
- workingDir: '/somewhere/else',
- worktreePath: null,
- });
-
- await manager.removeWorktreeForSession('s1');
-
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(storeMap.has('s1')).toBe(false);
- });
-
- it('clean and dirty removal do not clear snapshot refs directly', async () => {
- // snapshot ref 的清理由 restore 成功 apply 后负责;删除重试不能清掉尚未恢复的脏内容。
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
-
- await manager.removeWorktreeForSession('s1');
- expect(clearSnapshotRefMock).not.toHaveBeenCalled();
-
- clearSnapshotRefMock.mockClear();
- const meta2 = makeMeta('s2');
- storeMap.set('s2', meta2);
- isWorktreeDirtyMock.mockResolvedValue(true);
- autoStashMock.mockResolvedValue(true);
-
- await manager.removeWorktreeForSession('s2');
- expect(clearSnapshotRefMock).not.toHaveBeenCalled();
- });
-
- it('does not clear a snapshot during failed-then-retried removal', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock
- .mockResolvedValueOnce(true)
- .mockResolvedValueOnce(false)
- .mockResolvedValueOnce(false);
- autoStashMock.mockResolvedValue(true);
-
- let removeAttempts = 0;
- gitExecMock.mockImplementation(async (args: string[]) => {
- if (args[0] === 'symbolic-ref') {
- return { stdout: `refs/heads/${meta.branch}\n`, stderr: '' };
- }
- if (args[0] === 'worktree' && args[1] === 'remove') {
- removeAttempts += 1;
- if (removeAttempts < 3) throw new Error('locked');
- }
- return { stdout: '', stderr: '' };
- });
-
- await manager.removeWorktreeForSession('s1');
- expect(clearSnapshotRefMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
-
- await manager.removeWorktreeForSession('s1');
- expect(clearSnapshotRefMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(true);
-
- await manager.removeWorktreeForSession('s1');
- expect(clearSnapshotRefMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(false);
- });
-
- it('serializes duplicate recycle for the same session so a clean follow-up cannot clear the new snapshot', async () => {
- const meta = makeMeta('s1');
- storeMap.set('s1', meta);
- isWorktreeDirtyMock.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
-
- let releaseStash!: () => void;
- autoStashMock.mockImplementationOnce(
- () =>
- new Promise<boolean>((resolve) => {
- releaseStash = () => resolve(true);
- }),
- );
-
- const first = manager.removeWorktreeForSession('s1');
- const second = manager.removeWorktreeForSession('s1');
- await vi.waitFor(() => {
- expect(autoStashMock).toHaveBeenCalledWith(meta.path, 's1');
- });
-
- releaseStash();
- await Promise.all([first, second]);
-
- expect(
- gitExecMock.mock.calls.filter(
- ([args]) => Array.isArray(args) && args[0] === 'worktree' && args[1] === 'remove',
- ),
- ).toHaveLength(1);
- expect(gitExecMock).toHaveBeenCalledWith(
- ['worktree', 'remove', '--force', meta.path],
- BASE_REPO,
- );
- expect(clearSnapshotRefMock).not.toHaveBeenCalled();
- expect(storeMap.has('s1')).toBe(false);
- });
-
it('discard pre-created: absent and path mismatch are non-destructive', async () => {
await expect(
manager.discardPrecreatedWorktree('missing', '/repo/.xdt-worktrees/missing'),
@@ -1029,6 +486,13 @@ describe('removeWorktreeForSession', () => {
const worktreePath = path.join(base, '.xdt-worktrees', 's1');
const quarantinePath = `${worktreePath}.xdt-removing-crashed`;
fsSync.mkdirSync(quarantinePath, { recursive: true });
+ const originalGit = gitExecMock.getMockImplementation()!;
+ gitExecMock.mockImplementation(async (args, cwd) => {
+ if (args[0] === 'worktree' && args[1] === 'remove' && args[2] === quarantinePath) {
+ fsSync.rmSync(quarantinePath, { recursive: true });
+ }
+ return originalGit(args, cwd);
+ });
const meta: WorktreeMeta = {
...makeMeta('s1'),
baseRepo: base,
@@ -1099,13 +563,13 @@ describe('removeWorktreeForSession', () => {
it('defers safe.directory cleanup to the store when the global lock is not acquired', async () => {
crossProcessLockMock.mockImplementation(
- (_lockPath: string, _opts: unknown, task: (status: unknown) => Promise<unknown>) =>
- task({ held: false, reason: 'busy' }),
+ (_lockPath: string, opts: { label: string }, task: (status: unknown) => Promise<unknown>) =>
+ task(opts.label === 'worktree-resource' ? { held: true } : { held: false, reason: 'busy' }),
);
const meta = makeMeta('s1');
storeMap.set('s1', meta);
- await manager.removeWorktreeForSession('s1');
+ await manager.removeWorktreeForSession('s1', { preserveDirty: true });
// 目录已删、store.del 已执行; 拿不到锁时不得做无锁 --unset-all, 而是落盘待下次启动补清
expect(
diff --git a/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts b/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
index 97c9d756b8..6226b9ed69 100644
--- a/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreePoolSafety.test.ts
@@ -1,3 +1,15 @@
+const checkpointMock = vi.hoisted(() => vi.fn());
+const recyclePoolMock = vi.hoisted(() => vi.fn());
+vi.mock('../worktree/managedRecycle', () => ({
+ checkpointWorktreeForReuse: checkpointMock,
+ recycleManagedWorktree: recyclePoolMock,
+}));
+vi.mock('../worktree/legacyRuntimeGuard', () => ({
+ withLegacyWorktreeRuntimeGuard: (task: (isHeld: () => boolean) => Promise<unknown>) => task(() => true),
+}));
+vi.mock('../worktree/runtimeLeases', () => ({
+ readWorktreeRuntimePaths: async () => new Set(liveSessionRows.filter((row) => row.status === 'archived').flatMap((row) => [row.workingDir, row.worktreePath].filter(Boolean))),
+}));
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import path from 'node:path';
import fsSync from 'node:fs';
@@ -32,7 +44,7 @@ vi.mock('../worktree/worktreeStore', () => ({
get: (sessionId: string) => storeMap.get(sessionId) ?? null,
getAll: () => [...storeMap.values()],
getAllPaths: () => [...storeMap.values()].map((m) => m.path),
- set: vi.fn(),
+ set: async (id: string, meta: WorktreeMeta) => { storeMap.set(id, meta); },
del: (sessionId: string) => storeMap.delete(sessionId),
}));
@@ -44,6 +56,15 @@ vi.mock('../worktree/WorktreeManager', () => ({
vi.mock('../localDb/client/current', () => ({
getDbClient: () => ({
+ readLocalWorktreeReferences: async () => {
+ liveSessionQueryCount += 1;
+ if (liveSessionLookupError) throw liveSessionLookupError;
+ return [
+ ...liveSessionRows.map((row) => ({ ...row, source: 'desktop', currentDatabase: true })),
+ ...[...storeMap.values()].filter((meta) => !liveSessionRows.some((row) => row.id === meta.sessionId))
+ .map((meta) => ({ id: meta.sessionId, status: 'deleted', source: 'desktop', currentDatabase: true, workingDir: meta.path, worktreePath: meta.path })),
+ ];
+ },
drizzle: {
select: () => ({
from: () => ({
@@ -103,6 +124,14 @@ describe('WorktreePool safety', () => {
.mockReset()
.mockImplementation(async (_baseRepo: string, requestedName: string) => requestedName);
createWorktreeMock.mockReset();
+ checkpointMock.mockReset().mockResolvedValue(undefined);
+ recyclePoolMock.mockReset().mockImplementation(async (meta: WorktreeMeta, options: { canRemove: () => Promise<boolean> }) => {
+ if (!(await options.canRemove())) return false;
+ if (path.dirname(meta.path) !== path.join(meta.baseRepo, '.xdt-worktrees')) return false;
+ await gitExecMock(['worktree', 'remove', '--force', meta.path], meta.baseRepo);
+ storeMap.delete(meta.sessionId);
+ return true;
+ });
rmSpy = vi.spyOn(fs, 'rm');
pool = await import('../worktree/WorktreePool');
@@ -147,7 +176,7 @@ describe('WorktreePool safety', () => {
['worktree', 'remove', '--force', evictableMeta.path],
baseRepo,
);
- expect(liveSessionQueryCount).toBe(1);
+ expect(liveSessionQueryCount).toBeGreaterThanOrEqual(2);
});
it('does not return a live session worktree to the reusable pool', async () => {
@@ -243,7 +272,7 @@ describe('WorktreePool safety', () => {
gitExecMock.mockRejectedValueOnce(new Error('git remove failed'));
await expect(pool.releaseWorktree(meta.sessionId)).resolves.toBe('pooled');
- await expect(pool.drainOne(baseRepo)).rejects.toThrow('git remove failed');
+ await expect(pool.drainOne(baseRepo)).rejects.toThrow('pooled worktree was preserved');
expect(rmSpy).not.toHaveBeenCalled();
expect(storeMap.has(meta.sessionId)).toBe(true);
@@ -394,4 +423,34 @@ describe('WorktreePool safety', () => {
expect(gitExecMock).not.toHaveBeenCalled();
expect(storeMap.has(meta.sessionId)).toBe(true);
});
+
+ it('checkpoints before reset and replaces the old registration with one new generation', async () => {
+ const meta = makeMeta(baseRepo, 'previous', '2026-05-26T00:00:00.000Z');
+ fsSync.mkdirSync(meta.path, { recursive: true });
+ storeMap.set(meta.sessionId, meta);
+ expect(await pool.releaseWorktree(meta.sessionId)).toBe('pooled');
+ const order: string[] = [];
+ checkpointMock.mockImplementation(async () => { order.push('checkpoint'); });
+ gitExecMock.mockImplementation(async (args: string[]) => { order.push(args[0]); return { stdout: '', stderr: '' }; });
+ const result = await pool.acquireWorktree({ sessionId: 'next', name: 'next', baseRepo, sourceBranch: 'main', ephemeral: true });
+ expect(result.ok).toBe(true);
+ expect(order.slice(0, 4)).toEqual(['checkpoint', 'checkout', 'reset', 'clean']);
+ expect(storeMap.has(meta.sessionId)).toBe(false);
+ expect(storeMap.get('next')).toMatchObject({ path: meta.path, generation: expect.any(String) });
+ expect(storeMap.size).toBe(1);
+ });
+
+ it('leaves a pooled directory intact when a task references it before reuse', async () => {
+ const meta = makeMeta(baseRepo, 'previous', '2026-05-26T00:00:00.000Z');
+ fsSync.mkdirSync(meta.path, { recursive: true });
+ storeMap.set(meta.sessionId, meta);
+ expect(await pool.releaseWorktree(meta.sessionId)).toBe('pooled');
+ liveSessionRows.push({ id: 'late-borrower', status: 'active', workingDir: meta.path, worktreePath: null });
+ const req = { sessionId: 'next', name: 'next', baseRepo, sourceBranch: 'main', ephemeral: true };
+ await pool.acquireWorktree(req);
+ expect(checkpointMock).not.toHaveBeenCalled();
+ expect(gitExecMock).not.toHaveBeenCalled();
+ expect(storeMap.get(meta.sessionId)).toEqual(meta);
+ expect(createWorktreeMock).toHaveBeenCalledWith(req);
+ });
});
diff --git a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts
new file mode 100644
index 0000000000..6949186f95
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts
@@ -0,0 +1,174 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+
+import type { WorktreeMeta } from '../worktree/types';
+
+const state = vi.hoisted(() => ({ root: '', refs: [] as unknown[], registry: new Map<string, WorktreeMeta>() }));
+vi.mock('electron', () => ({
+ app: { getPath: () => state.root },
+ safeStorage: { encryptString: (text: string) => Buffer.from(text), decryptString: (bytes: Buffer) => bytes.toString() },
+}));
+vi.mock('../worktree/worktreeStore', () => ({
+ get: (id: string) => state.registry.get(id) ?? null,
+ getAll: () => [...state.registry.values()], getAllPaths: () => [...state.registry.values()].map((m) => m.path),
+ set: async (id: string, meta: WorktreeMeta) => { state.registry.set(id, meta); },
+ 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/gitExec', async (original) => {
+ const actual = await original<typeof import('../worktree/gitExec')>();
+ return { ...actual, gitExec: vi.fn(actual.gitExec) };
+});
+
+import { recycleManagedWorktree } from '../worktree/managedRecycle';
+import { restoreRecordedWorktree } from '../worktree/restoreRecovery';
+import { readRecycleRecord } from '../worktree/recycleJournal';
+import { captureWorktreeContent } from '../worktree/contentSnapshot';
+import { gitExec } from '../worktree/gitExec';
+
+const exec = promisify(execFile);
+describe('worktree recovery with real Git and encrypted archives', () => {
+ let repo: string;
+ const git = async (cwd: string, ...args: string[]) => (await exec('git', args, {
+ 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-'));
+ repo = path.join(state.root, 'repo');
+ await fs.mkdir(repo);
+ await git(repo, 'init', '-b', 'main');
+ await git(repo, 'config', 'user.name', 'Recovery Test');
+ await git(repo, 'config', 'user.email', 'recovery-test@localhost');
+ await git(repo, 'config', 'core.autocrlf', 'false');
+ await fs.writeFile(path.join(repo, 'tracked.txt'), 'base\n');
+ await fs.writeFile(path.join(repo, '.gitignore'), '.env\nignored/\n');
+ await git(repo, 'add', '.'); await git(repo, 'commit', '-m', 'fixture');
+ });
+ afterAll(async () => { await fs.rm(state.root, { recursive: true, force: true }); });
+
+ const createFixture = async (name: string) => {
+ const worktree = path.join(repo, '.cindy-worktrees', name);
+ await git(repo, 'worktree', 'add', '-b', `cindy/${name}`, worktree, 'main');
+ await fs.writeFile(path.join(worktree, 'draft.txt'), `${name} contents\n`);
+ const meta: WorktreeMeta = { sessionId: name, generation: `${name}-generation`, name, path: worktree, baseRepo: repo, branch: `cindy/${name}`, sourceBranch: 'main', createdAt: '2026-09-08T00:00:00Z' };
+ state.registry.set(name, meta);
+ state.refs.push({ id: name, status: 'archived', source: 'desktop', currentDatabase: true, workingDir: worktree, worktreePath: worktree });
+ return meta;
+ };
+
+ 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');
+ await git(worktree, 'checkout', '--detach');
+ const head = await git(worktree, 'rev-parse', 'HEAD');
+ await fs.writeFile(path.join(worktree, 'tracked.txt'), 'staged\n');
+ await git(worktree, 'add', 'tracked.txt');
+ await fs.writeFile(path.join(worktree, 'tracked.txt'), 'unstaged\n');
+ await fs.writeFile(path.join(worktree, '.env'), 'INVALID_TEST_SECRET=keep-me\n');
+ await fs.writeFile(path.join(worktree, 'untracked.txt'), 'untracked content\n');
+ await fs.mkdir(path.join(worktree, 'ignored'));
+ await fs.writeFile(path.join(worktree, 'ignored', 'data.bin'), Buffer.from([0, 255, 10, 48]));
+ const meta: WorktreeMeta = { sessionId: 'recover', generation: 'generation-one', name: 'recover', path: worktree, baseRepo: repo, branch: 'cindy/recover', sourceBranch: 'main', createdAt: '2026-09-08T00:00:00Z' };
+ state.registry.set(meta.sessionId, meta);
+ state.refs = [{ id: meta.sessionId, status: 'archived', source: 'desktop', currentDatabase: true, workingDir: worktree, worktreePath: worktree }];
+ const recycled = await recycleManagedWorktree(meta, { canRemove: async () => true });
+ expect(recycled, JSON.stringify(await readRecycleRecord(worktree))).toBe(true);
+ await expect(fs.stat(worktree)).rejects.toMatchObject({ code: 'ENOENT' });
+ const record = await readRecycleRecord(worktree);
+ expect(record?.snapshot?.head).toBe(head);
+ const archivedTree = await git(repo, 'ls-tree', '-r', '--name-only', record!.snapshot!.commit);
+ expect(archivedTree).not.toContain('.env');
+ expect(archivedTree).not.toContain('untracked.txt');
+ expect(await restoreRecordedWorktree(meta.sessionId, worktree)).toBe(true);
+ expect(await git(worktree, 'rev-parse', 'HEAD')).toBe(head);
+ expect(await git(worktree, 'show', ':tracked.txt')).toBe('staged');
+ expect(await fs.readFile(path.join(worktree, 'tracked.txt'), 'utf8')).toBe('unstaged\n');
+ expect(await fs.readFile(path.join(worktree, '.env'), 'utf8')).toBe('INVALID_TEST_SECRET=keep-me\n');
+ expect(await fs.readFile(path.join(worktree, 'untracked.txt'), 'utf8')).toBe('untracked content\n');
+ expect(await fs.readFile(path.join(worktree, 'ignored', 'data.bin'))).toEqual(Buffer.from([0, 255, 10, 48]));
+ expect(await git(worktree, 'status', '--porcelain')).toContain('MM tracked.txt');
+ expect((await readRecycleRecord(worktree))?.phase).toBe('restored');
+ }, 60_000);
+
+ it('taking a snapshot never modifies the original index or working files', async () => {
+ const worktree = path.join(repo, '.cindy-worktrees', 'snapshot');
+ await git(repo, 'worktree', 'add', '-b', 'cindy/snapshot', worktree, 'main');
+ await fs.writeFile(path.join(worktree, 'tracked.txt'), 'staged\n');
+ await git(worktree, 'add', 'tracked.txt');
+ await fs.writeFile(path.join(worktree, 'tracked.txt'), 'current\n');
+ const index = await git(worktree, 'rev-parse', '--path-format=absolute', '--git-path', 'index');
+ const before = await fs.readFile(index);
+ await captureWorktreeContent(worktree, 'refs/cindy/worktree-recovery/test');
+ expect(await fs.readFile(index)).toEqual(before);
+ expect(await fs.readFile(path.join(worktree, 'tracked.txt'), 'utf8')).toBe('current\n');
+ }, 30_000);
+
+ it('repairs an interrupted removal without deleting surviving files or duplicating Git registration', async () => {
+ const meta = await createFixture('partial');
+ const originalGit = vi.mocked(gitExec).getMockImplementation()!;
+ const originalRm = fs.rm;
+ const blockedRm = vi.spyOn(fs, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === meta.path) throw Object.assign(new Error('locked'), { code: 'EBUSY' });
+ return originalRm(target, options);
+ });
+ vi.mocked(gitExec).mockImplementation(async (args, cwd, options) => {
+ if (args.includes('remove') && args.includes(meta.path)) {
+ await originalRm(path.join(meta.path, '.git'));
+ await originalRm(path.join(meta.path, 'tracked.txt'));
+ throw new Error('EBUSY');
+ }
+ return originalGit(args, cwd, options);
+ });
+ try {
+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(false);
+ expect((await readRecycleRecord(meta.path))?.phase).toBe('removing');
+ } finally {
+ blockedRm.mockRestore();
+ vi.mocked(gitExec).mockImplementation(originalGit);
+ }
+ await fs.writeFile(path.join(meta.path, 'new-edit.txt'), 'late edit');
+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(false);
+ expect(await fs.readFile(path.join(meta.path, 'new-edit.txt'), 'utf8')).toBe('late edit');
+ await fs.unlink(path.join(meta.path, 'new-edit.txt'));
+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(true);
+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('partial contents\n');
+ expect(await fs.readFile(path.join(meta.path, 'tracked.txt'), 'utf8')).toBe('base\n');
+ const registered = (await git(repo, 'worktree', 'list', '--porcelain')).split('\n')
+ .filter((line) => line.startsWith('worktree ') && path.resolve(line.slice(9)) === path.resolve(meta.path));
+ expect(registered).toHaveLength(1);
+ }, 30_000);
+
+ it('rejects a corrupt encrypted archive before creating recovery files', async () => {
+ const meta = await createFixture('corrupt');
+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);
+ const record = (await readRecycleRecord(meta.path))!;
+ const archive = path.join(state.root, 'worktree-recycle', record.archive!.file);
+ const bytes = await fs.readFile(archive);
+ bytes[0] ^= 1;
+ await fs.writeFile(archive, bytes);
+ await expect(restoreRecordedWorktree(meta.sessionId, meta.path)).rejects.toThrow();
+ await expect(fs.stat(meta.path)).rejects.toMatchObject({ code: 'ENOENT' });
+ expect((await readRecycleRecord(meta.path))?.phase).toBe('removed');
+ }, 30_000);
+
+ it('preserves earlier recovery history across reuse and never overwrites a newer occupant', async () => {
+ const previous = await createFixture('history');
+ expect(await recycleManagedWorktree(previous, { canRemove: async () => true })).toBe(true);
+ await git(repo, 'worktree', 'add', '-b', 'cindy/successor', previous.path, 'main');
+ await fs.writeFile(path.join(previous.path, 'draft.txt'), 'successor contents\n');
+ const next = { ...previous, sessionId: 'successor', generation: 'successor-generation', branch: 'cindy/successor' };
+ state.registry.set(next.sessionId, next);
+ state.refs.push({ id: next.sessionId, status: 'archived', source: 'desktop', currentDatabase: true, workingDir: next.path, worktreePath: next.path });
+ expect(await restoreRecordedWorktree(previous.sessionId, previous.path)).toBe(false);
+ expect(await fs.readFile(path.join(next.path, 'draft.txt'), 'utf8')).toBe('successor contents\n');
+ expect(await recycleManagedWorktree(next, { canRemove: async () => true })).toBe(true);
+ expect((await readRecycleRecord(previous.path, previous.sessionId))?.generation).toBe(previous.generation);
+ expect(await restoreRecordedWorktree(previous.sessionId, previous.path)).toBe(true);
+ expect(await fs.readFile(path.join(previous.path, 'draft.txt'), 'utf8')).toBe('history contents\n');
+ }, 30_000);
+});
diff --git a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts
new file mode 100644
index 0000000000..30d5fae5be
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { WorktreeRecycleRecord } from '../worktree/recycleJournal';
+
+const state = vi.hoisted(() => ({ rows: [] as Array<{ id: string; status: string; source: string; currentDatabase: boolean }>, records: [] as WorktreeRecycleRecord[] }));
+const remove = vi.hoisted(() => vi.fn());
+const client = vi.hoisted(() => ({ readLocalWorktreeReferences: vi.fn() }));
+vi.mock('../localDb/client/current', () => ({ getDbClient: () => client }));
+vi.mock('../worktree/managedRecycle', () => ({ recycleManagedWorktree: remove }));
+vi.mock('../worktree/worktreeStore', () => ({ get: () => null, getAll: () => [] }));
+vi.mock('../worktree/liveSessionRefs', () => ({ loadLiveSessionPathKeys: async () => new Set(), hasLiveSessionReference: () => false, pathKey: (value: string) => value }));
+vi.mock('../worktree/recycleJournal', () => ({
+ listRecycleRecords: async () => state.records,
+ readRecycleRecord: async () => state.records[0] ?? null,
+ worktreeGeneration: () => 'one',
+}));
+import { runWorktreeRecycleMaintenance, stopWorktreeRecycleMaintenance } from '../worktree/recycleMaintenance';
+
+describe('durable worktree maintenance', () => {
+ let ready: boolean;
+ const closeAndRecycle = vi.fn();
+ const run = (force = false) => runWorktreeRecycleMaintenance({ isReady: () => ready, recycleCurrentSession: closeAndRecycle }, force);
+ beforeEach(() => {
+ stopWorktreeRecycleMaintenance(); ready = true;
+ state.records = [{ version: 1, id: 'resource', generation: 'one', meta: { sessionId: 'owner', path: 'resource' }, phase: 'pending', nextAttemptAt: 0, attempts: 0 }] as WorktreeRecycleRecord[];
+ state.rows = [{ id: 'owner', status: 'archived', source: 'desktop', currentDatabase: true }];
+ closeAndRecycle.mockReset().mockResolvedValue(undefined);
+ remove.mockReset().mockResolvedValue(true);
+ client.readLocalWorktreeReferences.mockReset().mockImplementation(async () => state.rows);
+ });
+ it('waits for both database and runtime services', async () => {
+ ready = false; await run(); expect(closeAndRecycle).not.toHaveBeenCalled();
+ ready = true; await run(); expect(closeAndRecycle).toHaveBeenCalledWith('owner', 'archived');
+ });
+ it('does not infer deletion from a row missing in the local view', async () => {
+ state.rows = []; await run(); expect(remove).not.toHaveBeenCalled(); expect(closeAndRecycle).not.toHaveBeenCalled();
+ });
+ it('does not re-enqueue historical registrations without an explicit request', async () => {
+ state.records = []; await run(); expect(closeAndRecycle).not.toHaveBeenCalled();
+ });
+ it('does not close a task through another selected database', async () => {
+ state.rows[0].currentDatabase = false;
+ await run(); expect(closeAndRecycle).not.toHaveBeenCalled(); expect(remove).toHaveBeenCalledOnce();
+ const guard = remove.mock.calls[0][1].canRemove;
+ expect(await guard()).toBe(true);
+ state.rows[0].status = 'active'; expect(await guard()).toBe(false);
+ });
+ it('coalesces overlapping ready events without concurrent cleanup', async () => {
+ let finish!: () => void;
+ closeAndRecycle.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const first = run();
+ await vi.waitFor(() => expect(closeAndRecycle).toHaveBeenCalledOnce());
+ const second = run();
+ expect(second).toBe(first);
+ expect(closeAndRecycle).toHaveBeenCalledOnce(); finish(); await first;
+ expect(closeAndRecycle).toHaveBeenCalledTimes(2);
+ });
+ it('honors backoff but permits a wakeup after runtime occupancy changes', async () => {
+ state.records[0].nextAttemptAt = Date.now() + 60_000;
+ await run(); expect(closeAndRecycle).not.toHaveBeenCalled();
+ await run(true); expect(closeAndRecycle).toHaveBeenCalledOnce();
+ });
+ it('bounds automatic attempts within a process lifetime', async () => {
+ for (let index = 0; index < 12; index++) await run();
+ expect(closeAndRecycle).toHaveBeenCalledTimes(8);
+ });
+ it('continues with other resources after one request fails', async () => {
+ state.records.push({ ...state.records[0], id: 'another-resource', meta: { ...state.records[0].meta, sessionId: 'second' } });
+ state.rows.push({ ...state.rows[0], id: 'second' });
+ closeAndRecycle.mockRejectedValueOnce(new Error('lock busy'));
+ await run();
+ expect(closeAndRecycle).toHaveBeenLastCalledWith('second', 'archived');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
new file mode 100644
index 0000000000..d420d4cf95
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+const state = vi.hoisted(() => ({ root: '' }));
+const notify = vi.hoisted(() => vi.fn());
+vi.mock('electron', () => ({ app: { getPath: () => state.root } }));
+vi.mock('../worktree/recycleMaintenance', () => ({ notifyWorktreeRecycleOpportunity: notify }));
+
+import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, readWorktreeRuntimePaths } from '../worktree/runtimeLeases';
+import { physicalWorktreeKey, withWorktreeResourceLock } from '../worktree/resourceLock';
+
+describe('worktree runtime evidence and physical locks', () => {
+ let worktree: string;
+ beforeEach(async () => {
+ state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-runtime-'));
+ worktree = path.join(state.root, 'repo', '.cindy-worktrees', 'one');
+ await fs.mkdir(path.join(worktree, 'src'), { recursive: true });
+ await fs.mkdir(path.join(state.root, '.dev-instances'));
+ notify.mockClear();
+ });
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await fs.rm(state.root, { recursive: true, force: true });
+ });
+
+ it('publishes a root lease before using a descendant and wakes retries only on actual release', async () => {
+ await acquireWorktreeRuntimeLease('one', path.join(worktree, 'src'));
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));
+ await releaseWorktreeRuntimeLease('one');
+ await releaseWorktreeRuntimeLease('one');
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());
+ expect(notify).toHaveBeenCalledOnce();
+ });
+
+ 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 }));
+ expect(await readWorktreeRuntimePaths()).toBeNull();
+ });
+
+ it('prefers a valid current instance record over its older backup', async () => {
+ vi.spyOn(process, 'kill').mockReturnValue(true);
+ await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'), JSON.stringify({ pid: 4242, worktreeLeaseProtocol: 1 }));
+ await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json.bak'), JSON.stringify({ pid: 4242 }));
+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());
+ });
+
+ it('does not mistake an unreadable live lease for a stopped runtime', async () => {
+ await acquireWorktreeRuntimeLease('one', worktree);
+ const root = path.join(state.root, 'worktree-runtime-leases');
+ const [name] = await fs.readdir(root);
+ await fs.writeFile(path.join(root, name), '{');
+ expect(await readWorktreeRuntimePaths()).toBeNull();
+ });
+
+ it('serializes independent callers and allows a nested call in the same operation', async () => {
+ let release!: () => void;
+ let entered!: () => void;
+ const enteredPromise = new Promise<void>((resolve) => { entered = resolve; });
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const order: string[] = [];
+ const first = withWorktreeResourceLock(worktree, async () => {
+ await withWorktreeResourceLock(path.join(worktree, 'src', '..'), async () => { order.push('nested'); });
+ entered(); await gate; order.push('released');
+ });
+ await enteredPromise;
+ const second = withWorktreeResourceLock(worktree, async () => { order.push('second'); });
+ expect(order).toEqual(['nested']);
+ release(); await Promise.all([first, second]);
+ expect(order).toEqual(['nested', 'released', 'second']);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts b/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
index 2bf88794c3..da72e2174c 100644
--- a/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeSessionRemovalRecycle.test.ts
@@ -1,3 +1,4 @@
+vi.mock('../worktree/recycleMaintenance', () => ({ auditRegisteredWorktrees: vi.fn() }));
/**
* sessionRemovalRecycle 回归(P0 重构:回收唯一驱动点):
* - ephemeral worktree 跳过(池生命周期)
@@ -441,7 +442,7 @@ describe('sessionRemovalRecycle', () => {
});
describe('reconcileWorktreesForDeletedSessions', () => {
- it('recycles only deleted / missing owners; active and archived preserved', async () => {
+ it('preserves historical deleted, missing, active and archived registrations without a durable request', async () => {
storeMap.set('active', makeMeta('active'));
storeMap.set('archived', makeMeta('archived'));
storeMap.set('deleted', makeMeta('deleted'));
@@ -457,7 +458,7 @@ describe('sessionRemovalRecycle', () => {
await mod.reconcileWorktreesForDeletedSessions();
const removed = removeMock.mock.calls.map((c) => c[0]).sort();
- expect(removed).toEqual(['deleted', 'missing']);
+ expect(removed).toEqual([]);
});
it('empty store → no db query, no removals', async () => {
@@ -475,14 +476,14 @@ describe('sessionRemovalRecycle', () => {
expect(removeMock).not.toHaveBeenCalled();
});
- it('single remove failure does not abort the rest', async () => {
+ it('does not begin historical removal during startup audit', async () => {
storeMap.set('d1', makeMeta('d1'));
storeMap.set('d2', makeMeta('d2'));
removeMock.mockRejectedValueOnce(new Error('locked'));
await mod.reconcileWorktreesForDeletedSessions();
- expect(removeMock).toHaveBeenCalledTimes(2);
+ expect(removeMock).not.toHaveBeenCalled();
});
});
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 382681a98b..25ea1a2df7 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1,3 +1,6 @@
+import { startWorktreeRecycleMaintenance, auditRegisteredWorktrees } from './worktree/recycleMaintenance';
+import { recycleSessionWorktreeForStatusChange } from './localDb/ipc/sessions';
+import { tryGetDbClient } from './localDb/client/current';
import {
app,
BrowserWindow,
@@ -491,7 +494,6 @@ import { registerRemoteResourcesIpc } from './device-link/remoteResourcesIpc';
import {
registerWorktreeIpc,
WorktreePool,
- reconcileWorktreesForDeletedSessions,
reconcilePendingSafeDirectoryCleanups,
} from './worktree';
// shadow savepoint 链的启动期对账(孤儿 refs/cindy/savepoints/* 清理)
@@ -5844,6 +5846,7 @@ const registerIpcHandlers = () => {
.catch(() => {});
});
makerIpcsRegistered = true;
+ worktreeRuntimeCloseReady = true;
// device-link 捕获自检放在这里(而非 bootstrap 线性段):maker:create-session / maker:send
// 由上面的 registerMakerCoreIpc 注册,属 splash 后的延迟注册;若在线性段(initDeviceLinkService
// 之后)就 assert,会误报这两个 sentinel「未捕获」。此刻所有 sentinel(含线性段已注册的
@@ -5855,16 +5858,7 @@ const registerIpcHandlers = () => {
// 不阻塞启动 —— 老链路仍可用; 下次 splash retry 再尝试。
}
- // Phase 3 恢复上次退出时保留的 worktree pool(未被 session 引用的 clean ephemeral → 入池,dirty → 保留,stale → 清除)。
- // 在 scheduler 之前恢复,确保首个 scheduler job 能命中池缓存。
- await WorktreePool.recoverPool().catch((err) => {
- console.error('[bootstrap-electron] recoverPool failed (non-fatal):', err);
- });
- // P0 重构对账:会话已删除(status='deleted' 或行已缺失)但 worktree 回收没跑完
- // (崩溃窗口/回收失败)的孤儿,启动期补一次回收。fire-and-forget,不阻塞启动。
- void reconcileWorktreesForDeletedSessions().catch((err) => {
- console.error('[bootstrap-electron] worktree reconcile failed (non-fatal):', err);
- });
+ startReadyWorktreeMaintenance();
// 删除 worktree 时因拿不到全局 safe.directory 锁而落盘的残留路径, 启动期补清。
void reconcilePendingSafeDirectoryCleanups().catch((err) => {
console.error('[bootstrap-electron] safe.directory cleanup reconcile failed (non-fatal):', err);
@@ -8385,6 +8379,7 @@ app.on('ready', async () => {
// takeover. registerMakerIpc also invokes this once its services exist,
// covering both possible splash/login orderings without duplicate runs.
void restoreBotRuntimeForCurrentOwner();
+ startReadyWorktreeMaintenance();
if (dbClientTakeover.mode === 'unchanged') {
// 副窗口会再次走 localDb.ensureReady;同 owner 的 lifecycle client 已由首个
// onReady 完整启动,因此这里只保留 DB 连接交接,不重复执行账号级启动维护。
@@ -9531,3 +9526,21 @@ if (
) {
require.cache[__filename] = module;
}
+
+let worktreeRuntimeCloseReady = false;
+let lastWorktreeMaintenanceDb: ReturnType<typeof tryGetDbClient> = null;
+
+/** Worktree maintenance needs both storage and runtime-close services. */
+function startReadyWorktreeMaintenance(): void {
+ startWorktreeRecycleMaintenance({
+ isReady: () => worktreeRuntimeCloseReady && getMakerIfReady() !== null && tryGetDbClient() !== null,
+ recycleCurrentSession: (sessionId, status) => recycleSessionWorktreeForStatusChange(sessionId, status),
+ onAttemptComplete: auditRegisteredWorktrees,
+ });
+ const db = tryGetDbClient();
+ if (worktreeRuntimeCloseReady && getMakerIfReady() && db && db !== lastWorktreeMaintenanceDb) {
+ lastWorktreeMaintenanceDb = db;
+ void auditRegisteredWorktrees().catch((error) => dbClientLog.warn('worktree audit postponed', error));
+ void WorktreePool.recoverPool().catch((error) => dbClientLog.warn('worktree pool recovery postponed', error));
+ }
+}
diff --git a/apps/desktop/src/main/devStartupStatus.ts b/apps/desktop/src/main/devStartupStatus.ts
index 0affc04646..f34e73e5d6 100644
--- a/apps/desktop/src/main/devStartupStatus.ts
+++ b/apps/desktop/src/main/devStartupStatus.ts
@@ -21,6 +21,7 @@ export type DesktopDevInstanceState = 'starting' | 'ready' | 'failed';
*/
export interface DesktopDevInstanceRecord {
schemaVersion: 1;
+ worktreeLeaseProtocol?: 1;
instanceId: string;
pid: number;
startedAtMs: number;
@@ -132,6 +133,7 @@ export async function beginDesktopDevInstance(
const startedAtMs = options.startedAtMs ?? Date.now();
const record: DesktopDevInstanceRecord = {
schemaVersion: 1,
+ worktreeLeaseProtocol: 1,
instanceId: options.instanceId ?? randomUUID(),
pid,
startedAtMs,
diff --git a/apps/desktop/src/main/localDb/client/DbClient.ts b/apps/desktop/src/main/localDb/client/DbClient.ts
index dd02e94422..d912d204aa 100644
--- a/apps/desktop/src/main/localDb/client/DbClient.ts
+++ b/apps/desktop/src/main/localDb/client/DbClient.ts
@@ -11,8 +11,11 @@ import { WorkerThreadTransport } from './WorkerThreadTransport.js';
import { createDrizzleProxy } from './drizzleProxy.js';
import type { DbTxArgsByName, DbTxName, DbTxResultByName } from './tx/types.js';
import { tx as runInprocTx } from '../worker/opHandlers/tx.js';
+import type { LocalWorktreeReference } from '../worker/worktreeReferences.js';
export interface DbClient {
+ /** Optional only for legacy transports; callers must preserve on absence. */
+ readLocalWorktreeReferences?(): Promise<LocalWorktreeReference[]>;
query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;
queryOne<T = unknown>(sql: string, params?: unknown[]): Promise<T | undefined>;
exec(
@@ -80,6 +83,8 @@ export async function createDbClient(opts: CreateDbClientOptions = {}): Promise<
rebindTerminationHandler();
const client: DbClient = {
+ readLocalWorktreeReferences: () =>
+ withTransport('worktreeReferences', () => transport.send('worktreeReferences')),
query: (sql, params) =>
withTransport('query', () => transport.send('query', { sql, params: params ?? [] })),
queryOne: (sql, params) =>
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 058539bf4e..d39578328e 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -5,6 +5,8 @@
* 失败时 throw `Error("[CODE] message")`,service 层包装回 `ApiError`。
*/
+import { withWorktreeResourceLocks } from '../../worktree/resourceLock';
+import { managedWorktreeRoot } from '../../worktree/runtimeLeases';
import fs from 'node:fs/promises';
import path from 'node:path';
@@ -174,13 +176,55 @@ function isOwnerScopeCurrent(scope: OwnerScope): boolean {
}
async function withStatusWriteLock<T>(
+ db: DbClient['drizzle'],
sessionId: string,
status: unknown,
task: () => Promise<T>,
alreadyLocked = false,
): Promise<T> {
- if (status === undefined || alreadyLocked) return task();
- return withSessionRouteLock(sessionId, task);
+ const write = async () => {
+ const resources = status === undefined ? [] : await readSessionWorktreeResources(db, sessionId);
+ const mutate = async () => {
+ if (status === 'archived' || status === 'deleted') await requestWorktreeRecycle(sessionId, resources);
+ return task();
+ };
+ return withWorktreeMutation(resources, mutate);
+ };
+ if (status === undefined || alreadyLocked) return write();
+ return withSessionRouteLock(sessionId, write);
+}
+
+async function requestWorktreeRecycle(sessionId: string, resources: readonly string[] = []): Promise<void> {
+ // Keep the existing localDb -> worktreeStore -> localDb dependency lazy.
+ const recycle = await import('../../worktree/managedRecycle');
+ await recycle.requestWorktreeRecycle(sessionId, resources);
+}
+
+/** Read from the same captured database that will receive the status/path update. */
+async function readSessionWorktreeResources(db: DbClient['drizzle'], sessionId: string): Promise<string[]> {
+ try {
+ const [row] = await db.select({
+ workingDir: sessions.workingDir, worktreePath: sessions.worktreePath, remoteHostId: sessions.remoteHostId,
+ }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);
+ if (!row || row.remoteHostId) return [];
+ return [row.workingDir, row.worktreePath].flatMap((value) => {
+ const root = value ? managedWorktreeRoot(value) : null;
+ return root ? [root] : [];
+ });
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'Worktree references are temporarily unavailable');
+ }
+}
+
+async function withWorktreeMutation<T>(resources: string[], task: () => Promise<T>): Promise<T> {
+ try {
+ return await withWorktreeResourceLocks(resources, task);
+ } catch (error) {
+ const code = (error as { code?: string })?.code;
+ if (code && error instanceof Error && error.message.startsWith(`[${code}]`)) throw error;
+ log.warn('worktree mutation postponed', { code: code ?? 'unavailable' });
+ throwIpcError('PRECONDITION_FAILED', 'Worktree is busy or its recovery record could not be saved');
+ }
}
async function writeSessionPatch(
@@ -1272,7 +1316,11 @@ export function registerSessionIpc(
autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,
source: 'local-db:sessions:create',
});
- await db.insert(sessions).values(insertRow);
+ const resource = !insertRow.remoteHostId && insertRow.workingDir
+ ? managedWorktreeRoot(insertRow.workingDir) : null;
+ const insert = async () => { await db.insert(sessions).values(insertRow); };
+ if (resource) await withWorktreeMutation([resource], insert);
+ else await insert();
const [row] = await db.select().from(sessions).where(eq(sessions.id, id));
if (!row) throwIpcError('NOT_FOUND', 'Session 创建后查询失败');
// recent-workdirs: 项目目录走 sidebar 分组,要进"最近"列表;dialogue 目录是
@@ -1655,6 +1703,7 @@ export function registerSessionIpc(
// 按下过保存,这个方向的偏差是安全的。
if (typeof p.title === 'string') noteUserTitleWritten(sid);
await withStatusWriteLock(
+ db,
sid,
p.status,
async () => {
@@ -1784,7 +1833,15 @@ export function registerSessionIpc(
compactTerminalSessionToolResults(dbClient, sid, p.status);
return updated;
};
- return p.workingDir === undefined ? update() : withSessionRouteLock(sid, update);
+ if (p.workingDir === undefined) return update();
+ return withSessionRouteLock(sid, async () => {
+ const [binding] = await db.select({ remoteHostId: sessions.remoteHostId }).from(sessions).where(eq(sessions.id, sid)).limit(1);
+ const resource = !binding?.remoteHostId && typeof p.workingDir === 'string'
+ ? managedWorktreeRoot(p.workingDir) : null;
+ const resources = await readSessionWorktreeResources(db, sid);
+ if (resource) resources.push(resource);
+ return withWorktreeMutation(resources, update);
+ });
});
// 窄口径会话元数据编辑(status / title / pinnedAt)。专为 device-link 控制端**远程**
@@ -1864,7 +1921,7 @@ export async function patchSessionMetaInDb(
const setObj = sessionPatchToRow(patch, { bumpUpdatedAt: false });
// 控制端远程改名走这条,与本机改名同口径(同样先记号后写库)。
if (patch.title !== undefined) noteUserTitleWritten(sessionId);
- const updated = await withStatusWriteLock(sessionId, patch.status, async () => {
+ const updated = await withStatusWriteLock(db, sessionId, patch.status, async () => {
if (patch.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sessionId);
await writeSessionPatch(db, sessionId, setObj, patch.status);
const row = await selectSessionWithCount(db, sessionId);
@@ -2050,18 +2107,30 @@ export async function setSessionsStatusInDb(
const ownerScope = captureOwnerScope();
const dbClient = getDbClient();
const applied = await withSessionRouteLocks(sessionIds, async () => {
- const rows = await dbClient.tx('sessions.setStatus', { sessionIds, status }).catch((err) => {
- const code = (err as { code?: string }).code;
- const message = err instanceof Error ? err.message : String(err);
- if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS' || code === 'PRECONDITION_FAILED') {
- throwIpcError(code, message);
+ const resources: string[] = [];
+ const perSession = new Map<string, string[]>();
+ for (const id of sessionIds) {
+ const paths = await readSessionWorktreeResources(dbClient.drizzle, id);
+ perSession.set(id, paths);
+ resources.push(...paths);
+ }
+ return withWorktreeMutation(resources, async () => {
+ if (status === 'archived') {
+ for (const id of sessionIds) await requestWorktreeRecycle(id, perSession.get(id));
}
- throw err;
+ const rows = await dbClient.tx('sessions.setStatus', { sessionIds, status }).catch((err) => {
+ const code = (err as { code?: string }).code;
+ const message = err instanceof Error ? err.message : String(err);
+ if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS' || code === 'PRECONDITION_FAILED') {
+ throwIpcError(code, message);
+ }
+ throw err;
});
for (const item of rows) {
cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);
}
return rows;
+ });
});
for (const item of applied) {
compactTerminalSessionToolResults(dbClient, item.sessionId, item.status);
diff --git a/apps/desktop/src/main/localDb/worker/__tests__/worktreeReferences.test.ts b/apps/desktop/src/main/localDb/worker/__tests__/worktreeReferences.test.ts
new file mode 100644
index 0000000000..afd7a97b4d
--- /dev/null
+++ b/apps/desktop/src/main/localDb/worker/__tests__/worktreeReferences.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import type Database from 'better-sqlite3';
+
+import { readLocalWorktreeReferences } from '../worktreeReferences';
+import type { DatabaseConstructor } from '../runtime';
+
+describe('machine-local task reference reader', () => {
+ let root: string;
+ let currentPath: string;
+ let current: Database.Database;
+ const opened = vi.fn();
+ const closed = vi.fn();
+ const otherQuery = vi.fn();
+ class ReadOnlyDatabase {
+ constructor(file: string, options: Database.Options) { opened(file, options); }
+ prepare(sql: string) { return { all: () => otherQuery(sql) }; }
+ close() { closed(); }
+ }
+ beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-task-reference-test-'));
+ currentPath = path.join(root, 'cindy-current.db');
+ fs.writeFileSync(currentPath, 'test fixture placeholder');
+ current = { prepare: (sql: string) => ({ all: () => sql === 'PRAGMA database_list'
+ ? [{ name: 'main', file: currentPath }]
+ : [{ id: 'current-task', status: 'active', workingDir: root, worktreePath: null, source: 'desktop' }] }) } as unknown as Database.Database;
+ opened.mockReset(); closed.mockReset();
+ otherQuery.mockReset().mockReturnValue([{ id: 'other-task', status: 'active', workingDir: root, worktreePath: null, source: 'desktop' }]);
+ });
+ afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); });
+ const read = () => readLocalWorktreeReferences(current, ReadOnlyDatabase as unknown as DatabaseConstructor, 'test-native-binding');
+
+ it('aggregates current and other local databases through read-only handles without changing owners', () => {
+ fs.writeFileSync(path.join(root, 'cindy-other.db'), '');
+ fs.writeFileSync(path.join(root, 'xdt-legacy.db'), '');
+ fs.writeFileSync(path.join(root, 'unrelated.db'), '');
+ const rows = read();
+ expect(rows.filter((row) => row.currentDatabase)).toHaveLength(1);
+ expect(rows.filter((row) => !row.currentDatabase)).toHaveLength(2);
+ expect(opened).toHaveBeenCalledTimes(2);
+ for (const [, options] of opened.mock.calls) expect(options).toEqual({ readonly: true, fileMustExist: true, nativeBinding: 'test-native-binding' });
+ expect(closed).toHaveBeenCalledTimes(2);
+ expect(otherQuery.mock.calls[0][0]).toContain('remote_host_id IS NULL');
+ expect(otherQuery.mock.calls[0][0]).not.toContain('messages');
+ });
+ it('does not return a partial view when another database cannot be queried', () => {
+ fs.writeFileSync(path.join(root, 'cindy-other.db'), '');
+ otherQuery.mockImplementation(() => { throw new Error('locked database'); });
+ expect(read).toThrow('locked database');
+ expect(closed).toHaveBeenCalledTimes(1);
+ });
+ it('rejects unrecognized profile layouts rather than ignoring them', () => {
+ fs.mkdirSync(path.join(root, 'profiles'));
+ fs.mkdirSync(path.join(root, 'profiles', 'another-profile'));
+ expect(read).toThrow('profile database catalog');
+ });
+ it('rejects a source created during the scan', () => {
+ fs.writeFileSync(path.join(root, 'cindy-other.db'), '');
+ otherQuery.mockImplementation(() => { fs.writeFileSync(path.join(root, 'cindy-new.db'), ''); return []; });
+ expect(read).toThrow('catalog changed');
+ });
+ it('rejects a directory masquerading as a database', () => {
+ fs.mkdirSync(path.join(root, 'cindy-other.db'));
+ expect(read).toThrow('regular file');
+ });
+});
diff --git a/apps/desktop/src/main/localDb/worker/dbWorker.ts b/apps/desktop/src/main/localDb/worker/dbWorker.ts
index 6adbac49b7..3b656fefc6 100644
--- a/apps/desktop/src/main/localDb/worker/dbWorker.ts
+++ b/apps/desktop/src/main/localDb/worker/dbWorker.ts
@@ -4,6 +4,7 @@ import type Database from 'better-sqlite3';
import type { RpcRequest, RpcResponse, WorkerEvent } from '../client/DbTransport.js';
import { dispatch, serializeWorkerError } from './dispatcher.js';
+import { readLocalWorktreeReferences } from './worktreeReferences.js';
import {
createWorkerDatabase,
type DatabaseConstructor,
@@ -75,6 +76,9 @@ function setDatabase(opts: DbWorkerStartupOptions): void {
async function dispatchRequest(req: RpcRequest): Promise<unknown> {
const readyDb = requireReadyDb();
+ if (req.op === 'worktreeReferences') {
+ return readLocalWorktreeReferences(readyDb, DatabaseCtor, startupOptions.nativeBinding);
+ }
if (req.op === 'echoTransfer') {
const { buffer } = (req.args ?? {}) as { buffer?: { byteLength?: number } };
return { byteLength: typeof buffer?.byteLength === 'number' ? buffer.byteLength : 0 };
diff --git a/apps/desktop/src/main/localDb/worker/worktreeReferences.ts b/apps/desktop/src/main/localDb/worker/worktreeReferences.ts
new file mode 100644
index 0000000000..cc87ea74a6
--- /dev/null
+++ b/apps/desktop/src/main/localDb/worker/worktreeReferences.ts
@@ -0,0 +1,61 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import type Database from 'better-sqlite3';
+
+import type { DatabaseConstructor } from './runtime.js';
+
+/** Machine-local deletion evidence only; never exposes messages or credentials. */
+export interface LocalWorktreeReference {
+ id: string;
+ status: string | null;
+ source: string | null;
+ workingDir: string | null;
+ worktreePath: string | null;
+ currentDatabase: boolean;
+}
+
+/**
+ * Read every known legacy task database through short-lived read-only handles.
+ * No migrations, pragmas that write, or owner switching. Any unreadable source
+ * invalidates the entire view, rather than turning its tasks into apparent orphans.
+ */
+export function readLocalWorktreeReferences(
+ current: Database.Database,
+ DatabaseCtor: DatabaseConstructor,
+ nativeBinding?: string,
+): LocalWorktreeReference[] {
+ const location = current.prepare('PRAGMA database_list').all() as Array<{ name: string; file: string }>;
+ const databasePath = location.find((entry) => entry.name === 'main')?.file;
+ if (!databasePath || !path.isAbsolute(databasePath)) throw new Error('task database path unavailable');
+ const currentPath = path.resolve(databasePath);
+ const root = path.dirname(currentPath);
+ if (fs.existsSync(path.join(root, 'profiles')) && fs.readdirSync(path.join(root, 'profiles')).length) {
+ throw new Error('profile database catalog requires a compatible reader');
+ }
+ const names = fs.readdirSync(root).filter((name) => /^(?:cindy|xdt)-.+\.db$/.test(name));
+ if (!names.includes(path.basename(currentPath))) throw new Error('unknown task database layout');
+ const rows: LocalWorktreeReference[] = [];
+ for (const name of names) {
+ const file = path.join(root, name);
+ if (!fs.lstatSync(file).isFile()) throw new Error('task database is not a regular file');
+ const isCurrent = file === currentPath;
+ const db = isCurrent ? current : new DatabaseCtor(file, {
+ readonly: true, fileMustExist: true, ...(nativeBinding ? { nativeBinding } : {}),
+ });
+ try {
+ const references = db.prepare(
+ 'SELECT id, status, source, working_dir AS workingDir, worktree_path AS worktreePath '
+ + 'FROM sessions WHERE remote_host_id IS NULL',
+ ).all() as Omit<LocalWorktreeReference, 'currentDatabase'>[];
+ rows.push(...references.map((row) => ({ ...row, currentDatabase: isCurrent })));
+ } finally {
+ if (!isCurrent) db.close();
+ }
+ }
+ // A source created during the scan has not been checked yet.
+ const after = fs.readdirSync(root).filter((name) => /^(?:cindy|xdt)-.+\.db$/.test(name));
+ if (after.length !== names.length || after.some((name) => !names.includes(name))) {
+ throw new Error('task database catalog changed during scan');
+ }
+ return rows;
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 1a627dc88d..830f56fa2c 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -9,6 +9,7 @@
*/
import { createMediaDownloadContext } from '../cindy-media/mediaDownloadApproval.js';
+import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease } from '../worktree/runtimeLeases';
import { readCodexContextWindowInfo } from './codex-context-window.js';
import { app, BrowserWindow } from 'electron';
import { createHash } from 'node:crypto';
@@ -2414,6 +2415,9 @@ export function getMaker(): Maker {
const createOpts = opts as MakerSessionCreateOpts;
createOpts.id ??= sessionId;
await prepareBotWorkspaceRuntime(createOpts);
+ if (!createOpts.remoteHostId && createOpts.workingDir) {
+ await acquireWorktreeRuntimeLease(sessionId, createOpts.workingDir);
+ }
let skillLinksChanged = false;
if (!createOpts.remoteHostId && createOpts.workingDir) {
const result = await prepareSharedProjectSkillLinks({
@@ -2510,6 +2514,9 @@ export function getMaker(): Maker {
}
},
onStartFailed: async ({ sessionId, stage, error }) => {
+ await releaseWorktreeRuntimeLease(sessionId).catch((error) => {
+ desktopMakerLogger.warn('worktree runtime lease release postponed', { sessionId, code: (error as NodeJS.ErrnoException).code });
+ });
const snapshot = pendingBotRuntimeSnapshots.get(sessionId);
if (!snapshot) return;
try {
@@ -2530,6 +2537,9 @@ export function getMaker(): Maker {
await writeCodexHistoryHasProductPrompt(sessionId, historyHasProductPrompt);
},
onClose: async (sessionId) => {
+ await releaseWorktreeRuntimeLease(sessionId).catch((error) => {
+ desktopMakerLogger.warn('worktree runtime lease release postponed', { sessionId, code: (error as NodeJS.ErrnoException).code });
+ });
// rehydrate close suppression 只跳过 worktree / temp file 这类重副作用;
// registry 必须先清,后续 resume 会在首个 /responses 前重新登记,避免旧 thread prompt 驻留。
unregisterCodexProxyPrompt(sessionId);
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index 51c478effb..2cec6dab22 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -38,13 +38,15 @@ import { hasKeepSentinel, isManagedWorktreePath } from './safety';
import {
isWorktreeDirty,
listNonReproducibleIgnoredFiles,
- autoStashDirtyWorktree,
- restoreAutoStashToPreservedWorktree,
} from './dirty';
import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRefs';
import { withWorktreeRestoreMutation } from './restoreLock';
+import { recycleManagedWorktree } from './managedRecycle';
+import { withWorktreeResourceLock } from './resourceLock';
+import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease } from './runtimeLeases';
import * as store from './worktreeStore';
import { createLogger } from '../logger';
+import { getDbClient } from '../localDb/client/current';
import {
getManagedWorktreeBasePath,
MANAGED_WORKTREE_DIR_NAME,
@@ -704,24 +706,21 @@ interface CreatedSnapshot {
}
async function rollbackPartialCreate(snap: CreatedSnapshot): Promise<void> {
- // 反向回滚: 仅当 git worktree add 已成功时, 用 git worktree remove --force 撤销
+ // A failed create may already have launched checkout or acquired a task reference.
if (snap.worktreeAdded) {
const { path: wp, baseRepo } = snap.worktreeAdded;
try {
- await gitExec(['worktree', 'remove', '--force', wp], baseRepo);
+ await withWorktreeResourceLock(wp, async () => {
+ if (hasKeepSentinel(wp) || hasLiveSessionReference({ path: wp }, await loadLiveSessionPathKeys())) return;
+ if ((await listNonReproducibleIgnoredFiles(baseRepo, wp)).length > 0) return;
+ await gitExec(['worktree', 'remove', wp], baseRepo);
+ });
} catch (err) {
log.warn(
`[worktree] rollback git worktree remove failed for ${wp}:`,
err instanceof Error ? err.message : String(err),
);
- // 尝试 fs.rm 兜底(只在 isManagedWorktreePath 通过时)
- if (isManagedWorktreePath(wp, baseRepo, [wp])) {
- try {
- await fs.rm(wp, { recursive: true, force: true });
- } catch {
- /* 已经尽力, 留给用户手动清理 */
- }
- }
+ // Never force through Git's last dirty/locked check during compensation.
}
}
// parentEnsured 不清理 — 托管 worktree 根目录本身留着没坏处, 下次复用
@@ -1009,103 +1008,109 @@ async function createWorktreeInner(req: CreateWorktreeReq): Promise<CreateWorktr
}
// 4. mkdirp parent
- const parentDir = path.dirname(worktreePath);
- await timed('ensure parent directory', () => fs.mkdir(parentDir, { recursive: true }));
- snap.parentEnsured = parentDir;
-
- // 5. git worktree add(--no-checkout 跳过文件解压, 加速主流程; longpaths 自动重试)
- // 对齐 CC Desktop: 大型仓库的全 checkout 可能耗时数十秒, 改成只建 worktree 元数据,
- // 后续 stageCheckout 同步拉关键文件, 全 checkout 后台跑。
- const branch = getBranchName(name);
- const addArgs = buildWorktreeAddArgs(branch, worktreePath, req.sourceBranch);
- try {
- await timed('git worktree add', () => gitExec(addArgs, baseRepo));
- } catch (err) {
- if (err instanceof GitExecError && /filename too long|core\.longpaths/i.test(err.stderr)) {
- // 启用 core.longpaths 后重试一次
- try {
- await gitExec(['config', '--global', 'core.longpaths', 'true']);
- await timed('git worktree add retry', () => gitExec(addArgs, baseRepo));
- } catch (retryErr) {
- return { ok: false, error: classifyError(classifyAny(retryErr)) };
+ return await withWorktreeResourceLock(worktreePath, async (): Promise<CreateWorktreeResp> => {
+ const parentDir = path.dirname(worktreePath);
+ await timed('ensure parent directory', () => fs.mkdir(parentDir, { recursive: true }));
+ snap.parentEnsured = parentDir;
+
+ // 5. git worktree add(--no-checkout 跳过文件解压, 加速主流程; longpaths 自动重试)
+ // 对齐 CC Desktop: 大型仓库的全 checkout 可能耗时数十秒, 改成只建 worktree 元数据,
+ // 后续 stageCheckout 同步拉关键文件, 全 checkout 后台跑。
+ const branch = getBranchName(name);
+ const addArgs = buildWorktreeAddArgs(branch, worktreePath, req.sourceBranch);
+ try {
+ await timed('git worktree add', () => gitExec(addArgs, baseRepo));
+ } catch (err) {
+ if (err instanceof GitExecError && /filename too long|core\.longpaths/i.test(err.stderr)) {
+ // 启用 core.longpaths 后重试一次
+ try {
+ await gitExec(['config', '--global', 'core.longpaths', 'true']);
+ await timed('git worktree add retry', () => gitExec(addArgs, baseRepo));
+ } catch (retryErr) {
+ return { ok: false, error: classifyError(classifyAny(retryErr)) };
+ }
+ } else {
+ return { ok: false, error: classifyError(classifyAny(err)) };
}
- } else {
- return { ok: false, error: classifyError(classifyAny(err)) };
}
- }
- snap.worktreeAdded = { path: worktreePath, baseRepo };
-
- // 5b. stageCheckout: 同步拉 agent 启动必读文件(.claude/.sivi/CLAUDE.md/...),
- // 后台跑全 checkout。fullCheckoutPromise 故意 fire-and-forget,
- // 失败仅日志, 不阻塞 IPC 返回。
- let bgPromise: Promise<void> | undefined;
- try {
- const stageRes = await timed('stage checkout', () => stageCheckout(worktreePath));
- bgPromise = stageRes.fullCheckoutPromise;
- } catch (err) {
- // stageCheckout 内部已记 warn, 这里再保险记一条; 不视为致命
- log.warn(
- `[worktree] stageCheckout failed for ${worktreePath}:`,
- err instanceof Error ? err.message : String(err),
- );
- }
- // 防止 unhandled rejection(stageCheckout 已设 .catch 但再保险一次)
- bgPromise?.catch(() => {});
+ snap.worktreeAdded = { path: worktreePath, baseRepo };
+
+ // 5b. stageCheckout: 同步拉 agent 启动必读文件(.claude/.sivi/CLAUDE.md/...),
+ // 后台跑全 checkout。fullCheckoutPromise 故意 fire-and-forget,
+ // 失败仅日志, 不阻塞 IPC 返回。
+ let bgPromise: Promise<void> | undefined;
+ const checkoutLease = `checkout:${req.sessionId}`;
+ await acquireWorktreeRuntimeLease(checkoutLease, worktreePath);
+ try {
+ const stageRes = await timed('stage checkout', () => stageCheckout(worktreePath));
+ bgPromise = stageRes.fullCheckoutPromise.finally(() => releaseWorktreeRuntimeLease(checkoutLease));
+ } catch (err) {
+ await releaseWorktreeRuntimeLease(checkoutLease);
+ // stageCheckout 内部已记 warn, 这里再保险记一条; 不视为致命
+ log.warn(
+ `[worktree] stageCheckout failed for ${worktreePath}:`,
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ // 防止 unhandled rejection(stageCheckout 已设 .catch 但再保险一次)
+ bgPromise?.catch(() => {});
- // 6. hooks
- try {
- await timed('configure hooks', () => configureHooksPath(worktreePath, baseRepo));
- } catch (err) {
- await rollbackPartialCreate(snap);
- return { ok: false, error: classifyError(classifyAny(err)) };
- }
+ // 6. hooks
+ try {
+ await timed('configure hooks', () => configureHooksPath(worktreePath, baseRepo));
+ } catch (err) {
+ await rollbackPartialCreate(snap);
+ return { ok: false, error: classifyError(classifyAny(err)) };
+ }
- // 7. copy .claude / .sivi(目录不存在则跳过)
- try {
- await timed('copy .claude/.sivi', () => copyClaudeSiviDirs(baseRepo, worktreePath));
- } catch (err) {
- // 拷贝失败不致命(.claude/.sivi 是辅助), 但仍记录并继续
- log.warn(
- `[worktree] copy .claude/.sivi failed for ${worktreePath}:`,
- err instanceof Error ? err.message : String(err),
- );
- }
+ // 7. copy .claude / .sivi(目录不存在则跳过)
+ try {
+ await timed('copy .claude/.sivi', () => copyClaudeSiviDirs(baseRepo, worktreePath));
+ } catch (err) {
+ // 拷贝失败不致命(.claude/.sivi 是辅助), 但仍记录并继续
+ log.warn(
+ `[worktree] copy .claude/.sivi failed for ${worktreePath}:`,
+ err instanceof Error ? err.message : String(err),
+ );
+ }
- // 8. include patterns
- try {
- const results = await timed('apply include file', () =>
- applyWorktreeIncludeFile(baseRepo, worktreePath),
- );
- const failed = results.filter((r) => r.status === 'failed');
- if (failed.length > 0) {
+ // 8. include patterns
+ try {
+ const results = await timed('apply include file', () =>
+ applyWorktreeIncludeFile(baseRepo, worktreePath),
+ );
+ const failed = results.filter((r) => r.status === 'failed');
+ if (failed.length > 0) {
+ log.warn(
+ `[worktree] ${failed.length} include files failed to copy:`,
+ failed.slice(0, 5).map((f) => `${f.relpath}: ${f.error ?? '<no error>'}`),
+ );
+ }
+ } catch (err) {
log.warn(
- `[worktree] ${failed.length} include files failed to copy:`,
- failed.slice(0, 5).map((f) => `${f.relpath}: ${f.error ?? '<no error>'}`),
+ `[worktree] applyWorktreeIncludeFile failed:`,
+ err instanceof Error ? err.message : String(err),
);
}
- } catch (err) {
- log.warn(
- `[worktree] applyWorktreeIncludeFile failed:`,
- err instanceof Error ? err.message : String(err),
- );
- }
- // 9. store + DB
- const meta: WorktreeMeta = {
- sessionId: req.sessionId,
- name,
- path: worktreePath,
- baseRepo,
- branch,
- sourceBranch: req.sourceBranch,
- createdAt: nowIso(),
- ...(recoveryKey ? { recoveryKey } : {}),
- ephemeral: req.ephemeral ?? false,
- };
- await timed('persist metadata', () => store.set(req.sessionId, meta));
+ // 9. store + DB
+ const meta: WorktreeMeta = {
+ sessionId: req.sessionId,
+ name,
+ path: worktreePath,
+ baseRepo,
+ branch,
+ sourceBranch: req.sourceBranch,
+ createdAt: nowIso(),
+ generation: randomUUID(),
+ ...(recoveryKey ? { recoveryKey } : {}),
+ ephemeral: req.ephemeral ?? false,
+ };
+ await timed('persist metadata', () => store.set(req.sessionId, meta));
- log.info(`[worktree:create] total completed in ${Date.now() - totalStartedAt}ms`);
- return { ok: true, meta };
+ log.info(`[worktree:create] total completed in ${Date.now() - totalStartedAt}ms`);
+ return { ok: true, meta };
+ });
} catch (err) {
// 兜底: 任何未捕获的异常走 classifier + rollback
await rollbackPartialCreate(snap);
@@ -1147,37 +1152,48 @@ export interface RemoveWorktreeOptions {
isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined;
/**
* 预创建补偿回收不能把用户可能已经手动写入的内容变成无会话可恢复的快照;
- * 命中 dirty 时保留整个 worktree,而不是走常规删除/归档的 auto-stash 流程。
+ * 命中 dirty 时保留整个 worktree。
*/
preserveDirty?: boolean;
}
/**
- * fire-and-forget: 即便失败也不抛, 仅记日志。
- *
- * P0 重构(2026-07)后唯一调用方是会话显式删除/归档触发的
- * sessionRemovalRecycle.recycleWorktreeForRemovedSession —— 不再挂在
- * onClose(子进程退出)上,/clear、鉴权重连、app 退出等瞬态 close 不会再走到这里。
- *
- * 流程:
- * 1. meta = store.get(sid); null → return
- * 2. live-ref 守卫: 其它会话仍引用该路径 → 保留(排除 sid 自身;其它终态会话
- * 只有在 runtime 已确认关闭时才不阻挡)
- * 3. dirty → auto-stash(失败 → 保留);成功后先撤销 store 登记,阻断 SEND
- * 4. try git worktree remove --force <meta.path>
- * 5. fail → isManagedWorktreePath 三条校验通过 → fs.rm -rf
- * 6. 仍失败 → reapply snapshot;成功才恢复 store,失败则保持未登记供发送期恢复
- * 7. 删除成功 → store.del(sid)(dirty 路径幂等;不动 sessions.worktree_path)
- * 8. **不带 -D**: 分支保留
+ * 显式归档/删除通过持久请求、全本地引用和运行态守卫回收。
+ * 内容快照不改动原目录或暂存区;确认目录消失后才清登记,失败保留请求供重试。
+ * 创建失败的补偿仍走保留脏内容的窄路径。调用方须处理锁/持久化不可用错误。
*/
export async function removeWorktreeForSession(
sessionId: string,
options: RemoveWorktreeOptions = {},
): Promise<void> {
+ if (!options.preserveDirty && !options.canRemove) {
+ // Existing no-options callers are creation/import failure compensation.
+ // They may discard an unclaimed clean checkout, but cannot authorize a
+ // normal task's terminal transition merely by calling this API.
+ options = { ...options, preserveDirty: true, canRemove: async () => {
+ try {
+ const db = getDbClient();
+ return Boolean(db.readLocalWorktreeReferences)
+ && !(await db.readLocalWorktreeReferences!()).some((row) => row.id === sessionId);
+ } catch { return false; }
+ } };
+ }
+ if (!options.preserveDirty) {
+ const meta = store.get(sessionId);
+ if (!meta) return;
+ await withWorktreeRestoreMutation(sessionId, () => recycleManagedWorktree(meta, {
+ ...options,
+ onRemoved: () => removeWorktreeSafeDirectory(meta.baseRepo, meta.path),
+ }));
+ return;
+ }
const previous = removeWorktreeQueues.get(sessionId) ?? Promise.resolve();
const run = previous
.catch(() => undefined)
- .then(() => removeWorktreeForSessionInner(sessionId, options));
+ .then(async () => {
+ const meta = store.get(sessionId);
+ if (meta) await withWorktreeResourceLock(meta.path, () => removeWorktreeForSessionInner(sessionId, options));
+ });
removeWorktreeQueues.set(sessionId, run);
try {
await run;
@@ -1311,28 +1327,8 @@ async function removeWorktreeForSessionInner(
if (!(await canRemoveWorktree(removalOptions, worktreePath, sessionId))) return;
}
- const finishRemoval = async (snapshotted: boolean): Promise<void> => {
- if (snapshotted) {
- // The shared mutation lock is already installed before auto-stash starts. Unregister only
- // after the snapshot is durable so SEND waits throughout the clean-worktree window.
- store.del(sessionId);
- }
-
- // closeSession / snapshot 期间会话可能已恢复为 active。真正删除前再读一次状态;
- // 若本轮已经 snapshot,则把内容重新 apply 回保留目录。
- if (!(await canRemoveWorktree(removalOptions, activeWorktreePath(meta), sessionId))) {
- if (snapshotted) {
- if (await restoreAutoStashToPreservedWorktree(meta.path, sessionId)) {
- await store.set(sessionId, meta);
- } else {
- log.warn(
- `[worktree] recycle cancelled for ${meta.path}, but snapshot reapply failed; ` +
- 'worktree stays unregistered so SEND remains blocked until restore succeeds',
- );
- }
- }
- return;
- }
+ const finishRemoval = async (): Promise<void> => {
+ if (!(await canRemoveWorktree(removalOptions, activeWorktreePath(meta), sessionId))) return;
let removalPath = activeWorktreePath(meta);
let quarantinePath: string | null = meta.quarantinePath ?? null;
@@ -1371,16 +1367,7 @@ async function removeWorktreeForSessionInner(
};
const restorePreservedWorktree = async (): Promise<void> => {
- if (!(await restoreQuarantine())) return;
- if (!snapshotted) return;
- if (await restoreAutoStashToPreservedWorktree(meta.path, sessionId)) {
- await store.set(sessionId, meta);
- } else {
- log.warn(
- `[worktree] recycle cancelled for ${meta.path}, but snapshot reapply failed; ` +
- 'worktree stays unregistered so SEND remains blocked until restore succeeds',
- );
- }
+ await restoreQuarantine();
};
const hasCurrentLiveReference = async (): Promise<boolean> => {
@@ -1458,96 +1445,29 @@ async function removeWorktreeForSessionInner(
return;
}
- let removedByGit = false;
try {
- // 预创建补偿回收必须让 git 在删除瞬间再次确认 worktree 仍然干净:
- // preserveDirty 的前置探测与这里之间可能有人刚写入文件,非强制 remove 会拒绝,
- // 从而保留目录。普通会话删除已经有 auto-stash 保护,仍沿用 --force。
- const removeArgs = removalOptions.preserveDirty
- ? ['worktree', 'remove', removalPath]
- : ['worktree', 'remove', '--force', removalPath];
- await gitExec(removeArgs, meta.baseRepo);
- removedByGit = true;
- } catch (err) {
- log.warn(
- `[worktree] git worktree remove failed for ${removalPath}:`,
- err instanceof Error ? err.message : String(err),
- );
- // preserveDirty 是补偿口的“绝不丢用户新写内容”承诺。git 拒绝非强制删除时
- // 不能再用 fs.rm 绕过它,否则会重新打开 dirty check 后写入的竞态窗口。
- if (removalOptions.preserveDirty) {
- await restoreQuarantine();
- return;
- }
- if (await hasCurrentLiveReference()) {
- log.info(
- `[worktree] preserved worktree at ${removalPath}: another session referenced it before fallback removal`,
- );
- await restorePreservedWorktree();
- return;
- }
- // fallback: fs.rm —— 必须三条校验通过
- if (
- isManagedWorktreePath(removalPath, meta.baseRepo, [...store.getAllPaths(), removalPath])
- ) {
- try {
- await fs.rm(removalPath, { recursive: true, force: true });
- // 让 git worktree 状态自洽
- try {
- await gitExec(['worktree', 'prune'], meta.baseRepo);
- } catch {
- /* prune 失败无影响 */
- }
- removedByGit = true; // 视为已清, 走 store.del
- } catch (rmErr) {
- log.error(
- `[worktree] fs.rm fallback failed for ${removalPath}:`,
- rmErr instanceof Error ? rmErr.message : String(rmErr),
- );
- // 不动 store, 留给用户手动清理或下次启动复用
- }
- } else {
- log.warn(
- `[worktree] isManagedWorktreePath check failed for ${removalPath}; refusing fs.rm`,
- );
- }
+ await gitExec(['worktree', 'remove', removalPath], meta.baseRepo);
+ } catch (error) {
+ // A precreated compensation may never bypass Git's final dirty check.
+ log.warn('[worktree] pre-created removal failed; preserving', error instanceof Error ? error.message : String(error));
+ await restoreQuarantine();
+ return;
}
-
- if (removedByGit) {
- // 写前日志: 先落盘清理意图(物理 + 逻辑拼写), 再删最后一份元数据。
- await removeWorktreeSafeDirectory(meta.baseRepo, meta.path, meta.quarantinePath, removalPath);
- store.del(sessionId);
- } else if (snapshotted) {
- // Both removal paths failed: put WIP back before restoring the live registration. If apply
- // also fails, keep it unregistered so the send-time restore gate retries the snapshot.
- if (await restoreAutoStashToPreservedWorktree(meta.path, sessionId)) {
- await store.set(sessionId, meta);
- } else {
- log.warn(
- `[worktree] remove failed for ${meta.path}, and snapshot reapply also failed; ` +
- 'worktree stays unregistered until restore succeeds',
- );
- }
+ try {
+ await fs.lstat(removalPath);
+ return;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return;
}
+ await removeWorktreeSafeDirectory(meta.baseRepo, meta.path, meta.quarantinePath, removalPath);
+ await store.del(sessionId);
};
if (await isWorktreeDirty(worktreePath)) {
- if (removalOptions.preserveDirty) {
- log.info(
- `[worktree] preserved worktree at ${worktreePath}: uncommitted changes block pre-created cleanup`,
- );
- return;
- }
- await withWorktreeRestoreMutation(sessionId, async () => {
- if (!(await autoStashDirtyWorktree(worktreePath, sessionId))) {
- log.warn(`[worktree] worktree at ${worktreePath} has uncommitted changes, preserving`);
- return;
- }
- await finishRemoval(true);
- });
+ log.info(`[worktree] pre-created worktree at ${worktreePath} has uncommitted changes; preserving`);
return;
}
- await finishRemoval(false);
+ await finishRemoval();
}
export type DiscardPrecreatedWorktreeResult =
diff --git a/apps/desktop/src/main/worktree/WorktreePool.ts b/apps/desktop/src/main/worktree/WorktreePool.ts
index 6349a9933d..47d52539df 100644
--- a/apps/desktop/src/main/worktree/WorktreePool.ts
+++ b/apps/desktop/src/main/worktree/WorktreePool.ts
@@ -9,6 +9,11 @@
* 淘汰策略:不使用 idle timeout,改为全局数量上限(MAX_WORKTREES)按 createdAt 淘汰 clean 条目。
*/
+import { randomUUID } from 'node:crypto';
+import { checkpointWorktreeForReuse, recycleManagedWorktree } from './managedRecycle';
+import { withWorktreeResourceLock } from './resourceLock';
+import { readRecycleRecord } from './recycleJournal';
+import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';
import path from 'node:path';
import fs from 'node:fs/promises';
@@ -24,7 +29,7 @@ import {
type LiveSessionPathKeys,
} from './liveSessionRefs';
import { getBranchName } from './nameGenerator';
-import { hasKeepSentinel, isManagedWorktreePath } from './safety';
+import { hasKeepSentinel } from './safety';
import * as store from './worktreeStore';
import { createLogger } from '../logger';
@@ -77,44 +82,44 @@ export async function acquireWorktree(
req.name,
);
const newBranch = getBranchName(resolvedName);
- await resetWorktree(
- entry.meta.path,
- entry.meta.baseRepo,
- req.sourceBranch,
- newBranch,
- opts,
- );
-
- const meta: WorktreeMeta = {
- ...entry.meta,
- sessionId: req.sessionId,
- name: resolvedName,
- branch: newBranch,
- sourceBranch: req.sourceBranch,
- createdAt: new Date().toISOString(),
- };
- await store.set(req.sessionId, meta);
-
- log.info(
- `[WorktreePool] reusing pooled worktree at ${meta.path} for session ${req.sessionId}`,
- );
- return { ok: true, meta };
+ return await withWorktreeResourceLock(entry.meta.path, () => withLegacyWorktreeRuntimeGuard(async (legacyGuardHeld) => {
+ const refs = await loadLiveSessionPathKeys({ contextPath: entry.meta.path });
+ if (hasKeepSentinel(entry.meta.path) || hasLiveSessionReference(entry.meta, refs)) throw new Error('pooled worktree is in use');
+ await resetWorktree(
+ entry.meta.path,
+ entry.meta.baseRepo,
+ req.sourceBranch,
+ newBranch,
+ opts,
+ async () => {
+ await checkpointWorktreeForReuse(entry.meta);
+ if (!legacyGuardHeld()) throw new Error('runtime evidence unavailable');
+ },
+ );
+
+ const meta: WorktreeMeta = {
+ ...entry.meta,
+ sessionId: req.sessionId,
+ name: resolvedName,
+ branch: newBranch,
+ sourceBranch: req.sourceBranch,
+ createdAt: new Date().toISOString(),
+ generation: randomUUID(),
+ };
+ await store.set(req.sessionId, meta);
+ if (entry.meta.sessionId !== req.sessionId) await store.del(entry.meta.sessionId);
+
+ log.info(
+ `[WorktreePool] reusing pooled worktree at ${meta.path} for session ${req.sessionId}`,
+ );
+ return { ok: true as const, meta };
+ }));
} catch (err) {
log.warn(
'[WorktreePool] resetWorktree failed, falling back to fresh creation:',
err instanceof Error ? err.message : String(err),
);
- if (await isWorktreeDirty(entry.meta.path)) {
- log.warn(`[WorktreePool] dirty worktree preserved at ${entry.meta.path}`);
- } else {
- const drained = await drainEntry(entry.meta)
- .then(() => true)
- .catch(async () => {
- await gitExec(['worktree', 'prune'], entry.meta.baseRepo).catch(() => {});
- return false;
- });
- if (drained) store.del(entry.meta.sessionId);
- }
+ log.warn('[WorktreePool] preserving failed reuse for recovery', { sessionId: entry.meta.sessionId });
}
}
@@ -136,6 +141,7 @@ async function resetWorktree(
sourceBranch: string,
newBranch: string,
opts?: { sourceFetchAlreadyAttempted?: boolean },
+ beforeReset?: () => Promise<void>,
): Promise<void> {
// 防御性断言:池中 worktree 理论上必定 clean
if (await isWorktreeDirty(worktreePath)) {
@@ -165,6 +171,9 @@ async function resetWorktree(
}
}
+ // Network refresh may take seconds; capture and recheck only after it completes.
+ await beforeReset?.();
+
// 2. 非覆盖式创建并切换分支。查重后的 TOCTOU 竞态会让 -b 安全失败,
// 绝不能用 -B 重置一个不属于池条目的已有分支。
await gitExec(['checkout', '--no-track', '-b', newBranch, sourceBranch], worktreePath);
@@ -243,7 +252,7 @@ export async function releaseWorktree(sessionId: string): Promise<'pooled' | 'pr
.then(() => true)
.catch(() => false);
if (drained) {
- store.del(existing.meta.sessionId);
+ await store.del(existing.meta.sessionId);
}
}
}
@@ -281,7 +290,7 @@ async function evictIfOverLimit(liveSessionPathKeys?: LiveSessionPathKeys): Prom
const drained = await drainEntry(candidate)
.then(() => true)
.catch(() => false);
- if (drained) store.del(candidate.sessionId);
+ if (drained) await store.del(candidate.sessionId);
else break;
}
}
@@ -307,9 +316,10 @@ async function findOldestCleanCandidate(
// 路径不存在直接清 store,视为本轮淘汰成功
try {
await fs.access(meta.path);
- } catch {
- store.del(meta.sessionId);
- return null; // store 已缩减,让外层 while 重新检查
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') continue;
+ // The removal core rechecks registration and references under the resource lock.
+ return meta;
}
// 哨兵: 用户声明保留,永不淘汰
@@ -326,32 +336,19 @@ async function findOldestCleanCandidate(
// ── drain ────────────────────────────────────────────────────────────────────
async function drainEntry(meta: WorktreeMeta): Promise<void> {
- try {
- await gitExec(['worktree', 'remove', '--force', meta.path], meta.baseRepo);
- log.info(`[WorktreePool] drained worktree at ${meta.path}`);
- } catch (err) {
- log.warn(
- `[WorktreePool] git worktree remove failed for ${meta.path}:`,
- err instanceof Error ? err.message : String(err),
- );
- if (!isManagedWorktreePath(meta.path, meta.baseRepo, store.getAllPaths())) {
- log.warn(`[WorktreePool] fs.rm fallback skipped for unmanaged path: ${meta.path}`);
- throw err;
- }
-
- // 兜底:只允许删除 Cindy 已登记的托管 worktree 目录
- try {
- await fs.rm(meta.path, { recursive: true, force: true });
- await gitExec(['worktree', 'prune'], meta.baseRepo).catch(() => {});
- log.info(`[WorktreePool] drained worktree via fs.rm at ${meta.path}`);
- } catch (rmErr) {
- log.error(
- `[WorktreePool] fs.rm fallback failed for ${meta.path}:`,
- rmErr instanceof Error ? rmErr.message : String(rmErr),
- );
- throw rmErr;
- }
- }
+ const removed = await recycleManagedWorktree(meta, {
+ canRemove: async () => {
+ if (!meta.ephemeral || hasLiveSessionReference(meta, await loadLiveSessionPathKeys({ contextPath: meta.path }))) return false;
+ try { await fs.lstat(meta.path); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;
+ return false;
+ }
+ const recovery = await readRecycleRecord(meta.path);
+ return recovery?.phase === 'removing' && Boolean(recovery.archive && recovery.snapshot)
+ || !(await isWorktreeDirty(meta.path));
+ },
+ });
+ if (!removed) throw new Error('pooled worktree was preserved');
}
// pathKey / loadLiveSessionPathKeys / hasLiveSessionReference 已抽到 liveSessionRefs.ts
@@ -370,7 +367,7 @@ export async function drainOne(baseRepo: string): Promise<void> {
if (!entry) return;
pool.delete(key);
await drainEntry(entry.meta);
- store.del(entry.meta.sessionId);
+ await store.del(entry.meta.sessionId);
}
// ── park / recover ──────────────────────────────────────────────────────────
@@ -395,12 +392,14 @@ export async function recoverPool(): Promise<void> {
const sorted = all.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
for (const meta of sorted) {
+ if (!meta.ephemeral || hasLiveSessionReference(meta, liveSessionPathKeys)) continue;
// 1. 路径是否还存在
try {
await fs.access(meta.path);
- } catch {
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') continue;
log.info(`[WorktreePool] stale store entry removed: ${meta.path}`);
- store.del(meta.sessionId);
+ await drainEntry(meta).catch(() => undefined);
continue;
}
@@ -438,7 +437,7 @@ export async function recoverPool(): Promise<void> {
const drained = await drainEntry(meta)
.then(() => true)
.catch(() => false);
- if (drained) store.del(meta.sessionId);
+ if (drained) await store.del(meta.sessionId);
}
}
}
diff --git a/apps/desktop/src/main/worktree/contentSnapshot.ts b/apps/desktop/src/main/worktree/contentSnapshot.ts
new file mode 100644
index 0000000000..2dfe8cd080
--- /dev/null
+++ b/apps/desktop/src/main/worktree/contentSnapshot.ts
@@ -0,0 +1,63 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+
+import { gitExec } from './gitExec';
+import type { WorktreeRecycleRecord } from './recycleJournal';
+
+async function indexHash(worktreePath: string): Promise<string> {
+ const { stdout } = await gitExec(['rev-parse', '--path-format=absolute', '--git-path', 'index'], worktreePath);
+ return createHash('sha256').update(await fs.readFile(stdout.trim())).digest('hex');
+}
+
+export async function worktreeContentBaselineMatches(
+ worktreePath: string,
+ snapshot: NonNullable<WorktreeRecycleRecord['snapshot']>,
+): Promise<boolean> {
+ const { stdout } = await gitExec(['rev-parse', 'HEAD'], worktreePath);
+ return stdout.trim() === snapshot.head && await indexHash(worktreePath) === snapshot.indexHash;
+}
+
+/** Snapshot the actual HEAD, index and file tree without stashing or changing the live checkout. */
+export async function captureWorktreeContent(
+ worktreePath: string,
+ ref: string,
+): Promise<NonNullable<WorktreeRecycleRecord['snapshot']>> {
+ const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-index-'));
+ const index = path.join(temp, 'index');
+ const options = { extraEnv: { GIT_INDEX_FILE: index, GIT_OPTIONAL_LOCKS: '0' } };
+ try {
+ const { stdout: headOutput } = await gitExec(['rev-parse', '--verify', 'HEAD^{commit}'], worktreePath);
+ const head = headOutput.trim();
+ const { stdout: indexPath } = await gitExec(['rev-parse', '--path-format=absolute', '--git-path', 'index'], worktreePath);
+ await fs.copyFile(indexPath.trim(), index);
+ const originalIndexHash = createHash('sha256').update(await fs.readFile(index)).digest('hex');
+ const { stdout: staged } = await gitExec(['write-tree'], worktreePath, options);
+ const indexTree = staged.trim();
+ // Untracked/ignored bytes go exclusively to the encrypted recovery archive.
+ await gitExec(['add', '--update', '--', '.'], worktreePath, options);
+ const { stdout: contents } = await gitExec(['write-tree'], worktreePath, options);
+ const tree = contents.trim();
+ // Retain both trees through the snapshot ref, including staged-only bytes.
+ const identity = {
+ GIT_AUTHOR_NAME: 'Cindy', GIT_AUTHOR_EMAIL: 'worktree@localhost',
+ GIT_COMMITTER_NAME: 'Cindy', GIT_COMMITTER_EMAIL: 'worktree@localhost',
+ };
+ const commitOptions = { extraEnv: identity };
+ const { stdout: indexCommit } = await gitExec(
+ ['commit-tree', indexTree, '-p', head, '-m', 'Worktree index recovery'], worktreePath, commitOptions,
+ );
+ const { stdout: commitOutput } = await gitExec(
+ ['commit-tree', tree, '-p', head, '-p', indexCommit.trim(), '-m', 'Worktree content recovery'],
+ worktreePath, commitOptions,
+ );
+ const commit = commitOutput.trim();
+ await gitExec(['update-ref', ref, commit], worktreePath);
+ const snapshot = { head, tree, indexTree, commit, ref, indexHash: originalIndexHash };
+ if (!(await worktreeContentBaselineMatches(worktreePath, snapshot))) throw new Error('worktree HEAD or index changed during snapshot');
+ return snapshot;
+ } finally {
+ await fs.rm(temp, { recursive: true, force: true });
+ }
+}
diff --git a/apps/desktop/src/main/worktree/legacyRuntimeGuard.ts b/apps/desktop/src/main/worktree/legacyRuntimeGuard.ts
new file mode 100644
index 0000000000..d59439649f
--- /dev/null
+++ b/apps/desktop/src/main/worktree/legacyRuntimeGuard.ts
@@ -0,0 +1,17 @@
+import { app } from 'electron';
+import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';
+
+import { acquireWindowsPackagedInstanceBarrier } from '../windowsPackagedInstanceBarrier';
+
+/**
+ * Older Windows packaged builds have no instance/lease files. A dev process
+ * sharing their profile must hold the existing Chromium startup barrier while
+ * recycling. A packaged process already owns that profile's singleton itself.
+ */
+export async function withLegacyWorktreeRuntimeGuard<T>(task: (isHeld: () => boolean) => Promise<T>): Promise<T> {
+ if (process.platform !== 'win32' || app.isPackaged !== false) return task(() => true);
+ const lease = await acquireWindowsPackagedInstanceBarrier({
+ userDataDir: app.getPath('userData'), programName: BRAND_IDENTITY.executableName,
+ });
+ try { return await task(() => lease.isHeld()); } finally { await lease.release(); }
+}
diff --git a/apps/desktop/src/main/worktree/liveSessionRefs.ts b/apps/desktop/src/main/worktree/liveSessionRefs.ts
index 787e8fe486..8407ccc8d9 100644
--- a/apps/desktop/src/main/worktree/liveSessionRefs.ts
+++ b/apps/desktop/src/main/worktree/liveSessionRefs.ts
@@ -2,10 +2,9 @@
* live-session 引用判定(WorktreePool 与 WorktreeManager 删除路径共用)。
*
* 语义:某 worktree 路径若仍被其它会话的 workingDir / worktreePath 指向,就视为"在用",
- * 删除/淘汰路径必须保留它。显式归档/删除回收可提供运行态观察器:archived/deleted 只在确认
- * 对应 runtime 已关闭后才不再阻挡;其它调用方没有观察器时保守保留 archived,但继续忽略
- * deleted。查询失败时返回 null,消费方按"无法确认 → 视为在用"的保守方向处理。未知或 NULL
- * status 同样按在用处理。
+ * 删除/淘汰路径必须保留它。引用来自全部本地任务数据库和跨实例运行时租约;
+ * archived/deleted 只有在完整租约视图里无占用时才不阻挡,当前实例观察器可额外保留。
+ * 任一来源不可读、旧实例不支持租约、未知或 NULL status 均按在用处理。
*
* 原实现内联在 WorktreePool.ts(MR1),P0 重构把它抽出来给
* removeWorktreeForSession 的删除守卫复用,并支持排除会话自身
@@ -13,10 +12,12 @@
*/
import path from 'node:path';
-import { sql } from 'drizzle-orm';
+import fs from 'node:fs';
import { getDbClient } from '../localDb/client/current';
-import { sessions } from '../localDb/schema';
+import { physicalWorktreeKey } from './resourceLock';
+import { readWorktreeRuntimePaths } from './runtimeLeases';
+import * as store from './worktreeStore';
import { createLogger } from '../logger';
import type { WorktreeMeta } from './types';
@@ -52,7 +53,7 @@ export interface LoadLiveSessionPathKeysOptions {
* 不构成"仍在用";显式回收观察器存在时,其它终态会话仍需运行态证明才能排除。
*/
excludeSessionId?: string;
- /** 终态会话只有在该观察器明确返回 false 时才不再视为 live。 */
+ /** 对当前实例的额外占用证据;跨实例租约始终必须完整可读。 */
isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined;
}
@@ -60,35 +61,32 @@ export async function loadLiveSessionPathKeys(
opts: LoadLiveSessionPathKeysOptions = {},
): Promise<LiveSessionPathKeys> {
try {
- const db = getDbClient().drizzle;
- const rows = await db
- .select({
- id: sessions.id,
- status: sessions.status,
- workingDir: sessions.workingDir,
- worktreePath: sessions.worktreePath,
- })
- .from(sessions)
- .where(
- opts.isSessionRuntimeAlive
- ? sql`${sessions.workingDir} IS NOT NULL OR ${sessions.worktreePath} IS NOT NULL`
- : sql`${sessions.status} != 'deleted' OR ${sessions.status} IS NULL`,
- );
-
- const keys = new Set<string>();
+ const db = getDbClient();
+ if (!db.readLocalWorktreeReferences) return null;
+ const rows = await db.readLocalWorktreeReferences();
+ const runtimePaths = await readWorktreeRuntimePaths();
+ if (!runtimePaths) return null;
+ const keys = new Set(runtimePaths);
+ const knownSessionIds = new Set(rows.map((row) => row.id));
+ for (const meta of store.getAll()) {
+ if (meta.sessionId !== opts.excludeSessionId && !knownSessionIds.has(meta.sessionId)) {
+ keys.add(await physicalWorktreeKey(meta.path));
+ }
+ }
for (const row of rows) {
- if (opts.excludeSessionId && row.id === opts.excludeSessionId) continue;
+ // The same id in another database is not the row the caller just closed.
+ if (row.currentDatabase && opts.excludeSessionId && row.id === opts.excludeSessionId) continue;
const isTerminal = row.status === 'archived' || row.status === 'deleted';
- if (!opts.isSessionRuntimeAlive && row.status === 'deleted') {
- continue;
- }
- if (isTerminal && opts.isSessionRuntimeAlive?.(row.id) === false) {
+ if (row.source !== 'bot' && isTerminal && (!row.currentDatabase || opts.isSessionRuntimeAlive?.(row.id) !== true)) {
continue;
}
const workingDirKey = pathKey(row.workingDir);
const worktreePathKey = pathKey(row.worktreePath);
if (workingDirKey) keys.add(workingDirKey);
if (worktreePathKey) keys.add(worktreePathKey);
+ for (const value of [row.workingDir, row.worktreePath]) {
+ if (value) keys.add(await physicalWorktreeKey(value));
+ }
}
return keys;
} catch (err) {
@@ -102,13 +100,21 @@ export async function loadLiveSessionPathKeys(
}
export function hasLiveSessionReference(
- meta: WorktreeMeta,
+ meta: Pick<WorktreeMeta, 'path' | 'quarantinePath'>,
liveSessionPathKeys: LiveSessionPathKeys,
): boolean {
if (!liveSessionPathKeys) return true;
const targets = [meta.path, meta.quarantinePath]
.map((value) => pathKey(value))
.filter((value): value is string => value !== null);
+ for (const value of [...targets]) {
+ try {
+ const real = pathKey(fs.realpathSync(value));
+ if (real && !targets.includes(real)) targets.push(real);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return true;
+ }
+ }
if (targets.length === 0) return true;
for (const target of targets) {
for (const candidate of liveSessionPathKeys) {
diff --git a/apps/desktop/src/main/worktree/managedRecycle.ts b/apps/desktop/src/main/worktree/managedRecycle.ts
new file mode 100644
index 0000000000..9060887c8c
--- /dev/null
+++ b/apps/desktop/src/main/worktree/managedRecycle.ts
@@ -0,0 +1,223 @@
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import { captureWorktreeContent, worktreeContentBaselineMatches } from './contentSnapshot';
+import { gitExec } from './gitExec';
+import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRefs';
+import {
+ newRecycleRecord, readRecycleRecord, writeRecycleRecord, worktreeGeneration,
+ type WorktreeRecycleRecord,
+} from './recycleJournal';
+import { createRecoveryArchive, inventoryWorktree, sameWorktreeFiles, verifyRecoveryArchive } from './recoveryArchive';
+import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
+import { isManagedWorktreePath } from './safety';
+import { assertManagedResourcePath, assertWorktreeGitIdentity } from './resourceSafety';
+import * as store from './worktreeStore';
+import type { WorktreeMeta } from './types';
+import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';
+
+export interface ManagedRecycleOptions {
+ canRemove?: () => Promise<boolean>;
+ isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined;
+ onRemoved?: () => Promise<void>;
+}
+
+/** Pool reset is destructive too: preserve the old generation before clean/reset. */
+export async function checkpointWorktreeForReuse(meta: WorktreeMeta): Promise<void> {
+ const current = store.get(meta.sessionId);
+ if (!current || worktreeGeneration(current) !== worktreeGeneration(meta) || await hasOtherGeneration(meta)) throw new Error('pooled generation changed');
+ await assertManagedResourcePath(meta, store.getAllPaths());
+ await assertWorktreeGitIdentity(meta);
+ if (hasLiveSessionReference(meta, await loadLiveSessionPathKeys({ contextPath: meta.path }))) {
+ throw new Error('pooled worktree is referenced');
+ }
+ const record = await newRecycleRecord(meta);
+ record.directoryIdentity = (await directoryIdentity(meta.path)) ?? undefined;
+ if (!record.directoryIdentity || !isManagedWorktreePath(meta.path, meta.baseRepo, store.getAllPaths())) {
+ throw new Error('pooled worktree path is unsafe');
+ }
+ const gitLink = await fs.lstat(path.join(meta.path, '.git'));
+ if (!gitLink.isFile() || gitLink.isSymbolicLink()) throw new Error('pooled worktree Git link is missing');
+ record.archive = await createRecoveryArchive(meta.path, record.id);
+ record.snapshot = await captureWorktreeContent(meta.path, `refs/cindy/worktree-recovery/${record.id}/${randomUUID()}`);
+ if (hasLiveSessionReference(meta, await loadLiveSessionPathKeys({ contextPath: meta.path }))
+ || !(await worktreeContentBaselineMatches(meta.path, record.snapshot))
+ || !sameWorktreeFiles(await inventoryWorktree(meta.path), record.archive.files)) {
+ throw new Error('pooled worktree changed before reuse');
+ }
+ await assertManagedResourcePath(meta, store.getAllPaths());
+ await assertWorktreeGitIdentity(meta);
+ if (await directoryIdentity(meta.path) !== record.directoryIdentity) throw new Error('pooled directory replaced');
+ record.phase = 'removed';
+ await writeRecycleRecord(record);
+}
+
+async function directoryIdentity(value: string): Promise<string | null> {
+ try {
+ const stat = await fs.lstat(value);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('worktree directory identity is unsafe');
+ return `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
+/** Written before the terminal status mutation, so a crash cannot lose the cleanup intent. */
+export async function requestWorktreeRecycle(sessionId: string, resourcePaths: readonly string[] = []): Promise<void> {
+ const own = store.get(sessionId);
+ const paths = new Set(await Promise.all(resourcePaths.map(physicalWorktreeKey)));
+ const candidates = own ? [own] : store.getAll();
+ for (const meta of candidates) {
+ if (meta.ephemeral || (!own && !paths.has(await physicalWorktreeKey(meta.path)))) continue;
+ await withWorktreeResourceLock(meta.path, async () => {
+ if (worktreeGeneration(store.get(meta.sessionId) ?? meta) !== worktreeGeneration(meta) || await hasOtherGeneration(meta)) return;
+ const previous = await readRecycleRecord(meta.path);
+ if (previous?.generation === worktreeGeneration(meta) && previous.phase !== 'restored') return;
+ const record = await newRecycleRecord(meta);
+ record.directoryIdentity = (await directoryIdentity(meta.path)) ?? undefined;
+ await writeRecycleRecord(record);
+ });
+ }
+}
+
+/** Complete a single durable request. Failure preserves registration and retry evidence. */
+export async function recycleManagedWorktree(meta: WorktreeMeta, options: ManagedRecycleOptions): Promise<boolean> {
+ return withWorktreeResourceLock(meta.path, () => withLegacyWorktreeRuntimeGuard(async (legacyGuardHeld) => {
+ const registered = store.get(meta.sessionId);
+ if (registered && worktreeGeneration(registered) !== worktreeGeneration(meta)) return false;
+ if (await hasOtherGeneration(meta)) return false;
+ let record = await readRecycleRecord(meta.path);
+ if (!record || record.generation !== worktreeGeneration(meta)) {
+ record = await newRecycleRecord(meta);
+ record.directoryIdentity = (await directoryIdentity(meta.path)) ?? undefined;
+ await writeRecycleRecord(record);
+ }
+ const defer = async (reason: string): Promise<false> => {
+ record.reason = reason;
+ record.attempts += 1;
+ record.nextAttemptAt = Date.now() + Math.min(30 * 60_000, 5_000 * 2 ** Math.min(record.attempts, 9));
+ await writeRecycleRecord(record);
+ return false;
+ };
+ const canRemove = async (): Promise<boolean> => {
+ if (!legacyGuardHeld()) return false;
+ if (!options.canRemove || !(await options.canRemove())) return false;
+ const current = store.get(meta.sessionId);
+ if (current && worktreeGeneration(current) !== record.generation) return false;
+ const refs = await loadLiveSessionPathKeys({
+ contextPath: meta.path, excludeSessionId: meta.sessionId,
+ isSessionRuntimeAlive: options.isSessionRuntimeAlive,
+ });
+ return !hasLiveSessionReference({ ...meta, path: await physicalWorktreeKey(meta.path) }, refs);
+ };
+ try {
+ if (meta.quarantinePath) return defer('legacy-quarantine-needs-review');
+ if (!(await canRemove())) return defer('referenced-or-runtime-unavailable');
+ const identity = await directoryIdentity(meta.path);
+ if (identity === null) {
+ record.phase = 'removed';
+ await writeRecycleRecord(record);
+ await options.onRemoved?.();
+ await unregisterResource(meta);
+ return true;
+ }
+ if (record.directoryIdentity && identity !== record.directoryIdentity) return defer('directory-replaced');
+ if (!isManagedWorktreePath(meta.path, meta.baseRepo, store.getAllPaths())) return defer('unmanaged-path');
+ const realParent = await physicalWorktreeKey(path.dirname(meta.path));
+ const expectedParent = path.join(await physicalWorktreeKey(meta.baseRepo), path.basename(path.dirname(meta.path)));
+ if (realParent !== expectedParent) return defer('redirected-worktree-parent');
+ try {
+ await fs.lstat(path.join(meta.path, '.worktree-keep'));
+ return defer('keep-sentinel');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ record.directoryIdentity = identity;
+ await assertManagedResourcePath(meta, store.getAllPaths());
+ const partialRemoval = record.phase === 'removing' && record.snapshot && record.archive;
+ if (!partialRemoval) {
+ // A missing .git must never fall through to the parent repository.
+ await assertWorktreeGitIdentity(meta);
+ // Save all bytes, including ignored files, before touching the live directory.
+ if (!record.archive || !sameWorktreeFiles(await inventoryWorktree(meta.path), record.archive.files)) {
+ record.archive = await createRecoveryArchive(meta.path, record.id);
+ record.snapshot = undefined;
+ await writeRecycleRecord(record);
+ }
+ if (!record.snapshot || !(await worktreeContentBaselineMatches(meta.path, record.snapshot))) {
+ record.snapshot = await captureWorktreeContent(meta.path, `refs/cindy/worktree-recovery/${record.id}/${randomUUID()}`);
+ }
+ record.phase = 'snapshotted';
+ await writeRecycleRecord(record);
+ }
+ if (!record.archive || !record.snapshot) return defer('recovery-evidence-missing');
+ await verifyRecoveryArchive(record.archive);
+ if (!sameWorktreeFiles(await inventoryWorktree(meta.path), record.archive.files, Boolean(partialRemoval))) {
+ return defer('files-changed');
+ }
+ if (!(await canRemove())) return defer('referenced-before-removal');
+ if (await directoryIdentity(meta.path) !== identity) return defer('directory-replaced');
+ await assertManagedResourcePath(meta, store.getAllPaths());
+ let gitLinkPresent = true;
+ try { await fs.lstat(path.join(meta.path, '.git')); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ gitLinkPresent = false;
+ }
+ if (!partialRemoval || gitLinkPresent) {
+ await assertWorktreeGitIdentity(meta);
+ if (!(await worktreeContentBaselineMatches(meta.path, record.snapshot))) return defer('git-baseline-changed');
+ }
+ record.phase = 'removing';
+ await writeRecycleRecord(record);
+ try {
+ await gitExec(['-c', 'core.longpaths=true', 'worktree', 'remove', '--force', meta.path], meta.baseRepo);
+ } catch {
+ // Git may remove .git before Windows reports EBUSY. Only delete surviving
+ // bytes still covered by this generation's authenticated recovery archive.
+ if (await directoryIdentity(meta.path) !== identity) return defer('remove-unconfirmed');
+ if (!(await canRemove())) return defer('referenced-before-fallback');
+ if (!sameWorktreeFiles(await inventoryWorktree(meta.path), record.archive.files, true)) return defer('residual-files-changed');
+ await assertManagedResourcePath(meta, store.getAllPaths());
+ let hasGit = true;
+ try { await fs.lstat(path.join(meta.path, '.git')); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ hasGit = false;
+ }
+ if (hasGit) {
+ await assertWorktreeGitIdentity(meta);
+ if (!(await worktreeContentBaselineMatches(meta.path, record.snapshot))) return defer('git-baseline-changed');
+ }
+ if (await directoryIdentity(meta.path) !== identity) return defer('directory-replaced');
+ await fs.rm(meta.path, { recursive: true, force: true });
+ }
+ if (await directoryIdentity(meta.path) !== null) return defer('directory-still-present');
+ await gitExec(['worktree', 'prune'], meta.baseRepo);
+ record.phase = 'removed';
+ record.reason = undefined;
+ await writeRecycleRecord(record);
+ await options.onRemoved?.();
+ await unregisterResource(meta);
+ return true;
+ } catch (error) {
+ return defer((error as NodeJS.ErrnoException).code ?? 'recycle-failed');
+ }
+ }));
+}
+
+async function unregisterResource(meta: WorktreeMeta): Promise<void> {
+ const physicalPath = await physicalWorktreeKey(meta.path);
+ for (const entry of store.getAll()) {
+ if (await physicalWorktreeKey(entry.path) === physicalPath) await store.del(entry.sessionId);
+ }
+}
+
+async function hasOtherGeneration(meta: WorktreeMeta): Promise<boolean> {
+ const physicalPath = await physicalWorktreeKey(meta.path);
+ for (const entry of store.getAll()) {
+ if (worktreeGeneration(entry) !== worktreeGeneration(meta)
+ && await physicalWorktreeKey(entry.path) === physicalPath) return true;
+ }
+ return false;
+}
diff --git a/apps/desktop/src/main/worktree/recoveryArchive.ts b/apps/desktop/src/main/worktree/recoveryArchive.ts
new file mode 100644
index 0000000000..9cb1e7bd6f
--- /dev/null
+++ b/apps/desktop/src/main/worktree/recoveryArchive.ts
@@ -0,0 +1,160 @@
+import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from 'node:crypto';
+import { createReadStream, createWriteStream } from 'node:fs';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { pipeline } from 'node:stream/promises';
+import { safeStorage } from 'electron';
+import * as tar from 'tar';
+
+import { recycleJournalRoot } from './recycleJournal';
+
+interface FileEvidence {
+ kind: 'file' | 'link' | 'directory';
+ hash: string;
+ mode: number;
+}
+
+/** Compressed, encrypted local recovery bytes; secrets never enter Git objects. */
+export interface WorktreeRecoveryArchive {
+ file: string;
+ encryptedKey: string;
+ iv: string;
+ tag: string;
+ files: Record<string, FileEvidence>;
+}
+
+function restorableMode(mode: number): number {
+ // Windows exposes read/write attributes; tar adds synthetic directory execute bits.
+ return mode & (process.platform === 'win32' ? 0o666 : 0o777);
+}
+
+export async function inventoryWorktree(root: string): Promise<Record<string, FileEvidence>> {
+ const files: Record<string, FileEvidence> = Object.create(null);
+ const walk = async (directory: string): Promise<void> => {
+ for (const name of await fs.readdir(directory)) {
+ if (directory === root && name === '.git') continue;
+ const absolute = path.join(directory, name);
+ const stat = await fs.lstat(absolute);
+ const relative = path.relative(root, absolute);
+ const mode = restorableMode(stat.mode);
+ if (stat.isSymbolicLink()) {
+ files[relative] = { kind: 'link', hash: await fs.readlink(absolute), mode };
+ } else if (stat.isDirectory()) {
+ files[relative] = { kind: 'directory', hash: '', mode };
+ await walk(absolute);
+ } else if (stat.isFile()) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(absolute)) hash.update(chunk);
+ files[relative] = { kind: 'file', hash: hash.digest('hex'), mode };
+ } else {
+ throw new Error('worktree contains an unsupported filesystem entry');
+ }
+ }
+ };
+ await walk(root);
+ return files;
+}
+
+export function sameWorktreeFiles(
+ actual: Record<string, FileEvidence>,
+ saved: Record<string, FileEvidence>,
+ allowMissing = false,
+): boolean {
+ if (!allowMissing && Object.keys(actual).length !== Object.keys(saved).length) return false;
+ return Object.entries(actual).every(([name, file]) => {
+ const expected = saved[name];
+ return expected?.kind === file.kind && expected.hash === file.hash && expected.mode === file.mode;
+ });
+}
+
+function archivePath(archive: Pick<WorktreeRecoveryArchive, 'file'>): string {
+ if (!/^[a-f0-9-]+\.tar\.gz\.enc$/.test(archive.file)) throw new Error('invalid recovery archive path');
+ return path.join(recycleJournalRoot(), archive.file);
+}
+
+function decryptArchive(archive: WorktreeRecoveryArchive) {
+ const key = Buffer.from(safeStorage.decryptString(Buffer.from(archive.encryptedKey, 'base64')), 'base64');
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(archive.iv, 'base64'));
+ key.fill(0);
+ decipher.setAuthTag(Buffer.from(archive.tag, 'base64'));
+ return decipher;
+}
+
+/** Fully authenticate before any restore is allowed to emit plaintext files. */
+export async function verifyRecoveryArchive(archive: WorktreeRecoveryArchive): Promise<void> {
+ const files: Record<string, FileEvidence> = Object.create(null);
+ const entries: Promise<void>[] = [];
+ const parser = tar.t({
+ strict: true,
+ onReadEntry(entry) {
+ const name = path.normalize(entry.path).replace(/[\\/]+$/, '');
+ if (path.isAbsolute(name) || name === '..' || name.startsWith(`..${path.sep}`) || name === '.git') {
+ throw new Error('unsafe worktree archive entry');
+ }
+ const check = (async () => {
+ if (files[name]) throw new Error('duplicate worktree archive entry');
+ const hash = createHash('sha256');
+ for await (const chunk of entry) hash.update(chunk);
+ const mode = restorableMode(entry.mode ?? 0);
+ if (entry.type === 'Directory') files[name] = { kind: 'directory', hash: '', mode };
+ else if (entry.type === 'SymbolicLink') {
+ if (typeof entry.linkpath !== 'string') throw new Error('invalid archive symbolic link');
+ files[name] = { kind: 'link', hash: entry.linkpath, mode };
+ }
+ else if (entry.type === 'Link') {
+ if (typeof entry.linkpath !== 'string') throw new Error('invalid archive hard link');
+ const target = archive.files[path.normalize(entry.linkpath)];
+ if (target?.kind !== 'file') throw new Error('invalid archive hard link');
+ files[name] = { ...target, mode };
+ } else if (entry.type === 'File') files[name] = { kind: 'file', hash: hash.digest('hex'), mode };
+ else throw new Error('unsupported worktree archive entry');
+ })();
+ // Handle rejection immediately even while the remaining encrypted stream drains.
+ void check.catch(() => {});
+ entries.push(check);
+ },
+ });
+ await pipeline(createReadStream(archivePath(archive)), decryptArchive(archive), parser);
+ await Promise.all(entries);
+ if (!sameWorktreeFiles(files, archive.files)) throw new Error('archive content does not match worktree inventory');
+}
+
+export async function createRecoveryArchive(root: string, resourceId: string): Promise<WorktreeRecoveryArchive> {
+ const files = await inventoryWorktree(root);
+ const key = randomBytes(32);
+ const iv = randomBytes(12);
+ const encryptedKey = safeStorage.encryptString(key.toString('base64')).toString('base64');
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
+ key.fill(0);
+ const file = `${resourceId}-${randomUUID()}.tar.gz.enc`;
+ await fs.mkdir(recycleJournalRoot(), { recursive: true });
+ const target = archivePath({ file });
+ try {
+ await pipeline(
+ tar.c({ cwd: root, gzip: true, follow: false, noDirRecurse: true, strict: true }, Object.keys(files)),
+ cipher,
+ createWriteStream(target, { flags: 'wx', mode: 0o600 }),
+ );
+ const handle = await fs.open(target, 'r+');
+ try { await handle.sync(); } finally { await handle.close(); }
+ const archive = { file, encryptedKey, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), files };
+ await verifyRecoveryArchive(archive);
+ if (!sameWorktreeFiles(await inventoryWorktree(root), files)) throw new Error('worktree changed during archive');
+ return archive;
+ } catch (error) {
+ await fs.rm(target, { force: true });
+ throw error;
+ }
+}
+
+/** Authenticate first; keep mode fills only missing bytes of a verified partial restore. */
+export async function extractRecoveryArchive(archive: WorktreeRecoveryArchive, staging: string, keep = false): Promise<void> {
+ await verifyRecoveryArchive(archive);
+ await pipeline(
+ createReadStream(archivePath(archive)), decryptArchive(archive),
+ tar.x({ cwd: staging, strict: true, preservePaths: false, unlink: !keep, keep }),
+ );
+ if (!sameWorktreeFiles(await inventoryWorktree(staging), archive.files)) {
+ throw new Error('restored worktree files do not match recovery archive');
+ }
+}
diff --git a/apps/desktop/src/main/worktree/recycleJournal.ts b/apps/desktop/src/main/worktree/recycleJournal.ts
new file mode 100644
index 0000000000..f7d322e200
--- /dev/null
+++ b/apps/desktop/src/main/worktree/recycleJournal.ts
@@ -0,0 +1,133 @@
+import { createHash, randomUUID } from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { app } from 'electron';
+
+import { physicalWorktreeKey, worktreeResourceId } from './resourceLock';
+import type { WorktreeMeta } from './types';
+import type { WorktreeRecoveryArchive } from './recoveryArchive';
+import { createLogger } from '../logger';
+
+const log = createLogger('worktreeRecycleJournal');
+
+/** Durable deletion intent and recovery evidence, independent of the active task ledger. */
+export interface WorktreeRecycleRecord {
+ version: 1;
+ id: string;
+ generation: string;
+ meta: WorktreeMeta;
+ requestedAt: string;
+ phase: 'pending' | 'snapshotted' | 'removing' | 'removed' | 'restoring' | 'restored';
+ attempts: number;
+ nextAttemptAt: number;
+ reason?: string;
+ directoryIdentity?: string;
+ snapshot?: { head: string; tree: string; indexTree: string; commit: string; ref: string; indexHash: string };
+ restoredGeneration?: string;
+ archive?: WorktreeRecoveryArchive;
+}
+
+export function recycleJournalRoot(): string {
+ return path.join(app.getPath('userData'), 'worktree-recycle');
+}
+
+export function worktreeGeneration(meta: WorktreeMeta): string {
+ return meta.generation ?? `${meta.sessionId}:${meta.createdAt}`;
+}
+
+function parseRecord(raw: string, id: string): WorktreeRecycleRecord {
+ const record = JSON.parse(raw) as WorktreeRecycleRecord;
+ if (!record || record.version !== 1 || record.id !== id || !record.meta
+ || typeof record.generation !== 'string' || !record.generation
+ || typeof record.meta.sessionId !== 'string' || !record.meta.sessionId
+ || typeof record.meta.path !== 'string' || !path.isAbsolute(record.meta.path)
+ || typeof record.meta.baseRepo !== 'string' || !path.isAbsolute(record.meta.baseRepo)
+ || typeof record.requestedAt !== 'string' || !Number.isFinite(Date.parse(record.requestedAt))
+ || !Number.isInteger(record.attempts) || record.attempts < 0
+ || !Number.isFinite(record.nextAttemptAt)
+ || !['pending', 'snapshotted', 'removing', 'removed', 'restoring', 'restored'].includes(record.phase)) {
+ throw new Error('invalid worktree recycle record');
+ }
+ return record;
+}
+
+export async function readRecycleRecord(value: string, sessionId?: string): Promise<WorktreeRecycleRecord | null> {
+ const id = worktreeResourceId(await physicalWorktreeKey(value));
+ try {
+ const record = parseRecord(await fs.readFile(path.join(recycleJournalRoot(), `${id}.json`), 'utf8'), id);
+ if (!sessionId || record.meta.sessionId === sessionId) return record;
+ const history = path.join(recycleJournalRoot(), 'history');
+ let names: string[];
+ try { names = await fs.readdir(history); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+ const matches: WorktreeRecycleRecord[] = [];
+ for (const name of names.filter((name) => name.startsWith(`${id}-`) && name.endsWith('.json'))) {
+ const candidate = parseRecord(await fs.readFile(path.join(history, name), 'utf8'), id);
+ if (candidate.meta.sessionId === sessionId) matches.push(candidate);
+ }
+ return matches.sort((a, b) => b.requestedAt.localeCompare(a.requestedAt))[0] ?? null;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
+/** Caller holds the physical resource lock. Atomic per-resource files cannot lose another resource's update. */
+export async function writeRecycleRecord(record: WorktreeRecycleRecord): Promise<void> {
+ if (!/^[a-f0-9]{64}$/.test(record.id)) throw new Error('invalid worktree resource id');
+ const root = recycleJournalRoot();
+ await fs.mkdir(root, { recursive: true });
+ if (record.archive && record.snapshot && record.phase === 'removed') {
+ const history = path.join(root, 'history');
+ await fs.mkdir(history, { recursive: true });
+ const key = createHash('sha256').update(`${record.generation}:${record.requestedAt}:${record.snapshot.commit}`).digest('hex');
+ await writeRecordFile(path.join(history, `${record.id}-${key}.json`), record);
+ }
+ await writeRecordFile(path.join(root, `${record.id}.json`), record);
+}
+
+async function writeRecordFile(target: string, record: WorktreeRecycleRecord): Promise<void> {
+ const temp = `${target}.${randomUUID()}.tmp`;
+ try {
+ const handle = await fs.open(temp, 'wx', 0o600);
+ try {
+ await handle.writeFile(JSON.stringify(record));
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+ await fs.rename(temp, target);
+ } finally {
+ await fs.rm(temp, { force: true });
+ }
+}
+
+export async function newRecycleRecord(meta: WorktreeMeta): Promise<WorktreeRecycleRecord> {
+ return {
+ version: 1, id: worktreeResourceId(await physicalWorktreeKey(meta.path)),
+ generation: worktreeGeneration(meta), meta, requestedAt: new Date().toISOString(),
+ phase: 'pending', attempts: 0, nextAttemptAt: 0,
+ };
+}
+
+/** Fail closed for a malformed file; callers report the failure without discarding evidence. */
+export async function listRecycleRecords(): Promise<WorktreeRecycleRecord[]> {
+ let names: string[];
+ try {
+ names = await fs.readdir(recycleJournalRoot());
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+ const records: WorktreeRecycleRecord[] = [];
+ for (const name of names.filter((value) => /^[a-f0-9]{64}\.json$/.test(value))) {
+ try {
+ records.push(parseRecord(await fs.readFile(path.join(recycleJournalRoot(), name), 'utf8'), name.slice(0, -5)));
+ } catch {
+ log.warn('invalid worktree recycle request preserved', { resourceId: name.slice(0, -5) });
+ }
+ }
+ return records;
+}
diff --git a/apps/desktop/src/main/worktree/recycleMaintenance.ts b/apps/desktop/src/main/worktree/recycleMaintenance.ts
new file mode 100644
index 0000000000..95875c8050
--- /dev/null
+++ b/apps/desktop/src/main/worktree/recycleMaintenance.ts
@@ -0,0 +1,147 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { app } from 'electron';
+
+import { getDbClient } from '../localDb/client/current';
+import { createLogger } from '../logger';
+import { listRecycleRecords, readRecycleRecord, worktreeGeneration } from './recycleJournal';
+import { recycleManagedWorktree } from './managedRecycle';
+import { hasLiveSessionReference, loadLiveSessionPathKeys, pathKey } from './liveSessionRefs';
+import * as store from './worktreeStore';
+import { physicalWorktreeKey, worktreeResourceId } from './resourceLock';
+
+const log = createLogger('worktreeRecycleMaintenance');
+let timer: ReturnType<typeof setInterval> | null = null;
+let running: Promise<void> | null = null;
+let pending = false;
+let pendingForce = false;
+let lastOptions: WorktreeMaintenanceOptions | null = null;
+const attemptsThisRun = new Map<string, number>();
+
+export interface WorktreeMaintenanceOptions {
+ isReady(): boolean;
+ recycleCurrentSession(sessionId: string, status: string): Promise<void>;
+ onAttemptComplete?(): Promise<void>;
+}
+
+/** Starts once both task storage and runtime-close services are usable. Repeated ready signals coalesce. */
+export function startWorktreeRecycleMaintenance(options: WorktreeMaintenanceOptions): void {
+ lastOptions = options;
+ if (!timer) {
+ timer = setInterval(() => { void runWorktreeRecycleMaintenance(options); }, 30_000);
+ timer.unref();
+ }
+ void runWorktreeRecycleMaintenance(options);
+}
+
+export function stopWorktreeRecycleMaintenance(): void {
+ if (timer) clearInterval(timer);
+ timer = null;
+ attemptsThisRun.clear();
+ lastOptions = null;
+}
+
+/** A stopped runtime is new evidence, so it can wake a request held by backoff. */
+export function notifyWorktreeRecycleOpportunity(physicalPath: string): void {
+ if (!lastOptions) return;
+ const prefix = `${worktreeResourceId(physicalPath)}:`;
+ for (const key of attemptsThisRun.keys()) if (key.startsWith(prefix)) attemptsThisRun.delete(key);
+ void runWorktreeRecycleMaintenance(lastOptions, true);
+}
+
+export function runWorktreeRecycleMaintenance(options: WorktreeMaintenanceOptions, force = false): Promise<void> {
+ pendingForce ||= force;
+ if (running) {
+ pending = true;
+ return running;
+ }
+ running = (async () => {
+ do {
+ pending = false;
+ const forcePass = pendingForce;
+ pendingForce = false;
+ if (!options.isReady()) return;
+ try {
+ await retryRequestedWorktrees(options, forcePass);
+ } catch (error) {
+ log.warn('worktree retry postponed', error instanceof Error ? error.message : String(error));
+ }
+ } while (pending);
+ })().finally(() => { running = null; });
+ return running;
+}
+
+async function retryRequestedWorktrees(options: WorktreeMaintenanceOptions, force: boolean): Promise<void> {
+ const db = getDbClient();
+ if (!db.readLocalWorktreeReferences) return;
+ const rows = await db.readLocalWorktreeReferences();
+ let attempted = false;
+ for (const record of await listRecycleRecords()) {
+ if (!options.isReady() || getDbClient() !== db) return;
+ if (record.phase === 'restored' || record.phase === 'restoring') continue;
+ if (record.phase === 'removed' && !store.get(record.meta.sessionId)) continue;
+ if (!force && record.nextAttemptAt > Date.now()) continue;
+ const budgetKey = `${record.id}:${record.generation}`;
+ if ((attemptsThisRun.get(budgetKey) ?? 0) >= 8) continue;
+ const currentMeta = store.get(record.meta.sessionId);
+ if (currentMeta && worktreeGeneration(currentMeta) !== record.generation) continue;
+ const ownerRows = rows.filter((row) => row.id === record.meta.sessionId);
+ // Unknown is not an orphan, including after switching the selected account.
+ if (!ownerRows.length || ownerRows.some((row) => row.source === 'bot' || (row.status !== 'archived' && row.status !== 'deleted'))) continue;
+ attemptsThisRun.set(budgetKey, (attemptsThisRun.get(budgetKey) ?? 0) + 1);
+ attempted = true;
+ try {
+ const currentRow = ownerRows.find((row) => row.currentDatabase);
+ if (currentRow) {
+ await options.recycleCurrentSession(record.meta.sessionId, currentRow.status!);
+ } else {
+ // Other local databases contribute evidence only. Their runtimes must be
+ // absent by the machine-wide lease guard; never close a task through the wrong DB.
+ await recycleManagedWorktree(record.meta, {
+ canRemove: async () => {
+ if (!options.isReady() || getDbClient() !== db) return false;
+ const latest = (await db.readLocalWorktreeReferences!()).filter((row) => row.id === record.meta.sessionId);
+ const request = await readRecycleRecord(record.meta.path);
+ return request?.generation === record.generation && latest.length > 0
+ && latest.every((row) => row.source !== 'bot' && (row.status === 'archived' || row.status === 'deleted'));
+ },
+ });
+ }
+ } catch (error) {
+ log.warn('worktree request postponed', { resourceId: record.id, code: (error as NodeJS.ErrnoException).code ?? 'unavailable' });
+ }
+ }
+ if (attempted) await options.onAttemptComplete?.();
+}
+
+/** Read-only classification: upgrading never turns historical registrations into deletion requests. */
+export async function auditRegisteredWorktrees(): Promise<void> {
+ const refs = await loadLiveSessionPathKeys();
+ const entries = [];
+ for (const meta of store.getAll()) {
+ let directory: 'present' | 'missing' | 'unreadable' | 'residual' = 'present';
+ let physicalPath = pathKey(meta.path);
+ try {
+ await fs.lstat(meta.path);
+ physicalPath = await physicalWorktreeKey(meta.path);
+ try { await fs.lstat(path.join(meta.path, '.git')); } catch (error) {
+ directory = (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'residual' : 'unreadable';
+ }
+ } catch (error) {
+ directory = (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unreadable';
+ }
+ const record = await readRecycleRecord(meta.path);
+ entries.push({ sessionId: meta.sessionId, path: meta.path, physicalPath, directory,
+ referenced: refs === null ? null : hasLiveSessionReference(meta, refs),
+ recycle: record?.phase ?? 'historical-review', reason: record?.reason,
+ });
+ }
+ const summary = {
+ registered: entries.length,
+ physicalPaths: new Set(entries.map((entry) => entry.physicalPath)).size,
+ existingDirectories: new Set(entries.filter((entry) => entry.directory === 'present' || entry.directory === 'residual').map((entry) => entry.physicalPath)).size,
+ referencedPaths: new Set(entries.filter((entry) => entry.referenced).map((entry) => entry.physicalPath)).size,
+ };
+ await fs.writeFile(path.join(app.getPath('userData'), 'worktree-audit.json'), JSON.stringify({ at: new Date().toISOString(), summary, entries }), { mode: 0o600 });
+ log.info('worktree registry audit completed', summary);
+}
diff --git a/apps/desktop/src/main/worktree/resourceLock.ts b/apps/desktop/src/main/worktree/resourceLock.ts
new file mode 100644
index 0000000000..d1584a90fd
--- /dev/null
+++ b/apps/desktop/src/main/worktree/resourceLock.ts
@@ -0,0 +1,57 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { withCrossProcessLock } from '../device-link/crossProcessLock';
+
+const heldResources = new AsyncLocalStorage<ReadonlyMap<string, { active: boolean }>>();
+
+/** Resolve aliases even while the leaf directory is absent during restore. */
+export async function physicalWorktreeKey(value: string): Promise<string> {
+ let cursor = path.resolve(value);
+ const suffix: string[] = [];
+ for (;;) {
+ try {
+ const real = path.join(await fs.realpath(cursor), ...suffix);
+ return process.platform === 'win32' ? real.toLowerCase() : real;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ const parent = path.dirname(cursor);
+ if (parent === cursor) throw error;
+ suffix.unshift(path.basename(cursor));
+ cursor = parent;
+ }
+ }
+}
+
+export function worktreeResourceId(key: string): string {
+ return createHash('sha256').update(key).digest('hex');
+}
+
+/** One physical directory, across tasks, aliases and Cindy processes. */
+export async function withWorktreeResourceLock<T>(value: string, task: () => Promise<T>): Promise<T> {
+ const key = await physicalWorktreeKey(value);
+ const inherited = heldResources.getStore();
+ if (inherited?.get(key)?.active) return task();
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
+ const lockPath = path.join(os.tmpdir(), `cindy-worktree-${uid}-${worktreeResourceId(key)}.lock`);
+ return withCrossProcessLock(lockPath, { label: 'worktree-resource', waitMs: 10_000 }, async (lock) => {
+ if (!lock.held) throw new Error('worktree resource is busy');
+ const token = { active: true };
+ try {
+ return await heldResources.run(new Map([...(inherited ?? []), [key, token]]), task);
+ } finally {
+ token.active = false;
+ }
+ });
+}
+
+/** Stable physical ordering prevents overlapping batch status/move operations from deadlocking. */
+export async function withWorktreeResourceLocks<T>(values: readonly string[], task: () => Promise<T>): Promise<T> {
+ const keys = [...new Set(await Promise.all(values.map(physicalWorktreeKey)))].sort();
+ const acquire = (index: number): Promise<T> => keys[index]
+ ? withWorktreeResourceLock(keys[index], () => acquire(index + 1)) : task();
+ return acquire(0);
+}
diff --git a/apps/desktop/src/main/worktree/resourceSafety.ts b/apps/desktop/src/main/worktree/resourceSafety.ts
new file mode 100644
index 0000000000..7f4c7bac4b
--- /dev/null
+++ b/apps/desktop/src/main/worktree/resourceSafety.ts
@@ -0,0 +1,52 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import { gitExec } from './gitExec';
+import { physicalWorktreeKey } from './resourceLock';
+import { isManagedWorktreeDirectoryName } from '../../shared/managedWorktreePaths';
+import type { WorktreeMeta } from './types';
+
+export async function assertManagedResourcePath(meta: WorktreeMeta, registeredPaths: string[]): Promise<void> {
+ await assertManagedResourceLocation(meta, registeredPaths);
+ const stat = await fs.lstat(meta.path);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('redirected worktree directory');
+ await assertAbsent(path.join(meta.path, '.worktree-keep'));
+}
+
+export async function assertManagedResourceLocation(meta: WorktreeMeta, registeredPaths: string[]): Promise<void> {
+ const resolved = path.resolve(meta.path);
+ const parent = path.dirname(resolved);
+ if (!isManagedWorktreeDirectoryName(path.basename(parent))
+ || path.dirname(parent) !== path.resolve(meta.baseRepo)
+ || !registeredPaths.some((value) => path.resolve(value) === resolved)) throw new Error('unmanaged worktree path');
+ const realParent = await physicalWorktreeKey(path.dirname(meta.path));
+ const expectedParent = path.join(await physicalWorktreeKey(meta.baseRepo), path.basename(path.dirname(meta.path)));
+ if (realParent !== expectedParent) throw new Error('redirected worktree parent');
+}
+
+async function assertAbsent(file: string): Promise<void> {
+ try { await fs.lstat(file); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw error;
+ }
+ throw new Error('worktree is locked or explicitly kept');
+}
+
+/** A regular .git link must resolve to this worktree in the expected repository. */
+export async function assertWorktreeGitIdentity(meta: WorktreeMeta): Promise<void> {
+ const link = await fs.lstat(path.join(meta.path, '.git'));
+ if (!link.isFile() || link.isSymbolicLink()) throw new Error('missing worktree Git link');
+ const { stdout: root } = await gitExec(['rev-parse', '--show-toplevel'], meta.path);
+ if (await physicalWorktreeKey(root.trim()) !== await physicalWorktreeKey(meta.path)) throw new Error('Git root mismatch');
+ const args = ['rev-parse', '--path-format=absolute', '--git-common-dir'];
+ const { stdout: common } = await gitExec(args, meta.path);
+ const { stdout: baseCommon } = await gitExec(args, meta.baseRepo);
+ if (!common.trim() || !baseCommon.trim()
+ || await physicalWorktreeKey(common.trim()) !== await physicalWorktreeKey(baseCommon.trim())) {
+ throw new Error('Git repository mismatch');
+ }
+ const { stdout: gitDir } = await gitExec(['rev-parse', '--path-format=absolute', '--git-dir'], meta.path);
+ const metadataRoot = path.join(await physicalWorktreeKey(common.trim()), 'worktrees');
+ if (path.dirname(await physicalWorktreeKey(gitDir.trim())) !== metadataRoot) throw new Error('Git worktree metadata mismatch');
+ for (const name of ['locked', 'index.lock', 'HEAD.lock']) await assertAbsent(path.join(gitDir.trim(), name));
+}
diff --git a/apps/desktop/src/main/worktree/restore.ts b/apps/desktop/src/main/worktree/restore.ts
index 49bf79db54..818f361553 100644
--- a/apps/desktop/src/main/worktree/restore.ts
+++ b/apps/desktop/src/main/worktree/restore.ts
@@ -31,6 +31,9 @@ import {
withWorktreeRestoreMutation,
} from './restoreLock';
import { copyClaudeSiviDirs } from './WorktreeManager';
+import { restoreRecordedWorktree } from './restoreRecovery';
+import { readRecycleRecord, worktreeGeneration } from './recycleJournal';
+import { withWorktreeResourceLock } from './resourceLock';
import * as store from './worktreeStore';
import { getDbClient } from '../localDb/client/current';
import { sessions } from '../localDb/schema';
@@ -362,6 +365,15 @@ async function getWorktreeRestorePlan(sessionId: string): Promise<WorktreeRestor
if (!worktreePath) return { status: { state: 'no-worktree' } };
const parsed = parseManagedWorktreePath(worktreePath);
if (!parsed) return { status: { state: 'no-worktree' } };
+ const recovery = await readRecycleRecord(worktreePath, sessionId);
+ if (recovery?.phase === 'restored' && registeredMeta
+ && [recovery.generation, recovery.restoredGeneration].includes(worktreeGeneration(registeredMeta))
+ && await pathExists(worktreePath)) {
+ return { status: { state: 'present', worktreePath, hasSnapshot: false }, parsed };
+ }
+ if (recovery?.snapshot && recovery.archive && ['removed', 'removing', 'restoring'].includes(recovery.phase)) {
+ return { status: { state: 'restorable', worktreePath, hasSnapshot: true }, parsed };
+ }
const registeredForPath =
registeredMeta && pathKey(registeredMeta.path) === pathKey(worktreePath)
@@ -434,6 +446,14 @@ export async function getWorktreeRestoreStatus(sessionId: string): Promise<Workt
async function restoreWorktreeForSessionOnce(sessionId: string): Promise<WorktreeRestoreResult> {
const plan = await getWorktreeRestorePlan(sessionId);
const { status } = plan;
+ if ('worktreePath' in status) {
+ try {
+ const restored = await restoreRecordedWorktree(sessionId, status.worktreePath);
+ if (restored !== null) return { ok: restored, snapshotApplied: restored, ...(restored ? {} : { reason: 'git-error' as const }) };
+ } catch (error) {
+ return { ok: false, reason: 'git-error', detail: error instanceof Error ? error.message : String(error) };
+ }
+ }
if (status.state === 'present') {
const parsed = plan.parsed ?? parseManagedWorktreePath(status.worktreePath);
if (!parsed) return { ok: true, snapshotApplied: true };
@@ -457,7 +477,7 @@ async function restoreWorktreeForSessionOnce(sessionId: string): Promise<Worktre
parsed.name,
);
if (!snapshotApplied) {
- store.del(sessionId);
+ await store.del(sessionId);
return { ok: true, snapshotApplied: false };
}
if (!store.get(sessionId) && plan.branch) {
@@ -486,7 +506,7 @@ async function restoreWorktreeForSessionOnce(sessionId: string): Promise<Worktre
parsed.name,
);
if (!snapshotApplied) {
- store.del(sessionId);
+ await store.del(sessionId);
return { ok: true, snapshotApplied: false };
}
await finishRestoredWorktree(sessionId, parsed, status.worktreePath, branch);
@@ -506,8 +526,12 @@ async function restoreWorktreeForSessionOnce(sessionId: string): Promise<Worktre
export function restoreWorktreeForSession(sessionId: string): Promise<WorktreeRestoreResult> {
const existing = restoreInFlight.get(sessionId);
if (existing) return existing;
- const tracked = withWorktreeRestoreMutation(sessionId, () =>
- restoreWorktreeForSessionOnce(sessionId),
+ const tracked = withWorktreeRestoreMutation(sessionId, async () => {
+ const worktreePath = store.get(sessionId)?.path ?? (await readSessionWorktreeBinding(sessionId))?.worktreePath;
+ return worktreePath
+ ? withWorktreeResourceLock(worktreePath, () => restoreWorktreeForSessionOnce(sessionId))
+ : restoreWorktreeForSessionOnce(sessionId);
+ },
).finally(() => {
if (restoreInFlight.get(sessionId) === tracked) {
restoreInFlight.delete(sessionId);
diff --git a/apps/desktop/src/main/worktree/restoreRecovery.ts b/apps/desktop/src/main/worktree/restoreRecovery.ts
new file mode 100644
index 0000000000..4c94cceeb6
--- /dev/null
+++ b/apps/desktop/src/main/worktree/restoreRecovery.ts
@@ -0,0 +1,117 @@
+import { constants } from 'node:fs';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+
+import { gitExec } from './gitExec';
+import { readRecycleRecord, writeRecycleRecord, worktreeGeneration } from './recycleJournal';
+import { extractRecoveryArchive, inventoryWorktree, sameWorktreeFiles, verifyRecoveryArchive } from './recoveryArchive';
+import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
+import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRefs';
+import { assertManagedResourceLocation, assertManagedResourcePath, assertWorktreeGitIdentity } from './resourceSafety';
+import * as store from './worktreeStore';
+import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';
+
+async function indexIsRestorable(worktreePath: string, indexTree: string): Promise<boolean> {
+ const { stdout } = await gitExec(['rev-parse', '--path-format=absolute', '--git-path', 'index'], worktreePath);
+ try { await fs.lstat(stdout.trim()); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;
+ throw error;
+ }
+ try {
+ await gitExec(['diff', '--cached', '--quiet', indexTree, '--'], worktreePath, { extraEnv: { GIT_OPTIONAL_LOCKS: '0' } });
+ return true;
+ } catch { return false; }
+}
+
+/** Restore new recovery records; return null to retain compatibility with older stash/branch recovery. */
+export async function restoreRecordedWorktree(sessionId: string, worktreePath: string): Promise<boolean | null> {
+ // Keep ordinary present/legacy lookups free of Windows helper processes.
+ const pending = await readRecycleRecord(worktreePath, sessionId);
+ if (!pending?.archive || !pending.snapshot || pending.phase === 'restored' || pending.phase === 'pending') return null;
+ return withWorktreeResourceLock(worktreePath, () => withLegacyWorktreeRuntimeGuard(async (legacyGuardHeld) => {
+ const record = await readRecycleRecord(worktreePath, sessionId);
+ if (!record?.snapshot || !record.archive || record.phase === 'restored' || record.phase === 'pending') return null;
+ if ([record.snapshot.head, record.snapshot.tree, record.snapshot.indexTree, record.snapshot.commit]
+ .some((value) => typeof value !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value))) return false;
+ if (await physicalWorktreeKey(record.meta.path) !== await physicalWorktreeKey(worktreePath)) return false;
+ const registered = store.get(sessionId);
+ if (registered && worktreeGeneration(registered) === record.restoredGeneration) {
+ // Registration was the final mutation; finish a journal write interrupted by a crash.
+ record.phase = 'restored';
+ await writeRecycleRecord(record);
+ return true;
+ }
+ if (registered && worktreeGeneration(registered) !== record.generation) return false;
+ for (const entry of store.getAll()) {
+ if (await physicalWorktreeKey(entry.path) === await physicalWorktreeKey(worktreePath)
+ && worktreeGeneration(entry) !== record.generation) return false;
+ }
+ await assertManagedResourceLocation(record.meta, [worktreePath]);
+ let identity: string | null = null;
+ try {
+ const stat = await fs.lstat(worktreePath);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) return false;
+ identity = `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ if (identity !== null && identity !== record.directoryIdentity) return false;
+ if (identity !== null) {
+ if (record.phase === 'snapshotted') {
+ // Snapshotting never mutates the live checkout. Cancelling recycling needs no apply.
+ record.phase = 'restored';
+ await writeRecycleRecord(record);
+ return true;
+ }
+ await assertManagedResourcePath(record.meta, [worktreePath]);
+ if (!sameWorktreeFiles(await inventoryWorktree(worktreePath), record.archive.files, true)) return false;
+ }
+ if (hasLiveSessionReference(record.meta, await loadLiveSessionPathKeys({ excludeSessionId: sessionId }))) return false;
+ await verifyRecoveryArchive(record.archive);
+ if (!legacyGuardHeld()) return false;
+ if (identity === null) {
+ await fs.mkdir(worktreePath, { recursive: false });
+ const stat = await fs.lstat(worktreePath);
+ record.directoryIdentity = `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
+ }
+ record.phase = 'restoring';
+ record.restoredGeneration ??= randomUUID();
+ await writeRecycleRecord(record);
+ const gitLink = path.join(worktreePath, '.git');
+ try {
+ await fs.lstat(gitLink);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ // Repair a partially deleted worktree without deleting any remaining user file.
+ const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-restore-'));
+ const checkout = path.join(temp, 'checkout');
+ try {
+ await gitExec(['worktree', 'prune'], record.meta.baseRepo);
+ await gitExec(['worktree', 'add', '--detach', '--no-checkout', checkout, record.snapshot.head], record.meta.baseRepo);
+ await fs.copyFile(path.join(checkout, '.git'), gitLink, constants.COPYFILE_EXCL);
+ await gitExec(['worktree', 'repair', worktreePath], record.meta.baseRepo);
+ } finally {
+ await fs.rm(temp, { recursive: true, force: true });
+ }
+ }
+ await assertManagedResourcePath(record.meta, [worktreePath]);
+ await assertWorktreeGitIdentity(record.meta);
+ if (!legacyGuardHeld()) return false;
+ const { stdout: head } = await gitExec(['rev-parse', 'HEAD'], worktreePath);
+ if (head.trim() !== record.snapshot.head) return false;
+ if (!(await indexIsRestorable(worktreePath, record.snapshot.indexTree))) return false;
+ await extractRecoveryArchive(record.archive, worktreePath, true);
+ if (hasLiveSessionReference(record.meta, await loadLiveSessionPathKeys({ excludeSessionId: sessionId }))) return false;
+ await assertManagedResourcePath(record.meta, [worktreePath]);
+ await assertWorktreeGitIdentity(record.meta);
+ if (!legacyGuardHeld()) return false;
+ if (!(await indexIsRestorable(worktreePath, record.snapshot.indexTree))) return false;
+ await gitExec(['read-tree', record.snapshot.indexTree], worktreePath);
+ await store.set(sessionId, { ...record.meta, sessionId, generation: record.restoredGeneration, quarantinePath: undefined });
+ record.phase = 'restored';
+ await writeRecycleRecord(record);
+ return true;
+ }));
+}
diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.ts
new file mode 100644
index 0000000000..c668270370
--- /dev/null
+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts
@@ -0,0 +1,120 @@
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { app } from 'electron';
+
+import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
+import { isManagedWorktreeDirectoryName } from '../../shared/managedWorktreePaths';
+
+function runtimeRoot(): string {
+ return path.join(app.getPath('userData'), 'worktree-runtime-leases');
+}
+
+/** Map a local cwd (including descendants) to its managed resource. SSH callers skip this helper. */
+export function managedWorktreeRoot(value: string): string | null {
+ let current = path.resolve(value);
+ for (;;) {
+ const parent = path.dirname(current);
+ if (isManagedWorktreeDirectoryName(path.basename(parent))) return current;
+ if (parent === current) return null;
+ current = parent;
+ }
+}
+
+function leaseFile(sessionId: string): string {
+ const key = createHash('sha256').update(sessionId).digest('hex');
+ return path.join(runtimeRoot(), `${process.pid}-${key}.json`);
+}
+
+export async function acquireWorktreeRuntimeLease(sessionId: string, cwd: string): Promise<void> {
+ const root = managedWorktreeRoot(cwd);
+ if (!root) return;
+ await withWorktreeResourceLock(root, async () => {
+ await fs.mkdir(runtimeRoot(), { recursive: true });
+ // A partial write is intentionally unreadable, hence protective to deletion.
+ await fs.writeFile(leaseFile(sessionId), JSON.stringify({
+ version: 1, pid: process.pid, path: await physicalWorktreeKey(root),
+ }), { mode: 0o600 });
+ });
+}
+
+export async function releaseWorktreeRuntimeLease(sessionId: string): Promise<void> {
+ let physicalPath: string | undefined;
+ try {
+ const lease = JSON.parse(await fs.readFile(leaseFile(sessionId), 'utf8'));
+ if (typeof lease.path === 'string') physicalPath = lease.path;
+ } catch {
+ // Releasing our own malformed/partial lease is still safe; it cannot wake another resource.
+ }
+ try { await fs.unlink(leaseFile(sessionId)); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw error;
+ }
+ const { notifyWorktreeRecycleOpportunity } = await import('./recycleMaintenance');
+ if (physicalPath) notifyWorktreeRecycleOpportunity(physicalPath);
+}
+
+function pidMayBeAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';
+ }
+}
+
+/** Unknown/older live instances keep terminal task references protected. */
+export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {
+ const registry = path.join(app.getPath('userData'), '.dev-instances');
+ const names = new Set((await fs.readdir(registry)).map((name) => name.replace(/\.bak$/, '')));
+ const compatiblePids = new Set([process.pid]);
+ for (const name of names) {
+ const match = /^(\d+)\.json$/.exec(name);
+ if (!match) continue;
+ const pid = Number(match[1]);
+ if (pid === process.pid || !pidMayBeAlive(pid)) continue;
+ try {
+ let raw: string;
+ try { raw = await fs.readFile(path.join(registry, name), 'utf8'); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ raw = await fs.readFile(path.join(registry, `${name}.bak`), 'utf8');
+ }
+ const record = JSON.parse(raw);
+ if (record.worktreeLeaseProtocol !== 1 || record.pid !== pid) return null;
+ compatiblePids.add(pid);
+ } catch {
+ return null;
+ }
+ }
+ if (process.platform !== 'win32') {
+ try {
+ const target = await fs.readlink(path.join(app.getPath('userData'), 'SingletonLock'));
+ const match = /-(\d+)$/.exec(target);
+ if (!match) return null;
+ const pid = Number(match[1]);
+ if (pidMayBeAlive(pid) && !compatiblePids.has(pid)) return null;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null;
+ }
+ }
+ let leases: string[];
+ try {
+ leases = await fs.readdir(runtimeRoot());
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return new Set();
+ throw error;
+ }
+ const paths = new Set<string>();
+ for (const name of leases) {
+ const match = /^(\d+)-[a-f0-9]{64}\.json$/.exec(name);
+ if (!match || !pidMayBeAlive(Number(match[1]))) continue;
+ try {
+ const lease = JSON.parse(await fs.readFile(path.join(runtimeRoot(), name), 'utf8'));
+ if (lease.version !== 1 || typeof lease.path !== 'string') return null;
+ paths.add(lease.path);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null;
+ }
+ }
+ return paths;
+}
diff --git a/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts b/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
index cf706f2f12..ee9fe8c159 100644
--- a/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
+++ b/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
@@ -9,12 +9,12 @@
* - 非 ephemeral worktree 的回收只由本模块驱动,触发点是 localDb 会话
* status → 'deleted' / 'archived' 的显式状态变更(见 localDb/ipc/sessions.ts)。
*
- * 崩溃窗口兜底:状态已写库但回收未跑完(app 崩溃/被杀)会留下孤儿 worktree,
- * 启动时 reconcileWorktreesForDeletedSessions() 对账清理(只认 deleted/行已缺失,
- * archived 不在启动期回收——归档回收错过就保留,偏保守)。
+ * 回收意图在状态写库前持久化;数据库和关闭运行时的服务都就绪后恢复重试。
+ * 历史登记仅分类审计,查不到当前账号的任务不构成删除依据。
*/
-import { eq, inArray } from 'drizzle-orm';
+import { eq } from 'drizzle-orm';
+import { auditRegisteredWorktrees } from './recycleMaintenance';
import { hasLiveSessionReference, pathKey } from './liveSessionRefs';
import { removeWorktreeForSession } from './WorktreeManager';
@@ -31,8 +31,7 @@ const log = createLogger('sessionRemovalRecycle');
*
* - ephemeral(scheduler 池)worktree 直接跳过:它的生命周期归 WorktreePool
* (onClose 池化、recoverPool、数量上限淘汰),这里删会与池内条目打架。
- * - 非 ephemeral 走 removeWorktreeForSession(内含 live-ref 守卫 + dirty
- * auto-stash + 删除安全门)。
+ * - 非 ephemeral 走 removeWorktreeForSession,保存可恢复内容后通过删除安全门。
*
* 调用方约定:先确保该会话的 CLI 子进程已关闭(Windows 下子进程 cwd 在
* worktree 内会锁目录,git worktree remove 必败),再调本函数。
@@ -214,52 +213,10 @@ async function readCurrentSessionStatus(
}
/**
- * 启动期对账:store 里登记的非 ephemeral worktree,若其 owning session 行已缺失
- * 或 status='deleted',说明删除时回收没跑完(崩溃窗口 / 回收失败),补一次回收。
- *
- * 刻意不处理 archived:升级前归档留下的 dirty worktree 存量(旧逻辑 dirty 保留)
- * 若在启动期一律补收,等于升级瞬间批量 stash+删目录,用户零感知——违背本次重构
- * 的初衷。归档场景只在归档动作发生时回收一次,错过就保留。
+ * 兼容旧启动入口:仅生成登记分类,不把历史状态或缺失任务推断成回收意图。
*/
export async function reconcileWorktreesForDeletedSessions(): Promise<void> {
- const candidates = store.getAll().filter((m) => !m.ephemeral);
- if (candidates.length === 0) return;
-
- let rows: Array<{ id: string; status: string | null; source: string | null }>;
- try {
- const db = getDbClient().drizzle;
- rows = await db
- .select({ id: sessions.id, status: sessions.status, source: sessions.source })
- .from(sessions)
- .where(
- inArray(
- sessions.id,
- candidates.map((m) => m.sessionId),
- ),
- );
- } catch (err) {
- // DB 不可用时不做任何删除(保守方向:漏收一轮无害,误删不可逆)。
- log.warn(
- '[sessionRemovalRecycle] reconcile skipped: session lookup failed',
- err instanceof Error ? err.message : String(err),
- );
- return;
- }
-
- const rowById = new Map(rows.map((r) => [r.id, r]));
- for (const meta of candidates) {
- const row = rowById.get(meta.sessionId);
- const status = row?.status;
- const orphaned = !row || (row.source !== 'bot' && status === 'deleted');
- if (!orphaned) continue;
- log.info(
- `[sessionRemovalRecycle] reconciling orphaned worktree at ${meta.path} (session ${meta.sessionId}, status=${status ?? 'missing'})`,
- );
- await removeWorktreeForSession(meta.sessionId).catch((err) => {
- log.warn(
- `[sessionRemovalRecycle] reconcile remove failed for ${meta.path}:`,
- err instanceof Error ? err.message : String(err),
- );
- });
- }
+ // Historical rows are evidence, not a deletion request. Durable retries are
+ // dispatched by recycleMaintenance after DB and runtime-close services are ready.
+ await auditRegisteredWorktrees();
}
diff --git a/apps/desktop/src/main/worktree/types.ts b/apps/desktop/src/main/worktree/types.ts
index 892b30e896..6a028432f5 100644
--- a/apps/desktop/src/main/worktree/types.ts
+++ b/apps/desktop/src/main/worktree/types.ts
@@ -10,6 +10,8 @@
* 同时也是 sessions.worktree_path 反范式快照的来源。
*/
export interface WorktreeMeta {
+ /** New physical contents at the same path invalidate old recycle requests. */
+ generation?: string;
sessionId: string;
/** 用户输入或 nameGenerator 给的名字(用于显示 + 路径段 + 分支段)。 */
name: string;
diff --git a/apps/desktop/src/main/worktree/worktreeStore.ts b/apps/desktop/src/main/worktree/worktreeStore.ts
index dccc568106..1fc0ab4797 100644
--- a/apps/desktop/src/main/worktree/worktreeStore.ts
+++ b/apps/desktop/src/main/worktree/worktreeStore.ts
@@ -58,8 +58,8 @@ function getStore(): Store<WorktreesStoreShape> {
schema: {
worktrees: { type: 'object' },
},
- // 文件被外部破坏时 reset 为 defaults, 避免反复抛 SyntaxError
- clearInvalidConfig: true,
+ // 损坏记录必须保留,不能重置为空后把未知资源当作无引用目录。
+ clearInvalidConfig: false,
});
return storeInstance;
}
@@ -86,7 +86,7 @@ export function _setStoreForTests(s: Store<WorktreesStoreShape> | null): void {
function readMap(): Record<string, WorktreeMeta> {
const raw = getStore().get('worktrees', {});
// 防御: 历史/损坏数据可能不是 object
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('invalid worktree registry');
return raw as Record<string, WorktreeMeta>;
}
@@ -189,9 +189,7 @@ export async function removePendingSafeDirectoryCleanups(paths: readonly string[
*/
export async function set(sessionId: string, meta: WorktreeMeta): Promise<void> {
if (!sessionId) throw new Error('worktreeStore.set: sessionId is required');
- const map = readMap();
- map[sessionId] = meta;
- writeMap(map);
+ await mutateRegistry((map) => { map[sessionId] = meta; });
try {
await setWorktreePathInDb(sessionId, meta.path);
} catch (err) {
@@ -205,10 +203,18 @@ export async function set(sessionId: string, meta: WorktreeMeta): Promise<void>
/**
* 删除 store 条目。**不**清 sessions.worktree_path(保留历史值, 徽标按 store 判)。
*/
-export function del(sessionId: string): void {
+export async function del(sessionId: string): Promise<void> {
if (!sessionId) return;
- const map = readMap();
- if (!(sessionId in map)) return;
- delete map[sessionId];
- writeMap(map);
+ await mutateRegistry((map) => { delete map[sessionId]; });
+}
+
+async function mutateRegistry(mutate: (map: Record<string, WorktreeMeta>) => void): Promise<void> {
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
+ await withCrossProcessLock(path.join(os.tmpdir(), `cindy-worktree-registry-${uid}.lock`),
+ { label: 'worktree-registry' }, async (status) => {
+ if (!status.held) throw new Error('worktree registry is busy');
+ const map = readMap();
+ mutate(map);
+ writeMap(map);
+ });
}