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): pin validated launch inputs

Chris2a5dd863cf1a
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b092994ec9..30d90bbd2d 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -7014,6 +7014,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const artifactFingerprint = await fingerprintReviewArtifacts(artifactPaths);
const completeArtifactFingerprintIsCurrent = async (): Promise<boolean> =>
(await fingerprintReviewArtifacts(artifactPaths)) === artifactFingerprint;
+ const readCurrentSourceIdentity = async () => {
+ const [currentSource] = await db
+ .select({
+ workingDir: sessions.workingDir,
+ workspaceKind: sessions.workspaceKind,
+ status: sessions.status,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, source.id))
+ .limit(1);
+ return currentSource ?? null;
+ };
return {
message: reviewMessage as UserMessage,
@@ -7035,6 +7047,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
...(readRoots.size > 0 ? { extraDirs: [...readRoots] } : {}),
}),
verifyBeforeStart: async (): Promise<ReviewFailureReason | null> => {
+ if (!reviewSourceIdentityMatches(source, await readCurrentSourceIdentity())) {
+ return {
+ code: 'source-workspace-changed',
+ message:
+ 'The source task workspace changed before Review started. Run /review again in the current workspace.',
+ };
+ }
if (
(await sourceHasActiveTurn(source.id)) ||
(await readReviewContextFingerprint(source.id)) !== evidence.contextFingerprint
@@ -7077,16 +7096,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return null;
},
verifyBeforePublish: async (): Promise<ReviewFailureReason | null> => {
- const [currentSource] = await db
- .select({
- workingDir: sessions.workingDir,
- workspaceKind: sessions.workspaceKind,
- status: sessions.status,
- })
- .from(sessions)
- .where(eq(sessions.id, source.id))
- .limit(1);
- if (!reviewSourceIdentityMatches(source, currentSource ?? null)) {
+ if (!reviewSourceIdentityMatches(source, await readCurrentSourceIdentity())) {
return {
code: 'source-workspace-changed',
message:
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts
index e0348ad1f2..2695926ca4 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts
@@ -63,6 +63,27 @@ describe('Review external input wiring', () => {
);
});
+ it('rechecks the exact active source identity before both launch and publish', () => {
+ expect(registerSource).toContain('const readCurrentSourceIdentity = async () => {');
+ expect(
+ registerSource.match(
+ /reviewSourceIdentityMatches\(source, await readCurrentSourceIdentity\(\)\)/g,
+ ),
+ ).toHaveLength(2);
+
+ const verifyBeforeStart = registerSource.indexOf('verifyBeforeStart: async');
+ const firstIdentityCheck = registerSource.indexOf(
+ 'reviewSourceIdentityMatches(source, await readCurrentSourceIdentity())',
+ verifyBeforeStart,
+ );
+ const verifyBeforePublish = registerSource.indexOf('verifyBeforePublish: async');
+ expect(firstIdentityCheck).toBeGreaterThan(verifyBeforeStart);
+ expect(firstIdentityCheck).toBeLessThan(verifyBeforePublish);
+ expect(registerSource.slice(verifyBeforeStart, verifyBeforePublish)).toContain(
+ "code: 'source-workspace-changed'",
+ );
+ });
+
it('retries failed startup reconciliation before admitting another Review', () => {
expect(registerSource.match(/createRetryableReviewStartup\(/g)).toHaveLength(2);
expect(registerSource).toContain('void ensureReviewStartupReady().catch(() => {});');
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index 5230bd47e5..6a5f83da22 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -1,3 +1,18 @@
+import {
+ mkdtempSync,
+ mkdirSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import * as path from 'node:path';
+import { runInNewContext } from 'node:vm';
+
import ts from 'typescript';
import { describe, expect, it } from 'vitest';
@@ -65,13 +80,13 @@ 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('normalizeReviewReadInput(');
+ expect(source).toContain('collectReviewPathFields(input)');
expect(source).toContain("new Set(['glob', 'globs', 'pattern', 'patterns'])");
expect(source).toContain('reviewSelectorTouchesCredential(selector)');
- expect(source).toContain(
- 'requestedPaths.every((candidate) => reviewReadIsAllowed(candidate, allowedPaths))',
- );
+ expect(source).toContain('resolveReviewReadPath(candidate, allowedPaths)');
+ expect(source).toContain('(input as Record<string, unknown>).path = resolvedPaths[0]!');
+ expect(source).toContain('pathFields[index].write(resolvedPaths[index]!)');
expect(source).not.toContain("toolName === 'grep' && statSync(target).isDirectory()");
expect(source).toContain(
'stat.isDirectory() ? isInsideRoot(target, allowed) : target === allowed',
@@ -81,4 +96,92 @@ describe('cindy-bridge extension source', () => {
expect(source).toContain('REVIEW_CREDENTIAL_PATH_PATTERNS.some');
expect(source).toContain('REVIEW_CREDENTIAL_GLOB_PATTERNS.some');
});
+
+ it.skipIf(process.platform === 'win32')(
+ 'pins every Pi read tool to the real path that passed Review validation',
+ () => {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+ const helperStart = source.indexOf('function isInsideRoot');
+ const helperEnd = source.indexOf('function reviewSearchPathTouchesCredential');
+ expect(helperStart).toBeGreaterThan(-1);
+ expect(helperEnd).toBeGreaterThan(helperStart);
+
+ const executableSource = [
+ 'const REVIEW_CREDENTIAL_PATH_PATTERNS: RegExp[] = [];',
+ source.slice(helperStart, helperEnd),
+ '(globalThis as any).normalizeReviewReadInput = normalizeReviewReadInput;',
+ ].join('\n');
+ const compiled = ts.transpileModule(executableSource, {
+ compilerOptions: {
+ module: ts.ModuleKind.None,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }).outputText;
+
+ const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-pi-review-read-'));
+ try {
+ const workingDir = path.join(tempRoot, 'workspace');
+ const outsideDir = path.join(tempRoot, 'outside');
+ mkdirSync(workingDir);
+ mkdirSync(outsideDir);
+ const approvedPath = path.join(workingDir, 'approved.txt');
+ const outsidePath = path.join(outsideDir, 'secret.txt');
+ const linkPath = path.join(workingDir, 'review-input.txt');
+ writeFileSync(approvedPath, 'approved');
+ writeFileSync(outsidePath, 'outside');
+ symlinkSync(approvedPath, linkPath);
+
+ type NormalizeReviewReadInput = (
+ toolName: string,
+ input: unknown,
+ allowedPaths: string[],
+ ) => boolean;
+ const context: {
+ normalizeReviewReadInput?: NormalizeReviewReadInput;
+ } & Record<string, unknown> = {
+ path,
+ process: { cwd: () => workingDir, platform: process.platform },
+ realpathSync,
+ statSync,
+ };
+ runInNewContext(compiled, context);
+ const normalizeReviewReadInput = context.normalizeReviewReadInput;
+ expect(normalizeReviewReadInput).toBeTypeOf('function');
+ if (!normalizeReviewReadInput) throw new Error('Review read normalizer was not loaded');
+
+ const inputs = [
+ { tool: 'read', input: { path: linkPath } },
+ {
+ tool: 'grep',
+ input: { request: { paths: [linkPath] }, pattern: 'approved' },
+ },
+ {
+ tool: 'find',
+ input: { options: { filePath: linkPath }, pattern: '*.txt' },
+ },
+ { tool: 'ls', input: { filepath: linkPath } },
+ ];
+ for (const { tool, input } of inputs) {
+ expect(normalizeReviewReadInput(tool, input, [approvedPath])).toBe(true);
+ }
+
+ expect(inputs[0]!.input.path).toBe(realpathSync(approvedPath));
+ expect(inputs[1]!.input.request.paths).toEqual([realpathSync(approvedPath)]);
+ expect(inputs[2]!.input.options.filePath).toBe(realpathSync(approvedPath));
+ expect(inputs[3]!.input.filepath).toBe(realpathSync(approvedPath));
+
+ for (const tool of ['read', 'grep', 'find', 'ls']) {
+ const defaultInput: Record<string, unknown> = {};
+ expect(normalizeReviewReadInput(tool, defaultInput, [workingDir])).toBe(true);
+ expect(defaultInput.path).toBe(realpathSync(workingDir));
+ }
+
+ unlinkSync(linkPath);
+ symlinkSync(outsidePath, linkPath);
+ expect(readFileSync(inputs[0]!.input.path, 'utf8')).toBe('approved');
+ } finally {
+ rmSync(tempRoot, { recursive: true, force: true });
+ }
+ },
+ );
});
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index c9c6b897cd..d46c05be8e 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -176,15 +176,15 @@ function isInsideRoot(candidate: string, root: string): boolean {
return rel === '' || (!rel.startsWith('..' + path.sep) && rel !== '..' && !path.isAbsolute(rel));
}
-function reviewReadIsAllowed(candidate: string, allowedPaths: string[]): boolean {
+function resolveReviewReadPath(candidate: string, allowedPaths: string[]): string | null {
try {
const requested = path.resolve(process.cwd(), candidate);
- if (REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(requested))) return false;
+ if (REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(requested))) return null;
const target = realpathSync(requested);
- if (REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(target))) return false;
+ if (REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(target))) return null;
const targetStat = statSync(target);
- if (targetStat.isFile() && targetStat.nlink > 1) return false;
- return allowedPaths.some((allowedPath) => {
+ if (targetStat.isFile() && targetStat.nlink > 1) return null;
+ const allowed = allowedPaths.some((allowedPath) => {
try {
const allowed = realpathSync(allowedPath);
const stat = statSync(allowed);
@@ -194,8 +194,9 @@ function reviewReadIsAllowed(candidate: string, allowedPaths: string[]): boolean
return false;
}
});
+ return allowed ? target : null;
} catch {
- return false;
+ return null;
}
}
@@ -208,43 +209,62 @@ const REVIEW_PATH_FIELD_KEYS = new Set([
'notebookpath',
]);
+type ReviewPathField = {
+ candidate: string;
+ write: (resolved: string) => void;
+};
+
// 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 {
+// object branch, retain a writer for every path-bearing field, then replace all
+// fields with the exact real paths that passed validation. Invalid or over-deep
+// path shapes fail closed without reaching the built-in tool.
+function collectReviewPathFields(input: unknown): ReviewPathField[] | null {
if (
- input != null
- && (typeof input !== 'object' || Array.isArray(input))
+ input == null
+ || typeof input !== 'object'
+ || Array.isArray(input)
) return null;
- const candidates: string[] = [];
- const visit = (value: unknown, field: string | null, depth: number): boolean => {
+ const fields: ReviewPathField[] = [];
+ const visit = (
+ value: unknown,
+ field: string | null,
+ depth: number,
+ write: (resolved: string) => void,
+ ): 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) {
+ for (let index = 0; index < value.length; index += 1) {
+ const item = value[index];
if (typeof item !== 'string') return false;
- candidates.push(item || process.cwd());
+ fields.push({
+ candidate: item || process.cwd(),
+ write: (resolved) => { value[index] = resolved; },
+ });
}
return true;
}
if (typeof value !== 'string') return false;
- candidates.push(value || process.cwd());
+ fields.push({ candidate: value || process.cwd(), write });
return true;
}
if (value == null) return true;
if (Array.isArray(value)) {
- return value.every((item) => visit(item, null, depth + 1));
+ return value.every((item, index) =>
+ visit(item, null, depth + 1, (resolved) => { value[index] = resolved; }));
}
if (typeof value === 'object') {
- return Object.entries(value as Record<string, unknown>)
- .every(([key, child]) => visit(child, key, depth + 1));
+ const record = value as Record<string, unknown>;
+ return Object.entries(record)
+ .every(([key, child]) =>
+ visit(child, key, depth + 1, (resolved) => { record[key] = resolved; }));
}
return true;
};
- return visit(input, null, 0) ? candidates : null;
+ return visit(input, null, 0, () => {}) ? fields : null;
}
function reviewSelectorEscapesScope(selector: string): boolean {
@@ -299,18 +319,32 @@ function collectReviewFileSelectors(toolName: string, input: unknown): string[]
return visit(input, null, 0) ? selectors : null;
}
-function reviewReadInputIsAllowed(
+function normalizeReviewReadInput(
toolName: string,
input: unknown,
allowedPaths: string[],
): boolean {
- const paths = collectReviewPathCandidates(input);
+ const pathFields = collectReviewPathFields(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));
+ if (!pathFields || !selectors) return false;
+ if (selectors.some((selector) =>
+ reviewSelectorEscapesScope(selector) || reviewSelectorTouchesCredential(selector))) {
+ return false;
+ }
+ const requestedPaths = pathFields.length > 0
+ ? pathFields.map((field) => field.candidate)
+ : [process.cwd()];
+ const resolvedPaths = requestedPaths.map((candidate) =>
+ resolveReviewReadPath(candidate, allowedPaths));
+ if (resolvedPaths.some((resolved) => resolved === null)) return false;
+ if (pathFields.length === 0) {
+ (input as Record<string, unknown>).path = resolvedPaths[0]!;
+ } else {
+ for (let index = 0; index < pathFields.length; index += 1) {
+ pathFields[index].write(resolvedPaths[index]!);
+ }
+ }
+ return true;
}
function reviewSearchPathTouchesCredential(candidate: string, baseDir = process.cwd()): boolean {
@@ -854,7 +888,7 @@ export default async function cindyBridge(pi: any) {
if (permission.reviewOnly) {
if (
READONLY_BUILTINS.has(event.toolName)
- && reviewReadInputIsAllowed(
+ && normalizeReviewReadInput(
event.toolName,
event.input,
permission.reviewReadPaths,