diff --git a/v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts b/v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts new file mode 100644 index 0000000000..7188d07f88 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts @@ -0,0 +1,132 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +const state = vi.hoisted(() => ({ root: '' })); +vi.mock('node:os', async importOriginal => { + const actual = await importOriginal(); + return { ...actual, userInfo: () => ({ ...actual.userInfo(), homedir: state.root }) }; +}); +// Exercise the actual policy and caller-identity exports without loading +// unrelated password-hashing/native security dependencies in this fixture. +vi.mock('@claude-flow/security', async () => ({ + ...await import('../../security/src/policy/index.js'), + ...await import('../../security/src/mcp-caller-identity.js'), +})); +import { policyTools } from '../src/mcp-tools/policy-tools.js'; +import { loadPolicyState, setPolicyMode, upsertPolicyRule, verifyPolicyLedger } from '../src/services/policy-runtime.js'; +import { callMCPTool } from '../src/mcp-client.js'; +import { configTools } from '../src/mcp-tools/config-tools.js'; +import { DualModeOrchestrator, type WorkerConfig } from '../../codex/src/dual-mode/orchestrator.js'; +import { delegateEnvelope, type CapabilityEnvelope } from '../../security/src/policy/index.js'; +const evaluate = policyTools.find(t => t.name === 'policy_evaluate')!; +beforeEach(() => { state.root = mkdtempSync(join(tmpdir(), 'ruflo-envelope-meter-')); }); +afterEach(() => rmSync(state.root, { recursive: true, force: true })); + +async function asWorker(envelope: CapabilityEnvelope | undefined, action: () => Promise): Promise { + execFileSync('git', ['init', '-q', state.root]); + const orchestrator = new DualModeOrchestrator({ projectPath: state.root }) as unknown as { + workerEnvironment(worker: WorkerConfig): NodeJS.ProcessEnv; + }; + const environment = orchestrator.workerEnvironment({ + id: 'ordinary-worker', platform: 'codex', role: 'reader', prompt: 'inspect', + readOnly: true, capabilityEnvelope: envelope, + }); + const names = ['CLAUDE_FLOW_CAPABILITY_ENVELOPE', 'CLAUDE_FLOW_PRINCIPAL_ID', 'CLAUDE_FLOW_MCP_CALLER_AUTH'] as const; + const previous = names.map(name => process.env[name]); + const cwd = process.cwd(); + try { + process.chdir(state.root); + process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE = environment.CLAUDE_FLOW_CAPABILITY_ENVELOPE; + process.env.CLAUDE_FLOW_PRINCIPAL_ID = environment.CLAUDE_FLOW_PRINCIPAL_ID; + process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'false'; + await action(); + } finally { + process.chdir(cwd); + names.forEach((name, index) => { + if (previous[index] === undefined) delete process.env[name]; + else process.env[name] = previous[index]; + }); + } +} + +for (const mode of ['legacy', 'observe', 'enforce'] as const) { + describe(`${mode} public policy evaluation`, () => { + it.each(['maxCostUsd', 'maxTokens', 'maxConcurrency'])('does not bypass %s by omitting metering', async ceiling => { + await upsertPolicyRule({ id: 'allow-fixture', effect: 'allow', actions: ['*'] }, state.root); + await setPolicyMode(mode, state.root); + const result = await evaluate.handler({ request: { + identity: { id: 'agent:fixture', type: 'agent' }, + action: { type: 'memory.read', namespace: 'notes' }, + context: { envelope: { [ceiling]: 1 } }, + } }, { projectRoot: state.root }); + expect(result).toMatchObject({ outcome: 'denied', enforcedOutcome: 'denied' }); + expect(await verifyPolicyLedger(state.root)).toMatchObject({ valid: true }); + }); + it('permits explicitly metered zero-cost reads within zero ceilings', async () => { + await upsertPolicyRule({ id: 'allow-fixture', effect: 'allow', actions: ['*'] }, state.root); + await setPolicyMode(mode, state.root); + expect(await evaluate.handler({ request: { + identity: { id: 'agent:fixture', type: 'agent' }, + action: { type: 'memory.read', namespace: 'notes', costUsd: 0, tokens: 0, concurrency: 0 }, + context: { envelope: { maxCostUsd: 0, maxTokens: 0, maxConcurrency: 0 } }, + } }, { projectRoot: state.root })).toMatchObject({ enforcedOutcome: 'allowed' }); + }); + + it('admits an ordinary generated worker envelope through real MCP dispatch', async () => { + await upsertPolicyRule({ id: 'allow-fixture', effect: 'allow', actions: ['mcp.tool.call'] }, state.root); + await setPolicyMode(mode, state.root); + const tool = configTools.find(t => t.name === 'config_set')!; + const handler = vi.spyOn(tool, 'handler'); + try { + await asWorker(undefined, async () => { + await expect(callMCPTool('config_set', { key: 'workerProof', value: 'admitted' }, { projectRoot: state.root })) + .resolves.toMatchObject({ success: true }); + expect(handler).toHaveBeenCalledOnce(); + expect(readFileSync(join(state.root, '.claude-flow', 'config.json'), 'utf8')).toContain('admitted'); + const receipt = loadPolicyState(state.root).receipts.at(-1)!; + expect(receipt.payload.request.identity.id).toBe('agent:ordinary-worker'); + expect(receipt.payload.request.action.costUsd).toBeUndefined(); + expect(receipt.payload.request.action.tokens).toBeUndefined(); + expect(receipt.payload.request.action.concurrency).toBeUndefined(); + expect(receipt.payload.request.context?.envelope?.maxConcurrency).toBeUndefined(); + expect(receipt.payload.decision.enforcedOutcome).toBe('allowed'); + }); + } finally { + handler.mockRestore(); + } + }); + + it.each([ + ['maxCostUsd', 'cost-outside-envelope'], + ['maxTokens', 'tokens-outside-envelope'], + ['maxConcurrency', 'concurrency-outside-envelope'], + ] as const)('preserves an opted-in %s and denies an unmetered worker before its handler', async (ceiling, reason) => { + await upsertPolicyRule({ id: 'allow-fixture', effect: 'allow', actions: ['mcp.tool.call'] }, state.root); + await setPolicyMode(mode, state.root); + const tool = configTools.find(t => t.name === 'config_set')!; + const handler = vi.spyOn(tool, 'handler'); + const requested: CapabilityEnvelope = { actions: ['*'], [ceiling]: 1 }; + try { + await asWorker(requested, async () => { + await expect(callMCPTool('config_set', { key: 'workerProof', value: 'must-not-run' }, { projectRoot: state.root })) + .rejects.toThrow(reason); + expect(handler).not.toHaveBeenCalled(); + expect(existsSync(join(state.root, '.claude-flow', 'config.json'))).toBe(false); + const receipt = loadPolicyState(state.root).receipts.at(-1)!; + expect(receipt.payload.request.context?.envelope?.[ceiling]).toBe(1); + expect(receipt.payload.decision.enforcedOutcome).toBe('denied'); + }); + } finally { + handler.mockRestore(); + } + }); + }); +} + +it.each(['maxCostUsd', 'maxTokens', 'maxConcurrency'] as const)('retains an explicit %s during delegation', ceiling => { + const parent: CapabilityEnvelope = { actions: ['*'], [ceiling]: 1, delegationDepth: 1 }; + expect(delegateEnvelope(parent, { actions: ['memory.read'] })[ceiling]).toBe(1); + expect(() => delegateEnvelope(parent, { [ceiling]: 2 })).toThrow('capability-envelope-cannot-grow'); +}); diff --git a/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts b/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts index c844861d39..c98b82ebb4 100644 --- a/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts +++ b/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts @@ -85,7 +85,10 @@ describe('policy runtime compatibility and transactions', () => { expect(loadPolicyState(root).rules).toHaveLength(0); }); - it('enforces a spawned worker capability envelope at MCP dispatch', async () => { + it.each([ + { ceiling: {}, reason: 'network-outside-envelope' }, + { ceiling: { maxConcurrency: 1 }, reason: 'concurrency-outside-envelope' }, + ])('enforces a spawned worker envelope at MCP dispatch: $reason', async ({ ceiling, reason }) => { const root = project(); await autoMigratePolicyStateIfNeeded(root); await upsertPolicyRule({ id: 'allow-tools', effect: 'allow', actions: ['mcp.tool.call'] }, root); @@ -96,11 +99,11 @@ describe('policy runtime compatibility and transactions', () => { tools: ['*'], network: false, destructive: false, - maxConcurrency: 1, + ...ceiling, }); await expect(callMCPTool('terminal_execute', { command: 'echo should-not-run', - }, { projectRoot: root })).rejects.toThrow('network-outside-envelope'); + }, { projectRoot: root })).rejects.toThrow(reason); }); it('uses parent policy from an isolated git worktree', async () => { diff --git a/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts b/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts index 798e3ea265..bb0593d91a 100644 --- a/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts +++ b/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts @@ -20,6 +20,7 @@ export interface WorkerCapabilityEnvelope { actions?: string[]; resources?: string[]; tools?: string[]; + /** Opt-in per-tool ceiling: requires a trusted concurrency meter at dispatch. */ maxConcurrency?: number; network?: boolean; destructive?: boolean; @@ -561,7 +562,9 @@ Remember: Other agents depend on your results in shared memory. Be concise and s actions: ['*'], resources: ['*'], tools: ['*'], - maxConcurrency: 1, + // MCP dispatch does not yet supply a worker-wide concurrency meter. + // Leave this dimension unconstrained unless the caller opts in; the + // scheduler still bounds worker processes with config.maxConcurrent. network: false, destructive: false, delegationDepth: 0, diff --git a/v3/@claude-flow/security/__tests__/agentic-policy-engine.test.ts b/v3/@claude-flow/security/__tests__/agentic-policy-engine.test.ts index 4e474dddd9..53969caa8b 100644 --- a/v3/@claude-flow/security/__tests__/agentic-policy-engine.test.ts +++ b/v3/@claude-flow/security/__tests__/agentic-policy-engine.test.ts @@ -266,19 +266,22 @@ describe('CapabilityEnvelope', () => { resource: 'src/app.ts', tool: 'apply_patch', concurrency: 2, + costUsd: 0, }, parent, 1_000).allowed).toBe(true); expect(checkCapabilityEnvelope({ type: 'code.write', resource: 'src/app.ts', tool: 'apply_patch', network: true, + costUsd: 0, + concurrency: 1, }, parent, 1_000)).toEqual({ allowed: false, reason: 'network-outside-envelope' }); }); it('enforces delegated envelope boundaries even in legacy mode', () => { const engine = new AgenticPolicyEngine({ mode: 'legacy', now: () => 1_000 }); const decision = engine.evaluate(request({ - action: { type: 'code.write', resource: 'src/app.ts', tool: 'apply_patch', network: true }, + action: { type: 'code.write', resource: 'src/app.ts', tool: 'apply_patch', network: true, costUsd: 0, concurrency: 1 }, context: { envelope: parent }, })); expect(decision.outcome).toBe('denied'); diff --git a/v3/@claude-flow/security/src/policy/envelope.ts b/v3/@claude-flow/security/src/policy/envelope.ts index 4b3fb36e14..c28409571b 100644 --- a/v3/@claude-flow/security/src/policy/envelope.ts +++ b/v3/@claude-flow/security/src/policy/envelope.ts @@ -43,14 +43,14 @@ export function checkCapabilityEnvelope( : envelope.writeNamespaces; checks.push([matches(namespaces, action.namespace), 'namespace-outside-envelope']); } - if (action.costUsd !== undefined && envelope.maxCostUsd !== undefined) { - checks.push([action.costUsd <= envelope.maxCostUsd, 'cost-outside-envelope']); + if (envelope.maxCostUsd !== undefined) { + checks.push([action.costUsd !== undefined && action.costUsd <= envelope.maxCostUsd, 'cost-outside-envelope']); } - if (action.tokens !== undefined && envelope.maxTokens !== undefined) { - checks.push([action.tokens <= envelope.maxTokens, 'tokens-outside-envelope']); + if (envelope.maxTokens !== undefined) { + checks.push([action.tokens !== undefined && action.tokens <= envelope.maxTokens, 'tokens-outside-envelope']); } - if (action.concurrency !== undefined && envelope.maxConcurrency !== undefined) { - checks.push([action.concurrency <= envelope.maxConcurrency, 'concurrency-outside-envelope']); + if (envelope.maxConcurrency !== undefined) { + checks.push([action.concurrency !== undefined && action.concurrency <= envelope.maxConcurrency, 'concurrency-outside-envelope']); } if (action.network === true) checks.push([envelope.network === true, 'network-outside-envelope']); if (action.destructive === true) checks.push([envelope.destructive === true, 'destructive-outside-envelope']); diff --git a/v3/docs/adr/ADR-324-agentic-policy-engine-codex-swarm.md b/v3/docs/adr/ADR-324-agentic-policy-engine-codex-swarm.md index 74649df7fa..9c8b744598 100644 --- a/v3/docs/adr/ADR-324-agentic-policy-engine-codex-swarm.md +++ b/v3/docs/adr/ADR-324-agentic-policy-engine-codex-swarm.md @@ -80,6 +80,13 @@ Unmatched actions allow only in `legacy`; `observe` records default-deny but doe An envelope may constrain actions, resources, tools, MCP servers, read/write namespaces, environments, network/destructive access, cost, tokens, concurrency, expiry, and delegation depth. +Cost, token, and per-tool concurrency ceilings are opt-in: omit a dimension +when no trusted dispatch meter is available. An explicitly supplied ceiling +requires its meter, including in `legacy` and `observe` modes; missing usage +is not zero. Dual-mode workers do not receive an implicit per-tool concurrency +ceiling. The orchestrator's `maxConcurrent` scheduler limit still bounds worker +processes and does not measure concurrent MCP calls across those processes. + Every child envelope must be a monotonic reduction. A child cannot: - add a pattern not granted by its parent;