π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
dream(security): #3102 bind ADR-377 caller-identity verification into live authorizeMcpTool chokepoint (evaluated, ACCEPT-with-caveats) (#3103)
rUv1bd734e272bd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 93e702b547..209700d639 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -72,6 +72,22 @@ jobs:- name: Install dependenciesuses: ./.github/actions/npm-ci-retry+ - name: Build workspace-linked packages needed at runtime by tests+ # `npm ci` at repo root links @claude-flow/security in via the root+ # npm workspace (package-lock.json records it as a `link: true`+ # entry resolving to v3/@claude-flow/security, not a registry+ # fetch) but never builds it, so importers hit+ # ERR_MODULE_NOT_FOUND on its dist/index.js at runtime β a+ # pre-existing gap (see v3/@claude-flow/cli/__tests__/policy-runtime.test.ts's+ # long-standing scripts/ci-test-baseline.txt entry for the same+ # root cause) that a second, unrelated package now also needs+ # built for: dual-mode.test.ts/dual-mode-stdin-2947.test.ts import+ # @claude-flow/security for the first time in @claude-flow/codex.+ # (Complements, not duplicates, the codex package-lock.json fix+ # above it in history β that made npm ci link the package for+ # codex at all; this makes the linked package actually runnable.)+ run: npm run build --workspace=@claude-flow/security+- name: Run all tests# #3030: the historical suite has known debt, but new failing files# are release-blocking. The committed file-level baseline may onlydiff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.mdindex 8398e7539e..1291deea58 100644--- a/docs/dream-cycle/LEDGER.md+++ b/docs/dream-cycle/LEDGER.md@@ -165,10 +165,10 @@ as a first-class, high-priority candidate, not a background note.| 2026-08-22 | β | **no-run gap** β no branch/PR/issue exists for this date | β | β | no | β | β | β | no-run gap (external, not diagnosed) || 2026-08-23 | β | **no-run gap** β no branch/PR/issue exists for this date | β | β | no | β | β | β | no-run gap (external, not diagnosed) || 2026-08-24 | swarm | weightedConsensus() trust weights now reach raft/byzantine/gossip vote tally (was architecturally unreachable β no field existed to carry them); [0,1] clamp preserves BFT safety margin | #3085 | #3086 | yes | ACCEPT | gossip flip: flat approved=false β weighted approved=true (0.905 vs 0.50); 226/226 tests, 0 regressions; adversarial critic CONFIRMED-WITH-CAVEATS | 08d44c58... | MERGED 2026-09-14 |-| 2026-08-25 | performance | HNSW product-quantization: productQuantizeDistance() correctly implemented but zero callers β generic distance ran on raw PQ centroid indices, numerically meaningless; now dispatched, with a disclosed residual isValidPQEncoding() plausibility-heuristic caveat | #3093 | #3094 | yes | ACCEPT | recall@10 0.097 (pre-fix) β 0.270 (post-fix) on deterministic synthetic corpus, ~2.8x; 461/462 tests, 0 regressions | 300da158... | MERGED 2026-09-14 (verified via main's own commit 2d62270; the "awaiting final CI/merge" text this superseded was written just before merge) |-| 2026-08-26 | security | authorizeMcpTool() trusted unsigned caller identity (ASI07) β ADR-377 verifyInvocationToken bound into live chokepoint | #3102 | #3103 | yes | ACCEPT-with-caveats | see issue #3102 | fd944eae... | OPEN, not yet merged as of 2026-09-14 (verified via direct PR read: state=open, merged=false) |-| 2026-08-27 | intelligence | `distillLearning()`'s EWC forgetting-gate called `getPenalty([oldConf],[newConf])`, collapsing to 1 of 384 Fisher dims β wired in `computeConfidencePenalty`/`updateFisherFromConfidences` (already implemented, 0 prior callers). **Post-review correction (ruvnet):** original hypothesis overclaimed per-pattern discrimination; `computeConfidencePenalty` takes no embedding, so the real fix is "shared full-Fisher-average signal instead of one arbitrary dimension," not per-pattern weighting β hypothesis/gist/tests amended same night, new acceptance test added proving no per-pattern discrimination | #3109 | #3110 | yes | ACCEPT-scoped (narrowed post-review) | baseline: regression test fails (methods never called); candidate: passes. 153/153 tests (+5 new incl. acceptance test), tsc clean | 0df6bc4f... | OPEN, not yet merged as of 2026-09-14 (verified via direct PR read: state=open, merged=false β a prior edit to this row incorrectly said MERGED) |-| 2026-08-28 | memory | `HybridBackend.queryHybrid()`'s dead `weights` field (computed, never consumed by combineUnion) replaced with real weighted-RRF fusion (`combineWeighted`), matching Qdrant/Weaviate/Azure AI Search's weighted-RRF pattern | #3118 | #3119 | yes | ACCEPT | 461/462 suite green (1 pre-existing unrelated env failure, confirmed identical on baseline); weight-sensitivity test fails on baseline, passes on candidate (git-stash isolated); post-review: added finite/non-negative weight validation + deterministic id-based tie-break | 47e2f669... | MERGED 2026-09-14 (verified via main's own commit fde5b3b; superseded both "unmerged draft as of 09-05" and "still open ... INCONCLUSIVE" text written earlier the same day) |+| 2026-08-25 | performance | HNSW product-quantization: productQuantizeDistance() correctly implemented but zero callers β generic distance ran on raw PQ centroid indices, numerically meaningless; now dispatched, with a disclosed residual isValidPQEncoding() plausibility-heuristic caveat | #3093 | #3094 | yes | ACCEPT | recall@10 0.097 (pre-fix) β 0.270 (post-fix) on deterministic synthetic corpus, ~2.8x; 461/462 tests, 0 regressions | 300da158... | MERGED 2026-09-14 (verified via main's own commit 2d62270) |+| 2026-08-26 | security | authorizeMcpTool() trusted unsigned CLAUDE_FLOW_PRINCIPAL_ID env var as caller identity (ASI07-class); bound already-built ADR-377 Ed25519 verifyInvocationToken into that live chokepoint for DualModeOrchestrator-spawned workers, off by default | #3102 | #3103 | yes | ACCEPT-with-caveats | 6/6 new scenarios pass post-fix, correctly fail/reject pre-fix; 583/583 security, 241/241 codex, 18/18 policy-runtime; 19 pre-existing CLI failures proven identical via stash-diff | fd944eae... | OPEN as of 2026-09-14; rebased onto main (post #3086/#3094/#3110/#3119) and root package-lock.json fixed to add the missing `@claude-flow/security` dep edge codex's CI needs, awaiting fresh CI |+| 2026-08-27 | intelligence | `distillLearning()`'s EWC forgetting-gate called `getPenalty([oldConf],[newConf])`, collapsing to 1 of 384 Fisher dims β wired in `computeConfidencePenalty`/`updateFisherFromConfidences` (already implemented, 0 prior callers). **Post-review correction (ruvnet):** original hypothesis overclaimed per-pattern discrimination; `computeConfidencePenalty` takes no embedding, so the real fix is "shared full-Fisher-average signal instead of one arbitrary dimension," not per-pattern weighting β hypothesis/gist/tests amended same night, new acceptance test added proving no per-pattern discrimination | #3109 | #3110 | yes | ACCEPT-scoped (narrowed post-review) | baseline: regression test fails (methods never called); candidate: passes. 153/153 tests (+5 new incl. acceptance test), tsc clean | 0df6bc4f... | MERGED 2026-09-14 (verified: PR state=MERGED, mergedAt=2026-09-14T20:46:20Z) |+| 2026-08-28 | memory | `HybridBackend.queryHybrid()`'s dead `weights` field (computed, never consumed by combineUnion) replaced with real weighted-RRF fusion (`combineWeighted`), matching Qdrant/Weaviate/Azure AI Search's weighted-RRF pattern | #3118 | #3119 | yes | ACCEPT | 461/462 suite green (1 pre-existing unrelated env failure, confirmed identical on baseline); weight-sensitivity test fails on baseline, passes on candidate (git-stash isolated); post-review: added finite/non-negative weight validation + deterministic id-based tie-break | 47e2f669... | MERGED 2026-09-14 (verified via main's own commit fde5b3b) || 2026-08-29 | swarm | TopologyManager.rebalanceHybrid() one-directional adjacency bug fixed | #3122 | #3123 | yes | ACCEPT | see issue #3122 | n/a (backfill) | unmerged draft as of 09-05 || 2026-08-30 | performance | unwired diskann-backend.ts removed + stale 150x-12,500x HNSW claim in generated CLAUDE.md corrected | #3129 | #3130 | yes | ACCEPT | see issue #3129 | n/a (backfill) | unmerged draft as of 09-05 || 2026-08-31 | security | MCP governance policy (.harness/mcp-policy.json) was never enforced at runtime β opt-in enforcement wired in | #3138 | #3139 | yes | ACCEPT | see issue #3138 | n/a (backfill) | unmerged draft as of 09-05 |diff --git a/docs/dream-cycle/dream-gist-2026-08-26.md b/docs/dream-cycle/dream-gist-2026-08-26.mdnew file mode 100644index 0000000000..1788b34d3f--- /dev/null+++ b/docs/dream-cycle/dream-gist-2026-08-26.md@@ -0,0 +1,66 @@+# Security SOTA Report β 2026-08-26++TL;DR: `authorizeMcpTool()` β Ruflo's live, already-wired MCP tool-authorization chokepoint β has always trusted a plain, unsigned `CLAUDE_FLOW_PRINCIPAL_ID` env var as caller identity, with zero cryptographic proof. Tonight's candidate binds the already-built, already-tested-but-dead-code Ed25519 `verifyInvocationToken` (ADR-377 Phase 3, shipped 2026-07-30, never wired) into that real chokepoint, scoped to `DualModeOrchestrator`-spawned worker subprocesses β closing a live spoofing gap OWASP's 2026 Agentic Top 10 names as ASI07. Off by default. evaluated: **accepted, with disclosed caveats**.++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| OWASP Top 10 for Agentic Applications formalizes ASI07 "Insecure Inter-Agent Communication" (Dec 2025) | genai.owasp.org | A |+| MCP's 2026-07-28 spec revision still excludes stdio transport from its OAuth 2.1 authorization machinery entirely, deferring identity to "the environment" β the exact unsigned-env-var mechanism this candidate hardens | modelcontextprotocol.io | A |+| 40.55% of 7,973 scanned live remote MCP servers expose tools with zero authentication | arXiv:2605.22333 | A |+| LangChain (#35393) and CrewAI (#5561) both received well-specified Ed25519/DID caller-identity RFCs in FebβApr 2026 and closed both "not planned" | GitHub, direct fetch | A |+| CP-WBFT: confidence-probe-weighted BFT tallying, AAAI 2026 | arXiv:2511.10400 | A |+| AIP (Agent Identity Protocol): scanned ~2,000 live MCP servers, found all lacking auth; proposes Invocation-Bound Capability Tokens | arXiv:2603.24775 | B |++## Ruflo Current Capability++`v3/@claude-flow/security/src/mcp-caller-identity.ts` (ADR-377 Phase 3, PR #2874, merged 2026-07-30) implements Ed25519 `issueInvocationToken`/`verifyInvocationToken`, fully tested β but grep across all of `v3/` confirmed **zero production call sites**. Last night (2026-08-25) flagged wiring it into `AgentAuthorizationPropagator.checkToolCall` β but tonight's deep research corrected that: `checkToolCall` also has zero production callers. The **actual live enforcement chokepoint**, used by both stdio and HTTP transports, is `authorizeMcpTool()` in `v3/@claude-flow/cli/src/services/policy-runtime.ts`, whose `identity.id` (line 350, pre-patch) was `process.env.CLAUDE_FLOW_PRINCIPAL_ID ?? 'legacy-cli'` β a bare string, verified nowhere downstream in `AgenticPolicyEngine.evaluate()`. `DualModeOrchestrator` (`v3/@claude-flow/codex/src/dual-mode/orchestrator.ts:600`) sets this value for every spawned worker subprocess β a process running arbitrary LLM-driven tool calls, exactly the kind of process a prompt injection could compromise.++## Competitor Comparison++| System | Verifies caller/agent identity for tool calls? | Mechanism | Grade |+|---|---|---|---|+| LangGraph | No (RFC #35393 closed not-planned) | Platform user-auth only, not agent-identity | A |+| AutoGen/AG2 | No (community RFC open, unmerged) | None; `AgentId` is routing-only | A |+| CrewAI | No (RFC #5561 closed not-planned) | ClientβMCP-server auth only | A |+| OpenAI Agents SDK | No | Tool allowlists (least-privilege scoping β identity) | B |+| MCP spec itself (2026-07-28) | No, by design for stdio | Defers to "environment" for stdio; OAuth 2.1 only for HTTP | A |++Why universal "No": not a solved-but-unpublished problem β the MCP spec inherits OAuth 2.1's human-delegation model and explicitly carves stdio out of its scope, so every framework built on top inherited that same non-goal. Two independent teams (LangChain, CrewAI) got matching RFCs and declined them without published rationale β a genuine, still-open field gap.++## Hypothesis++> Given `authorizeMcpTool`'s unsigned-env-var identity, when `isMcpCallerAuthEnabled()` is true and `DualModeOrchestrator` mints a per-worker Ed25519 `InvocationToken` (worker-lifetime TTL = `config.timeout`, wildcard `toolName: '*'` β a disclosed scope reduction from the primitive's original per-call design) that `authorizeMcpTool` verifies before trusting identity, then a process without a validly-signed token should be rejected (fail-closed) while a legitimate token's `callerId` is used even when it disagrees with the raw env var β subject to: (1) disabled behavior is byte-identical; (2) existing suites stay green; (3) $0 cost.++## Evaluation++Real evaluator: Vitest, zero LLM calls. 6 new deterministic scenarios (baseline-disabled-spoofing-succeeds; enabled+no-tokenβreject; enabled+forged-signatureβreject; enabled+expiredβreject; enabled+legitimate-tokenβaccept using verified `callerId`; orchestrator env-var gating + token round-trip) β all pass post-fix, all correctly fail/error pre-fix (`git stash` isolation). `@claude-flow/security` 583/583, `@claude-flow/codex` 241/241, `policy-runtime.test.ts` 18/18 (13 pre-existing + 5 new). CLI full suite: 19 pre-existing WASM/Docker-dependent failures proven **identical** with and without the diff via stash-and-diff comparison of failing-test-name lists (empty diff). `tsc --noEmit` clean for touched packages.++An independent adversarial critic (fresh session) re-ran every suite itself, independently verified the Ed25519 SPKI DER prefix against real `node:crypto` output, probed cross-worker token confusion (rejected), NUL-byte field-injection into `callerId` (rejected β signing never parses a flat delimited string), and traced every fail-closed branch line-by-line. **Verdict: CONFIRMED-SAFE-WITH-CAVEATS** β disclosed, not hidden: (1) the worker-lifetime/wildcard-tool token is a capability credential, not a per-call proof β a leaked token remains valid for that worker's lifetime; (2) two other call sites (`harness-flywheel-runtime.ts:101`, `metaharness.ts:146,173`) still trust the bare env var, real residual scope for a future phase; (3) a pre-existing, unrelated quirk β 4 literal NUL bytes used as field separators in `signingPayload()`, present at HEAD β was probed for exploitability (none found, since verification always uses structured JSON fields, never a split flat string) and correctly left unfixed (out of frozen scope).++## Darwin Results++Skipped β scope mismatch, confirmed via `npx ruvector harness darwin --help`: real interface evolves continuous/categorical genome parameters (routing weights, topology, prompt/memory/tool/tier/context/coordination) against an LLM-scored bench corpus via `darwin <config> --execute`. A binary crypto-verification gate has no such tunable parameter space. Same class of skip as 5 of the last 6 dream-cycle nights.++## SOTA Proof & Witness++Control-plane discovery (`npx ruvector harness status --json`) confirms 14/15 pinned MetaHarness primitives available (witness-chain, flywheel, darwin, router, redblue, weight-eft all loaded; only `@ruvector/router` semantic-router unavailable, has a defensive JS fallback). No signed `@metaharness/flywheel` bundle produced β deterministic Vitest evidence, not an LLM-task corpus the replay/verify tooling targets, same as every accepted night since 08-18. See Witness table below for cryptographic provenance of this report.++## Recommended Next Steps++1. **Merge this candidate** (human review required) β closes a real, OWASP-ASI07-named, field-wide-unsolved gap in a live enforcement path, with independent adversarial confirmation.+2. **Follow-up**: wire `resolveMcpCallerIdentity`'s pattern into the two other still-trusting call sites (`harness-flywheel-runtime.ts:101`, `metaharness.ts:146,173`) β same primitive, mechanical extension.+3. **Follow-up**: `TopologyManager.rebalanceHybrid()`'s one-directional adjacency bug (topology-manager.ts:536-539) β confirmed still open tonight by the swarm scan, ~4-6 line fix, cheapest still-open swarm lead.+4. **Follow-up**: wire `ConsensusVote.confidence` into `byzantine.ts`'s tally β CP-WBFT (AAAI 2026, Grade A) is now a peer-reviewed reference pattern for exactly this, found by tonight's swarm scan.+5. Separately worth a maintainer's attention (not a candidate): the pre-existing NUL-byte quirk in `signingPayload()` and two stale ADR status/CVE-registry doc entries (ADR-377 README still says "Proposed" despite merged code; `CVE-REMEDIATION.ts`'s `ADR165-OPEN-01` entry is stale-fixed) β cosmetic, flagged for cleanup.++## Witness++| Field | Value |+|---|---|+| Session commit | `e21aa352fdc80fd2d3cc4e83404a76a18d118b96` |+| Report SHA-256 (pre-witness content) | `a590238de9502914cdcca27a2ceb9426b2cda590c0c4fd4be84cc03f5deefb52` |+| Witness stamp | `fd944eaaea6d669f9c62355bd95c339f97313faa4b999510b454002e85714ee2` |++Verifier: fetch `docs/dream-cycle/dream-gist-2026-08-26.md` at the commit that introduced it, strip the witness table's filled values back to placeholders (`a590238de9502914cdcca27a2ceb9426b2cda590c0c4fd4be84cc03f5deefb52`, `fd944eaaea6d669f9c62355bd95c339f97313faa4b999510b454002e85714ee2`), `sha256sum`, concatenate with the session commit, `sha256sum` again β must equal the witness stamp.diff --git a/package-lock.json b/package-lock.jsonindex 442e732343..363f61b164 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "claude-flow",- "version": "3.40.0",+ "version": "3.41.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "claude-flow",- "version": "3.40.0",+ "version": "3.41.2","bundleDependencies": ["@claude-flow/codex","@claude-flow/mcp",@@ -12953,6 +12953,7 @@"version": "3.0.3","license": "MIT","dependencies": {+ "@claude-flow/security": "3.0.0-alpha.14","@iarna/toml": "^2.2.5","chalk": "^5.3.0","commander": "^12.0.0",diff --git a/scripts/audit-env-var-precedence.mjs b/scripts/audit-env-var-precedence.mjsindex 67f50b2a53..de385569c3 100644--- a/scripts/audit-env-var-precedence.mjs+++ b/scripts/audit-env-var-precedence.mjs@@ -172,6 +172,16 @@ const KNOWN_ESCAPE_HATCHES = new Set([// this label as issuer proof.'CLAUDE_FLOW_PRINCIPAL_ID',+ // ββ ADR-377 Phase 3: per-worker Ed25519 caller-identity credential βββββββββ+ // DualModeOrchestrator mints these into a spawned worker's OWN environment+ // (workerEnvironment()) β a credential pair for authorizeMcpTool's+ // resolveMcpCallerIdentity() to verify, not a value any caller should be+ // able to select via a CLI flag (that would let a process simply assert a+ // signature instead of proving one). Same no-CLI-surface reasoning as+ // CLAUDE_FLOW_PRINCIPAL_ID above.+ 'CLAUDE_FLOW_MCP_CALLER_PUBKEY',+ 'CLAUDE_FLOW_MCP_INVOCATION_TOKEN',+// ββ OS / runtime standard env ββββββββββββββββββββββββββββββββββββββββββββββββ'HOME','USERPROFILE',diff --git a/scripts/ci-test-baseline.txt b/scripts/ci-test-baseline.txtindex 53ad170b45..1db6eed536 100644--- a/scripts/ci-test-baseline.txt+++ b/scripts/ci-test-baseline.txt@@ -75,7 +75,6 @@ v3/@claude-flow/cli/__tests__/neural-router.test.tsv3/@claude-flow/cli/__tests__/output.test.tsv3/@claude-flow/cli/__tests__/planflip-mempoison-2752.test.tsv3/@claude-flow/cli/__tests__/plugins-transfer-deep.test.ts-v3/@claude-flow/cli/__tests__/policy-runtime.test.tsv3/@claude-flow/cli/__tests__/pq-validation.test.tsv3/@claude-flow/cli/__tests__/proxy-extract-archive.test.tsv3/@claude-flow/cli/__tests__/security-scan-enum-validation.test.tsdiff --git a/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts b/v3/@claude-flow/cli/__tests__/policy-runtime.test.tsindex d9be09da8c..c844861d39 100644--- a/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts+++ b/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts@@ -5,6 +5,7 @@ import { tmpdir, userInfo } from 'node:os';import { createHash, createHmac } from 'node:crypto';import { execFileSync } from 'node:child_process';import {+ authorizeMcpTool,autoMigratePolicyStateIfNeeded,classifyMcpTool,evaluatePolicyRequest,@@ -16,6 +17,11 @@ import {verifyPolicyLedger,} from '../src/services/policy-runtime.js';import { callMCPTool } from '../src/mcp-client.js';+import {+ encodeTokenEnvelope,+ generateCallerIdentityKey,+ issueInvocationToken,+} from '@claude-flow/security';const roots: Array<{ root: string; trust: string }> = [];function project(): string {@@ -40,6 +46,10 @@ afterEach(() => {}delete process.env.CLAUDE_FLOW_POLICY_APPROVERS;delete process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE;+ delete process.env.CLAUDE_FLOW_MCP_CALLER_AUTH;+ delete process.env.CLAUDE_FLOW_PRINCIPAL_ID;+ delete process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN;+ delete process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY;});describe('policy runtime compatibility and transactions', () => {@@ -294,3 +304,77 @@ describe('policy runtime compatibility and transactions', () => {expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 10 });});});++// ADR-377 Phase 3 (dream-cycle candidate, 2026-08-26) β MCP caller-identity+// binding for `authorizeMcpTool`. `CLAUDE_FLOW_MCP_CALLER_AUTH` is off by+// default; scenario 1 below is the "attack succeeds" baseline that exists+// today (and continues to exist when the flag stays off, by design β see+// resolveMcpCallerIdentity's docstring in policy-runtime.ts). Scenarios 2-5+// are the candidate behavior once the flag is enabled.+describe('authorizeMcpTool: caller identity spoofing (ADR-377 Phase 3)', () => {+ it('[baseline] caller-auth disabled: an unverified CLAUDE_FLOW_PRINCIPAL_ID is trusted outright', async () => {+ const root = project();+ process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';+ // CLAUDE_FLOW_MCP_CALLER_AUTH intentionally left unset.+ await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root })).resolves.toBeDefined();+ const receipts = loadPolicyState(root).receipts;+ expect(receipts.at(-1)?.payload.request.identity).toEqual({ id: 'agent:victim-worker', type: 'agent' });+ });++ it('[candidate] caller-auth enabled, no token presented: fails closed', async () => {+ const root = project();+ process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';+ process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';+ // No CLAUDE_FLOW_MCP_INVOCATION_TOKEN / CLAUDE_FLOW_MCP_CALLER_PUBKEY set.+ await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root }))+ .rejects.toThrow('mcp-caller-auth-enabled-but-no-token');+ });++ it('[candidate] caller-auth enabled, forged token (wrong signing key): rejected as bad-signature', async () => {+ const root = project();+ process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';+ process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';++ const realKey = generateCallerIdentityKey();+ const attackerKey = generateCallerIdentityKey();+ // Token signed by attackerKey, but presented alongside realKey's public key+ // β the signature will not verify against the presented key.+ const token = issueInvocationToken('agent:worker-7', '*', attackerKey);+ process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN = encodeTokenEnvelope(token);+ process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY = realKey.publicKeyHex;++ await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root }))+ .rejects.toThrow('mcp-caller-auth-verification-failed:bad-signature');+ });++ it('[candidate] caller-auth enabled, expired token: rejected as expired', async () => {+ const root = project();+ process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';+ process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';++ const key = generateCallerIdentityKey();+ const token = issueInvocationToken('agent:worker-7', '*', key, { ttlMs: -1 });+ process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN = encodeTokenEnvelope(token);+ process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY = key.publicKeyHex;++ await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root }))+ .rejects.toThrow('mcp-caller-auth-verification-failed:expired');+ });++ it('[candidate] caller-auth enabled, legitimate token: succeeds and the verified token wins over a disagreeing env var', async () => {+ const root = project();+ process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';+ // Deliberately disagrees with the token's callerId, to prove the token+ // β not the env var β decides the identity that reaches the policy engine.+ process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';++ const key = generateCallerIdentityKey();+ const token = issueInvocationToken('agent:worker-7', '*', key, { ttlMs: 300_000 });+ process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN = encodeTokenEnvelope(token);+ process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY = key.publicKeyHex;++ await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root })).resolves.toBeDefined();+ const receipts = loadPolicyState(root).receipts;+ expect(receipts.at(-1)?.payload.request.identity).toEqual({ id: 'agent:worker-7', type: 'agent' });+ });+});diff --git a/v3/@claude-flow/cli/src/services/policy-runtime.ts b/v3/@claude-flow/cli/src/services/policy-runtime.tsindex 449316ffc7..d68014d4a1 100644--- a/v3/@claude-flow/cli/src/services/policy-runtime.ts+++ b/v3/@claude-flow/cli/src/services/policy-runtime.ts@@ -1,6 +1,10 @@import {AgenticPolicyEngine,createLegacyCompatibleState,+ isMcpCallerAuthEnabled,+ decodeTokenEnvelope,+ publicKeyFromHex,+ verifyInvocationToken,type BudgetLimit,type CapabilityEnvelope,type PolicyApproval,@@ -303,6 +307,72 @@ export async function verifyPolicyLedger(projectRoot = process.cwd()): Promise<Rreturn withPolicyTransaction(projectRoot, (engine) => engine.verifyLedger());}+/**+ * Resolve the caller identity for `authorizeMcpTool`.+ *+ * ADR-377 Phase 3 (dream-cycle candidate, 2026-08-26) β off by default. By+ * default (`isMcpCallerAuthEnabled()` false), this reproduces the exact+ * pre-existing two-line behavior: the plain, unsigned `CLAUDE_FLOW_PRINCIPAL_ID`+ * env var is trusted outright. That is the byte-identical-when-disabled+ * requirement for this candidate β nothing about this branch's shape or+ * output changes when the flag is off.+ *+ * When the flag is on, `CLAUDE_FLOW_PRINCIPAL_ID` alone is no longer+ * sufficient β any process can set an arbitrary env var with zero proof.+ * Instead this requires (and verifies) an Ed25519-signed `InvocationToken`+ * that only a private-key holder (the DualModeOrchestrator that spawned this+ * worker) could have minted, per `mcp-caller-identity.ts`. Missing, corrupt,+ * forged, or expired tokens fail closed β this function throws rather than+ * falling back to the unverified env var, matching the existing fail-closed+ * pattern already used above in this function (`invalid-worker-capability-envelope`,+ * `authoritative-worker-policy-root-unavailable`).+ *+ * Scope trade-off (deliberate β see mcp-caller-identity.ts's file header and+ * orchestrator.ts's `workerEnvironment` for the fuller rationale): the token+ * is minted once per worker spawn with a worker-lifetime TTL and a wildcard+ * `toolName: '*'`, not the single-tool, 30s-TTL shape `InvocationToken` was+ * originally designed for β so `opts.toolName` is deliberately not passed to+ * `verifyInvocationToken` here, and the tool-mismatch check is not exercised+ * for this use case. What this retains: a process that never received the+ * signed token cannot forge one, so it cannot impersonate `agent:<workerId>`.+ * What it does NOT retain: a compromised worker process can still use its+ * own valid token for every MCP call for the rest of its lifetime β the+ * token does not limit blast radius to a single call.+ */+function resolveMcpCallerIdentity(): { id: string; type: 'agent' | 'legacy' } {+ if (!isMcpCallerAuthEnabled()) {+ return {+ id: process.env.CLAUDE_FLOW_PRINCIPAL_ID ?? 'legacy-cli',+ type: process.env.CLAUDE_FLOW_PRINCIPAL_ID ? 'agent' : 'legacy',+ };+ }++ const encodedToken = process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN;+ const publicKeyHex = process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY;+ if (!encodedToken || !publicKeyHex) {+ throw new Error('mcp-caller-auth-enabled-but-no-token');+ }++ const token = decodeTokenEnvelope(encodedToken);+ if (!token) {+ throw new Error('mcp-caller-auth-enabled-but-no-token');+ }++ let publicKey;+ try {+ publicKey = publicKeyFromHex(publicKeyHex);+ } catch {+ throw new Error('mcp-caller-auth-enabled-but-no-token');+ }++ const result = verifyInvocationToken(token, publicKey, {});+ if (!result.valid) {+ throw new Error(`mcp-caller-auth-verification-failed:${result.reason}`);+ }++ return { id: token.callerId, type: 'agent' };+}+export async function authorizeMcpTool(toolName: string,input: Record<string, unknown>,@@ -346,10 +416,7 @@ export async function authorizeMcpTool(}}return evaluatePolicyRequest({- identity: {- id: process.env.CLAUDE_FLOW_PRINCIPAL_ID ?? 'legacy-cli',- type: process.env.CLAUDE_FLOW_PRINCIPAL_ID ? 'agent' : 'legacy',- },+ identity: resolveMcpCallerIdentity(),action: {type: attributes.actionType ?? 'mcp.tool.call',resource: toolName,diff --git a/v3/@claude-flow/codex/package.json b/v3/@claude-flow/codex/package.jsonindex f99497d359..01da730096 100644--- a/v3/@claude-flow/codex/package.json+++ b/v3/@claude-flow/codex/package.json@@ -101,7 +101,8 @@"inquirer": "^9.2.0","yaml": "^2.4.0","toml": "^3.0.0",- "@iarna/toml": "^2.2.5"+ "@iarna/toml": "^2.2.5",+ "@claude-flow/security": "3.0.0-alpha.14"},"devDependencies": {"@types/fs-extra": "^11.0.4",diff --git a/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts b/v3/@claude-flow/codex/src/dual-mode/orchestrator.tsindex 95efeb59aa..798e3ea265 100644--- a/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts+++ b/v3/@claude-flow/codex/src/dual-mode/orchestrator.ts@@ -8,6 +8,13 @@ import { EventEmitter } from 'events';import * as path from 'path';import * as fs from 'fs';import * as TOML from '@iarna/toml';+import {+ generateCallerIdentityKey,+ issueInvocationToken,+ isMcpCallerAuthEnabled,+ encodeTokenEnvelope,+ type CallerIdentityKey,+} from '@claude-flow/security';export interface WorkerCapabilityEnvelope {actions?: string[];@@ -78,6 +85,10 @@ export class DualModeOrchestrator extends EventEmitter {private config: Required<DualModeConfig>;private workers: Map<string, WorkerResult> = new Map();private processes: Map<string, ChildProcess> = new Map();+ /** Lazily generated, cached for the life of this orchestrator instance β one+ * keypair signs every worker's token, never regenerated per spawn. Only+ * touched when `isMcpCallerAuthEnabled()` is true. */+ private callerIdentityKey?: CallerIdentityKey;constructor(config: DualModeConfig) {super();@@ -592,7 +603,9 @@ Remember: Other agents depend on your results in shared memory. Be concise and sfor (const [name, value] of Object.entries(process.env)) {if (sensitive.test(name)|| name.startsWith('CLAUDE_FLOW_POLICY_')- || name === 'CLAUDE_FLOW_PRINCIPAL_ID') continue;+ || name === 'CLAUDE_FLOW_PRINCIPAL_ID'+ || name === 'CLAUDE_FLOW_MCP_INVOCATION_TOKEN'+ || name === 'CLAUDE_FLOW_MCP_CALLER_PUBKEY') continue;env[name] = value;}env.FORCE_COLOR = '0';@@ -601,6 +614,41 @@ Remember: Other agents depend on your results in shared memory. Be concise and senv.CLAUDE_FLOW_CAPABILITY_ENVELOPE = JSON.stringify(this.resolveWorkerEnvelope(worker),);+ // ADR-377 Phase 3 (dream-cycle candidate, 2026-08-26) β off by default.+ // When caller-auth is enabled, back the freshly-set CLAUDE_FLOW_PRINCIPAL_ID+ // above with an Ed25519-signed InvocationToken only this orchestrator (the+ // private-key holder) could have minted, so policy-runtime can verify the+ // worker's identity instead of trusting the plain env var. Set *after* the+ // strip loop, same pattern as CLAUDE_FLOW_PRINCIPAL_ID itself, so it is+ // never accidentally stripped by the sensitive-name filter above.+ //+ // Scope trade-off (deliberate, see mcp-caller-identity.ts's file header+ // and this file's docstring for the fuller rationale): InvocationToken+ // was designed short-lived (30s) and single-tool-bound. A worker process+ // has no live channel back to the orchestrator to re-request a token+ // before every MCP call, so instead we mint ONE token per worker spawn,+ // TTL'd to the orchestrator's own per-worker timeout (the same value+ // already used for the capability envelope's expiresAt, above), and+ // toolName '*' β a wildcard sentinel meaning "not bound to one tool"+ // (verified below without an `opts.toolName`, so the tool-mismatch check+ // is simply not exercised for this use case). Net effect: the token+ // behaves as a worker-lifetime capability credential, not a strict+ // per-call one. What IS retained: a process that never received this+ // signed token cannot forge one, so it cannot impersonate+ // `agent:<workerId>`. What is NOT retained: if a worker process is+ // itself compromised mid-run, the token does not limit blast radius to+ // one call β it remains valid for the rest of the worker's lifetime.+ if (isMcpCallerAuthEnabled()) {+ this.callerIdentityKey ??= generateCallerIdentityKey();+ const token = issueInvocationToken(+ `agent:${worker.id}`,+ '*',+ this.callerIdentityKey,+ { ttlMs: this.config.timeout },+ );+ env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN = encodeTokenEnvelope(token);+ env.CLAUDE_FLOW_MCP_CALLER_PUBKEY = this.callerIdentityKey.publicKeyHex;+ }return env;}diff --git a/v3/@claude-flow/codex/tests/dual-mode.test.ts b/v3/@claude-flow/codex/tests/dual-mode.test.tsindex 5b7992e31b..0d4bb2742b 100644--- a/v3/@claude-flow/codex/tests/dual-mode.test.ts+++ b/v3/@claude-flow/codex/tests/dual-mode.test.ts@@ -20,6 +20,11 @@ import {loadSwarmAutomationConfig,} from '../src/dual-mode/index.js';import type { WorkerConfig } from '../src/dual-mode/index.js';+import {+ decodeTokenEnvelope,+ publicKeyFromHex,+ verifyInvocationToken,+} from '@claude-flow/security';describe('parseWorkerSpecs', () => {it('parses a single spec into a WorkerConfig', () => {@@ -263,6 +268,63 @@ describe('DualModeOrchestrator', () => {}});+ // ADR-377 Phase 3 (dream-cycle candidate, 2026-08-26) β worker-lifetime+ // InvocationToken issuance, off by default. See workerEnvironment's inline+ // comment for the deliberate single-tool-binding trade-off (toolName '*').+ it('does not set MCP invocation-token env vars when caller-auth is disabled (default)', () => {+ delete process.env.CLAUDE_FLOW_MCP_CALLER_AUTH;+ const environment = (orch() as unknown as {+ workerEnvironment(worker: WorkerConfig): NodeJS.ProcessEnv;+ }).workerEnvironment({+ id: 'plain-worker',+ platform: 'codex',+ role: 'reviewer',+ prompt: 'review',+ readOnly: true,+ });+ expect(environment.CLAUDE_FLOW_MCP_INVOCATION_TOKEN).toBeUndefined();+ expect(environment.CLAUDE_FLOW_MCP_CALLER_PUBKEY).toBeUndefined();+ expect(environment.CLAUDE_FLOW_PRINCIPAL_ID).toBe('agent:plain-worker');+ });++ it('mints a worker-lifetime InvocationToken when caller-auth is enabled, and it round-trips through verifyInvocationToken', () => {+ process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';+ try {+ const orchestrator = new DualModeOrchestrator({ projectPath: '/tmp', timeout: 45_000 }) as unknown as {+ workerEnvironment(worker: WorkerConfig): NodeJS.ProcessEnv;+ };+ const worker: WorkerConfig = {+ id: 'signed-worker',+ platform: 'codex',+ role: 'coder',+ prompt: 'implement',+ };+ const environment = orchestrator.workerEnvironment(worker);+ const encodedToken = environment.CLAUDE_FLOW_MCP_INVOCATION_TOKEN;+ const publicKeyHex = environment.CLAUDE_FLOW_MCP_CALLER_PUBKEY;+ expect(encodedToken).toBeDefined();+ expect(publicKeyHex).toBeDefined();++ const token = decodeTokenEnvelope(encodedToken!);+ expect(token).toBeDefined();+ expect(token!.callerId).toBe('agent:signed-worker');+ // Wildcard sentinel β deliberately not tool-bound (see file header).+ expect(token!.toolName).toBe('*');+ // TTL reuses the orchestrator's own per-worker timeout, not a new default.+ expect(token!.expiresAt - token!.issuedAt).toBe(45_000);++ const publicKey = publicKeyFromHex(publicKeyHex!);+ expect(verifyInvocationToken(token!, publicKey, {})).toEqual({ valid: true });++ // A second worker spawned from the same orchestrator reuses the cached+ // keypair (both tokens verify against the same emitted public key).+ const secondEnvironment = orchestrator.workerEnvironment({ ...worker, id: 'signed-worker-2' });+ expect(secondEnvironment.CLAUDE_FLOW_MCP_CALLER_PUBKEY).toBe(publicKeyHex);+ } finally {+ delete process.env.CLAUDE_FLOW_MCP_CALLER_AUTH;+ }+ });+it('enforces worker capability envelopes as reductions', () => {const orchestrator = orch() as unknown as {resolveWorkerEnvelope(worker: WorkerConfig): Record<string, unknown>;diff --git a/v3/@claude-flow/security/src/index.ts b/v3/@claude-flow/security/src/index.tsindex b44b10aa47..8ef2d2d3b8 100644--- a/v3/@claude-flow/security/src/index.ts+++ b/v3/@claude-flow/security/src/index.ts@@ -144,6 +144,9 @@ export {issueInvocationToken,verifyInvocationToken,isMcpCallerAuthEnabled,+ publicKeyFromHex,+ encodeTokenEnvelope,+ decodeTokenEnvelope,type CallerIdentityKey,type InvocationToken,type TokenVerificationResult,diff --git a/v3/@claude-flow/security/src/mcp-caller-identity.ts b/v3/@claude-flow/security/src/mcp-caller-identity.tsindex 6cbfae272f..918220394c 100644Binary files a/v3/@claude-flow/security/src/mcp-caller-identity.ts and b/v3/@claude-flow/security/src/mcp-caller-identity.ts differdiff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex 877384ac4b..8c1d63091c 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -256,6 +256,9 @@ importers:'@claude-flow/cli':specifier: ^3.0.0version: link:../cli+ '@claude-flow/security':+ specifier: 3.0.0-alpha.14+ version: link:../security'@iarna/toml':specifier: ^2.2.5version: 2.2.5