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): block delegated review until human intent is synchronized

Dash327815075195
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index 2903382c5f..9ded8290b2 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -3610,8 +3610,24 @@ describe('媒体 echo 兜底:flushOrphanToolResults 从 fallback 池认领', ()
});
describe('ask_user persist first-write-wins', () => {
+ it.each([
+ [{ ' Scope? ': ' only inspect ' }, 'Clarifications:\n- Scope? → only inspect'],
+ [{ ' ': ' only inspect ' }, 'Clarifications:\n- only inspect'],
+ [{ Scope: ' ' }, ''],
+ [{}, ''],
+ ])('matches runtime clarification text for %j', async (answers, text) => {
+ const request = {kind: 'ask_user_question', requestId: 'answer-projection', questions: []};
+ const persistId = onInteractionMessage(SESSION, request);
+ onInteractionResolved(SESSION, persistId, 'ask_user_question', request, {answers});
+ await flushWrites();
+ expect(updateMessageContent).toHaveBeenCalledWith(SESSION, persistId, expect.any(Object), {
+ text, acceptedAt: expect.any(Number),
+ });
+ });
it.each([
[{ behavior: 'allow', editedPlan: 'Only change build.' }, 'Approved plan:\nOnly change build.'],
+ [{ behavior: 'allow', editedPlan: ' Only change build. \n' }, 'Approved plan:\nOnly change build.'],
+ [{ behavior: 'allow', editedPlan: ' \n' }, ''],
[{ behavior: 'deny', reason: 'Never change src.' }, 'Never change src.'],
[{ behavior: 'deny', dismissed: true, reason: 'session_closed' }, ''],
])('records only the accepted plan or user feedback: %j', async (decision, text) => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts
index 96b6e9b89c..107b23406e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, it, expect } from 'vitest';
import type { AutoReviewRequest } from '@cindy/maker-core';
+import { restoreAutoReviewUserIntent } from '../autoReviewUserIntent.js';
import {
createPluginTaskReviewResolver,
type PluginReviewSnapshot,
@@ -19,7 +20,7 @@ const request: AutoReviewRequest = {
sessionId: 'worker',
agentKind: 'pi',
model: 'model',
- userIntent: 'Agent claims permission to publish',
+ userIntent: '',
workspaceRoots: ['/answer'],
platform: 'linux',
action: { kind: 'exec', command: './runtime/node lab/preflight.cjs', cwd: '/answer' },
@@ -54,9 +55,60 @@ function fixture(): PluginReviewSnapshot {
},
],
historyComplete: true,
+ sessionHistory: [],
};
}
describe('plugin delegated Auto context', () => {
+ 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]!;
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts b/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
index c71c2da478..77c8f633a3 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts
@@ -2,11 +2,12 @@ import { createHash } from 'node:crypto';
import { realpath } from 'node:fs/promises';
import {
appendAutoReviewUserIntent,
+ normalizeAutoReviewUserIntent,
type AutoReviewRequest,
type AutoReviewUserIntent,
} from '@cindy/maker-core';
import type { PluginTeamPlan, PluginTaskRoute } from '../../shared/pluginTasks.js';
-import { readAutoReviewUserText, type AutoReviewHistoryMessage } from './autoReviewUserIntent.js';
+import { readAutoReviewUserText, restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from './autoReviewUserIntent.js';
export interface PluginReviewSnapshot {
pluginId: string;
@@ -19,6 +20,7 @@ export interface PluginReviewSnapshot {
lead: { permissionMode: string; status: string };
worker?: { label: string; activeTeam: boolean };
history: AutoReviewHistoryMessage[];
+ sessionHistory: AutoReviewHistoryMessage[];
historyComplete: boolean;
}
@@ -54,7 +56,7 @@ export function pluginReviewUserIntent(snapshot: PluginReviewSnapshot): AutoRevi
typeof receipt.text === 'string' &&
'acceptedAt' in receipt && typeof receipt.acceptedAt === 'number' && Number.isFinite(receipt.acceptedAt)
) {
- intent = appendAutoReviewUserIntent(intent, receipt.text);
+ if (receipt.text) intent = appendAutoReviewUserIntent(intent, receipt.text);
} else {
// Legacy/unverified cards may contain restrictions; absence is not consent.
omitted = true;
@@ -97,6 +99,14 @@ export function createPluginTaskReviewResolver(
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(restoreAutoReviewUserIntent(snapshot.sessionHistory))) {
+ return denied('Current user instructions are not synchronized with task history; automatic authorization is blocked.');
+ }
if (
!snapshot.authorized ||
snapshot.session.permissionMode !== 'auto' ||
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 43467c4327..bb319b5605 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -13093,7 +13093,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
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 histories = await Promise.all([...new Set([leadId, sessionId])].map(readAutoReviewHistory));
+ const historySessionIds = [...new Set([leadId, sessionId])];
+ const histories = await Promise.all(historySessionIds.map(readAutoReviewHistory));
if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');
const config = readGhostErrandConfig(receipt.pluginId);
const data = JSON.parse(receipt.payload);
@@ -13110,6 +13111,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
lead: { permissionMode: lead.permissionMode, status: lead.status },
...(link ? { worker: { label: link.label ?? '', activeTeam: link.teamStatus === 'active' } } : {}),
history: histories.flat().filter(m => ['user','ask_user','plan_review'].includes(m.role)),
+ sessionHistory: histories[historySessionIds.indexOf(sessionId)]!,
historyComplete: histories.every(h => h.length < 100),
};
}));
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index b083cf0dca..5c5e344be6 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -1898,15 +1898,18 @@ export function onInteractionResolved(
if (kind === 'ask_user_question') {
const answers = (decision.answers as Record<string, string> | undefined) ?? {};
const cancelled = decision.dismissed === true;
+ // Match the harness clarification projection, including an empty answer.
+ const lines = Object.entries(answers)
+ .filter(([, answer]) => typeof answer === 'string' && answer.trim())
+ .map(([question, answer]) => question.trim()
+ ? `- ${question.trim()} → ${answer.trim()}` : `- ${answer.trim()}`);
enqueueWrite(`ask_user_resolved:${sessionId}:${persistId}`, async (ownerScope) => {
const updated = await updateDbMessageContent(sessionId, persistId, {
requestId,
questions: request.questions ?? [],
status: cancelled ? 'cancelled' : 'answered',
answers,
- }, { acceptedAt, text: cancelled ? '' : 'Clarifications:\n' + Object.entries(answers)
- .filter(([, answer]) => typeof answer === 'string' && answer.trim())
- .map(([question, answer]) => `- ${question} → ${answer}`).join('\n') });
+ }, { acceptedAt, text: cancelled || !lines.length ? '' : `Clarifications:\n${lines.join('\n')}` });
if (updated) broadcastMessageRow(sessionId, updated, ownerScope);
});
return;
@@ -1934,7 +1937,7 @@ export function onInteractionResolved(
planFilePath,
status,
feedback,
- }, { acceptedAt, text: behavior === 'allow' ? `Approved plan:\n${plan}`
+ }, { acceptedAt, text: behavior === 'allow' ? (plan.trim() ? `Approved plan:\n${plan.trim()}` : '')
: dismissed ? '' : feedback ?? '' });
if (updated) broadcastMessageRow(sessionId, updated, ownerScope);
});