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(plugin-auto): recheck authorization after projection reads

Dashafe808e662a8
diff --cc apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index 6d2c3e2f0f,28bd566fde..97cc6a1cbf
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@@ -2791,7 -2791,7 +2791,7 @@@ describe('production plugin Auto admiss
});
it.each([
- ...[false, true].flatMap(planned => ['reservation', 'directory', 'receipt', 'final-task', 'task-mode', 'disabled', 'healthy', 'archive-first', 'archive-admission', 'archive-reservation', 'archive-final'].map(point => ({ planned, point }))),
- ...[false, true].flatMap(planned => ['reservation', 'directory', 'receipt', 'final-task', 'task-mode', 'disabled', 'healthy', 'archive-first', 'archive-reservation', 'archive-final', 'plan-first', 'plan-reservation', 'plan-final'].map(point => ({ planned, point }))),
++ ...[false, true].flatMap(planned => ['reservation', 'directory', 'receipt', 'final-task', 'task-mode', 'disabled', 'healthy', 'archive-first', 'archive-admission', 'archive-reservation', 'archive-final', 'plan-first', 'plan-reservation', 'plan-final'].map(point => ({ planned, point }))),
...['explicit-match', 'canonical-directory', 'different-model', 'different-directory', 'normalized-fast', 'changed-plan', 'normalized-label', 'settled-label'].map(point => ({ planned: true, point })),
...['queued-plan-excludes', 'queued-plan-route', 'queued-plan-matches'].map(point => ({ planned: false, point })),
])('checks $point with planned=$planned before bootstrap', async ({ planned, point }) => {
diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts
index 0000000000,0000000000..da989a5a3d
new file mode 100644
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts
@@@ -1,0 -1,0 +1,74 @@@
++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 ts from 'typescript';
++
++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",
++};
++
++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=new Database(':memory:');
++ try {
++ db.exec(`CREATE TABLE sessions(id TEXT, 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);
++ 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),('worker','orca','worker','/answer','auto',0,'active','codex','p','model','high',0);
++ 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);`);
++ let currentPhase='healthy';
++ const mutate=(at:string)=>{if(currentPhase===at)db.exec(changes[change as keyof typeof changes]);};
++ let storageUnavailable=false;
++ const epoch={userId:'owner',clientEpoch:1,client:{drizzle:drizzle(db),
++ tx:async()=>{mutate('projection');return {};},
++ queryOne:async(sql:string,params:unknown[])=>{if(storageUnavailable)throw Error('storage unavailable');return db.prepare(sql).get(...params);},
++ }};
++ let load!:(id:string)=>Promise<{authorized:boolean}>;
++ const deps={setAutoReviewContextResolver:(fn:typeof load)=>{load=fn;},createPluginTaskReviewResolver:(fn:typeof load)=>fn,
++ getCurrentDbClientSnapshot:()=>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,
++ };
++ new Function(...Object.keys(deps),js)(...Object.values(deps));
++ db.exec("UPDATE sessions SET provider_id=NULL,working_dir='/评测/answer'");
++ expect((await load(sessionId)).authorized).toBe(true);
++ storageUnavailable=true;
++ await expect(load(sessionId)).rejects.toThrow('storage unavailable');
++ storageUnavailable=false;
++ currentPhase=phase;
++ expect((await load(sessionId)).authorized).toBe(false);
++ } finally {db.close();}
++});
diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts
index faa96f4b25,0000000000..7a55e291cd
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,349 -1,0 +1,353 @@@
+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 { 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 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('');
+ });
+ 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__/pluginTaskService.test.ts
index ef767356b7,8b08899b4e..d64f06edb8
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@@ -14,42 -13,6 +14,42 @@@ import
} from '../pluginTaskService.js';
import type { PluginTaskView } from '../../../shared/pluginTasks.js';
import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from '../sessionExecutionOwnership.js';
+import { PLUGIN_TEAM_PLAN_MAX_JSON_CHARS, PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../../shared/pluginTasks.js';
+
+it('rejects oversized plans before saving and refuses oversized legacy receipts without truncation', async () => {
+ const f=fixture(), task=await f.create();
+ const before=structuredClone(f.rows.get(task.taskId)!);
+ const plan={concurrency:2,items:Array.from({length:200},(_,i)=>({label:'w'+i,workingDir:'/answer',route:f.route,task:'x'.repeat(8000)}))};
+ await expect(f.service.setTeamPlan('p',task.taskId,plan)).rejects.toMatchObject({code:'INVALID_REQUEST'});
+ expect(f.rows.get(task.taskId)).toEqual(before);
+ for (const payload of [' '.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS+1), JSON.stringify({teamPlan:{task:'x'.repeat(PLUGIN_TEAM_PLAN_MAX_JSON_CHARS)}})])
+ expect(()=>readPluginTaskPlanReceipt(payload)).toThrow('size');
+ f.rows.get(task.taskId)!.payload=JSON.stringify({teamPlan:plan});
+ await expect(f.service.settleWorkerLabel('p',task.taskId,'w0')).rejects.toMatchObject({code:'INVALID_REQUEST'});
+});
+
+it.each([false,true])('production Auto context checks uninstall after its projection await (worker=%s)', async worker => {
+ for (const revoked of [false,true]) {
+ const f=fixture(),task=await f.create();
+ const session={...f.route,source:'plugin',workingDir:'/answer',permissionMode:'auto',status:'active'};
+ const results=[[session],worker?[{leadId:task.taskId,label:'w',teamId:'team',teamStatus:'active'}]:[],[session]];
+ const query={from:()=>query,where:()=>query,innerJoin:()=>query,limit:async()=>results.shift()};
- const epoch={client:{drizzle:{select:()=>query},tx:async()=>{if(revoked)await f.service.withUninstall('p',async()=>{});return {};}}};
++ const epoch={client:{drizzle:{select:()=>query},queryOne:async()=>({unchanged:1}),tx:async()=>{if(revoked)await f.service.withUninstall('p',async()=>{});return {};}}};
+ let load!:(id:string)=>Promise<unknown>;
+ const deps={setAutoReviewContextResolver:(callback:typeof load)=>{load=callback;},createPluginTaskReviewResolver:(callback:typeof load)=>callback,
+ getCurrentDbClientSnapshot:()=>epoch,sessions:{},orcaWorkers:{},orcaTeams:{},eq:()=>true,
+ createPluginTaskStore:()=>f.deps.store,drainPersistQueue:async()=>{},
+ pluginTaskServiceForCurrentOwner:()=>f.service,readGhostErrandConfig:()=>({permissionMode:'auto'}),
+ readPluginTaskPlanReceipt,pluginTaskAuthorizationRevision:()=> 'new-install',isPluginTaskAuthorized:()=>true};
+ 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;
+ new Function(...Object.keys(deps),js)(...Object.values(deps));
+ if(revoked)await expect(load(worker?'worker':task.taskId)).rejects.toMatchObject({code:'TASK_NOT_FOUND'});
+ else await expect(load(worker?'worker':task.taskId)).resolves.toMatchObject({authorized:true,pluginId:'p'});
+ }
+});
function fixture() {
let seq = 0;
@@@ -656,8 -619,28 +656,29 @@@ it('a rejected operation does not poiso
});
+
describe('current plugin dispatch authority', () => {
+ it.each(['before', 'route', 'insert'])('blocks independent Plan Mode before dispatch at %s', async point => {
+ const f=fixture(), task=await f.create();
+ const enable=()=>Object.assign(f.tasks.get(task.taskId)!,{permissionMode:'auto',planModeEnabled:true});
+ if(point==='before') enable();
+ if(point==='route') f.deps.resolveRoute=async()=>{enable();return f.route;};
+ if(point==='insert') {const insert=f.deps.store.insert;f.deps.store.insert=async row=>{await insert(row);enable();};}
+ const send=f.service.send('p',{taskId:task.taskId,expectedRevision:task.revision,requestKey:'plan',text:'input'});
+ if(point==='insert') await expect(send).resolves.toMatchObject({status:'reconciling'});
+ else await expect(send).rejects.toMatchObject({code:'PERMISSION_DENIED'});
+ expect(f.deps.dispatch).not.toHaveBeenCalled();
+ });
+ it.each(['before', 'route', 'save'])('blocks queued acceptance after Plan Mode at %s but keeps inspection/cancel', async point => {
+ const f=fixture(), run=await f.send();
+ const enable=()=>Object.assign(f.tasks.get(run.taskId)!,{permissionMode:'acceptEdits',planModeEnabled:true});
+ if(point==='before') enable();
+ if(point==='route') f.deps.resolveRoute=async()=>{enable();return f.route;};
+ if(point==='save') {const save=f.deps.store.save;f.deps.store.save=async row=>{await save(row);enable();};}
+ await expect(f.service.accept(run.taskId,{clientId:run.inputMessageId},f.execution)).rejects.toMatchObject({code:'PERMISSION_DENIED'});
+ await expect(f.service.get('p',run.taskId)).resolves.toMatchObject({planModeEnabled:true});
+ await expect(f.service.cancel('p',run.runId)).resolves.toMatchObject({status:'cancelled'});
+ });
it.each(['plan', 'acceptEdits', 'auto'])('allows only authority within %s configuration', configured => {
const modes = ['plan', 'acceptEdits', 'auto'];
for (const mode of [...modes, 'bypassPermissions', 'unknown', undefined]) {
diff --cc apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
index 87a014626b,0000000000..b1404f5924
mode 100644,000000..100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
@@@ -1,132 -1,0 +1,133 @@@
+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; status: string; route: PluginTaskRoute };
- lead: { permissionMode: string; status: 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.');
+ // 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 1e9be7b3f6,bc14da6607..c20104185e
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -13497,67 -13467,8 +13500,90 @@@ 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');
+ 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
++ 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) = ?
++ 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]),
++ ]);
++ 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: approvalRevision !== null && isPluginTaskAuthorized(receipt.pluginId) && config.permissionMode === 'auto',
++ 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, status: session.status,
++ 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, status: lead.status },
++ lead: { permissionMode: lead.permissionMode, planModeEnabled: !!lead.planModeEnabled, status: lead.status },
+ ...(link ? { worker: { label: link.label ?? '', activeTeam: link.teamStatus === 'active' } } : {}),
+ 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 5b2485b87a,1aacd6a630..be2291cac1
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@@ -72,25 -72,3 +72,26 @@@ 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 只接受经绑定插件身份写入的自有创建收据;已登记计划整体不可变,包括原本缺失的范围。
+旧计划缺少范围时沿用原审批行为,不事后补造授权;新范围须在新任务中登记完整计划。
+没有新增权限档位、没有提升到 Full access。
+
+审批在查询缓存前重新核对插件批准版本、启用状态、Auto 设置、账号 epoch、任务状态、
- 团队归属和计划匹配;异步结果返回前再次核对。真实用户限制来自 Host 保存的作者凭据,
- 不从 Orca 消息、模型声称或工具参数恢复。缺少旧作者凭据时标注历史不完整,不猜测授权。
++团队归属和计划匹配;异步结果返回前再次核对。
++历史投影和归属读取完成后,以同一条只读 SQL 比较本次使用的任务/Lead 权限、独立 Plan、状态、路由目录、团队链接及计划收据;变化拒绝本次授权,查询失败保留 unavailable。Lead 或 Worker 已开启独立 Plan 时不恢复委派 Auto。
++真实用户限制来自 Host 保存的作者凭据,不从 Orca 消息、模型声称或工具参数恢复。缺少旧作者凭据时标注历史不完整,不猜测授权。
+插件文字放在独立 `delegatedTask` 字段,不能覆盖用户限制、跨题授权或声称自己是用户。
+直接派发和排队派发均保存受保护的 `delegated-continuation` 作者凭据;应用重启后从同一 Host 收据重建委派范围。
+自动恢复、上下文重建、系统触发及受保护续行共用合成消息判据,不追加旧授权,也不清除真人限制;增量摘要与完整重放一致。运行时摘要版本升为 3,旧版摘要首次读取从原消息自动重建,无需重新授权,不改历史 migration。
+
+明确带任务范围的所有动作(包括读取)均检查范围;不会仅凭工作目录安全而忽略插件的禁读条款。明确的 Host 续行凭据在 SQL 限量前过滤,避免频繁协调消息挤走真实用户限制;空字符串凭据仍保留,因为用户只发送附件时也可能没有文字。用户消息携带新资源时,沿用普通任务规则,先清除旧指代授权再追加该行可信原话;不以可编辑的 origin 判定作者。缺凭据的旧卡片保守标记历史不完整。
+
+验证入口:`pluginTaskReviewContext.test.ts`、`pluginTaskService.test.ts`、`taskSlot.test.ts`、
+`auto-review-context.test.ts`、Pi/Claude Code 审批接线回归以及 `eval-auto-approval.mts` 的
+`delegated-*` 正反对照(后者需要真实审阅模型,当前拆分 PR 未运行付费验证)。主机身份校验是确定性边界,动作与任务是否相符仍由 Auto 审阅,
+不宣称题目目录是系统沙箱。