Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 快照核对与恢复修复补强

david92cee515a0e4
diff --git a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts
index 18c3aff45a..6a71e4f32b 100644
--- a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts
@@ -46,7 +46,7 @@ import { checkpointWorktreeForReuse, recycleManagedWorktree } from '../worktree/
import { restoreRecordedWorktree } from '../worktree/restoreRecovery';
import { newRecycleRecord, readRecycleRecord, writeRecycleRecord } from '../worktree/recycleJournal';
import { releaseObsoleteRecoverySnapshots } from '../worktree/recycleMaintenance';
-import { captureWorktreeContent } from '../worktree/contentSnapshot';
+import { captureWorktreeContent, worktreeContentMatches } from '../worktree/contentSnapshot';
import { GitExecError, gitExec } from '../worktree/gitExec';
import { acquireWorktree, releaseWorktree, parkAll } from '../worktree/WorktreePool';
import { createRecoveryArchive } from '../worktree/recoveryArchive';
@@ -409,6 +409,61 @@ describe('worktree recovery with real Git', () => {
expect((await readRecycleRecord(meta.path))?.phase).toBe('removed');
}, 30_000);
+ it('repairs a partial removal whose .git file points at deleted worktree metadata', async () => {
+ const meta = await createFixture('dangling-link');
+ const record = await newRecycleRecord(meta);
+ record.snapshot = await captureWorktreeContent(meta.path, `refs/cindy/worktree-recovery/${record.id}/dangling`, { includeUntracked: true });
+ const directory = await fs.lstat(meta.path);
+ record.directoryIdentity = `${directory.dev}:${directory.ino}:${directory.birthtimeMs}`;
+ record.phase = 'removing';
+ record.removingSince = Date.now();
+ await writeRecycleRecord(record);
+ // Git deleted the metadata and one file, then stopped before the directory's own .git file.
+ await fs.rm(await git(meta.path, 'rev-parse', '--absolute-git-dir'), { recursive: true, force: true });
+ await fs.rm(path.join(meta.path, 'draft.txt'));
+ state.registry.delete(meta.sessionId);
+
+ expect(await restoreRecordedWorktree(meta.sessionId, meta.path)).toBe(true);
+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('dangling-link contents\n');
+ expect(await git(meta.path, 'rev-parse', 'HEAD')).toBe(record.snapshot.head);
+ }, 30_000);
+
+ it('drops its own snapshot ref when HEAD or the index moves during capture', async () => {
+ const meta = await createFixture('moving-index');
+ const mocked = vi.mocked(gitExec);
+ const real = mocked.getMockImplementation()!;
+ mocked.mockImplementation(async (args, cwd, options) => {
+ const result = await real(args, cwd, options);
+ if (args[0] === 'update-ref' && args[1]?.startsWith('refs/cindy/')) await git(meta.path, 'add', 'draft.txt');
+ return result;
+ });
+ try {
+ await expect(captureWorktreeContent(meta.path, 'refs/cindy/worktree-recovery/moving/index', { includeUntracked: true }))
+ .rejects.toThrow('changed during snapshot');
+ } finally {
+ mocked.mockImplementation(real);
+ }
+ expect(await git(repo, 'for-each-ref', 'refs/cindy/worktree-recovery/moving/')).toBe('');
+ }, 30_000);
+
+ it('notices staging that happens while the full tree is compared', async () => {
+ const meta = await createFixture('staged-meanwhile');
+ const snapshot = await captureWorktreeContent(meta.path, 'refs/cindy/worktree-recovery/meanwhile/tree', { includeUntracked: true });
+ expect(await worktreeContentMatches(meta.path, snapshot)).toBe(true);
+ const mocked = vi.mocked(gitExec);
+ const real = mocked.getMockImplementation()!;
+ // Staging folds into the same full tree, so only a second staged check can see it.
+ mocked.mockImplementation(async (args, cwd, options) => {
+ if (args[0] === 'add' && args[1] === '--all') await git(meta.path, 'add', 'draft.txt');
+ return real(args, cwd, options);
+ });
+ try {
+ expect(await worktreeContentMatches(meta.path, snapshot)).toBe(false);
+ } finally {
+ mocked.mockImplementation(real);
+ }
+ }, 30_000);
+
it('keeps a partially removed directory when an older client\'s archive no longer verifies', async () => {
const meta = await createFixture('legacy-removing');
const record = await newRecycleRecord(meta);
diff --git a/apps/desktop/src/main/worktree/contentSnapshot.ts b/apps/desktop/src/main/worktree/contentSnapshot.ts
index 3853416501..4387f5dcbd 100644
--- a/apps/desktop/src/main/worktree/contentSnapshot.ts
+++ b/apps/desktop/src/main/worktree/contentSnapshot.ts
@@ -117,9 +117,12 @@ export async function worktreeContentMatches(
worktreePath: string,
snapshot: NonNullable<WorktreeRecycleRecord['snapshot']>,
): Promise<boolean> {
+ // `git add --all` folds staged and unstaged states into one tree, so HEAD and staged content
+ // are checked on both sides of it: a stage or reset meanwhile cannot pass unnoticed.
return snapshot.untracked === true
&& await worktreeStagedContentMatches(worktreePath, snapshot)
- && await fullContentTree(worktreePath) === snapshot.tree;
+ && await fullContentTree(worktreePath) === snapshot.tree
+ && await worktreeStagedContentMatches(worktreePath, snapshot);
}
/**
@@ -242,11 +245,17 @@ export async function captureWorktreeContent(
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();
+ try {
+ // 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();
+ } catch (error) {
+ // No caller ever learns of this ref, so no journal or sweep could release it later.
+ await gitExec(['update-ref', '-d', ref, commit], worktreePath).catch(() => undefined);
+ throw error;
+ }
return snapshot;
} finally {
await fs.rm(temp, { recursive: true, force: true });
diff --git a/apps/desktop/src/main/worktree/managedRecycle.ts b/apps/desktop/src/main/worktree/managedRecycle.ts
index a1bc931020..7b9c77f063 100644
--- a/apps/desktop/src/main/worktree/managedRecycle.ts
+++ b/apps/desktop/src/main/worktree/managedRecycle.ts
@@ -15,7 +15,7 @@ import {
} from './recycleJournal';
import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
import { isManagedWorktreePath } from './safety';
-import { assertManagedResourcePath, assertWorktreeGitIdentity } from './resourceSafety';
+import { assertManagedResourcePath, assertWorktreeGitIdentity, gitMetadataUsable } from './resourceSafety';
import * as store from './worktreeStore';
import type { WorktreeMeta } from './types';
import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';
@@ -81,27 +81,6 @@ 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.
diff --git a/apps/desktop/src/main/worktree/resourceSafety.ts b/apps/desktop/src/main/worktree/resourceSafety.ts
index 9d0b0edaeb..bf9b5631e4 100644
--- a/apps/desktop/src/main/worktree/resourceSafety.ts
+++ b/apps/desktop/src/main/worktree/resourceSafety.ts
@@ -32,6 +32,27 @@ async function assertAbsent(file: string): Promise<void> {
throw new Error('worktree is locked or explicitly kept');
}
+/** A `.git` file whose metadata directory was already deleted cannot answer Git queries. */
+export 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;
+ }
+}
+
/** A regular .git link must resolve to this worktree in the expected repository. */
export async function assertWorktreeGitIdentity(meta: WorktreeMeta): Promise<void> {
const link = await fs.lstat(path.join(meta.path, '.git'));
diff --git a/apps/desktop/src/main/worktree/restoreRecovery.ts b/apps/desktop/src/main/worktree/restoreRecovery.ts
index 910baaac73..6e924ad585 100644
--- a/apps/desktop/src/main/worktree/restoreRecovery.ts
+++ b/apps/desktop/src/main/worktree/restoreRecovery.ts
@@ -9,7 +9,9 @@ import { readRecycleRecord, writeRecycleRecord, worktreeGeneration } from './rec
import { extractRecoveryArchive, inventoryWorktree, sameWorktreeFiles, verifyRecoveryArchive } from './recoveryArchive';
import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';
import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRefs';
-import { assertManagedResourceLocation, assertManagedResourcePath, assertWorktreeGitIdentity } from './resourceSafety';
+import {
+ assertManagedResourceLocation, assertManagedResourcePath, assertWorktreeGitIdentity, gitMetadataUsable,
+} from './resourceSafety';
import * as store from './worktreeStore';
import { withLegacyWorktreeRuntimeGuard } from './legacyRuntimeGuard';
import {
@@ -55,16 +57,6 @@ 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
@@ -124,7 +116,7 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s
await assertManagedResourcePath(record.meta, [worktreePath]);
if (record.archive) {
if (!sameWorktreeFiles(await inventoryWorktree(worktreePath), record.archive.files, true)) return false;
- } else if (await pathExists(path.join(worktreePath, '.git'))
+ } else if (await gitMetadataUsable(worktreePath)
&& !(await presentFilesMatchSnapshotTree(worktreePath, record.snapshot.tree))) {
return false;
}
@@ -159,14 +151,8 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s
record.restoredGeneration ??= randomUUID();
await writeRecycleRecord(record);
const gitLink = path.join(worktreePath, '.git');
- let gitLinkExists = true;
- try {
- await fs.lstat(gitLink);
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
- gitLinkExists = false;
- }
- if (!gitLinkExists || record.restoreCheckoutPath) {
+ // A gitfile left pointing at deleted metadata is repaired like a missing one.
+ if (!(await gitMetadataUsable(worktreePath)) || record.restoreCheckoutPath) {
// Repair a partially deleted worktree without deleting any remaining user file.
// Persist the temporary checkout before creating it so a crash after `worktree add`
// can resume the same checkout instead of leaving its branch permanently occupied.
@@ -197,6 +183,8 @@ export async function restoreRecordedWorktree(sessionId: string, worktreePath: s
// Never delete or adopt an unexpected non-empty temporary directory.
return false;
}
+ // Only a link to removed metadata is replaced; it holds no user bytes.
+ if (!(await gitMetadataUsable(worktreePath))) await fs.rm(gitLink, { force: true });
try {
await fs.copyFile(path.join(checkout, '.git'), gitLink, constants.COPYFILE_EXCL);
} catch (error) {