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(review): bind capped workspace content

Chris6d1516c53723
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewCappedWorkspaceFingerprint.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewCappedWorkspaceFingerprint.test.ts
new file mode 100644
index 0000000000..5734b7ddd9
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewCappedWorkspaceFingerprint.test.ts
@@ -0,0 +1,91 @@
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ fingerprintReviewCappedWorkspaceFiles,
+ ReviewCappedWorkspaceFingerprintError,
+ ReviewCappedWorkspaceFingerprintLimitError,
+} from '../reviewCappedWorkspaceFingerprint.js';
+
+const tempDirs: string[] = [];
+
+async function makeTempDir(): Promise<string> {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-review-capped-fingerprint-'));
+ tempDirs.push(dir);
+ return dir;
+}
+
+afterEach(async () => {
+ await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
+});
+
+describe('capped Review workspace fingerprint', () => {
+ it('fully fingerprints same-size content changes', async () => {
+ const repoRoot = await makeTempDir();
+ const file = path.join(repoRoot, 'large.ts');
+ await fs.writeFile(file, 'aaa111zzz');
+ const before = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['large.ts']);
+
+ await fs.writeFile(file, 'aaa222zzz');
+ const after = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['large.ts']);
+
+ expect(after).not.toBe(before);
+ });
+
+ it('distinguishes a present file from a deleted capped path', async () => {
+ const repoRoot = await makeTempDir();
+ const file = path.join(repoRoot, 'deleted.ts');
+ await fs.writeFile(file, 'content');
+ const before = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['deleted.ts']);
+
+ await fs.unlink(file);
+ const after = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['deleted.ts']);
+
+ expect(after).not.toBe(before);
+ });
+
+ it('never reads sensitive capped paths', async () => {
+ const repoRoot = await makeTempDir();
+ const sensitive = path.join(repoRoot, '.env.local');
+ await fs.writeFile(sensitive, 'TOKEN=first');
+ const before = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['.env.local']);
+
+ await fs.writeFile(sensitive, 'TOKEN=other');
+ const after = await fingerprintReviewCappedWorkspaceFiles(repoRoot, ['.env.local']);
+
+ expect(after).toBe(before);
+ });
+
+ it('fails closed for traversal and an outside symlink', async () => {
+ const repoRoot = await makeTempDir();
+ await expect(
+ fingerprintReviewCappedWorkspaceFiles(repoRoot, ['../outside.ts']),
+ ).rejects.toBeInstanceOf(ReviewCappedWorkspaceFingerprintError);
+
+ if (process.platform === 'win32') return;
+ const outside = await makeTempDir();
+ await fs.writeFile(path.join(outside, 'outside.ts'), 'outside');
+ await fs.symlink(path.join(outside, 'outside.ts'), path.join(repoRoot, 'linked.ts'));
+ await expect(
+ fingerprintReviewCappedWorkspaceFiles(repoRoot, ['linked.ts']),
+ ).rejects.toBeInstanceOf(ReviewCappedWorkspaceFingerprintError);
+
+ await fs.writeFile(path.join(repoRoot, '.env.local'), 'TOKEN=secret');
+ await fs.symlink('.env.local', path.join(repoRoot, 'safe-name.ts'));
+ await expect(
+ fingerprintReviewCappedWorkspaceFiles(repoRoot, ['safe-name.ts']),
+ ).rejects.toBeInstanceOf(ReviewCappedWorkspaceFingerprintError);
+ });
+
+ it('fails closed instead of degrading to metadata above the byte limit', async () => {
+ const repoRoot = await makeTempDir();
+ await fs.writeFile(path.join(repoRoot, 'large.ts'), '1234');
+
+ await expect(
+ fingerprintReviewCappedWorkspaceFiles(repoRoot, ['large.ts'], { maxTotalBytes: 3 }),
+ ).rejects.toBeInstanceOf(ReviewCappedWorkspaceFingerprintLimitError);
+ });
+});
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
index 3cd5ed1c84..63a49a5eb4 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
@@ -5,7 +5,8 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-const { reviewRows, utilityProcessFork } = vi.hoisted(() => ({
+const { readReviewDataMock, reviewRows, utilityProcessFork } = vi.hoisted(() => ({
+ readReviewDataMock: vi.fn(),
reviewRows: [] as Array<Record<string, unknown>>,
utilityProcessFork: vi.fn(),
}));
@@ -24,7 +25,7 @@ vi.mock('../../localDb/client/current.js', () => ({
},
}),
}));
-vi.mock('../../git-review/ipc.js', () => ({ readReviewData: async () => null }));
+vi.mock('../../git-review/ipc.js', () => ({ readReviewData: readReviewDataMock }));
vi.mock('../../turn-change-set/store.js', () => ({
listTurnChangeSets: async () => [],
getTurnChangeSets: async () => [],
@@ -50,10 +51,16 @@ import {
} from '../reviewArtifactAuthorization.js';
import type { ReviewPdfUtilityChildLike } from '../reviewPdfProcess.js';
import type { ReviewPdfUtilityRequest } from '../reviewPdfProcessProtocol.js';
+import type { ReviewData } from '../../../shared/gitReviewWire.js';
+import {
+ fingerprintReviewCappedWorkspaceFiles,
+ ReviewCappedWorkspaceChangedError,
+} from '../reviewCappedWorkspaceFingerprint.js';
import {
listReviewHistoricalAttachments,
loadReviewEvidence,
readReviewContextFingerprint,
+ readReviewWorkspaceSnapshot,
} from '../reviewEvidence.js';
const tempDirs: string[] = [];
@@ -83,15 +90,173 @@ async function tempDir(): Promise<string> {
}
beforeEach(() => {
+ readReviewDataMock.mockResolvedValue(null);
utilityProcessFork.mockImplementation(() => new RejectingPdfUtility());
});
afterEach(async () => {
reviewRows.splice(0);
+ readReviewDataMock.mockReset();
utilityProcessFork.mockReset();
await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
});
+function cappedReviewData(repoRoot: string, filePath: string): ReviewData {
+ const scope = {
+ sessionId: 'source',
+ workdir: repoRoot,
+ worktreePath: repoRoot,
+ workingDir: repoRoot,
+ repoRoot,
+ branch: 'feature',
+ headOid: 'a'.repeat(40),
+ isDetached: false,
+ isUnborn: false,
+ source: 'workingDir' as const,
+ aheadBehind: { ahead: 0, behind: 0, upstream: null, stale: false },
+ disabledReason: null,
+ disabledMessage: null,
+ resolutionChain: [],
+ };
+ const statusFile = {
+ path: filePath,
+ oldPath: null,
+ indexStatus: null,
+ worktreeStatus: 'modified' as const,
+ isUntracked: false,
+ isUnmerged: false,
+ isSubmodule: false,
+ sources: ['unstaged' as const],
+ rawXY: ' M',
+ };
+ const cappedFile = {
+ id: `unstaged:${filePath}`,
+ source: 'unstaged' as const,
+ path: filePath,
+ oldPath: null,
+ status: 'modified' as const,
+ additions: 1,
+ deletions: 1,
+ changedLines: 2,
+ changedBytes: 9,
+ isBinary: false,
+ isSubmodule: false,
+ };
+ return {
+ scope,
+ status: {
+ scope,
+ files: [statusFile],
+ stagedCount: 0,
+ unstagedCount: 1,
+ untrackedCount: 0,
+ unmergedCount: 0,
+ inProgress: [],
+ writeDisabledReasons: [],
+ dirty: true,
+ },
+ diffs: {
+ staged: [],
+ unstaged: [],
+ capped: {
+ staged: null,
+ unstaged: {
+ reason: 'changed-bytes',
+ stats: { fileCount: 1, totalChangedLines: 2, totalChangedBytes: 9 },
+ files: [cappedFile],
+ },
+ },
+ },
+ summary: {
+ sessionId: 'source',
+ disabledReason: null,
+ disabledMessage: null,
+ totalFiles: 1,
+ stagedFiles: 0,
+ unstagedFiles: 1,
+ untrackedFiles: 0,
+ unmergedFiles: 0,
+ dirty: true,
+ },
+ };
+}
+
+describe('readReviewWorkspaceSnapshot', () => {
+ it('changes the fingerprint for a same-size capped file replacement', async () => {
+ const repoRoot = await tempDir();
+ const relativePath = 'large.ts';
+ const file = path.join(repoRoot, relativePath);
+ await fs.writeFile(file, 'aaa111zzz');
+ const reviewData = cappedReviewData(repoRoot, relativePath);
+ readReviewDataMock.mockResolvedValue(reviewData);
+
+ const before = await readReviewWorkspaceSnapshot('source');
+ await fs.writeFile(file, 'aaa222zzz');
+ const after = await readReviewWorkspaceSnapshot('source');
+
+ expect(after?.workspace).toEqual(before?.workspace);
+ expect(after?.fingerprint).not.toBe(before?.fingerprint);
+ });
+
+ it('retries until the capped Git summary and file content share one stable window', async () => {
+ const repoRoot = await tempDir();
+ const relativePath = 'large.ts';
+ const file = path.join(repoRoot, relativePath);
+ await fs.writeFile(file, 'aaa111zzz');
+ const reviewData = cappedReviewData(repoRoot, relativePath);
+ let reads = 0;
+ readReviewDataMock.mockImplementation(async () => {
+ reads += 1;
+ if (reads === 2) await fs.writeFile(file, 'aaa222zzz');
+ return reviewData;
+ });
+
+ const recovered = await readReviewWorkspaceSnapshot('source');
+ readReviewDataMock.mockResolvedValue(reviewData);
+ const stable = await readReviewWorkspaceSnapshot('source');
+
+ expect(reads).toBe(4);
+ expect(recovered?.fingerprint).toBe(stable?.fingerprint);
+ });
+
+ it('restarts the whole snapshot after a transient during-hash change', async () => {
+ const repoRoot = await tempDir();
+ const relativePath = 'large.ts';
+ await fs.writeFile(path.join(repoRoot, relativePath), 'aaa111zzz');
+ const reviewData = cappedReviewData(repoRoot, relativePath);
+ readReviewDataMock.mockResolvedValue(reviewData);
+ let fingerprintCalls = 0;
+
+ const snapshot = await readReviewWorkspaceSnapshot('source', {
+ fingerprintCappedWorkspaceFiles: async (...args) => {
+ fingerprintCalls += 1;
+ if (fingerprintCalls === 1) {
+ throw new ReviewCappedWorkspaceChangedError('transient write');
+ }
+ return fingerprintReviewCappedWorkspaceFiles(...args);
+ },
+ });
+
+ expect(snapshot?.fingerprint).toMatch(/^[a-f0-9]{64}$/);
+ expect(fingerprintCalls).toBe(3);
+ });
+
+ it('fails closed after repeated during-hash changes', async () => {
+ const repoRoot = await tempDir();
+ const relativePath = 'large.ts';
+ await fs.writeFile(path.join(repoRoot, relativePath), 'aaa111zzz');
+ readReviewDataMock.mockResolvedValue(cappedReviewData(repoRoot, relativePath));
+ const fingerprintCappedWorkspaceFiles = vi.fn(async () => {
+ throw new ReviewCappedWorkspaceChangedError('continuous writes');
+ });
+
+ await expect(
+ readReviewWorkspaceSnapshot('source', { fingerprintCappedWorkspaceFiles }),
+ ).rejects.toBeInstanceOf(ReviewCappedWorkspaceChangedError);
+ expect(fingerprintCappedWorkspaceFiles).toHaveBeenCalledTimes(3);
+ });
+});
+
describe('loadReviewEvidence attachment boundaries', () => {
it('fingerprints source-task activity while ignoring Review lifecycle cards', async () => {
const workingDir = await tempDir();
diff --git a/apps/desktop/src/main/reviewer/reviewCappedWorkspaceFingerprint.ts b/apps/desktop/src/main/reviewer/reviewCappedWorkspaceFingerprint.ts
new file mode 100644
index 0000000000..43d7e490e1
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/reviewCappedWorkspaceFingerprint.ts
@@ -0,0 +1,200 @@
+import { createHash, type Hash } from 'node:crypto';
+import { constants, promises as fs, type Stats } from 'node:fs';
+import path from 'node:path';
+
+import { isReviewSensitiveCredentialPath } from '@cindy/maker-core';
+
+import { isPathInside } from '../git-review/fsPathGuard.js';
+
+const MAX_CAPPED_WORKSPACE_PATHS = 10_000;
+const MAX_CAPPED_WORKSPACE_BYTES = 512 * 1024 * 1024;
+const READ_BUFFER_BYTES = 256 * 1024;
+const NOFOLLOW_FLAG = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0;
+
+export interface ReviewCappedWorkspaceFingerprintOptions {
+ /** Test seam; production remains bounded and fails closed above the limit. */
+ maxTotalBytes?: number;
+}
+
+export class ReviewCappedWorkspaceFingerprintError extends Error {}
+export class ReviewCappedWorkspaceFingerprintLimitError extends ReviewCappedWorkspaceFingerprintError {}
+export class ReviewCappedWorkspaceChangedError extends ReviewCappedWorkspaceFingerprintError {}
+
+function addRecord(hash: Hash, ...parts: Array<string | number>): void {
+ hash.update(JSON.stringify(parts)).update('\n');
+}
+
+function stableStatMatches(before: Stats, after: Stats): boolean {
+ return (
+ before.dev === after.dev &&
+ before.ino === after.ino &&
+ before.size === after.size &&
+ before.mtimeMs === after.mtimeMs &&
+ before.ctimeMs === after.ctimeMs &&
+ before.mode === after.mode
+ );
+}
+
+function assertSafeGitPath(rawPath: string): void {
+ if (
+ !rawPath ||
+ rawPath.includes('\0') ||
+ path.posix.isAbsolute(rawPath) ||
+ path.win32.isAbsolute(rawPath) ||
+ rawPath.split(/[\\/]/).includes('..')
+ ) {
+ throw new ReviewCappedWorkspaceFingerprintError(
+ 'Review refused an invalid capped workspace path',
+ );
+ }
+}
+
+async function lstatOrNull(filePath: string): Promise<Stats | null> {
+ try {
+ return await fs.lstat(filePath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
+async function hashRegularFile(input: {
+ hash: Hash;
+ repoRootReal: string;
+ candidate: string;
+ rawPath: string;
+ entryBefore: Stats;
+ remainingBytes: number;
+}): Promise<number> {
+ const linkTargetBefore = input.entryBefore.isSymbolicLink()
+ ? await fs.readlink(input.candidate)
+ : null;
+ const targetReal = await fs.realpath(input.candidate).catch(() => null);
+ const targetRelative = targetReal ? path.relative(input.repoRootReal, targetReal) : '';
+ if (
+ !targetReal ||
+ !isPathInside(input.repoRootReal, targetReal) ||
+ isReviewSensitiveCredentialPath(targetRelative)
+ ) {
+ throw new ReviewCappedWorkspaceFingerprintError(
+ 'Review refused a capped workspace path that resolves outside the repository',
+ );
+ }
+
+ const handle = await fs.open(targetReal, constants.O_RDONLY | NOFOLLOW_FLAG);
+ try {
+ const openedTargetReal = await fs.realpath(targetReal).catch(() => null);
+ if (!openedTargetReal || !isPathInside(input.repoRootReal, openedTargetReal)) {
+ throw new ReviewCappedWorkspaceFingerprintError(
+ 'Review refused a capped workspace path that changed its repository boundary',
+ );
+ }
+ const before = await handle.stat();
+ if (!before.isFile()) {
+ throw new ReviewCappedWorkspaceFingerprintError(
+ 'Review can only content-fingerprint regular capped workspace files',
+ );
+ }
+ if (before.size > input.remainingBytes) {
+ throw new ReviewCappedWorkspaceFingerprintLimitError(
+ 'Capped Review files exceed the 512 MB full-content fingerprint limit',
+ );
+ }
+
+ const contentHash = createHash('sha256');
+ const buffer = Buffer.allocUnsafe(READ_BUFFER_BYTES);
+ let offset = 0;
+ while (offset < before.size) {
+ const requested = Math.min(buffer.length, before.size - offset);
+ const { bytesRead } = await handle.read(buffer, 0, requested, offset);
+ if (bytesRead === 0) break;
+ contentHash.update(buffer.subarray(0, bytesRead));
+ offset += bytesRead;
+ }
+ const after = await handle.stat();
+ const entryAfter = await lstatOrNull(input.candidate);
+ const linkTargetAfter = entryAfter?.isSymbolicLink()
+ ? await fs.readlink(input.candidate).catch(() => null)
+ : null;
+ if (
+ offset !== before.size ||
+ !stableStatMatches(before, after) ||
+ !entryAfter ||
+ !stableStatMatches(input.entryBefore, entryAfter) ||
+ linkTargetAfter !== linkTargetBefore
+ ) {
+ throw new ReviewCappedWorkspaceChangedError(
+ 'A capped Review file changed while its content baseline was being prepared',
+ );
+ }
+
+ addRecord(
+ input.hash,
+ input.entryBefore.isSymbolicLink() ? 'symlink-file' : 'file',
+ input.rawPath,
+ linkTargetBefore ?? '',
+ before.size,
+ before.mode,
+ contentHash.digest('hex'),
+ );
+ return before.size;
+ } finally {
+ await handle.close().catch(() => undefined);
+ }
+}
+
+/**
+ * Fully hashes every non-sensitive current worktree file whose Git patch was
+ * replaced by a capped summary. Sampling is intentionally forbidden here:
+ * this digest is the freshness authority for content the reviewer may read.
+ */
+export async function fingerprintReviewCappedWorkspaceFiles(
+ repoRoot: string,
+ rawPaths: readonly string[],
+ options: ReviewCappedWorkspaceFingerprintOptions = {},
+): Promise<string> {
+ const maxTotalBytes = options.maxTotalBytes ?? MAX_CAPPED_WORKSPACE_BYTES;
+ if (!Number.isSafeInteger(maxTotalBytes) || maxTotalBytes <= 0) {
+ throw new TypeError('maxTotalBytes must be a positive safe integer');
+ }
+ const repoRootReal = await fs.realpath(repoRoot);
+ const paths = [...new Set(rawPaths)]
+ .filter((rawPath) => !isReviewSensitiveCredentialPath(rawPath))
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
+ if (paths.length > MAX_CAPPED_WORKSPACE_PATHS) {
+ throw new ReviewCappedWorkspaceFingerprintLimitError(
+ `Capped Review contains more than ${MAX_CAPPED_WORKSPACE_PATHS} file paths`,
+ );
+ }
+
+ const hash = createHash('sha256');
+ let totalBytes = 0;
+ for (const rawPath of paths) {
+ assertSafeGitPath(rawPath);
+ const candidate = path.join(repoRootReal, ...rawPath.split('/'));
+ if (!isPathInside(repoRootReal, candidate)) {
+ throw new ReviewCappedWorkspaceFingerprintError(
+ 'Review refused a capped workspace path outside the repository',
+ );
+ }
+ const entryBefore = await lstatOrNull(candidate);
+ if (!entryBefore) {
+ addRecord(hash, 'missing', rawPath);
+ continue;
+ }
+ if (!entryBefore.isFile() && !entryBefore.isSymbolicLink()) {
+ throw new ReviewCappedWorkspaceFingerprintError(
+ 'Review can only content-fingerprint regular capped workspace files',
+ );
+ }
+ totalBytes += await hashRegularFile({
+ hash,
+ repoRootReal,
+ candidate,
+ rawPath,
+ entryBefore,
+ remainingBytes: maxTotalBytes - totalBytes,
+ });
+ }
+ return hash.digest('hex');
+}
diff --git a/apps/desktop/src/main/reviewer/reviewEvidence.ts b/apps/desktop/src/main/reviewer/reviewEvidence.ts
index b0a29fd7cd..ecf6af45e6 100644
--- a/apps/desktop/src/main/reviewer/reviewEvidence.ts
+++ b/apps/desktop/src/main/reviewer/reviewEvidence.ts
@@ -37,6 +37,10 @@ import {
type ResolvedReviewArtifactPath,
type ReviewExplicitArtifactGrant,
} from './reviewArtifactAuthorization.js';
+import {
+ fingerprintReviewCappedWorkspaceFiles,
+ ReviewCappedWorkspaceChangedError,
+} from './reviewCappedWorkspaceFingerprint.js';
export interface ReviewAttachmentInput {
name: string;
@@ -99,12 +103,43 @@ function mapReviewWorkspace(
};
}
-export async function readReviewWorkspaceSnapshot(
- sourceSessionId: string,
-): Promise<{ workspace: ReviewWorkspaceEvidence; fingerprint: string | null } | null> {
- const reviewData = await readReviewData(sourceSessionId).catch(() => null);
- if (!reviewData) return null;
+interface ReviewWorkspaceSnapshot {
+ workspace: ReviewWorkspaceEvidence;
+ fingerprint: string | null;
+ hasCappedDiff: boolean;
+}
+
+interface ReviewWorkspaceSnapshotDeps {
+ readReviewData: typeof readReviewData;
+ fingerprintCappedWorkspaceFiles: typeof fingerprintReviewCappedWorkspaceFiles;
+}
+
+const defaultReviewWorkspaceSnapshotDeps: ReviewWorkspaceSnapshotDeps = {
+ readReviewData,
+ fingerprintCappedWorkspaceFiles: fingerprintReviewCappedWorkspaceFiles,
+};
+
+function cappedWorkspacePaths(workspace: ReviewWorkspaceEvidence): string[] {
+ return [workspace.diffs.capped?.staged, workspace.diffs.capped?.unstaged].flatMap((capped) =>
+ capped
+ ? capped.files.flatMap((file) => [file.path, file.oldPath].filter(Boolean) as string[])
+ : [],
+ );
+}
+
+async function buildReviewWorkspaceSnapshot(
+ reviewData: Awaited<ReturnType<typeof readReviewData>>,
+ fingerprintCappedWorkspaceFiles: typeof fingerprintReviewCappedWorkspaceFiles,
+): Promise<ReviewWorkspaceSnapshot> {
const workspace = mapReviewWorkspace(reviewData);
+ const hasCappedDiff = Boolean(workspace.diffs.capped?.staged || workspace.diffs.capped?.unstaged);
+ const cappedContentFingerprint =
+ hasCappedDiff && reviewData.scope.repoRoot
+ ? await fingerprintCappedWorkspaceFiles(
+ reviewData.scope.repoRoot,
+ cappedWorkspacePaths(workspace),
+ )
+ : null;
return {
workspace,
// A clean tree is not proof that the reviewer saw the same code: changing
@@ -127,13 +162,52 @@ export async function readReviewWorkspaceSnapshot(
inProgress: reviewData.status?.inProgress ?? [],
summary: reviewData.summary,
workspace,
+ cappedContentFingerprint,
}),
)
.digest('hex')
: null,
+ hasCappedDiff,
};
}
+export async function readReviewWorkspaceSnapshot(
+ sourceSessionId: string,
+ depsInput: Partial<ReviewWorkspaceSnapshotDeps> = {},
+): Promise<{ workspace: ReviewWorkspaceEvidence; fingerprint: string | null } | null> {
+ const deps = { ...defaultReviewWorkspaceSnapshotDeps, ...depsInput };
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ const reviewData = await deps.readReviewData(sourceSessionId).catch((error) => {
+ if (attempt === 0) return null;
+ throw error;
+ });
+ if (!reviewData) return null;
+ try {
+ const current = await buildReviewWorkspaceSnapshot(
+ reviewData,
+ deps.fingerprintCappedWorkspaceFiles,
+ );
+ if (!current.hasCappedDiff) return current;
+
+ // A capped summary and its full-content digest must describe one stable
+ // workspace window. Require a second matching snapshot; a transient edit
+ // during either full-file hash restarts the whole Git + content read.
+ const confirmationData = await deps.readReviewData(sourceSessionId);
+ const confirmation = await buildReviewWorkspaceSnapshot(
+ confirmationData,
+ deps.fingerprintCappedWorkspaceFiles,
+ );
+ if (!confirmation.hasCappedDiff) return confirmation;
+ if (confirmation.fingerprint === current.fingerprint) return confirmation;
+ } catch (error) {
+ if (!(error instanceof ReviewCappedWorkspaceChangedError) || attempt === 2) throw error;
+ }
+ }
+ throw new ReviewCappedWorkspaceChangedError(
+ 'The capped Review workspace kept changing while its content baseline was prepared',
+ );
+}
+
function parseJsonRecord(value: unknown): Record<string, unknown> | null {
let parsed = value;
if (typeof parsed === 'string') {