Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(review): exclude harness binaries and managed worktrees from fingerprint (#2376)
Chris Zhang44e51d31ce0d
diff --git a/apps/desktop/src/main/git-review/branchReader.ts b/apps/desktop/src/main/git-review/branchReader.tsindex 1be458ba58..7b7ee92296 100644--- a/apps/desktop/src/main/git-review/branchReader.ts+++ b/apps/desktop/src/main/git-review/branchReader.ts@@ -399,6 +399,13 @@ export async function listBranchBaseCandidates(scope: ReviewScope): Promise<Reviawait addCandidate(scope.repoRoot, candidates, item);}await markUpstreamCandidate(scope.repoRoot, candidates, upstream, initDefaultBranchName, remoteDefault);+ // Record which refs count as this repository's default. `init.defaultBranch`+ // is only readable here, so consumers cannot re-derive it from a ref name.+ for (const [refName, candidate] of candidates) {+ if (isDefaultBranchCandidateRef(refName, initDefaultBranchName, remoteDefault)) {+ candidates.set(refName, { ...candidate, isDefaultBranch: true });+ }+ }const withStaleRisk = await markStaleRiskCandidates(scope.repoRoot, Array.from(candidates.values()));return sortCandidates(withStaleRisk, initDefaultBranchName);}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 22a544b6e9..441f00a856 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -188,6 +188,7 @@ import {listReviewHistoricalAttachments,loadReviewEvidence,readReviewContextFingerprint,+ reviewBranchBaselineIsCurrent,reviewWorkspaceFingerprintIsCurrent,resolveReviewArtifactPath,SensitiveReviewPathError,@@ -207,6 +208,7 @@ import {ReviewArtifactFingerprintChangedError,ReviewArtifactFingerprintLimitError,} from '../reviewer/reviewArtifactFingerprint.js';+import { reviewChangeSetContentPaths } from '../reviewer/reviewEvidenceSafety.js';import { enforceReviewCreateOptions } from '../reviewer/reviewSessionPolicy.js';import { reviewSourceIdentityMatches } from '../reviewer/reviewSourceIdentity.js';import { buildReviewSessionTitle } from '../reviewer/reviewSessionTitle.js';@@ -7059,15 +7061,27 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}throw error;}+ // A committed branch is reviewable content on its own: opening an existing+ // worktree and running /review has no conversation, no dirty tree and no+ // turn of its own, yet the branch's commits are exactly what to review.if (evidence.context.length === 0 &&!evidence.workspace?.dirty &&+ !evidence.branch &&!evidence.changeSet &&evidence.artifacts.length === 0 &&!request.focus) {await cleanupPreparedArtifacts?.();- throwIpcError('INVALID_PARAMS', 'The current task has no reviewable content yet');+ // "Nothing to review" and "the branch was there but could not be read"+ // are different answers, and only the second one tells the user what to+ // do about it. The prompt-level warning never runs on this path.+ throwIpcError(+ 'INVALID_PARAMS',+ evidence.branchUnavailableReason+ ? `Review could not load this branch's changes (${evidence.branchUnavailableReason})`+ : 'The current task has no reviewable content yet',+ );}let builtPrompt: ReturnType<typeof buildReviewPrompt>;try {@@ -7075,6 +7089,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)focus: evidence.focusPath ? `审查路径:${evidence.focusPath}` : request.focus,context: evidence.context,workspace: evidence.workspace,+ branch: evidence.branch,+ ...(evidence.branchUnavailableReason+ ? { branchUnavailableReason: evidence.branchUnavailableReason }+ : {}),changeSet: evidence.changeSet,artifacts: evidence.artifacts,artifactsOmitted: evidence.artifactsOmitted,@@ -7117,11 +7135,52 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}}}- // Every harness grants read access to the source working directory.- // Git identity/diff fingerprints do not cover ignored build output,- // caches or nested-submodule contents, so the reusable result must- // also bind the complete non-sensitive readable workspace content.- const artifactPaths = [...reviewReadPaths, sourceWorkingDir];+ // Fingerprint what the review actually covers, not the whole+ // workspace: explicit artifacts, attachments and the reviewed change+ // set. The reviewer still reads the full workspace through workingDir,+ // but an unrelated file edit must not invalidate a completed review,+ // and a full-workspace content hash cannot stay inside its byte budget+ // on a real checkout.+ //+ // Change-set paths are bound even when Git evidence exists: the Git+ // fingerprint hashes identity, porcelain status and patches, so an+ // ignored deliverable built by the reviewed turn (dist/report.html)+ // is covered by neither unless it is included here.+ // The change set is the review target only when nothing better was+ // selected. With uncommitted work or a branch diff in hand it is not+ // part of the evidence, so neither its gaps nor its paths belong+ // here — those commits are already represented by the selected+ // evidence, and binding unreviewed paths would let an unrelated turn+ // refuse the review or invalidate its result.+ //+ // The accepted cost: a branch review does not bind an ignored file+ // the latest turn happened to produce, so editing that file mid-review+ // will not invalidate the result. Binding it would mean an unrelated+ // turn — one whose content is not being reviewed — could refuse the+ // review outright or expire it. Between "an unreviewed file went+ // unwatched" and "an unreviewed file blocked a valid review", this+ // takes the first. Reviewing that deliverable is still available by+ // attaching it explicitly, which puts it in reviewReadPaths.+ const changeSetIsReviewed = !evidence.workspace?.dirty && !evidence.branch;+ const changeSetContent = changeSetIsReviewed+ ? reviewChangeSetContentPaths(evidence.changeSet, sourceWorkingDir)+ : { paths: [], truncated: false };+ // A change set that cannot account for everything the turn changed —+ // whether it was summarized away or never enumerable in the first+ // place — cannot serve as a baseline. Refuse instead of publishing a+ // conclusion whose freshness check silently skipped the remainder.+ //+ // A Git fingerprint is not an exemption: it hashes tracked evidence+ // only, so a missing entry that happens to be an ignored deliverable+ // is covered by neither side — exactly the gap this change closes.+ if (changeSetContent.truncated) {+ throw new ReviewPreconditionError({+ code: 'artifact-unavailable',+ message:+ 'The reviewed change set cannot account for every file the turn changed, so Review cannot bind a complete content baseline',+ });+ }+ const artifactPaths = [...new Set([...reviewReadPaths, ...changeSetContent.paths])];const artifactFingerprintOptions = { linkConfinementRoot: sourceWorkingDir };let artifactFingerprint: string;try {@@ -7217,6 +7276,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)'The task files changed before Review started. Run /review again for the current result.',};}+ // The workspace fingerprint pins HEAD, not the base it is compared+ // against; a moved base changes the branch diff without touching it.+ if (!(await reviewBranchBaselineIsCurrent(source.id, evidence.branch))) {+ return {+ code: 'source-files-changed',+ message:+ 'The branch comparison base changed before Review started. Run /review again for the current result.',+ };+ }if (!(await artifactFingerprintIsCurrent(authorizedArtifactPaths,@@ -7268,6 +7336,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)'The task files changed while Review was running. Run /review again for the current result.',};}+ if (!(await reviewBranchBaselineIsCurrent(source.id, evidence.branch))) {+ return {+ code: 'source-files-changed',+ message:+ 'The branch comparison base changed while Review was running. Run /review again for the current result.',+ };+ }if (!(await artifactFingerprintIsCurrent(authorizedArtifactPaths,diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.tsindex 9e4be28bc6..8e243eb66d 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts@@ -5,11 +5,14 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-const { readReviewDataMock, reviewRows, utilityProcessFork } = vi.hoisted(() => ({- readReviewDataMock: vi.fn(),- reviewRows: [] as Array<Record<string, unknown>>,- utilityProcessFork: vi.fn(),-}));+const { readReviewDataMock, readReviewBranchDiffMock, reviewRows, utilityProcessFork } = vi.hoisted(+ () => ({+ readReviewDataMock: vi.fn(),+ readReviewBranchDiffMock: vi.fn(),+ reviewRows: [] as Array<Record<string, unknown>>,+ utilityProcessFork: vi.fn(),+ }),+);vi.mock('electron', () => ({ utilityProcess: { fork: utilityProcessFork } }));vi.mock('../../localDb/client/current.js', () => ({@@ -25,7 +28,10 @@ vi.mock('../../localDb/client/current.js', () => ({},}),}));-vi.mock('../../git-review/ipc.js', () => ({ readReviewData: readReviewDataMock }));+vi.mock('../../git-review/ipc.js', () => ({+ readReviewData: readReviewDataMock,+ readReviewBranchDiff: readReviewBranchDiffMock,+}));vi.mock('../../turn-change-set/store.js', () => ({listTurnChangeSets: async () => [],getTurnChangeSets: async () => [],@@ -61,6 +67,7 @@ import {loadReviewEvidence,readReviewContextFingerprint,readReviewWorkspaceSnapshot,+ reviewBranchBaselineIsCurrent,reviewWorkspaceFingerprintIsCurrent,} from '../reviewEvidence.js';@@ -92,12 +99,24 @@ async function tempDir(): Promise<string> {beforeEach(() => {readReviewDataMock.mockResolvedValue(nonGitReviewData());+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: null,+ baseOid: null,+ headOid: null,+ mergeBaseOid: null,+ candidates: [],+ diffs: [],+ capped: null,+ warning: null,+ });utilityProcessFork.mockImplementation(() => new RejectingPdfUtility());});afterEach(async () => {reviewRows.splice(0);readReviewDataMock.mockReset();+ readReviewBranchDiffMock.mockReset();utilityProcessFork.mockReset();await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));});@@ -182,6 +201,101 @@ function cappedReviewData(repoRoot: string, filePath: string): ReviewData {};}+function branchFileDiff(filePath: string) {+ return {+ id: `branch:${filePath}`,+ source: 'branch' as const,+ path: filePath,+ oldPath: null,+ status: 'modified' as const,+ kind: 'text' as const,+ size: 12,+ additions: 1,+ deletions: 0,+ isBinary: false,+ isSubmodule: false,+ isTooLarge: false,+ mode: { old: null, new: null },+ index: { oldOid: null, newOid: null },+ rawHeader: `diff --git a/${filePath} b/${filePath}`,+ rawPatch: '@@ -1 +1 @@\n-old\n+new',+ hunks: [],+ error: null,+ };+}++/** A dirty workspace whose only change is a binary file — a diff with no content. */+function binaryReviewData(repoRoot: string, filePath: string): ReviewData {+ const data = cappedReviewData(repoRoot, filePath);+ return {+ ...data,+ diffs: {+ staged: [],+ unstaged: [+ {+ ...branchFileDiff(filePath),+ id: `unstaged:${filePath}`,+ source: 'unstaged' as const,+ kind: 'binary' as const,+ isBinary: true,+ rawHeader: '',+ rawPatch: '',+ additions: 0,+ deletions: 0,+ error: 'Binary file',+ },+ ],+ capped: { staged: null, unstaged: null },+ },+ };+}++/** A Git workspace with everything committed, which is when branch review applies. */+function cleanGitReviewData(repoRoot: 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: 1, behind: 0, upstream: 'origin/main', stale: false },+ disabledReason: null,+ disabledMessage: null,+ resolutionChain: [],+ };+ return {+ scope,+ status: {+ scope,+ files: [],+ stagedCount: 0,+ unstagedCount: 0,+ untrackedCount: 0,+ unmergedCount: 0,+ inProgress: [],+ writeDisabledReasons: [],+ dirty: false,+ },+ diffs: { staged: [], unstaged: [], capped: { staged: null, unstaged: null } },+ summary: {+ sessionId: 'source',+ disabledReason: null,+ disabledMessage: null,+ totalFiles: 0,+ stagedFiles: 0,+ unstagedFiles: 0,+ untrackedFiles: 0,+ unmergedFiles: 0,+ dirty: false,+ },+ };+}+function nonGitReviewData(): ReviewData {const scope = {sessionId: 'source',@@ -255,6 +369,52 @@ describe('readReviewWorkspaceSnapshot', () => {expect(after?.fingerprint).not.toBe(before?.fingerprint);});+ it('changes the fingerprint for a same-size binary replacement', async () => {+ // A binary diff carries no patch and no blob oids — only path, kind and+ // size — so without its own content hash, swapping the bytes for different+ // ones of the same length would leave the Git digest identical.+ 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(binaryReviewData(repoRoot, relativePath));++ const before = await readReviewWorkspaceSnapshot('source');+ await fs.writeFile(file, Buffer.from([5, 6, 7, 8]));+ const after = await readReviewWorkspaceSnapshot('source');++ expect(after?.workspace).toEqual(before?.workspace);+ expect(after?.fingerprint).not.toBe(before?.fingerprint);+ });++ 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 whole+ // dirty workspace unreviewable. The cost of excluding it — edits inside+ // the submodule are not bound — is stated at the call site and tracked in+ // #2463; it is not offset by the porcelain status, which keeps no oid.+ const repoRoot = await tempDir();+ const submodulePath = 'vendor/lib';+ await fs.mkdir(path.join(repoRoot, submodulePath), { recursive: true });+ const data = binaryReviewData(repoRoot, submodulePath);+ readReviewDataMock.mockResolvedValue({+ ...data,+ diffs: {+ ...data.diffs,+ unstaged: data.diffs.unstaged.map((diff) => ({+ ...diff,+ kind: 'unrenderable' as const,+ isBinary: false,+ isSubmodule: true,+ error: null,+ })),+ },+ });++ await expect(readReviewWorkspaceSnapshot('source')).resolves.toBeTruthy();+ });+it('marks prepared Git evidence stale when the workspace changes before launch', async () => {const repoRoot = await tempDir();const relativePath = 'tracked.ts';@@ -629,4 +789,480 @@ describe('loadReviewEvidence attachment boundaries', () => {expect.objectContaining({ type: 'image', base64: 'c2Vjb25k', originalName: 'same.png' }),]);});++ it('does not read the branch diff while uncommitted work exists', async () => {+ // Uncommitted work is the review target; reading the branch as well would+ // bury it under commits the user is not asking about.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cappedReviewData(repoRoot, 'src/a.ts'));++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(readReviewBranchDiffMock).not.toHaveBeenCalled();+ expect(evidence.branch).toBeNull();+ });++ it('reports why a too-large branch diff is missing instead of falling back silently', async () => {+ // A guard like too-many-files returns a resolved base with no entries,+ // which looks identical to an unchanged branch. Falling through without+ // saying so would present one turn as the whole branch review.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [],+ diffs: [],+ capped: null,+ warning: { code: 'too-many-files', message: 'too many files' },+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch).toBeNull();+ expect(evidence.branchUnavailableReason).toBe('too-many-files');+ });++ it('refuses to compare against an unrelated local branch', async () => {+ // Unattended review picks no base. With no upstream or default present the+ // picker falls back to the first ordinary local branch, and presenting that+ // diff as "the branch's work" would be worse than presenting nothing.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'some-other-feature',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [+ {+ refName: 'some-other-feature',+ shortName: 'some-other-feature',+ kind: 'local',+ remote: null,+ oid: 'b'.repeat(40),+ },+ ],+ diffs: [],+ capped: null,+ warning: null,+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch).toBeNull();+ expect(evidence.branchUnavailableReason).toBe('ambiguous-base');+ });++ it('refuses to compare against an unrelated remote branch', async () => {+ // Same rule as the local case: a candidate that merely sorted first is not+ // a base. `origin/foo` is no more meaningful than `some-other-feature`.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/foo',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [+ {+ refName: 'origin/foo',+ shortName: 'foo',+ kind: 'remote',+ remote: 'origin',+ oid: 'b'.repeat(40),+ },+ ],+ diffs: [],+ capped: null,+ warning: null,+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch).toBeNull();+ expect(evidence.branchUnavailableReason).toBe('ambiguous-base');+ });++ it('accepts origin/main when the remote publishes no HEAD', async () => {+ // Candidates carry `shortName === refName`, so the remote prefix has to be+ // stripped rather than re-attached; getting that backwards rejects the most+ // ordinary base there is and silently drops the review back to one turn.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [+ {+ refName: 'origin/main',+ shortName: 'origin/main',+ kind: 'remote',+ remote: 'origin',+ oid: 'b'.repeat(40),+ isDefaultBranch: true,+ },+ ],+ diffs: [branchFileDiff('src/a.ts')],+ capped: null,+ warning: null,+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch?.baseRef).toBe('origin/main');+ });++ it('accepts a configured default branch under any name', async () => {+ // `init.defaultBranch` can name anything. Only the branch reader can read+ // that config, so the flag it sets must be honoured rather than second-+ // guessed by matching against main/master here.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/stable',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [+ {+ refName: 'origin/stable',+ shortName: 'origin/stable',+ kind: 'remote',+ remote: 'origin',+ oid: 'b'.repeat(40),+ isDefaultBranch: true,+ },+ ],+ diffs: [branchFileDiff('src/a.ts')],+ capped: null,+ warning: null,+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch?.baseRef).toBe('origin/stable');+ });++ it('counts branch files before redaction, including an all-sensitive branch', async () => {+ // Deriving the count from the sanitized list would report zero here, which+ // resolveTargetKind reads as "no changes" and downgrades to a `task`+ // review even though the branch is the selected evidence. The count is+ // coverage metadata; the patches themselves stay excluded.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [+ {+ refName: 'origin/main',+ shortName: 'origin/main',+ kind: 'remote-default',+ remote: 'origin',+ oid: 'b'.repeat(40),+ },+ ],+ diffs: [branchFileDiff('.env'), branchFileDiff('deploy/id_rsa')],+ capped: null,+ warning: null,+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch?.fileCount).toBe(2);+ expect(evidence.branch?.sensitiveFilesOmitted).toBe(2);+ expect(evidence.branch?.diffs).toEqual([]);+ });++ it('refuses a branch whose last segment merely looks like a default', async () => {+ // `feature/main` is an ordinary branch. Judging by basename would let it+ // pass as a default and reintroduce the unrelated-sibling comparison.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'feature/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [+ {+ refName: 'feature/main',+ shortName: 'feature/main',+ kind: 'local',+ remote: null,+ oid: 'b'.repeat(40),+ },+ ],+ diffs: [],+ capped: null,+ warning: null,+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch).toBeNull();+ expect(evidence.branchUnavailableReason).toBe('ambiguous-base');+ });++ it('accepts the branch upstream as a base', async () => {+ // An upstream is chosen by the user's own tracking config, so it is+ // meaningful even when its name looks nothing like a default.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/release-2026',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [+ {+ refName: 'origin/release-2026',+ shortName: 'release-2026',+ kind: 'upstream',+ remote: 'origin',+ oid: 'b'.repeat(40),+ },+ ],+ diffs: [branchFileDiff('src/a.ts')],+ capped: null,+ warning: null,+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch?.baseRef).toBe('origin/release-2026');+ });++ it('accepts a local default branch as a base', async () => {+ // A repository with no remote still has a meaningful base when it is named+ // like the default; rejecting it would disable branch review offline.+ const repoRoot = await tempDir();+ readReviewDataMock.mockResolvedValue(cleanGitReviewData(repoRoot));+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [+ {+ refName: 'main',+ shortName: 'main',+ kind: 'local',+ remote: null,+ oid: 'b'.repeat(40),+ isDefaultBranch: true,+ },+ ],+ diffs: [branchFileDiff('src/a.ts')],+ capped: null,+ warning: null,+ });++ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: repoRoot,+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(evidence.branch?.baseRef).toBe('main');+ });++ it('accepts a base tip that moved without moving the merge base', async () => {+ // Fetching commits onto the base after this branch diverged advances the+ // tip but not the merge base, so the patch is byte-for-byte the same.+ // Failing here would throw away a perfectly valid review.+ const branch = {+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ fileCount: 1,+ diffs: [],+ capped: null,+ };+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/main',+ baseOid: 'd'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [],+ diffs: [],+ capped: null,+ warning: null,+ });++ await expect(reviewBranchBaselineIsCurrent('source', branch)).resolves.toBe(true);+ });++ it('detects a moved merge base even though HEAD did not change', async () => {+ // The workspace fingerprint pins the source HEAD. A merge base that moves+ // changes what the branch diff means without touching HEAD — so freshness+ // has to check the baseline separately.+ const branch = {+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ fileCount: 1,+ diffs: [],+ capped: null,+ };+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/main',+ baseOid: 'd'.repeat(40),+ mergeBaseOid: 'e'.repeat(40),+ candidates: [],+ diffs: [],+ capped: null,+ warning: null,+ });++ await expect(reviewBranchBaselineIsCurrent('source', branch)).resolves.toBe(false);+ });++ it('accepts an unchanged comparison base', async () => {+ const branch = {+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ fileCount: 1,+ diffs: [],+ capped: null,+ };+ readReviewBranchDiffMock.mockResolvedValue({+ scope: null,+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ candidates: [],+ diffs: [],+ capped: null,+ warning: null,+ });++ await expect(reviewBranchBaselineIsCurrent('source', branch)).resolves.toBe(true);+ });++ it('fails closed when the comparison base cannot be re-read', async () => {+ readReviewBranchDiffMock.mockRejectedValue(new Error('git fetch in progress'));++ await expect(+ reviewBranchBaselineIsCurrent('source', {+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ fileCount: 1,+ diffs: [],+ capped: null,+ }),+ ).resolves.toBe(false);+ });++ it('does not read the branch diff for a non-Git task', async () => {+ const evidence = await loadReviewEvidence({+ sourceSessionId: 'source',+ workingDir: '/tmp/non-git-review',+ attachments: [],+ explicitArtifactGrant: {+ paths: [],+ pathIdentities: new Map(),+ inlineAttachmentKeys: [],+ },+ });++ expect(readReviewBranchDiffMock).not.toHaveBeenCalled();+ expect(evidence.branch).toBeNull();+ });});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewEvidenceSafety.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewEvidenceSafety.test.tsindex 94553af280..29e2007c41 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidenceSafety.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidenceSafety.test.ts@@ -1,8 +1,14 @@+import path from 'node:path';+import { describe, expect, it } from 'vitest';import type { FileDiff, ReviewDiffBucket } from '../../../shared/gitReviewWire.js';import type { TurnChangeSetDetail } from '../../../shared/turnChangeSet.js';-import { sanitizeReviewChangeSet, sanitizeReviewDiffBucket } from '../reviewEvidenceSafety.js';+import {+ reviewChangeSetContentPaths,+ sanitizeReviewChangeSet,+ sanitizeReviewDiffBucket,+} from '../reviewEvidenceSafety.js';function fileDiff(overrides: Partial<FileDiff> = {}): FileDiff {return {@@ -115,3 +121,211 @@ describe('review Git evidence safety', () => {expect(JSON.stringify(result.value)).not.toContain('TOKEN=secret');});});++describe('review change set content paths', () => {+ // path.resolve keeps expectations platform-native: '/repo' becomes 'D:\repo'+ // on the Windows CI runner, matching what a real change set records there.+ const abs = (...segments: string[]) => path.resolve(...segments);++ function changeSet(+ files: TurnChangeSetDetail['files'],+ cwd = '/repo',+ overrides: Partial<TurnChangeSetDetail> = {},+ ): TurnChangeSetDetail {+ return {+ id: 'turn-1',+ sessionId: 'source-1',+ anchorClientId: 'message-1',+ provider: 'codex',+ providerTurnId: null,+ cwd,+ state: 'complete',+ workspaceState: 'applied',+ isReversible: true,+ incompleteReasons: [],+ createdAt: 1,+ completedAt: 2,+ files,+ fileCount: files.length,+ additions: 0,+ deletions: 0,+ diffs: [],+ ...overrides,+ };+ }++ function file(path: string, oldPath: string | null = null): TurnChangeSetDetail['files'][number] {+ return { id: path, path, oldPath, status: 'modified', additions: 1, deletions: 0 };+ }++ it('resolves changed and renamed-from paths against the recorded cwd', () => {+ expect(+ reviewChangeSetContentPaths(+ changeSet([file('src/a.ts'), file('docs/new.md', 'docs/old.md')]),+ '/other',+ ).paths.sort(),+ ).toEqual(+ [abs('/repo', 'docs/new.md'), abs('/repo', 'docs/old.md'), abs('/repo', 'src/a.ts')].sort(),+ );+ });++ it('returns nothing when there is no change set', () => {+ expect(reviewChangeSetContentPaths(null, '/repo')).toEqual({ paths: [], truncated: false });+ });++ it('falls back to the working directory when the change set has no cwd', () => {+ expect(+ reviewChangeSetContentPaths(changeSet([file('src/a.ts')], ''), '/fallback').paths,+ ).toEqual([abs('/fallback', 'src/a.ts')]);+ });++ it('refuses escapes, absolute paths and credential files', () => {+ expect(+ reviewChangeSetContentPaths(+ changeSet([+ file('../outside.ts'),+ file('a/../../outside.ts'),+ file('/etc/passwd'),+ file('.env'),+ file('config/credentials.json'),+ ]),+ '/repo',+ ).paths,+ ).toEqual([]);+ });++ it('keeps ordinary filenames that begin with two dots', () => {+ // `..config` stays inside the root; only a bare `..` or a `../` prefix+ // escapes it. Dropping these silently left them out of the baseline while+ // still counting toward completeness, so edits to them went unnoticed.+ expect(+ reviewChangeSetContentPaths(+ changeSet([file('..config/result.md'), file('..report')]),+ '/repo',+ ).paths.sort(),+ ).toEqual([abs('/repo', '..config/result.md'), abs('/repo', '..report')].sort());+ });++ it('keeps a confined new path when only its rename source is unsafe', () => {+ // Each side is validated on its own: the file really did change and belongs+ // in the baseline, while the escaping rename source is simply dropped.+ expect(+ reviewChangeSetContentPaths(changeSet([file('renamed.ts', '../secret.ts')]), '/repo').paths,+ ).toEqual([abs('/repo', 'renamed.ts')]);+ });++ it('deduplicates paths reached through more than one entry', () => {+ expect(+ reviewChangeSetContentPaths(changeSet([file('src/a.ts'), file('src/a.ts')]), '/repo').paths,+ ).toEqual([abs('/repo', 'src/a.ts')]);+ });++ it('recovers files that the summarized list dropped but the patch still names', () => {+ // Persisted details are rebuilt through toSummary(), which caps `files` at+ // 50 while `diffs` keeps the full patch. Reading only `files` would leave+ // the 51st file onward outside the baseline.+ const result = reviewChangeSetContentPaths(+ changeSet([file('kept.ts')], '/repo', {+ fileCount: 2,+ diffs: [fileDiff({ path: 'dropped.ts' })],+ }),+ '/repo',+ );++ expect(result.paths.sort()).toEqual(+ [abs('/repo', 'dropped.ts'), abs('/repo', 'kept.ts')].sort(),+ );+ expect(result.truncated).toBe(false);+ });++ it('reports truncation when the change set names fewer files than it counts', () => {+ const result = reviewChangeSetContentPaths(+ changeSet([file('kept.ts')], '/repo', { fileCount: 51 }),+ '/repo',+ );++ expect(result.paths).toEqual([abs('/repo', 'kept.ts')]);+ expect(result.truncated).toBe(true);+ });++ it('does not treat a rename as two files when judging truncation', () => {+ // A rename contributes two names for one recorded file; counting raw+ // entries would hide a real truncation or invent one.+ expect(+ reviewChangeSetContentPaths(changeSet([file('new.ts', 'old.ts')], '/repo'), '/repo')+ .truncated,+ ).toBe(false);+ });++ it('does not let a rename hide a file the summary dropped', () => {+ // Counting path names would reach 2 here (new.ts + old.ts) and call a+ // 2-file change set complete. Counting file identities keeps it at 1.+ expect(+ reviewChangeSetContentPaths(+ changeSet([file('new.ts', 'old.ts')], '/repo', { fileCount: 2 }),+ '/repo',+ ).truncated,+ ).toBe(true);+ });++ it('treats deliberately redacted credential files as accounted for', () => {+ // sanitizeReviewChangeSet drops credential entries but keeps fileCount, so+ // a redacted change set looks truncated from the outside. Reviewing the+ // remaining deliverables must stay possible.+ const sanitized = sanitizeReviewChangeSet(+ changeSet([file('src/a.ts'), file('.env')], '/repo', {+ diffs: [fileDiff({ path: 'src/a.ts' }), fileDiff({ path: '.env' })],+ }),+ );++ const result = reviewChangeSetContentPaths(sanitized.value, '/repo');++ expect(sanitized.value?.incompleteReasons).toContain('sensitive-file');+ expect(result.paths).toEqual([abs('/repo', 'src/a.ts')]);+ expect(result.truncated).toBe(false);+ });++ it('fails closed when the turn changed something it could not enumerate', () => {+ // An opaque tool leaves no entry and no count, so a size comparison alone+ // sees a complete zero-file change set and would bind an empty baseline.+ const result = reviewChangeSetContentPaths(+ changeSet([], '/repo', { fileCount: 0, incompleteReasons: ['opaque-tool'] }),+ '/repo',+ );++ expect(result.paths).toEqual([]);+ expect(result.truncated).toBe(true);+ });++ it('fails closed for an unenumerable gap even alongside recorded files', () => {+ expect(+ reviewChangeSetContentPaths(+ changeSet([file('src/a.ts')], '/repo', { incompleteReasons: ['diff-too-large'] }),+ '/repo',+ ).truncated,+ ).toBe(true);+ });++ it('does not treat redaction alone as an unenumerable gap', () => {+ // sensitive-file is deliberate and accounted for; it must not fail closed.+ expect(+ reviewChangeSetContentPaths(+ changeSet([file('src/a.ts')], '/repo', { incompleteReasons: ['sensitive-file'] }),+ '/repo',+ ).truncated,+ ).toBe(false);+ });++ it('still fails closed when redaction cannot explain the whole shortfall', () => {+ // One entry was redacted, but the change set claims three files — the third+ // is simply missing and no baseline can cover it.+ const sanitized = sanitizeReviewChangeSet(+ changeSet([file('src/a.ts'), file('.env')], '/repo', {+ fileCount: 3,+ diffs: [fileDiff({ path: 'src/a.ts' }), fileDiff({ path: '.env' })],+ }),+ );++ expect(reviewChangeSetContentPaths(sanitized.value, '/repo').truncated).toBe(true);+ });+});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.tsindex 11d3bdb2d9..7058ede05d 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts@@ -47,10 +47,42 @@ describe('Review external input wiring', () => {expect(reviewStartSource).not.toContain('MAKER_INVOKE.INPUT_ENQUEUE');});- it('binds Git reviews to readable workspace content outside the Git snapshot', () => {- expect(registerSource).toContain(+ it('fingerprints reviewed evidence instead of scanning the whole workspace', () => {+ // A full-workspace content hash cannot stay inside its byte budget on a+ // real checkout, and unrelated edits must not invalidate a finished review.+ expect(registerSource).not.toContain('const artifactPaths = [...reviewReadPaths, sourceWorkingDir];',);+ // When the change set IS the evidence, its files are bound: Git evidence+ // hashes identity, status and patches, so an ignored deliverable built by+ // the reviewed turn is covered by neither fingerprint otherwise.+ expect(registerSource).toContain(+ 'const artifactPaths = [...new Set([...reviewReadPaths, ...changeSetContent.paths])];',+ );+ // A change set that cannot account for its own files is not a usable+ // baseline; publishing against it would skip the truncated remainder.+ // A Git fingerprint is not an exemption — it cannot see ignored files,+ // so a dropped entry that is an ignored deliverable is covered by neither.+ // The change set contributes nothing at all unless it is the selected+ // evidence: an unrelated turn must not refuse the review through the gate,+ // nor bind its own paths into the fingerprint and invalidate the result.+ expect(registerSource).toContain('const changeSetIsReviewed = !evidence.workspace?.dirty');+ // Matched with a regex rather than a literal: the repository checks out+ // with CRLF on Windows, so an embedded \n would never match there.+ expect(registerSource).toMatch(+ /\?\s*reviewChangeSetContentPaths\(evidence\.changeSet, sourceWorkingDir\)\s*:\s*\{ paths: \[\], truncated: false \};/,+ );+ expect(registerSource).toContain('if (changeSetContent.truncated) {');+ // The workspace fingerprint pins HEAD, not the base being compared against,+ // so both gates must recheck the branch baseline as well.+ expect(+ registerSource.match(+ /if \(!\(await reviewBranchBaselineIsCurrent\(source\.id, evidence\.branch\)\)\)/g,+ ),+ ).toHaveLength(2);+ expect(registerSource).not.toContain(+ 'if (changeSetContent.truncated && !evidence.workspaceFingerprint) {',+ );expect(registerSource).toContain('const artifactFingerprintOptions = { linkConfinementRoot: sourceWorkingDir };',);@@ -62,8 +94,15 @@ describe('Review external input wiring', () => {expect(registerSource.indexOf('if (!(await completeArtifactFingerprintIsCurrent()))'),).toBeLessThan(registerSource.indexOf('verifyBeforePublish: async'));- expect(registerSource).not.toContain(- '...(evidence.workspaceFingerprint ? [] : [sourceWorkingDir])',+ });++ it('reports a failed branch load instead of claiming there is nothing to review', () => {+ // A context-free worktree exits before the prompt is built, so the+ // prompt-level warning never runs; without this the user is told there is+ // no work when in fact the branch could not be loaded.+ // Regex, not a literal: the repository checks out with CRLF on Windows.+ expect(registerSource).toMatch(+ /evidence\.branchUnavailableReason\s*\?\s*`Review could not load this branch's changes/,);});diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewPrompt.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewPrompt.test.tsindex 79a5402cea..cbe3126387 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewPrompt.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewPrompt.test.ts@@ -300,4 +300,94 @@ describe('buildReviewPrompt', () => {expect(result.prompt).toContain('</untrusted-review-focus>');expect(result.prompt).toContain('用户特别关注”、“显式成果”');});++ it('reviews the branch against its base once the work is committed', () => {+ // A committed branch leaves a clean tree, so without branch evidence the+ // review would silently fall back to whatever the last turn happened to be.+ const result = buildReviewPrompt({+ context: [],+ workspace: null,+ branch: {+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ fileCount: 1,+ diffs: [fileDiff({ source: 'branch', path: 'src/feature.ts' })],+ capped: null,+ },+ changeSet: changeSet({ diffs: [fileDiff({ path: 'src/unrelated.ts' })] }),+ artifacts: [],+ });++ expect(result.targetKind).toBe('changes');+ expect(result.prompt).toContain('origin/main');+ expect(result.prompt).toContain('src/feature.ts');+ // The last turn must not stand in for the branch when both are present.+ expect(result.prompt).not.toContain('src/unrelated.ts');+ });++ it('prefers uncommitted work over the branch diff', () => {+ // Uncommitted changes are what the user is looking at right now.+ const result = buildReviewPrompt({+ context: [],+ workspace: {+ dirty: true,+ totalFiles: 1,+ stagedFiles: 0,+ unstagedFiles: 1,+ untrackedFiles: 0,+ disabledReason: null,+ diffs: {+ staged: [],+ unstaged: [fileDiff({ source: 'unstaged', path: 'src/wip.ts' })],+ capped: { staged: null, unstaged: null },+ },+ },+ branch: {+ baseRef: 'origin/main',+ baseOid: 'b'.repeat(40),+ mergeBaseOid: 'c'.repeat(40),+ fileCount: 1,+ diffs: [fileDiff({ source: 'branch', path: 'src/committed.ts' })],+ capped: null,+ },+ changeSet: null,+ artifacts: [],+ });++ expect(result.prompt).toContain('src/wip.ts');+ expect(result.prompt).not.toContain('src/committed.ts');+ });++ it('says so when the branch diff was unreadable and there is no change set', () => {+ // Context alone is enough for the preflight to launch, so this path is+ // reachable; without the note the reviewer would be told there is simply+ // no Git evidence and conclude the branch is unchanged.+ const result = buildReviewPrompt({+ context: [{ role: 'user', text: '看看这个分支' }],+ workspace: null,+ branch: null,+ branchUnavailableReason: 'too-many-files',+ changeSet: null,+ artifacts: [],+ });++ expect(result.prompt).toContain('too-many-files');+ expect(result.prompt).toContain('不得据此认为本分支没有变更');+ });++ it('says so when the branch diff was expected but unreadable', () => {+ // Falling back silently would let a one-turn review look like a full one.+ const result = buildReviewPrompt({+ context: [],+ workspace: null,+ branch: null,+ branchUnavailableReason: 'no-base-candidates',+ changeSet: changeSet({ diffs: [fileDiff()] }),+ artifacts: [],+ });++ expect(result.prompt).toContain('no-base-candidates');+ expect(result.prompt).toContain('只是最近一轮');+ });});diff --git a/apps/desktop/src/main/reviewer/reviewEvidence.ts b/apps/desktop/src/main/reviewer/reviewEvidence.tsindex 8da763422d..a834979fa9 100644--- a/apps/desktop/src/main/reviewer/reviewEvidence.ts+++ b/apps/desktop/src/main/reviewer/reviewEvidence.ts@@ -11,12 +11,13 @@ import { messages } from '../localDb/schema.js';import * as imageCacheStore from '../imageCacheStore.js';import * as cindyChatAttachments from '../cindy-media/chatAttachments.js';import * as cindyMediaBlobStore from '../cindy-media/blobStore.js';-import { readReviewData } from '../git-review/ipc.js';+import { readReviewBranchDiff, readReviewData } from '../git-review/ipc.js';import { getTurnChangeSets, listTurnChangeSets } from '../turn-change-set/store.js';import type { TurnChangeSetDetail } from '../../shared/turnChangeSet.js';import { readReviewRunFromAgentMeta } from '../../shared/reviewRun.js';import type {ReviewArtifactLabel,+ ReviewBranchEvidence,ReviewContextMessage,ReviewWorkspaceEvidence,} from './reviewPrompt.js';@@ -66,6 +67,8 @@ export interface LoadedReviewEvidence {contextFingerprint: string;workspace: ReviewWorkspaceEvidence | null;workspaceFingerprint: string | null;+ branch: ReviewBranchEvidence | null;+ branchUnavailableReason?: string;changeSet: TurnChangeSetDetail | null;artifacts: ReviewArtifactLabel[];artifactExcerpts: ReviewArtifactExcerpt[];@@ -103,6 +106,85 @@ function mapReviewWorkspace(};}+/**+ * The branch's own commits, read only when the tree is clean.+ *+ * With uncommitted work present that work is the review target. Once it is+ * committed the tree goes clean and the last turn is no longer a faithful+ * stand-in for the branch — reviewing it would silently cover one turn while+ * appearing to cover the whole branch.+ */+async function loadReviewBranchEvidence(+ sessionId: string,+ readBranchDiff: typeof readReviewBranchDiff,+): Promise<{ branch: ReviewBranchEvidence | null; unavailableReason?: string }> {+ let data: Awaited<ReturnType<typeof readReviewBranchDiff>>;+ try {+ data = await readBranchDiff(sessionId, null);+ } catch (error) {+ return { branch: null, unavailableReason: error instanceof Error ? error.message : '读取失败' };+ }+ if (!data.baseRef || !data.mergeBaseOid) {+ return { branch: null, unavailableReason: data.warning?.code ?? '未找到基线分支' };+ }+ // Nobody picks the base here — unlike the Git review pane, this runs+ // unattended. With no recognized default present, the picker just takes the+ // first remaining candidate in sort order, which can be an unrelated sibling+ // (`some-feature`, `origin/foo`); presenting that comparison as "the branch's+ // work" is worse than presenting nothing.+ //+ // So require a base that identifies itself rather than one that merely sorted+ // first: the repository's default branch, or the branch's own upstream. The+ // default flag comes from the branch reader because `init.defaultBranch` can+ // name anything — recognizing defaults by name here would reject a repository+ // that calls its default `stable`.+ const chosen = data.candidates.find((candidate) => candidate.refName === data.baseRef);+ const baseIdentifiesItself =+ !chosen ||+ chosen.isDefaultBranch === true ||+ chosen.kind === 'remote-default' ||+ chosen.kind === 'upstream';+ if (!baseIdentifiesItself) {+ return { branch: null, unavailableReason: 'ambiguous-base' };+ }+ const sanitized = sanitizeReviewDiffBucket({+ staged: data.diffs,+ unstaged: [],+ capped: { staged: data.capped, unstaged: null },+ });+ const diffs = sanitized.value.staged;+ const capped = sanitized.value.capped?.staged ?? null;+ // Count what the branch changed, not what survived redaction. `capped.stats`+ // is already a pre-redaction total, so deriving the uncapped count from the+ // sanitized list would make the two paths disagree — and a branch whose+ // every changed path is sensitive would report zero, which+ // `resolveTargetKind` reads as "no changes" and downgrades the run to a+ // `task` review even though the branch is the selected evidence. The count+ // is coverage metadata; the content stays excluded either way, and the+ // prompt states how many were withheld via `sensitiveFilesOmitted`.+ const fileCount = capped ? capped.stats.fileCount : data.diffs.length;+ if (fileCount === 0) {+ // A guard like `too-many-files` also yields zero entries, but it means the+ // branch changed too much to load — not that it changed nothing. Falling+ // through silently would present one turn as the branch review.+ if (data.warning) return { branch: null, unavailableReason: data.warning.code };+ // Nothing of its own to review; fall through to the last turn.+ return { branch: null };+ }+ return {+ branch: {+ baseRef: data.baseRef,+ baseOid: data.baseOid,+ mergeBaseOid: data.mergeBaseOid,+ fileCount,+ diffs,+ capped,+ sensitiveFilesOmitted: sanitized.omittedSensitiveFiles,+ ...(data.warning ? { unavailableReason: data.warning.code } : {}),+ },+ };+}+interface ReviewWorkspaceSnapshot {workspace: ReviewWorkspaceEvidence;fingerprint: string | null;@@ -119,12 +201,50 @@ const defaultReviewWorkspaceSnapshotDeps: ReviewWorkspaceSnapshotDeps = {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[])- : [],+/**+ * Dirty paths whose Git evidence does not carry their content.+ *+ * A capped bucket replaces patches with summaries, and a binary, submodule or+ * over-limit file is recorded with an empty patch and no blob oids — only path,+ * kind and size. Swapping such a file for different bytes of the same size+ * leaves the Git digest identical, so the reviewer could read the old bytes and+ * still pass both freshness gates. These paths need a content hash of their own.+ */+function workspacePathsWithoutContent(workspace: ReviewWorkspaceEvidence): string[] {+ const capped = [workspace.diffs.capped?.staged, workspace.diffs.capped?.unstaged].flatMap(+ (bucket) =>+ bucket+ ? bucket.files.flatMap((file) => [file.path, file.oldPath].filter(Boolean) as string[])+ : [],);+ const contentless = [...workspace.diffs.staged, ...workspace.diffs.unstaged]+ // Submodules are excluded on purpose: a gitlink is a directory, and the+ // content fingerprinter only accepts regular files, so passing one would+ // abort evidence loading outright — an initialized submodule anywhere in+ // the workspace would make Review refuse to run at all.+ //+ // The accepted cost, stated plainly: edits living *inside* a dirty+ // submodule are not bound. Porcelain v2 spends one boolean on "the+ // submodule has modified content" and FileStatus keeps neither that flag+ // nor any object id, so replacing one internal edit with another leaves+ // every value this digest sees unchanged. Closing it needs an identity+ // read this layer does not have — the gitlink oid plus a recursive digest+ // of the inner worktree — which is a submodule-aware reader, not another+ // path added to the file fingerprinter. That reader is out of scope here+ // and tracked in #2463; do not "fix" this by feeding the directory back+ // in, which is the crash described above.+ //+ // What bounds the exposure meanwhile: inner content is never part of the+ // evidence (diffReader classifies every submodule entry as `submodule`+ // with an empty patch, so no inner bytes reach the prompt), and a file+ // inside a submodule that is explicitly attached lands in reviewReadPaths+ // and is fully content-hashed by fingerprintReviewArtifacts. The unbound+ // case is the reviewer opening an inner file that is neither — the same+ // class as opening any unchanged tracked file, which no fingerprint here+ // covers either.+ .filter((diff) => !diff.rawPatch && !diff.isSubmodule)+ .flatMap((diff) => [diff.path, diff.oldPath].filter(Boolean) as string[]);+ return [...new Set([...capped, ...contentless])];}async function buildReviewWorkspaceSnapshot(@@ -132,13 +252,13 @@ async function buildReviewWorkspaceSnapshot(fingerprintCappedWorkspaceFiles: typeof fingerprintReviewCappedWorkspaceFiles,): Promise<ReviewWorkspaceSnapshot> {const workspace = mapReviewWorkspace(reviewData);- const hasCappedDiff = Boolean(workspace.diffs.capped?.staged || workspace.diffs.capped?.unstaged);+ const contentlessPaths = workspacePathsWithoutContent(workspace);+ // Whichever files needed their own content hash also need the stability+ // re-read below: both are answering "did these bytes hold still?".+ const hasCappedDiff = contentlessPaths.length > 0;const cappedContentFingerprint =hasCappedDiff && reviewData.scope.repoRoot- ? await fingerprintCappedWorkspaceFiles(- reviewData.scope.repoRoot,- cappedWorkspacePaths(workspace),- )+ ? await fingerprintCappedWorkspaceFiles(reviewData.scope.repoRoot, contentlessPaths): null;return {workspace,@@ -219,6 +339,35 @@ export async function reviewWorkspaceFingerprintIsCurrent(return current?.fingerprint === expectedFingerprint;}+/**+ * Whether the branch is still being compared against the same point.+ *+ * The workspace fingerprint covers the source HEAD, not the base: fetching or+ * moving the base branch advances the merge base and changes what the branch+ * diff means, while HEAD stays put. Without this a review could publish+ * findings drawn from a comparison that no longer exists.+ */+export async function reviewBranchBaselineIsCurrent(+ sourceSessionId: string,+ branch: ReviewBranchEvidence | null,+ readBranchDiff: typeof readReviewBranchDiff = readReviewBranchDiff,+): Promise<boolean> {+ if (!branch) return true;+ try {+ const current = await readBranchDiff(sourceSessionId, branch.baseRef);+ // The patch runs from the merge base to the source HEAD, so only those two+ // define the evidence. The base tip is deliberately not compared: fetching+ // commits onto the base after this branch diverged moves it without moving+ // the merge base, and failing the review there would discard a result whose+ // content is byte-for-byte the same. HEAD is covered by the workspace+ // fingerprint.+ return current.baseRef === branch.baseRef && current.mergeBaseOid === branch.mergeBaseOid;+ } catch {+ // An unreadable baseline cannot be proven unchanged.+ return false;+ }+}+function parseJsonRecord(value: unknown): Record<string, unknown> | null {let parsed = value;if (typeof parsed === 'string') {@@ -464,6 +613,12 @@ export async function loadReviewEvidence(input: {const changeSet = sanitizeReviewChangeSet(rawChangeSet).value;const workspaceSnapshot = await readReviewWorkspaceSnapshot(input.sourceSessionId);const workspace = workspaceSnapshot?.workspace ?? null;+ // Only when there is no uncommitted work: that work, when present, is what+ // the user is asking about, and reading the branch as well would bury it.+ const branchEvidence =+ workspace && !workspace.dirty && !workspace.disabledReason+ ? await loadReviewBranchEvidence(input.sourceSessionId, readReviewBranchDiff)+ : { branch: null };const artifacts: ReviewArtifactLabel[] = [];const artifactExcerpts: ReviewArtifactExcerpt[] = [];@@ -652,6 +807,10 @@ export async function loadReviewEvidence(input: {contextFingerprint: fingerprintReviewContextRows(visibleRows),workspace,workspaceFingerprint: workspaceSnapshot?.fingerprint ?? null,+ branch: branchEvidence.branch,+ ...(branchEvidence.unavailableReason+ ? { branchUnavailableReason: branchEvidence.unavailableReason }+ : {}),changeSet,artifacts,artifactExcerpts,diff --git a/apps/desktop/src/main/reviewer/reviewEvidenceSafety.ts b/apps/desktop/src/main/reviewer/reviewEvidenceSafety.tsindex dea4850e23..b8be0f8533 100644--- a/apps/desktop/src/main/reviewer/reviewEvidenceSafety.ts+++ b/apps/desktop/src/main/reviewer/reviewEvidenceSafety.ts@@ -1,3 +1,5 @@+import path from 'node:path';+import { isReviewSensitiveCredentialPath } from '@cindy/maker-core';import type {@@ -76,18 +78,28 @@ export function sanitizeReviewChangeSet(const diffs = filterSensitive<FileDiff>(changeSet.diffs, omitted);const files = filterSensitive<TurnChangeFileSummary>(changeSet.files, omitted);const omittedSensitiveFiles = omitted.size;- return {- value: {- ...changeSet,- diffs,- files,- incompleteReasons:- omittedSensitiveFiles > 0 && !changeSet.incompleteReasons.includes('sensitive-file')- ? [...changeSet.incompleteReasons, 'sensitive-file']- : changeSet.incompleteReasons,- },- omittedSensitiveFiles,+ const value: TurnChangeSetDetail = {+ ...changeSet,+ diffs,+ files,+ incompleteReasons:+ omittedSensitiveFiles > 0 && !changeSet.incompleteReasons.includes('sensitive-file')+ ? [...changeSet.incompleteReasons, 'sensitive-file']+ : changeSet.incompleteReasons,};+ // `fileCount` still counts the removed entries. Record which file identities+ // went away so a later completeness check can tell deliberate redaction from+ // a summary that lost files it can no longer name. Identity is used rather+ // than the source-prefixed evidence key so one file removed from both `files`+ // and `diffs` counts once, matching how `fileCount` counts it.+ if (omittedSensitiveFiles > 0) {+ const redacted = new Set<string>();+ for (const entry of [...changeSet.files, ...changeSet.diffs]) {+ if (hasSensitivePath(entry)) redacted.add(changeEntryIdentity(entry));+ }+ redactedChangeEntries.set(value, redacted);+ }+ return { value, omittedSensitiveFiles };}/** Used for local freshness hashing; sensitive status paths never enter the digest input. */@@ -96,3 +108,124 @@ export function sanitizeReviewStatusFiles<T extends { path: string; oldPath: str): T[] {return files.filter((file) => !hasSensitivePath(file));}++function isSafeRelativeChangePath(rawPath: string): boolean {+ return (+ !!rawPath &&+ !rawPath.includes('\0') &&+ !path.posix.isAbsolute(rawPath) &&+ !path.win32.isAbsolute(rawPath) &&+ !rawPath.split(/[\\/]/).includes('..')+ );+}++/**+ * Gaps where the turn is known to have changed something it could not record.+ *+ * These leave no entry to count, so a change set carrying one can report+ * `fileCount: 0` and still be missing real deliverables. Redaction is excluded:+ * it is deliberate, and the removed files are accounted for separately.+ */+const UNENUMERABLE_CHANGE_REASONS: ReadonlySet<string> = new Set([+ 'opaque-tool',+ 'outside-workspace',+ 'remote-session',+ 'file-too-large',+ 'binary-file',+ 'read-failed',+ 'diff-too-large',+ 'provider-diff-conflict',+ 'concurrent-workspace',+]);++export interface ReviewChangeSetContentPaths {+ paths: string[];+ /**+ * True when the change set cannot account for everything the turn changed, so+ * the returned paths cannot be a complete baseline for it.+ *+ * Two ways that happens. Persisted details are rebuilt through `toSummary()`,+ * which caps `files` at 50 entries while keeping the true `fileCount`. And a+ * turn can change something it could never enumerate at all — an opaque tool,+ * a file too large to diff — which leaves no entry and no count to compare.+ *+ * Deliberate redaction is neither: `sanitizeReviewChangeSet` removes+ * credential entries on purpose and records `sensitive-file`, so those files+ * are accounted for even though they are absent by design.+ */+ truncated: boolean;+}++/** Distinct file identity, so a rename's two path names still count as one file. */+function changeEntryIdentity(entry: { path: string; oldPath: string | null }): string {+ return `${entry.path}\0${entry.oldPath ?? ''}`;+}++/**+ * Entries `sanitizeReviewChangeSet` deliberately removed, keyed by file identity.+ *+ * Redaction keeps the original `fileCount` while dropping credential entries,+ * which from the outside looks identical to summary truncation. Recording the+ * removals as they happen is the only way to tell the two apart afterwards —+ * once sanitized, the entries are simply gone.+ */+const redactedChangeEntries = new WeakMap<TurnChangeSetDetail, Set<string>>();++function redactedChangeEntryCount(changeSet: TurnChangeSetDetail): number {+ return redactedChangeEntries.get(changeSet)?.size ?? 0;+}++/**+ * Absolute paths of the files a change set touches.+ *+ * Git evidence covers tracked content only: its fingerprint hashes Git identity,+ * porcelain status and patches, so a Git-ignored deliverable (a built report, a+ * generated bundle) produced by the reviewed turn is invisible to it. These+ * paths therefore matter even when a Git fingerprint exists — the caller decides+ * which of them Git already covers.+ *+ * Paths come from both `files` and `diffs` because those truncate independently.+ * Each is resolved against the change set's own recorded `cwd` and must stay+ * inside it; anything sensitive, unsafe or outside is dropped rather than+ * silently widening the review's read scope.+ */+export function reviewChangeSetContentPaths(+ changeSet: TurnChangeSetDetail | null,+ workingDir: string,+): ReviewChangeSetContentPaths {+ if (!changeSet) return { paths: [], truncated: false };+ const root = path.resolve(changeSet.cwd || workingDir);+ const paths = new Set<string>();+ // Count file identities, not path names: a rename names two paths for one+ // recorded file, and counting names would let a rename mask a missing file.+ const seen = new Set<string>();+ const collect = (rawPath: string | null | undefined): void => {+ if (typeof rawPath !== 'string' || !isSafeRelativeChangePath(rawPath)) return;+ if (isReviewSensitiveCredentialPath(rawPath)) return;+ const absolute = path.resolve(root, ...rawPath.split(/[\\/]/));+ const relative = path.relative(root, absolute);+ // `..config` is an ordinary filename; only a bare `..` or a `../` prefix+ // actually leaves the root.+ const escapesRoot = relative === '..' || relative.startsWith(`..${path.sep}`);+ if (escapesRoot || path.isAbsolute(relative)) return;+ if (isReviewSensitiveCredentialPath(absolute)) return;+ paths.add(absolute);+ };++ for (const entry of [...changeSet.files, ...changeSet.diffs]) {+ // `files` and `diffs` truncate independently, so an entry missing from the+ // summarized list may still be described by the full unified patch.+ seen.add(changeEntryIdentity(entry));+ collect(entry.path);+ collect(entry.oldPath);+ }++ const unenumerable = changeSet.incompleteReasons.some((reason) =>+ UNENUMERABLE_CHANGE_REASONS.has(reason),+ );+ return {+ paths: [...paths],+ truncated:+ unenumerable || seen.size + redactedChangeEntryCount(changeSet) < changeSet.fileCount,+ };+}diff --git a/apps/desktop/src/main/reviewer/reviewPrompt.ts b/apps/desktop/src/main/reviewer/reviewPrompt.tsindex db41515ce1..21e27639bb 100644--- a/apps/desktop/src/main/reviewer/reviewPrompt.ts+++ b/apps/desktop/src/main/reviewer/reviewPrompt.ts@@ -31,10 +31,39 @@ export interface ReviewWorkspaceEvidence {sensitiveFilesOmitted?: number;}+/**+ * The branch's own work: everything it changed relative to where it forked.+ *+ * A committed branch leaves a clean tree and an unrelated last turn, so without+ * this the review would see no code at all — or worse, review only the most+ * recent turn while appearing to cover the branch.+ */+export interface ReviewBranchEvidence {+ baseRef: string;+ /**+ * Where the comparison was anchored.+ *+ * The source HEAD alone does not pin a branch diff: fetching or moving the+ * base advances the merge base and changes what the branch is compared+ * against, while HEAD stays put. Freshness has to bind these too.+ */+ baseOid: string | null;+ mergeBaseOid: string;+ fileCount: number;+ diffs: FileDiff[];+ capped: ReviewCappedDiffData | null;+ sensitiveFilesOmitted?: number;+ /** Set when the branch diff could not be read completely. */+ unavailableReason?: string;+}+export interface BuildReviewPromptInput {focus?: string;context: ReviewContextMessage[];workspace: ReviewWorkspaceEvidence | null;+ branch?: ReviewBranchEvidence | null;+ /** Why no branch evidence is present, when it should have been. */+ branchUnavailableReason?: string;changeSet: TurnChangeSetDetail | null;artifacts: ReviewArtifactLabel[];artifactsOmitted?: boolean;@@ -146,7 +175,10 @@ function diffSection(diffs: FileDiff[]): string {return parts.join('\n\n');}-function cappedBucketSection(label: '已暂存' | '未暂存', capped: ReviewCappedDiffData): string {+function cappedBucketSection(+ label: '已暂存' | '未暂存' | '分支',+ capped: ReviewCappedDiffData,+): string {const safeFiles = capped.files.filter((file) =>!isReviewSensitiveCredentialPath(file.path) &&@@ -179,6 +211,19 @@ function workspaceDiffSection(workspace: ReviewWorkspaceEvidence): string {return clip(parts.join('\n\n'), MAX_DIFF_CHARS);}+function branchDiffSection(branch: ReviewBranchEvidence): string {+ const parts: string[] = [];+ if (branch.diffs.length > 0) parts.push(diffSection(branch.diffs));+ if (branch.capped) parts.push(cappedBucketSection('分支', branch.capped));+ if (parts.length === 0) {+ if ((branch.sensitiveFilesOmitted ?? 0) > 0) {+ return '(敏感路径变更已从证据中排除,且没有其它可嵌入的文本补丁;不得读取或评价敏感内容。)';+ }+ return '(本分支相对基线有变更,但没有可嵌入的文本补丁;请用只读工具检查列出的文件。)';+ }+ return clip(parts.join('\n\n'), MAX_DIFF_CHARS);+}+function coverageSection(input: BuildReviewPromptInput): string {if (input.workspace?.dirty) {const capped = [@@ -194,33 +239,61 @@ function coverageSection(input: BuildReviewPromptInput): string {? `${summary}${sensitiveNote}${capped.join('、')}变更因体量上限只有摘要;必须用只读工具补查非敏感路径,且不得声称已完整覆盖。`: `${summary}${sensitiveNote}下方包含当前已暂存和未暂存补丁;二进制、超大或不可渲染的非敏感文件仍须用只读工具核对。`;}+ if (input.branch) {+ const summary = `当前 Git 工作区没有未提交变更;下方是本分支相对基线 ${inlineLabel(input.branch.baseRef)} 的全部提交变更(${input.branch.fileCount} 个文件)。`;+ const sensitiveNote =+ (input.branch.sensitiveFilesOmitted ?? 0) > 0+ ? `其中 ${input.branch.sensitiveFilesOmitted} 份敏感路径变更已从证据中排除;不得读取或评价其内容。`+ : '';+ return input.branch.capped+ ? `${summary}${sensitiveNote}部分变更因体量上限只有摘要;必须用只读工具补查非敏感路径,且不得声称已完整覆盖。`+ : `${summary}${sensitiveNote}二进制、超大或不可渲染的非敏感文件仍须用只读工具核对。`;+ }if (input.changeSet) {const workspaceNote = input.workspace? input.workspace.disabledReason? `当前 Git 工作区不可用(${input.workspace.disabledReason})。`: '当前 Git 工作区没有未提交变更。': '当前 Git 工作区证据读取失败或不可用。';+ // A branch diff would be the better evidence here but could not be read;+ // say so explicitly rather than let the last turn stand in for the branch.+ const branchNote = input.branchUnavailableReason+ ? `本分支相对基线的整体差异无法读取(${input.branchUnavailableReason}),因此下方只是最近一轮的证据。`+ : '';const turnNote =input.changeSet.state === 'complete' && input.changeSet.incompleteReasons.length === 0? '下方提供最近一轮捕获的变更证据,但它不等同于当前工作区全量差异。': `最近一轮变更证据可能不完整。状态=${input.changeSet.state};缺口=${input.changeSet.incompleteReasons.join(', ') || '未说明'}。不得声称已完整覆盖。`;- return `${workspaceNote}${turnNote}`;+ return `${workspaceNote}${branchNote}${turnNote}`;}+ // A failed branch read must be stated on every path that reaches here, not+ // only alongside a change set: without one the reviewer would otherwise be+ // told there is simply no Git evidence, hiding that there is work it could+ // not load.+ const branchFailureNote = input.branchUnavailableReason+ ? `本分支相对基线的整体差异无法读取(${input.branchUnavailableReason}),下方没有对应补丁;不得据此认为本分支没有变更。`+ : '';if (input.workspace?.disabledReason) {- return `没有可用的 Git 变更证据(${input.workspace.disabledReason})。这不是跳过审查的理由:请审查当前成果、显式附件和工作目录中的相关文件。`;+ return `没有可用的 Git 变更证据(${input.workspace.disabledReason})。${branchFailureNote}这不是跳过审查的理由:请审查当前成果、显式附件和工作目录中的相关文件。`;}- return '没有可用的 Git 变更证据。这不是跳过审查的理由:请审查当前成果、显式附件和工作目录中的相关文件。';+ return `没有可用的 Git 变更证据。${branchFailureNote}这不是跳过审查的理由:请审查当前成果、显式附件和工作目录中的相关文件。`;}function changeEvidenceSection(input: BuildReviewPromptInput): string {+ // Uncommitted work first: it is what the user is looking at right now.+ // Then the branch's own commits, which are the deliverable once committed.+ // The last turn is a fallback for tasks with no branch of their own.if (input.workspace?.dirty) return workspaceDiffSection(input.workspace);+ if (input.branch) return branchDiffSection(input.branch);if (input.changeSet) return diffSection(input.changeSet.diffs);return '(无 Git 补丁。)';}function resolveTargetKind(input: BuildReviewPromptInput): ReviewTargetKind {const hasChanges =- !!input.workspace?.dirty || (!!input.changeSet && input.changeSet.diffs.length > 0);+ !!input.workspace?.dirty ||+ (!!input.branch && input.branch.fileCount > 0) ||+ (!!input.changeSet && input.changeSet.diffs.length > 0);const hasArtifacts = input.artifacts.length > 0;if (hasChanges && hasArtifacts) return 'mixed';if (hasChanges) return 'changes';diff --git a/apps/desktop/src/shared/gitReviewWire.ts b/apps/desktop/src/shared/gitReviewWire.tsindex 207d244f93..df15223d54 100644--- a/apps/desktop/src/shared/gitReviewWire.ts+++ b/apps/desktop/src/shared/gitReviewWire.ts@@ -258,6 +258,13 @@ export interface ReviewBranchBaseCandidate {remote: string | null;oid: string;isStaleRisk?: boolean;+ /**+ * This ref is the repository's default branch — the remote's published HEAD,+ * a conventional `main`/`master`, or whatever `init.defaultBranch` names.+ * Only the branch reader can see that config, so consumers must not try to+ * recognize a default by its name alone.+ */+ isDefaultBranch?: boolean;}export type ReviewBranchDiffWarningCode =