Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(review): close selector and lease gaps
Chris97c532fea70d
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.tsindex 6476f7c2d8..1eafc9bcc5 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts@@ -91,6 +91,8 @@ function makeDeps(owner: { instanceId: 'main-instance-1', processId: 123 },now: vi.fn(() => 1_000 + id),prepareRun: vi.fn(async () => makePreparedRun(launch)),+ acquireSourceLease: vi.fn(async () => true),+ releaseSourceLease: vi.fn(async () => undefined),createSourceCard: vi.fn(async () => undefined),updateSourceCard: vi.fn(async () => undefined),startReviewer: vi.fn(async () => reviewer),@@ -322,6 +324,55 @@ describe('maker:review:start IPC lifecycle', () => {expect(deps.closeReviewer).toHaveBeenCalledTimes(1);});+ it('uses the durable lease to admit only one shared-database handler', async () => {+ const firstHarness = new IpcHarness();+ const secondHarness = new IpcHarness();+ const firstReviewer = new FakeReviewer();+ const secondReviewer = new FakeReviewer();+ let lease: { runId: string; instanceId: string } | null = null;+ const acquireSourceLease = vi.fn(+ async (input: { runId: string; owner: { instanceId: string } }) => {+ if (lease) return false;+ lease = { runId: input.runId, instanceId: input.owner.instanceId };+ return true;+ },+ );+ const releaseSourceLease = vi.fn(+ async (input: { runId: string; owner: { instanceId: string } }) => {+ if (lease?.runId === input.runId && lease.instanceId === input.owner.instanceId) {+ lease = null;+ }+ },+ );+ const firstDeps = makeDeps(firstReviewer, {+ owner: { instanceId: 'first-main', processId: 101 },+ acquireSourceLease,+ releaseSourceLease,+ });+ const secondDeps = makeDeps(secondReviewer, {+ owner: { instanceId: 'second-main', processId: 202 },+ acquireSourceLease,+ releaseSourceLease,+ });+ registerReviewStartHandler(firstHarness, firstDeps);+ registerReviewStartHandler(secondHarness, secondDeps);++ await expect(+ firstHarness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest()),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ secondHarness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest()),+ ).rejects.toMatchObject({ code: 'SESSION_RUNNING' });+ expect(secondDeps.createSourceCard).not.toHaveBeenCalled();+ expect(secondDeps.startReviewer).not.toHaveBeenCalled();++ firstReviewer.emitStatus('closed');+ await vi.waitFor(() => expect(lease).toBeNull());+ await expect(+ secondHarness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest()),+ ).resolves.toMatchObject({ ok: true });+ });+it('ignores continuation boundaries and lets only the first terminal event finalize', 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.tsindex 0f67b60bcc..d5232383f0 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -209,7 +209,16 @@ import {type ReviewRunMeta,type ReviewRunOwner,} from '../../shared/reviewRun.js';-import { shouldFailInterruptedReview } from '../reviewer/reviewRunRecovery.js';+import {+ hasReviewOwnerProcessEnded,+ shouldFailInterruptedReview,+} from '../reviewer/reviewRunRecovery.js';+import {+ discardInvalidReviewSourceLease,+ listPersistedReviewSourceLeases,+ releaseReviewSourceLease,+ tryAcquireReviewSourceLease,+} from '../reviewer/reviewSourceLease.js';import {applyAgentSwitchToSessionRow,applyAgentSwitchResumeFallbackAtomically,@@ -6575,21 +6584,25 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)processId: process.pid,};const reconcileInterruptedReviews = async (): Promise<void> => {- const db = getDbClient().drizzle;- const rows = await db- .select({- sessionId: messages.sessionId,- clientId: messages.clientId,- agentMeta: messages.agentMeta,- })- .from(messages)- .where(- and(- eq(messages.role, 'assistant'),- isNull(messages.rewindAt),- sql`${messages.agentMeta} LIKE '%"reviewRun"%'`,+ const dbClient = getDbClient();+ const db = dbClient.drizzle;+ const [rows, sourceLeases] = await Promise.all([+ db+ .select({+ sessionId: messages.sessionId,+ clientId: messages.clientId,+ agentMeta: messages.agentMeta,+ })+ .from(messages)+ .where(+ and(+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),+ sql`${messages.agentMeta} LIKE '%"reviewRun"%'`,+ ),),- );+ listPersistedReviewSourceLeases(dbClient),+ ]);const interruptedAt = Date.now();for (const row of rows) {const reviewRun = readReviewRunFromAgentMeta(row.agentMeta);@@ -6604,6 +6617,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await patchMessageAgentMeta(row.sessionId, row.clientId, { reviewRun: failed });await broadcastMessageAgentMetaUpdate(row.sessionId, row.clientId);}+ for (const row of sourceLeases) {+ if (!row.lease) {+ await discardInvalidReviewSourceLease(dbClient, row);+ log.warn('discarded malformed Review source lease', {+ sourceSessionId: row.sourceSessionId,+ leaseRowId: row.id,+ });+ continue;+ }+ if (!hasReviewOwnerProcessEnded(row.lease.owner, reviewRunOwner)) continue;+ await releaseReviewSourceLease(dbClient, {+ sourceSessionId: row.sourceSessionId,+ runId: row.lease.runId,+ owner: row.lease.owner,+ });+ }};const sourceHasPersistedRunningReview = async (sourceSessionId: string): Promise<boolean> => {const rows = await getDbClient()@@ -6669,6 +6698,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)createReviewerSessionId: randomUUID,owner: reviewRunOwner,now: Date.now,+ acquireSourceLease: (input) => tryAcquireReviewSourceLease(getDbClient(), input),+ releaseSourceLease: async (input) => {+ await releaseReviewSourceLease(getDbClient(), input);+ },prepareRun: async ({ event, request, reviewerSessionId }) => {const db = getDbClient().drizzle;const [source] = await dbdiff --git a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts b/apps/desktop/src/main/maker-ipc/reviewStartHandler.tsindex fd0e6065c3..e8d97f2ed3 100644--- a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts+++ b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts@@ -132,6 +132,17 @@ export interface ReviewStartHandlerDeps {runId: string;reviewerSessionId: string;}): Promise<PreparedReviewRun>;+ acquireSourceLease(input: {+ sourceSessionId: string;+ runId: string;+ owner: ReviewRunOwner;+ createdAt: number;+ }): Promise<boolean>;+ releaseSourceLease(input: {+ sourceSessionId: string;+ runId: string;+ owner: ReviewRunOwner;+ }): Promise<void>;createSourceCard(input: ReviewCardWrite): Promise<void>;updateSourceCard(input: ReviewCardWrite): Promise<void>;startReviewer(createOpts: MakerSessionCreateOpts): Promise<ReviewRunnerHandle>;@@ -187,10 +198,36 @@ export function registerReviewStartHandler(let preparedRunCleaned = false;let preparedRunCleanup: (() => Promise<void>) | null = null;let terminalFinalization: Promise<void> | null = null;+ let sourceLeaseAcquired = false;+ let sourceCardCreated = false;+ let releasePromise: Promise<void> | null = null;- const release = (): void => {- const active = activeReviewsBySource.get(request.sourceSessionId);- if (active?.runId === runId) activeReviewsBySource.delete(request.sourceSessionId);+ const release = (): Promise<void> => {+ if (releasePromise) return releasePromise;+ releasePromise = (async () => {+ if (sourceLeaseAcquired) {+ try {+ await deps.releaseSourceLease({+ sourceSessionId: request.sourceSessionId,+ runId,+ owner: deps.owner,+ });+ sourceLeaseAcquired = false;+ } catch (error) {+ // Keep the in-process gate occupied if the durable gate could not+ // be released. A later process can reclaim it after owner death.+ deps.warn('review source lease release failed', {+ sourceSessionId: request.sourceSessionId,+ runId,+ error: error instanceof Error ? error.message : String(error),+ });+ return;+ }+ }+ const active = activeReviewsBySource.get(request.sourceSessionId);+ if (active?.runId === runId) activeReviewsBySource.delete(request.sourceSessionId);+ })();+ return releasePromise;};const disposeReviewerListeners = (): void => {disposeReviewEvents?.();@@ -223,7 +260,7 @@ export function registerReviewStartHandler(error?: string,): Promise<void> => {if (!runningMeta || !sourceAgentKind) {- release();+ await release();return;}const nextMeta: ReviewRunMeta = {@@ -241,7 +278,7 @@ export function registerReviewStartHandler(result,});} finally {- release();+ await release();}};@@ -251,6 +288,17 @@ export function registerReviewStartHandler(const preparedSourceAgentKind = prepared.sourceAgentKind;sourceAgentKind = preparedSourceAgentKind;const startedAt = deps.now();+ if (+ !(await deps.acquireSourceLease({+ sourceSessionId: request.sourceSessionId,+ runId,+ owner: deps.owner,+ createdAt: startedAt,+ }))+ ) {+ throwIpcError('SESSION_RUNNING', 'This task already has a review in progress');+ }+ sourceLeaseAcquired = true;runningMeta = {version: 1,runId,@@ -268,6 +316,7 @@ export function registerReviewStartHandler(meta: runningMeta,result: '',});+ sourceCardCreated = true;const launch = await prepared.prepareLaunch();await launch.verifyBeforeStart();@@ -311,7 +360,9 @@ export function registerReviewStartHandler('failed','',error instanceof Error ? error.message : String(error),- ).catch(release);+ ).catch(async () => {+ await release();+ });await closeReviewer();});void terminalFinalization;@@ -329,7 +380,7 @@ export function registerReviewStartHandler(reviewerSessionId,error: error instanceof Error ? error.message : String(error),});- release();+ await release();await closeReviewer();});void terminalFinalization;@@ -389,8 +440,14 @@ export function registerReviewStartHandler(await closeReviewer();const active = activeReviewsBySource.get(request.sourceSessionId);if (active?.runId === runId) {- const message = error instanceof Error ? error.message : String(error);- await updateSourceCard('failed', '', message).catch(release);+ if (sourceCardCreated) {+ const message = error instanceof Error ? error.message : String(error);+ await updateSourceCard('failed', '', message).catch(async () => {+ await release();+ });+ } else {+ await release();+ }}throw error;}diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.tsnew file mode 100644index 0000000000..fc5a4d51d2--- /dev/null+++ b/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts@@ -0,0 +1,140 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import Database from 'better-sqlite3';+import { afterEach, describe, expect, it } from 'vitest';++import type { DbClient } from '../../localDb/client/DbClient.js';+import {+ discardInvalidReviewSourceLease,+ listPersistedReviewSourceLeases,+ releaseReviewSourceLease,+ REVIEW_SOURCE_LEASE_CLIENT_ID,+ tryAcquireReviewSourceLease,+} from '../reviewSourceLease.js';++function asLeaseClient(db: Database.Database): Pick<DbClient, 'exec' | 'query'> {+ return {+ exec: async (sql, params = []) => db.prepare(sql).run(...params),+ query: async <T>(sql: string, params: unknown[] = []) => db.prepare(sql).all(...params) as T[],+ };+}++describe('Review source lease', () => {+ const cleanups: Array<() => void> = [];++ afterEach(() => {+ for (const cleanup of cleanups.splice(0).reverse()) cleanup();+ });++ function setup() {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-review-lease-'));+ const dbPath = path.join(dir, 'review.db');+ const first = new Database(dbPath);+ first.exec(`+ PRAGMA foreign_keys = ON;+ CREATE TABLE sessions (id TEXT PRIMARY KEY, status TEXT NOT NULL);+ CREATE TABLE messages (+ id TEXT PRIMARY KEY,+ client_id TEXT NOT NULL,+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ role TEXT NOT NULL,+ content TEXT NOT NULL,+ agent_meta TEXT,+ created_at INTEGER NOT NULL,+ rewind_at INTEGER+ );+ CREATE UNIQUE INDEX uniq_messages_session_client+ ON messages(session_id, client_id);+ INSERT INTO sessions (id, status) VALUES ('source-1', 'active');+ `);+ const second = new Database(dbPath);+ second.pragma('foreign_keys = ON');+ cleanups.push(() => {+ second.close();+ first.close();+ fs.rmSync(dir, { recursive: true, force: true });+ });+ return { first: asLeaseClient(first), second: asLeaseClient(second), raw: first };+ }++ it('admits exactly one shared-database owner and allows a successor after CAS release', async () => {+ const { first, second, raw } = setup();+ const firstOwner = { instanceId: 'first', processId: 101 };+ const secondOwner = { instanceId: 'second', processId: 202 };++ const acquired = await Promise.all([+ tryAcquireReviewSourceLease(first, {+ sourceSessionId: 'source-1',+ runId: 'run-1',+ owner: firstOwner,+ createdAt: 1,+ }),+ tryAcquireReviewSourceLease(second, {+ sourceSessionId: 'source-1',+ runId: 'run-2',+ owner: secondOwner,+ createdAt: 2,+ }),+ ]);+ expect(acquired.filter(Boolean)).toHaveLength(1);+ expect(+ raw+ .prepare(+ `SELECT count(*) AS count FROM messages+ WHERE client_id = ? AND rewind_at IS NULL`,+ )+ .get(REVIEW_SOURCE_LEASE_CLIENT_ID),+ ).toEqual({ count: 0 });++ const winner = acquired[0]+ ? { client: first, runId: 'run-1', owner: firstOwner }+ : { client: second, runId: 'run-2', owner: secondOwner };+ const loser = acquired[0]+ ? { client: second, runId: 'run-2', owner: secondOwner }+ : { client: first, runId: 'run-1', owner: firstOwner };+ const rows = await listPersistedReviewSourceLeases(second);+ expect(rows).toHaveLength(1);+ expect(rows[0]?.lease).toMatchObject({ runId: winner.runId, owner: winner.owner });++ await expect(+ releaseReviewSourceLease(loser.client, {+ sourceSessionId: 'source-1',+ runId: loser.runId,+ owner: loser.owner,+ }),+ ).resolves.toBe(false);+ await expect(+ releaseReviewSourceLease(winner.client, {+ sourceSessionId: 'source-1',+ runId: winner.runId,+ owner: winner.owner,+ }),+ ).resolves.toBe(true);+ await expect(+ tryAcquireReviewSourceLease(loser.client, {+ sourceSessionId: 'source-1',+ runId: loser.runId,+ owner: loser.owner,+ createdAt: 3,+ }),+ ).resolves.toBe(true);+ });++ it('reclaims a malformed hidden lease by immutable row id', async () => {+ const { first, raw } = setup();+ raw+ .prepare(+ `INSERT INTO messages+ (id, client_id, session_id, role, content, agent_meta, created_at, rewind_at)+ VALUES ('bad-row', ?, 'source-1', 'assistant', 'null', '{bad', 1, 1)`,+ )+ .run(REVIEW_SOURCE_LEASE_CLIENT_ID);++ const [row] = await listPersistedReviewSourceLeases(first);+ expect(row?.lease).toBeNull();+ await expect(discardInvalidReviewSourceLease(first, row!)).resolves.toBe(true);+ await expect(listPersistedReviewSourceLeases(first)).resolves.toEqual([]);+ });+});diff --git a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts b/apps/desktop/src/main/reviewer/reviewRunRecovery.tsindex 69c1e1b000..8e6fc1a623 100644--- a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts+++ b/apps/desktop/src/main/reviewer/reviewRunRecovery.ts@@ -11,6 +11,18 @@ export function isReviewProcessAlive(processId: number): boolean {}}+export function hasReviewOwnerProcessEnded(+ owner: ReviewRunOwner,+ currentOwner: ReviewRunOwner,+ processIsAlive: ReviewProcessAliveProbe = isReviewProcessAlive,+): boolean {+ if (owner.instanceId === currentOwner.instanceId) return false;+ // This process now owns the same PID, so the differently identified previous+ // owner has definitely terminated even if the OS immediately reused the PID.+ if (owner.processId === currentOwner.processId) return true;+ return !processIsAlive(owner.processId);+}+/*** A shared-userData instance may only fail a running card after proving that* the Main process which owns it has ended. Owner-less cards from older builds@@ -22,9 +34,5 @@ export function shouldFailInterruptedReview(processIsAlive: ReviewProcessAliveProbe = isReviewProcessAlive,): boolean {if (reviewRun.status !== 'running' || !reviewRun.owner) return false;- if (reviewRun.owner.instanceId === currentOwner.instanceId) return false;- // This process now owns the same PID, so the differently identified previous- // owner has definitely terminated even if the OS immediately reused the PID.- if (reviewRun.owner.processId === currentOwner.processId) return true;- return !processIsAlive(reviewRun.owner.processId);+ return hasReviewOwnerProcessEnded(reviewRun.owner, currentOwner, processIsAlive);}diff --git a/apps/desktop/src/main/reviewer/reviewSourceLease.ts b/apps/desktop/src/main/reviewer/reviewSourceLease.tsnew file mode 100644index 0000000000..ac1846b6c2--- /dev/null+++ b/apps/desktop/src/main/reviewer/reviewSourceLease.ts@@ -0,0 +1,158 @@+import { createId } from '@paralleldrive/cuid2';++import type { ReviewRunOwner } from '../../shared/reviewRun.js';+import type { DbClient } from '../localDb/client/DbClient.js';++/** One hidden row per source task makes the cross-process Review gate atomic. */+export const REVIEW_SOURCE_LEASE_CLIENT_ID = 'review:source-lease:v1';++export interface ReviewSourceLease {+ version: 1;+ runId: string;+ owner: ReviewRunOwner;+}++export interface PersistedReviewSourceLeaseRow {+ id: string;+ sourceSessionId: string;+ lease: ReviewSourceLease | null;+}++function reviewSourceLeaseAgentMeta(lease: ReviewSourceLease): string {+ return JSON.stringify({ reviewSourceLease: lease });+}++function reviewSourceLeaseToken(lease: ReviewSourceLease): string {+ return JSON.stringify({+ version: lease.version,+ runId: lease.runId,+ ownerInstanceId: lease.owner.instanceId,+ });+}++export function readReviewSourceLeaseFromAgentMeta(value: unknown): ReviewSourceLease | null {+ let envelope = value;+ if (typeof envelope === 'string') {+ try {+ envelope = JSON.parse(envelope) as unknown;+ } catch {+ return null;+ }+ }+ if (!envelope || typeof envelope !== 'object' || Array.isArray(envelope)) return null;+ const valueRecord = (envelope as Record<string, unknown>).reviewSourceLease;+ if (!valueRecord || typeof valueRecord !== 'object' || Array.isArray(valueRecord)) return null;+ const lease = valueRecord as Record<string, unknown>;+ const owner = lease.owner;+ if (+ lease.version !== 1 ||+ typeof lease.runId !== 'string' ||+ !lease.runId ||+ !owner ||+ typeof owner !== 'object' ||+ Array.isArray(owner)+ ) {+ return null;+ }+ const ownerRecord = owner as Record<string, unknown>;+ if (+ typeof ownerRecord.instanceId !== 'string' ||+ !ownerRecord.instanceId ||+ !Number.isSafeInteger(ownerRecord.processId) ||+ (ownerRecord.processId as number) <= 0+ ) {+ return null;+ }+ return valueRecord as unknown as ReviewSourceLease;+}++/**+ * The unique messages(session_id, client_id) index is the compare-and-insert.+ * A rewound assistant row stays out of history, FTS, prompts, and Review context.+ */+export async function tryAcquireReviewSourceLease(+ dbClient: Pick<DbClient, 'exec'>,+ input: {+ sourceSessionId: string;+ runId: string;+ owner: ReviewRunOwner;+ createdAt: number;+ },+): Promise<boolean> {+ const lease: ReviewSourceLease = {+ version: 1,+ runId: input.runId,+ owner: input.owner,+ };+ const result = await dbClient.exec(+ `INSERT INTO messages (+ id, client_id, session_id, role, content, agent_meta, created_at, rewind_at+ ) VALUES (?, ?, ?, 'assistant', ?, ?, ?, ?)+ ON CONFLICT(session_id, client_id) DO NOTHING`,+ [+ createId(),+ REVIEW_SOURCE_LEASE_CLIENT_ID,+ input.sourceSessionId,+ reviewSourceLeaseToken(lease),+ reviewSourceLeaseAgentMeta(lease),+ input.createdAt,+ input.createdAt,+ ],+ );+ return result.changes === 1;+}++/** Delete only the exact lease acquired by this run, never a newer successor. */+export async function releaseReviewSourceLease(+ dbClient: Pick<DbClient, 'exec'>,+ input: {+ sourceSessionId: string;+ runId: string;+ owner: ReviewRunOwner;+ },+): Promise<boolean> {+ const lease: ReviewSourceLease = {+ version: 1,+ runId: input.runId,+ owner: input.owner,+ };+ const result = await dbClient.exec(+ `DELETE FROM messages+ WHERE session_id = ? AND client_id = ? AND content = ?`,+ [input.sourceSessionId, REVIEW_SOURCE_LEASE_CLIENT_ID, reviewSourceLeaseToken(lease)],+ );+ return result.changes === 1;+}++export async function listPersistedReviewSourceLeases(+ dbClient: Pick<DbClient, 'query'>,+): Promise<PersistedReviewSourceLeaseRow[]> {+ const rows = await dbClient.query<{+ id: string;+ sourceSessionId: string;+ agentMeta: unknown;+ }>(+ `SELECT id, session_id AS sourceSessionId, agent_meta AS agentMeta+ FROM messages+ WHERE client_id = ?`,+ [REVIEW_SOURCE_LEASE_CLIENT_ID],+ );+ return rows.map((row) => ({+ id: row.id,+ sourceSessionId: row.sourceSessionId,+ lease: readReviewSourceLeaseFromAgentMeta(row.agentMeta),+ }));+}++/** Remove a malformed legacy/corrupt row only if its immutable id still matches. */+export async function discardInvalidReviewSourceLease(+ dbClient: Pick<DbClient, 'exec'>,+ row: Pick<PersistedReviewSourceLeaseRow, 'id' | 'sourceSessionId'>,+): Promise<boolean> {+ const result = await dbClient.exec(+ `DELETE FROM messages+ WHERE id = ? AND session_id = ? AND client_id = ?`,+ [row.id, row.sourceSessionId, REVIEW_SOURCE_LEASE_CLIENT_ID],+ );+ return result.changes === 1;+}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.tsindex 28164bb39e..605d02313d 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@@ -326,6 +326,18 @@ describe('ClaudeCodeAgent plan mode', () => {tool_name: 'Grep',tool_input: { path: sourcePath, pattern: 'value' },})).resolves.toEqual({ continue: true });+ await expect(reviewHook({+ hook_event_name: 'PreToolUse',+ tool_name: 'Grep',+ tool_input: { path: workingDir, pattern: 'value', glob: '**/*.ts' },+ })).resolves.toEqual({ continue: true });+ for (const glob of ['**/*.pem', '**/.env*', '../../outside/**', '{src/**,/etc/**}']) {+ await expect(reviewHook({+ hook_event_name: 'PreToolUse',+ tool_name: 'Grep',+ tool_input: { path: workingDir, pattern: 'value', glob },+ })).resolves.toMatchObject({ hookSpecificOutput: { permissionDecision: 'deny' } });+ }await expect(reviewHook({hook_event_name: 'PreToolUse',tool_name: 'Glob',@@ -343,6 +355,8 @@ describe('ClaudeCodeAgent plan mode', () => {'[.][.]/.ssh/*',path.join(os.homedir(), '**', '*'),String.raw`C:\\Users\\outside\\*`,+ '**/*.pem',+ '**/.env*',]) {await expect(reviewHook({hook_event_name: 'PreToolUse',diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 1e2191132a..23e1be0473 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -155,7 +155,10 @@ import type {} from '../../types/memory.js';import type { McpProviderContext } from '../../interfaces/mcp-provider.js';import { scanClaudeCustomizations } from './customization-scanner.js';-import { isReviewSensitiveCredentialPath } from '../shared/sensitive-credential-paths.js';+import {+ isReviewSensitiveCredentialPath,+ isReviewSensitiveCredentialSelector,+} from '../shared/sensitive-credential-paths.js';import {assertReviewMessageContentPaths,buildReviewReadGrants,@@ -285,6 +288,14 @@ function reviewGlobPatternEscapesScope(pattern: string): boolean {return /(^|[{(,|])(?:\/|[a-zA-Z]:\/)/.test(value);}+function reviewFileSelectorIsAllowed(selector: unknown): selector is string {+ return (+ typeof selector === 'string' &&+ !reviewGlobPatternEscapesScope(selector) &&+ !isReviewSensitiveCredentialSelector(selector)+ );+}+async function reviewReadToolIsInScope(params: {toolName: string;toolInput: Record<string, unknown> | undefined;@@ -292,8 +303,14 @@ async function reviewReadToolIsInScope(params: {grants: readonly ReviewReadGrant[];}): Promise<boolean> {if (params.toolName === 'Glob') {- const pattern = params.toolInput?.pattern;- if (typeof pattern !== 'string' || reviewGlobPatternEscapesScope(pattern)) return false;+ if (!reviewFileSelectorIsAllowed(params.toolInput?.pattern)) return false;+ }+ if (+ params.toolName === 'Grep' &&+ params.toolInput?.glob !== undefined &&+ !reviewFileSelectorIsAllowed(params.toolInput.glob)+ ) {+ return false;}const keyByTool: Partial<Record<string, string>> = {Read: 'file_path',diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.tsindex 61e98eda9b..14967bfcc4 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts@@ -1,8 +1,23 @@+import ts from 'typescript';import { describe, expect, it } from 'vitest';import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';describe('cindy-bridge extension source', () => {+ it('is valid standalone TypeScript for the Pi runtime to load', () => {+ const result = ts.transpileModule(CINDY_BRIDGE_EXTENSION_SOURCE, {+ compilerOptions: {+ module: ts.ModuleKind.ESNext,+ target: ts.ScriptTarget.ES2022,+ },+ reportDiagnostics: true,+ });+ const errors = (result.diagnostics ?? [])+ .filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)+ .map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));+ expect(errors).toEqual([]);+ });+it('overrides find with the managed ripgrep backend instead of runtime fd download', () => {const source = CINDY_BRIDGE_EXTENSION_SOURCE;@@ -48,8 +63,12 @@ describe('cindy-bridge extension source', () => {expect(source).toContain("reason: 'Cindy Review only permits read-only access to this task and its explicit artifacts.'",);+ expect(source).toContain('reviewReadInputIsAllowed(');+ expect(source).toContain('collectReviewPathCandidates(input)');+ expect(source).toContain("new Set(['glob', 'globs', 'pattern', 'patterns'])");+ expect(source).toContain('reviewSelectorTouchesCredential(selector)');expect(source).toContain(- 'reviewReadIsAllowed(rawPath, permission.reviewReadPaths)',+ 'requestedPaths.every((candidate) => reviewReadIsAllowed(candidate, allowedPaths))',);expect(source).not.toContain("toolName === 'grep' && statSync(target).isDirectory()");expect(source).toContain(diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 0aa517cecd..231877e71a 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -194,6 +194,120 @@ function reviewReadIsAllowed(candidate: string, allowedPaths: string[]): boolean}}+const REVIEW_PATH_FIELD_KEYS = new Set([+ 'path',+ 'paths',+ 'file_path',+ 'filepath',+ 'notebook_path',+ 'notebookpath',+]);++// Read tools have changed their input nesting across Pi versions. Walk every+// object branch and validate every path-bearing field instead of trusting only+// the top-level path value. Invalid or over-deep path shapes fail closed.+function collectReviewPathCandidates(input: unknown): string[] | null {+ if (+ input != null+ && (typeof input !== 'object' || Array.isArray(input))+ ) return null;+ const candidates: string[] = [];+ const visit = (value: unknown, field: string | null, depth: number): boolean => {+ if (depth > 6) return false;+ const normalizedField = field?.toLowerCase() ?? null;+ if (normalizedField && REVIEW_PATH_FIELD_KEYS.has(normalizedField)) {+ const plural = normalizedField === 'paths';+ if (plural) {+ if (!Array.isArray(value)) return false;+ for (const item of value) {+ if (typeof item !== 'string') return false;+ candidates.push(item || process.cwd());+ }+ return true;+ }+ if (typeof value !== 'string') return false;+ candidates.push(value || process.cwd());+ return true;+ }+ if (value == null) return true;+ if (Array.isArray(value)) {+ return value.every((item) => visit(item, null, depth + 1));+ }+ if (typeof value === 'object') {+ return Object.entries(value as Record<string, unknown>)+ .every(([key, child]) => visit(child, key, depth + 1));+ }+ return true;+ };+ return visit(input, null, 0) ? candidates : null;+}++function reviewSelectorEscapesScope(selector: string): boolean {+ const value = selector.trim();+ if (!value) return false;+ if (path.isAbsolute(value) || path.win32.isAbsolute(value)) return true;+ if (/[\\[\]]/.test(value) || value.includes('..')) return true;+ return /(^|[{(,|])(?:\/|[a-zA-Z]:\/)/.test(value);+}++function reviewSelectorTouchesCredential(selector: string): boolean {+ const candidates = [selector, ...selector.split(/[{},|]/)];+ return candidates.some((candidate) => {+ if (REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(candidate))) return true;+ const literalized = candidate.replace(/[*?[\]{}()!+@]/g, '');+ return literalized !== candidate+ && REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(literalized));+ });+}++function collectReviewFileSelectors(toolName: string, input: unknown): string[] | null {+ if (toolName !== 'grep' && toolName !== 'find') return [];+ const selectorFields = toolName === 'grep'+ ? new Set(['glob', 'globs'])+ : new Set(['glob', 'globs', 'pattern', 'patterns']);+ const selectors: string[] = [];+ const visit = (value: unknown, field: string | null, depth: number): boolean => {+ if (depth > 6) return false;+ const normalizedField = field?.toLowerCase() ?? null;+ if (normalizedField && selectorFields.has(normalizedField)) {+ if (Array.isArray(value)) {+ for (const item of value) {+ if (typeof item !== 'string') return false;+ selectors.push(item);+ }+ return true;+ }+ if (typeof value !== 'string') return false;+ selectors.push(value);+ return true;+ }+ if (value == null) return true;+ if (Array.isArray(value)) {+ return value.every((item) => visit(item, null, depth + 1));+ }+ if (typeof value === 'object') {+ return Object.entries(value as Record<string, unknown>)+ .every(([key, child]) => visit(child, key, depth + 1));+ }+ return true;+ };+ return visit(input, null, 0) ? selectors : null;+}++function reviewReadInputIsAllowed(+ toolName: string,+ input: unknown,+ allowedPaths: string[],+): boolean {+ const paths = collectReviewPathCandidates(input);+ const selectors = collectReviewFileSelectors(toolName, input);+ if (!paths || !selectors) return false;+ const requestedPaths = paths.length > 0 ? paths : [process.cwd()];+ return requestedPaths.every((candidate) => reviewReadIsAllowed(candidate, allowedPaths))+ && selectors.every((selector) =>+ !reviewSelectorEscapesScope(selector) && !reviewSelectorTouchesCredential(selector));+}+// ── MCP streamable-HTTP 极简 client ─────────────────────────────────────────interface McpServerRef {@@ -667,12 +781,13 @@ export default async function cindyBridge(pi: any) {pi.on('tool_call', async (event: any, ctx: any) => {const permission = currentPermissionState();if (permission.reviewOnly) {- const rawPath = typeof event.input?.path === 'string' && event.input.path- ? event.input.path- : process.cwd();if (READONLY_BUILTINS.has(event.toolName)- && reviewReadIsAllowed(rawPath, permission.reviewReadPaths)+ && reviewReadInputIsAllowed(+ event.toolName,+ event.input,+ permission.reviewReadPaths,+ )) return;return {block: true,diff --git a/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts b/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.tsindex c9d351ed3b..c29383e6e8 100644--- a/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts+++ b/packages/maker-core/src/agents/shared/sensitive-credential-paths.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import {isReviewSensitiveCredentialPath,+ isReviewSensitiveCredentialSelector,isSensitiveCredentialPath,} from "./sensitive-credential-paths.js";@@ -22,4 +23,16 @@ describe("Review credential path policy", () => {false,);});++ it("recognizes credentials hidden behind file selector syntax", () => {+ for (const selector of [+ "**/*.pem",+ "**/.env*",+ "{src/**,**/.ssh/**}",+ "**/{safe.ts,.env.local}",+ ]) {+ expect(isReviewSensitiveCredentialSelector(selector)).toBe(true);+ }+ expect(isReviewSensitiveCredentialSelector("{src,test}/**/*.{ts,tsx}")).toBe(false);+ });});diff --git a/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts b/packages/maker-core/src/agents/shared/sensitive-credential-paths.tsindex 9120fd4d28..10e834af4a 100644--- a/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts+++ b/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts@@ -49,3 +49,18 @@ export function isReviewSensitiveCredentialPath(target: string): boolean {return typeof target === 'string'&& REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERNS.some((pattern) => pattern.test(target));}++/**+ * File selectors are not concrete paths: glob metacharacters can hide a+ * sensitive basename from an otherwise path-shaped check. Inspect each+ * alternative and a metacharacter-free form before a Review search runs.+ */+export function isReviewSensitiveCredentialSelector(selector: string): boolean {+ if (typeof selector !== 'string') return false;+ const candidates = [selector, ...selector.split(/[{},|]/)];+ return candidates.some((candidate) => {+ if (isReviewSensitiveCredentialPath(candidate)) return true;+ const literalized = candidate.replace(/[*?[\]{}()!+@]/g, '');+ return literalized !== candidate && isReviewSensitiveCredentialPath(literalized);+ });+}