Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat: add ADR-324 agentic policy engine (#2822)

rUv495a451cf6f2
diff --git a/.github/workflows/no-metaharness-smoke.yml b/.github/workflows/no-metaharness-smoke.yml
index 7858c0a9aa..b4b625a39e 100644
--- a/.github/workflows/no-metaharness-smoke.yml
+++ b/.github/workflows/no-metaharness-smoke.yml
@@ -96,10 +96,11 @@ jobs:
# assert exit code 0 + degraded:true JSON.
run: |
set -e
- # Use an unresolvable npm registry so `npx metaharness@latest`
- # cannot fetch the package. The skills should detect this and
- # emit the degraded payload.
- export npm_config_registry=https://no-such-registry-9c8c43.example.invalid/
+ # Use a closed local port so `npx metaharness@latest` fails
+ # deterministically without waiting on DNS or network retries.
+ # The skills should detect this and emit the degraded payload.
+ export npm_config_registry=http://127.0.0.1:9/
+ export npm_config_fetch_retries=0
# Disable network-cache to ensure the npx miss is fresh
export NPX_NO_LOCAL=1
# Since the pinned-cache resolution (_invoke.mjs), skills no longer
@@ -129,8 +130,10 @@ jobs:
for skill in score genome mcp-scan threat-model oia-audit mint drift-from-history; do
echo "--- exercising ${skill}.mjs with unreachable registry ---"
ARGS="${SKILL_ARGS[$skill]}"
- OUT=$(node plugins/ruflo-metaharness/scripts/$skill.mjs $ARGS 2>&1 || echo '__NON_ZERO_EXIT__')
- EXIT=$(node plugins/ruflo-metaharness/scripts/$skill.mjs $ARGS > /dev/null 2>&1; echo $?)
+ set +e
+ OUT=$(node plugins/ruflo-metaharness/scripts/$skill.mjs $ARGS 2>&1)
+ EXIT=$?
+ set -e
echo "$OUT" | head -10
echo "exit: $EXIT"
# Assert: graceful path means exit 0 (or 3 for drift-from-history
diff --git a/AGENTS.md b/AGENTS.md
index a8267d2e1b..da92baa1f1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -26,6 +26,43 @@
---
+## Ruflo Policy-Governed Concurrent Codex Workflow
+
+Ruflo is the coordination ledger and policy decision point. Codex agents are
+the executors. Coordination records do not write code or run tests.
+
+1. Search AgentDB memory before planning.
+2. Initialize one bounded hierarchical swarm.
+3. Fan out only independent tasks.
+4. Give every writing agent a separate git worktree and a reduced capability
+ envelope; read-only agents may share a checkout.
+5. Assign one owner for shared manifests and lockfiles.
+6. Integrate committed handoffs in dependency order, then run scoped and full
+ verification.
+7. Store the successful pattern and retain the policy/MetaHarness receipts.
+
+Hard invariants:
+
+- Never run two writers in one worktree.
+- Delegation may only reduce tools, servers, namespaces, network, spend,
+ concurrency, expiry, and depth.
+- Policy denial cancels dependent work before side effects.
+- MetaHarness may evaluate candidates concurrently, but only ADR-322A may
+ promote them and MetaHarness may never expand its own SafetyEnvelope.
+- Do not commit, push, merge, release, or remove worktrees unless authorized.
+- Existing installations migrate in `legacy` policy mode; use `observe` before
+ switching to `enforce`.
+
+Useful checks:
+
+```bash
+npx ruflo policy status
+npx ruflo policy verify
+npx ruflo metaharness flywheel status
+```
+
+---
+
## 🚨 CRITICAL: CODEX DOES THE WORK, CLAUDE-FLOW ORCHESTRATES
```
diff --git a/CLAUDE.md b/CLAUDE.md
index 42a81ff911..9a0b489d82 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1167,13 +1167,13 @@ curl -s "https://gateway.pinata.cloud/ipfs/{NEW_CID}" | jq '.totalPlugins'
## MetaHarness Integration (ADR-150)
-Ruflo integrates with the upstream `metaharness` / `@metaharness/*` ecosystem as a sibling agent-harness scaffolding system (same author, designed around ruflo's primitives). Both `metaharness` and `@metaharness/router` are in `optionalDependencies` β€” never required at runtime.
+Ruflo integrates with the upstream `metaharness` / `@metaharness/*` ecosystem as a sibling agent-harness scaffolding system (same author, designed around ruflo's primitives). MetaHarness packages are optional peer dependencies and are never required at runtime.
### Architectural constraint (load-bearing)
**Ruflo remains operational if every MetaHarness package is removed.** Four rules:
1. **Removable**: `npm ls --without @metaharness/*` must still produce a working CLI
-2. **Optional in package.json**: `@metaharness/*` packages MUST be in `optionalDependencies`, never in `dependencies`
+2. **Optional in package.json**: `@metaharness/*` packages MUST be optional peers, never normal dependencies
3. **Graceful degradation**: every code path that touches MetaHarness catches `MODULE_NOT_FOUND` and falls back
4. **CI gate**: `.github/workflows/no-metaharness-smoke.yml` enforces all three by static grep + runtime drill on every PR
@@ -1221,6 +1221,16 @@ npx ruflo metaharness gepa --op genome # [email protected] GEPA library β€”
npx ruflo metaharness gepa --op render # genome β†’ the system prompt it compiles to
npx ruflo metaharness gepa --op analyze --transcript run.json
# classify failure modes in a transcript
+npx ruflo metaharness evolve --bench .harness/bench.json
+ # Darwin proposes candidates; governed gates decide
+npx ruflo metaharness bench verify --path .harness/bench.json
+ # create or verify stable benchmark corpora
+npx ruflo metaharness flywheel run --proposer auto --max-concurrency 2
+ # bounded concurrent evaluation; does not promote
+npx ruflo metaharness flywheel receipts # inspect immutable evaluation receipts
+npx ruflo metaharness flywheel promote <receipt-id> \
+ --public-key ./approved-ed25519-public.pem --confirm
+ # explicit policy-authorized atomic promotion
# Dedicated command
npx ruflo eject --name my-harness # lift ruflo project β†’ standalone harness
@@ -1245,6 +1255,7 @@ mcp__claude-flow__metaharness_security_bench # security-focused benchmark s
mcp__claude-flow__metaharness_redblue # @metaharness/redblue β€” adversarial red/blue LLM testing (init|run|patch|attack|report)
mcp__claude-flow__metaharness_learn # [email protected] β€” GEPA learning run ($0 dry-run default; run=true to spend)
mcp__claude-flow__metaharness_gepa # [email protected] β€” GEPA genome ops (genome|validate|render|analyze); gepaOptimize stays library-only
+mcp__claude-flow__metaharness_flywheel # ADR-322 β€” evaluate concurrently, inspect receipts/ledger, or explicitly promote
```
### Routing integration (ADR-148/149)
diff --git a/plugins/ruflo-metaharness/scripts/smoke.sh b/plugins/ruflo-metaharness/scripts/smoke.sh
index 6eadb353e3..981d716c23 100755
--- a/plugins/ruflo-metaharness/scripts/smoke.sh
+++ b/plugins/ruflo-metaharness/scripts/smoke.sh
@@ -21,6 +21,7 @@ TOOLS_SRC="$ROOT/../../v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts"
SUBS_SRC="$ROOT/../../v3/@claude-flow/cli/src/commands/metaharness.ts"
EXPECTED_TOOLS=$(grep -cE "name: 'metaharness_" "$TOOLS_SRC" 2>/dev/null; true)
EXPECTED_SUBS=$(grep -cE "^[[:space:]]+'?[a-z-]+'?:[[:space:]]*'[a-z-]+\.mjs'" "$SUBS_SRC" 2>/dev/null; true)
+EXPECTED_IN_PROCESS_TOOLS=1 # ADR-322 metaharness_flywheel
: "${EXPECTED_TOOLS:=0}"
: "${EXPECTED_SUBS:=0}"
@@ -883,11 +884,17 @@ for f in $REFS; do
COUNT=$((COUNT + 1))
[[ -f "$SCRIPTS_DIR/$f" ]] || miss="$miss mcp-script-${f}-missing"
done
-# One unique runScript() ref per MCP tool (mint deliberately excluded).
+# One unique runScript() ref per subprocess-backed MCP tool (mint deliberately
+# excluded). ADR-322's metaharness_flywheel is intentionally in-process so
+# evaluation cancellation and atomic promotion share the CLI transaction code.
# Cross-aspect check: runScript('*.mjs') call sites vs the derived
-# `name: 'metaharness_*'` declaration count in the same file β€” a handler
-# added without a script ref (or vice-versa) diverges these.
-[[ "$COUNT" == "$EXPECTED_TOOLS" ]] || miss="$miss mcp-script-count-stale:$COUNT-expected-$EXPECTED_TOOLS"
+# `name: 'metaharness_*'` declaration count minus the explicitly governed
+# in-process surface.
+EXPECTED_SCRIPT_TOOLS=$((EXPECTED_TOOLS - EXPECTED_IN_PROCESS_TOOLS))
+[[ "$COUNT" == "$EXPECTED_SCRIPT_TOOLS" ]] || miss="$miss mcp-script-count-stale:$COUNT-expected-$EXPECTED_SCRIPT_TOOLS"
+grep -q "name: 'metaharness_flywheel'" "$WRAPPER" 2>/dev/null || miss="$miss no-in-process-flywheel"
+grep -q "runFlywheelWorker" "$WRAPPER" 2>/dev/null || miss="$miss no-flywheel-evaluator"
+grep -q "promoteFlywheelCandidate" "$WRAPPER" 2>/dev/null || miss="$miss no-flywheel-promoter"
[[ -z "$miss" ]] && ok || bad "$miss"
step "17z52. SUBCOMMANDS map entries point at existing script files (iter 89)"
@@ -1696,11 +1703,11 @@ CODE=$?
step "17z9. MCP success-semantic footnote + audit_trend file inputs (iter 46)"
miss=""
WRAPPER="$ROOT/../../v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts"
-# Success-semantic constant declared + appended to N tool descriptions =
-# N+1 occurrences. N is the derived tool count β€” cross-aspect check within
-# the wrapper: footnote appends vs `name:` declarations.
+# Success-semantic constant declared + appended to every subprocess-backed
+# tool description. The in-process flywheel has its own transaction semantics,
+# so total occurrences equal the total tool count (1 constant + N-1 tools).
COUNT=$(grep -c "MCP_SUCCESS_SEMANTIC" "$WRAPPER" 2>/dev/null; true)
-[[ "$COUNT" == "$((EXPECTED_TOOLS + 1))" ]] || miss="$miss footnote-count:$COUNT-expected-$((EXPECTED_TOOLS + 1))"
+[[ "$COUNT" == "$EXPECTED_TOOLS" ]] || miss="$miss footnote-count:$COUNT-expected-$EXPECTED_TOOLS"
# audit_trend now exposes baselineFile / currentFile
grep -q "baselineFile" "$WRAPPER" 2>/dev/null || miss="$miss no-baseline-file"
grep -q "currentFile" "$WRAPPER" 2>/dev/null || miss="$miss no-current-file"
@@ -1738,9 +1745,10 @@ grep -q "success = exitCode === 0" "$WRAPPER" 2>/dev/null || miss="$miss no-exit
COUNT_OLD=$(grep -c "success: !r.degraded" "$WRAPPER" 2>/dev/null; true)
[[ "$COUNT_OLD" == "0" ]] || miss="$miss old-pattern-still-present:$COUNT_OLD"
COUNT_NEW=$(grep -c "success: r.success" "$WRAPPER" 2>/dev/null; true)
-# One `success: r.success` per handler = the derived tool count. Cross-aspect
-# check within the wrapper: handler success-wiring vs `name:` declarations.
-[[ "$COUNT_NEW" == "$EXPECTED_TOOLS" ]] || miss="$miss new-pattern-count:$COUNT_NEW-expected-$EXPECTED_TOOLS"
+# One `success: r.success` per subprocess-backed handler. The in-process
+# flywheel derives success from evaluation/promotion transaction results.
+EXPECTED_SCRIPT_TOOLS=$((EXPECTED_TOOLS - EXPECTED_IN_PROCESS_TOOLS))
+[[ "$COUNT_NEW" == "$EXPECTED_SCRIPT_TOOLS" ]] || miss="$miss new-pattern-count:$COUNT_NEW-expected-$EXPECTED_SCRIPT_TOOLS"
# Runtime anchors: iter 44 success assertions present
T="$ROOT/scripts/test-mcp-tools.mjs"
grep -q "iter 44 fix" "$T" 2>/dev/null || miss="$miss no-iter44-anchors"
@@ -2099,10 +2107,10 @@ grep -q "result has 'success'" "$F" || miss="$miss no-success-assertion"
grep -q "result has 'data'" "$F" || miss="$miss no-data-assertion"
grep -q "result has 'degraded'" "$F" || miss="$miss no-degraded-assertion"
grep -q "result has 'exitCode'" "$F" || miss="$miss no-exitcode-assertion"
-# All 15 tool names enumerated (similarity iter 36, drift_from_history iter 54,
+# All tool names enumerated (similarity iter 36, drift_from_history iter 54,
# ADR-153 added bench/evolve/security_bench, @metaharness/redblue added redblue,
-# [email protected]/[email protected] added learn + gepa)
-for tool in metaharness_score metaharness_genome metaharness_mcp_scan metaharness_threat_model metaharness_oia_audit metaharness_audit_list metaharness_audit_trend metaharness_similarity metaharness_drift_from_history metaharness_bench metaharness_evolve metaharness_security_bench metaharness_redblue metaharness_learn metaharness_gepa; do
+# [email protected]/[email protected] added learn + gepa, ADR-322 added flywheel)
+for tool in metaharness_score metaharness_genome metaharness_mcp_scan metaharness_threat_model metaharness_oia_audit metaharness_audit_list metaharness_audit_trend metaharness_similarity metaharness_drift_from_history metaharness_bench metaharness_evolve metaharness_security_bench metaharness_redblue metaharness_learn metaharness_gepa metaharness_flywheel; do
grep -q "${tool}" "$F" || miss="$miss missing-${tool}"
done
# test-mcp-tools.mjs keeps its own hardcoded `tools.length === N` literal β€”
diff --git a/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs b/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs
index c6db600fef..b864de38e6 100755
--- a/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs
+++ b/plugins/ruflo-metaharness/scripts/test-mcp-tools.mjs
@@ -74,7 +74,7 @@ async function main() {
// ──────────────────────────────────────────────────────────────────
console.log('Phase 1 β€” module shape');
assert(Array.isArray(tools), 'metaharnessTools is an array');
- assert(tools.length === 15, `15 tools registered (got ${tools.length})`);
+ assert(tools.length === 16, `16 tools registered (got ${tools.length})`);
const expectedNames = new Set([
'metaharness_score',
@@ -98,6 +98,8 @@ async function main() {
'metaharness_learn',
// @metaharness/[email protected] β€” GEPA library surface (genome ops)
'metaharness_gepa',
+ // ADR-322 β€” in-process governed evaluation and atomic promotion
+ 'metaharness_flywheel',
]);
const actualNames = new Set(tools.map((t) => t.name));
for (const name of expectedNames) {
diff --git a/v3/@claude-flow/cli/__tests__/bounded-worker-pool.test.ts b/v3/@claude-flow/cli/__tests__/bounded-worker-pool.test.ts
new file mode 100644
index 0000000000..ccf460d633
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/bounded-worker-pool.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+import { runBoundedPool } from '../src/services/bounded-worker-pool.js';
+
+describe('runBoundedPool', () => {
+ it('rejects invalid limits and duplicate task identities', async () => {
+ await expect(runBoundedPool([], { maxConcurrency: 0 }))
+ .rejects.toThrow('maxConcurrency must be a positive integer');
+ await expect(runBoundedPool([
+ { id: 'same', run: async () => 1 },
+ { id: 'same', run: async () => 2 },
+ ], { maxConcurrency: 2 })).rejects.toThrow('duplicate or empty task id');
+ });
+
+ it('enforces the hard concurrency cap and preserves input order', async () => {
+ let active = 0;
+ let observedPeak = 0;
+ const result = await runBoundedPool(
+ Array.from({ length: 12 }, (_, index) => ({
+ id: `candidate-${String(index).padStart(2, '0')}`,
+ run: async () => {
+ active += 1;
+ observedPeak = Math.max(observedPeak, active);
+ await new Promise((resolve) => setTimeout(resolve, 5 + ((11 - index) % 3)));
+ active -= 1;
+ return index;
+ },
+ })),
+ { maxConcurrency: 3 },
+ );
+ expect(result.peakConcurrency).toBe(3);
+ expect(observedPeak).toBe(3);
+ expect(result.results.map((item) => item.id)).toEqual(
+ Array.from({ length: 12 }, (_, index) => `candidate-${String(index).padStart(2, '0')}`),
+ );
+ expect(result.results.every((item) => item.status === 'fulfilled')).toBe(true);
+ });
+
+ it('cancels queued work after timeout without oversubscription', async () => {
+ const result = await runBoundedPool(
+ Array.from({ length: 6 }, (_, index) => ({
+ id: `task-${index}`,
+ run: async (signal: AbortSignal) => {
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(resolve, 100);
+ signal.addEventListener('abort', () => {
+ clearTimeout(timer);
+ reject(signal.reason);
+ }, { once: true });
+ });
+ return index;
+ },
+ })),
+ { maxConcurrency: 2, timeoutMs: 10 },
+ );
+ expect(result.peakConcurrency).toBe(2);
+ expect(result.results.every((item) => item.status === 'cancelled')).toBe(true);
+ });
+
+ it('returns at the wall-time bound when a task ignores cancellation', async () => {
+ const started = Date.now();
+ const result = await runBoundedPool([{
+ id: 'hung-third-party',
+ run: async () => new Promise<number>(() => {}),
+ }], { maxConcurrency: 1, timeoutMs: 15 });
+
+ expect(Date.now() - started).toBeLessThan(250);
+ expect(result.results[0]?.status).toBe('cancelled');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts b/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts
new file mode 100644
index 0000000000..b131594079
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts
@@ -0,0 +1,292 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir, userInfo } from 'node:os';
+import { createHash, createHmac } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import {
+ autoMigratePolicyStateIfNeeded,
+ classifyMcpTool,
+ evaluatePolicyRequest,
+ issuePolicyApproval,
+ loadPolicyState,
+ setPolicyBudget,
+ setPolicyMode,
+ upsertPolicyRule,
+ verifyPolicyLedger,
+} from '../src/services/policy-runtime.js';
+import { callMCPTool } from '../src/mcp-client.js';
+
+const roots: Array<{ root: string; trust: string }> = [];
+function project(): string {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-policy-runtime-'));
+ mkdirSync(join(root, '.claude-flow'), { recursive: true });
+ const projectId = createHash('sha256').update(root).digest('hex');
+ roots.push({
+ root,
+ trust: join(userInfo().homedir, '.config', 'ruflo', 'policy-trust', projectId),
+ });
+ return root;
+}
+
+afterEach(() => {
+ for (const item of roots.splice(0)) {
+ rmSync(item.trust, { recursive: true, force: true });
+ rmSync(item.root, { recursive: true, force: true });
+ }
+ delete process.env.CLAUDE_FLOW_POLICY_APPROVERS;
+ delete process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE;
+});
+
+describe('policy runtime compatibility and transactions', () => {
+ it('derives security attributes from trusted tool identity', () => {
+ expect(classifyMcpTool('memory_search')).toMatchObject({
+ actionType: 'memory.read',
+ namespaceAccess: 'read',
+ destructive: false,
+ });
+ expect(classifyMcpTool('memory_delete')).toMatchObject({
+ actionType: 'memory.write',
+ namespaceAccess: 'write',
+ destructive: true,
+ });
+ expect(classifyMcpTool('policy_rule_upsert')).toMatchObject({
+ actionType: 'policy.admin.rule_upsert',
+ destructive: true,
+ });
+ });
+
+ it('does not exempt policy administration from the MCP chokepoint', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await setPolicyMode('enforce', root);
+ await expect(callMCPTool('policy_rule_upsert', {
+ rule: { id: 'self-allow', effect: 'allow', actions: ['*'] },
+ projectRoot: root,
+ }, {
+ projectRoot: root,
+ principalId: 'agent:untrusted',
+ principalType: 'agent',
+ })).rejects.toThrow('MCP tool not found');
+ expect(loadPolicyState(root).rules).toHaveLength(0);
+ });
+
+ it('enforces a spawned worker capability envelope at MCP dispatch', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await upsertPolicyRule({ id: 'allow-tools', effect: 'allow', actions: ['mcp.tool.call'] }, root);
+ await setPolicyMode('enforce', root);
+ process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE = JSON.stringify({
+ actions: ['*'],
+ resources: ['*'],
+ tools: ['*'],
+ network: false,
+ destructive: false,
+ maxConcurrency: 1,
+ });
+ await expect(callMCPTool('terminal_execute', {
+ command: 'echo should-not-run',
+ }, { projectRoot: root })).rejects.toThrow('network-outside-envelope');
+ });
+
+ it('uses parent policy from an isolated git worktree', async () => {
+ const root = project();
+ execFileSync('git', ['init', '-q', root]);
+ writeFileSync(join(root, 'README.md'), 'policy worktree test\n');
+ execFileSync('git', ['-C', root, 'add', 'README.md']);
+ execFileSync('git', [
+ '-C', root, '-c', 'user.name=Ruflo Test', '-c', 'user.email=test@invalid',
+ 'commit', '-qm', 'initial',
+ ]);
+ await autoMigratePolicyStateIfNeeded(root);
+ await upsertPolicyRule({ id: 'allow-tools', effect: 'allow', actions: ['mcp.tool.call'] }, root);
+ await setPolicyMode('enforce', root);
+
+ const worktree = `${root}-worker`;
+ execFileSync('git', ['-C', root, 'worktree', 'add', '--detach', worktree, 'HEAD']);
+ const previousCwd = process.cwd();
+ process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE = JSON.stringify({
+ actions: ['*'],
+ resources: ['*'],
+ tools: ['*'],
+ network: false,
+ destructive: false,
+ });
+ try {
+ process.chdir(worktree);
+ await expect(callMCPTool('terminal_execute', {
+ command: 'echo should-not-run',
+ })).rejects.toThrow('network-outside-envelope');
+ expect(loadPolicyState(root).receipts).toHaveLength(1);
+ } finally {
+ process.chdir(previousCwd);
+ execFileSync('git', ['-C', root, 'worktree', 'remove', '--force', worktree]);
+ }
+ });
+
+ it('auto-migrates an existing installation once in legacy mode', async () => {
+ const root = project();
+ expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ migrated: true, mode: 'legacy' });
+ expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ migrated: false, mode: 'legacy' });
+ expect(loadPolicyState(root).migratedFrom).toContain('pre-ADR-324');
+ });
+
+ it('applies Codex policy mode changes without overwriting later CLI transitions', async () => {
+ const root = project();
+ mkdirSync(join(root, '.agents'), { recursive: true });
+ const config = join(root, '.agents', 'config.toml');
+ writeFileSync(config, '[policy]\nmode = "observe"\n');
+ expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ mode: 'observe' });
+
+ await setPolicyMode('enforce', root);
+ expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ mode: 'enforce' });
+
+ writeFileSync(config, '[policy]\nmode = "legacy"\n');
+ expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ mode: 'enforce' });
+ });
+
+ it('fails closed when enforced policy state is modified or removed', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await setPolicyMode('enforce', root);
+ const statePath = join(root, '.claude-flow', 'policy', 'state.json');
+ expect(existsSync(roots.at(-1)!.trust)).toBe(true);
+
+ const original = readFileSync(statePath, 'utf8');
+ const changed = JSON.parse(original) as { mode: string };
+ changed.mode = 'legacy';
+ writeFileSync(statePath, JSON.stringify(changed));
+ expect(() => loadPolicyState(root)).toThrow('policy-state-authentication-failed');
+
+ writeFileSync(statePath, original);
+ expect(loadPolicyState(root).mode).toBe('enforce');
+ unlinkSync(statePath);
+ expect(() => loadPolicyState(root)).toThrow('policy-state-missing-for-anchored-project');
+ });
+
+ it('binds the trust anchor to the canonical project path', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await setPolicyMode('enforce', root);
+ const alias = `${root}-alias`;
+ symlinkSync(root, alias);
+ try {
+ expect(loadPolicyState(alias).mode).toBe('enforce');
+ } finally {
+ unlinkSync(alias);
+ }
+ });
+
+ it('does not treat a local issuer string as authenticated human authority', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await expect(issuePolicyApproval({
+ id: 'forged-local-approval',
+ principal: 'agent:release',
+ actions: ['deployment.promote'],
+ issuedBy: 'user:claimed-admin',
+ expiresAt: Date.now() + 60_000,
+ maxUses: 1,
+ }, root)).rejects.toThrow('untrusted-approval-issuer');
+ });
+
+ it('moves from observation to enforcement without changing rule semantics', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await upsertPolicyRule({ id: 'allow-read', effect: 'allow', actions: ['code.read'] }, root);
+ await setPolicyMode('observe', root);
+ const writeObserved = await evaluatePolicyRequest({
+ identity: { id: 'agent-1', type: 'agent' },
+ action: { type: 'code.write', resource: 'src/a.ts' },
+ }, root);
+ expect(writeObserved.outcome).toBe('denied');
+ expect(writeObserved.enforcedOutcome).toBe('allowed');
+
+ await setPolicyMode('enforce', root);
+ const read = await evaluatePolicyRequest({
+ identity: { id: 'agent-1', type: 'agent' },
+ action: { type: 'code.read', resource: 'src/a.ts' },
+ }, root);
+ expect(read.enforcedOutcome).toBe('allowed');
+ const write = await evaluatePolicyRequest({
+ identity: { id: 'agent-1', type: 'agent' },
+ action: { type: 'code.write', resource: 'src/a.ts' },
+ }, root);
+ expect(write.enforcedOutcome).toBe('denied');
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 3 });
+ });
+
+ it('cryptographically binds signed evidence provenance claims', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await upsertPolicyRule({
+ id: 'verified-release',
+ effect: 'allow',
+ actions: ['deployment.promote'],
+ constraints: { requireSignedEvidence: true, requiredProvenance: ['tool_result'] },
+ }, root);
+ await setPolicyMode('enforce', root);
+ const key = 'test-evidence-key-material';
+ process.env.CLAUDE_FLOW_POLICY_EVIDENCE_KEYS = JSON.stringify({ ci: key });
+ const evidence = {
+ id: 'evidence-1',
+ provenance: 'tool_result' as const,
+ attestor: 'ci',
+ observedAt: 100,
+ contentHash: `sha256:${'a'.repeat(64)}`,
+ keyId: 'ci',
+ };
+ const claims = JSON.stringify(evidence);
+ const signature = `hmac-sha256:${createHmac('sha256', key).update(claims).digest('hex')}`;
+ try {
+ expect((await evaluatePolicyRequest({
+ identity: { id: 'agent:release', type: 'agent' },
+ action: { type: 'deployment.promote' },
+ context: { evidence: [{ ...evidence, signature }] },
+ }, root)).enforcedOutcome).toBe('allowed');
+ expect((await evaluatePolicyRequest({
+ identity: { id: 'agent:release', type: 'agent' },
+ action: { type: 'deployment.promote' },
+ context: {
+ evidence: [{ ...evidence, provenance: 'user_claim', signature }],
+ },
+ }, root)).enforcedOutcome).toBe('denied');
+ } finally {
+ delete process.env.CLAUDE_FLOW_POLICY_EVIDENCE_KEYS;
+ }
+ });
+
+ it('serializes concurrent decisions into one valid receipt chain', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await Promise.all(Array.from({ length: 20 }, (_, index) => evaluatePolicyRequest({
+ identity: { id: `agent:${index}`, type: 'agent' },
+ action: { type: 'code.read', resource: `file-${index}` },
+ }, root)));
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 20 });
+ });
+
+ it('cannot overspend a budget under concurrent decisions', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ await upsertPolicyRule({ id: 'allow-model', effect: 'allow', actions: ['model.call'] }, root);
+ await setPolicyBudget({
+ id: 'model-window',
+ principal: 'agent:*',
+ action: 'model.call',
+ maxCostUsd: 1,
+ periodMs: 60_000,
+ }, root);
+ await setPolicyMode('enforce', root);
+
+ const decisions = await Promise.all(Array.from({ length: 10 }, (_, index) => evaluatePolicyRequest({
+ identity: { id: `agent:${index}`, type: 'agent' },
+ action: { type: 'model.call', resource: 'openrouter', costUsd: 0.2 },
+ }, root)));
+
+ expect(decisions.filter((decision) => decision.enforcedOutcome === 'allowed')).toHaveLength(5);
+ expect(decisions.filter((decision) => decision.enforcedOutcome === 'denied')).toHaveLength(5);
+ expect(loadPolicyState(root).usage[0]?.costUsd).toBeCloseTo(1);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 10 });
+ });
+});
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index db9e19a28a..1af8af07fa 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -105,10 +105,8 @@
"@claude-flow/mcp": "3.0.0-alpha.8",
"@claude-flow/neural": "3.0.0-alpha.9",
"@claude-flow/shared": "3.0.0-alpha.7",
- "@metaharness/router": "^0.3.2",
"@noble/ed25519": "2.3.0",
"@ruvector/rabitq-wasm": "0.1.0",
- "metaharness": "^0.4.1",
"semver": "7.7.3",
"sql.js": "^1.13.0",
"yaml": "^2.8.0"
@@ -116,13 +114,31 @@
"optionalDependencies": {
"@claude-flow/memory": "^3.0.0-alpha.21",
"@claude-flow/security": "^3.0.0-alpha.12",
- "@metaharness/darwin": "^0.8.0",
- "@metaharness/flywheel": "^0.1.7",
"agentdb": "^3.0.0-alpha.17",
"agentic-flow": "^3.0.0-alpha.1",
"better-sqlite3": "^12.9.0",
"ruvector": "^0.2.27"
},
+ "peerDependencies": {
+ "@metaharness/darwin": "^0.8.0",
+ "@metaharness/flywheel": "^0.1.7",
+ "@metaharness/router": "^0.3.2",
+ "metaharness": "^0.4.1"
+ },
+ "peerDependenciesMeta": {
+ "@metaharness/darwin": {
+ "optional": true
+ },
+ "@metaharness/flywheel": {
+ "optional": true
+ },
+ "@metaharness/router": {
+ "optional": true
+ },
+ "metaharness": {
+ "optional": true
+ }
+ },
"publishConfig": {
"access": "public",
"tag": "latest"
diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.ts
index 00dabc25ed..69f946b8de 100644
--- a/v3/@claude-flow/cli/src/commands/index.ts
+++ b/v3/@claude-flow/cli/src/commands/index.ts
@@ -49,6 +49,7 @@ const commandLoaders: Record<string, CommandLoader> = {
plugins: () => import('./plugins.js'),
deployment: () => import('./deployment.js'),
claims: () => import('./claims.js'),
+ policy: () => import('./policy.js'),
embeddings: () => import('./embeddings.js'),
// P0 Commands
completions: () => import('./completions.js'),
@@ -195,6 +196,7 @@ export async function getProvidersCommand() { return loadCommand('providers'); }
export async function getPluginsCommand() { return loadCommand('plugins'); }
export async function getDeploymentCommand() { return loadCommand('deployment'); }
export async function getClaimsCommand() { return loadCommand('claims'); }
+export async function getPolicyCommand() { return loadCommand('policy'); }
export async function getEmbeddingsCommand() { return loadCommand('embeddings'); }
export async function getCompletionsCommand() { return loadCommand('completions'); }
export async function getAnalyzeCommand() { return loadCommand('analyze'); }
@@ -260,7 +262,7 @@ export async function getCommandsByCategory(): Promise<Record<string, Command[]>
analyzeCmd, routeCmd, progressCmd, providersCmd,
pluginsCmd, deploymentCmd, claimsCmd, issuesCmd,
updateCmd, processCmd, guidanceCmd, applianceCmd,
- cleanupCmd, autopilotCmd,
+ cleanupCmd, autopilotCmd, policyCmd,
] = await Promise.all([
loadCommand('daemon'), loadCommand('doctor'), loadCommand('embeddings'), loadCommand('neural'),
loadCommand('performance'), loadCommand('security'), loadCommand('ruvector'), loadCommand('hive-mind'),
@@ -268,7 +270,7 @@ export async function getCommandsByCategory(): Promise<Record<string, Command[]>
loadCommand('analyze'), loadCommand('route'), loadCommand('progress'), loadCommand('providers'),
loadCommand('plugins'), loadCommand('deployment'), loadCommand('claims'), loadCommand('issues'),
loadCommand('update'), loadCommand('process'), loadCommand('guidance'), loadCommand('appliance'),
- loadCommand('cleanup'), loadCommand('autopilot'),
+ loadCommand('cleanup'), loadCommand('autopilot'), loadCommand('policy'),
]);
return {
@@ -278,7 +280,7 @@ export async function getCommandsByCategory(): Promise<Record<string, Command[]>
mcpCommand, hooksCommand,
],
advanced: [
- neuralCmd, securityCmd, performanceCmd, embeddingsCmd,
+ neuralCmd, securityCmd, policyCmd, performanceCmd, embeddingsCmd,
hiveMindCmd, ruvectorCmd, guidanceCmd, autopilotCmd,
].filter(Boolean) as Command[],
utility: [
diff --git a/v3/@claude-flow/cli/src/commands/metaharness.ts b/v3/@claude-flow/cli/src/commands/metaharness.ts
index 580eca1540..a69ba8968c 100644
--- a/v3/@claude-flow/cli/src/commands/metaharness.ts
+++ b/v3/@claude-flow/cli/src/commands/metaharness.ts
@@ -47,6 +47,7 @@ import {
readFlywheelTransactionState,
verifyFlywheelLedger,
} from '../services/flywheel-transaction.js';
+import { evaluatePolicyRequest } from '../services/policy-runtime.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -112,6 +113,8 @@ async function dispatchFlywheel(
proposer: String(flywheelFlag(flags, 'proposer', 'auto')) as 'auto' | 'local' | 'darwin',
receiptPrivateKeyPem: privateKeyPath ? readFileSync(resolve(privateKeyPath), 'utf8') : undefined,
receiptPublicKeyPem: publicKeyPath ? readFileSync(resolve(publicKeyPath), 'utf8') : undefined,
+ maxConcurrency: Number(flywheelFlag(flags, 'maxConcurrency', 2)),
+ evaluationTimeoutMs: Number(flywheelFlag(flags, 'timeoutMs', 120_000)),
});
}
} else if (operation === 'receipts') {
@@ -133,11 +136,27 @@ async function dispatchFlywheel(
if (!receiptId || !publicKeyPath) {
data = { success: false, reason: 'promote requires <receipt-id> and --public-key <PEM path>' };
} else {
- const publicKey = readFileSync(resolve(publicKeyPath), 'utf8');
- data = await promoteFlywheelCandidate(projectRoot, receiptId, {
- confirm: flywheelFlag<boolean>(flags, 'confirm', false) === true,
- trustedPublicKeys: new Set([publicKey]),
- });
+ const policy = await evaluatePolicyRequest({
+ identity: { id: process.env.CLAUDE_FLOW_PRINCIPAL_ID ?? 'metaharness-local', type: 'agent', roles: ['optimizer'] },
+ action: {
+ type: 'metaharness.candidate.promote',
+ resource: receiptId,
+ environment: 'production',
+ destructive: true,
+ },
+ context: {
+ approvalIds: String(flywheelFlag(flags, 'approvalId', '')).split(',').filter(Boolean),
+ },
+ }, projectRoot);
+ if (policy.enforcedOutcome !== 'allowed') {
+ data = { success: false, reason: `policy-${policy.enforcedOutcome}:${policy.reason}`, policyReceiptId: policy.receiptId };
+ } else {
+ const publicKey = readFileSync(resolve(publicKeyPath), 'utf8');
+ data = await promoteFlywheelCandidate(projectRoot, receiptId, {
+ confirm: flywheelFlag<boolean>(flags, 'confirm', false) === true,
+ trustedPublicKeys: new Set([publicKey]),
+ });
+ }
}
} else {
data = { success: false, reason: `unknown flywheel operation: ${operation}` };
diff --git a/v3/@claude-flow/cli/src/commands/policy.ts b/v3/@claude-flow/cli/src/commands/policy.ts
new file mode 100644
index 0000000000..3aec0ae369
--- /dev/null
+++ b/v3/@claude-flow/cli/src/commands/policy.ts
@@ -0,0 +1,119 @@
+import type {
+ BudgetLimit,
+ PolicyRequest,
+ PolicyRule,
+ PolicyState,
+} from '@claude-flow/security';
+import type { Command, CommandContext, CommandResult } from '../types.js';
+import { output } from '../output.js';
+import {
+ autoMigratePolicyStateIfNeeded,
+ evaluatePolicyRequest,
+ loadPolicyState,
+ revokePolicyApproval,
+ setPolicyBudget,
+ setPolicyMode,
+ upsertPolicyRule,
+ verifyPolicyLedger,
+} from '../services/policy-runtime.js';
+
+function argJson<T>(value: string | undefined, label: string): T {
+ if (!value) throw new Error(`${label} requires a JSON argument`);
+ try { return JSON.parse(value) as T; }
+ catch { throw new Error(`${label} must be valid JSON`); }
+}
+
+function print(data: unknown): CommandResult {
+ output.writeln(JSON.stringify(data, null, 2));
+ return { success: true, exitCode: 0, data };
+}
+
+function requireInteractiveAdministrator(): void {
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
+ throw new Error('policy administration requires an interactive local terminal');
+ }
+}
+
+export const policyCommand: Command = {
+ name: 'policy',
+ description: 'Agentic policy engine β€” evaluate actions, manage rules/approvals, and verify the decision ledger (ADR-324)',
+ options: [
+ { name: 'mode', type: 'string', description: 'Policy mode: legacy | observe | enforce' },
+ { name: 'project-root', type: 'string', description: 'Project root containing .claude-flow/policy' },
+ ],
+ async action(context: CommandContext): Promise<CommandResult> {
+ const args = (context as { args?: string[] }).args ?? [];
+ const flags = (context as { flags?: Record<string, unknown> }).flags ?? {};
+ const root = String(flags.projectRoot ?? process.cwd());
+ const operation = args[0] ?? 'status';
+ try {
+ if (operation === 'init' || operation === 'migrate') {
+ if (flags.mode || args[1]) requireInteractiveAdministrator();
+ const migration = await autoMigratePolicyStateIfNeeded(root);
+ const mode = String(flags.mode ?? args[1] ?? '') as PolicyState['mode'];
+ if (mode) {
+ if (!['legacy', 'observe', 'enforce'].includes(mode)) throw new Error('mode must be legacy, observe, or enforce');
+ await setPolicyMode(mode, root);
+ }
+ return print({ ...migration, state: loadPolicyState(root) });
+ }
+ if (operation === 'status') {
+ const state = loadPolicyState(root);
+ return print({
+ version: state.version,
+ mode: state.mode,
+ migratedFrom: state.migratedFrom,
+ rules: state.rules.length,
+ budgets: state.budgets.length,
+ approvals: state.approvals.length,
+ receipts: state.receipts.length,
+ ledger: await verifyPolicyLedger(root),
+ });
+ }
+ if (operation === 'evaluate') {
+ return print(await evaluatePolicyRequest(argJson<PolicyRequest>(args[1], 'evaluate'), root));
+ }
+ if (operation === 'rule' && args[1] === 'add') {
+ requireInteractiveAdministrator();
+ const rule = argJson<PolicyRule>(args[2], 'rule add');
+ await upsertPolicyRule(rule, root);
+ return print({ success: true, ruleId: rule.id });
+ }
+ if (operation === 'budget' && args[1] === 'set') {
+ requireInteractiveAdministrator();
+ const budget = argJson<BudgetLimit>(args[2], 'budget set');
+ await setPolicyBudget(budget, root);
+ return print({ success: true, budgetId: budget.id });
+ }
+ if (operation === 'approve') {
+ throw new Error(
+ 'approval issuance requires an authenticated human identity adapter; '
+ + 'the local TTY is not an identity credential',
+ );
+ }
+ if (operation === 'revoke') {
+ requireInteractiveAdministrator();
+ if (!args[1]) throw new Error('revoke requires an approval id');
+ return print({ success: await revokePolicyApproval(args[1], root), approvalId: args[1] });
+ }
+ if (operation === 'audit') {
+ const state = loadPolicyState(root);
+ return print({ receipts: state.receipts });
+ }
+ if (operation === 'verify') return print(await verifyPolicyLedger(root));
+ throw new Error(`unknown policy operation: ${operation}`);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(message);
+ return { success: false, exitCode: 1, data: { error: message } };
+ }
+ },
+ examples: [
+ { command: 'ruflo policy status', description: 'Show policy mode and ledger health' },
+ { command: 'ruflo policy init --mode observe', description: 'Migrate an existing install without blocking legacy actions' },
+ { command: 'ruflo policy budget set \'{"id":"daily-model","action":"model.call","maxCostUsd":10,"periodMs":86400000}\'', description: 'Set an atomic policy budget ceiling' },
+ { command: 'ruflo policy evaluate \'{"identity":{"id":"agent-1","type":"agent"},"action":{"type":"deploy","environment":"production"}}\'', description: 'Evaluate an action and write a decision receipt' },
+ ],
+};
+
+export default policyCommand;
diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.ts
index 54cdc7f6f4..1c0e6a2a12 100644
--- a/v3/@claude-flow/cli/src/index.ts
+++ b/v3/@claude-flow/cli/src/index.ts
@@ -140,6 +140,24 @@ export class CLI {
// stamp read + string compare (sub-ms), and the copy runs at most once per
// version bump. Best-effort + silent β€” never blocks or fails a command.
if (commandPath[0] !== 'init' && commandPath[0] !== 'update') {
+ // ADR-324: existing installations acquire a versioned policy state on
+ // first use. Migration is additive and starts in legacy mode, so older
+ // AgentDB, MCP, hooks, and swarm workflows keep their exact behavior.
+ try {
+ const { autoMigratePolicyStateIfNeeded } = await import('./services/policy-runtime.js');
+ const migration = await autoMigratePolicyStateIfNeeded(process.cwd());
+ if (migration.migrated && this.output.isVerbose()) {
+ this.output.printDebug(`Initialized agentic policy compatibility state (${migration.mode})`);
+ }
+ } catch (error) {
+ // Legacy compatibility requires startup to remain available if the
+ // policy state cannot be initialized. Enforce-mode actions still
+ // fail at their authoritative dispatcher when state is unreadable.
+ if (this.output.isVerbose()) {
+ this.output.printDebug(`Policy compatibility migration skipped: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
try {
const { autoRefreshHelpersIfStale } = await import('./init/helper-refresh.js');
// alsoRefreshGlobal:true β€” refresh ~/.claude/helpers too, not just
diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.ts
index b894771ece..1b50cb0bce 100644
--- a/v3/@claude-flow/cli/src/mcp-client.ts
+++ b/v3/@claude-flow/cli/src/mcp-client.ts
@@ -24,6 +24,8 @@ import { analyzeTools } from './mcp-tools/analyze-tools.js';
import { progressTools } from './mcp-tools/progress-tools.js';
import { embeddingsTools } from './mcp-tools/embeddings-tools.js';
import { claimsTools } from './mcp-tools/claims-tools.js';
+import { policyTools } from './mcp-tools/policy-tools.js';
+import { authorizeMcpTool, classifyMcpTool } from './services/policy-runtime.js';
import { securityTools } from './mcp-tools/security-tools.js';
import { transferTools } from './mcp-tools/transfer-tools.js';
// V2 Compatibility tools
@@ -135,6 +137,10 @@ registerTools([
...progressTools,
...embeddingsTools,
...claimsTools,
+ // Remote MCP exposes evaluation/status only. Administrative mutation is a
+ // local CLI bootstrap/recovery operation until the server has authenticated
+ // human identity propagation.
+ ...policyTools.filter((tool) => ['policy_evaluate', 'policy_status'].includes(tool.name)),
...securityTools,
...transferTools,
// V2 Compatibility tools
@@ -230,6 +236,15 @@ export async function callMCPTool<T = unknown>(
}
try {
+ // ADR-324: one policy chokepoint for every local CLI/MCP invocation.
+ // Policy administration is not exempt: authorization calls the engine
+ // directly, so there is no recursive MCP dispatch. In enforce mode an
+ // administrator must explicitly allow policy.* actions or use the local
+ // CLI bootstrap path.
+ const decision = await authorizeMcpTool(toolName, input, context, classifyMcpTool(toolName));
+ if (decision.enforcedOutcome !== 'allowed') {
+ throw new Error(`policy-${decision.enforcedOutcome}:${decision.reason}; receipt=${decision.receiptId}`);
+ }
// Call the tool handler
const result = await tool.handler(input, context);
// ADR-146 P2: scan every tool result for indirect-injection before it
diff --git a/v3/@claude-flow/cli/src/mcp-tools/index.ts b/v3/@claude-flow/cli/src/mcp-tools/index.ts
index 95bc47ca65..163d17addf 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/index.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/index.ts
@@ -21,6 +21,7 @@ export { transferTools } from './transfer-tools.js';
export { securityTools } from './security-tools.js';
export { embeddingsTools } from './embeddings-tools.js';
export { claimsTools } from './claims-tools.js';
+export { policyTools } from './policy-tools.js';
export { wasmAgentTools } from './wasm-agent-tools.js';
export { ruvllmWasmTools } from './ruvllm-tools.js';
export { guidanceTools } from './guidance-tools.js';
diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
index 5992b98fd8..270f2471ab 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts
@@ -54,6 +54,7 @@ import { existsSync, readFileSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js';
+import { evaluatePolicyRequest } from '../services/policy-runtime.js';
import {
listFlywheelReceipts,
promoteFlywheelCandidate,
@@ -631,6 +632,9 @@ export const metaharnessTools: MCPTool[] = [
privateKeyPath: { type: 'string', description: 'Local Ed25519 private-key PEM path for signing run receipts; must be paired with publicKeyPath' },
publicKeyPath: { type: 'string', description: 'Local Ed25519 public-key PEM path used to sign a run or approve a promotion' },
confirm: { type: 'boolean', description: 'Required for promote; never inferred', default: false },
+ maxConcurrency: { type: 'number', description: 'ADR-324 hard local candidate-evaluation concurrency cap (1-8)', default: 2 },
+ timeoutMs: { type: 'number', description: 'Abort concurrent evaluation after this wall-clock limit', default: 120000 },
+ approvalIds: { type: 'array', items: { type: 'string' }, description: 'Scoped ADR-324 approval IDs for privileged promotion' },
},
required: ['operation'],
},
@@ -676,6 +680,8 @@ export const metaharnessTools: MCPTool[] = [
proposer: String(input.proposer ?? 'auto') as 'local' | 'auto' | 'darwin',
receiptPrivateKeyPem: privateKeyPath ? readFileSync(privateKeyPath, 'utf8') : undefined,
receiptPublicKeyPem: publicKeyPath ? readFileSync(publicKeyPath, 'utf8') : undefined,
+ maxConcurrency: Number(input.maxConcurrency ?? 2),
+ evaluationTimeoutMs: Number(input.timeoutMs ?? 120_000),
});
return { success: data.ran, data, degraded: false, exitCode: data.ran ? 0 : 1 };
}
@@ -683,6 +689,26 @@ export const metaharnessTools: MCPTool[] = [
if (!input.receiptId || !input.publicKeyPath) {
return { success: false, data: { reason: 'receiptId and publicKeyPath are required' }, degraded: false, exitCode: 2 };
}
+ const policy = await evaluatePolicyRequest({
+ identity: { id: 'metaharness-mcp', type: 'agent', roles: ['optimizer'] },
+ action: {
+ type: 'metaharness.candidate.promote',
+ resource: String(input.receiptId),
+ environment: 'production',
+ destructive: true,
+ },
+ context: {
+ approvalIds: Array.isArray(input.approvalIds) ? input.approvalIds.map(String) : undefined,
+ },
+ }, projectRoot);
+ if (policy.enforcedOutcome !== 'allowed') {
+ return {
+ success: false,
+ data: { reason: `policy-${policy.enforcedOutcome}:${policy.reason}`, policyReceiptId: policy.receiptId },
+ degraded: false,
+ exitCode: 1,
+ };
+ }
const publicKey = readFileSync(resolve(String(input.publicKeyPath)), 'utf8');
const data = await promoteFlywheelCandidate(projectRoot, String(input.receiptId), {
confirm: input.confirm === true,
diff --git a/v3/@claude-flow/cli/src/mcp-tools/policy-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/policy-tools.ts
new file mode 100644
index 0000000000..3c1fdeb0a3
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mcp-tools/policy-tools.ts
@@ -0,0 +1,154 @@
+import type {
+ BudgetLimit,
+ PolicyApproval,
+ PolicyRequest,
+ PolicyRule,
+ PolicyState,
+} from '@claude-flow/security';
+import type { MCPTool } from './types.js';
+import {
+ evaluatePolicyRequest,
+ issuePolicyApproval,
+ loadPolicyState,
+ revokePolicyApproval,
+ setPolicyBudget,
+ setPolicyMode,
+ upsertPolicyRule,
+ verifyPolicyLedger,
+} from '../services/policy-runtime.js';
+
+function requireAuthenticatedAdministrator(
+ context: Record<string, unknown> | undefined,
+): asserts context is Record<string, unknown> & { principalId: string; principalType: 'user' } {
+ if (context?.principalType !== 'user' || typeof context.principalId !== 'string') {
+ throw new Error('policy administration requires an authenticated user context');
+ }
+}
+
+export const policyTools: MCPTool[] = [
+ {
+ name: 'policy_evaluate',
+ description: 'Evaluate an agent action against ADR-324 policy and persist a tamper-evident decision receipt. Use when a consequential tool, deployment, network, spend, or promotion action needs authorization.',
+ category: 'security',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ request: { type: 'object', description: 'Policy request containing identity, action, and optional evidence/envelope context' },
+ },
+ required: ['request'],
+ },
+ handler: async (input, context) => evaluatePolicyRequest(
+ input.request as PolicyRequest,
+ typeof context?.projectRoot === 'string' ? context.projectRoot : process.cwd(),
+ ),
+ },
+ {
+ name: 'policy_status',
+ description: 'Inspect policy mode, migration state, rules, budgets, approvals, and ledger integrity. Use when diagnosing whether an installation is in compatibility, observation, or enforcement mode.',
+ category: 'security',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async (_input, context) => {
+ const root = typeof context?.projectRoot === 'string' ? context.projectRoot : process.cwd();
+ const state = loadPolicyState(root);
+ return {
+ version: state.version,
+ mode: state.mode,
+ migratedFrom: state.migratedFrom,
+ counts: {
+ rules: state.rules.length,
+ budgets: state.budgets.length,
+ approvals: state.approvals.length,
+ receipts: state.receipts.length,
+ },
+ ledger: await verifyPolicyLedger(root),
+ };
+ },
+ },
+ {
+ name: 'policy_rule_upsert',
+ description: 'Create or update a versioned agentic policy rule. Use when defining explicit allow, deny, or human-approval requirements; existing installations remain unchanged until rules and enforcement mode are configured.',
+ category: 'security',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ rule: { type: 'object' },
+ mode: { type: 'string', enum: ['legacy', 'observe', 'enforce'] },
+ },
+ required: ['rule'],
+ },
+ handler: async (input, context) => {
+ requireAuthenticatedAdministrator(context);
+ const root = typeof context?.projectRoot === 'string' ? context.projectRoot : process.cwd();
+ await upsertPolicyRule(input.rule as PolicyRule, root);
+ if (input.mode) await setPolicyMode(input.mode as PolicyState['mode'], root);
+ return { success: true, ruleId: (input.rule as PolicyRule).id, mode: loadPolicyState(root).mode };
+ },
+ },
+ {
+ name: 'policy_budget_set',
+ description: 'Create or update an atomic USD/token ceiling for a principal, action, and resource window. Use when constraining agent spend; budget checks and decision receipts commit under the same policy-state lock.',
+ category: 'security',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ budget: { type: 'object' },
+ },
+ required: ['budget'],
+ },
+ handler: async (input, context) => {
+ requireAuthenticatedAdministrator(context);
+ const budget = input.budget as BudgetLimit;
+ await setPolicyBudget(
+ budget,
+ typeof context?.projectRoot === 'string' ? context.projectRoot : process.cwd(),
+ );
+ return { success: true, budgetId: budget.id };
+ },
+ },
+ {
+ name: 'policy_approve',
+ description: 'Issue a scoped, expiring, limited-use human approval. Use when policy_evaluate returns approval_required; self-approval is rejected.',
+ category: 'security',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ approval: { type: 'object' },
+ },
+ required: ['approval'],
+ },
+ handler: async (input, context) => {
+ requireAuthenticatedAdministrator(context);
+ const requested = input.approval as Omit<PolicyApproval, 'uses' | 'issuedAt' | 'issuedBy'>
+ & { uses?: number; issuedAt?: number };
+ return issuePolicyApproval(
+ { ...requested, issuedBy: context.principalId },
+ typeof context.projectRoot === 'string' ? context.projectRoot : process.cwd(),
+ (issuer) => issuer === context.principalId,
+ );
+ },
+ },
+ {
+ name: 'policy_revoke',
+ description: 'Revoke an outstanding policy approval immediately. Use when responding to an incident or when a previously approved action is no longer authorized.',
+ category: 'security',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ approvalId: { type: 'string' },
+ },
+ required: ['approvalId'],
+ },
+ handler: async (input, context) => {
+ requireAuthenticatedAdministrator(context);
+ return {
+ success: await revokePolicyApproval(
+ String(input.approvalId),
+ typeof context.projectRoot === 'string' ? context.projectRoot : process.cwd(),
+ ),
+ };
+ },
+ },
+];
diff --git a/v3/@claude-flow/cli/src/services/bounded-worker-pool.ts b/v3/@claude-flow/cli/src/services/bounded-worker-pool.ts
new file mode 100644
index 0000000000..752c77f62f
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/bounded-worker-pool.ts
@@ -0,0 +1,108 @@
+export interface BoundedTask<T> {
+ id: string;
+ run: (signal: AbortSignal) => Promise<T>;
+}
+
+export interface BoundedTaskResult<T> {
+ id: string;
+ status: 'fulfilled' | 'rejected' | 'cancelled';
+ value?: T;
+ error?: string;
+}
+
+export interface BoundedPoolResult<T> {
+ results: BoundedTaskResult<T>[];
+ peakConcurrency: number;
+ durationMs: number;
+}
+
+/**
+ * Deterministic bounded worker pool for Codex/MetaHarness fanout.
+ *
+ * Completion order never affects result order. The caller-supplied AbortSignal
+ * and timeout cancel both queued and cooperative running work. No unbounded
+ * Promise.all is used.
+ */
+export async function runBoundedPool<T>(
+ tasks: readonly BoundedTask<T>[],
+ options: { maxConcurrency: number; timeoutMs?: number; signal?: AbortSignal },
+): Promise<BoundedPoolResult<T>> {
+ const started = Date.now();
+ if (!Number.isInteger(options.maxConcurrency) || options.maxConcurrency < 1) {
+ throw new Error('maxConcurrency must be a positive integer');
+ }
+ const ids = new Set<string>();
+ for (const task of tasks) {
+ if (!task.id || ids.has(task.id)) throw new Error(`duplicate or empty task id: ${task.id}`);
+ ids.add(task.id);
+ }
+ const maxConcurrency = Math.min(options.maxConcurrency, tasks.length || 1);
+ const controller = new AbortController();
+ const onAbort = () => controller.abort(options.signal?.reason ?? new Error('cancelled'));
+ options.signal?.addEventListener('abort', onAbort, { once: true });
+ const timer = options.timeoutMs && options.timeoutMs > 0
+ ? setTimeout(() => controller.abort(new Error('worker-pool-timeout')), options.timeoutMs)
+ : undefined;
+
+ const results = new Map<string, BoundedTaskResult<T>>();
+ let cursor = 0;
+ let active = 0;
+ let peakConcurrency = 0;
+
+ const worker = async (): Promise<void> => {
+ while (cursor < tasks.length) {
+ const taskIndex = cursor++;
+ const task = tasks[taskIndex]!;
+ if (controller.signal.aborted) {
+ results.set(task.id, { id: task.id, status: 'cancelled', error: String(controller.signal.reason ?? 'cancelled') });
+ continue;
+ }
+ active += 1;
+ peakConcurrency = Math.max(peakConcurrency, active);
+ let rejectOnAbort: (() => void) | undefined;
+ try {
+ const abort = new Promise<never>((_, reject) => {
+ if (controller.signal.aborted) {
+ reject(controller.signal.reason ?? new Error('cancelled'));
+ return;
+ }
+ rejectOnAbort = () => reject(controller.signal.reason ?? new Error('cancelled'));
+ controller.signal.addEventListener('abort', rejectOnAbort, { once: true });
+ });
+ // Promise.race enforces the caller-visible wall time even when a
+ // third-party task ignores AbortSignal. Cooperative tasks should still
+ // stop their underlying work when the signal fires.
+ const value = await Promise.race([task.run(controller.signal), abort]);
+ results.set(task.id, controller.signal.aborted
+ ? { id: task.id, status: 'cancelled', error: String(controller.signal.reason ?? 'cancelled') }
+ : { id: task.id, status: 'fulfilled', value });
+ } catch (error) {
+ results.set(task.id, {
+ id: task.id,
+ status: controller.signal.aborted ? 'cancelled' : 'rejected',
+ error: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ if (rejectOnAbort) controller.signal.removeEventListener('abort', rejectOnAbort);
+ active -= 1;
+ }
+ }
+ };
+
+ try {
+ await Promise.all(Array.from({ length: maxConcurrency }, () => worker()));
+ } finally {
+ if (timer) clearTimeout(timer);
+ options.signal?.removeEventListener('abort', onAbort);
+ }
+
+ return {
+ results: tasks.map((task) => results.get(task.id) ?? {
+ id: task.id,
+ status: 'cancelled',
+ error: 'not-started',
+ }),
+ peakConcurrency,
+ durationMs: Date.now() - started,
+ };
+}
diff --git a/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts b/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts
index 78895a2c6d..062e67f8f4 100644
--- a/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts
+++ b/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts
@@ -23,6 +23,7 @@ import {
type SafetyEnvelope,
} from './flywheel-proposer.js';
import { sha256Ref } from './flywheel-receipt.js';
+import { evaluatePolicyRequest } from './policy-runtime.js';
/** The human-labeled ADR-081 anchor β€” the never-regress relevance set. */
const ANCHOR: AnchorTask[] = [
@@ -56,10 +57,24 @@ export async function runFlywheelWorker(
proposer?: ProposerMode;
darwinInvoker?: DarwinInvoker;
allowSubstitutionPromotion?: boolean;
+ maxConcurrency?: number;
+ evaluationTimeoutMs?: number;
} = {},
): Promise<FlywheelResult> {
try {
if (!(opts.optInOverride ?? harnessLoopOptedIn())) return { ran: false, reason: 'opt-in required (RUFLO_HARNESS_LOOP=1)' };
+ const policy = await evaluatePolicyRequest({
+ identity: { id: process.env.CLAUDE_FLOW_PRINCIPAL_ID ?? 'metaharness-local', type: 'agent', roles: ['optimizer'] },
+ action: {
+ type: 'metaharness.flywheel.run',
+ resource: projectRoot,
+ environment: 'development',
+ concurrency: opts.maxConcurrency ?? 2,
+ },
+ }, projectRoot);
+ if (policy.enforcedOutcome !== 'allowed') {
+ return { ran: false, reason: `policy-${policy.enforcedOutcome}:${policy.reason}; receipt=${policy.receiptId}` };
+ }
const neural = await import('../mcp-tools/neural-tools.js');
const applier = await import('../config/harness-feedback-applier.js');
const tool = neural.neuralTools.find((t) => t.name === 'neural_patterns');
@@ -116,6 +131,8 @@ export async function runFlywheelWorker(
})),
darwinInvoker: opts.darwinInvoker,
allowSubstitutionPromotion: opts.allowSubstitutionPromotion,
+ maxConcurrency: Math.max(1, Math.min(opts.maxConcurrency ?? 2, 8)),
+ maxWallTimeMs: opts.evaluationTimeoutMs ?? 120_000,
});
const candidatePolicies = archive.paretoCandidates.map((candidate) => candidate.policy as unknown as RetrievalConfig);
if (!candidatePolicies.length) return { ran: false, reason: 'proposer archive contained no admissible candidates' };
@@ -139,6 +156,8 @@ export async function runFlywheelWorker(
effectiveProposer: archive.effectiveProposer,
proposerSubstitution: archive.proposerSubstitution,
candidatePolicies,
+ maxConcurrency: Math.max(1, Math.min(opts.maxConcurrency ?? 2, 8)),
+ evaluationTimeoutMs: opts.evaluationTimeoutMs,
};
return await runFlywheelTick(projectRoot, deps);
} catch (e) {
diff --git a/v3/@claude-flow/cli/src/services/harness-flywheel.ts b/v3/@claude-flow/cli/src/services/harness-flywheel.ts
index 0becfe5dd6..0ffb76d84e 100644
--- a/v3/@claude-flow/cli/src/services/harness-flywheel.ts
+++ b/v3/@claude-flow/cli/src/services/harness-flywheel.ts
@@ -35,6 +35,7 @@ import {
readFlywheelTransactionState,
registerFlywheelReceipt,
} from './flywheel-transaction.js';
+import { runBoundedPool } from './bounded-worker-pool.js';
export interface RetrievalConfig { alpha: number; subjectWeight: number; mmrLambda: number; bodyWeight: number; typePenaltyFactor: number; }
export const DEFAULT_CONFIG: RetrievalConfig = { alpha: 0.5, subjectWeight: 2.0, mmrLambda: 0.7, bodyWeight: 1.0, typePenaltyFactor: 1.0 };
@@ -44,7 +45,11 @@ export interface AnchorTask { id: string; input: { id: string; q: string }; expe
export interface FlywheelDeps {
getPatterns: () => HarvestPattern[] | Promise<HarvestPattern[]>;
- search: (query: string, config: RetrievalConfig) => Promise<RankedItem[]> | RankedItem[];
+ search: (
+ query: string,
+ config: RetrievalConfig,
+ signal?: AbortSignal,
+ ) => Promise<RankedItem[]> | RankedItem[];
anchorTasks: AnchorTask[];
activeParams?: () => Partial<RetrievalConfig> | null;
sample?: number;
@@ -60,6 +65,9 @@ export interface FlywheelDeps {
bootstrapIterations?: number;
/** Candidate policies supplied by an external proposer archive (ADR-322B). */
candidatePolicies?: RetrievalConfig[];
+ /** ADR-324: hard local cap for concurrent candidate/task evaluation. */
+ maxConcurrency?: number;
+ evaluationTimeoutMs?: number;
}
export interface FlywheelResult {
@@ -163,12 +171,32 @@ export async function evaluateFlywheelCandidate(projectRoot: string, deps: Flywh
// Precompute retrieval for baseline + all candidates over every task (async
// I/O up front β†’ the harness scoring stays pure/sync).
const cache = new Map<string, RankedItem[]>();
- const configs = [baseline, ...candidates];
- for (const cfg of configs) {
- for (const t of blended.tasks) {
- const q = (t.input as { q: string }).q;
- cache.set(`${t.id}::${cfgKey(cfg)}`, (await deps.search(q, cfg)) || []);
- }
+ const configs = [...new Map(
+ [baseline, ...candidates].map((config) => [cfgKey(config), config]),
+ ).values()];
+ const evalTasks = configs.flatMap((cfg) => blended.tasks.map((t) => {
+ const cacheKey = `${t.id}::${cfgKey(cfg)}`;
+ return {
+ id: cacheKey,
+ run: async (signal: AbortSignal) => {
+ if (signal.aborted) throw signal.reason;
+ return (await deps.search((t.input as { q: string }).q, cfg, signal)) || [];
+ },
+ };
+ }));
+ const batch = await runBoundedPool(evalTasks, {
+ maxConcurrency: deps.maxConcurrency ?? 2,
+ timeoutMs: deps.evaluationTimeoutMs ?? 120_000,
+ });
+ for (const item of batch.results) {
+ if (item.status === 'fulfilled') cache.set(item.id, item.value ?? []);
+ }
+ const failedEvaluations = batch.results.filter((item) => item.status !== 'fulfilled');
+ if (failedEvaluations.length > 0) {
+ return {
+ ran: false,
+ reason: `candidate evaluation incomplete (${failedEvaluations.length}/${batch.results.length}); peak concurrency ${batch.peakConcurrency}`,
+ };
}
const evalFn = (input: unknown, cfg: RetrievalConfig) => cache.get(`${(input as { id: string }).id}::${cfgKey(cfg)}`) ?? [];
const gradeFn = (output: unknown, expected: unknown) => grade(output as RankedItem[], expected);
diff --git a/v3/@claude-flow/cli/src/services/policy-runtime.ts b/v3/@claude-flow/cli/src/services/policy-runtime.ts
new file mode 100644
index 0000000000..449316ffc7
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/policy-runtime.ts
@@ -0,0 +1,407 @@
+import {
+ AgenticPolicyEngine,
+ createLegacyCompatibleState,
+ type BudgetLimit,
+ type CapabilityEnvelope,
+ type PolicyApproval,
+ type PolicyDecision,
+ type PolicyEvidence,
+ type PolicyRequest,
+ type PolicyRule,
+ type PolicyState,
+} from '@claude-flow/security';
+import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import {
+ closeSync,
+ existsSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ realpathSync,
+ renameSync,
+ statSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { userInfo } from 'node:os';
+
+const POLICY_DIR = join('.claude-flow', 'policy');
+const POLICY_FILE = 'state.json';
+const LOCK_FILE = 'state.lock';
+const LOCK_STALE_MS = 30_000;
+const LOCK_WAIT_MS = 5_000;
+
+function paths(projectRoot: string): { dir: string; state: string; lock: string } {
+ const root = resolve(projectRoot);
+ const dir = join(root, POLICY_DIR);
+ return { dir, state: join(dir, POLICY_FILE), lock: join(dir, LOCK_FILE) };
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
+}
+
+async function acquireLock(lockPath: string): Promise<() => void> {
+ const started = Date.now();
+ while (Date.now() - started < LOCK_WAIT_MS) {
+ try {
+ const fd = openSync(lockPath, 'wx', 0o600);
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, acquiredAt: Date.now() }));
+ closeSync(fd);
+ return () => {
+ try { unlinkSync(lockPath); } catch { /* already released */ }
+ };
+ } catch {
+ try {
+ if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) unlinkSync(lockPath);
+ } catch { /* another process changed the lock */ }
+ await sleep(10);
+ }
+ }
+ throw new Error('policy-state-lock-timeout');
+}
+
+function writeJsonAtomic(file: string, value: unknown): void {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
+ renameSync(temporary, file);
+}
+
+function trustPaths(projectRoot: string): { key: string; anchor: string } {
+ const trustRoot = join(userInfo().homedir, '.config', 'ruflo', 'policy-trust');
+ const projectId = createHash('sha256').update(realpathSync(projectRoot)).digest('hex');
+ const dir = join(trustRoot, projectId);
+ return { key: join(dir, 'anchor.key'), anchor: join(dir, 'state.anchor.json') };
+}
+
+function trustKey(projectRoot: string, create: boolean): Buffer | undefined {
+ const { key } = trustPaths(projectRoot);
+ if (!existsSync(key)) {
+ if (!create) return undefined;
+ mkdirSync(dirname(key), { recursive: true, mode: 0o700 });
+ writeFileSync(key, randomBytes(32), { mode: 0o600, flag: 'wx' });
+ }
+ const material = readFileSync(key);
+ if (material.length !== 32) throw new Error('invalid-policy-trust-key');
+ return material;
+}
+
+function stateAuthentication(state: PolicyState, key: Buffer): string {
+ return createHmac('sha256', key).update(JSON.stringify(state)).digest('hex');
+}
+
+function verifyStateAnchor(projectRoot: string, state: PolicyState | undefined): void {
+ const { anchor } = trustPaths(projectRoot);
+ if (!existsSync(anchor)) return;
+ if (!state) throw new Error('policy-state-missing-for-anchored-project');
+ const key = trustKey(projectRoot, false);
+ if (!key) throw new Error('policy-trust-key-missing');
+ const record = JSON.parse(readFileSync(anchor, 'utf8')) as { authentication?: string };
+ const expected = stateAuthentication(state, key);
+ const actual = record.authentication ?? '';
+ if (!/^[a-f0-9]{64}$/.test(actual)
+ || !timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(actual, 'hex'))) {
+ throw new Error('policy-state-authentication-failed');
+ }
+}
+
+function writePolicyState(projectRoot: string, statePath: string, state: PolicyState): void {
+ const anchorPath = trustPaths(projectRoot).anchor;
+ if (state.mode === 'enforce' || existsSync(anchorPath)) {
+ const key = trustKey(projectRoot, true)!;
+ const anchor = {
+ version: 1,
+ projectRoot: realpathSync(projectRoot),
+ mode: state.mode,
+ authentication: stateAuthentication(state, key),
+ updatedAt: Date.now(),
+ };
+ // On first enforcement, establish the external trust record first. A
+ // crash then leaves either a valid pair or an anchored mismatch that
+ // fails closed; it can never leave enforce state silently unanchored.
+ if (!existsSync(anchorPath)) {
+ writeJsonAtomic(anchorPath, anchor);
+ writeJsonAtomic(statePath, state);
+ return;
+ }
+ writeJsonAtomic(statePath, state);
+ writeJsonAtomic(anchorPath, anchor);
+ return;
+ }
+ writeJsonAtomic(statePath, state);
+}
+
+function detectLegacyCapabilities(projectRoot: string): string {
+ const candidates = [
+ '.swarm/memory.db',
+ '.claude-flow/memory.db',
+ '.claude-flow/data/memory.db',
+ 'agentdb.rvf',
+ 'agentdb-memory.db',
+ ];
+ const found = candidates.filter((candidate) => existsSync(join(projectRoot, candidate)));
+ const flags = [
+ process.env.CLAUDE_FLOW_STRICT_AUTH === 'true' ? 'strict-auth' : null,
+ process.env.CLAUDE_FLOW_STRICT_MEMORY === 'true' ? 'strict-memory' : null,
+ ].filter(Boolean);
+ return `pre-ADR-324; capabilities=${[...found, ...flags].join(',') || 'none-detected'}`;
+}
+
+function configuredPolicyMode(projectRoot: string): PolicyState['mode'] | undefined {
+ let configured: PolicyState['mode'] | undefined;
+ for (const relative of ['.agents/config.toml', '.codex/config.toml']) {
+ const file = join(resolve(projectRoot), relative);
+ if (!existsSync(file)) continue;
+ const content = readFileSync(file, 'utf8');
+ const section = content.match(/(?:^|\n)\[policy\]\s*\n([\s\S]*?)(?=\n\[[^\]]+\]|\s*$)/)?.[1];
+ const mode = section?.match(/(?:^|\n)\s*mode\s*=\s*"(legacy|observe|enforce)"/)?.[1];
+ if (mode) configured = mode as PolicyState['mode'];
+ }
+ return configured;
+}
+
+export function loadPolicyState(projectRoot = process.cwd()): PolicyState {
+ const target = paths(projectRoot);
+ if (!existsSync(target.state)) {
+ verifyStateAnchor(projectRoot, undefined);
+ return createLegacyCompatibleState(detectLegacyCapabilities(projectRoot));
+ }
+ const parsed = JSON.parse(readFileSync(target.state, 'utf8')) as PolicyState;
+ if (parsed.version !== 1 || !Array.isArray(parsed.rules) || !Array.isArray(parsed.receipts)) {
+ throw new Error(`unsupported-policy-state-version:${String(parsed.version)}`);
+ }
+ verifyStateAnchor(projectRoot, parsed);
+ return parsed;
+}
+
+export async function autoMigratePolicyStateIfNeeded(projectRoot = process.cwd()): Promise<{
+ migrated: boolean;
+ statePath?: string;
+ mode?: PolicyState['mode'];
+}> {
+ const target = paths(projectRoot);
+ if (existsSync(target.state)) {
+ const configured = configuredPolicyMode(projectRoot);
+ const current = loadPolicyState(projectRoot);
+ if (configured && current.configuredMode !== configured) {
+ await withPolicyTransaction(projectRoot, (engine) => engine.setConfiguredMode(configured));
+ }
+ return { migrated: false, statePath: target.state, mode: loadPolicyState(projectRoot).mode };
+ }
+ // Only upgrade existing Ruflo installations. A random directory should not
+ // acquire policy state merely because `ruflo --version` ran there.
+ if (!existsSync(join(resolve(projectRoot), '.claude-flow'))
+ && !existsSync(join(resolve(projectRoot), '.swarm'))) return { migrated: false };
+ mkdirSync(target.dir, { recursive: true, mode: 0o700 });
+ const release = await acquireLock(target.lock);
+ try {
+ if (!existsSync(target.state)) {
+ const state = createLegacyCompatibleState(detectLegacyCapabilities(projectRoot));
+ const configured = configuredPolicyMode(projectRoot);
+ if (configured) {
+ state.mode = configured;
+ state.configuredMode = configured;
+ }
+ writePolicyState(projectRoot, target.state, state);
+ }
+ } finally {
+ release();
+ }
+ return { migrated: true, statePath: target.state, mode: loadPolicyState(projectRoot).mode };
+}
+
+export async function withPolicyTransaction<T>(
+ projectRoot: string,
+ operation: (engine: AgenticPolicyEngine) => T | Promise<T>,
+ options: {
+ approvalIssuerVerifier?: (issuer: string) => boolean;
+ } = {},
+): Promise<T> {
+ const target = paths(projectRoot);
+ mkdirSync(target.dir, { recursive: true, mode: 0o700 });
+ const release = await acquireLock(target.lock);
+ try {
+ const engine = AgenticPolicyEngine.fromState(loadPolicyState(projectRoot), {
+ signingKey: process.env.CLAUDE_FLOW_POLICY_SIGNING_KEY,
+ keyId: process.env.CLAUDE_FLOW_POLICY_KEY_ID,
+ evidenceVerifier: verifyPolicyEvidence,
+ approvalIssuerVerifier: options.approvalIssuerVerifier,
+ });
+ const result = await operation(engine);
+ const nextState = engine.exportState();
+ if (!engine.verifyLedger().valid) throw new Error('policy-ledger-verification-failed');
+ writePolicyState(projectRoot, target.state, nextState);
+ return result;
+ } finally {
+ release();
+ }
+}
+
+function verifyPolicyEvidence(evidence: PolicyEvidence): boolean {
+ if (!evidence.keyId || !evidence.contentHash || !evidence.signature) return false;
+ let keys: Record<string, string>;
+ try {
+ keys = JSON.parse(process.env.CLAUDE_FLOW_POLICY_EVIDENCE_KEYS ?? '{}') as Record<string, string>;
+ } catch {
+ return false;
+ }
+ const key = keys[evidence.keyId];
+ if (!key || key.length < 16 || !/^sha256:[a-f0-9]{64}$/i.test(evidence.contentHash)) return false;
+ const signedClaims = JSON.stringify({
+ id: evidence.id,
+ provenance: evidence.provenance,
+ attestor: evidence.attestor,
+ observedAt: evidence.observedAt,
+ contentHash: evidence.contentHash,
+ keyId: evidence.keyId,
+ });
+ const expected = createHmac('sha256', key).update(signedClaims).digest('hex');
+ const provided = evidence.signature.replace(/^hmac-sha256:/, '');
+ if (!/^[a-f0-9]{64}$/i.test(provided)) return false;
+ return timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(provided, 'hex'));
+}
+
+export async function evaluatePolicyRequest(
+ request: PolicyRequest,
+ projectRoot = process.cwd(),
+): Promise<PolicyDecision> {
+ return withPolicyTransaction(projectRoot, (engine) => engine.evaluate(request));
+}
+
+export async function setPolicyMode(mode: PolicyState['mode'], projectRoot = process.cwd()): Promise<void> {
+ return withPolicyTransaction(projectRoot, (engine) => engine.setMode(mode));
+}
+
+export async function upsertPolicyRule(rule: PolicyRule, projectRoot = process.cwd()): Promise<void> {
+ return withPolicyTransaction(projectRoot, (engine) => engine.upsertRule(rule));
+}
+
+export async function setPolicyBudget(limit: BudgetLimit, projectRoot = process.cwd()): Promise<void> {
+ return withPolicyTransaction(projectRoot, (engine) => engine.setBudget(limit));
+}
+
+export async function issuePolicyApproval(
+ approval: Omit<PolicyApproval, 'uses' | 'issuedAt'> & { uses?: number; issuedAt?: number },
+ projectRoot = process.cwd(),
+ approvalIssuerVerifier?: (issuer: string) => boolean,
+): Promise<PolicyApproval> {
+ return withPolicyTransaction(
+ projectRoot,
+ (engine) => engine.issueApproval(approval),
+ { approvalIssuerVerifier },
+ );
+}
+
+export async function revokePolicyApproval(id: string, projectRoot = process.cwd()): Promise<boolean> {
+ return withPolicyTransaction(projectRoot, (engine) => engine.revokeApproval(id));
+}
+
+export async function verifyPolicyLedger(projectRoot = process.cwd()): Promise<ReturnType<AgenticPolicyEngine['verifyLedger']>> {
+ return withPolicyTransaction(projectRoot, (engine) => engine.verifyLedger());
+}
+
+export async function authorizeMcpTool(
+ toolName: string,
+ input: Record<string, unknown>,
+ context: Record<string, unknown> = {},
+ attributes: Readonly<{
+ actionType?: string;
+ network?: boolean;
+ destructive?: boolean;
+ namespaceAccess?: 'read' | 'write';
+ envelope?: CapabilityEnvelope;
+ costUsd?: number;
+ tokens?: number;
+ concurrency?: number;
+ }> = {},
+): Promise<PolicyDecision> {
+ let projectRoot = typeof context.projectRoot === 'string' ? context.projectRoot : process.cwd();
+ let processEnvelope: CapabilityEnvelope | undefined;
+ if (process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE) {
+ try {
+ const parsed = JSON.parse(process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE) as unknown;
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('not an object');
+ }
+ processEnvelope = parsed as CapabilityEnvelope;
+ } catch {
+ throw new Error('invalid-worker-capability-envelope');
+ }
+ // Linked git worktrees share one immutable common git directory. Derive
+ // the coordinator checkout from that directory so a worker cannot fall
+ // back to independent legacy policy state in its isolated worktree.
+ try {
+ const cwd = realpathSync(process.cwd());
+ const common = execFileSync(
+ 'git',
+ ['-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
+ ).trim();
+ projectRoot = dirname(realpathSync(common));
+ } catch {
+ throw new Error('authoritative-worker-policy-root-unavailable');
+ }
+ }
+ return evaluatePolicyRequest({
+ identity: {
+ id: process.env.CLAUDE_FLOW_PRINCIPAL_ID ?? 'legacy-cli',
+ type: process.env.CLAUDE_FLOW_PRINCIPAL_ID ? 'agent' : 'legacy',
+ },
+ action: {
+ type: attributes.actionType ?? 'mcp.tool.call',
+ resource: toolName,
+ tool: toolName,
+ server: typeof context.serverId === 'string' ? context.serverId : 'ruflo',
+ namespace: typeof input.namespace === 'string' ? input.namespace : undefined,
+ environment: typeof context.environment === 'string' ? context.environment : undefined,
+ costUsd: attributes.costUsd,
+ tokens: attributes.tokens,
+ concurrency: attributes.concurrency,
+ network: attributes.network === true,
+ destructive: attributes.destructive === true,
+ },
+ context: {
+ envelope: attributes.envelope ?? processEnvelope,
+ approvalIds: Array.isArray(context.approvalIds) ? context.approvalIds.map(String) : undefined,
+ evidence: Array.isArray(context.evidence) ? context.evidence as PolicyEvidence[] : undefined,
+ metadata: {
+ inputDigest: `sha256:${createHash('sha256').update(JSON.stringify(input)).digest('hex')}`,
+ },
+ },
+ }, projectRoot);
+}
+
+/** Trusted classification derived from the registered tool name, never input. */
+export function classifyMcpTool(toolName: string): {
+ actionType: string;
+ network: boolean;
+ destructive: boolean;
+ namespaceAccess?: 'read' | 'write';
+} {
+ const normalized = toolName.toLowerCase();
+ const policyAdmin = normalized.startsWith('policy_')
+ && !['policy_evaluate', 'policy_status'].includes(normalized);
+ const memoryRead = /^(?:memory|agentdb)_(?:pattern-)?(?:search|query|get|retrieve|list|status|stats)/.test(normalized);
+ const memoryWrite = /^(?:memory|agentdb)_(?:pattern-)?(?:store|insert|update|delete|clear|purge|init)/.test(normalized);
+ const terminal = /^(?:terminal_execute|bash|shell|exec)/.test(normalized);
+ const destructive = policyAdmin
+ || terminal
+ || /(delete|remove|clear|purge|revoke|promote|deploy|integrate|cleanup|terminate|stop)/.test(normalized);
+ const network = terminal
+ || /(github|browser|web_|http_|fetch|managed_agent|federation|ipfs|openrouter|provider)/.test(normalized);
+ return {
+ actionType: policyAdmin
+ ? `policy.admin.${normalized.slice('policy_'.length)}`
+ : memoryRead
+ ? 'memory.read'
+ : memoryWrite
+ ? 'memory.write'
+ : 'mcp.tool.call',
+ network,
+ destructive,
+ namespaceAccess: memoryRead ? 'read' : memoryWrite ? 'write' : undefined,
+ };
+}
diff --git a/v3/@claude-flow/cli/vitest.config.ts b/v3/@claude-flow/cli/vitest.config.ts
index d929c91713..67e0d5ac90 100644
--- a/v3/@claude-flow/cli/vitest.config.ts
+++ b/v3/@claude-flow/cli/vitest.config.ts
@@ -1,8 +1,14 @@
import { defineConfig } from 'vitest/config';
+import { fileURLToPath } from 'node:url';
export default defineConfig({
resolve: {
conditions: ['node'],
+ // Exercise the workspace security source rather than a stale installed
+ // package during cross-package policy integration tests (ADR-324).
+ alias: {
+ '@claude-flow/security': fileURLToPath(new URL('../security/src/index.ts', import.meta.url)),
+ },
},
plugins: [
{
diff --git a/v3/@claude-flow/codex/AGENTS.md b/v3/@claude-flow/codex/AGENTS.md
index d18d5783d4..fc3f6ce7e5 100644
--- a/v3/@claude-flow/codex/AGENTS.md
+++ b/v3/@claude-flow/codex/AGENTS.md
@@ -60,6 +60,25 @@ This project uses hierarchical swarm coordination for complex tasks:
- Documentation updates
- Configuration changes
+### Policy-Governed Concurrent Execution
+
+- Ruflo coordinates and records policy decisions; Codex workers execute.
+- Search AgentDB before planning and store validated patterns after success.
+- Use bounded fanout only for independent tasks.
+- Every writing worker gets a unique git worktree and a reduced capability
+ envelope. Never place two writers in one worktree.
+- Read-only researchers may share a checkout.
+- One integration agent owns shared manifests/lockfiles, consumes committed
+ handoffs in dependency order, and runs scoped then full tests.
+- Cancel dependent and not-yet-started sibling work on policy denial or dependency failure.
+- MetaHarness can benchmark candidates concurrently but cannot authorize its
+ own promotion or expand network, provider, spend, secret, or concurrency
+ scope.
+- Do not auto-commit, push, merge, release, or delete worktrees without user
+ authorization.
+- Existing projects start in ADR-324 `legacy` mode, may rehearse in `observe`,
+ and opt into `enforce` after reviewing receipts.
+
### Available Skills
Use `$skill-name` syntax to invoke:
diff --git a/v3/@claude-flow/codex/package.json b/v3/@claude-flow/codex/package.json
index 975cf35b04..046ae9ceef 100644
--- a/v3/@claude-flow/codex/package.json
+++ b/v3/@claude-flow/codex/package.json
@@ -39,6 +39,11 @@
"types": "./dist/loop/index.d.ts",
"import": "./dist/loop/index.js",
"require": "./dist/loop/index.js"
+ },
+ "./worktrees": {
+ "types": "./dist/worktrees/index.d.ts",
+ "import": "./dist/worktrees/index.js",
+ "require": "./dist/worktrees/index.js"
}
},
"files": [
diff --git a/v3/@claude-flow/codex/src/cli.ts b/v3/@claude-flow/codex/src/cli.ts
index 143ddcb517..13c102f31f 100644
--- a/v3/@claude-flow/codex/src/cli.ts
+++ b/v3/@claude-flow/codex/src/cli.ts
@@ -696,6 +696,38 @@ program.addCommand(createDualModeCommand());
import { createLoopCommand } from './loop/cli.js';
program.addCommand(createLoopCommand());
+// Policy-governed worktree isolation for concurrent Codex writers (ADR-324)
+import { CodexWorktreeCoordinator } from './worktrees/index.js';
+const worktree = program.command('worktree').description('Prepare, inspect, integrate, or clean registry-owned Codex swarm worktrees');
+worktree.command('prepare <run-id>')
+ .requiredOption('--agents <ids>', 'Comma-separated writing-agent IDs')
+ .option('--read-only <ids>', 'Comma-separated read-only agent IDs')
+ .option('--base <ref>', 'Git base ref', 'HEAD')
+ .option('--allow-dirty', 'Allow creating worktrees from a dirty coordinator checkout', false)
+ .option('-p, --path <path>', 'Repository root', process.cwd())
+ .action((runId, options) => {
+ const writers = String(options.agents).split(',').map((id) => id.trim()).filter(Boolean).map((id) => ({ id }));
+ const readers = String(options.readOnly ?? '').split(',').map((id) => id.trim()).filter(Boolean).map((id) => ({ id, readOnly: true }));
+ const result = new CodexWorktreeCoordinator(options.path).prepare(runId, [...writers, ...readers], {
+ allowDirty: options.allowDirty,
+ baseRef: options.base,
+ });
+ console.log(JSON.stringify(result, null, 2));
+ });
+worktree.command('status <run-id>')
+ .option('-p, --path <path>', 'Repository root', process.cwd())
+ .action((runId, options) => console.log(JSON.stringify(new CodexWorktreeCoordinator(options.path).status(runId), null, 2)));
+worktree.command('integrate <run-id>')
+ .option('--agents <ids>', 'Comma-separated agent IDs; defaults to all writers')
+ .option('-p, --path <path>', 'Repository root', process.cwd())
+ .action((runId, options) => {
+ const ids = options.agents ? String(options.agents).split(',').map((id) => id.trim()).filter(Boolean) : undefined;
+ console.log(JSON.stringify(new CodexWorktreeCoordinator(options.path).integrate(runId, ids), null, 2));
+ });
+worktree.command('cleanup <run-id>')
+ .option('-p, --path <path>', 'Repository root', process.cwd())
+ .action((runId, options) => console.log(JSON.stringify(new CodexWorktreeCoordinator(options.path).cleanup(runId), null, 2)));
+
// Error handling for unknown commands
program.on('command:*', () => {
console.error(chalk.red(`Invalid command: ${program.args.join(' ')}`));
diff --git a/v3/@claude-flow/codex/src/dual-mode/cli.ts b/v3/@claude-flow/codex/src/dual-mode/cli.ts
index bdd855156c..9f12aa02ea 100644
--- a/v3/@claude-flow/codex/src/dual-mode/cli.ts
+++ b/v3/@claude-flow/codex/src/dual-mode/cli.ts
@@ -11,7 +11,9 @@ import {
WorkerConfig,
CollaborationTemplates,
CollaborationResult,
+ loadSwarmAutomationConfig,
} from './orchestrator.js';
+import { CodexWorktreeCoordinator } from '../worktrees/coordinator.js';
/**
* Create the dual-mode command
@@ -43,8 +45,8 @@ function createRunCommand(): Command {
.option('--parallel-workers', 'Run --worker specs in parallel instead of chaining them sequentially', false)
.option('-c, --config <path>', 'Path to collaboration config JSON')
.option('--task <description>', 'Task description for the swarm')
- .option('--max-concurrent <n>', 'Maximum concurrent workers', '4')
- .option('--timeout <ms>', 'Worker timeout in milliseconds', '300000')
+ .option('--max-concurrent <n>', 'Maximum concurrent workers (bounded by .agents/config.toml)')
+ .option('--timeout <ms>', 'Worker timeout in milliseconds (bounded by .agents/config.toml)')
.option('--namespace <name>', 'Shared memory namespace', 'collaboration')
.action(async (templateArg: string | undefined, options) => {
console.log(chalk.cyan('═══════════════════════════════════════════════════════════════'));
@@ -53,10 +55,25 @@ function createRunCommand(): Command {
console.log(chalk.cyan('═══════════════════════════════════════════════════════════════'));
console.log();
+ const automation = loadSwarmAutomationConfig(process.cwd());
+ if (!automation.enabled) {
+ throw new Error('unattended swarm automation is disabled; set [swarm.automation] enabled = true');
+ }
+ const requestedConcurrency = options.maxConcurrent
+ ? parseInt(options.maxConcurrent, 10)
+ : automation.maxConcurrent;
+ const requestedTimeout = options.timeout
+ ? parseInt(options.timeout, 10)
+ : automation.agentTimeoutSeconds * 1000;
const config: DualModeConfig = {
projectPath: process.cwd(),
- maxConcurrent: parseInt(options.maxConcurrent, 10),
- timeout: parseInt(options.timeout, 10),
+ maxConcurrent: Math.min(requestedConcurrency, automation.maxConcurrent),
+ maxWriters: automation.maxWriters,
+ worktreeIsolation: automation.worktreeIsolation,
+ dependencyFailure: automation.dependencyFailure,
+ timeout: Math.min(requestedTimeout, automation.agentTimeoutSeconds * 1000),
+ maxOutputBytes: automation.maxOutputBytes,
+ policyPreflight: true,
sharedNamespace: options.namespace,
};
@@ -110,6 +127,24 @@ function createRunCommand(): Command {
return;
}
+ if (automation.worktreeIsolation) {
+ const runId = `dual-${Date.now().toString(36)}`;
+ const coordinator = new CodexWorktreeCoordinator(process.cwd());
+ const record = coordinator.prepare(
+ runId,
+ workers.map((worker) => ({
+ id: worker.id,
+ ...(worker.readOnly === undefined ? {} : { readOnly: worker.readOnly }),
+ })),
+ );
+ const assignments = new Map(record.assignments.map((item) => [item.agentId, item.path]));
+ workers = workers.map((worker) => {
+ const worktreePath = assignments.get(worker.id);
+ return { ...worker, ...(worktreePath ? { worktreePath } : {}) };
+ });
+ console.log(chalk.gray(` Worktree run: ${runId} (retained for explicit integrate/cleanup)`));
+ }
+
console.log();
console.log(chalk.bold('Swarm Configuration:'));
console.log(` Workers: ${workers.length}`);
diff --git a/v3/@claude-flow/codex/src/dual-mode/index.ts b/v3/@claude-flow/codex/src/dual-mode/index.ts
index 23409fcc9a..6c314bfebf 100644
--- a/v3/@claude-flow/codex/src/dual-mode/index.ts
+++ b/v3/@claude-flow/codex/src/dual-mode/index.ts
@@ -3,12 +3,18 @@
* Collaborative execution of Claude Code + Codex workers
*/
-export { DualModeOrchestrator, CollaborationTemplates } from './orchestrator.js';
+export {
+ DualModeOrchestrator,
+ CollaborationTemplates,
+ loadSwarmAutomationConfig,
+} from './orchestrator.js';
export type {
DualModeConfig,
WorkerConfig,
WorkerResult,
CollaborationResult,
+ LoadedSwarmAutomationConfig,
+ WorkerCapabilityEnvelope,
} from './orchestrator.js';
export { createDualModeCommand } from './cli.js';
diff --git a/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts b/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts
index b3db06ba7d..080c57c107 100644
--- a/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts
+++ b/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts
@@ -7,6 +7,18 @@ import { spawn, ChildProcess } from 'child_process';
import { EventEmitter } from 'events';
import * as path from 'path';
import * as fs from 'fs';
+import * as TOML from '@iarna/toml';
+
+export interface WorkerCapabilityEnvelope {
+ actions?: string[];
+ resources?: string[];
+ tools?: string[];
+ maxConcurrency?: number;
+ network?: boolean;
+ destructive?: boolean;
+ delegationDepth?: number;
+ expiresAt?: number;
+}
export interface WorkerConfig {
id: string;
@@ -17,13 +29,17 @@ export interface WorkerConfig {
maxTurns?: number;
timeout?: number;
dependsOn?: string[];
+ /** Required for concurrent writing roles; each writer must own one cwd. */
+ worktreePath?: string;
+ readOnly?: boolean;
+ capabilityEnvelope?: WorkerCapabilityEnvelope;
}
export interface WorkerResult {
id: string;
platform: 'claude' | 'codex';
role: string;
- status: 'pending' | 'running' | 'completed' | 'failed';
+ status: 'pending' | 'running' | 'completed' | 'failed' | 'skipped';
output?: string;
error?: string;
startedAt?: Date;
@@ -38,6 +54,11 @@ export interface DualModeConfig {
timeout?: number;
claudeCommand?: string;
codexCommand?: string;
+ maxOutputBytes?: number;
+ maxWriters?: number;
+ worktreeIsolation?: boolean;
+ dependencyFailure?: 'cancel' | 'skip';
+ policyPreflight?: boolean;
}
export interface CollaborationResult {
@@ -58,6 +79,15 @@ export class DualModeOrchestrator extends EventEmitter {
constructor(config: DualModeConfig) {
super();
+ if (!Number.isInteger(config.maxConcurrent ?? 4) || (config.maxConcurrent ?? 4) < 1) {
+ throw new Error('maxConcurrent must be a positive integer');
+ }
+ if (!Number.isFinite(config.maxOutputBytes ?? 1_048_576) || (config.maxOutputBytes ?? 1_048_576) < 1) {
+ throw new Error('maxOutputBytes must be positive');
+ }
+ if (!Number.isInteger(config.maxWriters ?? 2) || (config.maxWriters ?? 2) < 1) {
+ throw new Error('maxWriters must be a positive integer');
+ }
this.config = {
projectPath: config.projectPath,
maxConcurrent: config.maxConcurrent ?? 4,
@@ -65,6 +95,11 @@ export class DualModeOrchestrator extends EventEmitter {
timeout: config.timeout ?? 300000, // 5 minutes
claudeCommand: config.claudeCommand ?? 'claude',
codexCommand: config.codexCommand ?? 'codex',
+ maxOutputBytes: config.maxOutputBytes ?? 1_048_576,
+ maxWriters: config.maxWriters ?? 2,
+ worktreeIsolation: config.worktreeIsolation ?? false,
+ dependencyFailure: config.dependencyFailure ?? 'cancel',
+ policyPreflight: config.policyPreflight ?? false,
};
}
@@ -77,7 +112,7 @@ export class DualModeOrchestrator extends EventEmitter {
// Initialize memory database
await this.runCommand(
'npx',
- ['ruflo@latest', 'memory', 'init', '--force'],
+ ['ruflo@latest', 'memory', 'init'],
projectPath
);
@@ -114,6 +149,18 @@ export class DualModeOrchestrator extends EventEmitter {
await this.waitForDependencies(config.dependsOn);
}
+ if (this.config.policyPreflight) {
+ try {
+ await this.authorizeWorker(config);
+ } catch (error) {
+ result.status = 'failed';
+ result.error = error instanceof Error ? error.message : String(error);
+ result.completedAt = new Date();
+ this.emit('worker:failed', { id: config.id, error: result.error });
+ throw error;
+ }
+ }
+
result.status = 'running';
result.startedAt = new Date();
this.emit('worker:started', { id: config.id, role: config.role, platform: config.platform });
@@ -136,7 +183,7 @@ export class DualModeOrchestrator extends EventEmitter {
* Execute a headless Claude/Codex instance
*/
private async executeHeadless(config: WorkerConfig): Promise<string> {
- const { projectPath, timeout } = this.config;
+ const { projectPath, timeout, maxOutputBytes } = this.config;
const command = config.platform === 'claude' ? this.config.claudeCommand : this.config.codexCommand;
// Build the prompt with memory integration
@@ -156,7 +203,10 @@ export class DualModeOrchestrator extends EventEmitter {
args.push('--model', config.model);
}
} else {
- args = ['exec', '--sandbox', 'workspace-write', '--skip-git-repo-check'];
+ args = ['exec', '--sandbox',
+ config.readOnly ? 'read-only' : 'workspace-write',
+ '--skip-git-repo-check',
+ ];
if (config.model) {
args.push('-m', config.model);
}
@@ -168,19 +218,19 @@ export class DualModeOrchestrator extends EventEmitter {
let errorOutput = '';
const proc = spawn(command, args, {
- cwd: projectPath,
- env: { ...process.env, FORCE_COLOR: '0' },
+ cwd: config.worktreePath ? path.resolve(config.worktreePath) : projectPath,
+ env: this.workerEnvironment(config),
stdio: ['pipe', 'pipe', 'pipe'],
});
this.processes.set(config.id, proc);
proc.stdout?.on('data', (data) => {
- output += data.toString();
+ if (output.length < maxOutputBytes) output += data.toString().slice(0, maxOutputBytes - output.length);
});
proc.stderr?.on('data', (data) => {
- errorOutput += data.toString();
+ if (errorOutput.length < maxOutputBytes) errorOutput += data.toString().slice(0, maxOutputBytes - errorOutput.length);
});
const timer = setTimeout(() => {
@@ -192,7 +242,7 @@ export class DualModeOrchestrator extends EventEmitter {
clearTimeout(timer);
this.processes.delete(config.id);
- if (code === 0 || output.length > 0) {
+ if (code === 0) {
resolve(output || errorOutput);
} else {
reject(new Error(`Worker ${config.id} exited with code ${code}: ${errorOutput}`));
@@ -215,7 +265,7 @@ export class DualModeOrchestrator extends EventEmitter {
return `You are a ${config.role.toUpperCase()} agent in a collaborative dual-mode swarm.
Platform: ${config.platform === 'claude' ? 'Claude Code' : 'OpenAI Codex'}
-Working Directory: ${projectPath}
+Working Directory: ${config.worktreePath ? path.resolve(config.worktreePath) : projectPath}
Shared Memory Namespace: ${sharedNamespace}
COLLABORATION PROTOCOL:
@@ -265,14 +315,47 @@ Remember: Other agents depend on your results in shared memory. Be concise and s
// Group workers by dependency level
const levels = this.buildDependencyLevels(workers);
- // Execute each level in parallel
- for (const level of levels) {
- const promises = level.map(worker =>
- this.spawnWorker(worker).catch(err => {
- errors.push(`${worker.id}: ${err.message}`);
- })
- );
- await Promise.all(promises);
+ // Execute each level with a hard concurrency cap.
+ let cancelled = false;
+ collaboration: for (const level of levels) {
+ for (const batch of this.partitionLevel(level)) {
+ await Promise.all(batch.map(async (worker) => {
+ const failedDependency = worker.dependsOn?.find((id) => this.workers.get(id)?.status !== 'completed');
+ if (failedDependency) {
+ this.workers.set(worker.id, {
+ id: worker.id,
+ platform: worker.platform,
+ role: worker.role,
+ status: 'skipped',
+ error: `dependency failed: ${failedDependency}`,
+ });
+ errors.push(`${worker.id}: dependency failed: ${failedDependency}`);
+ return;
+ }
+ await this.spawnWorker(worker).catch(err => {
+ errors.push(`${worker.id}: ${err.message}`);
+ });
+ const result = this.workers.get(worker.id);
+ if (result?.status === 'failed') errors.push(`${worker.id}: ${result.error}`);
+ }));
+ if (this.config.dependencyFailure === 'cancel'
+ && batch.some((worker) => this.workers.get(worker.id)?.status === 'failed')) {
+ cancelled = true;
+ break collaboration;
+ }
+ }
+ }
+ if (cancelled) {
+ for (const worker of workers) {
+ if (this.workers.has(worker.id)) continue;
+ this.workers.set(worker.id, {
+ id: worker.id,
+ platform: worker.platform,
+ role: worker.role,
+ status: 'skipped',
+ error: 'collaboration cancelled after worker failure',
+ });
+ }
}
// Collect shared memory results
@@ -291,6 +374,16 @@ Remember: Other agents depend on your results in shared memory. Be concise and s
* Build dependency levels for parallel execution
*/
private buildDependencyLevels(workers: WorkerConfig[]): WorkerConfig[][] {
+ const ids = new Set<string>();
+ for (const worker of workers) {
+ if (!worker.id || ids.has(worker.id)) throw new Error(`duplicate worker id: ${worker.id}`);
+ ids.add(worker.id);
+ }
+ for (const worker of workers) {
+ for (const dependency of worker.dependsOn ?? []) {
+ if (!ids.has(dependency)) throw new Error(`worker ${worker.id} depends on missing worker ${dependency}`);
+ }
+ }
const levels: WorkerConfig[][] = [];
const placed = new Set<string>();
@@ -309,12 +402,8 @@ Remember: Other agents depend on your results in shared memory. Be concise and s
}
if (level.length === 0 && placed.size < workers.length) {
- // Circular dependency detected, add remaining
- for (const worker of workers) {
- if (!placed.has(worker.id)) {
- level.push(worker);
- }
- }
+ const remaining = workers.filter((worker) => !placed.has(worker.id)).map((worker) => worker.id);
+ throw new Error(`worker dependency cycle: ${remaining.join(', ')}`);
}
for (const worker of level) {
@@ -326,9 +415,46 @@ Remember: Other agents depend on your results in shared memory. Be concise and s
}
}
+ for (const level of levels) {
+ const writerPaths = new Set<string>();
+ const writers = level.filter((item) => !item.readOnly);
+ for (const worker of writers) {
+ if (this.config.worktreeIsolation && !worker.worktreePath) {
+ throw new Error(`writer ${worker.id} requires an isolated worktree`);
+ }
+ const writerPath = path.resolve(worker.worktreePath ?? this.config.projectPath);
+ if (this.config.worktreeIsolation && writerPaths.has(writerPath)) {
+ throw new Error(`concurrent writers must use distinct worktrees: ${writerPath}`);
+ }
+ writerPaths.add(writerPath);
+ }
+ }
return levels;
}
+ /** Preserve read-only parallelism while independently bounding writers. */
+ private partitionLevel(level: WorkerConfig[]): WorkerConfig[][] {
+ const remaining = [...level];
+ const batches: WorkerConfig[][] = [];
+ while (remaining.length > 0) {
+ const batch: WorkerConfig[] = [];
+ let writers = 0;
+ for (let index = 0; index < remaining.length && batch.length < this.config.maxConcurrent;) {
+ const candidate = remaining[index]!;
+ if (!candidate.readOnly && writers >= this.config.maxWriters) {
+ index += 1;
+ continue;
+ }
+ batch.push(candidate);
+ if (!candidate.readOnly) writers += 1;
+ remaining.splice(index, 1);
+ }
+ // maxWriters is validated as positive, so at least one item is schedulable.
+ batches.push(batch);
+ }
+ return batches;
+ }
+
/**
* Collect results from shared memory
*/
@@ -371,6 +497,92 @@ Remember: Other agents depend on your results in shared memory. Be concise and s
});
}
+ private async authorizeWorker(worker: WorkerConfig): Promise<void> {
+ const envelope = this.resolveWorkerEnvelope(worker);
+ const request = {
+ identity: { id: `agent:${worker.id}`, type: 'agent', roles: [worker.role] },
+ action: {
+ type: 'swarm.worker.spawn',
+ resource: worker.worktreePath ?? this.config.projectPath,
+ tool: worker.platform,
+ concurrency: 1,
+ network: false,
+ destructive: false,
+ },
+ context: {
+ metadata: { childCapabilityEnvelope: envelope },
+ },
+ };
+ const raw = await this.runCommand(
+ 'npx',
+ ['ruflo@latest', 'policy', 'evaluate', JSON.stringify(request)],
+ this.config.projectPath,
+ );
+ const decision = JSON.parse(raw) as { enforcedOutcome?: string; reason?: string };
+ if (decision.enforcedOutcome !== 'allowed') {
+ throw new Error(`worker policy denied: ${decision.reason ?? 'unknown reason'}`);
+ }
+ worker.capabilityEnvelope = envelope;
+ }
+
+ private defaultWorkerEnvelope(worker: WorkerConfig): WorkerCapabilityEnvelope {
+ return {
+ actions: ['*'],
+ resources: ['*'],
+ tools: ['*'],
+ maxConcurrency: 1,
+ network: false,
+ destructive: false,
+ delegationDepth: 0,
+ expiresAt: Date.now() + this.config.timeout,
+ };
+ }
+
+ private resolveWorkerEnvelope(worker: WorkerConfig): WorkerCapabilityEnvelope {
+ const parent = this.defaultWorkerEnvelope(worker);
+ const requested = worker.capabilityEnvelope;
+ if (!requested) return parent;
+ const child = { ...parent, ...requested };
+ const matches = (patterns: string[] | undefined, value: string): boolean => (
+ !patterns?.length
+ || patterns.some((pattern) => pattern === '*' || pattern === value
+ || (pattern.endsWith('*') && value.startsWith(pattern.slice(0, -1))))
+ );
+ const subset = (values: string[] | undefined, patterns: string[] | undefined): boolean => (
+ !patterns?.length || (!!values?.length && values.every((value) => matches(patterns, value)))
+ );
+ const valid = subset(child.actions, parent.actions)
+ && subset(child.resources, parent.resources)
+ && subset(child.tools, parent.tools)
+ && (parent.maxConcurrency === undefined
+ || (child.maxConcurrency !== undefined && child.maxConcurrency <= parent.maxConcurrency))
+ && (parent.expiresAt === undefined
+ || (child.expiresAt !== undefined && child.expiresAt <= parent.expiresAt))
+ && (parent.delegationDepth === undefined
+ || (child.delegationDepth !== undefined && child.delegationDepth <= parent.delegationDepth))
+ && !(child.network === true && parent.network !== true)
+ && !(child.destructive === true && parent.destructive !== true);
+ if (!valid) throw new Error(`worker ${worker.id} capability envelope cannot expand`);
+ return child;
+ }
+
+ private workerEnvironment(worker: WorkerConfig): NodeJS.ProcessEnv {
+ const env: NodeJS.ProcessEnv = {};
+ const sensitive = /(?:^|_)(?:API_?KEY|KEY|SECRET|TOKEN|PASSWORD|CREDENTIALS?)$/i;
+ for (const [name, value] of Object.entries(process.env)) {
+ if (sensitive.test(name)
+ || name.startsWith('CLAUDE_FLOW_POLICY_')
+ || name === 'CLAUDE_FLOW_PRINCIPAL_ID') continue;
+ env[name] = value;
+ }
+ env.FORCE_COLOR = '0';
+ env.CLAUDE_FLOW_PRINCIPAL_ID = `agent:${worker.id}`;
+ env.CLAUDE_FLOW_CAPABILITY_ENVELOPE = JSON.stringify(
+ this.resolveWorkerEnvelope(worker),
+ );
+ return env;
+ }
+
/**
* Stop all running workers
*/
@@ -383,6 +595,51 @@ Remember: Other agents depend on your results in shared memory. Be concise and s
}
}
+export interface LoadedSwarmAutomationConfig {
+ enabled: boolean;
+ maxConcurrent: number;
+ maxWriters: number;
+ worktreeIsolation: boolean;
+ agentTimeoutSeconds: number;
+ maxOutputBytes: number;
+ dependencyFailure: 'cancel' | 'skip';
+}
+
+export function loadSwarmAutomationConfig(projectPath: string): LoadedSwarmAutomationConfig {
+ const defaults: LoadedSwarmAutomationConfig = {
+ enabled: false,
+ maxConcurrent: 4,
+ maxWriters: 2,
+ worktreeIsolation: true,
+ agentTimeoutSeconds: 1800,
+ maxOutputBytes: 1_048_576,
+ dependencyFailure: 'cancel',
+ };
+ const file = [
+ path.join(projectPath, '.agents', 'config.toml'),
+ path.join(projectPath, '.codex', 'config.toml'),
+ ].find((candidate) => fs.existsSync(candidate));
+ if (!file) return defaults;
+ const parsed = TOML.parse(fs.readFileSync(file, 'utf8')) as {
+ swarm?: { automation?: Record<string, unknown> };
+ };
+ const automation = parsed.swarm?.automation;
+ if (!automation) return defaults;
+ const integer = (name: string, fallback: number): number => {
+ const value = automation[name];
+ return Number.isInteger(value) && Number(value) > 0 ? Number(value) : fallback;
+ };
+ return {
+ enabled: automation.enabled === true,
+ maxConcurrent: integer('max_concurrent', defaults.maxConcurrent),
+ maxWriters: integer('max_writers', defaults.maxWriters),
+ worktreeIsolation: automation.worktree_isolation !== false,
+ agentTimeoutSeconds: integer('agent_timeout_seconds', defaults.agentTimeoutSeconds),
+ maxOutputBytes: integer('max_output_bytes', defaults.maxOutputBytes),
+ dependencyFailure: automation.dependency_failure === 'skip' ? 'skip' : 'cancel',
+ };
+}
+
/**
* Pre-built collaboration templates
*/
@@ -395,6 +652,7 @@ export const CollaborationTemplates = {
id: 'architect',
platform: 'claude',
role: 'architect',
+ readOnly: true,
prompt: `Design the architecture for: ${feature}. Define components, interfaces, and data flow.`,
maxTurns: 10,
},
@@ -418,6 +676,7 @@ export const CollaborationTemplates = {
id: 'reviewer',
platform: 'claude',
role: 'reviewer',
+ readOnly: true,
prompt: `Review the code and tests for quality, security, and best practices.`,
dependsOn: ['coder', 'tester'],
maxTurns: 8,
@@ -432,6 +691,7 @@ export const CollaborationTemplates = {
id: 'scanner',
platform: 'codex',
role: 'security-scanner',
+ readOnly: true,
prompt: `Scan ${target} for security vulnerabilities. Check OWASP Top 10.`,
maxTurns: 10,
},
@@ -439,6 +699,7 @@ export const CollaborationTemplates = {
id: 'analyzer',
platform: 'claude',
role: 'security-analyst',
+ readOnly: true,
prompt: `Analyze scan results and identify critical vulnerabilities.`,
dependsOn: ['scanner'],
maxTurns: 8,
@@ -461,6 +722,7 @@ export const CollaborationTemplates = {
id: 'analyzer',
platform: 'claude',
role: 'code-analyzer',
+ readOnly: true,
prompt: `Analyze ${target} for refactoring opportunities. Identify code smells.`,
maxTurns: 8,
},
@@ -468,6 +730,7 @@ export const CollaborationTemplates = {
id: 'planner',
platform: 'claude',
role: 'refactor-planner',
+ readOnly: true,
prompt: `Create a refactoring plan based on the analysis.`,
dependsOn: ['analyzer'],
maxTurns: 6,
@@ -484,6 +747,7 @@ export const CollaborationTemplates = {
id: 'validator',
platform: 'codex',
role: 'validator',
+ readOnly: true,
prompt: `Run tests and validate the refactoring didn't break anything.`,
dependsOn: ['refactorer'],
maxTurns: 5,
diff --git a/v3/@claude-flow/codex/src/generators/agents-md.ts b/v3/@claude-flow/codex/src/generators/agents-md.ts
index 938f1fe8a7..9a2c9a78bd 100644
--- a/v3/@claude-flow/codex/src/generators/agents-md.ts
+++ b/v3/@claude-flow/codex/src/generators/agents-md.ts
@@ -8,6 +8,32 @@
import type { AgentsMdOptions, AgentsMdTemplate } from '../types.js';
import { BUILT_IN_SKILLS } from '../templates/index.js';
+function concurrentRufloWorkflow(): string {
+ return `## Ruflo + Codex Automated Workflow
+
+Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation.
+
+1. Search AgentDB memory for relevant patterns and constraints.
+2. Initialize one bounded hierarchical Ruflo swarm and register the task.
+3. Split only independent work into concurrent Codex workers.
+4. Give every writing worker a distinct git worktree and a reduced capability envelope.
+5. Keep dependency/lockfiles under one designated owner.
+6. Have the parent integrate committed handoffs in dependency order and run scoped, then full verification.
+7. Store the successful pattern and policy receipt after validation.
+
+### Concurrency and authority invariants
+
+- Never allow two writers in one worktree.
+- Read-only research agents may share a checkout; writing agents may not.
+- A child may drop capabilities but can never add tools, servers, namespaces, network access, spend, concurrency, or delegation depth.
+- Cancel dependent and not-yet-started sibling work when policy denies an action or a required dependency fails.
+- MetaHarness may benchmark candidates concurrently, but it cannot promote, serve, or expand its own SafetyEnvelope.
+- Only the integration agent changes shared manifests or lockfiles.
+- Do not auto-commit, push, merge, release, or delete worktrees unless the user authorized that operation.
+- Every consequential action must produce a policy decision receipt; production, destructive, spend, and promotion actions may require human approval.
+`;
+}
+
/**
* Generate an AGENTS.md file based on the provided options
*/
@@ -83,6 +109,8 @@ ${testCommand}
- Use parameterized queries for databases
- Sanitize output to prevent XSS
+${concurrentRufloWorkflow()}
+
## Links
- Documentation: https://github.com/ruvnet/ruflo
@@ -199,6 +227,8 @@ ${skillsTable}
**Critical rule:** DON'T STOP after calling claude-flow commands. Coordination commands return instantly β€” continue immediately with the next implementation step.
+${concurrentRufloWorkflow()}
+
## MCP Integration
Use MCP tools for coordination, then keep coding:
diff --git a/v3/@claude-flow/codex/src/generators/config-toml.ts b/v3/@claude-flow/codex/src/generators/config-toml.ts
index 9e7bf5c0e9..5835d3ca0e 100644
--- a/v3/@claude-flow/codex/src/generators/config-toml.ts
+++ b/v3/@claude-flow/codex/src/generators/config-toml.ts
@@ -5,6 +5,7 @@
*/
import type { ConfigTomlOptions, McpServerConfig, SkillConfig, ConfigProfile } from '../types.js';
+import { getRufloMcpServerConfig, renderMcpServerToml } from '../mcp-config.js';
/**
* Security configuration options
@@ -70,6 +71,8 @@ export async function generateConfigToml(options: ExtendedConfigTomlOptions = {}
security = {},
performance = {},
logging = {},
+ policy = {},
+ swarmAutomation = {},
} = options;
const lines: string[] = [];
@@ -85,6 +88,7 @@ export async function generateConfigToml(options: ExtendedConfigTomlOptions = {}
lines.push('# Place in .agents/config.toml (project) or .codex/config.toml (user).');
lines.push('# =============================================================================');
lines.push('');
+
lines.push('# =============================================================================');
lines.push('# Core Settings');
lines.push('# =============================================================================');
@@ -129,6 +133,27 @@ export async function generateConfigToml(options: ExtendedConfigTomlOptions = {}
lines.push(']');
lines.push('');
+ // All Codex root keys above must appear before the first TOML table.
+ lines.push('# =============================================================================');
+ lines.push('# Ruflo Agentic Policy Engine (ADR-324)');
+ lines.push('# =============================================================================');
+ lines.push('');
+ lines.push('[policy]');
+ lines.push('# legacy preserves existing installs; observe records would-deny decisions; enforce blocks');
+ lines.push(`mode = "${policy.mode ?? 'legacy'}"`);
+ lines.push('');
+
+ lines.push('[swarm.automation]');
+ lines.push('# Unattended fanout is opt-in. Interactive Codex may still delegate explicitly.');
+ lines.push(`enabled = ${swarmAutomation.enabled ?? false}`);
+ lines.push(`max_concurrent = ${swarmAutomation.maxConcurrent ?? 4}`);
+ lines.push(`max_writers = ${swarmAutomation.maxWriters ?? 2}`);
+ lines.push(`worktree_isolation = ${swarmAutomation.worktreeIsolation ?? true}`);
+ lines.push(`dependency_failure = "${swarmAutomation.dependencyFailure ?? 'cancel'}"`);
+ lines.push(`agent_timeout_seconds = ${swarmAutomation.agentTimeoutSeconds ?? 1800}`);
+ lines.push(`max_output_bytes = ${swarmAutomation.maxOutputBytes ?? 1048576}`);
+ lines.push('');
+
// Features
lines.push('# =============================================================================');
lines.push('# Features');
@@ -158,13 +183,7 @@ export async function generateConfigToml(options: ExtendedConfigTomlOptions = {}
// Default claude-flow server
const hasRuflo = mcpServers.some(s => s.name === 'ruflo' || s.name === 'claude-flow');
if (!hasRuflo) {
- lines.push(...generateMcpServer({
- name: 'ruflo',
- command: 'npx',
- args: ['-y', '--package=@claude-flow/cli@latest', 'claude-flow-mcp'],
- enabled: true,
- toolTimeout: 120,
- }));
+ lines.push(...generateMcpServer(getRufloMcpServerConfig()));
lines.push('');
}
@@ -196,8 +215,8 @@ export async function generateConfigToml(options: ExtendedConfigTomlOptions = {}
// Default profiles
const defaultProfiles: Record<string, ConfigProfile> = {
dev: {
- approvalPolicy: 'never',
- sandboxMode: 'danger-full-access',
+ approvalPolicy: 'on-request',
+ sandboxMode: 'workspace-write',
webSearch: 'live',
},
safe: {
@@ -534,15 +553,17 @@ sandbox_mode = "${sandboxMode}"
[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "--package=@claude-flow/cli@latest", "claude-flow-mcp"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
+startup_timeout_sec = 120
`;
}
/**
* Generate CI/CD config.toml
*/
-export async function generateCIConfigToml(): Promise<string> {
+export async function generateCIConfigToml(platform: NodeJS.Platform = process.platform): Promise<string> {
+ const mcpCommand = renderMcpServerToml(getRufloMcpServerConfig(platform, 300)).join('\n');
return `# =============================================================================
# Claude Flow V3 - CI/CD Pipeline Configuration
# =============================================================================
@@ -565,11 +586,7 @@ remote_compaction = false
child_agents_md = true
request_rule = false
-[mcp_servers.ruflo]
-command = "npx"
-args = ["-y", "--package=@claude-flow/cli@latest", "claude-flow-mcp"]
-enabled = true
-tool_timeout_sec = 300
+${mcpCommand}
[history]
persistence = "none"
@@ -645,7 +662,7 @@ remote_compaction = true
[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "--package=@claude-flow/cli@latest", "claude-flow-mcp"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
tool_timeout_sec = 120
@@ -850,7 +867,7 @@ remote_compaction = true
[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "--package=@claude-flow/cli@latest", "claude-flow-mcp"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
tool_timeout_sec = 120
@@ -931,7 +948,7 @@ remote_compaction = false
[mcp_servers.ruflo]
command = "npx"
-args = ["-y", "--package=@claude-flow/cli@latest", "claude-flow-mcp"]
+args = ["-y", "ruflo@latest", "mcp", "start"]
enabled = true
tool_timeout_sec = 60
diff --git a/v3/@claude-flow/codex/src/index.ts b/v3/@claude-flow/codex/src/index.ts
index f60605ef55..c2d32d8f68 100644
--- a/v3/@claude-flow/codex/src/index.ts
+++ b/v3/@claude-flow/codex/src/index.ts
@@ -44,8 +44,23 @@ export {
export { CodexInitializer, initializeCodexProject } from './initializer.js';
// Dual-mode collaborative execution
-export { DualModeOrchestrator, CollaborationTemplates, createDualModeCommand } from './dual-mode/index.js';
-export type { DualModeConfig, WorkerConfig, WorkerResult, CollaborationResult } from './dual-mode/index.js';
+export {
+ DualModeOrchestrator,
+ CollaborationTemplates,
+ createDualModeCommand,
+ loadSwarmAutomationConfig,
+} from './dual-mode/index.js';
+export type {
+ DualModeConfig,
+ WorkerConfig,
+ WorkerResult,
+ CollaborationResult,
+ LoadedSwarmAutomationConfig,
+ WorkerCapabilityEnvelope,
+} from './dual-mode/index.js';
+
+export { CodexWorktreeCoordinator } from './worktrees/index.js';
+export type { WorktreeAssignment, WorktreeRunRecord } from './worktrees/index.js';
// Codex /loop-compatible runner
export {
@@ -75,7 +90,7 @@ export {
/**
* Package version
*/
-export const VERSION = '3.0.1';
+export const VERSION = '3.0.2';
/**
* Package metadata
diff --git a/v3/@claude-flow/codex/src/initializer.ts b/v3/@claude-flow/codex/src/initializer.ts
index 5752cc5f79..0a8ae84338 100644
--- a/v3/@claude-flow/codex/src/initializer.ts
+++ b/v3/@claude-flow/codex/src/initializer.ts
@@ -16,6 +16,7 @@ import { generateAgentsMd } from './generators/agents-md.js';
import { generateSkillMd, generateBuiltInSkill } from './generators/skill-md.js';
import { generateConfigToml } from './generators/config-toml.js';
import { DEFAULT_SKILLS_BY_TEMPLATE, AGENTS_OVERRIDE_TEMPLATE, GITIGNORE_ENTRIES, ALL_AVAILABLE_SKILLS } from './templates/index.js';
+import { getRufloMcpAddCommand } from './mcp-config.js';
/**
* Bundled skills source directory (relative to package)
@@ -344,7 +345,7 @@ export class CodexInitializer {
} catch {
return {
registered: false,
- warning: 'Codex CLI not found. Run: codex mcp add ruflo -- npx -y --package=@claude-flow/cli@latest claude-flow-mcp',
+ warning: `Codex CLI not found. Run: ${getRufloMcpAddCommand()}`,
};
}
@@ -381,18 +382,11 @@ export class CodexInitializer {
// Register the MCP server.
//
- // #2774: MUST target the dedicated stdio server binary
- // (`claude-flow-mcp`, exported by `@claude-flow/cli`) β€” NOT the
- // `ruflo mcp start` management CLI. The management CLI stays alive
- // but never answers `initialize` on stdio, so Codex silently sees
- // the server as configured but exposes zero Ruflo tools. The
- // dedicated binary streams JSON-RPC over stdio directly, with all
- // progress noise routed to stderr (also fixes the #2253 regression
- // where an embedder progress line leaks onto stdout before the
- // handshake).
+ // Use the shared platform-aware Ruflo MCP definition so generators,
+ // migrations, and live registration cannot drift.
try {
execSync(
- 'codex mcp add ruflo -- npx -y --package=@claude-flow/cli@latest claude-flow-mcp',
+ getRufloMcpAddCommand(),
{
stdio: 'pipe',
timeout: 10000,
@@ -403,13 +397,13 @@ export class CodexInitializer {
const errorMessage = err instanceof Error ? err.message : String(err);
return {
registered: false,
- warning: `Failed to register MCP server: ${errorMessage}. Run manually: codex mcp add ruflo -- npx -y --package=@claude-flow/cli@latest claude-flow-mcp`,
+ warning: `Failed to register MCP server: ${errorMessage}. Run manually: ${getRufloMcpAddCommand()}`,
};
}
} catch {
return {
registered: false,
- warning: 'Could not register MCP server. Run manually: codex mcp add ruflo -- npx -y --package=@claude-flow/cli@latest claude-flow-mcp',
+ warning: `Could not register MCP server. Run manually: ${getRufloMcpAddCommand()}`,
};
}
}
@@ -743,7 +737,7 @@ ${this.skills.map(s => `- \`$${s}\` (Codex) / \`/${s}\` (Claude Code)`).join('\n
\`\`\`bash
# Start Ruflo's MCP server over stdio (dedicated entry point β€” the
# management \`ruflo mcp start\` CLI does NOT answer JSON-RPC on stdio).
-npx -y --package=@claude-flow/cli@latest claude-flow-mcp
+npx -y ruflo@latest mcp start
\`\`\`
## Swarm Orchestration
diff --git a/v3/@claude-flow/codex/src/migrations/index.ts b/v3/@claude-flow/codex/src/migrations/index.ts
index f782e537ea..8ab42908e6 100644
--- a/v3/@claude-flow/codex/src/migrations/index.ts
+++ b/v3/@claude-flow/codex/src/migrations/index.ts
@@ -16,6 +16,7 @@ import type {
ApprovalPolicy,
SandboxMode,
} from '../types.js';
+import { getRufloMcpServerConfig, renderMcpServerToml } from '../mcp-config.js';
/**
* Parsed CLAUDE.md structure
@@ -702,7 +703,10 @@ export function generateAgentsMdFromParsed(parsed: ParsedClaudeMd): string {
/**
* Convert settings.json to config.toml format
*/
-export function convertSettingsToToml(settings: Record<string, unknown>): string {
+export function convertSettingsToToml(
+ settings: Record<string, unknown>,
+ platform: NodeJS.Platform = process.platform,
+): string {
const lines: string[] = [];
lines.push('# Migrated from settings.json');
lines.push('# Generated by @claude-flow/codex');
@@ -754,6 +758,11 @@ export function convertSettingsToToml(settings: Record<string, unknown>): string
// MCP servers
if (settings.mcpServers && typeof settings.mcpServers === 'object') {
for (const [name, config] of Object.entries(settings.mcpServers as Record<string, unknown>)) {
+ // Claude Flow/Ruflo aliases are replaced with the dedicated MCP binary
+ // below. This avoids preserving the recursive `mcp start` CLI path.
+ if (name === 'claude-flow' || name === 'ruflo') {
+ continue;
+ }
const mcpConfig = config as { command?: string; args?: string[]; env?: Record<string, string> };
lines.push(`[mcp_servers.${name}]`);
if (mcpConfig.command) {
@@ -774,15 +783,29 @@ export function convertSettingsToToml(settings: Record<string, unknown>): string
}
lines.push('');
}
- } else {
- // Add default claude-flow server
- lines.push('[mcp_servers.ruflo]');
- lines.push('command = "npx"');
- lines.push('args = ["-y", "--package=@claude-flow/cli@latest", "claude-flow-mcp"]');
- lines.push('enabled = true');
- lines.push('');
}
+ // Ruflo is additive for every migrated installation. Unknown/custom MCP
+ // entries above are preserved.
+ lines.push(...renderMcpServerToml(getRufloMcpServerConfig(platform)));
+ lines.push('');
+
+ // Additive compatibility defaults. Enforcement and unattended fanout are
+ // deliberate transitions, never migration side effects.
+ lines.push('[policy]');
+ lines.push('mode = "legacy"');
+ lines.push('');
+
+ lines.push('[swarm.automation]');
+ lines.push('enabled = false');
+ lines.push('max_concurrent = 4');
+ lines.push('max_writers = 2');
+ lines.push('worktree_isolation = true');
+ lines.push('dependency_failure = "cancel"');
+ lines.push('agent_timeout_seconds = 1800');
+ lines.push('max_output_bytes = 1048576');
+ lines.push('');
+
// History
lines.push('[history]');
lines.push('persistence = "save-all"');
@@ -791,8 +814,8 @@ export function convertSettingsToToml(settings: Record<string, unknown>): string
// Profiles
lines.push('# Development profile');
lines.push('[profiles.dev]');
- lines.push('approval_policy = "never"');
- lines.push('sandbox_mode = "danger-full-access"');
+ lines.push('approval_policy = "on-request"');
+ lines.push('sandbox_mode = "workspace-write"');
lines.push('');
lines.push('# Safe profile');
@@ -841,6 +864,7 @@ export function generateConfigTomlFromParsed(parsed: ParsedClaudeMd): string {
// MCP servers
if (parsed.mcpServers.length > 0) {
for (const server of parsed.mcpServers) {
+ if (server.name === 'claude-flow' || server.name === 'ruflo') continue;
lines.push(`[mcp_servers.${server.name.replace(/-/g, '_')}]`);
lines.push(`command = "${server.command}"`);
if (server.args && server.args.length > 0) {
@@ -850,14 +874,23 @@ export function generateConfigTomlFromParsed(parsed: ParsedClaudeMd): string {
lines.push(`enabled = ${server.enabled ?? true}`);
lines.push('');
}
- } else {
- // Default claude-flow server
- lines.push('[mcp_servers.ruflo]');
- lines.push('command = "npx"');
- lines.push('args = ["-y", "--package=@claude-flow/cli@latest", "claude-flow-mcp"]');
- lines.push('enabled = true');
- lines.push('');
}
+ lines.push(...renderMcpServerToml(getRufloMcpServerConfig()));
+ lines.push('');
+
+ lines.push('[policy]');
+ lines.push('mode = "legacy"');
+ lines.push('');
+
+ lines.push('[swarm.automation]');
+ lines.push('enabled = false');
+ lines.push('max_concurrent = 4');
+ lines.push('max_writers = 2');
+ lines.push('worktree_isolation = true');
+ lines.push('dependency_failure = "cancel"');
+ lines.push('agent_timeout_seconds = 1800');
+ lines.push('max_output_bytes = 1048576');
+ lines.push('');
// Skills
if (parsed.skills.length > 0) {
@@ -875,8 +908,8 @@ export function generateConfigTomlFromParsed(parsed: ParsedClaudeMd): string {
// Profiles
lines.push('[profiles.dev]');
- lines.push('approval_policy = "never"');
- lines.push('sandbox_mode = "danger-full-access"');
+ lines.push('approval_policy = "on-request"');
+ lines.push('sandbox_mode = "workspace-write"');
lines.push('');
lines.push('[profiles.safe]');
diff --git a/v3/@claude-flow/codex/src/types.ts b/v3/@claude-flow/codex/src/types.ts
index 59985149a4..1d63aca4e9 100644
--- a/v3/@claude-flow/codex/src/types.ts
+++ b/v3/@claude-flow/codex/src/types.ts
@@ -123,6 +123,22 @@ export interface ConfigTomlOptions {
skills?: SkillConfig[];
profiles?: Record<string, ConfigProfile>;
historyPersistence?: 'none' | 'save-all';
+ policy?: PolicyConfig;
+ swarmAutomation?: SwarmAutomationConfig;
+}
+
+export interface PolicyConfig {
+ mode?: 'legacy' | 'observe' | 'enforce';
+}
+
+export interface SwarmAutomationConfig {
+ enabled?: boolean;
+ maxConcurrent?: number;
+ maxWriters?: number;
+ worktreeIsolation?: boolean;
+ dependencyFailure?: 'cancel' | 'skip';
+ agentTimeoutSeconds?: number;
+ maxOutputBytes?: number;
}
/**
diff --git a/v3/@claude-flow/codex/src/worktrees/coordinator.ts b/v3/@claude-flow/codex/src/worktrees/coordinator.ts
new file mode 100644
index 0000000000..20409fd995
--- /dev/null
+++ b/v3/@claude-flow/codex/src/worktrees/coordinator.ts
@@ -0,0 +1,153 @@
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
+import { basename, dirname, join, resolve } from 'node:path';
+
+const SAFE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
+
+export interface WorktreeAssignment {
+ agentId: string;
+ branch: string;
+ path: string;
+ readOnly: boolean;
+}
+
+export interface WorktreeRunRecord {
+ version: 1;
+ runId: string;
+ repoRoot: string;
+ createdAt: number;
+ assignments: WorktreeAssignment[];
+}
+
+function git(repoRoot: string, args: string[]): string {
+ return execFileSync('git', ['-C', repoRoot, ...args], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ maxBuffer: 4 * 1024 * 1024,
+ }).trim();
+}
+
+function assertId(value: string, label: string): void {
+ if (!SAFE_ID.test(value)) throw new Error(`invalid ${label}: ${value}`);
+}
+
+export class CodexWorktreeCoordinator {
+ readonly repoRoot: string;
+ readonly registryDir: string;
+ readonly worktreeBase: string;
+
+ constructor(repoRoot: string) {
+ this.repoRoot = resolve(repoRoot);
+ const top = git(this.repoRoot, ['rev-parse', '--show-toplevel']);
+ if (resolve(top) !== this.repoRoot) throw new Error(`repoRoot must be the git top-level: ${top}`);
+ this.registryDir = join(this.repoRoot, '.claude-flow', 'swarm', 'worktrees');
+ this.worktreeBase = join(dirname(this.repoRoot), '.ruflo-worktrees', basename(this.repoRoot));
+ }
+
+ prepare(
+ runId: string,
+ agents: Array<{ id: string; readOnly?: boolean }>,
+ options: { allowDirty?: boolean; baseRef?: string } = {},
+ ): WorktreeRunRecord {
+ assertId(runId, 'run id');
+ if (!agents.length) throw new Error('at least one agent is required');
+ const unique = new Set<string>();
+ for (const agent of agents) {
+ assertId(agent.id, 'agent id');
+ if (unique.has(agent.id)) throw new Error(`duplicate agent id: ${agent.id}`);
+ unique.add(agent.id);
+ }
+ const registryPath = this.registryPath(runId);
+ if (existsSync(registryPath)) return this.status(runId);
+ if (!options.allowDirty && git(this.repoRoot, ['status', '--porcelain']).length > 0) {
+ throw new Error('refusing to prepare writing worktrees from a dirty repository');
+ }
+
+ mkdirSync(this.registryDir, { recursive: true });
+ mkdirSync(join(this.worktreeBase, runId), { recursive: true });
+ const assignments: WorktreeAssignment[] = [];
+ try {
+ for (const agent of agents) {
+ const readOnly = agent.readOnly === true;
+ const branch = `ruflo/${runId}/${agent.id}`;
+ const worktreePath = join(this.worktreeBase, runId, agent.id);
+ if (readOnly) {
+ git(this.repoRoot, ['worktree', 'add', '--detach', worktreePath, options.baseRef ?? 'HEAD']);
+ } else {
+ git(this.repoRoot, ['worktree', 'add', '-b', branch, worktreePath, options.baseRef ?? 'HEAD']);
+ }
+ assignments.push({ agentId: agent.id, branch: readOnly ? '' : branch, path: worktreePath, readOnly });
+ }
+ const record: WorktreeRunRecord = {
+ version: 1,
+ runId,
+ repoRoot: this.repoRoot,
+ createdAt: Date.now(),
+ assignments,
+ };
+ this.writeRecord(registryPath, record);
+ return record;
+ } catch (error) {
+ for (const assignment of assignments.reverse()) {
+ try { git(this.repoRoot, ['worktree', 'remove', assignment.path]); } catch { /* retain work for recovery */ }
+ }
+ throw error;
+ }
+ }
+
+ status(runId: string): WorktreeRunRecord {
+ assertId(runId, 'run id');
+ const file = this.registryPath(runId);
+ if (!existsSync(file)) throw new Error(`unknown worktree run: ${runId}`);
+ const record = JSON.parse(readFileSync(file, 'utf8')) as WorktreeRunRecord;
+ if (record.version !== 1 || record.runId !== runId || resolve(record.repoRoot) !== this.repoRoot) {
+ throw new Error('invalid worktree registry record');
+ }
+ const expectedPrefix = resolve(join(this.worktreeBase, runId));
+ for (const assignment of record.assignments) {
+ const actual = resolve(assignment.path);
+ if (actual !== expectedPrefix && !actual.startsWith(`${expectedPrefix}/`)) {
+ throw new Error(`registry path escapes owned worktree root: ${actual}`);
+ }
+ }
+ return record;
+ }
+
+ integrate(runId: string, agentIds?: string[]): { merged: string[] } {
+ const record = this.status(runId);
+ const wanted = agentIds ? new Set(agentIds) : null;
+ const merged: string[] = [];
+ for (const assignment of record.assignments) {
+ if (assignment.readOnly || (wanted && !wanted.has(assignment.agentId))) continue;
+ git(this.repoRoot, ['merge', '--no-ff', '--no-edit', assignment.branch]);
+ merged.push(assignment.agentId);
+ }
+ return { merged };
+ }
+
+ cleanup(runId: string): { removed: string[]; retained: string[] } {
+ const record = this.status(runId);
+ const removed: string[] = [];
+ const retained: string[] = [];
+ for (const assignment of record.assignments) {
+ try {
+ git(this.repoRoot, ['worktree', 'remove', assignment.path]);
+ removed.push(assignment.agentId);
+ } catch {
+ retained.push(assignment.agentId);
+ }
+ }
+ if (retained.length === 0) unlinkSync(this.registryPath(runId));
+ return { removed, retained };
+ }
+
+ private registryPath(runId: string): string {
+ return join(this.registryDir, `${runId}.json`);
+ }
+
+ private writeRecord(file: string, record: WorktreeRunRecord): void {
+ const temporary = `${file}.${process.pid}.tmp`;
+ writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
+ renameSync(temporary, file);
+ }
+}
diff --git a/v3/@claude-flow/codex/src/worktrees/index.ts b/v3/@claude-flow/codex/src/worktrees/index.ts
new file mode 100644
index 0000000000..651ce70418
--- /dev/null
+++ b/v3/@claude-flow/codex/src/worktrees/index.ts
@@ -0,0 +1 @@
+export * from './coordinator.js';
diff --git a/v3/@claude-flow/codex/tests/dual-mode.test.ts b/v3/@claude-flow/codex/tests/dual-mode.test.ts
index 7bd445c4ac..2f4167fc89 100644
--- a/v3/@claude-flow/codex/tests/dual-mode.test.ts
+++ b/v3/@claude-flow/codex/tests/dual-mode.test.ts
@@ -6,8 +6,15 @@
* No real workers are spawned β€” only pure logic is exercised.
*/
import { describe, it, expect } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { parseWorkerSpecs, createDualModeCommand } from '../src/dual-mode/cli.js';
-import { DualModeOrchestrator, CollaborationTemplates } from '../src/dual-mode/index.js';
+import {
+ DualModeOrchestrator,
+ CollaborationTemplates,
+ loadSwarmAutomationConfig,
+} from '../src/dual-mode/index.js';
import type { WorkerConfig } from '../src/dual-mode/index.js';
describe('parseWorkerSpecs', () => {
@@ -108,6 +115,58 @@ describe('dual command wiring', () => {
});
describe('DualModeOrchestrator', () => {
+ it('loads enforceable swarm automation ceilings from config.toml', () => {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-codex-config-'));
+ mkdirSync(join(root, '.agents'));
+ writeFileSync(join(root, '.agents', 'config.toml'), [
+ '[swarm.automation]',
+ 'enabled = true',
+ 'max_concurrent = 3',
+ 'max_writers = 1',
+ 'worktree_isolation = true',
+ 'agent_timeout_seconds = 60',
+ 'max_output_bytes = 4096',
+ ].join('\n'));
+ expect(loadSwarmAutomationConfig(root)).toEqual({
+ enabled: true,
+ maxConcurrent: 3,
+ maxWriters: 1,
+ worktreeIsolation: true,
+ agentTimeoutSeconds: 60,
+ maxOutputBytes: 4096,
+ dependencyFailure: 'cancel',
+ });
+ });
+
+ it('loads existing Codex project configuration from .codex', () => {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-codex-config-'));
+ mkdirSync(join(root, '.codex'));
+ writeFileSync(join(root, '.codex', 'config.toml'), [
+ '[swarm.automation]',
+ 'enabled = true',
+ 'max_concurrent = 2',
+ ].join('\n'));
+ expect(loadSwarmAutomationConfig(root)).toMatchObject({
+ enabled: true,
+ maxConcurrent: 2,
+ });
+ });
+
+ it('rejects invalid concurrency and output ceilings', () => {
+ expect(() => new DualModeOrchestrator({
+ projectPath: '/tmp',
+ maxConcurrent: 0,
+ })).toThrow('maxConcurrent must be a positive integer');
+ expect(() => new DualModeOrchestrator({
+ projectPath: '/tmp',
+ maxOutputBytes: 0,
+ })).toThrow('maxOutputBytes must be positive');
+ expect(() => new DualModeOrchestrator({
+ projectPath: '/tmp',
+ maxWriters: 0,
+ })).toThrow('maxWriters must be a positive integer');
+ });
+
const orch = () => new DualModeOrchestrator({ projectPath: '/tmp' });
it('uses safe defaults (codex command, not claude)', () => {
@@ -118,6 +177,53 @@ describe('DualModeOrchestrator', () => {
expect(o.config.sharedNamespace).toBe('collaboration');
});
+ it('does not pass policy or provider secrets to workers', () => {
+ process.env.CLAUDE_FLOW_POLICY_SIGNING_KEY = 'do-not-leak';
+ process.env.OPENROUTER_API_KEY = 'do-not-leak';
+ try {
+ const environment = (orch() as unknown as {
+ workerEnvironment(worker: WorkerConfig): NodeJS.ProcessEnv;
+ }).workerEnvironment({
+ id: 'safe-worker',
+ platform: 'codex',
+ role: 'reviewer',
+ prompt: 'review',
+ readOnly: true,
+ });
+ expect(environment.CLAUDE_FLOW_POLICY_SIGNING_KEY).toBeUndefined();
+ expect(environment.OPENROUTER_API_KEY).toBeUndefined();
+ expect(environment.CLAUDE_FLOW_PRINCIPAL_ID).toBe('agent:safe-worker');
+ expect(environment.CLAUDE_FLOW_CAPABILITY_ENVELOPE).toContain('"network":false');
+ } finally {
+ delete process.env.CLAUDE_FLOW_POLICY_SIGNING_KEY;
+ delete process.env.OPENROUTER_API_KEY;
+ }
+ });
+
+ it('enforces worker capability envelopes as reductions', () => {
+ const orchestrator = orch() as unknown as {
+ resolveWorkerEnvelope(worker: WorkerConfig): Record<string, unknown>;
+ };
+ const base: WorkerConfig = {
+ id: 'bounded',
+ platform: 'codex',
+ role: 'coder',
+ prompt: 'work',
+ };
+ expect(orchestrator.resolveWorkerEnvelope({
+ ...base,
+ capabilityEnvelope: { actions: ['memory.read'], maxConcurrency: 1 },
+ })).toMatchObject({
+ actions: ['memory.read'],
+ network: false,
+ destructive: false,
+ });
+ expect(() => orchestrator.resolveWorkerEnvelope({
+ ...base,
+ capabilityEnvelope: { network: true },
+ })).toThrow('capability envelope cannot expand');
+ });
+
it('buildDependencyLevels groups a linear pipeline one-per-level', () => {
const ws: WorkerConfig[] = [
{ id: 'a', platform: 'claude', role: 'a', prompt: 'x' },
@@ -128,10 +234,10 @@ describe('DualModeOrchestrator', () => {
expect(levels.map(l => l.map(w => w.id))).toEqual([['a'], ['b'], ['c']]);
});
- it('buildDependencyLevels puts independent workers in the same level', () => {
+ it('buildDependencyLevels puts independent read-only workers in the same level', () => {
const ws: WorkerConfig[] = [
- { id: 'a', platform: 'claude', role: 'a', prompt: 'x' },
- { id: 'b', platform: 'codex', role: 'b', prompt: 'y' },
+ { id: 'a', platform: 'claude', role: 'a', prompt: 'x', readOnly: true },
+ { id: 'b', platform: 'codex', role: 'b', prompt: 'y', readOnly: true },
{ id: 'c', platform: 'codex', role: 'c', prompt: 'z', dependsOn: ['a', 'b'] },
];
const levels = (orch() as unknown as { buildDependencyLevels(w: WorkerConfig[]): WorkerConfig[][] }).buildDependencyLevels(ws);
@@ -140,12 +246,54 @@ describe('DualModeOrchestrator', () => {
expect(levels[1].map(w => w.id)).toEqual(['c']);
});
- it('buildDependencyLevels breaks a circular dependency instead of looping forever', () => {
+ it('buildDependencyLevels rejects circular dependencies', () => {
const ws: WorkerConfig[] = [
{ id: 'a', platform: 'claude', role: 'a', prompt: 'x', dependsOn: ['b'] },
{ id: 'b', platform: 'codex', role: 'b', prompt: 'y', dependsOn: ['a'] },
];
- const levels = (orch() as unknown as { buildDependencyLevels(w: WorkerConfig[]): WorkerConfig[][] }).buildDependencyLevels(ws);
- expect(levels.flat().map(w => w.id).sort()).toEqual(['a', 'b']);
+ expect(() => (orch() as unknown as { buildDependencyLevels(w: WorkerConfig[]): WorkerConfig[][] }).buildDependencyLevels(ws))
+ .toThrow(/dependency cycle/);
+ });
+
+ it('rejects concurrent writers sharing a worktree', () => {
+ const ws: WorkerConfig[] = [
+ { id: 'a', platform: 'codex', role: 'coder', prompt: 'x', worktreePath: '/tmp/shared' },
+ { id: 'b', platform: 'codex', role: 'tester', prompt: 'y', worktreePath: '/tmp/shared' },
+ ];
+ const isolated = new DualModeOrchestrator({ projectPath: '/tmp', worktreeIsolation: true });
+ expect(() => (isolated as unknown as { buildDependencyLevels(w: WorkerConfig[]): WorkerConfig[][] }).buildDependencyLevels(ws))
+ .toThrow(/distinct worktrees/);
+ });
+
+ it('accepts a wider dependency level and schedules it in bounded batches', () => {
+ const orchestrator = new DualModeOrchestrator({ projectPath: '/tmp', maxWriters: 1 });
+ const ws: WorkerConfig[] = [
+ { id: 'a', platform: 'codex', role: 'coder', prompt: 'x', worktreePath: '/tmp/a' },
+ { id: 'b', platform: 'codex', role: 'tester', prompt: 'y', worktreePath: '/tmp/b' },
+ ];
+ expect((orchestrator as unknown as {
+ buildDependencyLevels(w: WorkerConfig[]): WorkerConfig[][];
+ }).buildDependencyLevels(ws)[0]).toHaveLength(2);
+ });
+
+ it('bounds writers independently without serializing read-only workers', () => {
+ const orchestrator = new DualModeOrchestrator({
+ projectPath: '/tmp',
+ maxConcurrent: 3,
+ maxWriters: 1,
+ });
+ const level: WorkerConfig[] = [
+ { id: 'writer-a', platform: 'codex', role: 'coder', prompt: 'x' },
+ { id: 'reader-a', platform: 'claude', role: 'reviewer', prompt: 'y', readOnly: true },
+ { id: 'writer-b', platform: 'codex', role: 'tester', prompt: 'z' },
+ { id: 'reader-b', platform: 'claude', role: 'analyst', prompt: 'q', readOnly: true },
+ ];
+ const batches = (orchestrator as unknown as {
+ partitionLevel(items: WorkerConfig[]): WorkerConfig[][];
+ }).partitionLevel(level);
+ expect(batches.map((batch) => batch.map((item) => item.id))).toEqual([
+ ['writer-a', 'reader-a', 'reader-b'],
+ ['writer-b'],
+ ]);
});
});
diff --git a/v3/@claude-flow/codex/tests/generators.test.ts b/v3/@claude-flow/codex/tests/generators.test.ts
index da51ab6921..e339b83091 100644
--- a/v3/@claude-flow/codex/tests/generators.test.ts
+++ b/v3/@claude-flow/codex/tests/generators.test.ts
@@ -5,6 +5,7 @@
*/
import { describe, it, expect, beforeEach } from 'vitest';
+import * as TOML from '@iarna/toml';
import {
generateAgentsMd,
generateSkillMd,
@@ -111,6 +112,9 @@ describe('generateAgentsMd', () => {
expect(result).toContain('## Code Standards');
expect(result).toContain('## Security');
expect(result).toContain('## Memory System');
+ expect(result).toContain('## Ruflo + Codex Automated Workflow');
+ expect(result).toContain('Never allow two writers in one worktree');
+ expect(result).toContain('MetaHarness may benchmark candidates concurrently');
});
it('should include tech stack', async () => {
@@ -195,6 +199,22 @@ describe('generateAgentsMd', () => {
});
});
+ describe('policy and swarm automation config', () => {
+ it('generates safe backward-compatible policy and bounded concurrency defaults', async () => {
+ const result = await generateConfigToml({});
+ expect(result).toContain('[policy]');
+ expect(result).toContain('mode = "legacy"');
+ expect(result).toContain('[swarm.automation]');
+ expect(result).toContain('enabled = false');
+ expect(result).toContain('max_concurrent = 4');
+ expect(result).toContain('max_writers = 2');
+ expect(result).toContain('worktree_isolation = true');
+ expect(result).toContain('[profiles.dev]');
+ expect(result).toContain('approval_policy = "on-request"');
+ expect(result).toContain('sandbox_mode = "workspace-write"');
+ });
+ });
+
describe('full template', () => {
it('should include performance targets', async () => {
const options: AgentsMdOptions = {
@@ -607,6 +627,19 @@ describe('generateBuiltInSkill', () => {
// =============================================================================
describe('generateConfigToml', () => {
+ it('keeps Codex settings at the TOML root', async () => {
+ const parsed = TOML.parse(await generateConfigToml({
+ model: 'gpt-test',
+ approvalPolicy: 'on-request',
+ sandboxMode: 'workspace-write',
+ })) as Record<string, unknown>;
+ expect(parsed.model).toBe('gpt-test');
+ expect(parsed.approval_policy).toBe('on-request');
+ expect(parsed.sandbox_mode).toBe('workspace-write');
+ expect((parsed.policy as Record<string, unknown>).mode).toBe('legacy');
+ expect(((parsed.swarm as Record<string, unknown>).automation as Record<string, unknown>).enabled).toBe(false);
+ });
+
describe('default configuration', () => {
it('should generate valid TOML with header', async () => {
const result = await generateConfigToml({ platform: 'linux' });
@@ -650,7 +683,7 @@ describe('generateConfigToml', () => {
expect(result).toContain('[mcp_servers.ruflo]');
expect(result).toContain('command = "npx"');
- expect(result).toContain(`args = ["-y", "--package=@claude-flow/cli@latest", "claude-flow-mcp"]`);
+ expect(result).toContain(`args = ["-y", "ruflo@latest", "mcp", "start"]`);
expect(result).toContain('enabled = true');
});
@@ -658,8 +691,8 @@ describe('generateConfigToml', () => {
const result = await generateConfigToml();
expect(result).toContain('[profiles.dev]');
- expect(result).toContain('approval_policy = "never"');
- expect(result).toContain('sandbox_mode = "danger-full-access"');
+ expect(result).toContain('approval_policy = "on-request"');
+ expect(result).toContain('sandbox_mode = "workspace-write"');
expect(result).toContain('[profiles.safe]');
expect(result).toContain('sandbox_mode = "read-only"');
diff --git a/v3/@claude-flow/codex/tests/migrations.test.ts b/v3/@claude-flow/codex/tests/migrations.test.ts
index d628310d26..536b8bb2e1 100644
--- a/v3/@claude-flow/codex/tests/migrations.test.ts
+++ b/v3/@claude-flow/codex/tests/migrations.test.ts
@@ -10,6 +10,7 @@ import {
migrateFromClaudeCode,
convertSkillSyntax,
convertSettingsToToml,
+ generateConfigTomlFromParsed,
generateMigrationReport,
FEATURE_MAPPINGS,
} from '../src/migrations/index.js';
@@ -516,6 +517,49 @@ describe('convertSettingsToToml', () => {
expect(result).toContain('# Migrated from settings.json');
expect(result.split('\n').length).toBeGreaterThan(1);
});
+
+ it('adds compatibility-safe policy and bounded swarm defaults', () => {
+ const result = convertSettingsToToml({});
+
+ expect(result).toContain('[policy]');
+ expect(result).toContain('mode = "legacy"');
+ expect(result).toContain('[swarm.automation]');
+ expect(result).toContain('enabled = false');
+ expect(result).toContain('max_concurrent = 4');
+ expect(result).toContain('worktree_isolation = true');
+ expect(result).toContain('[profiles.dev]');
+ expect(result).toContain('sandbox_mode = "workspace-write"');
+ });
+});
+
+describe('generateConfigTomlFromParsed', () => {
+ it('preserves custom MCP servers and adds compatibility-safe Ruflo policy defaults', () => {
+ const result = generateConfigTomlFromParsed({
+ title: 'Migrated',
+ sections: [],
+ skills: [],
+ hooks: [],
+ customInstructions: [],
+ codeBlocks: [],
+ mcpServers: [{
+ name: 'custom',
+ command: 'node',
+ args: ['server.js'],
+ enabled: true,
+ }],
+ settings: {},
+ warnings: [],
+ });
+
+ expect(result).toContain('[mcp_servers.custom]');
+ expect(result).toContain('[mcp_servers.ruflo]');
+ expect(result).toContain('[policy]');
+ expect(result).toContain('mode = "legacy"');
+ expect(result).toContain('[swarm.automation]');
+ expect(result).toContain('enabled = false');
+ expect(result).toContain('[profiles.dev]');
+ expect(result).toContain('sandbox_mode = "workspace-write"');
+ });
});
// =============================================================================
diff --git a/v3/@claude-flow/codex/tests/worktrees.test.ts b/v3/@claude-flow/codex/tests/worktrees.test.ts
new file mode 100644
index 0000000000..d85d322438
--- /dev/null
+++ b/v3/@claude-flow/codex/tests/worktrees.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { CodexWorktreeCoordinator } from '../src/worktrees/index.js';
+
+const roots: string[] = [];
+
+function git(cwd: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8' }).trim();
+}
+
+function repo(): string {
+ const parent = mkdtempSync(join(tmpdir(), 'ruflo-codex-worktrees-'));
+ roots.push(parent);
+ const root = join(parent, 'repo');
+ execFileSync('git', ['init', root]);
+ git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'config', 'user.name', 'Test');
+ writeFileSync(join(root, 'README.md'), 'seed\n');
+ git(root, 'add', 'README.md');
+ git(root, 'commit', '-m', 'seed');
+ return root;
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+describe('CodexWorktreeCoordinator', () => {
+ it('creates distinct owned worktrees and cleans only clean assignments', () => {
+ const root = repo();
+ const coordinator = new CodexWorktreeCoordinator(root);
+ const record = coordinator.prepare('run-1', [{ id: 'coder' }, { id: 'tester' }, { id: 'research', readOnly: true }]);
+ expect(new Set(record.assignments.map((item) => item.path)).size).toBe(3);
+ expect(coordinator.prepare('run-1', [{ id: 'ignored' }])).toEqual(record);
+ expect(coordinator.cleanup('run-1')).toEqual({
+ removed: ['coder', 'tester', 'research'],
+ retained: [],
+ });
+ });
+
+ it('refuses dirty coordinator state and unsafe identifiers', () => {
+ const root = repo();
+ writeFileSync(join(root, 'README.md'), 'dirty\n');
+ const coordinator = new CodexWorktreeCoordinator(root);
+ expect(() => coordinator.prepare('run-2', [{ id: 'coder' }])).toThrow(/dirty repository/);
+ expect(() => coordinator.prepare('../escape', [{ id: 'coder' }], { allowDirty: true })).toThrow(/invalid run id/);
+ });
+
+ it('retains dirty worker worktrees during cleanup', () => {
+ const root = repo();
+ const coordinator = new CodexWorktreeCoordinator(root);
+ const record = coordinator.prepare('run-3', [{ id: 'coder' }]);
+ writeFileSync(join(record.assignments[0]!.path, 'uncommitted.txt'), 'keep me\n');
+ expect(coordinator.cleanup('run-3')).toEqual({ removed: [], retained: ['coder'] });
+ expect(coordinator.status('run-3').assignments[0]!.agentId).toBe('coder');
+ git(record.assignments[0]!.path, 'add', 'uncommitted.txt');
+ git(record.assignments[0]!.path, 'commit', '-m', 'preserve');
+ expect(coordinator.cleanup('run-3')).toEqual({ removed: ['coder'], retained: [] });
+ });
+});
diff --git a/v3/@claude-flow/mcp/__tests__/mcp.test.ts b/v3/@claude-flow/mcp/__tests__/mcp.test.ts
index 0156f52082..a0d7d1e70c 100644
--- a/v3/@claude-flow/mcp/__tests__/mcp.test.ts
+++ b/v3/@claude-flow/mcp/__tests__/mcp.test.ts
@@ -152,6 +152,62 @@ describe('@claude-flow/mcp', () => {
expect(result.content[0].type).toBe('text');
});
+ it('should deny a tool before its handler runs', async () => {
+ let handlerCalls = 0;
+ registry.register({
+ name: 'protected-tool',
+ description: 'A protected tool',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ handlerCalls++;
+ return { result: 'should not run' };
+ },
+ });
+ registry.setAuthorizer(async (name, input, context) => {
+ expect(name).toBe('protected-tool');
+ expect(input).toEqual({ destructive: true });
+ expect(context.sessionId).toBe('policy-test');
+ return {
+ allowed: false,
+ reason: 'approval required',
+ receiptId: 'receipt-1',
+ };
+ });
+
+ const result = await registry.execute(
+ 'protected-tool',
+ { destructive: true },
+ { sessionId: 'policy-test' },
+ );
+
+ expect(result.isError).toBe(true);
+ expect(result.content[0].text).toContain('approval required');
+ expect(handlerCalls).toBe(0);
+ expect(registry.getStats().totalExecutions).toBe(0);
+ });
+
+ it('should fail closed when the authorizer is unavailable', async () => {
+ let handlerCalls = 0;
+ registry.register({
+ name: 'protected-tool',
+ description: 'A protected tool',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ handlerCalls++;
+ return { result: 'should not run' };
+ },
+ });
+ registry.setAuthorizer(async () => {
+ throw new Error('policy store unavailable');
+ });
+
+ const result = await registry.execute('protected-tool', {});
+
+ expect(result.isError).toBe(true);
+ expect(result.content[0].text).toContain('Authorization unavailable');
+ expect(handlerCalls).toBe(0);
+ });
+
it('should return error for unknown tool', async () => {
const result = await registry.execute('unknown-tool', {});
expect(result.isError).toBe(true);
@@ -351,6 +407,25 @@ describe('@claude-flow/mcp', () => {
expect(server).toBeDefined();
});
+ it('fails construction when authorization is required but absent', () => {
+ expect(() => createMCPServer({
+ name: 'Protected Server',
+ transport: 'in-process',
+ requireToolAuthorization: true,
+ }, logger)).toThrow('no authorizer was provided');
+ });
+
+ it('accepts an authorizer in required mode', () => {
+ const protectedServer = createMCPServer({
+ name: 'Protected Server',
+ transport: 'in-process',
+ requireToolAuthorization: true,
+ }, logger, undefined, undefined, async () => ({ allowed: true }));
+ expect(protectedServer).toBeDefined();
+ expect(() => protectedServer.setToolAuthorizer(undefined))
+ .toThrow('tool authorization is required and cannot be disabled');
+ });
+
it('should register a tool', () => {
const result = server.registerTool({
name: 'test-tool',
diff --git a/v3/@claude-flow/mcp/src/index.ts b/v3/@claude-flow/mcp/src/index.ts
index 758f595eb7..870e46bb64 100644
--- a/v3/@claude-flow/mcp/src/index.ts
+++ b/v3/@claude-flow/mcp/src/index.ts
@@ -107,7 +107,13 @@ export { MCPServer, createMCPServer };
export type { IMCPServer } from './server.js';
// Tool Registry
-export { ToolRegistry, createToolRegistry, defineTool } from './tool-registry.js';
+export {
+ ToolRegistry,
+ createToolRegistry,
+ defineTool,
+ type ToolAuthorizationDecision,
+ type ToolAuthorizer,
+} from './tool-registry.js';
// Session Manager
import { SessionManager, createSessionManager } from './session-manager.js';
diff --git a/v3/@claude-flow/mcp/src/server.ts b/v3/@claude-flow/mcp/src/server.ts
index d53a2cb172..9f4f74edc3 100644
--- a/v3/@claude-flow/mcp/src/server.ts
+++ b/v3/@claude-flow/mcp/src/server.ts
@@ -24,7 +24,11 @@ import type {
ToolContext,
} from './types.js';
import { MCPServerError, ErrorCodes } from './types.js';
-import { ToolRegistry, createToolRegistry } from './tool-registry.js';
+import {
+ ToolRegistry,
+ createToolRegistry,
+ type ToolAuthorizer,
+} from './tool-registry.js';
import { SessionManager, createSessionManager } from './session-manager.js';
import { ConnectionPool, createConnectionPool } from './connection-pool.js';
import { ResourceRegistry, createResourceRegistry } from './resource-registry.js';
@@ -53,6 +57,7 @@ export interface IMCPServer {
stop(): Promise<void>;
registerTool(tool: MCPTool): boolean;
registerTools(tools: MCPTool[]): { registered: number; failed: string[] };
+ setToolAuthorizer(authorizer?: ToolAuthorizer): void;
getHealthStatus(): Promise<{
healthy: boolean;
error?: string;
@@ -111,12 +116,17 @@ export class MCPServer extends EventEmitter implements IMCPServer {
config: Partial<MCPServerConfig>,
private readonly logger: ILogger,
private readonly orchestrator?: unknown,
- private readonly swarmCoordinator?: unknown
+ private readonly swarmCoordinator?: unknown,
+ toolAuthorizer?: ToolAuthorizer,
) {
super();
this.config = { ...DEFAULT_CONFIG, ...config } as MCPServerConfig;
this.toolRegistry = createToolRegistry(logger);
+ if (this.config.requireToolAuthorization && !toolAuthorizer) {
+ throw new Error('tool authorization is required but no authorizer was provided');
+ }
+ this.toolRegistry.setAuthorizer(toolAuthorizer);
this.sessionManager = createSessionManager(logger, {
maxSessions: 100,
sessionTimeout: 30 * 60 * 1000,
@@ -290,6 +300,13 @@ export class MCPServer extends EventEmitter implements IMCPServer {
return this.toolRegistry.registerBatch(tools);
}
+ setToolAuthorizer(authorizer?: ToolAuthorizer): void {
+ if (this.config.requireToolAuthorization && !authorizer) {
+ throw new Error('tool authorization is required and cannot be disabled');
+ }
+ this.toolRegistry.setAuthorizer(authorizer);
+ }
+
unregisterTool(name: string): boolean {
return this.toolRegistry.unregister(name);
}
@@ -1125,7 +1142,8 @@ export function createMCPServer(
config: Partial<MCPServerConfig>,
logger: ILogger,
orchestrator?: unknown,
- swarmCoordinator?: unknown
+ swarmCoordinator?: unknown,
+ toolAuthorizer?: ToolAuthorizer,
): MCPServer {
- return new MCPServer(config, logger, orchestrator, swarmCoordinator);
+ return new MCPServer(config, logger, orchestrator, swarmCoordinator, toolAuthorizer);
}
diff --git a/v3/@claude-flow/mcp/src/tool-registry.ts b/v3/@claude-flow/mcp/src/tool-registry.ts
index 187737b896..1b812d2037 100644
--- a/v3/@claude-flow/mcp/src/tool-registry.ts
+++ b/v3/@claude-flow/mcp/src/tool-registry.ts
@@ -32,11 +32,25 @@ interface ToolSearchOptions {
cacheable?: boolean;
}
+export interface ToolAuthorizationDecision {
+ allowed: boolean;
+ reason?: string;
+ receiptId?: string;
+}
+
+export type ToolAuthorizer = (
+ name: string,
+ input: Record<string, unknown>,
+ context: ToolContext,
+ tool: MCPTool,
+) => ToolAuthorizationDecision | Promise<ToolAuthorizationDecision>;
+
export class ToolRegistry extends EventEmitter {
private readonly tools: Map<string, ToolMetadata> = new Map();
private readonly categoryIndex: Map<string, Set<string>> = new Map();
private readonly tagIndex: Map<string, Set<string>> = new Map();
private defaultContext?: ToolContext;
+ private authorizer?: ToolAuthorizer;
private totalRegistrations = 0;
private totalLookups = 0;
@@ -303,6 +317,52 @@ export class ToolRegistry extends EventEmitter {
...this.defaultContext,
...context,
};
+
+ if (this.authorizer) {
+ try {
+ const authorization = await this.authorizer(name, input, execContext, metadata.tool);
+ if (!authorization.allowed) {
+ const reason = authorization.reason || 'Denied by policy';
+ this.logger.warn('Tool authorization denied', {
+ name,
+ sessionId: execContext.sessionId,
+ receiptId: authorization.receiptId,
+ reason,
+ });
+ this.emit('tool:denied', {
+ name,
+ input,
+ sessionId: execContext.sessionId,
+ receiptId: authorization.receiptId,
+ reason,
+ });
+ return {
+ content: [{
+ type: 'text',
+ text: `Authorization denied: ${reason}`,
+ }],
+ isError: true,
+ };
+ }
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ this.logger.error('Tool authorization failed closed', { name, error });
+ this.emit('tool:denied', {
+ name,
+ input,
+ sessionId: execContext.sessionId,
+ reason,
+ });
+ return {
+ content: [{
+ type: 'text',
+ text: `Authorization unavailable: ${reason}`,
+ }],
+ isError: true,
+ };
+ }
+ }
+
this.totalExecutions++;
metadata.callCount++;
metadata.lastCalled = new Date();
@@ -351,6 +411,10 @@ export class ToolRegistry extends EventEmitter {
this.defaultContext = context;
}
+ setAuthorizer(authorizer?: ToolAuthorizer): void {
+ this.authorizer = authorizer;
+ }
+
getMetadata(name: string): ToolMetadata | undefined {
return this.tools.get(name);
}
diff --git a/v3/@claude-flow/mcp/src/types.ts b/v3/@claude-flow/mcp/src/types.ts
index d256fa17c6..e660f4fa03 100644
--- a/v3/@claude-flow/mcp/src/types.ts
+++ b/v3/@claude-flow/mcp/src/types.ts
@@ -115,6 +115,8 @@ export interface MCPServerConfig {
enableCaching?: boolean;
cacheTTL?: number;
logLevel?: 'debug' | 'info' | 'warn' | 'error';
+ /** Fail construction unless a ToolAuthorizer is installed. */
+ requireToolAuthorization?: boolean;
}
// ============================================================================
diff --git a/v3/@claude-flow/security/__tests__/agentic-policy-engine.test.ts b/v3/@claude-flow/security/__tests__/agentic-policy-engine.test.ts
new file mode 100644
index 0000000000..4e474dddd9
--- /dev/null
+++ b/v3/@claude-flow/security/__tests__/agentic-policy-engine.test.ts
@@ -0,0 +1,288 @@
+import { describe, expect, it } from 'vitest';
+import {
+ AgenticPolicyEngine,
+ checkCapabilityEnvelope,
+ createLegacyCompatibleState,
+ delegateEnvelope,
+ isEnvelopeReduction,
+ type PolicyRequest,
+ type PolicyRule,
+} from '../src/policy/index.js';
+
+const request = (overrides: Partial<PolicyRequest> = {}): PolicyRequest => ({
+ identity: { id: 'agent:coder', type: 'agent', roles: ['developer'] },
+ action: { type: 'code.write', resource: 'src/app.ts', environment: 'development' },
+ ...overrides,
+});
+
+describe('AgenticPolicyEngine', () => {
+ it('preserves existing installations in legacy mode', () => {
+ const engine = AgenticPolicyEngine.fromState(createLegacyCompatibleState());
+ const decision = engine.evaluate(request());
+ expect(decision.outcome).toBe('allowed');
+ expect(decision.enforcedOutcome).toBe('allowed');
+ expect(decision.reason).toBe('legacy-default-allow');
+ });
+
+ it('observes default deny without breaking the action', () => {
+ const engine = new AgenticPolicyEngine({ mode: 'observe' });
+ const decision = engine.evaluate(request());
+ expect(decision.outcome).toBe('denied');
+ expect(decision.enforcedOutcome).toBe('allowed');
+ });
+
+ it('enforces default deny and deny-overrides', () => {
+ const rules: PolicyRule[] = [
+ { id: 'allow-code', effect: 'allow', actions: ['code.*'] },
+ { id: 'deny-production', effect: 'deny', actions: ['code.write'], environments: ['production'], priority: 10 },
+ ];
+ const engine = new AgenticPolicyEngine({ mode: 'enforce', rules });
+ expect(engine.evaluate(request()).enforcedOutcome).toBe('allowed');
+ expect(engine.evaluate(request({
+ action: { type: 'code.write', resource: 'src/app.ts', environment: 'production' },
+ })).enforcedOutcome).toBe('denied');
+ });
+
+ it('requires signed tool evidence when a rule asks for it', () => {
+ const engine = new AgenticPolicyEngine({
+ mode: 'enforce',
+ evidenceVerifier: (evidence) => evidence.signature === 'valid-test-signature',
+ rules: [{
+ id: 'verified-deploy',
+ effect: 'allow',
+ actions: ['deployment.promote'],
+ constraints: { requireSignedEvidence: true, requiredProvenance: ['tool_result'] },
+ }],
+ });
+ const base = request({ action: { type: 'deployment.promote', environment: 'production' } });
+ expect(engine.evaluate(base).enforcedOutcome).toBe('denied');
+ expect(engine.evaluate({
+ ...base,
+ context: { evidence: [{
+ id: 'evidence-1',
+ provenance: 'tool_result',
+ signed: true,
+ signature: 'valid-test-signature',
+ }] },
+ }).enforcedOutcome).toBe('allowed');
+ expect(engine.evaluate({
+ ...base,
+ context: { evidence: [{ id: 'fake', provenance: 'tool_result', signed: true }] },
+ }).enforcedOutcome).toBe('denied');
+ expect(engine.evaluate({
+ ...base,
+ context: {
+ evidence: [
+ { id: 'verified-wrong-type', provenance: 'user_claim', signature: 'valid-test-signature' },
+ { id: 'unsigned-right-type', provenance: 'tool_result' },
+ ],
+ },
+ }).enforcedOutcome).toBe('denied');
+ });
+
+ it('requires a scoped human approval and forbids self approval', () => {
+ const engine = new AgenticPolicyEngine({
+ mode: 'enforce',
+ now: () => 1_000,
+ approvalIssuerVerifier: (issuer) => issuer === 'user:release-manager',
+ rules: [{ id: 'prod-approval', effect: 'require_approval', actions: ['deployment.promote'] }],
+ });
+ expect(() => engine.issueApproval({
+ id: 'self',
+ principal: 'agent:coder',
+ actions: ['deployment.promote'],
+ issuedBy: 'agent:coder',
+ expiresAt: 2_000,
+ maxUses: 2,
+ })).toThrow('self-approval-forbidden');
+ engine.issueApproval({
+ id: 'human-1',
+ principal: 'agent:coder',
+ actions: ['deployment.promote'],
+ issuedBy: 'user:release-manager',
+ expiresAt: 2_000,
+ maxUses: 1,
+ });
+ const deploy = request({
+ action: { type: 'deployment.promote', resource: 'prod' },
+ context: { approvalIds: ['human-1'], now: 1_100 },
+ });
+ expect(engine.evaluate(deploy).reason).toBe('approved-by:human-1');
+ expect(engine.evaluate(deploy).enforcedOutcome).toBe('approval_required');
+ });
+
+ it('uses authority time and rejects ambiguous approval accounting', () => {
+ let authorityNow = 2_000;
+ const engine = new AgenticPolicyEngine({
+ mode: 'enforce',
+ now: () => authorityNow,
+ approvalIssuerVerifier: () => true,
+ rules: [{ id: 'approval', effect: 'require_approval', actions: ['deploy'] }],
+ });
+ engine.issueApproval({
+ id: 'approval-1',
+ principal: 'agent:coder',
+ actions: ['deploy'],
+ issuedBy: 'user:admin',
+ issuedAt: 1_000,
+ expiresAt: 3_000,
+ maxUses: 1,
+ });
+ expect(() => engine.issueApproval({
+ id: 'approval-1',
+ principal: 'agent:coder',
+ actions: ['deploy'],
+ issuedBy: 'user:admin',
+ issuedAt: 1_000,
+ expiresAt: 3_000,
+ maxUses: 1,
+ })).toThrow('duplicate-approval-id');
+ expect(() => engine.issueApproval({
+ id: 'bad-uses',
+ principal: 'agent:coder',
+ actions: ['deploy'],
+ issuedBy: 'user:admin',
+ issuedAt: 1_000,
+ expiresAt: 3_000,
+ maxUses: 1,
+ uses: -1,
+ })).toThrow('invalid-approval');
+ expect(engine.evaluate(request({
+ action: { type: 'deploy' },
+ context: { approvalIds: ['approval-1'], now: 0 },
+ })).enforcedOutcome).toBe('allowed');
+ authorityNow = 4_000;
+ expect(engine.evaluate(request({
+ action: { type: 'deploy' },
+ context: { approvalIds: ['approval-1'], now: 0 },
+ })).enforcedOutcome).toBe('approval_required');
+ });
+
+ it('atomically accounts budget usage', () => {
+ const engine = new AgenticPolicyEngine({
+ mode: 'enforce',
+ now: () => 10,
+ rules: [{ id: 'allow-model', effect: 'allow', actions: ['model.call'] }],
+ budgets: [{ id: 'daily', principal: 'agent:*', action: 'model.call', maxCostUsd: 1, periodMs: 86_400_000 }],
+ });
+ const call = request({
+ action: { type: 'model.call', resource: 'openrouter', costUsd: 0.6 },
+ });
+ expect(engine.evaluate(call).enforcedOutcome).toBe('allowed');
+ expect(engine.evaluate(call).reason).toBe('budget-exceeded:daily');
+ });
+
+ it('creates and verifies a tamper-evident receipt chain', () => {
+ const engine = new AgenticPolicyEngine({ mode: 'legacy', signingKey: 'test-secret' });
+ engine.evaluate(request());
+ engine.evaluate(request({ action: { type: 'code.read', resource: 'README.md' } }));
+ expect(engine.verifyLedger()).toEqual({ valid: true, length: 2 });
+
+ const state = engine.exportState();
+ state.receipts[0]!.payload.decision.reason = 'tampered';
+ const tampered = AgenticPolicyEngine.fromState(state, { signingKey: 'test-secret' });
+ expect(tampered.verifyLedger().valid).toBe(false);
+ });
+
+ it('requires configured receipt authentication in both directions', () => {
+ const signed = new AgenticPolicyEngine({ mode: 'legacy', signingKey: 'test-secret' });
+ signed.evaluate(request());
+ const strippedState = signed.exportState();
+ delete strippedState.receipts[0]!.signature;
+ expect(AgenticPolicyEngine.fromState(strippedState, { signingKey: 'test-secret' }).verifyLedger().error)
+ .toBe('receipt-signature-missing');
+
+ const signedState = signed.exportState();
+ expect(AgenticPolicyEngine.fromState(signedState).verifyLedger().error)
+ .toBe('receipt-signing-key-required');
+ });
+
+ it('rejects negative and non-finite resource accounting', () => {
+ const engine = new AgenticPolicyEngine({ mode: 'legacy' });
+ expect(() => engine.evaluate(request({
+ action: { type: 'model.call', costUsd: -1 },
+ }))).toThrow('invalid-policy-action-costUsd');
+ expect(() => engine.evaluate(request({
+ action: { type: 'model.call', tokens: Number.POSITIVE_INFINITY },
+ }))).toThrow('invalid-policy-action-tokens');
+ });
+
+ it('fails closed when a constrained action omits required metering', () => {
+ const engine = new AgenticPolicyEngine({
+ mode: 'enforce',
+ rules: [{
+ id: 'bounded-model',
+ effect: 'allow',
+ actions: ['model.call'],
+ constraints: { maxCostUsd: 1, maxTokens: 1_000, maxConcurrency: 1 },
+ }],
+ });
+ expect(engine.evaluate(request({ action: { type: 'model.call' } })).enforcedOutcome).toBe('denied');
+ expect(engine.evaluate(request({
+ action: { type: 'model.call', costUsd: 0.5, tokens: 500, concurrency: 1 },
+ })).enforcedOutcome).toBe('allowed');
+ });
+});
+
+describe('CapabilityEnvelope', () => {
+ const parent = {
+ actions: ['code.*'],
+ resources: ['src/*'],
+ tools: ['exec_command', 'apply_patch'],
+ maxCostUsd: 10,
+ maxConcurrency: 4,
+ network: false,
+ destructive: false,
+ delegationDepth: 2,
+ expiresAt: 2_000,
+ };
+
+ it('allows only monotonic reductions', () => {
+ const child = delegateEnvelope(parent, {
+ actions: ['code.write'],
+ resources: ['src/app.ts'],
+ tools: ['apply_patch'],
+ maxCostUsd: 2,
+ maxConcurrency: 2,
+ network: false,
+ destructive: false,
+ });
+ expect(isEnvelopeReduction(parent, child)).toBe(true);
+ expect(child.delegationDepth).toBe(1);
+ expect(() => delegateEnvelope(parent, { tools: ['github_push'] })).toThrow('capability-envelope-cannot-grow');
+ const inherited = delegateEnvelope(parent, {});
+ expect(inherited.actions).toEqual(parent.actions);
+ expect(inherited.tools).toEqual(parent.tools);
+ expect(inherited.maxCostUsd).toBe(parent.maxCostUsd);
+ expect(checkCapabilityEnvelope({
+ type: 'deployment.promote',
+ tool: 'github_push',
+ }, inherited, 1_000).allowed).toBe(false);
+ });
+
+ it('blocks actions outside the envelope before execution', () => {
+ expect(checkCapabilityEnvelope({
+ type: 'code.write',
+ resource: 'src/app.ts',
+ tool: 'apply_patch',
+ concurrency: 2,
+ }, parent, 1_000).allowed).toBe(true);
+ expect(checkCapabilityEnvelope({
+ type: 'code.write',
+ resource: 'src/app.ts',
+ tool: 'apply_patch',
+ network: true,
+ }, 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 },
+ context: { envelope: parent },
+ }));
+ expect(decision.outcome).toBe('denied');
+ expect(decision.enforcedOutcome).toBe('denied');
+ expect(decision.reason).toBe('network-outside-envelope');
+ });
+});
diff --git a/v3/@claude-flow/security/package.json b/v3/@claude-flow/security/package.json
index 10b027f3e2..197213c573 100644
--- a/v3/@claude-flow/security/package.json
+++ b/v3/@claude-flow/security/package.json
@@ -11,6 +11,7 @@
},
"scripts": {
"test": "vitest run",
+ "benchmark:policy": "npm run build && node scripts/benchmark-policy-engine.mjs",
"test:oauth-surface": "vitest run __tests__/oauth-export-surface.test.ts __tests__/oauth-pkce.test.ts __tests__/oauth-browser.test.ts",
"build": "tsc && node scripts/verify-oauth-exports.mjs",
"prepublishOnly": "npm run build && npm run test:oauth-surface"
diff --git a/v3/@claude-flow/security/scripts/benchmark-policy-engine.mjs b/v3/@claude-flow/security/scripts/benchmark-policy-engine.mjs
new file mode 100644
index 0000000000..7bb740b8af
--- /dev/null
+++ b/v3/@claude-flow/security/scripts/benchmark-policy-engine.mjs
@@ -0,0 +1,51 @@
+import { performance } from 'node:perf_hooks';
+import { AgenticPolicyEngine, evaluatePolicy } from '../dist/policy/index.js';
+
+const iterations = Number(process.env.POLICY_BENCH_ITERATIONS ?? 50_000);
+const request = {
+ identity: { id: 'agent:benchmark', type: 'agent', roles: ['developer'] },
+ action: { type: 'code.write', resource: 'src/app.ts', environment: 'development' },
+ context: {
+ envelope: {
+ actions: ['code.*'],
+ resources: ['src/*'],
+ maxConcurrency: 4,
+ network: false,
+ destructive: false,
+ },
+ },
+};
+const rules = [
+ { id: 'allow-dev-code', effect: 'allow', actions: ['code.*'], roles: ['developer'], environments: ['development'] },
+ { id: 'deny-prod-write', effect: 'deny', actions: ['code.write'], environments: ['production'], priority: 100 },
+];
+
+const pureStarted = performance.now();
+for (let i = 0; i < iterations; i++) evaluatePolicy(request, rules, 'enforce');
+const pureMs = performance.now() - pureStarted;
+
+const receiptIterations = Math.min(iterations, 5_000);
+const engine = new AgenticPolicyEngine({ mode: 'enforce', rules });
+const receiptStarted = performance.now();
+for (let i = 0; i < receiptIterations; i++) engine.evaluate({ ...request, requestId: `bench-${i}` });
+const receiptMs = performance.now() - receiptStarted;
+
+const report = {
+ schema: 'ruflo.policy-benchmark/v1',
+ pure: {
+ iterations,
+ durationMs: Number(pureMs.toFixed(3)),
+ opsPerSecond: Math.round(iterations / (pureMs / 1_000)),
+ microsPerDecision: Number(((pureMs * 1_000) / iterations).toFixed(3)),
+ },
+ withReceipts: {
+ iterations: receiptIterations,
+ durationMs: Number(receiptMs.toFixed(3)),
+ opsPerSecond: Math.round(receiptIterations / (receiptMs / 1_000)),
+ microsPerDecision: Number(((receiptMs * 1_000) / receiptIterations).toFixed(3)),
+ ledgerValid: engine.verifyLedger().valid,
+ },
+};
+
+console.log(JSON.stringify(report, null, 2));
+if (!report.withReceipts.ledgerValid) process.exitCode = 1;
diff --git a/v3/@claude-flow/security/src/index.ts b/v3/@claude-flow/security/src/index.ts
index e06ba7419c..a4bfbb026f 100644
--- a/v3/@claude-flow/security/src/index.ts
+++ b/v3/@claude-flow/security/src/index.ts
@@ -134,6 +134,12 @@ export {
type ToolCallDecision,
} from './authorization/propagator.js';
+// Agentic Policy Engine (ADR-324)
+// Deterministic policy evaluation, monotonic capability envelopes, approvals,
+// budgets, and tamper-evident decision receipts. Legacy mode preserves the
+// behavior of pre-ADR-324 installations until enforcement is explicitly enabled.
+export * from './policy/index.js';
+
// OAuth 2.0 + PKCE + OS Keychain (ADR-306)
// A TypeScript port of meta-proxy's proven oauth/{client,pkce,browser,
// callback_server}.rs β€” see src/oauth/client.ts for why this targets the
diff --git a/v3/@claude-flow/security/src/policy/canonical.ts b/v3/@claude-flow/security/src/policy/canonical.ts
new file mode 100644
index 0000000000..ddb6c27383
--- /dev/null
+++ b/v3/@claude-flow/security/src/policy/canonical.ts
@@ -0,0 +1,35 @@
+import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
+
+function normalize(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(normalize);
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>)
+ .filter(([, item]) => item !== undefined)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, item]) => [key, normalize(item)]),
+ );
+ }
+ if (typeof value === 'number' && !Number.isFinite(value)) {
+ throw new TypeError('Policy canonicalization rejects non-finite numbers');
+ }
+ return value;
+}
+
+export function canonicalizePolicy(value: unknown): string {
+ return JSON.stringify(normalize(value));
+}
+
+export function policyHash(value: unknown): string {
+ return `sha256:${createHash('sha256').update(canonicalizePolicy(value)).digest('hex')}`;
+}
+
+export function signPolicyHash(hash: string, key: string | Buffer): string {
+ return createHmac('sha256', key).update(hash).digest('base64url');
+}
+
+export function verifyPolicySignature(hash: string, signature: string, key: string | Buffer): boolean {
+ const expected = Buffer.from(signPolicyHash(hash, key));
+ const actual = Buffer.from(signature);
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
+}
diff --git a/v3/@claude-flow/security/src/policy/engine.ts b/v3/@claude-flow/security/src/policy/engine.ts
new file mode 100644
index 0000000000..3ce5b11255
--- /dev/null
+++ b/v3/@claude-flow/security/src/policy/engine.ts
@@ -0,0 +1,299 @@
+import { policyHash, signPolicyHash, verifyPolicySignature } from './canonical.js';
+import { evaluatePolicy } from './evaluator.js';
+import type {
+ BudgetLimit,
+ BudgetUsage,
+ PolicyApproval,
+ PolicyDecision,
+ PolicyEvidence,
+ PolicyEngineOptions,
+ PolicyReceipt,
+ PolicyRequest,
+ PolicyRule,
+ PolicyState,
+} from './types.js';
+import { POLICY_STATE_VERSION } from './types.js';
+
+function wildcard(pattern: string | undefined, value: string | undefined): boolean {
+ if (!pattern) return true;
+ if (!value) return false;
+ return pattern === '*' || pattern === value || (pattern.endsWith('*') && value.startsWith(pattern.slice(0, -1)));
+}
+
+export class AgenticPolicyEngine {
+ private readonly now: () => number;
+ private readonly signingKey?: string | Buffer;
+ private readonly keyId?: string;
+ private readonly evidenceVerifier?: (evidence: PolicyEvidence, request: PolicyRequest) => boolean;
+ private readonly approvalIssuerVerifier?: (issuer: string) => boolean;
+ private state: PolicyState;
+
+ constructor(options: PolicyEngineOptions = {}) {
+ this.now = options.now ?? Date.now;
+ this.signingKey = options.signingKey;
+ this.keyId = options.keyId;
+ this.evidenceVerifier = options.evidenceVerifier;
+ this.approvalIssuerVerifier = options.approvalIssuerVerifier;
+ this.state = {
+ version: POLICY_STATE_VERSION,
+ mode: options.mode ?? 'legacy',
+ rules: [...(options.rules ?? [])],
+ budgets: [...(options.budgets ?? [])],
+ usage: [...(options.usage ?? [])],
+ approvals: [...(options.approvals ?? [])],
+ receipts: [...(options.receipts ?? [])],
+ };
+ }
+
+ static fromState(state: PolicyState, options: Omit<PolicyEngineOptions, 'mode' | 'rules' | 'budgets' | 'usage' | 'approvals' | 'receipts'> = {}): AgenticPolicyEngine {
+ const engine = new AgenticPolicyEngine({
+ ...options,
+ mode: state.mode,
+ rules: state.rules,
+ budgets: state.budgets,
+ usage: state.usage,
+ approvals: state.approvals,
+ receipts: state.receipts,
+ });
+ engine.state.migratedAt = state.migratedAt;
+ engine.state.migratedFrom = state.migratedFrom;
+ engine.state.configuredMode = state.configuredMode;
+ return engine;
+ }
+
+ exportState(): PolicyState {
+ return structuredClone(this.state);
+ }
+
+ setMode(mode: PolicyState['mode']): void {
+ this.state.mode = mode;
+ }
+
+ setConfiguredMode(mode: PolicyState['mode']): void {
+ this.state.configuredMode = mode;
+ const rank = { legacy: 0, observe: 1, enforce: 2 } as const;
+ if (rank[mode] > rank[this.state.mode]) this.state.mode = mode;
+ }
+
+ upsertRule(rule: PolicyRule): void {
+ if (!rule.id || !rule.actions.length) throw new Error('invalid-policy-rule');
+ for (const value of [
+ rule.constraints?.maxCostUsd,
+ rule.constraints?.maxTokens,
+ rule.constraints?.maxConcurrency,
+ ]) {
+ if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
+ throw new Error('invalid-policy-rule-limit');
+ }
+ }
+ const index = this.state.rules.findIndex((item) => item.id === rule.id);
+ if (index >= 0) this.state.rules[index] = structuredClone(rule);
+ else this.state.rules.push(structuredClone(rule));
+ }
+
+ setBudget(limit: BudgetLimit): void {
+ if (limit.periodMs <= 0) throw new Error('invalid-budget-period');
+ if (!Number.isFinite(limit.periodMs)
+ || [limit.maxCostUsd, limit.maxTokens].some((value) => (
+ value !== undefined && (!Number.isFinite(value) || value < 0)
+ ))) throw new Error('invalid-budget-limit');
+ const index = this.state.budgets.findIndex((item) => item.id === limit.id);
+ if (index >= 0) this.state.budgets[index] = structuredClone(limit);
+ else this.state.budgets.push(structuredClone(limit));
+ }
+
+ issueApproval(approval: Omit<PolicyApproval, 'uses' | 'issuedAt'> & { uses?: number; issuedAt?: number }): PolicyApproval {
+ if (approval.issuedBy === approval.principal) throw new Error('self-approval-forbidden');
+ if (this.approvalIssuerVerifier?.(approval.issuedBy) !== true) {
+ throw new Error('untrusted-approval-issuer');
+ }
+ const issuedAt = approval.issuedAt ?? this.now();
+ const record: PolicyApproval = { ...approval, issuedAt, uses: approval.uses ?? 0 };
+ if (this.state.approvals.some((item) => item.id === record.id)) throw new Error('duplicate-approval-id');
+ if (!record.id
+ || record.expiresAt <= issuedAt
+ || !Number.isInteger(record.maxUses)
+ || record.maxUses <= 0
+ || !Number.isInteger(record.uses)
+ || record.uses < 0
+ || record.uses > record.maxUses) throw new Error('invalid-approval');
+ this.state.approvals.push(record);
+ return structuredClone(record);
+ }
+
+ revokeApproval(id: string): boolean {
+ const approval = this.state.approvals.find((item) => item.id === id);
+ if (!approval || approval.revokedAt) return false;
+ approval.revokedAt = this.now();
+ return true;
+ }
+
+ evaluate(request: PolicyRequest): PolicyDecision {
+ const normalized: PolicyRequest = {
+ ...request,
+ requestId: request.requestId ?? crypto.randomUUID(),
+ // Caller time is evidence only; expiry, budgets, and receipts always use
+ // the authority's clock.
+ context: { ...request.context, now: this.now() },
+ };
+ this.validateRequest(normalized);
+ const verifiedEvidenceIds = (normalized.context?.evidence ?? [])
+ .filter((evidence) => evidence.id && this.evidenceVerifier?.(evidence, normalized) === true)
+ .map((evidence) => evidence.id!);
+ let decision = evaluatePolicy(normalized, this.state.rules, this.state.mode, verifiedEvidenceIds);
+ decision = this.applyBudget(normalized, decision);
+ decision = this.applyApproval(normalized, decision);
+ const receipt = this.appendReceipt(normalized, decision);
+ this.consumeBudget(normalized, decision);
+ return { ...decision, receiptId: receipt.payload.receiptId };
+ }
+
+ verifyLedger(): { valid: boolean; length: number; error?: string } {
+ let previous: string | null = null;
+ for (let i = 0; i < this.state.receipts.length; i++) {
+ const receipt = this.state.receipts[i]!;
+ if (receipt.payload.sequence !== i || receipt.payload.previousReceiptHash !== previous) {
+ return { valid: false, length: i, error: 'receipt-chain-mismatch' };
+ }
+ const hash = policyHash(receipt.payload);
+ const { receiptId, ...unsignedIdPayload } = receipt.payload;
+ if (hash !== receipt.hash || receiptId !== policyHash(unsignedIdPayload)) {
+ return { valid: false, length: i, error: 'receipt-hash-mismatch' };
+ }
+ if (this.signingKey && !receipt.signature) {
+ return { valid: false, length: i, error: 'receipt-signature-missing' };
+ }
+ if (receipt.signature && !this.signingKey) {
+ return { valid: false, length: i, error: 'receipt-signing-key-required' };
+ }
+ if (receipt.signature && this.signingKey && !verifyPolicySignature(hash, receipt.signature, this.signingKey)) {
+ return { valid: false, length: i, error: 'receipt-signature-invalid' };
+ }
+ previous = receipt.hash;
+ }
+ return { valid: true, length: this.state.receipts.length };
+ }
+
+ private applyBudget(request: PolicyRequest, decision: Omit<PolicyDecision, 'receiptId'>): Omit<PolicyDecision, 'receiptId'> {
+ if (decision.outcome === 'denied') return decision;
+ const now = request.context?.now ?? this.now();
+ for (const limit of this.state.budgets) {
+ if (!wildcard(limit.principal, request.identity.id)
+ || !wildcard(limit.action, request.action.type)
+ || !wildcard(limit.resource, request.action.resource)) continue;
+ let usage = this.state.usage.find((item) => item.limitId === limit.id);
+ if (!usage || now - usage.windowStartedAt >= limit.periodMs) {
+ usage = { limitId: limit.id, windowStartedAt: now, costUsd: 0, tokens: 0 };
+ }
+ if (limit.maxCostUsd !== undefined && usage.costUsd + (request.action.costUsd ?? 0) > limit.maxCostUsd) {
+ return { ...decision, outcome: 'denied', enforcedOutcome: this.state.mode === 'enforce' ? 'denied' : 'allowed', reason: `budget-exceeded:${limit.id}` };
+ }
+ if (limit.maxCostUsd !== undefined && request.action.costUsd === undefined) {
+ return { ...decision, outcome: 'denied', enforcedOutcome: this.state.mode === 'enforce' ? 'denied' : 'allowed', reason: `budget-metering-required:${limit.id}:costUsd` };
+ }
+ if (limit.maxTokens !== undefined && request.action.tokens === undefined) {
+ return { ...decision, outcome: 'denied', enforcedOutcome: this.state.mode === 'enforce' ? 'denied' : 'allowed', reason: `budget-metering-required:${limit.id}:tokens` };
+ }
+ if (limit.maxTokens !== undefined && usage.tokens + (request.action.tokens ?? 0) > limit.maxTokens) {
+ return { ...decision, outcome: 'denied', enforcedOutcome: this.state.mode === 'enforce' ? 'denied' : 'allowed', reason: `budget-exceeded:${limit.id}` };
+ }
+ }
+ return decision;
+ }
+
+ private applyApproval(request: PolicyRequest, decision: Omit<PolicyDecision, 'receiptId'>): Omit<PolicyDecision, 'receiptId'> {
+ if (decision.outcome !== 'approval_required') return decision;
+ const now = request.context?.now ?? this.now();
+ const ids = new Set(request.context?.approvalIds ?? []);
+ const approval = this.state.approvals.find((item) => (
+ ids.has(item.id)
+ && !item.revokedAt
+ && item.expiresAt > now
+ && item.uses < item.maxUses
+ && wildcard(item.principal, request.identity.id)
+ && item.actions.some((action) => wildcard(action, request.action.type))
+ && (!item.resources?.length || item.resources.some((resource) => wildcard(resource, request.action.resource)))
+ ));
+ if (!approval) return decision;
+ approval.uses += 1;
+ return {
+ ...decision,
+ outcome: 'allowed',
+ enforcedOutcome: 'allowed',
+ reason: `approved-by:${approval.id}`,
+ approvalId: approval.id,
+ obligations: [],
+ };
+ }
+
+ private consumeBudget(request: PolicyRequest, decision: Omit<PolicyDecision, 'receiptId'>): void {
+ if (decision.enforcedOutcome !== 'allowed') return;
+ const now = request.context?.now ?? this.now();
+ for (const limit of this.state.budgets) {
+ if (!wildcard(limit.principal, request.identity.id)
+ || !wildcard(limit.action, request.action.type)
+ || !wildcard(limit.resource, request.action.resource)) continue;
+ let usage = this.state.usage.find((item) => item.limitId === limit.id);
+ if (!usage || now - usage.windowStartedAt >= limit.periodMs) {
+ usage = { limitId: limit.id, windowStartedAt: now, costUsd: 0, tokens: 0 };
+ this.state.usage = this.state.usage.filter((item) => item.limitId !== limit.id);
+ this.state.usage.push(usage);
+ }
+ usage.costUsd += request.action.costUsd ?? 0;
+ usage.tokens += request.action.tokens ?? 0;
+ }
+ }
+
+ private appendReceipt(request: PolicyRequest, decision: Omit<PolicyDecision, 'receiptId'>): PolicyReceipt {
+ const previous = this.state.receipts.at(-1)?.hash ?? null;
+ const sequence = this.state.receipts.length;
+ const payloadWithoutId = {
+ previousReceiptHash: previous,
+ sequence,
+ issuedAt: request.context?.now ?? this.now(),
+ request,
+ decision,
+ policyHash: policyHash({ mode: this.state.mode, rules: this.state.rules, budgets: this.state.budgets }),
+ };
+ const receiptId = policyHash(payloadWithoutId);
+ const payload = { receiptId, ...payloadWithoutId };
+ const hash = policyHash(payload);
+ const receipt: PolicyReceipt = {
+ payload,
+ hash,
+ signature: this.signingKey ? signPolicyHash(hash, this.signingKey) : undefined,
+ keyId: this.signingKey ? (this.keyId ?? 'local') : undefined,
+ };
+ this.state.receipts.push(receipt);
+ return receipt;
+ }
+
+ private validateRequest(request: PolicyRequest): void {
+ if (!request.identity?.id || !request.identity.type || !request.action?.type) {
+ throw new Error('invalid-policy-request');
+ }
+ for (const [name, value] of [
+ ['costUsd', request.action.costUsd],
+ ['tokens', request.action.tokens],
+ ['concurrency', request.action.concurrency],
+ ] as const) {
+ if (value !== undefined && (!Number.isFinite(value) || value < 0)) {
+ throw new Error(`invalid-policy-action-${name}`);
+ }
+ }
+ }
+}
+
+export function createLegacyCompatibleState(source = 'pre-ADR-324'): PolicyState {
+ return {
+ version: POLICY_STATE_VERSION,
+ mode: 'legacy',
+ migratedFrom: source,
+ migratedAt: Date.now(),
+ rules: [],
+ budgets: [],
+ usage: [],
+ approvals: [],
+ receipts: [],
+ };
+}
diff --git a/v3/@claude-flow/security/src/policy/envelope.ts b/v3/@claude-flow/security/src/policy/envelope.ts
new file mode 100644
index 0000000000..4b3fb36e14
--- /dev/null
+++ b/v3/@claude-flow/security/src/policy/envelope.ts
@@ -0,0 +1,109 @@
+import type { CapabilityEnvelope, PolicyAction } from './types.js';
+
+export interface EnvelopeCheck {
+ allowed: boolean;
+ reason?: string;
+}
+
+function matches(patterns: readonly string[] | undefined, value: string | undefined): boolean {
+ if (!patterns?.length) return true;
+ if (!value) return false;
+ return patterns.some((pattern) => (
+ pattern === '*'
+ || pattern === value
+ || (pattern.endsWith('*') && value.startsWith(pattern.slice(0, -1)))
+ ));
+}
+
+function subset(child: readonly string[] | undefined, parent: readonly string[] | undefined): boolean {
+ if (!parent?.length) return true;
+ if (!child?.length) return false;
+ return child.every((value) => matches(parent, value));
+}
+
+export function checkCapabilityEnvelope(
+ action: PolicyAction,
+ envelope: CapabilityEnvelope | undefined,
+ now = Date.now(),
+): EnvelopeCheck {
+ if (!envelope) return { allowed: true };
+ if (envelope.expiresAt !== undefined && envelope.expiresAt <= now) {
+ return { allowed: false, reason: 'capability-envelope-expired' };
+ }
+ const checks: Array<[boolean, string]> = [
+ [matches(envelope.actions, action.type), 'action-outside-envelope'],
+ [matches(envelope.resources, action.resource), 'resource-outside-envelope'],
+ [matches(envelope.tools, action.tool), 'tool-outside-envelope'],
+ [matches(envelope.servers, action.server), 'server-outside-envelope'],
+ [matches(envelope.environments, action.environment), 'environment-outside-envelope'],
+ ];
+ if (action.namespace) {
+ const namespaces = action.type.includes('read')
+ ? envelope.readNamespaces
+ : 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 (action.tokens !== undefined && envelope.maxTokens !== undefined) {
+ checks.push([action.tokens <= envelope.maxTokens, 'tokens-outside-envelope']);
+ }
+ if (action.concurrency !== undefined && envelope.maxConcurrency !== undefined) {
+ checks.push([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']);
+ const failed = checks.find(([allowed]) => !allowed);
+ return failed ? { allowed: false, reason: failed[1] } : { allowed: true };
+}
+
+export function isEnvelopeReduction(parent: CapabilityEnvelope, child: CapabilityEnvelope): boolean {
+ const listChecks = [
+ subset(child.actions, parent.actions),
+ subset(child.resources, parent.resources),
+ subset(child.tools, parent.tools),
+ subset(child.servers, parent.servers),
+ subset(child.readNamespaces, parent.readNamespaces),
+ subset(child.writeNamespaces, parent.writeNamespaces),
+ subset(child.environments, parent.environments),
+ ];
+ const numericChecks: Array<[number | undefined, number | undefined]> = [
+ [child.maxCostUsd, parent.maxCostUsd],
+ [child.maxTokens, parent.maxTokens],
+ [child.maxConcurrency, parent.maxConcurrency],
+ [child.delegationDepth, parent.delegationDepth],
+ [child.expiresAt, parent.expiresAt],
+ ];
+ return listChecks.every(Boolean)
+ && numericChecks.every(([next, current]) => (
+ current === undefined
+ ? true
+ : next !== undefined && next <= current
+ ))
+ && !(child.network === true && parent.network !== true)
+ && !(child.destructive === true && parent.destructive !== true);
+}
+
+export function delegateEnvelope(
+ parent: CapabilityEnvelope,
+ child: CapabilityEnvelope,
+): CapabilityEnvelope {
+ if ((parent.delegationDepth ?? 0) <= 0) {
+ throw new Error('delegation-depth-exhausted');
+ }
+ const reduced = {
+ ...parent,
+ ...child,
+ delegationDepth: Math.min(
+ child.delegationDepth ?? Number.MAX_SAFE_INTEGER,
+ (parent.delegationDepth ?? 0) - 1,
+ ),
+ expiresAt: Math.min(
+ child.expiresAt ?? Number.MAX_SAFE_INTEGER,
+ parent.expiresAt ?? Number.MAX_SAFE_INTEGER,
+ ),
+ };
+ if (!isEnvelopeReduction(parent, reduced)) throw new Error('capability-envelope-cannot-grow');
+ return reduced;
+}
diff --git a/v3/@claude-flow/security/src/policy/evaluator.ts b/v3/@claude-flow/security/src/policy/evaluator.ts
new file mode 100644
index 0000000000..e4f8b043cf
--- /dev/null
+++ b/v3/@claude-flow/security/src/policy/evaluator.ts
@@ -0,0 +1,130 @@
+import { checkCapabilityEnvelope } from './envelope.js';
+import type {
+ PolicyConstraints,
+ PolicyDecision,
+ PolicyMode,
+ PolicyRequest,
+ PolicyRule,
+} from './types.js';
+
+function matches(patterns: readonly string[] | undefined, value: string | undefined): boolean {
+ if (!patterns?.length) return true;
+ if (!value) return false;
+ return patterns.some((pattern) => (
+ pattern === '*'
+ || pattern === value
+ || (pattern.endsWith('*') && value.startsWith(pattern.slice(0, -1)))
+ ));
+}
+
+function constraintsPass(request: PolicyRequest, constraints: PolicyConstraints | undefined): boolean {
+ if (!constraints) return true;
+ const { action } = request;
+ const evidence = request.context?.evidence ?? [];
+ const verifiedIds = new Set(
+ request.context?.metadata?.verifiedEvidenceIds instanceof Array
+ ? request.context.metadata.verifiedEvidenceIds
+ : [],
+ );
+ const verifiedEvidence = evidence.filter((item) => item.id && verifiedIds.has(item.id));
+ if (constraints.maxCostUsd !== undefined
+ && (action.costUsd === undefined || action.costUsd > constraints.maxCostUsd)) return false;
+ if (constraints.maxTokens !== undefined
+ && (action.tokens === undefined || action.tokens > constraints.maxTokens)) return false;
+ if (constraints.maxConcurrency !== undefined
+ && (action.concurrency === undefined || action.concurrency > constraints.maxConcurrency)) return false;
+ if (constraints.network === false && action.network === true) return false;
+ if (constraints.destructive === false && action.destructive === true) return false;
+ if (constraints.allowedNamespaces?.length && !matches(constraints.allowedNamespaces, action.namespace)) return false;
+ // Signature verification is performed by the engine's trusted verifier.
+ // A caller-authored `signed: true` flag is deliberately ignored.
+ if (constraints.requireSignedEvidence && verifiedEvidence.length === 0) return false;
+ if (constraints.requiredProvenance?.length) {
+ const relevant = constraints.requireSignedEvidence ? verifiedEvidence : evidence;
+ const available = new Set(relevant.map((item) => item.provenance));
+ if (!constraints.requiredProvenance.every((type) => available.has(type))) return false;
+ }
+ return true;
+}
+
+export function ruleMatches(rule: PolicyRule, request: PolicyRequest): boolean {
+ if (rule.enabled === false) return false;
+ const { identity, action } = request;
+ return matches(rule.actions, action.type)
+ && matches(rule.resources, action.resource)
+ && matches(rule.principals, identity.id)
+ && (!rule.identityTypes?.length || rule.identityTypes.includes(identity.type))
+ && (!rule.roles?.length || rule.roles.some((role) => identity.roles?.includes(role)))
+ && matches(rule.environments, action.environment)
+ && constraintsPass(request, rule.constraints);
+}
+
+export function evaluatePolicy(
+ request: PolicyRequest,
+ rules: readonly PolicyRule[],
+ mode: PolicyMode,
+ verifiedEvidenceIds: readonly string[] = [],
+): Omit<PolicyDecision, 'receiptId'> {
+ const requestId = request.requestId ?? crypto.randomUUID();
+ const envelope = checkCapabilityEnvelope(
+ request.action,
+ request.context?.envelope,
+ request.context?.now,
+ );
+ if (!envelope.allowed) {
+ return {
+ requestId,
+ outcome: 'denied',
+ // A capability envelope is delegated authority, not an observation-mode
+ // rule. Crossing it is always blocked, including legacy installations.
+ enforcedOutcome: 'denied',
+ mode,
+ reason: envelope.reason ?? 'capability-envelope-denied',
+ matchedRules: [],
+ obligations: [],
+ };
+ }
+
+ const verifiedRequest: PolicyRequest = {
+ ...request,
+ context: {
+ ...request.context,
+ metadata: {
+ ...request.context?.metadata,
+ verifiedEvidenceIds: [...verifiedEvidenceIds],
+ },
+ },
+ };
+ const matched = rules
+ .filter((rule) => ruleMatches(rule, verifiedRequest))
+ .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id.localeCompare(b.id));
+ const deny = matched.find((rule) => rule.effect === 'deny');
+ const approval = matched.find((rule) => rule.effect === 'require_approval');
+ const allow = matched.find((rule) => rule.effect === 'allow');
+
+ let outcome: PolicyDecision['outcome'];
+ let reason: string;
+ if (deny) {
+ outcome = 'denied';
+ reason = `denied-by:${deny.id}`;
+ } else if (approval) {
+ outcome = 'approval_required';
+ reason = `approval-required-by:${approval.id}`;
+ } else if (allow) {
+ outcome = 'allowed';
+ reason = `allowed-by:${allow.id}`;
+ } else {
+ outcome = mode === 'legacy' ? 'allowed' : 'denied';
+ reason = mode === 'legacy' ? 'legacy-default-allow' : 'default-deny';
+ }
+
+ return {
+ requestId,
+ outcome,
+ enforcedOutcome: mode === 'enforce' ? outcome : 'allowed',
+ mode,
+ reason,
+ matchedRules: matched.map((rule) => rule.id),
+ obligations: approval ? ['valid-human-approval'] : [],
+ };
+}
diff --git a/v3/@claude-flow/security/src/policy/index.ts b/v3/@claude-flow/security/src/policy/index.ts
new file mode 100644
index 0000000000..12b68943f9
--- /dev/null
+++ b/v3/@claude-flow/security/src/policy/index.ts
@@ -0,0 +1,5 @@
+export * from './types.js';
+export * from './canonical.js';
+export * from './envelope.js';
+export * from './evaluator.js';
+export * from './engine.js';
diff --git a/v3/@claude-flow/security/src/policy/types.ts b/v3/@claude-flow/security/src/policy/types.ts
new file mode 100644
index 0000000000..8b7508b881
--- /dev/null
+++ b/v3/@claude-flow/security/src/policy/types.ts
@@ -0,0 +1,190 @@
+export const POLICY_STATE_VERSION = 1;
+
+export type PolicyMode = 'legacy' | 'observe' | 'enforce';
+export type PolicyEffect = 'allow' | 'deny' | 'require_approval';
+export type PolicyOutcome = 'allowed' | 'denied' | 'approval_required';
+export type ProvenanceType =
+ | 'user_claim'
+ | 'agent_output'
+ | 'system_observation'
+ | 'tool_result'
+ | 'unknown';
+
+export interface PolicyIdentity {
+ id: string;
+ type: 'user' | 'agent' | 'service' | 'plugin' | 'legacy';
+ roles?: string[];
+ tenantId?: string;
+ parentId?: string;
+}
+
+export interface PolicyEvidence {
+ id?: string;
+ provenance: ProvenanceType;
+ /** Legacy transport hint. Never sufficient for requireSignedEvidence. */
+ signed?: boolean;
+ attestor?: string;
+ observedAt?: number;
+ contentHash?: string;
+ signature?: string;
+ keyId?: string;
+}
+
+export interface PolicyAction {
+ type: string;
+ resource?: string;
+ tool?: string;
+ server?: string;
+ namespace?: string;
+ environment?: string;
+ costUsd?: number;
+ tokens?: number;
+ concurrency?: number;
+ network?: boolean;
+ destructive?: boolean;
+}
+
+export interface CapabilityEnvelope {
+ actions?: string[];
+ resources?: string[];
+ tools?: string[];
+ servers?: string[];
+ readNamespaces?: string[];
+ writeNamespaces?: string[];
+ environments?: string[];
+ maxCostUsd?: number;
+ maxTokens?: number;
+ maxConcurrency?: number;
+ network?: boolean;
+ destructive?: boolean;
+ delegationDepth?: number;
+ expiresAt?: number;
+}
+
+export interface PolicyContext {
+ now?: number;
+ evidence?: PolicyEvidence[];
+ envelope?: CapabilityEnvelope;
+ approvalIds?: string[];
+ metadata?: Record<string, unknown>;
+}
+
+export interface PolicyRequest {
+ requestId?: string;
+ identity: PolicyIdentity;
+ action: PolicyAction;
+ context?: PolicyContext;
+}
+
+export interface PolicyConstraints {
+ maxCostUsd?: number;
+ maxTokens?: number;
+ maxConcurrency?: number;
+ network?: boolean;
+ destructive?: boolean;
+ requireSignedEvidence?: boolean;
+ requiredProvenance?: ProvenanceType[];
+ allowedNamespaces?: string[];
+}
+
+export interface PolicyRule {
+ id: string;
+ description?: string;
+ enabled?: boolean;
+ priority?: number;
+ effect: PolicyEffect;
+ actions: string[];
+ resources?: string[];
+ principals?: string[];
+ identityTypes?: PolicyIdentity['type'][];
+ roles?: string[];
+ environments?: string[];
+ constraints?: PolicyConstraints;
+ approvalTtlMs?: number;
+}
+
+export interface BudgetLimit {
+ id: string;
+ principal?: string;
+ action?: string;
+ resource?: string;
+ maxCostUsd?: number;
+ maxTokens?: number;
+ periodMs: number;
+}
+
+export interface BudgetUsage {
+ limitId: string;
+ windowStartedAt: number;
+ costUsd: number;
+ tokens: number;
+}
+
+export interface PolicyApproval {
+ id: string;
+ principal: string;
+ actions: string[];
+ resources?: string[];
+ issuedBy: string;
+ issuedAt: number;
+ expiresAt: number;
+ maxUses: number;
+ uses: number;
+ revokedAt?: number;
+}
+
+export interface PolicyDecision {
+ requestId: string;
+ outcome: PolicyOutcome;
+ enforcedOutcome: PolicyOutcome;
+ mode: PolicyMode;
+ reason: string;
+ matchedRules: string[];
+ obligations: string[];
+ approvalId?: string;
+ receiptId?: string;
+}
+
+export interface PolicyReceiptPayload {
+ receiptId: string;
+ previousReceiptHash: string | null;
+ sequence: number;
+ issuedAt: number;
+ request: PolicyRequest;
+ decision: Omit<PolicyDecision, 'receiptId'>;
+ policyHash: string;
+}
+
+export interface PolicyReceipt {
+ payload: PolicyReceiptPayload;
+ hash: string;
+ signature?: string;
+ keyId?: string;
+}
+
+export interface PolicyState {
+ version: number;
+ mode: PolicyMode;
+ migratedFrom?: string;
+ migratedAt?: number;
+ configuredMode?: PolicyMode;
+ rules: PolicyRule[];
+ budgets: BudgetLimit[];
+ usage: BudgetUsage[];
+ approvals: PolicyApproval[];
+ receipts: PolicyReceipt[];
+}
+
+export interface PolicyEngineOptions {
+ mode?: PolicyMode;
+ rules?: PolicyRule[];
+ budgets?: BudgetLimit[];
+ usage?: BudgetUsage[];
+ approvals?: PolicyApproval[];
+ receipts?: PolicyReceipt[];
+ signingKey?: string | Buffer;
+ keyId?: string;
+ now?: () => number;
+ evidenceVerifier?: (evidence: PolicyEvidence, request: PolicyRequest) => boolean;
+ approvalIssuerVerifier?: (issuer: string) => boolean;
+}
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
new file mode 100644
index 0000000000..bf82b697b3
--- /dev/null
+++ b/v3/docs/adr/ADR-324-agentic-policy-engine-codex-swarm.md
@@ -0,0 +1,325 @@
+# ADR-324: Agentic Policy Engine and Policy-Governed Codex Swarms
+
+**Status:** Accepted
+**Date:** 2026-07-28
+**Implementation:** Complete on `feat/adr-324-agentic-policy-engine`
+**Related:** ADR-053 (AgentDB), ADR-101 (federated claims), ADR-131 (tool-output guardrail), ADR-144 (authorization propagation), ADR-145 (memory governance), ADR-176 (self-benchmarking loop), ADR-322/A/B/C (MetaHarness proposer, promotion transaction, receipts)
+
+## Context
+
+Ruflo already contains useful but disconnected controls:
+
+- AgentDB memory, owner/access metadata, typed provenance, HNSW/RaBitQ and legacy SQL.js paths.
+- `AgentAuthorizationPropagator`, whose monotonic `AuthScope` was not wired into production dispatch.
+- Federation message policy, guidance authority levels, launch budgets, plugin integrity, and tool-output guardrails.
+- ADR-322's signed evaluation receipts and compare-and-swap promotion transaction.
+- A Codex adapter that registers Ruflo MCP and generates `AGENTS.md`, but whose concurrent workers could share one checkout and whose generated defaults did not define a single authorization authority.
+
+No component answered the general question:
+
+> May this identity perform this action on this resource, with this evidence,
+> authority, cost, concurrency, and delegation chain, right now?
+
+The missing authority also made concurrency unsafe. A coordinator could record work, but it could not prevent child agents or MetaHarness proposers from widening tools, network access, namespaces, spend, or promotion rights.
+
+## Decision
+
+Ruflo adopts `@claude-flow/security`'s `AgenticPolicyEngine` as the local authorization authority.
+
+```text
+identity + action + resource + evidence + capability envelope
+ + approval + budget + policy version
+ |
+ allow | deny | require_approval
+ |
+ hash-chained decision receipt
+```
+
+The engine is deterministic and side-effect free except for its state transaction. Adapters translate existing subsystem concepts into this request model. Existing specialized controls remain responsible for their domain mechanics; they no longer act as independent authorization authorities.
+
+### Modes and backwards compatibility
+
+| Mode | Logical decision | Runtime behavior |
+|---|---|---|
+| `legacy` | Existing behavior/default allow | allow and issue receipt |
+| `observe` | Evaluate default-deny policy | allow, record would-deny |
+| `enforce` | Evaluate default-deny policy | enforce allow/deny/approval |
+
+Existing installations are auto-migrated to a versioned policy state in `legacy` mode. Migration is additive and detects legacy AgentDB/RVF locations and strict-mode flags without rewriting memory rows, indexes, receipts, namespaces, controller state, ReasoningBank, SkillLibrary, or HNSW data.
+
+New policy fields default to absent/`unknown`. ANN index refreshes must never replace authoritative AgentDB rows. CLI/MCP command names and existing namespaces remain valid.
+
+No automatic update may:
+
+- upgrade across a major version;
+- replace user `AGENTS.md` text or unknown TOML keys;
+- delete or recreate a memory database;
+- rewrite v1 Flywheel receipts or ledger entries;
+- enable unattended fanout or enforcement without an explicit policy transition.
+
+Generated configuration may raise a persisted mode (`legacy` β†’ `observe` β†’
+`enforce`) but cannot lower it. A downgrade is an explicit, interactive local
+administrator action.
+
+### Rule evaluation
+
+Rules match action/resource patterns, principals, identity types, roles, environments, provenance, and hard constraints. Evaluation order is:
+
+1. Validate the request.
+2. Enforce the capability envelope.
+3. Apply matching rules in deterministic priority/id order.
+4. Deny overrides approval and allow.
+5. Approval overrides allow until a valid scoped approval is consumed.
+6. Apply budget ceilings.
+7. Apply mode (`legacy`, `observe`, `enforce`).
+8. Persist the decision receipt before returning authority.
+
+Unmatched actions allow only in `legacy`; `observe` records default-deny but does not block; `enforce` blocks.
+
+### Capability envelopes and delegation
+
+An envelope may constrain actions, resources, tools, MCP servers, read/write namespaces, environments, network/destructive access, cost, tokens, concurrency, expiry, and delegation depth.
+
+Every child envelope must be a monotonic reduction. A child cannot:
+
+- add a pattern not granted by its parent;
+- raise any numeric ceiling;
+- extend expiry or depth;
+- enable network/destructive access disabled by its parent.
+
+Envelope violations are always enforced, including in `legacy` and `observe`;
+those modes apply to policy-rule rollout, not delegated authority boundaries.
+
+Agents and optimizers cannot approve themselves. Approvals are scoped, expiring, revocable, and limited-use.
+Approval creation requires a deployment-supplied authenticated issuer
+verifier. An arbitrary `issuedBy` string, environment allowlist, or local TTY
+is not an authority credential. The default local CLI therefore cannot issue
+approvals. The unregistered administrative MCP adapter derives the issuer from
+authenticated user context and cannot accept a caller-supplied issuer.
+
+### Budgets
+
+Budgets match principal, action, and resource and limit USD/tokens per fixed window. Authorization and usage update occur under one cross-process policy-state lock. A denied action does not consume budget. Domain-specific budget providers may reserve additional resources but cannot weaken this ceiling.
+
+Cost, token, and concurrency fields are declared reservations supplied by a
+trusted adapter, not measurements from a provider invoice. A rule or budget
+that constrains one of these dimensions fails closed when its value is absent.
+Adapters must reserve before execution and reconcile separately; provider-side
+hard caps remain the final ceiling against a compromised or under-reporting
+adapter.
+
+### Receipts and ledger
+
+Every decision binds:
+
+- canonical request and evidence;
+- logical and enforced outcomes;
+- matched rules and obligations;
+- approval id, if consumed;
+- policy bundle hash;
+- previous receipt hash, sequence, and timestamp.
+
+Canonical JSON sorts object keys and rejects non-finite numbers. SHA-256 content identifiers and a hash chain make alteration evident. A configured local key adds an HMAC authentication tag. Cross-install/federated policy bundles continue to require their existing Ed25519 trust model; a local HMAC is not represented as third-party attestation.
+
+When a signing key is configured, unsigned receipts are invalid. Conversely, a
+signed ledger cannot be declared valid without the matching verification key.
+Signed policy evidence uses a trusted key selected by `keyId` from
+`CLAUDE_FLOW_POLICY_EVIDENCE_KEYS`; its HMAC binds id, provenance, attestor,
+observation time, content hash, and key id. The legacy caller-authored
+`signed: true` field is retained for transport compatibility but confers no
+authority.
+
+### Enforcement surfaces
+
+The first authoritative surface is the CLI MCP dispatcher: policy evaluates before tool handlers can produce side effects. The standalone MCP registry exposes the same middleware contract and can require an authorizer at construction; required mode cannot later remove its authorizer. Deployments must opt into that required mode. This ADR does not claim that every independently embedded MCP server or native Codex/Claude action is automatically wired.
+
+Learning, metrics, and pattern storage remain fail-open. Policy enforcement is synchronous and authoritative:
+
+- a first-run installation with no trust anchor may enter compatibility mode;
+- once enforcement creates a trust anchor, missing, modified, or unauthenticated
+ state fails closed and cannot silently return to legacy;
+- host or user-account compromise remains outside this local trust boundary.
+
+### AgentDB compatibility
+
+ADR-323 provenance values are valid evidence types:
+
+`user_claim`, `agent_output`, `system_observation`, `tool_result`, `unknown`.
+
+Policy adapters preserve all previous AgentDB capabilities and add namespace decisions without changing retrieval algorithms. `tool_result` and `system_observation` may be required for factual or production actions. A user claim is not silently upgraded into an observation.
+
+## Codex and Ruflo workflow
+
+Ruflo is the ledger/coordinator/policy decision point. Codex workers execute.
+
+1. Search AgentDB patterns.
+2. Initialize one bounded hierarchical swarm.
+3. Split only independent work.
+4. Assign one git worktree and declared reduced envelope to each writer.
+5. Run workers under hard concurrency/output/time budgets.
+6. Consume committed handoffs in dependency order.
+7. Run scoped tests, full tests, security guards, and MetaHarness.
+8. Store the validated pattern and retain decision/evaluation receipts.
+
+Read-only workers may share a checkout. Writers may not. A designated integration agent owns shared manifests and lockfiles. Dependency cycles, missing dependencies, shared writer paths, non-zero worker exits, and dependency failures are errors rather than implicit success.
+
+`[swarm.automation]` defaults:
+
+```toml
+enabled = false
+max_concurrent = 4
+max_writers = 2
+worktree_isolation = true
+dependency_failure = "cancel"
+agent_timeout_seconds = 1800
+max_output_bytes = 1048576
+```
+
+Worktree cleanup removes only registry-owned, clean worktrees. Dirty worktrees remain for recovery. No force removal or broad path deletion is permitted.
+
+The worker preflight, sanitized environment, declared envelope, and Codex
+sandbox are workflow controls, not an operating-system security boundary. A
+locally compromised child process can invoke tools outside Ruflo unless the
+host also applies container/VM, filesystem, network, and provider controls.
+For Ruflo MCP calls made from a linked worktree, the authoritative policy root
+is derived from Git's canonical common directory, so the worker cannot
+accidentally initialize an independent legacy policy state.
+
+## Concurrent MetaHarness development
+
+MetaHarness/Darwin proposes; Ruflo policy and ADR-322 dispose.
+
+- Candidate/task evaluation uses a bounded worker pool.
+- Result aggregation is deterministic in input/candidate-id order, independent of completion order.
+- Timeout cancellation covers queued and cooperative running work.
+- The run receives a local concurrency ceiling and evaluation wall-time budget.
+- Proposers and evaluators receive no `promote` or `materialize` capability.
+- `metaharness.flywheel.run` and `metaharness.candidate.promote` are distinct policy actions.
+- Promotion still requires ADR-322A confirmation, trusted signature, fresh baseline, fresh ledger head, and atomic compare-and-swap.
+- A policy denial happens before proposer, search, filesystem, or promotion side effects.
+
+Legacy v1 Flywheel receipts remain verifiable byte-for-byte. ADR-324 receipts are additional authorization evidence; they do not rewrite the Flywheel ledger.
+
+## Security model
+
+The design addresses:
+
+1. malicious candidate policy;
+2. compromised child/proposer process;
+3. stale or replayed approval;
+4. concurrent budget/promotion races;
+5. tampered decision ledger;
+6. namespace poisoning;
+7. resource-exhaustion through fanout;
+8. accidental destructive upgrades of prior AgentDB installations.
+
+It does not claim that a local HMAC protects against compromise of the host or signing key. Remote trust requires the established Ed25519 attestation paths.
+
+## Consequences
+
+Positive:
+
+- One auditable authorization result across CLI, MCP, Codex, AgentDB evidence, and MetaHarness.
+- Existing installations continue to work and can rehearse policy in observation mode.
+- Concurrent development has executable worktree and resource boundaries.
+- Optimizers can improve policy/configuration without becoming promotion authorities.
+
+Costs:
+
+- Every consequential action adds a small locked state transaction.
+- Administrators must define rules before enabling enforcement.
+- Legacy permissive behavior remains until a deliberate mode transition.
+
+## Implementation
+
+The normative implementation is split across existing package boundaries:
+
+| Concern | Implementation |
+|---|---|
+| Rules, envelopes, approvals, budgets, canonical receipts | `@claude-flow/security/src/policy` |
+| Cross-process transaction, migration, CLI/MCP adapter | `@claude-flow/cli/src/services/policy-runtime.ts` |
+| Administrator CLI | `ruflo policy status/init/evaluate/rule/budget/revoke/audit/verify`; approval issuance requires an authenticated adapter |
+| Policy MCP tools | Remote default: `policy_evaluate`, `policy_status`; administrative handlers exist for authenticated deployments but are not registered by default |
+| CLI MCP enforcement | `@claude-flow/cli/src/mcp-client.ts` |
+| Standalone MCP enforcement contract | `ToolRegistry.setAuthorizer` / `MCPServer.setToolAuthorizer` |
+| Bounded MetaHarness evaluation | `bounded-worker-pool.ts`, `harness-flywheel.ts`, `harness-flywheel-runtime.ts` |
+| Codex automation | bounded dual-mode orchestrator plus the worktree coordinator |
+| Upgrade behavior | additive Codex settings migration and CLI policy-state auto-migration |
+
+The policy state lives at `.claude-flow/policy/state.json`. Mutations acquire
+`.claude-flow/policy/state.lock` using exclusive creation and replace state by
+atomic rename. Decision, approval consumption, budget usage, and receipt append
+therefore commit as one transaction. A stale lock may be recovered after 30
+seconds; lock acquisition otherwise fails after five seconds.
+
+When enforcement is first enabled, an HMAC key and state authentication record
+are stored outside the workspace under
+`~/.config/ruflo/policy-trust/<project-hash>/`, where the project hash uses
+the canonical real path and cannot be redirected by a worker environment
+variable. Subsequent state loads authenticate the complete state. On first
+enforcement the anchor is written before enforce state, so any crash leaves
+either a valid pair or a fail-closed mismatch. A later crash
+between state and anchor replacement may fail closed and require administrator
+recovery; it cannot produce a silent downgrade.
+
+Generated and migrated Codex configurations install the dedicated
+`claude-flow-mcp` binary, preserve unrelated MCP servers, set policy mode to
+`legacy`, and leave swarm automation disabled. Windows uses `cmd /c`; POSIX
+uses `npx` directly. Existing `AGENTS.md` content is not replaced by runtime
+migration.
+
+Policy administration is not exempt from authorization. Bootstrap and recovery
+mutations use the interactive local `ruflo policy` command. Remote MCP registers
+only evaluation and status by default; administrative handlers require a
+deployment-specific authenticated human identity adapter. Approval issuance
+also requires the issuer allowlist. A standalone MCP server can set
+`requireToolAuthorization = true`, in which case construction fails unless an
+authorizer is supplied.
+
+### Validation evidence
+
+Validated on 2026-07-28:
+
+- Security: 22 files, 537 tests.
+- Codex generation, migration, dual-mode, and worktrees: 7 files, 211 tests.
+- Standalone MCP registry/server: 2 files, 69 tests.
+- Policy runtime, concurrent budget accounting, bounded worker pool,
+ MetaHarness ADR-322 paths, and ADR-323 compatibility: 5 files, 46 tests.
+- TypeScript: security, Codex, MCP, and the changed CLI surface compile cleanly.
+- `git diff --check`: clean.
+
+The policy microbenchmark records:
+
+```text
+pure evaluation: 1,590,091 decisions/second (0.629 Β΅s/decision)
+transaction receipt: 43,251 decisions/second (23.121 Β΅s/decision)
+receipt ledger: valid
+```
+
+These figures are local microbenchmarks, not a production latency guarantee.
+The receipt number excludes filesystem lock contention and disk latency.
+
+## Acceptance tests
+
+1. Legacy install migration preserves existing memory and defaults to `legacy`.
+2. Observe mode records deny while allowing the action.
+3. Enforce mode default-denies unmatched actions.
+4. Deny overrides allow and approval.
+5. A child cannot expand any envelope dimension.
+6. Self-approval, expired approval, replay beyond `maxUses`, and revoked approval fail.
+7. Concurrent budget decisions cannot overspend a ceiling.
+8. Altering one receipt byte breaks ledger verification.
+9. Native and fallback AgentDB paths preserve provenance and prior capabilities.
+10. CLI and MCP policy decisions occur before side effects.
+11. Two concurrent writers cannot share a worktree.
+12. Missing dependencies and cycles fail before workers launch.
+13. Worker fanout never exceeds configured concurrency and output bounds.
+14. Dirty registry-owned worktrees survive cleanup.
+15. MetaHarness peak concurrency never exceeds its envelope.
+16. Timeout cancels queued MetaHarness work.
+17. MetaHarness cannot promote without a separate policy allow/approval and ADR-322A authorization.
+18. Removing or lowering generated configuration cannot downgrade an enforced
+ policy; removing or modifying anchored state fails closed.
+19. A budgeted or constrained request with missing metering is denied.
+20. Worker environments strip common secret variables and policy authority
+ variables before launch.
diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml
index 556e1672c9..a6405920a5 100644
--- a/v3/pnpm-lock.yaml
+++ b/v3/pnpm-lock.yaml
@@ -126,6 +126,12 @@ importers:
'@claude-flow/shared':
specifier: 3.0.0-alpha.7
version: 3.0.0-alpha.7
+ '@metaharness/darwin':
+ specifier: ^0.8.0
+ version: 0.8.0
+ '@metaharness/flywheel':
+ specifier: ^0.1.7
+ version: 0.1.7
'@metaharness/router':
specifier: ^0.3.2
version: 0.3.2
@@ -154,12 +160,6 @@ importers:
'@claude-flow/security':
specifier: ^3.0.0-alpha.12
version: link:../security
- '@metaharness/darwin':
- specifier: ^0.8.0
- version: 0.8.0
- '@metaharness/flywheel':
- specifier: ^0.1.7
- version: 0.1.7
agentdb:
specifier: ^3.0.0-alpha.17
version: 3.0.0-alpha.17(@types/[email protected])([email protected])