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): enforce scheduler and file isolation

Chriscea026ee3153
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactAuthorization.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactAuthorization.test.ts
index 808792e9c0..34d6c95bee 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactAuthorization.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactAuthorization.test.ts
@@ -46,6 +46,27 @@ describe('authorizeReviewExplicitArtifacts', () => {
expect(confirm).not.toHaveBeenCalled();
});
+ it('rejects a pre-existing hard-linked artifact before confirmation', async () => {
+ if (process.platform === 'win32') return;
+ const workingDir = await tempDir();
+ const externalDir = await tempDir();
+ const outside = path.join(externalDir, 'outside-secret.txt');
+ const linked = path.join(externalDir, 'linked.txt');
+ await fs.writeFile(outside, 'sensitive bytes');
+ await fs.link(outside, linked);
+ const confirm = vi.fn(async () => true);
+
+ await expect(
+ authorizeReviewExplicitArtifacts({
+ workingDir,
+ attachments: [{ name: 'linked.txt', path: linked }],
+ resolvePath: async () => ({ absPath: linked, managed: false }),
+ confirm,
+ }),
+ ).rejects.toThrow(/multiply linked/i);
+ expect(confirm).not.toHaveBeenCalled();
+ });
+
it('requires a one-run confirmation for external paths and rejects cancellation', async () => {
const workingDir = await tempDir();
const externalDir = await tempDir();
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactContent.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactContent.test.ts
index 5614515d21..e0e63dc3b2 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactContent.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactContent.test.ts
@@ -219,4 +219,25 @@ describe('extractReviewArtifactContent', () => {
expect(result.warnings[0]?.message).toContain('大于 20 MB');
await expect(fs.stat(renamed)).resolves.toBeDefined();
});
+
+ it('does not extract content from a pre-existing hard-linked file', async () => {
+ if (process.platform === 'win32') return;
+ const dir = await tempDir();
+ const outside = path.join(dir, 'outside-secret.md');
+ const linked = path.join(dir, 'linked.md');
+ await fs.writeFile(outside, 'sensitive bytes');
+ await fs.link(outside, linked);
+
+ const result = await extractReviewArtifactContent({
+ label: 'linked.md',
+ category: 'text',
+ filePath: linked,
+ maxChars: 24_000,
+ });
+
+ expect(result.excerpt).toBeNull();
+ expect(result.warnings.map((item) => item.message).join('\n')).toContain(
+ 'multiply linked artifact file',
+ );
+ });
});
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
index 5063e28179..97ff754a89 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
@@ -197,6 +197,21 @@ describe('review artifact fingerprint', () => {
expect(openFile).not.toHaveBeenCalled();
});
+ it('rejects a hard link that already exists inside the artifact workspace', async () => {
+ if (process.platform === 'win32') return;
+ const root = await makeTempDir();
+ const workspace = path.join(root, 'workspace');
+ const outside = path.join(root, 'outside-secret.txt');
+ const linked = path.join(workspace, 'linked.txt');
+ await fs.mkdir(workspace);
+ await fs.writeFile(outside, 'sensitive bytes');
+ await fs.link(outside, linked);
+
+ await expect(fingerprintReviewArtifacts([workspace])).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 3b7a9c00dd..a524ec585e 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts
@@ -148,6 +148,24 @@ describe('materializeReviewArtifactSnapshots', () => {
).rejects.toBeInstanceOf(ReviewArtifactAuthorizationError);
});
+ it('rejects a hard link that already exists when snapshotting starts', async () => {
+ if (process.platform === 'win32') return;
+ const workingDir = await tempDir();
+ const externalDir = await tempDir();
+ const outside = path.join(externalDir, 'outside-secret.txt');
+ const linked = path.join(externalDir, 'linked.txt');
+ await fs.writeFile(outside, 'sensitive bytes');
+ await fs.link(outside, linked);
+
+ await expect(
+ materializeReviewArtifactSnapshots({
+ workingDir,
+ grant: await grantFor([linked]),
+ owner: TEST_OWNER,
+ }),
+ ).rejects.toThrow(/multiply linked/i);
+ });
+
it('rejects an atomic replacement after the original path was authorized', async () => {
const workingDir = await tempDir();
const externalDir = await tempDir();
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts b/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts
index e50d4b72f7..35042bf178 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactAuthorization.ts
@@ -135,6 +135,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',
+ );
+ }
const existingIdentity = pathIdentities.get(resolved.absPath);
if (existingIdentity && !reviewArtifactPathIdentityMatches(existingIdentity, stat)) {
throw new ReviewArtifactAuthorizationError(
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactContent.ts b/apps/desktop/src/main/reviewer/reviewArtifactContent.ts
index b08224add7..7124a071a7 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactContent.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactContent.ts
@@ -148,6 +148,7 @@ async function readPathBounded(
// path between the size check and the unbounded read.
const stat = await handle.stat();
if (!stat.isFile()) throw new Error('not a regular file');
+ if (stat.nlink > 1) throw new Error('multiply linked artifact file');
if (options.rejectOversize && stat.size > limit) {
throw new ReviewArtifactTooLargeError(`artifact exceeds ${limit} bytes`);
}
@@ -160,7 +161,11 @@ async function readPathBounded(
bytesRead += chunk.bytesRead;
}
const finalStat = await handle.stat();
- if (finalStat.size !== stat.size || finalStat.mtimeMs !== stat.mtimeMs) {
+ if (
+ finalStat.nlink > 1 ||
+ finalStat.size !== stat.size ||
+ finalStat.mtimeMs !== stat.mtimeMs
+ ) {
throw new Error('file changed while it was being read');
}
return {
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
index 5d53a2e88d..04e44d7708 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
@@ -110,6 +110,11 @@ async function addFile(
stat: Stats,
state: FingerprintState,
): Promise<void> {
+ if (stat.nlink > 1) {
+ throw new ReviewArtifactFingerprintChangedError(
+ 'Review refused a multiply linked file in its artifact workspace',
+ );
+ }
if (
!Number.isSafeInteger(stat.size) ||
stat.size < 0 ||
@@ -128,7 +133,11 @@ async function addFile(
try {
handle = await state.openFile(absolutePath, constants.O_RDONLY | NOFOLLOW_FLAG);
const opened = await handle.stat();
- if (!opened.isFile() || !reviewArtifactPathIdentityMatches(stat, opened)) {
+ if (
+ !opened.isFile() ||
+ opened.nlink > 1 ||
+ !reviewArtifactPathIdentityMatches(stat, opened)
+ ) {
throw new ReviewArtifactFingerprintChangedError(
'A review artifact changed while its content fingerprint was being prepared',
);
@@ -140,8 +149,10 @@ async function addFile(
if (
bytesRead !== opened.size ||
!reviewArtifactPathIdentityMatches(opened, afterHandle) ||
+ afterHandle.nlink > 1 ||
!afterPath ||
afterPath.isSymbolicLink() ||
+ afterPath.nlink > 1 ||
!reviewArtifactPathIdentityMatches(opened, afterPath)
) {
throw new ReviewArtifactFingerprintChangedError(
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts b/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
index 497cec0255..375bba7ebe 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
@@ -286,6 +286,11 @@ 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 (before.size > MAX_SNAPSHOT_FILE_BYTES) {
throw new ReviewArtifactAuthorizationError(
'A review artifact is larger than the 64 MB local snapshot limit',
@@ -315,8 +320,10 @@ async function copyOpenFile(
if (
sourceOffset !== before.size ||
!reviewArtifactSnapshotStatMatches(before, after) ||
+ after.nlink > 1 ||
!afterPath ||
afterPath.isSymbolicLink() ||
+ afterPath.nlink > 1 ||
!reviewArtifactPathIdentityMatches(expectedIdentity, afterPath)
) {
throw new ReviewArtifactAuthorizationError(
@@ -409,6 +416,11 @@ export async function materializeReviewArtifactSnapshots(input: {
if (!entry.isFile()) {
throw new ReviewArtifactAuthorizationError('Review only snapshots regular files');
}
+ if (entry.nlink > 1) {
+ throw new ReviewArtifactAuthorizationError(
+ 'Review refused a multiply linked artifact file',
+ );
+ }
if (!snapshotRoot) {
snapshotRoot = await fs.mkdtemp(
diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.ts
index ee4e6986c5..f9206be645 100644
--- a/apps/desktop/src/main/scheduler-host/index.ts
+++ b/apps/desktop/src/main/scheduler-host/index.ts
@@ -15,6 +15,7 @@ import { randomUUID } from 'node:crypto';
import { app } from 'electron';
import type { BrowserWindow } from 'electron';
+import { eq } from 'drizzle-orm';
import { Scheduler } from '@cindy/maker-scheduler';
import type { Logger, ScheduleRunner } from '@cindy/maker-scheduler';
@@ -22,6 +23,8 @@ import type { Maker } from '@cindy/maker-core';
import type { FeishuIM } from '@cindy/im';
import { dialogueWorkspaceRootDir } from '../localDb/dialogueWorkspace';
+import { sessions } from '../localDb/schema.js';
+import { isReviewSessionSource } from '../../shared/sessionSource.js';
import {
resolveDefaultScheduleRoute,
resolveRouteCopyCapabilities,
@@ -147,6 +150,20 @@ export async function startScheduler(deps: StartSchedulerDeps): Promise<Schedule
const rel = path.relative(dialogueWorkspaceRootDir(), dir);
return !rel.startsWith('..') && !path.isAbsolute(rel);
},
+ // Review sessions are host-owned read-only tasks, not normal unattended
+ // automation targets. Re-read their durable source for CRUD and every fire
+ // so renderer filtering or a restored schedule row cannot bypass isolation.
+ validateTargetSession: async (targetSessionId) => {
+ const [row] = await deps
+ .getDb()
+ .select({ source: sessions.source })
+ .from(sessions)
+ .where(eq(sessions.id, targetSessionId))
+ .limit(1);
+ if (isReviewSessionSource(row?.source)) {
+ throw new Error('Review tasks cannot be targets of scheduled automations');
+ }
+ },
// 卡死收口的通知出口。通知投递平时住在两个 runner 里(它们各自持 notifier),而
// 卡死收口刻意绕过 runner —— 要么它压根不返回、要么它把守卫 abort 当普通中断处理。
// 没有这条线,用户配了桌面/飞书通知也只会看到一个未读红点(PR #944 review P1)。
diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx
index d5f35dd691..3de8e092e6 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx
@@ -48,6 +48,7 @@ import {
usesBoundSessionModel,
} from '../lib/scheduleFormLogic';
import type { SessionReference } from '../../../../shared/sessionReference';
+import { isReviewSessionSource } from '../../../../shared/sessionSource';
export type Destination = 'local' | 'worktree' | 'thread';
export type AgentKind = 'claude-code' | 'codex' | 'pi';
@@ -1278,7 +1279,7 @@ export function ThreadPickerInline({ value, onSelect, onOpen, reference }: {
.list(50, 'active')
.then((list) => {
if (!alive) return;
- setSessions(list);
+ setSessions(list.filter((session) => !isReviewSessionSource(session.source)));
setError(null);
})
.catch((e: unknown) => {
diff --git a/apps/desktop/src/renderer/features/scheduler/components/__tests__/ThreadPickerInline.test.tsx b/apps/desktop/src/renderer/features/scheduler/components/__tests__/ThreadPickerInline.test.tsx
index f5e94df815..c28db947f0 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/__tests__/ThreadPickerInline.test.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/__tests__/ThreadPickerInline.test.tsx
@@ -4,7 +4,15 @@ import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
- list: vi.fn(async () => []),
+ list: vi.fn(
+ async () =>
+ [] as Array<{
+ id: string;
+ title: string;
+ agentKind: 'cc' | 'codex' | 'pi';
+ source?: string;
+ }>,
+ ),
}));
vi.mock('@/lib/sessionService', () => ({ list: mocks.list }));
@@ -20,6 +28,18 @@ afterEach(() => {
});
describe('ThreadPickerInline 会话引用状态', () => {
+ it('does not offer Review tasks as scheduler targets', async () => {
+ mocks.list.mockResolvedValueOnce([
+ { id: 'session-review', title: 'Review task', agentKind: 'codex', source: 'review' },
+ { id: 'session-normal', title: 'Desktop task', agentKind: 'codex', source: 'desktop' },
+ ]);
+
+ render(<ThreadPickerInline value="" onSelect={vi.fn()} />);
+
+ expect(await screen.findByRole('option', { name: 'Desktop task · Codex' })).toBeDefined();
+ expect(screen.queryByRole('option', { name: 'Review task · Codex' })).toBeNull();
+ });
+
it('普通绑定会话被删除后要求重新选择且不再显示打开入口', async () => {
render(
<ThreadPickerInline
diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.ts
index c074ac3f81..5c7300bfa8 100644
--- a/apps/desktop/src/shared/sessionSource.ts
+++ b/apps/desktop/src/shared/sessionSource.ts
@@ -17,6 +17,10 @@ export const SESSION_SOURCES = [
export type SessionSource = (typeof SESSION_SOURCES)[number];
+export function isReviewSessionSource(source: unknown): source is 'review' {
+ return source === 'review';
+}
+
// desktop sidebar 展示的会话 source 白名单。
// slack: IM 渠道自动建的会话——用户在 Slack 发消息后 desktop 同步可见。
// telegram: 共享 Cindy Telegram bot 派发并在本机执行的会话。
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 5d7a72fea3..c467008b47 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -157,13 +157,12 @@ import type { McpProviderContext } from '../../interfaces/mcp-provider.js';
import { scanClaudeCustomizations } from './customization-scanner.js';
import {
REVIEW_SENSITIVE_CREDENTIAL_GLOB_PATTERNS,
- isReviewSensitiveCredentialPath,
isReviewSensitiveCredentialSelector,
} from '../shared/sensitive-credential-paths.js';
import {
assertReviewMessageContentPaths,
buildReviewReadGrants,
- pathIsWithinReviewGrant,
+ resolveReviewReadPath,
type ReviewReadGrant,
} from '../shared/review-read-scope.js';
@@ -331,15 +330,7 @@ async function reviewReadToolIsInScope(params: {
typeof raw === 'string' && raw.trim()
? path.resolve(params.workingDir, raw)
: params.workingDir;
- if (isReviewSensitiveCredentialPath(candidate)) return false;
- let realPath: string;
- try {
- realPath = await fs.realpath(candidate);
- } catch {
- return false;
- }
- if (isReviewSensitiveCredentialPath(realPath)) return false;
- return params.grants.some((grant) => pathIsWithinReviewGrant(realPath, grant));
+ return (await resolveReviewReadPath(candidate, params.workingDir, params.grants)) !== null;
}
/**
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 c6e6537bb1..5230bd47e5 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@ -76,6 +76,8 @@ describe('cindy-bridge extension source', () => {
expect(source).toContain(
'stat.isDirectory() ? isInsideRoot(target, allowed) : target === allowed',
);
+ expect(source).toContain('targetStat.isFile() && targetStat.nlink > 1');
+ expect(source).toContain('reviewSearchPathHasMultipleLinks');
expect(source).toContain('REVIEW_CREDENTIAL_PATH_PATTERNS.some');
expect(source).toContain('REVIEW_CREDENTIAL_GLOB_PATTERNS.some');
});
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 2f2cd6c4b6..c9c6b897cd 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -182,10 +182,13 @@ function reviewReadIsAllowed(candidate: string, allowedPaths: string[]): boolean
if (REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(requested))) return false;
const target = realpathSync(requested);
if (REVIEW_CREDENTIAL_PATH_PATTERNS.some((re) => re.test(target))) return false;
+ const targetStat = statSync(target);
+ if (targetStat.isFile() && targetStat.nlink > 1) return false;
return 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;
} catch {
return false;
@@ -322,6 +325,16 @@ function reviewSearchPathTouchesCredential(candidate: string, baseDir = process.
}
}
+function reviewSearchPathHasMultipleLinks(candidate: string, baseDir = process.cwd()): boolean {
+ try {
+ const target = realpathSync(path.resolve(baseDir, candidate));
+ const stat = statSync(target);
+ return stat.isFile() && stat.nlink > 1;
+ } catch {
+ return true;
+ }
+}
+
function reviewGrepOutputPath(line: string): string | null {
const match = /^(.*?)(?::\d+:|-\d+-)/.exec(line);
return match?.[1] ?? null;
@@ -350,6 +363,7 @@ function filterReviewGrepResult(result: any, input: unknown): any {
const candidate = reviewGrepOutputPath(line);
if (!candidate) return true;
if (reviewSearchPathTouchesCredential(candidate, resultBase)) return false;
+ if (reviewSearchPathHasMultipleLinks(candidate, resultBase)) return false;
visibleMatch = true;
return true;
});
@@ -700,6 +714,7 @@ function rgGlob(
if (!line || lines.length >= limit) return;
const relative = line.replace(/\r$/, '');
if (reviewOnly && reviewSearchPathTouchesCredential(relative, cwd)) return;
+ if (reviewOnly && reviewSearchPathHasMultipleLinks(relative, cwd)) return;
// 完整镜像 Pi 上游 fd 规则:无 slash 时匹配 basename;有 slash 时启用
// full-path,且相对 pattern 自动加 **/,让 src/** 同时命中 monorepo 子包。
let candidate = path.basename(relative);
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 59e7a8c81a..778a7444b3 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
@@ -95,4 +95,28 @@ describe("review read scope", () => {
).toBeNull();
expect(await resolveReviewReadPath(keyLink, workspace, grants)).toBeNull();
});
+
+ it("rejects pre-existing hard links in workspace and explicit file grants", async () => {
+ if (process.platform === "win32") return;
+ const root = await makeTempDir();
+ const workspace = path.join(root, "workspace");
+ const outside = path.join(root, "outside-secret.txt");
+ const linked = path.join(workspace, "linked.txt");
+ await fs.mkdir(workspace);
+ await fs.writeFile(outside, "sensitive bytes");
+ await fs.link(outside, linked);
+
+ const grants = await buildReviewReadGrants(workspace, []);
+ expect(await resolveReviewReadPath(linked, workspace, grants)).toBeNull();
+ await expect(buildReviewReadGrants(workspace, [outside])).rejects.toThrow(
+ /multiply linked/i,
+ );
+ await expect(
+ assertReviewMessageContentPaths(
+ [{ type: "image", path: linked, mimeType: "image/png" }],
+ workspace,
+ grants,
+ ),
+ ).rejects.toThrow(/refused/i);
+ });
});
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 73a2049481..32658c9ebf 100644
--- a/packages/maker-core/src/agents/shared/review-read-scope.ts
+++ b/packages/maker-core/src/agents/shared/review-read-scope.ts
@@ -68,6 +68,9 @@ export async function buildReviewReadGrants(
if (!stat.isDirectory() && !stat.isFile()) {
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");
+ }
if (!grants.some((grant) => grant.realPath === realPath)) {
grants.push({ realPath, directory: stat.isDirectory() });
}
@@ -95,6 +98,14 @@ export async function resolveReviewReadPath(
return null;
}
if (isReviewSensitiveCredentialPath(realPath)) return null;
+ const stat = await fs.stat(realPath).catch(() => null);
+ if (
+ !stat ||
+ (!stat.isDirectory() && !stat.isFile()) ||
+ (stat.isFile() && stat.nlink > 1)
+ ) {
+ return null;
+ }
return grants.some((grant) => pathIsWithinReviewGrant(realPath, grant))
? realPath
: null;
diff --git a/packages/maker-scheduler/src/__tests__/scheduler.test.ts b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
index a030222643..d832e0ef15 100644
--- a/packages/maker-scheduler/src/__tests__/scheduler.test.ts
+++ b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
@@ -160,6 +160,10 @@ interface Harness {
function makeHarness(opts?: {
runnerImpl?: (s: Schedule, ctx: FireContext) => Promise<FireResult>;
isManagedWorkspaceDir?: (dir: string) => boolean;
+ validateTargetSession?: (
+ targetSessionId: string,
+ operation: 'create' | 'update' | 'fire',
+ ) => Promise<void>;
/** 传入共享 storage / clock 模拟"两个 app 实例共用同一 DB"的双开场景。 */
storage?: InMemoryStorage;
clock?: FakeClock;
@@ -191,6 +195,7 @@ function makeHarness(opts?: {
generateId: opts?.generateId ?? makeIdGen(),
tickIntervalMs: 60_000_000, // effectively disabled; tests call tick() manually
isManagedWorkspaceDir: opts?.isManagedWorkspaceDir,
+ validateTargetSession: opts?.validateTargetSession,
passive: opts?.passive,
maxConcurrentRuns: opts?.maxConcurrentRuns,
runStallMs: opts?.runStallMs,
@@ -260,6 +265,75 @@ describe('Scheduler', () => {
expect(blankDir.workspaceKind).toBe('dialogue');
});
+ it('rejects persisted Review targets at create, update, automatic fire, and runNow after restart', async () => {
+ const sourceBySessionId = new Map<string, string>([
+ ['session-normal', 'desktop'],
+ ['session-review', 'review'],
+ ]);
+ const operations: Array<{ targetSessionId: string; operation: string }> = [];
+ const validateTargetSession = async (
+ targetSessionId: string,
+ operation: 'create' | 'update' | 'fire',
+ ): Promise<void> => {
+ operations.push({ targetSessionId, operation });
+ if (sourceBySessionId.get(targetSessionId) === 'review') {
+ throw new Error('Review tasks cannot be targets of scheduled automations');
+ }
+ };
+ const local = makeHarness({ validateTargetSession });
+
+ await expect(
+ local.scheduler.create({ ...baseInput, targetSessionId: 'session-review' }),
+ ).rejects.toThrow('Review tasks cannot be targets');
+ expect(local.storage.schedules.size).toBe(0);
+
+ const schedule = await local.scheduler.create({
+ ...baseInput,
+ targetSessionId: 'session-normal',
+ });
+ await expect(
+ local.scheduler.update(schedule.id, { targetSessionId: 'session-review' }),
+ ).rejects.toThrow('Review tasks cannot be targets');
+ expect((await local.storage.get(schedule.id))?.targetSessionId).toBe('session-normal');
+
+ // The source is durable session state, so a target that becomes a Review
+ // task after scheduling must still be rejected by a restarted host.
+ sourceBySessionId.set('session-normal', 'review');
+ const restarted = makeHarness({
+ storage: local.storage,
+ clock: local.clock,
+ validateTargetSession,
+ });
+ await restarted.scheduler.start();
+ try {
+ local.clock.setTo(Date.UTC(2026, 0, 1, 0, 1, 0));
+ await restarted.scheduler.tick();
+ expect(restarted.runner.fire).not.toHaveBeenCalled();
+ expect(await restarted.scheduler.listRuns(schedule.id)).toMatchObject([
+ {
+ status: 'failed',
+ errorMsg: 'Review tasks cannot be targets of scheduled automations',
+ },
+ ]);
+
+ await restarted.scheduler.runNow(schedule.id);
+ expect(restarted.runner.fire).not.toHaveBeenCalled();
+ const runs = await restarted.scheduler.listRuns(schedule.id);
+ expect(runs).toHaveLength(2);
+ expect(runs.every((run) => run.status === 'failed')).toBe(true);
+ } finally {
+ await restarted.scheduler.stop();
+ }
+
+ expect(operations.map((entry) => entry.operation)).toEqual([
+ 'create',
+ 'create',
+ 'update',
+ 'fire',
+ 'fire',
+ ]);
+ });
+
it('create()/update() 把 app 管理工作区目录归一成对话任务(host 注入谓词)', async () => {
const h2 = makeHarness({
isManagedWorkspaceDir: (dir) => dir.startsWith('/managed/'),
diff --git a/packages/maker-scheduler/src/engine/scheduler.ts b/packages/maker-scheduler/src/engine/scheduler.ts
index 302e36938c..dc7c5f2502 100644
--- a/packages/maker-scheduler/src/engine/scheduler.ts
+++ b/packages/maker-scheduler/src/engine/scheduler.ts
@@ -97,6 +97,15 @@ export interface SchedulerOptions {
* 命中时 create/update 会把任务归一成对话任务(清 workingDir + workspaceKind='dialogue')。
*/
isManagedWorkspaceDir?: (dir: string) => boolean;
+ /**
+ * Host-owned validation for a persisted bound-session target. The scheduler
+ * calls it before CRUD persistence and again immediately before every fire,
+ * so a row restored from an older process cannot bypass a newer host policy.
+ */
+ validateTargetSession?: (
+ targetSessionId: string,
+ operation: 'create' | 'update' | 'fire',
+ ) => Promise<void>;
/**
* 被动模式:本实例不参与自动触发 —— start() 不装 tick 时钟、不做僵尸 run 清理
* (那是活跃实例的 in-flight,不能被本实例误标 interrupted)。CRUD / runNow /
@@ -333,6 +342,7 @@ export class Scheduler extends EventEmitter {
private readonly notifyForcedFailureHook?: SchedulerOptions['notifyForcedFailure'];
private readonly isManagedWorkspaceDir?: (dir: string) => boolean;
+ private readonly validateTargetSession?: SchedulerOptions['validateTargetSession'];
private readonly passive: boolean;
private lastDbSyncAt = 0;
@@ -377,6 +387,7 @@ export class Scheduler extends EventEmitter {
this.tickIntervalMs = opts.tickIntervalMs ?? DEFAULT_TICK_MS;
this.generateId = opts.generateId ?? defaultGenerateId;
this.isManagedWorkspaceDir = opts.isManagedWorkspaceDir;
+ this.validateTargetSession = opts.validateTargetSession;
this.notifyForcedFailureHook = opts.notifyForcedFailure;
this.passive = opts.passive ?? false;
this.maxConcurrentRuns = Math.max(1, opts.maxConcurrentRuns ?? DEFAULT_MAX_CONCURRENT_RUNS);
@@ -756,6 +767,9 @@ export class Scheduler extends EventEmitter {
let skipped = false;
this.updateInflightAttempt(runId, 'running');
try {
+ if (schedule.targetSessionId) {
+ await this.validateTargetSession?.(schedule.targetSessionId, 'fire');
+ }
const result = await this.runner.fire(schedule, {
runId,
firedAt,
@@ -1053,6 +1067,9 @@ export class Scheduler extends EventEmitter {
let skipped = false;
this.updateInflightAttempt(runId, 'running');
try {
+ if (schedule.targetSessionId) {
+ await this.validateTargetSession?.(schedule.targetSessionId, 'fire');
+ }
const result = await this.runner.fire(schedule, {
runId,
firedAt,
@@ -1276,6 +1293,9 @@ export class Scheduler extends EventEmitter {
nextFireAt: firstFireAt,
};
validateScheduleExecutionShape(schedule);
+ if (schedule.targetSessionId) {
+ await this.validateTargetSession?.(schedule.targetSessionId, 'create');
+ }
const inserted = await this.storage.insert(schedule);
this.activeSchedules.set(id, inserted);
this.emitEvent({ type: 'changed', scheduleId: id });
@@ -1335,6 +1355,9 @@ export class Scheduler extends EventEmitter {
Object.prototype.hasOwnProperty.call(patch, 'prompt'),
},
);
+ if (candidate.targetSessionId) {
+ await this.validateTargetSession?.(candidate.targetSessionId, 'update');
+ }
// expired 是一次性任务已消费的终态。编辑后的配置若已经表达为“循环且非手动”,
// 继续保留 expired 会让持久化状态与排期语义冲突:即使算出了 nextFireAt,任务也
// 不会进入 activeSchedules,重启后 listActive() 同样加载不到。状态恢复集中在引擎