π 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
docs(adr): three Proposed security ADRs (144, 145, 146) covering the dream-cycle cluster
ruv08bf1cf3242b
diff --git a/v3/docs/adr/ADR-144-agent-authorization-propagation.md b/v3/docs/adr/ADR-144-agent-authorization-propagation.mdnew file mode 100644index 0000000000..1111e41492--- /dev/null+++ b/v3/docs/adr/ADR-144-agent-authorization-propagation.md@@ -0,0 +1,135 @@+# ADR-144 β Agent Authorization Propagation and MCP Authentication Enforcement++**Status**: Proposed+**Date**: 2026-06-02+**Issue**: [ruvnet/ruflo#2248](https://github.com/ruvnet/ruflo/issues/2248)+**Related**: ADR-012 (MCP Security Features), ADR-013 (Core Security Module), ADR-131 (ToolOutputGuardrail β content layer), ADR-145 (Plugin supply-chain β install layer)++## Context++ADR-131 closed the *content* layer of OWASP ASI01: tool outputs and memory reads are now screened for embedded instructions before they enter agent reasoning. Three Grade A papers published May 2026 identify a separate, currently-unmitigated layer: **authorization propagation** across agent delegation chains.++The distinction matters:++| Layer | ADR | Question it answers |+|---|---|---|+| Content boundary | ADR-131 | "Does this text contain instructions trying to hijack the model?" |+| Action boundary | **this ADR** | "Is the agent acting now allowed to call this tool, on this server, on behalf of this principal?" |+| Install boundary | ADR-145 | "Is the code that's about to run trustworthy at all?" |++### Evidence++1. **MCP Authentication Measurement** (arXiv:2605.22333, May 2026, Grade A β empirical): First survey of 7,973 live MCP servers. **40.55% expose tools with zero authentication; 96.6% of OAuth-enabled servers contain β₯1 exploitable flaw** (most common: improper scope validation). Ruflo registers MCP tools but performs no runtime authentication check on server identity before accepting tool responses, so any agent that calls a federated MCP tool today has a >40% chance of trusting an unauthenticated source.++2. **AIRGuard** (arXiv:2605.28914, May 2026, Grade A β controlled benchmark): Runtime authority control at the action execution layer reduces agent attack success **from 36.3% to 5.5% (β85%)**. The load-bearing primitive is least-privilege authorization checked **per action**, not per session.++3. **Authorization Propagation** (arXiv:2605.05440, Apr 2026, Grade A β formal analysis): Multi-agent delegation creates an authorization-propagation problem with seven structural requirements not solvable by RBAC, ABAC, or ReBAC alone. When agent A delegates to agent B via SendMessage, B can escalate the granted scope by calling tools A was never authorized to invoke. Scope must travel **with** the delegation message and be enforced at every hop.++4. **Dual-Graph Provenance Defense** (arXiv:2605.26497, May 2026, Grade A): Comparing an *execution* provenance graph against an *authorization-intent* graph reduces indirect prompt injection success **from 40% to 1%**. Provenance is the audit trail required for any post-incident investigation.++### Current State++`@claude-flow/security` provides `InputValidator`, `PathValidator`, `SafeExecutor`, `PasswordHasher`, `TokenGenerator`. None of these track authorization scope across agent delegation boundaries, verify MCP server identity, enforce per-action privilege, or produce an execution provenance record. `SendMessage` (the comms primitive between named agents) carries no authorization metadata at all.++## Decision++Add `AgentAuthorizationPropagator` as a new component in `@claude-flow/security`, paired with an MCP-server auth validator in the CLI's MCP layer.++### `AgentAuthorizationPropagator` shape++**File**: `v3/@claude-flow/security/src/authorization/propagator.ts`++```typescript+interface AuthScope {+ principalId: string; // originating agent identity+ grantedTools: string[]; // MCP tool IDs this scope allows+ grantedServers: string[]; // MCP servers whose responses are accepted+ delegationDepth: number; // max remaining delegation hops+ expiresAt: number; // unix ms+}++interface SendMessageEnvelope<T = unknown> {+ scope: AuthScope; // NEW β attached to every SendMessage+ payload: T;+}++class AgentAuthorizationPropagator {+ // Attach a reduced scope to an outbound SendMessage.+ // Newly granted tools MUST be a subset of currentScope.grantedTools;+ // delegationDepth MUST decrement by β₯ 1.+ wrapOutbound<T>(payload: T, currentScope: AuthScope, requestedTools: string[]): SendMessageEnvelope<T>;++ // Validate an inbound tool call against the current delegation scope.+ // Returns the policy decision; never throws.+ checkToolCall(toolId: string, scope: AuthScope): { allowed: boolean; reason?: string };++ // Verify an MCP server presented valid auth before its response is consumed.+ verifyServerAuth(serverId: string, credential: unknown): boolean;++ // Record action in provenance log for the dual-graph audit (ADR-144 P2).+ recordAction(agentId: string, toolId: string, scope: AuthScope, outcome: 'allowed' | 'denied'): void;+}+```++Scope is **monotonically reducing**: each delegation hop can drop tools/servers but never add them. Adding requires the requesting agent to talk to the original principal out-of-band β the same shape as OAuth scope reduction.++### MCP Authentication Validator++**File**: `v3/@claude-flow/cli/src/mcp/auth-validator.ts`++Before any tool response from an MCP server enters agent reasoning:++1. The server MUST be in the registered allowlist *or* in `unauthenticated-allowed.json` (an explicit, audit-logged opt-out for known-public servers like a local read-only documentation server).+2. If the server declared OAuth support in its tool registration, the validator verifies token freshness and scope.+3. Otherwise, the response is rejected with `UNAUTHENTICATED_MCP_SERVER` and the rejection is surfaced to the agent β never silently dropped (same rule as ADR-131 reject findings).++### Integration plan (phased β P1 is the first PR)++| Phase | Scope | Where |+|---|---|---|+| **P1** | Component + tests + exports; SendMessage envelope schema | `@claude-flow/security/src/authorization/`, `@claude-flow/cli/src/types/` |+| P2 | Outbound: wrap every SendMessage in the comms layer | `@claude-flow/cli/src/agent/comms.ts` |+| P3 | Inbound: validate scope at the MCP tool dispatcher | `@claude-flow/cli/src/mcp-tools/dispatch.ts` |+| P4 | MCP auth validator wired before tool result processing | `@claude-flow/cli/src/mcp/auth-validator.ts` |+| P5 | Provenance log + dual-graph audit CLI | `@claude-flow/cli/src/commands/audit.ts` |++P2βP5 ship behind `CLAUDE_FLOW_STRICT_AUTH=true` so existing pipelines continue to work in legacy permissive mode until v4.0.++### Backwards compatibility++- The `scope` field on the envelope is **optional** in v1. Agents that don't set scope operate in legacy mode (all tools allowed, depth unlimited, server auth unchecked).+- `CLAUDE_FLOW_STRICT_AUTH=true` enables enforcement. This env var is a documented escape hatch (registered in `audit-env-var-precedence.mjs`).+- Existing `SafeExecutor` is unchanged.++## Alternatives considered++**Extend ADR-131 ToolOutputGuardrail.** Different layer. ADR-131 screens content before it enters reasoning; this ADR controls *who* is authorized to take actions. They must coexist β neither subsumes the other.++**RBAC on agent roles.** The formal analysis (arXiv:2605.05440) demonstrates RBAC cannot maintain authorization invariants across dynamic LLM delegation chains: roles don't compose under delegation. Scope-based propagation is the minimum viable solution.++**OAuth scope on every cross-agent call.** Closer to the right shape, but requires per-tool OAuth servers β operationally heavy and only solves the MCP-server identity half. Scope-envelope on SendMessage covers both agent-to-agent and agent-to-MCP-server in one mechanism.++## Consequences++**Positive**:+- Closes the 40.55% unauthenticated-MCP-server exposure surfaced by arXiv:2605.22333.+- Targets the AIRGuard 85%-reduction benchmark for action-layer attacks.+- Produces a provenance log that enables post-incident audit (maps to OWASP ASI07).+- Pairs cleanly with ADR-131: content boundary + action boundary together cover both layers of ASI01.++**Negative / risks**:+- The `scope` envelope adds ~100 bytes to every SendMessage (negligible vs payload).+- Strict mode breaks existing pipelines that rely on implicit cross-agent tool access β every agent spawn site must declare its scope explicitly.+- A misconfigured `unauthenticated-allowed.json` becomes a confused-deputy risk; treat it as security-sensitive and gate edits on CODEOWNERS review.++**Deferred**:+- Full dual-graph provenance comparison engine (expensive at runtime β Phase 2 of P5).+- Cross-organization delegation (MCP-I / DIF standard) β deferred pending spec maturity.++## Validation++P1 lands with:+- Unit tests for `wrapOutbound` scope-reduction invariants (cannot grant more than holder, cannot increase delegationDepth).+- Property tests for `checkToolCall` (every reachable scope chain remains a subset of the principal's original grant).+- Integration test demonstrating that a chain `principal β A β B β tool` denies a tool the principal never granted to A, even when B requests it.+- Benchmark: `wrapOutbound` + `checkToolCall` must add < 1 ms p99 to a SendMessage roundtrip.diff --git a/v3/docs/adr/ADR-145-plugin-supply-chain-integrity-memory-governance.md b/v3/docs/adr/ADR-145-plugin-supply-chain-integrity-memory-governance.mdnew file mode 100644index 0000000000..d0e98af91f--- /dev/null+++ b/v3/docs/adr/ADR-145-plugin-supply-chain-integrity-memory-governance.md@@ -0,0 +1,137 @@+# ADR-145 β Plugin Supply-Chain Integrity and Memory Namespace Governance++**Status**: Proposed+**Date**: 2026-06-02+**Issue**: [ruvnet/ruflo#2254](https://github.com/ruvnet/ruflo/issues/2254)+**Related**: ADR-004 (Plugin Architecture), ADR-006 (Unified Memory), ADR-015 (Unified Plugin System), ADR-131 (ToolOutputGuardrail β content layer), ADR-144 (Authorization Propagation β runtime layer)++## Context++ADR-131 closed the content boundary and ADR-144 closes the runtime action boundary. Both assume the *code that's about to run* is trustworthy in the first place. Two Grade A papers published AprilβMay 2026 demonstrate that assumption is broken under current Ruflo defenses.++### Threat: plugin supply-chain attacks++**Semantic Compliance Hijacking β SCH** (arXiv:2605.14460, May 14, 2026, Grade A): Eliminates the recognizable payload entirely. Instead of injecting malicious code, SCH wraps malicious intent in natural-language "compliance rule" text within plugin descriptions. The LLM agent reads the rule and **generates the harmful code itself at runtime**. Benchmark: **77.67% confidentiality breach, 67.33% RCE success, 0.00% scanner detection**. Signature-based defenses are completely blind because there is no static payload to sign against.++**DDIPE** (arXiv:2604.03081, Apr 3, 2026, Grade A): Document-Driven Implicit Payload Execution embeds malicious logic in plugin documentation and configuration templates. Tested across 4 frameworks, 5 models, 1,070 adversarial skills covering 15 MITRE ATT&CK categories. **Bypass rate 11.6β33.5%; 2.5% of adversarial skills evade both detection and alignment systems.** Four CVEs were disclosed from this research.++Ruflo's current plugin install path (`v3/@claude-flow/cli/src/plugins/store/discovery.ts`) fetches manifests from IPFS via Pinata. It carries **no signature verification** and **no semantic intent analysis**.++### Threat: memory-namespace poisoning++**MINJA** (arXiv:2601.05504, Jan 2026, Grade A): Query-only memory injection achieves **95% success under idealized conditions; 28β38% on production-deployed strong models**. The realistic-production number is still unacceptable for a system where compromised memory steers future agent behavior.++**Plan Injection** (arXiv:2506.17318, Jun 2026, Grade A): Context-chained memory attacks achieve **3Γ higher attack success** than prompt-based injection and **+17.7% exfiltration gain** by creating logical bridges between unrelated memory entries. The fix is **namespace isolation with explicit write grants** β agents cannot poison a namespace they have no business writing to.++**Mnemonic Sovereignty survey** (arXiv:2604.16548, Apr 2026, Grade A): Catalogs nine governance primitives required for secure long-term agent memory. No existing published architecture satisfies all nine. The Ruflo gap: the shared `collaboration` namespace (and all AgentDB namespaces) accepts writes from any agent with no per-namespace authorization. ADR-131 catches *what gets read out*; this ADR catches *who is allowed to write in*.++### Why this is architectural++Distinct from existing security ADRs:++| Layer | ADR | Concern |+|---|---|---|+| Install-time integrity | **this ADR (Part A)** | Is the plugin code trustworthy enough to load? |+| Memory write authority | **this ADR (Part B)** | Is this agent allowed to write to this namespace? |+| Runtime action authority | ADR-144 | Is this agent allowed to call this tool right now? |+| Tool/memory output content | ADR-131 | Does this content contain hijacking instructions? |++ADR-145 introduces two new trust boundaries, two new module surfaces, a protocol addition to the IPFS plugin registry manifest format, and an API addition to AgentDB. All four are architectural.++## Decision++### Part A β `PluginIntegrityVerifier`++Add `PluginIntegrityVerifier` to `@claude-flow/security` with two verification stages run at `plugins install` time.++**Stage 1 β Signature verification** (blocks DDIPE's static-payload variants):++- Every plugin published to the IPFS registry MUST carry a detached **Ed25519 signature** over its manifest hash. The signature lives alongside the manifest in IPFS; the registry index records the signing key's fingerprint.+- `discovery.ts` MUST refuse to install unsigned plugins when `CLAUDE_FLOW_STRICT_PLUGINS=true` (default: warn-only for backwards compatibility).+- Trust anchors (publisher keys we vouch for) live in `v3/@claude-flow/cli/src/plugins/trust/trust-anchors.json`. Edits are gated on CODEOWNERS review.++**Stage 2 β Semantic intent scan** (blocks SCH):++- During `plugins install`, the verifier pipes every natural-language field (description, README excerpt, "compliance rules", any field that ends up in agent context) through a lightweight intent classifier.+- The classifier scores against a taxonomy of malicious-intent categories: credential exfiltration, RCE, data poisoning, privilege escalation, persistence.+- Install blocks if confidence exceeds `CLAUDE_FLOW_PLUGIN_SCH_THRESHOLD` (default `0.8`).+- Fallback: LLM-free pattern rules covering the top-5 SCH families from arXiv:2605.14460 (Table 3 of the paper). The pattern fallback is what makes this safe to run during `plugins install` in environments without LLM credentials.++**Implementation targets**:+- `v3/@claude-flow/security/src/plugins/integrity-verifier.ts` (new)+- `v3/@claude-flow/cli/src/plugins/store/discovery.ts` β verification hook on install+- `v3/@claude-flow/cli/src/plugins/trust/trust-anchors.json` (new)++### Part B β Memory namespace write ACLs++Address governance primitives 1β3 from the Mnemonic Sovereignty taxonomy (write authorization, read authorization, update authorization). Primitives 4β9 (retention, decay, audit, etc.) deferred for a future ADR.++- Every agent spawn receives an explicit `writeNamespaces: string[]` grant.+- AgentDB enforces grants at the storage boundary β **not** by convention in the calling code.+- Agents not in the grant list for a namespace receive `MemoryWriteDenied` on write attempt.+- Read access remains open by default (read-time poisoning is caught at ADR-131's guardrail layer).+- A `readNamespaces` grant is *optional* in v1 and becomes required in v4 (matching the strict-mode escalation in ADR-144).++**Implementation targets**:+- `v3/@claude-flow/memory/src/namespaces/authorization.ts` (new)+- `v3/@claude-flow/memory/src/agent-db.ts` β grant enforcement+- `v3/@claude-flow/cli/src/agent/spawn.ts` β `writeNamespaces` parameter++### Integration plan (phased β P1 is the first PR)++| Phase | Scope | Where |+|---|---|---|+| **P1** | `PluginIntegrityVerifier` skeleton + Stage-1 signature path; trust-anchors file with the existing official-plugin keys | `@claude-flow/security/src/plugins/`, `@claude-flow/cli/src/plugins/trust/` |+| P2 | Stage-2 semantic scan (pattern fallback first, classifier opt-in) | same files |+| P3 | Memory namespace ACL primitives 1β3 in AgentDB | `@claude-flow/memory/src/namespaces/` |+| P4 | `agent spawn --write-namespaces` plumbing through every spawn callsite | `@claude-flow/cli/src/agent/spawn.ts`, hooks |+| P5 | Strict-mode flips to default in v4.0; legacy mode requires explicit env var to re-enable | release docs + breaking-change ADR |++### Backwards compatibility++- Plugin verification defaults to **warn-only** (`CLAUDE_FLOW_STRICT_PLUGINS=false`). Existing unsigned plugins continue to install with a warning.+- Memory namespace ACLs are **additive**: agents spawned without `writeNamespaces` retain legacy full-access until `CLAUDE_FLOW_STRICT_MEMORY=true` is set.+- Both strict modes become default in v4.0.0. The next-major release will be the breaking change.+- The two new env vars are documented escape hatches and MUST be registered in `audit-env-var-precedence.mjs` with rationale.++## Alternatives considered++**Pattern-matching SCH at content boundary (ADR-131 extension).** SCH attacks succeed against content screening because the malicious content *is* the description β there's no instruction-shaped hijack to match. Catching it requires semantic intent classification at install, before the description ever enters agent context.++**Per-plugin sandboxing instead of signing.** Process-level sandboxing buys defense-in-depth but doesn't solve SCH: the malicious behavior is generated by the host model, not by sandboxed plugin code. Signing addresses the trust question; sandboxing addresses the blast-radius question β both belong on the roadmap, but signing closes the more urgent gap.++**Skip Part B; rely on ADR-131 for memory.** ADR-131 catches read-side injection. Plan Injection (arXiv:2506.17318) shows that allowing arbitrary writes lets attackers stage payloads that look innocuous individually but compose into a hijack across multiple reads β content screening cannot catch that compositional pattern. Write authorization is the missing piece.++## Consequences++**Positive**:+- Closes the **77.67% breach / 0.00% detection** SCH gap (arXiv:2605.14460) at the semantic layer.+- Closes DDIPE static-payload variants via Stage-1 signature check.+- Reduces memory-poisoning propagation across agent boundaries (write ACLs are the only mechanism that scales with namespace count).+- Positions Ruflo's memory governance ahead of every 2026 competitor surveyed β none satisfy more than 4 of the 9 Mnemonic Sovereignty primitives.++**Negative / risks**:+- Plugin publishers must generate Ed25519 keypairs and sign manifests (new workflow). The ruflo-plugin-creator skill MUST be updated to scaffold the signing step.+- Semantic intent scan adds **~50β200 ms** to `plugins install` β acceptable at install time, would be unacceptable at runtime.+- Write-ACL migration requires updating every existing `agent_spawn` callsite that uses shared namespaces. Existing pipelines fail open in legacy mode until v4.++**Telemetry / observability**:+- Each verification decision (`pass`, `signature-missing`, `signature-invalid`, `sch-blocked`) MUST be logged with plugin id, publisher fingerprint, and category.+- Each `MemoryWriteDenied` MUST be logged with agent id, namespace, and the granted-namespaces set at spawn time.+- Both feed the security dashboard as adoption metrics.++## Validation++P1 lands with:+- Unit tests covering signature verification against the existing official-plugin keys (round-trip sign β verify; tamper-flips fail).+- Smoke test: `plugins install ./unsigned-plugin` warns by default, errors under `CLAUDE_FLOW_STRICT_PLUGINS=true`.+- Pattern-fallback test corpus drawn from arXiv:2605.14460's Table 3 examples.+- Integration test: agent spawned with `writeNamespaces: ['a']` cannot `memory_store` to namespace `b` under strict-memory mode; legacy mode allows it with a warning log.++## References++- arXiv:2605.14460 β *Exploiting LLM Agent Supply Chains via Payload-less Skills* (SCH)+- arXiv:2604.03081 β *Supply-Chain Poisoning Attacks Against LLM Coding Agent Skill Ecosystems* (DDIPE)+- arXiv:2601.05504 β *Memory Poisoning Attack and Defense on Memory-Based LLM Agents* (MINJA)+- arXiv:2506.17318 β *Plan Injection: Context-Chained Memory Attacks*+- arXiv:2604.16548 β *A Survey on the Security of Long-Term Memory in LLM Agents: Toward Mnemonic Sovereignty*diff --git a/v3/docs/adr/ADR-146-tool-output-guardrail-integration-rollout.md b/v3/docs/adr/ADR-146-tool-output-guardrail-integration-rollout.mdnew file mode 100644index 0000000000..911c3523ba--- /dev/null+++ b/v3/docs/adr/ADR-146-tool-output-guardrail-integration-rollout.md@@ -0,0 +1,128 @@+# ADR-146 β ToolOutputGuardrail Integration Rollout (ADR-131 P2βP5)++**Status**: Proposed+**Date**: 2026-06-02+**Issue**: [ruvnet/ruflo#2149](https://github.com/ruvnet/ruflo/issues/2149) (follow-up β original ADR-131 closed P1 only)+**Related**: ADR-131 (ToolOutputGuardrail β P1 shipped), ADR-144 (Authorization Propagation), ADR-145 (Plugin Supply-Chain Integrity)++## Context++ADR-131 shipped Phase 1 only: the `ToolOutputGuardrail` class is exported from `@claude-flow/security`, has tests and OWASP mapping docs, and is callable. It is not yet wired into a single hot path. The phased plan in ADR-131 Β§Integration Plan named four more phases (P2βP5) that close the actual ASI01 gap by running the guardrail at every place content crosses the agent boundary. None have shipped.++A status-quo system with the class but no call sites is worse than not having the ADR at all β it implies coverage we don't have. Issue #2149 was filed against the ASI01 gap and was left open because P1 shipped without P2βP5; closing it requires running the guardrail at the four content-entry boundaries it was designed for.++### What still leaks today++| Content path | Bypasses guardrail? | Attack surface |+|---|---|---|+| MCP tool result β agent context | **Yes** β no call site in dispatcher | Any compromised MCP server response (40.55% unauthenticated per ADR-144 evidence) |+| Memory read (`memory_search`, `memory_retrieve`) β agent context | **Yes** β no call site in retrieve path | Memory-poisoning chains (MINJA / Plan Injection per ADR-145 evidence) |+| Raft consensus state-transition payload β swarm | **Yes** β no call site in proposal pipeline | SwarmRaft-class injection (covered as "swarm-layer ASI01" in #2149) |+| Hooks tool output (third-party plugins) | **Yes** β no policy plumbing | Any plugin tool that doesn't run its own screen |++P1's class works in isolation but nothing in the runtime calls it. The shape of the gap is identical whether the attack vector is an indirect-injection paper from January or a brand-new one β boundaries with no screening are boundaries with no defence.++### Why a follow-up ADR (instead of just opening four PRs)++P2βP5 collectively add a new policy layer to four independent hot paths. Each path needs a per-boundary decision on `flag` / `redact` / `reject` defaults, an observability contract for the resulting telemetry, and a backwards-compatibility story (the swarm-layer integration in particular cannot break consensus). Those decisions are architectural enough that they should be recorded once, here, instead of relitigated in each PR review.++This ADR is also the right place to record the design coupling with ADR-144 (provenance log consumes guardrail findings) and ADR-145 (write-ACL denial events feed the same telemetry sink as guardrail rejections), so the three security ADRs read as one coherent picture rather than three disconnected layers.++## Decision++Roll out the four remaining ADR-131 phases as a single coordinated effort, with shared defaults and a shared telemetry sink.++### P2 β MCP tool result boundary++**Where**: `v3/@claude-flow/cli/src/mcp-tools/dispatch.ts` (the single chokepoint every tool result flows through).++**Shape**:+```ts+const { content, result, action } = guardrail.scanAndEnforce(rawToolResult);+if (action === 'reject') return { error: { code: 'GUARDRAIL_REJECT', category: result.category, ... } };+if (action === 'redact') rawToolResult = content;+recordTelemetry({ phase: 'P2-mcp-tool', toolName, action, ...result });+return rawToolResult;+```++**Policy defaults**: `low β allow`, `medium β flag (log only)`, `high β redact`, `critical β reject`. Rejection surfaces to the calling agent as a typed tool error β never silently drops to empty content (this rule was in ADR-131 P1 but is restated here so callers can rely on it).++### P3 β Memory read path++**Where**: `v3/@claude-flow/cli/src/memory/memory-bridge.ts` (every `bridgeRetrieve` / `bridgeSearch` return).++**Shape**: Same `scanAndEnforce` call applied to each result's content field. Per-namespace policy overrides supported via `memory.guardrail.<namespace>.<severity>` in `claude-flow.config.json` (e.g., a sandbox namespace might `allow` content that production would `redact`).++A reject finding here returns the entry with `content: <removed-by-guardrail>` and a structured warning rather than excluding the entry entirely β the caller needs to know the entry exists to track namespace state.++### P4 β Raft consensus payload validator++**Where**: hive-mind proposal pipeline (`v3/@claude-flow/cli/src/hive-mind/*` β exact file pinned during P4 PR).++**Constraint**: Raft must not deadlock on a rejected payload. If a proposal triggers a `reject`, the proposer's commit step substitutes a `proposalRejected` no-op with the same term/index, so the log advances and other nodes don't time out waiting for the original. The original proposal hash is recorded in the rejection telemetry for post-incident analysis.++P4 is the highest-risk phase. It ships behind `CLAUDE_FLOW_STRICT_CONSENSUS_GUARDRAIL=true` (default off) until at least two weeks of P2/P3 production telemetry are available to tune the swarm-layer pattern set.++### P5 β Per-tool policy overrides + structured telemetry++**Where**: `v3/@claude-flow/cli/src/hooks/*` for policy resolution; new `v3/@claude-flow/security/src/telemetry/guardrail-events.ts` for the sink.++Telemetry contract (consumed by ADR-144's provenance log and ADR-145's verification log):++```ts+interface GuardrailEvent {+ phase: 'P2-mcp-tool' | 'P3-memory-read' | 'P4-consensus' | 'P5-hook-policy';+ source: { kind: 'tool' | 'namespace' | 'proposal' | 'plugin'; id: string };+ result: GuardrailResult; // { severity, category, pattern, ... } β exact shape from ADR-131+ action: 'allow' | 'flag' | 'redact' | 'reject';+ agentId?: string; // who was about to consume the content+ scopeId?: string; // current AuthScope id from ADR-144+ ts: number; // unix ms+}+```++This is the **only** event shape security telemetry will ship in. ADR-144's `recordAction` and ADR-145's `MemoryWriteDenied` reuse it (different `phase` discriminator).++## Alternatives considered++**Open four independent PRs.** This is the do-nothing-architecturally option. It leaves the per-boundary policy defaults and the telemetry shape to be decided in PR review, which historically diverges (different reviewer, different defaults). The four phases must share a single policy contract; an ADR is the cheapest way to enforce that.++**Ship P2 first, defer P3βP5 indefinitely.** P2 alone closes ~60% of the ASI01 attack surface (MCP tool results are the most common content boundary). But MINJA / Plan Injection specifically target the memory read path P2 doesn't cover; partial rollout misadvertises coverage.++**Replace P4 with a separate consensus-layer ADR.** Defensible β the consensus interaction is the highest-complexity phase β but creates a four-ADR situation for what is fundamentally one rollout. The split makes more sense if a P4-specific design problem surfaces during P3 telemetry analysis; the current decision is to keep it under ADR-146 unless that happens.++## Consequences++**Positive**:+- Closes the `#2149` open issue with a concrete rollout plan whose acceptance criteria are testable per-phase.+- Three security ADRs (131 / 144 / 145) finally share one telemetry shape, so the security dashboard can render them as one picture.+- Per-namespace policy overrides (P3 and P5) let security-sensitive deployments tighten without affecting low-risk ones.++**Negative / risks**:+- P4's consensus interaction is intricate; getting the rejected-payload substitution wrong stalls the cluster. Phased rollout with a strict-mode env var (default off) is mandatory.+- Each phase adds latency. ADR-131 P1's class is pattern-based and sub-millisecond; the new call sites should preserve that, but P3's read path executes on every memory hit β needs to be benchmarked at the same time the call is added, not after the fact.+- More events on the security telemetry channel β needs a sampling story for high-volume deployments. Default sampling rate at P5: `flag` 10%, `redact`/`reject` 100%.++**Deferred**:+- Model-based classifier as an out-of-band reviewer (mentioned but deferred in ADR-131) β same deferral here. Pattern-based remains the only thing on the hot path.+- Non-English pattern sets β community contribution pathway; not blocking P2βP5.++## Validation++P2 lands with:+- Smoke test: a known indirect-injection payload returned from a mock MCP server is rejected, the agent sees a typed error, no content reaches reasoning.+- Benchmark: P2's added latency at p99 < 0.5 ms over a 10k-call run.++P3 lands with:+- Smoke test: a poisoned memory entry is `redacted` on read, the caller sees the structured warning, the namespace counter is unaffected.+- Per-namespace override tested with one `allow`-overridden namespace and one default namespace in the same call.++P4 lands with:+- Chaos test: 100 proposals, 10% triggering `reject`. Cluster must reach consensus on all 100 within the same wall-clock budget as a no-reject baseline (proposalRejected no-op substitution working).+- Strict mode initially `false`; flipped to default after two weeks of stable P2/P3 telemetry.++P5 lands with:+- `GuardrailEvent` schema validation tests, plus a `replay` script that consumes telemetry from a captured incident and reconstructs the rejected/redacted state.+- The security dashboard renders all three ADR feeds (131/144/145) from this single sink.++Closing `#2149` happens at the end of P5, not at the end of P2.