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(plugins): resolve delegated directories before final authorization

Dashcaea0d02e6af
diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts
index ff39201081,0000000000..5ee1bbd2aa
mode 100644,000000..100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts
@@@ -1,121 -1,0 +1,256 @@@
+import { readFileSync } from 'node:fs';
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { eq } from 'drizzle-orm';
+import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
- import { expect, it } from 'vitest';
++import { expect, it, vi } from 'vitest';
++import { mkdtemp, mkdir, rm, symlink, realpath } from 'node:fs/promises';
++import { tmpdir } from 'node:os';
++import { join } from 'node:path';
++import type { AutoReviewRequest, AutoReviewDecision } from '@cindy/maker-core';
++import { withAutoReviewContext } from '../../../../../../packages/maker-core/src/agents/shared/auto-review-decision.js';
++import { createPluginTaskReviewResolver, type PluginReviewSnapshot } from '../pluginTaskReviewContext.js';
++import { readPluginTaskPlanReceipt } from '../pluginTaskService.js';
++import { PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS, PLUGIN_TEAM_PLAN_MAX_JSON_CHARS } from '../../../shared/pluginTasks.js';
++
++const resolvePath = vi.hoisted(() => vi.fn());
++vi.mock('node:fs/promises', async importOriginal => ({
++ ...await importOriginal<typeof import('node:fs/promises')>(), realpath: resolvePath,
++}));
+import ts from 'typescript';
+import { readAutoReviewProjectionTransaction, type StoredAutoReviewProjection } from '../../localDb/autoReviewProjection.js';
+
+const sessions = sqliteTable('sessions', {
+ id:text('id'),source:text('source'),orcaRole:text('orca_role'),workingDir:text('working_dir'),
+ permissionMode:text('permission_mode'),planModeEnabled:integer('plan_mode_enabled',{mode:'boolean'}),
+ status:text('status'),agentKind:text('agent_kind'),providerId:text('provider_id'),model:text('model'),
+ effort:text('effort'),fastMode:integer('fast_mode',{mode:'boolean'}),
+});
+const orcaWorkers = sqliteTable('orca_workers',{sessionId:text('session_id'),teamId:text('team_id'),label:text('label')});
+const orcaTeams = sqliteTable('orca_teams',{id:text('id'),leadSessionId:text('lead_session_id'),status:text('status')});
+const source=readFileSync(new URL('../register.ts',import.meta.url),'utf8');
+const start=source.indexOf(' setAutoReviewContextResolver(createPluginTaskReviewResolver(async sessionId => {');
+const block=source.slice(start,source.indexOf('\n }));',start)+7);
+const js=ts.transpileModule(block,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
+const changes = {
+ workerPermission: "UPDATE sessions SET permission_mode='default' WHERE id='worker'",
+ workerPlan: "UPDATE sessions SET plan_mode_enabled=1 WHERE id='worker'",
+ workerStatus: "UPDATE sessions SET status='archived' WHERE id='worker'",
+ directory: "UPDATE sessions SET working_dir='/other' WHERE id='worker'",
+ route: "UPDATE sessions SET model='other' WHERE id='worker'",
+ leadPermission: "UPDATE sessions SET permission_mode='default' WHERE id='lead'",
+ leadPlan: "UPDATE sessions SET plan_mode_enabled=1 WHERE id='lead'",
+ leadStatus: "UPDATE sessions SET status='archived' WHERE id='lead'",
+ team: "UPDATE orca_teams SET status='archived'",
+ label: "UPDATE orca_workers SET label='other'",
+ unlink: "DELETE FROM orca_workers",
+ receipt: "UPDATE plugin_task_requests SET payload='{}', revision=2",
+};
+
+function fixture() {
+ const db=new Database(':memory:');
+ db.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, source TEXT, orca_role TEXT, working_dir TEXT, permission_mode TEXT, plan_mode_enabled INTEGER, status TEXT, agent_kind TEXT, provider_id TEXT, model TEXT, effort TEXT, fast_mode INTEGER, cleared_at INTEGER);
+ CREATE TABLE messages(id TEXT PRIMARY KEY, session_id TEXT, client_id TEXT, role TEXT, content TEXT, created_at INTEGER, agent_meta TEXT, rewind_at INTEGER);
+ CREATE TABLE orca_workers(session_id TEXT, team_id TEXT, label TEXT);
+ CREATE TABLE orca_teams(id TEXT, lead_session_id TEXT, status TEXT);
+ CREATE TABLE plugin_task_requests(id TEXT, target_id TEXT, plugin_id TEXT, operation TEXT, payload TEXT, revision INTEGER);
+ INSERT INTO sessions VALUES ('lead','plugin','lead','/answer','auto',0,'active','codex','p','model','high',0,NULL),('worker','orca','worker','/answer','auto',0,'active','codex','p','model','high',0,NULL);
+ INSERT INTO orca_workers VALUES ('worker','team','sample');
+ INSERT INTO orca_teams VALUES ('team','lead','active');
+ INSERT INTO plugin_task_requests VALUES ('lead','','plugin','create','{"teamPlan":{"task":"scope","items":[]}}',1);`);
+ db.exec(readFileSync(new URL('../../../../drizzle/0122_auto_review_projections.sql', import.meta.url), 'utf8'));
+ const companion = readFileSync(new URL('../../../../drizzle/scripts/0122_auto_review_projections.ts', import.meta.url), 'utf8');
+ const module = { exports: {} as { run: (db: Database.Database) => void } };
+ new Function('module', companion)(module);
+ module.exports.run(db);
- const control = { phase: '', mutate: () => {}, storageUnavailable: false };
++ resolvePath.mockReset().mockResolvedValue('/answer');
++ const control = { phase: '', mutate: () => {}, storageUnavailable: false,
++ accountChanged: false, ownershipValid: true, authorized: true, approvalRevision: 'install' as string | null, permissionMode: 'auto' };
+ const mutate=(at:string)=>{if(control.phase===at)control.mutate();};
+ const epoch={userId:'owner',clientEpoch:1,client:{drizzle:drizzle(db),
+ tx:async(_name:string,args:unknown)=>{const projection=readAutoReviewProjectionTransaction(db,args);mutate('projection');return projection;},
+ queryOne:async(sql:string,params:unknown[])=>{if(control.storageUnavailable)throw Error('storage unavailable');return db.prepare(sql).get(...params);},
+ }};
- let load!:(id:string)=>Promise<{authorized:boolean;projection:StoredAutoReviewProjection}>;
- const deps={setAutoReviewContextResolver:(fn:typeof load)=>{load=fn;},createPluginTaskReviewResolver:(fn:typeof load)=>fn,
- getCurrentDbClientSnapshot:()=>epoch,sessions,orcaWorkers,orcaTeams,eq,
++ let load!:(id:string)=>Promise<PluginReviewSnapshot & {projection:StoredAutoReviewProjection}>;
++ let resolve!: ReturnType<typeof createPluginTaskReviewResolver>;
++ const deps={setAutoReviewContextResolver:(fn:typeof resolve)=>{resolve=fn;},
++ createPluginTaskReviewResolver:(fn:typeof load)=>{load=fn;return createPluginTaskReviewResolver(fn);},
++ fsp: {realpath: resolvePath},
++ getCurrentDbClientSnapshot:()=>control.accountChanged ? null : epoch,sessions,orcaWorkers,orcaTeams,eq,
+ createPluginTaskStore:()=>({get:async()=>db.prepare('SELECT id,target_id AS targetId,plugin_id AS pluginId,operation,payload,revision FROM plugin_task_requests').get()}),
- drainPersistQueue:async()=>mutate('drain'),pluginTaskServiceForCurrentOwner:()=>({get:async()=>mutate('ownership')}),
- readGhostErrandConfig:()=>({permissionMode:'auto'}),readPluginTaskPlanReceipt:JSON.parse,
- pluginTaskAuthorizationRevision:()=> 'install',isPluginTaskAuthorized:()=>true,
++ drainPersistQueue:async()=>mutate('drain'),pluginTaskServiceForCurrentOwner:()=>({get:async()=>{mutate('ownership');if(!control.ownershipValid)throw Error('ownership revoked');}}),
++ readGhostErrandConfig:()=>({permissionMode:control.permissionMode}),readPluginTaskPlanReceipt,
++ pluginTaskAuthorizationRevision:()=>control.approvalRevision,isPluginTaskAuthorized:()=>control.authorized,
+ };
+ new Function(...Object.keys(deps),js)(...Object.values(deps));
- return {db,control,load};
++ return {db,control,load,resolve};
+}
+
+it.each(['drain','projection','ownership'].flatMap(phase=>[
+ ...Object.keys(changes).map(change=>({phase,change,sessionId:'worker'})),
+ ...['leadPermission','leadPlan','leadStatus','receipt'].map(change=>({phase,change,sessionId:'lead'})),
+]))('rejects changed $change for $sessionId after $phase with one final database read', async ({phase,change,sessionId})=>{
+ const {db,control,load}=fixture();
+ try {
+ db.exec("UPDATE sessions SET provider_id=NULL,working_dir='/评测/answer'");
+ expect((await load(sessionId)).authorized).toBe(true);
+ control.storageUnavailable=true;
+ await expect(load(sessionId)).rejects.toThrow('storage unavailable');
+ control.storageUnavailable=false;
+ control.phase=phase;
+ control.mutate=()=>db.exec(changes[change as keyof typeof changes]);
+ expect((await load(sessionId)).authorized).toBe(false);
+ } finally {db.close();}
+});
+
+it.each(['drain','projection','ownership'].flatMap(phase =>
+ [{sessionId:'worker',writer:'lead'},{sessionId:'worker',writer:'worker'},{sessionId:'lead',writer:'lead'}].flatMap(pair =>
+ ['insert','edit','delete','rewind','clear'].map(operation => ({phase,...pair,operation})),
+ ),
+))('rechecks $writer $operation evidence for $sessionId after $phase', async ({phase,sessionId,writer,operation}) => {
+ const {db,control,load}=fixture();
+ const add = (id:string, text:string, at:number) => db.prepare('INSERT INTO messages VALUES (?,?,?,?,?,?,?,NULL)').run(
+ id,writer,id,'user',JSON.stringify({text}),at,JSON.stringify({delivery:'turn',autoReviewUserText:text}),
+ );
+ try {
+ add('grant','allow publishing',1);
+ const before=await load(sessionId);
+ expect(before.authorized).toBe(true);
+ expect(JSON.stringify(before.projection.reviewIntent)).toContain('allow publishing');
+ control.phase=phase;
+ control.mutate=()=>{
+ if(operation==='insert') add('restriction','never publish',2);
+ if(operation==='edit') db.prepare('UPDATE messages SET content=?,agent_meta=? WHERE id=?').run(
+ JSON.stringify({text:'never publish'}),JSON.stringify({delivery:'turn',autoReviewUserText:'never publish'}),'grant');
+ if(operation==='delete') db.prepare('DELETE FROM messages WHERE id=?').run('grant');
+ if(operation==='rewind') db.prepare('UPDATE messages SET rewind_at=2 WHERE id=?').run('grant');
+ if(operation==='clear') db.prepare('UPDATE sessions SET cleared_at=1 WHERE id=?').run(writer);
+ };
+ const result=await load(sessionId);
+ const current=readAutoReviewProjectionTransaction(db,{sessionId,leadId:'lead'});
+ expect(current.revision).toBeGreaterThan(before.projection.revision);
+ expect(result.authorized).toBe(phase==='drain');
+ expect(result.projection.revision).toBe(phase==='drain'?current.revision:before.projection.revision);
+ // A subsequent request can read the new evidence; rejection does not poison the task.
+ control.phase='';
+ expect((await load(sessionId)).projection).toEqual(current);
+ expect((await load(sessionId)).authorized).toBe(true);
+ } finally {db.close();}
+});
++
++
++const request: AutoReviewRequest = {
++ sessionId: 'worker', agentKind: 'codex', model: 'model', userIntent: '',
++ workspaceRoots: ['/answer'], platform: 'linux',
++ action: {kind: 'exec', command: 'run-evaluation', cwd: '/answer'},
++};
++function setPlan(db: Database.Database, directory = '/alias') {
++ const route = {agentKind: 'codex', providerId: 'p', model: 'model', effort: 'high', fastMode: false};
++ db.prepare('UPDATE plugin_task_requests SET payload=?').run(JSON.stringify({route,
++ teamPlan: {concurrency: 1, task: 'scope', items: [{label: 'sample', task: 'scope', workingDir: directory, route}]},
++ }));
++}
++const duringPathChanges = {
++ ...Object.fromEntries(Object.entries(changes).map(([name, sql]) => [name, ({db}: ReturnType<typeof fixture>) => db.exec(sql)])),
++ planScope: ({db}: ReturnType<typeof fixture>) => db.exec("UPDATE plugin_task_requests SET payload=json_set(payload,'$.teamPlan.items[0].task','new scope')"),
++ settled: ({db}: ReturnType<typeof fixture>) => db.exec("UPDATE plugin_task_requests SET payload=json_set(payload,'$.settledLabels',json('[\"sample\"]'))"),
++ ownership: ({control}: ReturnType<typeof fixture>) => {control.ownershipValid=false;},
++ approval: ({control}: ReturnType<typeof fixture>) => {control.authorized=false;},
++ approvalRemoved: ({control}: ReturnType<typeof fixture>) => {control.approvalRevision=null;},
++ configAsk: ({control}: ReturnType<typeof fixture>) => {control.permissionMode='default';},
++ account: ({control}: ReturnType<typeof fixture>) => {control.accountChanged=true;},
++ userInstruction: ({db}: ReturnType<typeof fixture>) => db.prepare('INSERT INTO messages VALUES (?,?,?,?,?,?,?,NULL)').run(
++ 'revoke','worker','revoke','user',JSON.stringify({text:'Do not run'}),1,JSON.stringify({delivery:'turn',autoReviewUserText:'Do not run'})),
++};
++it.each(['initial', 'after cached allow'].flatMap(phase => Object.keys(duringPathChanges).map(change => ({phase,change}))))(
++ 'rejects $change during alias resolution at $phase preparation', async ({phase,change}) => {
++ const f=fixture();
++ try {
++ setPlan(f.db);
++ let entered!: () => void, release!: () => void;
++ const waiting=new Promise<void>(r=>{entered=r;});
++ const paused=new Promise<void>(r=>{release=r;});
++ if(phase==='after cached allow') resolvePath.mockResolvedValueOnce('/answer');
++ resolvePath.mockImplementationOnce(async()=>{entered();await paused;return '/answer';});
++ const cached=vi.fn(async():Promise<AutoReviewDecision>=>({verdict:'allow'}));
++ const pending=phase==='initial'
++ ? f.resolve(request).then(result=>{
++ expect(result.authorizationError).toBeTruthy();
++ expect(result.delegatedTask).toBeUndefined();
++ }, error=>{
++ expect(['account','ownership']).toContain(change);
++ expect(error.message).toBe(change==='account'?'Account changed':'ownership revoked');
++ })
++ : withAutoReviewContext(request,Object.assign(async()=>null,{prepareRequest:f.resolve}),cached).then(result=>{
++ if(change==='account'||change==='ownership') expect(result).toMatchObject({verdict:'ask',unavailable:true});
++ else expect(result.verdict).toBe('block');
++ });
++ await waiting;
++ duringPathChanges[change as keyof typeof duringPathChanges](f);
++ release();
++ await pending;
++ expect(cached).toHaveBeenCalledTimes(phase==='initial'?0:1);
++ } finally {f.db.close();}
++ },
++);
++it('allows a healthy alias through both preparations without changing its authorization revision', async()=>{
++ const f=fixture();
++ try {
++ setPlan(f.db);
++ const evaluated=vi.fn(async(prepared:AutoReviewRequest):Promise<AutoReviewDecision>=>{
++ expect(prepared.delegatedTask?.workingDir).toBe('/answer');
++ return {verdict:'allow'};
++ });
++ expect((await withAutoReviewContext(request,Object.assign(async()=>null,{prepareRequest:f.resolve}),evaluated)).verdict).toBe('allow');
++ expect(evaluated).toHaveBeenCalledOnce();
++ expect(resolvePath).toHaveBeenCalledTimes(2);
++ } finally {f.db.close();}
++});
++it.each(['ordinary','coordinator','exact Worker'])('does not resolve an alias for %s', async kind=>{
++ const f=fixture();
++ try {
++ setPlan(f.db,'/answer');
++ if(kind==='ordinary') f.db.exec("UPDATE sessions SET source='orca',orca_role=NULL WHERE id='worker'");
++ const result=await f.resolve({...request,sessionId:kind==='coordinator'?'lead':'worker'});
++ expect(result.authorizationError).toBeUndefined();
++ expect(!!result.delegatedTask).toBe(kind!=='ordinary');
++ expect(resolvePath).not.toHaveBeenCalled();
++ } finally {f.db.close();}
++});
++it('resolves real aliases before the final authorization read and denies changed or missing targets', async()=>{
++ const f=fixture();
++ const root=await mkdtemp(join(tmpdir(),'plugin-review-path-'));
++ const native=await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
++ try {
++ resolvePath.mockImplementation(native.realpath);
++ 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 canonical=await realpath(target);
++ f.db.prepare('UPDATE sessions SET working_dir=?').run(canonical);
++ setPlan(f.db,alias);
++ const r={...request,workspaceRoots:[canonical]};
++ expect((await f.resolve(r)).delegatedTask?.workingDir).toBe(canonical);
++ await rm(alias); await symlink(other,alias,'junction');
++ expect((await f.resolve(r)).authorizationError).toBeTruthy();
++ await rm(alias);
++ expect((await f.resolve(r)).authorizationError).toBeTruthy();
++ setPlan(f.db,join(target,'..','target'));
++ expect((await f.resolve(r)).delegatedTask?.workingDir).toBe(canonical);
++ f.control.authorized=false;
++ expect((await f.resolve(r)).authorizationError).toBeTruthy();
++ } finally {f.db.close();await rm(root,{recursive:true,force:true});}
++});
++
++it.each(['receipt', 'plan'])('rejects an oversized %s before resolving a directory', async kind=>{
++ const f=fixture();
++ try {
++ setPlan(f.db);
++ const raw=(f.db.prepare('SELECT payload FROM plugin_task_requests').get() as {payload:string}).payload;
++ const payload=kind==='receipt' ? raw+' '.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS) : JSON.stringify({
++ ...JSON.parse(raw), teamPlan:{...JSON.parse(raw).teamPlan,task:'x'.repeat(PLUGIN_TEAM_PLAN_MAX_JSON_CHARS)},
++ });
++ f.db.prepare('UPDATE plugin_task_requests SET payload=?').run(payload);
++ await expect(f.resolve(request)).rejects.toThrow('exceeds the supported size');
++ expect(resolvePath).not.toHaveBeenCalled();
++ } finally {f.db.close();}
++});
diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts
index 1b2c281396,0000000000..7b11d89219
mode 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,384 -1,0 +1,361 @@@
- import { mkdtemp, mkdir, realpath, rm, symlink } from 'node:fs/promises';
- import { tmpdir } from 'node:os';
- import { join } from 'node:path';
+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 },
++ worker: { label: 'w', activeTeam: true, directoryMatches: 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 });
+ });
+ 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();
+ 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});
- }
++it('rejects a Worker when the loader could not verify its directory', async () => {
++ const s=fixture();
++ s.worker!.directoryMatches=false;
++ expect((await createPluginTaskReviewResolver(async()=>s)(request)).authorizationError).toBeTruthy();
+});
diff --cc apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
index 35c3b5a6ee,0000000000..0a8f304f4b
mode 100644,000000..100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
@@@ -1,134 -1,0 +1,123 @@@
+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 };
++ worker?: { label: string; activeTeam: boolean; directoryMatches: 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 ||
++ !snapshot.worker.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.');
+ // 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/register.ts
index c211fdc0a8,e7770467bd..4153bcf558
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -13675,93 -13641,8 +13675,104 @@@ export function registerMakerIpc(maker
const readAutoReviewHistory = async (sessionId: string) => {
await drainPersistQueue();
- return listMessagesForAgentHandoff(sessionId, 100, undefined, 'authorization');
+ return listMessagesForAgentHandoff(sessionId, null, undefined, 'authorization');
};
+ setAutoReviewContextResolver(createPluginTaskReviewResolver(async sessionId => {
+ const epoch = getCurrentDbClientSnapshot();
+ if (!epoch) throw new Error('Task storage unavailable');
+ const db = epoch.client.drizzle;
+ const [session] = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);
+ if (!session) throw new Error('Task unavailable');
+ // Ordinary tasks do not depend on plugin receipt storage. Worker ownership
+ // is checked through its lead before touching the plugin task store.
+ if (session.source !== 'plugin' && session.orcaRole !== 'worker') {
+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');
+ return null;
+ }
+ const [link] = await db.select({ label: orcaWorkers.label, leadId: orcaTeams.leadSessionId,
+ teamId: orcaTeams.id, teamStatus: orcaTeams.status }).from(orcaWorkers)
+ .innerJoin(orcaTeams, eq(orcaWorkers.teamId, orcaTeams.id))
+ .where(eq(orcaWorkers.sessionId, sessionId)).limit(1);
+ const leadId = link?.leadId ?? sessionId;
+ const [lead] = await db.select().from(sessions).where(eq(sessions.id, leadId)).limit(1);
+ if (!lead) throw new Error('Lead unavailable');
+ if (lead.source !== 'plugin') {
+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');
+ return null;
+ }
+ const store = createPluginTaskStore(epoch.client);
+ const receipt = await store.get(leadId);
+ if (!receipt || receipt.operation !== 'create') {
+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');
+ return null;
+ }
+ if (!session || !lead || !session.workingDir) throw new Error('Delegated task unavailable');
+ const agentKind = session.agentKind === 'cc' ? 'cc' : session.agentKind === 'pi' ? 'pi' : session.agentKind === 'codex' ? 'codex' : null;
+ if (!agentKind) throw new Error('Delegated task route unavailable');
++ const data = readPluginTaskPlanReceipt(receipt.payload);
++ const item = link ? data.teamPlan?.items.find(item => item.label === link.label) : undefined;
++ let directoryMatches = item?.workingDir === session.workingDir;
++ if (item && !directoryMatches) {
++ try {
++ directoryMatches = await fsp.realpath(item.workingDir) === session.workingDir;
++ } catch {
++ directoryMatches = false;
++ }
++ }
++ // Resolve aliases before the live ownership/database/epoch fence. Returning
++ // the checked snapshot must not await filesystem I/O after that fence.
+ await drainPersistQueue();
+ const projection = await epoch.client.tx('authorization.readProjection', { sessionId, leadId });
+ // Reinstall must not revive the old Lead's delegated authority, including
+ // requests that were already waiting for history/projection reads at uninstall.
+ await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId, leadId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');
+ // The projection/ownership awaits must not return an old Worker grant.
+ // One final SELECT compares every database fact used below at one read point;
+ // a changed fact denies this review, while a query failure remains unavailable.
+ const unchanged = await epoch.client.queryOne<{ unchanged: number }>(`
+ SELECT 1 AS unchanged FROM sessions s
+ JOIN sessions l ON l.id = ?
+ LEFT JOIN orca_workers w ON w.session_id = s.id
+ LEFT JOIN orca_teams t ON t.id = w.team_id
+ JOIN plugin_task_requests r ON r.id = l.id
+ JOIN auto_review_projections p ON p.session_id = s.id AND p.lead_id = l.id
+ WHERE s.id = ?
+ AND json_array(s.source,s.orca_role,s.working_dir,s.permission_mode,coalesce(s.plan_mode_enabled,0),s.status,
+ s.agent_kind,s.provider_id,s.model,s.effort,coalesce(s.fast_mode,0)) = ?
+ AND json_array(l.source,l.permission_mode,coalesce(l.plan_mode_enabled,0),l.status) = ?
+ AND json_array(w.label,t.lead_session_id,t.id,t.status) = ?
+ AND json_array(r.id,r.target_id,r.plugin_id,r.operation,r.payload,r.revision) = ?
+ AND p.revision = ? AND p.projected_revision = p.revision AND p.version = 3
+ LIMIT 1`, [leadId, sessionId,
+ JSON.stringify([session.source,session.orcaRole,session.workingDir,session.permissionMode,Number(!!session.planModeEnabled),session.status,
+ session.agentKind,session.providerId,session.model,session.effort,Number(!!session.fastMode)]),
+ JSON.stringify([lead.source,lead.permissionMode,Number(!!lead.planModeEnabled),lead.status]),
+ JSON.stringify([link?.label,link?.leadId,link?.teamId,link?.teamStatus]),
+ JSON.stringify([receipt.id,receipt.targetId,receipt.pluginId,receipt.operation,receipt.payload,receipt.revision]),
+ projection.revision,
+ ]);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');
+ const config = readGhostErrandConfig(receipt.pluginId);
- const data = readPluginTaskPlanReceipt(receipt.payload);
+ const approvalRevision = pluginTaskAuthorizationRevision(receipt.pluginId);
+ return {
+ pluginId: receipt.pluginId,
+ authorized: !!unchanged && approvalRevision !== null && isPluginTaskAuthorized(receipt.pluginId) && config.permissionMode === 'auto',
+ revision: [epoch.userId, epoch.clientEpoch, approvalRevision, config.permissionMode, link],
+ plan: data.teamPlan, settledLabels: data.settledLabels,
+ registeredRoute: data.route,
+ session: { workingDir: session.workingDir, permissionMode: session.permissionMode, planModeEnabled: !!session.planModeEnabled, status: session.status,
+ route: { agentKind, providerId: session.providerId ?? '', model: session.model,
+ effort: session.effort, fastMode: !!session.fastMode } },
+ lead: { permissionMode: lead.permissionMode, planModeEnabled: !!lead.planModeEnabled, status: lead.status },
- ...(link ? { worker: { label: link.label ?? '', activeTeam: link.teamStatus === 'active' } } : {}),
++ ...(link ? { worker: { label: link.label ?? '', activeTeam: link.teamStatus === 'active', directoryMatches } } : {}),
+ projection,
+ history: [],
+ sessionHistory: [],
+ historyComplete: true,
+ };
+ }));
+
const { sendToAgentAccepted: sendToAgentAcceptedUnlocked } = createMakerSendTransaction({
prepareProductTurn: (sessionId) => {
const dispatch = prepareUpstreamMergeTurn(sessionId);
diff --cc docs/dev-rules/plugin-task-api-implementation.md
index 91b2809dd7,8904393455..d50c0295a4
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@@ -81,35 -81,3 +81,36 @@@ getTeam 的 completedAt 可由宿主落
`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。
++Worker 别名目录的异步解析在该次归属和最终授权核验之前完成;核验后只同步消费本次目录匹配结果,不再等待文件系统读取。该结果不写入回执,也不替代可信本地工作区边界。
+真实用户限制来自 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 审阅,
+不宣称题目目录是系统沙箱。