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): close isolated evidence recovery gaps

Chris4686afd074da
diff --git a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
index 79ddc20467..434d3f0e72 100644
--- a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
+++ b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
@@ -12,7 +12,12 @@ const writeFile = vi.hoisted(() => vi.fn(async () => {}));
const mkdir = vi.hoisted(() => vi.fn(async () => {}));
const chmod = vi.hoisted(() => vi.fn(async () => {}));
const lstat = vi.hoisted(() =>
- vi.fn(async () => ({ isDirectory: () => true, isSymbolicLink: () => false })),
+ vi.fn(async (target: string) => {
+ if (target.endsWith('.cindy-owner.json')) {
+ throw Object.assign(new Error('not found'), { code: 'ENOENT' });
+ }
+ return { isDirectory: () => true, isSymbolicLink: () => false };
+ }),
);
const readFile = vi.hoisted(() => vi.fn(async () => Buffer.from('image-bytes')));
vi.mock('node:fs/promises', () => ({
@@ -142,7 +147,7 @@ describe('normalizeUserMessage — device-link 出方向 OSS 引用物化', () =
expect(downloadToFile).toHaveBeenCalledTimes(1);
const [ossKeyArg, destArg] = downloadToFile.mock.calls[0] as unknown as [string, string];
expect(ossKeyArg).toBe('cindy/device-link/u/x.png');
- expect(destArg).toMatch(/cindy-attachments[\\/]sess-1[\\/].+\.png$/);
+ expect(destArg).toMatch(/cindy-attachments[\\/]v2-[^\\/]+[\\/]sess-1[\\/].+\.png$/);
const block = (out as { content: Array<{ type: string; path?: string; mimeType?: string }> })
.content[1];
expect(block.path).toBe(destArg); // path 指向下载目标
diff --git a/apps/desktop/src/main/git-review/__tests__/ipc.test.ts b/apps/desktop/src/main/git-review/__tests__/ipc.test.ts
index 7102653c7f..51aa6886c7 100644
--- a/apps/desktop/src/main/git-review/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/ipc.test.ts
@@ -7,9 +7,10 @@ import {
parseMarkdownPreviewPayload,
parseOpenFilePayload,
parseTarget,
+ readReviewData,
runReviewFileStageOperation,
} from '../ipc';
-import type { FileDiff, GitReviewDeps } from '../types';
+import type { FileDiff, GitReviewDeps, ReviewScope, ReviewStatus } from '../types';
const HEX_OID = '0123456789abcdef0123456789abcdef01234567';
const SHORT_HEX_OID = 'abc1234';
@@ -126,6 +127,33 @@ describe('git-review IPC payload guards', () => {
});
});
+describe('git-review evidence failures', () => {
+ it.each(['resolveScope', 'readStatus', 'readDiffs'] as const)(
+ 'propagates %s errors instead of manufacturing an empty non-Git result',
+ async (failingStage) => {
+ const failure = new Error(`${failingStage} failed`);
+ const scope = { disabledReason: null, repoRoot: '/repo' } as ReviewScope;
+ const status = { scope } as ReviewStatus;
+ const deps: GitReviewDeps = {
+ resolveScope: vi.fn(async () => {
+ if (failingStage === 'resolveScope') throw failure;
+ return scope;
+ }),
+ readStatus: vi.fn(async () => {
+ if (failingStage === 'readStatus') throw failure;
+ return status;
+ }),
+ readDiffs: vi.fn(async () => {
+ if (failingStage === 'readDiffs') throw failure;
+ return { staged: [], unstaged: [], capped: { staged: null, unstaged: null } };
+ }),
+ };
+
+ await expect(readReviewData('s1', deps)).rejects.toBe(failure);
+ },
+ );
+});
+
describe('git-review write busy gate', () => {
it('rejects queued writes before resolving or touching a repository', async () => {
const deps: GitReviewDeps = {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
index 6be169e2c8..d3975df770 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
@@ -25,13 +25,22 @@ vi.mock('../../logger.js', () => ({
createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
-import { cleanupSessionTempAttachments, normalizeUserMessage } from '../normalizeAttachments.js';
+import {
+ cleanupOrphanedTempAttachments,
+ cleanupSessionTempAttachments,
+ configureTempAttachmentOwner,
+ normalizeUserMessage,
+} from '../normalizeAttachments.js';
const tempDirs: string[] = [];
beforeEach(async () => {
tempRoot.value = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-review-inline-test-'));
tempDirs.push(tempRoot.value);
+ configureTempAttachmentOwner({
+ instanceId: 'normalize-attachments-test-owner',
+ processId: process.pid,
+ });
});
afterEach(async () => {
@@ -59,8 +68,20 @@ describe('inline attachment temporary files', () => {
const imagePath = imageBlock?.path;
if (typeof imagePath !== 'string') throw new Error('expected materialized image path');
const sessionTempDir = path.dirname(imagePath);
+ const ownerRoot = path.dirname(sessionTempDir);
+ const ownerRecord = JSON.parse(
+ await fs.readFile(path.join(ownerRoot, '.cindy-owner.json'), 'utf8'),
+ ) as Record<string, unknown>;
await expect(fs.readFile(imagePath, 'utf8')).resolves.toBe('private image bytes');
+ expect(ownerRecord).toMatchObject({
+ version: 1,
+ owner: {
+ instanceId: 'normalize-attachments-test-owner',
+ processId: process.pid,
+ },
+ });
+ expect(ownerRecord.expiresAt).toEqual(expect.any(Number));
if (process.platform !== 'win32') {
expect((await fs.stat(sessionTempDir)).mode & 0o777).toBe(0o700);
expect((await fs.stat(imagePath)).mode & 0o777).toBe(0o600);
@@ -69,9 +90,107 @@ describe('inline attachment temporary files', () => {
await cleanupSessionTempAttachments(sessionId);
await expect(fs.lstat(sessionTempDir)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.lstat(ownerRoot)).rejects.toMatchObject({ code: 'ENOENT' });
await cleanupSessionTempAttachments(sessionId);
});
+ it('reclaims a persisted owner root after its Main process terminates', async () => {
+ const normalized = await normalizeUserMessage('reviewer-crashed', {
+ type: 'user',
+ content: [{
+ type: 'image',
+ base64: Buffer.from('private image bytes').toString('base64'),
+ mimeType: 'image/png',
+ }],
+ });
+ if (typeof normalized === 'string' || typeof normalized.content === 'string') {
+ throw new Error('expected block message');
+ }
+ const imagePath = normalized.content[0]?.path;
+ if (typeof imagePath !== 'string') throw new Error('expected materialized image path');
+ const ownerRoot = path.dirname(path.dirname(imagePath));
+
+ await cleanupOrphanedTempAttachments({
+ currentOwner: { instanceId: 'restarted-main', processId: process.pid },
+ root: path.join(tempRoot.value, 'cindy-attachments'),
+ });
+
+ await expect(fs.lstat(ownerRoot)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('coalesces concurrent owner-root creation without dropping either attachment', async () => {
+ const makeMessage = (text: string) => ({
+ type: 'user' as const,
+ content: [{
+ type: 'file',
+ base64: Buffer.from(text).toString('base64'),
+ mimeType: 'text/plain',
+ }],
+ });
+ const [first, second] = await Promise.all([
+ normalizeUserMessage('concurrent-a', makeMessage('first')),
+ normalizeUserMessage('concurrent-b', makeMessage('second')),
+ ]);
+ if (
+ typeof first === 'string' ||
+ typeof first.content === 'string' ||
+ typeof second === 'string' ||
+ typeof second.content === 'string'
+ ) {
+ throw new Error('expected block messages');
+ }
+ const firstPath = first.content[0]?.path;
+ const secondPath = second.content[0]?.path;
+ expect(typeof firstPath).toBe('string');
+ expect(typeof secondPath).toBe('string');
+ expect(path.dirname(path.dirname(firstPath as string))).toBe(
+ path.dirname(path.dirname(secondPath as string)),
+ );
+
+ await Promise.all([
+ cleanupSessionTempAttachments('concurrent-a'),
+ cleanupSessionTempAttachments('concurrent-b'),
+ ]);
+ });
+
+ it('keeps an ambiguous live owner until its persisted deadline, then reclaims it', async () => {
+ const normalized = await normalizeUserMessage('reviewer-ambiguous', {
+ type: 'user',
+ content: [{
+ type: 'file',
+ base64: Buffer.from('private document bytes').toString('base64'),
+ mimeType: 'application/pdf',
+ }],
+ });
+ if (typeof normalized === 'string' || typeof normalized.content === 'string') {
+ throw new Error('expected block message');
+ }
+ const filePath = normalized.content[0]?.path;
+ if (typeof filePath !== 'string') throw new Error('expected materialized file path');
+ const ownerRoot = path.dirname(path.dirname(filePath));
+ const record = JSON.parse(
+ await fs.readFile(path.join(ownerRoot, '.cindy-owner.json'), 'utf8'),
+ ) as { expiresAt: number };
+ const sharedRoot = path.join(tempRoot.value, 'cindy-attachments');
+ const currentOwner = { instanceId: 'other-live-main', processId: process.pid + 100_000 };
+
+ await cleanupOrphanedTempAttachments({
+ currentOwner,
+ root: sharedRoot,
+ processIsAlive: () => true,
+ now: () => record.expiresAt - 1,
+ });
+ await expect(fs.lstat(ownerRoot)).resolves.toMatchObject({});
+
+ await cleanupOrphanedTempAttachments({
+ currentOwner,
+ root: sharedRoot,
+ processIsAlive: () => true,
+ now: () => record.expiresAt,
+ });
+ await expect(fs.lstat(ownerRoot)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
it.each(['shared root', 'session directory'] as const)(
'refuses a symlinked temporary attachment %s',
async (target) => {
@@ -83,7 +202,16 @@ describe('inline attachment temporary files', () => {
await fs.symlink(outside, sharedRoot);
} else {
await fs.mkdir(sharedRoot);
- await fs.symlink(outside, path.join(sharedRoot, 'reviewer-session'));
+ await normalizeUserMessage('seed-session', {
+ type: 'user',
+ content: [{
+ type: 'file',
+ base64: Buffer.from('seed').toString('base64'),
+ mimeType: 'text/plain',
+ }],
+ });
+ const [ownerRootName] = await fs.readdir(sharedRoot);
+ await fs.symlink(outside, path.join(sharedRoot, ownerRootName, 'reviewer-session'));
}
const normalized = await normalizeUserMessage('reviewer-session', {
@@ -103,6 +231,9 @@ describe('inline attachment temporary files', () => {
}
expect(normalized.content).toEqual([{ type: 'text', text: 'Review this image' }]);
await expect(fs.readdir(outside)).resolves.toEqual([]);
+ if (target === 'session directory') {
+ await cleanupSessionTempAttachments('seed-session');
+ }
},
);
});
diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
index 5a7ea6882b..39ede26e34 100644
--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
@@ -19,6 +19,7 @@
import { app } from 'electron';
import path from 'node:path';
+import { constants, type Stats } from 'node:fs';
import fs from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
@@ -32,10 +33,40 @@ import type { AttachmentIntegrity, AttachmentOssRef } from '../../shared/attachm
import { downloadToFile, removeRemote } from '../device-link/mediaTransfer.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { isDangerousAttachmentName } from '../../shared/attachmentSafety.js';
+import { readReviewRunOwner, type ReviewRunOwner } from '../../shared/reviewRun.js';
+import {
+ reviewRunOwnerStatus,
+ type ReviewOwnerLivenessProbe,
+ type ReviewProcessAliveProbe,
+} from '../reviewer/reviewRunRecovery.js';
const log = createLogger('maker-ipc/normalize');
const TEMP_DIRS_BY_SESSION = new Map<string, string>();
+const TEMP_OWNER_ROOT_PREFIX = 'v2-';
+const TEMP_OWNER_ROOT_NONCE = randomUUID();
+const TEMP_OWNER_ROOT_NAME = /^v2-(\d+)-([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i;
+const TEMP_OWNER_RECORD_NAME = '.cindy-owner.json';
+const TEMP_OWNER_RECORD_MAX_BYTES = 4 * 1024;
+const TEMP_OWNER_MAX_AGE_MS = 24 * 60 * 60 * 1_000;
+const NOFOLLOW_FLAG = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0;
+const TEMP_OWNER_ROOT_PREPARATIONS = new Map<string, Promise<string>>();
+let tempAttachmentOwner: ReviewRunOwner = {
+ instanceId: randomUUID(),
+ processId: process.pid,
+};
+
+interface TempAttachmentOwnerRecord {
+ version: 1;
+ createdAt: number;
+ expiresAt: number;
+ owner: ReviewRunOwner;
+}
+
+/** Share the exact Main-process identity used by Review lifecycle recovery. */
+export function configureTempAttachmentOwner(owner: ReviewRunOwner): void {
+ tempAttachmentOwner = owner;
+}
const EXT_BY_MIME: Record<string, string> = {
'image/png': '.png',
@@ -56,9 +87,16 @@ function tempRoot(): string {
return path.join(app.getPath('temp'), 'cindy-attachments');
}
+function tempOwnerRoot(): string {
+ return path.join(
+ tempRoot(),
+ `${TEMP_OWNER_ROOT_PREFIX}${process.pid}-${TEMP_OWNER_ROOT_NONCE}`,
+ );
+}
+
function tempDirFor(sessionId: string): string {
assertSafeTempSessionId(sessionId);
- return path.join(tempRoot(), sessionId);
+ return path.join(tempOwnerRoot(), sessionId);
}
async function assertRealTempDirectory(dir: string): Promise<void> {
@@ -68,13 +106,139 @@ async function assertRealTempDirectory(dir: string): Promise<void> {
}
}
+function tempOwnerRecordPath(ownerRoot: string): string {
+ return path.join(ownerRoot, TEMP_OWNER_RECORD_NAME);
+}
+
+function statMatches(before: Stats, after: Stats): boolean {
+ return (
+ before.dev === after.dev &&
+ before.ino === after.ino &&
+ before.size === after.size &&
+ before.mtimeMs === after.mtimeMs &&
+ before.ctimeMs === after.ctimeMs &&
+ before.mode === after.mode
+ );
+}
+
+function parseTempOwnerRecord(value: unknown): TempAttachmentOwnerRecord | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ const owner = readReviewRunOwner(record.owner);
+ if (
+ record.version !== 1 ||
+ typeof record.createdAt !== 'number' ||
+ !Number.isFinite(record.createdAt) ||
+ record.createdAt <= 0 ||
+ typeof record.expiresAt !== 'number' ||
+ !Number.isFinite(record.expiresAt) ||
+ record.expiresAt <= record.createdAt ||
+ record.expiresAt - record.createdAt > TEMP_OWNER_MAX_AGE_MS ||
+ !owner
+ ) {
+ return null;
+ }
+ return {
+ version: 1,
+ createdAt: record.createdAt,
+ expiresAt: record.expiresAt,
+ owner,
+ };
+}
+
+async function loadTempOwnerRecord(
+ ownerRoot: string,
+ currentUid: number | null,
+): Promise<TempAttachmentOwnerRecord | null> {
+ const recordPath = tempOwnerRecordPath(ownerRoot);
+ const before = await fs.lstat(recordPath).catch(() => null);
+ if (
+ !before ||
+ before.isSymbolicLink() ||
+ !before.isFile() ||
+ before.size > TEMP_OWNER_RECORD_MAX_BYTES ||
+ (currentUid !== null && before.uid !== currentUid)
+ ) {
+ return null;
+ }
+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
+ try {
+ handle = await fs.open(recordPath, constants.O_RDONLY | NOFOLLOW_FLAG);
+ const opened = await handle.stat();
+ if (!statMatches(before, opened)) return null;
+ const raw = await handle.readFile({ encoding: 'utf8' });
+ const afterHandle = await handle.stat();
+ const afterPath = await fs.lstat(recordPath).catch(() => null);
+ if (
+ !statMatches(opened, afterHandle) ||
+ !afterPath ||
+ afterPath.isSymbolicLink() ||
+ !statMatches(opened, afterPath)
+ ) {
+ return null;
+ }
+ return parseTempOwnerRecord(JSON.parse(raw) as unknown);
+ } catch {
+ return null;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+}
+
+async function ensureTempOwnerRoot(): Promise<string> {
+ const sharedRoot = tempRoot();
+ const ownerRoot = tempOwnerRoot();
+ const pending = TEMP_OWNER_ROOT_PREPARATIONS.get(ownerRoot);
+ if (pending) return pending;
+ const preparation = (async () => {
+ await fs.mkdir(sharedRoot, { recursive: true, mode: 0o700 });
+ await assertRealTempDirectory(sharedRoot);
+ await fs.chmod(sharedRoot, 0o700);
+ await fs.mkdir(ownerRoot, { recursive: true, mode: 0o700 });
+ await assertRealTempDirectory(ownerRoot);
+ await fs.chmod(ownerRoot, 0o700);
+
+ const recordPath = tempOwnerRecordPath(ownerRoot);
+ const currentUid = typeof process.getuid === 'function' ? process.getuid() : null;
+ const existing = await loadTempOwnerRecord(ownerRoot, currentUid);
+ if (existing) {
+ if (
+ existing.owner.instanceId !== tempAttachmentOwner.instanceId ||
+ existing.owner.processId !== tempAttachmentOwner.processId
+ ) {
+ throw new Error('Temporary attachment directory belongs to another process');
+ }
+ return ownerRoot;
+ }
+ if (await fs.lstat(recordPath).catch(() => null)) {
+ throw new Error('Temporary attachment owner record is invalid');
+ }
+
+ const createdAt = Date.now();
+ const record: TempAttachmentOwnerRecord = {
+ version: 1,
+ createdAt,
+ expiresAt: createdAt + TEMP_OWNER_MAX_AGE_MS,
+ owner: tempAttachmentOwner,
+ };
+ await fs.writeFile(recordPath, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
+ await fs.chmod(recordPath, 0o600);
+ return ownerRoot;
+ })();
+ TEMP_OWNER_ROOT_PREPARATIONS.set(ownerRoot, preparation);
+ try {
+ return await preparation;
+ } finally {
+ if (TEMP_OWNER_ROOT_PREPARATIONS.get(ownerRoot) === preparation) {
+ TEMP_OWNER_ROOT_PREPARATIONS.delete(ownerRoot);
+ }
+ }
+}
+
/** 在 session 临时目录下分配一个唯一文件路径(建目录,不写内容)。 */
async function ensureTempPath(sessionId: string, mimeType: string | undefined): Promise<string> {
- const root = tempRoot();
+ const root = await ensureTempOwnerRoot();
const dir = tempDirFor(sessionId);
- await fs.mkdir(root, { recursive: true, mode: 0o700 });
- await assertRealTempDirectory(root);
- await fs.chmod(root, 0o700);
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
await assertRealTempDirectory(dir);
await fs.chmod(dir, 0o700);
@@ -737,7 +901,81 @@ export async function cleanupSessionTempAttachments(sessionId: string): Promise<
TEMP_DIRS_BY_SESSION.delete(sessionId);
try {
await fs.rm(dir, { recursive: true, force: true });
+ const ownerRoot = path.dirname(dir);
+ const ownerStillInUse = [...TEMP_DIRS_BY_SESSION.values()].some(
+ (candidate) => path.dirname(candidate) === ownerRoot,
+ );
+ if (!ownerStillInUse) {
+ const remaining = await fs.readdir(ownerRoot).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ });
+ if (remaining?.every((entry) => entry === TEMP_OWNER_RECORD_NAME)) {
+ await fs.rm(ownerRoot, { recursive: true, force: true });
+ }
+ }
} catch (e) {
log.warn('cleanup temp attachments failed', { sessionId, error: String(e) });
}
}
+
+/**
+ * Reclaim attachment roots left by a crashed Main process. Only versioned,
+ * PID-scoped roots with a same-user owner record enter this cleanup boundary;
+ * ambiguous live owners survive until their persisted deadline.
+ */
+export async function cleanupOrphanedTempAttachments(options: {
+ currentOwner: ReviewRunOwner;
+ root?: string;
+ processIsAlive?: ReviewProcessAliveProbe;
+ ownerLivenessProbe?: ReviewOwnerLivenessProbe;
+ now?: () => number;
+}): Promise<void> {
+ const sharedRoot = options.root ?? tempRoot();
+ const entries = await fs.readdir(sharedRoot, { withFileTypes: true }).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ });
+ if (entries.length === 0) return;
+ await assertRealTempDirectory(sharedRoot);
+ const currentUid = typeof process.getuid === 'function' ? process.getuid() : null;
+ const now = options.now?.() ?? Date.now();
+
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const match = TEMP_OWNER_ROOT_NAME.exec(entry.name);
+ if (!match) continue;
+ const ownerPid = Number(match[1]);
+ if (!Number.isSafeInteger(ownerPid) || ownerPid <= 0) continue;
+
+ const candidate = path.join(sharedRoot, entry.name);
+ const stat = await fs.lstat(candidate).catch(() => null);
+ if (
+ !stat ||
+ stat.isSymbolicLink() ||
+ !stat.isDirectory() ||
+ (currentUid !== null && stat.uid !== currentUid)
+ ) {
+ continue;
+ }
+ const record = await loadTempOwnerRecord(candidate, currentUid);
+ if (!record || record.owner.processId !== ownerPid) {
+ const lastKnownActiveAt = Math.max(stat.birthtimeMs, stat.ctimeMs, stat.mtimeMs);
+ if (now - lastKnownActiveAt < TEMP_OWNER_MAX_AGE_MS) continue;
+ await fs.rm(candidate, { recursive: true, force: true });
+ continue;
+ }
+ const status = await reviewRunOwnerStatus(
+ record.owner,
+ options.currentOwner,
+ options.processIsAlive,
+ options.ownerLivenessProbe,
+ );
+ if (status === 'alive') continue;
+ if (status === 'unknown' && now < record.expiresAt) continue;
+ for (const [sessionId, dir] of TEMP_DIRS_BY_SESSION) {
+ if (path.dirname(dir) === candidate) TEMP_DIRS_BY_SESSION.delete(sessionId);
+ }
+ await fs.rm(candidate, { recursive: true, force: true });
+ }
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 9b34f7378e..b092994ec9 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -554,7 +554,9 @@ import {
} from './interactionRouter.js';
import { registerMakerMessageDeleteHandler } from './messageDeleteHandler.js';
import {
+ cleanupOrphanedTempAttachments,
cleanupSessionTempAttachments,
+ configureTempAttachmentOwner,
normalizeUserMessage,
materializeDirectSendOssAttachments,
materializeQueuedOssAttachmentsDeferred,
@@ -2439,6 +2441,7 @@ const reviewRunOwner: ReviewRunOwner = {
instanceId: randomUUID(),
processId: process.pid,
};
+configureTempAttachmentOwner(reviewRunOwner);
const ensureReviewOwnerLivenessReady = createRetryableReviewStartup(async () => {
const handle = await startReviewOwnerLiveness();
reviewRunOwner.liveness = handle.identity;
@@ -6809,6 +6812,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
reconcileInterruptedReviews(),
sessionTurnLeaseTracker.reconcileStaleLeases(),
cleanupOrphanedReviewArtifactSnapshots({ currentOwner: reviewRunOwner }),
+ cleanupOrphanedTempAttachments({ currentOwner: reviewRunOwner }),
]);
} catch (error) {
log.error('failed to prepare Review runtime state', {
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
index 1b1529375d..9e4be28bc6 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewEvidence.test.ts
@@ -91,7 +91,7 @@ async function tempDir(): Promise<string> {
}
beforeEach(() => {
- readReviewDataMock.mockResolvedValue(null);
+ readReviewDataMock.mockResolvedValue(nonGitReviewData());
utilityProcessFork.mockImplementation(() => new RejectingPdfUtility());
});
@@ -182,7 +182,63 @@ function cappedReviewData(repoRoot: string, filePath: string): ReviewData {
};
}
+function nonGitReviewData(): ReviewData {
+ const scope = {
+ sessionId: 'source',
+ workdir: '/tmp/non-git-review',
+ worktreePath: null,
+ workingDir: '/tmp/non-git-review',
+ repoRoot: null,
+ branch: null,
+ headOid: null,
+ isDetached: false,
+ isUnborn: false,
+ source: 'workingDir' as const,
+ aheadBehind: { ahead: 0, behind: 0, upstream: null, stale: false },
+ disabledReason: 'non-git' as const,
+ disabledMessage: 'Not a Git repository',
+ resolutionChain: [],
+ };
+ return {
+ scope,
+ status: null,
+ diffs: { staged: [], unstaged: [], capped: { staged: null, unstaged: null } },
+ summary: {
+ sessionId: 'source',
+ disabledReason: 'non-git',
+ disabledMessage: 'Not a Git repository',
+ totalFiles: 0,
+ stagedFiles: 0,
+ unstagedFiles: 0,
+ untrackedFiles: 0,
+ unmergedFiles: 0,
+ dirty: false,
+ },
+ };
+}
+
describe('readReviewWorkspaceSnapshot', () => {
+ it('fails closed when the Git evidence read throws instead of treating it as non-Git', async () => {
+ const failure = new Error('git index is locked');
+ readReviewDataMock.mockRejectedValue(failure);
+
+ await expect(readReviewWorkspaceSnapshot('source')).rejects.toBe(failure);
+ expect(readReviewDataMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails closed when the confirming Git evidence read throws', async () => {
+ const repoRoot = await tempDir();
+ const relativePath = 'large.ts';
+ await fs.writeFile(path.join(repoRoot, relativePath), 'aaa111zzz');
+ const failure = new Error('git diff became unreadable');
+ readReviewDataMock
+ .mockResolvedValueOnce(cappedReviewData(repoRoot, relativePath))
+ .mockRejectedValueOnce(failure);
+
+ await expect(readReviewWorkspaceSnapshot('source')).rejects.toBe(failure);
+ expect(readReviewDataMock).toHaveBeenCalledTimes(2);
+ });
+
it('changes the fingerprint for a same-size capped file replacement', async () => {
const repoRoot = await tempDir();
const relativePath = 'large.ts';
diff --git a/apps/desktop/src/main/reviewer/reviewEvidence.ts b/apps/desktop/src/main/reviewer/reviewEvidence.ts
index 614b8a91b2..8da763422d 100644
--- a/apps/desktop/src/main/reviewer/reviewEvidence.ts
+++ b/apps/desktop/src/main/reviewer/reviewEvidence.ts
@@ -177,11 +177,11 @@ export async function readReviewWorkspaceSnapshot(
): Promise<{ workspace: ReviewWorkspaceEvidence; fingerprint: string | null } | null> {
const deps = { ...defaultReviewWorkspaceSnapshotDeps, ...depsInput };
for (let attempt = 0; attempt < 3; attempt += 1) {
- const reviewData = await deps.readReviewData(sourceSessionId).catch((error) => {
- if (attempt === 0) return null;
- throw error;
- });
- if (!reviewData) return null;
+ // A normal non-Git task is represented by ReviewData with a disabled scope.
+ // An exception means Git evidence could not be read and must abort Review;
+ // turning it into null would incorrectly publish a completed, evidence-free
+ // result for a task that may in fact be a Git workspace.
+ const reviewData = await deps.readReviewData(sourceSessionId);
try {
const current = await buildReviewWorkspaceSnapshot(
reviewData,
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
index fb9cb080a6..3a4bd97cd2 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
@@ -307,7 +307,12 @@ describe('ClaudeCodeAgent plan mode', () => {
})).rejects.toThrow(/refused/i);
await expect(
reviewHook({ hook_event_name: 'PreToolUse', tool_name: 'Read' }),
- ).resolves.toEqual({ continue: true });
+ ).resolves.toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'allow',
+ updatedInput: { file_path: await fs.realpath(workingDir) },
+ },
+ });
await expect(reviewHook({
hook_event_name: 'PreToolUse',
tool_name: 'Read',
@@ -325,7 +330,12 @@ describe('ClaudeCodeAgent plan mode', () => {
hook_event_name: 'PreToolUse',
tool_name: 'Grep',
tool_input: { path: workingDir, pattern: 'value' },
- })).resolves.toEqual({ continue: true });
+ })).resolves.toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'allow',
+ updatedInput: { path: await fs.realpath(workingDir), pattern: 'value' },
+ },
+ });
await expect(reviewHook({
hook_event_name: 'PreToolUse',
tool_name: 'Grep',
@@ -335,12 +345,22 @@ describe('ClaudeCodeAgent plan mode', () => {
hook_event_name: 'PreToolUse',
tool_name: 'Grep',
tool_input: { path: sourcePath, pattern: 'value' },
- })).resolves.toEqual({ continue: true });
+ })).resolves.toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'allow',
+ updatedInput: { path: await fs.realpath(sourcePath), pattern: 'value' },
+ },
+ });
await expect(reviewHook({
hook_event_name: 'PreToolUse',
tool_name: 'Grep',
tool_input: { path: workingDir, pattern: 'value', glob: '**/*.ts' },
- })).resolves.toEqual({ continue: true });
+ })).resolves.toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'allow',
+ updatedInput: { path: await fs.realpath(workingDir), pattern: 'value', glob: '**/*.ts' },
+ },
+ });
for (const glob of ['**/*.pem', '**/.env*', '../../outside/**', '{src/**,/etc/**}']) {
await expect(reviewHook({
hook_event_name: 'PreToolUse',
@@ -352,12 +372,25 @@ describe('ClaudeCodeAgent plan mode', () => {
hook_event_name: 'PreToolUse',
tool_name: 'Glob',
tool_input: { pattern: '**/*.ts' },
- })).resolves.toEqual({ continue: true });
+ })).resolves.toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'allow',
+ updatedInput: { path: await fs.realpath(workingDir), pattern: '**/*.ts' },
+ },
+ });
await expect(reviewHook({
hook_event_name: 'PreToolUse',
tool_name: 'Glob',
tool_input: { pattern: '{src,test}/**/*.{ts,tsx}' },
- })).resolves.toEqual({ continue: true });
+ })).resolves.toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'allow',
+ updatedInput: {
+ path: await fs.realpath(workingDir),
+ pattern: '{src,test}/**/*.{ts,tsx}',
+ },
+ },
+ });
for (const pattern of [
'../../.ssh/*',
'{../../.ssh/*,**/*.ts}',
@@ -374,6 +407,52 @@ describe('ClaudeCodeAgent plan mode', () => {
tool_input: { pattern },
})).resolves.toMatchObject({ hookSpecificOutput: { permissionDecision: 'deny' } });
}
+
+ for (const [toolName, key, rawPath] of [
+ ['Read', 'file_path', sourcePath],
+ ['NotebookRead', 'notebook_path', sourcePath],
+ ['LS', 'path', workingDir],
+ ] as const) {
+ const result = await reviewHook({
+ hook_event_name: 'PreToolUse',
+ tool_name: toolName,
+ tool_input: { [key]: rawPath },
+ });
+ expect(result).toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'allow',
+ updatedInput: { [key]: await fs.realpath(rawPath) },
+ },
+ });
+ }
+
+ if (process.platform !== 'win32') {
+ const approvedPath = path.join(workingDir, 'approved.ts');
+ const swappedLink = path.join(workingDir, 'swapped.ts');
+ const outsidePath = path.join(externalDir, 'private.txt');
+ await fs.writeFile(approvedPath, 'approved');
+ await fs.writeFile(outsidePath, 'private');
+ await fs.symlink(approvedPath, swappedLink);
+
+ const decision = await reviewHook({
+ hook_event_name: 'PreToolUse',
+ tool_name: 'Read',
+ tool_input: { file_path: swappedLink },
+ });
+ await fs.unlink(swappedLink);
+ await fs.symlink(outsidePath, swappedLink);
+
+ expect(decision).toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'allow',
+ updatedInput: { file_path: await fs.realpath(approvedPath) },
+ },
+ });
+ expect(
+ (decision.hookSpecificOutput as { updatedInput: { file_path: string } }).updatedInput
+ .file_path,
+ ).not.toBe(swappedLink);
+ }
expect(downstreamHook).not.toHaveBeenCalled();
if (!handle.setPermissionMode) throw new Error('expected permission control');
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index c467008b47..2ed72ce5f3 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -300,21 +300,21 @@ function reviewFileSelectorIsAllowed(selector: unknown): selector is string {
);
}
-async function reviewReadToolIsInScope(params: {
+async function resolveReviewReadToolInput(params: {
toolName: string;
toolInput: Record<string, unknown> | undefined;
workingDir: string;
grants: readonly ReviewReadGrant[];
-}): Promise<boolean> {
+}): Promise<Record<string, unknown> | null> {
if (params.toolName === 'Glob') {
- if (!reviewFileSelectorIsAllowed(params.toolInput?.pattern)) return false;
+ if (!reviewFileSelectorIsAllowed(params.toolInput?.pattern)) return null;
}
if (
params.toolName === 'Grep' &&
params.toolInput?.glob !== undefined &&
!reviewFileSelectorIsAllowed(params.toolInput.glob)
) {
- return false;
+ return null;
}
const keyByTool: Partial<Record<string, string>> = {
Read: 'file_path',
@@ -324,13 +324,18 @@ async function reviewReadToolIsInScope(params: {
NotebookRead: 'notebook_path',
};
const key = keyByTool[params.toolName];
- if (!key) return false;
+ if (!key) return null;
const raw = params.toolInput?.[key];
const candidate =
typeof raw === 'string' && raw.trim()
? path.resolve(params.workingDir, raw)
: params.workingDir;
- return (await resolveReviewReadPath(candidate, params.workingDir, params.grants)) !== null;
+ const resolved = await resolveReviewReadPath(candidate, params.workingDir, params.grants);
+ if (!resolved) return null;
+ // The permission decision and the SDK tool execution must address the same
+ // filesystem object. In particular, never hand a validated symlink back to
+ // Read/Glob/Grep: it could be retargeted after this hook returns.
+ return { ...(params.toolInput ?? {}), [key]: resolved };
}
/**
@@ -1365,16 +1370,23 @@ export class ClaudeCodeAgent extends BaseAgent {
if (input.hook_event_name !== 'PreToolUse') return { continue: true };
const pre = input as PreToolUseHookInput;
const toolName = pre.tool_name;
- if (
- isReadOnlyClaudeTool(toolName) &&
- (await reviewReadToolIsInScope({
+ const updatedInput = isReadOnlyClaudeTool(toolName)
+ ? await resolveReviewReadToolInput({
toolName,
toolInput: pre.tool_input as Record<string, unknown> | undefined,
workingDir: opts.workingDir,
grants: reviewReadGrants,
- }))
- ) {
- return { continue: true };
+ })
+ : null;
+ if (updatedInput) {
+ return {
+ continue: true,
+ hookSpecificOutput: {
+ hookEventName: 'PreToolUse',
+ permissionDecision: 'allow',
+ updatedInput,
+ },
+ };
}
return {
continue: true,