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): 支持 pnpm 双链接工作区成果 (#2329)

Chris Zhangead258385135
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 1666f556c7..e95352a32e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/reviewStartHandler.test.ts
@@ -6,6 +6,7 @@ import {
readStartReviewRequest,
REVIEW_START_REQUEST_LIMITS,
registerReviewStartHandler,
+ ReviewPreconditionError,
type PreparedReviewLaunch,
type PreparedReviewRun,
type ReviewRunnerHandle,
@@ -792,6 +793,35 @@ describe('maker:review:start IPC lifecycle', () => {
expect(cleanup).toHaveBeenCalledTimes(1);
});
+ it('persists a stable failure code when artifact fingerprint preparation is unsafe', async () => {
+ const harness = new IpcHarness();
+ const reviewer = new FakeReviewer();
+ const deps = makeDeps(reviewer, {
+ prepareRun: vi.fn(async () =>
+ makePreparedRun(makeLaunch(), {
+ prepareLaunch: vi.fn(async () => {
+ throw new ReviewPreconditionError({
+ code: 'artifact-unavailable',
+ message: 'internal artifact safety detail',
+ });
+ }),
+ }),
+ ),
+ });
+ registerReviewStartHandler(harness, deps);
+
+ await expect(harness.invoke(MAKER_INVOKE.START_REVIEW, reviewRequest())).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ });
+ expect(deps.startReviewer).not.toHaveBeenCalled();
+ expect(deps.updateSourceCard).toHaveBeenCalledWith(
+ expect.objectContaining({
+ meta: expect.objectContaining({ status: 'failed', failureCode: 'artifact-unavailable' }),
+ }),
+ );
+ expect(vi.mocked(deps.updateSourceCard).mock.calls[0]?.[0].meta).not.toHaveProperty('error');
+ });
+
it('does not publish a generated reviewer id when reviewer bootstrap itself fails', 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 22ac9292d2..82c65fa53d 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -200,7 +200,11 @@ import {
cleanupOrphanedReviewArtifactSnapshots,
prepareStableReviewArtifactSnapshots,
} from '../reviewer/reviewArtifactSnapshot.js';
-import { fingerprintReviewArtifacts } from '../reviewer/reviewArtifactFingerprint.js';
+import {
+ fingerprintReviewArtifacts,
+ ReviewArtifactFingerprintChangedError,
+ ReviewArtifactFingerprintLimitError,
+} from '../reviewer/reviewArtifactFingerprint.js';
import { enforceReviewCreateOptions } from '../reviewer/reviewSessionPolicy.js';
import { reviewSourceIdentityMatches } from '../reviewer/reviewSourceIdentity.js';
import { buildReviewSessionTitle } from '../reviewer/reviewSessionTitle.js';
@@ -640,7 +644,11 @@ import { agentHandoffPending } from './agentHandoffPendingSingleton.js';
import { type MakerSessionCreateOpts, withCreateSessionStderr } from './sessionRequest.js';
import { persistAndHydrateSessionProvider } from './sessionProviderBootstrap.js';
import { registerMakerSessionSendHandler } from './sessionSendHandler.js';
-import { registerReviewStartHandler, type ReviewFailureReason } from './reviewStartHandler.js';
+import {
+ registerReviewStartHandler,
+ ReviewPreconditionError,
+ type ReviewFailureReason,
+} from './reviewStartHandler.js';
import { registerStopAgentTaskHandler } from './stopAgentTaskHandler.js';
import { registerStopSessionBackgroundTasksHandler } from './stopSessionBackgroundTasksHandler.js';
import { registerProviderHandlers } from './providerHandlers.js';
@@ -7062,9 +7070,39 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// caches or nested-submodule contents, so the reusable result must
// also bind the complete non-sensitive readable workspace content.
const artifactPaths = [...reviewReadPaths, sourceWorkingDir];
- const artifactFingerprint = await fingerprintReviewArtifacts(artifactPaths);
- const completeArtifactFingerprintIsCurrent = async (): Promise<boolean> =>
- (await fingerprintReviewArtifacts(artifactPaths)) === artifactFingerprint;
+ const artifactFingerprintOptions = { linkConfinementRoot: sourceWorkingDir };
+ let artifactFingerprint: string;
+ try {
+ artifactFingerprint = await fingerprintReviewArtifacts(
+ artifactPaths,
+ artifactFingerprintOptions,
+ );
+ } catch (error) {
+ if (
+ error instanceof ReviewArtifactFingerprintChangedError ||
+ error instanceof ReviewArtifactFingerprintLimitError
+ ) {
+ throw new ReviewPreconditionError({
+ code: 'artifact-unavailable',
+ message: error.message,
+ });
+ }
+ throw error;
+ }
+ const artifactFingerprintIsCurrent = async (
+ paths: readonly string[],
+ expected: string,
+ ): Promise<boolean> => {
+ try {
+ return (
+ (await fingerprintReviewArtifacts(paths, artifactFingerprintOptions)) === expected
+ );
+ } catch {
+ return false;
+ }
+ };
+ const completeArtifactFingerprintIsCurrent = (): Promise<boolean> =>
+ artifactFingerprintIsCurrent(artifactPaths, artifactFingerprint);
const readCurrentSourceIdentity = async () => {
const [currentSource] = await db
.select({
@@ -7128,8 +7166,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
}
if (
- (await fingerprintReviewArtifacts(authorizedArtifactPaths)) !==
- sourceArtifactFingerprint
+ !(await artifactFingerprintIsCurrent(
+ authorizedArtifactPaths,
+ sourceArtifactFingerprint,
+ ))
) {
return {
code: 'artifact-changed',
@@ -7177,8 +7217,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
}
if (
- (await fingerprintReviewArtifacts(authorizedArtifactPaths)) !==
- sourceArtifactFingerprint
+ !(await artifactFingerprintIsCurrent(
+ authorizedArtifactPaths,
+ sourceArtifactFingerprint,
+ ))
) {
return {
code: 'artifact-changed',
diff --git a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
index 6fbbfae84f..cebbf72061 100644
--- a/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/reviewStartHandler.ts
@@ -221,7 +221,7 @@ function terminalErrorDetails(event: AgentEvent): {
: { failureCode: 'provider-failed' };
}
-class ReviewPreconditionError extends Error {
+export class ReviewPreconditionError extends Error {
constructor(readonly reason: ReviewFailureReason) {
super(reason.message);
this.name = 'ReviewPreconditionError';
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactAuthorization.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactAuthorization.test.ts
index 34d6c95bee..eba8071982 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactAuthorization.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactAuthorization.test.ts
@@ -46,6 +46,43 @@ describe('authorizeReviewExplicitArtifacts', () => {
expect(confirm).not.toHaveBeenCalled();
});
+ it('grants an explicit scoped pnpm mirror but rejects an additional outside link', async () => {
+ if (process.platform === 'win32') return;
+ const workingDir = await tempDir();
+ const packageRoot = path.join(workingDir, 'packages', 'maker-core');
+ const sourcePath = path.join(packageRoot, 'src', 'index.ts');
+ const mirrorPath = path.join(
+ workingDir,
+ 'node_modules',
+ '@cindy',
+ 'maker-core',
+ 'src',
+ 'index.ts',
+ );
+ await fs.mkdir(path.dirname(sourcePath), { recursive: true });
+ await fs.mkdir(path.dirname(mirrorPath), { recursive: true });
+ await fs.writeFile(path.join(packageRoot, 'package.json'), '{"name":"@cindy/maker-core"}');
+ await fs.writeFile(sourcePath, 'export const value = 1;');
+ await fs.link(sourcePath, mirrorPath);
+ const artifactPath = await fs.realpath(sourcePath);
+ const confirm = vi.fn(async () => true);
+ const authorize = () =>
+ authorizeReviewExplicitArtifacts({
+ workingDir,
+ focus: sourcePath,
+ attachments: [],
+ resolvePath: async () => ({ absPath: artifactPath, managed: false }),
+ confirm,
+ });
+
+ await expect(authorize()).resolves.toMatchObject({ paths: [artifactPath] });
+ expect(confirm).not.toHaveBeenCalled();
+
+ const outsideDir = await tempDir();
+ await fs.link(sourcePath, path.join(outsideDir, 'third-link.ts'));
+ await expect(authorize()).rejects.toThrow(/multiply linked/i);
+ });
+
it('rejects a pre-existing hard-linked artifact before confirmation', async () => {
if (process.platform === 'win32') return;
const workingDir = await tempDir();
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
index 97ff754a89..044db7740d 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
@@ -25,6 +25,18 @@ afterEach(async () => {
});
describe('review artifact fingerprint', () => {
+ it.runIf(Boolean(process.env.CINDY_REVIEW_REAL_WORKSPACE))(
+ 'fingerprints an explicitly requested real workspace',
+ async () => {
+ const workspace = process.env.CINDY_REVIEW_REAL_WORKSPACE!;
+ const before = await fingerprintReviewArtifacts([workspace]);
+ const after = await fingerprintReviewArtifacts([workspace]);
+
+ expect(before).toMatch(/^[a-f0-9]{64}$/);
+ expect(after).toBe(before);
+ },
+ );
+
it('changes for same-size file edits and nested directory edits', async () => {
const dir = await makeTempDir();
const nested = path.join(dir, 'nested');
@@ -212,6 +224,125 @@ describe('review artifact fingerprint', () => {
);
});
+ it('accepts a two-link local package mirror confined to the denied node_modules tree', async () => {
+ if (process.platform === 'win32') return;
+ const workspace = await makeTempDir();
+ const sourcePackage = path.join(workspace, 'apps', 'mobile', 'modules', 'local-module');
+ const sourceFile = path.join(sourcePackage, 'src', 'index.ts');
+ const dependencyFile = path.join(workspace, 'node_modules', 'local-module', 'src', 'index.ts');
+ await fs.mkdir(path.dirname(sourceFile), { recursive: true });
+ await fs.mkdir(path.dirname(dependencyFile), { recursive: true });
+ await fs.writeFile(path.join(sourcePackage, 'package.json'), '{"name":"local-module"}');
+ await fs.writeFile(sourceFile, 'export const value = 1;');
+ await fs.link(sourceFile, dependencyFile);
+
+ await expect(fingerprintReviewArtifacts([workspace])).resolves.toMatch(/^[a-f0-9]{64}$/);
+ await expect(fingerprintReviewArtifacts([sourceFile, workspace])).resolves.toMatch(
+ /^[a-f0-9]{64}$/,
+ );
+ });
+
+ it('accepts a scoped pnpm mirror derived from confined package metadata', async () => {
+ if (process.platform === 'win32') return;
+ const root = await makeTempDir();
+ const workspace = path.join(root, 'workspace');
+ const sourcePackage = path.join(workspace, 'packages', 'maker-core');
+ const manifest = path.join(sourcePackage, 'package.json');
+ const sourceFile = path.join(sourcePackage, 'src', 'index.ts');
+ const dependencyFile = path.join(
+ workspace,
+ 'node_modules',
+ '@cindy',
+ 'maker-core',
+ 'src',
+ 'index.ts',
+ );
+ await fs.mkdir(path.dirname(sourceFile), { recursive: true });
+ await fs.mkdir(path.dirname(dependencyFile), { recursive: true });
+ await fs.writeFile(manifest, '{"name":"@cindy/maker-core"}');
+ await fs.writeFile(sourceFile, 'export const value = 1;');
+ await fs.link(sourceFile, dependencyFile);
+ const unrelatedFile = path.join(workspace, 'outside-package.txt');
+ await fs.writeFile(unrelatedFile, 'first');
+
+ const linkOptions = { linkConfinementRoot: workspace };
+ const singleFileFingerprint = await fingerprintReviewArtifacts([sourceFile], linkOptions);
+ const packageFingerprint = await fingerprintReviewArtifacts([sourcePackage], linkOptions);
+ const workspaceFingerprint = await fingerprintReviewArtifacts([workspace], linkOptions);
+ expect(singleFileFingerprint).toMatch(/^[a-f0-9]{64}$/);
+ expect(packageFingerprint).toMatch(/^[a-f0-9]{64}$/);
+ expect(workspaceFingerprint).toMatch(/^[a-f0-9]{64}$/);
+
+ await fs.writeFile(unrelatedFile, 'second');
+ await expect(fingerprintReviewArtifacts([sourceFile], linkOptions)).resolves.toBe(
+ singleFileFingerprint,
+ );
+ await expect(fingerprintReviewArtifacts([sourcePackage], linkOptions)).resolves.toBe(
+ packageFingerprint,
+ );
+ await expect(fingerprintReviewArtifacts([workspace], linkOptions)).resolves.not.toBe(
+ workspaceFingerprint,
+ );
+
+ const outsideManifest = path.join(root, 'outside-package.json');
+ await fs.writeFile(outsideManifest, '{"name":"@cindy/maker-core"}');
+ await fs.unlink(manifest);
+ await fs.symlink(outsideManifest, manifest);
+ await expect(fingerprintReviewArtifacts([sourceFile], linkOptions)).rejects.toBeInstanceOf(
+ ReviewArtifactFingerprintChangedError,
+ );
+ });
+
+ it('still rejects a local dependency mirror when the inode has any outside link', async () => {
+ if (process.platform === 'win32') return;
+ const root = await makeTempDir();
+ const workspace = path.join(root, 'workspace');
+ const sourcePackage = path.join(workspace, 'packages', 'local-module');
+ const sourceFile = path.join(sourcePackage, 'index.ts');
+ const dependencyFile = path.join(workspace, 'node_modules', 'local-module', 'index.ts');
+ const outsideFile = path.join(root, 'outside.ts');
+ await fs.mkdir(sourcePackage, { recursive: true });
+ await fs.mkdir(path.dirname(dependencyFile), { recursive: true });
+ await fs.writeFile(sourceFile, 'export const value = 1;');
+ await fs.link(sourceFile, dependencyFile);
+ await fs.link(sourceFile, outsideFile);
+
+ await expect(
+ fingerprintReviewArtifacts([sourceFile], { linkConfinementRoot: workspace }),
+ ).rejects.toBeInstanceOf(ReviewArtifactFingerprintChangedError);
+ });
+
+ it('rejects when a confined dependency mirror is replaced before the source is opened', async () => {
+ if (process.platform === 'win32') return;
+ const root = await makeTempDir();
+ const workspace = path.join(root, 'workspace');
+ const sourcePackage = path.join(workspace, 'packages', 'local-module');
+ const sourceFile = path.join(sourcePackage, 'index.ts');
+ const dependencyFile = path.join(workspace, 'node_modules', 'local-module', 'index.ts');
+ const outsideFile = path.join(root, 'outside.ts');
+ await fs.mkdir(sourcePackage, { recursive: true });
+ await fs.mkdir(path.dirname(dependencyFile), { recursive: true });
+ await fs.writeFile(sourceFile, 'export const value = 1;');
+ await fs.writeFile(outsideFile, 'outside bytes');
+ await fs.link(sourceFile, dependencyFile);
+ const canonicalSourceFile = await fs.realpath(sourceFile);
+ let replaced = false;
+
+ await expect(
+ fingerprintReviewArtifacts([sourceFile], {
+ linkConfinementRoot: workspace,
+ openFile: async (filePath, flags) => {
+ if (filePath === canonicalSourceFile && !replaced) {
+ replaced = true;
+ await fs.unlink(dependencyFile);
+ await fs.link(sourceFile, outsideFile + '.linked');
+ }
+ return fs.open(filePath, flags);
+ },
+ }),
+ ).rejects.toBeInstanceOf(ReviewArtifactFingerprintChangedError);
+ });
+
it('rejects a same-size replacement between extraction and the first baseline', async () => {
const dir = await makeTempDir();
const file = path.join(dir, 'draft.txt');
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts
index a524ec585e..428d2fb20f 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts
@@ -107,6 +107,110 @@ describe('materializeReviewArtifactSnapshots', () => {
await materialized.cleanup();
});
+ it('snapshots an explicit scoped pnpm mirror inside the source workspace', async () => {
+ if (process.platform === 'win32') return;
+ const workingDir = await tempDir();
+ const packageRoot = path.join(workingDir, 'packages', 'maker-core');
+ const sourcePath = path.join(packageRoot, 'src', 'index.ts');
+ const mirrorPath = path.join(
+ workingDir,
+ 'node_modules',
+ '@cindy',
+ 'maker-core',
+ 'src',
+ 'index.ts',
+ );
+ await fs.mkdir(path.dirname(sourcePath), { recursive: true });
+ await fs.mkdir(path.dirname(mirrorPath), { recursive: true });
+ await fs.writeFile(path.join(packageRoot, 'package.json'), '{"name":"@cindy/maker-core"}');
+ await fs.writeFile(sourcePath, 'export const value = 1;');
+ await fs.link(sourcePath, mirrorPath);
+ const artifactPath = await fs.realpath(sourcePath);
+
+ const prepared = await prepareStableReviewArtifactSnapshots({
+ workingDir,
+ grant: await grantFor([artifactPath]),
+ owner: TEST_OWNER,
+ prepare: async (snapshotGrant) => {
+ const snapshotPath = snapshotGrant.snapshotPaths?.get(artifactPath);
+ if (!snapshotPath) throw new Error('expected snapshot path');
+ return fs.readFile(snapshotPath, 'utf8');
+ },
+ });
+ expect(prepared.value).toBe('export const value = 1;');
+ await prepared.cleanup();
+ });
+
+ it('keeps a scoped pnpm package-directory focus live while fingerprinting it', async () => {
+ if (process.platform === 'win32') return;
+ const workingDir = await tempDir();
+ const packageRoot = path.join(workingDir, 'packages', 'maker-core');
+ const sourcePath = path.join(packageRoot, 'src', 'index.ts');
+ const mirrorPath = path.join(
+ workingDir,
+ 'node_modules',
+ '@cindy',
+ 'maker-core',
+ 'src',
+ 'index.ts',
+ );
+ await fs.mkdir(path.dirname(sourcePath), { recursive: true });
+ await fs.mkdir(path.dirname(mirrorPath), { recursive: true });
+ await fs.writeFile(path.join(packageRoot, 'package.json'), '{"name":"@cindy/maker-core"}');
+ await fs.writeFile(sourcePath, 'export const value = 1;');
+ await fs.link(sourcePath, mirrorPath);
+ const artifactPath = await fs.realpath(packageRoot);
+
+ const prepared = await prepareStableReviewArtifactSnapshots({
+ workingDir,
+ grant: await grantFor([artifactPath]),
+ owner: TEST_OWNER,
+ prepare: async (snapshotGrant) => snapshotGrant.liveDirectoryPaths,
+ });
+ expect(prepared.value).toEqual([artifactPath]);
+ await prepared.cleanup();
+ });
+
+ it('rejects a pnpm mirror replaced with an outside link after validation', async () => {
+ if (process.platform === 'win32') return;
+ const workingDir = await tempDir();
+ const outsideDir = await tempDir();
+ const packageRoot = path.join(workingDir, 'packages', 'maker-core');
+ const sourcePath = path.join(packageRoot, 'src', 'index.ts');
+ const mirrorPath = path.join(
+ workingDir,
+ 'node_modules',
+ '@cindy',
+ 'maker-core',
+ 'src',
+ 'index.ts',
+ );
+ await fs.mkdir(path.dirname(sourcePath), { recursive: true });
+ await fs.mkdir(path.dirname(mirrorPath), { recursive: true });
+ await fs.writeFile(path.join(packageRoot, 'package.json'), '{"name":"@cindy/maker-core"}');
+ await fs.writeFile(sourcePath, 'export const value = 1;');
+ await fs.link(sourcePath, mirrorPath);
+ const artifactPath = await fs.realpath(sourcePath);
+ const grant = await grantFor([artifactPath]);
+ let replaced = false;
+
+ await expect(
+ materializeReviewArtifactSnapshots({
+ workingDir,
+ grant,
+ owner: TEST_OWNER,
+ openFile: async (filePath, flags) => {
+ if (filePath === artifactPath && !replaced) {
+ replaced = true;
+ await fs.unlink(mirrorPath);
+ await fs.link(sourcePath, path.join(outsideDir, 'outside-link.ts'));
+ }
+ return fs.open(filePath, flags);
+ },
+ }),
+ ).rejects.toBeInstanceOf(ReviewArtifactAuthorizationError);
+ });
+
it('rejects a symlink substituted after the original path was authorized', async () => {
if (process.platform === 'win32') return;
const workingDir = await tempDir();
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts
index 2695926ca4..11d3bdb2d9 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts
@@ -51,7 +51,11 @@ describe('Review external input wiring', () => {
expect(registerSource).toContain(
'const artifactPaths = [...reviewReadPaths, sourceWorkingDir];',
);
- expect(registerSource).toContain('const completeArtifactFingerprintIsCurrent = async');
+ expect(registerSource).toContain(
+ 'const artifactFingerprintOptions = { linkConfinementRoot: sourceWorkingDir };',
+ );
+ expect(registerSource).toContain('const artifactFingerprintIsCurrent = async');
+ expect(registerSource).toContain('const completeArtifactFingerprintIsCurrent = ()');
expect(
registerSource.match(/if \(!\(await completeArtifactFingerprintIsCurrent\(\)\)\)/g),
).toHaveLength(2);
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts b/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts
index 35042bf178..419d64a75d 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts
@@ -2,6 +2,8 @@ import { createHash } from 'node:crypto';
import { promises as fs, type Stats } from 'node:fs';
import path from 'node:path';
+import { reviewFileLinkLayoutIsSafe } from '@cindy/maker-core';
+
export interface ReviewArtifactAuthorizationAttachment {
name: string;
path?: string;
@@ -108,6 +110,24 @@ export function isPathWithinReviewWorkspace(workingDir: string, candidate: strin
);
}
+/**
+ * Reuses the workspace read boundary for explicitly selected files. Only the
+ * exact pnpm mirror layout inside the canonical source workspace is allowed;
+ * external or additional hard links remain denied.
+ */
+export async function reviewArtifactFileLinkLayoutIsSafe(
+ artifactPath: string,
+ canonicalWorkingDir: string | null,
+ stat: Stats,
+): Promise<boolean> {
+ if (stat.nlink <= 1) return true;
+ return Boolean(
+ canonicalWorkingDir &&
+ isPathWithinReviewWorkspace(canonicalWorkingDir, artifactPath) &&
+ (await reviewFileLinkLayoutIsSafe(artifactPath, canonicalWorkingDir, stat)),
+ );
+}
+
/**
* Turns renderer-supplied paths into a one-run Main-owned grant. Workspace
* paths and Cindy-managed media need no extra click; external files and
@@ -135,10 +155,11 @@ export async function authorizeReviewExplicitArtifacts(input: {
'A review artifact changed while permission was being prepared',
);
}
- if (stat.isFile() && stat.nlink > 1) {
- throw new ReviewArtifactAuthorizationError(
- 'Review refused a multiply linked artifact file',
- );
+ if (
+ stat.isFile() &&
+ !(await reviewArtifactFileLinkLayoutIsSafe(resolved.absPath, canonicalWorkingDir, stat))
+ ) {
+ throw new ReviewArtifactAuthorizationError('Review refused a multiply linked artifact file');
}
const existingIdentity = pathIdentities.get(resolved.absPath);
if (existingIdentity && !reviewArtifactPathIdentityMatches(existingIdentity, stat)) {
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
index 04e44d7708..3ebfb14b9b 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
import { constants, promises as fs, type Stats } from 'node:fs';
import path from 'node:path';
-import { isReviewSensitiveCredentialPath } from '@cindy/maker-core';
+import { isReviewSensitiveCredentialPath, reviewFileLinkLayoutIsSafe } from '@cindy/maker-core';
import { reviewArtifactPathIdentityMatches } from './reviewArtifactAuthorization.js';
@@ -24,6 +24,14 @@ interface FingerprintState {
openFile: ReviewArtifactFileOpener;
}
+function isPathWithin(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return (
+ relative === '' ||
+ (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
+ );
+}
+
export interface ReviewArtifactFingerprintOptions {
/** Test seam; production uses the bounded fail-closed default. */
maxDirectoryEntries?: number;
@@ -31,6 +39,8 @@ export interface ReviewArtifactFingerprintOptions {
maxContentBytes?: number;
/** Test seam for deterministic lstat/open replacement coverage. */
openFile?: ReviewArtifactFileOpener;
+ /** Workspace root used only to validate confined pnpm hard-link mirrors. */
+ linkConfinementRoot?: string;
}
export class ReviewArtifactFingerprintLimitError extends Error {}
@@ -71,6 +81,28 @@ async function resolveFingerprintRoot(rawPath: string): Promise<string> {
return canonicalPath;
}
+async function resolveLinkConfinementRoot(rawPath: string): Promise<string> {
+ if (!path.isAbsolute(rawPath) || isSensitive(rawPath)) {
+ throw new ReviewArtifactFingerprintChangedError(
+ 'Review artifact link confinement root is invalid',
+ );
+ }
+ const canonicalPath = await fs.realpath(path.normalize(rawPath)).catch(() => null);
+ const stat = canonicalPath ? await fs.lstat(canonicalPath).catch(() => null) : null;
+ if (
+ !canonicalPath ||
+ isSensitive(canonicalPath) ||
+ !stat ||
+ stat.isSymbolicLink() ||
+ !stat.isDirectory()
+ ) {
+ throw new ReviewArtifactFingerprintChangedError(
+ 'Review artifact link confinement root changed while its fingerprint was prepared',
+ );
+ }
+ return canonicalPath;
+}
+
function addRecord(state: FingerprintState, ...parts: Array<string | number>): void {
state.hash.update(parts.join('\0')).update('\n');
}
@@ -107,10 +139,11 @@ async function hashRange(
async function addFile(
absolutePath: string,
relativePath: string,
+ linkConfinementRoot: string,
stat: Stats,
state: FingerprintState,
): Promise<void> {
- if (stat.nlink > 1) {
+ if (!(await reviewFileLinkLayoutIsSafe(absolutePath, linkConfinementRoot, stat))) {
throw new ReviewArtifactFingerprintChangedError(
'Review refused a multiply linked file in its artifact workspace',
);
@@ -135,8 +168,8 @@ async function addFile(
const opened = await handle.stat();
if (
!opened.isFile() ||
- opened.nlink > 1 ||
- !reviewArtifactPathIdentityMatches(stat, opened)
+ !reviewArtifactPathIdentityMatches(stat, opened) ||
+ !(await reviewFileLinkLayoutIsSafe(absolutePath, linkConfinementRoot, opened))
) {
throw new ReviewArtifactFingerprintChangedError(
'A review artifact changed while its content fingerprint was being prepared',
@@ -149,11 +182,11 @@ async function addFile(
if (
bytesRead !== opened.size ||
!reviewArtifactPathIdentityMatches(opened, afterHandle) ||
- afterHandle.nlink > 1 ||
!afterPath ||
afterPath.isSymbolicLink() ||
- afterPath.nlink > 1 ||
- !reviewArtifactPathIdentityMatches(opened, afterPath)
+ !reviewArtifactPathIdentityMatches(opened, afterPath) ||
+ afterHandle.nlink !== afterPath.nlink ||
+ !(await reviewFileLinkLayoutIsSafe(absolutePath, linkConfinementRoot, afterHandle))
) {
throw new ReviewArtifactFingerprintChangedError(
'A review artifact changed while its content fingerprint was being prepared',
@@ -175,6 +208,7 @@ async function addFile(
async function walk(
absolutePath: string,
relativePath: string,
+ linkConfinementRoot: string,
state: FingerprintState,
): Promise<void> {
if (isSensitive(absolutePath, relativePath)) return;
@@ -214,7 +248,7 @@ async function walk(
await assertCanonicalReviewArtifactPath(absolutePath);
}
if (stat.isFile()) {
- await addFile(absolutePath, relativePath, stat, state);
+ await addFile(absolutePath, relativePath, linkConfinementRoot, stat, state);
return;
}
if (!stat.isDirectory()) {
@@ -239,7 +273,7 @@ async function walk(
for (const entry of entries) {
const childRelative = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (isSensitive(entry.name, childRelative)) continue;
- await walk(path.join(absolutePath, entry.name), childRelative, state);
+ await walk(path.join(absolutePath, entry.name), childRelative, linkConfinementRoot, state);
}
}
@@ -268,15 +302,24 @@ export async function fingerprintReviewArtifacts(
contentBytesRemaining: maxContentBytes,
openFile: options.openFile ?? ((filePath, flags) => fs.open(filePath, flags)),
};
+ const linkConfinementRoot = options.linkConfinementRoot
+ ? await resolveLinkConfinementRoot(options.linkConfinementRoot)
+ : null;
const canonicalRoots = new Set<string>();
for (const rawPath of paths) {
if (!path.isAbsolute(rawPath) || isSensitive(rawPath)) continue;
const canonical = await resolveFingerprintRoot(rawPath);
if (!isSensitive(canonical)) canonicalRoots.add(canonical);
}
- for (const root of [...canonicalRoots].sort()) {
+ const effectiveRoots: string[] = [];
+ for (const root of [...canonicalRoots].sort(
+ (left, right) => left.length - right.length || (left < right ? -1 : left > right ? 1 : 0),
+ )) {
+ if (!effectiveRoots.some((parent) => isPathWithin(parent, root))) effectiveRoots.push(root);
+ }
+ for (const root of effectiveRoots.sort()) {
addRecord(state, 'root', root);
- await walk(root, '.', state);
+ await walk(root, '.', linkConfinementRoot ?? root, state);
}
return state.hash.digest('hex');
}
@@ -291,10 +334,11 @@ export class ReviewArtifactChangedDuringPreparationError extends Error {}
export async function prepareWithStableReviewArtifacts<T>(
paths: readonly string[],
prepare: () => Promise<T>,
+ options: ReviewArtifactFingerprintOptions = {},
): Promise<{ value: T; fingerprint: string }> {
- const before = await fingerprintReviewArtifacts(paths);
+ const before = await fingerprintReviewArtifacts(paths, options);
const value = await prepare();
- const after = await fingerprintReviewArtifacts(paths);
+ const after = await fingerprintReviewArtifacts(paths, options);
if (after !== before) {
throw new ReviewArtifactChangedDuringPreparationError(
'A review artifact changed while evidence was being prepared',
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts b/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
index 375bba7ebe..15b8f99a53 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
@@ -5,6 +5,7 @@ import path from 'node:path';
import {
isPathWithinReviewWorkspace,
+ reviewArtifactFileLinkLayoutIsSafe,
reviewArtifactPathIdentityMatches,
ReviewArtifactAuthorizationError,
type ReviewArtifactPathIdentity,
@@ -261,6 +262,7 @@ async function copyOpenFile(
sourcePath: string,
destinationPath: string,
expectedIdentity: ReviewArtifactPathIdentity,
+ canonicalWorkingDir: string | null,
openFile: ReviewArtifactFileOpener,
): Promise<number> {
const source = await openFile(sourcePath, constants.O_RDONLY | NOFOLLOW_FLAG).catch((error) => {
@@ -286,10 +288,8 @@ async function copyOpenFile(
if (!before.isFile()) {
throw new ReviewArtifactAuthorizationError('Review only snapshots regular files');
}
- if (before.nlink > 1) {
- throw new ReviewArtifactAuthorizationError(
- 'Review refused a multiply linked artifact file',
- );
+ if (!(await reviewArtifactFileLinkLayoutIsSafe(sourcePath, canonicalWorkingDir, before))) {
+ throw new ReviewArtifactAuthorizationError('Review refused a multiply linked artifact file');
}
if (before.size > MAX_SNAPSHOT_FILE_BYTES) {
throw new ReviewArtifactAuthorizationError(
@@ -317,13 +317,21 @@ async function copyOpenFile(
}
const after = await source.stat();
const afterPath = await fs.lstat(sourcePath).catch(() => null);
+ const afterHandleLayoutIsSafe = await reviewArtifactFileLinkLayoutIsSafe(
+ sourcePath,
+ canonicalWorkingDir,
+ after,
+ );
+ const afterPathLayoutIsSafe = afterPath
+ ? await reviewArtifactFileLinkLayoutIsSafe(sourcePath, canonicalWorkingDir, afterPath)
+ : false;
if (
sourceOffset !== before.size ||
!reviewArtifactSnapshotStatMatches(before, after) ||
- after.nlink > 1 ||
+ !afterHandleLayoutIsSafe ||
!afterPath ||
afterPath.isSymbolicLink() ||
- afterPath.nlink > 1 ||
+ !afterPathLayoutIsSafe ||
!reviewArtifactPathIdentityMatches(expectedIdentity, afterPath)
) {
throw new ReviewArtifactAuthorizationError(
@@ -416,7 +424,7 @@ export async function materializeReviewArtifactSnapshots(input: {
if (!entry.isFile()) {
throw new ReviewArtifactAuthorizationError('Review only snapshots regular files');
}
- if (entry.nlink > 1) {
+ if (!(await reviewArtifactFileLinkLayoutIsSafe(sourcePath, canonicalWorkingDir, entry))) {
throw new ReviewArtifactAuthorizationError(
'Review refused a multiply linked artifact file',
);
@@ -457,6 +465,7 @@ export async function materializeReviewArtifactSnapshots(input: {
sourcePath,
destinationPath,
expectedIdentity,
+ canonicalWorkingDir,
input.openFile ?? ((filePath, flags) => fs.open(filePath, flags)),
);
if (totalBytes > MAX_SNAPSHOT_TOTAL_BYTES) {
@@ -494,14 +503,18 @@ export async function prepareStableReviewArtifactSnapshots<T>(input: {
}): Promise<PreparedStableReviewArtifacts<T>> {
const holder: { materialized?: MaterializedReviewArtifacts } = {};
try {
- const stable = await prepareWithStableReviewArtifacts(input.grant.paths, async () => {
- holder.materialized = await materializeReviewArtifactSnapshots({
- workingDir: input.workingDir,
- grant: input.grant,
- owner: input.owner,
- });
- return input.prepare(holder.materialized.grant);
- });
+ const stable = await prepareWithStableReviewArtifacts(
+ input.grant.paths,
+ async () => {
+ holder.materialized = await materializeReviewArtifactSnapshots({
+ workingDir: input.workingDir,
+ grant: input.grant,
+ owner: input.owner,
+ });
+ return input.prepare(holder.materialized.grant);
+ },
+ { linkConfinementRoot: input.workingDir },
+ );
const ready = holder.materialized;
if (!ready) throw new Error('Review artifact snapshots were not prepared');
return {
diff --git a/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx b/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
index 69424bfa49..84ae503076 100644
--- a/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/systemCardReview.test.tsx
@@ -81,9 +81,9 @@ describe('SystemCard Review', () => {
it('localizes legacy built-in errors while preserving unknown provider detail', () => {
const { rerender } = renderCard({
status: 'failed',
- error: 'Reviewer returned no visible conclusion',
+ error: 'Review refused a multiply linked file in its artifact workspace',
});
- expect(screen.getByText('chat.systemCard.review.noResult')).toBeTruthy();
+ expect(screen.getByText('chat.systemCard.review.failure.artifactUnavailable')).toBeTruthy();
rerender(
<MemoryRouter initialEntries={['/cc-agent/source-task']}>
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index af16f3789b..8ec86969f5 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -1140,6 +1140,7 @@ const REVIEW_FAILURE_I18N_KEY: Record<ReviewFailureCode, string> = {
'source-conversation-changed': 'chat.systemCard.review.failure.sourceConversationChanged',
'source-files-changed': 'chat.systemCard.review.failure.sourceFilesChanged',
'artifact-changed': 'chat.systemCard.review.failure.artifactChanged',
+ 'artifact-unavailable': 'chat.systemCard.review.failure.artifactUnavailable',
'provider-failed': 'chat.systemCard.review.failure.providerFailed',
};
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 87f00c3251..a80bd3a583 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6420,6 +6420,7 @@
"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.",
"providerFailed": "The review task failed"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3d5066857c..f4eb484991 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6417,6 +6417,7 @@
"sourceConversationChanged": "元のタスクが変更されました。現在のタスクに対して /review をもう一度実行してください。",
"sourceFilesChanged": "元のタスクのファイルが変更されました。現在の成果に対して /review をもう一度実行してください。",
"artifactChanged": "レビュー対象の成果が変更されました。現在の成果に対して /review をもう一度実行してください。",
+ "artifactUnavailable": "Cindy はレビュー対象の成果を安全に読み取れませんでした。ワークスペースまたは添付ファイルを確認して、/review をもう一度実行してください。",
"providerFailed": "レビュータスクの実行に失敗しました"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 484520c423..d623fdd26b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6417,6 +6417,7 @@
"sourceConversationChanged": "원본 작업이 변경되었습니다. 현재 작업에 대해 /review를 다시 실행하세요.",
"sourceFilesChanged": "원본 작업의 파일이 변경되었습니다. 현재 결과물에 대해 /review를 다시 실행하세요.",
"artifactChanged": "검토 대상 결과물이 변경되었습니다. 현재 결과물에 대해 /review를 다시 실행하세요.",
+ "artifactUnavailable": "Cindy가 검토 대상 결과물을 안전하게 읽지 못했습니다. 작업 공간 또는 첨부 파일을 확인한 후 /review를 다시 실행하세요.",
"providerFailed": "검토 작업 실행에 실패했습니다"
}
}
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 2fbb2a6442..fbe52f47b3 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6417,6 +6417,7 @@
"sourceConversationChanged": "来源任务已变化,请针对当前任务重新运行 /review。",
"sourceFilesChanged": "来源任务的文件已变化,请针对当前成果重新运行 /review。",
"artifactChanged": "审查成果已变化,请针对当前成果重新运行 /review。",
+ "artifactUnavailable": "Cindy 无法安全读取审查成果,请检查工作区或附件后重新运行 /review。",
"providerFailed": "审查任务执行失败"
}
}
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 3ad2bcc49a..7e773b04cc 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2266,6 +2266,9 @@
"nestedLabel": "允許 Subagent 再建立 Subagent",
"nestedHint": "僅舊版 Codex Multi-Agent(V1)生效,Sol / Terra(V2)會忽略此設定。",
"nestedAria": "允許 Subagent 再建立 Subagent",
+ "cindyPolicyLabel": "使用 Cindy 自訂 Subagent 策略",
+ "cindyPolicyHint": "開啟後,Cindy 會注入策略,引導 Codex 在探索型任務中主動使用 Subagent。對於本身已擅長規劃與委派的模型,額外引導可能適得其反;關閉後不再注入,改用 Codex 的原生預設行為。",
+ "cindyPolicyAria": "使用 Cindy 自訂 Subagent 策略",
"localOnlyHint": "以上護欄僅對本機執行的 Codex 生效,SSH 遠端連線的 Codex 不受影響。"
},
"toast": {
@@ -6417,6 +6420,7 @@
"sourceConversationChanged": "來源任務已變更,請針對當前任務重新執行 /review。",
"sourceFilesChanged": "來源任務的檔案已變更,請針對當前成果重新執行 /review。",
"artifactChanged": "審查成果已變更,請針對當前成果重新執行 /review。",
+ "artifactUnavailable": "Cindy 無法安全讀取審查成果,請檢查工作區或附件後重新執行 /review。",
"providerFailed": "審查任務執行失敗"
}
}
diff --git a/apps/desktop/src/shared/reviewRun.ts b/apps/desktop/src/shared/reviewRun.ts
index 6e7ae09858..52a51655c3 100644
--- a/apps/desktop/src/shared/reviewRun.ts
+++ b/apps/desktop/src/shared/reviewRun.ts
@@ -11,6 +11,7 @@ export const REVIEW_FAILURE_CODES = [
'source-conversation-changed',
'source-files-changed',
'artifact-changed',
+ 'artifact-unavailable',
'provider-failed',
] as const;
@@ -57,6 +58,7 @@ const LEGACY_REVIEW_FAILURE_CODE_BY_ERROR = new Map<string, ReviewFailureCode>([
'A review artifact changed while Review was running. Run /review again for the current result.',
'artifact-changed',
],
+ ['Review refused a multiply linked file in its artifact workspace', 'artifact-unavailable'],
['Reviewer task failed', 'provider-failed'],
]);
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 6a5f83da22..f7a80ff044 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -1,4 +1,6 @@
import {
+ linkSync,
+ lstatSync,
mkdtempSync,
mkdirSync,
readFileSync,
@@ -9,8 +11,10 @@ import {
unlinkSync,
writeFileSync,
} from 'node:fs';
+import { spawn } from 'node:child_process';
import { tmpdir } from 'node:os';
import * as path from 'node:path';
+import { createInterface } from 'node:readline';
import { runInNewContext } from 'node:vm';
import ts from 'typescript';
@@ -18,6 +22,89 @@ import { describe, expect, it } from 'vitest';
import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
+type ReviewSearchHelpers = {
+ filterReviewGrepResult: (
+ result: unknown,
+ input: unknown,
+ allowedPaths: string[],
+ ) => { content: Array<{ text?: string }>; details?: unknown };
+ reviewSearchPathIsVisible: (
+ candidate: string,
+ allowedPaths: string[],
+ baseDir?: string,
+ ) => boolean;
+ rgGlob: (
+ pattern: string,
+ cwd: string,
+ options: { ignore: string[]; limit: number },
+ ) => Promise<string[]>;
+};
+
+function loadReviewSearchHelpers(
+ workingDir: string,
+ overrides: {
+ lstatSync?: typeof lstatSync;
+ managedRipgrepPath?: string;
+ } = {},
+): ReviewSearchHelpers {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+ const helperStart = source.indexOf("function isInsideRoot");
+ const helperEnd = source.indexOf("// ── MCP streamable-HTTP");
+ const findStart = source.indexOf("function rgGlob(");
+ const findEnd = source.indexOf("export default async function cindyBridge");
+ if (
+ helperStart < 0 ||
+ helperEnd <= helperStart ||
+ findStart < 0 ||
+ findEnd <= findStart
+ ) {
+ throw new Error(
+ "Review search helpers were not found in the generated bridge",
+ );
+ }
+ const executableSource = [
+ "const REVIEW_CREDENTIAL_PATH_PATTERNS: RegExp[] = [/(?:^|[\\\\/])node_modules(?:[\\\\/]|$)/i];",
+ "const REVIEW_CREDENTIAL_GLOB_PATTERNS: string[] = [];",
+ source.slice(helperStart, helperEnd),
+ "function currentPermissionState() {",
+ " return { reviewOnly: true, reviewReadPaths: (globalThis as any).__reviewReadPaths };",
+ "}",
+ "function managedRipgrepPath() { return (globalThis as any).__managedRipgrepPath; }",
+ source.slice(findStart, findEnd),
+ "(globalThis as any).filterReviewGrepResult = filterReviewGrepResult;",
+ "(globalThis as any).reviewSearchPathIsVisible = reviewSearchPathIsVisible;",
+ "(globalThis as any).rgGlob = rgGlob;",
+ ].join("\n");
+ const compiled = ts.transpileModule(executableSource, {
+ compilerOptions: {
+ module: ts.ModuleKind.None,
+ target: ts.ScriptTarget.ES2022,
+ },
+ }).outputText;
+ const context: Partial<ReviewSearchHelpers> & Record<string, unknown> = {
+ path,
+ process: { cwd: () => workingDir, platform: process.platform },
+ Buffer,
+ lstatSync: overrides.lstatSync ?? lstatSync,
+ readFileSync,
+ realpathSync,
+ statSync,
+ spawn,
+ createInterface,
+ __reviewReadPaths: [workingDir],
+ __managedRipgrepPath: overrides.managedRipgrepPath ?? "",
+ };
+ runInNewContext(compiled, context);
+ if (
+ !context.filterReviewGrepResult ||
+ !context.reviewSearchPathIsVisible ||
+ !context.rgGlob
+ ) {
+ throw new Error("Review search helpers were not loaded");
+ }
+ return context as ReviewSearchHelpers;
+}
+
describe('cindy-bridge extension source', () => {
it('is valid standalone TypeScript for the Pi runtime to load', () => {
const result = ts.transpileModule(CINDY_BRIDGE_EXTENSION_SOURCE, {
@@ -48,8 +135,12 @@ describe('cindy-bridge extension source', () => {
expect(source).not.toContain("'--glob', pattern");
expect(source).toContain('glob: rgGlob');
expect(source).toContain('const grepTool = createGrepTool(process.cwd())');
- expect(source).toContain('filterReviewGrepResult(result, params)');
- expect(source).toContain('reviewSearchPathTouchesCredential(relative, cwd)');
+ expect(source).toContain(
+ 'filterReviewGrepResult(result, params, permission.reviewReadPaths)',
+ );
+ expect(source).toContain(
+ 'reviewSearchPathIsVisible(relative, permission.reviewReadPaths, cwd)',
+ );
expect(source).toContain('spawn(managedRipgrepPath(), args, {');
expect(source).not.toContain("spawn('rg'");
expect(source).toContain("const MANAGED_RG_PATH_ENV = 'CINDY_PI_MANAGED_RG_PATH'");
@@ -88,11 +179,13 @@ describe('cindy-bridge extension source', () => {
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('reviewFileLinkLayoutIsSafe(target, targetStat, allowed)');
+ expect(source).toContain("candidates.add(path.join(dependencyRoot, 'node_modules'");
+ expect(source).toContain('reviewSearchPathHasUnsafeLinkLayout');
expect(source).toContain(
- 'stat.isDirectory() ? isInsideRoot(target, allowed) : target === allowed',
+ 'reviewSearchPathIsVisible(relative, permission.reviewReadPaths, cwd)',
);
- expect(source).toContain('targetStat.isFile() && targetStat.nlink > 1');
- expect(source).toContain('reviewSearchPathHasMultipleLinks');
+ expect(source).not.toContain('reviewSearchPathHasMultipleLinks');
expect(source).toContain('REVIEW_CREDENTIAL_PATH_PATTERNS.some');
expect(source).toContain('REVIEW_CREDENTIAL_GLOB_PATTERNS.some');
});
@@ -107,7 +200,7 @@ describe('cindy-bridge extension source', () => {
expect(helperEnd).toBeGreaterThan(helperStart);
const executableSource = [
- 'const REVIEW_CREDENTIAL_PATH_PATTERNS: RegExp[] = [];',
+ "const REVIEW_CREDENTIAL_PATH_PATTERNS: RegExp[] = [/(?:^|[\\\\/])node_modules(?:[\\\\/]|$)/i];",
source.slice(helperStart, helperEnd),
'(globalThis as any).normalizeReviewReadInput = normalizeReviewReadInput;',
].join('\n');
@@ -141,6 +234,9 @@ describe('cindy-bridge extension source', () => {
} & Record<string, unknown> = {
path,
process: { cwd: () => workingDir, platform: process.platform },
+ Buffer,
+ lstatSync,
+ readFileSync,
realpathSync,
statSync,
};
@@ -149,26 +245,30 @@ describe('cindy-bridge extension source', () => {
expect(normalizeReviewReadInput).toBeTypeOf('function');
if (!normalizeReviewReadInput) throw new Error('Review read normalizer was not loaded');
+ const readInput = { path: linkPath };
+ const grepInput = { request: { paths: [linkPath] }, pattern: 'approved' };
+ const findInput = { options: { filePath: linkPath }, pattern: '*.txt' };
+ const lsInput = { filepath: linkPath };
const inputs = [
- { tool: 'read', input: { path: linkPath } },
+ { tool: 'read', input: readInput },
{
tool: 'grep',
- input: { request: { paths: [linkPath] }, pattern: 'approved' },
+ input: grepInput,
},
{
tool: 'find',
- input: { options: { filePath: linkPath }, pattern: '*.txt' },
+ input: findInput,
},
- { tool: 'ls', input: { filepath: linkPath } },
+ { tool: 'ls', input: lsInput },
];
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));
+ expect(readInput.path).toBe(realpathSync(approvedPath));
+ expect(grepInput.request.paths).toEqual([realpathSync(approvedPath)]);
+ expect(findInput.options.filePath).toBe(realpathSync(approvedPath));
+ expect(lsInput.filepath).toBe(realpathSync(approvedPath));
for (const tool of ['read', 'grep', 'find', 'ls']) {
const defaultInput: Record<string, unknown> = {};
@@ -176,12 +276,250 @@ describe('cindy-bridge extension source', () => {
expect(defaultInput.path).toBe(realpathSync(workingDir));
}
+ const localPackage = path.join(workingDir, 'packages', 'maker-core');
+ const localSource = path.join(localPackage, 'src', 'index.ts');
+ const localMirror = path.join(
+ workingDir,
+ 'node_modules',
+ '@cindy',
+ 'maker-core',
+ 'src',
+ 'index.ts',
+ );
+ mkdirSync(path.dirname(localSource), { recursive: true });
+ mkdirSync(path.dirname(localMirror), { recursive: true });
+ writeFileSync(
+ path.join(localPackage, 'package.json'),
+ '{"name":"@cindy/maker-core"}',
+ );
+ writeFileSync(localSource, 'export const value = 1;');
+ linkSync(localSource, localMirror);
+ expect(
+ normalizeReviewReadInput('read', { path: localSource }, [workingDir]),
+ ).toBe(true);
+
+ const outsideManifest = path.join(outsideDir, 'package.json');
+ const localManifest = path.join(localPackage, 'package.json');
+ writeFileSync(outsideManifest, '{"name":"@cindy/maker-core"}');
+ unlinkSync(localManifest);
+ symlinkSync(outsideManifest, localManifest);
+ expect(
+ normalizeReviewReadInput('read', { path: localSource }, [workingDir]),
+ ).toBe(false);
+ unlinkSync(localManifest);
+ writeFileSync(localManifest, '{"name":"@cindy/maker-core"}');
+
+ linkSync(localSource, path.join(outsideDir, 'third-link.ts'));
+ expect(
+ normalizeReviewReadInput('read', { path: localSource }, [workingDir]),
+ ).toBe(false);
+
unlinkSync(linkPath);
symlinkSync(outsidePath, linkPath);
- expect(readFileSync(inputs[0]!.input.path, 'utf8')).toBe('approved');
+ expect(readFileSync(readInput.path, 'utf8')).toBe('approved');
} finally {
rmSync(tempRoot, { recursive: true, force: true });
}
},
);
+
+ it.skipIf(process.platform === "win32")(
+ "keeps safe pnpm links visible to Pi Grep and managed Find while rejecting unsafe layouts",
+ async () => {
+ const tempRoot = mkdtempSync(
+ path.join(tmpdir(), "cindy-pi-review-search-"),
+ );
+ try {
+ const workingDir = path.join(tempRoot, "workspace");
+ const outsideDir = path.join(tempRoot, "outside");
+ mkdirSync(workingDir);
+ mkdirSync(outsideDir);
+
+ const sourcePackage = path.join(
+ workingDir,
+ "packages",
+ "maker-core",
+ );
+ const sourcePath = path.join(sourcePackage, "src", "index.ts");
+ const mirrorPath = path.join(
+ workingDir,
+ "node_modules",
+ "@cindy",
+ "maker-core",
+ "src",
+ "index.ts",
+ );
+ mkdirSync(path.dirname(sourcePath), { recursive: true });
+ mkdirSync(path.dirname(mirrorPath), { recursive: true });
+ writeFileSync(
+ path.join(sourcePackage, "package.json"),
+ '{"name":"@cindy/maker-core"}',
+ );
+ writeFileSync(sourcePath, "export const safe = true;");
+ linkSync(sourcePath, mirrorPath);
+
+ const managedRipgrepPath = path.resolve(
+ process.cwd(),
+ "..",
+ "..",
+ "apps",
+ "ripgrep-bin",
+ `${process.platform}-${process.arch}`,
+ "rg",
+ );
+ expect(statSync(managedRipgrepPath).isFile()).toBe(true);
+ const helpers = loadReviewSearchHelpers(workingDir, {
+ managedRipgrepPath,
+ });
+ const relativeSource = path.relative(workingDir, sourcePath);
+ expect(
+ helpers.reviewSearchPathIsVisible(
+ relativeSource,
+ [workingDir],
+ workingDir,
+ ),
+ ).toBe(true);
+ const visibleGrep = helpers.filterReviewGrepResult(
+ {
+ content: [
+ {
+ type: "text",
+ text: `${relativeSource}:1:export const safe = true;`,
+ },
+ ],
+ },
+ { path: workingDir },
+ [workingDir],
+ );
+ expect(visibleGrep.content[0]?.text).toContain(relativeSource);
+ expect(
+ await helpers.rgGlob("index.ts", workingDir, {
+ ignore: [],
+ limit: 100,
+ }),
+ ).toContain(sourcePath);
+
+ const outsideSecret = path.join(outsideDir, "secret.ts");
+ const outsideAlias = path.join(workingDir, "outside-alias.ts");
+ writeFileSync(outsideSecret, "export const secret = true;");
+ linkSync(outsideSecret, outsideAlias);
+ expect(
+ helpers.reviewSearchPathIsVisible(
+ "outside-alias.ts",
+ [workingDir],
+ workingDir,
+ ),
+ ).toBe(false);
+ expect(
+ await helpers.rgGlob("*.ts", workingDir, { ignore: [], limit: 100 }),
+ ).not.toContain(outsideAlias);
+
+ const thirdLink = path.join(outsideDir, "third-link.ts");
+ linkSync(sourcePath, thirdLink);
+ expect(
+ helpers.reviewSearchPathIsVisible(
+ relativeSource,
+ [workingDir],
+ workingDir,
+ ),
+ ).toBe(false);
+ expect(
+ await helpers.rgGlob("index.ts", workingDir, {
+ ignore: [],
+ limit: 100,
+ }),
+ ).not.toContain(sourcePath);
+ unlinkSync(thirdLink);
+
+ let replaced = false;
+ const sourceIdentity = statSync(sourcePath);
+ const replacingHelpers = loadReviewSearchHelpers(workingDir, {
+ managedRipgrepPath,
+ lstatSync: ((candidate: Parameters<typeof lstatSync>[0]) => {
+ const candidateStat = lstatSync(candidate);
+ if (
+ !replaced &&
+ candidateStat.isFile() &&
+ candidateStat.ino === sourceIdentity.ino &&
+ candidateStat.dev === sourceIdentity.dev
+ ) {
+ replaced = true;
+ const candidatePath = candidate.toString();
+ unlinkSync(candidatePath);
+ writeFileSync(candidatePath, "export const replacement = true;");
+ return lstatSync(candidate);
+ }
+ return candidateStat;
+ }) as typeof lstatSync,
+ });
+ expect(
+ await replacingHelpers.rgGlob("index.ts", workingDir, {
+ ignore: [],
+ limit: 100,
+ }),
+ ).not.toContain(sourcePath);
+ expect(replaced).toBe(true);
+ } finally {
+ rmSync(tempRoot, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it.skipIf(
+ process.platform === "win32" || !process.env.CINDY_REVIEW_REAL_WORKSPACE,
+ )(
+ "keeps a real pnpm-linked workspace file visible to Pi Grep and managed Find",
+ async () => {
+ const workingDir = process.env.CINDY_REVIEW_REAL_WORKSPACE!;
+ const sourcePath = path.join(
+ workingDir,
+ "apps",
+ "mobile",
+ "modules",
+ "xdt-ios-app-distribution",
+ "src",
+ "index.ts",
+ );
+ expect(statSync(sourcePath).nlink).toBe(2);
+ const relativeSource = path.relative(workingDir, sourcePath);
+ const managedRipgrepPath = path.resolve(
+ process.cwd(),
+ "..",
+ "..",
+ "apps",
+ "ripgrep-bin",
+ `${process.platform}-${process.arch}`,
+ "rg",
+ );
+ const helpers = loadReviewSearchHelpers(workingDir, {
+ managedRipgrepPath,
+ });
+ expect(
+ helpers.reviewSearchPathIsVisible(
+ relativeSource,
+ [workingDir],
+ workingDir,
+ ),
+ ).toBe(true);
+ const visibleGrep = helpers.filterReviewGrepResult(
+ {
+ content: [
+ {
+ type: "text",
+ text: `${relativeSource}:1:export * from './types';`,
+ },
+ ],
+ },
+ { path: workingDir },
+ [workingDir],
+ );
+ expect(visibleGrep.content[0]?.text).toContain(relativeSource);
+ expect(
+ await helpers.rgGlob("index.ts", workingDir, {
+ ignore: [],
+ limit: 1000,
+ }),
+ ).toContain(sourcePath);
+ },
+ );
});
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 d46c05be8e..fc8926f85e 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -27,14 +27,14 @@ import {
REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS,
REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS,
SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS,
-} from '../shared/sensitive-credential-paths.js';
+} from "../shared/sensitive-credential-paths.js";
-export const CINDY_BRIDGE_EXTENSION_FILENAME = 'cindy-bridge.ts';
+export const CINDY_BRIDGE_EXTENSION_FILENAME = "cindy-bridge.ts";
export const CINDY_BRIDGE_EXTENSION_SOURCE = String.raw`/**
* cindy-bridge (generated by Cindy — do not edit; overwritten on session start)
*/
-import { readFileSync, realpathSync, statSync } from 'node:fs';
+import { lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
import { stat } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
@@ -176,6 +176,128 @@ function isInsideRoot(candidate: string, root: string): boolean {
return rel === '' || (!rel.startsWith('..' + path.sep) && rel !== '..' && !path.isAbsolute(rel));
}
+function reviewAncestorsWithin(start: string, root: string): string[] {
+ const boundary = path.resolve(root);
+ const ancestors: string[] = [];
+ let current = path.resolve(start);
+ while (isInsideRoot(current, boundary)) {
+ ancestors.push(current);
+ if (current === boundary) break;
+ const parent = path.dirname(current);
+ if (parent === current) break;
+ current = parent;
+ }
+ return ancestors;
+}
+
+function reviewStatsReferToSameFile(
+ left: ReturnType<typeof statSync>,
+ right: ReturnType<typeof statSync>,
+): boolean {
+ return left.ino !== 0 && left.dev === right.dev && left.ino === right.ino;
+}
+
+const REVIEW_PACKAGE_MANIFEST_MAX_BYTES = 256 * 1024;
+
+function normalizeReviewDeclaredPackageName(value: unknown): string | null {
+ if (
+ typeof value !== 'string'
+ || value.length === 0
+ || value.length > 214
+ || value !== value.trim()
+ ) return null;
+ const component = '[a-z0-9][a-z0-9._-]*';
+ const pattern = value.startsWith('@')
+ ? new RegExp('^@' + component + '/' + component + '$', 'i')
+ : new RegExp('^' + component + '$', 'i');
+ return pattern.test(value) ? value : null;
+}
+
+function reviewDeclaredPackageName(
+ packageRoot: string,
+ confinementRoot: string,
+): string | null {
+ try {
+ const manifestPath = path.join(packageRoot, 'package.json');
+ if (!isInsideRoot(manifestPath, confinementRoot)) return null;
+ const manifestLstat = lstatSync(manifestPath);
+ if (
+ manifestLstat.isSymbolicLink()
+ || !manifestLstat.isFile()
+ || manifestLstat.size > REVIEW_PACKAGE_MANIFEST_MAX_BYTES
+ ) return null;
+ const realManifest = realpathSync(manifestPath);
+ if (!isInsideRoot(realManifest, confinementRoot)) return null;
+ const manifestStat = statSync(realManifest);
+ if (!manifestStat.isFile() || manifestStat.size > REVIEW_PACKAGE_MANIFEST_MAX_BYTES) {
+ return null;
+ }
+ const raw = readFileSync(realManifest, 'utf8');
+ if (Buffer.byteLength(raw, 'utf8') > REVIEW_PACKAGE_MANIFEST_MAX_BYTES) return null;
+ return normalizeReviewDeclaredPackageName(JSON.parse(raw)?.name);
+ } catch {
+ return null;
+ }
+}
+
+function reviewFileLinkLayoutIsSafe(
+ target: string,
+ targetStat: ReturnType<typeof statSync>,
+ confinementRoot: string,
+): boolean {
+ if (!targetStat.isFile()) return targetStat.isDirectory();
+ if (targetStat.nlink <= 1) return true;
+ if (targetStat.nlink !== 2 || !isInsideRoot(target, confinementRoot)) {
+ return false;
+ }
+ const candidates = new Set<string>();
+ for (const packageRoot of reviewAncestorsWithin(path.dirname(target), confinementRoot)) {
+ const packageBase = path.basename(packageRoot);
+ if (!packageBase || packageBase === path.sep || packageBase === 'node_modules') continue;
+ const packageNames = [packageBase];
+ const declaredPackageName = reviewDeclaredPackageName(packageRoot, confinementRoot);
+ if (declaredPackageName) packageNames.push(declaredPackageName);
+ const scope = path.basename(path.dirname(packageRoot));
+ if (scope.startsWith('@') && scope.length > 1) {
+ packageNames.push(path.join(scope, packageBase));
+ }
+ const relativePath = path.relative(packageRoot, target);
+ if (!relativePath || relativePath.startsWith('..' + path.sep) || path.isAbsolute(relativePath)) {
+ continue;
+ }
+ for (const dependencyRoot of reviewAncestorsWithin(path.dirname(packageRoot), confinementRoot)) {
+ for (const packageName of packageNames) {
+ candidates.add(path.join(dependencyRoot, 'node_modules', packageName, relativePath));
+ }
+ }
+ }
+ for (const candidate of candidates) {
+ if (!REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(candidate))) continue;
+ try {
+ const candidateStat = lstatSync(candidate);
+ if (
+ candidateStat.isSymbolicLink()
+ || !candidateStat.isFile()
+ || candidateStat.nlink !== 2
+ || !reviewStatsReferToSameFile(targetStat, candidateStat)
+ ) {
+ continue;
+ }
+ const realCandidate = realpathSync(candidate);
+ if (
+ path.resolve(realCandidate) !== path.resolve(target)
+ && isInsideRoot(realCandidate, confinementRoot)
+ && REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(realCandidate))
+ ) {
+ return true;
+ }
+ } catch {
+ // Candidate disappeared or changed while validating; fail closed below.
+ }
+ }
+ return false;
+}
+
function resolveReviewReadPath(candidate: string, allowedPaths: string[]): string | null {
try {
const requested = path.resolve(process.cwd(), candidate);
@@ -183,13 +305,18 @@ function resolveReviewReadPath(candidate: string, allowedPaths: string[]): strin
const target = realpathSync(requested);
if (REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(target))) return null;
const targetStat = statSync(target);
- if (targetStat.isFile() && targetStat.nlink > 1) return null;
const allowed = allowedPaths.some((allowedPath) => {
try {
const allowed = realpathSync(allowedPath);
const stat = statSync(allowed);
if (stat.isFile() && stat.nlink > 1) return false;
- return stat.isDirectory() ? isInsideRoot(target, allowed) : target === allowed;
+ if (stat.isDirectory()) {
+ return (
+ isInsideRoot(target, allowed)
+ && reviewFileLinkLayoutIsSafe(target, targetStat, allowed)
+ );
+ }
+ return targetStat.nlink <= 1 && target === allowed;
} catch {
return false;
}
@@ -359,22 +486,59 @@ function reviewSearchPathTouchesCredential(candidate: string, baseDir = process.
}
}
-function reviewSearchPathHasMultipleLinks(candidate: string, baseDir = process.cwd()): boolean {
+function reviewSearchPathHasUnsafeLinkLayout(
+ candidate: string,
+ allowedPaths: string[],
+ baseDir = process.cwd(),
+): boolean {
try {
- const target = realpathSync(path.resolve(baseDir, candidate));
- const stat = statSync(target);
- return stat.isFile() && stat.nlink > 1;
+ const requested = path.resolve(baseDir, candidate);
+ const target = realpathSync(requested);
+ const targetStat = statSync(target);
+ if (!targetStat.isFile() || targetStat.nlink <= 1) return false;
+ const safeWithinGrant = allowedPaths.some((allowedPath) => {
+ try {
+ const allowed = realpathSync(allowedPath);
+ const allowedStat = statSync(allowed);
+ return (
+ allowedStat.isDirectory()
+ && isInsideRoot(target, allowed)
+ && reviewFileLinkLayoutIsSafe(target, targetStat, allowed)
+ );
+ } catch {
+ return false;
+ }
+ });
+ if (!safeWithinGrant) return true;
+ const finalTarget = realpathSync(requested);
+ const finalStat = statSync(finalTarget);
+ return (
+ path.resolve(finalTarget) !== path.resolve(target)
+ || !reviewStatsReferToSameFile(targetStat, finalStat)
+ || finalStat.nlink !== targetStat.nlink
+ );
} catch {
return true;
}
}
+function reviewSearchPathIsVisible(
+ candidate: string,
+ allowedPaths: string[],
+ baseDir = process.cwd(),
+): boolean {
+ return (
+ !reviewSearchPathTouchesCredential(candidate, baseDir)
+ && !reviewSearchPathHasUnsafeLinkLayout(candidate, allowedPaths, baseDir)
+ );
+}
+
function reviewGrepOutputPath(line: string): string | null {
const match = /^(.*?)(?::\d+:|-\d+-)/.exec(line);
return match?.[1] ?? null;
}
-function filterReviewGrepResult(result: any, input: unknown): any {
+function filterReviewGrepResult(result: any, input: unknown, allowedPaths: string[]): any {
if (!result || typeof result !== 'object' || !Array.isArray(result.content)) {
return { content: [{ type: 'text', text: 'No matches found' }], details: undefined };
}
@@ -396,8 +560,7 @@ function filterReviewGrepResult(result: any, input: unknown): any {
const lines = item.text.split('\n').filter((line: string) => {
const candidate = reviewGrepOutputPath(line);
if (!candidate) return true;
- if (reviewSearchPathTouchesCredential(candidate, resultBase)) return false;
- if (reviewSearchPathHasMultipleLinks(candidate, resultBase)) return false;
+ if (!reviewSearchPathIsVisible(candidate, allowedPaths, resultBase)) return false;
visibleMatch = true;
return true;
});
@@ -725,7 +888,8 @@ function rgGlob(
options: { ignore: string[]; limit: number },
): Promise<string[]> {
return new Promise((resolve, reject) => {
- const reviewOnly = currentPermissionState().reviewOnly;
+ const permission = currentPermissionState();
+ const reviewOnly = permission.reviewOnly;
const limit = Number.isFinite(options.limit) ? Math.max(1, Math.floor(options.limit)) : 1000;
const args = ['--files', '--hidden', '--no-require-git'];
for (const ignored of options.ignore) args.push('--glob', '!' + ignored);
@@ -747,8 +911,7 @@ function rgGlob(
reader.on('line', (line) => {
if (!line || lines.length >= limit) return;
const relative = line.replace(/\r$/, '');
- if (reviewOnly && reviewSearchPathTouchesCredential(relative, cwd)) return;
- if (reviewOnly && reviewSearchPathHasMultipleLinks(relative, cwd)) return;
+ if (reviewOnly && !reviewSearchPathIsVisible(relative, permission.reviewReadPaths, cwd)) return;
// 完整镜像 Pi 上游 fd 规则:无 slash 时匹配 basename;有 slash 时启用
// full-path,且相对 pattern 自动加 **/,让 src/** 同时命中 monorepo 子包。
let candidate = path.basename(relative);
@@ -796,9 +959,11 @@ export default async function cindyBridge(pi: any) {
execute: async (id: string, params: unknown, signal: AbortSignal, onUpdate: unknown) => {
// Fail closed before Pi upstream ensureTool can fall back to cwd/PATH lookup.
managedRipgrepPath();
- const reviewOnly = currentPermissionState().reviewOnly;
+ const permission = currentPermissionState();
const result = await grepTool.execute(id, params as any, signal, onUpdate as any);
- return reviewOnly ? filterReviewGrepResult(result, params) : result;
+ return permission.reviewOnly
+ ? filterReviewGrepResult(result, params, permission.reviewReadPaths)
+ : result;
},
});
diff --git a/packages/maker-core/src/agents/shared/review-read-scope.test.ts b/packages/maker-core/src/agents/shared/review-read-scope.test.ts
index 778a7444b3..9a31dfe211 100644
--- a/packages/maker-core/src/agents/shared/review-read-scope.test.ts
+++ b/packages/maker-core/src/agents/shared/review-read-scope.test.ts
@@ -27,6 +27,28 @@ afterEach(async () => {
});
describe("review read scope", () => {
+ it.runIf(Boolean(process.env.CINDY_REVIEW_REAL_WORKSPACE))(
+ "resolves a pnpm-linked source file in an explicitly requested real workspace",
+ async () => {
+ const workspace = process.env.CINDY_REVIEW_REAL_WORKSPACE!;
+ const source = path.join(
+ workspace,
+ "apps",
+ "mobile",
+ "modules",
+ "xdt-ios-app-distribution",
+ "src",
+ "index.ts",
+ );
+ expect((await fs.stat(source)).nlink).toBe(2);
+
+ const grants = await buildReviewReadGrants(workspace, []);
+ expect(await resolveReviewReadPath(source, workspace, grants)).toBe(
+ await fs.realpath(source),
+ );
+ },
+ );
+
it("allows workspace files and exact external attachment grants", async () => {
const root = await makeTempDir();
const workspace = path.join(root, "workspace");
@@ -119,4 +141,77 @@ describe("review read scope", () => {
),
).rejects.toThrow(/refused/i);
});
+
+ it("allows a two-link pnpm local package source only when its denied mirror is confined", async () => {
+ if (process.platform === "win32") return;
+ const root = await makeTempDir();
+ const workspace = path.join(root, "workspace");
+ const sourcePackage = path.join(
+ workspace,
+ "apps",
+ "mobile",
+ "modules",
+ "local-module",
+ );
+ const source = path.join(sourcePackage, "src", "index.ts");
+ const mirror = path.join(
+ workspace,
+ "node_modules",
+ "local-module",
+ "src",
+ "index.ts",
+ );
+ await fs.mkdir(path.dirname(source), { recursive: true });
+ await fs.mkdir(path.dirname(mirror), { recursive: true });
+ await fs.writeFile(source, "export const value = 1;");
+ await fs.link(source, mirror);
+
+ const grants = await buildReviewReadGrants(workspace, [
+ sourcePackage,
+ source,
+ ]);
+ expect(await resolveReviewReadPath(source, workspace, grants)).toBe(
+ await fs.realpath(source),
+ );
+
+ const outside = path.join(root, "outside.ts");
+ await fs.link(source, outside);
+ expect(await resolveReviewReadPath(source, workspace, grants)).toBeNull();
+ });
+
+ it("uses a confined package manifest to resolve scoped pnpm mirrors", async () => {
+ if (process.platform === "win32") return;
+ const root = await makeTempDir();
+ const workspace = path.join(root, "workspace");
+ const packageRoot = path.join(workspace, "packages", "maker-core");
+ const manifest = path.join(packageRoot, "package.json");
+ const source = path.join(packageRoot, "src", "index.ts");
+ const mirror = path.join(
+ workspace,
+ "node_modules",
+ "@cindy",
+ "maker-core",
+ "src",
+ "index.ts",
+ );
+ await fs.mkdir(path.dirname(source), { recursive: true });
+ await fs.mkdir(path.dirname(mirror), { recursive: true });
+ await fs.writeFile(manifest, '{"name":"@cindy/maker-core"}');
+ await fs.writeFile(source, "export const value = 1;");
+ await fs.link(source, mirror);
+
+ const grants = await buildReviewReadGrants(workspace, [
+ packageRoot,
+ source,
+ ]);
+ expect(await resolveReviewReadPath(source, workspace, grants)).toBe(
+ await fs.realpath(source),
+ );
+
+ const outsideManifest = path.join(root, "outside-package.json");
+ await fs.writeFile(outsideManifest, '{"name":"@cindy/maker-core"}');
+ await fs.unlink(manifest);
+ await fs.symlink(outsideManifest, manifest);
+ expect(await resolveReviewReadPath(source, workspace, grants)).toBeNull();
+ });
});
diff --git a/packages/maker-core/src/agents/shared/review-read-scope.ts b/packages/maker-core/src/agents/shared/review-read-scope.ts
index 32658c9ebf..42ed969f2e 100644
--- a/packages/maker-core/src/agents/shared/review-read-scope.ts
+++ b/packages/maker-core/src/agents/shared/review-read-scope.ts
@@ -1,4 +1,4 @@
-import { promises as fs } from "node:fs";
+import { promises as fs, type Stats } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -10,6 +10,172 @@ export interface ReviewReadGrant {
directory: boolean;
}
+function isPathWithin(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return (
+ relative === "" ||
+ (!relative.startsWith(`..${path.sep}`) &&
+ relative !== ".." &&
+ !path.isAbsolute(relative))
+ );
+}
+
+function ancestorsWithin(start: string, root: string): string[] {
+ const boundary = path.resolve(root);
+ const ancestors: string[] = [];
+ let current = path.resolve(start);
+ while (isPathWithin(boundary, current)) {
+ ancestors.push(current);
+ if (current === boundary) break;
+ const parent = path.dirname(current);
+ if (parent === current) break;
+ current = parent;
+ }
+ return ancestors;
+}
+
+function statsReferToSameFile(left: Stats, right: Stats): boolean {
+ return left.ino !== 0 && left.dev === right.dev && left.ino === right.ino;
+}
+
+const PACKAGE_MANIFEST_MAX_BYTES = 256 * 1024;
+
+function normalizeDeclaredPackageName(value: unknown): string | null {
+ if (
+ typeof value !== "string" ||
+ value.length === 0 ||
+ value.length > 214 ||
+ value !== value.trim()
+ ) {
+ return null;
+ }
+ const component = "[a-z0-9][a-z0-9._-]*";
+ const pattern = value.startsWith("@")
+ ? new RegExp(`^@${component}/${component}$`, "i")
+ : new RegExp(`^${component}$`, "i");
+ return pattern.test(value) ? value : null;
+}
+
+async function readDeclaredPackageName(
+ packageRoot: string,
+ confinementRoot: string,
+): Promise<string | null> {
+ const manifestPath = path.join(packageRoot, "package.json");
+ if (!isPathWithin(confinementRoot, manifestPath)) return null;
+ const manifestLstat = await fs.lstat(manifestPath).catch(() => null);
+ if (
+ !manifestLstat ||
+ manifestLstat.isSymbolicLink() ||
+ !manifestLstat.isFile() ||
+ manifestLstat.size > PACKAGE_MANIFEST_MAX_BYTES
+ ) {
+ return null;
+ }
+ const realManifest = await fs.realpath(manifestPath).catch(() => null);
+ if (!realManifest || !isPathWithin(confinementRoot, realManifest)) return null;
+ const manifestStat = await fs.stat(realManifest).catch(() => null);
+ if (
+ !manifestStat ||
+ !manifestStat.isFile() ||
+ manifestStat.size > PACKAGE_MANIFEST_MAX_BYTES
+ ) {
+ return null;
+ }
+ const raw = await fs.readFile(realManifest, "utf8").catch(() => null);
+ if (raw == null || Buffer.byteLength(raw, "utf8") > PACKAGE_MANIFEST_MAX_BYTES) {
+ return null;
+ }
+ try {
+ return normalizeDeclaredPackageName(
+ (JSON.parse(raw) as { name?: unknown }).name,
+ );
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * pnpm mirrors local file packages into node_modules with hard links. A file
+ * with exactly one denied mirror inside the same granted workspace cannot be
+ * an alias for an outside inode: both filesystem links are accounted for.
+ */
+export async function reviewFileLinkLayoutIsSafe(
+ realPath: string,
+ confinementRoot: string,
+ stat: Stats,
+): Promise<boolean> {
+ if (!stat.isFile()) return stat.isDirectory();
+ if (stat.nlink <= 1) return true;
+ if (stat.nlink !== 2 || !isPathWithin(confinementRoot, realPath)) {
+ return false;
+ }
+
+ const candidates = new Set<string>();
+ for (const packageRoot of ancestorsWithin(
+ path.dirname(realPath),
+ confinementRoot,
+ )) {
+ const packageBase = path.basename(packageRoot);
+ if (
+ !packageBase ||
+ packageBase === path.sep ||
+ packageBase === "node_modules"
+ )
+ continue;
+ const packageNames = [packageBase];
+ const declaredPackageName = await readDeclaredPackageName(
+ packageRoot,
+ confinementRoot,
+ );
+ if (declaredPackageName) packageNames.push(declaredPackageName);
+ const scope = path.basename(path.dirname(packageRoot));
+ if (scope.startsWith("@") && scope.length > 1)
+ packageNames.push(path.join(scope, packageBase));
+ const relativePath = path.relative(packageRoot, realPath);
+ if (
+ !relativePath ||
+ relativePath.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(relativePath)
+ ) {
+ continue;
+ }
+ for (const dependencyRoot of ancestorsWithin(
+ path.dirname(packageRoot),
+ confinementRoot,
+ )) {
+ for (const packageName of packageNames) {
+ candidates.add(
+ path.join(dependencyRoot, "node_modules", packageName, relativePath),
+ );
+ }
+ }
+ }
+
+ for (const candidate of candidates) {
+ if (!isReviewSensitiveCredentialPath(candidate)) continue;
+ const candidateStat = await fs.lstat(candidate).catch(() => null);
+ if (
+ !candidateStat ||
+ candidateStat.isSymbolicLink() ||
+ !candidateStat.isFile() ||
+ candidateStat.nlink !== 2 ||
+ !statsReferToSameFile(stat, candidateStat)
+ ) {
+ continue;
+ }
+ const realCandidate = await fs.realpath(candidate).catch(() => null);
+ if (
+ realCandidate &&
+ path.resolve(realCandidate) !== path.resolve(realPath) &&
+ isPathWithin(confinementRoot, realCandidate) &&
+ isReviewSensitiveCredentialPath(realCandidate)
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
function normalizeReviewPath(
rawPath: string,
workingDir: string,
@@ -37,13 +203,7 @@ export function pathIsWithinReviewGrant(
grant: ReviewReadGrant,
): boolean {
if (!grant.directory) return candidate === grant.realPath;
- const relative = path.relative(grant.realPath, candidate);
- return (
- relative === "" ||
- (!relative.startsWith(`..${path.sep}`) &&
- relative !== ".." &&
- !path.isAbsolute(relative))
- );
+ return isPathWithin(grant.realPath, candidate);
}
export async function buildReviewReadGrants(
@@ -69,7 +229,20 @@ export async function buildReviewReadGrants(
throw new Error("Review paths must refer to files or directories");
}
if (stat.isFile() && stat.nlink > 1) {
- throw new Error("Review refused a multiply linked local file");
+ let safeWithinDirectoryGrant = false;
+ for (const grant of grants) {
+ if (
+ grant.directory &&
+ pathIsWithinReviewGrant(realPath, grant) &&
+ (await reviewFileLinkLayoutIsSafe(realPath, grant.realPath, stat))
+ ) {
+ safeWithinDirectoryGrant = true;
+ break;
+ }
+ }
+ if (!safeWithinDirectoryGrant) {
+ throw new Error("Review refused a multiply linked local file");
+ }
}
if (!grants.some((grant) => grant.realPath === realPath)) {
grants.push({ realPath, directory: stat.isDirectory() });
@@ -99,16 +272,25 @@ export async function resolveReviewReadPath(
}
if (isReviewSensitiveCredentialPath(realPath)) return null;
const stat = await fs.stat(realPath).catch(() => null);
- if (
- !stat ||
- (!stat.isDirectory() && !stat.isFile()) ||
- (stat.isFile() && stat.nlink > 1)
- ) {
+ if (!stat || (!stat.isDirectory() && !stat.isFile())) {
+ return null;
+ }
+ const matchingGrants = grants.filter((grant) =>
+ pathIsWithinReviewGrant(realPath, grant),
+ );
+ if (matchingGrants.length === 0) return null;
+ if (stat.isFile() && stat.nlink > 1) {
+ for (const grant of matchingGrants) {
+ if (
+ grant.directory &&
+ (await reviewFileLinkLayoutIsSafe(realPath, grant.realPath, stat))
+ ) {
+ return realPath;
+ }
+ }
return null;
}
- return grants.some((grant) => pathIsWithinReviewGrant(realPath, grant))
- ? realPath
- : null;
+ return realPath;
}
/**
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.ts
index e0a647ce21..86a33ebe08 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
@@ -37,6 +37,25 @@ describe("Review credential path policy", () => {
).toBe(false);
});
+ it("keeps managed harness binaries and local build caches outside Review", () => {
+ for (const denied of [
+ "/repo/apps/claude-code-bin/darwin-arm64/claude",
+ "/repo/apps/codex-bin/win32-x64/codex.exe",
+ "/repo/apps/pi-bin/linux-x64/pi",
+ "/repo/apps/ripgrep-bin/darwin-arm64/rg",
+ "/repo/tools/pi/updates/0.83.0/darwin-arm64/pi",
+ "/repo/apps/desktop/.vite/build/main.js",
+ ]) {
+ expect(isReviewSensitiveCredentialPath(denied)).toBe(true);
+ }
+ expect(
+ isReviewSensitiveCredentialPath("/repo/src/codex-binary-format.ts"),
+ ).toBe(false);
+ expect(
+ isReviewSensitiveCredentialPath("/repo/packages/codex-bin/source.ts"),
+ ).toBe(false);
+ });
+
it("recognizes credentials hidden behind file selector syntax", () => {
for (const selector of [
"**/*.pem",
@@ -57,6 +76,9 @@ describe("Review credential path policy", () => {
"**/.env.*",
"**/.git/**",
"**/node_modules/**",
+ "**/apps/codex-bin/**",
+ "**/tools/pi/updates/**",
+ "**/.vite/**",
"**/credentials.json",
"**/auth.json",
"**/*.pem",
diff --git a/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts b/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts
index 835b1947c3..8d00623bf9 100644
--- a/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts
+++ b/packages/maker-core/src/agents/shared/sensitive-credential-paths.ts
@@ -52,6 +52,19 @@ export const REVIEW_SENSITIVE_CREDENTIAL_PATH_PATTERN_SPECS = [
// the Review read scope also keeps the full-workspace freshness fingerprint
// bounded without leaving readable ignored content outside that baseline.
{ source: String.raw`(?:^|[\\/])node_modules(?:[\\/]|$)`, flags: "i" },
+ // Cindy's managed harness binaries and local build cache are executable
+ // runtime inputs, not reviewable source artifacts. A real Cindy worktree is
+ // larger than the bounded content fingerprint if these generated payloads
+ // remain readable, so every harness excludes the same paths.
+ {
+ source: String.raw`(?:^|[\\/])apps[\\/](?:claude-code|codex|pi|ripgrep)-bin(?:[\\/]|$)`,
+ flags: "i",
+ },
+ {
+ source: String.raw`(?:^|[\\/])tools[\\/]pi[\\/]updates(?:[\\/]|$)`,
+ flags: "i",
+ },
+ { source: String.raw`(?:^|[\\/])\.vite(?:[\\/]|$)`, flags: "i" },
] as const;
/**
@@ -68,6 +81,12 @@ export const REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS = [
"**/.git/**",
"**/node_modules",
"**/node_modules/**",
+ "**/apps/claude-code-bin/**",
+ "**/apps/codex-bin/**",
+ "**/apps/pi-bin/**",
+ "**/apps/ripgrep-bin/**",
+ "**/tools/pi/updates/**",
+ "**/.vite/**",
"**/.ssh/**",
"**/.aws/**",
"**/.gnupg/**",
diff --git a/packages/maker-core/src/index.ts b/packages/maker-core/src/index.ts
index 3044bc739c..e02a2f0788 100644
--- a/packages/maker-core/src/index.ts
+++ b/packages/maker-core/src/index.ts
@@ -20,6 +20,7 @@ export {
assertReviewMessageContentPaths,
buildReviewReadGrants,
pathIsWithinReviewGrant,
+ reviewFileLinkLayoutIsSafe,
resolveReviewReadPath,
type ReviewReadGrant,
} from './agents/shared/review-read-scope.js';