From d216230a74b31219d065b0160d89a4d5784421b3 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 27 Sep 2026 13:22:21 -0400 Subject: [PATCH 1/5] fix(policy): require metering for explicit envelope ceilings --- .../policy-envelope-metering.test.ts | 44 +++++++++++++++++++ .../__tests__/agentic-policy-engine.test.ts | 5 ++- .../security/src/policy/envelope.ts | 12 ++--- 3 files changed, 54 insertions(+), 7 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts 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..9f5bd27154 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts @@ -0,0 +1,44 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +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 { setPolicyMode, upsertPolicyRule, verifyPolicyLedger } from '../src/services/policy-runtime.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 })); +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' }); + }); + }); +} 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']); From 261a3f4d386b9f417575091b19a491a43831ac9a Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 27 Sep 2026 10:30:40 -0400 Subject: [PATCH 2/5] test(memory): register one search mock factory per case --- .../__tests__/memory-search-scores-3327.test.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/v3/@claude-flow/cli/__tests__/memory-search-scores-3327.test.ts b/v3/@claude-flow/cli/__tests__/memory-search-scores-3327.test.ts index cefc6ee3a3..a28894a49f 100644 --- a/v3/@claude-flow/cli/__tests__/memory-search-scores-3327.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-search-scores-3327.test.ts @@ -25,7 +25,11 @@ interface SearchResponse { smartFallback?: string; stats?: { variantCount: number; rawCandidateCount: number }; } +let memoryModuleFactory: () => object | Promise; async function search(input: Record): Promise { + // Register once per search: two queued doMock calls for this resolved ID + // can finish out of order while Vite resolves their module IDs. + vi.doMock('/@id/@claude-flow/memory', memoryModuleFactory); const { memoryTools } = await import('../src/mcp-tools/memory-tools.js'); return memoryTools.find(t => t.name === 'memory_search')!.handler(input) as Promise; } @@ -37,7 +41,7 @@ beforeEach(() => { // are faked; this exercises the real MCP handler and its response whitelist. // The CLI's externalize-optional-deps plugin rewrites this dynamic import // to /@id/...; mock that resolved ID so Vitest 4 intercepts the import. - vi.doMock('/@id/@claude-flow/memory', async () => import('../../memory/src/smart-retrieval.js')); + memoryModuleFactory = async () => import('../../memory/src/smart-retrieval.js'); }); afterEach(() => vi.restoreAllMocks()); @@ -108,10 +112,10 @@ describe('memory_search score contract (#3327 Finding B)', () => { }); it.each(['missing export', 'import failure'])('preserves standard fallback on %s', async (reason) => { - vi.doMock('/@id/@claude-flow/memory', () => { + memoryModuleFactory = () => { if (reason === 'import failure') throw new Error('unavailable package'); return { smartSearch: undefined }; - }); + }; searchEntries.mockResolvedValue({ success: true, results: [entry('a', 0.49)] }); const result = await search({ query: 'alpha', smart: true }); expect(result.results).toEqual([{ @@ -123,14 +127,14 @@ describe('memory_search score contract (#3327 Finding B)', () => { }); it('supplies rawScore to older SmartRetrieval implementations that preserve candidate fields', async () => { - vi.doMock('/@id/@claude-flow/memory', () => ({ + memoryModuleFactory = () => ({ // The existing return projection is {...candidate, score}. This fake // deliberately does not create rawScore: the MCP adapter must supply it. smartSearch: async (rawSearch: (request: RawSearchRequest) => Promise<{ results: object[] }>) => { const raw = await rawSearch({ query: 'alpha' }); return { results: raw.results.map(r => ({ ...r, score: 0.05 })), stats: {} }; }, - })); + }); searchEntries.mockResolvedValue({ success: true, results: [entry('a', 0)] }); const result = await search({ query: 'alpha', smart: true, threshold: 0 }); expect(result.results[0].similarity).toBe(0); From 66a232cc6701e0deef261184389991c208a18bc6 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 27 Sep 2026 10:30:32 -0400 Subject: [PATCH 3/5] test(security): guarantee comparison fixtures differ --- .../security/__tests__/token-generator.test.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/v3/@claude-flow/security/__tests__/token-generator.test.ts b/v3/@claude-flow/security/__tests__/token-generator.test.ts index 93c55b148f..5086299ac3 100644 --- a/v3/@claude-flow/security/__tests__/token-generator.test.ts +++ b/v3/@claude-flow/security/__tests__/token-generator.test.ts @@ -306,14 +306,12 @@ describe('TokenGenerator', () => { expect(generator.compare('short', 'longer-token')).toBe(false); }); - it('should use timing-safe comparison', () => { - // This test verifies the comparison takes consistent time - // regardless of where the mismatch occurs - const token = generator.generate(); - const mismatchEarly = 'X' + token.slice(1); - const mismatchLate = token.slice(0, -1) + 'X'; + it.each(['X' + 'a'.repeat(41) + 'X', 'Y' + 'a'.repeat(41) + 'Y'])( + 'should reject early and late byte mismatches for %s', (token) => { + const mismatchEarly = (token[0] === 'X' ? 'Y' : 'X') + token.slice(1); + const mismatchLate = token.slice(0, -1) + (token.at(-1) === 'X' ? 'Y' : 'X'); - // Both comparisons should work (timing consistency is internal) + // Change a byte even when the original already begins or ends with X. expect(generator.compare(token, mismatchEarly)).toBe(false); expect(generator.compare(token, mismatchLate)).toBe(false); }); From 8912954947d818d43835c9bb889ff1b5a411d63e Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 27 Sep 2026 14:51:46 -0400 Subject: [PATCH 4/5] test(policy): distinguish missing metering from network denial --- v3/@claude-flow/cli/__tests__/policy-runtime.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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 () => { From dbdceb6184b9ede2c03ac4dadcd838f094c12895 Mon Sep 17 00:00:00 2001 From: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:10:23 -0400 Subject: [PATCH 5/5] fix(policy): keep unmetered worker ceilings opt-in Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> --- .../policy-envelope-metering.test.ts | 92 ++++++++++++++++++- .../codex/src/dual-mode/orchestrator.ts | 5 +- ...R-324-agentic-policy-engine-codex-swarm.md | 7 ++ 3 files changed, 101 insertions(+), 3 deletions(-) diff --git a/v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts b/v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts index 9f5bd27154..7188d07f88 100644 --- a/v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts +++ b/v3/@claude-flow/cli/__tests__/policy-envelope-metering.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { mkdtempSync, rmSync } from 'node:fs'; +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: '' })); @@ -14,10 +15,42 @@ vi.mock('@claude-flow/security', async () => ({ ...await import('../../security/src/mcp-caller-identity.js'), })); import { policyTools } from '../src/mcp-tools/policy-tools.js'; -import { setPolicyMode, upsertPolicyRule, verifyPolicyLedger } from '../src/services/policy-runtime.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 => { @@ -40,5 +73,60 @@ for (const mode of ['legacy', 'observe', 'enforce'] as const) { 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/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/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;