Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): Review 新鲜度绑定 staged index 身份 (#2512)
fico-hub4ac21c1ecd80
diff --git a/apps/desktop/src/main/git-review/__tests__/indexIdentityReader.git-integration.test.ts b/apps/desktop/src/main/git-review/__tests__/indexIdentityReader.git-integration.test.tsnew file mode 100644index 0000000000..edbb000feb--- /dev/null+++ b/apps/desktop/src/main/git-review/__tests__/indexIdentityReader.git-integration.test.ts@@ -0,0 +1,146 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';++import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。+vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });++import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';+import { runGit } from '../gitRunner';+import { readStagedIndexIdentity } from '../indexIdentityReader';++let repoPath: string;++const repoTemplate = new TestDirectoryTemplate('xdt-git-review-index-id-', async (dir) => {+ await runGit(['init'], { cwd: dir });+ await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });+ await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });+ await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });+ await runGit(['config', 'core.autocrlf', 'false'], { cwd: dir });+ await fs.writeFile(path.join(dir, 'seed.txt'), 'seed\n');+ await runGit(['add', 'seed.txt'], { cwd: dir });+ await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });+});++beforeEach(async () => {+ repoPath = await repoTemplate.createCopy();+});++afterEach(async () => {+ await fs.rm(repoPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });+});++afterAll(async () => {+ await repoTemplate.dispose();+});++describe('readStagedIndexIdentity (#2460)', () => {+ it('binds the staged blob oid: swapping the index blob changes the record set', async () => {+ const file = path.join(repoPath, 'blob.bin');+ await fs.writeFile(file, Buffer.from([1, 2, 3, 4]));+ await runGit(['add', 'blob.bin'], { cwd: repoPath });+ const before = await readStagedIndexIdentity(repoPath, ['blob.bin']);++ // 同尺寸不同字节换 blob,并把工作树字节还原 —— porcelain 与工作树内容+ // 指纹都看不出差异,只有 index oid 能区分(#2460 的攻击形态)。+ await fs.writeFile(file, Buffer.from([5, 6, 7, 8]));+ await runGit(['add', 'blob.bin'], { cwd: repoPath });+ await fs.writeFile(file, Buffer.from([1, 2, 3, 4]));+ const after = await readStagedIndexIdentity(repoPath, ['blob.bin']);++ expect(before).toHaveLength(1);+ expect(before[0]).toMatch(/^100644 0 [0-9a-f]{40,64}\tblob\.bin$/);+ expect(after).toHaveLength(1);+ expect(after).not.toEqual(before);+ });++ it('re-adding identical bytes keeps the record set stable (no false churn)', async () => {+ const file = path.join(repoPath, 'blob.bin');+ await fs.writeFile(file, Buffer.from([1, 2, 3, 4]));+ await runGit(['add', 'blob.bin'], { cwd: repoPath });+ const before = await readStagedIndexIdentity(repoPath, ['blob.bin']);++ await runGit(['add', 'blob.bin'], { cwd: repoPath });+ const after = await readStagedIndexIdentity(repoPath, ['blob.bin']);++ expect(after).toEqual(before);+ });++ it('records a staged deletion as an explicit absent marker', async () => {+ await runGit(['rm', 'seed.txt'], { cwd: repoPath });+ const records = await readStagedIndexIdentity(repoPath, ['seed.txt']);+ expect(records).toEqual(['absent\tseed.txt']);+ });++ it('expresses unmerged stages as one record per stage', async () => {+ // 构造冲突:两个分支各改 seed.txt 后合并。+ await runGit(['checkout', '-b', 'left'], { cwd: repoPath });+ await fs.writeFile(path.join(repoPath, 'seed.txt'), 'left\n');+ await runGit(['commit', '--no-gpg-sign', '-am', 'left'], { cwd: repoPath });+ await runGit(['checkout', '-b', 'right', 'HEAD~1'], { cwd: repoPath });+ await fs.writeFile(path.join(repoPath, 'seed.txt'), 'right\n');+ await runGit(['commit', '--no-gpg-sign', '-am', 'right'], { cwd: repoPath });+ await runGit(['merge', 'left'], { cwd: repoPath, allowedExitCodes: [0, 1] });++ const records = await readStagedIndexIdentity(repoPath, ['seed.txt']);+ expect(records).toHaveLength(3);+ const stages = records.map((record) => record.split(' ')[1]).sort();+ expect(stages).toEqual(['1', '2', '3']);+ });++ it('returns stable ordering regardless of input order and dedupes input paths', async () => {+ await fs.writeFile(path.join(repoPath, 'a.txt'), 'a\n');+ await fs.writeFile(path.join(repoPath, 'b.txt'), 'b\n');+ await runGit(['add', 'a.txt', 'b.txt'], { cwd: repoPath });++ const forward = await readStagedIndexIdentity(repoPath, ['a.txt', 'b.txt']);+ const backward = await readStagedIndexIdentity(repoPath, ['b.txt', 'a.txt', 'b.txt']);+ expect(backward).toEqual(forward);+ expect(forward.map((record) => record.split('\t')[1])).toEqual(['a.txt', 'b.txt']);+ });++ it('fails closed when the repository cannot be read', async () => {+ await expect(+ readStagedIndexIdentity(path.join(repoPath, 'no-such-dir'), ['seed.txt']),+ ).rejects.toThrow();+ });++ // Windows 文件名不允许控制字符,该形态只在 POSIX 上可构造。+ it.skipIf(process.platform === 'win32')(+ 'binds identity for paths containing newline instead of silently skipping them',+ async () => {+ const trickyName = 'a\nb.txt';+ await fs.writeFile(path.join(repoPath, trickyName), 'v1\n');+ await runGit(['add', '--', trickyName], { cwd: repoPath });+ const first = await readStagedIndexIdentity(repoPath, [trickyName]);+ expect(first).toHaveLength(1);+ expect(first[0]).not.toBe(`absent\t${trickyName}`);+ expect(first[0].endsWith(`\t${trickyName}`)).toBe(true);++ // #2460 攻击形态在换行路径上同样必须被身份变化捕获。+ await fs.writeFile(path.join(repoPath, trickyName), 'v2\n');+ await runGit(['add', '--', trickyName], { cwd: repoPath });+ const second = await readStagedIndexIdentity(repoPath, [trickyName]);+ expect(second).not.toEqual(first);+ },+ );++ it('merges results across pathspec batches identically to a single call', async () => {+ const names = Array.from({ length: 7 }, (_, i) => `batch-${i}.txt`);+ for (const name of names) {+ await fs.writeFile(path.join(repoPath, name), `${name}\n`);+ }+ await runGit(['add', '--', ...names], { cwd: repoPath });+ const queried = [...names, 'batch-missing.txt'];++ const single = await readStagedIndexIdentity(repoPath, queried);+ const batched = await readStagedIndexIdentity(repoPath, queried, {+ maxBatchPaths: 2,+ maxBatchPathspecBytes: 64,+ });+ expect(batched).toEqual(single);+ expect(batched).toHaveLength(queried.length);+ expect(batched).toContain('absent\tbatch-missing.txt');+ });+});diff --git a/apps/desktop/src/main/git-review/indexIdentityReader.ts b/apps/desktop/src/main/git-review/indexIdentityReader.tsnew file mode 100644index 0000000000..a85dcad3a1--- /dev/null+++ b/apps/desktop/src/main/git-review/indexIdentityReader.ts@@ -0,0 +1,114 @@+/**+ * Review 新鲜度的 staged index 身份读取(#2460)。+ *+ * 内容指纹只哈希**工作树文件**;staged 内容存放在 Git index 中。同一路径同时+ * 存在 staged 与 unstaged 的无正文 diff(binary / large-text / too-large /+ * capped)时,把 index blob 换成同尺寸的另一份、再把工作树字节还原:porcelain+ * status、空 patch 元数据与工作树内容指纹全部不变——两道 freshness gate 都会+ * 放行,review 结论针对的却是已经过期的 staged 证据。+ *+ * 这里只绑定 Git 已经算好的**对象身份** `(path, mode, stage, oid)`,不读 blob+ * 字节:oid 天然稳定(同内容同 oid,重复 git add 不误伤),也不引入新的字节+ * 读取面。staged 删除没有 index 条目——「缺席」本身就是身份,记为 absent 标记,+ * 与「换了另一份 blob」同样参与指纹。unmerged 条目的 stage 1/2/3 各自成行,+ * 完整可表达。git 命令失败时抛错 fail closed(与 Git 证据读取失败同语义,由+ * 调用方中止 Review)。+ */++import { runGit } from './gitRunner.js';++/** `:(top,literal)` 前缀:按仓库根字面匹配,不展开 glob。 */+function literalPathspec(gitPath: string): string {+ return `:(top,literal)${gitPath}`;+}++/**+ * pathspec 分批上限。Windows 的进程命令行封顶约 32K 字符,数千条 capped+ * staged 路径塞进单次 spawn 会直接失败;按累计字节与条数双重上限分批,+ * 批间合并结果,语义与单次调用一致。+ */+const MAX_BATCH_PATHSPEC_BYTES = 12_000;+const MAX_BATCH_PATHS = 500;++/** 供测试注入更小的分批上限;生产调用方不传,走默认常量。 */+export interface IndexIdentityBatchLimits {+ maxBatchPathspecBytes?: number;+ maxBatchPaths?: number;+}++function splitIntoBatches(paths: string[], limits?: IndexIdentityBatchLimits): string[][] {+ const maxBytes = limits?.maxBatchPathspecBytes ?? MAX_BATCH_PATHSPEC_BYTES;+ const maxPaths = limits?.maxBatchPaths ?? MAX_BATCH_PATHS;+ const batches: string[][] = [];+ let current: string[] = [];+ let currentBytes = 0;+ for (const p of paths) {+ // `:(top,literal)` 前缀 + 引号/分隔的粗略开销。+ const bytes = Buffer.byteLength(p, 'utf8') + 20;+ if (current.length > 0 && (currentBytes + bytes > maxBytes || current.length >= maxPaths)) {+ batches.push(current);+ current = [];+ currentBytes = 0;+ }+ current.push(p);+ currentBytes += bytes;+ }+ if (current.length > 0) batches.push(current);+ return batches;+}++/**+ * 读取一组路径的 staged index 身份记录,稳定排序返回。+ *+ * 返回记录形如 `<mode> <stage> <oid>\t<path>`(存在于 index)或+ * `absent\t<path>`(index 无该条目,如 staged 删除)。记录组与输入顺序无关,+ * 调用方把整组并入 workspace fingerprint 即完成绑定。+ */+export async function readStagedIndexIdentity(+ repoRoot: string,+ rawPaths: readonly string[],+ limits?: IndexIdentityBatchLimits,+): Promise<string[]> {+ // 不做字符过滤:pathspec 经 argv 传递、输出用 -z(NUL 分隔、无引号转义),+ // 含 \n / \r / \t 的合法 Git 路径同样必须绑定身份 —— 静默丢弃就是绕过口。+ // 记录并入 fingerprint 时经 JSON 序列化,控制字符不产生边界歧义。+ const paths = [...new Set(rawPaths)]+ .filter((p) => p.length > 0)+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));+ if (paths.length === 0) return [];++ // 记录格式:"<mode> <oid> <stage>\t<path>",NUL 分隔。+ const entriesByPath = new Map<string, string[]>();+ for (const batch of splitIntoBatches(paths, limits)) {+ // 输出预算按路径实际字节计,且 unmerged 一条输入产出 stage 1/2/3 三行,+ // 每行都含完整路径 —— 统一按三倍身份行计,不足 1MB 补足。+ const budget = batch.reduce((n, p) => n + (Buffer.byteLength(p, 'utf8') + 128) * 3, 0);+ const { stdout } = await runGit(+ ['ls-files', '--stage', '-z', '--', ...batch.map(literalPathspec)],+ { cwd: repoRoot, maxStdoutBytes: Math.max(1024 * 1024, budget) },+ );+ for (const record of stdout.split('\0')) {+ if (!record) continue;+ const tab = record.indexOf('\t');+ if (tab < 0) continue;+ const [mode, oid, stage] = record.slice(0, tab).trim().split(/\s+/);+ const filePath = record.slice(tab + 1);+ if (!mode || !oid || !stage || !filePath) continue;+ const rows = entriesByPath.get(filePath) ?? [];+ rows.push(`${mode} ${stage} ${oid}\t${filePath}`);+ entriesByPath.set(filePath, rows);+ }+ }++ const records: string[] = [];+ for (const p of paths) {+ const rows = entriesByPath.get(p);+ if (rows && rows.length > 0) {+ // unmerged 时同一路径有 stage 1/2/3 多行;行内排序保证稳定。+ records.push(...rows.sort());+ } else {+ records.push(`absent\t${p}`);+ }+ }+ return records;+}diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.tsindex 8e243eb66d..1f8dd41419 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts@@ -250,6 +250,47 @@ function binaryReviewData(repoRoot: string, filePath: string): ReviewData {};}+/** A dirty workspace whose only change is a staged binary file (#2460). */+function stagedBinaryReviewData(repoRoot: string, filePath: string): ReviewData {+ const data = cappedReviewData(repoRoot, filePath);+ return {+ ...data,+ status: {+ ...data.status!,+ files: [+ {+ ...data.status!.files[0],+ indexStatus: 'modified' as const,+ worktreeStatus: null,+ sources: ['staged' as const],+ rawXY: 'M ',+ },+ ],+ stagedCount: 1,+ unstagedCount: 0,+ },+ diffs: {+ staged: [+ {+ ...branchFileDiff(filePath),+ id: `staged:${filePath}`,+ source: 'staged' as const,+ kind: 'binary' as const,+ isBinary: true,+ rawHeader: '',+ rawPatch: '',+ additions: 0,+ deletions: 0,+ error: 'Binary file',+ },+ ],+ unstaged: [],+ capped: { staged: null, unstaged: null },+ },+ summary: { ...data.summary, stagedFiles: 1, unstagedFiles: 0 },+ };+}+/** A Git workspace with everything committed, which is when branch review applies. */function cleanGitReviewData(repoRoot: string): ReviewData {const scope = {@@ -388,6 +429,60 @@ describe('readReviewWorkspaceSnapshot', () => {expect(after?.fingerprint).not.toBe(before?.fingerprint);});+ it('binds the staged index identity into the fingerprint (#2460)', async () => {+ // Swapping the index blob for different bytes while restoring the worktree+ // leaves status and metadata identical; only the index object identity can+ // tell the two states apart.+ const repoRoot = await tempDir();+ const relativePath = 'assets/logo.png';+ const file = path.join(repoRoot, relativePath);+ await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(file, Buffer.from([1, 2, 3, 4]));+ readReviewDataMock.mockResolvedValue(stagedBinaryReviewData(repoRoot, relativePath));++ const before = await readReviewWorkspaceSnapshot('source', {+ readStagedIndexIdentity: async () => [`100644 0 ${'a'.repeat(40)}\t${relativePath}`],+ });+ const after = await readReviewWorkspaceSnapshot('source', {+ readStagedIndexIdentity: async () => [`100644 0 ${'b'.repeat(40)}\t${relativePath}`],+ });++ expect(after?.workspace).toEqual(before?.workspace);+ expect(before?.fingerprint).toMatch(/^[a-f0-9]{64}$/);+ expect(after?.fingerprint).not.toBe(before?.fingerprint);+ });++ it('fails closed when the staged index identity cannot be read (#2460)', async () => {+ const repoRoot = await tempDir();+ const relativePath = 'assets/logo.png';+ const file = path.join(repoRoot, relativePath);+ await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(file, Buffer.from([1, 2, 3, 4]));+ readReviewDataMock.mockResolvedValue(stagedBinaryReviewData(repoRoot, relativePath));+ const failure = new Error('git ls-files failed');++ await expect(+ readReviewWorkspaceSnapshot('source', {+ readStagedIndexIdentity: async () => {+ throw failure;+ },+ }),+ ).rejects.toBe(failure);+ });++ it('does not read the index identity when there is no staged evidence (#2460)', async () => {+ const repoRoot = await tempDir();+ const relativePath = 'large.ts';+ await fs.writeFile(path.join(repoRoot, relativePath), 'aaa111zzz');+ readReviewDataMock.mockResolvedValue(cappedReviewData(repoRoot, relativePath));+ const readStagedIndexIdentity = vi.fn(async () => []);++ await expect(+ readReviewWorkspaceSnapshot('source', { readStagedIndexIdentity }),+ ).resolves.toBeTruthy();+ expect(readStagedIndexIdentity).not.toHaveBeenCalled();+ });+it('does not hand a dirty submodule to the file fingerprinter', async () => {// A gitlink is a directory and the fingerprinter accepts only regular// files, so including it would abort evidence loading and make the wholediff --git a/apps/desktop/src/main/reviewer/reviewEvidence.ts b/apps/desktop/src/main/reviewer/reviewEvidence.tsindex a834979fa9..c2b5fcca41 100644--- a/apps/desktop/src/main/reviewer/reviewEvidence.ts+++ b/apps/desktop/src/main/reviewer/reviewEvidence.ts@@ -42,6 +42,7 @@ import {fingerprintReviewCappedWorkspaceFiles,ReviewCappedWorkspaceChangedError,} from './reviewCappedWorkspaceFingerprint.js';+import { readStagedIndexIdentity } from '../git-review/indexIdentityReader.js';export interface ReviewAttachmentInput {name: string;@@ -194,11 +195,13 @@ interface ReviewWorkspaceSnapshot {interface ReviewWorkspaceSnapshotDeps {readReviewData: typeof readReviewData;fingerprintCappedWorkspaceFiles: typeof fingerprintReviewCappedWorkspaceFiles;+ readStagedIndexIdentity: typeof readStagedIndexIdentity;}const defaultReviewWorkspaceSnapshotDeps: ReviewWorkspaceSnapshotDeps = {readReviewData,fingerprintCappedWorkspaceFiles: fingerprintReviewCappedWorkspaceFiles,+ readStagedIndexIdentity,};/**@@ -247,9 +250,36 @@ function workspacePathsWithoutContent(workspace: ReviewWorkspaceEvidence): strinreturn [...new Set([...capped, ...contentless])];}+/**+ * Sanitized staged evidence paths whose index identity must be bound (#2460).+ *+ * The content fingerprint above hashes worktree bytes only; staged content+ * lives in the Git index. When a path carries both a staged and an unstaged+ * contentless diff, swapping the index blob for another one of the same size+ * while restoring the worktree bytes leaves status, empty-patch metadata and+ * the worktree hash all unchanged — both freshness gates would keep accepting+ * a conclusion drawn from the stale staged bytes. Binding the index object+ * identity `(path, mode, stage, oid)` closes that without reading blob bytes.+ *+ * Collected from the sanitized staged evidence (plain staged diffs plus the+ * capped staged bucket), so sensitive-path filtering has already been applied.+ */+function stagedEvidencePaths(workspace: ReviewWorkspaceEvidence): string[] {+ const capped = (workspace.diffs.capped?.staged?.files ?? []).flatMap(+ (file) => [file.path, file.oldPath].filter(Boolean) as string[],+ );+ const staged = workspace.diffs.staged.flatMap(+ (diff) => [diff.path, diff.oldPath].filter(Boolean) as string[],+ );+ return [...new Set([...staged, ...capped])];+}+async function buildReviewWorkspaceSnapshot(reviewData: Awaited<ReturnType<typeof readReviewData>>,- fingerprintCappedWorkspaceFiles: typeof fingerprintReviewCappedWorkspaceFiles,+ deps: Pick<+ ReviewWorkspaceSnapshotDeps,+ 'fingerprintCappedWorkspaceFiles' | 'readStagedIndexIdentity'+ >,): Promise<ReviewWorkspaceSnapshot> {const workspace = mapReviewWorkspace(reviewData);const contentlessPaths = workspacePathsWithoutContent(workspace);@@ -258,7 +288,14 @@ async function buildReviewWorkspaceSnapshot(const hasCappedDiff = contentlessPaths.length > 0;const cappedContentFingerprint =hasCappedDiff && reviewData.scope.repoRoot- ? await fingerprintCappedWorkspaceFiles(reviewData.scope.repoRoot, contentlessPaths)+ ? await deps.fingerprintCappedWorkspaceFiles(reviewData.scope.repoRoot, contentlessPaths)+ : null;+ const stagedPaths = stagedEvidencePaths(workspace);+ // Identity only — no byte reads. A read failure propagates and aborts the+ // snapshot (fail closed), same as any other Git evidence read failure.+ const stagedIndexIdentity =+ stagedPaths.length > 0 && reviewData.scope.repoRoot+ ? await deps.readStagedIndexIdentity(reviewData.scope.repoRoot, stagedPaths): null;return {workspace,@@ -283,6 +320,7 @@ async function buildReviewWorkspaceSnapshot(summary: reviewData.summary,workspace,cappedContentFingerprint,+ stagedIndexIdentity,}),).digest('hex')@@ -303,20 +341,14 @@ export async function readReviewWorkspaceSnapshot(// result for a task that may in fact be a Git workspace.const reviewData = await deps.readReviewData(sourceSessionId);try {- const current = await buildReviewWorkspaceSnapshot(- reviewData,- deps.fingerprintCappedWorkspaceFiles,- );+ const current = await buildReviewWorkspaceSnapshot(reviewData, deps);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,- );+ const confirmation = await buildReviewWorkspaceSnapshot(confirmationData, deps);if (!confirmation.hasCappedDiff) return confirmation;if (confirmation.fingerprint === current.fingerprint) return confirmation;} catch (error) {