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): review current code in the actual checkout

Chrisbcd24eb69132
diff --git a/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts b/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts
index e5d5c73f38..e342049c39 100644
--- a/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts
+++ b/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts
@@ -5,7 +5,10 @@
import path from 'node:path';
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
+
+// The injected resolver never opens Electron's persistent store.
+vi.mock('electron-store', () => ({ default: class {} }));
import type { GitHeadInfo } from '../git-context/headReader';
import {
@@ -54,6 +57,26 @@ describe('extractDirCandidate', () => {
expect(extractDirCandidate(toolUse('Bash', { command: 'ls' }))).toBeNull();
});
+ it.each([
+ 'cd /Users/x/wt-a && git status',
+ "cd '/Users/x/wt-a' && git diff",
+ 'cd -- "/Users/x/wt-a" && python edit.py',
+ ])('Claude Bash reports a literal command directory: %s', (command) => {
+ expect(extractDirCandidate(toolUse('Bash', { command }))).toBe('/Users/x/wt-a');
+ });
+
+ it('accepts quoted directory spaces without interpreting shell expressions', () => {
+ expect(extractDirCandidate(toolUse('Bash', { command: "cd '/Users/x/code tree' && git status" })))
+ .toBe('/Users/x/code tree');
+ for (const command of [
+ 'cd "$HOME/wt-a" && git status',
+ 'cd /Users/$(whoami)/wt-a && git status',
+ 'cd ../wt-a && git status',
+ 'echo ok && cd /Users/x/wt-a && git status',
+ 'cd /Users/x/wt-* && git status',
+ ]) expect(extractDirCandidate(toolUse('Bash', { command }))).toBeNull();
+ });
+
it('相对路径不采纳(cwd / file_path 都要求绝对)→ null', () => {
expect(extractDirCandidate(toolUse('exec', { command: 'ls', cwd: '../wt-a' }))).toBeNull();
expect(extractDirCandidate(toolUse('Edit', { file_path: 'src/y.ts' }))).toBeNull();
@@ -105,6 +128,17 @@ describe('resolveSessionGitDir', () => {
};
}
+ it('uses a Bash-only linked checkout instead of the unchanged task directory', async () => {
+ const res = await resolveSessionGitDir(
+ { sessionId: 's', fallbackWorktreePath: null, fallbackWorkingDir: '/Users/x/main' },
+ deps({
+ contents: [toolUse('Bash', { command: 'cd /Users/x/wt-a && git status --short' })],
+ gitDirs: { '/Users/x/main': 'main', '/Users/x/wt-a': 'integration' },
+ }),
+ );
+ expect(res).toMatchObject({ workdir: path.resolve('/Users/x/wt-a'), source: 'telemetry', head: branchHead('integration') });
+ });
+
it('遥测命中:最近一条候选目录是 git → source=telemetry', async () => {
const res = await resolveSessionGitDir(
{ sessionId: 's', ...FALLBACKS },
diff --git a/apps/desktop/src/main/git-context/sessionDirResolver.ts b/apps/desktop/src/main/git-context/sessionDirResolver.ts
index de51f0f234..9f82f25580 100644
--- a/apps/desktop/src/main/git-context/sessionDirResolver.ts
+++ b/apps/desktop/src/main/git-context/sessionDirResolver.ts
@@ -10,7 +10,7 @@
* 信号(按 agent):
* - Codex exec:每条命令 content.input.cwd = agent 当前 shell 目录,直接可信
* (实测:agent `cd` 进 worktree 后,后续每条命令的 cwd 都跟着变)。
- * - Claude Code:Bash 不带 cwd;改用 Edit/Write/MultiEdit/NotebookEdit 的
+ * - Claude Code:Bash 的字面量开头 cd 或 Edit/Write/MultiEdit/NotebookEdit 的
* input.file_path 绝对路径,取其所在目录(Read 不算——读文件 ≠ 在此工作)。
*
* 取「最近一条产出候选目录的 tool-use」(= 对话此刻在哪),用 readGitHead 校验:
@@ -72,7 +72,7 @@ export interface SessionGitDirResult {
* 从一条 tool-use 消息 content(已是 JSON 文本)解析候选工作目录:
* - input.cwd 是绝对路径(Codex exec)→ 直接用;
* - toolName ∈ 编辑类 且 input.file_path 是绝对路径 → 取 path.dirname;
- * - 其它(Read / 普通 Bash / 脏 JSON / 相对路径)→ null。
+ * - 其它(Read / 无字面量 cd 的 Bash / 脏 JSON / 相对路径)→ null。
* 纯函数,不碰 IO。
*/
export function extractDirCandidate(
@@ -103,6 +103,18 @@ export function extractDirCandidate(
}
}
+ // Claude's Bash tool does not report cwd. A literal leading `cd ... &&`
+ // identifies where this command ran; ordinary Bash/Read remain non-signals.
+ // Do not evaluate variables, substitutions, relative paths or later cd's.
+ if (toolName === 'Bash' && typeof (input as { command?: unknown }).command === 'string') {
+ const command = (input as { command: string }).command;
+ const match = /^\s*cd\s+(?:--\s+)?(?:'([^'\n]+)'|"([^"\n]+)"|([^\s;&|]+))\s*&&/.exec(command);
+ const dir = match?.[1] ?? match?.[2] ?? match?.[3];
+ if (dir && !/[\x00-\x1f$`\\*?{}]/.test(dir) && path.isAbsolute(dir)) {
+ return posixDriveToWin32(dir, pathPlatform);
+ }
+ }
+
// cc 编辑类:先归一 POSIX 盘符路径(Windows 上 cc 常发 `/e/...`)再取 dirname。
if (EDIT_TOOL_NAMES.has(toolName)) {
const fp = (input as { file_path?: unknown }).file_path;
diff --git a/apps/desktop/src/main/git-review/__tests__/scopeResolver.test.ts b/apps/desktop/src/main/git-review/__tests__/scopeResolver.test.ts
index 3af1d3ad60..313e9dd8ca 100644
--- a/apps/desktop/src/main/git-review/__tests__/scopeResolver.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/scopeResolver.test.ts
@@ -2,11 +2,14 @@ import path from 'node:path';
import { describe, expect, it, vi } from 'vitest';
+vi.mock('electron-store', () => ({ default: class {} }));
+
import {
defaultScopeResolverDeps,
resolveReviewScope,
type ScopeResolverDeps,
withSessionReviewRowSnapshot,
+ withSessionReviewWorkspace,
} from '../scopeResolver';
import { GitRunError, type GitRunResult } from '../gitRunner';
@@ -34,6 +37,27 @@ function deps(patch: Partial<ScopeResolverDeps> = {}): ScopeResolverDeps {
}
describe('git-review scopeResolver', () => {
+ it('pins one Review directory and rereads its current HEAD without following new telemetry', async () => {
+ let head = 'a'.repeat(40);
+ const d = deps({ git: vi.fn(async (args, options) => ({
+ stdout: args.includes('--show-toplevel') ? `${options.cwd}\n`
+ : args.includes('--verify') ? `${head}\n`
+ : args[0] === 'symbolic-ref' ? 'integration\n' : '',
+ stderr: '', exitCode: 0,
+ })) });
+ await withSessionReviewWorkspace('s1', '/repo/actual', async () => {
+ expect(await resolveReviewScope('s1', d)).toMatchObject({
+ repoRoot: path.resolve('/repo/actual'), branch: 'integration', headOid: head,
+ });
+ head = 'b'.repeat(40);
+ expect((await resolveReviewScope('s1', d)).headOid).toBe(head);
+ expect(d.resolveSessionDir).not.toHaveBeenCalled();
+ await resolveReviewScope('other-task', d);
+ expect(d.resolveSessionDir).toHaveBeenCalledTimes(1);
+ });
+ expect((await resolveReviewScope('s1', d)).repoRoot).toBe(path.resolve('/repo/wt-store'));
+ });
+
it('prefers managed WorktreeStore path over DB snapshot fallback', async () => {
const d = deps();
const scope = await resolveReviewScope('s1', d);
diff --git a/apps/desktop/src/main/git-review/scopeResolver.ts b/apps/desktop/src/main/git-review/scopeResolver.ts
index bcdf97153d..48e3230236 100644
--- a/apps/desktop/src/main/git-review/scopeResolver.ts
+++ b/apps/desktop/src/main/git-review/scopeResolver.ts
@@ -26,6 +26,19 @@ export interface SessionReviewRow {
}
const sessionRowSnapshot = new AsyncLocalStorage<SessionReviewRow>();
+const selectedReviewWorkspace = new AsyncLocalStorage<{ sessionId: string; workingDir: string }>();
+
+/** Pin one Review invocation to its host-resolved/user-selected directory.
+ * Evidence, freshness checks and the Reviewer must all address this same tree.
+ * This does not change the source task's persisted directory or other callers.
+ */
+export function withSessionReviewWorkspace<T>(
+ sessionId: string,
+ workingDir: string,
+ task: () => Promise<T>,
+): Promise<T> {
+ return selectedReviewWorkspace.run({ sessionId, workingDir }, task);
+}
export function withSessionReviewRowSnapshot<T>(
row: SessionReviewRow,
@@ -216,11 +229,20 @@ export async function resolveReviewScope(
const managedWorktreePath = deps.getManagedWorktreePath(sessionId);
const fallbackWorktreePath = managedWorktreePath ?? row.worktreePath;
- const resolved = await deps.resolveSessionDir({
- sessionId,
- fallbackWorktreePath,
- fallbackWorkingDir: row.workingDir,
- });
+ const selected = selectedReviewWorkspace.getStore();
+ const pinnedDir = selected?.sessionId === sessionId ? selected.workingDir : null;
+ const pinnedHead = pinnedDir ? await readRemoteHeadState(pinnedDir, deps.git) : null;
+ const resolved = pinnedDir && pinnedHead
+ ? {
+ workdir: pinnedDir,
+ head: { kind: pinnedHead.isDetached ? 'detached' : 'branch', branch: pinnedHead.branch },
+ source: 'workingDir' as const,
+ }
+ : await deps.resolveSessionDir({
+ sessionId,
+ fallbackWorktreePath,
+ fallbackWorkingDir: row.workingDir,
+ });
// A remote row is handled above through the request-scoped SSH Git backend.
// A remote result here would lack the authoritative host id, so fail closed.
if (resolved.source === 'remote') {
@@ -242,7 +264,7 @@ export async function resolveReviewScope(
const resolutionChain = [
{ source: 'telemetry', path: resolved.source === 'telemetry' ? resolved.workdir : null, ok: resolved.source === 'telemetry' },
{ source: 'worktree', path: fallbackWorktreePath, ok: resolved.source === 'worktree' },
- { source: 'workingDir', path: row.workingDir, ok: resolved.source === 'workingDir' },
+ { source: 'workingDir', path: pinnedDir ?? row.workingDir, ok: resolved.source === 'workingDir' },
];
if (!resolved.workdir) {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts
index 5b1a1d1993..b9d1d7240e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts
@@ -950,6 +950,32 @@ describe('maker:review:start IPC lifecycle', () => {
expect(deps.closeReviewer).toHaveBeenCalledTimes(1);
});
+ it.each(['returned-failure', 'verification-exception'])(
+ 'keeps an existing conclusion when final verification encounters %s', async (mode) => {
+ const harness = new IpcHarness();
+ const reviewer = new FakeReviewer();
+ const launch = makeLaunch({ verifyBeforePublish: vi.fn(async () => {
+ if (mode === 'verification-exception') throw new Error('Git backend unavailable');
+ return { code: 'artifact-unavailable' as const, message: 'Cannot verify source files' };
+ }) });
+ const workspace = { workingDir: '/repo/actual', baseRef: 'main', hasUncommittedChanges: true };
+ const deps = makeDeps(reviewer, {
+ prepareRun: vi.fn(async () => makePreparedRun(launch, { workspace })),
+ });
+ registerReviewStartHandler(harness, deps);
+ await harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest());
+ expect(deps.createSourceCard).toHaveBeenCalledWith(expect.objectContaining({
+ meta: expect.objectContaining({ workspace }),
+ }));
+ reviewer.emit({ type: 'done', data: {} });
+ await vi.waitFor(() => expect(deps.updateSourceCard).toHaveBeenCalledTimes(1));
+ expect(deps.updateSourceCard).toHaveBeenCalledWith(expect.objectContaining({
+ result: 'P1: real finding', meta: expect.objectContaining({ status: 'failed', workspace }),
+ }));
+ expect(deps.closeReviewer).toHaveBeenCalledTimes(1);
+ },
+ );
+
it('fails the visible card when evidence changes before reviewer bootstrap', async () => {
const harness = new IpcHarness();
const reviewer = new FakeReviewer();
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 363252ea33..7b94521e72 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -328,6 +328,8 @@ import { invalidateWorkersByLeadSingleFlight } from '../localDb/ipc/orcaWorkerLi
import { messageToCamel, setSessionRuntimeProjector } from '../localDb/mapper.js';
import { visibleMessageTextForConversationSearch } from '../localDb/conversationSearch.pure.js';
import { buildReviewPrompt } from '../reviewer/reviewPrompt.js';
+import { resolveReviewScope, withSessionReviewWorkspace } from '../git-review/scopeResolver.js';
+import { selectReviewWorkspace } from '../reviewer/reviewWorkspaceSelection.js';
import {
listReviewHistoricalAttachments,
loadReviewEvidence,
@@ -354,7 +356,7 @@ import {
ReviewArtifactFingerprintChangedError,
ReviewArtifactFingerprintLimitError,
} from '../reviewer/reviewArtifactFingerprint.js';
-import { reviewChangeSetContentPaths } from '../reviewer/reviewEvidenceSafety.js';
+import { reviewChangeSetContentPaths, usableReviewChangeSet } from '../reviewer/reviewEvidenceSafety.js';
import { enforceReviewCreateOptions } from '../reviewer/reviewSessionPolicy.js';
import { reviewSourceIdentityMatches } from '../reviewer/reviewSourceIdentity.js';
import { buildReviewSessionTitle } from '../reviewer/reviewSessionTitle.js';
@@ -8303,7 +8305,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!source.workingDir) {
throwIpcError('INVALID_PARAMS', 'The source task has no working directory to review');
}
- const sourceWorkingDir = source.workingDir;
+ const sourceScope = await resolveReviewScope(source.id);
+ let sourceWorkingDir = sourceScope.repoRoot ?? sourceScope.workdir ?? source.workingDir;
+ const inReviewWorkspace = <T>(task: () => Promise<T>): Promise<T> =>
+ withSessionReviewWorkspace(source.id, sourceWorkingDir, task);
if (await sourceHasActiveTurn(source.id)) {
throwIpcError(
'SESSION_RUNNING',
@@ -8311,7 +8316,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
- let evidence: Awaited<ReturnType<typeof loadReviewEvidence>>;
+ let evidence!: Awaited<ReturnType<typeof loadReviewEvidence>>;
+ let workspaceSelected = false;
+ let historyCaptureIncomplete = false;
let sourceArtifactFingerprint = '';
let authorizedArtifactPaths: string[] = [];
let cleanupPreparedArtifacts: (() => Promise<void>) | null = null;
@@ -8327,37 +8334,69 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
cleanupRemoteAttachments = remote.cleanup;
cleanupPreparedArtifacts = remote.cleanup;
}
- const historicalAttachments = await listReviewHistoricalAttachments(source.id);
- const explicitArtifactGrant = await authorizeReviewExplicitArtifacts({
- workingDir: sourceWorkingDir,
- focus: request.focus,
- attachments: [...request.attachments, ...historicalAttachments],
- resolvePath: resolveReviewArtifactPath,
- confirm: (items) => confirmReviewExternalArtifacts(event as IpcMainInvokeEvent, items),
- });
- authorizedArtifactPaths = explicitArtifactGrant.paths;
- const prepared = await prepareStableReviewArtifactSnapshots({
- workingDir: sourceWorkingDir,
- grant: explicitArtifactGrant,
- owner: reviewRunOwner,
- prepare: (snapshotGrant) =>
- loadReviewEvidence({
- sourceSessionId: source.id,
- workingDir: sourceWorkingDir,
- focus: request.focus,
- attachments: request.attachments,
- explicitArtifactGrant: snapshotGrant,
- }),
- });
- cleanupPreparedArtifacts = async () => {
- try {
- await prepared.cleanup();
- } finally {
- await cleanupRemoteAttachments?.();
- }
+ const prepareEvidence = async () => {
+ const historicalAttachments = await listReviewHistoricalAttachments(source.id);
+ const explicitArtifactGrant = await authorizeReviewExplicitArtifacts({
+ workingDir: sourceWorkingDir,
+ focus: request.focus,
+ attachments: [...request.attachments, ...historicalAttachments],
+ resolvePath: resolveReviewArtifactPath,
+ confirm: (items) => confirmReviewExternalArtifacts(event as IpcMainInvokeEvent, items),
+ });
+ authorizedArtifactPaths = explicitArtifactGrant.paths;
+ const prepared = await prepareStableReviewArtifactSnapshots({
+ workingDir: sourceWorkingDir,
+ grant: explicitArtifactGrant,
+ owner: reviewRunOwner,
+ prepare: (snapshotGrant) =>
+ inReviewWorkspace(() => loadReviewEvidence({
+ sourceSessionId: source.id,
+ workingDir: sourceWorkingDir,
+ focus: request.focus,
+ attachments: request.attachments,
+ explicitArtifactGrant: snapshotGrant,
+ })),
+ });
+ cleanupPreparedArtifacts = async () => {
+ try {
+ await prepared.cleanup();
+ } finally {
+ await cleanupRemoteAttachments?.();
+ }
+ };
+ evidence = prepared.value;
+ sourceArtifactFingerprint = prepared.fingerprint;
};
- evidence = prepared.value;
- sourceArtifactFingerprint = prepared.fingerprint;
+ await prepareEvidence();
+ // An empty main checkout commonly means the work happened in a linked
+ // worktree. Historical turn metadata cannot tell us which current code
+ // the user wants; ask about the directory instead of refusing the run.
+ if (
+ evidence.workspace && !evidence.workspace.disabledReason &&
+ !evidence.workspace.dirty && !evidence.branch &&
+ evidence.artifacts.length === 0 && !evidence.focusPath && !isDeviceLinkInvoke()
+ ) {
+ const selectedDir = await selectReviewWorkspace(event as IpcMainInvokeEvent, sourceWorkingDir);
+ if (!selectedDir) throwIpcError('MUTATION_CANCELLED', 'Review workspace selection cancelled');
+ workspaceSelected = true;
+ if (path.resolve(selectedDir) !== path.resolve(sourceWorkingDir)) {
+ await cleanupPreparedArtifacts?.();
+ sourceWorkingDir = selectedDir;
+ await prepareEvidence();
+ }
+ }
+ // Reversible turn capture is advisory. Bash (even `git status`) and
+ // overlapping tasks mark it partial; a fresh Git baseline or explicitly
+ // selected artifacts must not be blocked by unrelated capture gaps.
+ const historicalChangeSet = evidence.changeSet;
+ evidence.changeSet = usableReviewChangeSet(evidence.changeSet, sourceWorkingDir, {
+ hasGitBaseline: !!evidence.workspaceFingerprint,
+ hasExplicitArtifacts: evidence.artifacts.length > 0 || workspaceSelected,
+ });
+ historyCaptureIncomplete = !!historicalChangeSet && !evidence.changeSet;
+ // An explicit directory choice targets its current code, not a turn
+ // captured in the previous task directory.
+ if (workspaceSelected) evidence.changeSet = null;
} catch (error) {
await cleanupPreparedArtifacts?.();
if (
@@ -8377,7 +8416,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
!evidence.branch &&
!evidence.changeSet &&
evidence.artifacts.length === 0 &&
- !request.focus
+ !request.focus &&
+ !workspaceSelected
) {
await cleanupPreparedArtifacts?.();
// "Nothing to review" and "the branch was there but could not be read"
@@ -8395,6 +8435,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
builtPrompt = buildReviewPrompt({
focus: evidence.focusPath ? `审查路径:${evidence.focusPath}` : request.focus,
context: evidence.context,
+ historyCaptureIncomplete,
workspace: evidence.workspace,
branch: evidence.branch,
...(evidence.branchUnavailableReason
@@ -8415,6 +8456,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sourceAgentKind: source.agentKind as 'cc' | 'codex' | 'pi',
prompt: builtPrompt.prompt,
targetKind: builtPrompt.targetKind,
+ workspace: {
+ workingDir: sourceWorkingDir,
+ ...(evidence.branch ? { baseRef: evidence.branch.baseRef } : {}),
+ hasUncommittedChanges: !!evidence.workspace?.dirty,
+ },
onAccepted: () => acceptRemoteAttachments?.(),
cleanup: async () => {
await cleanupPreparedArtifacts?.();
@@ -8489,6 +8535,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
}
const artifactPaths = [...new Set([...reviewReadPaths, ...changeSetContent.paths])];
+ if (workspaceSelected && !evidence.workspaceFingerprint) {
+ // A selected non-Git directory has no HEAD/status baseline. Bind
+ // its contents with the existing bounded artifact fingerprinter.
+ artifactPaths.push(sourceWorkingDir);
+ }
const artifactFingerprintOptions = { linkConfinementRoot: sourceWorkingDir };
let artifactFingerprint: string;
try {
@@ -8573,10 +8624,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
}
if (
- !(await reviewWorkspaceFingerprintIsCurrent(
+ !(await inReviewWorkspace(() => reviewWorkspaceFingerprintIsCurrent(
source.id,
evidence.workspaceFingerprint,
- ))
+ )))
) {
return {
code: 'source-files-changed',
@@ -8586,7 +8637,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
// 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))) {
+ if (!(await inReviewWorkspace(() => reviewBranchBaselineIsCurrent(source.id, evidence.branch)))) {
return {
code: 'source-files-changed',
message:
@@ -8633,10 +8684,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
}
if (
- !(await reviewWorkspaceFingerprintIsCurrent(
+ !(await inReviewWorkspace(() => reviewWorkspaceFingerprintIsCurrent(
source.id,
evidence.workspaceFingerprint,
- ))
+ )))
) {
return {
code: 'source-files-changed',
@@ -8644,7 +8695,7 @@ 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))) {
+ if (!(await inReviewWorkspace(() => reviewBranchBaselineIsCurrent(source.id, evidence.branch)))) {
return {
code: 'source-files-changed',
message:
diff --git a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
index 9b63fad98f..b52f3804da 100644
--- a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
@@ -10,7 +10,6 @@ import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-contin
import type { ReviewAttachmentInput } from '../reviewer/reviewEvidence.js';
import {
- isStaleReviewFailureCode,
type ReviewFailureCode,
type ReviewRunMeta,
type ReviewRunOwner,
@@ -152,6 +151,7 @@ export interface PreparedReviewRun {
sourceAgentKind: 'cc' | 'codex' | 'pi';
prompt: string;
targetKind: ReviewTargetKind;
+ workspace?: ReviewRunMeta['workspace'];
prepareLaunch(): Promise<PreparedReviewLaunch>;
/** Release transport staging once the Review prompt is durably accepted. */
onAccepted?(): void;
@@ -288,6 +288,7 @@ export function registerReviewStartHandler(
let settled = false;
let settlementCause: 'provider-terminal' | 'reviewer-closed' | null = null;
let reviewerClosed = false;
+ let completedResult = '';
let preparedRunCleaned = false;
let preparedRunCleanup: (() => Promise<void>) | null = null;
let terminalFinalization: Promise<void> | null = null;
@@ -494,6 +495,7 @@ export function registerReviewStartHandler(
sourceSessionId: request.sourceSessionId,
status: 'running',
targetKind: prepared.targetKind,
+ ...(prepared.workspace ? { workspace: prepared.workspace } : {}),
startedAt,
owner: deps.owner,
};
@@ -542,16 +544,12 @@ export function registerReviewStartHandler(
await closeReviewer();
return;
}
+ completedResult = result;
const staleReason = await launch.verifyBeforePublish();
if (staleReason) {
- if (isStaleReviewFailureCode(staleReason.code)) {
- // Keep the persisted status readable by older clients. The stable
- // reason code distinguishes an out-of-date completed result from
- // a Reviewer execution failure in current clients.
- await updateSourceCard('failed', result, staleReason.message, staleReason.code);
- } else {
- await updateSourceCard('failed', '', staleReason.message, staleReason.code);
- }
+ // Keep the completed conclusion visible, with its failed freshness
+ // check. Clients cannot treat it as a verified current result.
+ await updateSourceCard('failed', result, staleReason.message, staleReason.code);
await closeReviewer();
return;
}
@@ -565,7 +563,7 @@ export function registerReviewStartHandler(
});
await updateSourceCard(
'failed',
- '',
+ completedResult,
error instanceof Error ? error.message : String(error),
).catch((cardError) => {
deps.warn('review failure card retry setup failed', {
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
index eac985685d..9b8401fa86 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
@@ -1137,9 +1137,7 @@ describe('loadReviewEvidence attachment boundaries', () => {
]);
});
- 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.
+ it('reads the committed branch changes even when uncommitted work exists', async () => {
const repoRoot = await tempDir();
readReviewDataMock.mockResolvedValue(cappedReviewData(repoRoot, 'src/a.ts'));
@@ -1154,7 +1152,9 @@ describe('loadReviewEvidence attachment boundaries', () => {
},
});
- expect(readReviewBranchDiffMock).not.toHaveBeenCalled();
+ expect(readReviewBranchDiffMock).toHaveBeenCalledWith('source', null);
+ // This fixture has no commits above the baseline; reading it is still
+ // necessary to distinguish an unchanged branch from hidden committed work.
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.ts
index 29e2007c41..b8d5a4aedc 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidenceSafety.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidenceSafety.test.ts
@@ -8,6 +8,7 @@ import {
reviewChangeSetContentPaths,
sanitizeReviewChangeSet,
sanitizeReviewDiffBucket,
+ usableReviewChangeSet,
} from '../reviewEvidenceSafety.js';
function fileDiff(overrides: Partial<FileDiff> = {}): FileDiff {
@@ -158,6 +159,19 @@ describe('review change set content paths', () => {
return { id: path, path, oldPath, status: 'modified', additions: 1, deletions: 0 };
}
+ it('does not make incomplete Claude Bash history a prerequisite for current Git review', () => {
+ const captured = changeSet([], '/repo', {
+ provider: 'claude-code', state: 'partial', isReversible: false,
+ incompleteReasons: ['opaque-tool', 'concurrent-workspace'],
+ });
+ expect(reviewChangeSetContentPaths(captured, '/repo').truncated).toBe(true);
+ expect(usableReviewChangeSet(captured, '/repo', { hasGitBaseline: true, hasExplicitArtifacts: false })).toBeNull();
+ expect(usableReviewChangeSet(captured, '/repo', { hasGitBaseline: false, hasExplicitArtifacts: true })).toBeNull();
+ expect(usableReviewChangeSet(captured, '/repo', { hasGitBaseline: false, hasExplicitArtifacts: false })).toBe(captured);
+ const complete = changeSet([file('src/a.ts')]);
+ expect(usableReviewChangeSet(complete, '/repo', { hasGitBaseline: true, hasExplicitArtifacts: false })).toBe(complete);
+ });
+
it('resolves changed and renamed-from paths against the recorded cwd', () => {
expect(
reviewChangeSetContentPaths(
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewPrompt.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewPrompt.test.ts
index cbe3126387..53340e0f20 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewPrompt.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewPrompt.test.ts
@@ -326,8 +326,7 @@ describe('buildReviewPrompt', () => {
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.
+ it('reviews branch commits together with the current uncommitted edits', () => {
const result = buildReviewPrompt({
context: [],
workspace: {
@@ -353,10 +352,13 @@ describe('buildReviewPrompt', () => {
},
changeSet: null,
artifacts: [],
+ historyCaptureIncomplete: true,
});
expect(result.prompt).toContain('src/wip.ts');
- expect(result.prompt).not.toContain('src/committed.ts');
+ expect(result.prompt).toContain('src/committed.ts');
+ expect(result.prompt).toContain('以磁盘上的当前代码为最终状态');
+ expect(result.prompt).toContain('历史改动记录不完整');
});
it('says so when the branch diff was unreadable and there is no change set', () => {
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewSelfCheck.git-integration.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewSelfCheck.git-integration.test.ts
new file mode 100644
index 0000000000..bd84b5d251
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewSelfCheck.git-integration.test.ts
@@ -0,0 +1,117 @@
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, expect, it, vi } from 'vitest';
+
+const runtime = vi.hoisted(() => ({ resolveScope: vi.fn(), captured: null as unknown }));
+vi.mock('electron-store', () => ({ default: class {} }));
+// This fixture is local-only; no SSH transport or agent process is started.
+vi.mock('../../git-review/sshReviewBackend.js', () => ({
+ withSessionReviewExecution: (_id: string, task: () => unknown) => task(),
+ createSshPreviewReaderDeps: vi.fn(),
+}));
+vi.mock('../../localDb/client/current.js', () => ({
+ getDbClient: () => ({ drizzle: { select: () => ({ from: () => ({ where: () => ({
+ orderBy: () => ({ limit: async () => [] }), limit: async () => [],
+ }) }) }) } }),
+}));
+vi.mock('../../turn-change-set/store.js', () => ({
+ listTurnChangeSets: async () => runtime.captured ? [runtime.captured] : [],
+ getTurnChangeSets: async () => runtime.captured ? [runtime.captured] : [],
+}));
+vi.mock('../../git-review/ipc.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../git-review/ipc.js')>();
+ const { readStatus } = await import('../../git-review/statusReader.js');
+ const { readDiffs } = await import('../../git-review/diffReader.js');
+ return {
+ ...actual,
+ readReviewData: (id: string) => actual.readReviewData(id, {
+ resolveScope: runtime.resolveScope, readStatus, readDiffs, isSessionRunning: () => false,
+ }),
+ readReviewBranchDiff: (id: string, base: string | null) => actual.readReviewBranchDiff(id, base, {
+ resolveScope: runtime.resolveScope,
+ }),
+ };
+});
+
+import { readGitHead } from '../../git-context/headReader.js';
+import { resolveSessionGitDir } from '../../git-context/sessionDirResolver.js';
+import { runGit } from '../../git-review/gitRunner.js';
+import { resolveReviewScope, withSessionReviewWorkspace } from '../../git-review/scopeResolver.js';
+import { loadReviewEvidence, reviewWorkspaceFingerprintIsCurrent } from '../reviewEvidence.js';
+import { usableReviewChangeSet } from '../reviewEvidenceSafety.js';
+import { buildReviewPrompt } from '../reviewPrompt.js';
+import type { TurnChangeSetDetail } from '../../../shared/turnChangeSet.js';
+
+let fixtureRoot: string | null = null;
+afterEach(async () => {
+ runtime.captured = null;
+ vi.clearAllMocks();
+ if (fixtureRoot) await fs.rm(fixtureRoot, { recursive: true, force: true });
+ fixtureRoot = null;
+});
+
+it('reviews real committed and dirty code in the Bash worktree despite an empty partial turn capture', async () => {
+ fixtureRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-self-review-')));
+ const main = path.join(fixtureRoot, 'main');
+ const actual = path.join(fixtureRoot, 'actual');
+ await fs.mkdir(main);
+ const git = (args: string[], cwd = main) => runGit(args, { cwd });
+ await git(['init', '-b', 'main']);
+ await git(['config', 'user.name', 'Review Test']);
+ await git(['config', 'user.email', '[email protected]']);
+ await fs.writeFile(path.join(main, 'committed.ts'), 'export const committed = 1;\n');
+ await fs.writeFile(path.join(main, 'dirty.ts'), 'export const current = 1;\n');
+ await git(['add', 'committed.ts', 'dirty.ts']);
+ await git(['commit', '--no-gpg-sign', '-s', '-m', 'baseline']);
+ await git(['worktree', 'add', '-b', 'integration', actual]);
+ await fs.writeFile(path.join(actual, 'committed.ts'), 'export const committed = 0;\n');
+ await git(['add', 'committed.ts'], actual);
+ await git(['commit', '--no-gpg-sign', '-s', '-m', 'committed change'], actual);
+ await fs.writeFile(path.join(actual, 'dirty.ts'), 'export const current = 0;\n');
+
+ let commands = [JSON.stringify({ toolName: 'Bash', input: { command: `cd "${actual}" && git status --short` } })];
+ runtime.resolveScope.mockImplementation((sessionId: string) => resolveReviewScope(sessionId, {
+ getSessionRow: async () => ({ id: 'source', workingDir: main, worktreePath: null, remoteHostId: null }),
+ getManagedWorktreePath: () => null,
+ resolveSessionDir: (input) => resolveSessionGitDir(input, {
+ recentToolUseContents: async () => commands, probeGitDir: readGitHead,
+ }),
+ git: runGit,
+ }));
+ const sourceScope = await runtime.resolveScope('source');
+ expect(sourceScope.repoRoot).toBe(actual);
+
+ runtime.captured = {
+ id: 'turn', sessionId: 'source', anchorClientId: 'message', provider: 'claude-code',
+ providerTurnId: null, cwd: main, state: 'partial', workspaceState: 'applied', isReversible: false,
+ incompleteReasons: ['opaque-tool', 'concurrent-workspace'], createdAt: 1, completedAt: 2,
+ files: [], diffs: [], fileCount: 0, additions: 0, deletions: 0,
+ } satisfies TurnChangeSetDetail;
+ await withSessionReviewWorkspace('source', sourceScope.repoRoot, async () => {
+ const evidence = await loadReviewEvidence({
+ sourceSessionId: 'source', workingDir: actual, attachments: [], focus: '检查代码质量',
+ explicitArtifactGrant: { paths: [], pathIdentities: new Map(), inlineAttachmentKeys: [] },
+ });
+ expect(evidence.workspace?.dirty).toBe(true);
+ expect(evidence.branch?.diffs.map((diff) => diff.path)).toContain('committed.ts');
+ expect(evidence.workspace?.diffs.unstaged.map((diff) => diff.path)).toContain('dirty.ts');
+ evidence.changeSet = usableReviewChangeSet(evidence.changeSet, actual, {
+ hasGitBaseline: !!evidence.workspaceFingerprint, hasExplicitArtifacts: false,
+ });
+ expect(evidence.changeSet).toBeNull();
+ const prompt = buildReviewPrompt({ ...evidence, historyCaptureIncomplete: true }).prompt;
+ expect(prompt).toContain('committed.ts');
+ expect(prompt).toContain('dirty.ts');
+ expect(prompt).toContain('历史改动记录不完整');
+ expect(evidence.workspaceFingerprint).toBeTruthy();
+
+ // Later task telemetry may point back to main; this Review keeps its tree.
+ commands = [JSON.stringify({ toolName: 'exec', input: { cwd: main } })];
+ expect(await reviewWorkspaceFingerprintIsCurrent('source', evidence.workspaceFingerprint)).toBe(true);
+ await fs.writeFile(path.join(actual, 'dirty.ts'), 'export const current = 2;\n');
+ expect(await reviewWorkspaceFingerprintIsCurrent('source', evidence.workspaceFingerprint)).toBe(false);
+ });
+ expect((await runtime.resolveScope('source')).repoRoot).toBe(main);
+}, 30_000);
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewWorkspaceSelection.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewWorkspaceSelection.test.ts
new file mode 100644
index 0000000000..e3a0c454d6
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewWorkspaceSelection.test.ts
@@ -0,0 +1,56 @@
+import type { IpcMainInvokeEvent } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { assertTrusted, parent, showMessageBox, showOpenDialog } = vi.hoisted(() => ({
+ assertTrusted: vi.fn(),
+ parent: { isDestroyed: vi.fn(() => false) },
+ showMessageBox: vi.fn(),
+ showOpenDialog: vi.fn(),
+}));
+vi.mock('electron', () => ({
+ BrowserWindow: { fromWebContents: () => parent },
+ dialog: { showMessageBox, showOpenDialog },
+}));
+vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
+vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: assertTrusted }));
+
+import { selectReviewWorkspace } from '../reviewWorkspaceSelection.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ parent.isDestroyed.mockReturnValue(false);
+ assertTrusted.mockImplementation(() => {});
+ showMessageBox.mockResolvedValue({ response: 1 });
+ showOpenDialog.mockResolvedValue({ canceled: false, filePaths: ['/repo/actual'] });
+});
+
+describe('Review directory selection', () => {
+ const event = { sender: {} } as IpcMainInvokeEvent;
+
+ it('uses the directory picked in a native dialog without changing the source task', async () => {
+ expect(await selectReviewWorkspace(event, '/repo/main')).toBe('/repo/actual');
+ expect(assertTrusted).toHaveBeenCalledWith(event);
+ expect(showMessageBox).toHaveBeenCalledWith(parent, expect.objectContaining({ detail: '/repo/main' }));
+ expect(showOpenDialog).toHaveBeenCalledWith(parent, expect.objectContaining({ properties: ['openDirectory'] }));
+ });
+
+ it('lets the user explicitly review the current tree even without a diff', async () => {
+ showMessageBox.mockResolvedValue({ response: 0 });
+ expect(await selectReviewWorkspace(event, '/repo/main')).toBe('/repo/main');
+ expect(showOpenDialog).not.toHaveBeenCalled();
+ });
+
+ it.each(['question', 'picker', 'closed-window'])('cancels cleanly at %s', async (stage) => {
+ if (stage === 'question') showMessageBox.mockResolvedValue({ response: 2 });
+ if (stage === 'picker') showOpenDialog.mockResolvedValue({ canceled: true, filePaths: [] });
+ if (stage === 'closed-window') parent.isDestroyed.mockReturnValue(true);
+ expect(await selectReviewWorkspace(event, '/repo/main')).toBeNull();
+ });
+
+ it('rejects an untrusted caller before opening a directory picker', async () => {
+ assertTrusted.mockImplementation(() => { throw new Error('untrusted renderer'); });
+ await expect(selectReviewWorkspace(event, '/repo/main')).rejects.toThrow('untrusted renderer');
+ expect(showMessageBox).not.toHaveBeenCalled();
+ expect(showOpenDialog).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/reviewer/reviewEvidence.ts b/apps/desktop/src/main/reviewer/reviewEvidence.ts
index 57454c4a56..29d5c752bc 100644
--- a/apps/desktop/src/main/reviewer/reviewEvidence.ts
+++ b/apps/desktop/src/main/reviewer/reviewEvidence.ts
@@ -109,12 +109,8 @@ 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.
+ * The branch's own commits. Read independently of current uncommitted edits;
+ * a last-turn record is not a faithful substitute for the whole deliverable.
*/
async function loadReviewBranchEvidence(
sessionId: string,
@@ -691,10 +687,10 @@ 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.
+ // Self-review covers the deliverable: branch commits plus current edits.
+ // A dirty tree must not hide the already committed part of that work.
const branchEvidence =
- workspace && !workspace.dirty && !workspace.disabledReason
+ workspace && !workspace.disabledReason
? await loadReviewBranchEvidence(input.sourceSessionId, readReviewBranchDiff)
: { branch: null };
diff --git a/apps/desktop/src/main/reviewer/reviewEvidenceSafety.ts b/apps/desktop/src/main/reviewer/reviewEvidenceSafety.ts
index b8be0f8533..e1f8c84673 100644
--- a/apps/desktop/src/main/reviewer/reviewEvidenceSafety.ts
+++ b/apps/desktop/src/main/reviewer/reviewEvidenceSafety.ts
@@ -229,3 +229,20 @@ export function reviewChangeSetContentPaths(
unenumerable || seen.size + redactedChangeEntryCount(changeSet) < changeSet.fileCount,
};
}
+
+/** Turn capture is a fallback, not a prerequisite for reviewing current code.
+ * Never bind an incomplete historical record as if it were a full baseline.
+ * Fresh Git evidence / explicit artifacts have their own identity checks.
+ */
+export function usableReviewChangeSet(
+ changeSet: TurnChangeSetDetail | null,
+ workingDir: string,
+ current: { hasGitBaseline: boolean; hasExplicitArtifacts: boolean },
+): TurnChangeSetDetail | null {
+ if (
+ changeSet &&
+ (current.hasGitBaseline || current.hasExplicitArtifacts) &&
+ reviewChangeSetContentPaths(changeSet, workingDir).truncated
+ ) return null;
+ return changeSet;
+}
diff --git a/apps/desktop/src/main/reviewer/reviewPrompt.ts b/apps/desktop/src/main/reviewer/reviewPrompt.ts
index cc2b793e95..8f875dea3b 100644
--- a/apps/desktop/src/main/reviewer/reviewPrompt.ts
+++ b/apps/desktop/src/main/reviewer/reviewPrompt.ts
@@ -61,6 +61,7 @@ export interface ReviewBranchEvidence {
export interface BuildReviewPromptInput {
focus?: string;
context: ReviewContextMessage[];
+ historyCaptureIncomplete?: boolean;
workspace: ReviewWorkspaceEvidence | null;
branch?: ReviewBranchEvidence | null;
/** Why no branch evidence is present, when it should have been. */
@@ -193,7 +194,7 @@ function cappedBucketSection(
);
}
-function workspaceDiffSection(workspace: ReviewWorkspaceEvidence): string {
+function workspaceDiffSection(workspace: ReviewWorkspaceEvidence, budget = MAX_DIFF_CHARS): string {
const parts: string[] = [];
const diffs = [...workspace.diffs.staged, ...workspace.diffs.unstaged];
if (diffs.length > 0) parts.push(diffSection(diffs));
@@ -207,10 +208,10 @@ function workspaceDiffSection(workspace: ReviewWorkspaceEvidence): string {
}
return '(Git 状态显示存在未提交变更,但没有可嵌入的文本补丁;请用只读工具检查列出的工作区文件。)';
}
- return clip(parts.join('\n\n'), MAX_DIFF_CHARS);
+ return clip(parts.join('\n\n'), budget);
}
-function branchDiffSection(branch: ReviewBranchEvidence): string {
+function branchDiffSection(branch: ReviewBranchEvidence, budget = MAX_DIFF_CHARS): string {
const parts: string[] = [];
if (branch.diffs.length > 0) parts.push(diffSection(branch.diffs));
if (branch.capped) parts.push(cappedBucketSection('分支', branch.capped));
@@ -220,7 +221,7 @@ function branchDiffSection(branch: ReviewBranchEvidence): string {
}
return '(本分支相对基线有变更,但没有可嵌入的文本补丁;请用只读工具检查列出的文件。)';
}
- return clip(parts.join('\n\n'), MAX_DIFF_CHARS);
+ return clip(parts.join('\n\n'), budget);
}
function coverageSection(input: BuildReviewPromptInput): string {
@@ -229,7 +230,7 @@ function coverageSection(input: BuildReviewPromptInput): string {
input.workspace.diffs.capped?.staged ? '已暂存' : null,
input.workspace.diffs.capped?.unstaged ? '未暂存' : null,
].filter(Boolean);
- const summary = `当前 Git 工作区有 ${input.workspace.totalFiles} 个未提交文件(已暂存 ${input.workspace.stagedFiles}、未暂存 ${input.workspace.unstagedFiles}、未跟踪 ${input.workspace.untrackedFiles})。`;
+ const summary = `当前 Git 工作区有 ${input.workspace.totalFiles} 个未提交文件(已暂存 ${input.workspace.stagedFiles}、未暂存 ${input.workspace.unstagedFiles}、未跟踪 ${input.workspace.untrackedFiles})。${input.branch ? `审查同时包含本分支相对基线 ${inlineLabel(input.branch.baseRef)} 的 ${input.branch.fileCount} 个文件的已提交变更;以磁盘上的当前代码为最终状态。` : ''}${input.branchUnavailableReason ? `已提交分支差异无法读取(${inlineWarning(input.branchUnavailableReason)}),不得声称已覆盖全部分支改动。` : ''}`;
const sensitiveNote =
(input.workspace.sensitiveFilesOmitted ?? 0) > 0
? `其中 ${input.workspace.sensitiveFilesOmitted} 份敏感路径变更已从证据中排除;不得读取或评价其内容。`
@@ -279,10 +280,13 @@ function coverageSection(input: BuildReviewPromptInput): string {
}
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);
+ // Both describe the deliverable, with current edits applied over HEAD.
+ if (input.workspace?.dirty) {
+ return clip([
+ ...(input.branch ? ['## 已提交分支改动\n\n' + branchDiffSection(input.branch, Math.floor(MAX_DIFF_CHARS / 2))] : []),
+ '## 当前未提交修改\n\n' + workspaceDiffSection(input.workspace, input.branch ? Math.floor(MAX_DIFF_CHARS / 2) : MAX_DIFF_CHARS),
+ ].join('\n\n'), MAX_DIFF_CHARS);
+ }
if (input.branch) return branchDiffSection(input.branch);
if (input.changeSet) return diffSection(input.changeSet.diffs);
return '(无 Git 补丁。)';
@@ -352,7 +356,9 @@ export function buildReviewPrompt(input: BuildReviewPromptInput): BuiltReviewPro
: ''
}\n</untrusted-artifact-list>`
: '(没有显式附件;请根据任务上下文,用只读工具检查当前工作目录中的实际成果。)';
- const coverage = coverageSection(input);
+ const coverage = coverageSection(input) + (input.historyCaptureIncomplete
+ ? '\n历史改动记录不完整,本次不把它当作完整补丁。审查以当前 Git 证据和显式成果为准;未提供的历史或未跟踪成果不得声称已覆盖。'
+ : '');
const prompt = `你是 Cindy 的独立成果审查员。你在一个全新、无开发历史记忆的只读任务中工作。
diff --git a/apps/desktop/src/main/reviewer/reviewWorkspaceSelection.ts b/apps/desktop/src/main/reviewer/reviewWorkspaceSelection.ts
new file mode 100644
index 0000000000..47d3c8625f
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/reviewWorkspaceSelection.ts
@@ -0,0 +1,42 @@
+import path from 'node:path';
+
+import { BrowserWindow, dialog, type IpcMainInvokeEvent } from 'electron';
+
+import { t } from '../i18n.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+
+/** No changes were found in the task's directory. Let the user choose the
+ * actual checkout, or explicitly review the current code without a diff.
+ * Selection grants only this Review read access; it never moves the source task.
+ */
+export async function selectReviewWorkspace(
+ event: IpcMainInvokeEvent,
+ workingDir: string,
+): Promise<string | null> {
+ assertTrustedAppRendererEvent(event);
+ const parent = BrowserWindow.fromWebContents(event.sender);
+ if (!parent || parent.isDestroyed()) return null;
+ const choice = await dialog.showMessageBox(parent, {
+ type: 'question',
+ title: t('review.workspaceSelection.title'),
+ message: t('review.workspaceSelection.message'),
+ detail: workingDir,
+ buttons: [
+ t('review.workspaceSelection.current'),
+ t('review.workspaceSelection.choose'),
+ t('common.cancel'),
+ ],
+ defaultId: 1,
+ cancelId: 2,
+ noLink: true,
+ });
+ if (parent.isDestroyed() || choice.response === 2) return null;
+ if (choice.response === 0) return workingDir;
+ const picked = await dialog.showOpenDialog(parent, {
+ title: t('review.workspaceSelection.title'),
+ buttonLabel: t('review.workspaceSelection.open'),
+ defaultPath: path.dirname(workingDir),
+ properties: ['openDirectory'],
+ });
+ return !parent.isDestroyed() && !picked.canceled && picked.filePaths[0] ? picked.filePaths[0] : null;
+}
diff --git a/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx b/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
index a6f6aa9b37..435ba60300 100644
--- a/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
@@ -85,6 +85,18 @@ describe('SystemCard Review', () => {
expect(screen.getByTestId('location').textContent).toBe('/cc-agent/review-task');
});
+ it('keeps an unverified conclusion visible and resolves its directory from the persisted Review target', () => {
+ renderCard({
+ status: 'failed', failureCode: 'artifact-unavailable', reviewerSessionId: 'review-task',
+ result: 'P1: src/auth.ts:42 needs attention',
+ workspace: { workingDir: '/repo/actual', baseRef: 'main', hasUncommittedChanges: true },
+ }, '/repo/main');
+ expect(screen.getByText('chat.systemCard.review.unverifiedResult')).toBeTruthy();
+ expect(screen.getByTestId('review-markdown').getAttribute('data-working-dir')).toBe('/repo/actual');
+ expect(screen.getByTestId('review-markdown').getAttribute('data-allow-privileged-links')).toBe('false');
+ expect(screen.getByText(/\/repo\/actual/)).toBeTruthy();
+ });
+
it('renders a completed stale result with its rerun reason', () => {
renderCard({
status: 'failed',
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index 0908cd61fb..92eb024192 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -1287,6 +1287,10 @@ function ReviewCard({ data, workingDir }: { data?: Record<string, unknown>; work
const reviewerSessionId =
typeof data?.reviewerSessionId === 'string' ? data.reviewerSessionId : '';
const result = typeof data?.result === 'string' ? data.result : '';
+ const workspace = data?.workspace && typeof data.workspace === 'object'
+ ? data.workspace as Record<string, unknown> : null;
+ const reviewedDir = typeof workspace?.workingDir === 'string' ? workspace.workingDir : workingDir;
+ const reviewedBase = typeof workspace?.baseRef === 'string' ? workspace.baseRef : '';
const error = typeof data?.error === 'string' ? data.error : '';
const failureCode =
readReviewFailureCode(data?.failureCode) ?? reviewFailureCodeFromLegacyError(error);
@@ -1327,6 +1331,12 @@ function ReviewCard({ data, workingDir }: { data?: Record<string, unknown>; work
</Button>
)}
</div>
+ {workspace && reviewedDir && (
+ <p className="mt-1 break-all pl-[23px] text-xs text-muted-foreground">
+ {t('chat.systemCard.review.directory')}{reviewedDir}
+ {reviewedBase && <> · {t('chat.systemCard.review.baseline')}{reviewedBase}</>}
+ </p>
+ )}
{status === 'running' && (
<p className="mt-1 pl-[23px] text-xs text-muted-foreground">
{t('chat.systemCard.review.readOnlyHint')}
@@ -1342,12 +1352,13 @@ function ReviewCard({ data, workingDir }: { data?: Record<string, unknown>; work
{failureMessage}
</p>
)}
- {(status === 'completed' || status === 'stale') && result && (
+ {result && status !== 'running' && (
<div className="mt-3 border-t border-border pt-3">
+ {status === 'failed' && <p className="mb-2 text-xs text-muted-foreground">{t('chat.systemCard.review.unverifiedResult')}</p>}
<MarkdownRenderer
content={result}
- workingDir={workingDir ?? ''}
- allowPrivilegedLinks={status !== 'stale'}
+ workingDir={reviewedDir ?? ''}
+ allowPrivilegedLinks={status === 'completed'}
/>
</div>
)}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 32fce95901..a22734a060 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -3331,6 +3331,7 @@ export function CCAgentSessionView({
return { handled: true, accepted: true, message };
} catch (err) {
const ipcError = extractIpcError(err);
+ if (ipcError?.code === 'MUTATION_CANCELLED') return { handled: true, accepted: false, message };
toast.error(
ipcError
? t('review.toast.failed')
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 9b0ee18888..2f30b213d0 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -10185,9 +10185,12 @@
"sourceConversationChanged": "The source task changed. Run /review again for the current task.",
"sourceFilesChanged": "The source task files changed. Run /review again for the current result.",
"artifactChanged": "A review artifact changed. Run /review again for the current result.",
- "artifactUnavailable": "Cindy couldn't safely read the review artifacts. Check the workspace or attachments, then run /review again.",
+ "artifactUnavailable": "Cindy could not prepare the files for review. Check the selected directory or attachments, then run /review again.",
"providerFailed": "The review task failed"
- }
+ },
+ "directory": "Directory: ",
+ "baseline": "Base branch: ",
+ "unverifiedResult": "The reviewer produced these findings, but their validity could not be verified."
}
},
"markdownRenderer": {
@@ -13317,6 +13320,13 @@
"inline": "in-memory attachment",
"allow": "Allow once",
"cancel": "Cancel"
+ },
+ "workspaceSelection": {
+ "title": "Choose code to review",
+ "message": "No code diff is available in this directory. Review the current code, or select the directory where you worked.",
+ "current": "Review this directory",
+ "choose": "Choose another directory",
+ "open": "Review"
}
},
"learn": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index cf21a27b81..6bd73ca109 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -10168,9 +10168,12 @@
"sourceConversationChanged": "元のタスクが変更されました。現在のタスクに対して /review をもう一度実行してください。",
"sourceFilesChanged": "元のタスクのファイルが変更されました。現在の成果に対して /review をもう一度実行してください。",
"artifactChanged": "レビュー対象の成果が変更されました。現在の成果に対して /review をもう一度実行してください。",
- "artifactUnavailable": "Cindy はレビュー対象の成果を安全に読み取れませんでした。ワークスペースまたは添付ファイルを確認して、/review をもう一度実行してください。",
+ "artifactUnavailable": "レビュー用のファイルを準備できませんでした。選択したフォルダーまたは添付ファイルを確認し、/review を再実行してください。",
"providerFailed": "レビュータスクの実行に失敗しました"
- }
+ },
+ "directory": "フォルダー:",
+ "baseline": "基準ブランチ:",
+ "unverifiedResult": "以下の指摘は生成されましたが、現在も有効か確認できませんでした。"
}
},
"markdownRenderer": {
@@ -13289,6 +13292,13 @@
"inline": "メモリ内の添付ファイル",
"allow": "今回のみ許可",
"cancel": "キャンセル"
+ },
+ "workspaceSelection": {
+ "title": "レビューするコードを選択",
+ "message": "このディレクトリには利用できるコード差分がありません。現在のコードをレビューするか、実際に開発したディレクトリを選択できます。",
+ "current": "このフォルダーを確認",
+ "choose": "別のフォルダーを選択",
+ "open": "レビュー"
}
},
"learn": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 533f8d72b2..679bbca32f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -10168,9 +10168,12 @@
"sourceConversationChanged": "원본 작업이 변경되었습니다. 현재 작업에 대해 /review를 다시 실행하세요.",
"sourceFilesChanged": "원본 작업의 파일이 변경되었습니다. 현재 결과물에 대해 /review를 다시 실행하세요.",
"artifactChanged": "검토 대상 결과물이 변경되었습니다. 현재 결과물에 대해 /review를 다시 실행하세요.",
- "artifactUnavailable": "Cindy가 검토 대상 결과물을 안전하게 읽지 못했습니다. 작업 공간 또는 첨부 파일을 확인한 후 /review를 다시 실행하세요.",
+ "artifactUnavailable": "검토할 파일을 준비하지 못했습니다. 선택한 폴더나 첨부 파일을 확인한 후 /review를 다시 실행하세요.",
"providerFailed": "검토 작업 실행에 실패했습니다"
- }
+ },
+ "directory": "폴더: ",
+ "baseline": "기준 브랜치: ",
+ "unverifiedResult": "아래 결과가 생성되었지만 현재도 유효한지 확인하지 못했습니다."
}
},
"markdownRenderer": {
@@ -13289,6 +13292,13 @@
"inline": "메모리 첨부 파일",
"allow": "이번만 허용",
"cancel": "취소"
+ },
+ "workspaceSelection": {
+ "title": "검토할 코드 선택",
+ "message": "이 디렉터리에는 사용할 수 있는 코드 차이가 없습니다. 현재 코드를 검토하거나 실제 개발한 디렉터리를 선택하세요.",
+ "current": "현재 폴더 검토",
+ "choose": "다른 폴더 선택",
+ "open": "검토"
}
},
"learn": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 530cd2fee5..4cee33795e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -10168,9 +10168,12 @@
"sourceConversationChanged": "来源任务已变化,请针对当前任务重新运行 /review。",
"sourceFilesChanged": "来源任务的文件已变化,请针对当前成果重新运行 /review。",
"artifactChanged": "审查成果已变化,请针对当前成果重新运行 /review。",
- "artifactUnavailable": "Cindy 无法安全读取审查成果,请检查工作区或附件后重新运行 /review。",
+ "artifactUnavailable": "Cindy 无法准备审查文件,请检查所选目录或附件后重新运行 /review。",
"providerFailed": "审查任务执行失败"
- }
+ },
+ "directory": "目录:",
+ "baseline": "基线分支:",
+ "unverifiedResult": "以下结论已生成,但未能验证是否仍然有效。"
}
},
"markdownRenderer": {
@@ -13289,6 +13292,13 @@
"inline": "内存附件",
"allow": "仅本次允许",
"cancel": "取消"
+ },
+ "workspaceSelection": {
+ "title": "选择要审查的代码",
+ "message": "这个目录没有可用的代码差异。可以审查当前代码,或选择实际开发的目录。",
+ "current": "审查当前目录",
+ "choose": "选择其他目录",
+ "open": "审查"
}
},
"learn": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 02f454feb4..0f44057f73 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -10168,8 +10168,11 @@
"sourceFilesChanged": "來源任務的檔案已變更,請針對當前成果重新執行 /review。",
"artifactChanged": "審查成果已變更,請針對當前成果重新執行 /review。",
"providerFailed": "審查任務執行失敗",
- "artifactUnavailable": "Cindy 無法安全讀取審查成品,請檢查工作區或附件後重新執行 /review"
- }
+ "artifactUnavailable": "Cindy 無法準備審查檔案,請檢查所選目錄或附件後重新執行 /review。"
+ },
+ "directory": "目錄:",
+ "baseline": "基準分支:",
+ "unverifiedResult": "以下結論已產生,但未能驗證是否仍然有效。"
}
},
"markdownRenderer": {
@@ -13289,6 +13292,13 @@
"inline": "記憶體附件",
"allow": "僅本次允許",
"cancel": "取消"
+ },
+ "workspaceSelection": {
+ "title": "選擇要審查的程式碼",
+ "message": "這個目錄沒有可用的程式碼差異。可以審查目前程式碼,或選擇實際開發的目錄。",
+ "current": "審查目前目錄",
+ "choose": "選擇其他目錄",
+ "open": "審查"
}
},
"learn": {
diff --git a/apps/desktop/src/shared/reviewRun.ts b/apps/desktop/src/shared/reviewRun.ts
index c81254148e..2b13961f6d 100644
--- a/apps/desktop/src/shared/reviewRun.ts
+++ b/apps/desktop/src/shared/reviewRun.ts
@@ -147,6 +147,12 @@ export interface ReviewRunMeta {
reviewerSessionId?: string;
status: ReviewRunStatus;
targetKind: ReviewTargetKind;
+ /** Exact host-selected read scope, never the source task's stale label. */
+ workspace?: {
+ workingDir: string;
+ baseRef?: string;
+ hasUncommittedChanges: boolean;
+ };
startedAt: number;
/**
* Present on runs created by owner-aware clients. Optional only so cards
diff --git a/docs/product-rules/review-product-direction.md b/docs/product-rules/review-product-direction.md
index 0e4551a532..00ac24a03a 100644
--- a/docs/product-rules/review-product-direction.md
+++ b/docs/product-rules/review-product-direction.md
@@ -67,6 +67,14 @@ DeepSeek 等模型只要能在相应 harness 的普通任务中使用,也应
权限、目录等冻结配置。
- Reviewer 只复核,不自动修码。修复回到来源任务,修复后的成果需要再次复核。
+### 代码自审的审阅对象与恢复
+
+- `/review` 默认覆盖当前开发目录中本分支相对基线的已提交改动及未提交修改,不能因为工作区有未提交修改就省略分支改动。
+- 从任务的实际开发目录取证,Reviewer 读取和完成后的有效性校验也固定在同一目录;不能用 worktree 的补丁配项目主目录里的源码。来源任务本身的目录不因此被修改。
+- 找不到代码改动时,本机入口让用户选择实际开发目录,或明确审查当前目录的代码。结果卡展示实际目录与比较基线。
+- 历史变更捕获服务于回看与撤销,不是 Review 的启动资格。命令调用、并发或摘要截断造成的历史记录缺口,不能阻止基于实时 Git 证据或显式成果的审查。缺口必须说明,不能把不完整历史冒充完整比较基线。
+- Reviewer 已生成结论但后续校验失败时,保留结论作为未验证的只读记录,不能显示为成功或启用文件操作链接;不得清空结论后误导用户认为没有产出。
+
### 1.4 方法与专业边界
Review 可以借鉴成熟 code review 的缺陷标准、P0-P3、精确证据、结构化输出、只报告本次