Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 回收续删只删可证明已保存的文件,租约按心跳与进程身份失效
david475a7f60e09b
diff --git a/apps/desktop/help-knowledge/worktrees.md b/apps/desktop/help-knowledge/worktrees.mdindex 66d39f7235..61170dd95d 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 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.+- 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) and Git repositories cloned or initialised inside the worktree are **not kept**; reinstall, rebuild or clone them again after restoring. Restored files go through Git's usual line-ending and symlink handling, like a normal checkout. 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 ece620a088..fa6616b78e 100644--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts@@ -24,7 +24,12 @@ vi.mock('../worktree/runtimeLeases', async (original) => ({...await original<typeof import('../worktree/runtimeLeases')>(),readWorktreeRuntimePaths: vi.fn(async () => state.runtimes),}));-vi.mock('../worktree/contentSnapshot', () => ({ captureWorktreeContent: snapshot, worktreeContentMatches: baselineMatches }));+vi.mock('../worktree/contentSnapshot', () => ({+ captureWorktreeContent: snapshot, worktreeContentMatches: baselineMatches,+ worktreeStagedContentMatches: vi.fn(async () => true), releaseSnapshotRef: vi.fn(async () => true),+ // Path lists are covered with real Git; here a resumed removal checks timestamps only.+ discardableWorktreePaths: vi.fn(async () => null), snapshotTreePaths: vi.fn(async () => new Set()),+}));vi.mock('../worktree/gitExec', () => ({ gitExec: git }));import { checkpointWorktreeForReuse, recycleManagedWorktree, requestWorktreeRecycle } from '../worktree/managedRecycle';@@ -336,7 +341,8 @@ describe('shared worktree recycling', () => {return true;}).mockResolvedValueOnce(false);expect(await recycle()).toBe(false);- expect((await readRecycleRecord(meta.path))?.phase).toBe('removing');+ // Nothing was deleted, so the next attempt verifies (and if needed re-snapshots) the full tree.+ expect((await readRecycleRecord(meta.path))?.phase).toBe('snapshotted');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');diff --git a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.tsindex 88a0025277..87820689c5 100644--- a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts@@ -44,7 +44,8 @@ vi.mock('../worktree/gitExec', async (original) => {import { checkpointWorktreeForReuse, recycleManagedWorktree } from '../worktree/managedRecycle';import { restoreRecordedWorktree } from '../worktree/restoreRecovery';-import { readRecycleRecord, writeRecycleRecord } from '../worktree/recycleJournal';+import { newRecycleRecord, readRecycleRecord, writeRecycleRecord } from '../worktree/recycleJournal';+import { releaseObsoleteRecoverySnapshots } from '../worktree/recycleMaintenance';import { captureWorktreeContent } from '../worktree/contentSnapshot';import { GitExecError, gitExec } from '../worktree/gitExec';import { acquireWorktree, releaseWorktree, parkAll } from '../worktree/WorktreePool';@@ -152,6 +153,111 @@ describe('worktree recovery with real Git', () => {expect(await git(repo, 'rev-parse', 'cindy/attached')).toBe(await git(meta.path, 'rev-parse', 'HEAD'));}, 30_000);+ it('deletes nested repositories instead of waiting on them and restores only saved files', async () => {+ const meta = await createFixture('nested');+ const cloned = path.join(meta.path, 'vendor', 'cloned');+ await fs.mkdir(cloned, { recursive: true });+ await git(cloned, 'init', '-b', 'main');+ await fs.writeFile(path.join(cloned, 'lib.txt'), 'nested\n');+ await git(cloned, 'add', 'lib.txt');+ await git(cloned, '-c', 'user.name=Nested', '-c', 'user.email=nested@localhost', 'commit', '-m', 'nested');+ // A plain file beside the nested repository is ordinary new content and must be saved.+ await fs.writeFile(path.join(meta.path, 'vendor', 'notes.txt'), 'beside the clone\n');+ // A repository without a commit makes a plain `git add --all` fail outright.+ const scaffold = path.join(meta.path, 'scaffold');+ await fs.mkdir(scaffold);+ await git(scaffold, 'init');+ await fs.writeFile(path.join(scaffold, 'app.txt'), 'generated\n');+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);+ await expect(fs.stat(meta.path)).rejects.toMatchObject({ code: 'ENOENT' });+ const record = (await readRecycleRecord(meta.path))!;+ const savedTree = await git(repo, 'ls-tree', '-r', '--name-only', record.snapshot!.commit);+ expect(savedTree.split('\n')).toEqual(expect.arrayContaining(['draft.txt', 'vendor/notes.txt']));+ expect(savedTree).not.toContain('vendor/cloned');+ expect(savedTree).not.toContain('scaffold');+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(true);+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('nested contents\n');+ expect(await fs.readFile(path.join(meta.path, 'vendor', 'notes.txt'), 'utf8')).toBe('beside the clone\n');+ await expect(fs.stat(cloned)).rejects.toMatchObject({ code: 'ENOENT' });+ // A restored snapshot is consumed: its ref no longer keeps the objects alive.+ expect(await git(repo, 'for-each-ref', record.snapshot!.ref)).toBe('');+ }, 30_000);++ it('saves tracked edits hidden by assume-unchanged without touching the live index flag', async () => {+ const meta = await createFixture('hidden-edit');+ await git(meta.path, 'update-index', '--assume-unchanged', 'tracked.txt');+ await fs.writeFile(path.join(meta.path, 'tracked.txt'), 'local only\n');+ const probe = await captureWorktreeContent(meta.path, 'refs/cindy/worktree-recovery/probe/hidden', { includeUntracked: true });+ expect(await git(repo, 'show', `${probe.tree}:tracked.txt`)).toBe('local only');+ expect(await git(meta.path, 'ls-files', '-v', 'tracked.txt')).toBe('h tracked.txt');+ await git(repo, 'update-ref', '-d', probe.ref);++ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(true);+ expect(await fs.readFile(path.join(meta.path, 'tracked.txt'), 'utf8')).toBe('local only\n');+ }, 30_000);++ it('resumes a partial removal from the original snapshot and stops at a file written since', async () => {+ const meta = await createFixture('resumed');+ const record = await newRecycleRecord(meta);+ record.snapshot = await captureWorktreeContent(meta.path, `refs/cindy/worktree-recovery/${record.id}/resumed`, { includeUntracked: true });+ // Removal began after every existing file was written, then Windows stopped at a locked+ // file: draft.txt is gone while .git survives.+ record.phase = 'removing';+ record.removingSince = Date.now();+ record.removalDiscardable = [];+ await writeRecycleRecord(record);+ await fs.rm(path.join(meta.path, 'draft.txt'));+ const late = path.join(meta.path, 'late.txt');+ await fs.writeFile(late, 'written after removal began\n');+ const later = new Date(record.removingSince + 60_000);+ await fs.utimes(late, later, later);++ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(false);+ const waiting = (await readRecycleRecord(meta.path))!;+ expect(waiting.reason).toBe('residual-files-changed');+ expect(waiting.snapshot!.commit).toBe(record.snapshot.commit);+ expect(await fs.readFile(late, 'utf8')).toBe('written after removal began\n');+ await fs.rm(late);++ // Moved or copied in with its old timestamps: only the path shows it was never saved.+ const moved = path.join(meta.path, 'moved-in.txt');+ await fs.writeFile(moved, 'kept its original timestamps\n');+ waiting.removingSince = Date.now() + 60_000;+ await writeRecycleRecord(waiting);+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(false);+ expect((await readRecycleRecord(meta.path))?.reason).toBe('residual-files-changed');+ expect(await fs.readFile(moved, 'utf8')).toBe('kept its original timestamps\n');++ await fs.rm(moved);+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);+ await expect(fs.stat(meta.path)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(true);+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('resumed contents\n');+ }, 30_000);++ it('drops a superseded snapshot at once and a deleted task\'s snapshot only in the startup sweep', async () => {+ const meta = await createFixture('retention');+ const record = await newRecycleRecord(meta);+ record.snapshot = await captureWorktreeContent(meta.path, `refs/cindy/worktree-recovery/${record.id}/older`, { includeUntracked: true });+ record.phase = 'snapshotted';+ await writeRecycleRecord(record);+ await fs.writeFile(path.join(meta.path, 'draft.txt'), 'edited after the first snapshot\n');+ expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);+ const removed = (await readRecycleRecord(meta.path))!;+ expect(removed.snapshot!.ref).not.toBe(record.snapshot.ref);+ expect(await git(repo, 'for-each-ref', record.snapshot.ref)).toBe('');++ const owner = (status: string) => async () => [+ { id: meta.sessionId, status, source: 'desktop', currentDatabase: true, workingDir: meta.path, worktreePath: meta.path },+ ];+ // An archived task can still be unarchived; only a deleted one gives up its snapshot.+ await releaseObsoleteRecoverySnapshots(owner('archived'));+ expect(await git(repo, 'for-each-ref', removed.snapshot!.ref)).not.toBe('');+ await releaseObsoleteRecoverySnapshots(owner('deleted'));+ expect(await git(repo, 'for-each-ref', removed.snapshot!.ref)).toBe('');+ }, 30_000);+it('keeps an advanced branch and its missing worktree untouched', async () => {const meta = await createFixture('advanced');expect(await recycleManagedWorktree(meta, { canRemove: async () => true })).toBe(true);diff --git a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.tsindex d4c2eb2ec6..b32da8db19 100644--- a/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRecycleMaintenance.test.ts@@ -22,6 +22,7 @@ vi.mock('../worktree/liveSessionRefs', () => ({ loadLiveSessionPathKeys: async (const write = vi.hoisted(() => vi.fn());vi.mock('../worktree/recycleJournal', () => ({listRecycleRecords: list,+ listRecycleRecordsWithHistory: vi.fn(async () => [...state.records]),readRecycleRecord: read,writeRecycleRecord: write,pruneUnreferencedRecoveryArchives: vi.fn(async () => 0),@@ -79,11 +80,11 @@ 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 } }];+ it.each(['recycle-failed', 'EPERM'])('retries a request an older client paused over its archive (%s) exactly once', async (reason) => {+ state.records = [{ ...record(), reason, 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 } }];+ state.records = [{ ...current, reason, retryPolicy: { state: 'paused', failures: 3, failedWorkMs: 0 } }];});await maintenance.start();expect(closeAndRecycle).toHaveBeenCalledExactlyOnceWith('owner', 'archived');diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.tsindex fcca90ed0c..b11066faec 100644--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';@@ -37,6 +37,9 @@ describe('worktree runtime evidence and physical locks', () => {const seedLegacyLease = () => seedLegacySharedRuntimeLease(path.join(state.root, 'app-data'), worktree, gitLock);const hasGitLock = () => fs.stat(gitLock).then(() => true, () => false);const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;+ // The lease heartbeat interval is module-wide and starts with the first lease any test holds.+ beforeAll(() => { vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); });+ afterAll(() => { vi.useRealTimers(); });beforeEach(async () => {state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-runtime-'));state.userData = '';@@ -438,14 +441,67 @@ describe('worktree runtime evidence and physical locks', () => {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 () => {+ it('waives a lease from before this boot only once its live PID is proven to be another process', async () => {vi.spyOn(os, 'uptime').mockReturnValue(60);const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ vi.spyOn(process, 'kill').mockReturnValue(true);+ const protectedPath = new Set([await physicalWorktreeKey(worktree)]);+ // A corrected clock can make a live owner's lease look older than this boot.await ownedBy(lease, 4242, hourMs);+ expect(await readWorktreeRuntimePaths()).toEqual(protectedPath);+ await ownedBy(lease, 4242, hourMs + 1_000);+ readIdentity.mockResolvedValueOnce({ startedAtMs: Date.now() - 2 * hourMs, executablePath: path.join(state.root, 'Cindy.exe') });+ expect(await readWorktreeRuntimePaths()).toEqual(protectedPath);++ await ownedBy(lease, 4242, hourMs + 2_000);+ readIdentity.mockResolvedValueOnce({ startedAtMs: Date.now(), executablePath: path.join(state.root, 'wechat-pad.exe') });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ // Leases are never adopted, so a later Node or Electron process with the PID is not the owner either.+ await ownedBy(lease, 4242, hourMs + 3_000);+ readIdentity.mockResolvedValueOnce({ startedAtMs: Date.now(), executablePath: path.join(state.root, 'node.exe') });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ });++ it('recognises its live owner by recorded identity even when the clock was corrected after it started', async () => {+ vi.spyOn(os, 'uptime').mockReturnValue(30 * 24 * 60 * 60);+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;vi.spyOn(process, 'kill').mockReturnValue(true);+ // The owner was born by a fast clock, so its OS birth is later than every heartbeat since.+ const owner = { startedAtMs: Date.now() + hourMs, executablePath: path.join(state.root, 'Cindy.exe') };+ await ownedBy(lease, 4242, 2 * hourMs, { processIdentity: owner });+ readIdentity.mockResolvedValueOnce(owner);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ readIdentity.mockResolvedValueOnce({ ...owner, startedAtMs: owner.startedAtMs + 60_000 });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ });++ it('counts the grace period from the last heartbeat, and much longer for leases without one', async () => {+ vi.spyOn(os, 'uptime').mockReturnValue(30 * 24 * 60 * 60);+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ exitedOwner();+ await ownedBy(lease, 4242, 2 * hourMs, { heartbeatMs: undefined });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ await ownedBy(lease, 4242, 25 * hourMs, { heartbeatMs: undefined });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());++ // A lease with this process's PID that it does not hold was left by an earlier process.+ const stray = path.join(path.dirname(lease.file), `${process.pid}-${'a'.repeat(64)}.json`);+ await fs.writeFile(stray, JSON.stringify({ version: 1, pid: process.pid, path: await physicalWorktreeKey(worktree), heartbeatMs: 300_000 }));+ await ownedBy({ file: stray }, process.pid, 2 * hourMs);expect(await readWorktreeRuntimePaths()).toEqual(new Set());});+ it('refreshes the leases this process holds so a long task is not mistaken for an abandoned one', async () => {+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ const old = new Date(Date.now() - 2 * hourMs);+ await fs.utimes(lease.file, old, old);+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ let mtimeMs = old.getTime();+ for (let check = 0; check < 50 && mtimeMs === old.getTime(); check++) mtimeMs = (await fs.stat(lease.file)).mtimeMs;+ expect(mtimeMs).toBeGreaterThan(Date.now() - 60_000);+ await releaseWorktreeRuntimeLease(lease);+ });+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))!;@@ -458,13 +514,15 @@ describe('worktree runtime evidence and physical locks', () => {expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));});- it('ignores an unsupported instance registered before this boot without querying its PID', async () => {+ it('falls back to the boot time for an unsupported instance only when its identity is unavailable', 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();+ // A runtime born before the registration is that instance, whatever the boot estimate says.+ readIdentity.mockResolvedValueOnce({ startedAtMs: Date.now() - 2 * hourMs, executablePath: path.join(state.root, 'Cindy.exe') });+ expect(await readWorktreeRuntimePaths()).toBeNull();});});diff --git a/apps/desktop/src/main/desktopProcessIdentity.ts b/apps/desktop/src/main/desktopProcessIdentity.tsindex b38c4e8021..2f5cf75e39 100644--- a/apps/desktop/src/main/desktopProcessIdentity.ts+++ b/apps/desktop/src/main/desktopProcessIdentity.ts@@ -97,6 +97,20 @@ export function isReusedDesktopInstancePid(const runtimeRoot = (resourcesIndex >= 0 ? root.slice(0, resourcesIndex) : root).replace(/\/$/, '');if (executable.startsWith(`${runtimeRoot}/`)) return false;}+ return isLaterProcessThan(record, current, platform);+}++/**+ * Whether `current` is provably not the process that wrote `record`: born clearly after the+ * recorded OS identity or, without one, after `startedAtMs`. No executable is exempt; callers+ * whose records can be adopted by a replacement runtime add those exemptions themselves.+ */+export function isLaterProcessThan(+ record: { startedAtMs?: unknown; processIdentity?: unknown },+ current: DesktopProcessIdentity,+ platform: NodeJS.Platform = process.platform,+): boolean {+ if (!validIdentity(current, platform)) return false;// ps reports whole seconds; also allow timestamp rounding in legacy records.const toleranceMs = 2_000;if (record.processIdentity !== undefined) {diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.tsindex 483c4b24f1..5c45e94271 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 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.",+ 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) and Git repositories cloned or initialised inside the worktree are **not kept**; reinstall, rebuild or clone them again after restoring. Restored files go through Git's usual line-ending and symlink handling, like a normal checkout. 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/contentSnapshot.ts b/apps/desktop/src/main/worktree/contentSnapshot.tsindex 727d127b7c..3853416501 100644--- a/apps/desktop/src/main/worktree/contentSnapshot.ts+++ b/apps/desktop/src/main/worktree/contentSnapshot.ts@@ -43,12 +43,65 @@ async function withTemporaryIndex<T>(run: (env: Record<string, string>) => Promi}}+/**+ * Untracked nested repositories (`git clone` or `git init` inside the worktree). Git lists+ * them as `dir/` and does not descend into them; a snapshot could keep only a gitlink, and+ * one without a commit makes `git add` fail. Like ignored files they are not preserved.+ */+async function untrackedNestedRepositories(worktreePath: string, extraEnv: Record<string, string>): Promise<string[]> {+ const { stdout } = await gitExec(['ls-files', '--others', '--exclude-standard', '-z'], worktreePath, { extraEnv });+ return stdout.split('\0').filter((entry) => entry.endsWith('/')).map((entry) => entry.slice(0, -1));+}++/**+ * `git add` skips files marked assume-unchanged or skip-worktree, so local edits kept that way+ * would be neither saved nor noticed. Clear the marks in the temporary index only; the live+ * index keeps them. A skip-worktree file absent from disk (sparse checkout) keeps its mark,+ * otherwise it would be recorded as deleted.+ */+async function unmarkHiddenEdits(worktreePath: string, extraEnv: Record<string, string>): Promise<void> {+ const { stdout } = await gitExec(['ls-files', '-v', '-z'], worktreePath, { extraEnv });+ const marked: string[] = [];+ for (const entry of stdout.split('\0')) {+ const tag = entry[0];+ if (!tag || entry[1] !== ' ' || (tag === tag.toUpperCase() && tag !== 'S')) continue;+ const file = entry.slice(2);+ if (tag.toUpperCase() === 'S') {+ try { await fs.lstat(path.join(worktreePath, file)); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw error;+ }+ }+ marked.push(file);+ }+ for (let start = 0; start < marked.length; start += 200) {+ await gitExec(+ ['update-index', '--no-assume-unchanged', '--no-skip-worktree', '--', ...marked.slice(start, start + 200)],+ worktreePath, { extraEnv },+ );+ }+}++/** Stage tracked edits and, with `--all`, new files into a temporary index, skipping nested repositories. */+async function addWorktreeContent(worktreePath: string, mode: '--all' | '--update', extraEnv: Record<string, string>): Promise<void> {+ await unmarkHiddenEdits(worktreePath, extraEnv);+ const nested = mode === '--all' ? await untrackedNestedRepositories(worktreePath, extraEnv) : [];+ if (nested.length === 0) {+ await gitExec(['add', mode, '--', '.'], worktreePath, { extraEnv });+ return;+ }+ // A pathspec file avoids command-line length limits; it lives beside the temporary index.+ const pathspec = path.join(path.dirname(extraEnv.GIT_INDEX_FILE), 'pathspec');+ await fs.writeFile(pathspec, ['.', ...nested.map((entry) => `:(exclude,literal)${entry}`)].join('\0') + '\0');+ await gitExec(['add', mode, `--pathspec-from-file=${pathspec}`, '--pathspec-file-nul'], worktreePath, { extraEnv });+}+/** 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 });+ await addWorktreeContent(worktreePath, '--all', extraEnv);const { stdout } = await gitExec(['write-tree'], worktreePath, { extraEnv });return stdout.trim();});@@ -72,6 +125,7 @@ export async function worktreeContentMatches(/*** 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.+ * Nested repositories were never part of a snapshot and are left alone.*/export async function presentFilesMatchSnapshotTree(worktreePath: string, tree: string): Promise<boolean> {return withTemporaryIndex(async (extraEnv) => {@@ -83,7 +137,7 @@ export async function presentFilesMatchSnapshotTree(worktreePath: string, tree:if (fields[index] !== 'D') return false;}const { stdout: extra } = await gitExec(['ls-files', '--others', '--exclude-standard', '-z'], worktreePath, { extraEnv });- return extra.length === 0;+ return extra.split('\0').every((entry) => entry === '' || entry.endsWith('/'));});}@@ -165,8 +219,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();- // Ignored files are regenerable (dependencies, build output) and are never saved.- await gitExec(['add', includeUntracked ? '--all' : '--update', '--', '.'], worktreePath, options);+ // Ignored files (dependencies, build output) and nested repositories are never saved.+ await addWorktreeContent(worktreePath, includeUntracked ? '--all' : '--update', options.extraEnv);const { stdout: contents } = await gitExec(['write-tree'], worktreePath, options);const tree = contents.trim();// Retain both trees through the snapshot ref, including staged-only bytes.@@ -198,3 +252,61 @@ export async function captureWorktreeContent(await fs.rm(temp, { recursive: true, force: true });}}++export const SNAPSHOT_REF_PREFIX = 'refs/cindy/worktree-recovery/';++/**+ * Drop a recovery snapshot ref once nothing can restore from it (restored, superseded, or its+ * task deleted). Only the ref is removed; the repository's own gc reclaims the objects later.+ * The expected commit keeps a concurrently rewritten ref intact. Failure leaves the ref, which+ * is harmless.+ */+export async function releaseSnapshotRef(+ baseRepo: string,+ snapshot: Pick<NonNullable<WorktreeRecycleRecord['snapshot']>, 'ref' | 'commit'>,+): Promise<boolean> {+ if (!snapshot.ref.startsWith(SNAPSHOT_REF_PREFIX)) return false;+ try {+ await gitExec(['update-ref', '-d', snapshot.ref, snapshot.commit], baseRepo);+ return true;+ } catch {+ return false;+ }+}++/** Existing snapshot refs and the commits they point to, read with a single Git process. */+export async function listSnapshotRefs(baseRepo: string): Promise<Map<string, string>> {+ const { stdout } = await gitExec(+ ['for-each-ref', '--format=%(refname)%00%(objectname)', SNAPSHOT_REF_PREFIX], baseRepo,+ );+ const refs = new Map<string, string>();+ for (const line of stdout.split('\n')) {+ const [ref, commit] = line.trim().split('\0');+ if (ref && commit) refs.set(ref, commit);+ }+ return refs;+}++/** Above this many entries a removal falls back to timestamps alone; it keeps the journal small. */+const MAX_DISCARDABLE_ENTRIES = 2_000;++/**+ * Paths a snapshot deliberately leaves out: ignored files (wholly ignored directories collapse+ * to `dir/`) and nested repositories. Recorded when removal begins, so a resumed removal can+ * tell such bytes from files that appeared afterwards. Null when the list would be too long.+ */+export async function discardableWorktreePaths(worktreePath: string): Promise<string[] | null> {+ const listed = async (args: string[]) => (await gitExec(['ls-files', ...args, '-z'], worktreePath, {+ extraEnv: { GIT_OPTIONAL_LOCKS: '0' },+ })).stdout.split('\0').filter(Boolean);+ const ignored = await listed(['--others', '--ignored', '--exclude-standard', '--directory']);+ const nested = (await listed(['--others', '--exclude-standard'])).filter((entry) => entry.endsWith('/'));+ const entries = [...new Set([...ignored, ...nested])];+ return entries.length > MAX_DISCARDABLE_ENTRIES ? null : entries;+}++/** Every path a snapshot tree holds, read from the base repository with one Git process. */+export async function snapshotTreePaths(baseRepo: string, tree: string): Promise<Set<string>> {+ const { stdout } = await gitExec(['ls-tree', '-r', '-z', '--name-only', tree], baseRepo);+ return new Set(stdout.split('\0').filter(Boolean));+}diff --git a/apps/desktop/src/main/worktree/managedRecycle.ts b/apps/desktop/src/main/worktree/managedRecycle.tsindex b207eb38e0..44d7e038c7 100644--- a/apps/desktop/src/main/worktree/managedRecycle.ts+++ b/apps/desktop/src/main/worktree/managedRecycle.ts@@ -3,11 +3,15 @@ import { randomUUID } from 'node:crypto';import fs from 'node:fs/promises';import path from 'node:path';-import { captureWorktreeContent, worktreeContentMatches } from './contentSnapshot';+import {+ captureWorktreeContent, discardableWorktreePaths, releaseSnapshotRef, snapshotTreePaths,+ worktreeContentMatches, worktreeStagedContentMatches,+} from './contentSnapshot';import { gitExec } from './gitExec';import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRefs';+import { inventoryWorktree, sameWorktreeFiles } from './recoveryArchive';import {- newRecycleRecord, readRecycleRecord, writeRecycleRecord, worktreeGeneration,+ newRecycleRecord, readRecycleRecord, writeRecycleRecord, worktreeGeneration, type WorktreeRecycleRecord,} from './recycleJournal';import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';import { isManagedWorktreePath } from './safety';@@ -77,6 +81,99 @@ async function hasGitLink(worktreePath: string): Promise<boolean> {}}+/** A `.git` file whose metadata directory was already deleted cannot answer Git queries. */+async function gitMetadataUsable(worktreePath: string): Promise<boolean> {+ const link = path.join(worktreePath, '.git');+ let stat;+ try { stat = await fs.lstat(link); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw error;+ }+ // Anything but a regular gitfile goes through the identity check, which rejects it.+ if (!stat.isFile()) return true;+ const match = /^gitdir:\s*(.+?)\s*$/m.exec(await fs.readFile(link, 'utf8'));+ if (!match) return true;+ try {+ await fs.stat(path.resolve(worktreePath, match[1]));+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw error;+ }+}++/**+ * Surviving files that removal may delete: none written after `sinceMs` and, when the lists are+ * known, each one either saved in the snapshot or under a path the snapshot left out on purpose.+ * The path check catches files moved or copied in with their old timestamps; content swapped+ * into a saved path with a preserved timestamp remains undetectable. Directories are not dated+ * (deleting children updates them), nor is status-change time (Git may clear a read-only flag+ * before failing to delete a file). Discardable directories are not walked.+ */+async function residualFilesAllowed(+ root: string,+ sinceMs: number,+ saved: ReadonlySet<string> | null,+ discardable: readonly string[] | null,+): Promise<boolean> {+ const discarded = (relative: string): boolean => discardable!.some((entry) => (+ entry.endsWith('/') ? `${relative}/` === entry || relative.startsWith(entry) : relative === entry+ ));+ const walk = async (directory: string, prefix: string): Promise<boolean> => {+ let entries;+ try { entries = await fs.readdir(directory, { withFileTypes: true }); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;+ throw error;+ }+ for (const entry of entries) {+ const relative = `${prefix}${entry.name}`;+ const entryPath = path.join(directory, entry.name);+ // The worktree's own Git link predates removal and is never part of a snapshot.+ if (relative === '.git') continue;+ if (entry.isDirectory()) {+ if (saved && discarded(relative)) continue;+ if (!(await walk(entryPath, `${relative}/`))) return false;+ continue;+ }+ let stat;+ try { stat = await fs.lstat(entryPath); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw error;+ }+ if (Math.max(stat.mtimeMs, stat.birthtimeMs) > sinceMs) return false;+ if (saved && !saved.has(relative) && !discarded(relative)) return false;+ }+ return true;+ };+ return walk(root, '');+}++/**+ * A partially removed directory may only lose bytes that existed when removal began. The full+ * tree was verified against the snapshot after `removingSince` was taken and before it was+ * recorded, so every file written before that moment was saved, ignored or nested. Older+ * clients' records compare their archive inventory instead.+ */+async function residualFilesCovered(+ meta: WorktreeMeta,+ record: WorktreeRecycleRecord,+ snapshot: NonNullable<WorktreeRecycleRecord['snapshot']>,+): Promise<boolean> {+ if (record.archive) {+ if (!sameWorktreeFiles(await inventoryWorktree(meta.path), record.archive.files, true)) return false;+ } else {+ const since = record.removingSince;+ if (typeof since !== 'number' || !Number.isFinite(since)) return false;+ const discardable = Array.isArray(record.removalDiscardable) ? record.removalDiscardable : null;+ const saved = discardable ? await snapshotTreePaths(meta.baseRepo, snapshot.tree) : null;+ if (!(await residualFilesAllowed(meta.path, since, saved, discardable))) return false;+ }+ // While Git metadata survives, HEAD, the branch and staged content must be unchanged too.+ if (!(await gitMetadataUsable(meta.path))) return true;+ await assertWorktreeGitIdentity(meta);+ return worktreeStagedContentMatches(meta.path, snapshot);+}+/** 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);@@ -107,7 +204,8 @@ async function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: Managedif (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)) {+ // A restored record's snapshot ref is already released; never complete a removal on it.+ if (!record || record.generation !== worktreeGeneration(meta) || record.phase === 'restored') {record = await newRecycleRecord(meta);record.directoryIdentity = (await directoryIdentity(meta.path)) ?? undefined;await writeRecycleRecord(record);@@ -164,14 +262,17 @@ async function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: Managed}record.directoryIdentity = identity;await assertManagedResourcePath(meta, store.getAllPaths());- // 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));+ // Once deletion may have started, the directory can be partial (Windows stops at the first+ // locked file, with or without .git). Never snapshot it again: that would replace the+ // snapshot verified before deletion with a tree missing the files already deleted.+ const resumingRemoval = record.phase === 'removing' && Boolean(record.snapshot);if (!resumingRemoval) {// A missing .git must never fall through to the parent repository.await assertWorktreeGitIdentity(meta);- // Git keeps tracked and new files; ignored files (dependencies, build output) are not saved.+ // Git keeps tracked and new files; ignored files and nested repositories are not saved.+ let superseded: WorktreeRecycleRecord['snapshot'];if (!record.snapshot || !(await worktreeContentMatches(meta.path, record.snapshot))) {+ superseded = record.snapshot;record.snapshot = await captureWorktreeContent(meta.path, `refs/cindy/worktree-recovery/${record.id}/${randomUUID()}`, { includeUntracked: true },);@@ -179,36 +280,48 @@ async function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: Managed}record.phase = 'snapshotted';await writeRecycleRecord(record);+ // The new snapshot holds everything still present; the older one can no longer be restored.+ if (superseded && superseded.ref !== record.snapshot.ref) await releaseSnapshotRef(meta.baseRepo, superseded);}const snapshot = record.snapshot;if (!snapshot) return defer('recovery-evidence-missing');+ // Before deletion: the whole tree must still match the snapshot. After it may have started:+ // every surviving file must already have been covered when removal began.const contentUnchanged = async (): Promise<boolean> => {- if (!(await hasGitLink(meta.path))) return resumingRemoval;+ if (record.phase === 'removing') return residualFilesCovered(meta, record, snapshot);+ if (!(await hasGitLink(meta.path))) return false;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());- if (!(await contentUnchanged())) return defer('git-baseline-changed');- record.phase = 'removing';- await writeRecycleRecord(record);- // 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());- if (!(await contentUnchanged())) return defer('git-baseline-changed-before-removal');+ if (!(await contentUnchanged())) return defer(resumingRemoval ? 'residual-files-changed' : 'git-baseline-changed');+ if (!resumingRemoval) {+ // Revalidate the full tree immediately before the destructive Git operation; a late+ // editor/IDE write or a newly live reference keeps this generation protected. The+ // boundary is taken first and recorded only once the verification has completed, so+ // an interrupted verification leaves the request `snapshotted` and nothing unverified+ // can ever count as covered.+ const since = Date.now();+ if (!(await canRemove())) return defer('referenced-before-removal');+ if (await directoryIdentity(meta.path) !== identity) return defer('directory-replaced');+ await assertManagedResourcePath(meta, store.getAllPaths());+ await assertWorktreeGitIdentity(meta);+ if (!(await worktreeContentMatches(meta.path, snapshot))) return defer('git-baseline-changed-before-removal');+ record.removalDiscardable = (await discardableWorktreePaths(meta.path)) ?? undefined;+ record.removingSince = since;+ record.phase = 'removing';+ await writeRecycleRecord(record);+ }try {await gitExec(['-c', 'core.longpaths=true', 'worktree', 'remove', '--force', meta.path], meta.baseRepo);} catch {if (await directoryIdentity(meta.path) !== identity) return defer('remove-unconfirmed');if (!(await canRemove())) return defer('referenced-before-fallback');await assertManagedResourcePath(meta, store.getAllPaths());- if (await hasGitLink(meta.path)) {- await assertWorktreeGitIdentity(meta);- if (!(await worktreeContentMatches(meta.path, snapshot))) return defer('git-baseline-changed');- }+ // Only bytes that existed when removal began (saved, ignored or nested) may be deleted.+ if (!(await residualFilesCovered(meta, record, snapshot))) return defer('residual-files-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/recoveryArchiveIO.ts b/apps/desktop/src/main/worktree/recoveryArchiveIO.tsindex 8e0759fae2..269bee6be3 100644--- a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts+++ b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts@@ -11,7 +11,11 @@ export interface FileEvidence {mode: number;}-/** Compressed, encrypted local recovery bytes; secrets never enter Git objects. */+/**+ * Compressed, encrypted local bytes that never enter Git objects. Worktree recycling no longer+ * creates these (its Git snapshot stores new non-ignored files in the base repository's local+ * object store); records written by older clients still restore from them.+ */export interface WorktreeRecoveryArchive {file: string;encryptedKey: string;diff --git a/apps/desktop/src/main/worktree/recycleJournal.ts b/apps/desktop/src/main/worktree/recycleJournal.tsindex e927ed7ed3..11a59a5623 100644--- a/apps/desktop/src/main/worktree/recycleJournal.ts+++ b/apps/desktop/src/main/worktree/recycleJournal.ts@@ -36,6 +36,10 @@ export interface WorktreeRecycleRecord {archive?: WorktreeRecoveryArchive;/** The one fresh retry budget for a request an older client paused over its archive. */legacyArchiveRetry?: true;+ /** When deletion was first allowed to start; files written since stop a resumed removal. */+ removingSince?: number;+ /** Ignored and nested paths a snapshot left out, captured when removal began. */+ removalDiscardable?: string[];}export function recycleJournalRoot(): string {@@ -177,25 +181,10 @@ export async function pruneUnreferencedRecoveryArchives(now = Date.now()): Promi}const archives = names.filter((name) => archiveNamePattern.test(name));if (archives.length === 0) return 0;+ const records = await listRecycleRecordsWithHistory();+ if (!records) 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);- }+ for (const record of records) if (record.archive?.file) referenced.add(record.archive.file);let removed = 0;for (const name of archives) {if (referenced.has(name)) continue;@@ -211,6 +200,32 @@ export async function pruneUnreferencedRecoveryArchives(now = Date.now()): Promireturn removed;}+/**+ * Current and history records, or null when any of them cannot be read: an unreadable record+ * might still need the evidence a sweep would otherwise discard.+ */+export async function listRecycleRecordsWithHistory(): Promise<WorktreeRecycleRecord[] | null> {+ const root = recycleJournalRoot();+ const files: Array<{ file: string; id: string }> = [];+ for (const [directory, pattern] of [[root, /^[a-f0-9]{64}\.json$/], [path.join(root, 'history'), /^[a-f0-9]{64}-[a-f0-9]{64}\.json$/]] as const) {+ let names: string[];+ try { names = await fs.readdir(directory); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw error;+ }+ for (const name of names) if (pattern.test(name)) files.push({ file: path.join(directory, name), id: name.slice(0, 64) });+ }+ const records: WorktreeRecycleRecord[] = [];+ for (const { file, id } of files) {+ try { records.push(parseRecord(await fs.readFile(file, 'utf8'), id)); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ log.warn('worktree recycle sweep skipped: unreadable record', { resourceId: id });+ return null;+ }+ }+ return records;+}+/** 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 9fbdb6eadb..c1bc27dd23 100644--- a/apps/desktop/src/main/worktree/recycleMaintenance.ts+++ b/apps/desktop/src/main/worktree/recycleMaintenance.ts@@ -6,9 +6,11 @@ import { app } from 'electron';import { getDbClient } from '../localDb/client/current';import { createLogger } from '../logger';import {- listRecycleRecords, pruneUnreferencedRecoveryArchives, readRecycleRecord, watchRecycleJournal, worktreeGeneration, writeRecycleRecord,- type WorktreeRecycleRecord,+ listRecycleRecords, listRecycleRecordsWithHistory, pruneUnreferencedRecoveryArchives, readRecycleRecord,+ watchRecycleJournal, worktreeGeneration, writeRecycleRecord, type WorktreeRecycleRecord,} from './recycleJournal';+import { listSnapshotRefs, releaseSnapshotRef, SNAPSHOT_REF_PREFIX } from './contentSnapshot';+import type { LocalWorktreeReference } from '../localDb/worker/worktreeReferences';import { recycleManagedWorktree } from './managedRecycle';import { hasLiveSessionReference, loadLiveSessionPathKeys, pathKey } from './liveSessionRefs';import * as store from './worktreeStore';@@ -28,11 +30,20 @@ export interface WorktreeMaintenanceOptions {onAttemptComplete?(): Promise<void>;}-const legacyArchiveFailureReasons = new Set(['recycle-failed', 'ENOSPC']);+/** Paused for the directory's identity or location, not for the old archive flow: never retried. */+const unsafeResourceReasons = new Set([+ 'legacy-quarantine-needs-review', 'directory-replaced', 'unmanaged-path', 'redirected-worktree-parent',+]);+/**+ * Older clients paused requests after archive failures (timeouts, a disk filled by archives,+ * Windows EPERM/EBUSY/ENAMETOOLONG while packing). None of that work exists any more, so each+ * such request gets one fresh failure budget; a fault that persists pauses it again.+ */function grantsLegacyArchiveRetry(record: WorktreeRecycleRecord): boolean {- return !record.legacyArchiveRetry && !record.snapshot?.untracked && record.phase === 'pending'- && recyclePolicy(record).state === 'paused' && legacyArchiveFailureReasons.has(record.reason ?? '');+ return !record.legacyArchiveRetry && !record.snapshot?.untracked+ && ['pending', 'snapshotted', 'removing'].includes(record.phase)+ && recyclePolicy(record).state === 'paused' && record.reason !== undefined && !unsafeResourceReasons.has(record.reason);}/** Event-driven, single-flight maintenance with one timer for the earliest pending deadline. */@@ -183,6 +194,18 @@ export class WorktreeRecycleMaintenance {return granted;}+ private async releaseObsoleteSnapshots(): Promise<void> {+ try {+ const db = getDbClient();+ const readRows = db.readLocalWorktreeReferences?.bind(db);+ if (!readRows) return;+ const released = await releaseObsoleteRecoverySnapshots(readRows);+ if (released > 0) log.info('released obsolete worktree recovery snapshots', { count: released });+ } catch (error) {+ log.warn('worktree recovery snapshot release postponed', { code: (error as NodeJS.ErrnoException).code ?? 'unavailable' });+ }+ }+private async runPass(): Promise<void> {if (!this.options.isReady()) return;await this.ensureWatcher();@@ -193,6 +216,7 @@ export class WorktreeRecycleMaintenance {if (pendingLeaseReleases > 0) this.schedule(Date.now() + retryDelay(1));let records = await listRecycleRecords();if (this.initialPass && await this.retireRecoveryArchives(records)) records = await listRecycleRecords();+ if (this.initialPass) await this.releaseObsoleteSnapshots();const wakeIds = new Set(this.wakeIds);this.wakeIds.clear();// A resource may have been released while Cindy was closed: recheck waits@@ -276,6 +300,53 @@ export class WorktreeRecycleMaintenance {}}+/**+ * Delete snapshot refs nothing can restore from: the worktree was restored, or it was removed+ * and every known database marks its task deleted. Startup-only, like the savepoint sweep, so+ * the regular recycle path never reads task databases; a status change itself never deletes+ * recovery evidence. Archived tasks keep their snapshots because they can be unarchived; a+ * task missing from the databases is unknown, not deleted. Task databases are read only when a+ * removed record needs its owner checked. Costs one Git process per repository with+ * candidates, plus one per ref actually deleted.+ */+export async function releaseObsoleteRecoverySnapshots(+ readRows: () => Promise<readonly LocalWorktreeReference[]>,+): Promise<number> {+ const records = await listRecycleRecordsWithHistory();+ if (!records) return 0;+ // History keeps an older copy of the same record, so decide per ref across all copies.+ const copies = new Map<string, WorktreeRecycleRecord[]>();+ for (const record of records) {+ if (!record.snapshot?.ref.startsWith(SNAPSHOT_REF_PREFIX)) continue;+ copies.set(record.snapshot.ref, [...(copies.get(record.snapshot.ref) ?? []), record]);+ }+ const restored = (versions: readonly WorktreeRecycleRecord[]) => versions.some((record) => record.phase === 'restored');+ const removed = (versions: readonly WorktreeRecycleRecord[]) => versions.every((record) => record.phase === 'removed');+ const values = [...copies.values()];+ const rows = values.some((versions) => !restored(versions) && removed(versions)) ? await readRows() : [];+ const ownerDeleted = (sessionId: string): boolean => {+ const owned = rows.filter((row) => row.id === sessionId);+ return owned.length > 0 && owned.every((row) => row.source !== 'bot' && row.status === 'deleted');+ };+ const byRepo = new Map<string, Array<{ ref: string; commit: string }>>();+ for (const [ref, versions] of copies) {+ const obsolete = restored(versions)+ || (removed(versions) && versions.every((record) => ownerDeleted(record.meta.sessionId)));+ if (!obsolete) continue;+ const { baseRepo } = versions[0].meta;+ byRepo.set(baseRepo, [...(byRepo.get(baseRepo) ?? []), { ref, commit: versions[0].snapshot!.commit }]);+ }+ let released = 0;+ for (const [baseRepo, candidates] of byRepo) {+ let existing: Map<string, string>;+ try { existing = await listSnapshotRefs(baseRepo); } catch { continue; }+ for (const candidate of candidates) {+ if (existing.get(candidate.ref) === candidate.commit && await releaseSnapshotRef(baseRepo, candidate)) released++;+ }+ }+ return released;+}+/** Starts once both task storage and runtime-close services are usable. */export function startWorktreeRecycleMaintenance(options: WorktreeMaintenanceOptions): void {maintenance ??= new WorktreeRecycleMaintenance(options);diff --git a/apps/desktop/src/main/worktree/restoreRecovery.ts b/apps/desktop/src/main/worktree/restoreRecovery.tsindex 04e43ea087..910baaac73 100644--- a/apps/desktop/src/main/worktree/restoreRecovery.ts+++ b/apps/desktop/src/main/worktree/restoreRecovery.ts@@ -12,7 +12,9 @@ import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRimport { assertManagedResourceLocation, assertManagedResourcePath, assertWorktreeGitIdentity } from './resourceSafety';import * as store from './worktreeStore';import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';-import { checkoutMissingSnapshotFiles, presentFilesMatchSnapshotTree, readWorktreeHeadRef } from './contentSnapshot';+import {+ checkoutMissingSnapshotFiles, presentFilesMatchSnapshotTree, readWorktreeHeadRef, releaseSnapshotRef,+} from './contentSnapshot';function restoreCheckoutPathIsSafe(value: string): boolean {if (!path.isAbsolute(value)) return false;@@ -44,6 +46,11 @@ export function hasRecordedRecovery(record: RecycleRecord | null | undefined): rreturn Boolean(record?.snapshot && (record.archive || record.snapshot.untracked));}+/** The worktree holds the snapshot's content again; nothing can restore from it a second time. */+async function releaseRestoredSnapshot(record: RecycleRecord): Promise<void> {+ if (record.snapshot) await releaseSnapshotRef(record.meta.baseRepo, record.snapshot);+}+function restorableRecord(record: RecycleRecord | null): record is RecycleRecord {return hasRecordedRecovery(record) && record.phase !== 'restored' && record.phase !== 'pending';}@@ -80,6 +87,7 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s// Registration was the final mutation; finish a journal write interrupted by a crash.record.phase = 'restored';await writeRecycleRecord(record);+ await releaseRestoredSnapshot(record);return true;}if (registered && worktreeGeneration(registered) !== record.generation) return false;@@ -110,6 +118,7 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s// Snapshotting never mutates the live checkout. Cancelling recycling needs no apply.record.phase = 'restored';await writeRecycleRecord(record);+ await releaseRestoredSnapshot(record);return true;}await assertManagedResourcePath(record.meta, [worktreePath]);@@ -226,6 +235,7 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: sgeneration: record.restoredGeneration, quarantinePath: undefined });record.phase = 'restored';await writeRecycleRecord(record);+ await releaseRestoredSnapshot(record);return true;}));}diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.tsindex 989f8cb663..5ba01ec740 100644--- a/apps/desktop/src/main/worktree/runtimeLeases.ts+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts@@ -8,7 +8,9 @@ import { app } from 'electron';import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';import { isManagedWorktreeDirectoryName } from '../../shared/managedWorktreePaths';import { notifyWorktreeRecycleOpportunity } from './recycleEvents';-import { isReusedDesktopInstancePid, readDesktopProcessIdentity } from '../desktopProcessIdentity';+import {+ isLaterProcessThan, isReusedDesktopInstancePid, readDesktopProcessIdentity, type DesktopProcessIdentity,+} from '../desktopProcessIdentity';import { isGitProcessTreeAlive } from './gitExec';function runtimeRoot(): string {@@ -65,13 +67,58 @@ export async function acquireWorktreeRuntimeLease(});}+/** How often Main refreshes the modification time of the leases it holds, as a liveness heartbeat. */+const LEASE_HEARTBEAT_MS = 5 * 60_000;+/** Lease files this process published and has not released. */+const heldLeaseFiles = new Set<string>();+let leaseHeartbeat: ReturnType<typeof setInterval> | null = null;++function holdLeaseFile(file: string): void {+ heldLeaseFiles.add(file);+ if (leaseHeartbeat) return;+ leaseHeartbeat = setInterval(() => {+ const now = new Date();+ for (const held of heldLeaseFiles) void fs.utimes(held, now, now).catch(() => undefined);+ }, LEASE_HEARTBEAT_MS);+ leaseHeartbeat.unref?.();+}++function dropLeaseFile(file: string): void {+ heldLeaseFiles.delete(file);+ if (heldLeaseFiles.size || !leaseHeartbeat) return;+ clearInterval(leaseHeartbeat);+ leaseHeartbeat = null;+}++/** Bounds how long the first acquisition waits for this process's own OS identity. */+const OWN_IDENTITY_WAIT_MS = 2_000;+let ownIdentity: Promise<DesktopProcessIdentity | null> | null = null;++/**+ * This Main's OS birth time and executable, probed once. Readers compare it with the process+ * now holding the PID. Unavailable within the bound, the lease omits it and readers fall back+ * to its modification time.+ */+async function ownProcessIdentity(): Promise<DesktopProcessIdentity | null> {+ ownIdentity ??= readDesktopProcessIdentity(process.pid).catch(() => null);+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), OWN_IDENTITY_WAIT_MS); });+ try {+ return await Promise.race([ownIdentity, timeout]);+ } finally {+ clearTimeout(timer);+ }+}+async function publishRuntimeLease(sessionId: string, physicalPath: string, directory: string): Promise<WorktreeRuntimeLease> {await fs.mkdir(directory, { recursive: true });const lease = { file: leaseFile(sessionId, directory), physicalPath };+ const processIdentity = (await ownProcessIdentity()) ?? undefined;// A partial write is intentionally unreadable, hence protective to deletion.try {+ // heartbeatMs tells readers that the modification time tracks when this Main was last alive.await fs.writeFile(lease.file, JSON.stringify({- version: 1, pid: process.pid, path: physicalPath,+ version: 1, pid: process.pid, path: physicalPath, heartbeatMs: LEASE_HEARTBEAT_MS, processIdentity,}), { flag: 'wx', mode: 0o600 });} catch (error) {// Only this acquisition's partial write may be removed.@@ -80,6 +127,7 @@ async function publishRuntimeLease(sessionId: string, physicalPath: string, dire}throw error;}+ holdLeaseFile(lease.file);return lease;}@@ -127,6 +175,8 @@ async function releaseRuntimeKeepSentinel(lease: WorktreeRuntimeLease): Promise<}export async function releaseWorktreeRuntimeLease(lease: WorktreeRuntimeLease): Promise<void> {+ // Terminal I/O teardown has happened; a release that fails keeps its durable intent instead.+ dropLeaseFile(lease.file);await releaseRuntimeLeaseFile(lease);}@@ -241,31 +291,73 @@ function pidMayBeAlive(pid: number): boolean {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.+ * Counted from the lease's last heartbeat, i.e. from when its Main was last known alive.*/const ABANDONED_LEASE_GRACE_MS = 60 * 60_000;+/** Older clients wrote no heartbeat: their modification time is only the acquisition time. */+const LEGACY_ABANDONED_LEASE_GRACE_MS = 24 * 60 * 60_000;function startedBeforeBoot(timestampMs: unknown): boolean {return typeof timestampMs === 'number' && Number.isFinite(timestampMs)&& timestampMs < Date.now() - os.uptime() * 1000 - BOOT_MARGIN_MS;}+const isPid = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value > 0;++/**+ * Evidence (PID and stamp) whose writer is proven gone. Only that answer is cached: once the+ * writer has exited it stays gone, while "may still be the writer" must be asked again.+ */+const goneWriterCache = new Set<string>();++/**+ * Whether `pid` may be the process that last touched evidence stamped at `stampedAtMs`.+ * A live process born clearly after the writer cannot be it (PID reuse). A lease is written+ * by its own process and never adopted, so no executable name is exempt, unlike instance+ * registrations. The writer's recorded OS identity is compared when present: both times come+ * from the OS, so a clock corrected after the writer started cannot misjudge it. Older leases+ * compare against the stamp. An unknown identity stays protective.+ */+async function mayBeEvidenceWriter(pid: number, stampedAtMs: number, writerIdentity?: unknown): Promise<boolean> {+ if (!pidMayBeAlive(pid)) return false;+ const recorded = writerIdentity === undefined+ ? { startedAtMs: stampedAtMs }+ : { processIdentity: writerIdentity };+ const key = `${pid}:${JSON.stringify(recorded)}`;+ if (goneWriterCache.has(key)) return false;+ const identity = await readDesktopProcessIdentity(pid);+ if (!pidMayBeAlive(pid)) return false;+ if (!identity || !isLaterProcessThan(recorded, identity)) return true;+ if (goneWriterCache.size > 512) goneWriterCache.clear();+ goneWriterCache.add(key);+ return false;+}+/**- * 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.+ * A lease its Main never released, once no process that could still write is left: the owner+ * and recorded children have exited (or their PIDs were reused), and the lease predates this+ * boot or has gone without a heartbeat for the grace period. Live compatible Cindy instances+ * and leases this process holds always stay protective.*/async function isAbandonedLease(file: string,- lease: { pid?: unknown; childPid?: unknown; childPids?: unknown },+ lease: { pid?: unknown; processIdentity?: unknown; childPid?: unknown; childPids?: unknown; heartbeatMs?: unknown },+ liveInstancePids: ReadonlySet<number>,): 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;+ if (!isPid(lease.pid) || (lease.pid === process.pid && heldLeaseFiles.has(file))) return false;+ // This process holds every lease it wrote; one with its PID was left by an earlier process.+ if (lease.pid !== process.pid && liveInstancePids.has(lease.pid)) return false;const { mtimeMs } = await fs.stat(file);- if (startedBeforeBoot(mtimeMs)) return true;+ if (lease.pid !== process.pid && await mayBeEvidenceWriter(lease.pid, mtimeMs, lease.processIdentity)) return false;// 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;+ for (const child of children) {+ if (child == null) continue;+ if (!isPid(child) || await mayBeEvidenceWriter(child, mtimeMs)) return false;+ }+ if (startedBeforeBoot(mtimeMs)) return true;+ const grace = typeof lease.heartbeatMs === 'number' ? ABANDONED_LEASE_GRACE_MS : LEGACY_ABANDONED_LEASE_GRACE_MS;+ return Date.now() - mtimeMs > grace;}/** Unknown/older live instances keep terminal task references protected. */@@ -292,18 +384,15 @@ 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;- }+ // Always re-query: a replacement Cindy may hold this PID before it registers.const identity = await readDesktopProcessIdentity(pid);// A replacement instance may have registered while the OS query ran.if (await readRecord(name) !== raw) return null;if (!pidMayBeAlive(pid)) continue;- if (identity && isReusedDesktopInstancePid(record, identity)) {+ // A later OS birth proves the PID was reused. When the identity query fails (it can+ // time out), a registration from before this boot is still enough: that instance+ // cannot be running now. The SingletonLock check below revalidates before waiving it.+ if (identity ? isReusedDesktopInstancePid(record, identity) : startedBeforeBoot(record.startedAtMs)) {reusedInstanceRecords.set(pid, raw);continue;}@@ -358,7 +447,7 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {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;+ if (await isAbandonedLease(file, lease, compatiblePids)) 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 f14aa2fdc4..722562d8f8 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -206,8 +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 租约(`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` |+| 旧跨 profile 的 worktree 借用租约 | `app.getPath('appData')/Cindy/shared-worktree-runtime-leases`,内置模拟器下线后不再创建共享租约;回收器仍读取旧证据并重试已有 `.release` 回执。普通 Agent 的当前 profile 租约(`userData/worktree-runtime-leases`)照常创建与释放;持有它的主进程每 5 分钟刷新一次修改时间作为心跳(租约带 `heartbeatMs`)。租约只在显式释放后,或下列条件同时满足时不再保护:持有进程与记录的子进程都已不在(进程已退出,或该进程号已被启动更晚的进程复用:租约带持有进程自己的系统身份 `processIdentity` 时比对系统记录的启动时间,不受事后校时影响,旧租约与子进程比对租约最后修改时间;租约只由写入进程自己持有、不会被接管,因此不按进程名豁免;身份查询失败按仍在处理);并且租约写于本次开机之前(留 10 分钟时钟余量),或最后一次心跳距今超过 1 小时(无心跳的旧客户端租约为 24 小时)。当前进程持有的租约、兼容的存活实例的租约始终保护。`.dev-instances` 里不支持租约协议的旧实例登记,在进程身份证明进程号被复用时不再一票否决;身份查询失败时,开机前登记的也按复用处理,POSIX 的 SingletonLock 仍要先核对进程身份。见 `worktree/runtimeLeases.ts` |+| worktree 回收记录与恢复内容 | `userData/worktree-recycle/<资源 id>.json` 与 `history/`,记录删除意图、Git 快照引用与重试状态。归档/删除时只把已跟踪改动和未被 `.gitignore` 排除的新文件存进 Git 快照(`refs/cindy/worktree-recovery/...`;被 `assume-unchanged`/`skip-worktree` 隐藏的已跟踪改动也会存入,只在临时索引里清除标记,稀疏检出中不在盘上的文件除外),被忽略的依赖、构建产物、缓存,以及 worktree 内未跟踪的嵌套 Git 仓库(`git clone`/`git init` 产生)不保存,恢复后需重装、重建或重新克隆。快照对象写进基础仓库的本地对象库:普通 push 不会带上,`push --mirror` 或整体复制 `.git` 会;恢复内容经 Git 的换行与符号链接转换(与 `git checkout` 一致),不保证逐字节相同。快照引用在恢复成功、被新快照取代时立即删除;任务删除后只在启动对账时删除(常规回收路径不读任务库),归档任务的快照保留;对象由仓库自身 gc 回收。删除前对整棵树做最后一次核对,核对通过后才写入 `phase=removing` 与删除起点;此后不再重拍快照。续删只删除同时满足两点的文件:修改与创建时间都不晚于删除起点;路径在快照里,或在开始删除时记下的可丢弃路径(被忽略的文件、嵌套仓库)之下。可丢弃路径超过 2000 条时只按时间判断。保留原时间戳替换进已保存路径的内容无法识别。其余情况暂停删除。新客户端不再生成加密归档 `*.tar.gz.enc`;旧客户端记录里的归档照旧用于恢复,新客户端为仍完整的目录重拍快照后也会放弃旧归档;没有任何记录引用、超过 2 小时的归档在启动时删除,有记录读不出时整次跳过。旧客户端因失败暂停的请求(目录被替换、路径不受管等安全原因除外)升级后自动重试一次。见 `worktree/managedRecycle.ts`、`restoreRecovery.ts`、`recycleJournal.ts` 与 `recycleMaintenance.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 9076e57ec6..a059a03456 100644--- a/docs/dev-rules/development-workflow.md+++ b/docs/dev-rules/development-workflow.md@@ -28,7 +28,7 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径`apps/desktop/logs/`,读日志时拼 baseRepo 的绝对路径。- **会话结束与工作区保留**:是否 commit 由用户或宿主工作流决定,不能仅因会话结束强制提交。会话被删除或归档时脏 worktree 会先把改动和新文件存进 Git 快照再删目录;- 被 `.gitignore` 忽略的文件(依赖、构建产物)不保留。**PR+ 被 `.gitignore` 忽略的文件(依赖、构建产物)和 worktree 内克隆/初始化的嵌套仓库不保留。**PRmerged/closed 不等于 Cindy 会话已结束**:只要 owning session 仍 active,任何外部 Gitcleanup 都必须跳过该 `.cindy-worktrees` / `.xdt-worktrees` 目录与本地 `cindy/*` / `xdt/*` 分支,交给用户显式归档/删除会话时回收;禁止手动 `git worktree remove` 造成 active session 的 cwd