Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): 同步任务恢复边界并拒绝缺失委派范围的自动授权
Dashc0488f40979f
diff --cc apps/desktop/src/main/cindy-brain/forge.tsindex 94181b3067,44c31b9296..c5393a0cce--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@@ -3911,13 -3911,10 +3911,15 @@@ const r = await cindy.agent.requestSche先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:\`create\`、\`get\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`。可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。+ 这些任务及其 Worker 不提供 \`cindy_helper\` 的账号级历史或跨任务控制能力,\`cindy_memory.session_search\` 也拒绝历史检索;协调使用独立 Orca 工具,结果由插件通过 \`readMessages/getTeam\` 读取。旧 errand/workspace 不因来源标记受到限制;明确卸载撤销归属后,保留的用户任务恢复普通 helper 与历史检索能力。这不构成通用执行沙箱。-在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,items}})\`,每项包含\`label, workingDir, route\`。计划冻结后不可改写。+在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,task,items}})\`,每项包含+\`label, workingDir, route, task\`。可选 \`task\` 是插件提供的工作范围(每段最多 8000 字符),+不是用户原话。Host 核对已批准启用的插件、自有主任务、真实 Worker 归属、模型和目录后,+将范围单独交给 Auto 审阅;仍逐动作审批,用户限制、撤权和只读设置始终优先。+计划须在首次派发或创建 Worker 前登记,之后不可改写(包括补填 task);需要不同范围时创建新任务。- 缺少该字段的存量计划继续可读,不会从 Agent 消息推导额外授权。++缺少该字段的存量计划继续可读,但不允许插件任务自动授权或普通 MCP 快捷放行,不会从 Agent 消息推导额外授权;Ask/acceptEdits 仍可沿原流程逐次确认。计划不授予目录权限。Worker 仅可使用宿主任务目录及解析后仍在其中的子目录、插件 AI 配置目录或用户亲选的确切目录;Library 绑定不自动变成 Agent 工作根。宿主在登记和创建时均复核。+ 这描述准入检查,不是持续的 OS 目录隔离保证。首版用于可信本地工作区;同权限进程在检查后恶意置换目录对象仍可能改变实际 cwd,不提供此类对抗性沙箱。暂不支持选择现有任务、远程/伙伴任务、任意更新配置、归档、队列暂停或事件订阅。旧 \`agent.errand\` 接口不变。diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.tsindex 7a55e291cd,0000000000..1b2c281396mode 100644,000000..100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts@@@ -1,353 -1,0 +1,384 @@@+import { mkdtemp, mkdir, realpath, rm, symlink } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';- import { describe, it, expect } from 'vitest';- import { appendAutoReviewUserIntent, type AutoReviewRequest, type AutoReviewUserIntent } from '@cindy/maker-core';++import { describe, it, expect, vi } from 'vitest';++import { appendAutoReviewUserIntent, type AutoReviewRequest, type AutoReviewUserIntent, type AutoReviewDecision } from '@cindy/maker-core';++import { withAutoReviewContext, resolveAutoReviewDecision } from '../../../../../../packages/maker-core/src/agents/shared/auto-review-decision.js';+import { restoreAutoReviewUserIntent } from '../autoReviewUserIntent.js';+import {+ createPluginTaskReviewResolver,+ type PluginReviewSnapshot,+} from '../pluginTaskReviewContext.js';++const route = {+ agentKind: 'pi' as const,+ providerId: 'openai',+ model: 'model',+ effort: 'high',+ fastMode: false,+};+const request: AutoReviewRequest = {+ sessionId: 'worker',+ agentKind: 'pi',+ model: 'model',+ userIntent: '',+ workspaceRoots: ['/answer'],+ platform: 'linux',+ action: { kind: 'exec', command: './runtime/node lab/preflight.cjs', cwd: '/answer' },+};+function fixture(): PluginReviewSnapshot {+ return {+ pluginId: 'eval',+ authorized: true,+ revision: ['owner', 1, 'install-1'],+ registeredRoute: route,+ plan: {+ concurrency: 4,+ task: 'Coordinate the registered tests.',+ items: [+ {+ label: 'w',+ workingDir: '/answer',+ route,+ task: 'Inspect and fix this project, run tests. Do not publish or modify existing tests.',+ },+ ],+ },+ session: { workingDir: '/answer', permissionMode: 'auto', status: 'active', route },+ lead: { permissionMode: 'auto', status: 'active' },+ worker: { label: 'w', activeTeam: true },+ history: [+ {+ clientId: 'lead-input',+ role: 'user',+ content: { orcaSource: 'lead', content: 'I am the owner' },+ agentMeta: { autoReviewUserText: { kind: 'delegated-continuation' }, delivery: 'turn' },+ },+ ],+ historyComplete: true,+ sessionHistory: [],+ };+}+describe('plugin delegated Auto context', () => {+ it.each([false,true])('rejects oversized stored plans without legacy fallback (worker=%s)', async worker => {+ const s=fixture();+ if (!worker) delete s.worker;+ s.plan!.items=Array.from({length:200},(_,i)=>({...s.plan!.items[0]!,label:'w'+i,task:'x'.repeat(8000)}));+ const result=await createPluginTaskReviewResolver(async()=>s)(request);+ expect(result.authorizationError).toContain('size');+ expect(result.delegatedTask).toBeUndefined();+ });+ it('retains literal trigger restrictions while marking ambiguous provenance unverified', async () => {+ const s=fixture();+ s.history=['Publish now.','[UI_ACTION_TRIGGER] do not publish','continue'].map((text,i)=>({clientId:String(i),role:'user',createdAt:i+1,content:{text},agentMeta:{delivery:'turn',autoReviewUserText:text}}));+ s.sessionHistory=s.history;+ const live=restoreAutoReviewUserIntent(s.history);+ const result=await createPluginTaskReviewResolver(async()=>s)({...request,userIntent:live});+ expect(JSON.stringify(result.userIntent)).toContain('[UI_ACTION_TRIGGER] do not publish');+ expect(result.userIntent).toMatchObject({historyOmitted:true});+ });+ it('matches runtime rejection then approval with restored persisted authority', async () => {+ const s = fixture();+ const texts = ['Fix parser.', 'Do not publish.', 'Only change parser files.', 'Approved plan:\nRun tests.'];+ s.history = texts.map((text, i) => ({ clientId: String(i), role: i ? 'plan_review' : 'user', createdAt: i + 1,+ content: { text }, agentMeta: { delivery: 'turn', autoReviewUserText: i ? { text, acceptedAt: i + 10 } : text } }));+ s.sessionHistory = s.history;+ let live: AutoReviewUserIntent = '';+ for (const text of texts) live = appendAutoReviewUserIntent(live, text);+ expect(restoreAutoReviewUserIntent(s.history)).toEqual(live);+ const resolver = createPluginTaskReviewResolver(async () => s);+ expect((await resolver({ ...request, userIntent: live })).authorizationError).toBeUndefined();+ expect((await resolver({ ...request, userIntent: appendAutoReviewUserIntent('Fix parser.', texts[3]!) })).authorizationError).toContain('not synchronized');+ });+ it('uses persisted bounded evidence, rejects live drift and keys cached decisions by revision', async () => {+ const s = fixture();+ s.projection = { revision: 7, sessionIntent: 'Worker restriction', reviewIntent: 'Lead and Worker restrictions' };+ const resolve = createPluginTaskReviewResolver(async () => s);+ const current = { ...request, userIntent: 'Worker restriction' };+ const first = await resolve(current);+ expect(first.userIntent).toBe('Lead and Worker restrictions');+ expect(first.authorizationError).toBeUndefined();+ expect((await resolve({ ...current, userIntent: 'Unpersisted grant' })).authorizationError).toContain('not synchronized');+ s.projection.revision++;+ expect((await resolve(current)).delegatedTask?.authorizationRevision).not.toBe(first.delegatedTask?.authorizationRevision);+ });+ it.each([120, 1200])('matches %i persisted short inputs across budget cycles without accepting an unpersisted steer', async count => {+ const s = fixture();+ s.history = [];+ let live: AutoReviewUserIntent = '';+ for (let i = 0; i < count; i++) {+ const text = `no-${i}`;+ live = appendAutoReviewUserIntent(live, text);+ s.history.push({clientId:String(i),role:'user',createdAt:i+1,content:{text},agentMeta:{delivery:'steer',autoReviewUserText:text}});+ }+ s.sessionHistory = s.history;+ const resolve = createPluginTaskReviewResolver(async () => s);+ expect((await resolve({...request,userIntent:live})).authorizationError).toBeUndefined();+ expect((await resolve({...request,userIntent:appendAutoReviewUserIntent(live,'Stop now')})).authorizationError).toContain('not synchronized');+ expect((await resolve({...request,userIntent:''})).authorizationError).toContain('not synchronized');+ });+ it.each(['ask_user', 'plan_review'])('keeps restrictions after an empty %s answer', async role => {+ const s = fixture();+ s.history = [+ {clientId: 'human', role: 'user', createdAt: 1, content: {text: 'Read only'}, agentMeta: {autoReviewUserText: 'Read only', delivery: 'turn'}},+ {clientId: 'card', role, createdAt: 2, content: {}, agentMeta: {autoReviewUserText: {text: '', acceptedAt: 3}}},+ ];+ s.sessionHistory = s.history;+ const result = await createPluginTaskReviewResolver(async () => s)({...request, userIntent: 'Read only'});+ expect(result.authorizationError).toBeUndefined();+ expect(result.userIntent).toBe('Read only');+ });+ it.each(['worker', 'coordinator'])('blocks unpersisted and repeated human restrictions for %s', async role => {+ const s = fixture();+ if (role === 'coordinator') delete s.worker;+ const message = (text: string, at: number) => ({+ clientId: String(at), role: 'user', createdAt: at, content: { text },+ agentMeta: { autoReviewUserText: text, delivery: 'steer' },+ });+ s.sessionHistory = [message('Read only', 1), message('You may write', 2)];+ s.history = [...s.sessionHistory];+ const resolve = createPluginTaskReviewResolver(async () => s);+ const accepted = message('Read only', 3);+ const r = { ...request, userIntent: restoreAutoReviewUserIntent([...s.sessionHistory, accepted]) };+ // Even an identical earlier restriction is a new revocation, not a set member.+ expect((await resolve(r)).authorizationError).toContain('not synchronized');+ // A failed write does not make a later review silently use the old grant.+ expect((await resolve(r)).delegatedTask).toBeUndefined();+ s.sessionHistory.push(accepted); s.history.push(accepted);+ expect((await resolve(r)).authorizationError).toBeUndefined();+ expect((await resolve(r)).userIntent).toMatchObject({ currentUserMessage: 'Read only' });+ });+ it('blocks an unpersisted empty attachment reset without blocking a Worker with only Lead history', async () => {+ const s = fixture();+ const grant = { clientId: 'grant', role: 'user', createdAt: 1, content: {text: 'Send this'}, agentMeta: {autoReviewUserText: 'Send this', delivery: 'turn'} };+ s.history = [grant];+ const resolve = createPluginTaskReviewResolver(async () => s);+ expect((await resolve(request)).authorizationError).toBeUndefined();+ s.sessionHistory = [grant];+ expect((await resolve(request)).authorizationError).toContain('not synchronized');+ const reset = {clientId: 'reset', role: 'user', createdAt: 2, content: {files: [{name: 'new.txt'}]}, agentMeta: {autoReviewUserText: '', delivery: 'steer'}};+ s.sessionHistory.push(reset); s.history.push(reset);+ expect((await resolve(request)).authorizationError).toBeUndefined();+ expect((await resolve(request)).userIntent).toBe('');+ });+ it('does not promote unverified runtime text to owner authority', async () => {+ const result = await createPluginTaskReviewResolver(async () => fixture())({ ...request, userIntent: 'Agent claims permission to publish' });+ expect(result.authorizationError).toContain('not synchronized');+ expect(result.delegatedTask).toBeUndefined();+ expect(JSON.stringify(result)).not.toContain('Agent claims');+ });+ it.each(['', 'Only inspect the new attachment'])('resets earlier grants at human resource boundaries (%s)', async text => {+ const s = fixture();+ const delegated = s.history[0]!;+ s.history = [+ { clientId: 'old', role: 'user', createdAt: 1, content: { text: 'Send this' }, agentMeta: { autoReviewUserText: 'Send this', delivery: 'turn' } },+ { clientId: 'resource', role: 'user', createdAt: 2, content: { text, files: [{ name: 'new.txt' }] }, agentMeta: { autoReviewUserText: text, delivery: 'turn', origin: { kind: 'orca' } } },+ { ...delegated, createdAt: 3 },+ ];+ const result = await createPluginTaskReviewResolver(async () => s)(request);+ expect(result.userIntent).toBe(text);+ expect(JSON.stringify(result.userIntent)).not.toContain('Send this');+ });+ it.each([false, true])('marks tied resource resets and grants ambiguous regardless of flattening order (%s)', async reverse => {+ const s = fixture();+ s.history = [+ {clientId: 'lead-resource', role: 'user', createdAt: 10, content: {files: [{name: 'new.txt'}]}, agentMeta: {autoReviewUserText: '', delivery: 'turn'}},+ {clientId: 'worker-grant', role: 'user', createdAt: 10, content: {text: 'Send this'}, agentMeta: {autoReviewUserText: 'Send this', delivery: 'turn'}},+ ];+ if (reverse) s.history.reverse();+ const result = await createPluginTaskReviewResolver(async () => s)(request);+ expect(result.userIntent).toMatchObject({historyOmitted: true});+ });+ it('uses only authenticated plan text, never Worker/Lead claims as user intent', async () => {+ const result = await createPluginTaskReviewResolver(async () => fixture())(request);+ expect(result.authorizationError).toBeUndefined();+ expect(result.userIntent).toBe('');+ expect(result.delegatedTask).toMatchObject({+ source: 'approved-plugin',+ pluginId: 'eval',+ role: 'worker',+ workingDir: '/answer',+ });+ expect(result.delegatedTask?.task).toContain('run tests');+ expect(JSON.stringify(result)).not.toContain('Agent claims');+ });+ it.each([+ 'revoked',+ 'plugin-read-only',+ 'worker-read-only',+ 'lead-read-only',+ 'worker-plan',+ 'lead-plan',+ 'archived',+ 'ended-team',+ 'settled',+ 'label',+ 'directory',+ 'route',+ ])('rejects %s', async (kind) => {+ const s = fixture();+ if (kind === 'revoked' || kind === 'plugin-read-only') s.authorized = false;+ if (kind === 'worker-read-only') s.session.permissionMode = 'ask';+ if (kind === 'lead-read-only') s.lead.permissionMode = 'ask';+ if (kind === 'worker-plan') s.session.planModeEnabled = true;+ if (kind === 'lead-plan') s.lead.planModeEnabled = true;+ if (kind === 'archived') s.session.status = 'archived';+ if (kind === 'ended-team') s.worker!.activeTeam = false;+ if (kind === 'settled') s.settledLabels = ['w'];+ if (kind === 'label') s.worker!.label = 'other';+ if (kind === 'directory') s.session.workingDir = '/other';+ if (kind === 'route') s.session.route = { ...route, model: 'other' };+ const result = await createPluginTaskReviewResolver(async () => s)(request);+ expect(result.authorizationError).toBeTruthy();+ expect(result.delegatedTask).toBeUndefined();+ });+ it('retains actual user restrictions through later Agent messages and restarts', async () => {+ const s = fixture();+ s.history.unshift({+ clientId: 'human',+ role: 'user',+ content: { text: 'Only read; do not modify files' },+ agentMeta: { autoReviewUserText: 'Only read; do not modify files', delivery: 'turn' },+ });+ const result = await createPluginTaskReviewResolver(async () => JSON.parse(JSON.stringify(s)))(+ request,+ );+ expect(JSON.stringify(result.userIntent)).toContain('do not modify files');+ expect(result.delegatedTask).toBeDefined();+ });+ it('orders user answers by acceptance time, not when the question was displayed', async () => {+ const s = fixture();+ s.history.push({ clientId: 'q', role: 'ask_user', createdAt: 1, content: {},+ agentMeta: { autoReviewUserText: { text: 'Only read now', acceptedAt: 30 } } },+ { clientId: 'u', role: 'user', createdAt: 20, content: { text: 'You may edit' },+ agentMeta: { autoReviewUserText: 'You may edit', delivery: 'turn' } });+ const r = await createPluginTaskReviewResolver(async () => s)(request);+ expect(r.userIntent).toMatchObject({ currentUserMessage: 'Only read now' });+ expect(JSON.stringify(r.userIntent)).toContain('You may edit');+ });+ it('flags incomplete/legacy restriction history without inventing owner consent', async () => {+ const s = fixture();+ s.history[0]!.agentMeta = null;+ const result = await createPluginTaskReviewResolver(async () => s)(request);+ expect(result.userIntent).toMatchObject({ historyOmitted: true });+ });- it('keeps old plans usable without treating absent scope as authorization', async () => {++ const missingScopes = ['no-plan', 'missing', 'empty', 'blank', 'null', 'number', 'oversized'] as const;++ it.each([false, true].flatMap(worker => [false, true].flatMap(hostShortcut =>++ missingScopes.map(scope => ({ worker, hostShortcut, scope })),++ )))('blocks missing scope before shortcuts: $worker/$hostShortcut/$scope', async ({ worker, hostShortcut, scope }) => {+ const s = fixture();- delete s.plan!.items[0]!.task;- const result = await createPluginTaskReviewResolver(async () => s)(request);- expect(result.authorizationError).toBeUndefined();- expect(result.delegatedTask).toBeUndefined();- expect(result.userIntent).toBe('');++ if (!worker) delete s.worker;++ if (scope === 'no-plan') delete s.plan;++ else {++ const owner = worker ? s.plan!.items[0]! : s.plan!;++ if (scope === 'missing') delete owner.task;++ else Object.assign(owner, { task: ({ empty: '', blank: ' \t\n', null: null, number: 123, oversized: 'x'.repeat(8001) })[scope] });++ }++ const model = vi.fn(async (): Promise<AutoReviewDecision> => ({ verdict: 'allow' }));++ const delegate = Object.assign(model, { prepareRequest: createPluginTaskReviewResolver(async () => s) });++ const evaluate = vi.fn((prepared: AutoReviewRequest) => resolveAutoReviewDecision(prepared, delegate, hostShortcut));++ const result = await withAutoReviewContext({ ...request, action: { kind: 'read', path: '/answer/src/a.ts' } }, delegate, evaluate);++ expect(result.verdict).toBe('block');++ expect(evaluate).not.toHaveBeenCalled();++ expect(model).not.toHaveBeenCalled();++ });++ it.each([false, true])('does not reuse cached allow after scope disappears (worker=%s)', async worker => {++ const s = fixture();++ if (!worker) delete s.worker;++ const delegate = Object.assign(async () => null, { prepareRequest: createPluginTaskReviewResolver(async () => s) });++ const cached = vi.fn(async (): Promise<AutoReviewDecision> => ({ verdict: 'allow' }));++ expect((await withAutoReviewContext(request, delegate, cached)).verdict).toBe('allow');++ if (worker) delete s.plan!.items[0]!.task;++ else delete s.plan!.task;++ expect((await withAutoReviewContext(request, delegate, cached)).verdict).toBe('block');++ expect(cached).toHaveBeenCalledOnce();++ });++ it.each([false, true])('keeps normal-task shortcuts (host=%s)', async host => {++ const model = vi.fn(async (): Promise<AutoReviewDecision> => ({ verdict: 'block' }));++ const delegate = Object.assign(model, { prepareRequest: createPluginTaskReviewResolver(async () => null) });++ expect((await withAutoReviewContext({ ...request, action: { kind: 'read', path: '/answer/src/a.ts' } }, delegate,++ prepared => resolveAutoReviewDecision(prepared, delegate, host))).verdict).toBe('allow');++ expect(model).not.toHaveBeenCalled();+ });+ it('keeps normal task intent and strips any unverified delegation', async () => {+ const result = await createPluginTaskReviewResolver(async () => null)({+ ...request,+ delegatedTask: {+ source: 'approved-plugin',+ pluginId: 'fake',+ role: 'worker',+ task: 'all',+ workingDir: '/',+ authorizationRevision: 'fake',+ },+ });+ expect(result.userIntent).toBe(request.userIntent);+ expect(result.delegatedTask).toBeUndefined();+ });+ it('root coordinator has its own scope and unrelated plan progress does not invalidate Worker cache', async () => {+ const s = fixture();+ const resolve = createPluginTaskReviewResolver(async () => s);+ const first = await resolve(request);+ s.plan!.items.push({ label: 'another', workingDir: '/another', route, task: 'Other test' });+ s.settledLabels = ['another'];+ expect((await resolve(request)).delegatedTask?.authorizationRevision).toBe(+ first.delegatedTask?.authorizationRevision,+ );+ delete s.worker;+ expect((await resolve(request)).delegatedTask?.role).toBe('coordinator');+ });+});++it.each(['ask_user', 'plan_review'])('marks missing %s answer receipts as incomplete history', async role => {+ const s = fixture();+ s.history.push({ clientId: 'old-card', role, content: { status: 'answered', answer: 'Read only' }, agentMeta: null });+ const result = await createPluginTaskReviewResolver(async () => s)(request);+ expect(result.userIntent).toMatchObject({ historyOmitted: true });+ expect(JSON.stringify(result.userIntent)).not.toContain('Read only');+});++it.each(['agentKind', 'providerId', 'model', 'effort', 'fastMode'])('rejects coordinator drift in %s', async key => {+ const s = fixture(); delete s.worker;+ s.session.route = { ...route, [key]: key === 'fastMode' ? true : 'other' } as typeof route;+ const result = await createPluginTaskReviewResolver(async () => s)(request);+ expect(result.authorizationError).toBeTruthy();+ expect(result.delegatedTask).toBeUndefined();+});+it('does not infer a missing coordinator receipt route', async () => {+ const s = fixture(); delete s.worker; delete s.registeredRoute;+ expect((await createPluginTaskReviewResolver(async () => s)(request)).authorizationError).toBeTruthy();+});+it.each([false, true])('marks tied user grant/revocation as incomplete regardless of merge order (%s)', async reverse => {+ const s = fixture();+ s.history = ['Do not write', 'You may write'].map((text, i) => ({clientId: String(i), role: 'user', createdAt: 42, content: { text }, agentMeta: {autoReviewUserText: text, delivery: 'turn'}}));+ if (reverse) s.history.reverse();+ const result = await createPluginTaskReviewResolver(async () => s)(request);+ expect(result.userIntent).toMatchObject({historyOmitted: true});+ expect(JSON.stringify(result.userIntent)).toContain('Do not write');+});++it('accepts a plan alias only while it resolves to the stored Worker directory', async () => {+ const root = await mkdtemp(join(tmpdir(), 'plugin-review-path-'));+ try {+ const target = join(root, 'target'), other = join(root, 'other'), alias = join(root, 'alias');+ await mkdir(target); await mkdir(other);+ await symlink(target, alias, 'junction');+ const s = fixture();+ s.plan!.items[0]!.workingDir = alias;+ s.session.workingDir = await realpath(target);+ const r = {...request, workspaceRoots: [s.session.workingDir]};+ const resolve = createPluginTaskReviewResolver(async () => s);+ expect((await resolve(r)).delegatedTask?.workingDir).toBe(s.session.workingDir);+ await rm(alias);+ await symlink(other, alias, 'junction');+ expect((await resolve(r)).authorizationError).toBeTruthy();+ await rm(alias);+ expect((await resolve(r)).authorizationError).toBeTruthy();+ s.plan!.items[0]!.workingDir = join(target, '..', 'target');+ expect((await resolve(r)).authorizationError).toBeUndefined();+ s.authorized = false;+ expect((await resolve(r)).authorizationError).toBeTruthy();+ } finally {+ await rm(root, {recursive: true, force: true});+ }+});diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.tsindex e8931c34f3,5f1ee17693..b1f8d2f30a--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts@@@ -3,8 -3,30 +3,31 @@@ import { drizzle } from 'drizzle-orm/beimport { expect, it } from 'vitest';import type { DbClient } from '../../localDb/client/DbClient.js';import { createPluginTaskStore } from '../pluginTaskStore.js';+import { createPluginTaskService } from '../pluginTaskService.js';+ it.each(['absent', 'raw session', 'revoked', 'changed revision', 'other plugin', 'send'] as const)(+ 'rolls back only its uncreated receipt in SQLite: %s', async state => {+ const sqlite = new Database(':memory:');+ try {+ sqlite.exec(`CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, plugin_id TEXT,+ operation TEXT, target_id TEXT, request_key TEXT, fingerprint TEXT, payload TEXT,+ revision INTEGER, created_at INTEGER); CREATE TABLE sessions(id TEXT PRIMARY KEY)`);+ const store = createPluginTaskStore({ drizzle: drizzle(sqlite) } as unknown as DbClient);+ const row = { id: 'task', pluginId: 'p', operation: 'create' as const, targetId: '',+ requestKey: 'key', fingerprint: 'hash', payload: '{}', revision: 0, createdAt: 1 };+ await store.insert(row);+ if (state === 'raw session') sqlite.prepare('INSERT INTO sessions VALUES (?)').run(row.id);+ if (state === 'revoked') await store.revokePlugin('p');+ if (state === 'changed revision') await store.save(row);+ if (state === 'other plugin') sqlite.exec("UPDATE plugin_task_requests SET plugin_id='other'");+ if (state === 'send') sqlite.exec("UPDATE plugin_task_requests SET operation='send'");+ await store.discardUncreated(row);+ expect(await store.get(row.id)).toEqual(state === 'absent' ? undefined : expect.any(Object));+ expect(sqlite.prepare('SELECT COUNT(*) AS n FROM sessions').get()).toEqual({ n: state === 'raw session' ? 1 : 0 });+ } finally { sqlite.close(); }+ },+ );+it('durably revokes only create ownership while retaining plans, run results and request identities', async () => {const sqlite=new Database(':memory:');try {diff --cc apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.tsindex b1404f5924,0000000000..35c3b5a6eemode 100644,000000..100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts@@@ -1,133 -1,0 +1,134 @@@+import { createAutoReviewIntentProjection } from '@cindy/maker-shared/auto-review-intent';+import { createHash } from 'node:crypto';+import { realpath } from 'node:fs/promises';+import {+ normalizeAutoReviewUserIntent,+ type AutoReviewRequest,+ type AutoReviewUserIntent,+} from '@cindy/maker-core';+import type { PluginTeamPlan, PluginTaskRoute } from '../../shared/pluginTasks.js';+import { isPluginTeamPlanWithinBudget } from '../../shared/pluginTasks.js';+import type { StoredAutoReviewProjection } from '../localDb/autoReviewProjection.js';+import { restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from './autoReviewUserIntent.js';++export interface PluginReviewSnapshot {+ pluginId: string;+ authorized: boolean;+ revision: unknown;+ registeredRoute?: PluginTaskRoute;+ plan?: PluginTeamPlan;+ settledLabels?: string[];+ session: { workingDir: string; permissionMode: string; planModeEnabled?: boolean; status: string; route: PluginTaskRoute };+ lead: { permissionMode: string; planModeEnabled?: boolean; status: string };+ worker?: { label: string; activeTeam: boolean };+ history: AutoReviewHistoryMessage[];+ sessionHistory: AutoReviewHistoryMessage[];+ historyComplete: boolean;+ projection?: StoredAutoReviewProjection;+}++/** Only Host-captured authored text counts. Missing legacy receipts never imply missing restrictions. */+const intentProjection = createAutoReviewIntentProjection();+export function pluginReviewUserIntent(snapshot: PluginReviewSnapshot): AutoReviewUserIntent {+ return intentProjection.review(snapshot.history, snapshot.historyComplete);+}++/** Scope comes from the authenticated plugin receipt, never Lead/Worker prose or tool arguments. */+export function createPluginTaskReviewResolver(+ load: (sessionId: string) => Promise<PluginReviewSnapshot | null>,+) {+ return async (request: AutoReviewRequest): Promise<AutoReviewRequest> => {+ const { delegatedTask: _discard, authorizationError: _error, ...base } = request;+ if (!request.sessionId) return base;+ const snapshot = await load(request.sessionId);+ if (!snapshot) return base;+ const userIntent = snapshot.projection?.reviewIntent ?? pluginReviewUserIntent(snapshot);+ const denied = (reason: string): AutoReviewRequest => ({+ ...base,+ userIntent,+ authorizationError: reason,+ });+ // Accepted steer can precede (or outlive failure of) its transcript write.+ // Compare the same session projection used by dispatch, before merging Lead+ // restrictions. Preserve order/repetition and empty resource resets; text+ // membership cannot distinguish a repeated revocation from an older grant.+ if (JSON.stringify(normalizeAutoReviewUserIntent(request.userIntent)) !==+ JSON.stringify(snapshot.projection?.sessionIntent ?? restoreAutoReviewUserIntent(snapshot.sessionHistory))) {+ return denied('Current user instructions are not synchronized with task history; automatic authorization is blocked.');+ }+ if (+ !snapshot.authorized ||+ snapshot.session.planModeEnabled || snapshot.lead.planModeEnabled ||+ snapshot.session.permissionMode !== 'auto' ||+ snapshot.lead.permissionMode !== 'auto' ||+ snapshot.session.status !== 'active' ||+ snapshot.lead.status !== 'active'+ ) {+ return denied('Plugin or task Auto authorization is no longer active.');+ }+ const plan = snapshot.plan;+ if (plan && !isPluginTeamPlanWithinBudget(plan)) return denied('Team plan exceeds the supported size; automatic authorization is blocked.');+ const item = snapshot.worker+ ? plan?.items.find((x) => x.label === snapshot.worker!.label)+ : undefined;+ const task = snapshot.worker ? item?.task : plan?.task;+ // Worker creation stores a canonical local directory. Compare aliases to+ // that same identity, never broaden the plan to a parent or a new root.+ let directoryMatches = item?.workingDir === snapshot.session.workingDir;+ if (snapshot.worker && item && !directoryMatches) {+ try {+ directoryMatches = await realpath(item.workingDir) === snapshot.session.workingDir;+ } catch {+ directoryMatches = false;+ }+ }+ if (!snapshot.worker && task && (!snapshot.registeredRoute ||+ (['agentKind', 'providerId', 'model', 'effort', 'fastMode'] as const).some(+ k => snapshot.registeredRoute![k] !== snapshot.session.route[k],+ ))) return denied('Coordinator does not match its registered route.');+ if (+ snapshot.worker &&+ (!snapshot.worker.activeTeam ||+ !item ||+ snapshot.settledLabels?.includes(snapshot.worker.label) ||+ !directoryMatches ||+ (Object.keys(item.route) as Array<keyof PluginTaskRoute>).some(+ (k) => item.route[k] !== snapshot.session.route[k],+ ))+ ) {+ return denied('Worker does not match the active registered plan.');+ }+ if (request.workspaceRoots[0] !== snapshot.session.workingDir)+ return denied('Task working directory changed.');- if (!task) return { ...base, userIntent }; // Legacy plans keep existing review behavior, without an invented grant.- if (task.length > 8000) return denied('Host-registered delegated task scope is invalid.');++ // Missing scope does not turn a recognized plugin task into an ordinary task.++ if (typeof task !== 'string' || !task.trim() || task.length > 8000)++ return denied('Host-registered delegated task scope is missing or invalid.');+ // Hash includes both scope and live ownership facts; cached decisions cannot cross a change.+ const authorizationRevision = createHash('sha256')+ .update(+ JSON.stringify([+ snapshot.revision,+ snapshot.projection?.revision,+ snapshot.pluginId,+ snapshot.session,+ snapshot.lead,+ snapshot.worker,+ task,+ userIntent,+ ]),+ )+ .digest('hex');+ return {+ ...base,+ userIntent,+ delegatedTask: {+ source: 'approved-plugin',+ pluginId: snapshot.pluginId,+ role: snapshot.worker ? 'worker' : 'coordinator',+ task,+ workingDir: snapshot.session.workingDir,+ authorizationRevision,+ },+ };+ };+}diff --cc apps/desktop/src/main/maker-ipc/pluginTaskStore.tsindex 33c33c95f3,c5baf42a94..f82c943f23--- a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts@@@ -1,7 -1,6 +1,7 @@@-import { and, asc, eq, gt, or, sql } from 'drizzle-orm';+import { and, asc, eq, gt, or, getTableColumns, sql } from 'drizzle-orm';+import { PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../shared/pluginTasks.js';import type { DbClient } from '../localDb/client/DbClient.js';- import { pluginTaskRequests } from '../localDb/schema.js';+ import { pluginTaskRequests, sessions } from '../localDb/schema.js';import type { PluginTaskStore } from './pluginTaskService.js';import { PluginTaskError } from './pluginTaskService.js';diff --cc docs/dev-rules/plugin-task-api-implementation.mdindex d78b9c4188,446544ba5a..69c82d1083--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@@ -63,44 -65,12 +65,44 @@@ getTeam 的 completedAt 可由宿主落### 已登记协同计划与释放--`setTeamPlan({taskId,plan:{concurrency,items}})` 在本插件自己的创建收据中冻结计划。首次登记必须早于输入派发和 Worker 创建(包括创建预留);同一计划的幂等重放不受此限制。每项含唯一 label、workingDir 和精确 route;重复设置必须一致。未登记计划的存量插件沿用原行为。Worker 创建复用原子 reservation,预留后再次核对计划,计划上限只可收窄宿主硬上限。已结算 label 持久保留,不因归档再次变成可派发项。++`setTeamPlan({taskId,plan:{concurrency,items}})` 在本插件自己的创建收据中冻结计划。首次登记必须早于输入派发和 Worker 创建(包括创建预留);同一计划的幂等重放不受此限制。每项含唯一 label、workingDir 和精确 route;重复设置必须一致。未登记计划的存量任务保留读取、停止和已有成果,但不能据此取得委派 Auto 自动授权。Worker 创建复用原子 reservation,预留后再次核对计划,计划上限只可收窄宿主硬上限。已结算 label 持久保留,不因归档再次变成可派发项。- 计划保存目录准入返回的 canonical 路径,后续别名改链不会把冻结计划改成新目标;这不构成 OS 目录对象隔离。`getTeam` 先恢复 Lead 的持久输入队列,恢复失败或未确认时拒绝返回空闲;最终读取实时 Lead 状态,不以启动后的空内存队列报告批次完成。+ 计划保存目录准入返回的 canonical 路径,后续别名改链不会把冻结计划改成新目标;这不构成 OS 目录对象隔离。首版仅用于可信本地工作区,不防御同权限进程在最后校验后、harness 使用 cwd 前恶意替换目录对象;路径复核或 JS 锁不能消除该窗口,不把另建 OS 隔离后端列为本接口的发布前提。插件归属、显式撤权、用户降权与任务范围的检查仍须成立。`getTeam` 先恢复 Lead 的持久输入队列,恢复失败或未确认时拒绝返回空闲;最终读取实时 Lead 状态,不以启动后的空内存队列报告批次完成。`releaseWorker({taskId,workerId,completedAt})` 仅释放本插件 Lead 内、结束时间仍匹配、无活动/排队输入的 Worker。它与 getTeam 共用宿主成功终态判据,不能以 Worker 更新时间或失败轮结束时间替代交卷凭据。调用方应先保存交卷快照和评分。复用 Orca 的归档路径、transition 锁和发送锁;持锁后再次核对 completedAt 与归属。有计划时必须在归档前确认标签归属;无计划的兼容调用不写标签结算。已有发送锁时直接拒绝释放,不等待而形成锁反转;只有归档成功才结算 label。拒绝正在发送或运行的 Worker,保留任务历史与作答文件。`getTeam` 增加包含创建预留的 capacity 快照(advisory;准入仍由创建事务裁决)、逐 Worker 的等待确认状态、首条输入/首条执行消息时间、最近轮结束时间,以及 Worker/Lead 分列的 session-total 用量。`host-message-window` 是可观测作答窗口,不是精确模型计算时长。无确切 USD 金额时返回 null,不把订阅估值或其他币种直接当美元。写权限确认前及最终提交前,在原 session/send 锁下恢复持久输入队列;恢复未确认或仍有排队输入时拒绝提权,不把冷任务的空内存队列当作空闲。任务能力批准在收据临时文件准备完成后紧邻原子发布复核账号时效,该受保护替换不跨事件循环;普通收据写入保持原路径。++### 委派范围与 Auto 审阅++计划的顶层 `task` 及每项 `task` 是可选的插件原始任务说明,最多 8000 字符。+完整计划 `JSON.stringify(plan).length` 最多 1,048,576 个 UTF-16 字符(包含转义和元数据);超限返回 `INVALID_REQUEST`,不截断任务或删除旧计划。管道和服务入口统一检查;旧收据在解析前检查总量,恢复及 Auto 不把超限计划当作未登记。200 份现有七题公开范围的实测最大约 59 万字符可容纳,不保证任意自定义题或极长路径均可用满 200 份。+Host 只接受经绑定插件身份写入的自有创建收据;已登记计划整体不可变,包括原本缺失的范围。- 旧计划缺少范围时沿用原审批行为,不事后补造授权;新范围须在新任务中登记完整计划。++已识别插件任务的协调任务或 Worker 缺少有效范围时返回既有 authorizationError,在缓存、本地安全动作或 Host MCP 快捷路径之前拒绝自动授权;不退回普通任务、不从消息补造范围。旧计划继续可读,不事后补填;新范围须在新任务中登记完整计划。Ask/acceptEdits 保留既有逐次人工确认,普通无插件归属任务不受此限制。+没有新增权限档位、没有提升到 Full access。++审批在查询缓存前重新核对插件批准版本、启用状态、Auto 设置、账号 epoch、任务状态、+团队归属和计划匹配;异步结果返回前再次核对。+历史投影和归属读取完成后,以同一条只读 SQL 比较本次使用的任务/Lead 权限、独立 Plan、状态、路由目录、团队链接及计划收据,并复核授权投影修订号仍与读取值一致、投影已同步且版本为 3;变化拒绝本次授权,查询失败保留 unavailable。该检查同时覆盖 Lead 和 Worker 的真人证据变化,不只检查当前 Worker 的意图。Lead 或 Worker 已开启独立 Plan 时不恢复委派 Auto。+真实用户限制来自 Host 保存的作者凭据,不从 Orca 消息、模型声称或工具参数恢复。缺少旧作者凭据时标注历史不完整,不猜测授权。+插件文字放在独立 `delegatedTask` 字段,不能覆盖用户限制、跨题授权或声称自己是用户。+直接派发和排队派发均保存受保护的 `delegated-continuation` 作者凭据;应用重启后从同一 Host 收据重建委派范围。+自动恢复、上下文重建、系统触发及受保护续行共用合成消息判据,不追加旧授权,也不清除真人限制;增量摘要与完整重放一致。运行时摘要版本升为 3,旧版摘要首次读取从原消息自动重建,无需重新授权,不改历史 migration。++明确带任务范围的所有动作(包括读取)均检查范围;不会仅凭工作目录安全而忽略插件的禁读条款。明确的 Host 续行凭据在 SQL 限量前过滤,避免频繁协调消息挤走真实用户限制;空字符串凭据仍保留,因为用户只发送附件时也可能没有文字。用户消息携带新资源时,沿用普通任务规则,先清除旧指代授权再追加该行可信原话;不以可编辑的 origin 判定作者。缺凭据的旧卡片保守标记历史不完整。++Host 信任的 MCP 快捷路径在 Auto、Ask/acceptEdits 下都先经过现有委派上下文复核;只有复核后的普通任务可免确认。+同一判据覆盖 Claude 本地/SSH、Codex MCP elicitation/Host dynamic tool、Pi 主进程/持久子代理;+保留真实工具参数、审阅前后 Host 核验及最后的意图/缓存/目录时效检查。+Host 快捷放行及仅检查快捷资格的标志计入既有审阅缓存键;非 Auto 不调用模型,+核验不能放行时走既有逐次人工确认,无确认界面则拒绝;不会把 Host 的“Auto 不可用”误当成禁止用户逐次授权。+人工允许只批准当前动作,不恢复 Auto 或插件控制权,插件 API 自身仍核对调用者归属。+Auto 明确撤权仍直接拒绝,故障仍走 ask/unavailable。Full access、Plan 和独立 turn policy 保持原判据。+Pi 子代理未成功投递的自动 allow 再次投递前重走现有核验,不把旧决定当成持久授权;人工答复保留原投递重试行为。++验证入口:`pluginTaskReviewContext.test.ts`、`pluginTaskService.test.ts`、`taskSlot.test.ts`、+`auto-review-context.test.ts`、Pi/Claude Code 审批接线回归以及 `eval-auto-approval.mts` 的+`delegated-*` 正反对照(后者需要真实审阅模型,当前拆分 PR 未运行付费验证)。主机身份校验是确定性边界,动作与任务是否相符仍由 Auto 审阅,+不宣称题目目录是系统沙箱。