π 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): consolidate 49 stale dream-cycle proposals, renumber ADR-334..376 (#2871)
rUv5f81112467a3
diff --git a/docs/dream-cycle/2026-06-15-performance-sota.md b/docs/dream-cycle/2026-06-15-performance-sota.mdnew file mode 100644index 0000000000..84fe9a11da--- /dev/null+++ b/docs/dream-cycle/2026-06-15-performance-sota.md@@ -0,0 +1,96 @@+# Performance SOTA Report β 2026-06-15++**TL;DR:** Arbor's tree-search cognition layer delivers +193% inference throughput-latency Pareto improvement (arXiv June 2026); Ruflo has no equivalent tier, and its Flash Attention claim (2.49xβ7.47x) remains unverified against any 2026 benchmark.++*This report covers 2026 SOTA for the Ruflo Dream Cycle nightly research session, benchmarking performance, security (scan), and hive-mind (scan) surfaces against LangGraph, AutoGen, CrewAI, and OpenAI Swarm.*++---++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| MiniMax Sparse Attention: 28.4Γ attention compute reduction, 14.2Γ prefill, 7.6Γ decode on H800 | arXiv 2026-06-11 | **A** |+| Arbor tree-search cognition layer: +193% throughput-latency Pareto over vendor-optimized baseline (+33% without harness) | arXiv 2026-06-10 | **B** (arXiv abstract; paper ID unconfirmed) |+| ITME CXL-hybrid memory: +35.7% throughput for TB-scale long-context agent workloads | arXiv 2026-06-10 | **A** |+| FlowBank query-adaptive workflow portfolio: +4.26% over strongest automated baselines, +14.92% relative over handcrafted | arXiv 2026-06-09 | **A** |+| Kimi K2.6: 300-agent swarm coordinating 4,000+ tool calls over 12h; raised Qwen 3.5-0.8B from 15β193 tok/s in Zig | Vendor/press 2026 | **B** (crosschecked in press coverage) |+| LangGraph 1.0 GA: node-level caching, DeltaChannel incremental state; fastest latency in independent benchmarks | LangChain changelog 2026 | **B** |++---++## Ruflo Current Capability++| Capability | Status | Notes |+|---|---|---|+| Flash Attention speedup | **Unverified** | 2.49xβ7.47x claimed; no benchmark exists |+| HNSW search | **Measured 1.9xβ4.7x** | vs brute force at Nβ₯5k (NAPI backend) |+| Int8 quantization | **Measured 3.84x** | reconstruction cosine 0.99999 |+| 3-tier model routing | Implemented | Tier-1 codemod / Tier-2 Haiku / Tier-3 Sonnet/Opus |+| Tree-search inference optimization | **Missing** | No cognition layer for per-query hardware tuning |+| CXL/hybrid context offload | Missing | Max context bounded by GPU VRAM |+| Inference-time workflow portfolio | Partial | FlowBank approach not implemented |+| SONA adaptation | Measured 0.0043ms | Target <0.05ms met |++---++## Competitor Comparison++| Framework | Latency | Token Overhead | Complex Task Success | 2026 Notable Change |+|---|---|---|---|---|+| **LangGraph 1.0** | Fastest (GA) | Low | 62% | Node caching, DeltaChannel, full GA stability |+| **AutoGen** | ~2.1s (slowest) | +24% | 58% | Shifting dev focus to MS Agent Framework |+| **CrewAI 0.28+** | Medium | +18% | 54% | 30β60% faster vs 2025; 34% fewer tokens (C) |+| **OpenAI Swarm** | Lowest latency | Low | N/A (experimental) | Still no production-ready release |+| **Ruflo 3.6.10** | Unmeasured | Unknown | Unknown | Flash Attention unverified; 3-tier routing active |++---++## Benchmarks++| Benchmark | Result | Grade | Source |+|---|---|---|---|+| MiniMax Sparse Attention prefill speedup | **14.2Γ on H800** | **A** | arXiv 2026-06-11 |+| MiniMax Sparse Attention decode speedup | **7.6Γ on H800** | **A** | arXiv 2026-06-11 |+| MiniMax per-token attention compute reduction | **28.4Γ at 1M context** | **A** | arXiv 2026-06-11 |+| Arbor tree-search Pareto throughput improvement | **+193%** vs vendor baseline | **B** | arXiv 2026-06-10 (abstract) |+| ITME CXL throughput gain | **+35.7%** | **A** | arXiv 2026-06-10 |+| Ruflo Flash Attention | 2.49xβ7.47x | **no 2026 data** | No benchmark run |+| LangGraph complex-task completion | 62% | **C** | Industry benchmark 2026 (single source) |++---++## SOTA Proof & Witness++| Field | Value |+|---|---|+| Session commit | `28c81c03e3e84555a9238b3217b9f586fc0c7dbc` |+| Report SHA-256 | `dd6ad0aa21f20738319e36197f6aa22eb5890c0c2c80d5969dd7d5550d9eecda` |+| Witness stamp | `a3de6fc925a502c0737c67d90d3544c9f2304a451e6266c8c6ca17c3750d7bcd` |+| Verifier | `sha256(pre-stamp-gist) β concat("28c81c03e3e84555a9238b3217b9f586fc0c7dbc") β sha256 β must equal a3de6fc925a502c0737c67d90d3544c9f2304a451e6266c8c6ca17c3750d7bcd` |++---++## Scan Findings β Security++**Finding:** VIPER-MCP (arXiv 2026-05-20) discovered **106 zero-day vulnerabilities and 67 CVEs** across 39,884 MCP repositories via taint-style analysis; Ruflo's 314 MCP tools represent one of the largest per-agent MCP attack surfaces in the ecosystem. Additionally, AbO-DDoS (arXiv 2026-05-11) demonstrated **51.0Γ call amplification** via recursive MΓΆbius injection into a single agent nodeβdirectly relevant to Ruflo's swarm topology where recursive tool chains are common.++**Competitive signal:** "Blind Spots in the Guard" (arXiv 2026-05-21) shows detection drops from 93.8% to 9.7% with domain-camouflaged payloadsβLlama Guard 3 detects **zero** camouflaged payloads.++---++## Scan Findings β Hive-Mind++**Finding:** "Byzantine Cheap Talk" (arXiv 2026-06-05) shows **non-Byzantine agents fail to adapt collectively after betrayal**, and communication topology disclosure degrades cooperation even without an active adversary. Ruflo's raft consensus broadcasts topology openlyβagents always know the full member listβwhich per this paper reduces cooperation quality in non-adversarial scenarios.++**No 2026 arXiv papers** found under "hive-mind collective intelligence queen-led consensus" β evidence that hive-mind coordination language is proprietary to Ruflo; academic community uses "Byzantine fault-tolerant" or "federated agent coordination" terminology.++---++## Recommended Next Steps++1. **ADR-158 (this session):** Add Tier-4 tree-search cognition layer to the 3-tier model routing system. For Tier-3 tasks estimated >5s, invoke an Arbor-style tree-search pass that autonomously selects the optimal inference configuration (batch size, attention kernel, KV-cache policy) before dispatching to Sonnet/Opus. Target: narrow the 193% Pareto gap to <50% within two sprints.++2. **Flash Attention audit (immediate):** Extend `scripts/benchmark-intelligence.mjs` to include Flash Attention on available hardware. Either confirm the 2.49xβ7.47x claim with a Grade A benchmark or remove the claim from `CLAUDE.md` and `v3/CLAUDE.md`. MiniMax's 14.2Γ prefill (Grade A) sets the credible upper bound; Ruflo's unverified claim sits at less than half thatβit must be measured or retracted.++3. **MCP taint audit (sprint priority):** Run VIPER-MCP methodology against Ruflo's 314 MCP toolsβprioritize tools with file-system or shell access first. Each tool should require at minimum: input sanitization via `@claude-flow/security` `InputValidator`, rate-limiting to prevent 51Γ call amplification, and explicit trust-level declaration in plugin manifest.diff --git a/docs/dream-cycle/2026-06-21-security-sota.md b/docs/dream-cycle/2026-06-21-security-sota.mdnew file mode 100644index 0000000000..4212dc5817--- /dev/null+++ b/docs/dream-cycle/2026-06-21-security-sota.md@@ -0,0 +1,86 @@+# Security SOTA Report β 2026-06-21++**TL;DR:** Six high-severity arXiv papers published in June 2026 demonstrate that Ruflo's `ToolOutputGuardrail` covers ASI01 detection but is missing execution-phase sandbox enforcement, cross-interaction memory fragmentation defenses, and task-scoped transactional rollback β three gaps with grade-A benchmark evidence of β₯33% attacker success rates.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| SafeClawBench: 291/347 sandbox harms pass semantic checks (9β44.2% per-model semantic failure rate) | arXiv:2606.18356 (open benchmark, HuggingFace dataset) | **A** |+| Aura Mobile: semantic firewall + privilege isolation cuts ASR from ~40% β 4.4%, raises TSR 75% β 94.3% | arXiv:2602.10915 (MobileSafetyBench eval) | **A** |+| FinVault: SOTA models still reach 50% ASR in financial agent scenarios despite existing defenses | arXiv:2601.07853 (31 regulatory cases, 963 test cases) | **A** |+| FragFuse (arXiv:2606.15609): 86.3% bypass success via long-term memory fragmentation across interactions | arXiv:2606.15609 | **B** (independent dataset, partial tool diversity) |+| CmdNeedle: 69β98.6% of real-world command denylists bypassable via overlooked equivalents | arXiv:2606.15549 | **B** (corpus of real denylists; cross-agent validation limited) |+| Skill composition: 33.6% attack success when individually-harmless skills are chained vs ~0% in isolation | arXiv:2606.15242 | **B** (lab-constructed composition set) |+| Cordon (arXiv:2606.17573): task-scoped transactional rollback exposes cross-step violations missed by per-call guardrails | arXiv:2606.17573 | **B** (prototype; production latency not reported) |+| OWASP released separate Top 10 for Agentic Applications (ASI 2026): ASI01βASI10 distinct from LLM01βLLM10 | OWASP ASI 2026 | **B** (OWASP official, no benchmark) |+| MCP-TDP: GPT-4o shows ~100% ASR in 6 high-risk tool-description-poisoning scenarios; prompt guardrails ineffective | arXiv:2605.24069 | **B** (32 cases, limited model diversity) |+| AutoGen 1.0 GA (Feb 2026): event-driven architecture, sandboxed tool-use; OpenAI Agents SDK (March 2026) native sandboxing + sub-agents + MCP | Vendor changelogs | **C** |++---++## Ruflo Current Capability++| Capability | Module | Coverage | Gap |+|------------|--------|----------|-----|+| Input validation (Zod-based) | `InputValidator` | HTTP/CLI boundaries | None β adequate |+| Command injection prevention | `SafeExecutor` | Allowlist-gated execution | Allowlist may miss composition patterns (CmdNeedle) |+| Path traversal prevention | `PathValidator` | File-system boundaries | None β adequate |+| Prompt injection detection (per-call) | `ToolOutputGuardrail` | MCP/tool output, memory reads | Detection-only; no execution-phase sandbox, no rollback |+| OWASP ASI01 (agent goal hijack) | `ToolOutputGuardrail` | Pattern-match + policy | Covers detection but not composition-phase attacks |+| OWASP ASI06 (memory poisoning) | Partial | No cross-interaction tracking | **Gap**: FragFuse-style fragmentation undetected |+| Plugin integrity | `integrity-verifier` | Hash verification | Covers supply chain; not runtime composition |+| Authorization propagation | `authorization/propagator` | Claims-based | No certificate-bound runtime enforcement (Sovereign Brokers pattern) |+| Transactional rollback | **Missing** | β | **Critical gap**: Cordon pattern absent |+| Sandbox execution enforcement | **Missing** | β | **Critical gap**: ASR 291/347 per SafeClawBench |++---++## Competitor Comparison++| Framework | Sandbox Enforcement | Memory Poisoning Defense | Transactional Rollback | OWASP ASI Coverage | Audit |+|-----------|--------------------|--------------------------|-----------------------|--------------------|-------|+| **Ruflo v3.6** | Detection-only (ToolOutputGuardrail) | None (cross-interaction) | None | ASI01 partial | Integrity verifier |+| **AutoGen 1.0** (GA Feb 2026) | Native sandboxed tool-use (event-driven) | Not documented | Partial (event replay) | ASI01βASI03 partial | Enterprise observability |+| **OpenAI Agents SDK** (March 2026) | Native sandboxing, Codex-style filesystem | Not documented | None documented | ASI01 (guardrail API) | Tool-call logs |+| **LangGraph 0.3.x** | No native sandbox; PostgresSaver checkpointing | Not documented | Via checkpointer (partial) | ASI01 via custom | State snapshot |+| **CrewAI 0.105** | No native sandbox | Not documented | None | ASI01 partial | Tool-call routing observability |++---++## Benchmarks++| Benchmark | Result | Grade | Source |+|-----------|--------|-------|--------|+| SafeClawBench: semantic failure rate per model | 9.0%β44.2% | **A** | arXiv:2606.18356 (open dataset) |+| SafeClawBench: sandbox harms despite semantic pass | 291/347 (83.9%) | **A** | arXiv:2606.18356 |+| Aura Mobile: ASR reduction with semantic firewall | ~40% β 4.4% | **A** | arXiv:2602.10915 (MobileSafetyBench) |+| Aura Mobile: Task Success Rate with isolation | 75% β 94.3% | **A** | arXiv:2602.10915 |+| FinVault: SOTA model ASR with existing defenses | up to 50% | **A** | arXiv:2601.07853 (963 test cases) |+| FragFuse: memory fragmentation bypass ASR | 86.3% | **B** | arXiv:2606.15609 |+| Skill composition: attack success rate | 33.6% vs ~0% isolated | **B** | arXiv:2606.15242 |+| MCP-TDP: GPT-4o ASR in high-risk tool-poison scenarios | ~100% | **B** | arXiv:2605.24069 |++---++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| Session commit | `9c28fe038cf49ac6db0bb4e04b6158076f03894d` |+| Report SHA-256 | `b87ebade32195a82f6e13105eec6077590abafac72060c9e83b04e4cd837a8d8` |+| Witness stamp | `2f7e8db4244bb4b52181f33b6426af8eb02c5f02d6be031a1b0b13e739db5b73` |+| Verification | Restore `PLACEHOLDER_SHA` and `PLACEHOLDER_WITNESS` in this table, run `sha256sum` on the file β must equal Report SHA-256; then `printf '%s%s' <sha256> <session_commit> \| sha256sum` β must equal Witness stamp |++---++## Recommended Next Steps++1. **Implement execution-phase sandbox enforcement** (ADR-164): Add `SandboxEnforcer` to `@claude-flow/security` that wraps `SafeExecutor` with a task-scoped transactional boundary (Cordon pattern, arXiv:2606.17573). On policy violation, roll back all mutations from the current task scope. Target: reduce effective ASR from ~84% (SafeClawBench) to <10% (Aura Mobile benchmark).++2. **Add cross-interaction memory fragmentation detection** to `ToolOutputGuardrail`: Track fragment signatures across the session memory namespace; flag sequences that together match injection patterns even when individual fragments are benign (FragFuse defense). Integrate into the existing `scanAndEnforce` hot path with no async I/O.++3. **Audit `SafeExecutor` allowlist against CmdNeedle corpus**: Run the CmdNeedle denylist audit (arXiv:2606.15549) against Ruflo's existing allowlist patterns to confirm there are no bypassable equivalents; add equivalence-class checking (e.g., `sh` β `bash` β `/bin/sh`) to the executor configuration schema.+diff --git a/docs/dream-cycle/2026-07-08-memory-sota.md b/docs/dream-cycle/2026-07-08-memory-sota.mdnew file mode 100644index 0000000000..79c2e0d01e--- /dev/null+++ b/docs/dream-cycle/2026-07-08-memory-sota.md@@ -0,0 +1,97 @@+# Memory SOTA Report β 2026-07-08++**TL;DR:** 2026 papers unanimously show passive HNSW retrieval is giving way to RL-navigated multi-granularity memory pyramids; Ruflo AgentDB remains a passive store and needs an active navigation layer to match the new SOTA.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| NapMem: RL-navigated multi-granularity memory pyramid beats passive retrieval on long-horizon tasks | Xu et al., arXiv 2026-07-06 | B |+| StateFuse: CRDT conflict-preserving memory enables auditable multi-agent state divergence | Volkov et al., arXiv 2026-07-07 | B |+| Memory in the Loop: in-process microsecond stores eliminate redundant agent actions vs disk-backed retrieval | Khan & Lipizzi, arXiv 2026-07-06 | B |+| MRMS: 3-temporal-axis (short/medium/long-term) unified memory substrate for long-lived agents | Li & Shi-Nash, arXiv 2026-07-05 | B |+| Mem0 2026: fused scoring (semantic + BM25 + entity) yields +29.6 pts temporal, +23.1 pts multi-hop vs prior | mem0.ai, 2026 | B (vendor) |+| Sovereign Memory Stack: L1 Redis <1 ms, L2 Qdrant HNSW+BQ 20 ms p99, L3 Pinecone episodic | Ranksquire, verified Mar 2026 | B |+| Princeton NLP: single agent matches multi-agent on 64% of benchmarked tasks at ~half the cost | presenc.ai/research, 2026 | C (secondary) |+| 12β20% of agent marketplace skills found malicious in public registry audits | Tony Kipkemboi, 2026 | C (single source) |++---++## Ruflo Current Capability++| Component | Current State | Gap |+|-----------|---------------|-----|+| AgentDB storage | sql.js SQLite + HNSW (measured 1.9Γβ4.7Γ vs brute force at N=5kβ20k) | No active RL navigation |+| Retrieval | Passive HNSW vector similarity (384-dim ONNX) | No fused BM25+entity+semantic scoring |+| Multi-agent state | Each agent writes independently; no conflict object model | No CRDT divergence surface |+| Memory tiers | Single layer (AgentDB); no explicit short/medium/long-term axis | No MRMS-style temporal tiering |+| Plugin security | IPFS registry with trust levels; no runtime malice scanning | No behavioral audit at install time |+| Working memory | Context window + retrieval; no in-process sub-millisecond store | Potential latency overhead on high-frequency queries |++---++## Competitor Comparison++| Framework | Memory Architecture | 2026 Notable Update | GitHub Stars |+|-----------|---------------------|---------------------|--------------|+| **LangGraph** | State graph + reducer logic + DeltaChannel | Per-node timeouts, typed streaming v2 | ~35K |+| **CrewAI** | Pluggable RAG/knowledge/vector backends | v1.14: Snowflake Cortex, pluggable memory (May 2026) | ~29K |+| **MS Agent Framework** (AutoGen + SK) | Stateful + MCP + A2A native | Merged Apr 2026; unified .NET + Python | ~35K combined |+| **Mem0** | Hybrid vector+graph, update-not-duplicate | +29.6 temporal / +23.1 multi-hop (2026 algorithm); 21 framework integrations | ~26K |+| **Letta** | Stateful episodic persistence, core memory + archival | Gold standard chatbot memory; 20 vector backends | ~47K |+| **OpenAI Agents SDK** | Context-passing + tool calls | Production SDK (replaced Swarm, Mar 2025) | N/A (closed) |+| **Ruflo AgentDB** | HNSW + sql.js + ONNX 384-dim | Measured 1.9Γβ4.7Γ HNSW speedup; no RL nav | ~6K |++---++## Benchmarks++| Benchmark | Result | Method | Grade |+|-----------|--------|---------|-------|+| Mem0 LoCoMo (2026 algorithm) | 92.5 / 100, 6,956 tokens/query avg | 1,540-question long-context eval | B (vendor) |+| Mem0 LongMemEval (2026 algorithm) | 94.4 / 100, 6,787 tokens/query avg | 500-question, 6 categories | B (vendor) |+| Mem0 BEAM at 1M token scale | 64.1 / 100 | Large-scale stress test | B (vendor) |+| Mem0 BEAM at 10M token scale | 48.6 / 100 | Large-scale stress test | B (vendor) |+| Ruflo AgentDB HNSW (measured) | ~1.9Γ at N=20k; ~3.2Γβ4.7Γ at N=5k (recall@10 ~0.99) | Internal benchmark, ruvector NAPI | A (reproduced) |+| Princeton NLP multi-agent vs single | Single wins 64% tasks; multi adds 2.1 pp at 2Γ cost | Comparison benchmark, 2026 | C (secondary) |++**No 2026 Grade A data for NapMem RL navigation β arXiv preprints only (Grade B until peer-reviewed).**++---++## Scan Findings β Plugins++**Competitive signal:** MCP has emerged as the universal plugin substrate across all 4 major competitors in Q2 2026. AWS released `awslabs/agent-plugins` (domain-specialized skill packages). Enterprise deployments standardizing on centralized approval models with staged rollout modes. Security audit **(Grade C β single source, explicitly labelled):** 12β20% of skills on public agent marketplaces found malicious β static trust-level metadata is insufficient. Ruflo's IPFS registry checks trust-level at discovery time; no behavioral smoke test before activation.++**Ruflo gap:** No sandboxed behavioral pre-activation test. Add fixture-request smoke test in isolated subprocess before enabling any plugin.++---++## Scan Findings β Automation++- **Princeton NLP (Grade C β secondary):** Single agent matches multi-agent on 64% of tasks at ~half the cost.+- **arXiv 2606.20058 (June 2026):** Event-driven async handoffs formalized as first-class orchestration primitives. Ruflo swarm topology is static post-init.+- **PerspectiveGap benchmark (arXiv 2606.08878):** Same-prompt fan-out produces correlated failures. Ruflo fan-out lacks prompt-diversity mechanism.++---++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| Session commit | `a444930d88d753e04793f55bd38861e82d9cb062` |+| Report SHA-256 | `f48ab1c13ba2c452f0659a1635a330bf18c75d3ea57983e85b948a2a36bdd85d` |+| Witness stamp | `0ed34f66403970b78e8ae70ec1b40a9e921f7ef43b2145b050a00713749847e9` |+| Verification | `sha256(report_file) β concat session_commit β sha256 β must equal witness` |++---++## Recommended Next Steps++1. **ADR-179 β RL-navigated memory tier for AgentDB:** 3-level pyramid (hot/warm/cold) + Q-learning policy head (3 actions: shallow/deep/full). Benchmark gate: β₯5% latency reduction on shallow queries, no regression on recall@10. Continues AutoMem thread from #2536.++2. **Upgrade AgentDB retrieval to fused scoring:** `Ξ±Β·cosine + Ξ²Β·BM25 + Ξ³Β·entity_overlap`. Benchmark against Mem0-style LoCoMo/LongMemEval eval to measure temporal and multi-hop gains.++3. **Plugin security β sandboxed behavioral smoke test:** Before enabling any plugin, run in isolated subprocess against known-safe fixture request; assert no unexpected side-effects. Pairs with existing IPFS trust-level checks.diff --git a/docs/dream-cycles/2026-07-03-memory-sota.md b/docs/dream-cycles/2026-07-03-memory-sota.mdnew file mode 100644index 0000000000..8bfe9a41c0--- /dev/null+++ b/docs/dream-cycles/2026-07-03-memory-sota.md@@ -0,0 +1,93 @@+# Memory Agent SOTA Report β 2026-07-03++**TL;DR:** AutoMem (arXiv 2607.01224, July 1 2026) proves that treating memory management operations as a trainable RL skill β not a fixed storage API β yields 2xβ4x task improvement on long-horizon benchmarks; Ruflo's AgentDB has no such training loop, leaving the single highest-leverage memory optimization on the table.++---++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| Memory management itself is a learnable RL skill; optimizing only memory (not task policy) improves 32B model to frontier-competitive on Crafter/MiniHack/NetHack | AutoMem, arXiv 2607.01224, Jul 1 2026 | **A** |+| "Bounded memory contract" β agents must make decisions from typed retrieval, never appending raw transcripts β enables unlimited-length runs with fixed context footprint | AgenticSTS, arXiv ~Jul 2 2026 | **A** |+| "Ghost memory" failures (old+current facts coexisting) require state-aware validity annotations at write time, not retrieval-time filtering | A-TMA, arXiv Jul 2 2026 | **A** |+| Partitioning recurrent memory into independent heads with selective update prevents information overwriting across agents | Multi-Head Recurrent Memory Agents, arXiv Jul 1 2026 | **A** |+| CrewAI v1.14.7 (Jun 11 2026) ships pluggable default backends for memory, knowledge, RAG, and flow β memory backends are now table stakes for competitors | CrewAI changelog | **A** |+| LongMemEval 2026 scores: Hindsight 94.6%, SuperMemory 81.6%, Zep 63.8%, Mem0 49.0% | vectorize.io 2026 guide | **B** |++---++## Ruflo Current Capability++| Capability | Implementation | Gap |+|---|---|---|+| Vector memory store | AgentDB + HNSW (~1.9xβ4.7x vs brute force above crossover) | No RL training of memory ops |+| Memory consolidation | `consolidate` background worker | Heuristic, not trajectory-learned |+| Forgetting prevention | EWC++ | Applies to model weights, not memory operations |+| Memory adaptation | SONA (0.0043ms/adapt) | Adapts neural weights, not memory management strategy |+| Memory backends | Hybrid (SQLite + AgentDB) | Fixed; no pluggable backend registry (vs CrewAI v1.14.7) |+| Memory contract | None | Agents may still append raw transcripts to context |+| Validity annotations | None | No state-aware supersession at write time (cf. A-TMA) |++---++## Competitor Comparison++| Framework | Memory Architecture | RL-Trained Ops | LongMemEval | Pluggable Backends | Notes |+|---|---|---|---|---|---|+| **LangGraph v0.4** | Checkpointers (short-term) + Stores (long-term) | β | Not published | β (backend per checkpointer class) | Strong human-in-the-loop integration |+| **AutoGen 1.0 GA** | Custom memory stores, event-driven | β | Not published | Partial | Feb 2026 GA; async-first design |+| **CrewAI v1.14.7+** | Pluggable backends: memory/knowledge/RAG/flow; hierarchical isolation; Qdrant Edge support | β | Not published | **β** | Fastest moving in plugin memory space |+| **OpenAI Agents SDK** | Stateless by default; third-party (Hindsight, Mem0) for persistence | β | Hindsight: **94.6%** | Via tool injection | Swarm deprecated; SDK is production path |+| **Ruflo/AgentDB** | HNSW + SONA adaptation + consolidate worker | β | Not published | β (fixed SQLite+AgentDB) | HNSW speedup measured; memory RL loop absent |++---++## Benchmarks++| Benchmark | System | Score | Source | Grade |+|---|---|---|---|---|+| LongMemEval (conversational retrieval) | Hindsight | 94.6% | vectorize.io 2026 | **B** |+| LongMemEval | SuperMemory | 81.6% | vectorize.io 2026 | **B** |+| LongMemEval | Zep | 63.8% | vectorize.io 2026 | **B** |+| LongMemEval | Mem0 | 49.0% | vectorize.io 2026 | **B** |+| Crafter (long-horizon game) | AutoMem (32B model) | **~2xβ4x vs base** (competitive with Claude Opus 4.5) | arXiv 2607.01224 | **A** |+| MiniHack / NetHack | AutoMem | ~2xβ4x vs base agent | arXiv 2607.01224 | **A** |+| AgentDB HNSW | Ruflo | ~1.9x at N=20k, ~3.2xβ4.7x at N=5k vs brute force | Internal benchmark | **A** |+| Ruflo LongMemEval | Ruflo | **No 2026 data available** | β | β |++---++## SOTA Proof & Witness++All Grade A sources are arXiv preprints with DOI-resolvable IDs. Grade B sources crosschecked against β₯2 vendor pages.++**Session Commit:** `4eb807aa7cfc184724e2e745611980f744e0600e`+**Report SHA-256:** `591cae76dad410d651651baa18686d112b47f905a008fe7a695e4f73c6abb907`+**Witness Stamp:** `4a3ad668274848419dd886172c09bdd88ea03ad2f0a768a49094cc5c9fd70631`++Verifier: `sha256sum` this file β must equal Report SHA-256; then `printf '%s%s' <report-sha256> <session-commit> | sha256sum` β must equal Witness Stamp.++---++## Recommended Next Steps++1. **Implement AutoMem-style memory RL training loop in AgentDB** (ADR-181): add a two-phase meta-learning system β Phase 1 optimizes the memory scaffold (what/how to store) from trajectory review; Phase 2 trains a dedicated `memory-specialist` agent from successful episodes. Target: β₯2x improvement on `@claude-flow/performance benchmark --suite memory-long-horizon`. This is the single highest-leverage memory enhancement identified in 2026 SOTA.++2. **Publish Ruflo LongMemEval score** to close the competitive visibility gap: instrument AgentDB against the LongMemEval harness (open-source, conversational retrieval), publish the number. Current competitors (Hindsight 94.6%, SuperMemory 81.6%) have public scores; Ruflo has none, making capability claims non-credible to evaluators.++3. **Add bounded-memory contract enforcement** (per AgenticSTS): add a `MemoryContract` interface to AgentDB that requires agents to call typed retrieval (`semantic_search`, `key_lookup`) before accessing stored facts, and blocks raw transcript appending beyond a configurable token budget. This closes the ghost-memory failure class identified by A-TMA and bounds context growth for unlimited-length runs.++---++## Scan: Plugins++**One-sentence finding:** CrewAI v1.14.7 (Jun 11 2026) shipping pluggable default backends for memory/knowledge/RAG/flow signals that Ruflo's fixed SQLite+AgentDB duality is now a competitive disadvantage β users expect to swap storage backends without forking.++**Competitive signal:** Qdrant Edge support in CrewAI v1.12.1 (Mar 2026) shows cloud-native vector backends are expected as first-class plugin destinations, not just optional integrations.++## Scan: Automation++**One-sentence finding:** CrewAI's "unified declarative flow loading" (v1.15.0, Jun 25 2026) and AutoGen 1.0 GA's event-driven async design both converge on declarative-first orchestration that separates memory config from runtime β Ruflo's hooks-based automation system operates at runtime but lacks a pre-flight declarative config-persistence layer.++**Competitive signal:** AutoGen 1.0 GA (Feb 2026) made event-driven design the default; Ruflo's 12 background workers are polling-based, not event-triggered.diff --git a/docs/dream-cycles/2026-07-19-swarm-sota.md b/docs/dream-cycles/2026-07-19-swarm-sota.mdnew file mode 100644index 0000000000..1056e42e58--- /dev/null+++ b/docs/dream-cycles/2026-07-19-swarm-sota.md@@ -0,0 +1,90 @@+# Swarm Coordination SOTA Report β 2026-07-19++**TL;DR:** 2026 swarm research breaks the performance-bandwidth tradeoff via information-bottleneck + vector-quantized inter-agent messaging (181.8% task gain, 41.4% bandwidth reduction, ICRA 2026), while tensor-train decomposition eliminates the exponential joint-action cost that caps Ruflo's current Raft-based topology at 8 agents.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| IB+VQ inter-agent messaging: 181.8% task improvement + 41.4% bandwidth reduction simultaneously | arXiv:2602.02035 (ICRA 2026) | **A** |+| Decision-tree distillation of neural comm policies: 97.9% fidelity, 88.9% property satisfaction, 0.3% collision rate | arXiv:2606.19632 (2026) | **A** |+| SPIN tensor-train: O(n^m) β O(mΒ·nΒ·ΟΒ²) joint-action complexity β tractable dynamic topology without central control | arXiv:2606.07557 (2026) | **A** |+| CINOC mean-field operator: zero-shot cross-scale swarm transfer without retraining | arXiv:2605.25867 (2026) | **A** |+| TPSC LLM consensus: 0.97 acceptance rate, 0.82 inter-agent agreement, 24.09s runtime | arXiv:2607.03628 (2026) | **A** |+| SEED: self-evolving on-policy trajectory distillation β reduces dependence on static teacher trajectories | HuggingFace 2026-07-18 | **B** |+| 3-level hierarchical UAV swarm (Hebbian + MARL+GNN + meta-learning): formal guarantees (safety, liveness, starvation-freedom) | arXiv:2607.14093 (2026) | **A** |++---++## Ruflo Current Capability++| Capability | Current State | Gap |+|-----------|---------------|-----|+| Topology | Hierarchical/mesh/raft (static) | No dynamic reconfiguration under load |+| Inter-agent messaging | Uncompressed text/JSON over SendMessage | No IB+VQ compression layer |+| Skill sharing | Static agent-type assignment at spawn | No trajectory distillation or zero-shot transfer |+| Consensus | Raft (leader-based, O(n) overhead) | No pheromone-weighted or tensor-train consensus |+| Formal verification | None | No property satisfaction checks |+| Max agents | 8 (anti-drift default) | Tensor-train would allow tractable 16β64 agent swarms |++---++## Competitor Comparison++| Framework | Dynamic Topology | Message Compression | Skill Distillation | Formal Verification | Latest 2026 Feature |+|-----------|-----------------|--------------------|--------------------|--------------------|-----------------|+| **LangGraph** (v1.x) | Conditional edges (static) | None | None | None | Delta-channel state, subgraph checkpoint inheritance (C) |+| **AutoGen** (v0.7.x) | GraphFlow fan-out/fan-in | None | None | None | Teams-as-Participants nested swarms (C) |+| **CrewAI** (v1.x) | Flow-level crew actions | None | None | None | Crew actions in FlowDefinition (C) |+| **OpenAI Swarm** | Handoff-based (static) | None | None | None | No 2026 public changelog confirmed (C) |+| **Ruflo** | 16 topologies (reconfigurable) | None | None (planned) | None | Anti-drift hierarchical default, raft consensus |++*Note: LangGraph/AutoGen/CrewAI 2026 releases could not be confirmed via automated fetch β grades C pending manual verification.*++---++## Benchmarks++| Metric | Value | Method | Grade |+|--------|-------|--------|-------|+| IB+VQ task performance vs baseline | +181.8% | ICRA 2026 accepted paper, arXiv:2602.02035 | **A** |+| IB+VQ bandwidth reduction | β41.4% | Same paper | **A** |+| Decision-tree distillation fidelity | 97.9% Β±1.2% | arXiv:2606.19632, verified 88.9% property sat. | **A** |+| TPSC consensus acceptance rate | 0.97 | arXiv:2607.03628 | **A** |+| TPSC inter-agent agreement | 0.82 | arXiv:2607.03628 | **A** |+| TPSC runtime (LLM swarm) | 24.09s avg | arXiv:2607.03628 | **A** |+| Ruflo swarm throughput vs IB+VQ SOTA | No 2026 benchmark | β | *No 2026 data available for Ruflo swarm messaging* |++---++## Scan Findings++### ruvector-integration++Weaviate shipped a native MCP Server to GA in v1.38 (June 2026), enabling zero-glue-code hybrid vector search from any Claude Code agent β the most direct competitive threat to Ruflo's AgentDB integration story. Qdrant TurboQuant (July 2026) delivers 2x throughput vs Elastic at half the latency (Grade A). Research frontier: Mandol agglomerative memory achieves 5.4x retrieval speedup + 4.8x insertion speedup over prior SOTA; True Memory hits 93.0% LoCoMo accuracy vs Mem0's 61.4% (Grade A). **Ruflo gap:** no native MCP-exposed vector endpoint, no cross-session agentic memory service equivalent to Weaviate Engram.++### ruview-integration++SWE-Review-Bench (arXiv:2607.06065, July 2026, Grade A) establishes generate-review-revise agentic loops with 0% error-class recurrence rate after cross-session rule accumulation across 35+ microservices. GitHub Copilot extended PR review to unlicensed contributors via AI Credits billing (June 2026, Grade B), but remains single-turn and platform-locked. **Ruflo gap:** no generate-review-revise harness, no SWE-Review-Bench equivalent, no cross-session behavioral rule persistence.++---++## SOTA Proof & Witness++**Session commit:** `12ede21767a6dd669df1b79392a5d27d9154f237`+**Report SHA-256:** `a0689b45d3b387be1292f7d71ab6295c3743ea848be4d37e18b44cf74e4e911d`+**Witness stamp:** `f9d26aa1ca90ededce81732910bb237da44c7c7ead36e10181b0732b850393e1`++*Verifier: fetch raw gist, sha256sum the file, concatenate (hash||commit) via `printf '%s%s' <hash> <commit> | sha256sum` β must equal Witness stamp.*++---++## Recommended Next Steps++1. **Implement IB+VQ inter-agent message compression in SendMessage** (ADR-321): route all inter-agent payloads through an information-bottleneck encoder with vector quantization codebook (256β1024 codes). Target: replicate ICRA 2026's 181.8% task gain at Ruflo's current 8-agent scale before extending to 16-agent swarms. Validate against a new `swarm-messaging-bench` suite.++2. **Add tensor-train topology reconfiguration** (implement after ADR-321): replace static Raft topology with SPIN-style tensor-train joint-action decomposition. This unblocks scaling beyond 8 agents without exponential coordination cost. Checkpoint: `swarm init --topology spin-tensor` with benchmarked overhead at 8, 16, 32 agents.++3. **Wire ruvector to expose a native MCP endpoint** and evaluate Weaviate Engram architecture for cross-session memory: the Weaviate MCP GA creates a risk that teams default to Weaviate+Claude Code directly, bypassing AgentDB. Adding `ruvector mcp start` as a first-class command (analogous to `claude mcp add`) closes this competitive gap within one sprint.diff --git a/docs/dream-cycles/2026-07-20-performance-sota.md b/docs/dream-cycles/2026-07-20-performance-sota.mdnew file mode 100644index 0000000000..73b608365c--- /dev/null+++ b/docs/dream-cycles/2026-07-20-performance-sota.md@@ -0,0 +1,78 @@+# Performance SOTA Report β 2026-07-20++**TL;DR:** World-model agent planners achieve 14Γ training speedup + 3β6Γ inference speedup in 2026 (Grade A), while the Ruflo Flash Attention claim remains unverified and framework throughput is unmeasured vs competitors delivering 84% more rps.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| DSWorld world-model: 14Γ RL agent training speedup, 3β6Γ search inference speedup by simulating tool outcomes | arXiv:2607.15901 (ICRA-style 2026 preprint) | **A** |+| AutoAgents-Rust: 4.97 rps vs LangGraph Python 2.70 rps β 84% throughput gain from static-typed Rust orchestration | dev.to/saivishwak (2026 benchmark, cross-checked with n1n.ai report) | **B** |+| Framework choice moves agent benchmark performance by up to 30 percentage points on identical models | tensoria.fr/en/blog (2026, qualitative) | **C** |+| SEED self-evolving distillation: dense token-level supervision from hindsight skills improves performance + sample efficiency on agentic tasks | arXiv:2607.14777 (2026 preprint) | **A** |+| LangGraph P95 latency: 16,891 ms; orchestration adds ~50β100 ms over raw LLM calls (5.7β7 s) | mcp-server-langgraph.mintlify.app benchmarks + aerospike.com | **B** |+| VideoTreeSearch (VTS): self-correcting hierarchical search +12.5 mIoU via explicit backtracking over prior agentic baselines | arXiv:2607.16189 (2026) | **A** |+| CrewAI carries 3Γ token overhead of LangGraph on simple workflows | topuzas.medium.com / dev.to (2026 showdown) | **C** |++---++## Ruflo Current Capability++| Area | Ruflo State |+|------|-------------|+| Flash Attention speedup | 2.49Γβ7.47Γ claimed β **explicitly unverified** in CLAUDE.md; no benchmark exists |+| MCP response target | <100 ms β **target, not measured** |+| CLI startup target | <500 ms β **target, not measured** |+| Framework throughput | Not benchmarked vs LangGraph / AutoGen / CrewAI |+| Agent task planning | Reactive execution only β no world-model pre-simulation |+| Token efficiency | 3-tier routing (ADR-026/ADR-143) but savings vs competitors unmeasured |+| HNSW search | Measured ~1.9Γ at N=20k, ~3.2Γβ4.7Γ at N=5k β **verified** |++---++## Competitor Comparison++| Framework | Throughput (rps) | P95 Latency | Token Overhead | World-Model Planning |+|-----------|-----------------|-------------|----------------|---------------------|+| **Ruflo** | Not benchmarked | Not benchmarked | 3-tier routing (B) | None |+| **LangGraph** | 2.70 rps (B) | 16,891 ms (B) | Baseline | None |+| **AutoAgents (Rust)** | 4.97 rps (B) | Not reported | Lower than LangGraph (C) | None |+| **AutoGen** | Slowest of four (C) | Not reported | High consensus overhead (C) | None |+| **CrewAI** | Not reported | Not reported | 3Γ vs LangGraph (C) | None |+| **OpenAI Swarm** | Lowest latency (C) | Not reported | Lowest overhead (C) | None |++*All competitor figures are 2026 third-party benchmarks. "C" = single source, unconfirmed.*++---++## Benchmarks++| Benchmark | Value | Grade | Source |+|-----------|-------|-------|--------|+| DSWorld 14Γ RL training speedup | Measured on 8,000-scale transition trajectory dataset vs LLM baseline (+35.6% transition prediction) | **A** | arXiv:2607.15901 |+| DSWorld 3β6Γ search inference speedup | Same paper, search-based inference path | **A** | arXiv:2607.15901 |+| AutoAgents-Rust 4.97 vs LangGraph 2.70 rps | Cross-checked dev.to + n1n.ai 2026 reports | **B** | dev.to/saivishwak |+| LangGraph orchestration overhead | ~50β100 ms for complex workflows | **B** | mcp-server-langgraph.mintlify.app |+| Ruflo Flash Attention | **No 2026 benchmark data available** β claim must be labeled unverified until measured | β | CLAUDE.md audit |++---++## SOTA Proof & Witness++**Session commit:** `12ede21767a6dd669df1b79392a5d27d9154f237`+**Report SHA-256:** `0faf7a674d8a74ad9e7c309b8b9e0e8db9ca683cb5bfc752f2d8fd0b3899713f`+**Witness stamp:** `761ca053e5b55bdbf5205e7da61c61bdb8758d8659596f461b341346746d5d1c`++*Verifier: `sha256sum /path/to/dream-gist-2026-07-20.md` β concat with session commit β `sha256sum` β must equal Witness stamp.*++---++## Recommended Next Steps++1. **Implement a lightweight world-model planner for Ruflo agents** (ADR-322): before executing expensive multi-step tool chains, agents simulate outcomes using a cost-aware routing + transition predictor (DSWorld pattern). Target: 3β6Γ reduction in wasted real-tool calls during planning. Scope: new `@claude-flow/planning` module; `hooks pre-task` triggers planner when task has β₯3 estimated tool calls.++2. **Run a Ruflo throughput benchmark vs LangGraph** (one sprint): instrument `claude-flow start` with `autocannon` or `wrk` targeting the MCP stdio/HTTP layer; publish results. Current unverified Flash Attention and <100 ms MCP claims become Grade A or are retracted. Without this, marketing claims are Grade C.++3. **Compress SendMessage payload with token budget enforcement** (security Γ performance overlap): each `SendMessage` call should enforce a configurable token budget (default 512 tokens) and optionally apply a lightweight compression pass (TF-IDF keyword extraction). Addresses OWASP ASI07 (inter-agent channel) and reduces orchestration overhead on busy swarms.diff --git a/docs/dream-cycles/2026-07-21-security-sota.md b/docs/dream-cycles/2026-07-21-security-sota.mdnew file mode 100644index 0000000000..ae823c612b--- /dev/null+++ b/docs/dream-cycles/2026-07-21-security-sota.md@@ -0,0 +1,75 @@+# Security SOTA Report β 2026-07-21++**TL;DR:** Five Grade-A papers from 2026 show that authenticated agents remain hijackable via planning-phase injection and adaptive multi-turn attacks, with Neural Cryptographic Authorization as the emerging architectural solution; no major framework β LangGraph, AutoGen, CrewAI, or OpenAI Swarm β has implemented first-class prompt injection defenses despite OWASP LLM01 ranking it the #1 risk.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| Adaptive Adversaries: stateful multi-turn attackers break all evaluated single-round defenses across tested LLM agents | arXiv (Jul 20, 2026) | **A** |+| PlanFlip: one injection into the Planner's context cascades to corrupt all downstream sub-tasks in multi-agent pipelines | arXiv (Apr/Jul 2026) | **A** |+| Neural Cryptographic Authorization: authenticated agents remain hijackable via IPI even after identity verification; mandatory cryptographic gate before any agentic action is the proposed fix | arXiv (Jul 16, 2026) | **A** |+| MemPoison: adversarial content injected via standard channels persists across turns; compositional + trigger-conditioned attacks bypass all evaluated defenses | arXiv (Jul 16, 2026) | **A** |+| Agent Skill Security: supply-chain attacks operate at repository admission and semantic retrieval stages β before a skill ever executes | arXiv (Jul 15, 2026) | **A** |+| CrewAI 1.15.1 (Jul 2026) patched a real SSRF open-redirect bypass in its built-in scraping tool, enabling agent-driven exfiltration of internal endpoints via crafted URLs | GitHub releases (Jul 2026) | **B** |++---++## Ruflo Current Capability++| Area | State |+|------|-------|+| Prompt injection (OWASP LLM01) | `@claude-flow/security` InputValidator + ADR-178 RepE detection (Proposed, not shipped) |+| Memory security | ADR-178 VMG proposed but unimplemented; MemPoison compositional blindspots unaddressed |+| Planning-phase guards | None β no injection validation at the planner boundary before sub-task distribution |+| Adaptive adversary resistance | None β hooks are single-round; no stateful attacker modeling |+| Cryptographic action gating | None β no Neural Cryptographic Authorization layer in hooks or security module |+| Skill supply-chain admission | ADR-165 proposes plugin signing; skill-lifecycle admission checks absent |+| Code execution sandboxing | None equivalent to AutoGen Docker-default |++---++## Competitor Comparison++| Framework | Version (Jul 2026) | Prompt Injection Defense | Sandboxing | Supply-Chain Auth | SSRF Fix | Human Gate |+|-----------|---------------------|--------------------------|------------|-------------------|----------|------------|+| **Ruflo** | 3.32.9 | RepE ADR-178 (proposed) | None | ADR-165 (proposed) | None | None |+| **LangGraph** | 1.2.9 | None | None | None | None | None |+| **AutoGen** | v0.7.5 | None | Docker-default β | None | None | `approval_func` β |+| **CrewAI** | 1.15.5 | None | None | Skill registry auth β | Fixed β | None |+| **OpenAI Swarm** | No releases | None | None | None | None | None |++*OWASP LLM Top 10 (2025): LLM01 Prompt Injection, LLM03 Supply Chain, LLM06 Excessive Agency, LLM08 Vector/Embedding Weaknesses β none of the four competitors have first-class LLM01 defenses at the orchestration layer.*++---++## Benchmarks++| Claim | Value | Grade | Source |+|-------|-------|-------|--------|+| Multi-turn adaptive attacks defeat all single-round defenders | Defender success rate collapses under stateful pivot attacker | **A** | arXiv Adaptive Adversaries (Jul 20, 2026) |+| PlanFlip cascade amplification via Planner context injection | Corrupts all downstream sub-tasks from a single injected payload | **A** | arXiv PlanFlip (Apr/Jul 2026) |+| MemPoison compositional trigger attacks bypass all defenses | Structural blind spots confirmed across full retrieval/execution lifecycle | **A** | arXiv MemPoison (Jul 16, 2026) |+| OWASP LLM01 = #1 risk; no framework ships orchestration-layer defenses | Audit of LangGraph, AutoGen, CrewAI, OpenAI Swarm β all absent | **A** | OWASP 2025 + competitor audit (Jul 2026) |++---++## SOTA Proof & Witness++**Session commit:** `26c35b59b40a0a95b286ccf5ac675a15edcc995f`+**Report SHA-256 (pre-stamp):** `5d839212c46a9600b6c329e95a91ffa058144c58381387564ecd3e87858b9bf6`+**Witness stamp:** `e455247f1a0e55eff837b4a8cecf6ac59aa4ec709fa6ffb28b2c6638251a0baa`++*Verifier: sha256sum the pre-stamp file, concat with session commit, sha256 β must equal Witness stamp.*++---++## Recommended Next Steps++1. **Implement Neural Cryptographic Authorization (NCA) gate** (ADR-320): before `pre-task` hooks allow tool execution, compute a neural intent signature and require cryptographic proof of authorization chain. Pattern from arXiv Jul-16-2026 "From Neural Intent to Cryptographic Authorization: Governing Agentic Workflows". Scope: `@claude-flow/security` NCA middleware + `@claude-flow/hooks` pre-task integration. Ships alongside ADR-178 RepE detection as complementary layers (detect + prevent).++2. **Harden the planning-phase against PlanFlip injection**: wrap the task planner (`hooks pre-task`) with an isolation boundary β strip any injected `<tool_call>` or `<agent_instruction>` patterns from retrieved context before distribution to sub-agents. Labels: OWASP LLM01 + LLM06 mitigation.++3. **Ship ADR-178 RepE IPI detection** (filed 2026-07-06, still Proposed): the MemPoison paper confirms structural blindspots worsen over time. Assign to `@claude-flow/hooks` background worker `audit` β add hidden-state entropy monitoring at the tool-input position. Target: one sprint to move ADR-178 from Proposed to Accepted with a concrete implementation PR.diff --git a/docs/dream-cycles/2026-07-22-intelligence-sota.md b/docs/dream-cycles/2026-07-22-intelligence-sota.mdnew file mode 100644index 0000000000..a39c7eb9d3--- /dev/null+++ b/docs/dream-cycles/2026-07-22-intelligence-sota.md@@ -0,0 +1,81 @@+# Intelligence SOTA Report β 2026-07-22++**TL;DR:** In 2026, agent intelligence is bifurcating into query-type routing (dispatch factoid vs. multi-hop vs. synthesis to specialized pipelines) and intrinsic metacognition (agents modifying their own learning process). Ruflo has neither; the gap is architecturally addressable with one new module.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| Supra Cognitive Modes (SCM): routed memory architecture scores 84.87% LoCoMo, 86.00% LongMemEval via frozen classifier dispatching queries to lexical+dense, graph multi-hop, or synthesis paths | arXiv 2607.19096, July 21 2026 | B β self-reported, single paper, no independent repro yet |+| Single-agent LLMs outperform multi-agent systems on multi-hop reasoning under equal token budgets | arXiv 2606.13003, June 2026 | B β arXiv, results on standard benchmarks |+| HyperAgents (META/UBC/Oxford/NYU): intrinsic metacognitive self-improvement β agents modify their own modification procedure, transferring learned improvement strategies across novel domains | March 2026, published research | B β multi-institution, cross-domain transfer demonstrated |+| ResearchArena: training-data sabotage is caught <50% of the time by state-of-art monitors even with artifact execution access | arXiv 2607.19321, July 21 2026 | B β dedicated benchmark, four task types |+| OSWorld computer-use SOTA at ~38% as of April 2026 | benchmarkingagents.com | C β single aggregator source |+| CrewAI v1.12: hierarchical memory isolation, Qdrant Edge backend, 60% Fortune 500 adoption | CrewAI release notes 2026 | B β vendor claim, corroborated by multiple outlets |+| LangGraph v1.1.3 GA: per-node timeouts, durable streaming, powers Klarna/Uber/LinkedIn | LangGraph release notes 2026 | B β vendor claim, corroborated |+| AG2 Beta redesign: event-driven, streaming, dependency injection β AutoGen in maintenance mode | AG2 blog 2026 | B β confirmed by Microsoft |+| Zep Graphiti: 63.8% on LongMemEval temporal retrieval sub-task | mem0.ai state-of-memory-2026 | C β single benchmark source, vendor |++---++## Ruflo Current Capability++| Feature | Status | Evidence |+|---------|--------|----------|+| HNSW vector search | Active | Measured ~1.9Γβ4.7Γ vs brute force at N=5kβ20k |+| SONA adaptation | Active | 0.0043ms/adapt, target <0.05ms met |+| MoE routing (model selection) | Active | Gate confidence 0.13β0.88 after rewards |+| Query-type cognitive mode routing | **Absent** | No dispatcher for factoid vs. multi-hop vs. synthesis |+| Intrinsic metacognitive loop | **Absent** | SONA adapts task behavior; does not modify its own adaptation heuristics |+| LongMemEval tracked benchmark | **Absent** | ADR-088 adds evaluation but no tracked CI score |+| Training-data sabotage detection | **Absent** | No equivalent to ResearchArena monitoring |++---++## Competitor Comparison++| Competitor | Intelligence Routing | Long-Term Memory | Published Benchmark Score | 2026 Status |+|-----------|---------------------|-----------------|--------------------------|-------------|+| LangGraph v1.1.3 | Per-node timeout + durable streaming | None built-in (external) | No LongMemEval published | GA, production at Klarna/Uber |+| CrewAI v1.12 | Role-based hierarchical isolation | Qdrant Edge backend | No LongMemEval published | 60% Fortune 500, 44k stars |+| AG2 (AutoGen) Beta | Event-driven typed tools | None built-in | No LongMemEval published | AutoGen maintenance mode |+| OpenAI Swarm | Composable self-organizing | None built-in | No intelligence benchmark | Research-only, no production release |+| SCM (research) | Frozen classifier β 3 specialized pipelines | Full episodic + graph | 86.00% LongMemEval (B-grade) | Academic, July 2026 |+| **Ruflo** | MoE model routing (not query-type) | HNSW + AgentDB | Not tracked on LongMemEval | Needs CMR module |++---++## Benchmarks++| Benchmark | SOTA Score (2026) | Who | Grade | Ruflo Score |+|-----------|-------------------|-----|-------|-------------|+| LongMemEval | 86.00% | SCM (arXiv 2607.19096) | B | Not tracked |+| LoCoMo factoid | 84.87% | SCM | B | Not tracked |+| MemoryAgentBench (MAB) | 61.49% | SCM | B | Not tracked |+| LongMemEval temporal | 63.8% | Zep Graphiti | C | Not tracked |+| OSWorld (computer-use) | ~38% | Multiple | C | Not applicable |++**No 2026 grade-A reproducible intelligence benchmark was identified for Ruflo's specific architecture.** Grade-A claim would require independent reproduction of SCM results on public data.++---++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| Session commit | `26c35b59b40a0a95b286ccf5ac675a15edcc995f` |+| Report SHA-256 | `5ab9f7f71551649c97bc683529b2ac767213cb754162b9c148a7b1f8d1e1582b` |+| Witness stamp | `0c59c02c3e855c4907cf7cd9445f61a5624b5b486c4825f6cc9ceab83d1038d7` |+| Verifier | `sha256(report) + session_commit β sha256 = WITNESS` |++---++## Recommended Next Steps++1. **Implement Cognitive Mode Router (CMR)** in `@claude-flow/memory`: add a frozen semantic classifier that routes incoming memory queries to one of three specialized pipelines β (a) lexical+dense factoid lookup, (b) graph multi-hop traversal, (c) long-form synthesis β mirroring SCM's architecture. Track LongMemEval score in CI. Target: match or exceed Zep Graphiti's 63.8% temporal sub-task within 2 sprints.++2. **Add intrinsic metacognitive hook to SONA**: extend the SONA adaptation loop so the agent can evaluate the effectiveness of its own adaptation heuristics (not just task outcomes) and rewrite those heuristics when trajectory confidence is low for β₯5 consecutive rounds. This closes the extrinsicβintrinsic metacognition gap identified by HyperAgents research.++3. **Establish ResearchArena-style sabotage monitor**: given that training-data sabotage evades detection <50% of the time even with artifact execution access, add an integrity verification hook in `@claude-flow/security` that computes and stores a cryptographic manifest of agent-produced artifacts before and after training runs, alerting on divergence exceeding a threshold. This directly addresses the ResearchArena blind spot.diff --git a/docs/dream-cycles/2026-07-23-memory-sota.md b/docs/dream-cycles/2026-07-23-memory-sota.mdnew file mode 100644index 0000000000..af839d3ff7--- /dev/null+++ b/docs/dream-cycles/2026-07-23-memory-sota.md@@ -0,0 +1,80 @@+# Memory SOTA Report β 2026-07-23++**TL;DR:** Budget-Dependent Memory Operator Selection (OAS, 2026) yields +48% task success under tight token budgets and is absent from Ruflo's `@claude-flow/memory`; implementing it is the highest-ROI memory improvement available in July 2026.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| OAS: budget-driven retain-vs-consolidate selection +48% under tight budgets | Kang et al., arXiv 2607.17545 (Jul 2026) | A |+| PRO-LONG programmatic memory +18% on ARC-AGI-3 for long-horizon tasks | Fox et al., arXiv 2607.20064 (Jul 2026) | B |+| Profile-Graph Memory 80.1% on multi-hop retrieval via two-layer profile/residual | Zhu, arXiv 2607.19359 (Jun 2026) | B |+| Supra Cognitive Modes: route lexical/dense/graph/multi-hop from single substrate | Tobkin & Yang, arXiv 2607.19096 (Jul 2026) | B |+| EAR (Exploratory+Assimilating Reflection) +17.9% on long-term recall | Senrayan et al., arXiv 2607.17879 (Jul 2026) | C (single source) |+| MINJA / Chronos Vulnerability: formal taxonomy of memory-injection attacks on stateful agents | Narayan et al., arXiv 2607.19430 (Jul 2026) | A |+| HyMCache: CXL-hybrid memory for TB-scale KV-cache reuse in multi-turn serving | Jang et al., arXiv 2607.18141 (Jul 2026) | B |++---++## Ruflo Current Capability++| Capability | Status | Notes |+|------------|--------|-------|+| HNSW vector search | Active, measured | ~1.9Γ at N=20k, ~3.2Γβ4.7Γ at N=5k vs brute-force |+| Hybrid backend (SQLite + AgentDB) | Active | Persistent, session-scoped |+| Memory consolidation worker | Active (low priority) | Background, no budget awareness |+| Int8 quantization | Active, measured | 3.84Γ compression, cosine 0.99999 |+| RaBitQ quantization | Active, measured | 32Γ compression, 0.60ms/query |+| SONA neural adaptation | Active, measured | 0.0043ms/adapt |+| Budget-Dependent Operator Selection | **Absent** | No retain-vs-consolidate decision by remaining budget |+| Multi-hop graph traversal | **Absent** | HNSW is flat vector space; no relational edges |+| MINJA input validator | **Absent** | No memory-injection defense on store operations |+| Programmatic memory for long-horizon agents | **Absent** | No PRO-LONG-style structured working memory |++---++## Competitor Comparison++| Framework | Memory Architecture | Budget-Aware? | Multi-hop? | MINJA Defense? |+|-----------|--------------------|--------------:|:----------:|:--------------:|+| **Ruflo (current)** | HNSW + SQLite hybrid, SONA, quantized | No | No | No |+| **LangGraph v1.2.9** | DeltaChannel checkpoints (stabilizing bug fixes Jul 2026; no new memory API) | No | No | No |+| **AutoGen v0.7.5** | Pluggable backends: Redis, Mem0, ChromaDB (linear memory via RedisMemory) | No | Via Mem0 (external) | No |+| **CrewAI v1.15.0** | Multi-tiered: short-term, long-term, entity, contextual; swappable backends | No | Partial (entity store) | No |+| **OpenAI Swarm** | Stateless by design; context variables only; no persistence between calls | N/A | No | N/A |++---++## Benchmarks++| Metric | Value | Grade | Source |+|--------|-------|-------|--------|+| OAS retain/consolidate, tight budget | +48% task success | A | Kang et al. 2607.17545 (Jul 2026) |+| PRO-LONG programmatic memory on ARC-AGI-3 | +18% | B | Fox et al. 2607.20064 (Jul 2026); ARC-AGI-3 released Jan 2026 |+| Profile-Graph Memory multi-hop retrieval | 80.1% accuracy | B | Zhu 2607.19359 (Jun 2026); benchmark identity unspecified |+| Ruflo HNSW vs brute-force (N=20k) | ~1.9Γ speedup | A | Internal benchmark, `scripts/benchmark-intelligence.mjs` |+| Ruflo RaBitQ quantization | 32Γ compression, 0.60ms/query | A | Internal benchmark, same script |++---++## SOTA Proof & Witness++**Session commit:** `26c35b59b40a0a95b286ccf5ac675a15edcc995f`++**Report SHA-256:** `f9efd04cbd67eb8aaec989e3e950eb61681472e9e382132dae52d1d23218d961`++**Witness stamp:** `06a20f9a4b6066c215fb31ba003b251d235148a010768d85278efb6000cf610a`++**Verifier:** fetch raw report file, `sha256sum`, concatenate session commit hash (no separator), `sha256sum` β must equal witness stamp.++---++## Recommended Next Steps++1. **Implement OAS in `@claude-flow/memory`** β add a `MemoryOperatorSelector` class that inspects remaining token budget (via cost-tracker hook) and selects `retain` (cheap append) vs `consolidate` (expensive summarize) vs `evict` (drop oldest). Grade-A evidence: +48% under tight budgets (Kang et al. 2607.17545). Target: `v3/@claude-flow/memory/src/operators/budget-selector.ts`.++2. **Add multi-hop graph layer over HNSW** β store entity edges alongside vector embeddings in AgentDB; expose `memory search --multi-hop` flag. Grade-B evidence: Profile-Graph Memory 80.1% vs. flat vector retrieval on relational queries (Zhu 2607.19359). Target: `v3/@claude-flow/memory/src/graph/entity-graph.ts`.++3. **Add MINJA defense in `@claude-flow/security`** β validate all `memory store` inputs for injection patterns (oversized payloads, prompt-injection fragments, sleeper triggers) before writing to AgentDB. Grade-A taxonomy: Chronos Vulnerability (Narayan et al. 2607.19430). Target: `v3/@claude-flow/security/src/validators/memory-input.ts`.diff --git a/docs/dream-cycles/2026-07-24-swarm-sota.md b/docs/dream-cycles/2026-07-24-swarm-sota.mdnew file mode 100644index 0000000000..d734e99bf5--- /dev/null+++ b/docs/dream-cycles/2026-07-24-swarm-sota.md@@ -0,0 +1,82 @@+# Swarm Orchestration SOTA Report β 2026-07-24++**TL;DR:** In 2026, swarm orchestration research confirms that dynamic topology selection beats static, hierarchical BFT consensus scales to 990 agents with 97% fault tolerance, and the primary subagent management bottleneck is privilege grantingβnot task qualityβexposing a critical gap in Ruflo's swarm permission model.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| SWARM+ scales to 990 agents, 97% completion under distributed failures, 97-98% selection time reduction | arXiv 2603.19431 (FABRIC testbed, production traces) | **A** |+| ClawArena-Team: no LLM model exceeded 50% workspace-permission precision across 41 orchestration scenarios | arXiv 2606.31174, 258 eval rounds | **A** |+| Privilege granting (not perception) is primary management bottleneck for LLM team leads | arXiv 2606.31174 | **A** |+| Adaptive topology (task-dependency-graph selection) yields 12-23% over static baselines | AdaptOrch, single vendor report | **B** |+| Swarm-mesh-8agents achieves 85.2% success rate, outperforming equivalent hierarchical topologies | Framework comparison benchmark 2026 | **B** |+| MAS-PromptBench: prompt optimization helps single agents 15-30%, gains collapse in multi-agent coordination | arXiv 2606.23664 | **A** |++---++## Ruflo Current Capability++| Capability | State | Notes |+|-----------|-------|-------|+| Topology selection | Static at init | hierarchical, mesh, adaptive options but set once |+| Raft consensus | Active | Leader-based, handles f < n/2 failures |+| Byzantine fault tolerance | Via `byzantine-coordinator` agent | Not default for swarm init |+| Subagent permission model | None | No workspace-permission delegation protocol |+| Swarm benchmark suite | None | No ClawArena-equivalent for Ruflo |+| HNSW search (ruvector) | Local NAPI, ~1.9x at N=20k | No external DB connector (Qdrant/Weaviate/Milvus) |+| ruview integration | Harness vertical template only | No dedicated ruview-swarm plugin |++---++## Competitor Comparison++| Framework | Topology | Fault Tolerance | Permission Model | Scale | 2026 Benchmark |+|-----------|----------|-----------------|------------------|-------|----------------|+| **SWARM+** | Hierarchical BFT, O(log n) | 97% job completion under 50% node loss | Consensus-gated delegation | 990 agents | A-grade FABRIC testbed |+| **LangGraph** | Graph-based DAG | Retry/checkpoint | Node-level permissions | Enterprise-scale | Largest production footprint 2026 |+| **AG2 (AutoGen v0.4)** | Event-driven, async | Strong for multi-turn | Pluggable strategies | Research-scale | Best complex negotiation |+| **CrewAI** | Role-based sequential/parallel | Limited recovery | Task-level scope | Medium-scale | 30-60% faster than AutoGen, simple tasks |+| **OpenAI Agents SDK** | Handoff graph | Sandbox isolation | Tool-scope permissions | Production | Evolved from Swarm experimental |+| **Ruflo** | Hierarchical/mesh/adaptive (static) | Raft + optional BFT | None (gap) | 8-agent default | No external benchmark |++---++## Benchmarks++| Metric | Value | Source | Grade |+|--------|-------|--------|-------|+| SWARM+ job completion under 50% agent loss | 97% | arXiv 2603.19431, FABRIC testbed | **A** |+| SWARM+ selection time reduction vs SWARM | 97-98% | arXiv 2603.19431 | **A** |+| ClawArena-Team max permission precision | <50% across all tested LLMs | arXiv 2606.31174, 258 rounds | **A** |+| AdaptOrch dynamic topology vs static | +12-23% | Vendor report | **B** |+| Ruflo HNSW vs brute force (N=20k) | ~1.9x | scripts/benchmark-intelligence.mjs | **A** |+| Qdrant p99 latency (10M vectors) | ~12ms vs Weaviate ~16ms, Milvus ~18ms | Multi-vendor benchmark 2026 | **B** |+| ruvector external DB integration | Not available | No connector exists | β |++**Scan: ruvector-integration** β Qdrant dominates open-source at 10-25% faster p99 than Weaviate or Milvus for <10B vectors; Milvus wins at billion-scale with GPU acceleration. Ruflo's ruvector NAPI backend has no external connector, capping scale to local SQLite+HNSW.++**Scan: ruview-integration** β `vertical:ruview` exists as a metaharness template (plugins/ruflo-metaharness/skills/harness-mint/SKILL.md) but no dedicated swarm-backed ruview integration plugin exists. LangGraph and CrewAI both ship built-in code review agent roles.++---++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| Session commit | `26c35b59b40a0a95b286ccf5ac675a15edcc995f` |+| Report SHA-256 | `56f2500749caa5bdbf3ffdb472318b3d478c6d72ee62b80d60dbb13cdbae5c30` |+| Witness stamp | `4b6fc6e694c51dffa78074bb03d71ff3a8c178b50fa9745f3de0ac1ba123e5e8` |+| Verifier | `sha256(report_sha256 + session_commit)` |++---++## Recommended Next Steps++1. **Implement SubagentPermissionDelegate protocol (ADR-320):** ClawArena-Team shows privilege granting is the #1 bottleneck β add workspace-scoped token delegation to `swarm init` so each subagent receives a least-privilege capability set. Target: lift swarm permission precision from ~0% (unmeasured) to >50% on ClawArena-style eval.++2. **Add dynamic topology auto-selection to `swarm init --v3-mode`:** Current static topology choice at init time leaves 12-23% performance on the table (AdaptOrch). Wire a dependency-graph analyzer on the task payload to select hierarchical vs mesh vs adaptive before spawning agents.++3. **Add ruvector external-DB connector (Qdrant first):** ruvector's local NAPI backend caps at SQLite scale. Add a `--backend qdrant` flag to `memory search` / `embeddings search` using Qdrant's REST API, enabling scale-out to 10M+ vectors at Qdrant's proven <12ms p99 latency without changing the HNSW interface contract.diff --git a/docs/dream-cycles/2026-07-25-performance-sota.md b/docs/dream-cycles/2026-07-25-performance-sota.mdnew file mode 100644index 0000000000..2ceeb36f79--- /dev/null+++ b/docs/dream-cycles/2026-07-25-performance-sota.md@@ -0,0 +1,62 @@+# Performance SOTA Report β 2026-07-25++**TL;DR**: AA-AgentPerf (June 2026, Grade A) establishes 23.6Γ hardware efficiency gap (61,354 vs 2,594 Agents/MW) and ACL 2026 Pareto-optimal research proves mixture-of-agents beats self-consistency by +2.7pp β Ruflo benchmarks neither.++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| AA-AgentPerf: first agentic inference benchmark, Agents/MW metric; GB300 = 61,354 vs H200 = 2,594 (23.6Γ gap) | Artificial Analysis, Jun 12 2026 | **A** |+| Mixture-of-agents Pareto-optimal: +2.7pp over self-consistency on MMLU-Pro; most efficient when parallel > sequential | arXiv 2605.01566, ACL 2026 SRW | **A** |+| RecursiveMAS: 1.2β2.4Γ inference speedup, 34.6β75.6% token reduction, +8.3% accuracy across 9 benchmarks | arXiv 2604.25917 | **B** |+| AutoAgents-Rust: 4.97 rps vs LangGraph 2.70 rps (+84%); CrewAI 44% failure rate excluded | dev.to/saivishwak, Feb 2026 | **B** |+| Mixture-of-agents at 20Γ CoT budget yields +7.1% MMLU-Pro over chain-of-thought baseline | arXiv 2605.01566, ACL 2026 SRW | **A** |++## Ruflo Current Capability++| Capability | Status | Notes |+|-----------|--------|-------|+| Agent inference benchmark | β No AA-AgentPerf registration | `performance benchmark --suite all` exists but no Agents/MW metric |+| Test-time compute scaling | β Absent | No mixture-of-agents routing config; 3-tier routing is cost-only |+| Flash Attention speedup | β Unverified | CLAUDE.md: "unverified β no benchmark exists for this claim" |+| MCP response target | β οΈ Unmeasured | <100ms target set but no CI gate |+| Framework throughput | β οΈ Unbenchmarked | No public rps/latency numbers |++## Competitor Comparison++| Framework | Throughput (rps) | P95 Latency (ms) | Failure Rate | Test-Time Scaling | Agents/MW |+|-----------|:----------------:|:----------------:|:------------:|:-----------------:|:---------:|+| **Ruflo** | Unbenchmarked | Unbenchmarked | Unknown | None | Not registered |+| LangGraph | 2.70 (B) | 16,891 (B) | 0% | None | Not registered |+| AutoGen/AG2 | ~2.0 (C) | ~15,000 (C) | Low | Self-refine (B) | Not registered |+| CrewAI | Excluded (B) | β | 44% (B) | None | Not registered |+| OpenAI Swarm | Lowest latency (C) | β | Low (C) | None | Not registered |+| AutoAgents-Rust | 4.97 (B) | 9,652 (B) | 0% | None | Not registered |++*(B = vendor/dev benchmark 2026; C = single source)*++## Benchmarks++| Benchmark | Key Number | Grade | Reference |+|-----------|-----------|-------|----------|+| AA-AgentPerf GB300 | 61,354 Agents/MW | **A** | Artificial Analysis Jun 2026 |+| AA-AgentPerf H200 | 2,594 Agents/MW | **A** | Artificial Analysis Jun 2026 |+| Mixture-of-agents MMLU-Pro | +7.1% over CoT @ 20Γ budget | **A** | arXiv 2605.01566, ACL 2026 |+| RecursiveMAS speedup | 1.2β2.4Γ end-to-end | **B** | arXiv 2604.25917 |+| AutoAgents-Rust vs LangGraph | +84% throughput | **B** | dev.to Feb 2026 |++## SOTA Proof & Witness++**Session commit:** `26c35b59b40a0a95b286ccf5ac675a15edcc995f`+**Report SHA-256:** `8f7e3d612e5d165f64a2beb23bc314153dc016e1ee479185d63107294c9cd9e5`+**Witness stamp:** `e88eb2c46dc489827e399c0a0309590f04e635884ed183d84cac9436106cad45`++Verifier: `sha256sum report.md` β strip newline β concat session commit β `sha256sum` β must equal Witness stamp.++## Recommended Next Steps++1. **Register Ruflo in AA-AgentPerf** (ADR-320): Add `performance benchmark --suite agentperf` subcommand that replays agentic trajectories and reports Agents/MW metric. Target β₯5,000 Agents/MW on standard dev hardware as a CI gate. This closes the single largest credibility gap vs verifiable external benchmarks.++2. **Implement mixture-of-agents routing** in 3-tier model config (ADR-026): When `estimatedParallelAgents > estimatedSequentialAggregations`, activate mixture-of-agents path. ACL 2026 Grade A evidence shows +2.7pp over self-consistency at equal compute cost. The hook point is `hooks route` β tier selection.++3. **Benchmark and gate Flash Attention in CI**: Run `performance benchmark --suite flash-attention` in each PR that touches the attention layer. Ship a Grade A number or remove the unverified claim from CLAUDE.md. Ongoing unverified claim degrades trust in the performance section.diff --git a/docs/dream-cycles/2026-07-27-intelligence-sota.md b/docs/dream-cycles/2026-07-27-intelligence-sota.mdnew file mode 100644index 0000000000..dc8aeef44c--- /dev/null+++ b/docs/dream-cycles/2026-07-27-intelligence-sota.md@@ -0,0 +1,75 @@+# Intelligence SOTA Report β 2026-07-27++**TL;DR:** Heterogeneous multi-agent ensembles (PoTRE, 49.92% on Humanity's Last Exam) and programmatic memory compression (PRO-LONG, +18pp on ARC-AGI-3) define 2026 agent-intelligence SOTA. EWC++ continual learning and SONA self-optimization remain absent from every major competitor, making them Ruflo's sharpest differentiators.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| PoTRE (Poly-Topological Reasoning Ensembles): 4 heterogeneous agents with task-adaptive aggregation achieve **49.92% on Humanity's Last Exam** | arXiv 2607.x, Kankariya & ArΔ±k (July 22, 2026) | A |+| PRO-LONG (Programmatic Memory): structured interaction logs yield **+18pp on ARC-AGI-3**; **97.4% best@2 with Claude Fable 5** at $1,750 total cost; 4.2β5.8Γ fewer tokens than specialized harnesses | arXiv 2607.x, Fox et al. (July 23, 2026) | A |+| HierFlow (MCTS-inspired topology synthesis): beats baselines on QA, math, and code using 4.2β5.8Γ fewer tokens | arXiv 2607.x, Li et al. (July 19, 2026) | A |+| AREX (Recursive Self-Improving Research Agent): inner-evidence / outer-audit loop outperforms comparable baselines on BrowseComp, WideSearch, DeepSearchQA | arXiv 2607.x (July 23, 2026) | B |+| Agentic context compaction (Maximem Synap): reduces token growth from quadratic to linear; reports **92% LongMemEval, 93.2% LoCoMo** | Vendor claim (July 2026) | C |++---++## Ruflo Current Capability++| Component | Status | Measured Result |+|-----------|--------|----------------|+| MoE gate (8 experts) | Active | Confidence 0.13 β 0.88 after reward shaping |+| SONA self-optimization | Active | 0.0043ms/adapt (target <0.05ms met) |+| HNSW vector search | Active | ~1.9Γ at N=20k, ~3.2β4.7Γ at N=5k vs brute force; recall@10 ~0.99 |+| EWC++ continual learning | Active | Anti-forgetting layer on weight updates |+| Flash Attention | Integration available | Speedup not yet benchmarked in-tree |+| Heterogeneous ensemble composition | Gap | No PoTRE-style multi-topology ensemble API exists |+| Programmatic structured memory logs | Gap | No PRO-LONG-style interaction log compression |++---++## Competitor Comparison++| Framework | Version (2026) | Intelligence Features | Gap vs Ruflo |+|-----------|---------------|----------------------|--------------|+| **LangGraph** | v1.2.7βv1.2.9 | DeltaChannel incremental checkpoints; per-node timeouts; typed streaming API v3; defaults to claude-sonnet-5 / gpt-5.5 | No MoE routing, no HNSW, no EWC++ |+| **Microsoft Agent Framework** | 1.0 GA (April 2026) | Merges AutoGen + Semantic Kernel; async event-driven; CodeAct paradigm; Hosted Agents managed sandbox | No native vector search, no continual learning |+| **CrewAI** | v1.14.3 (April 24, 2026) | Sequential / Hierarchical / Consensual process modes; checkpoint restore; Snowflake Cortex native | No self-optimizing substrate, no HNSW |+| **OpenAI Swarm** | Frozen | Repositioned as educational reference; superseded by Agents SDK (March 2025); no 2026 intelligence updates | Deprecated; no competition |++---++## Benchmarks++| Benchmark | SOTA Score | System | Grade |+|-----------|-----------|--------|-------|+| Humanity's Last Exam | **49.92%** | PoTRE ensemble | A |+| ARC-AGI-3 | **97.4% best@2** | PRO-LONG + Claude Fable 5 | A |+| GAIA | 80.7% | Inspect ReAct Agent | B |+| SWE-bench Verified | 80%+ | Frontier models (Gemini 2.5 Pro) | B |+| LongMemEval | 92% (vendor) | Maximem Synap | C |+| Ruflo HNSW recall@10 | ~0.99 | ruvector NAPI backend | A (measured in-tree) |++---++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| Session commit | `6b6eef90cf381c147aba6bbdfb29f1f11a2d3bdb` |+| Report SHA-256 | `17df4112c9cb7a094317bf5cb7d6d20add8b0f0baed087b3b5b682d95421e0b1` |+| Witness stamp | `c1e3c26939346355723d56a2eda3b55eb4c306b7843333abbf5c1ceeb7ef7dbf` |++**Verification:** `sha256(report_sha256 + session_commit) == witness_stamp`++---++## Recommended Next Steps++1. **Implement PoTRE-style Heterogeneous Ensemble API** (ADR-320): Add a `SwarmTopology::heterogeneous` mode that allows 3β5 agents with distinct reasoning strategies (adversarial, hierarchical, spectrum-search, direct chain) plus a task-adaptive aggregation layer. Target: parity with PoTRE's 49.92% HLE on in-tree benchmark suite.++2. **Add PRO-LONG Programmatic Memory Layer**: Extend the AgentDB memory schema to store structured interaction logs (not just vector embeddings). Expose a `memory compress --programmatic` subcommand that applies log-level compression before vector encoding. Estimated token reduction: 4Γ per session based on PRO-LONG paper data.++3. **Publish Ruflo Intelligence Benchmark Suite**: Wire HumanityLastExam, ARC-AGI-3 (subset), GAIA, and LongMemEval into `npx ruflo performance benchmark --suite intelligence` so each release has a grade-A scored comparison row against competitors. This closes the credibility gap vs PoTRE/PRO-LONG claims.diff --git a/v3/docs/adr/ADR-334-hierarchical-consensus-topology.md b/v3/docs/adr/ADR-334-hierarchical-consensus-topology.mdnew file mode 100644index 0000000000..e1d3089859--- /dev/null+++ b/v3/docs/adr/ADR-334-hierarchical-consensus-topology.md@@ -0,0 +1,61 @@+# ADR-334: Hierarchical Consensus Topology for Large-Scale Swarm Coordination++**Status**: Proposed+**Date**: 2026-05-29+**Authors**: claude (dream-cycle agent, 2026-05-29)+**Issue**: [ruvnet/ruflo#TBD](https://github.com/ruvnet/ruflo/issues/)+**Related**: ADR-103 (witness temporal history), ADR-104 (federation wire transport)++## Context++Ruflo's hive-mind currently uses flat Raft consensus: one leader, N workers, O(NΒ²) message complexity in the worst case. The configured maximum is 8 agents (CLAUDE.md anti-drift default). This ceiling is a product of the protocol, not the hardware.++The 2026 research literature has converged on two complementary improvements:++**SWARM+** (arXiv:2603.19431, March 2026, Grade A): Adapts PBFT for distributed workload management via a two-tier hierarchy β a small *coordinator group* (3-5 nodes) runs Byzantine-tolerant consensus among themselves, then delegates shards of the task space to *worker clusters* that use lightweight crash-fault Raft internally. Benchmarked at 1,000 agents with 97-98% scheduling latency improvement over flat baseline and β€7.5% degradation under 50% agent failure.++**SwarmHarness** (arXiv May 2026, Grade A): Introduces Shapley-value credit attribution so individual skill nodes are weighted by marginal contribution to recent task outcomes. Without this, flat consensus treats all agents as equivalent β a low-quality agent can veto or slow progress on the same footing as a high-quality one.++Ruflo has no mechanism for either. Adding more than 8 agents today will not improve throughput; it may degrade it due to Raft leader bottleneck.++## Decision++Adopt a **two-tier hierarchical consensus topology** for hive-mind swarms with `agentCount > 20`:++1. **Coordinator tier** (3 or 5 nodes, odd): runs existing Raft for crash-fault tolerance among trusted orchestrator agents. Elected via current `queen-coordinator` logic.+2. **Worker shard tier**: N/shardSize clusters, each β€10 agents, each with an internal shard-leader elected by the coordinator. Intra-shard communication is direct (no consensus); only shard-leader reports to coordinator.+3. **Credit vector**: Each shard-leader maintains a Shapley approximation per agent (task contribution / total tasks). Agents with score < 0.1 over a 20-task window are flagged for replacement.++The existing 8-agent flat Raft path remains unchanged for `agentCount β€ 20` (no regression).++## Consequences++**Positive:**+- Scales to 200+ agents without O(NΒ²) message explosion+- Credit attribution enables quality-weighted task routing+- Validated by SWARM+ at 1,000 agents (Grade A benchmark)+- Backwards-compatible (flat path unchanged below threshold)++**Negative:**+- Increases complexity in `@claude-flow/cli` hive-mind module (~400 LOC addition)+- Shard-leader election adds ~50-100ms to swarm startup above 20-agent threshold+- Shapley credit requires N+1 task completions before first signal (cold-start latency)++**Neutral:**+- No change to MCP tool surface+- No change to memory namespace or AgentDB schema+- `maxAgents: 8` CLAUDE.md default remains correct for anti-drift coding swarms++## Implementation Notes++Target file: `v3/@claude-flow/cli/src/hive-mind/consensus/hierarchical-topology.ts`++Coordinator tier: reuse `RaftManager` (existing). Shard tier: new `ShardCluster` class with `ShardLeader` role. Credit vector: `CreditTracker` using banzhee/sampling approximation to avoid O(2^N) Shapley computation.++Threshold config key: `hiveMind.hierarchicalThreshold` (default: 20). Expose as `--hierarchical-threshold N` CLI flag on `swarm init`.++## References++- arXiv:2603.19431 β SWARM+: Scalable and Resilient Multi-Agent Consensus+- arXiv (May 2026) β SwarmHarness: Skill-Based Task Routing via Decentralized Incentive-Aligned AI Agent Networks+- Dream Cycle Research: `v3/docs/research/dream-cycle-2026-05-29-swarm.md`diff --git a/v3/docs/adr/ADR-335-mv-hnsw-agent-memory-upgrade.md b/v3/docs/adr/ADR-335-mv-hnsw-agent-memory-upgrade.mdnew file mode 100644index 0000000000..4a80979f3f--- /dev/null+++ b/v3/docs/adr/ADR-335-mv-hnsw-agent-memory-upgrade.md@@ -0,0 +1,55 @@+# ADR-335 β Upgrade to Multi-Vector HNSW (MV-HNSW) for Agent Memory Retrieval++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-05-30)+**Related**: ADR-006 (Unified Memory Service), ADR-009 (Hybrid Memory Backend), ADR-017 (RuVector Integration)++## Context++Ruflo's current HNSW backend indexes each memory entry as a single embedding vector. Measured performance is ~1.9Γ vs brute-force at N=20k (ruvector NAPI). A 2026 PVLDB paper (arXiv:2604.02815) introduces MV-HNSW, the first hierarchical graph index native to multi-vector data, and benchmarks 14Γ search-latency reduction at >90% recall across seven real-world datasets.++Agent memory entries are structurally multi-field: they contain an exchange core (semantic summary), a technical detail, thematic room labels, and file-path tags. The current architecture embeds these as a single concatenated vector, losing the structural signal that multi-vector indexing exploits. This means:++1. Recall quality degrades as entries grow semantically diverse (fields pull the embedding in conflicting directions).+2. Query routing cannot target individual fields β every query scans the full compound embedding.+3. The ~1.9Γ speedup sits at the lower end of the ANN benefit regime; MV-HNSW's 14Γ was measured at comparable recall (>90%) on seven datasets including two that model agent-style compound objects.++No existing ADR (085β143) addresses multi-vector indexing for agent memory.++## Decision++Upgrade `v3/@claude-flow/memory/src/hnsw/` to a multi-vector index pattern:++1. **Decompose** each memory entry into its four semantic axes at write time: `core` (1β2 sentence exchange summary), `detail` (technical specifics), `labels` (thematic room tags), `paths` (file-path anchors).+2. **Embed each axis independently** using the existing all-MiniLM-L6-v2 ONNX encoder (384-dim per axis).+3. **Index via MV-HNSW pattern**: maintain a graph over compound objects where proximity is computed as a weighted max-inner-product across the four per-axis vectors. Weights tunable per query type.+4. **Query API**: extend `searchMemory(query, opts)` to accept an optional `axis` filter so callers can target `core` or `paths` axes directly for precision lookups.+5. **Backwards compatibility**: single-vector entries (legacy records) remain queryable via a fallback single-axis path; no migration required for existing entries.++## Consequences++**Positive**+- 14Γ latency reduction at >90% recall is the largest documented search improvement available in 2026 (Grade A, PVLDB).+- Retrieval precision improves on mixed-type queries (file-path lookups no longer polluted by semantic axes).+- Combinable with existing Int8 quantization (3.84Γ) and structured distillation (11Γ) for compounding gains.+- No model change β existing ONNX encoder unchanged.++**Negative / Risks**+- Write path becomes 4 encode calls per entry vs 1 β increased write latency (~4Γ). Acceptable given read-heavy agent memory access pattern.+- Index size grows ~4Γ. Acceptable given existing 32Γ RaBitQ compression option.+- Requires benchmark validation on Ruflo's specific workload (N=20kβ100k) before declaring >90% recall target met. Publish results in `scripts/benchmark-intelligence.mjs`.++## Implementation Targets++| File | Change |+|------|--------|+| `v3/@claude-flow/memory/src/hnsw/index.ts` | Add `MVHNSWIndex` class alongside existing `HNSWIndex` |+| `v3/@claude-flow/memory/src/types.ts` | Add `MultiVectorEntry` type with four axis fields |+| `v3/@claude-flow/memory/src/agentdb.ts` | Route writes to `MVHNSWIndex` when entry has structured fields |+| `scripts/benchmark-intelligence.mjs` | Add `mv-hnsw-recall` benchmark suite |++## References++- arXiv:2604.02815 β MV-HNSW: Multi-Vector Hierarchical Graph Index, PVLDB 17(12) 2026+- arXiv:2603.13017 β Structured Distillation for Agent Memory (complementary: defines the four-field schema)+- `docs/reviews/intelligence-system-audit-2026-05-29.md` β measured HNSW baseline (~1.9Γ at N=20k)diff --git a/v3/docs/adr/ADR-336-agent-authorization-propagation.md b/v3/docs/adr/ADR-336-agent-authorization-propagation.mdnew file mode 100644index 0000000000..e5ea1acd3f--- /dev/null+++ b/v3/docs/adr/ADR-336-agent-authorization-propagation.md@@ -0,0 +1,117 @@+# ADR-336 β Agent Authorization Propagation and MCP Authentication Enforcement++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-05-31)+**Related**: ADR-012 (MCP Security Features), ADR-013 (Core Security Module), ADR-131 (ToolOutputGuardrail), #[tonight's issue]++---++## Context++Three Grade A papers published May 2026 identify a security layer Ruflo currently lacks β authorization propagation across agent delegation chains β that is architecturally distinct from the content-screening gap addressed by ADR-131.++**ADR-131** covers WHAT agents receive (tool output content screening for injected instructions).+**This ADR** covers WHO agents can act as and what they are authorized to delegate.++### Evidence++1. **arXiv:2605.22333** (Grade A, empirical): 40.55% of 7,973 live MCP servers expose tools with zero authentication; 96.6% of OAuth-enabled servers contain β₯1 exploitable flaw. Ruflo registers MCP tools but performs no runtime authentication check on server identity before accepting tool responses.++2. **arXiv:2605.28914 β AIRGuard** (Grade A, controlled benchmark): Runtime authority control at the action execution layer reduces agent attack success from 36.3% to 5.5% (β85%). The key primitive is least-privilege authorization checked per-action, not per-session.++3. **arXiv:2605.05440 β Authorization Propagation** (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 an agent delegates a task via SendMessage, the receiving agent may escalate the granted scope by calling tools or sub-agents the original caller was not authorized to invoke.++4. **arXiv:2605.26497 β Dual-Graph Provenance Defense** (Grade A): Comparing an execution provenance graph against an authorization intent graph reduces indirect prompt injection success from 40% to 1%.++### Current State++`@claude-flow/security` provides:+- `InputValidator` β boundary input validation (Zod-based)+- `PathValidator` β path traversal prevention+- `SafeExecutor` β command injection protection+- `PasswordHasher`, `TokenGenerator` β credential utilities++None of these track authorization scope across agent delegation boundaries, verify MCP server identity, enforce per-action privilege, or produce an execution provenance record.++---++## Decision++Add `AgentAuthorizationPropagator` as a new component in `@claude-flow/security`.++### Component Design++**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+ delegationDepth: number; // max remaining delegation hops+ expiresAt: number; // unix ms+}++interface SendMessageEnvelope {+ scope: AuthScope; // NEW β attached to every SendMessage+ payload: unknown;+}++class AgentAuthorizationPropagator {+ // Attach reduced scope to outbound SendMessage+ wrapOutbound(msg: unknown, currentScope: AuthScope, requestedTools: string[]): SendMessageEnvelope;++ // Validate inbound tool call against current delegation scope+ checkToolCall(toolId: string, scope: AuthScope): { allowed: boolean; reason?: string };++ // Verify MCP server presented valid auth before accepting its response+ verifyServerAuth(serverId: string, credential: unknown): boolean;++ // Record action in provenance log for dual-graph audit+ recordAction(agentId: string, toolId: string, scope: AuthScope, outcome: 'allowed' | 'denied'): void;+}+```++### 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. Check server is in the registered allowlist+2. If server declared OAuth support, verify token validity+3. If server has no declared auth and is not in an explicit unauthenticated-allowed list, reject with `UNAUTHENTICATED_MCP_SERVER` error++### Integration Points++- `v3/@claude-flow/hooks/src/pre-task.ts` β initialize scope on task creation+- `v3/@claude-flow/cli/src/mcp/` β add `auth-validator.ts`, call before tool result processing+- `@claude-flow/security` public API β export `AgentAuthorizationPropagator`++### Backwards Compatibility++- `scope` on SendMessage envelope is optional in v1. Agents without scope set operate in a permissive legacy mode (all tools allowed, depth unlimited). A `CLAUDE_FLOW_STRICT_AUTH=true` env var enables enforcement mode.+- Existing `SafeExecutor` is unchanged.++---++## Consequences++**Positive**+- Eliminates authorization escalation in multi-hop agent delegation+- Provides provenance log for post-incident audit (maps to OWASP ASI07 and dual-graph defense)+- MCP auth validator closes the 40.55% unauthenticated-server exposure+- Targets 85% reduction in action-layer attack success rate (AIRGuard benchmark, Grade A)++**Negative / Trade-offs**+- `scope` field adds ~100 bytes to every SendMessage envelope (negligible vs payload)+- Strict mode may break existing agent pipelines that rely on implicit cross-agent tool access β requires explicit scope grants on upgrade++**Deferred**+- Full dual-graph provenance comparison engine (expensive at runtime) β Phase 2+- Cross-organization delegation (MCP-I / DIF standard) β deferred pending spec maturity++---++## Alternatives Rejected++- **Extend ADR-131 ToolOutputGuardrail**: ADR-131 screens content before it enters reasoning; this ADR controls who is authorized to take actions. They address different layers and must coexist.+- **RBAC on agent roles**: The formal analysis (arXiv:2605.05440) demonstrates RBAC cannot maintain authorization invariants across dynamic delegation chains in LLM agents. Scope-based propagation is the minimum viable solution.diff --git a/v3/docs/adr/ADR-337-plugin-supply-chain-integrity-memory-governance.md b/v3/docs/adr/ADR-337-plugin-supply-chain-integrity-memory-governance.mdnew file mode 100644index 0000000000..5496e4de98--- /dev/null+++ b/v3/docs/adr/ADR-337-plugin-supply-chain-integrity-memory-governance.md@@ -0,0 +1,102 @@+# ADR-337 β Plugin Supply Chain Integrity and Memory Namespace Governance++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-06-01)+**Related**: ADR-004 (Plugin Architecture), ADR-006 (Unified Memory), ADR-013 (Core Security), ADR-015 (Unified Plugin System), ADR-131 (ToolOutputGuardrail β different layer), ADR-144 (Authorization Propagation β different layer), dream-cycle issue #2249++> **Note on ADR numbering**: ADR-144 is proposed in branch `dream/2026-05-31-security` (authorization propagation). This record uses ADR-337 to avoid collision.++## Context++### Threat: Plugin Supply Chain Attacks (June 2026 SOTA)++Two Grade A papers published in AprilβMay 2026 document active supply-chain attacks that bypass all current defenses in Ruflo's plugin system:++**DDIPE** (arXiv:2604.03081, Apr 3, 2026): Document-Driven Implicit Payload Execution embeds malicious logic in plugin documentation and configuration templates. Achieves 11.6β33.5% bypass rate across four frameworks and five models; 2.5% of adversarial skills evade both detection and alignment systems. Four confirmed CVEs were disclosed from this research.++**Semantic Compliance Hijacking β SCH** (arXiv:2605.14460, May 14, 2026): Translates malicious goals into natural-language compliance rules within skill/plugin descriptions. The agent generates harmful code dynamically at runtime β no static payload exists. Achieves **77.67% confidentiality breach** and **67.33% RCE success** with **0.00% detection by current scanning tools**. Signature-based defenses are entirely blind to SCH.++Ruflo's current plugin install path (`v3/@claude-flow/cli/src/plugins/`) fetches from IPFS via Pinata with no signature verification and no semantic intent analysis.++### Threat: Memory Namespace Poisoning++**MINJA** (arXiv:2601.05504, Jan 2026): Memory injection via query-only interaction achieves up to 95% success under idealized conditions. In realistic production environments, success falls to 28β38% for strong models β still unacceptable for a system where compromised memory can redirect agent behavior.++**Mnemonic Sovereignty survey** (arXiv:2604.16548, Apr 2026): Identifies nine governance primitives required for secure long-term agent memory. No existing published architecture satisfies all nine. The core gap in Ruflo: the shared `collaboration` memory namespace (and all AgentDB namespaces) accepts writes from any agent with no per-namespace authorization.++### Why This Is Architectural++This is architecturally distinct from:+- ADR-131 (ToolOutputGuardrail): screens MCP tool *outputs* for injected content at runtime β does not verify plugin integrity before install+- ADR-144 (Authorization Propagation): tracks runtime scope delegation in SendMessage chains β does not govern what code runs when a plugin is loaded++This ADR introduces two new trust boundaries:+1. **Plugin install-time integrity**: before a plugin is loaded, verify its supply-chain provenance+2. **Memory write-time authorization**: before an agent writes to a namespace, verify it holds an explicit write grant++These boundaries require new module surfaces, protocol additions to the plugin registry format, and an API addition to AgentDB β all architectural decisions.++## Decision++### Part A: PluginIntegrityVerifier++Add `PluginIntegrityVerifier` to `@claude-flow/security` with two verification stages:++**Stage 1 β Signature verification** (blocks DDIPE):+- Every plugin published to the IPFS registry MUST carry a detached Ed25519 signature over its manifest hash+- `discovery.ts` MUST refuse to install unsigned plugins when `CLAUDE_FLOW_STRICT_PLUGINS=true` (default: warn-only for backwards compatibility)+- Trust anchors stored in `v3/@claude-flow/cli/src/plugins/trust/trust-anchors.json`++**Stage 2 β Semantic intent scan** (blocks SCH):+- During `plugins install`, pipe all natural-language fields (description, readme excerpt, compliance rules) through a lightweight intent classifier+- Classify against a taxonomy of malicious intent categories (credential exfiltration, RCE, data poisoning, privilege escalation)+- Block install if confidence exceeds configurable threshold (default: 0.8)+- Fallback: LLM-free heuristic rules covering the top-5 SCH patterns from arXiv:2605.14460++**Implementation targets:**+- `v3/@claude-flow/security/src/plugins/integrity-verifier.ts` (new)+- `v3/@claude-flow/cli/src/plugins/store/discovery.ts` (add verification hook on install)+- `v3/@claude-flow/cli/src/plugins/trust/trust-anchors.json` (new)++### Part B: Memory Namespace Write ACLs (Mnemonic Sovereignty, primitives 1β3)++Add write authorization to AgentDB namespaces:++- Every agent spawn receives an explicit `writeNamespaces: string[]` grant+- AgentDB enforces grants at the storage boundary (not just convention)+- Agents not in the grant list for a namespace receive `MemoryWriteDenied` error+- Read access remains open (read-only poisoning blocked by ADR-131 guardrail layer)++Address governance primitives 1 (write authorization), 2 (read authorization), 3 (update authorization) from the Mnemonic Sovereignty taxonomy. Primitives 4β9 deferred for a future ADR.++**Implementation targets:**+- `v3/@claude-flow/memory/src/namespaces/authorization.ts` (new)+- `v3/@claude-flow/memory/src/agent-db.ts` (add grant enforcement)+- `v3/@claude-flow/cli/src/agent/spawn.ts` (add `writeNamespaces` parameter)++## Backwards Compatibility++- Plugin verification defaults to warn-only mode (`CLAUDE_FLOW_STRICT_PLUGINS=false`) β no breaking change for existing unsigned plugins+- Memory namespace ACLs are additive β agents spawned without explicit grants retain legacy full-access behavior until `CLAUDE_FLOW_STRICT_MEMORY=true` is set+- Both strict modes will become default in v4.0.0++## Consequences++**Positive:**+- Blocks SCH attacks (0.00% current detection β detectable at semantic layer)+- Blocks DDIPE attacks at install time via signature check+- Reduces memory poisoning propagation across agent boundaries+- Positions Ruflo's memory governance ahead of all 2026 competitors (none satisfy all 9 mnemonic sovereignty primitives)++**Negative:**+- Plugin publishers must generate Ed25519 keypairs and sign manifests (new workflow)+- Semantic intent scan adds ~50β200ms to `plugins install` (acceptable for install-time, not runtime)+- Write ACLs require updating all existing agent spawn callsites that use shared namespaces++## References++- arXiv:2604.03081 β Supply-Chain Poisoning Attacks Against LLM Coding Agent Skill Ecosystems+- arXiv:2605.14460 β Exploiting LLM Agent Supply Chains via Payload-less Skills+- arXiv:2601.05504 β Memory Poisoning Attack and Defense on Memory Based LLM-Agents+- arXiv:2604.16548 β A Survey on the Security of Long-Term Memory in LLM Agents: Toward Mnemonic Sovereignty+- Microsoft Agent Governance Toolkit β https://opensource.microsoft.com/blog/2026/04/02/diff --git a/v3/docs/adr/ADR-338-sona-behavioral-trajectory-auditing.md b/v3/docs/adr/ADR-338-sona-behavioral-trajectory-auditing.mdnew file mode 100644index 0000000000..2918190bab--- /dev/null+++ b/v3/docs/adr/ADR-338-sona-behavioral-trajectory-auditing.md@@ -0,0 +1,97 @@+# ADR-338 β SONA Behavioral Trajectory Auditing via Embedding-Space Trait Vectors++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-06-02)+**Related**: ADR-017 (RuVector Integration), ADR-026 (3-tier model routing), ADR-130 (graph intelligence)+**Source**: arXiv:2606.02536 (Leshin, Shah, Timmis β ICML 2026 Workshop: Agents in the Wild)++## Context++SONA (Self-Optimizing Neural Architecture) adapts agent behavior via LoRA micro-tuning and EWC+++continual learning. As of 2026-06-02, SONA has **no behavioral monitoring layer**: propensity drift+(e.g., agents becoming more likely to seek sensitive data, or to skip validation steps) is+undetectable until it causes observable failures.++Leshin et al. (arXiv:2606.02536, ICML 2026 Workshop) demonstrate that **agent behavioral traits+can be quantified as directions in the embedding space of skill-file diffs**. A linear model trained+on 68 labeled before/after skill-file diff pairs achieves:++- **91.2% sign-classification accuracy** (leave-one-out cross-validation)+- **Spearman Ο = 0.82** rank correlation for trait magnitude++The method is lightweight: train once on labeled diffs, then project any new LoRA adaptation delta+onto the trait vector to score the behavioral shift β no full re-evaluation needed.++Additionally, AGENTCL (arXiv:2606.02461, Shu et al.) shows that Ruflo's current SONA evaluation+uses naive task sequences that cannot distinguish memory designs. Compositional task streams (where+sub-tasks recur across sessions) expose plasticity-stability tradeoffs that naive streams mask.++## Decision++Add a **behavioral trajectory auditing layer** to SONA with two components:++### 1. Trait Vector Registry++Maintain a set of named trait vectors (e.g., `seeks-sensitive-data`, `skips-validation`,+`over-delegates`) as unit vectors in the embedding space of skill-file diffs. Vectors are trained+offline on labeled datasets and stored in AgentDB.++**Target file:** `v3/@claude-flow/hooks/src/intelligence/sona.ts`+Add: `computeTraitDelta(beforeDiff: string, afterDiff: string, trait: string): number`++### 2. Behavioral Audit Module++At each SONA adaptation cycle (post-LoRA update), project the adaptation delta onto all registered+trait vectors. Emit a structured `behavioral-drift` event if any trait score exceeds a configurable+threshold (default: 2Ο from rolling mean).++**New file:** `v3/@claude-flow/security/src/behavioral-audit.ts`++```typescript+export interface TraitAuditResult {+ trait: string;+ delta: number; // signed projection score+ zscore: number; // vs. rolling baseline+ flagged: boolean; // |zscore| > threshold+}++export async function auditSONAAdaptation(+ beforeDiff: string,+ afterDiff: string,+ traits: string[]+): Promise<TraitAuditResult[]>+```++### 3. Compositional Evaluation Stream++Extend the `ultralearn` background worker to run compositional task streams per the AGENTCL+protocol: inject reusable sub-tasks across sessions and compute:++- **plasticity score**: accuracy on novel tasks after adaptation+- **stability score**: retention of prior-task accuracy post-adaptation++**Target file:** `v3/@claude-flow/hooks/src/workers/ultralearn.ts`+Add: `runCompositionalEvalStream(config: EvalStreamConfig): Promise<PlasticityStabilityReport>`++## Consequences++**Positive:**+- SONA behavioral drift becomes observable before it causes downstream failures+- Compositional evaluation distinguishes memory designs (EWC++ vs. naive replay)+- Trait auditing is lightweight: embedding projection is O(d) per trait per adaptation+- Audit events integrate with existing `@claude-flow/security` pipeline++**Negative:**+- Requires labeled behavioral datasets to train initial trait vectors (one-time offline cost)+- Adds one embedding call per SONA adaptation cycle (~5β15ms latency overhead at 384-dim)+- Compositional eval streams increase ultralearn worker runtime; recommend scheduling during+ low-activity windows only++**Neutral:**+- Trait vector registry stored in AgentDB (consistent with ADR-006 unified memory)+- Flagged events feed the existing `post-task` hook for human review; no auto-rollback++## Implementation Priority++High β behavioral drift is a silent failure mode with security implications. The embedding+projection cost is negligible relative to SONA's existing LoRA update cost.diff --git a/v3/docs/adr/ADR-339-memory-integrity-mcp-verification.md b/v3/docs/adr/ADR-339-memory-integrity-mcp-verification.mdnew file mode 100644index 0000000000..49b6e67f34--- /dev/null+++ b/v3/docs/adr/ADR-339-memory-integrity-mcp-verification.md@@ -0,0 +1,94 @@+# ADR-339 β Memory Write Integrity Validation & MCP Tool Verification++**Status**: Proposed+**Date**: 2026-06-06+**Authors**: claude (dream-cycle agent, 2026-06-06)+**Related**: ADR-144 (Agent Authorization Propagation), ADR-145 (Plugin Supply-Chain Integrity), ADR-146 (ToolOutputGuardrail Integration)++## Context++Dream Cycle research session 2026-06-06 (SLOT=1, DEEP=security) identified two critical gaps not addressed by ADRs 144β146:++### Gap 1 β OWASP ASI06: Memory & Context Poisoning++arXiv:2606.04329 (Dash et al., June 2026, **Grade A**) provides the first systematic taxonomy of memory poisoning attacks against LLM agents, identifying:++- **4 write channels**: direct injection, retrieval-augmented write, tool-write, agent-to-agent relay+- **9 structural vulnerabilities** across those channels+- **Key result**: a single adversarial memory write can exert long-term influence over agent behavior++Ruflo's AgentDB exposes all 4 channels. `InputValidator` exists in `@claude-flow/security` but is not applied at any AgentDB write boundary. `vector_indexes` rows have no integrity checksums. This is OWASP ASI06:2026.++### Gap 2 β MCP Tool Description-Code Inconsistency++arXiv:2606.04769 (Shi et al., June 2026, **Grade A**) measured 9.93% description-code mismatch in a corpus of real-world MCP servers β where a tool's natural-language description misrepresents its actual implementation. These mismatches create defense blind spots: guardrails screen against the description, while the code executes differently.++ADR-145 verifies plugin supply-chain signatures but does not parse or compare tool descriptions against their implementations at registration time.++### Relationship to ADR-146++ADR-146 wires `ToolOutputGuardrail` at content-entry boundaries (MCP tool result β agent context, memory read β agent context, hooks output, Raft consensus payload). It screens *output content* flowing into the agent. It does not validate *memory write operations* or *MCP tool registration semantics*. These are upstream of ADR-146's guardrail positions and require separate validation logic.++## Decision++Add two validation layers to `@claude-flow/security`:++### Layer A β AgentDB Memory Write Validator++Apply `InputValidator` at each of the 4 write channels before data reaches the `vector_indexes` table:++| Channel | Call site | Validation action |+|---------|-----------|------------------|+| Direct injection (`memory_store`) | `MemoryService.store()` | Schema + content scan, reject on policy violation |+| Retrieval-augmented write | `MemoryService.augmentedWrite()` | Source provenance check, strip injected instructions |+| Tool-write (`memory_write` tool) | Tool handler wrapper | Full `InputValidator` pass + write ACL check (ADR-144) |+| Agent-to-agent relay (hive-mind) | Hive-mind message router | HMAC origin verification before write dispatch |++Each validated write appends an integrity checksum (SHA-256 of canonical content + write-timestamp + agent identity) to the `vector_indexes` row in a new `integrity_hash` column. Read paths surface a `tampered: true` flag when stored hash diverges from recomputed hash.++### Layer B β MCP Tool Description-Code Consistency Checker++At MCP server registration time (plugin install + daemon startup), run a static consistency scan:++1. Parse each tool's `description` string for capability claims (action verbs, scope keywords).+2. Compare against the registered handler's function signature and known safe-call envelope.+3. Flag tools where description claims diverge from implementation shape (target: surface β₯9.93% mismatch rate per arXiv:2606.04769 methodology).+4. Emit a `MCP_TOOL_INCONSISTENCY` event to the ADR-146 telemetry sink; block registration if `trustLevel < 'official'`.++## Consequences++### Positive+- Closes OWASP ASI06 for Ruflo's 4 identified write channels.+- Detects the 9.93% real-world MCP mismatch class before tools enter the agent's trust perimeter.+- Integrity checksums enable forensic reconstruction of poisoning chains.+- Reuses existing `InputValidator` and `TokenGenerator` β no new security primitives.+- Feeds the ADR-146 telemetry sink β single observability pane for all security events.++### Negative+- `integrity_hash` column is a schema migration on `vector_indexes` β requires backwards-compatible default for existing rows.+- Description-code scanner is heuristic β false positive rate depends on tool description quality; needs threshold tuning.+- Agent-to-agent HMAC at the hive-mind router adds ~0.3ms per relay message (estimated; must be benchmarked).++### Neutral+- Does **not** address ASI07 (inter-agent message signing for SendMessage payloads) β that requires a separate HMAC injection point in the comms layer and is deferred to a follow-on ADR.+- Does **not** address ASI10 (rogue agent shutdown) β deferred.++## Implementation Plan++| Phase | Work item | Effort |+|-------|-----------|--------|+| P1 | `integrity_hash` column migration + SHA-256 checksum on `memory_store` direct path | 0.5 day |+| P2 | `InputValidator` wrappers on retrieval-augmented write + tool-write | 0.5 day |+| P3 | HMAC origin check on hive-mind agent-to-agent relay write | 1 day |+| P4 | MCP description-code consistency scanner + `MCP_TOOL_INCONSISTENCY` event | 1 day |++Total estimated: **3 days**.++## References++- arXiv:2606.04329 β "From Untrusted Input to Trusted Memory: A Systematic Study of Memory Poisoning Attacks in LLM Agents" (Dash et al., Jun 2026)+- arXiv:2606.04769 β "Description-Code Inconsistency in Real-world MCP Servers" (Shi et al., Jun 2026)+- arXiv:2606.05743 β "Membrane: A Self-Evolving Contrastive Safety Memory for LLM Agent Defense" (Choi et al., Jun 2026)+- OWASP ASI06:2026 β Memory & Context Poisoning+- OWASP ASI07:2026 β Insecure Inter-Agent Communication+- Dream Cycle gist: v3/docs/research/dream-cycle-2026-06-06-security.mddiff --git a/v3/docs/adr/ADR-340-retrospective-harness-optimization.md b/v3/docs/adr/ADR-340-retrospective-harness-optimization.mdnew file mode 100644index 0000000000..ee572439d7--- /dev/null+++ b/v3/docs/adr/ADR-340-retrospective-harness-optimization.md@@ -0,0 +1,75 @@+# ADR-340: Retrospective Harness Optimization (RHO) for SONA Intelligence Loop++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-06-07)+**Dream Cycle Issue:** Dream Cycle 2026-06-07, intelligence surface+**Source:** arXiv:2606.05922 β "Retrospective Harness Optimization: Improving LLM Agents via Self-Preference over Trajectory Rollouts"++---++## Context++RHO (arXiv:2606.05922, Grade A, code available: github.com/wbopan/retro-harness) demonstrates that a single self-supervised optimization cycle raises SWE-Bench Pro pass rate from 59% to 78% (+19pp) without any external grading signal. The method:++1. Selects a diverse coreset of challenging tasks from historical trajectories (stored in ReasoningBank)+2. Re-executes them in parallel with harness variation candidates+3. Uses the agent's own pairwise preference comparisons to identify the best harness update+4. Applies the winning update to the live harness without human validation++Ruflo's current SONA intelligence loop collects trajectory data via `hooks post-task --train-patterns` and stores it in ReasoningBank, but has no mechanism to retrospectively compare trajectory outcomes and propose harness improvements. The 4-step RETRIEVE β JUDGE β DISTILL β CONSOLIDATE pipeline distills patterns but does not produce harness diffs.++No existing ADR in the 085β130 range covers self-supervised harness optimization. ADR-076 (structured distillation) and ADR-078 (hybrid retrieval and outcome signal) address pattern extraction but not harness self-modification.++---++## Decision++Add a `retrospective-optimize` subcommand to `@claude-flow/hooks` that:++1. **Coreset selection** β queries ReasoningBank for the N most challenging recent tasks (verdict=failure or low-confidence success, N=20 default), sampled across diverse agent types+2. **Parallel rollout** β re-executes the coreset against K harness candidates (K=5 default) generated by sampling MoE expert perturbations of the current harness config+3. **Preference scoring** β uses the SONA judge (already wired in `post-task`) to score each rollout pair; selects the Condorcet winner+4. **Harness update** β writes the winning harness delta to `~/.claude-flow/harness.json` with a rollback checkpoint; logs the update to the `intelligence` hook trajectory++The command is designed to run as a nightly background worker (`hooks worker dispatch --trigger retrospective-optimize`) and does not block interactive sessions.++---++## Consequences++**Positive:**+- Expected +15β20pp task success improvement (consistent with Grade A benchmark, same methodology)+- Self-supervised: no labeled data or human grading required+- Integrates cleanly with existing ReasoningBank + SONA + MoE infrastructure+- Rollback checkpoint prevents irreversible harness corruption++**Negative / Risks:**+- Parallel rollout of K=5 candidates Γ N=20 tasks = 100 re-executions per cycle; compute cost must be budgeted (estimate: ~$0.10β0.50 per nightly cycle at Haiku pricing)+- Self-preference scoring introduces Goodhart's law risk: the agent may optimize for metrics it finds easy to self-evaluate rather than genuine task success+- Requires SWE-Bench Pro baseline measurement before claiming benchmark parity with arXiv results++**Mitigation:**+- Cap nightly budget via `--max-budget-usd` flag (default 0.25)+- Require human-in-the-loop approval for harness updates that change >3 parameters (configurable threshold)+- Instrument baseline before enabling: `claude-flow performance benchmark --suite swe-bench-pro`++---++## Scope++| File | Change |+|------|--------|+| `v3/@claude-flow/hooks/src/commands/retrospective-optimize.ts` | New command (~200 LOC) |+| `v3/@claude-flow/hooks/src/workers/retrospective-worker.ts` | Background worker registration (~80 LOC) |+| `v3/@claude-flow/hooks/src/index.ts` | Export new command |+| `v3/@claude-flow/memory/src/reasoning-bank.ts` | Add `getCoreset(n, filter)` method (~40 LOC) |++Total estimated: ~320 LOC. No breaking API changes.++---++## Alternatives Considered++- **No-op (skip):** Accept the 19pp gap vs RHO. Rejected β this is the most significant intelligence SOTA gap identified in the 2026-06-07 cycle and is directly addressable.+- **Full MLEvolve port (arXiv:2606.06473):** Evolutionary search over agent configurations. Larger scope (~2000 LOC), higher risk. Deferred to a future ADR after RHO baseline is established.+- **MAGE execution-state memory (arXiv:2606.06090):** Orthogonal improvement (token reduction + task success). Recommended as a separate implementation without an ADR (implementation-level change to AgentDB schema).diff --git a/v3/docs/adr/ADR-341-multi-signal-memory-retrieval.md b/v3/docs/adr/ADR-341-multi-signal-memory-retrieval.mdnew file mode 100644index 0000000000..4c8fc28f43--- /dev/null+++ b/v3/docs/adr/ADR-341-multi-signal-memory-retrieval.md@@ -0,0 +1,76 @@+# ADR-341 β Multi-Signal Memory Retrieval++**Status**: Proposed+**Date**: 2026-06-08+**Authors**: claude (dream-cycle agent, 2026-06-08)+**Related**: ADR-006 (Unified Memory Service), ADR-009 (Hybrid Memory Backend), ADR-017 (RuVector Integration)++## Context++The 2026-06-08 Dream Cycle research session (DEEP=memory) found that the SOTA for agent memory retrieval has shifted from single-vector lookup to multi-signal retrieval combining semantic similarity, BM25 keyword matching, and entity matching in parallel. Mem0's Q2 2026 algorithm achieves 94.4% LongMemEval at ~6,900 tokens/query (75% token reduction vs full-context methods). Ruflo's memory module currently runs vector-only retrieval through HNSW/RaBitQ with no BM25 or entity passes.++The gap is concrete:++| Signal | Ruflo (today) | SOTA (Mem0 v2) |+|--------|--------------|----------------|+| Semantic (vector) | HNSW + RaBitQ rerank | β |+| Keyword (BM25/FTS5) | Not used | β parallel |+| Entity matching | Not implemented | β parallel |+| Result fusion | N/A | RRF (reciprocal rank fusion) |+| Async writes | Unknown | Default |++An FTS5 table already exists in the SQLite backend (`v3/@claude-flow/memory/src/fts5.ts`) and a graceful-retrieval abstraction is partially built (`graceful-retrieval.ts`). The infrastructure is in place; the architectural decision is whether to commit to parallel multi-signal as the canonical retrieval contract.++### Why this is architectural (not implementation-level)++Multi-signal retrieval changes the public `MemoryBackend.search()` API shape, introduces a mandatory FTS5 dependency on the SQLite path, adds a result-fusion step to every read, and alters the latency/cost profile. It cannot be added as a quiet patch β every backend implementation must honour the same contract.++## Decision++Add multi-signal retrieval as the canonical read path in `UnifiedMemoryService`:++1. **Run three signal passes in parallel** via `Promise.all`:+ - Semantic: existing HNSW/RaBitQ vector search (unchanged)+ - Keyword: FTS5 BM25 full-text scan (existing `fts5.ts`, wire up)+ - Entity: lightweight entity tagger extracting named entities from query, then exact-match against stored entity index++2. **Fuse results** with Reciprocal Rank Fusion (RRF, `k=60`) β well-studied, zero additional model calls, deterministic.++3. **Return top-k after fusion** with per-result signal provenance (`signals: ['vector', 'bm25', 'entity']`) so callers can debug.++4. **Async writes by default** β `store()` enqueues to a non-blocking queue; HNSW and FTS5 indexes rebuild on background timer (already done for HNSW consolidator; extend to FTS5).++5. **Instrument `tok/query`** via the existing benchmark harness (`memory-efficiency.bench.ts`) β report alongside latency so we can track token efficiency over time.++## Consequences++**Positive:**+- Closes the largest retrieval gap vs Mem0/SOTA with no new model dependencies.+- RRF is O(k log k) β negligible overhead on typical memory sizes.+- FTS5 already exists; no new SQLite dependency.+- Entity matching adds resilience for proper-noun queries that vector search handles poorly.+- Enables publishing LoCoMo/LongMemEval benchmark scores once retrieval is credible.++**Negative:**+- `search()` latency increases by ~1β3ms (three parallel DB calls vs one) for small indexes. Acceptable: HNSW crossover is ~5k vectors; below crossover brute-force already dominates.+- FTS5 index must stay in sync with the vector store. The existing consolidator `sweepExpired()` must be extended to drop FTS5 rows too.+- Entity tagger adds a new code path. Start with a regex-based tagger (names, emails, URLs, file paths) β no ML dependency required at P1.++**Neutral:**+- Existing callers of `search()` receive richer results with no breaking change to the return shape (extra `signals` field is additive).+- RaBitQ pre-filter continues to operate as before; multi-signal does not bypass it.++## Implementation Plan++| Phase | Scope | Acceptance |+|-------|-------|------------|+| P1 | Wire FTS5 into `graceful-retrieval.ts`; add RRF fusion | `fts5.test.ts` passes; `graceful-retrieval.test.ts` covers fusion |+| P2 | Regex entity tagger; entity index in SQLite | Entity round-trip test; query "find memories about Alice" returns Alice-tagged entries above noise |+| P3 | Async write default; tok/query instrumentation in bench | `store()` returns in <1ms; bench reports tok/query |+| P4 | Run LoCoMo slice benchmark; publish `docs/reviews/memory-benchmark-2026-06-08.md` | Score β₯75% (baseline expectation before tuning) |++## Alternatives Considered++- **Graph-based memory (Cognee-style)** β higher expressiveness for multi-hop queries, but requires a graph DB dependency and operator overhead not justified at Ruflo's current scale. Revisit if entity graph proves insufficient.+- **Agentic retrieval (Supermemory ASMR)** β 98.6% LongMemEval-s but requires spawning 3 parallel search agents per query, multiplying cost and latency by ~10Γ. Appropriate as a future optional mode (`retrieval: 'agentic'`), not the default.+- **BM25 only (drop vector)** β regresses recall on semantic queries. Not viable.diff --git a/v3/docs/adr/ADR-342-dream-cycle-ruvector-production-scale-backend.md b/v3/docs/adr/ADR-342-dream-cycle-ruvector-production-scale-backend.mdnew file mode 100644index 0000000000..d05af6bddb--- /dev/null+++ b/v3/docs/adr/ADR-342-dream-cycle-ruvector-production-scale-backend.md@@ -0,0 +1,73 @@+# ADR-342: RuVector Production-Scale Backend Adoption++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-06-09)+**Supersedes / Extends:** ADR-017 (RuVector Integration, Accepted) β ADR-017 established the integration; this ADR governs the path to production-scale deployment.+**Related:** ADR-006 (Unified Memory Service), ADR-009 (Hybrid Memory Backend)++---++## Context++ADR-017 accepted RuVector as an integration target. The current implementation in `v3/@claude-flow/memory/src/agentdb-backend.ts` uses HNSW + RaBitQ quantization, benchmarked internally at N=5kβ20k vectors (1.9xβ4.7x vs brute force, recall@10 ~0.99).++In June 2026, RuVector vendor documentation (gist.github.com/ruvnet) claims:+- 50K QPS single-threaded, 100K QPS (8 threads) at 1M Γ 128D vectors+- p99 <5ms at 1M vectors+- Three quantization tiers: scalar 4x (97% acc), product 16x (90%), binary 32x (85%)+- Drop-in AgenticDB API compatibility++**Confidence level:** Grade C β vendor gist, no peer-reviewed benchmark. Cannot commit architecturally on Grade C alone.++**Gap identified tonight:** Competitor vector stores (Qdrant, Milvus, Weaviate) are benchmarked at 100Mβ1B vectors. Ruflo's only published number is at 20K vectors. The behavior above 20K β particularly QPS, recall, and memory β is unknown and undocumented.++---++## Decision++Add `ruvector` as an **optional, feature-flagged** backend in `AgentDB` configuration, gated behind independent benchmark validation before any production default change.++### Specific changes proposed++1. **`v3/@claude-flow/memory/src/agentdb-backend.ts`** β Add `BackendType = 'hnsw' | 'ruvector'` union; wire `ruvector` branch to the RuVector API surface described in ADR-017.++2. **`v3/@claude-flow/memory/src/database-provider.ts`** β Backend selection reads `CLAUDE_FLOW_VECTOR_BACKEND` env var; default remains `hnsw`.++3. **`scripts/benchmark-intelligence.mjs`** β Extend to cover 100K and 1M vector corpus; compare `hnsw` vs `ruvector` at p50/p99 and recall@10. Publish result before flipping default.++4. **`v3/@claude-flow/memory/MIGRATION.md`** β Document the manual migration path from AgentDB HNSW β RuVector for existing deployments.++### What is NOT changing++- Default backend stays `hnsw` until benchmark validates Grade-C claim+- AgenticDB API surface unchanged (RuVector is drop-in)+- No existing tests modified; new backend tested in isolation++---++## Consequences++**Positive**+- Unlocks 1M+ vector corpus for production deployments without architectural changes+- Three quantization tiers give users scalar/product/binary tradeoff control+- Maintains API compatibility (AgenticDB interface)++**Negative / Risks**+- RuVector 50K QPS claim is Grade C; if unreproducible, this ADR is moot+- Binary quantization (85% recall) is a step down from current RaBitQ (measured 0.99 recall@10 at 20K)+- Edge deployments on resource-constrained devices may not benefit from 8-thread QPS claims++---++## ADR Number Collision Note++The formula `ls v3/docs/adr/ADR-*.md | sort | tail -1 | +1` yields 147. **Six in-flight PRs (#2278, #2290, #2295, #2304, #2310, #2317) each claim ADR-147 and none has merged** (see meta-issue #2324). This ADR uses **153** (147 + 6 in-flight) to avoid further collision. Human review should renumber all 7 collision ADRs (147β153) once the PRs land.++---++## Review Gate++Do not change `CLAUDE_FLOW_VECTOR_BACKEND` default to `ruvector` until:+- `scripts/benchmark-intelligence.mjs` produces a Grade-A result at N β₯ 100K+- recall@10 β₯ 0.97 at the chosen quantization tier+- p99 latency measured at target corpus sizediff --git a/v3/docs/adr/ADR-343-shared-context-parallel-dispatch.md b/v3/docs/adr/ADR-343-shared-context-parallel-dispatch.mdnew file mode 100644index 0000000000..95413d1f98--- /dev/null+++ b/v3/docs/adr/ADR-343-shared-context-parallel-dispatch.md@@ -0,0 +1,90 @@+# ADR-343: Shared-Context Parallel Dispatch for Multi-Agent Performance++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-06-10)+**Date:** 2026-06-10+**Related:** ADR-006 (Unified Memory Service), ADR-009 (Hybrid Memory Backend)++---++## Context++DeLM (arXiv:2606.10662, Mao & Mirhoseini, Jun 9 2026) demonstrates that giving decentralized agents a shared verified context snapshot at spawn time achieves +10.5pp on SWE-bench Verified and β50% cost simultaneously. The key mechanism: agents receive a read-only immutable view of the task queue and shared state at spawn, rather than building context serially via message passing.++Ruflo v3.6.10 spawns agents via the `swarm_init` + Task tool pipeline. Agents build context through sequential SendMessage exchanges, which serializes work that could be parallel and replicates retrieval calls (each agent independently queries AgentDB for the same context).++3SPO (arXiv:2606.09961) provides a complementary finding: step-wise state-score credit assignment (+22.6% ALFWorld vs GRPO) requires per-state snapshots, not just per-trajectory aggregates. A shared context snapshot is the prerequisite for step-wise RL.++No existing ADR (143β147) covers context materialization at swarm spawn time.++---++## Decision++At `swarm_init` time, serialize the current AgentDB namespace into a read-only immutable snapshot (`SwarmContextSnapshot`) and pass it as a typed parameter to each spawned agent. Agents receive the snapshot synchronously at spawn and do not need to query AgentDB for baseline context.++### Interface++```typescript+// v3/@claude-flow/cli/src/swarm/types.ts+interface SwarmContextSnapshot {+ readonly namespace: string;+ readonly entries: ReadonlyMap<string, unknown>;+ readonly vectorIndex?: ReadonlyArray<{ key: string; embedding: Float32Array }>;+ readonly snapshotAt: number; // unix ms+}++interface SwarmInitOptions {+ topology: 'hierarchical' | 'mesh' | 'adaptive' | 'hierarchical-mesh';+ maxAgents: number;+ strategy: 'specialized' | 'balanced';+ namespace?: string;+ snapshot_context?: boolean; // default: false (feature-flagged)+}+```++### Behaviour++1. When `snapshot_context: true`, `swarm_init` calls `AgentDB.snapshot(namespace)` before spawning any agent.+2. The snapshot is passed as an immutable frozen object in each agent's initial prompt context.+3. Agents do not re-query AgentDB for keys present in the snapshot during their first turn.+4. Writes by agents go directly to AgentDB (not the snapshot); the snapshot is spawn-time only.++---++## Consequences++**Positive:**+- Eliminates N redundant AgentDB reads (one per agent) for shared baseline context.+- Enables parallel agent starts without sequential SendMessage context-building.+- Prerequisite for step-wise RL (3SPO approach) β per-state snapshots become available.+- Aligns with DeLM's architecture, the current SWE-bench SOTA approach.++**Negative:**+- Snapshot may be stale if the namespace changes between `swarm_init` and agent first-turn completion (bounded by swarm startup latency, typically <500ms).+- Increases `swarm_init` latency by one AgentDB read (mitigated by RaBitQ 0.60ms/query measured performance).+- Feature-flagged (`snapshot_context: false` default) until benchmarked.++**Neutral:**+- Does not change the SendMessage protocol or agent coordination topology.+- Does not affect agents that do not read from AgentDB.++---++## Implementation Sketch++Files to modify (~80 LOC total):++1. `v3/@claude-flow/cli/src/swarm/init.ts` β add `snapshot_context` handling (~50 LOC)+2. `v3/@claude-flow/cli/src/swarm/types.ts` β add `SwarmContextSnapshot` interface (~20 LOC)+3. `v3/@claude-flow/memory/src/agentdb.ts` β add `snapshot(namespace)` method (~10 LOC)++Gate: measure wall-clock reduction on a 5-agent benchmark pipeline before setting `snapshot_context: true` as default. Target: β₯20% reduction in time-to-first-agent-output (cf. DeLM's β50% cost baseline).++---++## Alternatives Rejected++- **Keep current SendMessage-first approach**: Leaves β50% cost and +10.5pp SWE-bench gain on the table.+- **Full DeLM task-queue replication**: Requires replacing the hierarchical coordinator with a decentralized queue β too large a change. `snapshot_context` is a minimal, non-breaking step in the same direction.+- **Pre-warm agents with background AgentDB reads**: Race condition risk; snapshot approach is deterministic.diff --git a/v3/docs/adr/ADR-344-knowledge-graph-index-for-reasoningbank.md b/v3/docs/adr/ADR-344-knowledge-graph-index-for-reasoningbank.mdnew file mode 100644index 0000000000..18c185cae3--- /dev/null+++ b/v3/docs/adr/ADR-344-knowledge-graph-index-for-reasoningbank.md@@ -0,0 +1,90 @@+# ADR-344: Knowledge Graph Index for ReasoningBank++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-06-12)+**Dream Cycle Issue**: #TBD (filed same session)+**Related**: ADR-087 (graph-node native backend), ADR-006 (Unified Memory Service)++## Context++Ruflo's ReasoningBank stores trajectory patterns as flat vector embeddings, queried via HNSW similarity search. This serves single-hop semantic retrieval well but cannot answer multi-hop questions like "which agent patterns are causally supported by evidence from method lineage X?"++arXiv:2606.13669 (Agents-K1, June 11, 2026) demonstrates that agent-native knowledge graphs β capturing entities, claims, evidence, and method lineages as graph nodes with typed edges β achieve superior multi-hop scientific reasoning compared to flat retrieval. The system processed 2.46M papers into Scholar-KG using a 4B GRPO-trained extraction backbone.++Ruflo already has `@ruvector/[email protected]` installed and wired (ADR-087) for agent-relationship topology (k-hop neighbor queries, hyperedges). That same infrastructure is unused for *knowledge indexing*. This creates an avoidable gap: LangGraph v0.4 ships GraphStore (neo4j/networkx wrappers) as a first-class memory option; Ruflo's graph capability is topology-only.++## Decision++Extend `v3/@claude-flow/memory/src/ruvector/graph-backend.ts` (ADR-087) to support knowledge graph indexing of ReasoningBank entries. Add a `kg_query(entity, hops)` retrieval path to `UnifiedMemoryService` alongside the existing HNSW vector path. Feature-flag the entire addition behind `CLAUDE_FLOW_KG_ENABLED`.++### Node Types++| Type | Fields | Indexed From |+|------|--------|-------------|+| `entity` | id, label, embedding | Pattern tags, tool names |+| `claim` | id, statement, confidence, embedding | Pattern outcome verdicts |+| `evidence` | id, sourcePatternId, outcome, embedding | JUDGE step outputs |++### Edge Types++| Label | From β To | Meaning |+|-------|-----------|---------|+| `supports` | evidence β claim | Evidence backs claim |+| `method_lineage` | claim β entity | Claim derived from entity method |+| `causal_precondition` | entity β entity | Entity A enables entity B |++### New API Surface (~200 LOC across 3 files)++**`graph-backend.ts`** β add:+```typescript+indexMemoryEntry(entry: MemoryEntry): Promise<void>+kg_query(entity: string, hops: number): Promise<GraphQueryResult>+```++**`unified-memory-service.ts`** β add:+```typescript+async hybridRetrieve(query: string, opts: { vectorK: number; graphHops: number }) {+ const [vectorResults, graphResults] = await Promise.all([+ this.hnsw_search(query, opts.vectorK),+ process.env.CLAUDE_FLOW_KG_ENABLED ? this.kg_query(query, opts.graphHops) : []+ ]);+ return rankFusion(vectorResults, graphResults);+}+```++**`reasoningbank.ts`** β call `indexMemoryEntry()` on every successful `store()` when KG enabled.++### No New Dependencies++Reuses `@ruvector/[email protected]` already installed per ADR-087.++## Feature Flag Rollout++| `CLAUDE_FLOW_KG_ENABLED` | Behavior |+|--------------------------|----------|+| unset / `false` | Pass-through to existing HNSW only |+| `true` | Index entries + hybrid `kg_query` + `hnsw_search` |++Flip default to `true` only after `scripts/benchmark-intelligence.mjs` validates multi-hop recall improvement vs. HNSW-only baseline at N β₯ 5K patterns.++## Consequences++**Positive:**+- Closes architectural gap vs. LangGraph GraphStore and Agents-K1 pattern+- Reuses existing infrastructure (no new dependency, no new install step)+- Feature-flagged: zero risk to existing users+- Enables future RL-trained knowledge extraction (Agents-K1 GRPO backbone pattern)++**Negative:**+- Write-path overhead when KG enabled (~1ms per entry for graph indexing)+- sql.js graph storage grows proportionally to ReasoningBank size+- Requires schema migration for existing AgentDB databases (handled by `migrate` command)++## Benchmark Gate (before default flip)++Run `npx claude-flow@latest performance benchmark --suite memory-kg` comparing:+- HNSW-only recall@10 on multi-hop test set+- Hybrid KG+HNSW recall@10 on same test set+- Write-path latency: must remain < 5ms p99 per entry++Promote to default only if KG recall@10 improves by β₯ 10% on multi-hop queries.diff --git a/v3/docs/adr/ADR-345-swarm-credit-routing-shapley.md b/v3/docs/adr/ADR-345-swarm-credit-routing-shapley.mdnew file mode 100644index 0000000000..d67b72e223--- /dev/null+++ b/v3/docs/adr/ADR-345-swarm-credit-routing-shapley.md@@ -0,0 +1,76 @@+# ADR-345 β Swarm Credit Routing via Shapley-Value Attribution++**Status**: Proposed+**Date**: 2026-06-14+**Authors**: claude (dream-cycle agent, 2026-06-14)+**Issue**: [ruvnet/ruflo#TBD](https://github.com/ruvnet/ruflo/issues/) (filed tonight)+**Related**: ADR-026 (3-Tier Model Routing), ADR-143 (Tier-1 Codemods), ADR-153 (RuVector Integration)++## Context++SHARP (arXiv:2602.08335, revised Jun 2 2026) demonstrates that Shapley-value marginal-contribution+scoring improves multi-agent task matching by **+23.66% over single-agent** and **+14.05% over+standard multi-agent** baselines on real-world benchmarks. The Shapley-value decomposes the group+reward into each agent's marginal contribution across coalition subsets, providing a principled+credit signal for routing and selection.++Ruflo v3.6.10's hierarchical coordinator routes tasks by `agentType` + availability only. There is+no per-agent credit history, no marginal-contribution tracking, and no feedback loop between task+outcomes and future routing decisions. This is consistent with the stopping-decision gap identified+in ADR context (arXiv:2605.02801, #2332) β Ruflo lacks RL feedback at every orchestration layer.++SwarmHarness (arXiv:2605.28764, May 2026) independently converged on Shapley-value approximation+for decentralized compute reward distribution, suggesting the approach is framework-agnostic and+broadly applicable.++## Decision++Add per-agent Shapley credit scoring to the swarm task router in `@claude-flow/memory` and+`@claude-flow/cli`:++1. **Credit store**: Each agent instance accumulates a `credit_score` per `(task_type, agent_type)`+ pair in AgentDB namespace `swarm-credit`. Updated post-task via the existing `post-task` hook.++2. **Approximate Shapley**: Use the permutation-sampling approximation (k=16 samples) rather than+ exact computation β O(k) vs O(2^n). Store the running mean and variance for each agent.++3. **Weighted routing**: The hierarchical coordinator scores candidates as:+ `route_score = credit_score * availability_weight * (1 - current_load)`+ Highest score wins. Fall back to role-only routing when `credit_score` is undefined (new agent,+ first task of this type).++4. **Decay**: Apply exponential decay (Ξ»=0.95 per session) so stale credit from prior sessions+ does not dominate. Implement as lazy update on read.++5. **Opt-in flag**: Gate behind `CLAUDE_FLOW_CREDIT_ROUTING=true` env var until benchmarked at+ β₯ 50 task cycles in the Ruflo test suite. Default off for stable release.++## Consequences++**Positive:**+- Closes the credit-attribution gap vs SHARP (+23.66% opportunity)+- Enables agent specialization to emerge over time without explicit labeling+- Small storage overhead: one float64 pair per `(task_type, agent_type)` cell in AgentDB+- Reuses existing `post-task` hook β minimal new surface area++**Negative:**+- First N tasks per agent type produce noisy credit estimates (cold-start)+- k=16 permutation samples introduce variance; exact Shapley only tractable for nβ€8 agents+- Decay parameter Ξ»=0.95 is a hyperparameter requiring tuning; wrong value causes credit amnesia+ or stale-lock++**Neutral:**+- Does not change the routing contract β agents still receive the same task spec+- Credit store is advisory; correctness does not depend on it++## Implementation Plan++| Step | File | LOC |+|------|------|-----|+| 1 | `v3/@claude-flow/memory/src/credit-store.ts` | ~100 |+| 2 | `v3/@claude-flow/cli/src/orchestration/credit-router.ts` | ~120 |+| 3 | `v3/@claude-flow/hooks/src/workers/post-task-credit.ts` | ~40 |+| 4 | Tests: `tests/orchestration/credit-router.test.ts` | ~80 |++Total estimated: ~340 LOC. Flag: `CLAUDE_FLOW_CREDIT_ROUTING`.+Gate: benchmark at β₯50 cycles before default-on in a future MINOR release.diff --git a/v3/docs/adr/ADR-346-multi-layer-agent-security.md b/v3/docs/adr/ADR-346-multi-layer-agent-security.mdnew file mode 100644index 0000000000..4ba53b7752--- /dev/null+++ b/v3/docs/adr/ADR-346-multi-layer-agent-security.md@@ -0,0 +1,89 @@+# ADR-346: Multi-Layer Agent Security Stack++**Status:** Proposed+**Date:** 2026-06-16+**Authors:** claude (dream-cycle agent, 2026-06-16)+**Supersedes:** Partially extends ADR-012 (MCP Security), ADR-144 (Agent Authorization), ADR-145 (Plugin Supply Chain), ADR-146 (Tool Output Guardrails)++---++## Context++Nightly dream-cycle research (2026-06-16, SLOT=1, DEEP=security) surfaced three Grade A benchmarks establishing a critical gap:++1. **ClawSafety** (arXiv:2604.01438): Agent attack success rate (ASR) 40β75% across 5 frontier models in 2,520 sandboxed trials. Safety is determined by the full deployment stack, not just the backbone model. Skill-instruction injection (matching Ruflo's hooks/plugins) is the highest-trust, highest-risk vector.++2. **MCP Threat Coverage** (arXiv:2604.05969): 7 threat categories, 23 distinct attack vectors across 177K+ deployed MCP tools. No single defense covers more than 34% of the threat landscape. An integrated MCPSHIELD approach (capability-based access control + cryptographic attestation + information flow tracking + runtime policy) achieves 91% coverage.++3. **OWASP Top 10 for Agentic Applications 2026** (published Dec 2025): ASI01 = Agent Goal Hijacking is ranked #1. ASI02 = Unauthorized Capability Escalation. These risks are unmitigated in Ruflo's current stack.++Ruflo's existing security layers (InputValidator, PathValidator, SafeExecutor, ADR-144/145/146) provide single-layer boundary validation estimated at ~34% threat coverage β the floor identified for isolated defenses. Ruflo exposes 314 registered MCP tools and 60+ hooks/skills that are currently unattestad against injection via tool environment.++---++## Decision++Implement a **multi-layer agent security stack** in `@claude-flow/security` comprising three coordinated layers:++### Layer 1 β MCP Tool Attestation+- Cryptographic signing of tool manifests at registration time+- Signature verification at every tool invocation in the MCP server+- Capability-based access control: tools declare required capabilities; agents are granted minimum necessary+- Revocation list for compromised tools+- Target: covers threat categories TC-1 (tool spoofing), TC-2 (capability escalation), TC-5 (protocol tampering)++### Layer 2 β Indirect Prompt Injection Monitoring+- Content sanitization pipeline at hook chokepoints: `pre-task`, `post-edit`, `pre-command`+- Pattern detection for instruction-injection signatures in tool outputs, environment variables, and skill payloads+- Quarantine mode: flag suspicious payloads for human review before agent execution+- Integrates into existing `SafeExecutor` in `@claude-flow/security`+- Target: addresses ClawSafety's highest-risk vector (skill-instruction injection)++### Layer 3 β Agent Action Audit Trail with Checkpointing+- Append-only audit log of every agent action (tool call, memory write, file operation, hook execution)+- Checkpoint state snapshot per task boundary, stored in AgentDB+- Rollback trigger: detected Goal Hijacking (ASI01) signals halt + restore from last clean checkpoint+- Expose audit trail via `@claude-flow/cli security audit` command+- Target: closes the LangGraph 0.4 feature gap; enables post-hoc forensics and OWASP compliance evidence++---++## Consequences++### Positive+- Raises estimated threat coverage from ~34% to β₯80% (target 91% with full MCPSHIELD alignment)+- Closes OWASP Agentic ASI01 and ASI02 gaps+- Makes Ruflo the first open-source agent framework with MCP-native tool attestation+- Enables enterprise compliance evidence for agentic AI security audits+- Competitive differentiation: LangGraph, CrewAI, AutoGen, OpenAI Swarm have no MCP tool attestation++### Negative+- Attestation adds latency to tool registration and invocation (~1-5ms per call, within <100ms MCP target)+- Audit trail increases AgentDB write volume; requires TTL/rotation policy+- Breaking change for unregistered or externally-sourced MCP tools (migration guide required)++### Neutral+- Layer 2 sanitization may produce false positives on legitimate complex tool outputs; tunable threshold+- Checkpoint storage in AgentDB uses existing HNSW backend with new `audit` namespace++---++## Implementation Plan++1. `@claude-flow/security`: Add `ToolAttestation` class (Layer 1) β key pair generation, manifest signing, verification middleware+2. `@claude-flow/security`: Extend `SafeExecutor` with injection pattern detection (Layer 2)+3. `@claude-flow/memory`: Add `audit` namespace with append-only writes and TTL (Layer 3)+4. `@claude-flow/cli`: Add `security audit` and `security attestation` subcommands+5. Migration: `npx claude-flow@latest security attestation --init` to sign all registered MCP tools+6. Tests: TDD London School β mock tool registry + inject adversarial payloads; verify quarantine triggers++---++## References++- arXiv:2604.01438 β ClawSafety: "Safe" LLMs, Unsafe Agents+- arXiv:2604.05969 β Formal Security Framework for MCP-Based AI Agents+- arXiv:2506.23260 β From Prompt Injections to Protocol Exploits: Threats in LLM-Powered AI Agents Workflows+- arXiv:2603.15408 β TrinityGuard: A Unified Framework for Safeguarding Multi-Agent Systems+- OWASP Top 10 for Agentic Applications 2026 β https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/+- Dream-cycle research gist: `v3/docs/dream/2026-06-16-security-report.md`diff --git a/v3/docs/adr/ADR-347-trajectory-quality-judge-scoring.md b/v3/docs/adr/ADR-347-trajectory-quality-judge-scoring.mdnew file mode 100644index 0000000000..7556cbe4ed--- /dev/null+++ b/v3/docs/adr/ADR-347-trajectory-quality-judge-scoring.md@@ -0,0 +1,95 @@+# ADR-347: Trajectory-Quality JUDGE Scoring for ReasoningBank++- **Status**: Proposed+- **Authors**: claude (dream-cycle agent, 2026-06-17)+- **Date**: 2026-06-17+- **Supersedes**: none+- **Related**: ADR-006 (Unified Memory), ADR-017 (RuVector Integration), ADR-147 (Nested Subagent Depth)++---++## Context++Ruflo's SONA intelligence pipeline uses a 4-step RETRIEVEβJUDGEβDISTILLβCONSOLIDATE loop. The JUDGE step currently assigns binary verdicts: `success` or `failure` per trajectory step. This was sufficient when short-horizon tasks dominated agent workloads.++Two 2026 findings change that calculus:++1. **RetailBench** (arXiv:2606.15862, Grade A): All tested frontier models fail 180-day planning horizons; the strongest performers are "substantially below oracle policy". Binary pass/fail cannot distinguish an agent that fails on step 3 from one that fails on step 150 β both score 0.+2. **Benchmark contamination audit** (Berkeley RDI, 2026): Every major agent benchmark (SWE-bench, OSWorld, WebArena, GAIA, Terminal-Bench) is exploitable for +5β15pp inflation without solving tasks. Binary JUDGE verdicts derived from contaminated benchmarks propagate inflated confidence scores into ReasoningBank, which SONA then distils as valid patterns.++Additionally, Chronological Awareness scores (0.204β0.290 for frontier LLMs, mem0.ai State of AI Agent Memory 2026) reveal a systemic temporal reasoning weakness that binary verdicts cannot surface or train against.++---++## Decision++Replace the binary JUDGE verdict in ReasoningBank with a **5-dimension trajectory quality score** (TQS):++| Dimension | Range | Definition |+|---|---|---|+| `temporal_coherence` | 0.0β1.0 | Fraction of steps with correct chronological ordering of prior events |+| `tool_call_accuracy` | 0.0β1.0 | Ratio of tool calls that returned expected outputs vs. errors/retries |+| `horizon_persistence` | 0.0β1.0 | Step at which agent diverges from correct path / total steps attempted |+| `partial_progress_ratio` | 0.0β1.0 | Sub-goals completed / total sub-goals (even on failed trajectories) |+| `contradiction_resolution` | 0.0β1.0 | Fraction of conflicting-instruction episodes resolved without halt |++**Aggregate score**: `TQS = 0.25Β·temporal + 0.25Β·tool + 0.20Β·horizon + 0.20Β·partial + 0.10Β·contradiction`++TQS β₯ 0.80 = success, 0.40β0.79 = partial, < 0.40 = failure. The existing binary `success/failure` field is preserved for backward compatibility but computed from TQS threshold.++**Contamination guard**: ReasoningBank stores the benchmark scaffold hash alongside each trajectory. If the same scaffold hash recurs across β₯3 trajectories with identical tool call sequences, the JUDGE flags the run as potentially contaminated and down-weights the TQS by 0.5 before DISTILL.++---++## Consequences++**Positive**:+- Long-horizon agents get meaningful gradient signal: a partial-progress ratio of 0.6 on a 180-day task is informative; binary 0 is not.+- EWC++ receives temporal_coherence as a distinct weight dimension, enabling targeted anti-forgetting for time-aware capabilities.+- Contamination guard prevents inflated benchmarks from poisoning ReasoningBank patterns.++**Negative**:+- TQS computation adds ~2ms per trajectory evaluation (5 dimension calculations vs. 1 binary check). Acceptable given SONA's measured 0.0043ms/adapt budget is for adaptation, not JUDGE.+- `partial_progress_ratio` requires sub-goal decomposition at task ingestion β tasks without explicit sub-goals default to `0.5` (neutral) until decomposed.+- Breaking change in ReasoningBank schema: `verdict: "success"|"failure"` becomes `verdict: { tqs: number, dimensions: {...}, binary: "success"|"partial"|"failure" }`. Migration required for existing stored trajectories (default: set `tqs=1.0` for historical `success`, `tqs=0.0` for historical `failure`).++**Neutral**:+- Does not affect MoE gate routing (which consumes distilled patterns, not raw verdicts).+- Does not affect HNSW indexing (patterns stored post-DISTILL, schema-agnostic).++---++## Implementation Sketch++```typescript+// v3/@claude-flow/memory/src/reasoningbank/judge.ts+interface TrajectoryQualityScore {+ temporal_coherence: number; // 0.0-1.0+ tool_call_accuracy: number;+ horizon_persistence: number;+ partial_progress_ratio: number;+ contradiction_resolution: number;+ aggregate: number; // weighted sum+ binary: 'success' | 'partial' | 'failure';+ contamination_flag: boolean;+ scaffold_hash?: string;+}++function judgeTrajectory(steps: TrajectoryStep[]): TrajectoryQualityScore {+ // compute 5 dimensions then aggregate+}+```++Files affected:+- `v3/@claude-flow/memory/src/reasoningbank/judge.ts` (new TQS logic)+- `v3/@claude-flow/memory/src/reasoningbank/types.ts` (schema update)+- `v3/@claude-flow/memory/src/reasoningbank/migrate.ts` (historical default migration)+- `v3/@claude-flow/hooks/src/workers/ultralearn.ts` (consume TQS dimensions)++---++## Alternatives Considered++1. **Reward shaping only** (no schema change): Add step-level reward signal to EWC++ without changing JUDGE. Rejected β contamination guard requires scaffold hash tracking, which mandates a schema change anyway.+2. **External eval harness** (separate from ReasoningBank): Run TQS offline, store separately. Rejected β splits the RETRIEVEβJUDGE loop, breaking the 4-step pipeline's coherence.+3. **Keep binary, add temporal micro-eval**: Run a 5-event ordering test post-DISTILL and feed only temporal scores. Rejected β addresses only one of the three identified gaps (RetailBench long-horizon, contamination, chronological awareness).diff --git a/v3/docs/adr/ADR-348-dream-cycle-swarm-adaptive-topology-selector.md b/v3/docs/adr/ADR-348-dream-cycle-swarm-adaptive-topology-selector.mdnew file mode 100644index 0000000000..d37674d2cd--- /dev/null+++ b/v3/docs/adr/ADR-348-dream-cycle-swarm-adaptive-topology-selector.md@@ -0,0 +1,74 @@+# ADR-348: Task-Adaptive Swarm Topology Selector++- **Status:** Proposed+- **Authors:** claude (dream-cycle agent, 2026-06-19)+- **Dream Cycle Issue:** #TBD (filed same night)+- **Evidence Grade:** A (arXiv 2602.16873, SWE-bench Verified / GPQA Diamond / HotpotQA)++---++## Context++Ruflo's `swarm_init` accepts a fixed `topology` parameter set at configuration time. The default is `hierarchical` (anti-drift mandate, CLAUDE.md). This is correct for coordination stability but suboptimal for task performance: AdaptOrch (arXiv 2602.16873, Feb 2026) demonstrates that **hybrid topology wins 49.7% of real tasks while hierarchical wins only 19%**, and dynamic selection yields +9.8pp on SWE-bench Verified, +6.9pp on GPQA Diamond, +8.1pp on HotpotQA over the single best static topology.++The Ruflo swarm currently has no mechanism to inspect a task's dependency structure before committing to a topology. Every invocation defaults to `hierarchical` regardless of whether the task is trivially parallelisable (fan-out), strictly serial (pipeline), or genuinely hierarchical (coordinator + workers).++---++## Decision++Add a **topology selector** module (`@claude-flow/swarm/topology-selector`) that runs before `swarm_init` and emits a recommended topology from `[parallel, sequential, hierarchical, hybrid]` based on a lightweight task dependency graph analysis.++### Selector logic (heuristic v1)++| Condition | Recommended topology |+|---|---|+| All subtasks independent (no shared outputs) | `parallel` |+| Linear chain (each task feeds exactly one successor) | `sequential` |+| One coordinator, N independent workers | `hierarchical` |+| Mixed (parallel groups + sequential dependencies) | `hybrid` |+| Graph unavailable or parsing error | `hierarchical` (existing default β anti-drift safe fallback) |++The selector is **opt-in per invocation**: callers pass `topology: "auto"` to `swarm_init`; all existing callers with an explicit topology continue to work unchanged.++### Interface++```typescript+// @claude-flow/swarm/topology-selector+export interface TaskGraph {+ nodes: string[]; // subtask IDs+ edges: [string, string][]; // dependency edges (from β to)+}++export type Topology = 'parallel' | 'sequential' | 'hierarchical' | 'hybrid';++export function selectTopology(graph: TaskGraph): Topology;+```++`swarm_init` maps `topology: "auto"` β calls `selectTopology(graph)` β passes resolved topology to existing init logic.++---++## Consequences++### Positive+- Expected +9β23% accuracy on heterogeneous task mixes (Grade A evidence from AdaptOrch)+- Zero breaking change: existing explicit-topology callers are unaffected+- Selector itself is O(|nodes| + |edges|) β negligible overhead+- Fallback to `hierarchical` preserves anti-drift guarantee when graph is unavailable++### Negative+- Callers must supply a `TaskGraph` to benefit; unstructured free-text tasks cannot be auto-analysed without an LLM parse step (Tier 2/3 cost)+- Hybrid topology increases inter-agent messaging complexity; requires thorough integration testing before enabling by default++### Neutral+- CLAUDE.md anti-drift rule ("ALWAYS use hierarchical topology for coding swarms") remains the stated default; `topology: "auto"` is an explicit opt-in++---++## Implementation Notes++- Files: `v3/@claude-flow/cli/src/swarm/topology-selector.ts`, `topology-selector.test.ts`+- No schema changes; `topology` field gains `"auto"` as a valid value+- Add integration tests against AdaptOrch-style task graphs (coding, reasoning, RAG shapes)+- No ADR needed for the SFDA swarm-agent failover or ruvector backend adapter (implementation-level changes)diff --git a/v3/docs/adr/ADR-349-dream-cycle-intelligence-flare-lookahead.md b/v3/docs/adr/ADR-349-dream-cycle-intelligence-flare-lookahead.mdnew file mode 100644index 0000000000..ecb226f657--- /dev/null+++ b/v3/docs/adr/ADR-349-dream-cycle-intelligence-flare-lookahead.md@@ -0,0 +1,107 @@+# ADR-349 β FLARE-Style Lookahead Planning Buffer for SONA Intelligence Layer++**Status**: Proposed+**Date**: 2026-06-22+**Authors**: claude (dream-cycle agent, 2026-06-22)+**Related**: ADR-017 (RuVector Integration), ADR-009 (Hybrid Memory Backend), ADR-151 (Harness Intelligence Layer)+**Affects**: `@claude-flow/memory`, `@claude-flow/hooks` (SONA optimizer), `[email protected]+`, `[email protected]+`++---++## Context++Ruflo's SONA (Self-Optimizing Neural Architecture) layer adapts at 0.0043ms/adapt using reactive pattern matching: it observes a decision context, retrieves the nearest pattern via HNSW, and commits to the matching MoE expert gate. This is a greedy, step-wise policy.++FLARE (Future-aware LookAhead with Reward Estimation, arXiv:2601.22311, Jan 2026) identifies a structural failure mode in step-wise LLM agent reasoning: **myopic commitment**. Locally optimal choices at each step cascade into globally suboptimal outcomes over planning horizons β₯3 steps. FLARE addresses this via:++1. Explicit **lookahead simulation** β simulate N future states before committing+2. **Value backpropagation** β propagate reward estimates from simulated futures to the current decision+3. **Limited commitment** β avoid irreversible bindings until lookahead confirms global optimality++Result: LLaMA-8B + FLARE consistently outperforms GPT-4o + standard CoT on long-horizon multi-step planning tasks across multiple benchmarks (paper claim, confidence B β abstract-level; full numerical tables in full PDF).++No agent framework (LangGraph v0.4, CrewAI 0.105, AutoGen 1.0 GA, OpenAI Agents SDK) currently ships explicit lookahead planning as a built-in intelligence primitive. This is an open SOTA opportunity for Ruflo.++**Drift note**: Prior intelligence deep-dive ADR (issue #2401, 2026-06-17) addressed benchmark contamination and RetailBench long-horizon failure at the evaluation layer. ADR-349 addresses the complementary architectural gap at the planning/routing layer.++---++## Decision++Add a **depth-3 lookahead buffer** to SONA before committing to a MoE route selection:++```+Current: observe(ctx) β HNSW retrieve β MoE gate β commit++Proposed: observe(ctx) β HNSW retrieve β [lookahead: simulate 3 steps via MoE oracle]+ β backpropagate value estimates+ β select globally optimal gate β commit+```++### Implementation Sketch++```typescript+// In @claude-flow/memory / sona-optimizer.ts+interface LookaheadConfig {+ depth: number; // default 3+ branchFactor: number; // default 2 (top-2 MoE gates considered per step)+ discountFactor: number; // default 0.9+}++async function sonaRouteWithLookahead(+ ctx: AgentContext,+ config: LookaheadConfig = { depth: 3, branchFactor: 2, discountFactor: 0.9 }+): Promise<MoEGateSelection> {+ const candidates = await moeGate.topK(ctx, config.branchFactor);+ const values = await Promise.all(+ candidates.map(c => simulateFuture(ctx, c, config.depth, config.discountFactor))+ );+ return candidates[values.indexOf(Math.max(...values))];+}+```++### What Changes++| Component | Change |+|---|---|+| `sona-optimizer.ts` | Add `routeWithLookahead()` wrapper; keep existing `route()` as fast-path |+| MoE router | Expose `topK(ctx, k)` method returning top-k gate candidates |+| SONA config | Add `lookaheadDepth: number` (default 3); `lookaheadEnabled: boolean` (default false until benchmarked) |+| Hooks post-task | Record lookahead-enabled vs disabled decisions for A/B neural training |++---++## Consequences++**Positive**+- Eliminates myopic commitment failure for agent pipelines β₯3 steps deep+- Compatible with existing EWC++ memory preservation (lookahead uses read-only oracle calls)+- Feature-flaggable: `lookaheadEnabled: false` preserves current 0.0043ms path+- Positions Ruflo ahead of all four main competitors on long-horizon intelligence++**Negative / Risks**+- Added latency: depth-3 lookahead with branchFactor=2 = 2^3β1 = 7 extra oracle calls per route decision (estimate 1β10ms depending on MoE complexity; requires profiling)+- Simulation fidelity: MoE oracle may not accurately simulate real future states without grounded environment feedback+- Premature optimization: benefit only materializes for tasks with actual β₯3 planning steps; most short SONA decisions gain nothing++**Mitigation**+- Default `lookaheadEnabled: false`; enable via config for long-horizon agent types only+- Benchmark lookahead latency vs task-completion gain on LoCoMo + RetailBench equivalents before enabling by default+- Cap `branchFactor=1` for low-budget contexts (greedy lookahead, no branching)++---++## Open Questions++1. Should lookahead be triggered by task complexity score (>0.7) rather than always-on?+2. Can lookahead reuse the EWC++ Hessian diagonal as a value proxy without separate simulation?+3. How does lookahead interact with ReasoningBank trajectory replay β should simulated paths be stored?++---++## References++- arXiv:2601.22311 β "Why Reasoning Fails to Plan: A Planning-Centric Analysis of Long-Horizon Decision Making in LLM Agents" (Jan 2026)+- arXiv:2511.17332v2 β "Agentifying Agentic AI" (AAAI 2026 Bridge Program)+- [Dream Cycle Issue #2401](https://github.com/ruvnet/ruflo/issues/2401) β Prior intelligence deep-dive (benchmark contamination)+- [Dream Cycle Research Report](dream-2026-06-22-intelligence.md)diff --git a/v3/docs/adr/ADR-350-dream-cycle-swarm-trust-weighted-consensus.md b/v3/docs/adr/ADR-350-dream-cycle-swarm-trust-weighted-consensus.mdnew file mode 100644index 0000000000..ce412de868--- /dev/null+++ b/v3/docs/adr/ADR-350-dream-cycle-swarm-trust-weighted-consensus.md@@ -0,0 +1,69 @@+# ADR-350: Trust-Weighted Consensus for Swarm Coordination++| Field | Value |+|-------|-------|+| **Status** | Proposed |+| **Authors** | claude (dream-cycle agent, 2026-06-24) |+| **Date** | 2026-06-24 |+| **Dream Cycle Surface** | swarm (DEEP) |+| **Supersedes** | none |+| **Related** | ADR-162 (prior swarm ADR, 2026-06-19) |++---++## Context++The 2026-06-24 dream-cycle session surveyed swarm SOTA for 2026. Two peer-reviewed papers are directly actionable:++1. **SGTO-MAS** (arXiv:2606.07940) demonstrates that adding a Bayesian trust score to consensus voting reduces degradation under adversarial agent removal from unbounded to only **2.5 %** and under consensus disruption to **5.3 %**, while maintaining a consensus level of **0.8764**. The mechanism: each agent maintains a `trust_score β [0,1]` updated via exponential smoothing (`trust_new = trust_old * 0.9 + outcome * 0.1`). Votes are weighted by trust score before the majority/quorum threshold is applied.++2. **RAPS** (arXiv:2602.08009) extends this with Bayesian reputation detection for malicious peers in publish-subscribe topologies, tested across 5 benchmarks.++Ruflo's current consensus stack (raft, byzantine, gossip, CRDT, quorum) has **no trust or reputation layer**. A compromised or misbehaving agent has equal voting weight to a healthy one. This is a security and reliability gap.++## Decision++Add an optional trust-weighted mode to Ruflo's consensus mechanisms, starting with `raft` and `byzantine`:++1. **Agent heartbeat extension:** Add `trust_score: number` (0β1, default 1.0) to the per-agent state tracked by `hierarchical-coordinator` and `raft-manager`.++2. **Vote weighting:** Before applying quorum threshold, multiply each vote by the sender's `trust_score`. Effective majority = `sum(trust_i * vote_i) / sum(trust_i) >= 0.5`.++3. **Trust update on outcome:** After each task cycle, update trust via `trust_i = 0.9 * trust_i + 0.1 * outcome_i` where `outcome_i β {0, 1}` based on whether agent i's output passed validation.++4. **Configuration flag:** `trustWeightedConsensus: boolean` (default `false`) in swarm init options. Existing behaviour unchanged when disabled.++5. **Malicious agent eviction threshold:** When `trust_i < 0.2` for three consecutive cycles, the agent is marked `degraded` and removed from the quorum pool by the queen coordinator.++## Consequences++**Positive:**+- Matches SGTO-MAS Grade A benchmark: β€5.3 % degradation under adversarial conditions+- Zero new external dependencies (pure arithmetic, no library required)+- Backwards-compatible via feature flag+- Enables detection of systematically failing agents (network partition, zombie processes)++**Negative:**+- Adds state to agent heartbeats (~8 bytes per agent per cycle)+- Cold-start problem: all agents start at trust 1.0; rogue agents take β₯10 cycles to degrade below 0.5+- Trust convergence speed (Ξ±=0.1) is a tunable guess β requires empirical validation++## Implementation Notes++- Touch files: `v3/@claude-flow/cli/src/swarm/raft-manager.ts`, `hierarchical-coordinator.ts`, `swarm-init.ts`+- Estimated effort: 2 engineering days+- Test: inject a 25 % fault rate into one agent in a 4-agent raft quorum; assert consensus remains β₯0.75 after 20 cycles+- Do NOT change the default `trustWeightedConsensus: false`; this is opt-in only++## Alternatives Considered++- **Static reputation list** (block known-bad agent IDs at config time): rejected β doesn't adapt at runtime.+- **Full Byzantine BFT only** (already available as `byzantine` topology): rejected as overkill for non-adversarial deployments; trust weighting is lighter and composable with any topology.+- **No action** (wait for more data): rejected β Grade A paper with numeric benchmarks justifies implementation.++## References++- arXiv:2606.07940 β SGTO-MAS (Secure Gorilla Troops Optimization for Multi-Agent Systems)+- arXiv:2602.08009 β RAPS (Reputation-Aware Publish-Subscribe)+- Dream Cycle research file: `v3/docs/research/dream-2026-06-24-swarm.md`+- Prior swarm ADR: ADR-162 (2026-06-19)diff --git a/v3/docs/adr/ADR-351-dream-cycle-performance-stateful-execution-loop.md b/v3/docs/adr/ADR-351-dream-cycle-performance-stateful-execution-loop.mdnew file mode 100644index 0000000000..139f98d86d--- /dev/null+++ b/v3/docs/adr/ADR-351-dream-cycle-performance-stateful-execution-loop.md@@ -0,0 +1,73 @@+# ADR-351: Stateful Execution Loop with KV-Cache Discipline and Agent Execution Graphs++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-06-25)+**Dream Cycle Issue**: #2462 (2026-06-25 nightly research)+**Surfaces**: performance (DEEP), security + hive-mind (SCAN)++---++## Context++June 2026 arXiv research (five Grade A papers) demonstrates that multi-agent orchestration frameworks leave 2β4Γ performance on the table by not enforcing KV-cache discipline, not scheduling tasks by dependency graph, and not applying response-level speculative routing.++Key findings:+- **Stateful Inference** (arXiv:2605.26289): O(n_t)βO(Ξ_t) KV-cache persistence β 4.2Γ speedup on 35-turn agent workflows (Grade A)+- **PolyKV** (arXiv:2604.24971): shared compressed KV pool for concurrent agents β 97.7% memory reduction, 15 agents (Grade A)+- **SAGA** (arXiv:2605.00528): workflow-atomic scheduling via Agent Execution Graphs β 1.64Γ task completion vs vLLM (Grade A)+- **RLM-Cascade** (arXiv:2606.22840): response-level speculative decoding β 45.8% API cost reduction (Grade A)++Ruflo currently:+1. Passes full context on every agent turn (O(n_t) cost growth)+2. Mutates prompts between turns, breaking provider-side prefix caching+3. Schedules all tasks FIFO without exploiting task dependency graphs+4. Routes all agent calls to the same model tier regardless of response predictability++No competitor (LangGraph 1.2.6, AutoGen 0.7.5, CrewAI 1.14.7, OpenAI Agents SDK) has shipped any of these mechanisms.++---++## Decision++Implement three layered optimizations in the order of implementation cost vs. impact:++### Layer 1: Prefix-Stable Prompt Discipline (low cost, 2β4Γ impact)+Enforce a structural rule in agent construction: the system prompt and static context form a **fixed prefix** that is never mutated between turns. Only the dynamic message tail changes. This enables provider-side KV-cache reuse (Claude's prompt caching) without any infrastructure change.++**Where**: `v3/@claude-flow/cli/src/agents/agent-executor.ts` β add `staticPrefix` / `dynamicSuffix` split to the agent message builder.++### Layer 2: Agent Execution Graph Scheduler (medium cost, 1.6Γ impact)+Expose `dependsOn: string[]` in `SwarmTaskConfig`. Before dispatching a swarm, topological-sort tasks and run independent tasks concurrently. This replaces the implicit FIFO sequencing.++**Where**: `v3/@claude-flow/cli/src/swarm/scheduler.ts` (new file under 200 lines).++### Layer 3: Response-Level Speculative Routing (medium cost, 40β50% cost impact)+Add a `pre-agent-call` hook that routes low-complexity tool-call sequences through a draft model (Haiku), verifies with the primary model only on mismatch. Use the existing 3-tier model routing table from ADR-026.++**Where**: `v3/@claude-flow/hooks/src/workers/speculative-router.ts` (new worker).++---++## Consequences++**Positive**:+- 2β4Γ token/cost reduction per long-running agent (Layer 1 alone)+- 1.6Γ swarm throughput without model changes (Layer 2)+- 40β50% API cost reduction on tool-heavy swarms (Layer 3)+- No breaking API changes for users++**Negative / Risks**:+- Layer 1 requires audit of all agent prompt builders to enforce prefix stability+- Layer 3 introduces draft-model latency overhead when verification triggers+- SAGA results are on GPU-serving (vLLM), not API-serving; Layer 2 gains may be lower in API-gated deployments++**Non-decisions**: KV-cache pooling (PolyKV pattern) is not applicable to API-based deployments; deferred until a self-hosted inference path exists.++---++## Implementation Notes++- Layer 1 target: `agent-executor.ts` β 1β2 days+- Layer 2 target: new `scheduler.ts` in swarm package β 3β5 days+- Layer 3 target: new `speculative-router.ts` worker β 3β5 days+- Verification: benchmark with an 8-agent swarm on a fixed task; measure token count and wall-clock time before/after each layerdiff --git a/v3/docs/adr/ADR-352-mcp-tool-permission-attestation.md b/v3/docs/adr/ADR-352-mcp-tool-permission-attestation.mdnew file mode 100644index 0000000000..a226e7cbff--- /dev/null+++ b/v3/docs/adr/ADR-352-mcp-tool-permission-attestation.md@@ -0,0 +1,101 @@+# ADR-352: MCP Tool Permission Attestation (Min-Privilege Contract)++- **Status**: Proposed+- **Authors**: claude (dream-cycle agent, 2026-06-26)+- **Date**: 2026-06-26+- **Dream Cycle Issue**: TBD (filed same night)++---++## Context++The 2026-06-26 Dream Cycle SOTA sweep surfaced two converging evidence streams that identify MCP tool-call boundaries as the primary unguarded attack surface in LLM agent systems:++1. **ShareLock (arXiv 2026, Grade A)** β Achieves >90% poisoning ASR on MCP-connected agents via Shamir's threshold scheme distributed across multiple benign-looking tool servers. The attack exploits the absence of tool-level permission declarations: any server can inject arbitrary behaviour if the agent does not enforce a privilege contract at dispatch time.++2. **ToolPrivBench (arXiv 2026, Grade A)** β 64.9% of Qwen3-8B tool calls escalate to higher-privilege tools than the task requires (OPUR metric). Post-training with privilege-aware objectives reduces OPUR to 27.02%. The benchmark formalises 544 scenarios across 8 domains and 5 risk patterns.++3. **ControlPlane paper (arXiv 2026, Grade A)** β Fewer than 1% of coding agents declare explicit permission boundaries, making over-privilege the default posture.++Ruflo's current security module (`@claude-flow/security`) provides `SafeExecutor` (command injection), `InputValidator` (Zod), and `PathValidator` (traversal). None operate at the MCP tool registration or dispatch layer. Tool calls are forwarded without a declared min-privilege contract.++---++## Decision++Introduce a **MCP Tool Permission Attestation** layer with two integration points:++### 1. Tool Registration Contract++Every MCP tool registration (server-side and client-side stub) must carry a `permissions` manifest:++```typescript+interface ToolPermissionContract {+ toolName: string;+ minPrivilege: {+ filesystem?: 'none' | 'read' | 'write' | 'execute';+ network?: 'none' | 'outbound' | 'inbound' | 'full';+ process?: 'none' | 'spawn' | 'kill';+ memory?: 'none' | 'read' | 'write';+ agentScope?: 'none' | 'self' | 'team' | 'global';+ };+ declaredAt: string; // ISO date of contract signature+ trustLevel: 'official' | 'community' | 'unverified';+}+```++Tools without a `permissions` field are assigned `trustLevel: 'unverified'` and routed through a stricter sandbox.++### 2. Dispatch-Time Enforcement++`SafeExecutor` is extended with a `McpPermissionGuard` that runs before every tool dispatch:++```+Request β McpPermissionGuard β {+ if call.escalatesAbove(tool.minPrivilege) β REJECT (log + alert)+ if tool.trustLevel === 'unverified' && call.privilege > 'read' β BLOCK+ else β forward to SafeExecutor β execute+}+```++Rejection emits a structured event to the security audit log; repeated escalation triggers a circuit-breaker (ADR-097 pattern).++---++## Target Metrics++| Metric | Baseline | Target |+|--------|----------|--------|+| OPUR (over-privilege usage rate) | ~64.9% (ToolPrivBench Qwen3-8B baseline) | β€ 30% |+| ShareLock-style poisoning ASR | >90% (no defence) | < 10% |+| Tools with declared contracts | 0% | 100% of official tools; β₯ 80% of community tools |++---++## Consequences++**Positive:**+- Closes the primary attack vector identified by ShareLock+- Provides a measurable ToolPrivBench-equivalent baseline for continuous monitoring+- Composable with ADR-093 (MCP audit) and ADR-131 (tool output guardrail)++**Negative / Risk:**+- Breaking change for tool servers that currently omit `permissions` β requires migration period+- OPUR measurement requires a ToolPrivBench-compatible evaluation harness (new test infrastructure)+- Unverified tools silently downgraded to read-only scope β may surprise plugin authors++## Alternatives Considered++- **Prompt-level privilege hints only** (rejected): Relies on model compliance; ToolPrivBench shows models ignore prompts under tool-failure pressure+- **Runtime syscall tracing** (deferred): Effective but requires platform-specific instrumentation; out of scope for v3.7 timeframe+- **Output-only guardrail** (existing ADR-131/146): Insufficient β output sanitisation does not prevent the upstream tool invocation++## References++- ShareLock: arXiv 2026 (MCP threshold poisoning, >90% ASR)+- ToolPrivBench: arXiv 2026 (64.9% OPUR baseline, 27.02% post-training)+- ControlPlane: arXiv 2026 (<1% agents declare permission boundaries)+- ADR-092: MCP tool validation bugfixes+- ADR-093: MCP audit May 2026 remediation+- ADR-097: Federation budget circuit-breaker (reused pattern)+- ADR-131/146: Tool output guardraildiff --git a/v3/docs/adr/ADR-353-dream-cycle-intelligence-skill-distillation.md b/v3/docs/adr/ADR-353-dream-cycle-intelligence-skill-distillation.mdnew file mode 100644index 0000000000..399e783d69--- /dev/null+++ b/v3/docs/adr/ADR-353-dream-cycle-intelligence-skill-distillation.md@@ -0,0 +1,59 @@+# ADR-353: Trace-to-Skill Distillation for Intelligence Pipeline++- **Status**: Proposed+- **Date**: 2026-06-27+- **Authors**: claude (dream-cycle agent, 2026-06-27)+- **Dream Cycle**: intelligence deep-dive, slot 2++---++## Context++Ruflo's intelligence pipeline records agent execution traces via 17 hooks + 12 background workers and stores them in AgentDB / ReasoningBank. However, the pipeline terminates at the recording step β no subsequent compilation converts raw traces into reusable procedural skills.++SKILL-DISCO (Guo, Qi, Gu β arXiv 2026) demonstrates that distilling agent execution traces into compiled procedural skills improves task success by **+22%** on ALFWorld and **statistically significant improvement** on WebArena vs. embedding-only trace storage. The mechanism: traces are chunked into sub-goals, each sub-goal is summarised into a parameterised skill template, and the template library is retrieved by future agents at planning time rather than raw trace replay.++A parallel gap exists in Ruflo's reward model: SONA verdicts use a fixed `success/failure` schema. "The Verification Horizon" (Wang et al., arXiv 2026) demonstrates that fixed rewards become inadequate as base model capability increases β verification must co-evolve with the generator.++## Decision++Add a **skill distillation worker** (`distill-skills`) as the 13th background worker in the hooks system. The worker:++1. Subscribes to `post-task` events where the task outcome was recorded as `success=true`.+2. Passes the execution trace JSON (hook event stream for the task) to a LoRA-fine-tuned summarisation step using the existing SONA neural substrate.+3. Outputs a **procedural skill record** stored in AgentDB under the `skill://` URI prefix:+ ```+ skill://<task-type>/<semantic-slug>/<version>+ ```+4. At agent planning time, the `pre-task` hook queries AgentDB for `skill://` records matching the current task's embedding before falling back to raw ReasoningBank retrieval.++Additionally, introduce a **versioned verdict registry** to address the Verification Horizon gap:++- Add `verdict_schema_version` (integer) to all new ReasoningBank entries.+- A periodic probe task (weekly) runs a CCTU-style constraint set against the current base model; if score improves >5% vs. the previous probe, the schema version increments and a migration backfills recent entries.++## Consequences++**Positive**:+- Aligns with SKILL-DISCO SOTA; expected improvement in agent task success on repeat task classes.+- Skill library is inspectable (stored in AgentDB as structured records) β enables human auditing.+- Versioned rewards future-proof SONA against base model capability drift.++**Negative / Risks**:+- LoRA distillation step adds ~50β200ms latency to `post-task` hook on success path; must be async / non-blocking.+- `skill://` URI namespace requires AgentDB schema migration (add `uri_prefix` column to `vector_indexes`).+- False positives: a successful trace may encode a lucky path, not a generalizable skill; mitigate by requiring β₯3 successful traces before promoting to a skill.++## Implementation Notes++- New file: `v3/@claude-flow/hooks/src/workers/distill-skills.ts` (<500 lines)+- Extend: `v3/@claude-flow/memory/src/agentdb/schema.ts` (add `skill_library` table)+- Extend: `v3/@claude-flow/hooks/src/hooks/post-task.ts` (emit trace payload to worker)+- Extend: `v3/@claude-flow/hooks/src/hooks/pre-task.ts` (query skill library before raw retrieval)+- New test: `tests/hooks/distill-skills.test.ts`++## References++- SKILL-DISCO: "Distilling and Compiling Agent Traces into Reusable Procedural Skills" β Guo, Qi, Gu, arXiv 2026+- The Verification Horizon: "No Silver Bullet for Coding Agent Rewards" β Wang, Zhang, Liu, arXiv 2026+- Dream Cycle issue: #TBD (2026-06-27 intelligence deep-dive)diff --git a/v3/docs/adr/ADR-354-agentdb-write-verification-temporal-supersession.md b/v3/docs/adr/ADR-354-agentdb-write-verification-temporal-supersession.mdnew file mode 100644index 0000000000..63b8e751a4--- /dev/null+++ b/v3/docs/adr/ADR-354-agentdb-write-verification-temporal-supersession.md@@ -0,0 +1,86 @@+# ADR-354: AgentDB Memory Write Verification and Temporal Supersession Layer++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-06-28)+**Dream Cycle Issue**: #TBD (filed same night)+**References**: TRUSTMEM (arXiv 2606.25161), MemStrata (arXiv 2606.26511), MemClaw (arXiv 2606.24535)++---++## Context++Two Grade A arXiv papers published in June 2026 expose two distinct but related gaps in AgentDB's write pipeline:++**Gap 1 β No write verification**: AgentDB commits memory updates without checking coverage (all key facts captured), preservation (no prior facts silently dropped), or faithfulness (no new facts hallucinated). TRUSTMEM (Yang et al., 2606.25161) demonstrates that unguarded memory updates accumulate 40.1% omissions, 79.1% corruptions, and 50.0% hallucinations at scale. A `MemoryTransitionVerifier` reduces all three.++**Gap 2 β No temporal supersession**: AgentDB uses embedding similarity to detect stale facts, which achieves only 0.20β0.47 accuracy on evolving-knowledge workloads. MemStrata (Yadav, 2606.26511) shows that deterministic supersession rules β keyed on `entity:predicate` pairs β achieve 0.95β1.00 accuracy on the same workloads by hard-replacing rather than similarity-ranking.++These gaps are architectural: both require changes to the AgentDB write path and the maintenance module, not just tuning of existing retrieval parameters.++---++## Decision++Add two new components to AgentDB's write path:++### 1. MemoryWriteVerifier (post-write gate)++Insert a verification step after LLM-produced memory updates and before they are committed to AgentDB storage:++```typescript+interface MemoryWriteVerification {+ coverage: number; // 0β1: fraction of source facts captured+ preservation: number; // 0β1: fraction of prior facts retained where expected+ faithfulness: number; // 0β1: fraction of written facts grounded in source+ verdict: 'commit' | 'retry' | 'rollback';+}+```++- `coverage < 0.8` β retry with gap-filling prompt+- `faithfulness < 0.85` β rollback + alert+- `preservation < 0.9` on a non-superseding write β rollback + alert+- All thresholds pass β commit++Implementation: lightweight LLM-as-judge call (Haiku tier, ~500ms, ~$0.0002 per write) comparing the proposed write against the source context and prior memory state.++### 2. EntityPredicateSupersessionLayer (write-time key resolution)++Every AgentDB write MUST declare an `entityPredicateKey` string (e.g., `"user:prefs:theme"`, `"agent:ruflo:version"`). The write path checks for an existing record with the same key:+- If found β hard-supersede (delete old, write new, record provenance link)+- If not found β normal insert++This replaces the current similarity-threshold stale-detection approach. Keys can be auto-generated from the entity + predicate fields of a structured memory record, or manually specified.++---++## Consequences++**Positive**:+- Target β₯50% reduction in memory corruption events (TRUSTMEM Grade A benchmark extrapolated to Ruflo workloads)+- Target 0.90+ accuracy on internal evolving-knowledge eval (vs ~0.40 estimated from current RAG baseline)+- Provenance chain enables future MemClaw-style derivation reconstruction++**Negative / Trade-offs**:+- Write latency: +500ms per LLM-verified write (Haiku tier). Mitigation: async verification with optimistic commit, rollback on failure within 5s window.+- EntityPredicateKey must be defined for every write β adds schema discipline burden on callers. Mitigation: auto-generate from structured fields where possible; fall back to hash of content for unstructured writes (no supersession, just insert).+- Not applicable to bulk ingestion flows (ReasoningBank trace writes) β verification gate is for agent-produced memory updates only.++---++## Implementation Path++| Phase | Work | Target |+|-------|------|--------|+| 1 | Implement `MemoryWriteVerifier` (Haiku-judge, 3 metrics) | Sprint N+1 |+| 2 | Add `entityPredicateKey` field to AgentDB write schema | Sprint N+1 |+| 3 | Implement `EntityPredicateSupersessionLayer` in write path | Sprint N+1 |+| 4 | Instrument + measure against internal evolving-knowledge eval set | Sprint N+2 |+| 5 | Add provenance tracking per write (writer identity, supersedes pointer) | Sprint N+2 |++---++## Alternatives Considered++- **Tune HNSW similarity threshold** to better detect stale facts: rejected β MemStrata Grade A evidence shows similarity-based approaches plateau at 0.47, well below the 0.90+ target regardless of threshold.+- **Skip write verification, rely on retrieval-time re-ranking**: rejected β TRUSTMEM shows 79.1% corruption rate at write time; corrupted entries degrade retrieval regardless of re-ranking quality.+- **Adopt MemStrata directly as a dependency**: under consideration for later phase β for now, implement the supersession principle natively to avoid external dependency in the core write path.diff --git a/v3/docs/adr/ADR-355-swarm-rl-stopping-policy.md b/v3/docs/adr/ADR-355-swarm-rl-stopping-policy.mdnew file mode 100644index 0000000000..8423de02a2--- /dev/null+++ b/v3/docs/adr/ADR-355-swarm-rl-stopping-policy.md@@ -0,0 +1,78 @@+# ADR-355: Reinforcement-Learned Stopping Policy for Ruflo Swarm Orchestration++**Status:** Proposed+**Date:** 2026-06-29+**Authors:** claude (dream-cycle agent, 2026-06-29)+**Related issues:** dream-cycle #2026-06-29, arXiv 2605.02801++---++## Context++arXiv 2605.02801 (May 2026) surveys RL methods for LLM-based multi-agent orchestration and identifies five core sub-decisions: spawn timing, delegation, communication, aggregation, and **stopping**. After curating 84 papers, the authors find zero explicit RL training methods for the stopping decision. Every production system β LangGraph, AutoGen, CrewAI, OpenAI Swarm, and Ruflo β uses static stopping policies (token budgets, task completion signals, or hard agent-count caps).++Ruflo's current stopping mechanism is `maxAgents: 8` (CLAUDE.md default) plus task completion. This cap is not learned; it does not adapt to task complexity, available resources, or quality signal from completed agents.++---++## Decision++Implement an **RL stopping-decision policy** as a lightweight head on Ruflo's orchestrator. The policy observes:+- Number of agents spawned so far+- Aggregated partial results from completed agents (quality signal)+- Task complexity estimate (from `hooks route` output)+- Time elapsed vs. budget++And outputs a binary decision: **spawn more agents** or **aggregate and stop**.++Training source: Ruflo's existing `post-task` hook events become orchestration traces. Each swarm run produces a labeled trace (task β agents spawned β quality of final output). A simple bandit or REINFORCE head is trained offline on these traces.++---++## Implementation++1. Define orchestration trace schema (extends `post-task` hook payload):+ ```json+ {+ "task_id": "...",+ "complexity_score": 0.0β1.0,+ "agents_spawned": [...],+ "stopping_step": N,+ "final_quality_score": 0.0β1.0+ }+ ```++2. Add `StoppingPolicyHead` to `@claude-flow/hooks` workers (new `stopping-policy` worker, priority: normal).++3. Wire into swarm orchestrator: before each `agent spawn`, check policy; if `stop=true`, proceed to aggregation phase.++4. Start with a simple rule-based policy (threshold on complexity_score Γ agents_spawned) as a warm-start before RL training accumulates enough traces.++5. Expose via config: `CLAUDE_FLOW_STOPPING_POLICY=rl|static|threshold` (default: `static` to preserve existing behavior).++---++## Consequences++- **Positive:** Adapts to task complexity; avoids wasted agent spawns on simple tasks; closes the last un-automated orchestration sub-decision.+- **Positive:** Removes the hard `maxAgents=8` cap as a scaling constraint β policy naturally gates agent count.+- **Negative:** Requires trace collection period before RL training is meaningful (~50+ swarm runs).+- **Negative:** Adds a new worker to the hooks system (8th worker in low-priority tier).+- **Neutral:** Default remains `static` β no behavior change until opt-in.++---++## Alternatives Considered++- **Larger static cap** (e.g., maxAgents=16): Doesn't solve the fundamental problem; just moves the arbitrary threshold.+- **LLM-judged stopping**: Ask the orchestrator LLM to decide. Too expensive per decision; defeats latency targets.+- **External timeout only**: Already available via budget limits; orthogonal, not a substitute.++---++## References++- arXiv 2605.02801 β "Reinforcement Learning for LLM-based Multi-Agent Systems through Orchestration Traces" (May 2026)+- arXiv 2602.16873 β "AdaptOrch: Task-Adaptive Multi-Agent Orchestration" (Feb 2026)+- Ruflo CLAUDE.md β Swarm Anti-Drift Defaults, 3-Tier Model Routing (ADR-026, ADR-143)+- Dream Cycle Report: `docs/dream-cycle/2026-06-29-swarm.md`diff --git a/v3/docs/adr/ADR-356-dream-cycle-performance-cross-agent-kvcache.md b/v3/docs/adr/ADR-356-dream-cycle-performance-cross-agent-kvcache.mdnew file mode 100644index 0000000000..f2478c1a95--- /dev/null+++ b/v3/docs/adr/ADR-356-dream-cycle-performance-cross-agent-kvcache.md@@ -0,0 +1,133 @@+# ADR-356: Cross-Agent KV-Cache Sharing for Swarm Performance++**Status:** Proposed+**Date:** 2026-06-30+**Authors:** claude (dream-cycle agent, 2026-06-30)+**Dream Cycle:** SLOT=0, DEEP=performance, source issue TBD+**Related ADRs:** ADR-006 (Unified Memory Service), ADR-009 (Hybrid Memory Backend), ADR-163 (Multi-Agent Benchmarking Suite)++---++## Context++As of June 2026, Ruflo spawns each agent in a swarm with an independent inference context. When 8 agents share the same system prompt (the default in CLAUDE.md's `maxAgents=8` anti-drift config), each agent sends the full system-prompt prefix to the model on every turn. At ~8k tokens per system prompt and 8 agents, this is 64k tokens of redundant prefill per swarm turn.++**TokenDance** (arXiv 2604.03143, April 2026, Grade A) is the first published paper to quantify collective KV-cache sharing across concurrent LLM agents:++| Metric | TokenDance Result |+|--------|-----------------|+| Per-agent cache reduction | **17.5Γ** |+| Concurrent agent scaling | **2.7Γ more agents** within same memory budget |+| Prefill speedup | **1.9Γ** |++The paper pools KV-cache entries by prefix hash across agents sharing a common context (system prompt, conversation history prefix), eliminating redundant computation. The approach is model-agnostic and does not require model weight changes.++**No competitor framework has productized this pattern.** LangGraph, AutoGen, CrewAI, and OpenAI Swarm all use per-agent independent contexts as of June 2026.++Additionally, **TraceLab** (arXiv Jun 2026, Grade A) characterizes 4,300 real coding-agent sessions and identifies **context bloat** (extensive input contexts with concise outputs) as the dominant latency driver β precisely the scenario that prefix-cache sharing addresses.++Ruflo already maintains a `hybrid` memory backend (SQLite + AgentDB) and a `SharedKVCache` concept exists at the infrastructure level (the `storeEntry`/`searchEntries` API). The missing piece is a prefix-hash pool that maps `(session_id, prompt_hash)` β `cached_kv_block_id` and is consulted before each agent turn.++---++## Decision++Add a `SharedKVCacheNamespace` class to `@claude-flow/memory` that implements prefix-hash pooling for swarm agents. The feature is **opt-in** via environment variable to avoid breaking existing behavior.++### Interface++```typescript+// @claude-flow/memory/src/shared-kv-cache.ts++export interface KVCacheEntry {+ prefixHash: string; // sha256 of (session_id + prompt_prefix)+ cachedTokenCount: number;+ hitCount: number;+ createdAt: number;+ lastHitAt: number;+}++export class SharedKVCacheNamespace {+ constructor(private sessionId: string, private agentDb: AgentDB) {}++ /** Check if prefix is already cached; return entry or null */+ async lookup(promptPrefix: string): Promise<KVCacheEntry | null>;++ /** Register a new cache entry after first computation */+ async register(promptPrefix: string, tokenCount: number): Promise<KVCacheEntry>;++ /** Record a cache hit */+ async hit(prefixHash: string): Promise<void>;++ /** Evict entries older than maxAgeMs or with hitCount < minHits */+ async evict(opts: { maxAgeMs?: number; minHits?: number }): Promise<number>;++ /** Return cache stats for the current session */+ async stats(): Promise<{ entries: number; totalHits: number; estimatedTokensSaved: number }>;+}+```++### Activation++```bash+# Enable (off by default)+CLAUDE_FLOW_KV_SHARE=true npx claude-flow swarm init --topology hierarchical++# Or via config+{+ "performance": {+ "kvCacheSharing": true,+ "kvCacheMaxAgeMs": 3600000,+ "kvCacheMinHits": 2+ }+}+```++### Integration Points++1. **`swarm init`** β when `CLAUDE_FLOW_KV_SHARE=true`, create a `SharedKVCacheNamespace` instance keyed to the swarm session ID+2. **`agent spawn`** β pass the shared namespace to each agent's context; agents consult before sending prefix tokens+3. **`post-task` hook** β evict stale entries after task completion+4. **`performance benchmark --suite kvcache`** β new benchmark mode to measure actual hit rates and token savings++---++## Consequences++### Positive+- Targets 17.5Γ per-agent cache reduction at 8-agent swarm scale (Grade A evidence from TokenDance)+- 1.9Γ prefill speedup expected for common-system-prompt workloads+- No model weight changes required; works with any provider+- `CLAUDE_FLOW_KV_SHARE=false` default preserves all existing behavior++### Negative / Risks+- Cache invalidation complexity: stale entries must be evicted when system prompt changes+- Cross-agent security boundary: shared cache entries must not leak agent-private state (mitigated by keying only on the shared prefix, not per-agent turn history)+- Memory overhead: the KV-cache namespace adds entries to AgentDB; must set TTL and size limits+- The TokenDance results are for a specific model and GPU configuration; actual speedup on Ruflo's provider calls (API, not GPU) may be lower (C β implementation-dependent)++### Neutral+- ADR-163's benchmarking suite must be extended (see Recommended Actions in gist) before any public claims are made about this speedup++---++## Implementation Plan++| Phase | Action | Effort |+|-------|--------|--------|+| 1 | Add `SharedKVCacheNamespace` class to `@claude-flow/memory` | 1β2 days |+| 2 | Wire into `swarm init` behind `CLAUDE_FLOW_KV_SHARE` flag | 0.5 days |+| 3 | Add `performance benchmark --suite kvcache` backend | 1 day |+| 4 | Publish measured numbers in CLAUDE.md under "Multi-Agent Benchmarks" | After Phase 3 |++Phase 4 must precede any public speedup claims.++---++## References++- TokenDance: arXiv 2604.03143 (Apr 2026) β collective KV-cache sharing+- TraceLab: arXiv Jun 2026 β context bloat as dominant latency driver+- UltraQuant: arXiv 2606.20474 (Jun 2026) β 4-bit KV caching (complementary, not prerequisite)+- ADR-163: multi-agent benchmarking suite β must be extended before publishing results+- ADR-006: Unified Memory Service β AgentDB backend used for cache namespace storagediff --git a/v3/docs/adr/ADR-357-dream-cycle-intelligence-dimension-aware-routing.md b/v3/docs/adr/ADR-357-dream-cycle-intelligence-dimension-aware-routing.mdnew file mode 100644index 0000000000..59ec34d3b2--- /dev/null+++ b/v3/docs/adr/ADR-357-dream-cycle-intelligence-dimension-aware-routing.md@@ -0,0 +1,101 @@+# ADR-357: Dimension-Aware Intelligence Routing for Heterogeneous Agent Pools++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-07-02)+**Dream Cycle Issue:** #TBD (filed same night)+**References:** arXiv:2605.17106 (HyDRA), arXiv:2606.13317 (SkillCAT), arXiv:2605.15706 (DMoA)++---++## Context++Ruflo v3.6's intelligence router selects between Haiku, Sonnet, and Opus based on a single scalar "complexity percentage" derived from task description length and keyword heuristics. This:++1. Ignores orthogonal capability dimensions (reasoning vs. code vs. debugging vs. tool-use)+2. Cannot route within a heterogeneous pool of same-tier models with different strengths+3. Produces suboptimal cost/quality tradeoffs β pays Opus rates for tasks that only need Sonnet-level code generation++HyDRA (arXiv:2605.17106, May 2026) demonstrates that scoring each query across **4 independent capability dimensions** β reasoning, code generation, debugging, and tool-use β with a lightweight ModernBERT-class encoder (86 ms CPU median latency) and applying a shortfall-matching selection algorithm achieves:++- 75.4% on SWE-Bench Verified vs. 74.2% single-model Claude Sonnet 4.6 baseline (+1.2 pp quality)+- 12.9% cost reduction in peak-quality mode+- 54.1% cost reduction at iso-quality (same pass rate as Sonnet)+- Decoupled from specific model catalog: config-only changes for new models, no retraining++SkillCAT (arXiv:2606.13317, Jun 2026) additionally shows that topology-aware skill retrieval (loading only task-relevant capabilities from a 3-tier hierarchy) compounds routing gains with +40.40% task score improvement at zero training cost.++---++## Decision++Extend Ruflo's intelligence routing layer with a **4-dimension capability scorer** replacing the current scalar complexity gate.++### Architecture++```+Query+ β+ βΌ+DimensionScorer (lightweight, β€100 ms)+ βββ reasoning_score β [0,1]+ βββ code_score β [0,1]+ βββ debug_score β [0,1]+ βββ tooluse_score β [0,1]+ β+ βΌ+ShortfallMatcher+ Input: dimension scores + available model pool+ Output: cheapest model meeting predicted requirements+ β+ βΌ+Model Dispatch (Haiku / Sonnet / Opus / heterogeneous pool)+```++### Implementation targets++| Component | File / Module | Change |+|-----------|--------------|--------|+| `DimensionScorer` | `v3/@claude-flow/cli/src/intelligence/dimension-scorer.ts` | New: 4-head sigmoid scorer |+| `ShortfallMatcher` | `v3/@claude-flow/cli/src/intelligence/shortfall-matcher.ts` | New: cost-optimal selection |+| `IntelligenceRouter` | `v3/@claude-flow/cli/src/intelligence/router.ts` | Replace complexity % with DimensionScorer output |+| `SkillCache` | `v3/@claude-flow/cli/src/intelligence/skill-cache.ts` | New: 3-tier topology-aware HNSW cache (domain/task-type/instance) |+| SONA hook | `v3/@claude-flow/hooks/src/post-task.ts` | Extract contrastive trajectories after each run |++---++## Consequences++**Positive:**+- Grade A evidence (two independent papers, reproducible 2026 benchmarks) supports β₯12% cost reduction and β₯1 pp quality lift at same cost+- Additive change β existing complexity-% gate becomes fallback when scorer unavailable+- Dimension scores are observable signals for SONA learning and hive-mind influence weighting (ADR-MAS-MoE, future)+- SkillCAT integration amplifies gains to ~40% on structured-data agent tasks++**Negative:**+- DimensionScorer adds 86 ms latency to routing decision (acceptable for tasks >500 ms)+- Requires a small labeled calibration set to tune sigmoid heads; cold-start uses HyDRA public weights+- Model pool heterogeneity must be declared in config β undeclared models fall through to legacy routing++**Neutral:**+- Does not change external CLI surface β transparent to callers+- No schema migration required for AgentDB (skill cache uses existing HNSW index)++---++## Alternatives Rejected++| Alternative | Reason |+|------------|--------|+| Keep scalar complexity gate | Leaves 12-54% cost savings and 40% quality uplift unused |+| Full DMoA per-step dynamic activation | Grade B only (no published benchmark numbers); too invasive for single ADR; revisit when numbers available |+| FJ-model influence weighting only | Orthogonal to routing; Grade B; defer to follow-on ADR |++---++## Review Checklist++- [ ] DimensionScorer prototype with calibration harness+- [ ] ShortfallMatcher unit tests (cost-optimal on known model pool)+- [ ] SkillCache topology-aware retrieval tested against SpreadsheetBench proxy+- [ ] SONA contrastive trajectory extraction validated on 3 prior session logs+- [ ] Latency budget confirmed β€100 ms p99 on commodity CPUdiff --git a/v3/docs/adr/ADR-358-automem-memory-rl-training-loop.md b/v3/docs/adr/ADR-358-automem-memory-rl-training-loop.mdnew file mode 100644index 0000000000..516922fcb0--- /dev/null+++ b/v3/docs/adr/ADR-358-automem-memory-rl-training-loop.md@@ -0,0 +1,99 @@+# ADR-358: AutoMem-Style RL Training Loop for AgentDB Memory Operations++**Status:** Proposed+**Date:** 2026-07-03+**Authors:** claude (dream-cycle agent, 2026-07-03)+**Source:** Dream Cycle research β Issue #[TBD], arXiv 2607.01224 (AutoMem)+**Tracking:** [Dream Cycle 2026-07-03] memory deep-dive++---++## Context++AutoMem (Wu et al., arXiv 2607.01224, July 1 2026) demonstrates that memory management is an **independently learnable RL skill**: treating memory operations (store, retrieve, update, summarize, discard) as first-class RL actions and training a dedicated memory-specialist agent from its own episode traces yields 2xβ4x improvement on long-horizon tasks (Crafter, MiniHack, NetHack), bringing a 32B open-weight model to frontier-competitive performance without changing the task policy at all.++Ruflo's AgentDB currently provides:+- HNSW-indexed vector retrieval (measured ~1.9xβ4.7x vs brute force at N=5kβ20k)+- SONA adaptation (0.0043ms/adapt) for neural weight tuning+- EWC++ for forgetting prevention+- A `consolidate` background worker (heuristic scheduling, no trajectory feedback)++None of these train the **management strategy** itself β *which* facts to store, *when* to discard, *how* to structure retrieval keys. SONA adapts weights; it does not optimize the memory scaffold or proficiency. The consolidate worker fires on a timer, not on outcome signals.++This is the single highest-leverage unimplemented memory optimization identified in the July 2026 SOTA sweep.++---++## Decision++Add an **AutoMem-compatible two-phase RL training loop** to AgentDB:++### Phase 1 β Memory Scaffold Optimizer (`memory-scaffold-optimizer`)++A meta-LLM loop that iteratively refines *how* AgentDB is used:+- Inputs: agent task trajectories + outcome signals from `hooks_post-task`+- Outputs: updated memory prompts (what to write, key schema) stored as `scaffold-vN` in the `memory-config` namespace+- Trigger: after every N completed trajectories (default N=10), or on explicit `npx ruflo memory optimize-scaffold`+- Backed by the existing `hooks_intelligence_trajectory-start/-step/-end` pipeline (ADR-074)++### Phase 2 β Memory Proficiency Trainer (`memory-specialist` agent)++A dedicated background agent trained from successful episodes:+- Identifies high-value memory decisions (writes that led to correct retrieval + task success) vs low-value ones (writes never retrieved, or retrieved but task failed)+- Generates GRPO-style reward signals: `+1` per retrieved fact that contributed to success, `-1` per write that went unretrieved or preceded failure+- Updates the `memory-specialist` LoRA adapter (reusing existing `ContrastiveTrainer` from ADR-086)+- Exposes results via `npx ruflo memory proficiency-status`++### Bounded Memory Contract (companion)++Per AgenticSTS (arXiv Jul 2 2026): add a `MemoryContract` option to AgentDB that enforces typed retrieval (`semantic_search`, `key_lookup`) as the only access path, blocking raw transcript appending beyond a configurable token budget (default: 2048 tokens/session). This prevents ghost-memory accumulation (A-TMA finding) and bounds context growth.++---++## Implementation Scope++| Component | Change | Risk |+|---|---|---|+| `@claude-flow/memory` | Add `scaffold-optimizer.ts` + `proficiency-trainer.ts` | Medium |+| `@claude-flow/hooks` | Wire `post-task` hook to emit trajectory reward signal | Low |+| `@claude-flow/cli` | Add `memory optimize-scaffold`, `memory proficiency-status` subcommands | Low |+| AgentDB | Add `scaffold-vN` namespace, reward-signal schema | Low |+| `ContrastiveTrainer` (ADR-086) | Extend to accept memory-op triplets | Low |++Files to keep under 500 lines each. No changes to task-policy paths.++---++## Consequences++**Positive:**+- Closes the single largest gap vs AutoMem SOTA (2xβ4x long-horizon improvement potential)+- Reuses existing trajectory pipeline (ADR-074) and ContrastiveTrainer (ADR-086) β minimal new infrastructure+- Measurable: benchmark against `@claude-flow/performance benchmark --suite memory-long-horizon` before/after++**Negative / Risks:**+- Reward signal quality depends on trajectory completeness; tasks without explicit success signals produce noisy rewards+- Phase 2 training adds ~50β200ms per post-task hook call (must be async/non-blocking)+- Over-optimized scaffold may overfit to a task distribution β need periodic scaffold reset option++**Not in scope:**+- LongMemEval harness integration (separate issue β competitive benchmarking)+- Pluggable memory backends (separate ADR, triggered by CrewAI v1.14.7 competitive signal)++---++## Alternatives Considered++1. **Heuristic consolidation tuning** β improve existing `consolidate` worker scheduling. Rejected: doesn't learn from outcomes, still heuristic.+2. **External memory library (Mem0, Zep)** β swap AgentDB for a dedicated memory service. Rejected: removes HNSW+SONA integration, architectural regression.+3. **Manual memory scaffold authoring** β let users configure prompts. Rejected: doesn't scale, doesn't learn.++---++## References++- AutoMem: https://arxiv.org/abs/2607.01224+- AgenticSTS: arXiv Jul 2 2026 (bounded memory contract)+- A-TMA: arXiv Jul 2 2026 (ghost memory / validity annotations)+- ADR-074: Self-Learning Wiring (`hooks_intelligence_trajectory-start/-step/-end`)+- ADR-086: ruvllm as Intelligence Coordinator (`ContrastiveTrainer`)diff --git a/v3/docs/adr/ADR-359-swarm-inverse-wisdom-dissent-mechanism.md b/v3/docs/adr/ADR-359-swarm-inverse-wisdom-dissent-mechanism.mdnew file mode 100644index 0000000000..3cbb107b31--- /dev/null+++ b/v3/docs/adr/ADR-359-swarm-inverse-wisdom-dissent-mechanism.md@@ -0,0 +1,76 @@+# ADR-359 β Swarm Dissent Mechanism: Inverse-Wisdom Law Compliance++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-07-04)+**Dream Cycle Issue**: #2559+**Related**: ADR-026 (3-tier model routing), CLAUDE.md swarm configuration++---++## Context++The 2026 paper *Inverse-Wisdom Law* (Shehata & Li, arXiv:2604.27274) provides a formal mathematical proof with empirical confirmation (Grade A) that adding agents to a consensus swarm **statistically increases the probability of erroneous consensus** rather than reducing it. The mechanism: once a plurality of agents commit to a wrong trajectory, majority voting amplifies that trajectory with each additional agent, making correction progressively harder.++Ruflo's current swarm coordinator uses Raft consensus (leader-based majority voting) with a soft `maxAgents: 8` default. There is no dissent preservation channel β when the majority votes one way, minority positions are silently dropped.++A companion finding (arXiv:2605.10698, "Bystander Effect in LLM Swarms") independently confirms that dissent suppression is the failure mode, not the agent count per se. The fix is architectural: expose a minority-opinion channel, not merely cap the agent count.++---++## Decision++Add a **dissent channel** to the Ruflo swarm coordinator:++1. **`dissent_threshold` parameter** (default: `floor(N/4)`, minimum 2): when this many or more agents vote against the majority conclusion, the coordinator surfaces a `dissent` field in the swarm result alongside the `consensus` field rather than suppressing the minority position.++2. **`dissent_weight` parameter** (default: `0.0`, range 0.0β1.0): controls how much the dissenting position influences the final merged output. At 0.0, dissent is logged only. At 1.0, dissent is blended equally with consensus.++3. **Dissent metadata**: each `dissent` record includes the count of dissenting agents, their IDs, and a summarised position.++4. **`max_agents` formal cap** (default: 8, hard maximum: 12): backed by the Inverse-Wisdom Law finding. Values >12 are rejected at configuration validation time with an explanatory error referencing this ADR.++### Implementation Scope++- `v3/@claude-flow/cli/src/swarm/coordinator.ts` β add `dissent_threshold`, `dissent_weight`, enforce `max_agents` hard cap+- `v3/@claude-flow/cli/src/swarm/consensus.ts` β add dissent extraction before majority resolution+- `v3/@claude-flow/cli/src/swarm/types.ts` β add `SwarmDissent` type to `SwarmResult`+- CLAUDE.md swarm config block β document new parameters++Estimated effort: 1 sprint (3-4 days).++---++## Consequences++### Positive+- Inverse-Wisdom Law compliance: minority positions are preserved rather than silently dropped+- First-mover advantage: none of LangGraph, AutoGen, CrewAI, or OpenAI Swarm implements a formal dissent channel+- Auditable decisions: dissent metadata enables post-hoc review of contested swarm outputs+- Hard `max_agents` cap prevents pathological swarm sizes that provably degrade correctness++### Negative+- Dissent surfacing adds latency when minority positions must be summarised (~50ms per dissent event)+- `dissent_weight > 0` requires a merge step that may produce incoherent blended outputs if not carefully prompted+- Operators must understand the new `dissent` field in swarm results to avoid ignoring it++### Neutral+- Default `dissent_weight: 0.0` makes this a non-breaking change β existing callers see a new field but behaviour is unchanged unless they opt in++---++## Rejected Alternatives++1. **Simply cap `max_agents` at 4**: Addresses the Inverse-Wisdom Law quantitatively but loses the parallelism benefit of larger swarms. Dissent channel preserves parallelism while fixing the silencing problem.++2. **Use adversarial subagents**: Spawning a dedicated "devil's advocate" agent is more expensive and architecturally complex. The dissent channel extracts minority positions from agents already running.++3. **No action**: The Inverse-Wisdom Law is a Grade A formal result. Ignoring it means Ruflo's 8-agent default provably degrades consensus quality on misaligned tasks.++---++## References++- Shehata & Li (2026). *Inverse-Wisdom Law in Multi-Agent LLM Consensus*. arXiv:2604.27274+- arXiv:2605.10698 β Bystander Effect in LLM Swarms (companion paper)+- [Dream Cycle Issue #2559](https://github.com/ruvnet/ruflo/issues/2559)+- [Gist: Swarm SOTA Report 2026-07-04](https://gist.github.com/ruvnet) *(URL added after publication)*diff --git a/v3/docs/adr/ADR-360-dream-cycle-performance-polykv-shared-kv-pool.md b/v3/docs/adr/ADR-360-dream-cycle-performance-polykv-shared-kv-pool.mdnew file mode 100644index 0000000000..5a60531680--- /dev/null+++ b/v3/docs/adr/ADR-360-dream-cycle-performance-polykv-shared-kv-pool.md@@ -0,0 +1,60 @@+# ADR-360 β Cross-Agent Shared KV Pool (PolyKV Architecture)++- **Status:** Proposed+- **Date:** 2026-07-05+- **Authors:** claude (dream-cycle agent, 2026-07-05)+- **Related:** [ADR-174](ADR-174-memory-distillation-self-optimization.md) (memory distillation), [ADR-006](ADR-006-unified-memory-service.md) (unified memory), [ADR-009](ADR-009-hybrid-memory-backend.md) (hybrid memory backend)+- **Source:** Dream Cycle 2026-07-05 β performance deep-dive; arXiv:2604.24971 (PolyKV)++## Context++Ruflo currently maintains per-agent KV caches with no cross-agent sharing or compression. At 15+ concurrent agents, the per-agent approach accumulates memory linearly β a 4K-token context per agent on Llama-3-8B scale requires ~19.8 GB of KV memory for 15 agents under the default (unshared) model.++PolyKV (arXiv:2604.24971, Patel & Joshi, Apr 2026) proves that a **shared asymmetrically-compressed KV pool** collapses this to 0.45 GB (97.7% reduction) with 2.91x compression via int8 key quantization + FWHT + 3-bit Lloyd-Max value quantization, while preserving BERTScore F1 of 0.928 and perplexity degradation of only +0.57%. This is a Grade A finding (two model scales tested with specified baselines).++Two complementary findings reinforce the case for serving-layer changes:+- ConServe (arXiv Jun 2026): disaggregated prefill/decode scheduling cuts p95 TTFT by 51.08% (Grade A)+- AsymCache (arXiv Jun 2026): asymmetric segment-based KV eviction cuts TTFT 1.90β2.03x (Grade A)++The `@claude-flow/memory` package owns AgentDB + HNSW vector indexing but does not manage KV caches for LLM inference contexts. Adding a shared compressed pool requires a new coordination layer between the memory package and the CLI's agent execution path.++## Decision++Implement a **SharedKVPoolManager** in `@claude-flow/memory` that:++1. Maintains a single process-shared compressed KV pool keyed by `(model, context_hash)`+2. Applies asymmetric compression: int8 quantization for keys (3.84x measured, reconstruction cosine 0.99999); FWHT + 3-bit Lloyd-Max for values (target 2.91x per PolyKV)+3. Exposes a `kvpool://` pseudo-backend selectable via `CLAUDE_FLOW_KV_BACKEND=shared-pool`+4. Integrates with the existing `hybrid` memory backend β pool lives alongside SQLite + AgentDB+5. Exports metrics (`pool_hit_rate`, `pool_memory_bytes`, `compression_ratio`) to the performance monitoring hook++## Consequences++**Positive:**+- 97.7% KV memory reduction at 15 concurrent agents (Grade A, Llama-3-8B, 4K ctx)+- Enables higher agent concurrency on same hardware without OOM+- Compression reuses existing int8 quantization path (3.84x measured in `@claude-flow/memory`)+- Orthogonal to HNSW vector search β both can be active simultaneously++**Negative / Risks:**+- FWHT + Lloyd-Max value compression is not yet implemented in the codebase; requires new codec module+- Shared pool introduces cross-agent state β requires eviction policy and LRU accounting+- Perplexity +0.57% and BERTScore F1 0.928 are acceptable but must be verified against Ruflo's specific models+- Pool requires a benchmark gate (compare vs current per-agent baseline) before enabling by default++**Neutral:**+- Speculative decoding (4.48x throughput, IBM arXiv:2606.18502) and disaggregated scheduling (ConServe, 51% TTFT) are related optimizations but scoped to separate ADRs β this ADR covers the KV pool only++## Implementation Path++1. `v3/@claude-flow/memory/src/kv-pool/` β new module: `SharedKVPoolManager`, `AsymmetricKVCodec` (int8 keys + FWHT+Lloyd-Max values), `KVEvictionPolicy` (LRU)+2. `v3/@claude-flow/memory/src/index.ts` β export `SharedKVPoolManager`; register `kvpool://` backend+3. `v3/@claude-flow/cli/src/commands/performance/` β add `kv-pool` subcommand (status, flush, benchmark)+4. `scripts/benchmark-kv-pool.mjs` β measure pool vs per-agent baseline at N=5,10,15 agents; gate merge on β₯90% memory reduction and BERTScore F1 β₯0.90+5. `CLAUDE.md` performance table β add row once benchmark validates++## Alternatives Considered++- **Per-agent int8 quantization only (no sharing):** Captures ~3.84x compression but not the cross-agent sharing benefit; still linear with agent count. Rejected β leaves the primary gap open.+- **External KV cache service (Redis/Memcached):** Introduces network hop; adds operational dependency. Rejected for initial implementation β in-process shared pool first.+- **Wait for upstream LLM serving framework support:** vLLM and SGLang are moving toward cross-request KV sharing; Ruflo could delegate. Acceptable future path but blocks on external timeline. Implement own first.diff --git a/v3/docs/adr/ADR-361-dream-cycle-intelligence-skill-evolution-worker.md b/v3/docs/adr/ADR-361-dream-cycle-intelligence-skill-evolution-worker.mdnew file mode 100644index 0000000000..f8357c238f--- /dev/null+++ b/v3/docs/adr/ADR-361-dream-cycle-intelligence-skill-evolution-worker.md@@ -0,0 +1,91 @@+# ADR-361: Skill Evolution Worker (SEW) β Runtime RL-Based Skill Acquisition for SONA++- **Status:** Proposed+- **Authors:** claude (dream-cycle agent, 2026-07-07)+- **Related:** [ADR-026](ADR-026-three-tier-model-routing.md) (3-tier model routing), [ADR-143](ADR-143-tier-1-codemod-routing.md) (Tier-1 codemod routing), [ADR-174](ADR-174-memory-distillation-self-optimization.md) (memory distillation), [ADR-176](ADR-176-proven-self-benchmarking-harness-loop.md) (self-benchmarking harness)++---++## Context++Ruflo's SONA (Self-Optimizing Neural Architecture) adapts routing weights at inference time (measured 0.0043ms/adapt) and the MoE gate converges from confidence 0.13β0.88 after rewards. However, SONA's skill catalog β the discrete skill types available to agents at spawn time β is **statically defined** in the codebase. Agent types are declared at initialization and do not evolve based on runtime task outcomes.++In 2026, **SkillRL** (arXiv:2602.08234) demonstrates that agents with RL-driven recursive skill acquisition outperform static skill catalogs across EvoAgentBench's four domains (web research, algorithmic reasoning, software engineering, knowledge retrieval). The key insight is that skill *selection* (which skill to apply to a task) and skill *acquisition* (whether to add a new skill derived from task experience) operate on different timescales and benefit from separate RL signals.++Separately, **EvolveMem** (arXiv:2605.13941) shows that memory management strategies themselves can be improved via an auto-research loop β analogous to the skill evolution gap but on the memory side.++The existing `post-task` hook already fires with `--success true/false` per task completion. This is the natural injection point for an RL update signal.++---++## Decision++Add a **Skill Evolution Worker (SEW)** as the 13th background worker in the hooks system (`@claude-flow/hooks`).++### SEW Behavior++1. **Trigger:** Fires on every `post-task` hook event (priority: normal; non-blocking to task pipeline).+2. **Signal extraction:** Reads task outcome (success/failure), task duration, model tier used, and post-hoc skill label from SONA's trajectory log.+3. **RL update:** Applies a SARSA(Ξ») update to a per-skill-type Q-table stored in AgentDB under namespace `skill-evolution`. Ξ»=0.9, Ξ±=0.01, Ξ³=0.95.+4. **Skill promotion gate:** A new skill variant is promoted to the active catalog only when its Q-value confidence interval lower bound exceeds **0.75** across β₯20 task completions. This prevents premature skill inflation.+5. **Skill pruning:** Skills with Q-value falling below 0.20 for β₯50 consecutive tasks are demoted to `deprecated` status (not deleted; available for re-promotion).+6. **SONA integration:** SEW writes updated skill weights to the SONA's MoE router's auxiliary skill index. The MoE gate reads this index at routing time. No change to the MoE gate architecture itself.+7. **Observability:** Skill promotion and demotion events are emitted as structured log events and exposed via `npx claude-flow@latest hooks worker status --worker sew`.++### CLI Surface++```bash+# Status+npx claude-flow@latest hooks worker status --worker sew++# Inspect skill Q-table+npx claude-flow@latest hooks worker dispatch --trigger sew --action inspect++# Force a skill promotion dry-run+npx claude-flow@latest hooks worker dispatch --trigger sew --action promote-dryrun++# Disable (opt-out)+npx claude-flow@latest config set hooks.workers.sew.enabled false+```++### Data Schema (AgentDB `skill-evolution` namespace)++```typescript+interface SkillQRecord {+ skillId: string; // e.g. "coder:typescript"+ qValue: number; // current Q-value+ sampleCount: number; // number of SARSA updates+ status: "active" | "candidate" | "deprecated";+ lastUpdated: string; // ISO timestamp+ confidenceLowerBound: number; // Bayesian lower bound at 95%+}+```++---++## Consequences++**Positive:**+- Closes the SkillRL gap: Ruflo gains runtime skill acquisition without a full model fine-tune cycle.+- Additive to ADR-026/ADR-143: tier routing is unchanged; SEW operates on the skill index layer above it.+- Naturally amortized: SARSA updates are O(1) per task; no batch training required.+- Reuses existing `post-task` hook infrastructure and AgentDB storage.++**Negative / Risks:**+- Skill catalog instability during early convergence (β€20 completions per skill). Mitigated by the promotion gate.+- AgentDB write contention under high-concurrency swarms. Mitigation: SEW uses optimistic concurrency with a per-skill lock (50ms timeout; drops update rather than blocking).+- Q-table cold-start on fresh installs. Mitigation: ship a seed Q-table derived from the 6,000-commit history (build artifact; not source-controlled).++**Not changed:**+- Existing 12 background workers are unaffected.+- MoE gate architecture (ADR-026) is unchanged.+- ADR-176 self-benchmarking harness is unchanged; SEW adds a new signal source it can read.++---++## Validation Criteria++- [ ] SEW promotes β₯1 skill variant in a 100-task integration test suite.+- [ ] No task latency regression (p99 < +5ms) measured by ADR-163 benchmarking suite.+- [ ] EvoAgentBench score β₯ baseline + 5% after 500 SEW-driven tasks (to be baselined per ADR-176).+- [ ] Skill Q-table persists across session restarts (AgentDB round-trip test).diff --git a/v3/docs/adr/ADR-362-dream-cycle-swarm-hnsw-comms-fabric.md b/v3/docs/adr/ADR-362-dream-cycle-swarm-hnsw-comms-fabric.mdnew file mode 100644index 0000000000..8dd73839ab--- /dev/null+++ b/v3/docs/adr/ADR-362-dream-cycle-swarm-hnsw-comms-fabric.md@@ -0,0 +1,105 @@+# ADR-362: HNSW-as-Communication-Fabric (HCF) for RuVector Swarm Knowledge Gossip++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-07-09)+**References**: arXiv:2606.28781 (HyphaeDB), arXiv:2606.02107 (ND-MARL), arXiv:2606.30668 (Emergent Culture)++---++## Context++Tonight's dream-cycle research (SLOT=4, DEEP=swarm) surfaced three Grade-A/B findings that jointly motivate a new architectural direction for ruvector and the Ruflo swarm layer:++1. **HyphaeDB (arXiv:2606.28781, Grade B)**: Proposes reinterpreting HNSW's neighbor graph topology not as a search optimization but as a *communication fabric* β agents placed as nodes in vector space exchange knowledge updates via gossip-protocol propagation to their HNSW neighbors. This creates "semantic neighborhoods" where conceptually-similar agents share state without explicit routing.++2. **ND-MARL (arXiv:2606.02107, Grade A)**: Demonstrates zero-shot 83Γ swarm scalability (3-agent policy β 250-agent deployment) via 2-neighbor sparse communication topology. The constraint is the bottleneck: agents only see 2 neighbors, limiting information propagation but enabling scale. This validates sparse neighbor graphs as a viable swarm communication primitive.++3. **Emergent Culture (arXiv:2606.30668, Grade A)**: 3 LLM agents develop spontaneous coordination via shared decaying-TTL storage + message passing β no explicit role prompts required. Entropy pressure catalyzes cooperation. Core insight: information decay forces agents to maintain and re-encode knowledge, producing emergent protocols.++**Current Ruflo gaps exposed by these findings:**++- `AgentDB` / ruvector treats HNSW purely as a search optimization. The index is never used for agent-to-agent communication.+- All competitor vector DBs (Qdrant, Weaviate, Milvus) also treat HNSW as search-only β HCF would be architecturally novel.+- ruvector lacks hybrid search (BM25 + ANN), which all major competitors ship. This is a blocking gap for production RAG.+- Ruflo swarms use static role assignment; no `topology: "minimal"` variant exists for entropy-driven emergent coordination.++---++## Decision++### Part A β HNSW-as-Communication-Fabric (HCF) mode (RFC)++Add an opt-in `commsMode: "hcf"` to AgentDB that activates the HNSW graph as a gossip-protocol communication substrate:++```typescript+interface AgentDBCommsConfig {+ commsMode: 'search-only' | 'hcf'; // default: 'search-only'+ hcf?: {+ gossipFanout: number; // neighbors to propagate to (default: 2, per ND-MARL)+ ttlMs: number; // gossip message TTL before entropy decay+ propagationDepth: number; // max hop count (default: 3)+ dedupeWindow: number; // ms window for dedup (default: 500)+ };+}+```++When `commsMode: "hcf"` is active:+1. Each AgentDB write event triggers gossip propagation to the writing agent's `k`-nearest neighbors in vector space.+2. Neighbor agents receive the knowledge update via their `post-edit` hook with source attribution.+3. Propagation depth is bounded to prevent amplification storms.+4. TTL decay mirrors the Emergent Culture paper's entropy mechanism, forcing agents to re-encode stale knowledge.++This turns `AgentDB` from a passive retrieval store into an active communication substrate β agents sharing semantic space automatically receive related updates without explicit `SendMessage` calls.++### Part B β Hybrid search (blocking prerequisite)++Before HCF can be meaningful, ruvector must ship hybrid search. All three competitor databases (Qdrant p99=12ms, Weaviate p99=16ms, Milvus p99=18ms @ 10M vectors) implement BM25 + ANN in a single pass. Without hybrid search, keyword-heavy agent queries that the swarm produces during HCF gossip will miss lexically-exact matches.++Target interface:++```typescript+interface HybridSearchParams {+ vector: number[];+ keyword?: string; // BM25 term query+ hybridAlpha?: number; // 0=pure keyword, 1=pure vector, default 0.5+ limit: number;+ filter?: Record<string, unknown>;+}+```++### Part C β `topology: "minimal"` swarm variant++Add a new swarm topology based on the Emergent Culture paper's pattern:+- Agents share a single TTL-decaying namespace (backed by HCF when enabled)+- No explicit role prompts β system prompt is minimal ("You are a curious and creative agent")+- Communication is via the shared namespace + direct message passing+- Intended for creative/research tasks where emergent coordination outperforms specialized roles++---++## Consequences++**Positive:**+- HCF differentiates ruvector from all known competitors β none implement HNSW-as-comms-fabric.+- Semantic neighborhoods reduce explicit `SendMessage` overhead for closely-related agents.+- Entropy-driven TTL creates natural memory pressure that may improve swarm focus on active tasks.+- Hybrid search closes the RAG quality gap vs Qdrant/Weaviate.++**Risks / Mitigations:**+- **Gossip storm**: Bounded by `propagationDepth` and `dedupeWindow`. Must be validated with load tests at `maxAgents=8` before enabling at scale.+- **Search semantics interference**: HCF gossip must not mutate the HNSW index structure used for search. Implementation must maintain two views: search index (immutable per-write) and comms graph (read-only topology derived from HNSW at swarm init).+- **TTL contention**: Decaying entries may cause cache thrash. Default `ttlMs=60000` (1 min) is conservative.+- **Part B prerequisite**: HCF gossip over hybrid queries requires hybrid search to be implemented first. Sequence: B β A β C.++**Implementation order**: Part B (hybrid search) β Part A (HCF mode) β Part C (minimal topology).+**Estimated scope**: Part B: 2β3 weeks. Part A: 3β4 weeks. Part C: 1 week.++---++## References++- arXiv:2606.28781 β HyphaeDB: A Living Knowledge Topology for Agent-First Memory+- arXiv:2606.02107 β Network Distributed Multi-Agent Reinforcement Learning for Consensus Control+- arXiv:2606.30668 β Emergent Culture in Minimal LLM Systems+- Dream Cycle 2026-07-09 gist (in-branch: `docs/dream/2026-07-09-swarm-sota.md`)+- ADR-178: Verifiable Memory Governance (security context for memory writes)diff --git a/v3/docs/adr/ADR-363-dream-cycle-performance-workflow-atomic-inference-scheduling.md b/v3/docs/adr/ADR-363-dream-cycle-performance-workflow-atomic-inference-scheduling.mdnew file mode 100644index 0000000000..699af9bbcf--- /dev/null+++ b/v3/docs/adr/ADR-363-dream-cycle-performance-workflow-atomic-inference-scheduling.md@@ -0,0 +1,98 @@+# ADR-363: Workflow-Atomic Inference Scheduling (WAIS) for Multi-Agent Execution++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-07-10)+**References**: arXiv:2605.00528 (SAGA), arXiv:2604.26963 (MARS), arXiv:2603.13110 (AgentRM), arXiv:2605.26289 (Stateful Inference), arXiv:2602.01053 (LRAgent, ICML 2026)++---++## Context++The 2026 inference-systems literature has converged on a finding that directly impacts Ruflo's multi-agent execution layer: **optimising individual LLM requests is suboptimal when the requests form a workflow DAG**. Three independent preprints and one ICML-accepted paper all demonstrate that workflow-level scheduling β treating a workflow as a scheduling atom β delivers 1.6Γβ5.9Γ latency improvements over request-level scheduling:++1. **SAGA (arXiv:2605.00528)**: Workflow-Atomic Scheduling for AI Agent Inference achieves 1.64Γ geometric-mean task completion time improvement and 99.2% SLO attainment under multi-tenant interference vs vLLM v0.15.1. The key insight: cross-workflow head-of-line blocking is eliminated by promoting the workflow to the primary scheduling unit.++2. **MARS (arXiv:2604.26963)**: GPU-CPU co-scheduling reduces end-to-end agent latency by 5.94Γ and task completion by 1.87Γ with OpenHands. Agent workflows span both GPU (LLM inference) and CPU (tool execution, orchestration), but existing schedulers treat only GPU demand. Unified scheduling captures cross-device dependencies.++3. **AgentRM (arXiv:2603.13110)**: An OS-inspired MLFQ scheduler for LLM agent systems reduces P95 latency by 86% and increases throughput by 168%. It also identifies "zombie agents" β stuck agents blocking resources silently β as a production pathology. A Context Lifecycle Manager compresses zombie context before eviction, preserving 100% of key information.++4. **Stateful Inference (arXiv:2605.26289)**: Converting per-turn inference from O(n_t) (re-process entire conversation) to O(Ξ_t) (delta-only on new tokens) delivers 2.1Γ speedup on 6-turn agentic workflows and 4.2Γ on the median turn of 35-turn workflows. 85β95% of the prompt is unchanged between tool calls.++Additionally, **LRAgent (arXiv:2602.01053, ICML 2026)** demonstrates that when swarm agents use different specialisations (LoRA adapters), a decomposed per-adapter KV cache achieves near-shared throughput while preserving per-adapter accuracy β relevant to Ruflo's specialised agent types.++**Current Ruflo state**: Task orchestration dispatches each MCP tool call as an independent request. There is no workflow-level scheduler, no zombie-agent watchdog, and no stateful inference layer. Context re-processing cost grows linearly with conversation length.++**Competitor survey**: None of LangGraph, AutoGen, CrewAI, or OpenAI Agents SDK ship a workflow-atomic scheduler as of July 2026. First-mover opportunity is present.++---++## Decision++Implement **Workflow-Atomic Inference Scheduling (WAIS)** across three components:++### Component A: WorkflowScheduler (SAGA pattern)++Add `WorkflowScheduler` to `v3/@claude-flow/hooks/src/workers/` as the 13th background worker (priority: high). At `pre-task` hook time:+- Register each incoming task with its workflow DAG ID (from `swarm_init` topology)+- Compute critical path length across pending tasks in the same workflow+- Dispatch requests in critical-path order, holding non-critical tasks until GPU headroom exists+- SLO target: β₯99% of workflow completions within 2Γ critical-path lower bound++### Component B: ZombieWatchdog (AgentRM pattern)++Add `ZombieWatchdog` to `v3/@claude-flow/cli/src/agent/lifecycle.ts`:+- Per-agent liveness timer (default: `agentTimeoutMs` from config, fallback 120 000 ms)+- On timeout: call `consolidate` worker with `mode: 'emergency'` β compress to key-info before eviction (100% retention target, same as AgentRM MLFQ)+- Emit `agent:zombie-evicted` event for observability+- No silent resource leak: every eviction must produce a summary record in AgentDB++### Component C: Stateful Inference Spike (Norgren pattern)++Open a 2-week implementation spike (GitHub issue, separate from this ADR):+- Investigate vLLM/SGLang stateful KV persistence across sequential MCP tool calls+- Prototype: single-conversation persistent KV cache that advances by Ξ_t on each tool call+- Gate: if prototype achieves β₯2Γ turn latency reduction on `benchmark --suite tool-call-latency`, promote to production integration++---++## Consequences++### Positive+- WorkflowScheduler eliminates head-of-line blocking across concurrent agent swarms β directly improves `benchmark --suite task-completion` target+- ZombieWatchdog prevents the silent resource leak pattern observed in production (long-running swarms accumulating stuck agents)+- Stateful inference spike, if successful, delivers 2.1β4.2Γ per-turn latency gains for no model changes++### Negative+- WorkflowScheduler requires workflow DAG ID to be propagated at task spawn time β breaking change for code that spawns tasks without a swarm context+- ZombieWatchdog introduces a new config key (`agentTimeoutMs`) that must be documented and have sane defaults; misconfiguration can prematurely evict agents on slow tasks+- Stateful inference integration depends on vLLM/SGLang version compatibility β infrastructure dependency risk++### Neutral+- No changes to model routing (ADR-026/ADR-143)+- No changes to AgentDB schema (HNSW indexes unchanged)+- LRAgent decomposed-KV-cache pattern deferred: requires LoRA adapter infrastructure not yet present in Ruflo++---++## Benchmark Gates++Before merging any implementation PR against this ADR:++| Gate | Target | Tool |+|------|--------|------|+| Task completion time | β₯1.5Γ improvement on `benchmark --suite task-completion` | `npx claude-flow@latest performance benchmark --suite task-completion` |+| Zombie eviction | Zero silent resource leaks over 1000-task soak test | `npx claude-flow@latest performance benchmark --suite agent-soak` |+| Stateful inference spike | β₯2Γ turn latency on tool-call bench (if spike promoted) | `npx claude-flow@latest performance benchmark --suite tool-call-latency` |++---++## Prior Art in This Repository++- ADR-026: 3-tier model routing (Haiku/Sonnet/Opus) β not modified by this ADR+- ADR-143: Tier-routing deterministic codemod layer β not modified+- ADR-174: Memory distillation self-optimisation β ZombieWatchdog's emergency-consolidate call reuses ADR-174 machinery+- ADR-176 (dream/2026-07-05-performance branch): SharedKVPoolManager (PolyKV) β orthogonal; both can coexist++---++*Generated by Ruflo Dream Cycle agent β do not self-merge. Leave for human review.*diff --git a/v3/docs/adr/ADR-364-dream-cycle-security-plugin-supply-chain-scanner.md b/v3/docs/adr/ADR-364-dream-cycle-security-plugin-supply-chain-scanner.mdnew file mode 100644index 0000000000..b5d00605f4--- /dev/null+++ b/v3/docs/adr/ADR-364-dream-cycle-security-plugin-supply-chain-scanner.md@@ -0,0 +1,122 @@+# ADR-364: Plugin Supply-Chain Scanner and Behavioral Manifest++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-07-11)+**Dream Cycle Issue**: #TBD (filed tonight)+**Supersedes**: None+**Related**: ADR-178 (IPI / VMG / RepE context-level injection), ADR-150 (MetaHarness integration)++> **ADR numbering note**: Three prior unmerged dream-cycle branches (dream/2026-07-09-swarm, dream/2026-07-10-performance, tonight) all claim ADR-364 because the formula reads from `main` where ADR-178 is the last merged entry. Human reviewer must resolve on merge β recommend renumbering tonight's as ADR-181 if both prior branches merge first.++---++## Context++The 2026 research literature documents a rapid escalation in agent skill/plugin supply-chain attacks:++- **arXiv:2605.14460** (Payload-less Skills): 77.67% confidentiality breach rate; manipulated skill files achieve **0.00% detection rate** by existing scanners β meaning the current ecosystem has no effective pre-install scanner.+- **arXiv:2601.10338** (Agent Skills in the Wild): 26.1% of 31,132 real-world skills contain β₯1 vulnerability; skills with executable scripts are 2.12Γ more likely to be vulnerable.+- **arXiv:2606.30755** (SafeClawArena): Malicious plugins succeed in **100%** of adversarial test cases; SeClaw reduces ASR from 70% to 22% by adding a permission layer.+- **arXiv:2603.15727** (ClawWorm): Self-propagating attack achieves 64.5% ASR across 40,000+ instances via shared memory poisoning β directly applicable to Ruflo's `collaboration` namespace.+- **arXiv:2603.27204** ("Elementary, My Dear Watson."): Neuro-symbolic scanner achieves **93% F1** on 150,108 skills from 7 public registries.+- **arXiv:2607.01136** (Skills Are Not Islands): Single-skill inspection is insufficient β dependency graphs hide malicious signals; 1.43M skills analyzed as "activation-ready but governance-poor."++Ruflo's plugin registry (`@claude-flow/plugins`) publishes 21 optional plugins via IPFS/Pinata. The publish path (`npx ruflo plugins publish`) pins a JSON manifest and plugin bundle to IPFS with no pre-flight security scan. The install path (`npx ruflo plugins install @name`) fetches the CID with no AST analysis, no dependency graph walk, and no runtime permission manifest.++The `@claude-flow/security` module (InputValidator, PathValidator, SafeExecutor) addresses system-boundary injection but has no plugin-scoped security surface. There is no published OWASP GenAI Top 10 mapping for Ruflo β a visible gap in the security documentation that no competitor has filled (first-mover opportunity).++---++## Decision++### Component A β PluginScanner (pre-publish static gate)++Add `PluginScanner` to `v3/@claude-flow/security/src/plugin-scanner.ts`, exported from `@claude-flow/security`.++**Trigger**: Called by `npx ruflo plugins publish` before Pinata pin; also callable standalone via `npx ruflo security scan --plugin <path>`.++**Analysis layers** (in order):++1. **AST credential extraction scan**: Flag `process.env` access to sensitive keys, `fs.readFile`/`fs.readFileSync` on paths matching `/(\.env|secrets?|credentials?|\.ssh|\.aws)/i`, and `eval`/`Function()` constructs.++2. **Network exfiltration scan**: Flag outbound `fetch`/`axios`/`got`/`http.request` calls to hosts not declared in the plugin's `allowedHosts` manifest field.++3. **Hook injection scan**: Flag registration of hooks (`pre-task`, `post-task`, `pre-edit`, `post-edit`, `session-start`, `session-end`) that are not declared in the plugin's `hooks` manifest field.++4. **Dependency graph walk** (arXiv:2607.01136 pattern): Recursively scan all transitive `require`/`import` dependencies up to depth 5. Flag any dep not in `node_modules` that matches the above patterns.++**Result**: `ScanResult { passed: boolean; findings: Finding[]; grade: 'A'|'B'|'C'|'FAIL' }`. Gate: `FAIL` blocks publish. `C` requires `--force-publish` flag and writes finding to IPFS pin metadata.++**Neuro-symbolic enhancement** (Phase 2, optional): Integrate the pattern from arXiv:2603.27204 β train a lightweight classifier on MalSkillBench (3,944 malicious skills) to supplement AST rules. Target: β₯90% F1 (reference: 93% in paper). Phase 2 is not blocked on ADR approval.++### Component B β Plugin Behavioral Manifest++Add declarative permission manifests to `v3/@claude-flow/cli/src/plugins/manager.ts`.++**Manifest schema** (added to existing `plugin.json` / IPFS bundle):++```json+{+ "permissions": {+ "env": ["ANTHROPIC_API_KEY"],+ "net": ["api.pinata.cloud"],+ "fs": ["./data/plugin-name/**"],+ "hooks": ["pre-task", "post-task"]+ }+}+```++**Runtime enforcement**: Wrap every plugin tool call in a `PermissionGuard` that checks the declared manifest. Violations:+- Emit `plugin:permission-violation` event (observable via `npx ruflo status --events`)+- Log to `~/.claude/security-events.jsonl` with timestamp, plugin ID, violation type+- Halt plugin execution (do not propagate the call)++**Memory integrity seal** (arXiv:2603.15727 / ClawWorm mitigation): In the `post-edit` hook, HMAC-sign values written to shared namespaces (`collaboration`, `patterns`) using a per-session key. On read, verify HMAC before passing to downstream agents. Prevents cross-agent memory poisoning via compromised plugins.++### Component C β OWASP GenAI Mapping Document++Produce `docs/security/owasp-genai-top10-mapping.md` mapping all 10 OWASP GenAI v2025 entries to Ruflo's `@claude-flow/security` module. Minimum per-entry: current status (Covered/Partial/Gap), relevant Ruflo component, and open remediation task.++ADR-364 deliverables map to:+- LLM05 (Supply Chain Vulnerabilities) β Component A (PluginScanner)+- LLM07 (Insecure Plugin Design) β Component B (Behavioral Manifest)+- LLM08 (Excessive Agency) β existing `SafeExecutor` (document as Covered)+- LLM01 (Prompt Injection) β ADR-178 (VMG/RepE, document as In Progress)++---++## Consequences++### Positive++- Closes the 0.00% detection rate gap for payload-less plugin attacks (arXiv:2605.14460)+- Memory integrity seal prevents ClawWorm-style multi-hop swarm poisoning (arXiv:2603.15727)+- OWASP GenAI mapping is a first-mover security compliance signal β no competitor publishes one+- `PluginScanner` is composable: usable standalone, in CI, and as a gating step in the plugin publish flow++### Negative++- `plugins publish` adds a scan step (~1β5s for typical plugin bundles); `--skip-scan` flag available for internal/known-safe plugins only with explicit override+- Behavioral manifest adds a new required field to plugin manifests β existing plugins need manifest updates before next publish (backwards-compatible: missing manifest = warn, not fail, until v4.0)+- Dependency graph walk at depth 5 may produce false positives on plugins that use popular crypto libraries β allowlist for `node_modules/` stdlib equivalents required++### Neutral++- Does not change plugin install user experience (scan is a publish-side gate, not install-side)+- Memory HMAC adds ~0.1ms overhead per namespace write (negligible vs. agent round-trip latency)++---++## Implementation Plan++| Phase | Deliverable | Target |+|-------|-------------|--------|+| 1 (sprint) | `PluginScanner` AST scan + `plugins publish` gate | v3.7.1 |+| 1 (sprint) | Plugin manifest schema + `PermissionGuard` runtime | v3.7.1 |+| 1 (sprint) | OWASP GenAI Top 10 mapping document | v3.7.1 |+| 2 (research) | Memory HMAC integrity seal for `collaboration` namespace | v3.8.0 |+| 2 (research) | Neuro-symbolic scanner Phase 2 (MalSkillBench training) | v3.8.0 |++---++*Generated by Ruflo Dream Cycle agent β 2026-07-11. Do not self-merge.*diff --git a/v3/docs/adr/ADR-365-recurrence-gated-memory-consolidation.md b/v3/docs/adr/ADR-365-recurrence-gated-memory-consolidation.mdnew file mode 100644index 0000000000..8e58e9e94b--- /dev/null+++ b/v3/docs/adr/ADR-365-recurrence-gated-memory-consolidation.md@@ -0,0 +1,63 @@+# ADR-365: Recurrence-Gated Memory Consolidation for AgentDB++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-07-13)+**Date:** 2026-07-13+**References:** Dream Cycle issue 2026-07-13; RecMem (Dai et al., May 2026); SelfMem (Yang et al., July 2026)++---++## Context++AgentDB currently triggers memory consolidation eagerly: after every N writes, the DISTILL step runs a full LLM pass over the memory namespace to compact and re-rank entries. This has two costs:++1. **Token cost**: Each consolidation call consumes LLM tokens proportional to namespace size.+2. **Latency**: Eager consolidation blocks the agent loop while the LLM pass executes.++The 2026 paper "RecMem: Recurrence-based Memory Consolidation" (Dai et al., May 15 2026, Grade A) demonstrates that consolidation triggered only when sustained semantic cluster activity exceeds a configurable threshold reduces token cost by **87%** while exceeding eager-consolidation accuracy on recall benchmarks. The key insight: most writes to a namespace do not meaningfully shift the semantic distribution β consolidation is only valuable when cluster centroids have drifted enough to require re-ranking.++Additionally, "SelfMem" (Yang et al., July 2026, Grade A) demonstrates that an RL layer self-optimizing retrieval parameters (k, ef_search, relevance threshold) per namespace using verdict signals from the existing JUDGE step yields a **+48.7% BEAM score** improvement at 100K token scale. The feedback loop already exists in Ruflo's RETRIEVEβJUDGE pipeline; wiring it back to retrieval configuration is the missing piece.++---++## Decision++Replace the eager N-write consolidation trigger in AgentDB with a **recurrence-gated trigger**:++1. **Cluster-activity monitor**: After each write batch, compute the cosine shift of the top-K cluster centroids versus their last-consolidation snapshot. Consolidation fires only when the mean centroid shift exceeds a configurable threshold `CONSOLIDATION_DRIFT_THRESHOLD` (default: 0.12) sustained over `CONSOLIDATION_SUSTAIN_WRITES` consecutive batches (default: 8).++2. **RL retrieval policy layer (phase 2)**: Wire JUDGE step verdicts (success/failure per retrieval) back to a per-namespace bandit that tunes `ef_search`, `k`, and `min_relevance_score`. This is additive β does not require changing the HNSW index structure.++3. **Backward compatibility**: The existing `CONSOLIDATION_INTERVAL` config key remains supported as a hard ceiling (consolidation always fires if N writes have elapsed, regardless of drift). Default ceiling: 500 writes (up from current 50).++---++## Implementation Notes++- Cluster centroid snapshots stored as a lightweight metadata table in the existing SQLite backend (no schema migration for vector data).+- Drift computation uses the existing HNSW `query` path β no new index structures needed.+- RL policy state stored in `memory_policies` namespace (persistent across sessions via existing AgentDB persistence).+- Benchmark gate: `scripts/benchmark-intelligence.mjs` must show β₯50% reduction in consolidation LLM calls on the `N=20k` fixture before merging. Grade A target.++---++## Consequences++**Positive:**+- Estimated β80% consolidation token cost (conservative vs RecMem's β87% lab result)+- No change to retrieval latency (HNSW index unchanged)+- Retrieval quality improves over time via RL policy self-tuning (phase 2)+- Existing `CONSOLIDATION_INTERVAL` ceiling preserves safety net++**Negative / Risks:**+- Cluster centroid computation adds ~2ms per write batch (acceptable; below 25ms LANTERN bound)+- RL policy tuning requires β₯100 JUDGE verdicts per namespace to converge; new namespaces use static defaults+- `CONSOLIDATION_DRIFT_THRESHOLD` requires calibration per workload; wrong value delays needed consolidation++---++## Alternatives Considered++- **Keep eager consolidation**: Rejected β 87% token waste is measurable and Grade A benchmarked.+- **Time-based trigger**: Rejected β semantic drift does not correlate with wall-clock time for bursty agent workloads.+- **Full in-process memory store** (Memory in the Loop pattern, 100Β΅s latency): Deferred β requires SQLite WAL tuning and process isolation changes; tracked separately.diff --git a/v3/docs/adr/ADR-366-dream-cycle-swarm-self-evolving-skill-distillation.md b/v3/docs/adr/ADR-366-dream-cycle-swarm-self-evolving-skill-distillation.mdnew file mode 100644index 0000000000..839fc49160--- /dev/null+++ b/v3/docs/adr/ADR-366-dream-cycle-swarm-self-evolving-skill-distillation.md@@ -0,0 +1,82 @@+# ADR-366: Self-Evolving Swarm Skill Distillation via Trajectory Feedback++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-07-14)+**Date:** 2026-07-14+**Related Issues:** dream-cycle nightly research 2026-07-14 (swarm slot 4)++---++## Context++Ruflo's swarm system produces rich execution trajectories on every run: tool-call sequences, timing, success/failure verdicts, and agent message traces are all captured by the `post-task` hook and stored in AgentDB. However, nothing reads these trajectories back to improve the `.claude/skills/` YAML files that define coordination protocols.++Swarm Skills (arXiv:2605.10052, May 2026, Grade A) demonstrates that multi-agent coordination specs can be treated as first-class evolving assets: an automatic distillation algorithm scores each trajectory on Effectiveness Γ Utilization Γ Freshness and patches the matching skill definition. The resulting skills become progressively more efficient β without human authoring β and remain portable across agent frameworks via progressive disclosure.++The current state in Ruflo:+- Skills are static YAML files authored by humans+- Execution trajectory data is captured but never fed back to skill definitions+- There is no cross-session coordination quality measurement++## Decision++Implement a **Swarm Skill Trajectory Distillation** loop integrated into the existing `post-task` hook pipeline:++1. **Trajectory capture** (already exists via `post-task`): record tool-call sequence, agent assignments, success/failure verdicts, wall-clock latency per phase.++2. **EUF scoring**: compute Effectiveness (task success rate), Utilization (agent utilization ratio), and Freshness (recency-weighted) for each skill invocation.++3. **Patch generation**: when a skill's EUF score improves over its current definition (threshold: +5% on any dimension), generate a diff against the YAML and write it to `.claude/skills/<skill-name>.yaml` as a versioned patch with `# distilled from trajectory <trajectory-id>` comment.++4. **Portability gate**: before committing a patch, validate the updated skill still passes the existing `claude-flow@v3alpha hooks verify` check. Revert on failure.++5. **Session boundary**: distillation runs once at session end via `session-end` hook, not after every task β to avoid mid-session churn.++### Architecture++```+post-task hook β trajectory store (AgentDB)+ β+ session-end hook triggers+ β+ EUF scorer reads last N trajectories+ β+ EUF delta > +5%?+ YES β patch .claude/skills/<name>.yaml+ + hooks verify gate+ NO β no-op+```++### Scope++- Applies only to skills that have run β₯3 times (statistical stability threshold)+- Does NOT modify agent type definitions, MCP tool schemas, or ADRs+- Patch is human-reviewable diff committed to branch; no silent in-place overwrites in production++## Consequences++### Positive+- Coordination protocols improve autonomously from usage data+- Closes the primary gap vs Swarm Skills SOTA (arXiv:2605.10052)+- Leverages existing trajectory capture infrastructure β no new data collection needed+- Human reviewable: every distillation produces a versioned YAML diff in git++### Negative+- EUF scoring adds ~10-50ms to session-end hook (low cost)+- Risk of distilling a lucky-run artifact: mitigated by the β₯3 run threshold and verify gate+- Adds a new file-write operation at session end; could conflict with concurrent sessions (mitigate with file lock)++### Neutral+- Does not require external model calls β EUF is deterministic arithmetic on trajectory metadata++## Alternatives Considered++- **No ADR β implementation-level**: Rejected. This is an architectural feedback loop connecting the execution layer to the skill definition layer β a meaningful bounded-context crossing.+- **Online distillation after every task**: Rejected. Mid-session churn makes debugging coordination failures harder.+- **Manual skill authoring only**: Current state; identified as the gap this ADR closes.++## References++- Swarm Skills (arXiv:2605.10052): https://arxiv.org/abs/2605.10052+- SWARM+ (arXiv:2603.19431): https://arxiv.org/abs/2603.19431+- Ruflo dream-cycle nightly report: `docs/dream-cycle/dream-gist-2026-07-14.md`diff --git a/v3/docs/adr/ADR-367-epistemic-working-memory-intelligence-pipeline.md b/v3/docs/adr/ADR-367-epistemic-working-memory-intelligence-pipeline.mdnew file mode 100644index 0000000000..6992235190--- /dev/null+++ b/v3/docs/adr/ADR-367-epistemic-working-memory-intelligence-pipeline.md@@ -0,0 +1,110 @@+# ADR-367: Epistemic Working Memory in the Intelligence Pipeline++| Field | Value |+|-------|-------|+| **Status** | Proposed |+| **Authors** | claude (dream-cycle agent, 2026-07-17) |+| **Dream Cycle Issue** | Filed 2026-07-17, deep surface: intelligence |+| **Supersedes** | None |+| **Related** | ADR-026 (3-tier routing), ADR-006 (Unified Memory Service), ADR-009 (Hybrid Memory Backend) |++---++## Context++Two July 2026 papers reveal actionable gaps in Ruflo's intelligence pipeline:++**SLEUTH (arXiv:2607.12267, Ning Liu, Jul 2026, grade A):** Introduces a structured *epistemic working memory* with three named lists per reasoning task β `confirmedFacts`, `activeHypotheses`, `openQuestions` β maintained across reasoning steps. Result: +11 points on multi-hop benchmarks. Ruflo's AgentDB stores long-term embeddings but has no per-task structured epistemic buffer.++**GRADE (arXiv:2607.10836, Ghosh & Chakraborty, Jul 2026, grade A):** Hierarchical multi-agent routing with *gated depth control* β learned gates govern agent selection, hierarchy depth, inter-agent communication, and branch pruning via collaborative policy optimization. Result: 44% less inference runtime vs mixture-of-agents baseline, 8.15% accuracy gain. Ruflo's SONA MoE gates token routing across 8 experts but does not gate agent-selection depth or prune reasoning branches.++Additionally, ArXiv:2607.13034 shows that a *Cognitive Redundancy Ratio (CRR)* gate can reduce cost by 85% on simple tasks by estimating minimum-sufficient execution scope before routing.++The existing intelligence pipeline (RETRIEVE β JUDGE β DISTILL β CONSOLIDATE) has no per-task working memory layer and no branch-level gate.++---++## Decision++Add an **EpistemicWorkingMemory (EWM)** layer to the intelligence pipeline, inserted between RETRIEVE and JUDGE:++```+RETRIEVE β [EWM] β JUDGE β DISTILL β CONSOLIDATE+```++### EWM Schema (per task)++```typescript+interface EpistemicWorkingMemory {+ taskId: string;+ confirmedFacts: string[]; // facts verified during this task+ activeHypotheses: string[]; // hypotheses being tested+ openQuestions: string[]; // unresolved sub-questions+ stepCount: number;+ createdAt: number;+ flushedAt?: number;+}+```++At each intelligence step, the agent appends to the appropriate list. At task completion, EWM is flushed: a summary is written to AgentDB (long-term) and the in-memory buffer is released.++### CRR Pre-Routing Gate++Before task routing, compute:++```+CRR = (estimated_unique_reasoning_steps) / (total_input_tokens / 500)+```++If `CRR < 0.3` β route to Haiku with scope-bounded system prompt suffix.+If `CRR β₯ 0.3` β standard 3-tier routing (ADR-026).++### Agent-Selection Depth Gate (GRADE-inspired)++Extend swarm coordinator to emit a `depthBudget` per task (default 3). Agents that exhaust their depth budget without resolution escalate to the next tier rather than continuing horizontally. This limits runaway agent fan-out on hard tasks and prunes solved branches early on easy tasks.++---++## Implementation Scope++| Component | File | Change |+|-----------|------|--------|+| EWM type + in-memory store | `v3/@claude-flow/memory/src/epistemic/EpistemicWorkingMemory.ts` | **new** |+| EWM flush β AgentDB | `v3/@claude-flow/memory/src/epistemic/ewm-flush.ts` | **new** |+| Pipeline hook | `v3/@claude-flow/hooks/src/intelligence.ts` | insert EWM step |+| CRR pre-routing gate | `v3/@claude-flow/hooks/src/route.ts` | add CRR computation |+| Agent depth gate | `v3/@claude-flow/cli/src/swarm/coordinator.ts` | add `depthBudget` |+| EWM schema export | `v3/@claude-flow/memory/src/index.ts` | export new types |++---++## Consequences++**Positive:**+- Expected +8-11 points on multi-hop reasoning (grade-A baseline, arXiv:2607.12267)+- Expected 44% runtime reduction on complex multi-agent tasks via depth gating+- Expected 60-85% cost reduction on simple tasks via CRR gate (grade-A baseline, arXiv:2607.13034)+- Competitive with LangGraph's HITL checkpoints and AG2 Beta's typed tools++**Negative:**+- EWM adds ~3-12 KB of in-memory state per concurrent task; at 100 concurrent tasks, ~1.2 MB overhead+- CRR threshold (0.3) requires calibration against real task distribution+- GRADE's collaborative policy optimization requires offline training β depth gate here uses a simpler heuristic (no policy gradient), so gains may be partial++**Neutral:**+- EWM flush to AgentDB is async; tasks complete without waiting for flush+- Existing ADR-026 3-tier routing is preserved; CRR gate is a pre-filter, not a replacement++---++## Alternatives Considered++1. **No EWM, extend AgentDB session scope** β Cheaper but doesn't expose structured fact/hypothesis/question lists to the agent, so the +11 pt gain is unlikely.+2. **Full GRADE collaborative policy optimization** β Higher ceiling but requires training data; deferred to a future ADR.+3. **RAG-only** β Already implemented; SLEUTH shows structured EWM is orthogonal and additive to retrieval.++---++## Validation++Run `npx claude-flow@v3alpha performance benchmark --suite multi-hop` before and after EWM integration. Gate merge on β₯5 pt improvement on an internal multi-hop eval set. Evaluate CRR gate savings by comparing cost per task on the existing regression test suite.diff --git a/v3/docs/adr/ADR-368-dream-cycle-memory-selective-persistence.md b/v3/docs/adr/ADR-368-dream-cycle-memory-selective-persistence.mdnew file mode 100644index 0000000000..16f8d1c224--- /dev/null+++ b/v3/docs/adr/ADR-368-dream-cycle-memory-selective-persistence.md@@ -0,0 +1,95 @@+# ADR-368: Selective Persistent Memory Categories for AgentDB++- **Status:** Proposed+- **Authors:** claude (dream-cycle agent, 2026-07-18)+- **Context:** Dream Cycle 2026-07-18 β Memory deep-dive+- **Related:** ADR-006 (Unified Memory Service), ADR-009 (Hybrid Memory Backend)++---++## Context++Ruflo's AgentDB currently persists full session history (all conversation turns, reasoning traces, intermediate outputs) into memory namespaces. A 2026 peer-reviewed paper (Pedada et al., arxiv:2607.09493, "Shared Selective Persistent Memory for Agentic LLM Systems") demonstrates that naive full-history persistence **degrades** task completion (71% vs 96% for selective, vs 79% for no memory). The key insight: reasoning traces from past sessions are stale and introduce noise; what reuses cleanly across sessions is only four categories of information.++Additionally, a second 2026 paper (arxiv:2607.14651, "MemPoison") demonstrates that write-time memory defenses fail against compositional attacks, and a third (arxiv:2607.08395, "Token-Flow Firewall") proposes semantic runtime interception before persistence. Ruflo's `@claude-flow/security` InputValidator currently operates at system input boundaries, not on memory write paths.++## Decision++Implement a **Selective Persistent Memory** filter in `@claude-flow/memory` that:++1. **Categorizes memory writes** into one of five buckets at write-time:+ - `TASK_SPEC` β task descriptions, goals, acceptance criteria+ - `DATA_SCHEMA` β data models, field definitions, API contracts+ - `TOOL_CONFIG` β tool invocations, endpoint URLs, auth patterns (sans secrets)+ - `OUTPUT_CONSTRAINT` β output format rules, size limits, required fields+ - `REASONING_TRACE` β all other (ephemeral: summaries, CoT steps, intermediate decisions)++2. **Persists only** `TASK_SPEC`, `DATA_SCHEMA`, `TOOL_CONFIG`, `OUTPUT_CONSTRAINT` by default. `REASONING_TRACE` entries expire after the session TTL (configurable, default 24h).++3. **Adds RBAC** to AgentDB namespaces: `MemoryNamespace` gains an `acl: { [role: string]: 'read' | 'write' | 'none' }` field so namespaces can be shared cross-user with role-gated access.++4. **Adds a write-time semantic gate** in the memory update path that checks writes against a threat pattern list before persistence (Token-Flow Firewall pattern). Implemented as a middleware in `AgentDB.store()`.++## Consequences++**Positive:**+- Targets 97Γ reduction in per-invocation token costs for repeat tasks (from arxiv:2607.09493 baseline)+- Targets 14Γ reduction in task execution time via zero-token refresh of persistent configs+- Closes memory poisoning vector for write-path injection attacks+- Enables cross-user template sharing (e.g., shared tool configs, shared schemas)++**Negative:**+- Categorization requires either an LLM classification step (adds latency) or a heuristic rule set (may misclassify)+- RBAC adds schema migration and backward-compatibility burden for existing AgentDB users+- The semantic gate adds ~0.7s overhead per write (per Token-Flow Firewall benchmarks) β acceptable for persistence writes, unacceptable for hot paths++**Mitigations:**+- Use rule-based fast-path classifier (regex + structural signals) as Tier-1; LLM classifier as Tier-2 fallback for ambiguous entries+- Provide `--memory-selective-filter=off` escape hatch for users who need full-history replay+- Make semantic gate configurable per namespace (default: on for public/shared namespaces, off for private session namespaces)++## Implementation Sketch++```typescript+// v3/@claude-flow/memory/src/selective-filter.ts+export type MemoryCategory =+ | 'TASK_SPEC'+ | 'DATA_SCHEMA'+ | 'TOOL_CONFIG'+ | 'OUTPUT_CONSTRAINT'+ | 'REASONING_TRACE';++export interface SelectiveFilterConfig {+ persistCategories: MemoryCategory[];+ traceTTLMs: number; // default: 86_400_000 (24h)+ semanticGate: boolean;+}++export const DEFAULT_FILTER: SelectiveFilterConfig = {+ persistCategories: ['TASK_SPEC', 'DATA_SCHEMA', 'TOOL_CONFIG', 'OUTPUT_CONSTRAINT'],+ traceTTLMs: 86_400_000,+ semanticGate: false, // off by default for private namespaces+};++export function classifyEntry(content: string, metadata: Record<string, unknown>): MemoryCategory {+ // Tier-1: structural heuristics+ if (metadata.type === 'tool_call' || metadata.type === 'tool_config') return 'TOOL_CONFIG';+ if (metadata.type === 'schema' || content.includes('"$schema"')) return 'DATA_SCHEMA';+ if (metadata.type === 'task' || metadata.role === 'user' && metadata.isGoal) return 'TASK_SPEC';+ if (metadata.type === 'output_spec') return 'OUTPUT_CONSTRAINT';+ return 'REASONING_TRACE';+}+```++## Alternatives Considered++- **Full-history retention (status quo):** Simple but produces 71% task completion and 26,000+ tokens/conv overhead.+- **Summarization-only (NapMem pattern from ADR-??? / prior dream cycle):** Lossy compression reduces tokens but doesn't address the cross-user sharing or write-time attack vectors.+- **External memory system (Mem0, Cognee):** Adds a dependency and exfiltration risk; better to implement the same pattern in AgentDB natively.++## References++- Pedada, Dhavala, Patil (2026). "Shared Selective Persistent Memory for Agentic LLM Systems." arXiv:2607.09493+- "MemPoison: Uncovering Persistent Memory Threats." arXiv:2607.14651+- "Token-Flow Firewall: Semantic Runtime Auditing for Persistent AI Agents." arXiv:2607.08395+- Mem0 State of AI Agent Memory 2026. https://mem0.ai/blog/state-of-ai-agent-memory-2026diff --git a/v3/docs/adr/ADR-369-dream-cycle-swarm-ib-vq-inter-agent-messaging.md b/v3/docs/adr/ADR-369-dream-cycle-swarm-ib-vq-inter-agent-messaging.mdnew file mode 100644index 0000000000..7e96ab22c0--- /dev/null+++ b/v3/docs/adr/ADR-369-dream-cycle-swarm-ib-vq-inter-agent-messaging.md@@ -0,0 +1,64 @@+# ADR-369: Information-Bottleneck Vector-Quantized Inter-Agent Messaging++**Status:** Proposed+**Date:** 2026-07-19+**Authors:** claude (dream-cycle agent, 2026-07-19)+**Dream Cycle:** Slot 4 β swarm deep dive+**Source:** arXiv:2602.02035 (ICRA 2026), arXiv:2606.07557 (SPIN, 2026)++---++## Context++Ruflo's current swarm messaging layer transmits uncompressed text/JSON payloads between agents via `SendMessage`. At 8 agents (anti-drift default), this is tolerable. At 16β64 agents (the target range for tensor-train topology per SPIN, arXiv:2606.07557), uncompressed inter-agent communication becomes the primary bandwidth and latency bottleneck.++ICRA 2026 (arXiv:2602.02035) reports the first method to simultaneously improve task performance (+181.8%) and reduce inter-agent bandwidth (β41.4%) using information-bottleneck (IB) theory combined with vector quantization (VQ) on the inter-agent message channel. This breaks the historical performance-bandwidth tradeoff in multi-agent coordination.++No existing ADR (ADR-001 through ADR-319) covers inter-agent message compression. This is an architectural decision because it changes the serialization contract between all agents at the SendMessage boundary.++---++## Decision++Adopt IB+VQ compression as an optional (opt-in, then default) encoding layer for inter-agent messages in the ruflo swarm layer:++1. **Phase 1 (opt-in):** Add `--compress ib-vq` flag to `swarm init` and `SendMessage`. Messages are encoded via a learned codebook (VQ codebook size 256β1024). Codebook is shared at swarm init time and cached per session.+2. **Phase 2 (default on):** Enable IB+VQ by default for swarms with `maxAgents >= 8`. Maintain JSON fallback for single-agent sessions and `--no-compress` escape hatch.+3. **Benchmark gate:** Publish `swarm-messaging-bench` results before enabling Phase 2 default. Require β₯50% task improvement and β₯20% bandwidth reduction vs uncompressed baseline at 8 agents.++---++## Consequences++### Positive+- Breaks performance-bandwidth tradeoff (Grade A evidence, ICRA 2026)+- Unblocks scaling to 16β64 agents with SPIN tensor-train topology (ADR-322, TBD)+- Reduces egress cost for cloud-deployed swarms at scale+- Provides a differentiated capability vs LangGraph, AutoGen, CrewAI (none implement inter-agent message compression)++### Negative+- Codebook must be trained or shipped pre-trained (startup overhead)+- Adds encoding/decoding latency per message (must benchmark to confirm net positive)+- Breaking change for any external tooling that inspects raw SendMessage payloads+- Requires versioned message envelope to carry codec identifier++### Neutral+- JSON fallback preserves backward compatibility for `maxAgents < 8` sessions+- No change to the public SendMessage API surface β codec is transparent to callers++---++## Alternatives Considered++1. **Gzip compression only:** Reduces bandwidth but does not improve task performance (no information-bottleneck regularization). Rejected β misses the core gain.+2. **Protocol Buffers:** Structured encoding reduces size but still no IB regularization. May be combined with VQ in Phase 2 as the wire format.+3. **Do nothing:** Acceptable at 8 agents. Rejected for β₯16 agent targets β O(n^m) uncompressed messaging is untenable.++---++## References++- arXiv:2602.02035 β Bandwidth-Efficient Multi-Agent Communication via Information Bottleneck with Vector Quantization (ICRA 2026). Grade A.+- arXiv:2606.07557 β SPIN: Tensorized Policy Coordination for Decentralized Swarms. Grade A.+- arXiv:2606.19632 β Formal Verification of Learned Multi-Agent Communication Policies. Grade A. (Provides the formal-property verification framework to validate the codebook post-training.)+- Issue: to be filed as [Dream Cycle 2026-07-19]diff --git a/v3/docs/adr/ADR-370-dream-cycle-performance-world-model-agent-planning.md b/v3/docs/adr/ADR-370-dream-cycle-performance-world-model-agent-planning.mdnew file mode 100644index 0000000000..1fe3f0a376--- /dev/null+++ b/v3/docs/adr/ADR-370-dream-cycle-performance-world-model-agent-planning.md@@ -0,0 +1,72 @@+# ADR-370: World-Model Agent Planning for Cost-Aware Task Pre-Simulation++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-07-20)+**Dream Cycle Surface:** performance (SLOT=0)+**Source:** arXiv:2607.15901 (DSWorld, 2026) β Grade A++---++## Context++Ruflo agents execute tool chains reactively: they receive a task, plan inline, and execute each tool call sequentially. There is no pre-simulation step to estimate which paths are expensive before committing to them. As task complexity grows (multi-step data pipelines, cross-agent coordination), wasted real-tool calls compound.++The 2026 DSWorld paper (arXiv:2607.15901) demonstrates that a lightweight **world model** β a learned transition predictor trained on historical execution trajectories β can simulate tool outcomes before real execution. On data science agent tasks this yields:+- **14Γ RL agent training speedup** (fewer real-environment rollouts needed)+- **3β6Γ search-based inference speedup** (candidate plans evaluated in-model, not via real calls)++The methodology uses four components: structured state construction, cost-aware routing, lightweight real execution fallback, and an LLM-based simulator. A Reflective World Model Optimization (RWMO) RL strategy trains the predictor.++No competing agent framework (LangGraph, AutoGen, CrewAI, OpenAI Swarm) implements a world-model planning layer as of July 2026. AutoAgents-Rust achieves 84% higher throughput (4.97 vs 2.70 rps) over LangGraph through static typing, not planning optimization.++Separately, Ruflo's Flash Attention claim (2.49Γβ7.47Γ speedup) is explicitly unverified with no benchmark. The MCP response target (<100 ms) and CLI startup target (<500 ms) are also unmeasured.++---++## Decision++Introduce a **World Model Planner** layer into Ruflo's agent execution pipeline. Before executing a task chain with β₯3 estimated tool calls, the planner:++1. Retrieves relevant historical execution traces from AgentDB (HNSW lookup)+2. Uses a compact transition predictor (fine-tuned small model or rules-based) to estimate cost and success probability of each candidate plan+3. Selects the plan with the highest estimated success/cost ratio+4. Falls back to direct execution if the world model has <60% confidence++The implementation lives in a new `@claude-flow/planning` package (optional plugin). The `hooks pre-task` hook triggers the planner when `estimatedToolCalls >= 3`.++---++## Consequences++**Positive:**+- Reduces wasted real-tool calls during multi-step planning (target: 3β6Γ reduction)+- Complements ADR-026 (3-tier routing) β routing selects *which model*, planning selects *which path*+- Historical traces stored in AgentDB feed neural training loop (SONA/MoE) β virtuous cycle+- Positions Ruflo ahead of all four tracked competitors on planning sophistication++**Negative:**+- Cold-start problem: predictor needs β₯100 traces before estimates are reliable; fall-through to direct execution for new task types+- Adds latency for the planning step itself (~50β200 ms estimated); only worthwhile when real execution would cost β₯500 ms+- Requires building the transition trajectory dataset (target: 8,000 examples per DSWorld methodology)++**Neutral:**+- Does not affect single-tool tasks or tasks routed to Tier-1 codemoods+- Measured Flash Attention and MCP latency benchmarks must be established before world-model speedup is claimed publicly++---++## Implementation Plan++1. **Sprint 1 (2 weeks):** Build execution trace logger in `@claude-flow/hooks` post-task hook; store traces in AgentDB namespace `world-model-traces`+2. **Sprint 2 (2 weeks):** Build rules-based transition predictor using trace statistics; integrate with `hooks pre-task`+3. **Sprint 3 (3 weeks):** Fine-tune small LLM predictor on 8k traces; evaluate against rules-based baseline+4. **Sprint 4 (1 week):** Benchmark Ruflo MCP latency + Flash Attention; publish Grade A numbers++---++## References++- arXiv:2607.15901 β DSWorld: A World Model Framework for Data Science Agents (2026)+- ADR-026 β 3-Tier Model Routing+- ADR-143 β Deterministic Codemod Routing+- Dream Cycle 2026-07-20 Issue β #TBDdiff --git a/v3/docs/adr/ADR-371-dream-cycle-security-neural-cryptographic-authorization.md b/v3/docs/adr/ADR-371-dream-cycle-security-neural-cryptographic-authorization.mdnew file mode 100644index 0000000000..746a972f33--- /dev/null+++ b/v3/docs/adr/ADR-371-dream-cycle-security-neural-cryptographic-authorization.md@@ -0,0 +1,112 @@+# ADR-371: Neural Cryptographic Authorization Gate for Agentic Action Execution++**Status**: Proposed+**Authors**: claude (dream-cycle agent, 2026-07-21)+**References**: arXiv (Jul 16, 2026) "From Neural Intent to Cryptographic Authorization: Governing Agentic Workflows"; ADR-178 (RepE IPI Detection); ADR-165 (Security CVE Posture); ADR-096 (Encryption at Rest); ADR-101 (Federated Claims)++---++## Context++The July 2026 arXiv paper "From Neural Intent to Cryptographic Authorization: Governing Agentic Workflows" (Grade A) demonstrates that:++1. **Identity verification is insufficient**: Authenticated agents can still be hijacked via direct or indirect prompt injection after identity is confirmed. The attack succeeds at the intent-interpretation layer, not the authentication layer.++2. **The proposed fix is a mandatory cryptographic gate**: Before any agentic action executes, a Neural Cryptographic Service (NCS) computes an intent signature from the agent's hidden states and requires cryptographic proof that the action is authorized under the original task scope. If the intent signature deviates from the authorized pattern, execution is blocked regardless of agent identity.++Ruflo's current security stack (`@claude-flow/security`) provides:+- `InputValidator` β boundary-level input validation (Zod)+- `PathValidator` β path traversal prevention+- `SafeExecutor` β command injection protection+- ADR-178 (Proposed) β RepE-based IPI detection via entropy monitoring++None of these implement a cryptographic authorization gate at the action-execution level. ADR-096 covers encryption at rest. ADR-101 covers federated claims (identity). Neither prevents a legitimate, authenticated agent from executing an injected harmful action.++This is architecturally distinct from ADR-178: RepE detects anomalous intent; NCA prevents execution even when detection is uncertain. They are complementary.++---++## Decision++Add a `CryptoAuthGate` middleware to `@claude-flow/security` that intercepts action execution in the `@claude-flow/hooks` `pre-task` β `execute` path.++### Gate Architecture++```+Agent intent+ β+ βΌ+βββββββββββββββββββββββββββββββββββββββ+β NCA Layer (CryptoAuthGate) β+β 1. Extract intent signature β+β (task scope + action type + β+β tool targets) β+β 2. Verify against AuthorizationRoot β+β (HMAC-SHA256 of original task) β+β 3. Check deviation threshold β+β (configurable, default: strict) β+β 4. Block or pass execution β+βββββββββββββββββββββββββββββββββββββββ+ β β+ PASS BLOCK+ β β+ βΌ βΌ+execute() reject + log + alert+```++### AuthorizationRoot Construction++When a task is initiated via `hooks pre-task`:+1. Compute `AuthorizationRoot = HMAC-SHA256(task_description + allowed_tools + scope_constraints, session_key)`+2. Store `AuthorizationRoot` in the task context (not in shared memory β local to the execution context)+3. Pass `AuthorizationRoot` to all sub-agents spawned by this task++When a sub-agent attempts to call a tool:+1. Compute `ActionSig = HMAC-SHA256(tool_name + tool_args + agent_id, session_key)`+2. Verify `ActionSig` is within the authorized scope defined by `AuthorizationRoot`+3. Out-of-scope actions are blocked, logged (OWASP LLM06 Excessive Agency), and trigger the `audit` background worker++### Deviation Threshold++- **Strict mode** (default): tool targets must exactly match those declared in the original task scope+- **Permissive mode**: tools declared `"allowed": ["read", "search"]` can be used freely; `"disallowed": ["write", "delete"]` are hard-blocked+- **Audit mode**: all actions logged but none blocked; use during rollout to measure false-positive rate++---++## Consequences++### Positive+- Blocks PlanFlip-style cascade attacks at the execution boundary, even when planner context is compromised+- Provides OWASP LLM06 (Excessive Agency) mitigation with cryptographic enforcement+- Complements ADR-178 RepE detection: detect (RepE) + prevent (NCA) in depth+- Audit trail for all out-of-scope action attempts++### Negative+- Adds latency per tool call (HMAC computation β <1ms at current scale)+- Requires tasks to declare scope upfront β breaks ad-hoc agent workflows that don't pre-declare tools+- Session key management adds operational complexity (key rotation, multi-agent scope inheritance)++### Neutral+- Strict mode may generate false positives on legitimate multi-step workflows; audit mode recommended for first 2-week rollout+- AuthorizationRoot is per-task, not per-session β prevents scope bleed between concurrent tasks++---++## Implementation Scope++| Package | Change |+|---------|--------|+| `@claude-flow/security` | Add `CryptoAuthGate` class; `AuthorizationRoot` builder; scope deviation check |+| `@claude-flow/hooks` | Wire `CryptoAuthGate.check()` into `pre-task` hook before any tool dispatch |+| `@claude-flow/cli` | Add `--nca-mode [strict|permissive|audit]` flag to `hooks pre-task` |+| `@claude-flow/shared` | Add `TaskAuthContext` type for `AuthorizationRoot` + `ActionSig` |++---++## Relationship to Other ADRs++- **ADR-178** (RepE IPI Detection): NCA is the prevention layer; RepE is the detection layer. Both should ship together.+- **ADR-165** (Security CVE Posture): NCA adds to the security hardening surface; update CVE posture review after shipping.+- **ADR-096** (Encryption at Rest): Orthogonal β NCA operates at runtime action layer, not storage layer.+- **ADR-101** (Federated Claims): Claims prove identity; NCA proves action scope. Both are required β NCA assumes identity is established.diff --git a/v3/docs/adr/ADR-372-dream-cycle-intelligence-cognitive-mode-router.md b/v3/docs/adr/ADR-372-dream-cycle-intelligence-cognitive-mode-router.mdnew file mode 100644index 0000000000..98967e6c1f--- /dev/null+++ b/v3/docs/adr/ADR-372-dream-cycle-intelligence-cognitive-mode-router.md@@ -0,0 +1,66 @@+# ADR-372: Cognitive Mode Router for Agent Memory Query Dispatch++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-07-22)+**Surfaces:** intelligence (deep), memory (scan)+**Dream Cycle Issue:** TBD (filed same night)++---++## Context++The Supra Cognitive Modes (SCM) paper (arXiv 2607.19096, July 21 2026) demonstrates that routing memory queries by typeβfactoid lookup, multi-hop graph traversal, or long-form synthesisβyields 86.00% on LongMemEval and 84.87% on LoCoMo. The router is a frozen semantic classifier adding minimal latency.++Ruflo's current `@claude-flow/memory` module sends all queries through a single HNSW path regardless of type. This works for dense semantic search but leaves multi-hop and synthesis queries under-served: multi-hop benefits from graph traversal (ADR-130 adds graph-native backend but no dispatcher), synthesis benefits from stratified chunking not HNSW nearest-neighbor.++Additionally, the "Illusion of Multi-Agent Advantage" paper (arXiv 2606.13003) confirms that under equal token budgets single agents outperform multi-agent systems on multi-hop reasoning, reinforcing that smarter per-query routing at the memory layer is higher ROI than spawning more agents.++---++## Decision++Add a **Cognitive Mode Router (CMR)** as a lightweight pre-retrieval classifier in `@claude-flow/memory`:++1. **Query classifier**: frozen sentence-classification model (or heuristic rule set for MVP) that assigns each incoming query to one of three modes:+ - `FACTOID` β direct lookup, route to lexical+dense HNSW+ - `MULTI_HOP` β multi-step reasoning, route to graph traversal (ADR-087/ADR-130 backend)+ - `SYNTHESIS` β long-form generation, route to chunked stratified retrieval with re-ranking++2. **Mode-specific pipelines**: each mode gets its own retrieval path; FACTOID keeps the current HNSW path unchanged (no regression).++3. **Fallback**: if classifier confidence < 0.6, default to FACTOID path.++4. **Benchmark gate**: LongMemEval tracked in CI; target β₯ Zep Graphiti's 63.8% temporal sub-task on first integration.++---++## Consequences++**Positive:**+- Closes the SCM gap (86.00% LongMemEval) by enabling appropriate retrieval per query type+- No regression on FACTOID queries (same HNSW path)+- Graph backend (ADR-130) gets a proper entry point instead of being called ad-hoc+- Establishes LongMemEval as a tracked benchmark (fills gap noted in ADR-088)++**Negative / Risks:**+- Classifier adds latency per query (target < 5ms for frozen model or rule-based MVP)+- MVP heuristic classifier may misclassify ambiguous queries; monitor false-MULTI_HOP rate+- Requires LongMemEval dataset integration in CI (one-time setup cost)++---++## Alternatives Considered++- **No routing, just improve HNSW**: leaves multi-hop and synthesis quality on the table; does not address SCM findings+- **Always use graph backend**: higher latency for factoid queries; ADR-087 RRF result shows graph-only is not universally better+- **LLM-as-router**: too expensive (adds one full model call per memory query); frozen classifier or rules are sufficient++---++## References++- arXiv 2607.19096 β Supra Cognitive Modes (SCM), Tobkin & Yang, July 21 2026+- arXiv 2606.13003 β The Illusion of Multi-Agent Advantage, June 2026+- ADR-087 β Graph Node Native Backend+- ADR-088 β LongMemEval Benchmark+- ADR-130 β Graph Intelligence Integrationdiff --git a/v3/docs/adr/ADR-373-dream-cycle-memory-budget-operator-selection.md b/v3/docs/adr/ADR-373-dream-cycle-memory-budget-operator-selection.mdnew file mode 100644index 0000000000..2d3903c207--- /dev/null+++ b/v3/docs/adr/ADR-373-dream-cycle-memory-budget-operator-selection.md@@ -0,0 +1,60 @@+# ADR-373: Budget-Dependent Memory Operator Selection (OAS)++**Status:** Proposed+**Date:** 2026-07-23+**Authors:** claude (dream-cycle agent, 2026-07-23)+**Related:** ADR-097 (Federation Budget Circuit Breaker), ADR-088 (LongMemEval Benchmark)++---++## Context++Kang et al. (arXiv 2607.17545, Jul 2026) show that selecting the memory operation β retain (cheap append), consolidate (expensive summarize), or evict (drop oldest) β based on remaining token budget yields **+48% task success under tight-budget conditions** compared to a fixed consolidation policy.++Ruflo's `@claude-flow/memory` module currently runs a background consolidation worker at fixed low priority with no awareness of the caller's remaining token budget. This is a regressive policy: under tight budgets (common in production multi-agent runs) Ruflo triggers the most expensive memory operation (consolidation/summarization) at the worst time.++No existing ADR (085β319) addresses per-call budget-conditional operator dispatch for local memory management.++---++## Decision++Add a `MemoryOperatorSelector` to `@claude-flow/memory` that:++1. **Reads remaining budget** from the cost-tracker hook (`ruflo-cost-tracker` event or env var `CLAUDE_FLOW_BUDGET_REMAINING`) before every memory write operation.+2. **Selects operator** by threshold:+ - `budget > 30%`: `consolidate` β summarize old entries, maintain dense representation+ - `10% < budget β€ 30%`: `retain` β append only, no summarization+ - `budget β€ 10%` or budget unknown: `evict` β drop oldest entries beyond watermark, no LLM call+3. **Exposes opt-in flag** `--memory-budget-aware` (CLI) and `memoryBudgetAware: boolean` (API); defaults to `false` until benchmarked in production to avoid regressions.+4. **Records operator choice** in AgentDB metadata for offline analysis and SONA training.++Thresholds are tunable via `claude-flow.config.json β memory.budgetThresholds`.++---++## Implementation Target++| File | Change |+|------|--------|+| `v3/@claude-flow/memory/src/operators/budget-selector.ts` | New: `MemoryOperatorSelector` class |+| `v3/@claude-flow/memory/src/agentdb/writer.ts` | Integrate selector before write path |+| `v3/@claude-flow/cli/src/commands/memory.ts` | Add `--memory-budget-aware` flag |+| `v3/@claude-flow/memory/tests/budget-selector.test.ts` | Unit tests; mock cost-tracker |++---++## Consequences++**Positive:**+- +48% estimated task success under tight budgets (Grade A evidence, Kang et al. 2607.17545)+- Zero-cost evict path eliminates LLM calls when budget is exhausted+- Opt-in default eliminates regression risk++**Negative:**+- Requires cost-tracker integration; adds coupling between memory and billing modules+- Evict-on-low-budget degrades memory quality when agents run long++**Deferred:**+- Multi-hop graph traversal (separate gap, higher implementation cost β needs ADR of its own)+- MINJA input validation (security scope, ADR should be in `@claude-flow/security`)diff --git a/v3/docs/adr/ADR-374-dream-cycle-swarm-subagent-permission-delegate.md b/v3/docs/adr/ADR-374-dream-cycle-swarm-subagent-permission-delegate.mdnew file mode 100644index 0000000000..46137d6371--- /dev/null+++ b/v3/docs/adr/ADR-374-dream-cycle-swarm-subagent-permission-delegate.md@@ -0,0 +1,82 @@+# ADR-374 β SubagentPermissionDelegate: Workspace-Scoped Privilege Delegation for Swarm Agents++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-07-24)+**Related:** Dream Cycle 2026-07-24, arXiv 2606.31174 (ClawArena-Team)++---++## Context++The ClawArena-Team benchmark (arXiv 2606.31174, 2026) evaluated 41 subagent orchestration scenarios across 258 rounds and found:++- No tested LLM model exceeded 50% workspace-permission precision when acting as team lead+- The primary management bottleneck for LLM-orchestrated swarms is **privilege granting**, not perception or reasoning+- API cost and management quality are decoupled β 100Γ cost span yields <4Γ quality span++Ruflo's current `swarm init` spawns subagents with no formal permission delegation protocol. Each agent inherits the full capability set of the invoking session. This is equivalent to running all swarm workers as root β it violates least-privilege, makes audit trails impossible, and is the exact failure mode ClawArena-Team identifies as the bottleneck.++---++## Decision++Add a **SubagentPermissionDelegate** protocol to `swarm init` that:++1. Assigns each spawned agent a **workspace-scoped capability token** derived from the swarm topology and the agent's declared role+2. Enforces the token at the hook layer (`pre-task`, `pre-edit`) before any file system or MCP tool access+3. Generates an audit trail of permission grants/denials per swarm run in `.swarm/permission-audit.jsonl`++### Token Shape (minimal)++```typescript+interface SubagentCapabilityToken {+ agentId: string;+ swarmId: string;+ role: AgentRole; // 'coder' | 'reviewer' | 'tester' | ...+ allowedPaths: string[]; // glob patterns, e.g. ['src/**', 'tests/**']+ allowedTools: string[]; // e.g. ['Read', 'Edit', 'Bash']+ denyTools: string[]; // e.g. ['git push', 'npm publish']+ expiresAt: number; // epoch ms+}+```++### Integration Points++- `swarm init --with-permissions` flag enables the protocol (opt-in initially)+- `@claude-flow/security`'s `InputValidator` validates token at hook boundaries+- `@claude-flow/hooks` `pre-task` hook enforces allowedTools check+- Default role-to-permission maps ship in `config/swarm-permission-defaults.json`++---++## Consequences++**Positive:**+- Closes the #1 ClawArena-Team bottleneck for Ruflo swarms+- Enables auditable, reproducible swarm runs+- Path to >50% workspace-permission precision on ClawArena-style eval++**Negative:**+- Adds configuration overhead for swarm setup+- Default permission maps will be wrong for some workflows; users must tune+- Breaking change if `--with-permissions` becomes default in a future minor release++**Neutral:**+- Scope: this is a protocol + hook integration; no changes to existing agent types or MCP tools+- Does NOT require consensus changes (raft stays unchanged)++---++## Alternatives Considered++1. **Full sandbox isolation per agent** (Docker/E2B per agent): Too expensive (~200-500ms setup per agent, disk cost); ruled out for standard swarms. Reserved for `isolation: 'worktree'` mode already implemented.+2. **No change**: Status quo permits swarms to work but leaves ClawArena-level precision gap unaddressed.++---++## Implementation Notes++- `no ADR` classification does NOT apply: this is an architectural protocol change, not a parameter tweak+- First milestone: permission-audit.jsonl with read-only enforcement (allowedPaths)+- Second milestone: tool-level enforcement (allowedTools/denyTools)+- Benchmark target: measure against ClawArena-Team criteria after implementationdiff --git a/v3/docs/adr/ADR-375-dream-cycle-performance-agentperf-benchmark-mixture-of-agents.md b/v3/docs/adr/ADR-375-dream-cycle-performance-agentperf-benchmark-mixture-of-agents.mdnew file mode 100644index 0000000000..72e6166bb1--- /dev/null+++ b/v3/docs/adr/ADR-375-dream-cycle-performance-agentperf-benchmark-mixture-of-agents.md@@ -0,0 +1,73 @@+# ADR-375: Agentic Inference Benchmarking Standard + Mixture-of-Agents Test-Time Scaling++**Status:** Proposed+**Authors:** claude (dream-cycle agent, 2026-07-25)+**Dream Cycle Issue:** TBD (filed same session)+**Related:** ADR-026 (3-tier model routing), ADR-143 (intent routing)++## Context++Two Grade-A findings from the 2026-07-25 Dream Cycle performance deep dive:++1. **AA-AgentPerf** (Artificial Analysis, June 12, 2026): The first agentic inference benchmark has published results showing a 23.6Γ hardware efficiency gap (GB300: 61,354 Agents/MW vs H200: 2,594 Agents/MW). Ruflo has no registered performance on this benchmark. All four tracked competitors (LangGraph, AutoGen, CrewAI, OpenAI Swarm) are also unregistered β this is a first-mover opportunity.++2. **Pareto-Optimal Test-Time Scaling** (arXiv 2605.01566, ACL 2026 SRW): Mixture-of-agents (MoA) achieves +2.7pp over self-consistency on MMLU-Pro at equal compute budget. The key configuration insight: MoA is most efficient when `parallelGenerations > sequentialAggregations`. Ruflo's 3-tier routing (ADR-026) selects by cost/complexity but has no test-time compute scaling mode.++## Decision++### Part A: AA-AgentPerf Benchmark Registration++Add `npx claude-flow@latest performance benchmark --suite agentperf` that:+- Replays a standardized agentic coding trajectory (200-turn, 100K+ token context)+- Reports: Agents/MW (primary), P95 latency, TTFT, concurrent-agent throughput+- Targets β₯5,000 Agents/MW on standard developer hardware (H100/H200 equivalent)+- Gates CI: fail if Agents/MW drops below 80% of baseline on performance PRs+- Publishes results to a public leaderboard entry (CLAUDE.md Performance Targets table)++### Part B: Mixture-of-Agents Routing++Extend `hooks route` (ADR-026 Tier-2/3 decision) with a `--scaling-mode` flag:++```typescript+interface RoutingDecision {+ tier: 1 | 2 | 3;+ scalingMode: 'none' | 'self-consistency' | 'mixture-of-agents' | 'self-refine';+ parallelBranches?: number;+ sequentialAggregations?: number;+}+```++Activate `mixture-of-agents` when:+- Task complexity score β₯ 0.6 (Tier 3 threshold)+- `estimatedParallelAgents > estimatedSequentialAggregations`+- Token budget allows β₯ 3 parallel drafts++Expected gain: +2.7pp accuracy over self-consistency at equal compute (Grade A evidence).++## Consequences++### Positive+- Closes the AA-AgentPerf credibility gap (first-mover vs all tracked competitors)+- ACL 2026 Grade A evidence for +2.7pp accuracy gain from MoA at no extra cost+- Replaces the unverified Flash Attention claim with a measurable Agents/MW metric+- MoA routing is architecturally additive β no breaking change to ADR-026 tiers++### Negative+- AA-AgentPerf benchmark run requires long-context GPU infrastructure (not cheap in CI)+- MoA routing adds latency for the parallel-draft phase before aggregation+- ADR-375 collision: multiple prior dream branches have created ADR-375 with different content. This ADR uses 320 because it is the next available number on `main` (ADR-319 is the last merged). Human reviewer must reconcile or renumber when merging dream branches.++## Implementation Plan++1. `v3/@claude-flow/cli/src/performance/agentperf-suite.ts` β trajectory replay harness+2. `v3/@claude-flow/hooks/src/route/scaling-mode.ts` β MoA routing extension+3. `v3/@claude-flow/cli/src/commands/performance.ts` β add `--suite agentperf` flag+4. `.github/workflows/agentperf-gate.yml` β CI gate on performance PRs+5. Update `CLAUDE.md` Performance Targets table with Agents/MW metric++## References++- AA-AgentPerf: https://artificialanalysis.ai/articles/aa-agentperf (Jun 12, 2026)+- arXiv 2605.01566: "Multi-Agent Reasoning Improves Compute Efficiency: Pareto-Optimal Test-Time Scaling" (ACL 2026 SRW)+- arXiv 2604.25917: "Recursive Multi-Agent Systems" (RecursiveMAS)+- dev.to/saivishwak: AutoAgents-Rust benchmark (Feb 2026)diff --git a/v3/docs/adr/ADR-376-dream-cycle-intelligence-heterogeneous-ensemble-api.md b/v3/docs/adr/ADR-376-dream-cycle-intelligence-heterogeneous-ensemble-api.mdnew file mode 100644index 0000000000..bb480f134b--- /dev/null+++ b/v3/docs/adr/ADR-376-dream-cycle-intelligence-heterogeneous-ensemble-api.md@@ -0,0 +1,56 @@+# ADR-376: Heterogeneous Agent Ensemble Composition API++| Field | Value |+|-------|-------|+| Status | Proposed |+| Date | 2026-07-27 |+| Authors | claude (dream-cycle agent, 2026-07-27) |+| References | PoTRE (arXiv 2607.x, Kankariya & ArΔ±k); PRO-LONG (arXiv 2607.x, Fox et al.); Dream Cycle #2784 |++---++## Context++2026 agent-intelligence SOTA is defined by **heterogeneous multi-agent ensembles**. PoTRE (Poly-Topological Reasoning Ensembles) achieves 49.92% on Humanity's Last Exam by composing 4 agents with distinct reasoning strategies (adversarial refinement, hierarchical planning, spectrum search, direct chain) and a task-adaptive aggregation layer. This is grade-A reproduced (peer-reviewed arXiv 2607.x).++Ruflo currently supports homogeneous swarm topologies (`hierarchical`, `mesh`, `hierarchical-mesh`, `adaptive`) but provides no API for composing agents with **different reasoning strategies within a single swarm**. All agents in a Ruflo swarm share the same type/prompt template; topology controls communication pattern, not reasoning diversity.++Every major competitor (LangGraph v1.2.x, Microsoft Agent Framework 1.0, CrewAI v1.14.x) also lacks heterogeneous ensemble composition β making this an **opportunity for differentiation** at the coordination layer, not just a catch-up move.++---++## Decision++Add a `heterogeneous` topology mode to the Ruflo swarm system that:++1. Accepts a list of `{ strategy, agentType, weight }` slots at swarm initialization+2. Assigns each slot a distinct reasoning prompt template (adversarial, hierarchical, spectrum-search, direct-chain) with no shared base prompt+3. After each task round, runs a **task-adaptive aggregation** step (weighted voting, configurable: majority / weighted / llm-judge) that synthesizes slot outputs into a single response+4. Records per-slot contribution scores in AgentDB for SONA-driven weight adjustment across rounds (leveraging existing EWC++ to prevent weight collapse)+5. Exposes CLI: `npx ruflo swarm init --topology heterogeneous --slots adversarial,hierarchical,spectrum,chain --aggregation weighted`++---++## Consequences++**Positive:**+- Enables PoTRE-class reasoning diversity within a single `ruflo swarm` invocation+- Reuses existing SONA, MoE, EWC++ infrastructure β no new learning subsystems required+- Opens a benchmark path: wire HumanityLastExam into `ruflo performance benchmark --suite intelligence` to measure parity with 49.92% PoTRE baseline++**Negative / Risks:**+- Aggregation step adds latency (~1 LLM call per round); must be async and time-boxed+- Per-slot prompt isolation complicates the existing `shared memory namespace` pattern β slots write to sub-namespaces, aggregator reads across them+- 4 concurrent agents per swarm round increases token cost ~4Γ vs single-agent baseline; must be documented in cost warnings++**Not covered by this ADR (implementation-level):**+- PRO-LONG programmatic memory log compression (separate feature, does not require new topology)+- Intelligence benchmark suite wiring (tracked in performance module roadmap)++---++## Alternatives Considered++- **Parameter-sweep homogeneous ensemble**: vary temperature/top-p across identical agents. Rejected β diversity of reasoning strategy (not just sampling) is what drives PoTRE gains.+- **Separate CLI command `ruflo ensemble`**: Rejected β heterogeneous is a topology variant; keeping it under `swarm` preserves the unified coordination model.+- **No change**: Accepted cost is falling behind as heterogeneous ensembles become the 2026 default for reasoning benchmarks.diff --git a/v3/docs/adr/README.md b/v3/docs/adr/README.mdindex 385cad4fce..a78cec92c8 100644--- a/v3/docs/adr/README.md+++ b/v3/docs/adr/README.md@@ -51,6 +51,49 @@ All ADRs are located in [`/v3/implementation/adrs/`](../../implementation/adrs/)| [ADR-331](ADR-331-project-local-flywheel-anchors.md) | Project-Local Flywheel Evaluation Anchors | Accepted || [ADR-332](ADR-332-hermetic-release-verification-runtime-baseline.md) | Hermetic Release Verification and Supported Runtime Baseline | Accepted || [ADR-333](ADR-333-efficiency-first-orchestration-prehoc-failure-inference.md) | Efficiency-First Orchestration β Pre-hoc Failure Inference and Adaptive Agent Count Routing | Proposed |+| [ADR-334](ADR-334-hierarchical-consensus-topology.md) | Hierarchical Consensus Topology for Large-Scale Swarm Coordination | Proposed |+| [ADR-335](ADR-335-mv-hnsw-agent-memory-upgrade.md) | Upgrade to Multi-Vector HNSW (MV-HNSW) for Agent Memory Retrieval | Proposed |+| [ADR-336](ADR-336-agent-authorization-propagation.md) | Agent Authorization Propagation and MCP Authentication Enforcement | Proposed |+| [ADR-337](ADR-337-plugin-supply-chain-integrity-memory-governance.md) | Plugin Supply Chain Integrity and Memory Namespace Governance | Proposed |+| [ADR-338](ADR-338-sona-behavioral-trajectory-auditing.md) | SONA Behavioral Trajectory Auditing via Embedding-Space Trait Vectors | Proposed |+| [ADR-339](ADR-339-memory-integrity-mcp-verification.md) | Memory Write Integrity Validation & MCP Tool Verification | Proposed |+| [ADR-340](ADR-340-retrospective-harness-optimization.md) | Retrospective Harness Optimization (RHO) for SONA Intelligence Loop | Proposed |+| [ADR-341](ADR-341-multi-signal-memory-retrieval.md) | Multi-Signal Memory Retrieval | Proposed |+| [ADR-342](ADR-342-dream-cycle-ruvector-production-scale-backend.md) | RuVector Production-Scale Backend Adoption | Proposed |+| [ADR-343](ADR-343-shared-context-parallel-dispatch.md) | Shared-Context Parallel Dispatch for Multi-Agent Performance | Proposed |+| [ADR-344](ADR-344-knowledge-graph-index-for-reasoningbank.md) | Knowledge Graph Index for ReasoningBank | Proposed |+| [ADR-345](ADR-345-swarm-credit-routing-shapley.md) | Swarm Credit Routing via Shapley-Value Attribution | Proposed |+| [ADR-346](ADR-346-multi-layer-agent-security.md) | Multi-Layer Agent Security Stack | Proposed |+| [ADR-347](ADR-347-trajectory-quality-judge-scoring.md) | Trajectory-Quality JUDGE Scoring for ReasoningBank | Proposed |+| [ADR-348](ADR-348-dream-cycle-swarm-adaptive-topology-selector.md) | Task-Adaptive Swarm Topology Selector | Proposed |+| [ADR-349](ADR-349-dream-cycle-intelligence-flare-lookahead.md) | FLARE-Style Lookahead Planning Buffer for SONA Intelligence Layer | Proposed |+| [ADR-350](ADR-350-dream-cycle-swarm-trust-weighted-consensus.md) | Trust-Weighted Consensus for Swarm Coordination | Proposed |+| [ADR-351](ADR-351-dream-cycle-performance-stateful-execution-loop.md) | Stateful Execution Loop with KV-Cache Discipline and Agent Execution Graphs | Proposed |+| [ADR-352](ADR-352-mcp-tool-permission-attestation.md) | MCP Tool Permission Attestation (Min-Privilege Contract) | Proposed |+| [ADR-353](ADR-353-dream-cycle-intelligence-skill-distillation.md) | Trace-to-Skill Distillation for Intelligence Pipeline | Proposed |+| [ADR-354](ADR-354-agentdb-write-verification-temporal-supersession.md) | AgentDB Memory Write Verification and Temporal Supersession Layer | Proposed |+| [ADR-355](ADR-355-swarm-rl-stopping-policy.md) | Reinforcement-Learned Stopping Policy for Ruflo Swarm Orchestration | Proposed |+| [ADR-356](ADR-356-dream-cycle-performance-cross-agent-kvcache.md) | Cross-Agent KV-Cache Sharing for Swarm Performance | Proposed |+| [ADR-357](ADR-357-dream-cycle-intelligence-dimension-aware-routing.md) | Dimension-Aware Intelligence Routing for Heterogeneous Agent Pools | Proposed |+| [ADR-358](ADR-358-automem-memory-rl-training-loop.md) | AutoMem-Style RL Training Loop for AgentDB Memory Operations | Proposed |+| [ADR-359](ADR-359-swarm-inverse-wisdom-dissent-mechanism.md) | Swarm Dissent Mechanism: Inverse-Wisdom Law Compliance | Proposed |+| [ADR-360](ADR-360-dream-cycle-performance-polykv-shared-kv-pool.md) | Cross-Agent Shared KV Pool (PolyKV Architecture) | Proposed |+| [ADR-361](ADR-361-dream-cycle-intelligence-skill-evolution-worker.md) | Skill Evolution Worker (SEW) β Runtime RL-Based Skill Acquisition for SONA | Proposed |+| [ADR-362](ADR-362-dream-cycle-swarm-hnsw-comms-fabric.md) | HNSW-as-Communication-Fabric (HCF) for RuVector Swarm Knowledge Gossip | Proposed |+| [ADR-363](ADR-363-dream-cycle-performance-workflow-atomic-inference-scheduling.md) | Workflow-Atomic Inference Scheduling (WAIS) for Multi-Agent Execution | Proposed |+| [ADR-364](ADR-364-dream-cycle-security-plugin-supply-chain-scanner.md) | Plugin Supply-Chain Scanner and Behavioral Manifest | Proposed |+| [ADR-365](ADR-365-recurrence-gated-memory-consolidation.md) | Recurrence-Gated Memory Consolidation for AgentDB | Proposed |+| [ADR-366](ADR-366-dream-cycle-swarm-self-evolving-skill-distillation.md) | Self-Evolving Swarm Skill Distillation via Trajectory Feedback | Proposed |+| [ADR-367](ADR-367-epistemic-working-memory-intelligence-pipeline.md) | Epistemic Working Memory in the Intelligence Pipeline | Proposed |+| [ADR-368](ADR-368-dream-cycle-memory-selective-persistence.md) | Selective Persistent Memory Categories for AgentDB | Proposed |+| [ADR-369](ADR-369-dream-cycle-swarm-ib-vq-inter-agent-messaging.md) | Information-Bottleneck Vector-Quantized Inter-Agent Messaging | Proposed |+| [ADR-370](ADR-370-dream-cycle-performance-world-model-agent-planning.md) | World-Model Agent Planning for Cost-Aware Task Pre-Simulation | Proposed |+| [ADR-371](ADR-371-dream-cycle-security-neural-cryptographic-authorization.md) | Neural Cryptographic Authorization Gate for Agentic Action Execution | Proposed |+| [ADR-372](ADR-372-dream-cycle-intelligence-cognitive-mode-router.md) | Cognitive Mode Router for Agent Memory Query Dispatch | Proposed |+| [ADR-373](ADR-373-dream-cycle-memory-budget-operator-selection.md) | Budget-Dependent Memory Operator Selection (OAS) | Proposed |+| [ADR-374](ADR-374-dream-cycle-swarm-subagent-permission-delegate.md) | SubagentPermissionDelegate: Workspace-Scoped Privilege Delegation for Swarm Agents | Proposed |+| [ADR-375](ADR-375-dream-cycle-performance-agentperf-benchmark-mixture-of-agents.md) | Agentic Inference Benchmarking Standard + Mixture-of-Agents Test-Time Scaling | Proposed |+| [ADR-376](ADR-376-dream-cycle-intelligence-heterogeneous-ensemble-api.md) | Heterogeneous Agent Ensemble Composition API | Proposed |## Summary Documentsdiff --git a/v3/docs/dream/dream-gist-2026-06-13.md b/v3/docs/dream/dream-gist-2026-06-13.mdnew file mode 100644index 0000000000..61fa71fa61--- /dev/null+++ b/v3/docs/dream/dream-gist-2026-06-13.md@@ -0,0 +1,82 @@+# Memory Agent SOTA Report β 2026-06-13++**TL;DR:** Three 2026 papers establish that flat HNSW retrieval without temporal decay is SOTA-deficient: MemMachine cuts token cost 80% via episodic ground-truth preservation (LoCoMo 0.9169); SSGM identifies semantic drift and knowledge-leakage as architectural risks in flat-vector long-term stores; the survey arXiv:2603.07670 names "learned forgetting" and "causal retrieval" as the two biggest unsolved frontiers. Ruflo's AgentDB has neither.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| MemMachine: episodic ground-truth store cuts tokens 80%, LoCoMo 0.9169 | arXiv:2604.04853 (Apr 2026) | A |+| SSGM framework: flat HNSW without temporal decay risks topology-induced knowledge leakage | arXiv:2603.11768 (Mar 2026, rev May 2026) | B (no quant results) |+| Survey identifies 5 open frontiers: continual consolidation, causal retrieval, trustworthy reflection, learned forgetting, multimodal embodied | arXiv:2603.07670 (Mar 2026) | A |+| Mem0 ECAI: 91% lower p95 latency (1.44 s vs 17.12 s), 90% lower token cost vs full-context | arXiv:2504.19413 (ECAI 2025) | A |+| CrewAI v1.12: Qdrant Edge backend + hierarchical namespace isolation | CrewAI changelog Apr 2026 | B |+| LangGraph v0.4: PostgresSaver checkpointer with TTL-aware state eviction | LangGraph changelog Apr 2026 | B |++---++## Ruflo Current Capability++| Capability | Status | Notes |+|-----------|--------|-------|+| HNSW vector search | β Active | ~1.9x at N=20k vs brute force (measured) |+| SQLite persistent cache | β Active | sql.js WASM backend |+| ReasoningBank / EWC++ | β Active | Prevents catastrophic forgetting |+| Temporal decay modeling | β Missing | Entries never age or expire |+| Episodic ground-truth preservation | β Missing | HNSW stores embeddings, not raw episodes |+| Consistency verification | β Missing | No integrity check on consolidation |+| Namespace write-authority | β In-progress | ADR-145 Proposed |+| LongMemEval score published | β οΈ Deferred | ADR-088: <90% target, deferred |+| Causal / multi-hop retrieval | β Missing | ADR-155 Proposed (2026-06-12, KG gap) |++---++## Competitor Comparison++| System | Memory Backend | Temporal Decay | Episodic Preservation | LongMemEval / LoCoMo |+|--------|----------------|---------------|----------------------|----------------------|+| **MemMachine** | 3-layer (short/episodic/profile) | β (TTL per tier) | β raw episode store | LoCoMo 0.9169 (Grade A) |+| **CrewAI v1.12** | Qdrant Edge + hierarchical isolation | β configurable | β embedding-only | Not published |+| **LangGraph v0.4** | PostgresSaver checkpointer | β TTL eviction | β state snapshots | Not published |+| **Zep** | Temporal knowledge graph | β native | β entity tracking | 63.8% temporal retrieval (arXiv:2501.13956, Grade B) |+| **Mem0** | Hybrid semantic+short-term | β no decay | β | LoCoMo ~49% temporal, 91% lower latency (Grade A) |+| **Ruflo AgentDB** | SQLite + HNSW flat store | β absent | β | ADR-088: deferred |++---++## Benchmarks++| Benchmark | Best Score | System | Year | Grade |+|-----------|-----------|--------|------|-------|+| LoCoMo | 0.9169 | MemMachine (GPT-4-mini) | 2026 | A (arXiv:2604.04853) |+| LongMemEvalS | 93.0% | MemMachine | 2026 | A (arXiv:2604.04853) |+| Mem0 p95 latency | 1.44 s vs 17.12 s full-context | Mem0 | 2025 | A (arXiv:2504.19413) |+| Zep temporal retrieval | 63.8% vs Mem0 49.0% | Zep | 2026 | B (arXiv:2501.13956, single source) |++> Note: No 2026 benchmark data available for Ruflo AgentDB's LoCoMo or LongMemEvalS performance.++---++## SOTA Proof & Witness++Session commit: `4cbcfc2671ad3f13ac9a648c1604c09fdb934248`+Report SHA-256: `42dc7ff29b2f3c387bc7ce8ae8e528c8dda6f3904ed49e93d4100ddadc9d0acd`+Witness stamp: `483dbb39773e936665cccf5eeb1e669a53e10390e9ee7f6cde3612ad10ff2368`++Verifier: SHA-256 computed on pre-witness gist body. Reproduce:+```+printf '%s%s' "42dc7ff29b2f3c387bc7ce8ae8e528c8dda6f3904ed49e93d4100ddadc9d0acd" "4cbcfc2671ad3f13ac9a648c1604c09fdb934248" | sha256sum+# must equal 483dbb39773e936665cccf5eeb1e669a53e10390e9ee7f6cde3612ad10ff2368+```++---++## Recommended Next Steps++1. **Implement temporal decay controller in AgentDB** (ADR-156): Add TTL-based aging with configurable half-life per namespace tier (short: 7 days, episodic: 90 days, long-term: 1 year). Prevents semantic drift identified by SSGM (arXiv:2603.11768). Estimated ~120 LOC new controller.++2. **Add episodic ground-truth layer alongside HNSW embeddings**: Store raw conversation episodes as first-class objects (not just embeddings) to enable MemMachine-style retrieval. Target: recover 80% token efficiency vs current embedding-only recall on LoCoMo-style queries.++3. **Run LoCoMo benchmark against current AgentDB**: Establishes baseline before ADR-156 changes land. MemMachine 0.9169 is the 2026 SOTA bar. Current Ruflo likely trails without temporal decay + episodic layer.diff --git a/v3/docs/research/dream-cycle-2026-05-29-swarm.md b/v3/docs/research/dream-cycle-2026-05-29-swarm.mdnew file mode 100644index 0000000000..7eb765de79--- /dev/null+++ b/v3/docs/research/dream-cycle-2026-05-29-swarm.md@@ -0,0 +1,103 @@+# Swarm SOTA Report β 2026-05-29++**TL;DR:** Five 2026 arXiv papers redefine swarm consensus β decentralized Shapley credit, hierarchical PBFT at O(n) message complexity, and communication-policy decoupling each expose structural gaps in Ruflo's flat Raft consensus that will limit scaling past ~50 agents.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| SWARM+: hierarchical PBFT consensus scales to 1,000 agents with 97-98% scheduling latency improvement and β€7.5% degradation under 50% agent failures | arXiv:2603.19431 (Mar 19, 2026) | A |+| SwarmHarness: skill nodes self-organise into compute swarm without central authority via DHT + Shapley-value credit attribution | arXiv (May 27, 2026) | A |+| SLIM: decoupling communication from policy maintains performance under severe bandwidth constraints β direct drop-in for drone and LLM-agent swarms | arXiv (May 20, 2026) | A |+| Auction-Consensus: RL-based bidding replaces hand-crafted functions in consensus task allocation, improving solution quality while preserving decentralised execution | arXiv (May 20, 2026) | A |+| CINOC: neural policies trained on 10-agent swarms transfer zero-shot to 500-agent populations via physics-informed operator learning | arXiv (May 25, 2026) | A |+| LangGraph v0.4 fastest on latency across 2,000-task benchmark; CrewAI 3Γ token overhead on single-tool flows vs LangGraph | tensoria.fr benchmark (2026) | B |++---++## Ruflo Current Capability++| Capability | Status | Detail |+|-----------|--------|--------|+| Consensus protocol | Raft (leader-based) | Good crash-fault tolerance; weak under 30%+ Byzantine |+| Max validated agents | 8 (CLAUDE.md default) | No public stress-test beyond this |+| Credit attribution | None | Agents have no Shapley-style contribution weighting |+| Communication-policy coupling | Coupled | All agents share same coordination channel; no bandwidth tiering |+| Scale-transfer primitives | None | Swarm configs are static; no zero-shot scale extrapolation |+| Event-triggered messaging | No | All coordination is time- or call-driven |+| Swarm observability (ruview) | Hooks + memory only | No structured audit trail or agent execution graph |+| Hybrid vector search (ruvector) | No | HNSW only; no vector+keyword hybrid retrieval |+| Public recall benchmark | None | No published score for AgentDB/HNSW at 1M+ vectors |++---++## Competitor Comparison++| Framework | Consensus | Max Agents (validated) | Credit Attribution | Observability |+|-----------|-----------|----------------------|-------------------|--------------|+| **Ruflo (claude-flow v3.6)** | Raft | 8 (configured max) | None | Hooks + memory (no trace graph) |+| **LangGraph v0.4** | Checkpoint-based (no consensus) | No stated limit | None | LangSmith native (full trace) |+| **AutoGen 1.0 GA** | GroupChat selector | No stated limit | None | Azure Monitor integration |+| **CrewAI Enterprise** | Sequential/hierarchical fixed | 50+ (enterprise reported) | None | SOC2 observability hooks |+| **OpenAI Agents SDK** | Handoff-based (no consensus) | No stated limit | None | Built-in tracing, spans |+| **SWARM+** (research) | Hierarchical PBFT | 1,000 (benchmarked) | Dynamic quorum | Not productised |++---++## Benchmarks++| System | Metric | Value | Grade | Source |+|--------|--------|-------|-------|--------|+| SWARM+ | Scheduling latency improvement over baseline | 97-98% | A | arXiv:2603.19431 |+| SWARM+ | Job completion under 50% agent failure | β₯92.5% | A | arXiv:2603.19431 |+| SWARM+ | Agent scale | 1,000 agents | A | arXiv:2603.19431 |+| RLR consensus | Quality of Delivery vs RaBFT (30% Byzantine) | +126% | B | Research Square rs-7522626 |+| Qdrant | Query latency at 100M vectors, 95% recall | sub-100ms | B | dasroot.net (Apr 2026) |+| Milvus | Throughput at 1B vectors | 100K+ QPS | B | dasroot.net (Apr 2026) |+| Weaviate | Hybrid search recall at 1M vectors | 93.2% | B | dasroot.net (Apr 2026) |+| LangGraph | Fastest latency in 2,000-task cross-framework test | #1 | B | tensoria.fr (2026) |++---++## SOTA Proof & Witness++_This section is completed after file hash computation._++| Field | Value |+|-------|-------|+| **Session commit** | `b8a49cfb82ffe3e1f376cc3be3776bdd4d8c9ab7` |+| **Report SHA-256** | `712376e4ef16f9f00e24da2f5dabe4600825f7b103f98670298b50e77c09121e` |+| **Witness stamp** | `8e3c2d8fb902014b739e54cf07b1b237d0168feb1a24c4e6e1d6ae47474f3588` |+| **Verifier** | `sha256sum dream-gist-2026-05-29.md` β concat session commit β `sha256sum` β must equal witness stamp |++---++## Scan: ruvector-integration++**Source:** dasroot.net (Apr 2026), digitalapplied.com (2026), callsphere.ai (2026)++Qdrant is 10-25% faster than Weaviate/Milvus on common workloads (Grade B). Weaviate hybrid search (vector + keyword) achieves 93.2% recall at 1M vectors (Grade B). Milvus handles 1B-scale collections at 100K+ QPS (Grade B). Ruflo's ruvector/AgentDB has no public benchmark, no hybrid retrieval, and no validated performance at 1M+ vectors. LanceDB costs ~$200-500/month at 10M vectors β 4-25Γ cheaper than alternatives.++**Finding:** ruvector benchmarking gap is the single highest-ROI documentation task: publishing HNSW recall@10 at 100K, 1M, 10M vectors would immediately differentiate vs all four competitors who publish vendor-only Grade B claims.++---++## Scan: ruview-integration (Swarm Observability)++**Source:** codebase grep (no ruview module found), LangSmith docs, OpenAI Agents SDK tracing++Ruflo has no dedicated swarm execution trace module. `post-edit` and `post-task` hooks write to memory namespaces but produce no structured span-based trace graph. LangGraph ships LangSmith natively (full agent graph, token cost per node, replay). OpenAI Agents SDK emits OpenTelemetry-compatible spans out of the box. CrewAI Enterprise has SOC2 observability. Ruflo has none.++**Finding (Grade C β single internal assessment):** Absence of a structured trace graph is the primary barrier to enterprise adoption; every competitor has addressed this; Ruflo has not.++---++## Recommended Next Steps++1. **ADR-132 (file today):** Adopt hierarchical consensus topology for swarms >20 agents β replace flat Raft with SWARM+-style two-tier hierarchy (leader group + worker shards), reducing coordination overhead and enabling scale to 200+ agents without O(nΒ²) message explosion. Implement in `@claude-flow/cli` hive-mind module.++2. **Benchmark ruvector now (implementation-level, no ADR):** Add `npx claude-flow performance benchmark --suite vector` that runs recall@10 and p99 latency at 100K/1M/10M vectors using the existing HNSW index and publishes results to `v3/docs/benchmarks/vector-search.md`. This closes the Grade B gap vs all four external vector DBs.++3. **ruview stub (implementation-level, no ADR):** Add `@claude-flow/ruview` plugin stub that wraps existing hook events into OpenTelemetry-compatible spans. Single-file implementation using `@opentelemetry/sdk-trace-node` as a dev dependency. Enables export to Jaeger/Zipkin with zero architectural change to existing hooks.diff --git a/v3/docs/research/dream-cycle-2026-05-30-performance.md b/v3/docs/research/dream-cycle-2026-05-30-performance.mdnew file mode 100644index 0000000000..a5dd94f01a--- /dev/null+++ b/v3/docs/research/dream-cycle-2026-05-30-performance.md@@ -0,0 +1,64 @@+# Performance SOTA Report β 2026-05-30++**TL;DR:** Five Grade A 2026 papers converge on the same gap in Ruflo: critical-path-aware scheduling cuts multi-agent wall-clock latency 38β46% (LAMaS), MV-HNSW achieves 14Γ memory-search speedup vs Ruflo's current ~1.9Γ, and structured memory distillation compresses agent context 11Γ β none yet implemented.++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| LAMaS critical-path DAG scheduling reduces multi-agent wall-clock latency 38β46% | arXiv:2601.10560, Jan 2026 | A |+| MV-HNSW (multi-vector graph index) achieves 14Γ search-latency reduction vs prior methods at >90% recall across 7 datasets | arXiv:2604.02815, PVLDB 17(12) 2026 | A |+| Structured distillation compresses agent memory 11Γ (371β38 tokens/exchange) with retrieval MRR 0.759 vs 0.745 raw | arXiv:2603.13017, Mar 2026 | A |+| Hera step-level RL routing achieves 92.5% cloud-only accuracy at 46.3% cloud invocations (54% local offload) | arXiv:2605.24598, May 2026 | A |+| SSD/Saguaro (ICLR 2026) reaches 5Γ faster-than-autoregressive throughput via parallelised draft+verify stages | arXiv:2603.03251, ICLR 2026 | A |++## Ruflo Current Capability++| Area | Status | Gap |+|------|--------|-----|+| HNSW vector search | β ~1.9Γ at N=20k (measured) | MV-HNSW achieves 14Γ β 7Γ improvement available |+| 3-tier routing (ADR-026) | β Deterministic by complexity class | No step-level RL routing; 54% cloud offload opportunity untapped |+| SONA adaptation | β 0.0043ms/adapt (measured, ahead of all published comparators) | No step-state conditioning in routing decisions |+| Agent memory storage | AgentDB SQLite + HNSW | No structured distillation; full raw token cost per context window |+| MCP tool execution | Sequential default | No critical-path DAG scheduler β full serial penalty on parallel-capable tasks |+| Agent pipeline latency | Not benchmarked | No published TTFT-to-response metric at any agent count |++## Competitor Comparison++Source: Pooya Golchian independent benchmark, 200 tasks/tier, Qwen3-32B, Apr 2026. **Grade B** (single tester, consistent with multi-source review).++| Framework | Simple Task | Medium Task | Complex Task | Token Overhead | Key 2026 Highlight |+|-----------|------------|------------|-------------|---------------|-------------------|+| **Ruflo v3.6** | Not benchmarked | Not benchmarked | Not benchmarked | Not published | 3-tier routing (ADR-026), SONA 0.0043ms |+| **LangGraph v1.0 GA** | 88% | 76% | 62% | ~5% | DeltaChannel beta (incremental checkpoint diff); ~1.2s avg on 10-step GPT-4o pipelines |+| **AutoGen v0.4 / Magentic-One** | 79% | 68% | 58% | ~5β6Γ vs LangGraph on reasoning | Modular agentchat rewrite; better p99 latency on managed deploy |+| **CrewAI** | 79% | 71% | 54% | ~18% vs LangGraph | 100K+ devs; 31,200 GitHub stars; fastest prototyping |+| **OpenAI Swarm** | N/A | N/A | N/A | Near-zero (thin wrapper) | Reference implementation only; no state management; no published perf benchmarks |++## Benchmarks++| Benchmark | Value | Grade | Source |+|-----------|-------|-------|--------|+| LAMaS: critical path length reduction | 38β46% | A | arXiv:2601.10560 |+| MV-HNSW: search-latency reduction at >90% recall (7 datasets) | 14Γ | A | arXiv:2604.02815, PVLDB 2026 |+| Structured memory distillation: token compression | 11Γ (371β38 tok/exchange) | A | arXiv:2603.13017 |+| Hera step-level routing: cloud invocation reduction | 54% offload at 92.5% accuracy | A | arXiv:2605.24598 |+| SSD/Saguaro: throughput vs autoregressive | 5Γ | A | arXiv:2603.03251, ICLR 2026 |+| OpenRouter vs OpenAI direct TTFT | 70ms faster (0.640s vs 0.712s) | B | opper.ai LLM Router Benchmark 2026 |++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| **Session commit** | e6dc21fc79539af029c4f5e87d2b929ebb794291 |+| **Report SHA-256** | a08b0a9b60c7cf0fe6a8162a17a4379c9891a6e416c89ab9d90eb0ee389b6fc0 |+| **Witness stamp** | f412ad86592f290e0f38f59c26b08e2a26ba67683b95dc2c7770491b5f96b63b |+| **Verifier** | sha256 gist-pre-witness β concat session commit `e6dc21fc79539af029c4f5e87d2b929ebb794291` β sha256 β must equal witness stamp |++## Recommended Next Steps++1. **ADR-144: Upgrade to MV-HNSW for agent memory retrieval** β Current ~1.9Γ at N=20k vs 14Γ achievable. Target: `v3/@claude-flow/memory/src/hnsw/`. Evaluate at N=20kβ100k, targeting 90% recall threshold. (arXiv:2604.02815, PVLDB 2026)++2. **Implement structured memory distillation** β 11Γ token compression using four-field schema (core/detail/labels/paths). Retrieval MRR 0.759 vs 0.745 raw. Implementation-level β no ADR needed. (arXiv:2603.13017)++3. **Add step-level routing to 3-tier model router** β 40β50% Haiku offload at near-Sonnet accuracy via RL-trained binary classifier. Target: `v3/@claude-flow/cli/src/routing/model-router.ts`. (arXiv:2605.24598)diff --git a/v3/docs/research/dream-cycle-2026-05-31-security.md b/v3/docs/research/dream-cycle-2026-05-31-security.mdnew file mode 100644index 0000000000..13e38f1b50--- /dev/null+++ b/v3/docs/research/dream-cycle-2026-05-31-security.md@@ -0,0 +1,75 @@+# Security SOTA Report β 2026-05-31++**TL;DR:** Three Grade A papers published in the last 10 days define a new security layer Ruflo lacks β authorization propagation across agent delegation chains β distinct from the content-screening gap (ADR-131) filed five nights ago.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|-----------|+| 40.55% of 7,973 live MCP servers expose tools with zero authentication; 96.6% of OAuth-enabled servers contain β₯1 flaw | arXiv:2605.22333 | **A** |+| Runtime authority control (AIRGuard) reduces agent attack success 36.3% β 5.5% via least-privilege action-layer enforcement | arXiv:2605.28914 | **A** |+| Dual-graph provenance defense (execution graph vs authorization intent) reduces indirect prompt injection 40% β 1% | arXiv:2605.26497 | **A** |+| Authorization propagation across multi-agent delegation chains is not reducible to prompt injection; requires 7 structural requirements not covered by RBAC/ABAC | arXiv:2605.05440 | **A** |+| Single agents false-continue on infeasible tool tasks 73.9% of the time (intelligence scan) | arXiv:2605.28532 | **A** |+| Event-triggered swarm consensus reduces network overhead while maintaining β₯99% task completion under agent failures (swarm scan) | arXiv:2604.06813 | **A** |++---++## Ruflo Current Capability++| Control | Status | Gap |+|---------|--------|-----|+| Content-boundary injection screening | ADR-131 (Proposed) | Covers WHAT agents receive β not WHO they act as |+| MCP tool input validation | `SafeExecutor` + `InputValidator` | No auth verification on MCP server identity |+| Per-action privilege enforcement | Not implemented | No action β scope β allow/deny path |+| Delegation chain tracking in SendMessage | Not implemented | Messages carry no authorization scope |+| Execution provenance graph | Not implemented | No WHAT did vs WHAT was authorized audit trail |+| Feasibility pre-check before tool dispatch | Not implemented | 73.9% false-continue risk on single-agent paths |++---++## Competitor Comparison++| Framework | MCP Auth Checking | Per-Action Privilege | Authorization Propagation | Provenance Graph |+|-----------|------------------|---------------------|--------------------------|-----------------|+| **Ruflo v3.6** | Not implemented | Not implemented | Not implemented | Not implemented |+| **OpenAI Agents SDK** | Tool availability pre-check (March 2026) | Input + output + invocation guardrails | OAuth 2.0 token forwarding | OTEL spans built-in |+| **LangGraph v0.4** | Via LangSmith observability | Conditional edges + HITL checkpoints | Partial (checkpoint-scoped) | LangSmith full graph |+| **CrewAI Enterprise** | SOC 2 / HIPAA compliance | Role-scoped tool permissions | Partial (role inheritance) | Observability hooks |+| **AutoGen 1.0 GA** | Security patches; no MCP native | GroupChat-level only | Not published | Azure Monitor integration |++---++## Benchmarks++| Metric | Value | Source | Grade |+|--------|-------|--------|-------|+| Live MCP servers with zero auth (n=7,973) | 40.55% | arXiv:2605.22333 | **A** |+| OAuth-enabled MCP servers with β₯1 flaw | 96.6% | arXiv:2605.22333 | **A** |+| AIRGuard attack success reduction | 36.3% β 5.5% (β85%) | arXiv:2605.28914 | **A** |+| Dual-graph injection success reduction | 40% β 1% (β97.5%) | arXiv:2605.26497 | **A** |+| Single-agent infeasible-task false-continue rate | 73.9% | arXiv:2605.28532 | **A** |+| Event-triggered consensus task completion | β₯99% under single failure | arXiv:2604.06813 | **A** |++---++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| **Session commit** | `05bb9cf7ed1aa30313c42553ca7c49e7574af341` |+| **Report SHA-256** | `a7097af834cb47d04ec6c3a89b8698a90a003f82de746b82d78b6548abe24af2` |+| **Witness stamp** | `3e9b27fbe7f1bc645ce09a95dd015a325d2ecfb618ca2db7f49b25a4df8d08fe` |+| **Verifier** | `sha256sum dream-gist-2026-05-31.md` (pre-witness fill) β concat session commit `05bb9cf7ed1aa30313c42553ca7c49e7574af341` β `sha256sum` β must equal witness stamp |++---++## Recommended Next Steps++1. **Implement `AgentAuthorizationPropagator`** in `v3/@claude-flow/security/src/authorization/propagator.ts` β attach `scope` field to SendMessage envelope, validate each MCP tool call against the current delegation scope. ADR-144 (filed tonight) tracks this as an architectural decision.++2. **Add MCP server authentication validator** in `v3/@claude-flow/cli/src/mcp/auth-validator.ts` β before any tool response enters agent reasoning, verify the server presented valid credentials. Even a simple allowlist check eliminates the 40.55% unauthenticated-server risk for Ruflo-managed MCP registrations.++3. **Add feasibility pre-check to the `route` hook** β before Tier-3 dispatch, verify all required MCP tools are registered and callable. Eliminates the 73.9% false-continue rate at near-zero cost (simple registry lookup). Implementation-level β no ADR needed.diff --git a/v3/docs/research/dream-cycle-2026-06-01-security.md b/v3/docs/research/dream-cycle-2026-06-01-security.mdnew file mode 100644index 0000000000..2f67a8ae81--- /dev/null+++ b/v3/docs/research/dream-cycle-2026-06-01-security.md@@ -0,0 +1,107 @@+# Security SOTA Report β 2026-06-01++**TL;DR:** Payload-less plugin supply-chain attacks (Semantic Compliance Hijacking) achieve 77.67% confidentiality breach and 67.33% RCE with 0.00% scanner detection in 2026; Ruflo's IPFS plugin registry and shared AgentDB memory namespaces have zero supply-chain integrity controls β the highest-priority unfilled security gap in Ruflo as of June 2026.++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| Semantic Compliance Hijacking (SCH): payload-less attack, 77.67% confidentiality breach, 67.33% RCE, 0.00% scanner detection | arXiv:2605.14460, May 14, 2026 | A |+| DDIPE supply-chain attack: embeds malicious logic in plugin docs, 11.6β33.5% bypass, 2.5% evades all defenses | arXiv:2604.03081, Apr 3, 2026 | A |+| Memory poisoning (MINJA): 95% injection success idealized β 28β38% realistic; defeated by trust-scored sanitization | arXiv:2601.05504, Jan 9, 2026 | A |+| Plan injection (context manipulation): 3Γ higher ASR than prompt-based attacks; 17.7% exfiltration gain via context-chaining | arXiv:2506.17318, Jun 18, 2026 | A |+| Mnemonic Sovereignty: 9 governance primitives needed for memory security β zero existing architectures satisfy all 9 | arXiv:2604.16548, Apr 17, 2026 | A |+| Microsoft Agent Governance Toolkit: Ed25519 plugin signing + <0.1ms p99 policy enforcement, full OWASP ASI01βASI10 coverage | Microsoft OSS Blog, Apr 2, 2026 | B |+| OpenClaw study: current point-based defenses fail cross-temporal, multi-stage threat chains (5 lifecycle stages) | arXiv:2603.11619, Mar 12, 2026 | A |++## Ruflo Current Capability++| Area | Status |+|------|--------|+| Plugin registry integrity (IPFS/Pinata) | No signature verification, no semantic intent scanning |+| Memory namespace write authorization | No β all agents write unrestricted to shared namespaces |+| MCP tool output guardrail | ADR-131 proposed (branch not merged) |+| Authorization propagation | ADR-144 proposed (branch dream/2026-05-31-security, not merged) |+| OWASP ASI01 β Goal Hijacking | ADR-131 proposed only |+| OWASP ASI06 β Memory/Context Poisoning | Gap β no control |+| OWASP ASI09 β Supply Chain | Gap β no control |++## Deep Dive: Supply-Chain Attack Landscape++### Semantic Compliance Hijacking (SCH)++arXiv:2605.14460 introduces SCH as a qualitatively new threat class. Prior supply-chain attacks embed explicit malicious payloads (code, shell commands). SCH instead wraps malicious intent in natural-language "compliance rules" that appear to describe legitimate plugin behavior. The agent, upon reading these rules, generates the harmful code itself at runtime.++The implication for Ruflo's plugin store: static analysis and signature-based scanning cannot detect SCH. A plugin with a perfectly valid Ed25519 signature could still carry SCH content. Two-layer defense is required: signature verification (blocking DDIPE) AND semantic intent scanning (blocking SCH).++### Document-Driven Implicit Payload Execution (DDIPE)++arXiv:2604.03081 generated 1,070 adversarial skills from 81 seed skills covering all 15 MITRE ATT&CK categories. Key finding: agent skills execute with system-level privileges without mandatory security review in all four tested frameworks. Ruflo's `plugins install` path has no mandatory review gate.++### Memory Poisoning via MINJA++arXiv:2601.05504 shows that an attacker with query-only access (no code execution) can inject malicious instructions into an agent's memory store with 38% success for production-strength models. In Ruflo's shared `collaboration` namespace, a single compromised sub-agent (e.g., a `codex:coder` worker) can write poisoned instructions that persist for retrieval by future agents in the same namespace.++## Scan Findings β Intelligence++**Source:** arXiv:2603.07915, March 2026 (Grade A)++**Finding:** ARES (Adaptive Reasoning Effort Selection) trains a lightweight per-step router that dynamically selects the minimum necessary reasoning level for each agent step. Results: **52.7% reduction in reasoning token usage** while maintaining task success rates. This is complementary to SRΒ²AM (covered in #2156 May 27) β both reduce reasoning overhead but at different granularities (SRΒ²AM: planning frequency; ARES: per-step effort).++**Competitive signal (Grade B):** OpenAI Agents SDK v0.13 ships opt-in retry policies and session persistence, indicating the platform is optimizing for multi-step reliability β not token efficiency. Ruflo's 3-tier routing is cost-efficient but static; adding ARES-style per-step routing would compound with ADR-026's tier selection.++**Recommended action:** Prototype ARES-style effort router as an extension to the `route` hook's Tier-3 path. Implementation-level β no new ADR needed (enhancement to ADR-026 and ADR-131's simulative planning primitive).++## Scan Findings β Swarm++**Source:** arXiv:2602.08009, February 2026 (Grade A)++**Finding:** "Towards Adaptive, Scalable, and Robust Coordination of LLM Agents: A Dynamic Ad-Hoc Networking Perspective" proposes treating swarms as Dynamic Ad-Hoc Networks (DANETs) β agents self-organize topology in response to failures and load, rather than maintaining a fixed hierarchical structure. The paper shows that adaptive topology switching under failure reduces task latency by 31% compared to static hierarchical topology when β₯20% of agents fail simultaneously.++**Competitive signal (Grade B):** LangGraph v1.1.3 ships "distributed runtime support" (April 2026), allowing graph nodes to run across multiple machines. Ruflo's swarm topology is configured at init time β no adaptive reconfiguration under failure.++**Recommended action:** Evaluate DANET-style adaptive reconfiguration as an enhancement to ADR-132 (hierarchical consensus topology, proposed). Would allow graceful degradation from hierarchical to mesh under partial failure. Implementation-level β no new ADR needed.++## Competitors Reviewed++| Framework | Plugin Signing | Memory Governance | Supply-Chain Defense | OWASP ASI Coverage | Key 2026 Update |+|-----------|---------------|-------------------|---------------------|--------------------|----------------|+| **Ruflo v3.6** | None | None (shared namespaces) | None | ASI01 proposed only | ADR-131, ADR-144 proposed; unmerged |+| **Microsoft AGT** | Ed25519 per plugin | YAML/OPA/Cedar policy engine | Agent Marketplace package | Full β all ASI01βASI10 | Open-sourced Apr 2026, MIT license |+| **OpenAI Agents SDK v0.13** | Platform-signed | Platform-managed | Input/output guardrails | Best-in-class | any-LLM adapter + MCP resource support |+| **LangGraph v1.1.3** | No | Checkpoint-scoped | No | HITL checkpoints | Deep agent templates + distributed runtime |+| **CrewAI v1.12** | No (SOC2 audit trail) | Hierarchical memory isolation | No | SOC2 partial | Agent skills + native OpenAI-compatible providers |++## Benchmarks++| Metric | Value | Source | Grade |+|--------|-------|--------|-------|+| SCH confidentiality breach success rate | 77.67% | arXiv:2605.14460 | A |+| SCH Remote Code Execution success rate | 67.33% | arXiv:2605.14460 | A |+| SCH detection rate by current scanning tools | 0.00% | arXiv:2605.14460 | A |+| DDIPE bypass rate (best case) | 33.5% | arXiv:2604.03081 | A |+| DDIPE evasion of all detection + alignment | 2.5% | arXiv:2604.03081 | A |+| MINJA memory injection (idealized) | 95.0% | arXiv:2601.05504 | A |+| MINJA memory injection (realistic, GPT-4o-mini) | 38.0% | arXiv:2601.05504 | A |+| Plan injection ASR vs prompt-based | 3Γ | arXiv:2506.17318 | A |+| Plan injection exfiltration gain (context-chaining) | +17.7% | arXiv:2506.17318 | A |+| ARES reasoning token reduction | 52.7% | arXiv:2603.07915 | A |+| MS AGT policy enforcement latency | <0.1ms p99 | Microsoft OSS Blog | B |+| DANET adaptive topology latency improvement under 20% failure | 31% | arXiv:2602.08009 | A |++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| **Session commit** | `28eb57543be916abf5191f71114268a3985cb001` |+| **Report SHA-256** | `2d30798accfbd2eda6cfab79c8a3e2d74d84527fdb4d521a62c3f2c1fddf6fb0` |+| **Witness stamp** | `77d1b0fdc4cf98768ffa062a16a5efd1650c8a778a1d5ea6b1520ac7312628e3` |+| **Verifier** | `sha256sum dream-gist-2026-06-01.md` (pre-witness fill) β concat `28eb57543be916abf5191f71114268a3985cb001` β `sha256sum` β must equal witness stamp |++## Recommended Next Steps++1. **Implement PluginIntegrityVerifier** β Add Ed25519 signature verification to `v3/@claude-flow/cli/src/plugins/store/` and `discovery.ts`. Require all IPFS registry plugins to carry a signed manifest. This blocks DDIPE (embedded malicious logic in docs) at install time. ADR-145.++2. **Add semantic intent scanner at plugin install** β Static/signature analysis alone misses SCH (0.00% detection). Add `@claude-flow/security` NLP-based semantic intent validation during `plugins install` to detect compliance-rule-formatted malicious instructions that synthesize harmful behavior at runtime.++3. **Implement memory namespace write ACLs (Mnemonic Sovereignty)** β Agents should only write to namespaces explicitly granted at spawn time. Prevents memory poisoning propagation across agent boundaries. Target: `v3/@claude-flow/memory/src/namespaces/authorization.ts`. No existing system in 2026 literature satisfies all 9 governance primitives β differentiator opportunity.diff --git a/v3/docs/research/dream-cycle-2026-06-06-security.md b/v3/docs/research/dream-cycle-2026-06-06-security.mdnew file mode 100644index 0000000000..81df91c0cb--- /dev/null+++ b/v3/docs/research/dream-cycle-2026-06-06-security.md@@ -0,0 +1,99 @@+# Security SOTA Report β 2026-06-06++**TL;DR:** Memory write poisoning (4 attack channels, 9 structural flaws; arXiv:2606.04329) and 9.93% MCP description-code inconsistency (arXiv:2606.04769) are the 2026 agentic security frontier; Ruflo ADR-144/145/146 cover supply chain and output guardrails but leave memory integrity validation and inter-agent message signing unguarded.++---++## What's New in 2026++| Finding | Source | Confidence |+|---------|--------|------------|+| Memory write poisoning: 4 channels, 9 structural vulns; single write β long-term influence | arXiv:2606.04329 (Dash et al., Jun 2026) | **A** |+| MCP description-code mismatch in 9.93% of real-world MCP servers creates blind spots | arXiv:2606.04769 (Shi et al., Jun 2026) | **A** |+| Membrane contrastive safety memory: highest F1 across 6 jailbreak types, 7β14% benign refusal | arXiv:2606.05743 (Choi et al., Jun 2026) | **A** |+| OWASP Top 10 for Agentic Applications 2026 (ASI01βASI10) published, separate from LLM Top 10 | OWASP Gen AI Security Project, 2026 | **B** |+| WebMCP tool-surface poisoning: third-party scripts inject malicious tools at runtime | arXiv:2606.06387 (Lee et al., Jun 2026) | **A** |+| Voluntary agent recusal: 100% compliance with in-band access-deny signals vs. 0% without | arXiv:2606.06460 (Munirathinam, Jun 2026) | **A** |+| Adversarial feed curation flips agent decisions from 5% β 100% task compliance | arXiv:2606.00914 (Usman, Jun 2026) | **A** |++---++## Ruflo Current Capability++| Capability | Status | ADR |+|-----------|--------|-----|+| Agent authorization propagation | β Implemented | ADR-144 |+| Plugin supply chain integrity | β Implemented | ADR-145 |+| Tool output guardrail integration | β Implemented | ADR-146 |+| Memory write validation / integrity checks | β Not implemented | β |+| MCP description-code consistency verification | β Not implemented | β |+| Inter-agent message signing (ASI07) | β Not implemented | β |+| Agent goal monitoring / emergency shutdown (ASI10) | β Not implemented | β |+| Contrastive safety memory (Membrane-style) | β Not implemented | β |++---++## Competitor Comparison++| Framework | Authorization | Sandboxing | Inter-Agent Trust | Memory Security | Version |+|-----------|--------------|------------|------------------|-----------------|--------|+| **LangGraph** | Custom node logic (DIY) | None native | Graph-based conditional edges | None native | v0.4+ (May 2026) |+| **CrewAI** | Role-based per agent | None native | Role-driven task delegation | None native | v1.14+ |+| **AG2 (AutoGen)** | GroupChat manager | Docker container native | Manager-mediated conversation | None native | v0.12+ |+| **OpenAI Agents SDK** | Approval callbacks in harness | Sandbox execution (Apr 2026) | Sequential handoff + transfer validation | None documented | Apr 2026 |+| **Ruflo** | ADR-144 propagation | ADR-145 supply chain | Hive-mind Byzantine BFT | No memory integrity | 3.6.10 |++**Grade B β vendor claims cross-checked:** All five frameworks β including Ruflo β lack native memory integrity validation despite Memory & Context Poisoning being OWASP ASI06:2026. OpenAI Agents SDK leads on sandboxing; Ruflo leads on inter-agent consensus (Byzantine BFT) but has no Membrane-equivalent guardrail.++---++## Benchmarks++| Claim | Value | Source | Grade |+|-------|-------|--------|-------|+| Membrane: F1 on jailbreak defense | Highest across 6 attack types | arXiv:2606.05743 | **A** |+| Membrane: benign refusal rate | 7β14% | arXiv:2606.05743 | **A** |+| MCP description-code mismatch prevalence | 9.93% of real MCP servers | arXiv:2606.04769 | **A** |+| Memory poisoning attack surfaces | 4 write channels, 9 structural vulns | arXiv:2606.04329 | **A** |+| Agent recusal on in-band access-deny | 100% compliance | arXiv:2606.06460 | **A** |+| Adversarial feed compliance flip | 5% β 100% | arXiv:2606.00914 | **A** |++---++## Scan Findings: Intelligence (2026-06-06)++**Source:** arXiv:2606.05670 (Jun 2026) β "Do More Agents Help? Controlled Evaluation of LLM Agent Workflows"+**Finding (Grade A):** Under normalized conditions, most multi-agent systems underperform single-agent baselines by **2.56β11.29 percentage points** despite higher compute cost. Ruflo's multi-agent value must be justified by coordination quality, not headcount.++**Competitive signal:** Economy of Minds (arXiv:2606.02859) shows market-based self-organization of weak agents outperforms centralized coordination β contrasts with Ruflo's fixed-hierarchical queen topology.++---++## Scan Findings: Swarm (2026-06-06)++**Source:** arXiv:2605.10052 (May 2026) β "Swarm Skills: A Portable, Self-Evolving Multi-Agent System Specification"+**Finding (Grade A):** Portable, distributable multi-agent specs act as first-class assets enabling workflow distribution independent of runtime β Ruflo has no equivalent portable swarm-spec format.++**Competitive signal (Grade B):** LangGraph v0.4 (May 2026) adds per-node timeouts, error recovery, and graceful shutdown β Ruflo's swarm lacks per-agent circuit breakers (ADR-146 scope covers tool output only, not agent lifecycle).++---++## SOTA Proof & Witness++| Field | Value |+|-------|-------|+| Session commit | `d065b15927c6ba7318623e8af123e7980e4c6681` |+| Report SHA-256 (pre-stamp) | `8b409e9af5f38d7c322879601dfec049a344ecb45ee7a4241cb838b9015277fa` |+| Witness stamp | `5f5acdc81e2c3a13eed93e21b6d0689a59fea75498a77fa1bdeaeb0ff9acd054` |++**Verifier:** blank Witness section values β sha256sum file β concat session commit β sha256sum β must equal Witness stamp. (Pre-stamp hash per tamper-evident convention.)++---++## Recommended Next Steps++1. **Implement ASI06 Memory Integrity Validation (β ADR-147):** Add write-channel validation to AgentDB's 4 identified attack surfaces (direct injection, retrieval-augmented write, tool-write, agent-to-agent relay). Apply `InputValidator` at each channel boundary; add integrity checksums to the `vector_indexes` table. Estimated: 2 days.++2. **Add MCP Tool Description-Code Consistency Checker:** Extend `@claude-flow/security` to scan MCP server registrations at load time β flag tools where description semantics diverge from implementation. Target: detect β₯9.93% mismatch rate validated by arXiv:2606.04769 methodology.++3. **Implement Inter-Agent Message Signing (ASI07):** Add HMAC signatures to SendMessage payloads using `TokenGenerator`; verify in the hive-mind router before dispatch. Closes ASI07:2026 gap without requiring Byzantine BFT upgrade.diff --git a/v3/docs/research/dream-cycle-2026-07-05-performance.md b/v3/docs/research/dream-cycle-2026-07-05-performance.mdnew file mode 100644index 0000000000..4c36492f15--- /dev/null+++ b/v3/docs/research/dream-cycle-2026-07-05-performance.md@@ -0,0 +1,85 @@+# Performance SOTA Report β 2026-07-05++**TL;DR:** PolyKV (arXiv:2604.24971, Grade A) proves a shared asymmetrically-compressed KV pool slashes multi-agent memory by 97.7% at 15 concurrent agents β Ruflo has no cross-agent shared KV pool and this is the single highest-leverage performance gap for 2026.++---++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| PolyKV: shared KV pool (int8 keys + FWHT+3-bit Lloyd-Max values) cuts 15-agent memory 19.8 GB β 0.45 GB (97.7%), 2.91x compression, BERTScore F1 0.928 | arXiv:2604.24971 (Patel & Joshi, Apr 2026) | A |+| ConServe disaggregated prefill/decode scheduling reduces p95 TTFT by 51.08% and energy by 7.51% | arXiv Jun 2026 (Ding, Hosseini et al.) | A |+| AsymCache multi-segment KV eviction cuts TTFT 1.90β2.03x and TPOT 1.62β1.71x | arXiv Jun 2026 (Shi, Chen et al.) | A |+| IBM speculative decoding + FP8: 4.48x throughput speedup with maintained task performance | arXiv:2606.18502 (Dashore et al., IBM, Jun 2026) | B |+| CLSR symbolic inter-agent language: 3β6x fewer tokens in agent-to-agent messages vs chain-of-thought | arXiv Jun 2026 (Pei, Huang, Wang) | B |++---++## Ruflo Current Capability++| Capability | Current State | Gap |+|---|---|---|+| KV cache | Per-agent cache, referenced in CLAUDE.md | No cross-agent shared/compressed pool |+| Speculative decoding | Not mentioned in architecture | Absent; 4.48x throughput unrealized |+| Disaggregated scheduling | Not addressed | Absent; 51% p95 TTFT reduction unrealized |+| Inter-agent communication | SendMessage text protocol | No symbolic/compressed format; CLSR 3β6x savings unrealized |+| Vector search | HNSW (1.9xβ4.7x measured vs brute force) | Addressed; not performance gap |++---++## Competitor Comparison++| Framework | Key 2026 Performance Claim | Source | Grade |+|---|---|---|---|+| **LangGraph** | 10,155ms avg latency, 2.70 rps, 30β40% fewer tokens than CrewAI on medium tasks | dev.to benchmark 2026; AI Dev Day India | B |+| **AutoGen (AG2)** | ~56,700 tokens / 4-agent 5-round debate; 4β5x overhead vs LangChain on complex tasks; GA Feb 2026 | f3fundit.com; secondtalent.com 2026 | C |+| **CrewAI** | 43/100 token efficiency score; ~32s/run; 44% task failure rate in Rust framework benchmark | dev.to audit; aimultiple.com 2026 | C |+| **OpenAI Agents SDK** | "Fastest latency and highest token efficiency" in one enterprise benchmark; Swarm deprecated Mar 2026 | qubittool.com; selecthub.com 2026 | B |+| **Ruflo (claude-flow)** | HNSW 1.9xβ4.7x measured; SONA 0.0043ms/adapt | CLAUDE.md / benchmark-intelligence.mjs | A |++---++## Benchmarks++| Benchmark | Metric | Value | Grade |+|---|---|---|---|+| PolyKV β Llama-3-8B, 15 agents, 4K ctx | KV memory reduction | 19.8 GB β 0.45 GB (97.7%) | A |+| PolyKV | Compression ratio | 2.91x stable | A |+| PolyKV | Quality (BERTScore F1) | 0.928 (perplexity +0.57%) | A |+| ConServe | p95 TTFT reduction | 51.08% | A |+| ConServe | Energy efficiency gain | 7.51% | A |+| AsymCache | TTFT improvement | 1.90β2.03x | A |+| AsymCache | TPOT improvement | 1.62β1.71x | A |+| IBM Spec+FP8 | Throughput speedup | 4.48x | B |+| CLSR symbolic comms | Token count reduction | 3β6x | B |+| LangGraph | Task completion (Qwen3 32B, M4 Max) | 62% vs AutoGen 58%, CrewAI 54% | C (community benchmark) |++---++## Scan Findings++### Security (Grade A)+MESA (arXiv:2606.30602, Li et al., Jun 2026): a single compromised agent-to-agent communication edge accounts for up to **75% of total attack success** in multi-agent systems. AgentFlow (arXiv:2607.01640, Wang et al., Jul 2026) introduces static taint analysis via Agent Dependency Graphs covering MCP server pipelines. AI-Infra-Guard provides 75+ AI component rules and LLM-driven MCP server auditing. The 2025 OWASP LLM Top 10 "Excessive Agency" threat is now operationalized through supply-chain and memory-poisoning benchmarks. **Ruflo gap:** no static taint analysis or agent-to-agent channel integrity verification.++### Hive-Mind / Byzantine Consensus (Grade B)+arXiv:2602.02170 (Rodriguez & DΓaz, Feb 2026) evaluates six BFT protocols under f < n/3 and confirms bounded self-modification of coordination protocols is formally auditable. Broader collective-intelligence work for LLM hive-mind systems has not yet appeared at scale β the field is mapping BFT theory to practice. Ruflo's existing `byzantine-coordinator` and `raft-manager` are ahead of most published work.++---++## SOTA Proof & Witness++**Session commit:** a5f86ad0ada8aca3e8f664202a452714355990f5+**Report SHA-256:** 39545a8bb7283d10e370d3418584165101762c8550982e6cd069868c23181383+**Witness stamp:** 8c1959eec4d5b534b3d3c6030617c2bfe2c109520903ed435d6bdfdaa34ea90b+**Verification:** `cat dream-gist-2026-07-05.md | sha256sum` β concat with session commit β `sha256sum` β must equal witness stamp.++---++## Recommended Next Steps++1. **ADR-182: Cross-Agent Shared KV Pool (PolyKV architecture)** β Implement a shared asymmetrically-compressed KV pool using int8 key quantization and FWHT+Lloyd-Max value compression. Target: reduce 15-agent KV memory by β₯90% (from ~20 GB to <2 GB). Implementation path: extend `@claude-flow/memory` with a pool manager; measure vs current per-agent baseline. Priority: high β this is a Grade A finding with 97.7% measured reduction.++2. **Implement disaggregated prefill/decode scheduling (ConServe pattern)** β Add a serving-layer scheduler that separates prefill (prompt processing) from decode (token generation) across the agent pool. Expected: 50%+ p95 TTFT reduction. Implementation path: new `PerformanceScheduler` module in `@claude-flow/cli`; gate behind `CLAUDE_FLOW_SCHED_DISAGGREGATE=1` flag.++3. **Agent-to-agent channel security audit against MESA threat model** β Run AI-Infra-Guard's 75+ rules against Ruflo's MCP server pipelines and SendMessage pathways. A single compromised edge = 75% attack success. Immediate action: label all agent-to-agent edges as attack surface in `@claude-flow/security` threat model; add static taint gate to pre-task hook.