Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 归档任务后真正删除 worktree,不再整包备份
david0f4d0dc55ce5
diff --git a/apps/desktop/help-knowledge/worktrees.md b/apps/desktop/help-knowledge/worktrees.mdindex daa102d97c..66d39f7235 100644--- a/apps/desktop/help-knowledge/worktrees.md+++ b/apps/desktop/help-knowledge/worktrees.md@@ -21,7 +21,7 @@ A session can run inside its own **git worktree** — a separate working copy of- Created on first agent turn that needs files.- Survives across app restarts as long as the session is around. Transient closes (`/clear`, reconnecting, quitting the app) do **not** remove it.- The folder is removed only when you explicitly **delete or archive** the session; the **branch is preserved** (no force-delete), so you can keep the work or merge / cherry-pick from it later.-- Uncommitted changes inside the worktree are **auto-stashed** before the folder is removed, so nothing is silently lost. Removal is also skipped if you leave a `.worktree-keep` file in it or another live session is still using it.+- Uncommitted changes and new files inside the worktree are **saved in Git** before the folder is removed, and come back when the session is restored. Files ignored by `.gitignore` (dependencies such as `node_modules`, build output, caches) are **not kept**; reinstall or rebuild them after restoring. Removal is skipped if you leave a `.worktree-keep` file in it or another live session is still using it.**When the option is disabled:**diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.tsindex 693ec210fd..ece620a088 100644--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts@@ -1,8 +1,3 @@-// These suites exercise real archive I/O in Node; Electron worker isolation is covered separately.-vi.mock('../worktree/recoveryArchiveWorkerClient', async () => {- const { executeRecoveryArchiveTask } = await import('../worktree/recoveryArchiveTask');- return { runRecoveryArchiveTask: executeRecoveryArchiveTask };-});import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import fs from 'node:fs/promises';import os from 'node:os';@@ -14,7 +9,6 @@ import type { LocalWorktreeReference } from '../localDb/worker/worktreeReferenceconst state = vi.hoisted(() => ({ root: '', userData: '', 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());@@ -30,16 +24,11 @@ vi.mock('../worktree/runtimeLeases', async (original) => ({...await original<typeof import('../worktree/runtimeLeases')>(),readWorktreeRuntimePaths: vi.fn(async () => state.runtimes),}));-vi.mock('../worktree/contentSnapshot', () => ({ captureWorktreeContent: snapshot, worktreeContentBaselineMatches: baselineMatches }));+vi.mock('../worktree/contentSnapshot', () => ({ captureWorktreeContent: snapshot, worktreeContentMatches: baselineMatches }));vi.mock('../worktree/gitExec', () => ({ gitExec: git }));-vi.mock('../worktree/recoveryArchive', async (original) => ({- ...await original<typeof import('../worktree/recoveryArchive')>(),- createRecoveryArchive: archive, verifyRecoveryArchive: async () => {},-}));import { checkpointWorktreeForReuse, recycleManagedWorktree, requestWorktreeRecycle } from '../worktree/managedRecycle';-import { readRecycleRecord } from '../worktree/recycleJournal';-import { inventoryWorktree } from '../worktree/recoveryArchive';+import { pruneUnreferencedRecoveryArchives, readRecycleRecord, writeRecycleRecord } from '../worktree/recycleJournal';import { physicalWorktreeKey } from '../worktree/resourceLock';import { readWorktreeRuntimePaths } from '../worktree/runtimeLeases';import { releaseWorktreeRuntimeLease } from '../worktree/runtimeLeases';@@ -62,9 +51,8 @@ describe('shared worktree recycling', () => {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' });+ snapshot.mockReset().mockResolvedValue({ head: 'actual-head', tree: 'file-tree', indexTree: 'index-tree', commit: 'saved-commit', ref: 'saved-ref', untracked: true });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') };@@ -79,13 +67,13 @@ describe('shared worktree recycling', () => {});const recycle = () => recycleManagedWorktree(meta, { canRemove: async () => removable });- it('does not rebuild failed archives after the durable budget is exhausted', async () => {- archive.mockRejectedValue(new Error('temporary filesystem failure'));+ it('does not retake failed snapshots after the durable budget is exhausted', async () => {+ snapshot.mockRejectedValue(new Error('temporary filesystem failure'));for (let attempt = 0; attempt < 5; attempt++) expect(await recycle()).toBe(false);- expect(archive).toHaveBeenCalledTimes(3);+ expect(snapshot).toHaveBeenCalledTimes(3);expect((await readRecycleRecord(meta.path))?.retryPolicy?.state).toBe('paused');await expect(checkpointWorktreeForReuse(meta)).rejects.toThrow('recycling is paused');- expect(archive).toHaveBeenCalledTimes(3);+ expect(snapshot).toHaveBeenCalledTimes(3);expect((await fs.stat(meta.path)).isDirectory()).toBe(true);expect(state.registry.has(meta.sessionId)).toBe(true);});@@ -124,14 +112,51 @@ describe('shared worktree recycling', () => {expect(checked).toBe(12); expect(peak).toBe(1);});- 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' }; });+ it('saves new files in the Git snapshot, writes no archive, and drops registration after deletion', async () => {expect(await recycle()).toBe(true);- expect(order).toEqual(['archive', 'snapshot']);+ expect(snapshot).toHaveBeenCalledWith(meta.path, expect.any(String), { includeUntracked: true });+ await expect(fs.stat(meta.path)).rejects.toMatchObject({ code: 'ENOENT' });expect(state.registry.has(meta.sessionId)).toBe(false);+ const record = await readRecycleRecord(meta.path);+ expect(record?.phase).toBe('removed');+ expect(record?.archive).toBeUndefined();+ expect((await fs.readdir(path.join(state.root, 'worktree-recycle'))).filter((name) => name.endsWith('.enc'))).toEqual([]);+ });+ it('finishes a request whose directory is already gone, even while another task names the path', async () => {+ state.refs.push({ ...state.refs[0], id: 'borrower', status: 'active' });+ await fs.rm(meta.path, { recursive: true });+ expect(await recycle()).toBe(true);+ expect(snapshot).not.toHaveBeenCalled();expect((await readRecycleRecord(meta.path))?.phase).toBe('removed');+ expect(state.registry.has(meta.sessionId)).toBe(false);+ expect(git).toHaveBeenCalledWith(['worktree', 'prune'], meta.baseRepo);+ });+ it('deletes only old recovery archives that no record references, and none when a record is unreadable', async () => {+ await requestWorktreeRecycle(meta.sessionId);+ const record = (await readRecycleRecord(meta.path))!;+ const journal = path.join(state.root, 'worktree-recycle');+ const archives = { referenced: 'aaaa', orphan: 'bbbb', young: 'cccc' };+ const name = (kind: keyof typeof archives) => `${record.id}-${archives[kind]}.tar.gz.enc`;+ const old = new Date(Date.now() - 3 * 60 * 60_000);+ for (const kind of ['referenced', 'orphan', 'young'] as const) {+ await fs.writeFile(path.join(journal, name(kind)), 'encrypted bytes');+ if (kind !== 'young') await fs.utimes(path.join(journal, name(kind)), old, old);+ }+ await writeRecycleRecord({ ...record, archive: { file: name('referenced'), encryptedKey: '', iv: '', tag: '', files: {} } });+ const unreadable = path.join(journal, `${'f'.repeat(64)}.json`);+ await fs.writeFile(unreadable, '{');+ expect(await pruneUnreferencedRecoveryArchives()).toBe(0);+ await fs.rm(unreadable);++ expect(await pruneUnreferencedRecoveryArchives()).toBe(1);+ expect((await fs.readdir(journal)).filter((entry) => entry.endsWith('.enc')).sort())+ .toEqual([name('referenced'), name('young')].sort());+ });+ it('keeps a request waiting when the owner task is no longer archived, even if the directory is gone', async () => {+ removable = false;+ await fs.rm(meta.path, { recursive: true });+ expect(await recycle()).toBe(false);+ expect(state.registry.has(meta.sessionId)).toBe(true);});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 });@@ -150,7 +175,7 @@ describe('shared worktree recycling', () => {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();+ expect(snapshot).not.toHaveBeenCalled();});it('protects a worktree borrowed by another isolated profile until release', async () => {const actual = await vi.importActual<typeof import('../worktree/runtimeLeases')>('../worktree/runtimeLeases');@@ -168,7 +193,7 @@ describe('shared worktree recycling', () => {// The recycler has a different userData and no active database reference.state.userData = ownerProfile;expect(await recycle()).toBe(false);- expect(archive).not.toHaveBeenCalled();+ expect(snapshot).not.toHaveBeenCalled();expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('uncommitted contents');expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(meta.path)]));@@ -197,7 +222,7 @@ describe('shared worktree recycling', () => {state.userData = ownerProfile;expect(await readWorktreeRuntimePaths()).toEqual(new Set());expect(await recycle()).toBe(false);- expect(archive).not.toHaveBeenCalled();+ expect(snapshot).not.toHaveBeenCalled();expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('uncommitted contents');await release!();expect(await recycle()).toBe(true);@@ -210,24 +235,18 @@ describe('shared worktree recycling', () => {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();+ expect(snapshot).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();+ expect(snapshot).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);@@ -243,11 +262,6 @@ describe('shared worktree recycling', () => {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);@@ -316,13 +330,14 @@ describe('shared worktree recycling', () => {expect((await readRecycleRecord(meta.path))?.reason).toBe('git-baseline-changed');expect(git.mock.calls.some(([args]) => args.includes('remove'))).toBe(false);});- it('rechecks files after marking removal and preserves a late editor write', async () => {+ it('rechecks content after marking removal and preserves a late editor write', async () => {baselineMatches.mockImplementationOnce(async () => {await fs.writeFile(path.join(meta.path, 'late-editor-write.txt'), 'keep me');return true;- });+ }).mockResolvedValueOnce(false);expect(await recycle()).toBe(false);- expect((await readRecycleRecord(meta.path))?.reason).toBe('files-changed-before-removal');+ expect((await readRecycleRecord(meta.path))?.phase).toBe('removing');+ expect((await readRecycleRecord(meta.path))?.reason).toBe('git-baseline-changed-before-removal');expect(git.mock.calls.some(([args]) => args.includes('remove'))).toBe(false);expect(await fs.readFile(path.join(meta.path, 'late-editor-write.txt'), 'utf8')).toBe('keep me');expect(state.registry.has(meta.sessionId)).toBe(true);@@ -334,27 +349,27 @@ describe('shared worktree recycling', () => {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();+ expect(snapshot).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();+ expect(snapshot).not.toHaveBeenCalled();});it('preserves indexed submodules before creating incomplete recovery evidence', async () => {const originalGit = git.getMockImplementation()!;git.mockImplementation(async (args: string[]) => args.includes('--stage')? { stdout: `160000 ${'a'.repeat(40)} 0\tchild\0` } : originalGit(args));expect(await recycle()).toBe(false);- expect(archive).not.toHaveBeenCalled();+ expect(snapshot).not.toHaveBeenCalled();expect(state.registry.has(meta.sessionId)).toBe(true);});it('preserves submodule metadata even after its gitlink was removed from the index', async () => {await fs.mkdir(path.join(meta.baseRepo, '.git', 'worktrees', 'one', 'modules', 'child'), { recursive: true });expect(await recycle()).toBe(false);- expect(archive).not.toHaveBeenCalled();+ expect(snapshot).not.toHaveBeenCalled();expect(state.registry.has(meta.sessionId)).toBe(true);});it('rejects a Git link pointing at another repository', async () => {@@ -362,6 +377,6 @@ describe('shared worktree recycling', () => {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();+ expect(snapshot).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.tsindex 5d1f43c1f6..88a0025277 100644--- a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts@@ -48,12 +48,13 @@ import { readRecycleRecord, writeRecycleRecord } from '../worktree/recycleJournaimport { captureWorktreeContent } from '../worktree/contentSnapshot';import { GitExecError, gitExec } from '../worktree/gitExec';import { acquireWorktree, releaseWorktree, parkAll } from '../worktree/WorktreePool';-import { extractRecoveryArchive } from '../worktree/recoveryArchive';+import { createRecoveryArchive } from '../worktree/recoveryArchive';+import { physicalWorktreeKey, worktreeResourceId } from '../worktree/resourceLock';import { releaseWorktreeRuntimeLease } from '../worktree/runtimeLeases';import { seedLegacySharedRuntimeLease } from './fixtures/legacySharedRuntimeLease';const exec = promisify(execFile);-describe('worktree recovery with real Git and encrypted archives', () => {+describe('worktree recovery with real Git', () => {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' },@@ -99,7 +100,7 @@ describe('worktree recovery with real Git and encrypted archives', () => {} finally { await releaseWorktreeRuntimeLease(lease); }}, 30_000);- it('restores detached HEAD, staged-only bytes, unstaged files, ignored files and untracked files', async () => {+ it('restores detached HEAD, staged-only bytes, unstaged and untracked files without keeping ignored 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');@@ -119,18 +120,24 @@ describe('worktree recovery with real Git and encrypted archives', () => {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(record?.archive).toBeUndefined();+ expect((await fs.readdir(path.join(state.root, 'worktree-recycle'))).filter((name) => name.endsWith('.enc'))).toEqual([]);+ const savedTree = await git(repo, 'ls-tree', '-r', '--name-only', record!.snapshot!.commit);+ expect(savedTree).not.toContain('.env');+ expect(savedTree).not.toContain('ignored/');+ expect(savedTree).toContain('untracked.txt');expect(await restoreRecordedWorktree(meta.sessionId, worktree)).toBe(true);expect(await git(worktree, 'rev-parse', 'HEAD')).toBe(head);await expect(git(worktree, 'symbolic-ref', '--quiet', 'HEAD')).rejects.toThrow();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');+ // Ignored files are regenerable (dependencies, build output) and are not kept.+ await expect(fs.stat(path.join(worktree, '.env'))).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(fs.stat(path.join(worktree, 'ignored'))).rejects.toMatchObject({ code: 'ENOENT' });+ const status = await git(worktree, 'status', '--porcelain');+ expect(status).toContain('MM tracked.txt');+ expect(status).toContain('?? untracked.txt');expect((await readRecycleRecord(worktree))?.phase).toBe('restored');}, 60_000);@@ -278,11 +285,16 @@ describe('worktree recovery with real Git and encrypted archives', () => {expect(registered).toHaveLength(1);}, 30_000);- it('rejects a corrupt encrypted archive before creating recovery files', async () => {+ it('rejects a corrupt encrypted archive from an older client before creating recovery files', async () => {const meta = await createFixture('corrupt');+ const legacyArchive = await createRecoveryArchive(meta.path, worktreeResourceId(await physicalWorktreeKey(meta.path)));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);+ // Model the record shape older clients wrote: snapshot without untracked files, plus an archive.+ delete record.snapshot!.untracked;+ record.archive = legacyArchive;+ await writeRecycleRecord(record);+ 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);@@ -352,11 +364,8 @@ describe('worktree recovery with real Git and encrypted archives', () => {expect(record.phase).toBe('removed');expect(record.generation).toBe(meta.generation);expect(await git(repo, 'rev-parse', record.snapshot!.ref)).toBe(record.snapshot!.commit);- const saved = path.join(state.root, 'copy-conflict-saved');- await fs.mkdir(saved);- await extractRecoveryArchive(record.archive!, saved);- expect(await fs.readFile(path.join(saved, '.claude', 'config.txt'), 'utf8')).toBe('original tracked config\n');- expect(await fs.readFile(path.join(saved, '.env'), 'utf8')).toBe('original ignored bytes\n');+ expect(record.archive).toBeUndefined();+ expect(await git(repo, 'show', `${record.snapshot!.commit}:.claude/config.txt`)).toBe('original tracked config');expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(false);expect(await fs.readFile(conflictPath, 'utf8')).toBe('partial copy\n');expect(await fs.readFile(path.join(meta.path, 'late-user-edit.txt'), 'utf8')).toBe('new user bytes\n');diff --git a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.tsindex c9ab155f80..d4c2eb2ec6 100644--- a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts@@ -19,12 +19,19 @@ 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 }));+const write = vi.hoisted(() => vi.fn());vi.mock('../worktree/recycleJournal', () => ({listRecycleRecords: list,readRecycleRecord: read,+ writeRecycleRecord: write,+ pruneUnreferencedRecoveryArchives: vi.fn(async () => 0),worktreeGeneration: () => 'one',watchRecycleJournal: watch,}));+vi.mock('../worktree/resourceLock', async (original) => ({+ ...await original<typeof import('../worktree/resourceLock')>(),+ withWorktreeResourceLock: async <T>(_value: string, task: () => Promise<T>) => task(),+}));import { WorktreeRecycleMaintenance } from '../worktree/recycleMaintenance';import { notifyWorktreeRecycleOpportunity, notifyWorktreeRecycleRecordChanged } from '../worktree/recycleEvents';import { worktreeResourceId } from '../worktree/resourceLock';@@ -53,6 +60,9 @@ describe('durable worktree maintenance', () => {remove.mockReset().mockResolvedValue(true);list.mockReset().mockImplementation(async () => [...state.records]);read.mockReset().mockImplementation(async (value: string) => state.records.find((item) => item.meta.path === value) ?? null);+ write.mockReset().mockImplementation(async (next: WorktreeRecycleRecord) => {+ state.records = state.records.map((item) => item.id === next.id ? next : item);+ });closeWatch.mockReset();watch.mockReset().mockImplementation(async (changed, error) => {state.changed = changed; state.watchError = error; return closeWatch;@@ -69,6 +79,31 @@ describe('durable worktree maintenance', () => {ready = true; await maintenance.start();expect(closeAndRecycle).toHaveBeenCalledWith('owner', 'archived'); expect(watch).toHaveBeenCalledOnce();});+ it('retries a request an older client paused over its archive exactly once', async () => {+ state.records = [{ ...record(), reason: 'recycle-failed', attempts: 3, retryPolicy: { state: 'paused', failures: 3, failedWorkMs: 1_800_000 } }];+ closeAndRecycle.mockImplementation(async () => {+ const [current] = state.records;+ state.records = [{ ...current, reason: 'recycle-failed', retryPolicy: { state: 'paused', failures: 3, failedWorkMs: 0 } }];+ });+ await maintenance.start();+ expect(closeAndRecycle).toHaveBeenCalledExactlyOnceWith('owner', 'archived');+ expect(state.records[0].legacyArchiveRetry).toBe(true);++ maintenance.stop();+ maintenance = new WorktreeRecycleMaintenance({ isReady: () => ready, recycleCurrentSession: closeAndRecycle });+ await maintenance.start();+ expect(closeAndRecycle).toHaveBeenCalledOnce();+ });+ it('keeps a pause the user chose or a newer client recorded', async () => {+ state.records = [+ { ...record('kept'), reason: 'user-kept', retryPolicy: { state: 'kept', failures: 0, failedWorkMs: 0 } },+ { ...record('identity'), reason: 'directory-replaced', retryPolicy: { state: 'paused', failures: 1, failedWorkMs: 0 } },+ ];+ state.rows = ['kept', 'identity'].map((id) => ({ id, status: 'archived', source: 'desktop', currentDatabase: true }));+ await maintenance.start();+ expect(write).not.toHaveBeenCalled();+ expect(closeAndRecycle).not.toHaveBeenCalled();+ });it('does not infer deletion from a row missing in the local view', async () => {state.rows = []; await maintenance.start();expect(remove).not.toHaveBeenCalled(); expect(closeAndRecycle).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.tsindex 03f03a2bf7..fcca90ed0c 100644--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts@@ -28,6 +28,9 @@ import { physicalWorktreeKey, withWorktreeResourceLock } from '../worktree/resouimport { createLinkedWorktreeMetadata } from './fixtures/linkedWorktree';import { seedLegacySharedRuntimeLease } from './fixtures/legacySharedRuntimeLease';+// Registrations in identity tests start after boot, so only process identity decides.+const t0 = Date.now();+describe('worktree runtime evidence and physical locks', () => {let worktree: string;let gitLock: string;@@ -293,10 +296,10 @@ describe('worktree runtime evidence and physical locks', () => {it('ignores a legacy registration whose PID was reused, but keeps its detached-child lease', async () => {const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;const file = path.join(state.root, '.dev-instances', '4242.json');- const raw = JSON.stringify({ pid: 4242, startedAtMs: 10_000 });+ const raw = JSON.stringify({ pid: 4242, startedAtMs: t0 + 10_000 });await fs.writeFile(file, raw);vi.spyOn(process, 'kill').mockReturnValue(true);- readIdentity.mockResolvedValue({ startedAtMs: 100_000, executablePath: path.join(state.root, 'chrome.exe') });+ readIdentity.mockResolvedValue({ startedAtMs: t0 + 100_000, executablePath: path.join(state.root, 'chrome.exe') });expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));expect(await fs.readFile(file, 'utf8')).toBe(raw);await releaseWorktreeRuntimeLease(lease);@@ -305,15 +308,15 @@ describe('worktree runtime evidence and physical locks', () => {it('keeps a real legacy Cindy instance protective', async () => {await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'),- JSON.stringify({ pid: 4242, startedAtMs: 100_000 }));+ JSON.stringify({ pid: 4242, startedAtMs: t0 + 100_000 }));vi.spyOn(process, 'kill').mockReturnValue(true);- readIdentity.mockResolvedValue({ startedAtMs: 99_000, executablePath: process.execPath });+ readIdentity.mockResolvedValue({ startedAtMs: t0 + 99_000, executablePath: process.execPath });expect(await readWorktreeRuntimePaths()).toBeNull();});describe('POSIX SingletonLock PID reuse', () => {- const raw = JSON.stringify({ pid: 4242, startedAtMs: 10_000 });- const identity = { startedAtMs: 100_000, executablePath: '/usr/bin/other' };+ const raw = JSON.stringify({ pid: 4242, startedAtMs: t0 + 10_000 });+ const identity = { startedAtMs: t0 + 100_000, executablePath: '/usr/bin/other' };beforeEach(async () => {Object.defineProperty(process, 'platform', { ...platformDescriptor, value: 'darwin' });await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'), raw);@@ -352,7 +355,7 @@ describe('worktree runtime evidence and physical locks', () => {readIdentity.mockResolvedValueOnce(identity).mockImplementationOnce(async () => {const file = path.join(state.root, '.dev-instances', '4242.json');if (change === 'remove') await fs.unlink(file);- else await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: 200_000 }));+ else await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: t0 + 200_000 }));return identity;});expect(await readWorktreeRuntimePaths()).toBeNull();@@ -361,15 +364,15 @@ describe('worktree runtime evidence and physical locks', () => {it('keeps a replacement Cindy protective before its new registration is published', async () => {await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'),- JSON.stringify({ pid: 4242, startedAtMs: 1 }));+ JSON.stringify({ pid: 4242, startedAtMs: t0 + 1 }));vi.spyOn(process, 'kill').mockReturnValue(true);- readIdentity.mockResolvedValue({ startedAtMs: 100_000, executablePath: path.join(state.root, 'Cindy.exe') });+ readIdentity.mockResolvedValue({ startedAtMs: t0 + 100_000, executablePath: path.join(state.root, 'Cindy.exe') });expect(await readWorktreeRuntimePaths()).toBeNull();});it('preserves when process identity is unavailable even for a very old registration', async () => {await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'),- JSON.stringify({ pid: 4242, startedAtMs: 1 }));+ JSON.stringify({ pid: 4242, startedAtMs: t0 + 1 }));vi.spyOn(process, 'kill').mockReturnValue(true);expect(await readWorktreeRuntimePaths()).toBeNull();});@@ -384,22 +387,22 @@ describe('worktree runtime evidence and physical locks', () => {it('does not apply stale evidence after another instance replaces the registry record', async () => {const file = path.join(state.root, '.dev-instances', '4242.json');- await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: 10_000 }));+ await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: t0 + 10_000 }));vi.spyOn(process, 'kill').mockReturnValue(true);readIdentity.mockImplementation(async () => {- await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: 200_000 }));- return { startedAtMs: 100_000, executablePath: path.join(state.root, 'chrome.exe') };+ await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: t0 + 200_000 }));+ return { startedAtMs: t0 + 100_000, executablePath: path.join(state.root, 'chrome.exe') };});expect(await readWorktreeRuntimePaths()).toBeNull();});it('does not trust a backup after a new primary registration appears during the probe', async () => {const file = path.join(state.root, '.dev-instances', '4242.json');- await fs.writeFile(`${file}.bak`, JSON.stringify({ pid: 4242, startedAtMs: 10_000 }));+ await fs.writeFile(`${file}.bak`, JSON.stringify({ pid: 4242, startedAtMs: t0 + 10_000 }));vi.spyOn(process, 'kill').mockReturnValue(true);readIdentity.mockImplementation(async () => {- await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: 200_000 }));- return { startedAtMs: 100_000, executablePath: path.join(state.root, 'chrome.exe') };+ await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: t0 + 200_000 }));+ return { startedAtMs: t0 + 100_000, executablePath: path.join(state.root, 'chrome.exe') };});expect(await readWorktreeRuntimePaths()).toBeNull();});@@ -422,6 +425,49 @@ describe('worktree runtime evidence and physical locks', () => {expect(await readWorktreeRuntimePaths()).toEqual(new Set());});+ describe('leases and registrations nothing will ever release', () => {+ const hourMs = 60 * 60_000;+ const ownedBy = async (lease: { file: string }, pid: number, ageMs: number, extra: Record<string, unknown> = {}) => {+ const value = JSON.parse(await fs.readFile(lease.file, 'utf8')) as Record<string, unknown>;+ await fs.writeFile(lease.file, JSON.stringify({ ...value, ...extra, pid }));+ const at = new Date(Date.now() - ageMs);+ await fs.utimes(lease.file, at, at);+ };+ const exitedOwner = (alive: (pid: number) => boolean = () => false) => vi.spyOn(process, 'kill').mockImplementation((pid) => {+ if (alive(Number(pid))) return true;+ throw Object.assign(new Error('owner is gone'), { code: 'ESRCH' });+ });++ it('waives a lease written before this boot even when its PID now belongs to another process', async () => {+ vi.spyOn(os, 'uptime').mockReturnValue(60);+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ await ownedBy(lease, 4242, hourMs);+ vi.spyOn(process, 'kill').mockReturnValue(true);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ });++ it('waives an exited owner lease after the grace period while a recorded child keeps it protective', async () => {+ vi.spyOn(os, 'uptime').mockReturnValue(30 * 24 * 60 * 60);+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ await ownedBy(lease, 4242, 2 * hourMs);+ exitedOwner();+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());++ await ownedBy(lease, 4242, 2 * hourMs, { childPid: 4343 });+ exitedOwner((pid) => pid === 4343);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ });++ it('ignores an unsupported instance registered before this boot without querying its PID', async () => {+ vi.spyOn(os, 'uptime').mockReturnValue(60);+ await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'),+ JSON.stringify({ pid: 4242, startedAtMs: Date.now() - hourMs, state: 'failed' }));+ vi.spyOn(process, 'kill').mockReturnValue(true);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ expect(readIdentity).not.toHaveBeenCalled();+ });+ });+it('reclaims a dead-owner lease only through explicit orphan cancellation', async () => {const lease = (await acquireWorktreeRuntimeLease('orphan', worktree))!;recordWorktreeRuntimeLeaseChild(lease, 12345);diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.tsindex 6f7275ba2e..483c4b24f1 100644--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts@@ -171,6 +171,6 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [id: "worktrees",title: "Working in an isolated git worktree",summary: "Opt a session into an isolated git worktree so its changes stay on their own branch and folder.",- content: "A session can run inside its own **git worktree** — a separate working copy of the same repository on its own branch — so the agent's edits don't mix with your main checkout.\n\n**Opting in:**\n\n- In the new-chat view, click the working-directory chip → the **gear** icon to open the Advanced popover → tick the **worktree** checkbox.\n- The worktree is created **on first message send**, not on session create. An overlay shows the status (creating / ready / failed).\n\n**Where it goes:**\n\n- Folder: `<repo>/.cindy-worktrees/<auto-generated-name>/` — kept inside the same repo so git tooling can find it. Worktrees created by older versions under `.xdt-worktrees/` remain supported.\n- Branch: `cindy/<auto-generated-name>` — auto-created off the source branch you pick, which defaults to the repo's current branch (HEAD). Branches created by older versions under `xdt/` remain supported and do not need to be renamed.\n\n**Lifecycle:**\n\n- Created on first agent turn that needs files.\n- Survives across app restarts as long as the session is around. Transient closes (`/clear`, reconnecting, quitting the app) do **not** remove it.\n- The folder is removed only when you explicitly **delete or archive** the session; the **branch is preserved** (no force-delete), so you can keep the work or merge / cherry-pick from it later.\n- Uncommitted changes inside the worktree are **auto-stashed** before the folder is removed, so nothing is silently lost. Removal is also skipped if you leave a `.worktree-keep` file in it or another live session is still using it.\n\n**When the option is disabled:**\n\n- Git is not installed on your machine.\n- The chosen working directory isn't a git repository.\n- The chosen directory is already inside an existing worktree (no nesting).\n\n**Error cases (shown on the overlay):**\n\n- `permission-denied` (can't write into the repo dir), `git-crypt-locked` (repo uses git-crypt and isn't unlocked), `dubious-ownership` (git's safe.directory check tripped), `lfs-error`, `not-a-git-repo`, `git-not-installed`.\n\n**Notes:**\n\n- The agent's **Read / Write / Bash** tools automatically operate inside the worktree path — you don't need to switch directories manually.\n- Because the branch survives the worktree, \"did the agent's changes go anywhere?\" is always answerable with `git branch --list 'cindy/*' 'xdt/*'`.\n- Worktrees are a per-session opt-in — they're not on by default and they don't change non-worktree sessions in any way.",+ content: "A session can run inside its own **git worktree** — a separate working copy of the same repository on its own branch — so the agent's edits don't mix with your main checkout.\n\n**Opting in:**\n\n- In the new-chat view, click the working-directory chip → the **gear** icon to open the Advanced popover → tick the **worktree** checkbox.\n- The worktree is created **on first message send**, not on session create. An overlay shows the status (creating / ready / failed).\n\n**Where it goes:**\n\n- Folder: `<repo>/.cindy-worktrees/<auto-generated-name>/` — kept inside the same repo so git tooling can find it. Worktrees created by older versions under `.xdt-worktrees/` remain supported.\n- Branch: `cindy/<auto-generated-name>` — auto-created off the source branch you pick, which defaults to the repo's current branch (HEAD). Branches created by older versions under `xdt/` remain supported and do not need to be renamed.\n\n**Lifecycle:**\n\n- Created on first agent turn that needs files.\n- Survives across app restarts as long as the session is around. Transient closes (`/clear`, reconnecting, quitting the app) do **not** remove it.\n- The folder is removed only when you explicitly **delete or archive** the session; the **branch is preserved** (no force-delete), so you can keep the work or merge / cherry-pick from it later.\n- Uncommitted changes and new files inside the worktree are **saved in Git** before the folder is removed, and come back when the session is restored. Files ignored by `.gitignore` (dependencies such as `node_modules`, build output, caches) are **not kept**; reinstall or rebuild them after restoring. Removal is skipped if you leave a `.worktree-keep` file in it or another live session is still using it.\n\n**When the option is disabled:**\n\n- Git is not installed on your machine.\n- The chosen working directory isn't a git repository.\n- The chosen directory is already inside an existing worktree (no nesting).\n\n**Error cases (shown on the overlay):**\n\n- `permission-denied` (can't write into the repo dir), `git-crypt-locked` (repo uses git-crypt and isn't unlocked), `dubious-ownership` (git's safe.directory check tripped), `lfs-error`, `not-a-git-repo`, `git-not-installed`.\n\n**Notes:**\n\n- The agent's **Read / Write / Bash** tools automatically operate inside the worktree path — you don't need to switch directories manually.\n- Because the branch survives the worktree, \"did the agent's changes go anywhere?\" is always answerable with `git branch --list 'cindy/*' 'xdt/*'`.\n- Worktrees are a per-session opt-in — they're not on by default and they don't change non-worktree sessions in any way.",},];diff --git a/apps/desktop/src/main/worktree/WorktreePool.ts b/apps/desktop/src/main/worktree/WorktreePool.tsindex baaf41cfbf..3b73030829 100644--- a/apps/desktop/src/main/worktree/WorktreePool.ts+++ b/apps/desktop/src/main/worktree/WorktreePool.ts@@ -13,7 +13,7 @@ import { randomUUID } from 'node:crypto';import { checkpointWorktreeForReuse, recycleManagedWorktree } from './managedRecycle';import { withWorktreeResourceLock } from './resourceLock';import { readRecycleRecord } from './recycleJournal';-import { restoreRecordedWorktree } from './restoreRecovery';+import { hasRecordedRecovery, restoreRecordedWorktree } from './restoreRecovery';import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';import path from 'node:path';import fs from 'node:fs/promises';@@ -392,7 +392,7 @@ async function drainEntry(meta: WorktreeMeta): Promise<void> {return false;}const recovery = await readRecycleRecord(meta.path);- return recovery?.phase === 'removing' && Boolean(recovery.archive && recovery.snapshot)+ return recovery?.phase === 'removing' && hasRecordedRecovery(recovery)|| !(await isWorktreeDirty(meta.path));},});diff --git a/apps/desktop/src/main/worktree/contentSnapshot.ts b/apps/desktop/src/main/worktree/contentSnapshot.tsindex 25ed616e77..727d127b7c 100644--- a/apps/desktop/src/main/worktree/contentSnapshot.ts+++ b/apps/desktop/src/main/worktree/contentSnapshot.ts@@ -33,6 +33,72 @@ export async function worktreeContentBaselineMatches(&& (snapshot.headRef === undefined || await readWorktreeHeadRef(worktreePath) === snapshot.headRef);}+/** Run Git against a throwaway index so the live index is never locked or rewritten. */+async function withTemporaryIndex<T>(run: (env: Record<string, string>) => Promise<T>): Promise<T> {+ const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-index-'));+ try {+ return await run({ GIT_INDEX_FILE: path.join(temp, 'index'), GIT_OPTIONAL_LOCKS: '0' });+ } finally {+ await fs.rm(temp, { recursive: true, force: true });+ }+}++/** Tracked and untracked content that `.gitignore` does not exclude, as a tree. */+async function fullContentTree(worktreePath: string): Promise<string> {+ return withTemporaryIndex(async (extraEnv) => {+ const { stdout: indexPath } = await gitExec(['rev-parse', '--path-format=absolute', '--git-path', 'index'], worktreePath);+ await fs.copyFile(indexPath.trim(), extraEnv.GIT_INDEX_FILE);+ await gitExec(['add', '--all', '--', '.'], worktreePath, { extraEnv });+ const { stdout } = await gitExec(['write-tree'], worktreePath, { extraEnv });+ return stdout.trim();+ });+}++/**+ * Same HEAD, staged content and non-ignored files as a snapshot that includes untracked files.+ * Compares content rather than index bytes, so a `git status` stat refresh by an editor does+ * not keep an archived worktree waiting. Older snapshots saved untracked bytes only in the+ * recovery archive, so they never match: callers take a new snapshot before deleting anything.+ */+export async function worktreeContentMatches(+ worktreePath: string,+ snapshot: NonNullable<WorktreeRecycleRecord['snapshot']>,+): Promise<boolean> {+ return snapshot.untracked === true+ && await worktreeStagedContentMatches(worktreePath, snapshot)+ && await fullContentTree(worktreePath) === snapshot.tree;+}++/**+ * Files still present in a partially removed or reused checkout must be a subset of the+ * snapshot: missing files are fine, while edited or new non-ignored files stop recovery.+ */+export async function presentFilesMatchSnapshotTree(worktreePath: string, tree: string): Promise<boolean> {+ return withTemporaryIndex(async (extraEnv) => {+ await gitExec(['read-tree', tree], worktreePath, { extraEnv });+ await gitExec(['update-index', '-q', '--refresh'], worktreePath, { extraEnv }).catch(() => undefined);+ const { stdout: changed } = await gitExec(['diff-files', '--name-status', '-z'], worktreePath, { extraEnv });+ const fields = changed.split('\0').filter(Boolean);+ for (let index = 0; index < fields.length; index += 2) {+ if (fields[index] !== 'D') return false;+ }+ const { stdout: extra } = await gitExec(['ls-files', '--others', '--exclude-standard', '-z'], worktreePath, { extraEnv });+ return extra.length === 0;+ });+}++/** Write snapshot files that are missing; existing files are never overwritten. */+export async function checkoutMissingSnapshotFiles(worktreePath: string, tree: string): Promise<void> {+ await withTemporaryIndex(async (extraEnv) => {+ await gitExec(['read-tree', tree], worktreePath, { extraEnv });+ // Without --force Git skips existing paths and reports them as errors; completeness is checked below.+ await gitExec(['checkout-index', '--all', '--quiet'], worktreePath, { extraEnv }).catch(() => undefined);+ await gitExec(['update-index', '-q', '--refresh'], worktreePath, { extraEnv }).catch(() => undefined);+ const { stdout } = await gitExec(['diff-files', '--name-status', '-z', '--diff-filter=D'], worktreePath, { extraEnv });+ if (stdout.length > 0) throw new Error('snapshot files could not be restored');+ });+}+/** Staged content of the live index, read from a copy so the live index is never locked or rewritten. */async function stagedTree(worktreePath: string): Promise<string | null> {const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-index-'));@@ -79,11 +145,13 @@ export class WorktreeChangedDuringSnapshotError extends Error {* Snapshot the actual HEAD, index and file tree without stashing or changing the live checkout.* `stagedContentOnly` checks consistency like {@link worktreeStagedContentMatches}, for callers* that only need the captured content; the default byte comparison suits destructive recycling.+ * `includeUntracked` also saves new files that `.gitignore` does not exclude, so recycling can+ * delete the directory without any other copy of its bytes.*/export async function captureWorktreeContent(worktreePath: string,ref: string,- { stagedContentOnly = false }: { stagedContentOnly?: boolean } = {},+ { stagedContentOnly = false, includeUntracked = false }: { stagedContentOnly?: boolean; includeUntracked?: boolean } = {},): Promise<NonNullable<WorktreeRecycleRecord['snapshot']>> {const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-index-'));const index = path.join(temp, 'index');@@ -97,8 +165,8 @@ export async function captureWorktreeContent(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);+ // Ignored files are regenerable (dependencies, build output) and are never saved.+ await gitExec(['add', includeUntracked ? '--all' : '--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.@@ -116,8 +184,12 @@ export async function captureWorktreeContent();const commit = commitOutput.trim();await gitExec(['update-ref', ref, commit], worktreePath);- const snapshot = { head, headRef, tree, indexTree, commit, ref, indexHash: originalIndexHash };- const unchanged = stagedContentOnly+ const snapshot = {+ head, headRef, tree, indexTree, commit, ref, indexHash: originalIndexHash,+ ...(includeUntracked ? { untracked: true as const } : {}),+ };+ // Recycling rechecks the full tree before deleting; here only HEAD and staged content matter.+ const unchanged = stagedContentOnly || includeUntracked? await worktreeStagedContentMatches(worktreePath, snapshot): await worktreeContentBaselineMatches(worktreePath, snapshot);if (!unchanged) throw new WorktreeChangedDuringSnapshotError();diff --git a/apps/desktop/src/main/worktree/managedRecycle.ts b/apps/desktop/src/main/worktree/managedRecycle.tsindex 0966967b59..b207eb38e0 100644--- a/apps/desktop/src/main/worktree/managedRecycle.ts+++ b/apps/desktop/src/main/worktree/managedRecycle.ts@@ -3,13 +3,12 @@ import { randomUUID } from 'node:crypto';import fs from 'node:fs/promises';import path from 'node:path';-import { captureWorktreeContent, worktreeContentBaselineMatches } from './contentSnapshot';+import { captureWorktreeContent, worktreeContentMatches } from './contentSnapshot';import { gitExec } from './gitExec';import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRefs';import {newRecycleRecord, readRecycleRecord, writeRecycleRecord, worktreeGeneration,} from './recycleJournal';-import { createRecoveryArchive, inventoryWorktree, sameWorktreeFiles, verifyRecoveryArchive } from './recoveryArchive';import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';import { isManagedWorktreePath } from './safety';import { assertManagedResourcePath, assertWorktreeGitIdentity } from './resourceSafety';@@ -45,11 +44,9 @@ export async function checkpointWorktreeForReuse(meta: WorktreeMeta): Promise<vo}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()}`);+ record.snapshot = await captureWorktreeContent(meta.path, `refs/cindy/worktree-recovery/${record.id}/${randomUUID()}`, { includeUntracked: true });if (hasLiveSessionReference(meta, await loadLiveSessionPathKeys({ contextPath: meta.path }))- || !(await worktreeContentBaselineMatches(meta.path, record.snapshot))- || !sameWorktreeFiles(await inventoryWorktree(meta.path), record.archive.files)) {+ || !(await worktreeContentMatches(meta.path, record.snapshot))) {throw new Error('pooled worktree changed before reuse');}await assertManagedResourcePath(meta, store.getAllPaths());@@ -70,6 +67,16 @@ async function directoryIdentity(value: string): Promise<string | null> {}}+async function hasGitLink(worktreePath: string): Promise<boolean> {+ try {+ await fs.lstat(path.join(worktreePath, '.git'));+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ 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);@@ -113,11 +120,15 @@ async function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: Managedawait writeRecycleRecord(record);return false;};- const canRemove = async (): Promise<boolean> => {+ // The owner still wants this generation gone (task archived/deleted, no newer registration).+ const ownerAllowsRemoval = 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;+ return !current || worktreeGeneration(current) === record.generation;+ };+ const canRemove = async (): Promise<boolean> => {+ if (!(await ownerAllowsRemoval())) return false;const refs = await loadLiveSessionPathKeys({contextPath: meta.path, excludeSessionId: meta.sessionId,isSessionRuntimeAlive: options.isSessionRuntimeAlive,@@ -126,15 +137,20 @@ async function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: Managed};try {if (meta.quarantinePath) return defer('legacy-quarantine-needs-review');- if (!(await canRemove())) return defer('referenced-or-runtime-unavailable');+ if (!(await ownerAllowsRemoval())) return defer('referenced-or-runtime-unavailable');const identity = await directoryIdentity(meta.path);if (identity === null) {+ // Nothing left to delete, so other references cannot keep this request waiting.record.phase = 'removed';+ record.reason = undefined;await writeRecycleRecord(record);+ await gitExec(['worktree', 'prune'], meta.baseRepo).catch(() => undefined);await options.onRemoved?.();- await unregisterResource(meta);+ if (await canRemove()) await unregisterResource(meta);+ else await store.del(meta.sessionId);return true;}+ if (!(await canRemove())) return defer('referenced-or-runtime-unavailable');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));@@ -148,78 +164,50 @@ async function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: Managed}record.directoryIdentity = identity;await assertManagedResourcePath(meta, store.getAllPaths());- const partialRemoval = record.phase === 'removing' && record.snapshot && record.archive;- if (!partialRemoval) {+ // Git can delete .git before Windows reports EBUSY; such a resumed removal keeps the+ // snapshot that was verified before deletion started.+ const resumingRemoval = record.phase === 'removing' && Boolean(record.snapshot) && !(await hasGitLink(meta.path));+ if (!resumingRemoval) {// 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()}`);+ // Git keeps tracked and new files; ignored files (dependencies, build output) are not saved.+ if (!record.snapshot || !(await worktreeContentMatches(meta.path, record.snapshot))) {+ record.snapshot = await captureWorktreeContent(+ meta.path, `refs/cindy/worktree-recovery/${record.id}/${randomUUID()}`, { includeUntracked: true },+ );+ record.archive = undefined;}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');- }+ const snapshot = record.snapshot;+ if (!snapshot) return defer('recovery-evidence-missing');+ const contentUnchanged = async (): Promise<boolean> => {+ if (!(await hasGitLink(meta.path))) return resumingRemoval;+ await assertWorktreeGitIdentity(meta);+ return worktreeContentMatches(meta.path, snapshot);+ };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');- }+ if (!(await contentUnchanged())) return defer('git-baseline-changed');record.phase = 'removing';await writeRecycleRecord(record);- // Revalidate immediately before the destructive Git operation. The- // earlier inventory is only a snapshot; a late editor/IDE write or a- // newly live reference must keep this generation protected.- 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-before-removal');- }+ // Revalidate immediately before the destructive Git operation: a late+ // editor/IDE write or a newly live reference keeps this generation protected.if (!(await canRemove())) return defer('referenced-before-removal');if (await directoryIdentity(meta.path) !== identity) return defer('directory-replaced');await assertManagedResourcePath(meta, store.getAllPaths());- let finalGitLinkPresent = true;- try { await fs.lstat(path.join(meta.path, '.git')); } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;- finalGitLinkPresent = false;- }- if (!partialRemoval || finalGitLinkPresent) {- await assertWorktreeGitIdentity(meta);- if (!(await worktreeContentBaselineMatches(meta.path, record.snapshot))) return defer('git-baseline-changed-before-removal');- }+ if (!(await contentUnchanged())) return defer('git-baseline-changed-before-removal');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) {+ if (await hasGitLink(meta.path)) {await assertWorktreeGitIdentity(meta);- if (!(await worktreeContentBaselineMatches(meta.path, record.snapshot))) return defer('git-baseline-changed');+ if (!(await worktreeContentMatches(meta.path, 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 });diff --git a/apps/desktop/src/main/worktree/recycleJournal.ts b/apps/desktop/src/main/worktree/recycleJournal.tsindex aeb3a68414..e927ed7ed3 100644--- a/apps/desktop/src/main/worktree/recycleJournal.ts+++ b/apps/desktop/src/main/worktree/recycleJournal.ts@@ -27,11 +27,15 @@ export interface WorktreeRecycleRecord {retryPolicy?: WorktreeRecyclePolicy;/** null is a durable marker that recovery has reserved a previously absent directory. */directoryIdentity?: string | null;- snapshot?: { head: string; headRef?: string | null; tree: string; indexTree: string; commit: string; ref: string; indexHash: string };+ /** `untracked` marks a tree that also holds new non-ignored files; older snapshots relied on `archive`. */+ snapshot?: { head: string; headRef?: string | null; tree: string; indexTree: string; commit: string; ref: string; indexHash: string; untracked?: true };restoredGeneration?: string;/** Temporary checkout used to repair a partially removed worktree. */restoreCheckoutPath?: string;+ /** Written only by older clients; still honoured when restoring their records. */archive?: WorktreeRecoveryArchive;+ /** The one fresh retry budget for a request an older client paused over its archive. */+ legacyArchiveRetry?: true;}export function recycleJournalRoot(): string {@@ -106,7 +110,7 @@ export async function writeRecycleRecord(record: WorktreeRecycleRecord): Promiseawait fs.mkdir(root, { recursive: true });// Must be discoverable before committing an intent that permits destructive I/O.await publishJournalLocation(root);- if (record.archive && record.snapshot && record.phase === 'removed') {+ if (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');@@ -153,6 +157,60 @@ export async function newRecycleRecord(meta: WorktreeMeta): Promise<WorktreeRecy};}+const archiveNamePattern = /^[a-f0-9-]+\.tar\.gz\.enc$/;+/** Older clients may still be writing an archive in a shared profile; their writes finish well within this. */+const ORPHAN_ARCHIVE_MIN_AGE_MS = 2 * 60 * 60_000;++/**+ * Delete recovery archives no record points to. Older clients left one per interrupted attempt;+ * its key lived only in the unsaved record, so nothing can ever decrypt it. Any unreadable+ * record skips the sweep, since it might reference an archive.+ */+export async function pruneUnreferencedRecoveryArchives(now = Date.now()): Promise<number> {+ const root = recycleJournalRoot();+ let names: string[];+ try {+ names = await fs.readdir(root);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 0;+ throw error;+ }+ const archives = names.filter((name) => archiveNamePattern.test(name));+ if (archives.length === 0) return 0;+ const referenced = new Set<string>();+ const history = path.join(root, 'history');+ let historyNames: string[] = [];+ try { historyNames = await fs.readdir(history); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ const recordFiles = [+ ...names.filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).map((name) => ({ file: path.join(root, name), id: name.slice(0, 64) })),+ ...historyNames.filter((name) => /^[a-f0-9]{64}-[a-f0-9]{64}\.json$/.test(name)).map((name) => ({ file: path.join(history, name), id: name.slice(0, 64) })),+ ];+ for (const { file, id } of recordFiles) {+ let record: WorktreeRecycleRecord;+ try { record = parseRecord(await fs.readFile(file, 'utf8'), id); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ log.warn('recovery archive sweep skipped: unreadable record', { resourceId: id });+ return 0;+ }+ if (record.archive?.file) referenced.add(record.archive.file);+ }+ let removed = 0;+ for (const name of archives) {+ if (referenced.has(name)) continue;+ const file = path.join(root, name);+ try {+ if (now - (await fs.stat(file)).mtimeMs < ORPHAN_ARCHIVE_MIN_AGE_MS) continue;+ await fs.rm(file, { force: true });+ removed++;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ }+ return removed;+}+/** Fail closed for a malformed file; callers report the failure without discarding evidence. */export async function listRecycleRecords(): Promise<WorktreeRecycleRecord[]> {let names: string[];diff --git a/apps/desktop/src/main/worktree/recycleMaintenance.ts b/apps/desktop/src/main/worktree/recycleMaintenance.tsindex b92bbf3860..9fbdb6eadb 100644--- a/apps/desktop/src/main/worktree/recycleMaintenance.ts+++ b/apps/desktop/src/main/worktree/recycleMaintenance.ts@@ -5,11 +5,14 @@ import { app } from 'electron';import { getDbClient } from '../localDb/client/current';import { createLogger } from '../logger';-import { listRecycleRecords, readRecycleRecord, watchRecycleJournal, worktreeGeneration, type WorktreeRecycleRecord } from './recycleJournal';+import {+ listRecycleRecords, pruneUnreferencedRecoveryArchives, readRecycleRecord, watchRecycleJournal, worktreeGeneration, writeRecycleRecord,+ type WorktreeRecycleRecord,+} from './recycleJournal';import { recycleManagedWorktree } from './managedRecycle';import { hasLiveSessionReference, loadLiveSessionPathKeys, pathKey } from './liveSessionRefs';import * as store from './worktreeStore';-import { physicalWorktreeKey } from './resourceLock';+import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';import { subscribeWorktreeRecycleEvents } from './recycleEvents';import { retryPendingWorktreeRuntimeLeaseReleases } from './runtimeLeases';@@ -25,6 +28,13 @@ export interface WorktreeMaintenanceOptions {onAttemptComplete?(): Promise<void>;}+const legacyArchiveFailureReasons = new Set(['recycle-failed', 'ENOSPC']);++function grantsLegacyArchiveRetry(record: WorktreeRecycleRecord): boolean {+ return !record.legacyArchiveRetry && !record.snapshot?.untracked && record.phase === 'pending'+ && recyclePolicy(record).state === 'paused' && legacyArchiveFailureReasons.has(record.reason ?? '');+}+/** Event-driven, single-flight maintenance with one timer for the earliest pending deadline. */export class WorktreeRecycleMaintenance {private timer: ReturnType<typeof setTimeout> | null = null;@@ -142,6 +152,37 @@ export class WorktreeRecycleMaintenance {return Math.max(record.nextAttemptAt, this.attempts.get(this.key(record))?.notBefore ?? 0);}+ /**+ * Recycling no longer builds recovery archives. Once per start, delete archives nothing can+ * decrypt, and give requests that older clients paused (usually an archive timeout or a disk+ * filled by archives) one fresh failure budget. Paused-by-user or identity faults stay put.+ */+ private async retireRecoveryArchives(records: readonly WorktreeRecycleRecord[]): Promise<boolean> {+ let granted = false;+ try {+ const pruned = await pruneUnreferencedRecoveryArchives();+ if (pruned > 0) log.info('removed unreferenced worktree recovery archives', { count: pruned });+ for (const candidate of records) {+ if (!grantsLegacyArchiveRetry(candidate)) continue;+ await withWorktreeResourceLock(candidate.meta.path, async () => {+ const record = await readRecycleRecord(candidate.meta.path);+ if (!record || record.id !== candidate.id || record.generation !== candidate.generation+ || !grantsLegacyArchiveRetry(record)) return;+ record.retryPolicy = { state: 'retrying', failures: 0, failedWorkMs: 0 };+ record.reason = undefined;+ record.attempts = 0;+ record.nextAttemptAt = 0;+ record.legacyArchiveRetry = true;+ await writeRecycleRecord(record);+ granted = true;+ });+ }+ } catch (error) {+ log.warn('worktree recovery archive retirement postponed', { code: (error as NodeJS.ErrnoException).code ?? 'unavailable' });+ }+ return granted;+ }+private async runPass(): Promise<void> {if (!this.options.isReady()) return;await this.ensureWatcher();@@ -150,7 +191,8 @@ export class WorktreeRecycleMaintenance {try { pendingLeaseReleases = await retryPendingWorktreeRuntimeLeaseReleases(); }catch (error) { log.warn('worktree runtime lease release retry postponed', { code: (error as NodeJS.ErrnoException).code ?? 'unavailable' }); pendingLeaseReleases = 1; }if (pendingLeaseReleases > 0) this.schedule(Date.now() + retryDelay(1));- const records = await listRecycleRecords();+ let records = await listRecycleRecords();+ if (this.initialPass && await this.retireRecoveryArchives(records)) records = await listRecycleRecords();const wakeIds = new Set(this.wakeIds);this.wakeIds.clear();// A resource may have been released while Cindy was closed: recheck waitsdiff --git a/apps/desktop/src/main/worktree/restore.ts b/apps/desktop/src/main/worktree/restore.tsindex f2f08cd14d..a7f67c77af 100644--- a/apps/desktop/src/main/worktree/restore.ts+++ b/apps/desktop/src/main/worktree/restore.ts@@ -31,7 +31,7 @@ import {withWorktreeRestoreMutation,} from './restoreLock';import { copyClaudeSiviDirs } from './WorktreeManager';-import { restoreRecordedWorktree } from './restoreRecovery';+import { hasRecordedRecovery, restoreRecordedWorktree } from './restoreRecovery';import { readRecycleRecord, worktreeGeneration } from './recycleJournal';import { withWorktreeResourceLock } from './resourceLock';import * as store from './worktreeStore';@@ -371,7 +371,7 @@ async function getWorktreeRestorePlan(sessionId: string): Promise<WorktreeRestor&& await pathExists(worktreePath)) {return { status: { state: 'present', worktreePath, hasSnapshot: false }, parsed };}- if (recovery?.snapshot && recovery.archive && ['removed', 'removing', 'restoring'].includes(recovery.phase)) {+ if (hasRecordedRecovery(recovery) && ['removed', 'removing', 'restoring'].includes(recovery.phase)) {return { status: { state: 'restorable', worktreePath, hasSnapshot: true }, parsed };}diff --git a/apps/desktop/src/main/worktree/restoreRecovery.ts b/apps/desktop/src/main/worktree/restoreRecovery.tsindex 2e5af33c95..04e43ea087 100644--- a/apps/desktop/src/main/worktree/restoreRecovery.ts+++ b/apps/desktop/src/main/worktree/restoreRecovery.ts@@ -12,7 +12,7 @@ import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRimport { assertManagedResourceLocation, assertManagedResourcePath, assertWorktreeGitIdentity } from './resourceSafety';import * as store from './worktreeStore';import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';-import { readWorktreeHeadRef } from './contentSnapshot';+import { checkoutMissingSnapshotFiles, presentFilesMatchSnapshotTree, readWorktreeHeadRef } from './contentSnapshot';function restoreCheckoutPathIsSafe(value: string): boolean {if (!path.isAbsolute(value)) return false;@@ -37,14 +37,39 @@ async function indexIsRestorable(worktreePath: string, indexTree: string): Promi} catch { return false; }}-/** Restore new recovery records; return null to retain compatibility with older stash/branch recovery. */+type RecycleRecord = NonNullable<Awaited<ReturnType<typeof readRecycleRecord>>>;++/** Recovery evidence is complete: older snapshots without untracked files also need their archive. */+export function hasRecordedRecovery(record: RecycleRecord | null | undefined): record is RecycleRecord {+ return Boolean(record?.snapshot && (record.archive || record.snapshot.untracked));+}++function restorableRecord(record: RecycleRecord | null): record is RecycleRecord {+ return hasRecordedRecovery(record) && record.phase !== 'restored' && record.phase !== 'pending';+}++async function pathExists(value: string): Promise<boolean> {+ try {+ await fs.lstat(value);+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw error;+ }+}++/**+ * Restore recorded recycles; return null to retain compatibility with older stash/branch recovery.+ * Records from older clients carry an encrypted archive; newer ones rebuild files from the Git+ * snapshot, which holds tracked and new files but not ignored ones.+ */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;+ if (!restorableRecord(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 || !restorableRecord(record)) 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;const headRef = record.snapshot.headRef;@@ -88,10 +113,15 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: sreturn true;}await assertManagedResourcePath(record.meta, [worktreePath]);- if (!sameWorktreeFiles(await inventoryWorktree(worktreePath), record.archive.files, true)) return false;+ if (record.archive) {+ if (!sameWorktreeFiles(await inventoryWorktree(worktreePath), record.archive.files, true)) return false;+ } else if (await pathExists(path.join(worktreePath, '.git'))+ && !(await presentFilesMatchSnapshotTree(worktreePath, record.snapshot.tree))) {+ return false;+ }}if (hasLiveSessionReference(record.meta, await loadLiveSessionPathKeys({ excludeSessionId: sessionId }))) return false;- await verifyRecoveryArchive(record.archive);+ if (record.archive) await verifyRecoveryArchive(record.archive);if (!legacyGuardHeld()) return false;if (headRef) {try {@@ -175,7 +205,13 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: sif (head.trim() !== record.snapshot.head) return false;if (headRef !== undefined && await readWorktreeHeadRef(worktreePath) !== headRef) return false;if (!(await indexIsRestorable(worktreePath, record.snapshot.indexTree))) return false;- await extractRecoveryArchive(record.archive, worktreePath, true);+ if (record.archive) {+ await extractRecoveryArchive(record.archive, worktreePath, true);+ } else {+ // Recheck after the Git link was repaired: surviving files must still be snapshot bytes.+ if (!(await presentFilesMatchSnapshotTree(worktreePath, record.snapshot.tree))) return false;+ await checkoutMissingSnapshotFiles(worktreePath, record.snapshot.tree);+ }if (hasLiveSessionReference(record.meta, await loadLiveSessionPathKeys({ excludeSessionId: sessionId }))) return false;await assertManagedResourcePath(record.meta, [worktreePath]);await assertWorktreeGitIdentity(record.meta);diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.tsindex 0a0044f306..989f8cb663 100644--- a/apps/desktop/src/main/worktree/runtimeLeases.ts+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts@@ -1,6 +1,7 @@import { createHash, randomUUID } from 'node:crypto';import fsSync from 'node:fs';import fs from 'node:fs/promises';+import os from 'node:os';import path from 'node:path';import { app } from 'electron';@@ -236,6 +237,37 @@ function pidMayBeAlive(pid: number): boolean {}}+/** Generous margin for clock corrections after boot; only clearly older evidence is waived. */+const BOOT_MARGIN_MS = 10 * 60_000;+/**+ * Once Main is gone, an agent it started gets no further input and settles well within this.+ * Until then a crashed owner's lease stays protective, because its child may still be writing.+ */+const ABANDONED_LEASE_GRACE_MS = 60 * 60_000;++function startedBeforeBoot(timestampMs: unknown): boolean {+ return typeof timestampMs === 'number' && Number.isFinite(timestampMs)+ && timestampMs < Date.now() - os.uptime() * 1000 - BOOT_MARGIN_MS;+}++/**+ * A lease left by a Main process that never released it: written before this boot, or its+ * owner (and any recorded child) has exited and the grace period has passed.+ */+async function isAbandonedLease(+ file: string,+ lease: { pid?: unknown; childPid?: unknown; childPids?: unknown },+): Promise<boolean> {+ const isPid = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value > 0;+ if (!isPid(lease.pid) || lease.pid === process.pid) return false;+ const { mtimeMs } = await fs.stat(file);+ if (startedBeforeBoot(mtimeMs)) return true;+ // Unknown child evidence stays protective, like the explicit orphan reclaim path.+ const children = [lease.childPid, ...(Array.isArray(lease.childPids) ? lease.childPids : [])];+ if (children.some((child) => child != null && (!isPid(child) || pidMayBeAlive(child)))) return false;+ return !pidMayBeAlive(lease.pid) && Date.now() - mtimeMs > ABANDONED_LEASE_GRACE_MS;+}+/** 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');@@ -260,6 +292,13 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {// Only unsupported instances can block the entire lease view. Do not add// an OS subprocess per compatible instance to the normal recycle path.if (record.worktreeLeaseProtocol !== 1) {+ // An instance registered before this boot cannot still run: the PID now+ // belongs to an unrelated process. The SingletonLock check below still+ // revalidates the process identity before waiving that lock.+ if (startedBeforeBoot(record.startedAtMs)) {+ reusedInstanceRecords.set(pid, raw);+ continue;+ }const identity = await readDesktopProcessIdentity(pid);// A replacement instance may have registered while the OS query ran.if (await readRecord(name) !== raw) return null;@@ -313,10 +352,13 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {for (const name of leases) {if (!leaseNamePattern.test(name)) continue;// Main may have crashed while a detached child still uses the directory.- // Only explicit release proves source I/O stopped, across every profile.+ // Explicit release proves source I/O stopped; otherwise only a reboot or an+ // exited owner past the grace period does, across every profile.try {- const lease = JSON.parse(await fs.readFile(path.join(directory, name), 'utf8'));+ const file = path.join(directory, name);+ const lease = JSON.parse(await fs.readFile(file, 'utf8'));if (lease.version !== 1 || typeof lease.path !== 'string') return null;+ if (await isAbandonedLease(file, lease)) continue;paths.add(lease.path);} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null;diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 2ddc46d740..f14aa2fdc4 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -206,7 +206,8 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复| Skill 卸载清理回执 | `app.getPath('userData')/skillhub/uninstall-cleanups/<token>.json`,记录操作 owner、旧文件/注册/偏好身份与完成阶段;跨窗口和重启保留,当前 owner 重试完成后删除,不作为授权凭据 || 跨 profile 的 Cindy 内置 Skill 副本 | `app.getPath('appData')/Cindy/shared-system-skills`,只保存随应用发布、可由 bundle 重建的官方 Skill;Global、China、dev 与 isolated profile 共用稳定物理路径,更新和共享发现链接必须持有下述互斥锁 || 跨 profile 的共享 Skill 文件互斥 | `app.getPath('appData')/Cindy/shared-skill-mutation-locks`,仅存文件锁及未完成操作的 token/名称哈希,保证正式版/dev/isolated 共用;短期锁复用既有崩溃回收,持久屏障必须等对应清理完成后删除,读取损坏只阻止相关名称 |-| 旧跨 profile 的 worktree 借用租约 | `app.getPath('appData')/Cindy/shared-worktree-runtime-leases`,内置模拟器下线后不再创建共享租约;回收器仍读取旧证据并重试已有 `.release` 回执,不能因进程退出就移除保护。普通 Agent 的当前 profile 租约照常创建与释放 |+| 旧跨 profile 的 worktree 借用租约 | `app.getPath('appData')/Cindy/shared-worktree-runtime-leases`,内置模拟器下线后不再创建共享租约;回收器仍读取旧证据并重试已有 `.release` 回执。普通 Agent 的当前 profile 租约(`userData/worktree-runtime-leases`)照常创建与释放。两处租约都只有三种情况不再保护:显式释放;写于本次开机之前(留 10 分钟时钟余量);持有进程与记录的子进程都已退出且超过 1 小时。仅进程刚退出不算,未知子进程证据仍保护。`.dev-instances` 里开机前启动、不支持租约协议的旧实例登记同样不再一票否决,但 POSIX 的 SingletonLock 仍要先核对进程身份。见 `worktree/runtimeLeases.ts` |+| worktree 回收记录与恢复内容 | `userData/worktree-recycle/<资源 id>.json` 与 `history/`,记录删除意图、Git 快照引用与重试状态。归档/删除时只把已跟踪改动和未被 `.gitignore` 排除的新文件存进 Git 快照(`refs/cindy/worktree-recovery/...`),被忽略的依赖、构建产物、缓存不保存,恢复后需重装或重建。新客户端不再生成加密归档 `*.tar.gz.enc`;旧客户端记录里的归档照旧用于恢复,没有任何记录引用、超过 2 小时的归档在启动时删除(其密钥只存在于未落盘的记录里,无法解密),有记录读不出时整次跳过。旧客户端因归档失败暂停的请求升级后自动重试一次。见 `worktree/managedRecycle.ts`、`restoreRecovery.ts` 与 `recycleJournal.ts` || 旧版 worktree 回收器兼容锁 | 不再创建新的跨 profile Git 锁;保留旧回执对 `<commonGitDir>/worktrees/<id>/locked` 及更早 `.worktree-keep` 的清理。仅当最后一个共享借用结束且自建文件身份和内容仍匹配时删除,不覆盖用户锁;失败沿用 `.release` 重试。支持精确的 `bigint:dev:ino:birthtimeNs` 身份;旧数字编号为 0 或超过安全整数范围时无法证明归属,保留锁但仍释放已结束的租约,避免 Windows 编号精度丢失误删用户替换文件 || 跨 profile 的 worktree 回收日志位置 | `app.getPath('appData')/Cindy/shared-worktree-recycle-journals`,仍按日志目录哈希发布原 profile 日志位置,兼容可能同时运行的旧客户端;新客户端不再读取其他 profile 的日志来借用工程。不复制恢复状态、不代替 owner 执行恢复 || 供应商分享:分享者电脑上的受邀者用量 | `userData/remote-agent/provider-share-usage.json`,按(日期、分享、成员、Agent、供应商、模型)聚合 token 与轮次,行内 `byMember` 按组内电脑的键再分(2026-10-11 加;行键与合计不变,旧版本照常累计并原样写回,合计多出各台之和的部分算没区分电脑),原子替换写入,保留 400 天;只含服务端生成的分享与成员 id,不含昵称、对话或凭证。成员删除后保留(管理页不再显示),同一人重新加入时接续 |diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.mdindex 32fb2991b2..9076e57ec6 100644--- a/docs/dev-rules/development-workflow.md+++ b/docs/dev-rules/development-workflow.md@@ -27,7 +27,8 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径- **宿主 app 日志不在你的 cwd 下**:dev 日志在启动 checkout(通常是 baseRepo)的`apps/desktop/logs/`,读日志时拼 baseRepo 的绝对路径。- **会话结束与工作区保留**:是否 commit 由用户或宿主工作流决定,不能仅因会话结束- 强制提交。会话被删除或归档时脏 worktree 会先存内容快照再删目录。**PR+ 强制提交。会话被删除或归档时脏 worktree 会先把改动和新文件存进 Git 快照再删目录;+ 被 `.gitignore` 忽略的文件(依赖、构建产物)不保留。**PRmerged/closed 不等于 Cindy 会话已结束**:只要 owning session 仍 active,任何外部 Gitcleanup 都必须跳过该 `.cindy-worktrees` / `.xdt-worktrees` 目录与本地 `cindy/*` / `xdt/*` 分支,交给用户显式归档/删除会话时回收;禁止手动 `git worktree remove` 造成 active session 的 cwd