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。

refactor(orca): 交付判定抽成纯函数,注入契约进 guard tier

Zhang Yunjin5b57f5a694e7
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaDeliveryWiring.contract.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaDeliveryWiring.contract.test.ts
new file mode 100644
index 0000000000..67f055b321
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaDeliveryWiring.contract.test.ts
@@ -0,0 +1,27 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+/**
+ * Cross-file wiring contract: queued acceptance and terminal-time retries must never get the
+ * round-scoped guard again. The behaviour of the scope itself is unit-tested; this guard only
+ * pins that production wiring still feeds it (removing the injection silently reverts the fix,
+ * because the service then falls back to the round guard).
+ */
+describe('Orca delivery authority wiring', () => {
+ const here = resolve(__dirname, '..');
+ const register = readFileSync(resolve(here, 'register.ts'), 'utf8');
+ const service = readFileSync(resolve(here, 'orcaTeamService.ts'), 'utf8');
+
+ it('injects the delivery guard into the Orca team service', () => {
+ expect(register).toMatch(
+ /captureDeliveryAuthority:\s*\(leadSessionId\)\s*=>\s*captureOrcaDeliveryAuthority\(leadSessionId\)/,
+ );
+ });
+
+ it('uses the delivery guard at acceptance and at deferred acknowledgement', () => {
+ expect(service).toMatch(/assertAcceptedCurrent\s*=\s*params\.assertDeliveryCurrent\s*\?\?\s*params\.assertCurrent/);
+ expect(service).toMatch(/assertDeliveryCurrent:\s*await deps\.captureDeliveryAuthority\?\.\(link\.leadSessionId\)/);
+ expect(service.match(/captureDeferredAuthority\(params\.callerLeadSessionId, opts\)/g)).toHaveLength(2);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index 614cede8a0..78fa53b78c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -8,7 +8,9 @@ import { AcceptedCallbackDispatchCancelled, runAcceptedCallback } from '../accep
import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue';
import {
+ captureOrcaDeliveryBaselines,
createOrcaTeamService,
+ evaluateOrcaDeliveryScope,
findFocusTargetWorker,
type DispatchWorkerMessageResult,
type OrcaTeamServiceDeps,
@@ -3797,144 +3799,78 @@ it('release closes under its own send fence and fails closed on close error',asy
expect(deps.archiveWorkerSession).not.toHaveBeenCalled();
});
-describe('Orca delivery authority', () => {
- // The delivery gate lives in register.ts. Slice it the same way the cleanup-authority
- // suite does: real source, fake host bindings.
- const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
- const start = source.indexOf(' const captureOrcaDeliveryAuthority = async (');
- const end = source.indexOf(' async function discardWorkerWorktree(', start);
-
- type Row = { status: string; clearedAt: number | null; permissionMode: string; planModeEnabled: boolean };
-
- function compile(initialLine: Row | null) {
- let line = initialLine;
- let live: unknown = null;
- const epoch = {
- client: {
- drizzle: {
- select: () => ({
- from: () => ({
- where: () => ({ limit: async () => (line ? [line] : []) }),
- }),
- }),
- },
- },
- };
- const bindings = {
- PluginTaskError,
- getCurrentDbClientSnapshot: () => epoch,
- createPluginTaskStore: () => ({ get: async () => undefined }),
- hasRevokedPluginTaskOwnership: () => false,
- sessions: {},
- eq: () => ({}),
- isAppSessionBoundaryPending: () => false,
- maker: { getSession: () => live },
- pluginTaskServiceForCurrentOwner: () => ({
- get: async () => ({ status: 'active', permissionMode: 'auto' }),
- }),
- assertPluginWorkerAutoAuthorized: () => undefined,
- };
- const factory = new Function(
- ...Object.keys(bindings),
- ts.transpileModule(`${source.slice(start, end)}
-return captureOrcaDeliveryAuthority;`, {
- compilerOptions: { target: ts.ScriptTarget.ES2022 },
- }).outputText,
- )(...Object.values(bindings)) as (leadSessionId: string) => Promise<() => Promise<void>>;
- return {
- setLive: (session: unknown) => {
- live = session;
- },
- setLine: (next: Row | null) => {
- line = next;
- },
- authorize: () => factory('lead-1'),
- };
- }
-
- const permission = (mode: string, generation: number, plan = false) => ({
- stablePermissionModeState: { mode, generation },
- stablePlanModeState: { enabled: plan, generation },
- });
- const row = (overrides: Partial<Row> = {}): Row => ({
+describe('Orca delivery scope', () => {
+ const permission = (mode: string, planEnabled = false) => ({ mode, planEnabled });
+ const row = (overrides: Partial<{
+ status: string; clearedAt: number | null; permissionMode: string; planModeEnabled: boolean;
+ }> = {}) => ({
status: 'active',
clearedAt: 100,
permissionMode: 'bypassPermissions',
planModeEnabled: false,
...overrides,
});
-
- it('accepts a rehydrated runtime whose permission counters restarted', async () => {
- const h = compile(row());
- h.setLive(permission('bypassPermissions', 3));
- const assertDelivery = await h.authorize();
-
- // Idle release + rehydrate: a new Session instance restarts its in-memory generations.
- h.setLive(permission('bypassPermissions', 0));
- await expect(assertDelivery()).resolves.toBeUndefined();
-
- // A released runtime is not a revocation on its own: the persisted mode still matches.
- h.setLive(null);
- await expect(assertDelivery()).resolves.toBeUndefined();
+ const live = (mode: string, planEnabled = false) => ({
+ stablePermissionModeState: { mode },
+ stablePlanModeState: { enabled: planEnabled },
+ });
+ const evaluate = (
+ overrides: Partial<Parameters<typeof evaluateOrcaDeliveryScope>[0]> = {},
+ ) => evaluateOrcaDeliveryScope({
+ clearedAtAtCapture: 100,
+ persistedAtCapture: permission('bypassPermissions'),
+ liveAtCapture: permission('bypassPermissions'),
+ row: row(),
+ live: live('bypassPermissions'),
+ ...overrides,
});
- it('keeps a resumed runtime mode that the persisted row does not carry', async () => {
- // A cold resume can run a stricter/looser mode than the row without rewriting it.
- const h = compile(row({ permissionMode: 'ask' }));
- h.setLive(permission('bypassPermissions', 1));
- const assertDelivery = await h.authorize();
-
- // Idle release: the row still says ask, and the user changed nothing.
- h.setLive(null);
- await expect(assertDelivery()).resolves.toBeUndefined();
+ it('accepts a rehydrated runtime and a released one', () => {
+ // Idle release + rehydrate keeps the same semantics; in-memory generation counters are
+ // intentionally not part of the comparison.
+ expect(evaluate({ live: live('bypassPermissions') })).toBe('ok');
+ expect(evaluate({ live: null })).toBe('ok');
});
- it('rejects delivery while the owner is switching permissions or when the mode changed', async () => {
- const h = compile(row());
- h.setLive(permission('bypassPermissions', 3));
- const assertDelivery = await h.authorize();
-
- // Mid-switch: the stable snapshots disappear. Work must not start on the old snapshot.
- h.setLive({
- stablePermissionModeState: null,
- stablePlanModeState: { enabled: false, generation: 0 },
+ it('captures the two permission baselines from their own sources', () => {
+ expect(captureOrcaDeliveryBaselines({
+ row: row({ permissionMode: 'ask' }),
+ live: live('bypassPermissions'),
+ })).toEqual({
+ clearedAtAtCapture: 100,
+ persistedAtCapture: { mode: 'ask', planEnabled: false },
+ liveAtCapture: { mode: 'bypassPermissions', planEnabled: false },
});
- await expect(assertDelivery()).rejects.toThrow('Task permissions are changing');
-
- h.setLive(permission('ask', 0));
- await expect(assertDelivery()).rejects.toThrow('Task permissions changed before delivery');
-
- h.setLive(permission('bypassPermissions', 0, true));
- await expect(assertDelivery()).rejects.toThrow('Task permissions changed before delivery');
});
- it('compares the persisted mode when the runtime is gone', async () => {
- const h = compile(row());
- h.setLive(permission('bypassPermissions', 3));
- const assertDelivery = await h.authorize();
- h.setLive(null);
-
- h.setLine(row({ permissionMode: 'ask' }));
- await expect(assertDelivery()).rejects.toThrow('Task permissions changed before delivery');
-
- h.setLine(row({ planModeEnabled: true }));
- await expect(assertDelivery()).rejects.toThrow('Task permissions changed before delivery');
+ it('keeps a resumed runtime mode that the persisted row does not carry', () => {
+ // Cold resume can run a mode the row never recorded; releasing the runtime must not turn
+ // that into a revocation.
+ expect(evaluate({
+ row: row({ permissionMode: 'ask' }),
+ persistedAtCapture: permission('ask'),
+ liveAtCapture: permission('bypassPermissions'),
+ live: null,
+ })).toBe('ok');
});
- it('rejects delivery when the task really changed', async () => {
- const h = compile(row());
- h.setLive(permission('bypassPermissions', 3));
- const assertDelivery = await h.authorize();
-
- h.setLive(permission('bypassPermissions', 0));
- h.setLine(row({ clearedAt: 200 }));
- await expect(assertDelivery()).rejects.toThrow('Orca task is no longer deliverable');
+ it('rejects a switch in flight or a changed permission', () => {
+ expect(evaluate({
+ live: { stablePermissionModeState: null, stablePlanModeState: { enabled: false } },
+ })).toBe('permissions-changing');
+ expect(evaluate({ live: live('ask') })).toBe('permissions-changed');
+ expect(evaluate({ live: live('bypassPermissions', true) })).toBe('permissions-changed');
+ });
- h.setLine(null);
- await expect(assertDelivery()).rejects.toThrow('Orca task is no longer deliverable');
+ it('compares the persisted mode when the runtime is gone', () => {
+ expect(evaluate({ live: null, row: row({ permissionMode: 'ask' }) })).toBe('permissions-changed');
+ expect(evaluate({ live: null, row: row({ planModeEnabled: true }) })).toBe('permissions-changed');
+ expect(evaluate({ live: null, persistedAtCapture: null })).toBe('permissions-changed');
});
- it('is wired into the Orca team service', () => {
- expect(source).toMatch(/captureDeliveryAuthority:\s*\(leadSessionId\)\s*=>/);
+ it('rejects a task that was cleared, deleted or removed', () => {
+ expect(evaluate({ row: row({ clearedAt: 200 }) })).toBe('task-gone');
+ expect(evaluate({ row: row({ status: 'deleted' }) })).toBe('task-gone');
+ expect(evaluate({ row: null })).toBe('task-gone');
});
});
diff --git a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
index b95a137e82..6dd4a97ef9 100644
--- a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
@@ -268,6 +268,82 @@ export interface WorkerTerminalTurnCapture {
autoBridgeIdentity: object | null;
}
+export interface OrcaDeliveryPermissionBaseline {
+ mode: string;
+ planEnabled: boolean;
+}
+
+export interface OrcaDeliverySessionRowSnapshot {
+ status: string;
+ clearedAt: number | null;
+ permissionMode: string;
+ planModeEnabled: boolean;
+}
+
+export interface OrcaDeliveryLiveSnapshot {
+ stablePermissionModeState: { mode: string | null } | null;
+ stablePlanModeState: { enabled: boolean } | null;
+}
+
+export type OrcaDeliveryVerdict = 'ok' | 'task-gone' | 'permissions-changing' | 'permissions-changed';
+
+/**
+ * Baselines captured at admission, each tagged with the source it belongs to: a resumed runtime
+ * can run a permission mode the persisted row does not carry, so they must never be shared.
+ */
+export function captureOrcaDeliveryBaselines(input: {
+ row: OrcaDeliverySessionRowSnapshot | null;
+ live: OrcaDeliveryLiveSnapshot | null;
+}): {
+ clearedAtAtCapture: number | null;
+ persistedAtCapture: OrcaDeliveryPermissionBaseline | null;
+ liveAtCapture: OrcaDeliveryPermissionBaseline | null;
+} {
+ const livePermission = input.live?.stablePermissionModeState;
+ const livePlan = input.live?.stablePlanModeState;
+ return {
+ clearedAtAtCapture: input.row?.clearedAt ?? null,
+ persistedAtCapture: input.row
+ ? { mode: input.row.permissionMode, planEnabled: input.row.planModeEnabled }
+ : null,
+ liveAtCapture: livePermission?.mode && livePlan
+ ? { mode: livePermission.mode, planEnabled: livePlan.enabled }
+ : null,
+ };
+}
+
+/**
+ * Delivery-scope decision for a dispatch accepted after the caller's turn ended.
+ * Durable facts only, and each permission baseline is compared against its own source: a resumed
+ * runtime may run a mode the persisted row does not carry, so mixing baselines cancels valid work.
+ */
+export function evaluateOrcaDeliveryScope(input: {
+ /** Cleared boundary captured at admission (`null` when the row was already missing). */
+ clearedAtAtCapture: number | null;
+ persistedAtCapture: OrcaDeliveryPermissionBaseline | null;
+ liveAtCapture: OrcaDeliveryPermissionBaseline | null;
+ row: OrcaDeliverySessionRowSnapshot | null;
+ live: OrcaDeliveryLiveSnapshot | null;
+}): OrcaDeliveryVerdict {
+ const { row, live } = input;
+ if (!row || row.status === 'deleted' || row.clearedAt !== input.clearedAtAtCapture) return 'task-gone';
+ if (live) {
+ const permission = live.stablePermissionModeState;
+ const plan = live.stablePlanModeState;
+ // A permission/Plan switch in flight is a live revocation: never start work on the old one.
+ if (!permission?.mode || !plan) return 'permissions-changing';
+ if (!input.liveAtCapture
+ || permission.mode !== input.liveAtCapture.mode
+ || plan.enabled !== input.liveAtCapture.planEnabled) return 'permissions-changed';
+ return 'ok';
+ }
+ // A released runtime is not a revocation by itself, but the row is then the only authority.
+ if (!input.persistedAtCapture
+ || row.permissionMode !== input.persistedAtCapture.mode
+ || row.planModeEnabled !== input.persistedAtCapture.planEnabled) return 'permissions-changed';
+ return 'ok';
+}
+
/** service 的 I/O 边界。register.ts 只负责把 DB、Maker、IPC broadcast 作为依赖组合进来。 */
export interface OrcaTeamServiceDeps {
captureControlAuthority?(leadSessionId: string): Promise<() => Promise<void>>;
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 76a95469af..bc2d5d08cf 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -991,7 +991,9 @@ import {
} from './orcaUiAssignmentHistoryGate.js';
import { orcaModelDiscoveryFailure, throwOrcaServiceFailure } from './orcaServiceFailure.js';
import {
+ captureOrcaDeliveryBaselines,
createOrcaTeamService,
+ evaluateOrcaDeliveryScope,
findFocusTargetWorker,
type InterruptWorkerResult,
type ListWorkerQueuedMessagesResult,
@@ -15505,20 +15507,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return row ?? null;
};
const sessionAtCapture = await readSessionRow();
- const liveAtCapture = maker.getSession(leadSessionId);
- // Two baselines, each compared against its own source: a resumed runtime can run a
- // permission mode the row does not carry (and the row is not rewritten for it), so mixing
- // them would cancel a valid dispatch after the runtime is released. Instance generation
- // counters restart on rehydrate, so only the semantics are ever compared.
- const livePermissionAtCapture = liveAtCapture?.stablePermissionModeState && liveAtCapture.stablePlanModeState
- ? {
- mode: liveAtCapture.stablePermissionModeState.mode,
- planEnabled: liveAtCapture.stablePlanModeState.enabled,
- }
- : null;
- const persistedPermissionAtCapture = sessionAtCapture
- ? { mode: sessionAtCapture.permissionMode, planEnabled: sessionAtCapture.planModeEnabled }
- : null;
+ const baselines = captureOrcaDeliveryBaselines({
+ row: sessionAtCapture,
+ live: maker.getSession(leadSessionId) ?? null,
+ });
return async () => {
if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
if (isAppSessionBoundaryPending()) throw new PluginTaskError('HOST_NOT_READY', 'Account is switching');
@@ -15526,27 +15518,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const currentPluginId = current?.operation === 'create' && !hasRevokedPluginTaskOwnership(current) ? current.pluginId : null;
if (epoch !== getCurrentDbClientSnapshot() || currentPluginId !== pluginId) throw new PluginTaskError('PERMISSION_DENIED', 'Orca task ownership changed');
const row = await readSessionRow();
- if (!row || row.status === 'deleted' || row.clearedAt !== (sessionAtCapture?.clearedAt ?? null))
+ const verdict = evaluateOrcaDeliveryScope({
+ ...baselines,
+ row,
+ live: maker.getSession(leadSessionId) ?? null,
+ });
+ if (verdict === 'task-gone')
throw new PluginTaskError('PERMISSION_DENIED', 'Orca task is no longer deliverable');
- const live = maker.getSession(leadSessionId);
- if (live) {
- const permission = live.stablePermissionModeState;
- const plan = live.stablePlanModeState;
- // A permission/Plan switch in flight is a live revocation: never start work on the old
- // snapshot while the owner is changing it.
- if (!permission || !plan)
- throw new PluginTaskError('PERMISSION_DENIED', 'Task permissions are changing');
- if (!livePermissionAtCapture
- || permission.mode !== livePermissionAtCapture.mode
- || plan.enabled !== livePermissionAtCapture.planEnabled)
- throw new PluginTaskError('PERMISSION_DENIED', 'Task permissions changed before delivery');
- } else if (!persistedPermissionAtCapture
- || row.permissionMode !== persistedPermissionAtCapture.mode
- || row.planModeEnabled !== persistedPermissionAtCapture.planEnabled) {
- // An absent runtime is released or not rehydrated yet, not a revocation by itself —
- // but the persisted row is then the only authority left to compare against.
+ if (verdict === 'permissions-changing')
+ throw new PluginTaskError('PERMISSION_DENIED', 'Task permissions are changing');
+ if (verdict === 'permissions-changed')
throw new PluginTaskError('PERMISSION_DENIED', 'Task permissions changed before delivery');
- }
if (pluginId === null) return;
const task = await pluginTaskServiceForCurrentOwner!().get(pluginId, leadSessionId);
if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index 50caa20f01..6aa89aab17 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -157,6 +157,8 @@ const desktopGuardInclude = [
'src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts',
'src/main/__tests__/discordExternalization.test.ts',
'src/main/__tests__/sessionRuntimeControlWiring.test.ts',
+ // Orca queued acceptance must keep using delivery-scoped authority, not the round guard.
+ 'src/main/maker-ipc/__tests__/orcaDeliveryWiring.contract.test.ts',
'src/main/localDb/ipc/__tests__/sessionCreatedBroadcast.test.ts',
'src/renderer/__tests__/promptRecommendationBadge.test.ts',
'src/renderer/__tests__/sessionHeaderMenuParity.test.ts',