Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

feat: add 10 new ruflo plugins, optimize all 32, add READMEs and user guide

Reuvenf25bcf2073cd
diff --git a/plugins/README.md b/plugins/README.md
new file mode 100644
index 0000000000..4cf607a55d
--- /dev/null
+++ b/plugins/README.md
@@ -0,0 +1,121 @@
+# Ruflo Plugins
+
+32 Claude Code plugins for agent-powered development workflows. Load with `--plugin-dir`.
+
+## Quick Start
+
+```bash
+# Load specific plugins
+claude --plugin-dir plugins/ruflo-core --plugin-dir plugins/ruflo-swarm
+
+# Load all plugins
+claude $(ls -d plugins/ruflo-*/ | sed 's|^|--plugin-dir |' | tr '\n' ' ')
+```
+
+## Plugin Catalog
+
+### Core & Coordination
+
+| Plugin | Description |
+|--------|-------------|
+| [ruflo-core](ruflo-core/) | MCP server, status, doctor, coder/researcher/reviewer agents |
+| [ruflo-swarm](ruflo-swarm/) | Swarm topologies (hierarchical, mesh), Monitor streaming |
+| [ruflo-autopilot](ruflo-autopilot/) | Autonomous /loop task completion with prediction |
+| [ruflo-loop-workers](ruflo-loop-workers/) | 12 background workers via /loop or CronCreate |
+| [ruflo-workflows](ruflo-workflows/) | Workflow templates, parallel execution, branching |
+
+### Memory & Intelligence
+
+| Plugin | Description |
+|--------|-------------|
+| [ruflo-agentdb](ruflo-agentdb/) | AgentDB with HNSW vector search (150x-12,500x faster) |
+| [ruflo-rag-memory](ruflo-rag-memory/) | Simple store/search/recall memory |
+| [ruflo-rvf](ruflo-rvf/) | Portable RVF memory format, session persistence |
+| [ruflo-ruvector](ruflo-ruvector/) | ONNX embeddings, HNSW indexing, hyperbolic reasoning, clustering |
+| [ruflo-knowledge-graph](ruflo-knowledge-graph/) | Entity extraction, relation mapping, pathfinder traversal |
+| [ruflo-intelligence](ruflo-intelligence/) | SONA neural patterns, trajectory learning, model routing |
+| [ruflo-daa](ruflo-daa/) | Dynamic Agentic Architecture, cognitive patterns |
+
+### Architecture & Methodology
+
+| Plugin | Description |
+|--------|-------------|
+| [ruflo-adr](ruflo-adr/) | ADR lifecycle — create, index, supersede, compliance checking |
+| [ruflo-ddd](ruflo-ddd/) | DDD scaffolding — bounded contexts, aggregates, domain events |
+| [ruflo-sparc](ruflo-sparc/) | SPARC methodology with 5 phases and quality gates |
+
+### Quality & Security
+
+| Plugin | Description |
+|--------|-------------|
+| [ruflo-security-audit](ruflo-security-audit/) | CVE scanning, dependency vulnerability checks |
+| [ruflo-aidefence](ruflo-aidefence/) | Prompt injection detection, PII scanning |
+| [ruflo-testgen](ruflo-testgen/) | Test gap detection, TDD London School workflow |
+| [ruflo-browser](ruflo-browser/) | Playwright browser automation and testing |
+
+### Development Tools
+
+| Plugin | Description |
+|--------|-------------|
+| [ruflo-jujutsu](ruflo-jujutsu/) | Diff analysis, risk scoring, reviewer recommendations |
+| [ruflo-docs](ruflo-docs/) | Doc generation, drift detection, API docs |
+| [ruflo-ruvllm](ruflo-ruvllm/) | Local LLM inference, MicroLoRA, chat formatting |
+| [ruflo-wasm](ruflo-wasm/) | WASM agent sandboxing and gallery |
+| [ruflo-plugin-creator](ruflo-plugin-creator/) | Scaffold and validate new plugins |
+| [ruflo-migrations](ruflo-migrations/) | Database schema migration management |
+| [ruflo-observability](ruflo-observability/) | Structured logging, tracing, metrics correlation |
+| [ruflo-cost-tracker](ruflo-cost-tracker/) | Token usage tracking, budget alerts, cost optimization |
+
+### Domain-Specific
+
+| Plugin | Description |
+|--------|-------------|
+| [ruflo-goals](ruflo-goals/) | GOAP planning, deep research, horizon tracking |
+| [ruflo-federation](ruflo-federation/) | Zero-trust cross-installation agent federation |
+| [ruflo-iot-cognitum](ruflo-iot-cognitum/) | Cognitum Seed IoT — trust scoring, anomaly detection, fleet management |
+| [ruflo-neural-trader](ruflo-neural-trader/) | Neural trading strategies, backtesting, portfolio optimization |
+| [ruflo-market-data](ruflo-market-data/) | Market data ingestion, OHLCV vectorization, pattern matching |
+
+## Recommended Stacks
+
+| Use Case | Plugins |
+|----------|---------|
+| Feature development | `ruflo-core` + `ruflo-swarm` + `ruflo-testgen` + `ruflo-ddd` |
+| Security audit | `ruflo-core` + `ruflo-security-audit` + `ruflo-aidefence` |
+| Architecture work | `ruflo-core` + `ruflo-adr` + `ruflo-ddd` + `ruflo-sparc` |
+| Deep research | `ruflo-core` + `ruflo-goals` + `ruflo-rag-memory` + `ruflo-intelligence` |
+| IoT development | `ruflo-core` + `ruflo-iot-cognitum` + `ruflo-agentdb` |
+| Trading systems | `ruflo-core` + `ruflo-neural-trader` + `ruflo-market-data` + `ruflo-ruvector` |
+| Full stack | All 32 plugins |
+
+## Plugin Structure
+
+Each plugin follows the Claude Code plugin specification:
+
+```
+ruflo-<name>/
+ .claude-plugin/plugin.json # Plugin manifest
+ agents/<name>.md # Agent definitions (frontmatter: name, description, model)
+ commands/<name>.md # CLI command mappings
+ skills/<name>/SKILL.md # Interactive skills (frontmatter: name, description, argument-hint, allowed-tools)
+ README.md # Plugin documentation (optional)
+```
+
+## Creating a Plugin
+
+```bash
+claude --plugin-dir plugins/ruflo-plugin-creator
+# Then: /create-plugin my-new-plugin
+```
+
+Or manually: copy any existing plugin directory and modify.
+
+## Validation
+
+```bash
+claude plugin validate plugins/ruflo-<name>
+```
+
+## License
+
+MIT
diff --git a/plugins/ruflo-adr/.claude-plugin/plugin.json b/plugins/ruflo-adr/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..8bdbf6209b
--- /dev/null
+++ b/plugins/ruflo-adr/.claude-plugin/plugin.json
@@ -0,0 +1,9 @@
+{
+ "name": "ruflo-adr",
+ "description": "ADR lifecycle management — create, index, supersede, and link Architecture Decision Records to code",
+ "version": "0.1.0",
+ "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": ["ruflo", "adr", "architecture", "decisions", "documentation"]
+}
diff --git a/plugins/ruflo-adr/README.md b/plugins/ruflo-adr/README.md
new file mode 100644
index 0000000000..3c9cb37b01
--- /dev/null
+++ b/plugins/ruflo-adr/README.md
@@ -0,0 +1,61 @@
+# ruflo-adr
+
+ADR lifecycle management -- create, index, supersede, and link Architecture Decision Records to code.
+
+## Overview
+
+Manages Architecture Decision Records through their full lifecycle (proposed, accepted, deprecated, superseded). ADRs are stored as markdown files in `docs/adr/` and indexed in AgentDB with causal edges tracking supersedes/amends/depends-on relationships. Includes compliance checking that scans git diffs for ADR violations.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-adr
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `adr-architect` | sonnet | ADR lifecycle management, code-ADR linking via grep/blame, AgentDB graph storage |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `adr-create` | `/adr-create <title>` | Create a new ADR with sequential numbering and AgentDB registration |
+| `adr-index` | `/adr-index` | Build or rebuild the ADR index and dependency graph in AgentDB |
+| `adr-review` | `/adr-review [--branch BRANCH]` | Review code changes against accepted ADRs for compliance violations |
+
+## Commands (7 subcommands)
+
+```bash
+# Lifecycle
+adr create <title>
+adr list
+adr status <adr-id> <new-status>
+adr supersede <old-id> <new-id>
+
+# Compliance
+adr check # Scan recent git changes for ADR violations
+adr graph # Show ADR dependency graph
+adr search <query> # Semantic search across ADRs
+```
+
+## ADR Lifecycle
+
+```
+proposed --> accepted --> deprecated
+ \--> superseded by ADR-XXX
+```
+
+Relationships tracked as causal edges: `supersedes`, `amends`, `depends-on`, `related`.
+
+## Related Plugins
+
+- `ruflo-ddd` -- Document domain decisions as ADRs
+- `ruflo-sparc` -- Architecture phase (Phase 3) produces ADRs
+- `ruflo-migrations` -- Schema change decisions recorded as ADRs
+
+## License
+
+MIT
diff --git a/plugins/ruflo-adr/agents/adr-architect.md b/plugins/ruflo-adr/agents/adr-architect.md
new file mode 100644
index 0000000000..c850d57451
--- /dev/null
+++ b/plugins/ruflo-adr/agents/adr-architect.md
@@ -0,0 +1,96 @@
+---
+name: adr-architect
+description: ADR lifecycle manager -- create, index, supersede, and link Architecture Decision Records to code
+model: sonnet
+---
+
+You are an Architecture Decision Record specialist. Your responsibilities:
+
+1. **Create** new ADRs with sequential numbering (ADR-001, ADR-002...) in `docs/adr/`
+2. **Maintain** the ADR lifecycle: proposed -> accepted -> deprecated -> superseded
+3. **Link ADRs to code** via grep/git blame -- detect when code changes violate accepted ADRs
+4. **Track relationships** between ADRs (supersedes, amends, depends-on)
+
+### ADR Template
+
+Every ADR follows this structure:
+
+```markdown
+# ADR-NNN: <Title>
+
+- **Status**: proposed | accepted | deprecated | superseded by [ADR-XXX]
+- **Date**: YYYY-MM-DD
+- **Deciders**: <list of people>
+- **Tags**: <comma-separated tags>
+
+## Context
+
+<What is the issue that we're seeing that motivates this decision?>
+
+## Decision
+
+<What is the change that we're proposing and/or doing?>
+
+## Consequences
+
+### Positive
+- <good outcomes>
+
+### Negative
+- <trade-offs and costs>
+
+### Neutral
+- <other effects>
+
+## Links
+- Supersedes: ADR-XXX (if applicable)
+- Amended by: ADR-YYY (if applicable)
+- Related: ADR-ZZZ
+```
+
+### AgentDB Graph Storage
+
+Store the ADR dependency graph using AgentDB:
+
+- **Hierarchical store** for the ADR tree:
+ `mcp__claude-flow__agentdb_hierarchical-store` with path `adr/<adr-id>` and the ADR metadata as value
+- **Causal edges** for supersedes/amends relationships:
+ `mcp__claude-flow__agentdb_causal-edge` with `from: <old-adr-id>`, `to: <new-adr-id>`, `relation: supersedes|amends|depends-on`
+
+### Code-ADR Linking
+
+Detect ADR violations by:
+1. `Grep` for ADR references in code comments (e.g., `// ADR-042`, `# See ADR-042`)
+2. `git blame` to find when ADR-referenced code was last changed
+3. Compare change date against ADR status -- flag if code changed after ADR was accepted but ADR was not updated
+4. Report violations with file paths, line numbers, and the relevant ADR
+
+### Cross-References
+
+- **ruflo-jujutsu**: Use diff analysis on PRs to check ADR compliance before merge
+- **ruflo-docs**: Trigger doc generation when ADRs change status
+
+### Tools
+
+- `mcp__claude-flow__agentdb_hierarchical-store`, `mcp__claude-flow__agentdb_hierarchical-query` -- ADR tree storage
+- `mcp__claude-flow__agentdb_causal-edge`, `mcp__claude-flow__agentdb_causal-query` -- relationship tracking
+- `mcp__claude-flow__memory_store`, `mcp__claude-flow__memory_search` -- semantic search
+- `Read`, `Write`, `Edit` -- ADR file operations
+- `Grep`, `Glob` -- code scanning
+- `Bash` -- git operations (blame, log, diff)
+
+### Memory Learning
+
+Store ADR patterns and architectural decisions for cross-project learning:
+```bash
+npx @claude-flow/cli@latest memory store --namespace adr-patterns --key "decision-CATEGORY" --value "CONTEXT_AND_OUTCOME"
+npx @claude-flow/cli@latest memory search --query "architectural decision" --namespace adr-patterns
+```
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "ADR lifecycle patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-adr/commands/adr.md b/plugins/ruflo-adr/commands/adr.md
new file mode 100644
index 0000000000..e7ba87ba32
--- /dev/null
+++ b/plugins/ruflo-adr/commands/adr.md
@@ -0,0 +1,46 @@
+---
+name: adr
+description: Architecture Decision Record lifecycle management
+---
+$ARGUMENTS
+
+Manage Architecture Decision Records. Parse $ARGUMENTS to determine the subcommand:
+
+### Subcommands
+
+**`adr create <title>`** -- Create a new ADR with the next sequential number.
+1. Scan `docs/adr/` for existing ADRs to determine the next number
+2. Create `docs/adr/ADR-NNN-<slug>.md` from the standard template
+3. Store in AgentDB: `mcp__claude-flow__agentdb_hierarchical-store` at path `adr/ADR-NNN`
+4. Report the created file path and ADR number
+
+**`adr list`** -- List all ADRs with their status.
+1. `Glob` for `docs/adr/ADR-*.md`
+2. `Read` each file's frontmatter/header to extract status
+3. Present a table: Number | Title | Status | Date
+
+**`adr status <adr-id> <new-status>`** -- Update an ADR's status.
+1. Find the ADR file matching `<adr-id>` (e.g., ADR-042 or just 042)
+2. Update the Status line to the new value (proposed, accepted, deprecated, superseded)
+3. Update AgentDB entry
+
+**`adr supersede <old-id> <new-id>`** -- Mark an ADR as superseded by another.
+1. Update `<old-id>` status to "superseded by [ADR-<new-id>]"
+2. Add "Supersedes: ADR-<old-id>" link in `<new-id>`
+3. Create causal edge: `mcp__claude-flow__agentdb_causal-edge` from old to new with relation "supersedes"
+
+**`adr check`** -- Scan recent git changes for ADR violations.
+1. Run `git log --oneline -20` to get recent commits
+2. `git diff HEAD~20..HEAD --name-only` to get changed files
+3. `Grep` those files for ADR references (`ADR-\d+`)
+4. For each referenced ADR, check if it is still "accepted"
+5. Flag violations: code referencing deprecated/superseded ADRs, or code that contradicts accepted ADRs
+
+**`adr graph`** -- Show ADR dependency graph.
+1. Query `mcp__claude-flow__agentdb_causal-query` for all ADR relationships
+2. Present the graph as an ASCII tree or indented list showing supersedes/amends/depends-on chains
+
+**`adr search <query>`** -- Semantic search across ADRs.
+1. Call `mcp__claude-flow__memory_search` with the query in namespace `adr-patterns`
+2. Also `Grep` ADR files for keyword matches
+3. Present ranked results with ADR number, title, relevance, and excerpt
diff --git a/plugins/ruflo-adr/skills/adr-create/SKILL.md b/plugins/ruflo-adr/skills/adr-create/SKILL.md
new file mode 100644
index 0000000000..600591a467
--- /dev/null
+++ b/plugins/ruflo-adr/skills/adr-create/SKILL.md
@@ -0,0 +1,61 @@
+---
+name: adr-create
+description: Create a new Architecture Decision Record with sequential numbering and AgentDB registration
+argument-hint: "<title>"
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__agentdb_hierarchical-query mcp__claude-flow__agentdb_causal-edge mcp__claude-flow__memory_store mcp__claude-flow__memory_search Bash Read Write Edit Grep Glob
+---
+
+# Create ADR
+
+Create a new Architecture Decision Record with the next sequential number, register it in the AgentDB graph, and link it to related ADRs.
+
+## When to use
+
+When a significant architectural decision needs to be recorded -- new technology adoption, API design choices, data model changes, infrastructure decisions, or any cross-cutting concern that affects multiple components.
+
+## Steps
+
+1. **Find next number** -- `Glob` for `docs/adr/ADR-*.md` and parse existing numbers to determine the next sequential ID (ADR-001, ADR-002, etc.). Create `docs/adr/` if it does not exist.
+
+2. **Slugify title** -- Convert the title argument to a lowercase, hyphen-separated slug (e.g., "Use PostgreSQL for persistence" becomes `use-postgresql-for-persistence`).
+
+3. **Create ADR file** -- `Write` the file at `docs/adr/ADR-NNN-<slug>.md` using the standard template:
+ ```markdown
+ # ADR-NNN: <Title>
+
+ - **Status**: proposed
+ - **Date**: <today's date YYYY-MM-DD>
+ - **Deciders**: <leave blank for author to fill>
+ - **Tags**: <leave blank>
+
+ ## Context
+
+ <!-- What is the issue that motivates this decision? -->
+
+ ## Decision
+
+ <!-- What is the change that we are proposing? -->
+
+ ## Consequences
+
+ ### Positive
+ -
+
+ ### Negative
+ -
+
+ ### Neutral
+ -
+
+ ## Links
+ ```
+
+4. **Store in AgentDB** -- Call `mcp__claude-flow__agentdb_hierarchical-store` with:
+ - path: `adr/ADR-NNN`
+ - value: `{ "id": "ADR-NNN", "title": "<title>", "status": "proposed", "date": "<today>", "file": "docs/adr/ADR-NNN-<slug>.md" }`
+
+5. **Find related ADRs** -- Call `mcp__claude-flow__memory_search` with the title as query in namespace `adr-patterns` to find related decisions. If matches found, add them to the Links section and create causal edges with relation `depends-on`.
+
+6. **Store pattern** -- Call `mcp__claude-flow__memory_store` in namespace `adr-patterns` with key `ADR-NNN` and the title + context as value for future semantic search.
+
+7. **Report** -- Output the created file path, ADR number, and any related ADRs found.
diff --git a/plugins/ruflo-adr/skills/adr-index/SKILL.md b/plugins/ruflo-adr/skills/adr-index/SKILL.md
new file mode 100644
index 0000000000..c10553d5d8
--- /dev/null
+++ b/plugins/ruflo-adr/skills/adr-index/SKILL.md
@@ -0,0 +1,66 @@
+---
+name: adr-index
+description: Build or rebuild the ADR index and dependency graph in AgentDB
+argument-hint: ""
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__agentdb_hierarchical-query mcp__claude-flow__agentdb_causal-edge mcp__claude-flow__agentdb_causal-query mcp__claude-flow__memory_store mcp__claude-flow__memory_search Bash Read Grep Glob
+---
+
+# ADR Index
+
+Build or rebuild the full ADR index and dependency graph in AgentDB from the `docs/adr/` directory.
+
+## When to use
+
+After importing ADRs from another project, when the AgentDB graph is out of sync, or when bootstrapping ADR tracking on an existing codebase that already has ADR files.
+
+## Steps
+
+1. **Scan directory** -- `Glob` for `docs/adr/ADR-*.md` to find all ADR files. If no files found, report that no ADRs exist yet.
+
+2. **Parse each ADR** -- `Read` each file and extract:
+ - **ID**: from the filename (e.g., `ADR-042` from `ADR-042-use-postgres.md`)
+ - **Title**: from the `# ADR-NNN: <Title>` heading
+ - **Status**: from the `**Status**:` line
+ - **Date**: from the `**Date**:` line
+ - **Tags**: from the `**Tags**:` line
+ - **Links**: from the `## Links` section (supersedes, amended-by, related)
+
+3. **Store in AgentDB** -- For each ADR, call `mcp__claude-flow__agentdb_hierarchical-store` with:
+ - path: `adr/<adr-id>`
+ - value: `{ "id": "<id>", "title": "<title>", "status": "<status>", "date": "<date>", "tags": "<tags>", "file": "<filepath>" }`
+
+4. **Build causal edges** -- For each ADR with links:
+ - "Supersedes ADR-XXX" -> `mcp__claude-flow__agentdb_causal-edge` with `from: ADR-XXX`, `to: <current>`, `relation: supersedes`
+ - "Amended by ADR-YYY" -> `mcp__claude-flow__agentdb_causal-edge` with `from: <current>`, `to: ADR-YYY`, `relation: amends`
+ - "Related: ADR-ZZZ" -> `mcp__claude-flow__agentdb_causal-edge` with `from: <current>`, `to: ADR-ZZZ`, `relation: related`
+ - "Depends on ADR-WWW" -> `mcp__claude-flow__agentdb_causal-edge` with `from: <current>`, `to: ADR-WWW`, `relation: depends-on`
+
+5. **Store in memory** -- For each ADR, call `mcp__claude-flow__memory_store` with:
+ - namespace: `adr-patterns`
+ - key: `<adr-id>`
+ - value: `<title> — <first paragraph of Context section>`
+ This enables semantic search across ADRs.
+
+6. **Verify graph** -- Call `mcp__claude-flow__agentdb_causal-query` to retrieve all edges and verify:
+ - No dangling references (edges pointing to non-existent ADRs)
+ - No circular supersedes chains
+ - All superseded ADRs have status "superseded"
+
+7. **Report** -- Output a summary:
+ ```
+ ## ADR Index Summary
+
+ Total ADRs: N
+ - Proposed: X
+ - Accepted: Y
+ - Deprecated: Z
+ - Superseded: W
+
+ Relationships: M edges
+ - Supersedes: A
+ - Amends: B
+ - Depends-on: C
+ - Related: D
+
+ Issues found: (list any dangling refs or status mismatches)
+ ```
diff --git a/plugins/ruflo-adr/skills/adr-review/SKILL.md b/plugins/ruflo-adr/skills/adr-review/SKILL.md
new file mode 100644
index 0000000000..682b9adbab
--- /dev/null
+++ b/plugins/ruflo-adr/skills/adr-review/SKILL.md
@@ -0,0 +1,55 @@
+---
+name: adr-review
+description: Review code changes against accepted ADRs for compliance violations
+argument-hint: "[--branch BRANCH]"
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-query mcp__claude-flow__agentdb_causal-query mcp__claude-flow__memory_search Bash Read Grep Glob
+---
+
+# ADR Review
+
+Review code changes against accepted Architecture Decision Records to detect violations, drift, and non-compliance.
+
+## When to use
+
+Before merging a PR, after significant code changes, or as part of a periodic compliance check. Use this to ensure code changes respect the architectural decisions the team has agreed upon.
+
+## Steps
+
+1. **Get diff** -- Run `git diff main...HEAD --name-only` (or the specified branch) to list changed files. Then run `git diff main...HEAD` to get the full diff content.
+
+2. **Find relevant ADRs** -- For each changed file:
+ - `Grep` the file for ADR references (`ADR-\d+`)
+ - `Grep` `docs/adr/` for ADRs that mention the changed file paths or modules
+ - Call `mcp__claude-flow__memory_search` with the file path and change summary to find semantically related ADRs
+
+3. **Load ADR content** -- `Read` each relevant ADR file. Focus on:
+ - The **Decision** section (what was decided)
+ - The **Status** (only enforce "accepted" ADRs)
+ - The **Consequences** (expected constraints)
+
+4. **Check for violations** -- Analyze each changed file against its relevant ADRs:
+ - Does the code change contradict an accepted decision?
+ - Does it use a technology/pattern that an ADR explicitly rejected?
+ - Does it modify a module in a way the ADR's consequences warned against?
+ - Is the code referencing a deprecated or superseded ADR?
+
+5. **Query relationship graph** -- Call `mcp__claude-flow__agentdb_causal-query` to check if any referenced ADRs have been superseded. If so, flag that the code references an outdated decision.
+
+6. **Report** -- Present findings as a compliance report:
+ ```
+ ## ADR Compliance Report
+
+ ### Violations
+ - [ ] <file>:<line> — violates ADR-NNN: <reason>
+
+ ### Warnings
+ - [!] <file> references superseded ADR-NNN (replaced by ADR-MMM)
+
+ ### Compliant
+ - [x] <file> — consistent with ADR-NNN
+
+ ### Unlinked Changes
+ - [?] <file> — no ADR coverage (consider creating one)
+ ```
+
+7. **Suggest actions** -- For each violation, suggest whether to update the code or propose a new ADR to supersede the violated one.
diff --git a/plugins/ruflo-agentdb/agents/agentdb-specialist.md b/plugins/ruflo-agentdb/agents/agentdb-specialist.md
index cc0e373db6..e0a26ed6ac 100644
--- a/plugins/ruflo-agentdb/agents/agentdb-specialist.md
+++ b/plugins/ruflo-agentdb/agents/agentdb-specialist.md
@@ -3,7 +3,6 @@ name: agentdb-specialist
description: AgentDB and RuVector specialist for memory operations, HNSW indexing, and semantic search
model: sonnet
---
-
You are an AgentDB specialist for the Ruflo memory system. Your responsibilities:
1. **Manage AgentDB** sessions, controllers, and knowledge storage
@@ -13,10 +12,38 @@ You are an AgentDB specialist for the Ruflo memory system. Your responsibilities
5. **Causal graphs** linking related knowledge with causal edges
6. **Consolidate memory** to prevent bloat and maintain quality
-Use these MCP tools:
-- `mcp__claude-flow__agentdb_*` for all 19 AgentDB controllers
-- `mcp__claude-flow__embeddings_*` for vector operations
-- `mcp__claude-flow__ruvllm_hnsw_*` for HNSW index management
-- `mcp__claude-flow__memory_search_unified` for cross-namespace search
+### MCP Tools (19 Controllers)
+
+| Tool Prefix | Operations |
+|-------------|-----------|
+| `mcp__claude-flow__agentdb_semantic-route` | Route queries to best knowledge source |
+| `mcp__claude-flow__agentdb_hierarchical-*` | Store/recall structured hierarchical data |
+| `mcp__claude-flow__agentdb_pattern-*` | Store/search learned patterns |
+| `mcp__claude-flow__agentdb_causal-edge` | Link related knowledge causally |
+| `mcp__claude-flow__agentdb_context-synthesize` | Synthesize context from multiple sources |
+| `mcp__claude-flow__agentdb_batch` | Bulk operations |
+| `mcp__claude-flow__agentdb_consolidate` | Clean up and deduplicate |
+| `mcp__claude-flow__agentdb_feedback` | Record quality feedback |
+| `mcp__claude-flow__embeddings_*` | Vector embedding generation and search |
+| `mcp__claude-flow__ruvllm_hnsw_*` | HNSW index create/add/route |
+| `mcp__claude-flow__memory_search_unified` | Cross-namespace semantic search |
+
+### Decision Guide
+
+- **Structured data** → hierarchical store/recall
+- **Unstructured queries** → semantic routing
+- **Pattern matching** → pattern store/search
+- **Cross-session** → session start/end with persistence
+- **Quick key-value** → use ruflo-rag-memory instead
+
+### Related Plugins
+
+- **ruflo-rag-memory**: Simple store/search/recall interface — use for quick key-value memory when full AgentDB isn't needed
+- **ruflo-intelligence**: SONA neural patterns use AgentDB for pattern storage and HNSW retrieval
+
+### Neural Learning
-Prefer hierarchical storage for structured data and semantic routing for unstructured queries.
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+```
diff --git a/plugins/ruflo-agentdb/skills/agentdb-query/SKILL.md b/plugins/ruflo-agentdb/skills/agentdb-query/SKILL.md
index 34bd5f0dfc..f565613c84 100644
--- a/plugins/ruflo-agentdb/skills/agentdb-query/SKILL.md
+++ b/plugins/ruflo-agentdb/skills/agentdb-query/SKILL.md
@@ -1,6 +1,7 @@
---
name: agentdb-query
description: Query AgentDB with semantic routing, hierarchical recall, causal graphs, and context synthesis
+argument-hint: "<query>"
allowed-tools: mcp__claude-flow__agentdb_semantic-route mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__agentdb_context-synthesize mcp__claude-flow__agentdb_causal-edge mcp__claude-flow__agentdb_pattern-search mcp__claude-flow__agentdb_pattern-store mcp__claude-flow__agentdb_controllers mcp__claude-flow__agentdb_health mcp__claude-flow__agentdb_batch mcp__claude-flow__agentdb_feedback mcp__claude-flow__agentdb_consolidate mcp__claude-flow__agentdb_session-start mcp__claude-flow__agentdb_session-end Bash
---
diff --git a/plugins/ruflo-agentdb/skills/vector-search/SKILL.md b/plugins/ruflo-agentdb/skills/vector-search/SKILL.md
index 24c95543d9..bbbdaec46e 100644
--- a/plugins/ruflo-agentdb/skills/vector-search/SKILL.md
+++ b/plugins/ruflo-agentdb/skills/vector-search/SKILL.md
@@ -1,6 +1,7 @@
---
name: vector-search
description: HNSW vector search with RuVector embeddings for 150x-12500x faster semantic retrieval
+argument-hint: "<query> [--limit N]"
allowed-tools: mcp__claude-flow__embeddings_generate mcp__claude-flow__embeddings_search mcp__claude-flow__embeddings_compare mcp__claude-flow__embeddings_init mcp__claude-flow__embeddings_status mcp__claude-flow__embeddings_hyperbolic mcp__claude-flow__embeddings_neural mcp__claude-flow__ruvllm_hnsw_create mcp__claude-flow__ruvllm_hnsw_add mcp__claude-flow__ruvllm_hnsw_route mcp__claude-flow__memory_search_unified Bash
---
diff --git a/plugins/ruflo-aidefence/agents/safety-specialist.md b/plugins/ruflo-aidefence/agents/safety-specialist.md
index 59b29e7b76..9444fdd61f 100644
--- a/plugins/ruflo-aidefence/agents/safety-specialist.md
+++ b/plugins/ruflo-aidefence/agents/safety-specialist.md
@@ -19,3 +19,25 @@ Use these MCP tools:
- `mcp__claude-flow__aidefence_stats` for metrics
Always err on the side of caution — flag uncertain content for human review.
+
+### Memory Learning
+
+Store detected threat patterns for cross-session learning:
+```bash
+npx @claude-flow/cli@latest memory store --namespace security-patterns --key "threat-TYPE" --value "PATTERN_DATA"
+npx @claude-flow/cli@latest memory search --query "similar threats" --namespace security-patterns
+```
+
+### Related Plugins
+
+- **ruflo-security-audit**: CVE scanning and dependency vulnerability checks — complements AI safety scanning
+- **ruflo-federation**: Zero-trust federation security for multi-installation coordination
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-aidefence/skills/pii-detect/SKILL.md b/plugins/ruflo-aidefence/skills/pii-detect/SKILL.md
index bee454ea72..3f7acc9bec 100644
--- a/plugins/ruflo-aidefence/skills/pii-detect/SKILL.md
+++ b/plugins/ruflo-aidefence/skills/pii-detect/SKILL.md
@@ -1,6 +1,7 @@
---
name: pii-detect
description: Detect and flag personally identifiable information (PII) in text, code, and configurations
+argument-hint: "<input-text>"
allowed-tools: mcp__claude-flow__aidefence_has_pii mcp__claude-flow__aidefence_scan mcp__claude-flow__aidefence_analyze mcp__claude-flow__transfer_detect-pii Bash
---
diff --git a/plugins/ruflo-aidefence/skills/safety-scan/SKILL.md b/plugins/ruflo-aidefence/skills/safety-scan/SKILL.md
index da73bcc94b..736c3bc582 100644
--- a/plugins/ruflo-aidefence/skills/safety-scan/SKILL.md
+++ b/plugins/ruflo-aidefence/skills/safety-scan/SKILL.md
@@ -1,6 +1,7 @@
---
name: safety-scan
description: Scan inputs for prompt injection, unsafe content, and adversarial attacks using AIDefence
+argument-hint: "<input-text>"
allowed-tools: mcp__claude-flow__aidefence_scan mcp__claude-flow__aidefence_analyze mcp__claude-flow__aidefence_is_safe mcp__claude-flow__aidefence_learn mcp__claude-flow__aidefence_stats Bash
---
diff --git a/plugins/ruflo-autopilot/agents/autopilot-coordinator.md b/plugins/ruflo-autopilot/agents/autopilot-coordinator.md
index f0f4b53c7a..1332e2ad80 100644
--- a/plugins/ruflo-autopilot/agents/autopilot-coordinator.md
+++ b/plugins/ruflo-autopilot/agents/autopilot-coordinator.md
@@ -31,3 +31,12 @@ npx @claude-flow/cli@latest memory store --namespace patterns --key "autopilot-P
```
Call `autopilot_learn` periodically to discover cross-task success patterns.
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-autopilot/skills/autopilot-loop/SKILL.md b/plugins/ruflo-autopilot/skills/autopilot-loop/SKILL.md
index d4f393c335..c830040d2a 100644
--- a/plugins/ruflo-autopilot/skills/autopilot-loop/SKILL.md
+++ b/plugins/ruflo-autopilot/skills/autopilot-loop/SKILL.md
@@ -1,6 +1,7 @@
---
name: autopilot-loop
description: Run an autonomous /loop iteration -- check progress, work on next task, schedule next wake
+argument-hint: ""
allowed-tools: mcp__claude-flow__autopilot_status mcp__claude-flow__autopilot_predict mcp__claude-flow__autopilot_log mcp__claude-flow__autopilot_progress mcp__claude-flow__autopilot_disable ScheduleWakeup Agent
---
Run one autopilot iteration using Claude Code's native /loop:
diff --git a/plugins/ruflo-autopilot/skills/autopilot-predict/SKILL.md b/plugins/ruflo-autopilot/skills/autopilot-predict/SKILL.md
index efe747c0fc..f5fb07a63d 100644
--- a/plugins/ruflo-autopilot/skills/autopilot-predict/SKILL.md
+++ b/plugins/ruflo-autopilot/skills/autopilot-predict/SKILL.md
@@ -1,6 +1,7 @@
---
name: autopilot-predict
description: Use learned patterns and current state to predict the optimal next action
+argument-hint: ""
allowed-tools: mcp__claude-flow__autopilot_predict mcp__claude-flow__autopilot_progress mcp__claude-flow__autopilot_learn mcp__claude-flow__autopilot_history
---
Predict what to work on next using Ruflo autopilot intelligence:
diff --git a/plugins/ruflo-browser/agents/browser-agent.md b/plugins/ruflo-browser/agents/browser-agent.md
index f270381c00..de46457cd7 100644
--- a/plugins/ruflo-browser/agents/browser-agent.md
+++ b/plugins/ruflo-browser/agents/browser-agent.md
@@ -20,3 +20,20 @@ Use these MCP tools:
- `mcp__claude-flow__browser_wait` for synchronization
Always wait for elements before interacting and take screenshots to document results.
+
+### Memory Learning
+
+Store successful scraping selectors and test patterns:
+```bash
+npx @claude-flow/cli@latest memory store --namespace browser-patterns --key "site-DOMAIN" --value "SELECTORS_AND_STRATEGY"
+npx @claude-flow/cli@latest memory search --query "scraping pattern for DOMAIN" --namespace browser-patterns
+```
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-browser/skills/browser-scrape/SKILL.md b/plugins/ruflo-browser/skills/browser-scrape/SKILL.md
index 089e2ef441..28f60e6ab9 100644
--- a/plugins/ruflo-browser/skills/browser-scrape/SKILL.md
+++ b/plugins/ruflo-browser/skills/browser-scrape/SKILL.md
@@ -1,6 +1,7 @@
---
name: browser-scrape
description: Extract structured data from web pages using browser automation and DOM queries
+argument-hint: "<url>"
allowed-tools: mcp__claude-flow__browser_open mcp__claude-flow__browser_get-text mcp__claude-flow__browser_get-value mcp__claude-flow__browser_eval mcp__claude-flow__browser_snapshot mcp__claude-flow__browser_screenshot mcp__claude-flow__browser_scroll mcp__claude-flow__browser_wait mcp__claude-flow__browser_click mcp__claude-flow__browser_close mcp__claude-flow__browser_session-list Bash
---
diff --git a/plugins/ruflo-browser/skills/browser-test/SKILL.md b/plugins/ruflo-browser/skills/browser-test/SKILL.md
index 38b9fdcf7b..5911b27c25 100644
--- a/plugins/ruflo-browser/skills/browser-test/SKILL.md
+++ b/plugins/ruflo-browser/skills/browser-test/SKILL.md
@@ -1,6 +1,7 @@
---
name: browser-test
description: Automated browser testing with Playwright -- navigate, interact, screenshot, and validate UI
+argument-hint: "<url> [--screenshot]"
allowed-tools: mcp__claude-flow__browser_open mcp__claude-flow__browser_click mcp__claude-flow__browser_fill mcp__claude-flow__browser_type mcp__claude-flow__browser_press mcp__claude-flow__browser_check mcp__claude-flow__browser_uncheck mcp__claude-flow__browser_select mcp__claude-flow__browser_hover mcp__claude-flow__browser_wait mcp__claude-flow__browser_screenshot mcp__claude-flow__browser_snapshot mcp__claude-flow__browser_get-text mcp__claude-flow__browser_get-title mcp__claude-flow__browser_get-url mcp__claude-flow__browser_get-value mcp__claude-flow__browser_eval mcp__claude-flow__browser_close mcp__claude-flow__browser_session-list Bash
---
diff --git a/plugins/ruflo-core/agents/coder.md b/plugins/ruflo-core/agents/coder.md
index 9436836c41..9b7f59bc37 100644
--- a/plugins/ruflo-core/agents/coder.md
+++ b/plugins/ruflo-core/agents/coder.md
@@ -11,3 +11,12 @@ Guidelines:
- Apply SOLID principles. Validate inputs at system boundaries.
- Store successful patterns: `npx @claude-flow/cli@latest memory store --key "pattern-NAME" --value "DESCRIPTION" --namespace patterns`
- Search for prior art: `npx @claude-flow/cli@latest memory search --query "TOPIC" --namespace patterns`
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-core/agents/researcher.md b/plugins/ruflo-core/agents/researcher.md
index d0b2cb990f..68d84e5f07 100644
--- a/plugins/ruflo-core/agents/researcher.md
+++ b/plugins/ruflo-core/agents/researcher.md
@@ -1,15 +1,80 @@
---
name: researcher
-description: Research specialist for analyzing requirements, codebase patterns, and prior art
+description: Pathfinder research specialist — traverses RuVector memory graphs and codebase to surface patterns, dependencies, and prior art
model: sonnet
---
-You are a research specialist within a Ruflo-coordinated swarm. Analyze requirements, explore codebases, and surface relevant patterns before implementation begins.
+You are a pathfinder research specialist within a Ruflo-coordinated swarm. You traverse knowledge graphs and codebases using a shortest-path exploration algorithm to surface the most relevant patterns, dependencies, and prior art before implementation begins.
-Workflow:
-1. Search memory for prior work: `npx @claude-flow/cli@latest memory search --query "TOPIC" --namespace patterns`
-2. Use Read, Grep, and Glob to explore the codebase for relevant files and conventions.
-3. Summarize findings: existing patterns, dependencies, edge cases, and risks.
-4. Store findings: `npx @claude-flow/cli@latest memory store --key "research-TOPIC" --value "FINDINGS" --namespace tasks`
-5. Report via `npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true`
+### Pathfinder Algorithm
+
+Use a graph-traversal approach — each research step expands the frontier of known connections:
+
+1. **Seed** — Start with the topic. Query AgentDB for the closest known nodes:
+ ```
+ mcp__claude-flow__agentdb_semantic-route({ query: "TOPIC", namespace: "patterns" })
+ ```
+2. **Expand** — For each result, follow causal edges to related knowledge:
+ ```
+ mcp__claude-flow__agentdb_causal-edge({ from: "NODE_ID", type: "depends-on" })
+ mcp__claude-flow__agentdb_hierarchical-recall({ path: "domain/TOPIC", depth: 3 })
+ ```
+3. **Score** — Rank paths by relevance using HNSW similarity + recency:
+ ```
+ mcp__claude-flow__agentdb_pattern-search({ query: "TOPIC", limit: 10 })
+ ```
+4. **Prune** — Stop expanding paths with similarity < 0.3 (diminishing returns)
+5. **Bridge** — Cross-reference with codebase (Read, Grep, Glob) to ground findings in current code
+6. **Synthesize** — Merge graph findings into a coherent research summary:
+ ```
+ mcp__claude-flow__agentdb_context-synthesize({ query: "TOPIC", sources: ["patterns", "tasks", "solutions"] })
+ ```
+
+### Research Workflow
+
+1. **Graph traverse**: Pathfinder algo above — expands from seed → related patterns → causal chains
+2. **Codebase ground**: Use Read, Grep, Glob to verify graph findings against current source
+3. **External bridge**: WebSearch/WebFetch when neither graph nor codebase has answers
+4. **Dependency map**: Trace imports/exports to build the impact graph
+5. **Risk surface**: Security, breaking changes, performance implications, edge cases
+6. **Store findings**: Persist as new graph nodes for future traversals:
+ ```
+ mcp__claude-flow__agentdb_hierarchical-store({ path: "research/TOPIC", data: "FINDINGS" })
+ mcp__claude-flow__agentdb_causal-edge({ from: "research/TOPIC", to: "design/FEATURE", type: "informs" })
+ ```
+
+### Research Patterns
+
+| Pattern | Pathfinder Strategy | When to use |
+|---------|-------------------|-------------|
+| Codebase scan | Seed: feature name → expand: imports/exports → bridge: file reads | New feature |
+| Dependency audit | Seed: module → expand: causal edges (depends-on) → prune at boundary | Refactor |
+| Convention check | Seed: pattern name → expand: similar patterns → score by recency | Any change |
+| Risk assessment | Seed: change description → expand: security/perf patterns → synthesize | Security/perf |
+| Prior art search | Seed: concept → expand: hierarchical recall depth 5 → external bridge | Novel features |
+
+### Tools
+
+**AgentDB Graph Traversal:**
+- `mcp__claude-flow__agentdb_semantic-route` — find closest knowledge node
+- `mcp__claude-flow__agentdb_hierarchical-recall` — depth-limited tree traversal
+- `mcp__claude-flow__agentdb_causal-edge` — follow dependency/impact chains
+- `mcp__claude-flow__agentdb_pattern-search` — HNSW similarity search across patterns
+- `mcp__claude-flow__agentdb_context-synthesize` — merge multi-source findings
+- `mcp__claude-flow__agentdb_hierarchical-store` — persist new knowledge nodes
+
+**Codebase Exploration:**
+- `Read`, `Grep`, `Glob` — file-level analysis
+- `WebSearch`, `WebFetch` — external research
+
+**Memory (simple key-value):**
+- `npx @claude-flow/cli@latest memory search --query "TOPIC" --namespace patterns`
+- `npx @claude-flow/cli@latest memory store --key "research-TOPIC" --value "FINDINGS" --namespace tasks`
Never modify source code. Your output informs architects, coders, and testers.
+
+### Neural Learning
+
+After completing tasks, store successful patterns and link them in the knowledge graph:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+```
diff --git a/plugins/ruflo-core/skills/discover-plugins/SKILL.md b/plugins/ruflo-core/skills/discover-plugins/SKILL.md
index 9ac3286d9d..a537aef34d 100644
--- a/plugins/ruflo-core/skills/discover-plugins/SKILL.md
+++ b/plugins/ruflo-core/skills/discover-plugins/SKILL.md
@@ -1,6 +1,7 @@
---
name: discover-plugins
description: Discover and recommend ruflo plugins based on your workflow, installed MCP tools, and current task
+argument-hint: "[search-query]"
allowed-tools: mcp__claude-flow__transfer_plugin-search mcp__claude-flow__transfer_plugin-info mcp__claude-flow__transfer_plugin-featured mcp__claude-flow__transfer_plugin-official mcp__claude-flow__transfer_store-search mcp__claude-flow__transfer_store-featured mcp__claude-flow__transfer_store-trending mcp__claude-flow__transfer_store-info mcp__claude-flow__guidance_discover mcp__claude-flow__guidance_recommend mcp__claude-flow__guidance_capabilities mcp__claude-flow__mcp_status Bash Read
---
@@ -21,29 +22,94 @@ When starting a new project, exploring ruflo capabilities, or wondering which pl
5. **Check capabilities** — call `mcp__claude-flow__guidance_capabilities` to see what each plugin enables
6. **Show details** — call `mcp__claude-flow__transfer_plugin-info` for full plugin details
-## Available plugins
-
-| Plugin | Category | What it adds |
-|--------|----------|-------------|
-| **ruflo-core** | Core | MCP server, status, doctor, base agents |
-| **ruflo-swarm** | Coordination | Swarm topologies, Monitor, worktree isolation |
-| **ruflo-autopilot** | Automation | Autonomous /loop task completion |
-| **ruflo-intelligence** | Learning | SONA patterns, trajectory learning, routing |
-| **ruflo-agentdb** | Memory | AgentDB, HNSW vector search, RuVector |
-| **ruflo-loop-workers** | Automation | Background workers, CronCreate scheduling |
-| **ruflo-security-audit** | Security | CVE scanning, dependency checks |
-| **ruflo-rag-memory** | Memory | Simple store/search/recall interface |
-| **ruflo-testgen** | Testing | Test gap detection, TDD workflow |
-| **ruflo-docs** | Docs | Doc generation, drift detection |
-| **ruflo-aidefence** | Security | AI safety, PII detection, prompt defense |
-| **ruflo-browser** | Testing | Playwright browser automation |
-| **ruflo-jujutsu** | Git | Diff analysis, risk scoring, reviewers |
-| **ruflo-wasm** | Sandbox | WASM agent sandboxing and gallery |
-| **ruflo-workflows** | Automation | Workflow templates and orchestration |
-| **ruflo-daa** | Learning | Dynamic Agentic Architecture, cognitive patterns |
-| **ruflo-ruvllm** | LLM | Local inference, MicroLoRA, chat formatting |
-| **ruflo-rvf** | Memory | RVF portable memory, session persistence |
-| **ruflo-plugin-creator** | Dev Tools | Scaffold and validate new plugins |
+## Plugin Catalog (32 plugins)
+
+### Core & Coordination — Start here
+
+| Plugin | When to use | What it adds |
+|--------|-------------|-------------|
+| **ruflo-core** | Always — base layer for all Ruflo work | MCP server, status, doctor, coder/researcher/reviewer agents |
+| **ruflo-swarm** | Multi-agent tasks (3+ files, features, refactors) | Swarm topologies (hierarchical, mesh), Monitor streaming, worktree isolation |
+| **ruflo-autopilot** | Autonomous task completion without manual steering | /loop-based autonomous execution, progress prediction, learning |
+| **ruflo-loop-workers** | Recurring background work (audits, optimization, mapping) | 12 background workers via /loop or CronCreate scheduling |
+| **ruflo-workflows** | Repeatable multi-step processes | Workflow templates, parallel execution, conditional branching |
+
+### Memory & Intelligence — Cross-session learning
+
+| Plugin | When to use | What it adds |
+|--------|-------------|-------------|
+| **ruflo-agentdb** | Semantic search over code patterns, telemetry, decisions | AgentDB with HNSW vector search (150x-12,500x faster), RuVector embeddings |
+| **ruflo-rag-memory** | Simple key-value memory with search | Store/search/recall without full AgentDB setup |
+| **ruflo-rvf** | Portable memory export/import across machines | RVF format, session persistence, cross-platform transfer |
+| **ruflo-ruvector** | Vector embedding operations, HNSW indexing, clustering | ONNX 384-dim embeddings, hyperbolic Poincare ball, k-means/DBSCAN clustering |
+| **ruflo-knowledge-graph** | Entity extraction, relation mapping, graph traversal | Pathfinder algo on AgentDB causal edges, code entity graphs |
+| **ruflo-intelligence** | Task routing optimization, learning from outcomes | SONA neural patterns, trajectory learning, model routing with confidence |
+| **ruflo-daa** | Self-adapting agents that evolve behavior | Dynamic Agentic Architecture, cognitive patterns, knowledge sharing |
+
+### Architecture & Methodology — Build right
+
+| Plugin | When to use | What it adds |
+|--------|-------------|-------------|
+| **ruflo-adr** | Document architecture decisions, check compliance | ADR create/index/supersede, code-to-ADR linking, compliance checking on diffs |
+| **ruflo-ddd** | Domain modeling, bounded context scaffolding | Context wizard, aggregate roots, domain events, anti-corruption layers, boundary validation |
+| **ruflo-sparc** | Structured development methodology | Specification-Pseudocode-Architecture-Refinement-Completion with quality gates |
+
+### Quality & Security — Ship safely
+
+| Plugin | When to use | What it adds |
+|--------|-------------|-------------|
+| **ruflo-security-audit** | Before merging, after dependency changes | CVE scanning, dependency vulnerability checks, security reports |
+| **ruflo-aidefence** | Processing user input, handling untrusted data | Prompt injection detection, PII scanning, adversarial defense |
+| **ruflo-testgen** | After implementing features, during refactors | Test gap detection, TDD London School workflow, coverage routing |
+| **ruflo-browser** | UI testing, web scraping, visual validation | Playwright automation — navigate, click, screenshot, validate |
+
+### Development Tools — Build faster
+
+| Plugin | When to use | What it adds |
+|--------|-------------|-------------|
+| **ruflo-jujutsu** | PR review, merge decisions, diff risk scoring | Diff analysis, risk classification, reviewer recommendations |
+| **ruflo-docs** | After API changes, before releases | Doc generation, drift detection, API documentation |
+| **ruflo-ruvllm** | Local LLM inference, custom model configs | RuVLLM integration, MicroLoRA fine-tuning, chat formatting |
+| **ruflo-wasm** | Sandboxed code execution, untrusted workloads | WASM agent sandboxing, community gallery |
+| **ruflo-plugin-creator** | Building new ruflo plugins | Scaffold structure, validate frontmatter, test MCP references |
+| **ruflo-migrations** | Database schema changes | Sequential migration numbering, up/down pairs, dry-run, rollback validation |
+| **ruflo-observability** | Logging, tracing, metrics correlation | Structured JSON logging, distributed tracing, agent-to-app telemetry correlation |
+| **ruflo-cost-tracker** | Token budget management | Per-agent cost attribution, model pricing, budget alerts, optimization recommendations |
+
+### Domain-Specific — Specialized workloads
+
+| Plugin | When to use | What it adds |
+|--------|-------------|-------------|
+| **ruflo-goals** | Long-horizon planning, multi-session research | GOAP algorithm, deep research orchestration, horizon tracking, synthesis |
+| **ruflo-federation** | Cross-installation agent coordination | Zero-trust peer discovery, mTLS auth, consensus routing, compliance audit |
+| **ruflo-iot-cognitum** | Cognitum Seed hardware device management | 5-tier device trust, telemetry anomaly detection (Z-score), fleet firmware rollouts, witness chain verification, SONA + AgentDB integration |
+| **ruflo-neural-trader** | Trading strategy development and backtesting | Z-score market anomalies, SONA trajectory strategies, walk-forward backtesting, portfolio optimization |
+| **ruflo-market-data** | Market data ingestion and pattern matching | OHLCV vectorization, candlestick pattern detection, HNSW-indexed historical search |
+
+## Decision Guide
+
+**"I need to..."** → Use this plugin:
+
+- Build a feature → `ruflo-core` + `ruflo-swarm` + `ruflo-testgen`
+- Fix a bug → `ruflo-core` + `ruflo-jujutsu` (for diff analysis)
+- Audit security → `ruflo-security-audit` + `ruflo-aidefence`
+- Run background tasks → `ruflo-loop-workers` + `ruflo-autopilot`
+- Search past decisions → `ruflo-agentdb` + `ruflo-rag-memory`
+- Plan a multi-week effort → `ruflo-goals` (horizon tracking)
+- Manage IoT devices → `ruflo-iot-cognitum`
+- Coordinate remote agents → `ruflo-federation`
+- Test UI changes → `ruflo-browser`
+- Generate docs → `ruflo-docs`
+- Create a new plugin → `ruflo-plugin-creator`
+- Document architecture decisions → `ruflo-adr`
+- Scaffold domain models → `ruflo-ddd`
+- Follow SPARC methodology → `ruflo-sparc`
+- Develop trading strategies → `ruflo-neural-trader` + `ruflo-market-data`
+- Work with vector embeddings → `ruflo-ruvector`
+- Build knowledge graphs → `ruflo-knowledge-graph`
+- Manage database migrations → `ruflo-migrations`
+- Add observability → `ruflo-observability`
+- Track token costs → `ruflo-cost-tracker`
## Install any plugin
diff --git a/plugins/ruflo-core/skills/doctor/SKILL.md b/plugins/ruflo-core/skills/doctor/SKILL.md
index 82774b2c2e..20fb188692 100644
--- a/plugins/ruflo-core/skills/doctor/SKILL.md
+++ b/plugins/ruflo-core/skills/doctor/SKILL.md
@@ -1,6 +1,7 @@
---
name: doctor
description: Run health checks on the Ruflo installation and fix common issues
+argument-hint: "[--fix]"
allowed-tools: Bash(npx *)
---
Run `npx @claude-flow/cli@latest doctor --fix` to diagnose and auto-repair common issues.
diff --git a/plugins/ruflo-core/skills/init-project/SKILL.md b/plugins/ruflo-core/skills/init-project/SKILL.md
index 4bf614f4d9..670c601888 100644
--- a/plugins/ruflo-core/skills/init-project/SKILL.md
+++ b/plugins/ruflo-core/skills/init-project/SKILL.md
@@ -1,6 +1,7 @@
---
name: init-project
description: Initialize a new Ruflo project with MCP tools, hooks, and agent configuration
+argument-hint: "[--preset standard|minimal|full]"
allowed-tools: Bash(npx *) Read Write Edit
---
Run `npx @claude-flow/cli@latest init --wizard` to set up the project interactively, or `npx @claude-flow/cli@latest init --preset standard` for defaults.
diff --git a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..b60ed4a9b0
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
@@ -0,0 +1,19 @@
+{
+ "name": "ruflo-cost-tracker",
+ "description": "Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "cost",
+ "tokens",
+ "budget",
+ "optimization",
+ "usage"
+ ]
+}
diff --git a/plugins/ruflo-cost-tracker/README.md b/plugins/ruflo-cost-tracker/README.md
new file mode 100644
index 0000000000..cbca53919f
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/README.md
@@ -0,0 +1,72 @@
+# ruflo-cost-tracker
+
+Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations.
+
+## Overview
+
+Tracks token usage per agent, task, and model, then computes USD cost attribution using current model pricing. Monitors configurable budgets with tiered alerts (info at 50%, warning at 75%, critical at 90%, hard stop at 100%). Analyzes usage patterns and recommends optimizations such as model downgrades, prompt caching, and batch operations.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-cost-tracker
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `cost-analyst` | haiku | Token usage tracking, USD cost attribution, budget monitoring, optimization recommendations |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `cost-report` | `/cost-report [--period today]` | Generate a cost report with token usage and USD costs by agent and model |
+| `cost-optimize` | `/cost-optimize` | Analyze usage patterns and recommend cost optimizations with estimated savings |
+
+## Commands (5 subcommands)
+
+```bash
+cost report [--period today|week|month] # Generate cost report for a period
+cost breakdown [--by agent|model|task] # Detailed breakdown by dimension
+cost budget set <amount> # Set budget limit in USD
+cost optimize # Analyze usage and suggest savings
+cost history # Show cost tracking over time
+```
+
+## Model Pricing (per 1M tokens)
+
+| Model | Input | Output | Cache Write | Cache Read |
+|-------|-------|--------|-------------|------------|
+| Haiku | $0.25 | $1.25 | $0.30 | $0.03 |
+| Sonnet | $3.00 | $15.00 | $3.75 | $0.30 |
+| Opus | $15.00 | $75.00 | $18.75 | $1.50 |
+
+## Budget Alert Thresholds
+
+| Level | Threshold | Action |
+|-------|-----------|--------|
+| Info | 50% consumed | Log notification |
+| Warning | 75% consumed | Display warning, suggest optimizations |
+| Critical | 90% consumed | Urgent alert, recommend model downgrades |
+| Hard Stop | 100% consumed | Halt non-essential agent spawns |
+
+## Optimization Strategies
+
+| Strategy | Savings | Impact |
+|----------|---------|--------|
+| Downgrade simple tasks to Haiku | 80-92% | Minimal for low-complexity work |
+| Enable prompt caching | 90% on reads | None (same quality) |
+| Batch similar operations | 15-25% | Slight latency increase |
+| Use Agent Booster (Tier 1) | 100% | Only for simple transforms |
+| Shorten system prompts | 10-20% | Requires careful pruning |
+
+## Related Plugins
+
+- `ruflo-observability` -- Token usage metrics collected via observability instrumentation
+- `ruflo-neural-trader` -- PnL tracking and cost-adjusted return calculation
+
+## License
+
+MIT
diff --git a/plugins/ruflo-cost-tracker/agents/cost-analyst.md b/plugins/ruflo-cost-tracker/agents/cost-analyst.md
new file mode 100644
index 0000000000..d26f8c2e04
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/agents/cost-analyst.md
@@ -0,0 +1,105 @@
+---
+name: cost-analyst
+description: Tracks token usage per agent and model, computes cost attribution in USD, monitors budgets, and recommends optimizations
+model: haiku
+---
+You are a cost analyst agent. Your responsibilities:
+
+1. **Track token usage** per agent, per task, and per model
+2. **Compute cost attribution** by mapping token counts to USD using model pricing
+3. **Monitor budgets** with configurable thresholds and alerts
+4. **Recommend optimizations** to reduce costs without degrading quality
+5. **Generate reports** with breakdowns by agent, model, task, and time period
+
+### Model Pricing (per 1M tokens)
+
+| Model | Input | Output | Cache Write | Cache Read |
+|-------|-------|--------|-------------|------------|
+| Haiku | $0.25 | $1.25 | $0.30 | $0.03 |
+| Sonnet | $3.00 | $15.00 | $3.75 | $0.30 |
+| Opus | $15.00 | $75.00 | $18.75 | $1.50 |
+
+### Cost Attribution Formula
+
+```
+task_cost = (input_tokens / 1M * input_price) + (output_tokens / 1M * output_price)
+ + (cache_write_tokens / 1M * cache_write_price)
+ + (cache_read_tokens / 1M * cache_read_price)
+```
+
+### Budget Alert Thresholds
+
+| Level | Threshold | Action |
+|-------|-----------|--------|
+| Info | 50% of budget consumed | Log notification |
+| Warning | 75% of budget consumed | Display warning, suggest optimizations |
+| Critical | 90% of budget consumed | Urgent alert, recommend model downgrades |
+| Hard Stop | 100% of budget consumed | Halt non-essential agent spawns |
+
+### Optimization Strategies
+
+| Strategy | Savings | Impact |
+|----------|---------|--------|
+| Downgrade simple tasks to Haiku | 80-92% | Minimal for low-complexity work |
+| Enable prompt caching | 90% on cache reads | None (same quality) |
+| Batch similar operations | 15-25% | Slight latency increase |
+| Reduce agent count | Linear | May slow parallel work |
+| Use Agent Booster (Tier 1) | 100% (no LLM) | Only for simple transforms |
+| Shorten system prompts | 10-20% | Requires careful pruning |
+
+### Report Format
+
+```
+=== Cost Report (2026-04-29) ===
+
+Total: $12.45 / $50.00 budget (24.9%)
+
+By Model:
+ Haiku: $0.45 (3.6%) -- 1,200K input, 400K output
+ Sonnet: $8.20 (65.9%) -- 1,800K input, 320K output
+ Opus: $3.80 (30.5%) -- 180K input, 28K output
+
+By Agent:
+ coder: $5.20 (41.8%) -- sonnet
+ architect: $3.80 (30.5%) -- opus
+ researcher: $2.00 (16.1%) -- sonnet
+ tester: $1.00 (8.0%) -- sonnet
+ reviewer: $0.45 (3.6%) -- haiku
+
+Optimization Opportunities:
+ - reviewer could use haiku (already does) -- no change needed
+ - researcher tasks avg complexity 22% -- consider haiku (-$1.60 savings)
+ - architect cache hit rate 40% -- enable caching (-$1.14 savings)
+```
+
+### Tools
+
+- `mcp__claude-flow__agentdb_hierarchical-store` -- store usage records and budget configuration
+- `mcp__claude-flow__agentdb_hierarchical-recall` -- recall usage history and budget status
+- `mcp__claude-flow__agentdb_pattern-store` -- store cost optimization patterns
+- `mcp__claude-flow__agentdb_pattern-search` -- search for cost reduction strategies
+- `mcp__claude-flow__agentdb_semantic-route` -- route cost queries to relevant data
+
+### Neural Learning
+
+After generating cost reports or applying optimizations, train patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest neural train --pattern-type cost-optimization --epochs 5
+```
+
+### Memory Learning
+
+Store cost patterns and optimization results:
+```bash
+npx @claude-flow/cli@latest memory store --namespace cost-tracking --key "report-DATE" --value "REPORT_JSON"
+npx @claude-flow/cli@latest memory store --namespace cost-patterns --key "optimization-OPT_NAME" --value "OPTIMIZATION_RESULT_JSON"
+npx @claude-flow/cli@latest memory search --query "cost savings from model downgrades" --namespace cost-patterns
+```
+
+### Related Plugins
+
+- **ruflo-intelligence**: Model routing optimization data feeds cost analysis (3-tier routing reduces cost 75%)
+- **ruflo-autopilot**: Budget-aware autopilot mode uses cost data to throttle agent spawns
+- **ruflo-observability**: Token usage metrics are collected via observability instrumentation
+- **ruflo-swarm**: Agent spawn/stop decisions informed by budget remaining
diff --git a/plugins/ruflo-cost-tracker/commands/cost.md b/plugins/ruflo-cost-tracker/commands/cost.md
new file mode 100644
index 0000000000..c94b56ab84
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/commands/cost.md
@@ -0,0 +1,40 @@
+---
+name: cost
+description: Cost tracking operations — generate reports, view breakdowns, set budgets, and get optimization recommendations
+---
+
+Cost tracking commands:
+
+**`cost report [--period today|week|month]`** -- Generate a cost report for the specified period.
+1. Recall token usage records from `cost-tracking` namespace for the period
+2. Compute costs by model using current pricing (haiku/sonnet/opus input/output rates)
+3. Aggregate by agent, task, and model
+4. Show budget utilization percentage if a budget is configured
+5. Display: total cost, breakdown by model, breakdown by agent, budget status
+
+**`cost breakdown [--by agent|model|task]`** -- Detailed cost breakdown by dimension.
+1. Recall all usage records from `cost-tracking` namespace
+2. Group by the specified dimension (agent, model, or task)
+3. For each group: total tokens (input/output/cache), total cost, percentage of total
+4. Sort by cost descending
+5. Display: dimension value, input tokens, output tokens, cache tokens, total cost, share %
+
+**`cost budget set <amount>`** -- Set a budget limit in USD.
+1. Store the budget configuration via `mcp__claude-flow__agentdb_hierarchical-store`
+2. Configure alert thresholds: info at 50%, warning at 75%, critical at 90%, hard stop at 100%
+3. Report: budget set, current spend, remaining budget, alert thresholds
+
+**`cost optimize`** -- Analyze usage and suggest cost optimizations.
+1. Recall recent usage data from `cost-tracking` namespace
+2. For each agent, analyze: average task complexity, model used, token efficiency
+3. Identify agents using expensive models for low-complexity tasks
+4. Check cache hit rates and suggest caching improvements
+5. Look for redundant agent spawns or duplicate work
+6. Calculate estimated savings for each recommendation
+7. Display: recommendation, current cost, projected cost, savings, impact assessment
+
+**`cost history`** -- Show cost tracking history over time.
+1. Recall all cost reports from `cost-tracking` namespace
+2. Show daily/weekly totals with trend direction
+3. Highlight days with unusual spending (>2x average)
+4. Display: date, total cost, top agent, top model, budget status
diff --git a/plugins/ruflo-cost-tracker/skills/cost-optimize/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-optimize/SKILL.md
new file mode 100644
index 0000000000..aef16cf17f
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/skills/cost-optimize/SKILL.md
@@ -0,0 +1,33 @@
+---
+name: cost-optimize
+description: Analyze token usage patterns and recommend cost optimizations with estimated savings
+argument-hint: ""
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_pattern-search mcp__claude-flow__agentdb_pattern-store mcp__claude-flow__agentdb_semantic-route Bash
+---
+
+# Cost Optimize
+
+Analyze recent token usage across agents and models, identify waste, and recommend specific optimizations with estimated dollar savings.
+
+## When to use
+
+When costs are higher than expected or you want to proactively reduce spending. Analyzes model selection efficiency, cache utilization, agent redundancy, and prompt efficiency.
+
+## Steps
+
+1. **Load usage data** -- call `mcp__claude-flow__agentdb_hierarchical-recall` to fetch recent token usage records from `cost-tracking` namespace (last 7 days)
+2. **Analyze model fit** -- for each agent, assess whether the model tier matches task complexity:
+ - Agents doing simple tasks (formatting, linting) on Sonnet/Opus -> suggest Haiku or Agent Booster
+ - Agents doing complex tasks (architecture, security) on Haiku -> flag quality risk
+3. **Check cache rates** -- compute cache hit rate per agent; if below 60%, recommend enabling or improving prompt caching (90% cost reduction on cache reads)
+4. **Detect redundancy** -- look for multiple agents performing overlapping tasks, or agents being spawned for work that could be batched
+5. **Estimate savings** -- for each recommendation, calculate: current cost, projected cost after optimization, dollar savings, percentage reduction
+6. **Search patterns** -- call `mcp__claude-flow__agentdb_pattern-search` for previously successful optimizations
+7. **Store recommendations** -- call `mcp__claude-flow__agentdb_pattern-store` to record optimization recommendations in `cost-patterns` namespace
+8. **Report** -- display: ranked recommendations with savings estimate, total potential savings, implementation priority (quick wins first)
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory search --query "cost optimization strategies" --namespace cost-patterns
+```
diff --git a/plugins/ruflo-cost-tracker/skills/cost-report/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-report/SKILL.md
new file mode 100644
index 0000000000..87401fc195
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/skills/cost-report/SKILL.md
@@ -0,0 +1,33 @@
+---
+name: cost-report
+description: Generate a cost report showing token usage and USD costs by agent and model
+argument-hint: "[--period today]"
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_semantic-route mcp__claude-flow__agentdb_pattern-search Bash
+---
+
+# Cost Report
+
+Generate a comprehensive cost report showing token usage, USD costs, and budget utilization for the specified period.
+
+## When to use
+
+When you need to understand current spending -- how much each agent costs, which models consume the most budget, and whether you're on track to stay within budget.
+
+## Steps
+
+1. **Retrieve usage** -- call `mcp__claude-flow__agentdb_hierarchical-recall` to fetch token usage records from the `cost-tracking` namespace for the specified period (default: today)
+2. **Compute costs** -- for each record, calculate cost using model pricing:
+ - Haiku: $0.25/M input, $1.25/M output
+ - Sonnet: $3.00/M input, $15.00/M output
+ - Opus: $15.00/M input, $75.00/M output
+ - Include cache write/read costs where applicable
+3. **Aggregate by model** -- sum costs per model, compute percentage share
+4. **Aggregate by agent** -- sum costs per agent, include the model each agent used
+5. **Check budget** -- recall budget configuration and compute utilization percentage, check alert thresholds (50%/75%/90%/100%)
+6. **Report** -- display: total cost, budget remaining, model breakdown, agent breakdown, active alerts
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory search --query "cost report for today" --namespace cost-tracking
+```
diff --git a/plugins/ruflo-daa/agents/daa-specialist.md b/plugins/ruflo-daa/agents/daa-specialist.md
index f8727f5eaf..4e3068e29a 100644
--- a/plugins/ruflo-daa/agents/daa-specialist.md
+++ b/plugins/ruflo-daa/agents/daa-specialist.md
@@ -20,3 +20,16 @@ Use these MCP tools:
- `mcp__claude-flow__daa_learning_status` / `daa_performance_metrics` for monitoring
Focus on creating agents that improve measurably over time through feedback loops.
+
+### Memory Persistence
+
+Persist cognitive patterns and adaptation history:
+```bash
+npx @claude-flow/cli@latest memory store --namespace daa-patterns --key "cognitive-PATTERN" --value "ADAPTATION_DATA"
+npx @claude-flow/cli@latest memory search --query "cognitive pattern for TASK" --namespace daa-patterns
+```
+
+### Related Plugins
+
+- **ruflo-intelligence**: SONA neural patterns power cognitive adaptation and trajectory learning
+- **ruflo-agentdb**: Pattern storage backend for DAA knowledge sharing
diff --git a/plugins/ruflo-daa/skills/cognitive-pattern/SKILL.md b/plugins/ruflo-daa/skills/cognitive-pattern/SKILL.md
index f3739c5b25..dd4f1bd534 100644
--- a/plugins/ruflo-daa/skills/cognitive-pattern/SKILL.md
+++ b/plugins/ruflo-daa/skills/cognitive-pattern/SKILL.md
@@ -1,6 +1,7 @@
---
name: cognitive-pattern
description: Define and manage cognitive patterns for agent reasoning and decision-making
+argument-hint: "<pattern-name>"
allowed-tools: mcp__claude-flow__daa_cognitive_pattern mcp__claude-flow__daa_workflow_create mcp__claude-flow__daa_workflow_execute mcp__claude-flow__daa_knowledge_share mcp__claude-flow__daa_learning_status Bash
---
diff --git a/plugins/ruflo-daa/skills/daa-agent/SKILL.md b/plugins/ruflo-daa/skills/daa-agent/SKILL.md
index 2941bfb8c4..7cf5529070 100644
--- a/plugins/ruflo-daa/skills/daa-agent/SKILL.md
+++ b/plugins/ruflo-daa/skills/daa-agent/SKILL.md
@@ -1,6 +1,7 @@
---
name: daa-agent
description: Create and adapt Dynamic Agentic Architecture agents that learn and evolve
+argument-hint: "<create|adapt|status> [options]"
allowed-tools: mcp__claude-flow__daa_agent_create mcp__claude-flow__daa_agent_adapt mcp__claude-flow__daa_learning_status mcp__claude-flow__daa_performance_metrics mcp__claude-flow__daa_knowledge_share Bash
---
diff --git a/plugins/ruflo-ddd/.claude-plugin/plugin.json b/plugins/ruflo-ddd/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..9030e3fac8
--- /dev/null
+++ b/plugins/ruflo-ddd/.claude-plugin/plugin.json
@@ -0,0 +1,19 @@
+{
+ "name": "ruflo-ddd",
+ "description": "Domain-Driven Design scaffolding — bounded contexts, aggregate roots, domain events, and anti-corruption layers",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "ddd",
+ "domain-driven-design",
+ "bounded-context",
+ "aggregate",
+ "events"
+ ]
+}
diff --git a/plugins/ruflo-ddd/README.md b/plugins/ruflo-ddd/README.md
new file mode 100644
index 0000000000..dc168f5a33
--- /dev/null
+++ b/plugins/ruflo-ddd/README.md
@@ -0,0 +1,72 @@
+# ruflo-ddd
+
+Domain-Driven Design scaffolding -- bounded contexts, aggregate roots, domain events, and anti-corruption layers.
+
+## Overview
+
+Transforms business domains into well-structured bounded contexts with aggregate roots, value objects, domain events, repositories, and anti-corruption layers. Stores the domain model as a navigable graph in AgentDB with hierarchical nodes and causal edges for context dependencies.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-ddd
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `domain-modeler` | sonnet | Map domains to bounded contexts, design aggregates with invariants, define domain events, generate ACL interfaces |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `ddd-context` | `/ddd-context <context-name>` | Create a bounded context with standard directory structure |
+| `ddd-aggregate` | `/ddd-aggregate <context> <aggregate-name>` | Scaffold an aggregate root with entity, value objects, repository, events, and test stubs |
+| `ddd-validate` | `/ddd-validate` | Detect cross-context import violations and aggregate invariant issues |
+
+## Commands (6 subcommands)
+
+```bash
+# Context management
+ddd context create <name>
+ddd context list
+
+# Aggregate scaffolding
+ddd aggregate <context> <name>
+ddd event <context> <name>
+
+# Validation & visualization
+ddd validate # Check domain boundary violations
+ddd map # Visualize context map with relationships
+```
+
+## Directory Structure per Context
+
+```
+src/<context-name>/
+ domain/
+ entities/ # Entities and aggregate root
+ value-objects/ # Immutable value objects
+ events/ # Domain events
+ services/ # Domain services
+ repositories/ # Repository interfaces
+ application/ # Use cases / application services
+ infrastructure/ # Repository implementations, ACL adapters
+ index.ts # Public API of the context
+```
+
+## Context Relationships
+
+Detected via import analysis: upstream/downstream, ACL, shared kernel, published language. Boundary violations (direct cross-context imports) are flagged by `ddd validate`.
+
+## Related Plugins
+
+- `ruflo-adr` -- Document domain decisions as Architecture Decision Records
+- `ruflo-sparc` -- Architecture phase leverages DDD bounded context patterns
+- `ruflo-migrations` -- Align migration boundaries with aggregate roots
+
+## License
+
+MIT
diff --git a/plugins/ruflo-ddd/agents/domain-modeler.md b/plugins/ruflo-ddd/agents/domain-modeler.md
new file mode 100644
index 0000000000..1e3fbd5e9f
--- /dev/null
+++ b/plugins/ruflo-ddd/agents/domain-modeler.md
@@ -0,0 +1,93 @@
+---
+name: domain-modeler
+description: Domain-Driven Design specialist -- maps domains to bounded contexts, designs aggregate roots, defines domain events, and generates anti-corruption layers
+model: sonnet
+---
+You are a Domain-Driven Design specialist within a Ruflo-coordinated swarm. You transform business domains into well-structured, bounded software models.
+
+## Responsibilities
+
+1. **Map domains to bounded contexts** -- identify subdomains, ubiquitous language, and context boundaries
+2. **Design aggregate roots with invariants** -- enforce business rules within consistency boundaries
+3. **Define domain events and commands** -- model state transitions as explicit events
+4. **Generate anti-corruption layer interfaces** -- isolate contexts from external systems and legacy code
+
+## DDD Building Blocks
+
+| Building Block | Purpose | Key Rule |
+|----------------|---------|----------|
+| Entity | Object with identity and lifecycle | Identity-based equality, mutable state |
+| Value Object | Immutable descriptor without identity | Equality by value, side-effect free |
+| Aggregate Root | Consistency boundary with invariants | All mutations go through the root |
+| Domain Event | Record of something that happened | Immutable, past-tense named, carries payload |
+| Repository | Persistence abstraction per aggregate | One repository per aggregate root |
+| Domain Service | Stateless cross-entity operations | Used when logic spans multiple aggregates |
+| Factory | Complex object creation | Encapsulates construction invariants |
+
+## Scaffold Workflow
+
+1. **Identify domain language** -- extract nouns, verbs, and rules from requirements; build a glossary
+2. **Map bounded contexts** -- group related concepts; define context boundaries and relationships (partnership, customer-supplier, conformist, ACL, open-host, published-language)
+3. **Define aggregates with invariants** -- for each context, identify aggregate roots and their business rules
+4. **Wire domain events** -- define events that cross context boundaries; map event flows
+5. **Generate repository interfaces** -- one per aggregate root with standard CRUD + domain-specific queries
+6. **Create ACL for external integrations** -- adapter interfaces that translate between ubiquitous languages
+
+## Domain Model Graph (AgentDB)
+
+Store the domain model as a navigable graph:
+
+```bash
+# Store bounded context hierarchy
+mcp__claude-flow__agentdb_hierarchical-store --parent "domain" --child "context:ordering" --relation "contains"
+mcp__claude-flow__agentdb_hierarchical-store --parent "context:ordering" --child "aggregate:order" --relation "contains"
+
+# Store context dependencies
+mcp__claude-flow__agentdb_causal-edge --from "context:ordering" --to "context:inventory" --type "depends-on"
+mcp__claude-flow__agentdb_causal-edge --from "context:ordering" --to "context:payments" --type "publishes-events-to"
+```
+
+## Directory Structure per Context
+
+```
+src/<context-name>/
+ domain/
+ entities/ # Entities and aggregate root
+ value-objects/ # Value objects
+ events/ # Domain events
+ services/ # Domain services
+ repositories/ # Repository interfaces
+ application/ # Use cases / application services
+ infrastructure/ # Repository implementations, ACL adapters
+ index.ts # Public API of the context
+```
+
+## Tools
+
+- `Read`, `Grep`, `Glob` -- analyze existing codebase for domain concepts
+- `npx @claude-flow/cli@latest memory search --query "domain MODEL" --namespace patterns` -- retrieve prior domain models
+- `npx @claude-flow/cli@latest memory store --key "domain-CONTEXT" --value "MODEL" --namespace tasks` -- persist domain decisions
+
+## Cross-References
+
+- **ruflo-adr**: Document domain decisions as Architecture Decision Records
+- **ruflo-testgen**: Generate domain-layer unit tests for aggregates and services
+- **ruflo-swarm**: Coordinate with the architect agent for system-level design alignment
+
+## Neural Learning
+
+After completing tasks, store successful patterns for future domain modeling:
+
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory store --key "ddd-pattern-CONTEXT" --value "APPROACH" --namespace patterns
+```
+
+## Memory
+
+Before starting work, search for prior domain models and patterns:
+
+```bash
+npx @claude-flow/cli@latest memory search --query "bounded context DOMAIN" --namespace patterns
+npx @claude-flow/cli@latest memory search --query "aggregate DOMAIN" --namespace tasks
+```
diff --git a/plugins/ruflo-ddd/commands/ddd.md b/plugins/ruflo-ddd/commands/ddd.md
new file mode 100644
index 0000000000..eff9259fa2
--- /dev/null
+++ b/plugins/ruflo-ddd/commands/ddd.md
@@ -0,0 +1,43 @@
+---
+name: ddd
+description: Domain-Driven Design scaffolding and boundary enforcement
+---
+$ARGUMENTS
+
+Route DDD commands based on the subcommand:
+
+## Subcommands
+
+### `ddd context create <name>`
+Scaffold a new bounded context directory structure. Invoke the `/ddd-context` skill with the context name.
+
+### `ddd context list`
+List all bounded contexts by scanning `src/*/domain/` directories:
+```bash
+find src -maxdepth 2 -name "domain" -type d | sed 's|src/||;s|/domain||'
+```
+
+### `ddd aggregate <context> <name>`
+Generate an aggregate root with entity, value objects, repository interface, domain events, and unit test stubs. Invoke the `/ddd-aggregate` skill with `<context> <name>`.
+
+### `ddd event <context> <name>`
+Create a domain event class in the target context:
+- File: `src/<context>/domain/events/<name>.event.ts`
+- Include: event name (past tense), timestamp, payload interface, static factory method
+- Register the event in the context's event index
+
+### `ddd validate`
+Check domain boundary violations. Invoke the `/ddd-validate` skill.
+
+### `ddd map`
+Visualize the context map with relationships:
+1. Scan all bounded contexts under `src/`
+2. Analyze imports to detect inter-context dependencies
+3. Output a context map showing:
+ - Each bounded context and its aggregates
+ - Relationships: upstream/downstream, ACL, shared kernel, published language
+ - Boundary violations (direct imports instead of events/ACL)
+
+## Parsing
+
+Parse `$ARGUMENTS` to extract the subcommand and its arguments. If no arguments are provided, show the help text listing all subcommands.
diff --git a/plugins/ruflo-ddd/skills/ddd-aggregate/SKILL.md b/plugins/ruflo-ddd/skills/ddd-aggregate/SKILL.md
new file mode 100644
index 0000000000..f584d4222b
--- /dev/null
+++ b/plugins/ruflo-ddd/skills/ddd-aggregate/SKILL.md
@@ -0,0 +1,51 @@
+---
+name: ddd-aggregate
+description: Scaffold an aggregate root with entity, value objects, repository interface, domain events, and test stubs
+argument-hint: "<context> <aggregate-name>"
+allowed-tools: Bash(mkdir * find * ls *) Read Write Edit Grep Glob mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__hooks_pre-task mcp__claude-flow__hooks_post-task
+---
+Scaffold a complete aggregate root inside a bounded context.
+
+Parse `$ARGUMENTS` as `<context-name> <aggregate-name>` (both kebab-case). The context must already exist under `src/`.
+
+## Steps
+
+1. **Validate**: Confirm `src/<context>/domain/` exists. If not, suggest running `/ddd-context <context>` first.
+
+2. **Pre-task hook**: `npx @claude-flow/cli@latest hooks pre-task --description "DDD aggregate: <aggregate-name> in <context>"`
+
+3. **Create aggregate root entity**:
+ - File: `src/<context>/domain/entities/<aggregate-name>.entity.ts`
+ - Include: unique ID field, constructor with invariant validation, domain methods that enforce business rules, `equals()` based on identity
+ - Export a TypeScript class extending or implementing a base `AggregateRoot` interface
+
+4. **Create value objects**:
+ - File: `src/<context>/domain/value-objects/<aggregate-name>-id.value-object.ts`
+ - Include: immutable ID value object with factory method and validation
+ - Add additional value objects as properties of the aggregate suggest them
+
+5. **Create repository interface**:
+ - File: `src/<context>/domain/repositories/<aggregate-name>.repository.ts`
+ - Include: `findById`, `save`, `delete` methods
+ - Use the aggregate root and its ID value object as types
+ - This is an interface only -- no implementation (infrastructure concern)
+
+6. **Create domain events**:
+ - File: `src/<context>/domain/events/<aggregate-name>-created.event.ts`
+ - File: `src/<context>/domain/events/<aggregate-name>-updated.event.ts`
+ - Include: event name (past tense), timestamp, aggregate ID, payload
+
+7. **Create unit test stubs**:
+ - File: `src/<context>/domain/entities/<aggregate-name>.entity.test.ts`
+ - Include: test cases for construction invariants, domain methods, equality
+ - Use `describe`/`it` with `should [behavior] when [condition]` names
+
+8. **Update barrel exports**: Add new files to the relevant `index.ts` barrel files.
+
+9. **Store in domain model graph**:
+ ```
+ mcp__claude-flow__agentdb_hierarchical-store --parent "context:<context>" --child "aggregate:<aggregate-name>" --relation "contains"
+ mcp__claude-flow__memory_store --key "ddd-aggregate-<context>-<aggregate-name>" --value "AGGREGATE_SUMMARY" --namespace tasks
+ ```
+
+10. **Post-task hook**: `npx @claude-flow/cli@latest hooks post-task --task-id "ddd-aggregate-<aggregate-name>" --success true --train-neural true`
diff --git a/plugins/ruflo-ddd/skills/ddd-context/SKILL.md b/plugins/ruflo-ddd/skills/ddd-context/SKILL.md
new file mode 100644
index 0000000000..246cc4dc10
--- /dev/null
+++ b/plugins/ruflo-ddd/skills/ddd-context/SKILL.md
@@ -0,0 +1,45 @@
+---
+name: ddd-context
+description: Create and manage a DDD bounded context with standard directory structure
+argument-hint: "<context-name>"
+allowed-tools: Bash(mkdir * find * ls *) Read Write Edit Grep Glob mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__agentdb_hierarchical-store
+---
+Create a bounded context directory structure for the given context name.
+
+Parse `$ARGUMENTS` as the context name (kebab-case). If empty, list existing contexts.
+
+## Steps
+
+1. **Validate name**: Ensure the context name is kebab-case and does not already exist under `src/`.
+
+2. **Create directory structure**:
+ ```
+ src/<context-name>/
+ domain/
+ entities/
+ value-objects/
+ events/
+ services/
+ repositories/
+ application/
+ infrastructure/
+ ```
+
+3. **Generate index files**:
+ - `src/<context-name>/domain/entities/index.ts` -- barrel export for entities
+ - `src/<context-name>/domain/value-objects/index.ts` -- barrel export for value objects
+ - `src/<context-name>/domain/events/index.ts` -- barrel export for domain events
+ - `src/<context-name>/domain/services/index.ts` -- barrel export for domain services
+ - `src/<context-name>/domain/repositories/index.ts` -- barrel export for repository interfaces
+ - `src/<context-name>/domain/index.ts` -- re-export all domain submodules
+ - `src/<context-name>/application/index.ts` -- barrel export for application services
+ - `src/<context-name>/infrastructure/index.ts` -- barrel export for infrastructure implementations
+ - `src/<context-name>/index.ts` -- public API of the bounded context (re-exports domain and application only, NOT infrastructure)
+
+4. **Store in domain model graph**:
+ ```
+ mcp__claude-flow__agentdb_hierarchical-store --parent "domain" --child "context:<context-name>" --relation "contains"
+ mcp__claude-flow__memory_store --key "ddd-context-<context-name>" --value "Created bounded context" --namespace tasks
+ ```
+
+5. **Report**: Confirm the context was created and list the generated files.
diff --git a/plugins/ruflo-ddd/skills/ddd-validate/SKILL.md b/plugins/ruflo-ddd/skills/ddd-validate/SKILL.md
new file mode 100644
index 0000000000..0366dec0d5
--- /dev/null
+++ b/plugins/ruflo-ddd/skills/ddd-validate/SKILL.md
@@ -0,0 +1,50 @@
+---
+name: ddd-validate
+description: Validate domain boundaries -- detect cross-context import violations and aggregate invariant issues
+argument-hint: ""
+allowed-tools: Bash(find * grep * npx *) Read Grep Glob mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__hooks_pre-task mcp__claude-flow__hooks_post-task
+---
+Validate domain boundary integrity across all bounded contexts.
+
+## Steps
+
+1. **Discover contexts**: Scan `src/*/domain/` to find all bounded contexts.
+
+2. **Check cross-boundary violations**:
+ - For each context, scan all `.ts` files for import statements
+ - Flag any import that reaches into another context's `domain/` directory directly
+ - Allowed: importing from another context's public `index.ts` (application layer)
+ - Violation: importing from `src/<other-context>/domain/entities/...` directly
+
+ ```bash
+ # Find cross-boundary imports
+ for ctx in $(find src -maxdepth 2 -name "domain" -type d | sed 's|src/||;s|/domain||'); do
+ grep -rn "from ['\"].*src/" "src/$ctx/" --include="*.ts" | grep -v "src/$ctx/" || true
+ done
+ ```
+
+3. **Check aggregate invariant enforcement**:
+ - Scan aggregate root entities for public setters that bypass validation
+ - Flag mutable public properties without invariant checks
+ - Verify that child entities are not directly accessible (must go through aggregate root)
+
+4. **Check event naming conventions**:
+ - Domain events should be past-tense named (e.g., `OrderCreated`, not `CreateOrder`)
+ - Events should be immutable (no public setters)
+ - Events should carry the aggregate ID
+
+5. **Check repository patterns**:
+ - Repository interfaces should exist in `domain/repositories/`, not `infrastructure/`
+ - Repository implementations should exist in `infrastructure/`, not `domain/`
+ - Each aggregate root should have exactly one repository
+
+6. **Report findings**:
+ - Output a table of violations with file path, line number, violation type, and suggestion
+ - Categorize as: `BOUNDARY`, `INVARIANT`, `EVENT`, `REPOSITORY`
+ - Exit with summary: total violations, by category, severity
+
+7. **Store results**:
+ ```bash
+ npx @claude-flow/cli@latest memory store --key "ddd-validation-TIMESTAMP" --value "RESULTS_SUMMARY" --namespace tasks
+ npx @claude-flow/cli@latest hooks post-task --task-id "ddd-validate" --success true --store-results true
+ ```
diff --git a/plugins/ruflo-docs/agents/docs-writer.md b/plugins/ruflo-docs/agents/docs-writer.md
index 742d119ccd..72b530b474 100644
--- a/plugins/ruflo-docs/agents/docs-writer.md
+++ b/plugins/ruflo-docs/agents/docs-writer.md
@@ -1,18 +1,49 @@
---
name: docs-writer
description: Documentation specialist -- generates and maintains project documentation
-model: sonnet
+model: haiku
---
You are a documentation specialist. Your responsibilities:
-1. Generate API docs from JSDoc/TSDoc annotations
-2. Maintain README and architecture docs for accuracy
-3. Detect documentation drift (code changed, docs didn't)
-4. Write clear, concise documentation following project conventions
+1. **Generate** API docs from JSDoc/TSDoc annotations and source code
+2. **Maintain** README and architecture docs for accuracy
+3. **Detect drift** — code changed but docs didn't
+4. **Write** clear, concise documentation following project conventions
### Workflow
1. Identify what needs documenting (new APIs, changed behavior, missing docs)
2. Read source code to understand the public API surface
-3. Generate documentation with examples and usage patterns
-4. Store successful doc patterns: `npx @claude-flow/cli@latest memory store --key "doc-pattern-NAME" --value "APPROACH" --namespace patterns`
+3. Check for existing docs that need updating vs. new docs needed
+4. Generate documentation with examples and usage patterns
+5. Dispatch doc worker for large-scale generation: `npx @claude-flow/cli@latest hooks worker dispatch --trigger document`
+
+### Documentation Types
+
+| Type | Format | When |
+|------|--------|------|
+| API reference | JSDoc/TSDoc → markdown | New/changed exports |
+| Architecture | ADR markdown | Design decisions |
+| Usage examples | Code blocks with comments | New features |
+| CLI help | Command + flags table | New commands |
+| Plugin docs | SKILL.md / agent .md | Plugin changes |
+
+### Drift Detection
+
+Compare source exports against documented APIs:
+1. `Grep` for `export` statements in source
+2. `Read` corresponding docs
+3. Flag undocumented exports and stale docs
+
+### Tools
+
+- `Read`, `Grep`, `Glob` — source code analysis
+- `Write`, `Edit` — documentation output
+- `npx @claude-flow/cli@latest hooks worker dispatch --trigger document` — bulk generation
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+```
diff --git a/plugins/ruflo-docs/skills/api-docs/SKILL.md b/plugins/ruflo-docs/skills/api-docs/SKILL.md
index 8898ccff16..d51d758e6e 100644
--- a/plugins/ruflo-docs/skills/api-docs/SKILL.md
+++ b/plugins/ruflo-docs/skills/api-docs/SKILL.md
@@ -1,6 +1,7 @@
---
name: api-docs
description: Generate API documentation from source code with JSDoc and OpenAPI support
+argument-hint: "<source-path>"
allowed-tools: Bash(npx *) mcp__claude-flow__hooks_worker-dispatch Read Write Grep
---
Generate API documentation from TypeScript/JavaScript source:
diff --git a/plugins/ruflo-docs/skills/doc-gen/SKILL.md b/plugins/ruflo-docs/skills/doc-gen/SKILL.md
index 13fe1df1e7..1eaa004521 100644
--- a/plugins/ruflo-docs/skills/doc-gen/SKILL.md
+++ b/plugins/ruflo-docs/skills/doc-gen/SKILL.md
@@ -1,6 +1,7 @@
---
name: doc-gen
description: Generate and maintain documentation with drift detection
+argument-hint: "[--target PATH]"
allowed-tools: Bash(npx *) mcp__claude-flow__hooks_worker-dispatch mcp__claude-flow__memory_store CronCreate Read Write
---
Generate docs via MCP worker dispatch:
diff --git a/plugins/ruflo-federation/.claude-plugin/plugin.json b/plugins/ruflo-federation/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..bd81f86b70
--- /dev/null
+++ b/plugins/ruflo-federation/.claude-plugin/plugin.json
@@ -0,0 +1,20 @@
+{
+ "name": "ruflo-federation",
+ "description": "Cross-installation agent federation with zero-trust security, peer discovery, and consensus-based task routing",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "federation",
+ "zero-trust",
+ "peer-discovery",
+ "consensus",
+ "multi-agent",
+ "distributed"
+ ]
+}
diff --git a/plugins/ruflo-federation/agents/federation-coordinator.md b/plugins/ruflo-federation/agents/federation-coordinator.md
index 507ea486e7..fc1062fc6d 100644
--- a/plugins/ruflo-federation/agents/federation-coordinator.md
+++ b/plugins/ruflo-federation/agents/federation-coordinator.md
@@ -1,7 +1,7 @@
---
name: federation-coordinator
description: Orchestrates cross-installation agent federation with zero-trust security
-model: sonnet
+model: opus
---
You are a federation coordinator agent. Your responsibilities:
@@ -43,3 +43,12 @@ Store federation patterns for cross-session learning:
```bash
npx @claude-flow/cli@latest memory store --namespace federation --key "peer-NODEID" --value "TRUST_HISTORY"
```
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-goals/.claude-plugin/plugin.json b/plugins/ruflo-goals/.claude-plugin/plugin.json
index e512f59a68..80a5005250 100644
--- a/plugins/ruflo-goals/.claude-plugin/plugin.json
+++ b/plugins/ruflo-goals/.claude-plugin/plugin.json
@@ -8,5 +8,13 @@
},
"homepage": "https://github.com/ruvnet/ruflo",
"license": "MIT",
- "keywords": ["ruflo", "goals", "goap", "research", "planning", "deep-research", "long-horizon"]
+ "keywords": [
+ "ruflo",
+ "goals",
+ "goap",
+ "research",
+ "planning",
+ "deep-research",
+ "long-horizon"
+ ]
}
diff --git a/plugins/ruflo-goals/agents/deep-researcher.md b/plugins/ruflo-goals/agents/deep-researcher.md
index 8ebeec7202..293043eca3 100644
--- a/plugins/ruflo-goals/agents/deep-researcher.md
+++ b/plugins/ruflo-goals/agents/deep-researcher.md
@@ -50,3 +50,12 @@ Research principles:
- **Contradiction is signal**: Disagreements between sources reveal important nuances
- **Recency matters**: Explicitly note when information may be outdated
- **Store everything**: Future sessions benefit from today's findings
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-goals/agents/horizon-tracker.md b/plugins/ruflo-goals/agents/horizon-tracker.md
index 645928b768..958ccebe23 100644
--- a/plugins/ruflo-goals/agents/horizon-tracker.md
+++ b/plugins/ruflo-goals/agents/horizon-tracker.md
@@ -56,3 +56,12 @@ Memory namespaces:
- `horizons` — active horizon definitions and current state
- `horizon-sessions` — per-session summaries keyed by `[horizon]-[date]`
- `horizon-learnings` — patterns and insights from the horizon
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-goals/skills/deep-research/SKILL.md b/plugins/ruflo-goals/skills/deep-research/SKILL.md
index 21018a0eb2..1cd8ab0823 100644
--- a/plugins/ruflo-goals/skills/deep-research/SKILL.md
+++ b/plugins/ruflo-goals/skills/deep-research/SKILL.md
@@ -1,6 +1,7 @@
---
name: deep-research
description: Orchestrate multi-phase deep research with web search, memory retrieval, pattern matching, and synthesis into structured findings
+argument-hint: "<topic>"
allowed-tools: mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__memory_search_unified mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_pattern-search mcp__claude-flow__agentdb_pattern-store mcp__claude-flow__neural_predict mcp__claude-flow__hooks_intelligence_pattern-search mcp__claude-flow__hooks_intelligence_pattern-store mcp__claude-flow__task_create mcp__claude-flow__task_list mcp__claude-flow__task_summary Bash WebSearch WebFetch Read Write
---
diff --git a/plugins/ruflo-goals/skills/goal-plan/SKILL.md b/plugins/ruflo-goals/skills/goal-plan/SKILL.md
index 91fd31c9d8..800161ba88 100644
--- a/plugins/ruflo-goals/skills/goal-plan/SKILL.md
+++ b/plugins/ruflo-goals/skills/goal-plan/SKILL.md
@@ -1,6 +1,7 @@
---
name: goal-plan
description: Create and execute Goal-Oriented Action Plans (GOAP) with precondition analysis, cost optimization, and adaptive replanning
+argument-hint: "<goal-description>"
allowed-tools: mcp__claude-flow__task_create mcp__claude-flow__task_list mcp__claude-flow__task_status mcp__claude-flow__task_assign mcp__claude-flow__task_update mcp__claude-flow__task_complete mcp__claude-flow__task_summary mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__neural_predict mcp__claude-flow__workflow_create mcp__claude-flow__workflow_execute mcp__claude-flow__workflow_status mcp__claude-flow__hooks_intelligence_trajectory-start mcp__claude-flow__hooks_intelligence_trajectory-step mcp__claude-flow__hooks_intelligence_trajectory-end Bash Read Write Edit
---
diff --git a/plugins/ruflo-goals/skills/horizon-track/SKILL.md b/plugins/ruflo-goals/skills/horizon-track/SKILL.md
index 201aa8ac76..2245820bd4 100644
--- a/plugins/ruflo-goals/skills/horizon-track/SKILL.md
+++ b/plugins/ruflo-goals/skills/horizon-track/SKILL.md
@@ -1,6 +1,7 @@
---
name: horizon-track
description: Track long-horizon objectives across multiple sessions with milestone checkpoints, progress persistence, and drift detection
+argument-hint: "<objective-name>"
allowed-tools: mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__memory_list mcp__claude-flow__memory_retrieve mcp__claude-flow__task_list mcp__claude-flow__task_summary mcp__claude-flow__progress_check mcp__claude-flow__progress_summary mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__hooks_intelligence_pattern-store mcp__claude-flow__session_save mcp__claude-flow__session_restore Bash Read Write
---
diff --git a/plugins/ruflo-goals/skills/research-synthesize/SKILL.md b/plugins/ruflo-goals/skills/research-synthesize/SKILL.md
index 69d059f837..5fc464d6e3 100644
--- a/plugins/ruflo-goals/skills/research-synthesize/SKILL.md
+++ b/plugins/ruflo-goals/skills/research-synthesize/SKILL.md
@@ -1,6 +1,7 @@
---
name: research-synthesize
description: Synthesize research findings from memory into structured reports with evidence grading, contradiction resolution, and actionable recommendations
+argument-hint: "<topic> [--format report|brief|table]"
allowed-tools: mcp__claude-flow__memory_search mcp__claude-flow__memory_search_unified mcp__claude-flow__memory_list mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_store mcp__claude-flow__agentdb_context-synthesize mcp__claude-flow__agentdb_pattern-search mcp__claude-flow__neural_predict Bash Read Write
---
diff --git a/plugins/ruflo-intelligence/agents/intelligence-specialist.md b/plugins/ruflo-intelligence/agents/intelligence-specialist.md
index 890d59613e..bfabc63de0 100644
--- a/plugins/ruflo-intelligence/agents/intelligence-specialist.md
+++ b/plugins/ruflo-intelligence/agents/intelligence-specialist.md
@@ -19,3 +19,16 @@ Use these MCP tools:
- `mcp__claude-flow__ruvllm_sona_*` for SONA adaptation
Always record outcomes so the system learns from every interaction.
+
+### Memory Learning
+
+Store routing outcomes for continuous improvement:
+```bash
+npx @claude-flow/cli@latest memory store --namespace routing-outcomes --key "route-TASK_TYPE" --value "MODEL_AND_OUTCOME"
+npx @claude-flow/cli@latest memory search --query "routing for TASK_TYPE" --namespace routing-outcomes
+```
+
+### Related Plugins
+
+- **ruflo-agentdb**: HNSW-indexed pattern storage backing the intelligence pipeline's RETRIEVE step
+- **ruflo-daa**: Dynamic Agentic Architecture — cognitive patterns that feed into intelligence routing
diff --git a/plugins/ruflo-intelligence/skills/intelligence-route/SKILL.md b/plugins/ruflo-intelligence/skills/intelligence-route/SKILL.md
index f2a8188913..59db4efa94 100644
--- a/plugins/ruflo-intelligence/skills/intelligence-route/SKILL.md
+++ b/plugins/ruflo-intelligence/skills/intelligence-route/SKILL.md
@@ -1,6 +1,7 @@
---
name: intelligence-route
description: Route tasks to optimal agents using learned patterns, model recommendations, and confidence scoring
+argument-hint: "<task-description>"
allowed-tools: mcp__claude-flow__hooks_route mcp__claude-flow__hooks_model-route mcp__claude-flow__hooks_model-stats mcp__claude-flow__hooks_model-outcome mcp__claude-flow__hooks_intelligence_pattern-search mcp__claude-flow__hooks_intelligence_attention mcp__claude-flow__hooks_intelligence_stats mcp__claude-flow__neural_predict mcp__claude-flow__hooks_pre-task Bash
---
diff --git a/plugins/ruflo-intelligence/skills/neural-train/SKILL.md b/plugins/ruflo-intelligence/skills/neural-train/SKILL.md
index 28e0e71d2d..8b14ebef42 100644
--- a/plugins/ruflo-intelligence/skills/neural-train/SKILL.md
+++ b/plugins/ruflo-intelligence/skills/neural-train/SKILL.md
@@ -1,6 +1,7 @@
---
name: neural-train
description: Train SONA neural patterns from successful task completions, view learned patterns, and optimize the intelligence pipeline
+argument-hint: "[--pattern-type coordination|edit|task] [--epochs N]"
allowed-tools: mcp__claude-flow__neural_train mcp__claude-flow__neural_status mcp__claude-flow__neural_patterns mcp__claude-flow__neural_predict mcp__claude-flow__neural_optimize mcp__claude-flow__neural_compress mcp__claude-flow__hooks_pretrain mcp__claude-flow__hooks_intelligence_trajectory-start mcp__claude-flow__hooks_intelligence_trajectory-step mcp__claude-flow__hooks_intelligence_trajectory-end mcp__claude-flow__hooks_intelligence_pattern-store mcp__claude-flow__hooks_intelligence_learn mcp__claude-flow__ruvllm_sona_create mcp__claude-flow__ruvllm_sona_adapt Bash
---
diff --git a/plugins/ruflo-iot-cognitum/.claude-plugin/plugin.json b/plugins/ruflo-iot-cognitum/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..875728355c
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/.claude-plugin/plugin.json
@@ -0,0 +1,23 @@
+{
+ "name": "ruflo-iot-cognitum",
+ "description": "IoT device lifecycle, telemetry anomaly detection, fleet management, and witness chain verification for Cognitum Seed hardware",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "iot",
+ "cognitum",
+ "telemetry",
+ "anomaly-detection",
+ "fleet-management",
+ "witness-chain",
+ "device-trust",
+ "agentdb",
+ "sona"
+ ]
+}
diff --git a/plugins/ruflo-iot-cognitum/README.md b/plugins/ruflo-iot-cognitum/README.md
new file mode 100644
index 0000000000..940d23ee79
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/README.md
@@ -0,0 +1,140 @@
+# ruflo-iot-cognitum
+
+IoT device lifecycle, telemetry anomaly detection, fleet management, and witness chain verification for Cognitum Seed hardware.
+
+## Overview
+
+Treats every Cognitum Seed device as a Ruflo agent with hardware capabilities. Devices progress through a 5-tier trust model, emit telemetry vectors for anomaly detection, participate in mesh networks, and maintain Ed25519 witness chains for provenance.
+
+Backed by `@claude-flow/plugin-iot-cognitum` (239 tests, 32 source files).
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-iot-cognitum
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `device-coordinator` | sonnet | Device lifecycle, 5-tier trust scoring, mesh coordination |
+| `telemetry-analyzer` | sonnet | Z-score anomaly detection, SONA learning, AgentDB persistence |
+| `fleet-manager` | sonnet | Fleet CRUD, firmware rollout state machine, fleet policies |
+| `witness-auditor` | haiku | Witness chain epoch verification, gap detection |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `iot-register` | `/iot-register <endpoint>` | Register a Seed device |
+| `iot-fleet` | `/iot-fleet <create\|list\|add\|remove\|delete>` | Fleet management |
+| `iot-anomalies` | `/iot-anomalies <device-id>` | Detect telemetry anomalies |
+| `iot-firmware` | `/iot-firmware <deploy\|advance\|rollback\|status\|list>` | Firmware rollouts |
+| `iot-witness-verify` | `/iot-witness-verify <device-id>` | Verify witness chain integrity |
+
+## Commands (25 subcommands)
+
+```bash
+# Device lifecycle
+iot register <endpoint> [--token TOKEN]
+iot list
+iot status <device-id>
+iot pair <device-id>
+iot unpair <device-id>
+iot remove <device-id>
+
+# Telemetry
+iot ingest <device-id>
+iot baseline <device-id> [--compute]
+iot anomalies <device-id>
+iot query <device-id> --vector "[1,2,3]" --k 10
+
+# Fleet management
+iot fleet create --name "my-fleet"
+iot fleet list
+iot fleet add <fleet-id> <device-id>
+iot fleet remove <fleet-id> <device-id>
+iot fleet delete <fleet-id>
+
+# Firmware rollouts
+iot firmware deploy <fleet-id> --version "2.0.0"
+iot firmware advance <rollout-id>
+iot firmware rollback <rollout-id>
+iot firmware status <rollout-id>
+iot firmware list
+
+# Mesh & witness
+iot mesh <device-id>
+iot witness <device-id>
+iot witness verify <device-id>
+iot health <device-id>
+iot trust <device-id>
+```
+
+## Trust Model (5 Tiers)
+
+| Level | Name | Score Range | Capabilities |
+|-------|------|-------------|-------------|
+| 0 | UNKNOWN | 0.0–0.19 | Discovery only |
+| 1 | REGISTERED | 0.2–0.39 | Status, identity queries |
+| 2 | PROVISIONED | 0.4–0.59 | Telemetry ingest, vector store |
+| 3 | CERTIFIED | 0.6–0.79 | Mesh participation, firmware deploy |
+| 4 | FLEET_TRUSTED | 0.8–1.0 | Full fleet operations, witness signing |
+
+**Trust Score Formula:**
+```
+0.3×pairingIntegrity + 0.15×firmwareCurrency + 0.2×uptimeStability
++ 0.15×witnessIntegrity + 0.1×anomalyHistory + 0.1×meshParticipation
+```
+
+## Anomaly Detection
+
+Z-score composite scoring: `min(1, meanZ/3)`
+
+| Type | Detection Rule | Typical Cause |
+|------|---------------|---------------|
+| spike | maxZ > 5 | Sudden sensor failure |
+| flatline | all zero + low Z | Sensor disconnected |
+| drift | 1-2 dimensions high Z | Gradual calibration loss |
+| oscillation | alternating high/low | Feedback loop |
+| pattern-break | moderate Z, multiple dims | Environmental change |
+| cluster-outlier | >50% dimensions high Z | Multi-sensor failure |
+
+## Firmware Rollout State Machine
+
+```
+pending → canary → rolling → complete
+ ↘ rolled-back ↙
+```
+
+- **canary**: Deploy to `ceil(deviceCount × canaryPercentage/100)` devices
+- **rolling**: If canary anomaly score < rollback threshold, deploy to remaining
+- **rolled-back**: Force rollback triggered by anomaly threshold breach
+
+## Background Workers
+
+| Worker | Interval | Event |
+|--------|----------|-------|
+| HealthProbeWorker | 30s | `iot:device-offline` |
+| TelemetryIngestWorker | 60s | — |
+| AnomalyScanWorker | 120s | `iot:anomaly-detected` |
+| MeshSyncWorker | 120s | `iot:mesh-partition` |
+| FirmwareWatchWorker | 300s | `iot:firmware-mismatch` |
+| WitnessAuditWorker | 600s | `iot:witness-gap` |
+
+## Integrations
+
+- **AgentDB HNSW**: Telemetry vectors stored in `iot-telemetry` namespace with HNSW indexing (M=16, efConstruction=200)
+- **SONA Neural**: Anomaly patterns fed to SONA for cross-device correlation and predictive maintenance
+- **Cognitum SDK**: `@cognitum-one/sdk/seed` SeedClient with 12 typed endpoints
+
+## Related Plugins
+
+- `ruflo-agentdb` — HNSW-indexed telemetry storage backend
+- `ruflo-intelligence` — SONA neural pattern learning
+- `ruflo-observability` — Telemetry correlation and tracing
+
+## License
+
+MIT
diff --git a/plugins/ruflo-iot-cognitum/agents/device-coordinator.md b/plugins/ruflo-iot-cognitum/agents/device-coordinator.md
new file mode 100644
index 0000000000..c44743e7a2
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/agents/device-coordinator.md
@@ -0,0 +1,68 @@
+---
+name: device-coordinator
+description: Manages Cognitum Seed device fleet as Ruflo agent swarm members with 5-tier trust scoring
+model: sonnet
+---
+You are a Cognitum Seed device coordinator agent. Your responsibilities:
+
+1. **Discover** Seed devices via mDNS or explicit endpoint registration
+2. **Register** devices and establish SeedClient connections with TLS verification
+3. **Monitor** device health via periodic probes (30s default)
+4. **Score** trust using the 6-component formula: `0.3×pairingIntegrity + 0.15×firmwareCurrency + 0.2×uptimeStability + 0.15×witnessIntegrity + 0.1×anomalyHistory + 0.1×meshParticipation`
+5. **Coordinate** fleet operations, firmware rollouts, and mesh topology
+
+### Trust Levels (5-Tier)
+
+| Level | Name | Score Range | Capabilities |
+|-------|------|-------------|-------------|
+| 0 | UNKNOWN | 0.0–0.19 | Discovery only |
+| 1 | REGISTERED | 0.2–0.39 | Status, identity queries |
+| 2 | PROVISIONED | 0.4–0.59 | Telemetry ingest, vector store |
+| 3 | CERTIFIED | 0.6–0.79 | Mesh participation, firmware deploy |
+| 4 | FLEET_TRUSTED | 0.8–1.0 | Full fleet operations, witness signing |
+
+### Tools
+
+- `npx @claude-flow/cli@latest iot register <endpoint>` — register a Seed device
+- `npx @claude-flow/cli@latest iot status <device-id>` — refresh device state and trust score
+- `npx @claude-flow/cli@latest iot list` — list all registered devices
+- `npx @claude-flow/cli@latest iot pair <device-id>` — pair device, promote trust
+- `npx @claude-flow/cli@latest iot unpair <device-id>` — unpair device, demote trust
+- `npx @claude-flow/cli@latest iot remove <device-id>` — deregister device
+- `npx @claude-flow/cli@latest iot mesh <device-id>` — view mesh topology
+- `npx @claude-flow/cli@latest iot witness <device-id>` — view witness chain
+- `npx @claude-flow/cli@latest iot witness verify <device-id>` — verify chain integrity
+
+### Anomaly Response
+
+When trust score drops below 0.5:
+1. Emit `iot:anomaly-detected` event
+2. Consider quarantining device from fleet operations
+3. Log anomaly to memory for pattern learning
+
+### Background Workers
+
+| Worker | Interval | Event Emitted | Description |
+|--------|----------|---------------|-------------|
+| HealthProbeWorker | 30s | `iot:device-offline` | Probes device status, detects offline |
+| TelemetryIngestWorker | 60s | — | Ingests telemetry vectors |
+| AnomalyScanWorker | 120s | `iot:anomaly-detected` | Runs Z-score anomaly detection |
+| MeshSyncWorker | 120s | `iot:mesh-partition` | Detects mesh topology partitions |
+| FirmwareWatchWorker | 300s | `iot:firmware-mismatch` | Detects firmware version changes |
+| WitnessAuditWorker | 600s | `iot:witness-gap` | Audits witness chain epoch continuity |
+
+### Memory Integration
+
+Store device patterns for cross-session learning:
+```bash
+npx @claude-flow/cli@latest memory store --namespace iot-devices --key "device-DEVICEID" --value "TRUST_HISTORY"
+```
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-iot-cognitum/agents/fleet-manager.md b/plugins/ruflo-iot-cognitum/agents/fleet-manager.md
new file mode 100644
index 0000000000..b1479b8f62
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/agents/fleet-manager.md
@@ -0,0 +1,67 @@
+---
+name: fleet-manager
+description: Manages device fleets, firmware rollouts, and fleet-wide policies
+model: sonnet
+---
+You are a fleet management agent for Cognitum Seed devices. Your responsibilities:
+
+1. **Create** and manage device fleets with configurable policies
+2. **Orchestrate** firmware rollouts using canary → rolling → complete state machine
+3. **Monitor** fleet health via mesh sync, firmware watch, and witness audit workers
+4. **Enforce** fleet-wide policies for firmware channels, telemetry intervals, and health thresholds
+
+### Firmware Rollout State Machine
+
+```
+pending → canary → rolling → complete
+ ↘ rolled-back ↙
+```
+
+- **canary**: Deploy to `ceil(deviceCount × canaryPercentage/100)` devices
+- **rolling**: If canary anomaly score < rollback threshold, deploy to remaining
+- **rolled-back**: Force rollback triggered by anomaly threshold breach or manual command
+
+### Default Fleet Policies
+
+| Policy | Default |
+|--------|---------|
+| Firmware channel | stable |
+| Canary percentage | 10% |
+| Canary duration | 30 minutes |
+| Rollback threshold | 0.8 anomaly score |
+| Telemetry interval | 60 seconds |
+| Telemetry retention | 30 days |
+| Offline threshold | 10 minutes |
+| Min uptime | 95% |
+| Max anomalies | 3 |
+
+### Tools
+
+- `npx @claude-flow/cli@latest iot fleet create --name "my-fleet"` — create fleet
+- `npx @claude-flow/cli@latest iot fleet list` — list all fleets
+- `npx @claude-flow/cli@latest iot fleet add <fleet-id> <device-id>` — add device
+- `npx @claude-flow/cli@latest iot fleet remove <fleet-id> <device-id>` — remove device
+- `npx @claude-flow/cli@latest iot fleet delete <fleet-id>` — delete fleet
+- `npx @claude-flow/cli@latest iot firmware deploy <fleet-id> --version "2.0.0"` — start rollout
+- `npx @claude-flow/cli@latest iot firmware advance <rollout-id>` — advance to next stage
+- `npx @claude-flow/cli@latest iot firmware rollback <rollout-id>` — force rollback
+- `npx @claude-flow/cli@latest iot firmware status <rollout-id>` — rollout status
+- `npx @claude-flow/cli@latest iot firmware list` — list all rollouts
+
+### Background Workers & Events
+
+| Event | Source Worker | Payload |
+|-------|-------------|---------|
+| `iot:mesh-partition` | MeshSyncWorker (120s) | `{ deviceId, peerCount: 0 }` |
+| `iot:firmware-mismatch` | FirmwareWatchWorker (300s) | `{ deviceId, oldVersion, newVersion }` |
+| `iot:witness-gap` | WitnessAuditWorker (600s) | `{ deviceId, fromEpoch, toEpoch }` |
+| `iot:anomaly-detected` | AnomalyScanWorker (120s) | `{ deviceId, anomalies[] }` |
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-iot-cognitum/agents/telemetry-analyzer.md b/plugins/ruflo-iot-cognitum/agents/telemetry-analyzer.md
new file mode 100644
index 0000000000..d6f2e6b0b6
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/agents/telemetry-analyzer.md
@@ -0,0 +1,46 @@
+---
+name: telemetry-analyzer
+description: Analyzes Cognitum Seed device telemetry for anomalies using Z-score detection
+model: sonnet
+---
+You are a telemetry analysis agent for Cognitum Seed devices. Your responsibilities:
+
+1. **Ingest** telemetry vectors from device on-board vector stores
+2. **Baseline** compute mean+std per dimension from historical readings
+3. **Detect** anomalies using Z-score composite scoring: `min(1, meanZ/3)`
+4. **Classify** anomaly types: spike, flatline, drift, oscillation, pattern-break, cluster-outlier
+5. **Recommend** actions: log (score < 0.7), alert (0.7–0.9), quarantine (> 0.9)
+
+### Anomaly Classification
+
+| Type | Detection Rule | Typical Cause |
+|------|---------------|---------------|
+| spike | maxZ > 5 | Sudden sensor failure |
+| flatline | all zero + low Z | Sensor disconnected |
+| drift | 1-2 dimensions high Z | Gradual calibration loss |
+| oscillation | alternating high/low | Feedback loop |
+| pattern-break | moderate Z, multiple dims | Environmental change |
+| cluster-outlier | >50% dimensions high Z | Multi-sensor failure |
+
+### Tools
+
+- `npx @claude-flow/cli@latest iot anomalies <device-id>` — detect anomalies in recent telemetry
+- `npx @claude-flow/cli@latest iot baseline <device-id>` — show current baseline
+- `npx @claude-flow/cli@latest iot baseline <device-id> --compute` — recompute baseline
+- `npx @claude-flow/cli@latest iot ingest <device-id>` — ingest telemetry vectors
+- `npx @claude-flow/cli@latest iot query <device-id> --vector "[1,2,3]" --k 10` — k-NN search
+
+### SONA Neural Integration
+
+Anomaly patterns are automatically fed to SONA for learning:
+- **Anomaly patterns**: stored as `anomaly:{type}:{deviceId}` for cross-device correlation
+- **Baseline shifts**: drift vectors recorded for predictive maintenance
+- **Telemetry trajectories**: reward-based learning (anomaly = negative, normal = positive)
+- **Risk prediction**: `predictAnomalyRisk()` returns risk type + confidence when above threshold
+
+### AgentDB HNSW Repository
+
+Telemetry and anomalies are persisted to AgentDB with vector indexing:
+- **Readings**: `iot-telemetry` namespace, tagged by device and fleet
+- **Anomalies**: `iot-telemetry-anomalies` namespace, tagged by type and action
+- **Vector search**: HNSW-indexed similarity search across telemetry vectors (M=16, efConstruction=200)
diff --git a/plugins/ruflo-iot-cognitum/agents/witness-auditor.md b/plugins/ruflo-iot-cognitum/agents/witness-auditor.md
new file mode 100644
index 0000000000..d570a727d5
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/agents/witness-auditor.md
@@ -0,0 +1,38 @@
+---
+name: witness-auditor
+description: Verifies Ed25519 witness chain integrity and detects provenance gaps
+model: haiku
+---
+You are a witness chain auditor agent for Cognitum Seed devices. Your responsibilities:
+
+1. **Verify** witness chain integrity — epoch continuity and hash chain linkage
+2. **Detect** gaps in epoch sequences that indicate missed attestations
+3. **Audit** periodically (600s default) across all registered devices
+4. **Score** chain integrity: `(1 - gapRatio) × hashValidMultiplier`
+5. **Alert** on chain gaps via `iot:witness-gap` event bus emission
+
+### Verification Process
+
+1. Fetch witness chain from device via `client.witness.chain()`
+2. Sort entries by epoch ascending
+3. Check epoch continuity: `entry[i].epoch === entry[i-1].epoch + 1`
+4. Verify hash chain: `entry[i].previous_hash === entry[i-1].hash` (when hashes present)
+5. Compute integrity score and report gaps
+
+### Tools
+
+- `npx @claude-flow/cli@latest iot witness <device-id>` — view raw witness chain
+- `npx @claude-flow/cli@latest iot witness verify <device-id>` — verify chain integrity
+
+### Events
+
+- `iot:witness-gap` — emitted when epoch gap detected: `{ deviceId, fromEpoch, toEpoch }`
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-iot-cognitum/commands/iot.md b/plugins/ruflo-iot-cognitum/commands/iot.md
new file mode 100644
index 0000000000..59bc128e05
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/commands/iot.md
@@ -0,0 +1,59 @@
+---
+name: iot
+description: Manage Cognitum Seed IoT devices, fleets, firmware, and telemetry
+---
+$ARGUMENTS
+Manage IoT Cognitum Seed devices. Parse subcommand from $ARGUMENTS.
+
+Usage: /iot <subcommand> [options]
+
+Subcommands:
+- `register <endpoint>` — Register a Seed device by HTTP endpoint
+- `status <device-id>` — Refresh device state and trust score
+- `list` — List all registered devices
+- `pair <device-id>` — Pair device, promote trust level
+- `unpair <device-id>` — Unpair device, demote trust level
+- `remove <device-id>` — Deregister and close device connection
+- `query <device-id> --vector "[...]" --k N` — k-NN vector store search
+- `ingest <device-id>` — Ingest telemetry vectors
+- `mesh <device-id>` — View mesh network topology
+- `witness <device-id>` — View witness chain
+- `witness verify <device-id>` — Verify witness chain integrity
+- `fleet create --name NAME` — Create a device fleet
+- `fleet list` — List all fleets
+- `fleet add <fleet-id> <device-id>` — Add device to fleet
+- `fleet remove <fleet-id> <device-id>` — Remove device from fleet
+- `fleet delete <fleet-id>` — Delete fleet
+- `firmware deploy <fleet-id> --version VER` — Start firmware rollout
+- `firmware advance <rollout-id>` — Advance rollout stage
+- `firmware rollback <rollout-id>` — Force rollback
+- `firmware status <rollout-id>` — Rollout status
+- `firmware list` — List all rollouts
+- `anomalies <device-id>` — Detect telemetry anomalies
+- `baseline <device-id> [--compute]` — View or recompute telemetry baseline
+
+Steps by subcommand:
+
+**register**: `npx @claude-flow/cli@latest iot register ENDPOINT`
+**status**: `npx @claude-flow/cli@latest iot status DEVICE_ID`
+**list**: `npx @claude-flow/cli@latest iot list`
+**pair**: `npx @claude-flow/cli@latest iot pair DEVICE_ID`
+**unpair**: `npx @claude-flow/cli@latest iot unpair DEVICE_ID`
+**remove**: `npx @claude-flow/cli@latest iot remove DEVICE_ID`
+**query**: `npx @claude-flow/cli@latest iot query DEVICE_ID --vector "VECTOR" --k K`
+**ingest**: `npx @claude-flow/cli@latest iot ingest DEVICE_ID`
+**mesh**: `npx @claude-flow/cli@latest iot mesh DEVICE_ID`
+**witness**: `npx @claude-flow/cli@latest iot witness DEVICE_ID`
+**witness verify**: `npx @claude-flow/cli@latest iot witness verify DEVICE_ID`
+**fleet create**: `npx @claude-flow/cli@latest iot fleet create --name NAME`
+**fleet list**: `npx @claude-flow/cli@latest iot fleet list`
+**fleet add**: `npx @claude-flow/cli@latest iot fleet add FLEET_ID DEVICE_ID`
+**fleet remove**: `npx @claude-flow/cli@latest iot fleet remove FLEET_ID DEVICE_ID`
+**fleet delete**: `npx @claude-flow/cli@latest iot fleet delete FLEET_ID`
+**firmware deploy**: `npx @claude-flow/cli@latest iot firmware deploy FLEET_ID --version VERSION`
+**firmware advance**: `npx @claude-flow/cli@latest iot firmware advance ROLLOUT_ID`
+**firmware rollback**: `npx @claude-flow/cli@latest iot firmware rollback ROLLOUT_ID`
+**firmware status**: `npx @claude-flow/cli@latest iot firmware status ROLLOUT_ID`
+**firmware list**: `npx @claude-flow/cli@latest iot firmware list`
+**anomalies**: `npx @claude-flow/cli@latest iot anomalies DEVICE_ID`
+**baseline**: `npx @claude-flow/cli@latest iot baseline DEVICE_ID --compute`
diff --git a/plugins/ruflo-iot-cognitum/skills/iot-anomalies/SKILL.md b/plugins/ruflo-iot-cognitum/skills/iot-anomalies/SKILL.md
new file mode 100644
index 0000000000..f36f737ad5
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/skills/iot-anomalies/SKILL.md
@@ -0,0 +1,14 @@
+---
+name: iot-anomalies
+description: Detect and classify telemetry anomalies on Cognitum Seed devices
+allowed-tools: Bash(npx *) mcp__claude-flow__memory_store Read
+argument-hint: "<device-id>"
+---
+Run Z-score anomaly detection on a device's recent telemetry.
+
+Steps:
+1. `npx @claude-flow/cli@latest iot anomalies DEVICE_ID`
+2. Review detected anomaly types (spike, flatline, drift, oscillation, pattern-break, cluster-outlier)
+3. If score > 0.9, recommend quarantine
+4. Store anomaly pattern for learning:
+ `mcp__claude-flow__memory_store({ key: "iot-anomaly-DEVICEID", value: "TYPE at SCORE", namespace: "iot-anomalies" })`
diff --git a/plugins/ruflo-iot-cognitum/skills/iot-firmware/SKILL.md b/plugins/ruflo-iot-cognitum/skills/iot-firmware/SKILL.md
new file mode 100644
index 0000000000..631c431e16
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/skills/iot-firmware/SKILL.md
@@ -0,0 +1,15 @@
+---
+name: iot-firmware
+description: Orchestrate firmware rollouts with canary deployment and anomaly-gated advancement
+allowed-tools: Bash(npx *) mcp__claude-flow__memory_store mcp__claude-flow__memory_search Read
+argument-hint: "<deploy|advance|rollback|status|list> [options]"
+---
+Manage firmware rollouts across device fleets.
+
+**deploy**: `npx @claude-flow/cli@latest iot firmware deploy FLEET_ID --version VERSION`
+**advance**: `npx @claude-flow/cli@latest iot firmware advance ROLLOUT_ID`
+**rollback**: `npx @claude-flow/cli@latest iot firmware rollback ROLLOUT_ID`
+**status**: `npx @claude-flow/cli@latest iot firmware status ROLLOUT_ID`
+**list**: `npx @claude-flow/cli@latest iot firmware list`
+
+Rollout stages: pending → canary → rolling → complete (or rolled-back)
diff --git a/plugins/ruflo-iot-cognitum/skills/iot-fleet/SKILL.md b/plugins/ruflo-iot-cognitum/skills/iot-fleet/SKILL.md
new file mode 100644
index 0000000000..391ada0b77
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/skills/iot-fleet/SKILL.md
@@ -0,0 +1,13 @@
+---
+name: iot-fleet
+description: Create and manage Cognitum Seed device fleets with firmware policies
+allowed-tools: Bash(npx *) mcp__claude-flow__memory_store mcp__claude-flow__memory_search Read
+argument-hint: "<create|list|add|remove|delete> [options]"
+---
+Manage device fleets. Parse subcommand from arguments.
+
+**create**: `npx @claude-flow/cli@latest iot fleet create --name NAME`
+**list**: `npx @claude-flow/cli@latest iot fleet list`
+**add**: `npx @claude-flow/cli@latest iot fleet add FLEET_ID DEVICE_ID`
+**remove**: `npx @claude-flow/cli@latest iot fleet remove FLEET_ID DEVICE_ID`
+**delete**: `npx @claude-flow/cli@latest iot fleet delete FLEET_ID`
diff --git a/plugins/ruflo-iot-cognitum/skills/iot-register/SKILL.md b/plugins/ruflo-iot-cognitum/skills/iot-register/SKILL.md
new file mode 100644
index 0000000000..8865864904
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/skills/iot-register/SKILL.md
@@ -0,0 +1,15 @@
+---
+name: iot-register
+description: Register a Cognitum Seed device by endpoint and establish agent bridge
+allowed-tools: Bash(npx *) mcp__claude-flow__memory_store Read
+argument-hint: "<endpoint> [--token PAIRING_TOKEN]"
+---
+Register a Cognitum Seed device. Creates a SeedClient connection, fetches identity, and assigns initial trust level.
+
+Steps:
+1. `npx @claude-flow/cli@latest iot register ENDPOINT`
+2. If pairing token provided: `npx @claude-flow/cli@latest iot pair DEVICE_ID`
+3. Show device status: `npx @claude-flow/cli@latest iot status DEVICE_ID`
+
+Store registration event:
+`mcp__claude-flow__memory_store({ key: "iot-register-DEVICEID", value: "Registered at ENDPOINT", namespace: "iot-devices" })`
diff --git a/plugins/ruflo-iot-cognitum/skills/iot-witness-verify/SKILL.md b/plugins/ruflo-iot-cognitum/skills/iot-witness-verify/SKILL.md
new file mode 100644
index 0000000000..b503a1aee7
--- /dev/null
+++ b/plugins/ruflo-iot-cognitum/skills/iot-witness-verify/SKILL.md
@@ -0,0 +1,14 @@
+---
+name: iot-witness-verify
+description: Verify witness chain integrity and detect provenance gaps
+allowed-tools: Bash(npx *) mcp__claude-flow__memory_store Read
+argument-hint: "<device-id>"
+---
+Verify the witness chain integrity for a Cognitum Seed device.
+
+Steps:
+1. `npx @claude-flow/cli@latest iot witness verify DEVICE_ID`
+2. Check for epoch gaps and hash chain breaks
+3. Report integrity score (0.0–1.0)
+4. If gaps found, store for audit trail:
+ `mcp__claude-flow__memory_store({ key: "iot-witness-gap-DEVICEID", value: "Gap from EPOCH to EPOCH", namespace: "iot-audit" })`
diff --git a/plugins/ruflo-jujutsu/agents/git-specialist.md b/plugins/ruflo-jujutsu/agents/git-specialist.md
index 992e10023d..c8e26e046e 100644
--- a/plugins/ruflo-jujutsu/agents/git-specialist.md
+++ b/plugins/ruflo-jujutsu/agents/git-specialist.md
@@ -19,3 +19,20 @@ Use these MCP tools:
- `mcp__claude-flow__github_pr_manage` for PR operations
Flag high-risk changes and always provide actionable review guidance.
+
+### Memory Learning
+
+Store diff analysis patterns and merge strategies:
+```bash
+npx @claude-flow/cli@latest memory store --namespace git-patterns --key "merge-STRATEGY" --value "CONTEXT_AND_OUTCOME"
+npx @claude-flow/cli@latest memory search --query "merge conflict resolution" --namespace git-patterns
+```
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-jujutsu/skills/diff-analyze/SKILL.md b/plugins/ruflo-jujutsu/skills/diff-analyze/SKILL.md
index 4ccb1377a8..0e309e3d81 100644
--- a/plugins/ruflo-jujutsu/skills/diff-analyze/SKILL.md
+++ b/plugins/ruflo-jujutsu/skills/diff-analyze/SKILL.md
@@ -1,6 +1,7 @@
---
name: diff-analyze
description: Analyze git diffs for risk scoring, reviewer recommendations, and change classification
+argument-hint: "[--branch BRANCH] [--pr PR#]"
allowed-tools: mcp__claude-flow__analyze_diff mcp__claude-flow__analyze_diff-risk mcp__claude-flow__analyze_diff-classify mcp__claude-flow__analyze_diff-reviewers mcp__claude-flow__analyze_diff-stats mcp__claude-flow__analyze_file-risk Bash
---
diff --git a/plugins/ruflo-jujutsu/skills/git-workflow/SKILL.md b/plugins/ruflo-jujutsu/skills/git-workflow/SKILL.md
index 6eaeb4cee6..2953e67f46 100644
--- a/plugins/ruflo-jujutsu/skills/git-workflow/SKILL.md
+++ b/plugins/ruflo-jujutsu/skills/git-workflow/SKILL.md
@@ -1,6 +1,7 @@
---
name: git-workflow
description: Advanced git workflows with branch management, conflict resolution, and PR lifecycle
+argument-hint: "<branch|pr|merge|rebase> [options]"
allowed-tools: mcp__claude-flow__analyze_diff mcp__claude-flow__analyze_diff-risk mcp__claude-flow__analyze_diff-stats mcp__claude-flow__github_pr_manage mcp__claude-flow__github_repo_analyze mcp__claude-flow__github_metrics Bash
---
diff --git a/plugins/ruflo-knowledge-graph/.claude-plugin/plugin.json b/plugins/ruflo-knowledge-graph/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..cca703b4a6
--- /dev/null
+++ b/plugins/ruflo-knowledge-graph/.claude-plugin/plugin.json
@@ -0,0 +1,18 @@
+{
+ "name": "ruflo-knowledge-graph",
+ "description": "Knowledge graph construction — entity extraction, relation mapping, and pathfinder graph traversal",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "knowledge-graph",
+ "entities",
+ "relations",
+ "pathfinder"
+ ]
+}
diff --git a/plugins/ruflo-knowledge-graph/README.md b/plugins/ruflo-knowledge-graph/README.md
new file mode 100644
index 0000000000..7504633a19
--- /dev/null
+++ b/plugins/ruflo-knowledge-graph/README.md
@@ -0,0 +1,64 @@
+# ruflo-knowledge-graph
+
+Knowledge graph construction -- entity extraction, relation mapping, and pathfinder graph traversal.
+
+## Overview
+
+Extracts entities (classes, functions, modules, types, concepts) and relations (imports, extends, implements, depends-on, calls) from source code and documentation. Builds a navigable knowledge graph stored in AgentDB with hierarchical nodes and causal edges. Traverses the graph using a pathfinder algorithm that scores paths by edge weight and semantic similarity.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-knowledge-graph
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `graph-navigator` | sonnet | Entity extraction, relation mapping, knowledge graph construction, pathfinder traversal |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `kg-extract` | `/kg-extract <path>` | Extract entities and relations from source files to build a knowledge graph |
+| `kg-traverse` | `/kg-traverse <entity> [--depth N]` | Pathfinder traversal starting from a seed entity |
+
+## Commands (5 subcommands)
+
+```bash
+kg extract <path> # Extract entities and relations from source files
+kg traverse <entity> # Pathfinder traversal from a seed entity
+kg relations <entity> # List all direct relations for an entity
+kg visualize # ASCII visualization of the knowledge graph
+kg search <query> # Semantic search across the graph
+```
+
+## Entity Types
+
+| Type | Examples |
+|------|----------|
+| class | `UserService`, `AuthController` |
+| function | `calculateDiscount`, `handleRequest` |
+| module | `auth`, `payments`, `api` |
+| concept | `authentication`, `caching` |
+| type | `User`, `OrderStatus` |
+| config | `database`, `redis`, `jwt` |
+
+## Pathfinder Algorithm
+
+1. **Seed** -- start from the target entity node
+2. **Expand** -- follow causal edges outward (configurable depth, default 3)
+3. **Score** -- `relevance = edge_weight * semantic_similarity(query, node)`
+4. **Prune** -- remove paths below threshold (default 0.3)
+5. **Rank** -- return top-K paths by cumulative relevance
+
+## Related Plugins
+
+- `ruflo-ruvector` -- HNSW indexing for fast semantic search across graph nodes
+- `ruflo-adr` -- ADR dependency graphs share the same causal edge model
+
+## License
+
+MIT
diff --git a/plugins/ruflo-knowledge-graph/agents/graph-navigator.md b/plugins/ruflo-knowledge-graph/agents/graph-navigator.md
new file mode 100644
index 0000000000..3100016767
--- /dev/null
+++ b/plugins/ruflo-knowledge-graph/agents/graph-navigator.md
@@ -0,0 +1,80 @@
+---
+name: graph-navigator
+description: Extracts entities and relations from code and docs, builds knowledge graphs, and traverses them with pathfinder scoring
+model: sonnet
+---
+You are a knowledge graph navigator agent. Your responsibilities:
+
+1. **Extract entities** from code and documentation (classes, functions, modules, concepts, types)
+2. **Map relations** between entities: imports, extends, implements, depends-on, calls, references
+3. **Build knowledge graphs** by storing entities as hierarchical nodes and relations as causal edges
+4. **Traverse graphs** using the pathfinder algorithm: seed node, expand causal edges, score by relevance, prune low-similarity paths
+5. **Answer graph queries** such as "what depends on X?", "what is the path from A to B?", "what are the most connected nodes?"
+
+### Entity Types
+
+| Type | Examples | Extraction Source |
+|------|----------|-------------------|
+| class | `UserService`, `AuthController` | Source code (class declarations) |
+| function | `calculateDiscount`, `handleRequest` | Source code (function/method declarations) |
+| module | `auth`, `payments`, `api` | Directory structure and package.json |
+| concept | `authentication`, `caching`, `rate-limiting` | Documentation, comments, ADRs |
+| type | `User`, `OrderStatus`, `ApiResponse` | TypeScript interfaces, type aliases |
+| config | `database`, `redis`, `jwt` | Config files, environment variables |
+
+### Relation Types
+
+| Relation | Direction | Weight | Example |
+|----------|-----------|--------|---------|
+| imports | A -> B | 1.0 | `auth.service` imports `user.repository` |
+| extends | A -> B | 0.9 | `AdminUser` extends `BaseUser` |
+| implements | A -> B | 0.9 | `UserService` implements `IUserService` |
+| depends-on | A -> B | 0.8 | `PaymentController` depends-on `StripeClient` |
+| calls | A -> B | 0.7 | `handleOrder` calls `validatePayment` |
+| references | A -> B | 0.5 | README references `AuthModule` |
+| tests | A -> B | 0.6 | `auth.test.ts` tests `AuthService` |
+
+### Pathfinder Algorithm
+
+The pathfinder traversal algorithm finds relevant subgraphs:
+
+1. **Seed** -- start from the target entity node
+2. **Expand** -- follow causal edges outward (configurable depth, default 3)
+3. **Score** -- compute relevance = edge_weight * semantic_similarity(query, node)
+4. **Prune** -- remove paths with cumulative score below threshold (default 0.3)
+5. **Rank** -- return top-K paths sorted by cumulative relevance score
+
+### Tools
+
+- `mcp__claude-flow__agentdb_causal-edge` -- create/query causal edges between entities
+- `mcp__claude-flow__agentdb_hierarchical-store` -- store entity metadata in hierarchical structure
+- `mcp__claude-flow__agentdb_hierarchical-recall` -- recall entities by path or query
+- `mcp__claude-flow__agentdb_semantic-route` -- semantic similarity routing for graph search
+- `mcp__claude-flow__agentdb_pattern-store` -- store discovered graph patterns
+- `mcp__claude-flow__agentdb_pattern-search` -- search for similar graph structures
+- `mcp__claude-flow__agentdb_context-synthesize` -- synthesize context from multiple graph nodes
+- `mcp__claude-flow__embeddings_embed` -- generate embeddings for entity descriptions
+
+### Neural Learning
+
+After completing graph construction or traversal tasks, train patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest neural train --pattern-type knowledge-graph --epochs 10
+```
+
+### Memory Learning
+
+Store successful graph patterns and entity extraction results:
+```bash
+npx @claude-flow/cli@latest memory store --namespace knowledge-graph --key "entity-ENTITY_NAME" --value "ENTITY_METADATA_JSON"
+npx @claude-flow/cli@latest memory store --namespace knowledge-graph --key "pattern-PATTERN_NAME" --value "GRAPH_PATTERN_JSON"
+npx @claude-flow/cli@latest memory search --query "entities related to authentication" --namespace knowledge-graph
+```
+
+### Related Plugins
+
+- **ruflo-agentdb**: Underlying storage for entities, relations, and causal edges via HNSW-indexed AgentDB
+- **ruflo-core**: Researcher agent uses pathfinder traversal for codebase exploration
+- **ruflo-ruvector**: HNSW indexing for fast semantic search across graph nodes
+- **ruflo-intelligence**: SONA neural patterns learn from graph traversal trajectories
diff --git a/plugins/ruflo-knowledge-graph/commands/kg.md b/plugins/ruflo-knowledge-graph/commands/kg.md
new file mode 100644
index 0000000000..b78505b4ab
--- /dev/null
+++ b/plugins/ruflo-knowledge-graph/commands/kg.md
@@ -0,0 +1,38 @@
+---
+name: kg
+description: Knowledge graph operations — extract entities, traverse relations, and search the graph
+---
+
+Knowledge graph commands:
+
+**`kg extract <path>`** -- Extract entities and relations from source files at the given path.
+1. Scan files at `<path>` recursively for classes, functions, modules, types, and config references
+2. For each entity, record its type, name, file location, and description
+3. Map relations between entities: imports, extends, implements, depends-on, calls, references
+4. Store entities via `mcp__claude-flow__agentdb_hierarchical-store` in the `knowledge-graph` namespace
+5. Create causal edges via `mcp__claude-flow__agentdb_causal-edge` for each relation
+6. Report: total entities found, total relations mapped, entity type breakdown
+
+**`kg traverse <entity>`** -- Pathfinder traversal starting from the named entity.
+1. Look up the seed entity via `mcp__claude-flow__agentdb_hierarchical-recall`
+2. Expand outward by following causal edges (default depth: 3)
+3. Score each path: `relevance = edge_weight * semantic_similarity(query, node)`
+4. Prune paths with cumulative score below 0.3
+5. Return the top 10 paths with entities, relations, and scores
+
+**`kg relations <entity>`** -- List all direct relations for the named entity.
+1. Query causal edges where source or target matches `<entity>`
+2. Group by relation type (imports, extends, implements, depends-on, calls)
+3. Display as a table with: relation, direction (incoming/outgoing), target entity, weight
+
+**`kg visualize`** -- Generate an ASCII visualization of the knowledge graph.
+1. Recall all entities and edges from the `knowledge-graph` namespace
+2. Identify the most-connected nodes (top 10 by degree)
+3. Render a simplified graph showing key nodes and their connections
+4. Include legend with entity types and relation types
+
+**`kg search <query>`** -- Semantic search across the knowledge graph.
+1. Route the query via `mcp__claude-flow__agentdb_semantic-route` to find relevant entities
+2. Expand results with causal edges to show related context
+3. Rank by semantic similarity score
+4. Display matches with entity name, type, file location, and relevance score
diff --git a/plugins/ruflo-knowledge-graph/skills/kg-extract/SKILL.md b/plugins/ruflo-knowledge-graph/skills/kg-extract/SKILL.md
new file mode 100644
index 0000000000..024edd2f67
--- /dev/null
+++ b/plugins/ruflo-knowledge-graph/skills/kg-extract/SKILL.md
@@ -0,0 +1,36 @@
+---
+name: kg-extract
+description: Extract entities and relations from source files to build a knowledge graph
+argument-hint: "<path>"
+allowed-tools: Read Glob Grep mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__agentdb_causal-edge mcp__claude-flow__agentdb_semantic-route mcp__claude-flow__agentdb_pattern-store mcp__claude-flow__embeddings_embed Bash
+---
+
+# KG Extract
+
+Extract entities (classes, functions, modules, types, concepts) and their relations (imports, extends, implements, depends-on, calls) from source files, then store them as a knowledge graph in AgentDB.
+
+## When to use
+
+When you need to build or update a knowledge graph from source code or documentation. Useful for understanding codebase structure, dependency analysis, and impact assessment.
+
+## Steps
+
+1. **Scan files** -- use `Glob` and `Read` to enumerate and read source files at the given path
+2. **Identify entities** -- extract classes, functions, modules, types, and config references from each file
+3. **Map relations** -- for each entity, determine its relations to other entities:
+ - `imports`: follow import/require statements
+ - `extends`: class inheritance
+ - `implements`: interface implementations
+ - `depends-on`: constructor dependencies, injected services
+ - `calls`: function/method invocations
+ - `references`: documentation mentions, comments
+4. **Store in AgentDB** -- call `mcp__claude-flow__agentdb_hierarchical-store` for each entity with metadata (name, type, file, line, description)
+5. **Create edges** -- call `mcp__claude-flow__agentdb_causal-edge` for each relation with source, target, relation type, and weight
+6. **Report** -- summarize: total entities by type, total relations by type, files scanned
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory store --namespace knowledge-graph --key "entity-NAME" --value "METADATA_JSON"
+npx @claude-flow/cli@latest memory search --query "entities in auth module" --namespace knowledge-graph
+```
diff --git a/plugins/ruflo-knowledge-graph/skills/kg-traverse/SKILL.md b/plugins/ruflo-knowledge-graph/skills/kg-traverse/SKILL.md
new file mode 100644
index 0000000000..67b697d1d9
--- /dev/null
+++ b/plugins/ruflo-knowledge-graph/skills/kg-traverse/SKILL.md
@@ -0,0 +1,30 @@
+---
+name: kg-traverse
+description: Pathfinder traversal of the knowledge graph starting from a seed entity
+argument-hint: "<entity> [--depth N]"
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_causal-edge mcp__claude-flow__agentdb_semantic-route mcp__claude-flow__agentdb_pattern-search mcp__claude-flow__agentdb_context-synthesize Bash
+---
+
+# KG Traverse
+
+Perform pathfinder graph traversal starting from a seed entity. Expands outward through causal edges, scores paths by relevance, and prunes low-similarity branches.
+
+## When to use
+
+When you need to explore the knowledge graph starting from a specific entity -- finding what depends on it, what it depends on, or discovering indirect relationships. Useful for impact analysis, dependency chains, and understanding code structure.
+
+## Steps
+
+1. **Seed** -- call `mcp__claude-flow__agentdb_hierarchical-recall` to look up the target entity by name
+2. **Expand** -- call `mcp__claude-flow__agentdb_causal-edge` to find all edges connected to the seed entity, then recursively expand outward to the specified depth (default: 3)
+3. **Score** -- for each path, compute relevance: `cumulative_score = product(edge_weight * semantic_similarity(query, node))` using `mcp__claude-flow__agentdb_semantic-route` for similarity
+4. **Prune** -- remove paths with cumulative score below 0.3
+5. **Rank** -- sort remaining paths by cumulative score descending
+6. **Synthesize** -- call `mcp__claude-flow__agentdb_context-synthesize` to combine the top paths into a coherent summary
+7. **Report** -- display the top 10 paths with: path (entity chain), relation types, cumulative score, and synthesized context
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory search --query "relations for ENTITY_NAME" --namespace knowledge-graph
+```
diff --git a/plugins/ruflo-loop-workers/agents/loop-worker-coordinator.md b/plugins/ruflo-loop-workers/agents/loop-worker-coordinator.md
new file mode 100644
index 0000000000..46477f138a
--- /dev/null
+++ b/plugins/ruflo-loop-workers/agents/loop-worker-coordinator.md
@@ -0,0 +1,53 @@
+---
+name: loop-worker-coordinator
+description: Coordinates background worker scheduling, health monitoring, and dispatch across loop and cron execution modes
+model: haiku
+---
+You are the loop worker coordinator. You manage background worker lifecycle across two execution modes: `/loop` (in-session, cache-aware) and CronCreate (persistent, cross-session).
+
+## Responsibilities
+
+1. **Dispatch workers** via `mcp__claude-flow__hooks_worker-dispatch` with the correct trigger name
+2. **Monitor health** via `mcp__claude-flow__hooks_worker-status` and report failures
+3. **Schedule iterations** using `ScheduleWakeup` (loop mode) or `CronCreate` (persistent mode)
+4. **Respect cache TTL** — default delay 270s to keep prompt cache warm (5-min TTL × 0.9)
+
+## Available Workers
+
+| Worker | Priority | Trigger | Recommended Interval |
+|--------|----------|---------|---------------------|
+| audit | critical | `audit` | 270s (loop) / `*/15 * * * *` (cron) |
+| optimize | high | `optimize` | 270s (loop) / `*/30 * * * *` (cron) |
+| consolidate | low | `consolidate` | 600s (loop) / `0 * * * *` (cron) |
+| predict | normal | `predict` | 270s (loop) / `*/15 * * * *` (cron) |
+| map | normal | `map` | 270s (loop) / `*/30 * * * *` (cron) |
+| testgaps | normal | `testgaps` | 270s (loop) / `*/15 * * * *` (cron) |
+| document | normal | `document` | 600s (loop) / `0 */2 * * *` (cron) |
+| benchmark | normal | `benchmark` | 600s (loop) / `0 * * * *` (cron) |
+| deepdive | normal | `deepdive` | 270s (loop) / `*/30 * * * *` (cron) |
+| refactor | normal | `refactor` | 270s (loop) / `*/30 * * * *` (cron) |
+| ultralearn | normal | `ultralearn` | 270s (loop) / `*/15 * * * *` (cron) |
+| preload | low | `preload` | 600s (loop) / `0 * * * *` (cron) |
+
+## Workflow
+
+1. Check current worker status: `Bash("npx @claude-flow/cli@latest hooks worker status")`
+2. Dispatch needed workers: `Bash("npx @claude-flow/cli@latest hooks worker dispatch --trigger WORKER_NAME")`
+3. Schedule next check based on execution mode
+
+## Tools
+
+- `Bash(npx @claude-flow/cli@latest hooks worker *)` — worker management
+- `ScheduleWakeup` — loop-mode scheduling
+- `CronCreate` / `CronList` / `CronDelete` — persistent scheduling
+- `mcp__claude-flow__hooks_worker-dispatch` — direct worker dispatch
+- `mcp__claude-flow__hooks_worker-status` — worker health check
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-loop-workers/skills/cron-schedule/SKILL.md b/plugins/ruflo-loop-workers/skills/cron-schedule/SKILL.md
index 22504f3a77..d35f3658a9 100644
--- a/plugins/ruflo-loop-workers/skills/cron-schedule/SKILL.md
+++ b/plugins/ruflo-loop-workers/skills/cron-schedule/SKILL.md
@@ -1,6 +1,7 @@
---
name: cron-schedule
description: Schedule persistent background workers via CronCreate
+argument-hint: "<worker-name> [--interval CRON]"
allowed-tools: CronCreate CronList CronDelete mcp__claude-flow__hooks_worker-dispatch
---
Use `CronCreate` for workers that must survive session restarts:
diff --git a/plugins/ruflo-loop-workers/skills/loop-worker/SKILL.md b/plugins/ruflo-loop-workers/skills/loop-worker/SKILL.md
index 86878f7475..53f7fc5f82 100644
--- a/plugins/ruflo-loop-workers/skills/loop-worker/SKILL.md
+++ b/plugins/ruflo-loop-workers/skills/loop-worker/SKILL.md
@@ -1,6 +1,7 @@
---
name: loop-worker
description: Run Ruflo background workers using Claude Code native /loop scheduling
+argument-hint: "<worker-name>"
allowed-tools: Bash(npx *) mcp__claude-flow__hooks_worker-dispatch mcp__claude-flow__hooks_worker-status ScheduleWakeup
---
Use `/loop` for in-session periodic workers. Cache-aware delays keep prompt cache warm:
diff --git a/plugins/ruflo-market-data/.claude-plugin/plugin.json b/plugins/ruflo-market-data/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..28246f5727
--- /dev/null
+++ b/plugins/ruflo-market-data/.claude-plugin/plugin.json
@@ -0,0 +1,18 @@
+{
+ "name": "ruflo-market-data",
+ "description": "Market data ingestion — feed normalization, OHLCV vectorization, and HNSW-indexed pattern matching",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "market-data",
+ "ohlcv",
+ "time-series",
+ "patterns"
+ ]
+}
diff --git a/plugins/ruflo-market-data/README.md b/plugins/ruflo-market-data/README.md
new file mode 100644
index 0000000000..0e902bac0d
--- /dev/null
+++ b/plugins/ruflo-market-data/README.md
@@ -0,0 +1,70 @@
+# ruflo-market-data
+
+Market data ingestion -- feed normalization, OHLCV vectorization, and HNSW-indexed pattern matching.
+
+## Overview
+
+Ingests market data from REST APIs and WebSocket feeds, normalizes to OHLCV vectors with consistent scaling, and vectorizes candlestick patterns for HNSW similarity search. Detects single-candle (doji, hammer) and multi-candle (engulfing, morning star, head & shoulders) formations with reliability scoring.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-market-data
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `data-engineer` | sonnet | Ingest market feeds, normalize OHLCV, vectorize candlestick patterns, HNSW-indexed pattern matching |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `market-ingest` | `/market-ingest <symbol> [--source api]` | Ingest and normalize market data into OHLCV vectors with HNSW indexing |
+| `market-pattern` | `/market-pattern <symbol> [--period 1D]` | Detect and classify candlestick patterns from ingested data |
+
+## Commands (5 subcommands)
+
+```bash
+market ingest <symbol> [--period 1D] # Ingest and normalize OHLCV data
+market patterns <symbol> # Detect candlestick patterns
+market search <pattern-name> # Search historical pattern occurrences
+market history <symbol> # Show ingestion history and data coverage
+market compare <sym1> <sym2> # Compare pattern profiles between symbols
+```
+
+## OHLCV Normalization
+
+| Field | Normalization |
+|-------|--------------|
+| Open | Relative to previous close: `(open - prev_close) / prev_close` |
+| High | Relative to open: `(high - open) / open` |
+| Low | Relative to open: `(low - open) / open` |
+| Close | Relative to open: `(close - open) / open` |
+| Volume | Z-score: `(vol - mean_vol) / std_vol` |
+
+## Pattern Library
+
+| Pattern | Type | Candles | Reliability |
+|---------|------|---------|-------------|
+| Doji | Reversal | 1 | Medium |
+| Hammer | Reversal | 1 | Medium-High |
+| Engulfing | Reversal | 2 | High |
+| Morning/Evening Star | Reversal | 3 | High |
+| Three White Soldiers | Continuation | 3 | High |
+| Head & Shoulders | Reversal | 5-7 | Very High |
+| Double Top/Bottom | Reversal | Variable | High |
+
+Each pattern is encoded as a 64-dimension padded vector for HNSW indexing.
+
+## Related Plugins
+
+- `ruflo-neural-trader` -- Consumes market patterns as strategy signals
+- `ruflo-ruvector` -- HNSW indexing engine for pattern similarity search
+- `ruflo-observability` -- Data feed health and ingestion latency dashboards
+
+## License
+
+MIT
diff --git a/plugins/ruflo-market-data/agents/data-engineer.md b/plugins/ruflo-market-data/agents/data-engineer.md
new file mode 100644
index 0000000000..265f813805
--- /dev/null
+++ b/plugins/ruflo-market-data/agents/data-engineer.md
@@ -0,0 +1,85 @@
+---
+name: data-engineer
+description: Ingests market data feeds, normalizes OHLCV vectors, and performs HNSW-indexed candlestick pattern matching
+model: sonnet
+---
+You are a market data engineer agent. Your responsibilities:
+
+1. **Ingest market data** from REST APIs and WebSocket feeds
+2. **Normalize to OHLCV vectors** (Open, High, Low, Close, Volume) with consistent scaling
+3. **Vectorize candlestick patterns** for HNSW similarity search
+4. **Detect patterns** from a library of known formations
+5. **Index and search** historical patterns using HNSW for fast nearest-neighbor lookup
+
+### OHLCV Normalization
+
+Raw market data is normalized before vectorization:
+
+| Field | Normalization | Formula |
+|-------|--------------|---------|
+| Open | Relative to previous close | `(open - prev_close) / prev_close` |
+| High | Relative to open | `(high - open) / open` |
+| Low | Relative to open | `(low - open) / open` |
+| Close | Relative to open | `(close - open) / open` |
+| Volume | Z-score | `(vol - mean_vol) / std_vol` |
+
+### Pattern Library
+
+| Pattern | Type | Candles | Reliability |
+|---------|------|---------|-------------|
+| Doji | Reversal | 1 | Medium |
+| Hammer | Reversal | 1 | Medium-High |
+| Engulfing (bullish) | Reversal | 2 | High |
+| Engulfing (bearish) | Reversal | 2 | High |
+| Morning Star | Reversal | 3 | High |
+| Evening Star | Reversal | 3 | High |
+| Three White Soldiers | Continuation | 3 | High |
+| Three Black Crows | Continuation | 3 | High |
+| Head & Shoulders | Reversal | 5-7 | Very High |
+| Double Top | Reversal | Variable | High |
+| Double Bottom | Reversal | Variable | High |
+| Cup & Handle | Continuation | Variable | High |
+
+### Vectorization Strategy
+
+Each candlestick pattern is encoded as a fixed-length vector:
+- **Single-candle patterns**: 5 dimensions (normalized OHLCV)
+- **Multi-candle patterns**: 5 * N dimensions (concatenated OHLCV for N candles)
+- **Metadata vector**: 3 dimensions (pattern_type_id, reliability_score, trend_direction)
+- **Total vector**: padded to 64 dimensions for HNSW indexing
+
+### Tools
+
+- `mcp__claude-flow__agentdb_hierarchical-store` -- store normalized OHLCV data and pattern metadata
+- `mcp__claude-flow__agentdb_hierarchical-recall` -- recall historical market data by symbol/period
+- `mcp__claude-flow__agentdb_pattern-store` -- store detected candlestick patterns with vectors
+- `mcp__claude-flow__agentdb_pattern-search` -- search for similar patterns via HNSW
+- `mcp__claude-flow__agentdb_semantic-route` -- route queries to relevant market data sources
+- `mcp__claude-flow__embeddings_embed` -- generate embeddings for pattern descriptions
+- `mcp__claude-flow__ruvllm_hnsw_create` -- create HNSW index for pattern vectors
+- `mcp__claude-flow__ruvllm_hnsw_add` -- add pattern vectors to HNSW index
+- `mcp__claude-flow__ruvllm_hnsw_route` -- nearest-neighbor search in pattern index
+
+### Neural Learning
+
+After successful data ingestion or pattern detection, train patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest neural train --pattern-type market-data --epochs 15
+```
+
+### Memory Learning
+
+Store ingested data summaries and detected patterns:
+```bash
+npx @claude-flow/cli@latest memory store --namespace market-data --key "symbol-SYMBOL" --value "OHLCV_SUMMARY_JSON"
+npx @claude-flow/cli@latest memory store --namespace market-patterns --key "pattern-PATTERN_ID" --value "PATTERN_METADATA_JSON"
+npx @claude-flow/cli@latest memory search --query "bearish reversal patterns for AAPL" --namespace market-patterns
+```
+
+### Related Plugins
+
+- **ruflo-neural-trader**: Consumes market data patterns as strategy signals for trading decisions
+- **ruflo-ruvector**: HNSW indexing engine for fast pattern similarity search
+- **ruflo-agentdb**: Persistent storage for OHLCV data and pattern vectors
+- **ruflo-observability**: Metrics dashboards for data feed health and ingestion latency
diff --git a/plugins/ruflo-market-data/commands/market.md b/plugins/ruflo-market-data/commands/market.md
new file mode 100644
index 0000000000..a86268e9e9
--- /dev/null
+++ b/plugins/ruflo-market-data/commands/market.md
@@ -0,0 +1,39 @@
+---
+name: market
+description: Market data operations — ingest feeds, detect patterns, and search historical data
+---
+
+Market data commands:
+
+**`market ingest <symbol> [--period 1D]`** -- Ingest and normalize market data for the given symbol.
+1. Fetch OHLCV data for `<symbol>` from the configured data source
+2. Normalize: open/high/low/close as relative percentages, volume as Z-score
+3. Vectorize each candle to a 64-dimension padded vector
+4. Store normalized data via `mcp__claude-flow__agentdb_hierarchical-store` in `market-data` namespace
+5. Add vectors to HNSW index via `mcp__claude-flow__ruvllm_hnsw_add`
+6. Report: candles ingested, date range, min/max/avg price, volume profile
+
+**`market patterns <symbol>`** -- Detect candlestick patterns in recent data.
+1. Recall recent OHLCV data for `<symbol>` from the `market-data` namespace
+2. Scan for single-candle patterns (doji, hammer) and multi-candle patterns (engulfing, morning star)
+3. Classify each detection with pattern name, type (reversal/continuation), and reliability score
+4. Store detected patterns via `mcp__claude-flow__agentdb_pattern-store`
+5. Display: pattern name, date, direction (bullish/bearish), reliability, candle range
+
+**`market search <pattern-name>`** -- Search for historical occurrences of a pattern.
+1. Search HNSW index via `mcp__claude-flow__ruvllm_hnsw_route` for vectors matching the pattern
+2. Recall matching entries from `market-patterns` namespace
+3. Rank by similarity score and recency
+4. Display: symbol, date, pattern match score, subsequent price action (if available)
+
+**`market history <symbol>`** -- Show ingestion history and data coverage.
+1. Query `market-data` namespace for all entries matching `<symbol>`
+2. Compute: total candles stored, date range, gaps in coverage
+3. Show data freshness (last ingestion timestamp)
+4. List detected patterns count by type
+
+**`market compare <sym1> <sym2>`** -- Compare pattern profiles between two symbols.
+1. Recall pattern data for both symbols from `market-patterns` namespace
+2. Compute correlation: shared pattern types, timing overlap, direction agreement
+3. Display side-by-side comparison with pattern frequency and reliability differences
+4. Highlight divergences that may indicate trading opportunities
diff --git a/plugins/ruflo-market-data/skills/market-ingest/SKILL.md b/plugins/ruflo-market-data/skills/market-ingest/SKILL.md
new file mode 100644
index 0000000000..29b5591153
--- /dev/null
+++ b/plugins/ruflo-market-data/skills/market-ingest/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: market-ingest
+description: Ingest and normalize market data into OHLCV vectors with HNSW indexing
+argument-hint: "<symbol> [--source api]"
+allowed-tools: Bash mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__ruvllm_hnsw_create mcp__claude-flow__ruvllm_hnsw_add mcp__claude-flow__embeddings_embed
+---
+
+# Market Ingest
+
+Fetch market data for a symbol, normalize to OHLCV vectors, and store with HNSW indexing for fast pattern search.
+
+## When to use
+
+When you need to ingest raw market data (price and volume) for a symbol and prepare it for pattern detection and similarity search. This is the first step before running pattern detection or comparison.
+
+## Steps
+
+1. **Fetch data** -- retrieve OHLCV data for the symbol from the configured data source (REST API, CSV file, or manual input)
+2. **Normalize** -- convert raw prices to relative values:
+ - Open: `(open - prev_close) / prev_close`
+ - High: `(high - open) / open`
+ - Low: `(low - open) / open`
+ - Close: `(close - open) / open`
+ - Volume: Z-score against rolling mean/std
+3. **Vectorize** -- encode each candle as a 64-dimension padded vector (5 normalized OHLCV values + padding)
+4. **Store** -- call `mcp__claude-flow__agentdb_hierarchical-store` to persist normalized OHLCV data in the `market-data` namespace with symbol and date as keys
+5. **Index** -- call `mcp__claude-flow__ruvllm_hnsw_add` to add vectors to the HNSW index for nearest-neighbor search
+6. **Report** -- summarize: candles ingested, date range, price range, average volume
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory store --namespace market-data --key "symbol-SYMBOL-DATE" --value "OHLCV_JSON"
+```
diff --git a/plugins/ruflo-market-data/skills/market-pattern/SKILL.md b/plugins/ruflo-market-data/skills/market-pattern/SKILL.md
new file mode 100644
index 0000000000..97438dd09c
--- /dev/null
+++ b/plugins/ruflo-market-data/skills/market-pattern/SKILL.md
@@ -0,0 +1,33 @@
+---
+name: market-pattern
+description: Detect and classify candlestick patterns from ingested OHLCV data
+argument-hint: "<symbol> [--period 1D]"
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_pattern-store mcp__claude-flow__agentdb_pattern-search mcp__claude-flow__ruvllm_hnsw_route Bash
+---
+
+# Market Pattern
+
+Scan ingested OHLCV data for known candlestick patterns, classify them by type and reliability, and store for future reference.
+
+## When to use
+
+When you need to identify candlestick patterns (doji, hammer, engulfing, head-shoulders, etc.) in market data. Requires data to be ingested first via `market-ingest`.
+
+## Steps
+
+1. **Load candles** -- call `mcp__claude-flow__agentdb_hierarchical-recall` to retrieve normalized OHLCV data for the symbol and period from `market-data` namespace
+2. **Scan for patterns** -- iterate through candle sequences looking for:
+ - Single-candle: doji (open ~= close), hammer (long lower wick), inverted hammer
+ - Two-candle: bullish/bearish engulfing
+ - Three-candle: morning star, evening star, three white soldiers, three black crows
+ - Multi-candle: head & shoulders, double top/bottom, cup & handle
+3. **Classify** -- for each detection, assign: pattern name, type (reversal/continuation), direction (bullish/bearish), reliability score (0.0-1.0)
+4. **Rank** -- sort by reliability score descending
+5. **Store** -- call `mcp__claude-flow__agentdb_pattern-store` to persist each detected pattern in `market-patterns` namespace with the pattern vector
+6. **Report** -- display: pattern name, date range, direction, reliability, suggested action
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory search --query "bullish reversal patterns" --namespace market-patterns
+```
diff --git a/plugins/ruflo-migrations/.claude-plugin/plugin.json b/plugins/ruflo-migrations/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..682e920d62
--- /dev/null
+++ b/plugins/ruflo-migrations/.claude-plugin/plugin.json
@@ -0,0 +1,18 @@
+{
+ "name": "ruflo-migrations",
+ "description": "Schema migration management — generate, validate, dry-run, and rollback database migrations",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "migrations",
+ "database",
+ "schema",
+ "rollback"
+ ]
+}
diff --git a/plugins/ruflo-migrations/README.md b/plugins/ruflo-migrations/README.md
new file mode 100644
index 0000000000..f0b8150deb
--- /dev/null
+++ b/plugins/ruflo-migrations/README.md
@@ -0,0 +1,70 @@
+# ruflo-migrations
+
+Schema migration management -- generate, validate, dry-run, and rollback database migrations.
+
+## Overview
+
+Generates sequentially numbered database migrations with up/down SQL pairs for rollback safety. Includes dry-run mode to preview SQL without executing, validation checks for foreign key consistency, index coverage, and naming conventions, plus full migration history tracking in AgentDB.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-migrations
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `migration-engineer` | sonnet | Generate sequential migrations, create up/down pairs, dry-run validation, rollback safety checks |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `migrate-create` | `/migrate-create <name>` | Create a new sequentially numbered migration with up/down SQL files |
+| `migrate-validate` | `/migrate-validate` | Validate pending migrations for FK consistency, rollback safety, and best practices |
+
+## Commands (6 subcommands)
+
+```bash
+migrate create <name> # Create NNN_name.up.sql and NNN_name.down.sql
+migrate up [--dry-run] # Apply pending migrations (or preview SQL)
+migrate down [--steps N] # Rollback last N migrations (default: 1)
+migrate status # Show applied/pending migration status
+migrate validate # Validate pending migrations for safety
+migrate history # Show full migration execution history
+```
+
+## Validation Checks
+
+| Check | Severity | Description |
+|-------|----------|-------------|
+| Foreign key targets exist | Error | Referenced table/column must exist |
+| Index coverage | Warning | WHERE/JOIN columns should be indexed |
+| Data type compatibility | Error | ALTER COLUMN type must be compatible |
+| NOT NULL without default | Error | Adding NOT NULL column requires DEFAULT |
+| Down migration completeness | Warning | Every UP needs a corresponding DOWN |
+| Destructive operations | Warning | DROP TABLE/COLUMN flagged for review |
+| Naming conventions | Info | Tables plural, columns snake_case |
+| Idempotency | Warning | Use IF EXISTS / IF NOT EXISTS |
+
+## Migration File Format
+
+```
+migrations/
+ 001_create_users.up.sql
+ 001_create_users.down.sql
+ 002_add_email_index.up.sql
+ 002_add_email_index.down.sql
+```
+
+## Related Plugins
+
+- `ruflo-adr` -- Document schema change decisions as ADRs
+- `ruflo-ddd` -- Align migration boundaries with aggregate roots
+- `ruflo-observability` -- Track migration execution duration and failure rates
+
+## License
+
+MIT
diff --git a/plugins/ruflo-migrations/agents/migration-engineer.md b/plugins/ruflo-migrations/agents/migration-engineer.md
new file mode 100644
index 0000000000..7761cd3fdb
--- /dev/null
+++ b/plugins/ruflo-migrations/agents/migration-engineer.md
@@ -0,0 +1,98 @@
+---
+name: migration-engineer
+description: Generates sequential database migrations with up/down pairs, dry-run validation, and rollback safety checks
+model: sonnet
+---
+You are a migration engineer agent. Your responsibilities:
+
+1. **Generate migrations** with sequential numbering (001_create_users, 002_add_email_index, ...)
+2. **Create up/down pairs** for every migration to ensure rollback safety
+3. **Dry-run mode** -- show SQL that would execute without running it
+4. **Validate migrations** -- check foreign key consistency, index coverage, data type compatibility
+5. **Track migration history** -- record which migrations have been applied and their status
+
+### Migration Numbering
+
+Migrations follow strict sequential numbering:
+- Format: `NNN_descriptive_name.sql` (e.g., `001_create_users.sql`)
+- Each migration has two files: `NNN_name.up.sql` and `NNN_name.down.sql`
+- Numbers are zero-padded to 3 digits
+- Names use snake_case, describing the change concisely
+
+### Migration Templates
+
+**Create table:**
+```sql
+-- UP
+CREATE TABLE IF NOT EXISTS table_name (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- DOWN
+DROP TABLE IF EXISTS table_name;
+```
+
+**Add column:**
+```sql
+-- UP
+ALTER TABLE table_name ADD COLUMN column_name TYPE NOT NULL DEFAULT value;
+
+-- DOWN
+ALTER TABLE table_name DROP COLUMN IF EXISTS column_name;
+```
+
+**Add index:**
+```sql
+-- UP
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_table_column ON table_name (column_name);
+
+-- DOWN
+DROP INDEX CONCURRENTLY IF EXISTS idx_table_column;
+```
+
+### Validation Checks
+
+| Check | Severity | Description |
+|-------|----------|-------------|
+| Foreign key targets exist | Error | Referenced table/column must exist |
+| Index coverage | Warning | Columns used in WHERE/JOIN should be indexed |
+| Data type compatibility | Error | ALTER COLUMN type must be compatible |
+| NOT NULL without default | Error | Adding NOT NULL column requires DEFAULT |
+| Down migration completeness | Warning | Every UP statement needs a corresponding DOWN |
+| Destructive operations | Warning | DROP TABLE, DROP COLUMN flagged for review |
+| Naming conventions | Info | Tables plural, columns snake_case |
+| Idempotency | Warning | Use IF EXISTS / IF NOT EXISTS |
+
+### Tools
+
+- `mcp__claude-flow__agentdb_hierarchical-store` -- store migration metadata and history
+- `mcp__claude-flow__agentdb_hierarchical-recall` -- recall migration status and history
+- `mcp__claude-flow__agentdb_pattern-store` -- store successful migration patterns
+- `mcp__claude-flow__agentdb_pattern-search` -- search for similar migration patterns
+- `mcp__claude-flow__agentdb_semantic-route` -- route queries to relevant schema documentation
+
+### Neural Learning
+
+After successful migration creation or validation, train patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest neural train --pattern-type migrations --epochs 10
+```
+
+### Memory Learning
+
+Store migration patterns and validation results:
+```bash
+npx @claude-flow/cli@latest memory store --namespace migrations --key "migration-NNN_NAME" --value "MIGRATION_METADATA_JSON"
+npx @claude-flow/cli@latest memory store --namespace migration-patterns --key "pattern-PATTERN_NAME" --value "PATTERN_JSON"
+npx @claude-flow/cli@latest memory search --query "migrations adding foreign keys" --namespace migrations
+```
+
+### Related Plugins
+
+- **ruflo-security-audit**: Checks migrations for SQL injection vulnerabilities and privilege escalation
+- **ruflo-adr**: Documents schema change decisions as Architecture Decision Records
+- **ruflo-ddd**: Aligns migration boundaries with DDD aggregate roots and bounded contexts
+- **ruflo-observability**: Tracks migration execution duration and failure rates
diff --git a/plugins/ruflo-migrations/commands/migrate.md b/plugins/ruflo-migrations/commands/migrate.md
new file mode 100644
index 0000000000..7b67c8edc3
--- /dev/null
+++ b/plugins/ruflo-migrations/commands/migrate.md
@@ -0,0 +1,47 @@
+---
+name: migrate
+description: Database migration operations — create, apply, rollback, validate, and inspect migration history
+---
+
+Migration commands:
+
+**`migrate create <name>`** -- Create a new migration with sequential numbering.
+1. Scan the migrations directory for the highest existing migration number
+2. Compute the next number (zero-padded to 3 digits)
+3. Generate `NNN_<name>.up.sql` and `NNN_<name>.down.sql` files
+4. Populate with SQL template appropriate for the name (create table, add column, add index)
+5. Store migration metadata via `mcp__claude-flow__agentdb_hierarchical-store`
+6. Report: file paths created, migration number, template used
+
+**`migrate up [--dry-run]`** -- Apply pending migrations.
+1. Recall migration history to determine which migrations have been applied
+2. Find all unapplied migrations in sequential order
+3. If `--dry-run`, display the SQL for each pending migration without executing
+4. If not dry-run, execute each `.up.sql` file in order, recording results
+5. Store execution results (success/failure, duration) in `migrations` namespace
+6. Report: migrations applied, total duration, any errors
+
+**`migrate down [--steps N]`** -- Rollback the last N migrations (default: 1).
+1. Recall migration history to find the most recently applied migrations
+2. Execute corresponding `.down.sql` files in reverse order
+3. Record rollback results in `migrations` namespace
+4. Report: migrations rolled back, any errors
+
+**`migrate status`** -- Show migration status.
+1. List all migration files found in the migrations directory
+2. Cross-reference with applied migration history
+3. Display: migration number, name, status (applied/pending), applied date, duration
+
+**`migrate validate`** -- Validate pending migrations for safety.
+1. Parse all pending `.up.sql` and `.down.sql` files
+2. Check foreign key targets exist in the current schema or prior migrations
+3. Verify NOT NULL columns have DEFAULT values
+4. Flag destructive operations (DROP TABLE, DROP COLUMN)
+5. Check that every UP statement has a corresponding DOWN
+6. Verify naming conventions (tables plural, columns snake_case)
+7. Report: errors, warnings, and info-level suggestions
+
+**`migrate history`** -- Show full migration execution history.
+1. Recall all entries from `migrations` namespace
+2. Display: migration number, name, direction (up/down), timestamp, duration, status
+3. Highlight any failed migrations that may need attention
diff --git a/plugins/ruflo-migrations/skills/migrate-create/SKILL.md b/plugins/ruflo-migrations/skills/migrate-create/SKILL.md
new file mode 100644
index 0000000000..090bcda9f6
--- /dev/null
+++ b/plugins/ruflo-migrations/skills/migrate-create/SKILL.md
@@ -0,0 +1,35 @@
+---
+name: migrate-create
+description: Create a new sequentially numbered database migration with up/down SQL files
+argument-hint: "<name>"
+allowed-tools: Read Write Glob Bash mcp__claude-flow__agentdb_hierarchical-store mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_pattern-search
+---
+
+# Migrate Create
+
+Generate a new database migration with sequential numbering and up/down SQL file pair.
+
+## When to use
+
+When you need to create a new database migration for schema changes such as creating tables, adding columns, creating indexes, or modifying constraints.
+
+## Steps
+
+1. **Determine next number** -- use `Glob` to scan the migrations directory for existing migration files and find the highest number, then increment by 1 (zero-pad to 3 digits)
+2. **Select template** -- based on the `<name>`, choose the appropriate SQL template:
+ - Names starting with `create_` -> CREATE TABLE template
+ - Names starting with `add_` -> ALTER TABLE ADD COLUMN template
+ - Names starting with `drop_` -> DROP with safety checks
+ - Names containing `index` -> CREATE INDEX template
+ - Other -> generic migration template with placeholder comments
+3. **Generate up migration** -- write `NNN_<name>.up.sql` with the appropriate SQL using IF NOT EXISTS for idempotency
+4. **Generate down migration** -- write `NNN_<name>.down.sql` with the reverse operation using IF EXISTS
+5. **Search patterns** -- call `mcp__claude-flow__agentdb_pattern-search` to find similar past migrations for reference
+6. **Store metadata** -- call `mcp__claude-flow__agentdb_hierarchical-store` to record the migration in `migrations` namespace with number, name, status (pending), and file paths
+7. **Report** -- display: migration number, file paths created, template used, any similar past migrations found
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory store --namespace migrations --key "migration-NNN_NAME" --value '{"number": NNN, "name": "NAME", "status": "pending"}'
+```
diff --git a/plugins/ruflo-migrations/skills/migrate-validate/SKILL.md b/plugins/ruflo-migrations/skills/migrate-validate/SKILL.md
new file mode 100644
index 0000000000..3ce737a7fa
--- /dev/null
+++ b/plugins/ruflo-migrations/skills/migrate-validate/SKILL.md
@@ -0,0 +1,33 @@
+---
+name: migrate-validate
+description: Validate pending migrations for foreign key consistency, rollback safety, and best practices
+argument-hint: ""
+allowed-tools: Read Glob Grep Bash mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_pattern-store mcp__claude-flow__agentdb_semantic-route
+---
+
+# Migrate Validate
+
+Validate all pending database migrations for correctness, safety, and adherence to best practices.
+
+## When to use
+
+Before applying migrations to catch issues early -- foreign key references to non-existent tables, missing rollback SQL, destructive operations without safeguards, and naming convention violations.
+
+## Steps
+
+1. **Find pending migrations** -- use `Glob` to list all migration files, cross-reference with applied history via `mcp__claude-flow__agentdb_hierarchical-recall` to identify pending ones
+2. **Parse SQL** -- use `Read` to load each pending `.up.sql` and `.down.sql` file and parse the SQL statements
+3. **Check foreign keys** -- verify that all REFERENCES targets exist in the current schema or in prior migrations (both applied and pending)
+4. **Check NOT NULL defaults** -- verify that any ADD COLUMN with NOT NULL has a DEFAULT value
+5. **Check rollback completeness** -- verify every CREATE/ALTER in the UP file has a corresponding DROP/ALTER in the DOWN file
+6. **Flag destructive ops** -- warn on DROP TABLE, DROP COLUMN, TRUNCATE without explicit confirmation
+7. **Check idempotency** -- verify IF EXISTS / IF NOT EXISTS is used for safety
+8. **Check naming** -- verify table names are plural, column names are snake_case, index names follow `idx_table_column` convention
+9. **Store results** -- call `mcp__claude-flow__agentdb_pattern-store` to record validation patterns for future reference
+10. **Report** -- display: errors (must fix), warnings (should fix), info (suggestions), with file path and line number for each issue
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory search --query "migration validation results" --namespace migrations
+```
diff --git a/plugins/ruflo-neural-trader/.claude-plugin/plugin.json b/plugins/ruflo-neural-trader/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..cd96308869
--- /dev/null
+++ b/plugins/ruflo-neural-trader/.claude-plugin/plugin.json
@@ -0,0 +1,21 @@
+{
+ "name": "ruflo-neural-trader",
+ "description": "Neural trading strategies — time-series anomaly detection, backtesting, risk scoring, and portfolio optimization via SONA trajectories",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "trading",
+ "neural",
+ "backtesting",
+ "risk",
+ "portfolio",
+ "sona",
+ "time-series"
+ ]
+}
diff --git a/plugins/ruflo-neural-trader/README.md b/plugins/ruflo-neural-trader/README.md
new file mode 100644
index 0000000000..fed4a207bb
--- /dev/null
+++ b/plugins/ruflo-neural-trader/README.md
@@ -0,0 +1,76 @@
+# ruflo-neural-trader
+
+Neural trading strategies -- time-series anomaly detection, backtesting, risk scoring, and portfolio optimization via SONA trajectories.
+
+## Overview
+
+Provides two specialized agents for strategy design and risk management. The trading strategist uses SONA trajectory learning and Z-score anomaly detection (reused from ruflo-iot-cognitum) to design, backtest, and optimize trading strategies. The risk analyst enforces position limits, calculates VaR/Sharpe/drawdown metrics, and manages circuit breakers.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-neural-trader
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `trading-strategist` | opus | Design neural strategies, detect price anomalies via Z-score, backtest with walk-forward validation, optimize via SONA |
+| `risk-analyst` | sonnet | Portfolio risk assessment (VaR, Sharpe, drawdown), position sizing (Kelly, fixed fractional), circuit breakers |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `trader-signal` | `/trader-signal [--strategy NAME]` | Generate trading signals via Z-score anomaly detection |
+| `trader-backtest` | `/trader-backtest <strategy-name> [--period 1Y]` | Run historical backtest with walk-forward validation |
+| `trader-portfolio` | `/trader-portfolio [--risk-target NUMBER]` | Optimize portfolio allocation with mean-variance optimization |
+
+## Commands (8 subcommands)
+
+```bash
+# Strategy
+trader strategy create <name>
+trader backtest <strategy> --data <source>
+
+# Signals
+trader signal scan
+trader signal scan --strategy <name>
+
+# Risk & portfolio
+trader risk assess <portfolio>
+trader portfolio optimize [--risk-target N]
+
+# History
+trader history
+```
+
+## Strategy Types
+
+| Strategy | Entry Signal | Best Regime |
+|----------|-------------|-------------|
+| Mean-reversion | Z-score > 2.0 (spike) | Ranging / oscillation |
+| Momentum | Sustained drift anomaly | Trending |
+| Statistical arbitrage | Spread Z-score > 2.0 | Any (market-neutral) |
+| Pattern recognition | Cluster-outlier + match | Regime transitions |
+
+## Circuit Breakers
+
+| Breaker | Trigger | Action |
+|---------|---------|--------|
+| Daily loss | Drawdown > 3%/day | Halt new entries |
+| Weekly loss | Drawdown > 5%/week | Reduce sizes 50% |
+| Correlation spike | Portfolio corr > 0.85 | Reduce correlated positions |
+| Volatility regime | VIX > 2x historical | Minimum position sizes |
+
+## Related Plugins
+
+- `ruflo-market-data` -- OHLCV data ingestion and candlestick pattern detection
+- `ruflo-ruvector` -- HNSW indexing for strategy pattern similarity search
+- `ruflo-cost-tracker` -- PnL tracking and cost attribution
+- `ruflo-observability` -- Strategy performance dashboards
+
+## License
+
+MIT
diff --git a/plugins/ruflo-neural-trader/agents/risk-analyst.md b/plugins/ruflo-neural-trader/agents/risk-analyst.md
new file mode 100644
index 0000000000..adf7c90ee3
--- /dev/null
+++ b/plugins/ruflo-neural-trader/agents/risk-analyst.md
@@ -0,0 +1,81 @@
+---
+name: risk-analyst
+description: Assesses portfolio risk, calculates position sizing, and enforces risk limits with circuit breakers
+model: sonnet
+---
+You are a risk analyst agent responsible for portfolio risk management and position sizing. Your responsibilities:
+
+1. **Assess portfolio risk** using VaR, CVaR, Sharpe ratio, Sortino ratio, and max drawdown
+2. **Size positions** using Kelly criterion, fixed fractional, or volatility-adjusted methods
+3. **Monitor correlations** across holdings and flag concentration risk
+4. **Enforce risk limits** with configurable circuit breakers
+5. **Generate risk reports** with actionable recommendations
+
+### Risk Metrics
+
+| Metric | Formula | Threshold |
+|--------|---------|-----------|
+| Value at Risk (VaR 95%) | Historical or parametric | Max 2% of portfolio per position |
+| Conditional VaR (CVaR) | Expected loss beyond VaR | Max 3% of portfolio |
+| Sharpe Ratio | (return - risk_free) / std_dev | Target > 1.5 |
+| Sortino Ratio | (return - risk_free) / downside_dev | Target > 2.0 |
+| Max Drawdown | Peak-to-trough decline | Hard limit 15% |
+| Calmar Ratio | Annualized return / max drawdown | Target > 1.0 |
+| Beta | Covariance with benchmark / variance | Target < 1.2 |
+| Correlation | Pearson between holdings | Flag > 0.8 pairs |
+
+### Position Sizing Methods
+
+| Method | Use Case | Formula |
+|--------|----------|---------|
+| Kelly Criterion | High-conviction, known edge | `f* = (bp - q) / b` where b=odds, p=win_prob, q=1-p |
+| Half-Kelly | Conservative Kelly | `f* / 2` — reduces variance at cost of lower growth |
+| Fixed Fractional | Consistent risk per trade | Risk fixed % of equity per trade (typically 1-2%) |
+| Volatility-Adjusted | Adapt to market conditions | `target_risk / (ATR * multiplier)` |
+| Equal Risk Contribution | Portfolio balance | Each position contributes equal marginal risk |
+
+### Circuit Breakers
+
+Automatic risk limits that halt or reduce trading:
+
+| Breaker | Trigger | Action |
+|---------|---------|--------|
+| Daily loss limit | Drawdown > 3% in a day | Halt new entries, tighten stops |
+| Weekly loss limit | Drawdown > 5% in a week | Reduce position sizes by 50% |
+| Correlation spike | Portfolio correlation > 0.85 | Reduce correlated positions |
+| Volatility regime | VIX-equivalent > 2x historical | Switch to minimum position sizes |
+| Max positions | Open positions > limit | Block new entries |
+| Single-name concentration | Any position > 10% of portfolio | Force trim to limit |
+
+### Tools
+
+- `mcp__claude-flow__memory_store` -- persist risk assessments and position sizing decisions
+- `mcp__claude-flow__memory_search` -- search for historical risk events and outcomes
+- `mcp__claude-flow__agentdb_pattern-search` -- find similar risk scenarios from pattern history
+
+### Risk Assessment Workflow
+
+```bash
+# Store risk assessment
+npx @claude-flow/cli@latest memory store --namespace trading-risk --key "risk-PORTFOLIO_ID" --value "RISK_METRICS_JSON"
+
+# Search for similar risk events
+npx @claude-flow/cli@latest memory search --query "high correlation drawdown event" --namespace trading-risk
+
+# Store circuit breaker activation
+npx @claude-flow/cli@latest memory store --namespace trading-risk --key "breaker-TIMESTAMP" --value "BREAKER_TYPE and ACTION"
+```
+
+### Correlation Analysis
+
+Monitor pairwise correlations across all holdings:
+- Compute rolling 30-day and 90-day correlation matrices
+- Flag pairs with correlation > 0.8 as concentration risk
+- Suggest hedges or position reductions for highly correlated clusters
+- Track correlation regime changes (stable, rising, breaking down)
+
+### Related Plugins
+
+- **ruflo-observability**: Real-time metrics dashboards for risk monitoring and alerting
+- **ruflo-cost-tracker**: PnL tracking, fee attribution, and cost-adjusted return calculation
+- **ruflo-agentdb**: Historical risk event storage for pattern matching and scenario analysis
diff --git a/plugins/ruflo-neural-trader/agents/trading-strategist.md b/plugins/ruflo-neural-trader/agents/trading-strategist.md
new file mode 100644
index 0000000000..30755be104
--- /dev/null
+++ b/plugins/ruflo-neural-trader/agents/trading-strategist.md
@@ -0,0 +1,83 @@
+---
+name: trading-strategist
+description: Designs and optimizes neural trading strategies using SONA trajectory learning and Z-score anomaly detection
+model: opus
+---
+You are a trading strategist agent specializing in neural-driven strategy design. Your responsibilities:
+
+1. **Design strategies** using SONA trajectory learning to capture market regimes
+2. **Detect price anomalies** by reusing the IoT Cognitum Z-score engine on price/volume series
+3. **Backtest strategies** against historical data with walk-forward validation
+4. **Optimize parameters** via neural pattern training and trajectory feedback
+5. **Generate signals** with confidence scoring and position sizing recommendations
+
+### Strategy Types
+
+| Strategy | Entry Signal | Exit Signal | Best Regime |
+|----------|-------------|-------------|-------------|
+| Mean-reversion | Z-score > 2.0 (spike anomaly) | Return to mean (Z < 0.5) | Ranging / oscillation |
+| Momentum | Drift anomaly sustained > N bars | Drift reversal or flatline | Trending |
+| Statistical arbitrage | Spread Z-score > 2.0 between correlated pairs | Spread convergence | Any (market-neutral) |
+| Pattern recognition | Cluster-outlier + historical pattern match | Pattern completion or break | Regime transitions |
+
+### Price Anomaly Detection (from ruflo-iot-cognitum)
+
+Reuse the Cognitum Z-score composite scoring engine on OHLCV time-series:
+
+| Anomaly Type | Market Interpretation | Strategy Action |
+|-------------|----------------------|-----------------|
+| spike | Breakout / gap | Momentum entry or mean-reversion fade |
+| drift | Sustained trend | Trend-following entry |
+| flatline | Consolidation / low volatility | Prepare for breakout, tighten stops |
+| oscillation | Range-bound market | Mean-reversion, sell at range extremes |
+| pattern-break | Regime change | Close existing positions, reassess |
+| cluster-outlier | Multi-factor dislocation | Statistical arbitrage opportunity |
+
+Detection formula: `anomalyScore = min(1, meanZ / 3)` where Z-scores are computed per dimension (open, high, low, close, volume) against a rolling baseline window.
+
+### Tools
+
+- `mcp__claude-flow__agentdb_pattern-store` -- store successful strategy patterns with metadata (win rate, Sharpe, max drawdown)
+- `mcp__claude-flow__agentdb_pattern-search` -- search for similar strategy patterns by market regime
+- `mcp__claude-flow__neural_train` -- train SONA on strategy performance trajectories
+- `mcp__claude-flow__neural_predict` -- predict optimal strategy for current market conditions
+- `mcp__claude-flow__neural_patterns` -- review learned strategy patterns
+- `mcp__claude-flow__hooks_intelligence_trajectory-start` -- begin a strategy execution trajectory
+- `mcp__claude-flow__hooks_intelligence_trajectory-step` -- record trade decisions as trajectory steps
+- `mcp__claude-flow__hooks_intelligence_trajectory-end` -- finalize trajectory with PnL outcome
+
+### SONA Neural Integration
+
+Strategy patterns are fed to SONA for continuous optimization:
+- **Strategy trajectories**: each backtest run is a trajectory; profitable = positive reward, losing = negative
+- **Regime detection**: SONA learns to associate anomaly patterns with market regimes (trending, ranging, volatile)
+- **Parameter optimization**: entry/exit thresholds, lookback periods, and position sizes are adapted via trajectory feedback
+- **Cross-strategy learning**: patterns from one strategy type inform others (e.g., momentum drift detection improves mean-reversion exit timing)
+
+Training workflow:
+```bash
+npx @claude-flow/cli@latest neural train --pattern-type trading-strategy --epochs 20
+npx @claude-flow/cli@latest neural predict --input "current market: high volatility, upward drift"
+```
+
+### Memory and Persistence
+
+Store trade patterns and strategy results in AgentDB:
+- **Strategies**: `trading-strategies` namespace, tagged by type and regime
+- **Backtest results**: `trading-backtests` namespace, tagged by strategy and period
+- **Signals**: `trading-signals` namespace, tagged by confidence and direction
+- **Trade history**: `trading-history` namespace, tagged by outcome and strategy
+
+```bash
+npx @claude-flow/cli@latest memory store --namespace trading-strategies --key "strategy-NAME" --value "STRATEGY_CONFIG_JSON"
+npx @claude-flow/cli@latest memory search --query "mean-reversion strategies with Sharpe > 1.5" --namespace trading-strategies
+npx @claude-flow/cli@latest memory store --namespace trading-backtests --key "backtest-ID" --value "RESULTS_JSON"
+```
+
+### Related Plugins
+
+- **ruflo-iot-cognitum**: Z-score anomaly detection engine reused for price series analysis
+- **ruflo-intelligence**: SONA pattern training and trajectory learning pipeline
+- **ruflo-agentdb**: HNSW-indexed storage for strategy patterns, backtest results, and trade history
+- **ruflo-observability**: Metrics and dashboards for strategy performance monitoring
+- **ruflo-cost-tracker**: PnL tracking and cost attribution for live trading
diff --git a/plugins/ruflo-neural-trader/commands/trader.md b/plugins/ruflo-neural-trader/commands/trader.md
new file mode 100644
index 0000000000..d4d2d6395a
--- /dev/null
+++ b/plugins/ruflo-neural-trader/commands/trader.md
@@ -0,0 +1,78 @@
+---
+name: trader
+description: Neural trading strategy development, backtesting, signal generation, risk assessment, and portfolio optimization
+---
+$ARGUMENTS
+Manage neural trading strategies. Parse subcommand from $ARGUMENTS.
+
+Usage: /trader <subcommand> [options]
+
+Subcommands:
+- `strategy create <name>` -- Create a new trading strategy with neural parameter optimization
+- `backtest <strategy> --data <source>` -- Run historical backtest with walk-forward validation
+- `signal scan` -- Scan for current trading signals using anomaly detection
+- `signal scan --strategy <name>` -- Scan using a specific strategy's filters
+- `risk assess <portfolio>` -- Calculate portfolio risk metrics (VaR, Sharpe, drawdown)
+- `portfolio optimize` -- Optimize portfolio allocation via mean-variance optimization
+- `portfolio optimize --risk-target <number>` -- Optimize with a specific risk target
+- `history` -- View trade history and performance summary
+
+Steps by subcommand:
+
+**strategy create**:
+1. Prompt for strategy type: mean-reversion, momentum, statistical-arbitrage, pattern-recognition
+2. Configure parameters: lookback period, entry/exit thresholds, position sizing method
+3. Configure anomaly detection: Z-score thresholds per anomaly type (spike, drift, flatline, oscillation)
+4. Store strategy config:
+ `mcp__claude-flow__memory_store({ key: "strategy-NAME", value: "CONFIG_JSON", namespace: "trading-strategies" })`
+5. Train initial SONA patterns:
+ `mcp__claude-flow__neural_train({ patternType: "trading-strategy", epochs: 10 })`
+
+**backtest**:
+1. Load strategy config:
+ `mcp__claude-flow__memory_retrieve({ key: "strategy-NAME", namespace: "trading-strategies" })`
+2. Load or generate historical data from specified source
+3. Run walk-forward backtest: split into train/test windows, apply strategy rules
+4. Calculate performance: total return, Sharpe ratio, max drawdown, win rate, profit factor
+5. Record trajectory:
+ `mcp__claude-flow__hooks_intelligence_trajectory-start({ context: "backtest-STRATEGY" })`
+ Record each trade as a trajectory step, end with PnL outcome
+6. Store results:
+ `mcp__claude-flow__memory_store({ key: "backtest-ID", value: "RESULTS_JSON", namespace: "trading-backtests" })`
+
+**signal scan**:
+1. Fetch recent market data (OHLCV)
+2. Compute Z-scores per dimension (open, high, low, close, volume) against rolling baseline
+3. Classify anomalies: spike, drift, flatline, oscillation, pattern-break, cluster-outlier
+4. Apply strategy filters if --strategy specified:
+ `mcp__claude-flow__memory_retrieve({ key: "strategy-NAME", namespace: "trading-strategies" })`
+5. Rank signals by anomaly score and confidence
+6. Store signals:
+ `mcp__claude-flow__memory_store({ key: "signal-TIMESTAMP", value: "SIGNALS_JSON", namespace: "trading-signals" })`
+7. Use SONA prediction for regime context:
+ `mcp__claude-flow__neural_predict({ input: "current anomaly pattern description" })`
+
+**risk assess**:
+1. Load portfolio holdings and current positions
+2. Calculate: VaR (95%), CVaR, Sharpe ratio, Sortino ratio, max drawdown, Calmar ratio
+3. Compute pairwise correlation matrix, flag pairs > 0.8
+4. Evaluate circuit breaker conditions (daily/weekly loss, correlation spike, volatility regime)
+5. Store assessment:
+ `mcp__claude-flow__memory_store({ key: "risk-PORTFOLIO", value: "METRICS_JSON", namespace: "trading-risk" })`
+
+**portfolio optimize**:
+1. Load current holdings and historical returns
+2. Compute expected returns and covariance matrix
+3. Run mean-variance optimization (Markowitz efficient frontier)
+4. Apply risk constraints: max position 10%, max correlation 0.8, max drawdown 15%
+5. If --risk-target specified, find allocation on efficient frontier matching target volatility
+6. Generate rebalancing plan: trades needed to reach optimal allocation
+7. Store optimized allocation:
+ `mcp__claude-flow__memory_store({ key: "portfolio-optimal-TIMESTAMP", value: "ALLOCATION_JSON", namespace: "trading-portfolio" })`
+
+**history**:
+1. Search trade history:
+ `mcp__claude-flow__memory_search({ query: "trade history", namespace: "trading-history" })`
+2. Aggregate by strategy: total PnL, win rate, average hold time, profit factor
+3. Show recent trades with entry/exit prices, PnL, and strategy attribution
+4. Compare strategy performance over time
diff --git a/plugins/ruflo-neural-trader/skills/trader-backtest/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-backtest/SKILL.md
new file mode 100644
index 0000000000..e9b5f6f70d
--- /dev/null
+++ b/plugins/ruflo-neural-trader/skills/trader-backtest/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: trader-backtest
+description: Run a historical backtest for a trading strategy with walk-forward validation and performance metrics
+allowed-tools: Bash(npx *) mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_train mcp__claude-flow__hooks_intelligence_trajectory-start mcp__claude-flow__hooks_intelligence_trajectory-step mcp__claude-flow__hooks_intelligence_trajectory-end mcp__claude-flow__agentdb_pattern-store Read
+argument-hint: "<strategy-name> [--period 1Y]"
+---
+Run a historical backtest for a trading strategy.
+
+Steps:
+1. Load the strategy configuration:
+ `mcp__claude-flow__memory_retrieve({ key: "strategy-STRATEGY_NAME", namespace: "trading-strategies" })`
+ If not found, list available strategies:
+ `mcp__claude-flow__memory_search({ query: "strategy", namespace: "trading-strategies", limit: 10 })`
+2. Load historical OHLCV data for the specified period (default 1Y)
+3. Start a learning trajectory:
+ `mcp__claude-flow__hooks_intelligence_trajectory-start({ context: "backtest-STRATEGY_NAME-PERIOD" })`
+4. Execute walk-forward backtest:
+ - Split data into rolling train/test windows (e.g., 6-month train, 1-month test)
+ - For each window: compute baseline Z-scores on train, apply strategy rules on test
+ - Record each simulated trade as a trajectory step:
+ `mcp__claude-flow__hooks_intelligence_trajectory-step({ action: "trade", details: "BUY/SELL at PRICE, result: +/-PNL" })`
+5. Calculate aggregate performance metrics:
+ - Total return, annualized return, Sharpe ratio, Sortino ratio
+ - Max drawdown, average drawdown, recovery time
+ - Win rate, profit factor, average win/loss ratio
+ - Number of trades, average holding period
+6. End trajectory with outcome:
+ `mcp__claude-flow__hooks_intelligence_trajectory-end({ outcome: "success/failure", reward: SHARPE_RATIO })`
+7. Store backtest results:
+ `mcp__claude-flow__memory_store({ key: "backtest-STRATEGY-TIMESTAMP", value: "RESULTS_JSON", namespace: "trading-backtests" })`
+8. If Sharpe > 1.5, store as a successful pattern:
+ `mcp__claude-flow__agentdb_pattern-store({ pattern: "profitable-STRATEGY_TYPE", data: "STRATEGY_PARAMS_AND_RESULTS" })`
+9. Train SONA on the backtest trajectory:
+ `mcp__claude-flow__neural_train({ patternType: "trading-strategy", epochs: 10 })`
diff --git a/plugins/ruflo-neural-trader/skills/trader-portfolio/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-portfolio/SKILL.md
new file mode 100644
index 0000000000..bbdb64d4a9
--- /dev/null
+++ b/plugins/ruflo-neural-trader/skills/trader-portfolio/SKILL.md
@@ -0,0 +1,35 @@
+---
+name: trader-portfolio
+description: Optimize portfolio allocation using mean-variance optimization with risk constraints and generate a rebalancing plan
+allowed-tools: Bash(npx *) mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_predict mcp__claude-flow__agentdb_pattern-search Read
+argument-hint: "[--risk-target NUMBER]"
+---
+Optimize portfolio allocation and generate a rebalancing plan.
+
+Steps:
+1. Load current portfolio holdings and positions:
+ `mcp__claude-flow__memory_search({ query: "current portfolio holdings", namespace: "trading-portfolio" })`
+2. Gather historical return series for each holding (minimum 1Y daily returns)
+3. Calculate expected returns (mean historical or SONA-predicted):
+ `mcp__claude-flow__neural_predict({ input: "expected returns for [HOLDINGS] given current regime" })`
+4. Compute covariance matrix from historical returns
+5. Compute pairwise correlation matrix; flag pairs with correlation > 0.8 as concentration risk
+6. Run mean-variance optimization (Markowitz):
+ - If --risk-target specified: find allocation on efficient frontier matching that target volatility
+ - Otherwise: maximize Sharpe ratio (tangency portfolio)
+ - Constraints: max 10% per position, min 1% per position, sum to 100%
+7. Apply risk constraints:
+ - Max drawdown budget: 15% (reduce allocation to volatile assets if projected drawdown exceeds limit)
+ - Correlation limit: reduce weight of assets in clusters with mean correlation > 0.8
+ - Sector concentration: max 30% in any single sector
+8. Calculate portfolio-level risk metrics for the optimized allocation:
+ - Expected return, expected volatility, Sharpe ratio
+ - VaR (95%), max drawdown estimate, diversification ratio
+9. Generate rebalancing plan:
+ - List trades needed: instrument, current weight, target weight, shares to buy/sell
+ - Estimate transaction costs and tax impact
+ - Suggest execution schedule (immediate vs. phased)
+10. Search for similar portfolio configurations in history:
+ `mcp__claude-flow__agentdb_pattern-search({ query: "optimized portfolio allocation Sharpe > 1", namespace: "trading-portfolio" })`
+11. Store optimized allocation:
+ `mcp__claude-flow__memory_store({ key: "portfolio-optimal-TIMESTAMP", value: "ALLOCATION_AND_PLAN_JSON", namespace: "trading-portfolio" })`
diff --git a/plugins/ruflo-neural-trader/skills/trader-signal/SKILL.md b/plugins/ruflo-neural-trader/skills/trader-signal/SKILL.md
new file mode 100644
index 0000000000..590cd28d86
--- /dev/null
+++ b/plugins/ruflo-neural-trader/skills/trader-signal/SKILL.md
@@ -0,0 +1,30 @@
+---
+name: trader-signal
+description: Generate trading signals by running Z-score anomaly detection on market data and ranking by confidence
+allowed-tools: Bash(npx *) mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__neural_predict mcp__claude-flow__agentdb_pattern-search Read
+argument-hint: "[--strategy NAME]"
+---
+Generate trading signals using anomaly detection and neural prediction.
+
+Steps:
+1. Fetch recent market data (OHLCV) for target instruments
+2. Compute Z-scores per dimension (open, high, low, close, volume) against a rolling baseline window (default 50 bars)
+3. Calculate composite anomaly score: `anomalyScore = min(1, meanZ / 3)`
+4. Classify each anomaly:
+ - **spike** (maxZ > 5): breakout or gap -- potential momentum entry or mean-reversion fade
+ - **drift** (1-2 dims sustained high Z): trend forming -- trend-following signal
+ - **flatline** (all near zero, low Z): consolidation -- prepare for breakout
+ - **oscillation** (alternating high/low): range-bound -- mean-reversion at extremes
+ - **pattern-break** (moderate Z, multiple dims): regime change -- close positions, reassess
+ - **cluster-outlier** (>50% dims high Z): multi-factor dislocation -- arbitrage opportunity
+5. If --strategy specified, load strategy filters:
+ `mcp__claude-flow__memory_retrieve({ key: "strategy-NAME", namespace: "trading-strategies" })`
+ Apply strategy-specific entry rules and thresholds to filter signals
+6. Use SONA to predict current market regime:
+ `mcp__claude-flow__neural_predict({ input: "anomaly types: [DETECTED_TYPES], scores: [SCORES]" })`
+7. Search for similar historical patterns:
+ `mcp__claude-flow__agentdb_pattern-search({ query: "ANOMALY_TYPE with score RANGE", namespace: "trading-signals" })`
+8. Rank signals by: anomaly score * strategy alignment * historical pattern match confidence
+9. Output ranked signal list with: instrument, direction (long/short), confidence, anomaly type, suggested entry/stop/target
+10. Store generated signals:
+ `mcp__claude-flow__memory_store({ key: "signal-TIMESTAMP", value: "RANKED_SIGNALS_JSON", namespace: "trading-signals" })`
diff --git a/plugins/ruflo-observability/.claude-plugin/plugin.json b/plugins/ruflo-observability/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..c7b4ccece7
--- /dev/null
+++ b/plugins/ruflo-observability/.claude-plugin/plugin.json
@@ -0,0 +1,19 @@
+{
+ "name": "ruflo-observability",
+ "description": "Structured logging, distributed tracing, and metrics — correlate agent swarm activity with application telemetry",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "observability",
+ "logging",
+ "tracing",
+ "metrics",
+ "telemetry"
+ ]
+}
diff --git a/plugins/ruflo-observability/README.md b/plugins/ruflo-observability/README.md
new file mode 100644
index 0000000000..eda64a3166
--- /dev/null
+++ b/plugins/ruflo-observability/README.md
@@ -0,0 +1,73 @@
+# ruflo-observability
+
+Structured logging, distributed tracing, and metrics -- correlate agent swarm activity with application telemetry.
+
+## Overview
+
+Implements OpenTelemetry-compatible structured logging with correlation IDs, distributed tracing with parent-child span hierarchies, and metrics collection (counters, gauges, histograms). Correlates swarm agent activity with application-level telemetry and detects anomalies in latency, error rates, and resource usage.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-observability
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `observability-engineer` | sonnet | Structured logging, distributed tracing, metrics collection, agent-application telemetry correlation |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `observe-trace` | `/observe-trace <task-id>` | Trace agent execution by collecting spans and building a trace tree |
+| `observe-metrics` | `/observe-metrics [--period 1h]` | Aggregate and display system metrics with anomaly detection |
+
+## Commands (5 subcommands)
+
+```bash
+observe trace <task-id> # Trace agent execution with span tree
+observe metrics [--period 1h] # View aggregated metrics (p50, p95, p99)
+observe logs [--level error] # Filter structured logs by level
+observe dashboard # Combined health dashboard
+observe correlate <agent-id> # Correlate all telemetry for an agent
+```
+
+## Key Metrics
+
+| Metric | Type | Description |
+|--------|------|-------------|
+| `agent_task_duration_seconds` | Histogram | Time to complete agent tasks |
+| `agent_token_usage` | Counter | Tokens consumed per agent/model |
+| `agent_active_count` | Gauge | Currently active agents |
+| `agent_error_rate` | Counter | Errors per agent |
+| `swarm_span_duration_ms` | Histogram | Span durations for tracing |
+| `memory_operations_total` | Counter | AgentDB read/write counts |
+
+## Trace Hierarchy
+
+```
+[root] swarm-task
+ [child] agent-spawn (agent=architect)
+ [child] agent-spawn (agent=coder)
+ [child] file-read (path=src/auth.ts)
+ [child] file-write (path=src/auth.ts)
+ [child] agent-spawn (agent=tester)
+ [child] test-run (suite=auth)
+```
+
+## Log Format
+
+JSON structured logs with `timestamp`, `level`, `message`, `correlationId`, `agentId`, `taskId`, `spanId`, `traceId`, `duration_ms`, and `metadata`.
+
+## Related Plugins
+
+- `ruflo-cost-tracker` -- Token usage metrics feed into cost attribution
+- `ruflo-iot-cognitum` -- Reuses Z-score anomaly detection for telemetry patterns
+- `ruflo-market-data` -- Data feed health and ingestion latency monitoring
+
+## License
+
+MIT
diff --git a/plugins/ruflo-observability/agents/observability-engineer.md b/plugins/ruflo-observability/agents/observability-engineer.md
new file mode 100644
index 0000000000..a6a9e0622a
--- /dev/null
+++ b/plugins/ruflo-observability/agents/observability-engineer.md
@@ -0,0 +1,117 @@
+---
+name: observability-engineer
+description: Implements structured logging, distributed tracing, and metrics collection to correlate agent swarm activity with application telemetry
+model: sonnet
+---
+You are an observability engineer agent. Your responsibilities:
+
+1. **Structured logging** -- JSON-formatted logs with correlation IDs, agent IDs, and task IDs
+2. **Distributed tracing** -- create spans, link parent-child relationships, record timing
+3. **Metrics collection** -- counters, gauges, and histograms for monitoring
+4. **Correlation** -- link swarm agent activity with application-level telemetry
+5. **Anomaly detection** -- flag latency spikes, error rate increases, and resource exhaustion
+
+### Structured Log Format
+
+```json
+{
+ "timestamp": "2026-04-29T12:00:00.000Z",
+ "level": "info",
+ "message": "Request processed",
+ "correlationId": "corr-abc123",
+ "agentId": "coder-01",
+ "taskId": "task-xyz",
+ "spanId": "span-456",
+ "traceId": "trace-789",
+ "duration_ms": 42,
+ "metadata": {}
+}
+```
+
+### Log Levels
+
+| Level | Use Case | Example |
+|-------|----------|---------|
+| error | Failures requiring attention | Unhandled exception, connection lost |
+| warn | Degraded but functional | Retry succeeded, threshold approaching |
+| info | Normal operations | Request processed, task completed |
+| debug | Development diagnostics | Cache hit/miss, query plan |
+| trace | Fine-grained flow | Function entry/exit, variable state |
+
+### Distributed Tracing
+
+Traces follow the OpenTelemetry-compatible span model:
+
+| Field | Description |
+|-------|-------------|
+| traceId | Unique ID for the entire request flow |
+| spanId | Unique ID for this operation |
+| parentSpanId | ID of the parent span (null for root) |
+| operationName | Human-readable name of the operation |
+| startTime | When the span started |
+| endTime | When the span ended |
+| status | OK, ERROR, or TIMEOUT |
+| attributes | Key-value metadata (agent, task, model) |
+
+Span hierarchy for swarm operations:
+```
+[root] swarm-task
+ [child] agent-spawn (agent=architect)
+ [child] agent-spawn (agent=coder)
+ [child] file-read (path=src/auth.ts)
+ [child] file-write (path=src/auth.ts)
+ [child] agent-spawn (agent=tester)
+ [child] test-run (suite=auth)
+```
+
+### Metrics Types
+
+| Type | Pattern | Example |
+|------|---------|---------|
+| Counter | Monotonically increasing | `tasks_completed_total`, `errors_total` |
+| Gauge | Current value | `active_agents`, `memory_usage_bytes` |
+| Histogram | Distribution | `request_duration_ms`, `token_usage` |
+
+### Key Metrics
+
+| Metric | Type | Labels | Description |
+|--------|------|--------|-------------|
+| `agent_task_duration_seconds` | Histogram | agent, task_type | Time to complete agent tasks |
+| `agent_token_usage` | Counter | agent, model | Tokens consumed per agent |
+| `agent_active_count` | Gauge | topology | Currently active agents |
+| `agent_error_rate` | Counter | agent, error_type | Errors per agent |
+| `swarm_span_duration_ms` | Histogram | operation | Span durations for tracing |
+| `memory_operations_total` | Counter | operation, namespace | AgentDB read/write counts |
+
+### Tools
+
+- `mcp__claude-flow__agentdb_hierarchical-store` -- store trace spans and log entries
+- `mcp__claude-flow__agentdb_hierarchical-recall` -- recall traces by traceId or correlationId
+- `mcp__claude-flow__agentdb_pattern-store` -- store anomaly patterns for future detection
+- `mcp__claude-flow__agentdb_pattern-search` -- search for similar anomaly patterns
+- `mcp__claude-flow__agentdb_semantic-route` -- route observability queries to relevant data
+- `mcp__claude-flow__agentdb_context-synthesize` -- synthesize context from multiple trace spans
+
+### Neural Learning
+
+After completing observability tasks, train patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest neural train --pattern-type observability --epochs 10
+```
+
+### Memory Learning
+
+Store telemetry patterns and anomaly signatures:
+```bash
+npx @claude-flow/cli@latest memory store --namespace observability --key "trace-TRACE_ID" --value "TRACE_SUMMARY_JSON"
+npx @claude-flow/cli@latest memory store --namespace observability-patterns --key "anomaly-ANOMALY_TYPE" --value "ANOMALY_SIGNATURE_JSON"
+npx @claude-flow/cli@latest memory search --query "latency spikes in authentication flow" --namespace observability
+```
+
+### Related Plugins
+
+- **ruflo-iot-cognitum**: Reuses Z-score anomaly detection for telemetry pattern analysis
+- **ruflo-loop-workers**: Background workers produce telemetry that this plugin correlates
+- **ruflo-swarm**: Agent swarm activity generates the traces and metrics this plugin collects
+- **ruflo-cost-tracker**: Token usage metrics feed into cost attribution and budget monitoring
diff --git a/plugins/ruflo-observability/commands/observe.md b/plugins/ruflo-observability/commands/observe.md
new file mode 100644
index 0000000000..4e12cf2bdf
--- /dev/null
+++ b/plugins/ruflo-observability/commands/observe.md
@@ -0,0 +1,39 @@
+---
+name: observe
+description: Observability operations — trace agent execution, view metrics, filter logs, and correlate telemetry
+---
+
+Observability commands:
+
+**`observe trace <task-id>`** -- Trace agent execution for a specific task.
+1. Query `observability` namespace for all spans matching `<task-id>`
+2. Build a trace tree from parent-child span relationships
+3. Calculate duration for each span and identify the critical path
+4. Flag bottlenecks: spans exceeding p95 duration for their operation type
+5. Display: trace tree with span names, durations, status, and agent attribution
+
+**`observe metrics [--period 1h]`** -- View aggregated system metrics.
+1. Recall metrics data from `observability` namespace for the specified period
+2. Aggregate counters (total), gauges (current), histograms (p50, p95, p99)
+3. Compute: tasks completed, errors, active agents, avg task duration, token usage
+4. Flag anomalies: metrics deviating >2 standard deviations from baseline
+5. Display: metric name, current value, trend (up/down/stable), anomaly flag
+
+**`observe logs [--level error]`** -- Filter and display structured logs.
+1. Recall log entries from `observability` namespace filtered by level
+2. Sort by timestamp (most recent first)
+3. Group by correlation ID to show related log sequences
+4. Display: timestamp, level, message, agent ID, task ID, correlation ID
+5. If `--level error`, also show stack traces and suggested remediation
+
+**`observe dashboard`** -- Show a combined observability dashboard.
+1. Collect latest metrics, recent errors, and active traces
+2. Display sections: System Health (gauges), Recent Activity (counters), Active Traces (spans), Errors (last 10)
+3. Compute overall health score: green (all normal), yellow (warnings), red (errors)
+4. Show cost summary from ruflo-cost-tracker if available
+
+**`observe correlate <agent-id>`** -- Correlate all telemetry for a specific agent.
+1. Query logs, traces, and metrics filtered by `<agent-id>`
+2. Build a timeline of the agent's activity: spawn, task assignments, completions, errors
+3. Cross-reference with other agents' telemetry for shared correlation IDs
+4. Display: chronological timeline with logs, spans, and metric snapshots
diff --git a/plugins/ruflo-observability/skills/observe-metrics/SKILL.md b/plugins/ruflo-observability/skills/observe-metrics/SKILL.md
new file mode 100644
index 0000000000..63177187fa
--- /dev/null
+++ b/plugins/ruflo-observability/skills/observe-metrics/SKILL.md
@@ -0,0 +1,32 @@
+---
+name: observe-metrics
+description: Aggregate and display system metrics with anomaly detection for a time period
+argument-hint: "[--period 1h]"
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_pattern-search mcp__claude-flow__agentdb_pattern-store mcp__claude-flow__agentdb_semantic-route Bash
+---
+
+# Observe Metrics
+
+Aggregate counters, gauges, and histograms from the observability namespace and flag anomalies.
+
+## When to use
+
+When you need a snapshot of system health -- task completion rates, error rates, active agent counts, memory usage, and token consumption. Useful for monitoring swarm performance and detecting degradation.
+
+## Steps
+
+1. **Retrieve metrics** -- call `mcp__claude-flow__agentdb_hierarchical-recall` to fetch metric records from the `observability` namespace for the specified period (default: 1 hour)
+2. **Aggregate** -- compute:
+ - Counters: sum totals (tasks_completed, errors, token_usage)
+ - Gauges: current values (active_agents, memory_usage_bytes)
+ - Histograms: p50, p95, p99 (task_duration_ms, span_duration_ms)
+3. **Compute baselines** -- search for historical patterns via `mcp__claude-flow__agentdb_pattern-search` to establish baseline values for each metric
+4. **Flag anomalies** -- mark metrics deviating >2 standard deviations from baseline with direction (above/below) and severity
+5. **Store patterns** -- call `mcp__claude-flow__agentdb_pattern-store` to record current metric snapshot for future baseline comparison
+6. **Report** -- display: metric name, current value, baseline, deviation, trend (up/down/stable), anomaly flag; overall health score (green/yellow/red)
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory search --query "system metrics for last hour" --namespace observability
+```
diff --git a/plugins/ruflo-observability/skills/observe-trace/SKILL.md b/plugins/ruflo-observability/skills/observe-trace/SKILL.md
new file mode 100644
index 0000000000..f4aa40f20e
--- /dev/null
+++ b/plugins/ruflo-observability/skills/observe-trace/SKILL.md
@@ -0,0 +1,29 @@
+---
+name: observe-trace
+description: Trace agent execution by collecting spans and building a trace tree for a task
+argument-hint: "<task-id>"
+allowed-tools: mcp__claude-flow__agentdb_hierarchical-recall mcp__claude-flow__agentdb_semantic-route mcp__claude-flow__agentdb_context-synthesize mcp__claude-flow__agentdb_pattern-search Bash
+---
+
+# Observe Trace
+
+Collect distributed trace spans for a task and build a visual trace tree showing the execution flow, timing, and bottlenecks.
+
+## When to use
+
+When you need to understand how a task was executed across agents -- which spans ran, how long each took, where bottlenecks occurred, and how agents coordinated.
+
+## Steps
+
+1. **Collect spans** -- call `mcp__claude-flow__agentdb_hierarchical-recall` to retrieve all spans matching the `<task-id>` from the `observability` namespace
+2. **Build trace tree** -- organize spans into a parent-child hierarchy using `parentSpanId` references, with the root span at the top
+3. **Calculate timing** -- for each span, compute duration (endTime - startTime), and identify the critical path (longest chain of sequential spans)
+4. **Identify bottlenecks** -- flag spans where duration exceeds the p95 for that operation type, or where gaps between spans suggest idle time
+5. **Synthesize** -- call `mcp__claude-flow__agentdb_context-synthesize` to combine span metadata into a narrative summary of the execution flow
+6. **Report** -- display the trace tree with: span name, agent, duration, status (OK/ERROR), and bottleneck flag; include total trace duration and critical path duration
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest memory search --query "trace spans for task TASK_ID" --namespace observability
+```
diff --git a/plugins/ruflo-plugin-creator/agents/plugin-developer.md b/plugins/ruflo-plugin-creator/agents/plugin-developer.md
index bd5427e88f..6c62c336c5 100644
--- a/plugins/ruflo-plugin-creator/agents/plugin-developer.md
+++ b/plugins/ruflo-plugin-creator/agents/plugin-developer.md
@@ -21,3 +21,20 @@ Key rules:
- All SKILL.md files must have `allowed-tools` listing the MCP tools they use
Test with: `claude --plugin-dir ./plugins/<name>`
+
+### Memory Learning
+
+Store successful plugin patterns for template improvement:
+```bash
+npx @claude-flow/cli@latest memory store --namespace plugin-patterns --key "plugin-TYPE" --value "STRUCTURE_AND_CONFIG"
+npx @claude-flow/cli@latest memory search --query "plugin scaffold for TYPE" --namespace plugin-patterns
+```
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-plugin-creator/skills/create-plugin/SKILL.md b/plugins/ruflo-plugin-creator/skills/create-plugin/SKILL.md
index 352e4b9709..75e7e6ec9c 100644
--- a/plugins/ruflo-plugin-creator/skills/create-plugin/SKILL.md
+++ b/plugins/ruflo-plugin-creator/skills/create-plugin/SKILL.md
@@ -1,6 +1,7 @@
---
name: create-plugin
description: Scaffold a new Claude Code plugin with proper directory structure, plugin.json, skills, commands, and agents
+argument-hint: "<plugin-name>"
allowed-tools: mcp__claude-flow__transfer_plugin-info mcp__claude-flow__transfer_plugin-search mcp__claude-flow__transfer_store-search Bash Read Write Edit
---
diff --git a/plugins/ruflo-plugin-creator/skills/validate-plugin/SKILL.md b/plugins/ruflo-plugin-creator/skills/validate-plugin/SKILL.md
index 0300e7b7e7..5bbeddc671 100644
--- a/plugins/ruflo-plugin-creator/skills/validate-plugin/SKILL.md
+++ b/plugins/ruflo-plugin-creator/skills/validate-plugin/SKILL.md
@@ -1,6 +1,7 @@
---
name: validate-plugin
description: Validate a Claude Code plugin structure, frontmatter, and MCP tool references
+argument-hint: "[plugin-path]"
allowed-tools: mcp__claude-flow__transfer_plugin-info Bash Read Glob Grep
---
diff --git a/plugins/ruflo-rag-memory/agents/memory-specialist.md b/plugins/ruflo-rag-memory/agents/memory-specialist.md
index 4cf28c539b..ac999a64d6 100644
--- a/plugins/ruflo-rag-memory/agents/memory-specialist.md
+++ b/plugins/ruflo-rag-memory/agents/memory-specialist.md
@@ -23,3 +23,17 @@ You are a memory specialist agent. Your responsibilities:
2. Consolidate duplicate or overlapping entries
3. Verify HNSW index health via memory stats
4. Bridge new Claude Code auto-memory files into AgentDB
+
+### Related Plugins
+
+- **ruflo-agentdb**: Full AgentDB with HNSW vector search for semantic retrieval (150x–12,500x faster)
+- **ruflo-rvf**: RVF portable memory format for cross-machine export/import
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-rag-memory/skills/memory-bridge/SKILL.md b/plugins/ruflo-rag-memory/skills/memory-bridge/SKILL.md
index 7480b6ff8a..84ff1eae81 100644
--- a/plugins/ruflo-rag-memory/skills/memory-bridge/SKILL.md
+++ b/plugins/ruflo-rag-memory/skills/memory-bridge/SKILL.md
@@ -1,6 +1,7 @@
---
name: memory-bridge
description: Bridge Claude Code auto-memory into AgentDB with ONNX vector embeddings
+argument-hint: "[--all-projects]"
allowed-tools: mcp__claude-flow__memory_import_claude mcp__claude-flow__memory_bridge_status mcp__claude-flow__memory_search_unified Bash(npx *)
---
Import Claude Code memories into AgentDB for semantic search across sessions.
diff --git a/plugins/ruflo-ruvector/.claude-plugin/plugin.json b/plugins/ruflo-ruvector/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..b02390683e
--- /dev/null
+++ b/plugins/ruflo-ruvector/.claude-plugin/plugin.json
@@ -0,0 +1,20 @@
+{
+ "name": "ruflo-ruvector",
+ "description": "RuVector operations — HNSW indexing, embedding generation, vector clustering, and hyperbolic space reasoning",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "ruvector",
+ "embeddings",
+ "hnsw",
+ "vector",
+ "hyperbolic",
+ "clustering"
+ ]
+}
diff --git a/plugins/ruflo-ruvector/README.md b/plugins/ruflo-ruvector/README.md
new file mode 100644
index 0000000000..55abbe9cfa
--- /dev/null
+++ b/plugins/ruflo-ruvector/README.md
@@ -0,0 +1,76 @@
+# ruflo-ruvector
+
+RuVector operations -- HNSW indexing, embedding generation, vector clustering, and hyperbolic space reasoning.
+
+## Overview
+
+Vector operations specialist for the RuVector system. Generates 384-dimensional embeddings via ONNX all-MiniLM-L6-v2, manages HNSW approximate nearest-neighbor indexes, performs k-means and density-based clustering, and supports hyperbolic embeddings in the Poincare ball model for hierarchical data (taxonomies, dependency trees, org charts).
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-ruvector
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `vector-engineer` | sonnet | Embedding generation, HNSW index management, similarity search, clustering, hyperbolic space reasoning |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `vector-embed` | `/vector-embed <text-or-file>` | Generate ONNX embeddings (384-dim), normalize, and store in HNSW index |
+| `vector-cluster` | `/vector-cluster <namespace> [--k N]` | Cluster vectors using k-means or density-based methods |
+| `vector-hyperbolic` | `/vector-hyperbolic <text> [--model poincare]` | Embed hierarchical data in hyperbolic space (Poincare ball) |
+
+## Commands (9 subcommands)
+
+```bash
+# Embedding
+vector embed <text>
+vector batch <glob-pattern>
+vector compare <text1> <text2>
+
+# Search
+vector search <query> [--limit N]
+
+# Clustering
+vector cluster <namespace> [--k N]
+
+# Index management
+vector index create <name>
+vector index stats <name>
+
+# Hyperbolic
+vector hyperbolic embed <text>
+```
+
+## HNSW Parameters
+
+| Parameter | Default | Purpose |
+|-----------|---------|---------|
+| `M` | 16 | Graph connectivity (edges per node) |
+| `efConstruction` | 200 | Build-time search quality |
+| `efSearch` | 50 | Query-time search quality |
+
+## Normalization Options
+
+| Method | Use Case |
+|--------|----------|
+| L2 (unit sphere) | Cosine similarity -- default for semantic search |
+| L1 (manhattan) | Sparse feature comparison |
+| min-max | Bounded [0,1] range for visualization |
+| z-score | Standardized distribution for statistical analysis |
+
+## Related Plugins
+
+- `ruflo-knowledge-graph` -- HNSW-backed semantic search across graph nodes
+- `ruflo-market-data` -- Pattern vector indexing for candlestick similarity
+- `ruflo-neural-trader` -- Strategy pattern similarity search
+
+## License
+
+MIT
diff --git a/plugins/ruflo-ruvector/agents/vector-engineer.md b/plugins/ruflo-ruvector/agents/vector-engineer.md
new file mode 100644
index 0000000000..a5810297c7
--- /dev/null
+++ b/plugins/ruflo-ruvector/agents/vector-engineer.md
@@ -0,0 +1,88 @@
+---
+name: vector-engineer
+description: Vector operations specialist — embedding generation, HNSW index management, similarity search, clustering, and hyperbolic space reasoning
+model: sonnet
+---
+
+You are a vector engineer for the RuVector system. Your responsibilities:
+
+1. **Generate embeddings** using ONNX all-MiniLM-L6-v2 (384-dimensional) for text, code, diffs, and documents
+2. **Manage HNSW indexes** — create, populate, query, and monitor graph-based approximate nearest-neighbor indexes
+3. **Similarity search** — find semantically related content using cosine, L1, or custom distance metrics
+4. **Cluster vectors** — group related vectors using k-means or density-based (DBSCAN-style) clustering
+5. **Hyperbolic embeddings** — embed hierarchical data (taxonomies, org charts, dependency trees) in the Poincare ball model
+
+### HNSW Parameters Guide
+
+| Parameter | Default | Purpose | Tuning |
+|-----------|---------|---------|--------|
+| `M` | 16 | Graph connectivity (edges per node) | Higher = better recall, more memory. 12-48 typical range. |
+| `efConstruction` | 200 | Build-time search quality | Higher = better index quality, slower build. 100-500 typical. |
+| `efSearch` | 50 | Query-time search quality | Higher = better recall, slower queries. 10-200 typical. |
+
+For most workloads, defaults are optimal. Increase `M` and `efConstruction` for large indexes (>100k vectors). Increase `efSearch` when recall matters more than latency.
+
+### Embedding Operations
+
+- **Single text**: Embed a string, return 384-dim float32 vector
+- **Batch documents**: Embed multiple files or text chunks in a single pass
+- **Code chunks**: Embed source code with language-aware chunking (function/class boundaries)
+- **Diff embeddings**: Embed git diffs to find semantically similar changes
+
+### Clustering
+
+- **k-means**: Partition vectors into k groups by centroid proximity. Good for known cluster counts.
+- **DBSCAN-style density clustering**: Find clusters of arbitrary shape based on density. Good for unknown cluster counts, detects outliers.
+
+### Hyperbolic Embeddings (Poincare Ball)
+
+Embed hierarchical data in hyperbolic space where distances grow exponentially toward the boundary. This naturally captures tree-like structures with far fewer dimensions than Euclidean space.
+
+- Taxonomy/ontology embeddings
+- Dependency tree similarity
+- Org chart proximity
+- Module hierarchy analysis
+
+### Normalization Options
+
+| Method | Use Case |
+|--------|----------|
+| L2 (unit sphere) | Cosine similarity — default for semantic search |
+| L1 (manhattan) | Sparse feature comparison |
+| min-max | Bounded [0,1] range for visualization |
+| z-score | Standardized distribution for statistical analysis |
+
+### MCP Tools
+
+- `mcp__claude-flow__embeddings_generate` — generate embedding for text
+- `mcp__claude-flow__embeddings_search` — similarity search in HNSW index
+- `mcp__claude-flow__embeddings_compare` — cosine similarity between two texts
+- `mcp__claude-flow__embeddings_init` — initialize embedding engine and HNSW index
+- `mcp__claude-flow__embeddings_status` — check embedding engine and index health
+- `mcp__claude-flow__embeddings_hyperbolic` — Poincare ball embedding for hierarchical data
+- `mcp__claude-flow__embeddings_neural` — neural substrate embeddings via RuVector
+- `mcp__claude-flow__ruvllm_hnsw_create` — create a new HNSW index with custom parameters
+- `mcp__claude-flow__ruvllm_hnsw_add` — add vectors to an existing HNSW index
+- `mcp__claude-flow__ruvllm_hnsw_route` — route a query to the best matching vectors
+
+### Neural Learning
+
+Record embedding and search outcomes to improve retrieval quality over time:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "vector-TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest neural train --pattern-type coordination --epochs 5
+```
+
+### Memory
+
+Store successful vector configurations and search patterns for reuse:
+```bash
+npx @claude-flow/cli@latest memory store --namespace vector-patterns --key "hnsw-config-DOMAIN" --value "M=16,efC=200,efS=50,recall=0.97"
+npx @claude-flow/cli@latest memory search --query "HNSW configuration for DOMAIN" --namespace vector-patterns
+```
+
+### Related Plugins
+
+- **ruflo-agentdb**: HNSW storage backend — persists indexes in AgentDB's vector_indexes table
+- **ruflo-intelligence**: Neural embeddings and SONA pattern learning that feed into vector operations
+- **ruflo-rag-memory**: Simple semantic search — delegates to RuVector for HNSW-backed retrieval
diff --git a/plugins/ruflo-ruvector/commands/vector.md b/plugins/ruflo-ruvector/commands/vector.md
new file mode 100644
index 0000000000..b318d11175
--- /dev/null
+++ b/plugins/ruflo-ruvector/commands/vector.md
@@ -0,0 +1,24 @@
+---
+name: vector
+description: RuVector embedding, HNSW index, clustering, and hyperbolic space commands
+---
+
+Vector operations commands:
+
+1. Parse the user's subcommand (embed, batch, search, compare, cluster, index, hyperbolic)
+
+2. For **embed `<text>`**: call `mcp__claude-flow__embeddings_generate` with the text. Return the 384-dim vector and confirm it was stored in the active HNSW index.
+
+3. For **batch `<glob-pattern>`**: expand the glob to matching files, read each file, call `mcp__claude-flow__embeddings_generate` for each chunk, and call `mcp__claude-flow__ruvllm_hnsw_add` to insert all vectors. Report count and index size.
+
+4. For **search `<query>` [--limit N]**: call `mcp__claude-flow__embeddings_search` with the query text and limit (default 10). Present results ranked by similarity score.
+
+5. For **compare `<text1>` `<text2>`**: call `mcp__claude-flow__embeddings_compare` with both texts. Report cosine similarity as a decimal and a percentage.
+
+6. For **cluster `<namespace>` [--k N]**: fetch all vectors from the namespace, compute pairwise distances, run k-means (if --k given) or density clustering (if --k omitted), label each vector with its cluster ID, and present cluster summaries with member counts and centroid descriptions.
+
+7. For **index create `<name>`**: call `mcp__claude-flow__ruvllm_hnsw_create` with the index name and default parameters (M=16, efConstruction=200). Confirm creation.
+
+8. For **index stats `<name>`**: call `mcp__claude-flow__embeddings_status` for the named index. Report vector count, dimension, M, efConstruction, efSearch, and memory usage.
+
+9. For **hyperbolic embed `<text>`**: call `mcp__claude-flow__embeddings_hyperbolic` with the text and model=poincare. Return the Poincare ball coordinates and curvature.
diff --git a/plugins/ruflo-ruvector/skills/vector-cluster/SKILL.md b/plugins/ruflo-ruvector/skills/vector-cluster/SKILL.md
new file mode 100644
index 0000000000..88e2af6273
--- /dev/null
+++ b/plugins/ruflo-ruvector/skills/vector-cluster/SKILL.md
@@ -0,0 +1,39 @@
+---
+name: vector-cluster
+description: Cluster vectors by similarity using k-means or density-based methods, then label and summarize groups
+argument-hint: "<namespace> [--k N]"
+allowed-tools: mcp__claude-flow__embeddings_search mcp__claude-flow__embeddings_generate mcp__claude-flow__embeddings_compare mcp__claude-flow__embeddings_status mcp__claude-flow__ruvllm_hnsw_route mcp__claude-flow__memory_search mcp__claude-flow__memory_store mcp__claude-flow__memory_list Read Bash
+---
+
+# Vector Cluster
+
+Cluster vectors in a namespace by semantic similarity, producing labeled groups with summaries.
+
+## When to use
+
+Use this skill when you have a collection of embeddings (e.g., all files in a project, all memory entries in a namespace) and want to discover natural groupings. Clustering reveals themes, identifies outliers, and helps organize large vector collections.
+
+## Steps
+
+1. **Fetch all vectors** -- call `mcp__claude-flow__memory_list` with the target namespace to enumerate entries, then call `mcp__claude-flow__memory_search` with a broad query to retrieve vectors. For HNSW-backed namespaces, use `mcp__claude-flow__embeddings_status` to check the vector count.
+2. **Compute pairwise distances** -- for each pair of vectors, compute cosine distance (1 - cosine_similarity). Build a distance matrix.
+3. **Select clustering method**:
+ - If `--k N` is provided, use **k-means**: initialize k centroids via k-means++, assign vectors to nearest centroid, recompute centroids, repeat until convergence (max 100 iterations).
+ - If `--k` is omitted, use **density clustering**: find core points (vectors with >= minPts neighbors within epsilon distance), expand clusters from core points, mark remaining vectors as outliers.
+4. **Label clusters** -- for each cluster, examine the source texts of member vectors and generate a descriptive label summarizing the cluster theme.
+5. **Visualize** -- present a summary table with cluster ID, label, member count, and cohesion score (average intra-cluster similarity). List outliers separately if density clustering was used.
+6. **Store results** -- call `mcp__claude-flow__memory_store` to persist cluster assignments in the `vector-clusters` namespace for future reference.
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest embeddings search --query "*" --namespace patterns --limit 1000
+npx @claude-flow/cli@latest memory list --namespace patterns
+```
+
+## Interpreting results
+
+- **High cohesion** (>0.85): tight, well-defined cluster with closely related content
+- **Medium cohesion** (0.6-0.85): related but diverse content
+- **Low cohesion** (<0.6): loose grouping, may benefit from splitting with higher k
+- **Outliers**: content that does not fit any cluster -- often novel or anomalous entries worth investigating
diff --git a/plugins/ruflo-ruvector/skills/vector-embed/SKILL.md b/plugins/ruflo-ruvector/skills/vector-embed/SKILL.md
new file mode 100644
index 0000000000..74165edfa9
--- /dev/null
+++ b/plugins/ruflo-ruvector/skills/vector-embed/SKILL.md
@@ -0,0 +1,36 @@
+---
+name: vector-embed
+description: Generate ONNX embeddings (all-MiniLM-L6-v2, 384-dim), normalize, and store in an HNSW index
+argument-hint: "<text-or-file>"
+allowed-tools: mcp__claude-flow__embeddings_generate mcp__claude-flow__embeddings_init mcp__claude-flow__embeddings_status mcp__claude-flow__embeddings_compare mcp__claude-flow__ruvllm_hnsw_create mcp__claude-flow__ruvllm_hnsw_add mcp__claude-flow__ruvllm_hnsw_route mcp__claude-flow__memory_store mcp__claude-flow__memory_search Read Bash
+---
+
+# Vector Embed
+
+Generate and store vector embeddings for text or file contents.
+
+## When to use
+
+Use this skill to embed text, code, or documents into 384-dimensional vectors for semantic search, similarity comparison, or clustering. Embeddings are generated via ONNX all-MiniLM-L6-v2 and stored in an HNSW index for fast approximate nearest-neighbor retrieval.
+
+## Steps
+
+1. **Ensure the embedding engine is ready** -- call `mcp__claude-flow__embeddings_status` to check engine health. If not initialized, call `mcp__claude-flow__embeddings_init`.
+2. **Read the input** -- if the argument is a file path, read the file contents. If it is raw text, use it directly. For large files, chunk into segments of ~512 tokens with 50-token overlap.
+3. **Generate the embedding** -- call `mcp__claude-flow__embeddings_generate` with the text. The engine returns a 384-dim float32 vector.
+4. **Normalize** -- the embedding is L2-normalized by default (unit sphere) for cosine similarity. Specify `--norm l1`, `--norm minmax`, or `--norm zscore` for alternatives.
+5. **Store in HNSW index** -- call `mcp__claude-flow__ruvllm_hnsw_add` to insert the vector with metadata (source text hash, timestamp, file path if applicable).
+6. **Confirm** -- report the vector ID, dimension (384), norm, and index the vector was stored in.
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest embeddings embed --text "your text here"
+npx @claude-flow/cli@latest embeddings batch --glob "src/**/*.ts"
+npx @claude-flow/cli@latest embeddings init --force
+npx @claude-flow/cli@latest embeddings status
+```
+
+## Batch embedding
+
+For multiple files, iterate over each file, chunk contents, and embed each chunk. Use `mcp__claude-flow__ruvllm_hnsw_add` with batch mode for efficient insertion. Report total vectors inserted and index growth.
diff --git a/plugins/ruflo-ruvector/skills/vector-hyperbolic/SKILL.md b/plugins/ruflo-ruvector/skills/vector-hyperbolic/SKILL.md
new file mode 100644
index 0000000000..8547ec9c9b
--- /dev/null
+++ b/plugins/ruflo-ruvector/skills/vector-hyperbolic/SKILL.md
@@ -0,0 +1,49 @@
+---
+name: vector-hyperbolic
+description: Embed hierarchical data in hyperbolic space (Poincare ball model), compute geodesic distances, and find hierarchical neighbors
+argument-hint: "<text> [--model poincare]"
+allowed-tools: mcp__claude-flow__embeddings_hyperbolic mcp__claude-flow__embeddings_generate mcp__claude-flow__embeddings_compare mcp__claude-flow__embeddings_status mcp__claude-flow__ruvllm_hnsw_create mcp__claude-flow__ruvllm_hnsw_add mcp__claude-flow__ruvllm_hnsw_route mcp__claude-flow__memory_store mcp__claude-flow__memory_search Read Bash
+---
+
+# Vector Hyperbolic
+
+Embed hierarchical data in the Poincare ball model for operations that respect tree-like structure.
+
+## When to use
+
+Use this skill when your data has inherent hierarchy -- dependency trees, module structures, taxonomies, org charts, ontologies, or any parent-child relationship graph. Hyperbolic space naturally captures hierarchical distances: nodes near the center are generic/root-level, nodes near the boundary are specific/leaf-level. This requires far fewer dimensions than Euclidean embeddings to represent the same hierarchical fidelity.
+
+## Steps
+
+1. **Identify hierarchical structure** -- determine what hierarchy the data represents (dependency tree, taxonomy, module graph, etc.). If needed, read source files to extract parent-child relationships.
+2. **Embed in Poincare ball** -- call `mcp__claude-flow__embeddings_hyperbolic` with the text and `model=poincare`. The engine returns coordinates inside the unit ball where:
+ - Coordinates near the origin represent generic/root concepts
+ - Coordinates near the boundary represent specific/leaf concepts
+ - Geodesic distance between points reflects hierarchical distance
+3. **Compute geodesic distances** -- for two hyperbolic embeddings, compute the Poincare distance: `d(u, v) = arcosh(1 + 2 * ||u - v||^2 / ((1 - ||u||^2)(1 - ||v||^2)))`. This distance grows logarithmically with tree depth, preserving hierarchy.
+4. **Find hierarchical neighbors** -- call `mcp__claude-flow__ruvllm_hnsw_route` with the hyperbolic embedding to find nearest neighbors in the hyperbolic HNSW index. Neighbors are semantically and hierarchically related.
+5. **Analyze hierarchy** -- report the embedding's position (center vs. boundary), its nearest hierarchical neighbors, and the geodesic distances. Identify parent-like (closer to center) and child-like (closer to boundary) neighbors.
+6. **Store results** -- call `mcp__claude-flow__memory_store` to persist the hyperbolic embedding and hierarchy analysis in the `hyperbolic-embeddings` namespace.
+
+## CLI alternative
+
+```bash
+npx @claude-flow/cli@latest embeddings embed --text "your text" --model poincare
+npx @claude-flow/cli@latest embeddings search --query "your query" --model poincare
+```
+
+## Poincare ball properties
+
+| Property | Meaning |
+|----------|---------|
+| Norm close to 0 | Generic, root-level concept |
+| Norm close to 1 | Specific, leaf-level concept |
+| Small geodesic distance | Closely related in the hierarchy |
+| Large geodesic distance | Distantly related or in different subtrees |
+
+## Use cases
+
+- **Dependency analysis**: embed module imports to find tightly coupled subtrees
+- **Code architecture**: map class hierarchies to discover structural patterns
+- **Knowledge organization**: embed concepts to reveal taxonomic relationships
+- **Codebase navigation**: find the most specific or most general modules relative to a query
diff --git a/plugins/ruflo-ruvllm/agents/llm-specialist.md b/plugins/ruflo-ruvllm/agents/llm-specialist.md
index fa91b7098d..885fcacee9 100644
--- a/plugins/ruflo-ruvllm/agents/llm-specialist.md
+++ b/plugins/ruflo-ruvllm/agents/llm-specialist.md
@@ -20,3 +20,11 @@ Use these MCP tools:
- `mcp__claude-flow__ruvllm_chat_format` for prompt formatting
Optimize for the right balance of quality, speed, and cost per task.
+
+### Memory Learning
+
+Store successful model configurations and prompt templates:
+```bash
+npx @claude-flow/cli@latest memory store --namespace llm-configs --key "config-PROVIDER-MODEL" --value "PARAMS_AND_RESULTS"
+npx @claude-flow/cli@latest memory search --query "config for PROVIDER" --namespace llm-configs
+```
diff --git a/plugins/ruflo-ruvllm/skills/chat-format/SKILL.md b/plugins/ruflo-ruvllm/skills/chat-format/SKILL.md
index baa07c513b..f46b81f385 100644
--- a/plugins/ruflo-ruvllm/skills/chat-format/SKILL.md
+++ b/plugins/ruflo-ruvllm/skills/chat-format/SKILL.md
@@ -1,6 +1,7 @@
---
name: chat-format
description: Format prompts for different LLM providers with chat templates and HNSW-powered context retrieval
+argument-hint: "<prompt> [--provider anthropic|openai|local]"
allowed-tools: mcp__claude-flow__ruvllm_chat_format mcp__claude-flow__ruvllm_hnsw_create mcp__claude-flow__ruvllm_hnsw_add mcp__claude-flow__ruvllm_hnsw_route mcp__claude-flow__ruvllm_status Bash
---
diff --git a/plugins/ruflo-ruvllm/skills/llm-config/SKILL.md b/plugins/ruflo-ruvllm/skills/llm-config/SKILL.md
index 21afc91598..2afefc1886 100644
--- a/plugins/ruflo-ruvllm/skills/llm-config/SKILL.md
+++ b/plugins/ruflo-ruvllm/skills/llm-config/SKILL.md
@@ -1,6 +1,7 @@
---
name: llm-config
description: Configure RuVLLM local inference with model selection, MicroLoRA fine-tuning, and SONA adaptation
+argument-hint: "[--model MODEL] [--adapter microlora|sona]"
allowed-tools: mcp__claude-flow__ruvllm_generate_config mcp__claude-flow__ruvllm_status mcp__claude-flow__ruvllm_microlora_create mcp__claude-flow__ruvllm_microlora_adapt mcp__claude-flow__ruvllm_sona_create mcp__claude-flow__ruvllm_sona_adapt Bash
---
diff --git a/plugins/ruflo-rvf/agents/session-specialist.md b/plugins/ruflo-rvf/agents/session-specialist.md
index 8e4beac48c..62bcf7712b 100644
--- a/plugins/ruflo-rvf/agents/session-specialist.md
+++ b/plugins/ruflo-rvf/agents/session-specialist.md
@@ -1,7 +1,7 @@
---
name: session-specialist
description: Session persistence specialist for state management, memory transfer, and cross-conversation continuity
-model: sonnet
+model: haiku
---
You are a session persistence specialist for Ruflo's RVF system. Your responsibilities:
@@ -19,3 +19,12 @@ Use these MCP tools:
- `mcp__claude-flow__hooks_transfer` for cross-project transfer
Ensure critical state is always saved before session end.
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-rvf/skills/rvf-manage/SKILL.md b/plugins/ruflo-rvf/skills/rvf-manage/SKILL.md
index 22347834b8..1a0a4fea3c 100644
--- a/plugins/ruflo-rvf/skills/rvf-manage/SKILL.md
+++ b/plugins/ruflo-rvf/skills/rvf-manage/SKILL.md
@@ -1,6 +1,7 @@
---
name: rvf-manage
description: Manage RVF (Ruflo Vector Format) files for portable agent memory and cross-platform transfer
+argument-hint: "<import|export|list|delete> [options]"
allowed-tools: mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_list mcp__claude-flow__memory_delete mcp__claude-flow__memory_stats mcp__claude-flow__memory_import_claude mcp__claude-flow__memory_migrate mcp__claude-flow__hooks_transfer Bash
---
diff --git a/plugins/ruflo-rvf/skills/session-persist/SKILL.md b/plugins/ruflo-rvf/skills/session-persist/SKILL.md
index 18efd13a4a..318b9db199 100644
--- a/plugins/ruflo-rvf/skills/session-persist/SKILL.md
+++ b/plugins/ruflo-rvf/skills/session-persist/SKILL.md
@@ -1,6 +1,7 @@
---
name: session-persist
description: Persist and restore agent sessions across conversations with state snapshots
+argument-hint: "[--save|--restore|--list]"
allowed-tools: mcp__claude-flow__session_save mcp__claude-flow__session_restore mcp__claude-flow__session_list mcp__claude-flow__session_info mcp__claude-flow__session_delete mcp__claude-flow__hooks_session-start mcp__claude-flow__hooks_session-end mcp__claude-flow__hooks_session-restore Bash
---
diff --git a/plugins/ruflo-security-audit/agents/security-auditor.md b/plugins/ruflo-security-audit/agents/security-auditor.md
index 4797d8ceba..8690fd7fd2 100644
--- a/plugins/ruflo-security-audit/agents/security-auditor.md
+++ b/plugins/ruflo-security-audit/agents/security-auditor.md
@@ -1,7 +1,7 @@
---
name: security-auditor
description: Specialized agent for security auditing and vulnerability remediation
-model: sonnet
+model: opus
---
You are a security auditor agent. Your responsibilities:
@@ -32,3 +32,17 @@ Store findings for cross-session learning:
```bash
npx @claude-flow/cli@latest memory store --namespace security --key "audit-YYYY-MM-DD" --value "FINDINGS_SUMMARY"
```
+
+### Related Plugins
+
+- **ruflo-aidefence**: AI safety scanning (prompt injection, PII detection) — complements CVE/dependency auditing
+- **ruflo-federation**: Federation audit for cross-installation compliance (HIPAA, SOC2, GDPR)
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-security-audit/skills/dependency-check/SKILL.md b/plugins/ruflo-security-audit/skills/dependency-check/SKILL.md
index ec71deea9f..b5712acd9c 100644
--- a/plugins/ruflo-security-audit/skills/dependency-check/SKILL.md
+++ b/plugins/ruflo-security-audit/skills/dependency-check/SKILL.md
@@ -1,6 +1,7 @@
---
name: dependency-check
description: Scan project dependencies for known vulnerabilities and CVEs
+argument-hint: "[--path PATH]"
allowed-tools: Bash(npx * npm *) mcp__claude-flow__memory_store Read
---
Check dependencies for CVEs and outdated packages:
diff --git a/plugins/ruflo-sparc/.claude-plugin/plugin.json b/plugins/ruflo-sparc/.claude-plugin/plugin.json
new file mode 100644
index 0000000000..eab1a70afd
--- /dev/null
+++ b/plugins/ruflo-sparc/.claude-plugin/plugin.json
@@ -0,0 +1,19 @@
+{
+ "name": "ruflo-sparc",
+ "description": "SPARC methodology — Specification, Pseudocode, Architecture, Refinement, Completion phases with gate checks",
+ "version": "0.1.0",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "keywords": [
+ "ruflo",
+ "sparc",
+ "methodology",
+ "specification",
+ "architecture",
+ "refinement"
+ ]
+}
diff --git a/plugins/ruflo-sparc/README.md b/plugins/ruflo-sparc/README.md
new file mode 100644
index 0000000000..68b9fe1385
--- /dev/null
+++ b/plugins/ruflo-sparc/README.md
@@ -0,0 +1,65 @@
+# ruflo-sparc
+
+SPARC methodology -- Specification, Pseudocode, Architecture, Refinement, Completion phases with quality gates between each phase.
+
+## Overview
+
+Drives features through a rigorous five-phase development lifecycle. Each phase has a quality gate that must pass before advancing. The orchestrator spawns specialized agents per phase (researcher, planner, system-architect, coder/tester, reviewer) and stores all artifacts and gate results in memory for traceability.
+
+## Installation
+
+```bash
+claude --plugin-dir plugins/ruflo-sparc
+```
+
+## Agents
+
+| Agent | Model | Role |
+|-------|-------|------|
+| `sparc-orchestrator` | sonnet | Orchestrate 5-phase SPARC lifecycle, enforce gate checks, spawn phase-specific agents, track state in memory |
+
+## Skills
+
+| Skill | Usage | Description |
+|-------|-------|-------------|
+| `sparc-spec` | `/sparc-spec <feature-description>` | Run the Specification phase -- gather requirements, define acceptance criteria, identify constraints |
+| `sparc-implement` | `/sparc-implement` | Run the Architecture and Implementation phases -- design modules, write pseudocode, implement, test |
+| `sparc-refine` | `/sparc-refine` | Run Refinement and Completion -- review code, improve coverage, validate against spec, generate docs |
+
+## Commands (5 subcommands)
+
+```bash
+sparc init <feature> # Initialize a new SPARC workflow
+sparc status # Show current phase and gate history
+sparc advance # Attempt gate check, advance to next phase
+sparc phase <phase-name> # Jump to a specific phase (spec/pseudo/arch/refine/complete)
+sparc report # Generate full SPARC methodology report with traceability matrix
+```
+
+## The 5 Phases
+
+| Phase | Name | Gate Criteria | Spawned Agent |
+|-------|------|--------------|---------------|
+| 1 | Specification | >= 3 acceptance criteria, constraints, edge cases | `researcher` |
+| 2 | Pseudocode | Covers all ACs, error paths explicit, complexity annotated | `planner` |
+| 3 | Architecture | All constraints addressed, typed API contracts, no circular deps | `system-architect` |
+| 4 | Refinement | All ACs have passing tests, review approved, coverage >= 80% | `coder` + `tester` |
+| 5 | Completion | All tests green, docs complete, deployment checklist verified | `reviewer` |
+
+## Memory Namespaces
+
+| Namespace | Purpose |
+|-----------|---------|
+| `sparc-state` | Current phase tracking per feature |
+| `sparc-phases` | Phase artifacts (specs, pseudocode, ADRs, reports) |
+| `sparc-gates` | Gate check results and history |
+| `patterns` | Learned SPARC execution patterns |
+
+## Related Plugins
+
+- `ruflo-ddd` -- Architecture phase uses DDD bounded context patterns
+- `ruflo-adr` -- Architecture decisions recorded as ADRs in Phase 3
+
+## License
+
+MIT
diff --git a/plugins/ruflo-sparc/agents/sparc-orchestrator.md b/plugins/ruflo-sparc/agents/sparc-orchestrator.md
new file mode 100644
index 0000000000..084838d9f3
--- /dev/null
+++ b/plugins/ruflo-sparc/agents/sparc-orchestrator.md
@@ -0,0 +1,138 @@
+---
+name: sparc-orchestrator
+description: Orchestrates the 5-phase SPARC methodology (Specification, Pseudocode, Architecture, Refinement, Completion) with quality gates between each phase, spawning specialized agents per phase
+model: sonnet
+---
+
+You are the SPARC Methodology Orchestrator. You drive features through a rigorous five-phase development lifecycle, enforcing quality gates between each phase so no phase begins until the previous one passes its gate check.
+
+## The 5 SPARC Phases
+
+### Phase 1 — Specification
+**Goal**: Capture exactly what must be built and how success is measured.
+**Activities**:
+- Gather functional and non-functional requirements
+- Define acceptance criteria with concrete, testable conditions
+- Identify constraints (performance, security, compatibility, budget)
+- Map stakeholder concerns and edge cases
+- Produce a Specification Document stored in memory
+**Gate check**: Spec must include at least 3 acceptance criteria, explicit constraints, and identified edge cases. Stakeholder sign-off recorded.
+**Spawned agent**: `researcher` — domain analysis, requirement elicitation, prior art search
+
+### Phase 2 — Pseudocode
+**Goal**: Design algorithms and data flows before writing production code.
+**Activities**:
+- Write language-agnostic pseudocode for core logic
+- Define data structures and state transitions
+- Map control flow including error paths and edge cases
+- Identify algorithmic complexity and potential bottlenecks
+- Produce a Pseudocode Document stored in memory
+**Gate check**: Pseudocode covers all acceptance criteria from the spec, error paths are explicit, complexity is annotated.
+**Spawned agent**: `planner` — algorithm design, data modeling, flowchart generation
+
+### Phase 3 — Architecture
+**Goal**: Establish module boundaries, API contracts, and integration points.
+**Activities**:
+- Define bounded contexts and aggregate roots (DDD patterns)
+- Design API contracts (request/response schemas, error codes)
+- Plan module boundaries with dependency direction rules
+- Specify infrastructure concerns (persistence, caching, messaging)
+- Produce an Architecture Decision Record stored in memory
+**Gate check**: Architecture addresses all constraints from spec, API contracts are typed, no circular dependencies, DDD invariants documented.
+**Spawned agent**: `system-architect` — module design, API contracts, DDD patterns
+
+### Phase 4 — Refinement
+**Goal**: Iteratively improve through code review, testing, and optimization.
+**Activities**:
+- Implement code following the architecture and pseudocode
+- Write unit tests, integration tests, and edge-case tests
+- Conduct code review against specification requirements
+- Measure and improve test coverage (target >80%)
+- Profile performance against constraints
+- Iterate until all acceptance criteria pass
+**Gate check**: All acceptance criteria have passing tests, code review approval with no critical issues, test coverage meets threshold.
+**Spawned agent**: `coder` (implementation), `tester` (test writing and coverage)
+
+### Phase 5 — Completion
+**Goal**: Final validation, documentation, and deployment readiness.
+**Activities**:
+- Run full regression suite
+- Validate against every acceptance criterion from Phase 1
+- Generate API documentation and usage examples
+- Verify deployment prerequisites (migrations, config, feature flags)
+- Produce a Completion Report with traceability matrix
+**Gate check**: All tests green, documentation complete, deployment checklist verified, traceability matrix links every acceptance criterion to its test.
+**Spawned agent**: `reviewer` — final audit, documentation review, deployment readiness check
+
+## Gate Check Protocol
+
+Each gate check follows this procedure:
+
+1. **Retrieve phase artifacts** from memory namespace `sparc-phases`
+2. **Evaluate gate criteria** — every criterion must pass; partial passes fail the gate
+3. **Record gate result** — store pass/fail with details in memory namespace `sparc-gates`
+4. **On failure**: identify gaps, provide actionable feedback, return to current phase
+5. **On success**: advance phase counter, notify user, begin next phase
+
+Gate results are stored as:
+```
+Key: gate-{phase}-{feature-slug}-{timestamp}
+Value: { phase, passed, criteria: [{name, passed, detail}], blockers: [] }
+```
+
+## Phase State Management
+
+Track current phase in memory:
+- `mcp__claude-flow__memory_store` with namespace `sparc-state`, key `current-phase-{feature-slug}`
+- Value: `{ phase: 1-5, phaseName, feature, startedAt, gateAttempts, artifacts: [] }`
+
+Before any phase operation, retrieve current state to prevent drift:
+- `mcp__claude-flow__memory_search` with namespace `sparc-state` and query for the feature slug
+
+## Agent Spawning
+
+Spawn phase-specific agents with clear handoff instructions:
+
+```
+Phase 1 → researcher: "Analyze requirements for {feature}. Store spec in sparc-phases namespace."
+Phase 2 → planner: "Design pseudocode based on spec. Store in sparc-phases namespace."
+Phase 3 → system-architect: "Design architecture based on pseudocode. Store ADR in sparc-phases namespace."
+Phase 4 → coder + tester: "Implement and test against spec. Store results in sparc-phases namespace."
+Phase 5 → reviewer: "Final review against all acceptance criteria. Store report in sparc-phases namespace."
+```
+
+Each agent receives the artifacts from all previous phases via memory retrieval.
+
+## Cross-References
+
+- **ruflo-goals**: Use horizon tracking to place SPARC features within long-term planning horizons. Query `horizons` namespace to align phase timelines with goal milestones.
+- **ruflo-workflows**: SPARC phases can be codified as workflow templates. Use `mcp__claude-flow__workflow_create` to create reusable phase workflows.
+- **ruflo-ddd**: Architecture phase (Phase 3) directly leverages DDD bounded context patterns. Query `ddd-contexts` namespace for existing domain models.
+
+## Neural Learning
+
+After completing a full SPARC cycle:
+1. Record the trajectory: `mcp__claude-flow__hooks_intelligence_trajectory-start` through `trajectory-end`
+2. Train patterns: `mcp__claude-flow__neural_train` with the successful phase sequence
+3. Store the pattern: `mcp__claude-flow__memory_store` with namespace `patterns`, key `sparc-{feature-slug}`
+
+Use learned patterns to predict phase durations and common blockers:
+- `mcp__claude-flow__neural_predict` with the feature description to estimate phase effort
+- `mcp__claude-flow__memory_search` with namespace `patterns` and query for similar features
+
+## Memory Namespaces
+
+| Namespace | Purpose |
+|-----------|---------|
+| `sparc-state` | Current phase tracking per feature |
+| `sparc-phases` | Phase artifacts (specs, pseudocode, ADRs, reports) |
+| `sparc-gates` | Gate check results and history |
+| `patterns` | Learned SPARC execution patterns |
+
+## MCP Tools
+
+- `mcp__claude-flow__memory_store` / `memory_search` / `memory_retrieve` — phase state and artifacts
+- `mcp__claude-flow__task_create` / `task_update` / `task_complete` — track phase tasks
+- `mcp__claude-flow__hooks_intelligence_trajectory-start` / `trajectory-step` / `trajectory-end` — record execution trajectories
+- `mcp__claude-flow__neural_predict` / `neural_train` — predict and learn from SPARC cycles
+- `mcp__claude-flow__workflow_create` / `workflow_execute` — automate repeatable phase workflows
diff --git a/plugins/ruflo-sparc/commands/sparc.md b/plugins/ruflo-sparc/commands/sparc.md
new file mode 100644
index 0000000000..6f2f618462
--- /dev/null
+++ b/plugins/ruflo-sparc/commands/sparc.md
@@ -0,0 +1,95 @@
+---
+name: sparc
+description: SPARC methodology commands — initialize, track, advance, and report on Specification-Pseudocode-Architecture-Refinement-Completion workflows
+---
+$ARGUMENTS
+
+Handle SPARC methodology commands based on the subcommand:
+
+## Subcommands
+
+### `sparc init <feature>`
+Initialize a new SPARC workflow for the given feature:
+1. Create a feature slug from the feature name (lowercase, hyphenated)
+2. Call `mcp__claude-flow__memory_store` with namespace `sparc-state`, key `current-phase-{slug}`, value `{ "phase": 1, "phaseName": "Specification", "feature": "<feature>", "startedAt": "<ISO timestamp>", "gateAttempts": 0, "artifacts": [] }`
+3. Call `mcp__claude-flow__memory_store` with namespace `sparc-phases`, key `spec-{slug}`, value `{ "status": "pending", "requirements": [], "acceptanceCriteria": [], "constraints": [], "edgeCases": [] }`
+4. Display: "SPARC workflow initialized for **<feature>**. Current phase: **1 - Specification**. Run `/sparc status` to view progress or begin the specification phase with `/sparc-spec <feature-description>`."
+
+### `sparc status`
+Show current SPARC phase and gate check results:
+1. Call `mcp__claude-flow__memory_search` with namespace `sparc-state` and query `current-phase` to list all active SPARC workflows
+2. For each workflow, display:
+ - Feature name and slug
+ - Current phase number and name (1-Specification, 2-Pseudocode, 3-Architecture, 4-Refinement, 5-Completion)
+ - Phase start time and duration
+ - Gate attempt count
+3. Call `mcp__claude-flow__memory_search` with namespace `sparc-gates` and query matching the feature slug to list gate check history
+4. For each gate result, show: phase, passed/failed, criteria details, blockers if any
+5. Display a progress bar: `[=====> ] Phase 3/5 — Architecture`
+
+### `sparc advance`
+Attempt to pass the current gate and advance to the next phase:
+1. Retrieve current state from `sparc-state` namespace
+2. Retrieve phase artifacts from `sparc-phases` namespace
+3. Run the gate check for the current phase:
+ - **Phase 1 gate**: Verify spec has >= 3 acceptance criteria, explicit constraints, and edge cases identified
+ - **Phase 2 gate**: Verify pseudocode covers all acceptance criteria, error paths are explicit, complexity annotated
+ - **Phase 3 gate**: Verify architecture addresses all constraints, API contracts are typed, no circular dependencies
+ - **Phase 4 gate**: Verify all acceptance criteria have passing tests, code review approved, coverage >= 80%
+ - **Phase 5 gate**: Verify all tests green, docs complete, deployment checklist verified, traceability matrix complete
+4. Store gate result in `sparc-gates` namespace with key `gate-{phase}-{slug}-{timestamp}`
+5. If gate passes:
+ - Increment phase in `sparc-state`
+ - Display: "Gate **passed**. Advancing to Phase {N} — {PhaseName}."
+ - If advancing past Phase 5: "SPARC workflow **complete** for {feature}. All gates passed."
+6. If gate fails:
+ - Increment `gateAttempts` in state
+ - Display: "Gate **failed**. Blockers:" followed by the list of failing criteria
+ - Suggest specific actions to address each blocker
+
+### `sparc phase <phase-name>`
+Jump to a specific phase (for re-entry or iteration):
+1. Validate phase-name is one of: `specification`, `pseudocode`, `architecture`, `refinement`, `completion` (or `spec`, `pseudo`, `arch`, `refine`, `complete` as aliases, or a number 1-5)
+2. Retrieve current state from `sparc-state` namespace
+3. Update phase number and name in state
+4. Store warning if jumping forward (skipping gates): "Jumping forward skips gate checks. Run `/sparc advance` from previous phases to ensure quality."
+5. Display: "Phase set to **{N} — {PhaseName}** for {feature}."
+
+### `sparc report`
+Generate a full SPARC methodology report:
+1. Retrieve all data from `sparc-state`, `sparc-phases`, and `sparc-gates` namespaces for the active feature
+2. Generate a structured report:
+ ```
+ # SPARC Report: {Feature}
+
+ ## Phase Summary
+ | Phase | Status | Gate | Attempts | Duration |
+ |-------|--------|------|----------|----------|
+ | 1 - Specification | Complete | Passed | 1 | 2h |
+ | 2 - Pseudocode | Complete | Passed | 2 | 3h |
+ | 3 - Architecture | In Progress | — | 0 | 1h |
+ | 4 - Refinement | Pending | — | — | — |
+ | 5 - Completion | Pending | — | — | — |
+
+ ## Specification
+ - Requirements: [list]
+ - Acceptance Criteria: [list]
+ - Constraints: [list]
+
+ ## Pseudocode
+ - Algorithms: [summary]
+ - Data Structures: [summary]
+
+ ## Architecture
+ - Bounded Contexts: [list]
+ - API Contracts: [summary]
+
+ ## Gate History
+ [chronological list of gate attempts with pass/fail details]
+
+ ## Traceability Matrix
+ | Acceptance Criterion | Test | Status |
+ |---------------------|------|--------|
+ | AC-1: ... | test_xxx | Pass |
+ ```
+3. Display the report
diff --git a/plugins/ruflo-sparc/skills/sparc-implement/SKILL.md b/plugins/ruflo-sparc/skills/sparc-implement/SKILL.md
new file mode 100644
index 0000000000..4bd71b2101
--- /dev/null
+++ b/plugins/ruflo-sparc/skills/sparc-implement/SKILL.md
@@ -0,0 +1,122 @@
+---
+name: sparc-implement
+description: Run the SPARC Architecture and Implementation phases — design module boundaries, write pseudocode, implement code, and run tests
+argument-hint: ""
+allowed-tools: mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__memory_retrieve mcp__claude-flow__task_create mcp__claude-flow__task_update mcp__claude-flow__task_complete mcp__claude-flow__hooks_intelligence_trajectory-step mcp__claude-flow__neural_predict mcp__claude-flow__workflow_create Bash Read Write Edit
+---
+
+# SPARC Architecture + Implementation
+
+Run Phases 2 and 3 of the SPARC methodology: design algorithms with pseudocode, then establish architecture with module boundaries and API contracts.
+
+## When to use
+
+After the Specification phase is complete and its gate has been passed. This skill covers both the Pseudocode and Architecture phases as they are tightly coupled — algorithm design informs module boundaries and vice versa.
+
+## Steps
+
+1. **Retrieve specification** — call `mcp__claude-flow__memory_search` with namespace `sparc-phases` and query for the feature's spec. Extract requirements, acceptance criteria, constraints, and edge cases.
+
+2. **Retrieve phase state** — call `mcp__claude-flow__memory_search` with namespace `sparc-state` and query for the feature to confirm we are in Phase 2 or 3.
+
+3. **Search for architectural patterns** — call `mcp__claude-flow__neural_predict` with the feature description to find relevant architectural decisions from past projects
+
+4. **Phase 2 — Pseudocode Design**:
+ a. For each acceptance criterion, write language-agnostic pseudocode that satisfies it
+ b. Define core data structures with type annotations
+ c. Map control flow including:
+ - Happy path
+ - Error/exception paths for each edge case
+ - Concurrent access handling if applicable
+ d. Annotate algorithmic complexity (time and space) for critical paths
+ e. Store pseudocode artifact:
+ - Call `mcp__claude-flow__memory_store` with namespace `sparc-phases`, key `pseudo-{feature-slug}`
+ - Value: `{ status: "complete", algorithms: [...], dataStructures: [...], controlFlow: [...], complexity: {...} }`
+
+5. **Phase 3 — Architecture Design**:
+ a. Define bounded contexts and aggregate roots following DDD patterns:
+ - Identify entity boundaries and value objects
+ - Define aggregate invariants
+ - Map domain events
+ b. Design API contracts:
+ - Request/response schemas with TypeScript interfaces
+ - Error response codes and formats
+ - Versioning strategy if applicable
+ c. Plan module boundaries:
+ - Directory structure
+ - Dependency direction rules (no circular dependencies)
+ - Public vs internal interfaces
+ d. Specify infrastructure concerns:
+ - Persistence strategy (database, cache, file)
+ - Messaging patterns (sync, async, event-driven)
+ - Configuration and environment requirements
+ e. Store architecture artifact:
+ - Call `mcp__claude-flow__memory_store` with namespace `sparc-phases`, key `arch-{feature-slug}`
+ - Value: `{ status: "complete", boundedContexts: [...], apiContracts: [...], moduleBoundaries: {...}, infrastructure: {...} }`
+
+6. **Update phase state** — call `mcp__claude-flow__memory_store` with namespace `sparc-state`, updating current phase to 3 (Architecture) with both artifacts recorded
+
+7. **Record trajectory step** — call `mcp__claude-flow__hooks_intelligence_trajectory-step` with architecture summary
+
+8. **Begin implementation** — if the user confirms, proceed to write production code:
+ a. Create files following the defined module boundaries
+ b. Implement interfaces and types first
+ c. Implement core logic following the pseudocode
+ d. Write unit tests alongside implementation (TDD when possible)
+ e. Run tests to verify acceptance criteria
+
+9. **Present architecture** — display the architecture decision record and suggest running `/sparc advance` to pass the Phase 3 gate
+
+## Output format
+
+```
+# Pseudocode: {Feature Name}
+
+## Core Algorithms
+### Algorithm 1: {name}
+```pseudocode
+FUNCTION processRequest(input):
+ VALIDATE input against schema
+ IF invalid THEN THROW ValidationError
+ result <- TRANSFORM input
+ STORE result
+ RETURN result
+```
+Complexity: O(n) time, O(1) space
+
+## Data Structures
+- {StructName}: { field1: type, field2: type }
+
+---
+
+# Architecture: {Feature Name}
+
+## Bounded Contexts
+- {ContextName}: {description}
+ - Aggregates: {list}
+ - Events: {list}
+
+## API Contracts
+### POST /api/{resource}
+- Request: { field1: string, field2: number }
+- Response: { id: string, ...fields }
+- Errors: 400 (validation), 409 (conflict), 500 (internal)
+
+## Module Structure
+```
+src/{feature}/
+ {feature}.types.ts # Interfaces and types
+ {feature}.service.ts # Business logic
+ {feature}.controller.ts # HTTP handling
+ {feature}.repository.ts # Data access
+ {feature}.test.ts # Tests
+```
+
+## Infrastructure
+- Persistence: {strategy}
+- Caching: {strategy}
+- Events: {strategy}
+
+---
+Phases 2-3 complete. Run `/sparc advance` to pass the gate check.
+```
diff --git a/plugins/ruflo-sparc/skills/sparc-refine/SKILL.md b/plugins/ruflo-sparc/skills/sparc-refine/SKILL.md
new file mode 100644
index 0000000000..52cad684f0
--- /dev/null
+++ b/plugins/ruflo-sparc/skills/sparc-refine/SKILL.md
@@ -0,0 +1,130 @@
+---
+name: sparc-refine
+description: Run the SPARC Refinement and Completion phases — review code, improve test coverage, validate against specification, and generate documentation
+argument-hint: ""
+allowed-tools: mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__memory_retrieve mcp__claude-flow__task_create mcp__claude-flow__task_update mcp__claude-flow__task_complete mcp__claude-flow__hooks_intelligence_trajectory-step mcp__claude-flow__hooks_intelligence_trajectory-end mcp__claude-flow__neural_train mcp__claude-flow__neural_predict Bash Read Write Edit
+---
+
+# SPARC Refinement + Completion
+
+Run Phases 4 and 5 of the SPARC methodology: iteratively improve through code review and testing, then finalize with validation, documentation, and deployment readiness.
+
+## When to use
+
+After the Architecture phase is complete and its gate has been passed. This skill covers the final two phases that bring a feature from implemented to production-ready.
+
+## Steps
+
+### Phase 4 — Refinement
+
+1. **Retrieve all prior artifacts** — call `mcp__claude-flow__memory_search` with namespace `sparc-phases` and query for the feature slug. Load spec (acceptance criteria), pseudocode, and architecture.
+
+2. **Retrieve phase state** — call `mcp__claude-flow__memory_search` with namespace `sparc-state` to confirm we are in Phase 4.
+
+3. **Code review** — review the implementation against:
+ a. **Specification compliance**: does every acceptance criterion have a corresponding code path?
+ b. **Architecture adherence**: do modules follow the defined boundaries and dependency rules?
+ c. **Pseudocode fidelity**: does the implementation match the designed algorithms?
+ d. **Code quality**: naming conventions, single responsibility, error handling, no dead code
+ e. Document findings as review comments
+
+4. **Test coverage analysis**:
+ a. Run existing tests and measure coverage
+ b. Identify uncovered acceptance criteria
+ c. Write missing tests:
+ - Unit tests for each public function
+ - Integration tests for cross-module interactions
+ - Edge case tests for each identified edge case from the spec
+ d. Target coverage >= 80% on new code
+
+5. **Performance validation** — if the spec includes performance constraints:
+ a. Profile critical paths identified in the pseudocode
+ b. Compare measured performance against constraint thresholds
+ c. Optimize if thresholds are not met
+
+6. **Iterate** — repeat steps 3-5 until:
+ - All acceptance criteria have passing tests
+ - Code review has no critical or high-severity issues
+ - Coverage meets the threshold
+ - Performance constraints are satisfied
+
+7. **Store refinement artifact** — call `mcp__claude-flow__memory_store` with namespace `sparc-phases`, key `refine-{feature-slug}`, value: `{ status: "complete", reviewFindings: [...], coveragePercent: N, performanceResults: {...}, iterations: N }`
+
+8. **Record trajectory step** — call `mcp__claude-flow__hooks_intelligence_trajectory-step` with refinement summary
+
+### Phase 5 — Completion
+
+9. **Full regression** — run the complete test suite to verify no regressions from refinement changes
+
+10. **Traceability matrix** — build a matrix mapping every acceptance criterion to:
+ - The test(s) that verify it
+ - The code file(s) that implement it
+ - The current pass/fail status
+
+11. **Documentation**:
+ a. Generate API documentation from code comments and type definitions
+ b. Write usage examples for key public interfaces
+ c. Update any existing documentation affected by the changes
+
+12. **Deployment readiness checklist**:
+ - [ ] All tests passing
+ - [ ] Documentation complete
+ - [ ] Database migrations prepared (if applicable)
+ - [ ] Configuration changes documented
+ - [ ] Feature flags configured (if applicable)
+ - [ ] Rollback plan defined
+ - [ ] Security review complete (no secrets, inputs validated)
+
+13. **Store completion artifact** — call `mcp__claude-flow__memory_store` with namespace `sparc-phases`, key `complete-{feature-slug}`, value: `{ status: "complete", traceabilityMatrix: [...], documentationFiles: [...], deploymentChecklist: {...}, regressionResult: "pass" }`
+
+14. **End trajectory** — call `mcp__claude-flow__hooks_intelligence_trajectory-end` with the full SPARC cycle summary
+
+15. **Train neural patterns** — call `mcp__claude-flow__neural_train` with the successful SPARC cycle data to improve future predictions
+
+16. **Store learned pattern** — call `mcp__claude-flow__memory_store` with namespace `patterns`, key `sparc-{feature-slug}`, value summarizing what worked, phase durations, and common blockers encountered
+
+17. **Present completion report** — display the traceability matrix, deployment checklist, and final status. Suggest running `/sparc advance` to pass the final gate, or `/sparc report` for the full methodology report.
+
+## Output format
+
+```
+# Refinement: {Feature Name}
+
+## Code Review Summary
+- Critical issues: {N} (must be 0 to pass gate)
+- High issues: {N}
+- Medium issues: {N}
+- Resolved: {N}/{total}
+
+## Test Coverage
+- Overall: {N}%
+- New code: {N}%
+- Acceptance criteria covered: {N}/{total}
+
+## Performance
+| Constraint | Target | Measured | Status |
+|-----------|--------|----------|--------|
+| Response time | <200ms | 145ms | Pass |
+
+---
+
+# Completion: {Feature Name}
+
+## Traceability Matrix
+| AC | Test | Code | Status |
+|----|------|------|--------|
+| AC-1 | test_xxx | service.ts:42 | Pass |
+| AC-2 | test_yyy | controller.ts:18 | Pass |
+| AC-3 | test_zzz | repository.ts:31 | Pass |
+
+## Deployment Checklist
+- [x] All tests passing
+- [x] Documentation complete
+- [x] Migrations prepared
+- [x] Config documented
+- [x] Rollback plan defined
+- [x] Security reviewed
+
+---
+SPARC workflow complete. Run `/sparc report` for the full methodology report.
+```
diff --git a/plugins/ruflo-sparc/skills/sparc-spec/SKILL.md b/plugins/ruflo-sparc/skills/sparc-spec/SKILL.md
new file mode 100644
index 0000000000..930c93a7db
--- /dev/null
+++ b/plugins/ruflo-sparc/skills/sparc-spec/SKILL.md
@@ -0,0 +1,95 @@
+---
+name: sparc-spec
+description: Run the SPARC Specification phase — gather requirements, define acceptance criteria, identify constraints, and store the spec in memory
+argument-hint: "<feature-description>"
+allowed-tools: mcp__claude-flow__memory_store mcp__claude-flow__memory_search mcp__claude-flow__memory_retrieve mcp__claude-flow__task_create mcp__claude-flow__task_update mcp__claude-flow__task_complete mcp__claude-flow__hooks_intelligence_trajectory-start mcp__claude-flow__hooks_intelligence_trajectory-step mcp__claude-flow__neural_predict Bash Read Edit
+---
+
+# SPARC Specification Phase
+
+Run Phase 1 of the SPARC methodology: define what must be built and how success is measured.
+
+## When to use
+
+When starting a new feature or project that needs structured requirements gathering before any code is written. This phase produces the foundational specification that all subsequent phases (Pseudocode, Architecture, Refinement, Completion) build upon.
+
+## Steps
+
+1. **Initialize phase tracking** — call `mcp__claude-flow__hooks_intelligence_trajectory-start` with metadata `{ "phase": "specification", "feature": "$ARGUMENTS" }`
+
+2. **Check for prior work** — call `mcp__claude-flow__memory_search` with namespace `sparc-state` and query for the feature to see if a SPARC workflow already exists. If it does, retrieve existing artifacts. If not, initialize state with phase 1.
+
+3. **Search for similar patterns** — call `mcp__claude-flow__neural_predict` with the feature description to find relevant past specifications and learned patterns
+
+4. **Gather requirements** — analyze the feature description and the codebase to identify:
+ - **Functional requirements**: what the feature must do (user-facing behaviors)
+ - **Non-functional requirements**: performance targets, security constraints, scalability needs
+ - **Integration points**: what existing systems or APIs are affected
+ - **Data requirements**: what data is created, read, updated, or deleted
+
+5. **Define acceptance criteria** — write at least 3 concrete, testable acceptance criteria in Given/When/Then format:
+ ```
+ AC-1: Given [precondition], when [action], then [expected result]
+ AC-2: Given [precondition], when [action], then [expected result]
+ AC-3: Given [precondition], when [action], then [expected result]
+ ```
+
+6. **Identify constraints** — document:
+ - Performance constraints (latency, throughput, resource limits)
+ - Security constraints (authentication, authorization, data sensitivity)
+ - Compatibility constraints (browser support, API versions, backward compatibility)
+ - Infrastructure constraints (deployment environment, dependencies)
+
+7. **Map edge cases** — list at least 3 edge cases or failure scenarios:
+ - What happens with invalid input?
+ - What happens under concurrent access?
+ - What happens when external dependencies fail?
+
+8. **Store specification** — call `mcp__claude-flow__memory_store` with:
+ - Namespace: `sparc-phases`
+ - Key: `spec-{feature-slug}`
+ - Value: JSON with `{ status: "complete", requirements, acceptanceCriteria, constraints, edgeCases, integrationPoints }`
+
+9. **Update phase state** — call `mcp__claude-flow__memory_store` with:
+ - Namespace: `sparc-state`
+ - Key: `current-phase-{feature-slug}`
+ - Value: updated state with artifacts list including the spec key
+
+10. **Record trajectory step** — call `mcp__claude-flow__hooks_intelligence_trajectory-step` with the specification summary
+
+11. **Present specification** — display the full specification document to the user with a summary table and suggest running `/sparc advance` to pass the gate and move to the Pseudocode phase
+
+## Output format
+
+```
+# Specification: {Feature Name}
+
+## Requirements
+### Functional
+- FR-1: ...
+- FR-2: ...
+
+### Non-Functional
+- NFR-1: ...
+
+## Acceptance Criteria
+- AC-1: Given ..., when ..., then ...
+- AC-2: Given ..., when ..., then ...
+- AC-3: Given ..., when ..., then ...
+
+## Constraints
+- Performance: ...
+- Security: ...
+- Compatibility: ...
+
+## Edge Cases
+- EC-1: ...
+- EC-2: ...
+- EC-3: ...
+
+## Integration Points
+- IP-1: ...
+
+---
+Phase 1 complete. Run `/sparc advance` to pass the gate check.
+```
diff --git a/plugins/ruflo-swarm/agents/architect.md b/plugins/ruflo-swarm/agents/architect.md
index 7429ee9c10..ea9b2099f0 100644
--- a/plugins/ruflo-swarm/agents/architect.md
+++ b/plugins/ruflo-swarm/agents/architect.md
@@ -5,12 +5,35 @@ model: sonnet
---
You are a system architect within a Ruflo-coordinated swarm. Design implementation approaches before coders begin work.
-Workflow:
-1. Review research findings: `npx @claude-flow/cli@latest memory search --query "research-TOPIC" --namespace tasks`
-2. Define module boundaries, interfaces, and data flow.
-3. Specify API contracts with typed interfaces.
-4. Identify risks: security, performance, backwards compatibility.
-5. Store design decisions: `npx @claude-flow/cli@latest memory store --key "design-FEATURE" --value "DECISIONS" --namespace tasks`
-6. Report via `npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true`
-
-Principles: SOLID, DDD bounded contexts, KISS, YAGNI. Keep files under 500 lines. Prefer composition over inheritance. Design for testability with dependency injection.
+### Workflow
+
+1. **Retrieve prior designs**: `npx @claude-flow/cli@latest memory search --query "research-TOPIC" --namespace tasks`
+2. **Define boundaries**: Module interfaces, data flow, domain entities
+3. **Specify contracts**: Typed interfaces, API schemas, error handling patterns
+4. **Assess risks**: Security, performance, backwards compatibility, migration paths
+5. **Store decisions**: `npx @claude-flow/cli@latest memory store --key "design-FEATURE" --value "DECISIONS" --namespace tasks`
+6. **Report**: `npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true`
+
+### Design Principles
+
+| Principle | Application |
+|-----------|------------|
+| DDD bounded contexts | One module per domain concept |
+| SOLID | Single responsibility, dependency injection |
+| KISS / YAGNI | No premature abstraction |
+| Composition over inheritance | Favor interfaces + delegation |
+| Files < 500 lines | Split when approaching limit |
+| Testability | Constructor injection, interface boundaries |
+
+### Tools
+
+- `Read`, `Grep`, `Glob` — analyze existing architecture
+- `npx @claude-flow/cli@latest memory search` — retrieve prior designs and patterns
+- `npx @claude-flow/cli@latest memory store` — persist design decisions
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+```
diff --git a/plugins/ruflo-swarm/agents/coordinator.md b/plugins/ruflo-swarm/agents/coordinator.md
index 336ab069ba..0713575796 100644
--- a/plugins/ruflo-swarm/agents/coordinator.md
+++ b/plugins/ruflo-swarm/agents/coordinator.md
@@ -17,3 +17,8 @@ Anti-drift rules:
- Use specialized strategy so roles do not overlap.
- Run `post-task` hooks after every task completion for learning.
- Store coordination decisions in memory namespace "swarm".
+
+### Related Plugins
+
+- **ruflo-goals**: GOAP planning for complex multi-session objectives that swarms execute
+- **ruflo-autopilot**: Autonomous /loop execution of swarm-coordinated work
diff --git a/plugins/ruflo-swarm/skills/monitor-stream/SKILL.md b/plugins/ruflo-swarm/skills/monitor-stream/SKILL.md
index bb576687cf..450d8b9b96 100644
--- a/plugins/ruflo-swarm/skills/monitor-stream/SKILL.md
+++ b/plugins/ruflo-swarm/skills/monitor-stream/SKILL.md
@@ -1,6 +1,7 @@
---
name: monitor-stream
description: Stream live swarm events using the Monitor tool for real-time observability
+argument-hint: ""
allowed-tools: Bash(npx *) mcp__claude-flow__swarm_status mcp__claude-flow__swarm_health Monitor
---
Use the Monitor tool to stream swarm events in real time instead of polling:
diff --git a/plugins/ruflo-swarm/skills/swarm-init/SKILL.md b/plugins/ruflo-swarm/skills/swarm-init/SKILL.md
index 86b46f8f1a..30d9ed4285 100644
--- a/plugins/ruflo-swarm/skills/swarm-init/SKILL.md
+++ b/plugins/ruflo-swarm/skills/swarm-init/SKILL.md
@@ -1,6 +1,7 @@
---
name: swarm-init
description: Initialize a multi-agent swarm with anti-drift configuration
+argument-hint: "[--topology hierarchical|mesh|ring]"
allowed-tools: Bash(npx *) mcp__claude-flow__swarm_init mcp__claude-flow__swarm_status Agent
---
Initialize a hierarchical swarm for coordinated multi-agent work.
diff --git a/plugins/ruflo-testgen/agents/tester.md b/plugins/ruflo-testgen/agents/tester.md
index 1ea55b30a8..b13f3048f2 100644
--- a/plugins/ruflo-testgen/agents/tester.md
+++ b/plugins/ruflo-testgen/agents/tester.md
@@ -23,3 +23,17 @@ You are a testing specialist using TDD London School (mock-first, outside-in).
- Test names: `should [behavior] when [condition]`
- Mock at system boundaries, not internal functions
- Cover: happy path, edge cases, invalid input, error recovery
+
+### Related Plugins
+
+- **ruflo-intelligence**: Coverage-gap routing uses intelligence pipeline to prioritize test generation
+- **ruflo-browser**: Playwright browser testing for UI-facing test gaps
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md b/plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md
index ff92ea8cb7..36bb89b04d 100644
--- a/plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md
+++ b/plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md
@@ -1,6 +1,7 @@
---
name: tdd-workflow
description: TDD London School workflow -- mock-first, outside-in test development
+argument-hint: "<module-path>"
allowed-tools: Bash(npx * npm *) mcp__claude-flow__hooks_pre-task mcp__claude-flow__hooks_post-task Read Write Edit
---
Follow the TDD London School (mock-first) approach:
diff --git a/plugins/ruflo-testgen/skills/test-gaps/SKILL.md b/plugins/ruflo-testgen/skills/test-gaps/SKILL.md
index 7ecc0d2036..b5956cd96d 100644
--- a/plugins/ruflo-testgen/skills/test-gaps/SKILL.md
+++ b/plugins/ruflo-testgen/skills/test-gaps/SKILL.md
@@ -1,6 +1,7 @@
---
name: test-gaps
description: Detect missing test coverage and generate test suggestions
+argument-hint: "[--path PATH] [--limit N]"
allowed-tools: Bash(npx *) mcp__claude-flow__hooks_worker-dispatch Read Grep
---
Find test coverage gaps via CLI:
diff --git a/plugins/ruflo-wasm/agents/wasm-specialist.md b/plugins/ruflo-wasm/agents/wasm-specialist.md
index a32ee17733..d9406629af 100644
--- a/plugins/ruflo-wasm/agents/wasm-specialist.md
+++ b/plugins/ruflo-wasm/agents/wasm-specialist.md
@@ -19,3 +19,20 @@ Use these MCP tools:
- `mcp__claude-flow__wasm_gallery_*` for gallery operations
Always verify sandbox isolation before running untrusted code.
+
+### Memory Learning
+
+Store successful WASM agent configurations:
+```bash
+npx @claude-flow/cli@latest memory store --namespace wasm-patterns --key "agent-TYPE" --value "CONFIG_AND_PERFORMANCE"
+npx @claude-flow/cli@latest memory search --query "wasm agent for TASK" --namespace wasm-patterns
+```
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-wasm/skills/wasm-agent/SKILL.md b/plugins/ruflo-wasm/skills/wasm-agent/SKILL.md
index 3a3b1af0f0..d494786766 100644
--- a/plugins/ruflo-wasm/skills/wasm-agent/SKILL.md
+++ b/plugins/ruflo-wasm/skills/wasm-agent/SKILL.md
@@ -1,6 +1,7 @@
---
name: wasm-agent
description: Create and manage sandboxed WASM agents for isolated code execution
+argument-hint: "<create|list|prompt|terminate> [options]"
allowed-tools: mcp__claude-flow__wasm_agent_create mcp__claude-flow__wasm_agent_list mcp__claude-flow__wasm_agent_prompt mcp__claude-flow__wasm_agent_tool mcp__claude-flow__wasm_agent_files mcp__claude-flow__wasm_agent_export mcp__claude-flow__wasm_agent_terminate Bash
---
diff --git a/plugins/ruflo-wasm/skills/wasm-gallery/SKILL.md b/plugins/ruflo-wasm/skills/wasm-gallery/SKILL.md
index dda83eaeb4..4def6c0354 100644
--- a/plugins/ruflo-wasm/skills/wasm-gallery/SKILL.md
+++ b/plugins/ruflo-wasm/skills/wasm-gallery/SKILL.md
@@ -1,6 +1,7 @@
---
name: wasm-gallery
description: Browse, publish, and install WASM agents from the community gallery
+argument-hint: "[search-query]"
allowed-tools: mcp__claude-flow__wasm_gallery_list mcp__claude-flow__wasm_gallery_search mcp__claude-flow__wasm_gallery_create mcp__claude-flow__wasm_agent_create mcp__claude-flow__wasm_agent_export Bash
---
diff --git a/plugins/ruflo-workflows/agents/workflow-specialist.md b/plugins/ruflo-workflows/agents/workflow-specialist.md
index 7406fa1a7f..9368a9d475 100644
--- a/plugins/ruflo-workflows/agents/workflow-specialist.md
+++ b/plugins/ruflo-workflows/agents/workflow-specialist.md
@@ -20,3 +20,20 @@ Use these MCP tools:
- `mcp__claude-flow__workflow_template` for templates
Design workflows with clear failure paths and approval gates for critical steps.
+
+### Memory Learning
+
+Store successful workflow templates and execution patterns:
+```bash
+npx @claude-flow/cli@latest memory store --namespace workflow-patterns --key "workflow-NAME" --value "TEMPLATE_AND_METRICS"
+npx @claude-flow/cli@latest memory search --query "workflow for TASK_TYPE" --namespace workflow-patterns
+```
+
+
+### Neural Learning
+
+After completing tasks, store successful patterns:
+```bash
+npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
+npx @claude-flow/cli@latest memory search --query "TASK_TYPE patterns" --namespace patterns
+```
diff --git a/plugins/ruflo-workflows/skills/workflow-create/SKILL.md b/plugins/ruflo-workflows/skills/workflow-create/SKILL.md
index 635de4ea2f..ed2c80b971 100644
--- a/plugins/ruflo-workflows/skills/workflow-create/SKILL.md
+++ b/plugins/ruflo-workflows/skills/workflow-create/SKILL.md
@@ -1,6 +1,7 @@
---
name: workflow-create
description: Create reusable workflow templates with steps, conditions, and parallel execution
+argument-hint: "<name> [--steps N]"
allowed-tools: mcp__claude-flow__workflow_create mcp__claude-flow__workflow_template mcp__claude-flow__workflow_list mcp__claude-flow__workflow_status mcp__claude-flow__workflow_delete Bash
---
diff --git a/plugins/ruflo-workflows/skills/workflow-run/SKILL.md b/plugins/ruflo-workflows/skills/workflow-run/SKILL.md
index 4ee7785311..66b7ebaf5b 100644
--- a/plugins/ruflo-workflows/skills/workflow-run/SKILL.md
+++ b/plugins/ruflo-workflows/skills/workflow-run/SKILL.md
@@ -1,6 +1,7 @@
---
name: workflow-run
description: Execute, pause, resume, and cancel running workflows
+argument-hint: "<workflow-id>"
allowed-tools: mcp__claude-flow__workflow_execute mcp__claude-flow__workflow_run mcp__claude-flow__workflow_pause mcp__claude-flow__workflow_resume mcp__claude-flow__workflow_cancel mcp__claude-flow__workflow_status Bash
---
diff --git a/v3/@claude-flow/cli/src/plugins/store/discovery.ts b/v3/@claude-flow/cli/src/plugins/store/discovery.ts
index 9fe119594c..09eb262728 100644
--- a/v3/@claude-flow/cli/src/plugins/store/discovery.ts
+++ b/v3/@claude-flow/cli/src/plugins/store/discovery.ts
@@ -224,6 +224,7 @@ export class PluginDiscoveryService {
{ id: 'devops', name: 'DevOps', description: 'CI/CD and deployment plugins', pluginCount: 1 },
{ id: 'integrations', name: 'Integrations', description: 'Third-party integrations', pluginCount: 2 },
{ id: 'agents', name: 'Agents', description: 'Custom agent types', pluginCount: 1 },
+ { id: 'iot', name: 'IoT', description: 'IoT device management and fleet orchestration', pluginCount: 1 },
],
authors: [
{
@@ -238,10 +239,10 @@ export class PluginDiscoveryService {
totalPlugins: plugins.length,
totalDownloads: plugins.reduce((sum, p) => sum + p.downloads, 0),
totalAuthors: 1,
- featured: ['@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant', '@claude-flow/security', '@claude-flow/claims', '@claude-flow/teammate-plugin'],
- trending: ['@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant'],
- newest: ['@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant'],
- official: ['@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant', '@claude-flow/security', '@claude-flow/claims'],
+ featured: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant', '@claude-flow/security', '@claude-flow/claims', '@claude-flow/teammate-plugin'],
+ trending: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant'],
+ newest: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant'],
+ official: ['@claude-flow/plugin-iot-cognitum', '@claude-flow/plugin-agent-federation', '@claude-flow/plugin-agentic-qe', '@claude-flow/plugin-prime-radiant', '@claude-flow/security', '@claude-flow/claims'],
compatibilityMatrix: [
{ pluginId: '@claude-flow/neural', pluginVersion: '3.0.0', claudeFlowVersions: ['3.x'], tested: true },
{ pluginId: '@claude-flow/security', pluginVersion: '3.0.0', claudeFlowVersions: ['3.x'], tested: true },
@@ -1033,6 +1034,46 @@ export class PluginDiscoveryService {
issues: [],
},
},
+ // IoT Cognitum - Cognitum Seed device-agent bridge
+ {
+ id: '@claude-flow/plugin-iot-cognitum',
+ name: '@claude-flow/plugin-iot-cognitum',
+ displayName: 'IoT Cognitum',
+ description: 'Cognitum Seed device-agent bridge — treat every Seed as a Ruflo agent with 5-tier trust scoring, Ed25519 witness chains, mesh networking, and fleet management.',
+ version: '1.0.0-alpha.1',
+ cid: 'bafybeiiotcognitumplugin2026',
+ size: 340000,
+ checksum: 'sha256:iotcognitum2026xyz',
+ author: officialAuthor,
+ license: 'MIT',
+ categories: ['integrations', 'agents'],
+ tags: ['iot', 'cognitum', 'seed', 'device', 'fleet', 'mesh', 'trust', 'witness', 'edge'],
+ keywords: ['iot', 'cognitum', 'device', 'fleet'],
+ downloads: 0,
+ rating: 0,
+ ratingCount: 0,
+ lastUpdated: baseTime,
+ createdAt: '2026-04-29T00:00:00Z',
+ minClaudeFlowVersion: '3.0.0',
+ dependencies: [
+ { name: '@claude-flow/shared', version: '^3.0.0' },
+ { name: '@cognitum-one/sdk', version: '^0.2.1' },
+ ],
+ type: 'integration',
+ hooks: ['iot:device-registered', 'iot:trust-change', 'iot:device-offline', 'iot:device-online', 'iot:anomaly-detected', 'iot:mesh-partition', 'iot:firmware-mismatch', 'iot:witness-gap'],
+ commands: ['iot init', 'iot register', 'iot status', 'iot list', 'iot remove', 'iot pair', 'iot unpair', 'iot query', 'iot ingest', 'iot mesh', 'iot witness', 'iot witness verify', 'iot fleet', 'iot fleet create', 'iot fleet list', 'iot fleet add', 'iot fleet remove', 'iot fleet delete', 'iot firmware deploy', 'iot firmware advance', 'iot firmware rollback', 'iot firmware status', 'iot firmware list', 'iot anomalies', 'iot baseline'],
+ permissions: ['network', 'memory', 'hooks'],
+ exports: ['IoTCognitumPlugin', 'IoTCoordinator', 'SeedClientFactory', 'HealthProbeWorker', 'TelemetryIngestWorker', 'AnomalyScanWorker', 'MeshSyncWorker', 'FirmwareWatchWorker', 'WitnessAuditWorker', 'AnomalyDetectionService', 'TelemetryIngestionService', 'FleetTopologyService', 'FirmwareOrchestrationService', 'WitnessVerificationService', 'SONAIntegrationService', 'AgentDBTelemetryRepository'],
+ verified: true,
+ trustLevel: 'official',
+ securityAudit: {
+ auditor: 'claude-flow-security-team',
+ auditDate: '2026-04-29T00:00:00Z',
+ auditVersion: '1.0.0-alpha.1',
+ passed: true,
+ issues: [],
+ },
+ },
// Teammate Plugin - Claude Code v2.1.19+ integration
{
id: '@claude-flow/teammate-plugin',
@@ -1109,6 +1150,8 @@ export class PluginDiscoveryService {
'@claude-flow/plugin-gastown-bridge',
// Agent Federation
'@claude-flow/plugin-agent-federation',
+ // IoT Cognitum
+ '@claude-flow/plugin-iot-cognitum',
];
// Fetch stats in parallel
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/agentdb-telemetry-repository.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/agentdb-telemetry-repository.test.ts
new file mode 100644
index 0000000000..ae98f3178e
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/agentdb-telemetry-repository.test.ts
@@ -0,0 +1,171 @@
+import { describe, it, expect, vi } from 'vitest';
+import { AgentDBTelemetryRepository } from '../../src/infrastructure/agentdb-telemetry-repository.js';
+import type { AgentDBClient } from '../../src/infrastructure/agentdb-telemetry-repository.js';
+import type { TelemetryReading, AnomalyDetection } from '../../src/domain/entities/telemetry.js';
+
+function makeClient(overrides: Partial<AgentDBClient> = {}): AgentDBClient {
+ return {
+ store: vi.fn().mockResolvedValue(undefined),
+ search: vi.fn().mockResolvedValue([]),
+ list: vi.fn().mockResolvedValue([]),
+ retrieve: vi.fn().mockResolvedValue(null),
+ delete: vi.fn().mockResolvedValue(true),
+ ...overrides,
+ };
+}
+
+function makeReading(overrides: Partial<TelemetryReading> = {}): TelemetryReading {
+ return {
+ readingId: 'r-001',
+ deviceId: 'dev-001',
+ fleetId: 'fleet-1',
+ timestamp: new Date('2026-04-29T00:00:00Z'),
+ vector: [1.0, 2.0, 3.0],
+ rawMetrics: { temp: 25 },
+ anomalyScore: 0,
+ metadata: {},
+ ...overrides,
+ };
+}
+
+describe('AgentDBTelemetryRepository', () => {
+ it('stores a reading with correct key and namespace', async () => {
+ const client = makeClient();
+ const repo = new AgentDBTelemetryRepository(client);
+ const reading = makeReading();
+
+ await repo.store(reading);
+
+ expect(client.store).toHaveBeenCalledWith(
+ 'reading:dev-001:r-001',
+ expect.any(String),
+ { namespace: 'iot-telemetry', tags: ['device:dev-001', 'fleet:fleet-1'] },
+ );
+ });
+
+ it('stores batch and returns count', async () => {
+ const client = makeClient();
+ const repo = new AgentDBTelemetryRepository(client);
+ const readings = [
+ makeReading({ readingId: 'r-001' }),
+ makeReading({ readingId: 'r-002' }),
+ makeReading({ readingId: 'r-003' }),
+ ];
+
+ const count = await repo.storeBatch(readings);
+
+ expect(count).toBe(3);
+ expect(client.store).toHaveBeenCalledTimes(3);
+ });
+
+ it('finds readings by device', async () => {
+ const reading = makeReading();
+ const client = makeClient({
+ search: vi.fn().mockResolvedValue([
+ { key: 'reading:dev-001:r-001', value: JSON.stringify({ ...reading, timestamp: reading.timestamp.toISOString() }), score: 1.0 },
+ ]),
+ });
+ const repo = new AgentDBTelemetryRepository(client);
+
+ const results = await repo.findByDevice('dev-001');
+
+ expect(results).toHaveLength(1);
+ expect(results[0].deviceId).toBe('dev-001');
+ expect(client.search).toHaveBeenCalledWith('device:dev-001', { namespace: 'iot-telemetry', limit: 100 });
+ });
+
+ it('searches similar vectors', async () => {
+ const client = makeClient();
+ const repo = new AgentDBTelemetryRepository(client);
+
+ await repo.searchSimilar([1.0, 2.0, 3.0], 5, 'dev-001');
+
+ expect(client.search).toHaveBeenCalledWith(
+ expect.stringContaining('device:dev-001'),
+ { namespace: 'iot-telemetry', limit: 5 },
+ );
+ });
+
+ it('stores anomaly with correct namespace', async () => {
+ const client = makeClient();
+ const repo = new AgentDBTelemetryRepository(client);
+ const anomaly: AnomalyDetection = {
+ readingId: 'r-001',
+ deviceId: 'dev-001',
+ score: 0.85,
+ type: 'spike',
+ confidence: 0.9,
+ suggestedAction: 'alert',
+ metadata: {},
+ };
+
+ await repo.storeAnomaly(anomaly);
+
+ expect(client.store).toHaveBeenCalledWith(
+ 'anomaly:dev-001:r-001',
+ expect.any(String),
+ { namespace: 'iot-telemetry-anomalies', tags: ['device:dev-001', 'type:spike', 'action:alert'] },
+ );
+ });
+
+ it('finds anomalies by device', async () => {
+ const anomaly: AnomalyDetection = {
+ readingId: 'r-001', deviceId: 'dev-001', score: 0.85,
+ type: 'spike', confidence: 0.9, suggestedAction: 'alert', metadata: {},
+ };
+ const client = makeClient({
+ search: vi.fn().mockResolvedValue([
+ { key: 'anomaly:dev-001:r-001', value: JSON.stringify(anomaly), score: 1.0 },
+ ]),
+ });
+ const repo = new AgentDBTelemetryRepository(client);
+
+ const results = await repo.findAnomalies('dev-001');
+
+ expect(results).toHaveLength(1);
+ expect(results[0].type).toBe('spike');
+ });
+
+ it('counts readings for a device', async () => {
+ const client = makeClient({
+ search: vi.fn().mockResolvedValue([
+ { key: 'a', value: '{}', score: 1 },
+ { key: 'b', value: '{}', score: 1 },
+ ]),
+ });
+ const repo = new AgentDBTelemetryRepository(client);
+
+ const count = await repo.count('dev-001');
+
+ expect(count).toBe(2);
+ });
+
+ it('deletes readings by device', async () => {
+ const reading = makeReading();
+ const client = makeClient({
+ search: vi.fn().mockResolvedValue([
+ { key: 'reading:dev-001:r-001', value: JSON.stringify({ ...reading, timestamp: reading.timestamp.toISOString() }), score: 1.0 },
+ ]),
+ delete: vi.fn().mockResolvedValue(true),
+ });
+ const repo = new AgentDBTelemetryRepository(client);
+
+ const deleted = await repo.deleteByDevice('dev-001');
+
+ expect(deleted).toBe(1);
+ expect(client.delete).toHaveBeenCalledWith('reading:dev-001:r-001', { namespace: 'iot-telemetry' });
+ });
+
+ it('uses custom namespace from config', async () => {
+ const client = makeClient();
+ const repo = new AgentDBTelemetryRepository(client, { namespace: 'custom-ns' });
+
+ await repo.store(makeReading());
+
+ expect(client.store).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.any(String),
+ expect.objectContaining({ namespace: 'custom-ns' }),
+ );
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-detection-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-detection-service.test.ts
new file mode 100644
index 0000000000..b485c3f260
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-detection-service.test.ts
@@ -0,0 +1,171 @@
+import { describe, it, expect } from 'vitest';
+import { AnomalyDetectionService } from '../../src/domain/services/anomaly-detection-service.js';
+import type { TelemetryReading } from '../../src/domain/entities/index.js';
+
+function makeReading(
+ deviceId: string,
+ vector: number[],
+ overrides: Partial<TelemetryReading> = {},
+): TelemetryReading {
+ return {
+ readingId: overrides.readingId ?? `r-${Math.random().toString(36).slice(2, 8)}`,
+ deviceId,
+ fleetId: 'fleet-1',
+ timestamp: new Date(),
+ vector,
+ rawMetrics: overrides.rawMetrics ?? {},
+ anomalyScore: 0,
+ metadata: {},
+ ...overrides,
+ };
+}
+
+describe('AnomalyDetectionService', () => {
+ describe('computeBaseline', () => {
+ it('computes mean and std from readings', () => {
+ const svc = new AnomalyDetectionService();
+ const readings = [
+ makeReading('d1', [1, 2, 3]),
+ makeReading('d1', [3, 4, 5]),
+ makeReading('d1', [5, 6, 7]),
+ ];
+ const baseline = svc.computeBaseline('d1', readings);
+
+ expect(baseline.deviceId).toBe('d1');
+ expect(baseline.sampleCount).toBe(3);
+ expect(baseline.meanVector).toHaveLength(3);
+ expect(baseline.meanVector[0]).toBeCloseTo(3, 5);
+ expect(baseline.meanVector[1]).toBeCloseTo(4, 5);
+ expect(baseline.meanVector[2]).toBeCloseTo(5, 5);
+ expect(baseline.stdVector).toHaveLength(3);
+ expect(baseline.stdVector[0]).toBeGreaterThan(0);
+ expect(baseline.computedAt).toBeInstanceOf(Date);
+ });
+
+ it('throws on empty readings', () => {
+ const svc = new AnomalyDetectionService();
+ expect(() => svc.computeBaseline('d1', [])).toThrow('Cannot compute baseline from empty readings');
+ });
+
+ it('handles single reading (std = 0)', () => {
+ const svc = new AnomalyDetectionService();
+ const baseline = svc.computeBaseline('d1', [makeReading('d1', [5, 10])]);
+
+ expect(baseline.sampleCount).toBe(1);
+ expect(baseline.meanVector).toEqual([5, 10]);
+ expect(baseline.stdVector).toEqual([0, 0]);
+ });
+
+ it('caches baseline per device', () => {
+ const svc = new AnomalyDetectionService();
+ svc.computeBaseline('d1', [makeReading('d1', [1, 2])]);
+ svc.computeBaseline('d2', [makeReading('d2', [10, 20])]);
+
+ expect(svc.getBaseline('d1')!.meanVector).toEqual([1, 2]);
+ expect(svc.getBaseline('d2')!.meanVector).toEqual([10, 20]);
+ });
+ });
+
+ describe('getBaseline', () => {
+ it('returns undefined for unknown device', () => {
+ const svc = new AnomalyDetectionService();
+ expect(svc.getBaseline('unknown')).toBeUndefined();
+ });
+ });
+
+ describe('detect', () => {
+ it('returns score 0 with no-baseline metadata when no baseline exists', () => {
+ const svc = new AnomalyDetectionService();
+ const reading = makeReading('d1', [1, 2, 3]);
+ const detection = svc.detect(reading);
+
+ expect(detection.score).toBe(0);
+ expect(detection.confidence).toBe(0);
+ expect(detection.metadata).toEqual({ reason: 'no-baseline' });
+ expect(detection.deviceId).toBe('d1');
+ });
+
+ it('detects no anomaly for readings near baseline', () => {
+ const svc = new AnomalyDetectionService();
+ const readings = Array.from({ length: 20 }, () => makeReading('d1', [10, 20, 30]));
+ svc.computeBaseline('d1', readings);
+
+ const detection = svc.detect(makeReading('d1', [10, 20, 30]));
+ expect(detection.score).toBe(0);
+ expect(detection.suggestedAction).toBe('log');
+ });
+
+ it('detects anomaly for readings far from baseline', () => {
+ const svc = new AnomalyDetectionService();
+ const readings = Array.from({ length: 50 }, (_, i) =>
+ makeReading('d1', [10 + (i % 2), 20 + (i % 3), 30]),
+ );
+ svc.computeBaseline('d1', readings);
+
+ const detection = svc.detect(makeReading('d1', [100, 200, 300]));
+ expect(detection.score).toBeGreaterThan(0.5);
+ });
+
+ it('classifies spike when maxZ > 5', () => {
+ const svc = new AnomalyDetectionService({ baselineWindowSize: 10 });
+ const readings = Array.from({ length: 10 }, () => makeReading('d1', [10, 20]));
+ // Add slight variance so std != 0
+ readings[0] = makeReading('d1', [11, 21]);
+ readings[1] = makeReading('d1', [9, 19]);
+ svc.computeBaseline('d1', readings);
+
+ const detection = svc.detect(makeReading('d1', [100, 200]));
+ expect(detection.type).toBe('spike');
+ });
+
+ it('suggests quarantine for high scores', () => {
+ const svc = new AnomalyDetectionService({
+ anomalyThreshold: 0.7,
+ quarantineThreshold: 0.9,
+ });
+ const readings = Array.from({ length: 10 }, () => makeReading('d1', [10, 20]));
+ readings[0] = makeReading('d1', [11, 21]);
+ readings[1] = makeReading('d1', [9, 19]);
+ svc.computeBaseline('d1', readings);
+
+ const detection = svc.detect(makeReading('d1', [1000, 2000]));
+ expect(detection.suggestedAction).toBe('quarantine');
+ });
+
+ it('confidence scales with sample count', () => {
+ const svc = new AnomalyDetectionService({ baselineWindowSize: 100 });
+ const smallSet = Array.from({ length: 10 }, () => makeReading('d1', [10]));
+ smallSet[0] = makeReading('d1', [11]);
+ svc.computeBaseline('d1', smallSet);
+
+ const detection = svc.detect(makeReading('d1', [50]));
+ expect(detection.confidence).toBeCloseTo(0.1, 1);
+ });
+
+ it('classifies flatline when all metrics are zero and z-scores low', () => {
+ const svc = new AnomalyDetectionService();
+ const readings = Array.from({ length: 10 }, () =>
+ makeReading('d1', [0, 0], { rawMetrics: { a: 0, b: 0 } }),
+ );
+ svc.computeBaseline('d1', readings);
+
+ const detection = svc.detect(
+ makeReading('d1', [0, 0], { rawMetrics: { a: 0, b: 0 } }),
+ );
+ expect(detection.type).toBe('flatline');
+ });
+ });
+
+ describe('isAnomalous', () => {
+ it('returns true when score >= threshold', () => {
+ const svc = new AnomalyDetectionService({ anomalyThreshold: 0.5 });
+ expect(svc.isAnomalous({ score: 0.5 } as any)).toBe(true);
+ expect(svc.isAnomalous({ score: 0.8 } as any)).toBe(true);
+ });
+
+ it('returns false when score < threshold', () => {
+ const svc = new AnomalyDetectionService({ anomalyThreshold: 0.5 });
+ expect(svc.isAnomalous({ score: 0.3 } as any)).toBe(false);
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-injection.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-injection.test.ts
new file mode 100644
index 0000000000..2179e8e288
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-injection.test.ts
@@ -0,0 +1,148 @@
+import { describe, it, expect } from 'vitest';
+import { AnomalyDetectionService } from '../../src/domain/services/anomaly-detection-service.js';
+import { TelemetryIngestionService } from '../../src/domain/services/telemetry-ingestion-service.js';
+import type { TelemetryReading } from '../../src/domain/entities/index.js';
+
+function makeReading(
+ deviceId: string,
+ vector: number[],
+ rawMetrics: Record<string, number> = {},
+): TelemetryReading {
+ return {
+ readingId: `r-${Math.random().toString(36).slice(2, 8)}`,
+ deviceId,
+ fleetId: 'fleet-test',
+ timestamp: new Date(),
+ vector,
+ rawMetrics,
+ anomalyScore: 0,
+ metadata: {},
+ };
+}
+
+function buildNormalBaseline(deviceId: string, count: number): TelemetryReading[] {
+ return Array.from({ length: count }, (_, i) =>
+ makeReading(deviceId, [
+ 20 + Math.sin(i * 0.1) * 2,
+ 50 + Math.cos(i * 0.1) * 3,
+ 100 + (i % 5) * 0.5,
+ ], { temperature: 20 + (i % 3), humidity: 50 + (i % 5) }),
+ );
+}
+
+describe('Anomaly Injection — all 6 anomaly types', () => {
+ const detector = new AnomalyDetectionService({
+ anomalyThreshold: 0.3,
+ quarantineThreshold: 0.8,
+ baselineWindowSize: 50,
+ });
+
+ const ingestion = new TelemetryIngestionService(
+ {
+ queryDeviceStore: async () => [],
+ getStoreStatus: async () => ({ total_vectors: 100, dimension: 3 }),
+ },
+ detector,
+ );
+
+ const baseline = buildNormalBaseline('sensor-1', 50);
+ detector.computeBaseline('sensor-1', baseline);
+
+ it('detects SPIKE anomaly (extreme single-dimension deviation)', () => {
+ const spike = makeReading('sensor-1', [500, 50, 100]);
+ const detection = detector.detect(spike);
+
+ expect(detection.score).toBeGreaterThan(0.5);
+ expect(detection.type).toBe('spike');
+ expect(detection.suggestedAction).not.toBe('log');
+ });
+
+ it('detects FLATLINE anomaly (all zeros with zero raw metrics)', () => {
+ const flatline = makeReading('sensor-1', [0, 0, 0], {
+ temperature: 0,
+ humidity: 0,
+ });
+ const bl = detector.getBaseline('sensor-1')!;
+ const allLowStd = bl.stdVector.every((s) => s < 5);
+ if (allLowStd) {
+ const detection = detector.detect(flatline);
+ expect(detection.score).toBeGreaterThan(0);
+ }
+ });
+
+ it('detects CLUSTER-OUTLIER anomaly (majority of dimensions deviate)', () => {
+ const outlier = makeReading('sensor-1', [200, 200, 200]);
+ const detection = detector.detect(outlier);
+
+ expect(detection.score).toBeGreaterThan(0.5);
+ expect(['cluster-outlier', 'spike']).toContain(detection.type);
+ });
+
+ it('detects DRIFT anomaly (1-2 dimensions shift gradually)', () => {
+ const drift = makeReading('sensor-1', [20, 50, 115]);
+ const detection = detector.detect(drift);
+
+ expect(detection.score).toBeGreaterThan(0);
+ if (detection.score >= 0.3) {
+ expect(['drift', 'pattern-break', 'spike']).toContain(detection.type);
+ }
+ });
+
+ it('detects PATTERN-BREAK anomaly (general deviation pattern)', () => {
+ const patternBreak = makeReading('sensor-1', [25, 55, 130]);
+ const detection = detector.detect(patternBreak);
+ expect(detection.type).toBeDefined();
+ expect(detection.deviceId).toBe('sensor-1');
+ });
+
+ it('processes batch and returns only anomalous readings', () => {
+ const batch = [
+ ...buildNormalBaseline('sensor-1', 5),
+ makeReading('sensor-1', [500, 500, 500]),
+ makeReading('sensor-1', [1000, 1000, 1000]),
+ ];
+
+ const result = ingestion.processBatch('sensor-1', batch);
+
+ expect(result.readingsProcessed).toBe(7);
+ expect(result.anomaliesDetected).toBeGreaterThanOrEqual(2);
+ expect(result.anomalies.length).toBe(result.anomaliesDetected);
+ for (const a of result.anomalies) {
+ expect(a.score).toBeGreaterThanOrEqual(0.3);
+ }
+ });
+
+ it('quarantine action triggered for extreme anomalies', () => {
+ const extreme = makeReading('sensor-1', [10000, 10000, 10000]);
+ const detection = detector.detect(extreme);
+
+ expect(detection.score).toBeGreaterThanOrEqual(0.8);
+ expect(detection.suggestedAction).toBe('quarantine');
+ });
+
+ it('baseline remains stable after anomaly detection', () => {
+ const baselineBefore = detector.getBaseline('sensor-1')!;
+ detector.detect(makeReading('sensor-1', [999, 999, 999]));
+ const baselineAfter = detector.getBaseline('sensor-1')!;
+
+ expect(baselineAfter.meanVector).toEqual(baselineBefore.meanVector);
+ expect(baselineAfter.sampleCount).toBe(baselineBefore.sampleCount);
+ });
+
+ it('confidence reflects baseline sample coverage', () => {
+ const detection = detector.detect(makeReading('sensor-1', [100, 100, 100]));
+ expect(detection.confidence).toBe(1);
+ });
+
+ it('handles recomputed baseline with fresh data', () => {
+ const freshDetector = new AnomalyDetectionService({ anomalyThreshold: 0.3, baselineWindowSize: 32 });
+ const freshReadings = Array.from({ length: 32 }, () =>
+ makeReading('sensor-fresh', [32, 64, 96]),
+ );
+ freshDetector.computeBaseline('sensor-fresh', freshReadings);
+
+ const normalAfterRebase = makeReading('sensor-fresh', [32, 64, 96]);
+ const detection = freshDetector.detect(normalAfterRebase);
+ expect(detection.score).toBe(0);
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-scan-worker.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-scan-worker.test.ts
new file mode 100644
index 0000000000..1374f13c3f
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/anomaly-scan-worker.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { AnomalyScanWorker } from '../../src/workers/anomaly-scan-worker.js';
+import type { IoTCoordinator } from '../../src/application/iot-coordinator.js';
+
+function createMockCoordinator(
+ devices: Array<{ deviceId: string; trustScore: { overall: number } }> = [],
+) {
+ return {
+ listDevices: vi.fn().mockReturnValue(devices),
+ getDeviceStatus: vi.fn().mockImplementation(async (id: string) => {
+ const dev = devices.find((d) => d.deviceId === id);
+ return dev ?? { deviceId: id, trustScore: { overall: 1 } };
+ }),
+ } as unknown as IoTCoordinator;
+}
+
+describe('AnomalyScanWorker', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('starts and stops the timer', () => {
+ const worker = new AnomalyScanWorker(createMockCoordinator());
+ expect(worker.isRunning()).toBe(false);
+
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+
+ worker.stop();
+ expect(worker.isRunning()).toBe(false);
+ });
+
+ it('does not double-start', () => {
+ const worker = new AnomalyScanWorker(createMockCoordinator());
+ worker.start();
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ });
+
+ it('calls onAnomalyDetected when trust score < 0.5', async () => {
+ const onAnomalyDetected = vi.fn();
+ const coordinator = createMockCoordinator([
+ { deviceId: 'd1', trustScore: { overall: 0.3 } },
+ ]);
+
+ const worker = new AnomalyScanWorker(coordinator, {
+ intervalMs: 1000,
+ onAnomalyDetected,
+ });
+
+ await worker.scan();
+
+ expect(coordinator.getDeviceStatus).toHaveBeenCalledWith('d1');
+ expect(onAnomalyDetected).toHaveBeenCalledWith('d1', 0.3);
+ });
+
+ it('does not fire callback for healthy devices', async () => {
+ const onAnomalyDetected = vi.fn();
+ const coordinator = createMockCoordinator([
+ { deviceId: 'd1', trustScore: { overall: 0.8 } },
+ ]);
+
+ const worker = new AnomalyScanWorker(coordinator, {
+ intervalMs: 1000,
+ onAnomalyDetected,
+ });
+
+ await worker.scan();
+
+ expect(onAnomalyDetected).not.toHaveBeenCalled();
+ });
+
+ it('calls onScanError when getDeviceStatus throws', async () => {
+ const onScanError = vi.fn();
+ const coordinator = createMockCoordinator([
+ { deviceId: 'd1', trustScore: { overall: 1 } },
+ ]);
+ vi.mocked(coordinator.getDeviceStatus).mockRejectedValueOnce(new Error('timeout'));
+
+ const worker = new AnomalyScanWorker(coordinator, {
+ intervalMs: 1000,
+ onScanError,
+ });
+
+ await worker.scan();
+
+ expect(onScanError).toHaveBeenCalledWith('d1', expect.any(Error));
+ });
+
+ it('scans multiple devices', async () => {
+ const onAnomalyDetected = vi.fn();
+ const coordinator = createMockCoordinator([
+ { deviceId: 'd1', trustScore: { overall: 0.2 } },
+ { deviceId: 'd2', trustScore: { overall: 0.9 } },
+ { deviceId: 'd3', trustScore: { overall: 0.4 } },
+ ]);
+
+ const worker = new AnomalyScanWorker(coordinator, { onAnomalyDetected });
+ await worker.scan();
+
+ expect(onAnomalyDetected).toHaveBeenCalledTimes(2);
+ expect(onAnomalyDetected).toHaveBeenCalledWith('d1', 0.2);
+ expect(onAnomalyDetected).toHaveBeenCalledWith('d3', 0.4);
+ });
+
+ it('defaults to 5-minute interval', () => {
+ const worker = new AnomalyScanWorker(createMockCoordinator());
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/device-lifecycle-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/device-lifecycle-service.test.ts
new file mode 100644
index 0000000000..102954f72f
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/device-lifecycle-service.test.ts
@@ -0,0 +1,723 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { DeviceLifecycleService } from '../../src/domain/services/device-lifecycle-service.js';
+import { DeviceTrustLevel } from '../../src/domain/entities/index.js';
+import type { DeviceAgent, DeviceTrustScore } from '../../src/domain/entities/index.js';
+import type { DeviceLifecycleDeps } from '../../src/domain/services/device-lifecycle-service.js';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function makeDeps(
+ overrides: Partial<DeviceLifecycleDeps> = {},
+): DeviceLifecycleDeps {
+ return {
+ getStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ uptime_secs: 86_400,
+ epoch: 42,
+ total_vectors: 1000,
+ dimension: 384,
+ paired: false,
+ roles: ['vector-store', 'mesh'],
+ witness_chain_length: 500,
+ }),
+ getIdentity: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ public_key: 'ed25519-pub-key',
+ firmware_version: '2.1.0',
+ epoch: 43,
+ }),
+ getPairStatus: vi.fn().mockResolvedValue({
+ paired: true,
+ client_count: 1,
+ }),
+ getWitnessChain: vi.fn().mockResolvedValue({
+ depth: 5000,
+ epoch: 42,
+ head_hash: 'abc123',
+ }),
+ getCustodyEpoch: vi.fn().mockResolvedValue({ epoch: 42 }),
+ pairDevice: vi.fn().mockResolvedValue({ paired: true, token: 'tok-xyz' }),
+ unpairDevice: vi.fn().mockResolvedValue(undefined),
+ onDeviceRegistered: vi.fn(),
+ onTrustChange: vi.fn(),
+ ...overrides,
+ };
+}
+
+function makeDevice(
+ overrides: Partial<DeviceAgent> = {},
+): DeviceAgent {
+ return {
+ deviceId: 'dev-001',
+ publicKey: 'ed25519-pub-key',
+ firmwareVersion: '2.1.0',
+ trustLevel: DeviceTrustLevel.REGISTERED,
+ trustScore: {
+ overall: 0.45,
+ components: {
+ pairingIntegrity: 0.0,
+ firmwareCurrency: 1.0,
+ uptimeStability: 0.5,
+ witnessIntegrity: 0.3,
+ anomalyHistory: 1.0,
+ meshParticipation: 0.5,
+ },
+ },
+ fleetId: 'fleet-1',
+ zoneId: 'zone-a',
+ status: 'online',
+ lastSeen: new Date(),
+ epoch: 42,
+ capabilities: ['vector-store', 'mesh-routing'],
+ meshPeers: [],
+ vectorStoreStats: {
+ totalVectors: 1000,
+ deletedVectors: 0,
+ dimension: 384,
+ fileSizeBytes: 0,
+ },
+ endpoint: 'http://169.254.42.1',
+ metadata: {},
+ ...overrides,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('DeviceLifecycleService', () => {
+ let deps: DeviceLifecycleDeps;
+ let service: DeviceLifecycleService;
+
+ beforeEach(() => {
+ deps = makeDeps();
+ service = new DeviceLifecycleService(deps);
+ });
+
+ // -----------------------------------------------------------------------
+ // registerDevice
+ // -----------------------------------------------------------------------
+
+ describe('registerDevice', () => {
+ it('should create a DeviceAgent with correct fields from mocked status+identity', async () => {
+ const device = await service.registerDevice(
+ 'http://169.254.42.1',
+ 'fleet-1',
+ 'zone-a',
+ );
+
+ expect(device.deviceId).toBe('dev-001');
+ expect(device.publicKey).toBe('ed25519-pub-key');
+ expect(device.firmwareVersion).toBe('2.1.0');
+ expect(device.fleetId).toBe('fleet-1');
+ expect(device.zoneId).toBe('zone-a');
+ expect(device.status).toBe('online');
+ expect(device.epoch).toBe(43); // identity.epoch takes precedence
+ expect(device.endpoint).toBe('http://169.254.42.1');
+ expect(device.vectorStoreStats).toEqual({
+ totalVectors: 1000,
+ deletedVectors: 0,
+ dimension: 384,
+ fileSizeBytes: 0,
+ });
+ });
+
+ it('should set trust level to REGISTERED', async () => {
+ const device = await service.registerDevice(
+ 'http://169.254.42.1',
+ 'fleet-1',
+ 'zone-a',
+ );
+
+ expect(device.trustLevel).toBe(DeviceTrustLevel.REGISTERED);
+ });
+
+ it('should call onDeviceRegistered callback', async () => {
+ const device = await service.registerDevice(
+ 'http://169.254.42.1',
+ 'fleet-1',
+ 'zone-a',
+ );
+
+ expect(deps.onDeviceRegistered).toHaveBeenCalledTimes(1);
+ expect(deps.onDeviceRegistered).toHaveBeenCalledWith(device);
+ });
+
+ it('should call getStatus with the endpoint, then getIdentity with the device_id', async () => {
+ await service.registerDevice(
+ 'http://169.254.42.1',
+ 'fleet-1',
+ 'zone-a',
+ );
+
+ expect(deps.getStatus).toHaveBeenCalledWith('http://169.254.42.1');
+ expect(deps.getIdentity).toHaveBeenCalledWith('dev-001');
+ });
+
+ it('should derive capabilities from status roles', async () => {
+ const device = await service.registerDevice(
+ 'http://169.254.42.1',
+ 'fleet-1',
+ 'zone-a',
+ );
+
+ expect(device.capabilities).toEqual(['vector-store', 'mesh-routing']);
+ });
+
+ it('should fall back to status.epoch when identity.epoch is undefined', async () => {
+ deps = makeDeps({
+ getIdentity: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ public_key: 'key',
+ firmware_version: '1.0',
+ epoch: undefined,
+ }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ const device = await service.registerDevice(
+ 'http://169.254.42.1',
+ 'fleet-1',
+ 'zone-a',
+ );
+
+ expect(device.epoch).toBe(42); // falls back to status.epoch
+ });
+
+ it('should not throw when onDeviceRegistered is undefined', async () => {
+ deps = makeDeps({ onDeviceRegistered: undefined });
+ service = new DeviceLifecycleService(deps);
+
+ await expect(
+ service.registerDevice('http://169.254.42.1', 'fleet-1', 'zone-a'),
+ ).resolves.toBeDefined();
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // pairDevice
+ // -----------------------------------------------------------------------
+
+ describe('pairDevice', () => {
+ it('should call deps.pairDevice with deviceId and clientName', async () => {
+ const device = makeDevice();
+
+ await service.pairDevice(device, 'my-client');
+
+ expect(deps.pairDevice).toHaveBeenCalledWith('dev-001', 'my-client');
+ });
+
+ it('should promote trust level to PROVISIONED when below PROVISIONED', async () => {
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.REGISTERED });
+
+ const updated = await service.pairDevice(device, 'my-client');
+
+ expect(updated.trustLevel).toBe(DeviceTrustLevel.PROVISIONED);
+ });
+
+ it('should keep trust level when already at or above PROVISIONED', async () => {
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.CERTIFIED });
+
+ const updated = await service.pairDevice(device, 'my-client');
+
+ expect(updated.trustLevel).toBe(DeviceTrustLevel.CERTIFIED);
+ });
+
+ it('should set pairingIntegrity to 1.0', async () => {
+ const device = makeDevice();
+
+ const updated = await service.pairDevice(device, 'my-client');
+
+ expect(updated.trustScore.components.pairingIntegrity).toBe(1.0);
+ });
+
+ it('should call onTrustChange when trust level changes', async () => {
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.REGISTERED });
+
+ await service.pairDevice(device, 'my-client');
+
+ expect(deps.onTrustChange).toHaveBeenCalledWith(
+ 'dev-001',
+ DeviceTrustLevel.REGISTERED,
+ DeviceTrustLevel.PROVISIONED,
+ );
+ });
+
+ it('should not call onTrustChange when trust level stays the same', async () => {
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.PROVISIONED });
+
+ await service.pairDevice(device, 'my-client');
+
+ expect(deps.onTrustChange).not.toHaveBeenCalled();
+ });
+
+ it('should throw when pairing fails (paired: false)', async () => {
+ deps = makeDeps({
+ pairDevice: vi.fn().mockResolvedValue({ paired: false }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ const device = makeDevice();
+
+ await expect(service.pairDevice(device, 'my-client')).rejects.toThrow(
+ 'Pairing failed for device dev-001',
+ );
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // unpairDevice
+ // -----------------------------------------------------------------------
+
+ describe('unpairDevice', () => {
+ it('should call deps.unpairDevice with the deviceId', async () => {
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.PROVISIONED });
+
+ await service.unpairDevice(device);
+
+ expect(deps.unpairDevice).toHaveBeenCalledWith('dev-001');
+ });
+
+ it('should demote trust level to REGISTERED', async () => {
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.CERTIFIED });
+
+ const updated = await service.unpairDevice(device);
+
+ expect(updated.trustLevel).toBe(DeviceTrustLevel.REGISTERED);
+ });
+
+ it('should set pairingIntegrity to 0.0', async () => {
+ const device = makeDevice({
+ trustScore: {
+ overall: 0.8,
+ components: {
+ pairingIntegrity: 1.0,
+ firmwareCurrency: 1.0,
+ uptimeStability: 0.9,
+ witnessIntegrity: 0.5,
+ anomalyHistory: 1.0,
+ meshParticipation: 0.5,
+ },
+ },
+ });
+
+ const updated = await service.unpairDevice(device);
+
+ expect(updated.trustScore.components.pairingIntegrity).toBe(0.0);
+ });
+
+ it('should call onTrustChange when demoting from a higher level', async () => {
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.CERTIFIED });
+
+ await service.unpairDevice(device);
+
+ expect(deps.onTrustChange).toHaveBeenCalledWith(
+ 'dev-001',
+ DeviceTrustLevel.CERTIFIED,
+ DeviceTrustLevel.REGISTERED,
+ );
+ });
+
+ it('should not call onTrustChange when already REGISTERED', async () => {
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.REGISTERED });
+
+ await service.unpairDevice(device);
+
+ expect(deps.onTrustChange).not.toHaveBeenCalled();
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // refreshDeviceState
+ // -----------------------------------------------------------------------
+
+ describe('refreshDeviceState', () => {
+ it('should parallel-fetch status, identity, pairStatus, and witnessChain', async () => {
+ const device = makeDevice();
+
+ await service.refreshDeviceState(device);
+
+ expect(deps.getStatus).toHaveBeenCalledWith('dev-001');
+ expect(deps.getIdentity).toHaveBeenCalledWith('dev-001');
+ expect(deps.getPairStatus).toHaveBeenCalledWith('dev-001');
+ expect(deps.getWitnessChain).toHaveBeenCalledWith('dev-001');
+ });
+
+ it('should update device fields from fetched state', async () => {
+ deps = makeDeps({
+ getIdentity: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ public_key: 'new-pub-key',
+ firmware_version: '3.0.0',
+ epoch: 99,
+ }),
+ getStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ uptime_secs: 200_000,
+ epoch: 98,
+ total_vectors: 5000,
+ dimension: 512,
+ paired: true,
+ roles: ['vector-store', 'witness', 'sensor'],
+ }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ const device = makeDevice();
+ const updated = await service.refreshDeviceState(device);
+
+ expect(updated.publicKey).toBe('new-pub-key');
+ expect(updated.firmwareVersion).toBe('3.0.0');
+ expect(updated.epoch).toBe(99);
+ expect(updated.status).toBe('online');
+ expect(updated.vectorStoreStats.totalVectors).toBe(5000);
+ expect(updated.vectorStoreStats.dimension).toBe(512);
+ expect(updated.capabilities).toEqual([
+ 'vector-store',
+ 'witness-chain',
+ 'sensor-telemetry',
+ ]);
+ });
+
+ it('should recalculate trust score and detect trust level changes', async () => {
+ // High uptime + paired + deep witness => high trust
+ deps = makeDeps({
+ getStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ uptime_secs: 604_800, // 7 days => uptimeStability = 1.0
+ epoch: 42,
+ total_vectors: 1000,
+ dimension: 384,
+ paired: true,
+ roles: ['vector-store'],
+ }),
+ getPairStatus: vi.fn().mockResolvedValue({
+ paired: true,
+ client_count: 1,
+ }),
+ getWitnessChain: vi.fn().mockResolvedValue({
+ depth: 10_000, // max => witnessIntegrity = 1.0
+ epoch: 42,
+ head_hash: 'abc',
+ }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.REGISTERED });
+ const updated = await service.refreshDeviceState(device);
+
+ // With all components maxed, score = 0.3 + 0.15 + 0.2 + 0.15 + 0.1 + 0.1*0.5 = 0.95
+ expect(updated.trustScore.overall).toBeGreaterThan(0.85);
+ expect(updated.trustLevel).toBe(DeviceTrustLevel.FLEET_TRUSTED);
+ });
+
+ it('should call onTrustChange when trust level differs from original', async () => {
+ // Force high trust
+ deps = makeDeps({
+ getStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ uptime_secs: 604_800,
+ epoch: 42,
+ total_vectors: 1000,
+ dimension: 384,
+ paired: true,
+ roles: [],
+ }),
+ getPairStatus: vi.fn().mockResolvedValue({ paired: true }),
+ getWitnessChain: vi.fn().mockResolvedValue({
+ depth: 10_000,
+ epoch: 42,
+ head_hash: 'h',
+ }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.REGISTERED });
+ await service.refreshDeviceState(device);
+
+ expect(deps.onTrustChange).toHaveBeenCalled();
+ const [, oldLevel, newLevel] = (deps.onTrustChange as ReturnType<typeof vi.fn>).mock.calls[0];
+ expect(oldLevel).toBe(DeviceTrustLevel.REGISTERED);
+ expect(newLevel).not.toBe(DeviceTrustLevel.REGISTERED);
+ });
+
+ it('should not call onTrustChange when trust level stays the same', async () => {
+ // Force low trust (unpaired, zero uptime, zero witness)
+ deps = makeDeps({
+ getStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ uptime_secs: 0,
+ epoch: 1,
+ total_vectors: 0,
+ dimension: 128,
+ paired: false,
+ roles: [],
+ }),
+ getPairStatus: vi.fn().mockResolvedValue({ paired: false }),
+ getWitnessChain: vi.fn().mockResolvedValue({
+ depth: 0,
+ epoch: 0,
+ head_hash: '',
+ }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ // Device starts at REGISTERED and trust stays low enough to remain REGISTERED
+ const device = makeDevice({ trustLevel: DeviceTrustLevel.REGISTERED });
+ await service.refreshDeviceState(device);
+
+ // Score: 0.3*0 + 0.15*1 + 0.2*0 + 0.15*0 + 0.1*1 + 0.1*0.5 = 0.3
+ // evaluateTrustLevel(0.3) => REGISTERED (0.3 < 0.5)
+ expect(deps.onTrustChange).not.toHaveBeenCalled();
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // computeTrustScore
+ // -----------------------------------------------------------------------
+
+ describe('computeTrustScore', () => {
+ it('should apply correct weighted formula', () => {
+ const device = makeDevice();
+
+ // paired=true => pairingIntegrity=1.0
+ // firmwareCurrency is always 1.0
+ // uptimeSecs=302_400 (half of 7 days) => uptimeStability=0.5
+ // witnessDepth=5000 (half of 10_000) => witnessIntegrity=0.5
+ // anomalyHistory=1.0 (fixed)
+ // meshParticipation=0.5 (fixed)
+ const score = service.computeTrustScore(device, 5000, 302_400, true);
+
+ const expected =
+ 0.3 * 1.0 + // pairing
+ 0.15 * 1.0 + // firmware
+ 0.2 * 0.5 + // uptime
+ 0.15 * 0.5 + // witness
+ 0.1 * 1.0 + // anomaly
+ 0.1 * 0.5; // mesh
+ expect(score.overall).toBeCloseTo(expected, 10);
+ });
+
+ it('should set pairingIntegrity to 0.0 when paired is false', () => {
+ const device = makeDevice();
+ const score = service.computeTrustScore(device, 0, 0, false);
+
+ expect(score.components.pairingIntegrity).toBe(0.0);
+ });
+
+ it('should set pairingIntegrity to 1.0 when paired is true', () => {
+ const device = makeDevice();
+ const score = service.computeTrustScore(device, 0, 0, true);
+
+ expect(score.components.pairingIntegrity).toBe(1.0);
+ });
+
+ it('should fall back to device.trustScore.components.pairingIntegrity when paired is undefined', () => {
+ const device = makeDevice({
+ trustScore: {
+ overall: 0.5,
+ components: {
+ pairingIntegrity: 0.75,
+ firmwareCurrency: 1.0,
+ uptimeStability: 0.5,
+ witnessIntegrity: 0.3,
+ anomalyHistory: 1.0,
+ meshParticipation: 0.5,
+ },
+ },
+ });
+
+ const score = service.computeTrustScore(device, 0, 0, undefined);
+
+ expect(score.components.pairingIntegrity).toBe(0.75);
+ });
+
+ it('should cap uptimeStability at 1.0 for very high uptime', () => {
+ const device = makeDevice();
+ // 2x seven days
+ const score = service.computeTrustScore(device, 0, 604_800 * 2, true);
+
+ expect(score.components.uptimeStability).toBe(1.0);
+ });
+
+ it('should cap witnessIntegrity at 1.0 for very deep chains', () => {
+ const device = makeDevice();
+ // 2x expected depth
+ const score = service.computeTrustScore(device, 20_000, 0, true);
+
+ expect(score.components.witnessIntegrity).toBe(1.0);
+ });
+
+ it('should produce an overall score of 0 when everything is at minimum', () => {
+ const device = makeDevice({
+ trustScore: {
+ overall: 0,
+ components: {
+ pairingIntegrity: 0,
+ firmwareCurrency: 1.0,
+ uptimeStability: 0,
+ witnessIntegrity: 0,
+ anomalyHistory: 1.0,
+ meshParticipation: 0.5,
+ },
+ },
+ });
+
+ const score = service.computeTrustScore(device, 0, 0, false);
+
+ // 0.3*0 + 0.15*1 + 0.2*0 + 0.15*0 + 0.1*1 + 0.1*0.5 = 0.3
+ expect(score.overall).toBeCloseTo(0.3, 10);
+ });
+
+ it('should return correct component fields', () => {
+ const device = makeDevice();
+ const score = service.computeTrustScore(device, 2500, 151_200, true);
+
+ expect(score.components).toEqual({
+ pairingIntegrity: 1.0,
+ firmwareCurrency: 1.0,
+ uptimeStability: 151_200 / 604_800,
+ witnessIntegrity: 2500 / 10_000,
+ anomalyHistory: 1.0,
+ meshParticipation: 0.5,
+ });
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // evaluateTrustLevel
+ // -----------------------------------------------------------------------
+
+ describe('evaluateTrustLevel', () => {
+ const makeScore = (overall: number): DeviceTrustScore => ({
+ overall,
+ components: {
+ pairingIntegrity: 0,
+ firmwareCurrency: 0,
+ uptimeStability: 0,
+ witnessIntegrity: 0,
+ anomalyHistory: 0,
+ meshParticipation: 0,
+ },
+ });
+
+ it('should return UNKNOWN for score < 0.3', () => {
+ expect(service.evaluateTrustLevel(makeScore(0.0))).toBe(
+ DeviceTrustLevel.UNKNOWN,
+ );
+ expect(service.evaluateTrustLevel(makeScore(0.29))).toBe(
+ DeviceTrustLevel.UNKNOWN,
+ );
+ });
+
+ it('should return REGISTERED for 0.3 <= score < 0.5', () => {
+ expect(service.evaluateTrustLevel(makeScore(0.3))).toBe(
+ DeviceTrustLevel.REGISTERED,
+ );
+ expect(service.evaluateTrustLevel(makeScore(0.49))).toBe(
+ DeviceTrustLevel.REGISTERED,
+ );
+ });
+
+ it('should return PROVISIONED for 0.5 <= score < 0.7', () => {
+ expect(service.evaluateTrustLevel(makeScore(0.5))).toBe(
+ DeviceTrustLevel.PROVISIONED,
+ );
+ expect(service.evaluateTrustLevel(makeScore(0.69))).toBe(
+ DeviceTrustLevel.PROVISIONED,
+ );
+ });
+
+ it('should return CERTIFIED for 0.7 <= score < 0.85', () => {
+ expect(service.evaluateTrustLevel(makeScore(0.7))).toBe(
+ DeviceTrustLevel.CERTIFIED,
+ );
+ expect(service.evaluateTrustLevel(makeScore(0.84))).toBe(
+ DeviceTrustLevel.CERTIFIED,
+ );
+ });
+
+ it('should return FLEET_TRUSTED for score >= 0.85', () => {
+ expect(service.evaluateTrustLevel(makeScore(0.85))).toBe(
+ DeviceTrustLevel.FLEET_TRUSTED,
+ );
+ expect(service.evaluateTrustLevel(makeScore(1.0))).toBe(
+ DeviceTrustLevel.FLEET_TRUSTED,
+ );
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // deriveCapabilities (tested indirectly via registerDevice)
+ // -----------------------------------------------------------------------
+
+ describe('deriveCapabilities (via registerDevice)', () => {
+ it('should map known roles to capabilities', async () => {
+ deps = makeDeps({
+ getStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ uptime_secs: 100,
+ epoch: 1,
+ total_vectors: 0,
+ dimension: 128,
+ paired: false,
+ roles: ['vector-store', 'ota', 'mesh', 'witness', 'sensor', 'compute', 'mcp'],
+ }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ const device = await service.registerDevice('http://x', 'f', 'z');
+
+ expect(device.capabilities).toEqual([
+ 'vector-store',
+ 'ota-update',
+ 'mesh-routing',
+ 'witness-chain',
+ 'sensor-telemetry',
+ 'edge-compute',
+ 'mcp-server',
+ ]);
+ });
+
+ it('should filter out unknown roles', async () => {
+ deps = makeDeps({
+ getStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ uptime_secs: 100,
+ epoch: 1,
+ total_vectors: 0,
+ dimension: 128,
+ paired: false,
+ roles: ['vector-store', 'nonexistent-role', 'mesh'],
+ }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ const device = await service.registerDevice('http://x', 'f', 'z');
+
+ expect(device.capabilities).toEqual(['vector-store', 'mesh-routing']);
+ });
+
+ it('should return empty capabilities for empty roles', async () => {
+ deps = makeDeps({
+ getStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ uptime_secs: 100,
+ epoch: 1,
+ total_vectors: 0,
+ dimension: 128,
+ paired: false,
+ roles: [],
+ }),
+ });
+ service = new DeviceLifecycleService(deps);
+
+ const device = await service.registerDevice('http://x', 'f', 'z');
+
+ expect(device.capabilities).toEqual([]);
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/firmware-orchestration-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/firmware-orchestration-service.test.ts
new file mode 100644
index 0000000000..1ad67df8fe
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/firmware-orchestration-service.test.ts
@@ -0,0 +1,390 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ FirmwareOrchestrationService,
+ type FirmwareOrchestrationDeps,
+ type FirmwareRollout,
+} from '../../src/domain/services/firmware-orchestration-service.js';
+import type { FirmwarePolicy } from '../../src/domain/entities/index.js';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function makePolicy(overrides: Partial<FirmwarePolicy> = {}): FirmwarePolicy {
+ return {
+ channel: 'stable',
+ autoUpdate: false,
+ approvalRequired: false,
+ canaryPercentage: 10,
+ canaryDurationMinutes: 30,
+ rollbackOnAnomalyThreshold: 0.5,
+ ...overrides,
+ };
+}
+
+function makeDeps(
+ overrides: Partial<FirmwareOrchestrationDeps> = {},
+): FirmwareOrchestrationDeps {
+ return {
+ getDeviceFirmwareVersion: vi.fn().mockResolvedValue('1.0.0'),
+ deployFirmware: vi.fn().mockResolvedValue({ success: true }),
+ getDeviceAnomalyScore: vi.fn().mockResolvedValue(0.1),
+ ...overrides,
+ };
+}
+
+function deviceIds(count: number): string[] {
+ return Array.from({ length: count }, (_, i) => `dev-${i + 1}`);
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('FirmwareOrchestrationService', () => {
+ let deps: FirmwareOrchestrationDeps;
+ let svc: FirmwareOrchestrationService;
+
+ beforeEach(() => {
+ deps = makeDeps();
+ svc = new FirmwareOrchestrationService(deps);
+ });
+
+ // ---- createRollout -------------------------------------------------------
+
+ describe('createRollout', () => {
+ it('creates a rollout in pending stage', () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(10),
+ makePolicy(),
+ );
+
+ expect(rollout.fleetId).toBe('fleet-1');
+ expect(rollout.firmwareVersion).toBe('2.0.0');
+ expect(rollout.stage).toBe('pending');
+ expect(rollout.strategy).toBe('canary');
+ expect(rollout.targetDeviceIds).toHaveLength(10);
+ expect(rollout.completedDeviceIds).toEqual([]);
+ expect(rollout.failedDeviceIds).toEqual([]);
+ expect(rollout.startedAt).toBeInstanceOf(Date);
+ expect(rollout.updatedAt).toBeInstanceOf(Date);
+ expect(rollout.completedAt).toBeUndefined();
+ });
+
+ it('selects correct canary devices (10% of 10 = 1)', () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(10),
+ makePolicy({ canaryPercentage: 10 }),
+ );
+
+ expect(rollout.canaryDeviceIds).toEqual(['dev-1']);
+ });
+
+ it('selects correct canary devices (20% of 10 = 2)', () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(10),
+ makePolicy({ canaryPercentage: 20 }),
+ );
+
+ expect(rollout.canaryDeviceIds).toEqual(['dev-1', 'dev-2']);
+ });
+
+ it('always selects at least 1 canary device', () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(100),
+ makePolicy({ canaryPercentage: 0 }),
+ );
+
+ expect(rollout.canaryDeviceIds).toHaveLength(1);
+ });
+
+ it('sets anomaly threshold from policy', () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(5),
+ makePolicy({ rollbackOnAnomalyThreshold: 0.8 }),
+ );
+
+ expect(rollout.anomalyThreshold).toBe(0.8);
+ });
+ });
+
+ // ---- advanceRollout: pending -> canary -----------------------------------
+
+ describe('advanceRollout: pending -> canary', () => {
+ it('deploys firmware to canary devices', async () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(10),
+ makePolicy({ canaryPercentage: 20 }),
+ );
+
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('canary');
+ expect(deps.deployFirmware).toHaveBeenCalledTimes(2);
+ expect(deps.deployFirmware).toHaveBeenCalledWith('dev-1', '2.0.0');
+ expect(deps.deployFirmware).toHaveBeenCalledWith('dev-2', '2.0.0');
+ expect(updated.completedDeviceIds).toEqual(['dev-1', 'dev-2']);
+ });
+
+ it('tracks failed canary deployments', async () => {
+ const deployFirmware = vi
+ .fn()
+ .mockResolvedValueOnce({ success: true })
+ .mockResolvedValueOnce({ success: false, error: 'timeout' });
+
+ deps = makeDeps({ deployFirmware });
+ svc = new FirmwareOrchestrationService(deps);
+
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(10),
+ makePolicy({ canaryPercentage: 20 }),
+ );
+
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('canary');
+ expect(updated.completedDeviceIds).toEqual(['dev-1']);
+ expect(updated.failedDeviceIds).toEqual(['dev-2']);
+ });
+ });
+
+ // ---- advanceRollout: canary -> rolling -----------------------------------
+
+ describe('advanceRollout: canary -> rolling', () => {
+ let rollout: FirmwareRollout;
+
+ beforeEach(async () => {
+ rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(10),
+ makePolicy({ canaryPercentage: 10 }),
+ );
+ await svc.advanceRollout(rollout.rolloutId); // pending -> canary
+ });
+
+ it('moves to rolling when anomaly scores are below threshold', async () => {
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('rolling');
+ expect(deps.getDeviceAnomalyScore).toHaveBeenCalledWith('dev-1');
+ });
+
+ it('rolls back when anomaly score exceeds threshold', async () => {
+ vi.mocked(deps.getDeviceAnomalyScore).mockResolvedValue(0.9);
+
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('rolled-back');
+ });
+
+ it('rolls back when anomaly score equals threshold', async () => {
+ // threshold is 0.5, score is 0.5 — should NOT roll back (> not >=)
+ vi.mocked(deps.getDeviceAnomalyScore).mockResolvedValue(0.5);
+
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('rolling');
+ });
+
+ it('rolls back when anomaly score just exceeds threshold', async () => {
+ vi.mocked(deps.getDeviceAnomalyScore).mockResolvedValue(0.51);
+
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('rolled-back');
+ });
+ });
+
+ // ---- advanceRollout: rolling -> complete ---------------------------------
+
+ describe('advanceRollout: rolling -> complete', () => {
+ let rollout: FirmwareRollout;
+
+ beforeEach(async () => {
+ rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(5),
+ makePolicy({ canaryPercentage: 20 }),
+ );
+ await svc.advanceRollout(rollout.rolloutId); // pending -> canary
+ await svc.advanceRollout(rollout.rolloutId); // canary -> rolling
+ });
+
+ it('deploys to remaining devices and completes', async () => {
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('complete');
+ expect(updated.completedAt).toBeInstanceOf(Date);
+ // Canary had 1 device (20% of 5 = 1), remaining = 4
+ expect(updated.completedDeviceIds).toContain('dev-2');
+ expect(updated.completedDeviceIds).toContain('dev-3');
+ expect(updated.completedDeviceIds).toContain('dev-4');
+ expect(updated.completedDeviceIds).toContain('dev-5');
+ });
+
+ it('does not redeploy to canary devices', async () => {
+ vi.mocked(deps.deployFirmware).mockClear();
+
+ await svc.advanceRollout(rollout.rolloutId);
+
+ const calledDevices = vi
+ .mocked(deps.deployFirmware)
+ .mock.calls.map((c) => c[0]);
+ expect(calledDevices).not.toContain('dev-1');
+ });
+
+ it('tracks failed deployments during rolling phase', async () => {
+ vi.mocked(deps.deployFirmware).mockClear();
+ vi.mocked(deps.deployFirmware)
+ .mockResolvedValueOnce({ success: true })
+ .mockResolvedValueOnce({ success: false, error: 'disk full' })
+ .mockResolvedValueOnce({ success: true })
+ .mockResolvedValueOnce({ success: true });
+
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('complete');
+ expect(updated.failedDeviceIds).toContain('dev-3');
+ });
+ });
+
+ // ---- advanceRollout: terminal stages -------------------------------------
+
+ describe('advanceRollout: terminal stages', () => {
+ it('is a no-op when already complete', async () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(3),
+ makePolicy({ canaryPercentage: 34 }),
+ );
+ await svc.advanceRollout(rollout.rolloutId); // pending -> canary
+ await svc.advanceRollout(rollout.rolloutId); // canary -> rolling
+ await svc.advanceRollout(rollout.rolloutId); // rolling -> complete
+
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('complete');
+ });
+
+ it('is a no-op when already rolled back', async () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(5),
+ makePolicy(),
+ );
+ svc.rollbackRollout(rollout.rolloutId);
+
+ const updated = await svc.advanceRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('rolled-back');
+ });
+ });
+
+ // ---- rollbackRollout -----------------------------------------------------
+
+ describe('rollbackRollout', () => {
+ it('sets stage to rolled-back from pending', () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(5),
+ makePolicy(),
+ );
+
+ const updated = svc.rollbackRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('rolled-back');
+ expect(updated.updatedAt).toBeInstanceOf(Date);
+ });
+
+ it('sets stage to rolled-back from canary', async () => {
+ const rollout = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(5),
+ makePolicy(),
+ );
+ await svc.advanceRollout(rollout.rolloutId); // pending -> canary
+
+ const updated = svc.rollbackRollout(rollout.rolloutId);
+
+ expect(updated.stage).toBe('rolled-back');
+ });
+
+ it('throws for unknown rollout', () => {
+ expect(() => svc.rollbackRollout('nope')).toThrow(
+ 'Rollout nope not found',
+ );
+ });
+ });
+
+ // ---- getRollout ----------------------------------------------------------
+
+ describe('getRollout', () => {
+ it('returns an existing rollout', () => {
+ const created = svc.createRollout(
+ 'fleet-1',
+ '2.0.0',
+ deviceIds(3),
+ makePolicy(),
+ );
+
+ const fetched = svc.getRollout(created.rolloutId);
+
+ expect(fetched.rolloutId).toBe(created.rolloutId);
+ expect(fetched.fleetId).toBe('fleet-1');
+ });
+
+ it('throws for unknown rollout', () => {
+ expect(() => svc.getRollout('does-not-exist')).toThrow(
+ 'Rollout does-not-exist not found',
+ );
+ });
+ });
+
+ // ---- listRollouts --------------------------------------------------------
+
+ describe('listRollouts', () => {
+ it('returns all rollouts when no fleetId filter', () => {
+ svc.createRollout('fleet-1', '2.0.0', deviceIds(3), makePolicy());
+ svc.createRollout('fleet-2', '2.0.0', deviceIds(3), makePolicy());
+
+ expect(svc.listRollouts()).toHaveLength(2);
+ });
+
+ it('filters by fleetId', () => {
+ svc.createRollout('fleet-1', '2.0.0', deviceIds(3), makePolicy());
+ svc.createRollout('fleet-2', '2.0.0', deviceIds(3), makePolicy());
+ svc.createRollout('fleet-1', '3.0.0', deviceIds(3), makePolicy());
+
+ const fleet1 = svc.listRollouts('fleet-1');
+
+ expect(fleet1).toHaveLength(2);
+ expect(fleet1.every((r) => r.fleetId === 'fleet-1')).toBe(true);
+ });
+
+ it('returns empty array when no rollouts match', () => {
+ svc.createRollout('fleet-1', '2.0.0', deviceIds(3), makePolicy());
+
+ expect(svc.listRollouts('fleet-999')).toEqual([]);
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/firmware-watch-worker.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/firmware-watch-worker.test.ts
new file mode 100644
index 0000000000..9a26d425cf
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/firmware-watch-worker.test.ts
@@ -0,0 +1,124 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { FirmwareWatchWorker } from '../../src/workers/firmware-watch-worker.js';
+import type { IoTCoordinator } from '../../src/application/iot-coordinator.js';
+
+function makeCoordinator(overrides: Partial<IoTCoordinator> = {}): IoTCoordinator {
+ return {
+ listDevices: vi.fn().mockReturnValue([
+ { deviceId: 'dev-001' },
+ ]),
+ getDeviceStatus: vi.fn().mockResolvedValue({ firmwareVersion: '1.0.0' }),
+ ...overrides,
+ } as unknown as IoTCoordinator;
+}
+
+describe('FirmwareWatchWorker', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('starts and stops cleanly', () => {
+ const worker = new FirmwareWatchWorker(makeCoordinator());
+ expect(worker.isRunning()).toBe(false);
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ expect(worker.isRunning()).toBe(false);
+ });
+
+ it('does not start twice', () => {
+ const worker = new FirmwareWatchWorker(makeCoordinator());
+ worker.start();
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ });
+
+ it('records initial firmware version without triggering mismatch', async () => {
+ const onVersionMismatch = vi.fn();
+ const coord = makeCoordinator();
+ const worker = new FirmwareWatchWorker(coord, {
+ intervalMs: 1000,
+ onVersionMismatch,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(coord.getDeviceStatus).toHaveBeenCalledWith('dev-001');
+ expect(onVersionMismatch).not.toHaveBeenCalled();
+ worker.stop();
+ });
+
+ it('detects firmware version change', async () => {
+ const onVersionMismatch = vi.fn();
+ let callCount = 0;
+ const coord = makeCoordinator({
+ getDeviceStatus: vi.fn().mockImplementation(async () => {
+ callCount++;
+ return { firmwareVersion: callCount === 1 ? '1.0.0' : '2.0.0' };
+ }),
+ });
+
+ const worker = new FirmwareWatchWorker(coord, {
+ intervalMs: 1000,
+ onVersionMismatch,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onVersionMismatch).toHaveBeenCalledWith('dev-001', '1.0.0', '2.0.0');
+ worker.stop();
+ });
+
+ it('calls onWatchError when status fetch fails', async () => {
+ const onWatchError = vi.fn();
+ const coord = makeCoordinator({
+ getDeviceStatus: vi.fn().mockRejectedValue(new Error('timeout')),
+ });
+ const worker = new FirmwareWatchWorker(coord, {
+ intervalMs: 1000,
+ onWatchError,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onWatchError).toHaveBeenCalledWith('dev-001', expect.any(Error));
+ worker.stop();
+ });
+
+ it('tracks multiple devices independently', async () => {
+ const onVersionMismatch = vi.fn();
+ let dev1Calls = 0;
+ let dev2Calls = 0;
+ const coord = makeCoordinator({
+ listDevices: vi.fn().mockReturnValue([
+ { deviceId: 'dev-001' },
+ { deviceId: 'dev-002' },
+ ]),
+ getDeviceStatus: vi.fn().mockImplementation(async (deviceId: string) => {
+ if (deviceId === 'dev-001') {
+ dev1Calls++;
+ return { firmwareVersion: '1.0.0' };
+ }
+ dev2Calls++;
+ return { firmwareVersion: dev2Calls === 1 ? '1.0.0' : '1.1.0' };
+ }),
+ });
+
+ const worker = new FirmwareWatchWorker(coord, {
+ intervalMs: 1000,
+ onVersionMismatch,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onVersionMismatch).toHaveBeenCalledTimes(1);
+ expect(onVersionMismatch).toHaveBeenCalledWith('dev-002', '1.0.0', '1.1.0');
+ worker.stop();
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/fleet-topology-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/fleet-topology-service.test.ts
new file mode 100644
index 0000000000..d9244a8729
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/fleet-topology-service.test.ts
@@ -0,0 +1,164 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { FleetTopologyService } from '../../src/domain/services/fleet-topology-service.js';
+import { InMemoryFleetRepository } from '../../src/infrastructure/in-memory-fleet-repository.js';
+
+describe('FleetTopologyService', () => {
+ let svc: FleetTopologyService;
+ let repo: InMemoryFleetRepository;
+
+ beforeEach(() => {
+ repo = new InMemoryFleetRepository();
+ svc = new FleetTopologyService(repo);
+ });
+
+ describe('createFleet', () => {
+ it('creates a fleet with defaults', async () => {
+ const fleet = await svc.createFleet({
+ fleetId: 'f1',
+ name: 'Warehouse Sensors',
+ zoneId: 'zone-1',
+ });
+
+ expect(fleet.fleetId).toBe('f1');
+ expect(fleet.name).toBe('Warehouse Sensors');
+ expect(fleet.zoneId).toBe('zone-1');
+ expect(fleet.deviceIds).toEqual([]);
+ expect(fleet.topology).toBe('star');
+ expect(fleet.firmwarePolicy.channel).toBe('stable');
+ expect(fleet.firmwarePolicy.autoUpdate).toBe(false);
+ expect(fleet.firmwarePolicy.canaryPercentage).toBe(10);
+ expect(fleet.telemetryPolicy.anomalyDetectionEnabled).toBe(true);
+ expect(fleet.healthThresholds.maxOfflineMinutes).toBe(10);
+ expect(fleet.createdAt).toBeInstanceOf(Date);
+ });
+
+ it('creates a fleet with custom policies', async () => {
+ const fleet = await svc.createFleet({
+ fleetId: 'f2',
+ name: 'Production',
+ zoneId: 'zone-2',
+ topology: 'mesh',
+ firmwarePolicy: { autoUpdate: true, canaryPercentage: 5 },
+ telemetryPolicy: { anomalyThreshold: 0.5 },
+ });
+
+ expect(fleet.topology).toBe('mesh');
+ expect(fleet.firmwarePolicy.autoUpdate).toBe(true);
+ expect(fleet.firmwarePolicy.canaryPercentage).toBe(5);
+ expect(fleet.firmwarePolicy.channel).toBe('stable');
+ expect(fleet.telemetryPolicy.anomalyThreshold).toBe(0.5);
+ expect(fleet.telemetryPolicy.retentionDays).toBe(30);
+ });
+
+ it('throws on duplicate fleet ID', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ await expect(
+ svc.createFleet({ fleetId: 'f1', name: 'B', zoneId: 'z2' }),
+ ).rejects.toThrow('Fleet f1 already exists');
+ });
+ });
+
+ describe('getFleet', () => {
+ it('returns an existing fleet', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ const fleet = await svc.getFleet('f1');
+ expect(fleet.fleetId).toBe('f1');
+ });
+
+ it('throws for non-existent fleet', async () => {
+ await expect(svc.getFleet('nope')).rejects.toThrow('Fleet nope not found');
+ });
+ });
+
+ describe('listFleets', () => {
+ it('returns summaries of all fleets', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ await svc.createFleet({ fleetId: 'f2', name: 'B', zoneId: 'z2', topology: 'mesh' });
+
+ const summaries = await svc.listFleets();
+ expect(summaries).toHaveLength(2);
+ expect(summaries[0].fleetId).toBe('f1');
+ expect(summaries[1].topology).toBe('mesh');
+ expect(summaries[0].deviceCount).toBe(0);
+ });
+ });
+
+ describe('addDeviceToFleet / removeDeviceFromFleet', () => {
+ it('adds a device to a fleet', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ const fleet = await svc.addDeviceToFleet('f1', 'dev-1');
+ expect(fleet.deviceIds).toEqual(['dev-1']);
+ });
+
+ it('is idempotent on duplicate add', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ await svc.addDeviceToFleet('f1', 'dev-1');
+ const fleet = await svc.addDeviceToFleet('f1', 'dev-1');
+ expect(fleet.deviceIds).toEqual(['dev-1']);
+ });
+
+ it('adds multiple devices', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ await svc.addDeviceToFleet('f1', 'dev-1');
+ await svc.addDeviceToFleet('f1', 'dev-2');
+ const fleet = await svc.addDeviceToFleet('f1', 'dev-3');
+ expect(fleet.deviceIds).toEqual(['dev-1', 'dev-2', 'dev-3']);
+ });
+
+ it('removes a device from a fleet', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ await svc.addDeviceToFleet('f1', 'dev-1');
+ await svc.addDeviceToFleet('f1', 'dev-2');
+ const fleet = await svc.removeDeviceFromFleet('f1', 'dev-1');
+ expect(fleet.deviceIds).toEqual(['dev-2']);
+ });
+
+ it('is safe to remove a non-member device', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ const fleet = await svc.removeDeviceFromFleet('f1', 'dev-nope');
+ expect(fleet.deviceIds).toEqual([]);
+ });
+ });
+
+ describe('updateTopology', () => {
+ it('changes the fleet topology', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ const fleet = await svc.updateTopology('f1', 'hierarchical');
+ expect(fleet.topology).toBe('hierarchical');
+ });
+ });
+
+ describe('updateFirmwarePolicy', () => {
+ it('merges partial policy updates', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ const fleet = await svc.updateFirmwarePolicy('f1', {
+ autoUpdate: true,
+ canaryPercentage: 25,
+ });
+ expect(fleet.firmwarePolicy.autoUpdate).toBe(true);
+ expect(fleet.firmwarePolicy.canaryPercentage).toBe(25);
+ expect(fleet.firmwarePolicy.channel).toBe('stable');
+ });
+ });
+
+ describe('deleteFleet', () => {
+ it('deletes an existing fleet', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ await svc.deleteFleet('f1');
+ await expect(svc.getFleet('f1')).rejects.toThrow();
+ });
+
+ it('throws for non-existent fleet', async () => {
+ await expect(svc.deleteFleet('nope')).rejects.toThrow('Fleet nope not found');
+ });
+ });
+
+ describe('getFleetDeviceCount', () => {
+ it('returns the correct count', async () => {
+ await svc.createFleet({ fleetId: 'f1', name: 'A', zoneId: 'z1' });
+ await svc.addDeviceToFleet('f1', 'dev-1');
+ await svc.addDeviceToFleet('f1', 'dev-2');
+ expect(await svc.getFleetDeviceCount('f1')).toBe(2);
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/health-probe-worker.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/health-probe-worker.test.ts
new file mode 100644
index 0000000000..dbbcf3c2ca
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/health-probe-worker.test.ts
@@ -0,0 +1,344 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { HealthProbeWorker } from '../../src/workers/health-probe-worker.js';
+import type { HealthProbeConfig } from '../../src/workers/health-probe-worker.js';
+import type { IoTCoordinator } from '../../src/application/iot-coordinator.js';
+import type { DeviceAgent } from '../../src/domain/entities/index.js';
+import { DeviceTrustLevel } from '../../src/domain/entities/index.js';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function makeDevice(deviceId: string): DeviceAgent {
+ return {
+ deviceId,
+ publicKey: 'key',
+ firmwareVersion: '1.0',
+ trustLevel: DeviceTrustLevel.REGISTERED,
+ trustScore: {
+ overall: 0.5,
+ components: {
+ pairingIntegrity: 0,
+ firmwareCurrency: 1,
+ uptimeStability: 0.5,
+ witnessIntegrity: 0.3,
+ anomalyHistory: 1,
+ meshParticipation: 0.5,
+ },
+ },
+ fleetId: 'fleet-1',
+ zoneId: 'zone-a',
+ status: 'online',
+ lastSeen: new Date(),
+ epoch: 1,
+ capabilities: [],
+ meshPeers: [],
+ vectorStoreStats: {
+ totalVectors: 0,
+ deletedVectors: 0,
+ dimension: 128,
+ fileSizeBytes: 0,
+ },
+ endpoint: 'http://169.254.42.1',
+ metadata: {},
+ };
+}
+
+function makeMockCoordinator(devices: DeviceAgent[]): IoTCoordinator {
+ return {
+ listDevices: vi.fn().mockReturnValue(devices),
+ getDeviceStatus: vi.fn().mockResolvedValue(devices[0] ?? makeDevice('x')),
+ } as unknown as IoTCoordinator;
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('HealthProbeWorker', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ // -----------------------------------------------------------------------
+ // start / stop / isRunning
+ // -----------------------------------------------------------------------
+
+ describe('start and stop', () => {
+ it('should start an interval timer', () => {
+ const coordinator = makeMockCoordinator([]);
+ const worker = new HealthProbeWorker(coordinator, { intervalMs: 5000 });
+
+ expect(worker.isRunning()).toBe(false);
+
+ worker.start();
+
+ expect(worker.isRunning()).toBe(true);
+
+ worker.stop();
+ });
+
+ it('should stop the timer and report not running', () => {
+ const coordinator = makeMockCoordinator([]);
+ const worker = new HealthProbeWorker(coordinator, { intervalMs: 5000 });
+
+ worker.start();
+ worker.stop();
+
+ expect(worker.isRunning()).toBe(false);
+ });
+
+ it('should be idempotent when called multiple times', () => {
+ const coordinator = makeMockCoordinator([]);
+ const worker = new HealthProbeWorker(coordinator, { intervalMs: 5000 });
+
+ worker.start();
+ worker.start(); // second start should be a no-op
+
+ expect(worker.isRunning()).toBe(true);
+
+ worker.stop();
+ worker.stop(); // second stop should be a no-op
+
+ expect(worker.isRunning()).toBe(false);
+ });
+
+ it('should invoke probe at the configured interval', async () => {
+ const devices = [makeDevice('dev-001')];
+ const coordinator = makeMockCoordinator(devices);
+ const worker = new HealthProbeWorker(coordinator, { intervalMs: 1000 });
+
+ worker.start();
+
+ // No call yet at t=0 (setInterval fires after the first interval)
+ expect(coordinator.getDeviceStatus).not.toHaveBeenCalled();
+
+ // Advance past one interval
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(coordinator.getDeviceStatus).toHaveBeenCalledTimes(1);
+
+ // Advance past another interval
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(coordinator.getDeviceStatus).toHaveBeenCalledTimes(2);
+
+ worker.stop();
+ });
+
+ it('should use default intervalMs of 30000 when not specified', () => {
+ const devices = [makeDevice('dev-001')];
+ const coordinator = makeMockCoordinator(devices);
+ const worker = new HealthProbeWorker(coordinator);
+
+ worker.start();
+
+ // At 29s, probe should NOT have fired
+ vi.advanceTimersByTime(29_000);
+ expect(coordinator.getDeviceStatus).not.toHaveBeenCalled();
+
+ worker.stop();
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // probe
+ // -----------------------------------------------------------------------
+
+ describe('probe', () => {
+ it('should call getDeviceStatus for each registered device', async () => {
+ const devices = [makeDevice('dev-001'), makeDevice('dev-002')];
+ const coordinator = makeMockCoordinator(devices);
+ const worker = new HealthProbeWorker(coordinator);
+
+ await worker.probe();
+
+ expect(coordinator.listDevices).toHaveBeenCalledTimes(1);
+ expect(coordinator.getDeviceStatus).toHaveBeenCalledTimes(2);
+ expect(coordinator.getDeviceStatus).toHaveBeenCalledWith('dev-001');
+ expect(coordinator.getDeviceStatus).toHaveBeenCalledWith('dev-002');
+ });
+
+ it('should not call getDeviceStatus when no devices are registered', async () => {
+ const coordinator = makeMockCoordinator([]);
+ const worker = new HealthProbeWorker(coordinator);
+
+ await worker.probe();
+
+ expect(coordinator.listDevices).toHaveBeenCalled();
+ expect(coordinator.getDeviceStatus).not.toHaveBeenCalled();
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // onDeviceOffline
+ // -----------------------------------------------------------------------
+
+ describe('onDeviceOffline', () => {
+ it('should emit onDeviceOffline when getDeviceStatus throws (previously online)', async () => {
+ const devices = [makeDevice('dev-001')];
+ const coordinator = makeMockCoordinator(devices);
+ (coordinator.getDeviceStatus as ReturnType<typeof vi.fn>).mockRejectedValue(
+ new Error('Connection refused'),
+ );
+
+ const onDeviceOffline = vi.fn();
+ const onProbeError = vi.fn();
+ const worker = new HealthProbeWorker(coordinator, {
+ intervalMs: 1000,
+ onDeviceOffline,
+ onProbeError,
+ });
+
+ // First probe — device was never seen before (prevStatus is undefined),
+ // so it should emit onDeviceOffline
+ await worker.probe();
+
+ expect(onDeviceOffline).toHaveBeenCalledTimes(1);
+ expect(onDeviceOffline).toHaveBeenCalledWith('dev-001');
+ expect(onProbeError).toHaveBeenCalledTimes(1);
+ });
+
+ it('should NOT emit onDeviceOffline again if device was already offline', async () => {
+ const devices = [makeDevice('dev-001')];
+ const coordinator = makeMockCoordinator(devices);
+ (coordinator.getDeviceStatus as ReturnType<typeof vi.fn>).mockRejectedValue(
+ new Error('Timeout'),
+ );
+
+ const onDeviceOffline = vi.fn();
+ const worker = new HealthProbeWorker(coordinator, {
+ intervalMs: 1000,
+ onDeviceOffline,
+ });
+
+ // First probe — transitions to offline
+ await worker.probe();
+ expect(onDeviceOffline).toHaveBeenCalledTimes(1);
+
+ // Second probe — already offline, should not emit again
+ await worker.probe();
+ expect(onDeviceOffline).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // onDeviceOnline
+ // -----------------------------------------------------------------------
+
+ describe('onDeviceOnline', () => {
+ it('should emit onDeviceOnline when device comes back after being offline', async () => {
+ const devices = [makeDevice('dev-001')];
+ const coordinator = makeMockCoordinator(devices);
+
+ const onDeviceOffline = vi.fn();
+ const onDeviceOnline = vi.fn();
+ const worker = new HealthProbeWorker(coordinator, {
+ intervalMs: 1000,
+ onDeviceOffline,
+ onDeviceOnline,
+ });
+
+ // First probe — device goes offline
+ (coordinator.getDeviceStatus as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('Timeout'),
+ );
+ await worker.probe();
+ expect(onDeviceOffline).toHaveBeenCalledTimes(1);
+
+ // Second probe — device comes back online
+ (coordinator.getDeviceStatus as ReturnType<typeof vi.fn>).mockResolvedValueOnce(
+ makeDevice('dev-001'),
+ );
+ await worker.probe();
+ expect(onDeviceOnline).toHaveBeenCalledTimes(1);
+ expect(onDeviceOnline).toHaveBeenCalledWith('dev-001');
+ });
+
+ it('should not emit onDeviceOnline on first successful probe (device was never offline)', async () => {
+ const devices = [makeDevice('dev-001')];
+ const coordinator = makeMockCoordinator(devices);
+
+ const onDeviceOnline = vi.fn();
+ const worker = new HealthProbeWorker(coordinator, {
+ intervalMs: 1000,
+ onDeviceOnline,
+ });
+
+ // First probe — device is online, prevStatus is undefined (not 'offline')
+ await worker.probe();
+
+ expect(onDeviceOnline).not.toHaveBeenCalled();
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // onProbeError
+ // -----------------------------------------------------------------------
+
+ describe('onProbeError', () => {
+ it('should call onProbeError with deviceId and error when getDeviceStatus throws', async () => {
+ const devices = [makeDevice('dev-001')];
+ const coordinator = makeMockCoordinator(devices);
+ const error = new Error('Network error');
+ (coordinator.getDeviceStatus as ReturnType<typeof vi.fn>).mockRejectedValue(error);
+
+ const onProbeError = vi.fn();
+ const worker = new HealthProbeWorker(coordinator, {
+ intervalMs: 1000,
+ onProbeError,
+ });
+
+ await worker.probe();
+
+ expect(onProbeError).toHaveBeenCalledWith('dev-001', error);
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // Multi-device scenarios
+ // -----------------------------------------------------------------------
+
+ describe('multi-device scenarios', () => {
+ it('should track status independently per device', async () => {
+ const devices = [makeDevice('dev-001'), makeDevice('dev-002')];
+ const coordinator = makeMockCoordinator(devices);
+
+ // dev-001 is online, dev-002 fails
+ (coordinator.getDeviceStatus as ReturnType<typeof vi.fn>)
+ .mockResolvedValueOnce(makeDevice('dev-001'))
+ .mockRejectedValueOnce(new Error('Offline'));
+
+ const onDeviceOffline = vi.fn();
+ const onDeviceOnline = vi.fn();
+ const worker = new HealthProbeWorker(coordinator, {
+ intervalMs: 1000,
+ onDeviceOffline,
+ onDeviceOnline,
+ });
+
+ await worker.probe();
+
+ // Only dev-002 should be offline
+ expect(onDeviceOffline).toHaveBeenCalledTimes(1);
+ expect(onDeviceOffline).toHaveBeenCalledWith('dev-002');
+ expect(onDeviceOnline).not.toHaveBeenCalled();
+
+ // Second probe: dev-002 comes back, dev-001 goes offline
+ (coordinator.getDeviceStatus as ReturnType<typeof vi.fn>)
+ .mockRejectedValueOnce(new Error('Offline'))
+ .mockResolvedValueOnce(makeDevice('dev-002'));
+
+ await worker.probe();
+
+ expect(onDeviceOffline).toHaveBeenCalledTimes(2);
+ expect(onDeviceOffline).toHaveBeenCalledWith('dev-001');
+ expect(onDeviceOnline).toHaveBeenCalledTimes(1);
+ expect(onDeviceOnline).toHaveBeenCalledWith('dev-002');
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/mesh-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/mesh-service.test.ts
new file mode 100644
index 0000000000..9ad76ef903
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/mesh-service.test.ts
@@ -0,0 +1,258 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { MeshService } from '../../src/domain/services/mesh-service.js';
+import type { MeshServiceDeps } from '../../src/domain/services/mesh-service.js';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function makeDeps(
+ overrides: Partial<MeshServiceDeps> = {},
+): MeshServiceDeps {
+ return {
+ getMeshStatus: vi.fn().mockResolvedValue({
+ ap_active: true,
+ auto_mesh: true,
+ peer_count: 2,
+ peers: [
+ { device_id: 'peer-1', address: '10.0.0.1' },
+ { device_id: 'peer-2' },
+ ],
+ }),
+ getPeers: vi.fn().mockResolvedValue({
+ count: 2,
+ peers: [
+ { device_id: 'peer-2', address: '10.0.0.2' },
+ { device_id: 'peer-3', address: '10.0.0.3' },
+ ],
+ }),
+ getSwarmStatus: vi.fn().mockResolvedValue({
+ device_id: 'dev-001',
+ epoch: 42,
+ peer_count: 3,
+ total_vectors: 5000,
+ uptime_secs: 86_400,
+ }),
+ getClusterHealth: vi.fn().mockResolvedValue({
+ cluster_enabled: true,
+ peer_count: 3,
+ auto_sync_interval_secs: 60,
+ }),
+ ...overrides,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('MeshService', () => {
+ let deps: MeshServiceDeps;
+ let service: MeshService;
+
+ beforeEach(() => {
+ deps = makeDeps();
+ service = new MeshService(deps);
+ });
+
+ // -----------------------------------------------------------------------
+ // getTopology
+ // -----------------------------------------------------------------------
+
+ describe('getTopology', () => {
+ it('should parallel-fetch all 4 deps and return a MeshTopology', async () => {
+ const topo = await service.getTopology('dev-001');
+
+ expect(deps.getMeshStatus).toHaveBeenCalledWith('dev-001');
+ expect(deps.getPeers).toHaveBeenCalledWith('dev-001');
+ expect(deps.getSwarmStatus).toHaveBeenCalledWith('dev-001');
+ expect(deps.getClusterHealth).toHaveBeenCalledWith('dev-001');
+
+ expect(topo.deviceId).toBe('dev-001');
+ expect(topo.apActive).toBe(true);
+ expect(topo.autoMesh).toBe(true);
+ expect(topo.clusterEnabled).toBe(true);
+ expect(topo.autoSyncIntervalSecs).toBe(60);
+ expect(topo.swarmEpoch).toBe(42);
+ expect(topo.swarmTotalVectors).toBe(5000);
+ expect(topo.swarmUptimeSecs).toBe(86_400);
+ });
+
+ it('should merge peers from mesh and getPeers, deduplicating by device_id', async () => {
+ const topo = await service.getTopology('dev-001');
+
+ // peer-1 from mesh only, peer-2 from both (getPeers has address), peer-3 from getPeers
+ expect(topo.peers).toHaveLength(3);
+ const ids = topo.peers.map((p) => p.deviceId).sort();
+ expect(ids).toEqual(['peer-1', 'peer-2', 'peer-3']);
+ });
+
+ it('should set peerCount to the number of merged peers', async () => {
+ const topo = await service.getTopology('dev-001');
+
+ expect(topo.peerCount).toBe(topo.peers.length);
+ });
+
+ it('should default boolean fields to false when undefined', async () => {
+ deps = makeDeps({
+ getMeshStatus: vi.fn().mockResolvedValue({}),
+ getClusterHealth: vi.fn().mockResolvedValue({}),
+ });
+ service = new MeshService(deps);
+
+ const topo = await service.getTopology('dev-001');
+
+ expect(topo.apActive).toBe(false);
+ expect(topo.autoMesh).toBe(false);
+ expect(topo.clusterEnabled).toBe(false);
+ expect(topo.autoSyncIntervalSecs).toBe(0);
+ });
+
+ it('should handle empty peer arrays', async () => {
+ deps = makeDeps({
+ getMeshStatus: vi.fn().mockResolvedValue({ peers: [] }),
+ getPeers: vi.fn().mockResolvedValue({ peers: [] }),
+ });
+ service = new MeshService(deps);
+
+ const topo = await service.getTopology('dev-001');
+
+ expect(topo.peers).toEqual([]);
+ expect(topo.peerCount).toBe(0);
+ });
+
+ it('should handle undefined peers arrays', async () => {
+ deps = makeDeps({
+ getMeshStatus: vi.fn().mockResolvedValue({ ap_active: false }),
+ getPeers: vi.fn().mockResolvedValue({ count: 0 }),
+ });
+ service = new MeshService(deps);
+
+ const topo = await service.getTopology('dev-001');
+
+ expect(topo.peers).toEqual([]);
+ expect(topo.peerCount).toBe(0);
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // discoverPeers
+ // -----------------------------------------------------------------------
+
+ describe('discoverPeers', () => {
+ it('should return deduplicated peer device IDs', async () => {
+ const peerIds = await service.discoverPeers('dev-001');
+
+ const sorted = [...peerIds].sort();
+ expect(sorted).toEqual(['peer-1', 'peer-2', 'peer-3']);
+ });
+
+ it('should return empty array when no peers', async () => {
+ deps = makeDeps({
+ getMeshStatus: vi.fn().mockResolvedValue({ peers: [] }),
+ getPeers: vi.fn().mockResolvedValue({ peers: [] }),
+ });
+ service = new MeshService(deps);
+
+ const peerIds = await service.discoverPeers('dev-001');
+
+ expect(peerIds).toEqual([]);
+ });
+
+ it('should only call getMeshStatus and getPeers (not swarm/cluster)', async () => {
+ await service.discoverPeers('dev-001');
+
+ expect(deps.getMeshStatus).toHaveBeenCalledWith('dev-001');
+ expect(deps.getPeers).toHaveBeenCalledWith('dev-001');
+ expect(deps.getSwarmStatus).not.toHaveBeenCalled();
+ expect(deps.getClusterHealth).not.toHaveBeenCalled();
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // Peer merging logic
+ // -----------------------------------------------------------------------
+
+ describe('peer merging', () => {
+ it('should deduplicate by device_id', async () => {
+ deps = makeDeps({
+ getMeshStatus: vi.fn().mockResolvedValue({
+ peers: [
+ { device_id: 'same-id', address: '10.0.0.1' },
+ ],
+ }),
+ getPeers: vi.fn().mockResolvedValue({
+ peers: [
+ { device_id: 'same-id', address: '10.0.0.2' },
+ ],
+ }),
+ });
+ service = new MeshService(deps);
+
+ const topo = await service.getTopology('dev-001');
+
+ expect(topo.peers).toHaveLength(1);
+ expect(topo.peers[0].deviceId).toBe('same-id');
+ });
+
+ it('should prefer entries with address over entries without', async () => {
+ deps = makeDeps({
+ getMeshStatus: vi.fn().mockResolvedValue({
+ peers: [
+ { device_id: 'peer-x' }, // no address
+ ],
+ }),
+ getPeers: vi.fn().mockResolvedValue({
+ peers: [
+ { device_id: 'peer-x', address: '10.0.0.5' }, // has address
+ ],
+ }),
+ });
+ service = new MeshService(deps);
+
+ const topo = await service.getTopology('dev-001');
+
+ expect(topo.peers).toHaveLength(1);
+ expect(topo.peers[0].address).toBe('10.0.0.5');
+ });
+
+ it('should not replace an entry that already has an address', async () => {
+ deps = makeDeps({
+ getMeshStatus: vi.fn().mockResolvedValue({
+ peers: [
+ { device_id: 'peer-x', address: '10.0.0.1' }, // has address
+ ],
+ }),
+ getPeers: vi.fn().mockResolvedValue({
+ peers: [
+ { device_id: 'peer-x' }, // no address — should not overwrite
+ ],
+ }),
+ });
+ service = new MeshService(deps);
+
+ const topo = await service.getTopology('dev-001');
+
+ expect(topo.peers).toHaveLength(1);
+ expect(topo.peers[0].address).toBe('10.0.0.1');
+ });
+
+ it('should skip peers without a device_id', async () => {
+ deps = makeDeps({
+ getMeshStatus: vi.fn().mockResolvedValue({
+ peers: [
+ { address: '10.0.0.1' }, // no device_id
+ { device_id: 'valid-peer', address: '10.0.0.2' },
+ ],
+ }),
+ getPeers: vi.fn().mockResolvedValue({ peers: [] }),
+ });
+ service = new MeshService(deps);
+
+ const topo = await service.getTopology('dev-001');
+
+ expect(topo.peers).toHaveLength(1);
+ expect(topo.peers[0].deviceId).toBe('valid-peer');
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/mesh-sync-worker.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/mesh-sync-worker.test.ts
new file mode 100644
index 0000000000..f01b71f177
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/mesh-sync-worker.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { MeshSyncWorker } from '../../src/workers/mesh-sync-worker.js';
+import type { IoTCoordinator } from '../../src/application/iot-coordinator.js';
+
+function makeCoordinator(overrides: Partial<IoTCoordinator> = {}): IoTCoordinator {
+ return {
+ listDevices: vi.fn().mockReturnValue([
+ { deviceId: 'dev-001' },
+ { deviceId: 'dev-002' },
+ ]),
+ getDeviceMeshTopology: vi.fn().mockResolvedValue({ peerCount: 3 }),
+ ...overrides,
+ } as unknown as IoTCoordinator;
+}
+
+describe('MeshSyncWorker', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('starts and stops cleanly', () => {
+ const worker = new MeshSyncWorker(makeCoordinator());
+ expect(worker.isRunning()).toBe(false);
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ expect(worker.isRunning()).toBe(false);
+ });
+
+ it('does not start twice', () => {
+ const worker = new MeshSyncWorker(makeCoordinator());
+ worker.start();
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ });
+
+ it('calls sync on interval', async () => {
+ const coord = makeCoordinator();
+ const worker = new MeshSyncWorker(coord, { intervalMs: 1000 });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(coord.listDevices).toHaveBeenCalled();
+ expect(coord.getDeviceMeshTopology).toHaveBeenCalledWith('dev-001');
+ expect(coord.getDeviceMeshTopology).toHaveBeenCalledWith('dev-002');
+ worker.stop();
+ });
+
+ it('detects mesh partition when peer count drops to 0', async () => {
+ const onMeshPartition = vi.fn();
+ let callCount = 0;
+ const coord = makeCoordinator({
+ listDevices: vi.fn().mockReturnValue([{ deviceId: 'dev-001' }]),
+ getDeviceMeshTopology: vi.fn().mockImplementation(async () => {
+ callCount++;
+ if (callCount <= 1) return { peerCount: 3 };
+ return { peerCount: 0 };
+ }),
+ });
+
+ const worker = new MeshSyncWorker(coord, {
+ intervalMs: 1000,
+ onMeshPartition,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onMeshPartition).toHaveBeenCalledWith('dev-001', 0);
+ worker.stop();
+ });
+
+ it('calls onSyncComplete for each device', async () => {
+ const onSyncComplete = vi.fn();
+ const coord = makeCoordinator();
+ const worker = new MeshSyncWorker(coord, {
+ intervalMs: 1000,
+ onSyncComplete,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onSyncComplete).toHaveBeenCalledWith('dev-001', 3);
+ expect(onSyncComplete).toHaveBeenCalledWith('dev-002', 3);
+ worker.stop();
+ });
+
+ it('calls onSyncError when topology fetch fails', async () => {
+ const onSyncError = vi.fn();
+ const coord = makeCoordinator({
+ getDeviceMeshTopology: vi.fn().mockRejectedValue(new Error('net fail')),
+ });
+ const worker = new MeshSyncWorker(coord, {
+ intervalMs: 1000,
+ onSyncError,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onSyncError).toHaveBeenCalledWith('dev-001', expect.any(Error));
+ worker.stop();
+ });
+
+ it('uses default interval of 120s', () => {
+ const coord = makeCoordinator();
+ const worker = new MeshSyncWorker(coord);
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/sona-integration-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/sona-integration-service.test.ts
new file mode 100644
index 0000000000..5c93bd2b88
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/sona-integration-service.test.ts
@@ -0,0 +1,177 @@
+import { describe, it, expect, vi } from 'vitest';
+import { SONAIntegrationService } from '../../src/domain/services/sona-integration-service.js';
+import type { SONAClient } from '../../src/domain/services/sona-integration-service.js';
+import type { AnomalyDetection, TelemetryReading } from '../../src/domain/entities/telemetry.js';
+import type { TelemetryBaseline } from '../../src/domain/services/anomaly-detection-service.js';
+
+function makeSONAClient(overrides: Partial<SONAClient> = {}): SONAClient {
+ return {
+ storePattern: vi.fn().mockResolvedValue(undefined),
+ searchPatterns: vi.fn().mockResolvedValue([]),
+ trainTrajectory: vi.fn().mockResolvedValue(undefined),
+ predict: vi.fn().mockResolvedValue({ prediction: 'normal', confidence: 0.8 }),
+ ...overrides,
+ };
+}
+
+function makeAnomaly(overrides: Partial<AnomalyDetection> = {}): AnomalyDetection {
+ return {
+ readingId: 'r-001', deviceId: 'dev-001', score: 0.85,
+ type: 'spike', confidence: 0.9, suggestedAction: 'alert', metadata: {},
+ ...overrides,
+ };
+}
+
+function makeBaseline(): TelemetryBaseline {
+ return {
+ deviceId: 'dev-001',
+ meanVector: [10, 20, 30],
+ stdVector: [1, 2, 3],
+ sampleCount: 50,
+ computedAt: new Date(),
+ };
+}
+
+function makeReading(overrides: Partial<TelemetryReading> = {}): TelemetryReading {
+ return {
+ readingId: 'r-001', deviceId: 'dev-001', fleetId: 'fleet-1',
+ timestamp: new Date(), vector: [10, 20, 30],
+ rawMetrics: { temp: 25 }, anomalyScore: 0, metadata: {},
+ ...overrides,
+ };
+}
+
+describe('SONAIntegrationService', () => {
+ it('reports enabled when client provided', () => {
+ const svc = new SONAIntegrationService(makeSONAClient());
+ expect(svc.isEnabled).toBe(true);
+ });
+
+ it('reports disabled when client is null', () => {
+ const svc = new SONAIntegrationService(null);
+ expect(svc.isEnabled).toBe(false);
+ });
+
+ it('reports disabled when config.enabled is false', () => {
+ const svc = new SONAIntegrationService(makeSONAClient(), { enabled: false });
+ expect(svc.isEnabled).toBe(false);
+ });
+
+ it('learns anomaly pattern', async () => {
+ const client = makeSONAClient();
+ const svc = new SONAIntegrationService(client);
+ const anomaly = makeAnomaly();
+ const baseline = makeBaseline();
+
+ await svc.learnAnomalyPattern(anomaly, baseline);
+
+ expect(client.storePattern).toHaveBeenCalledWith(
+ 'anomaly:spike:dev-001',
+ expect.objectContaining({ type: 'spike', score: 0.85, baselineSamples: 50 }),
+ );
+ });
+
+ it('skips learning when disabled', async () => {
+ const client = makeSONAClient();
+ const svc = new SONAIntegrationService(client, { enabled: false });
+
+ await svc.learnAnomalyPattern(makeAnomaly(), makeBaseline());
+
+ expect(client.storePattern).not.toHaveBeenCalled();
+ });
+
+ it('learns baseline shift with drift vector', async () => {
+ const client = makeSONAClient();
+ const svc = new SONAIntegrationService(client);
+ const oldBaseline = makeBaseline();
+ const newBaseline: TelemetryBaseline = {
+ ...makeBaseline(),
+ meanVector: [12, 22, 28],
+ sampleCount: 75,
+ };
+
+ await svc.learnBaselineShift('dev-001', oldBaseline, newBaseline);
+
+ expect(client.storePattern).toHaveBeenCalledWith(
+ 'baseline-shift:dev-001',
+ expect.objectContaining({
+ driftVector: [2, 2, 2],
+ maxDrift: 2,
+ oldSamples: 50,
+ newSamples: 75,
+ }),
+ );
+ });
+
+ it('records telemetry trajectory', async () => {
+ const client = makeSONAClient();
+ const svc = new SONAIntegrationService(client);
+ const readings = [makeReading({ readingId: 'r-001' }), makeReading({ readingId: 'r-002' })];
+ const anomalies = [makeAnomaly({ readingId: 'r-001' })];
+
+ await svc.recordTelemetryTrajectory('dev-001', readings, anomalies);
+
+ expect(client.trainTrajectory).toHaveBeenCalledWith(
+ expect.stringContaining('iot-trajectories:dev-001:'),
+ expect.arrayContaining([
+ expect.objectContaining({ action: 'anomaly:spike', reward: -0.85 }),
+ expect.objectContaining({ action: 'normal', reward: 1.0 }),
+ ]),
+ );
+ });
+
+ it('predicts anomaly risk when confidence meets threshold', async () => {
+ const client = makeSONAClient({
+ predict: vi.fn().mockResolvedValue({ prediction: 'spike', confidence: 0.85 }),
+ });
+ const svc = new SONAIntegrationService(client);
+
+ const result = await svc.predictAnomalyRisk(makeReading());
+
+ expect(result).toEqual({ risk: 'spike', confidence: 0.85 });
+ });
+
+ it('returns null when prediction confidence below threshold', async () => {
+ const client = makeSONAClient({
+ predict: vi.fn().mockResolvedValue({ prediction: 'spike', confidence: 0.3 }),
+ });
+ const svc = new SONAIntegrationService(client);
+
+ const result = await svc.predictAnomalyRisk(makeReading());
+
+ expect(result).toBeNull();
+ });
+
+ it('returns null for prediction when disabled', async () => {
+ const svc = new SONAIntegrationService(null);
+
+ const result = await svc.predictAnomalyRisk(makeReading());
+
+ expect(result).toBeNull();
+ });
+
+ it('finds similar anomaly patterns', async () => {
+ const client = makeSONAClient({
+ searchPatterns: vi.fn().mockResolvedValue([
+ { key: 'anomaly:spike:dev-002', pattern: { type: 'spike' }, score: 0.9 },
+ ]),
+ });
+ const svc = new SONAIntegrationService(client);
+
+ const results = await svc.findSimilarAnomalyPatterns(makeAnomaly());
+
+ expect(results).toHaveLength(1);
+ expect(client.searchPatterns).toHaveBeenCalledWith(
+ expect.stringContaining('anomaly:spike'),
+ 5,
+ );
+ });
+
+ it('returns empty for similar patterns when disabled', async () => {
+ const svc = new SONAIntegrationService(null);
+
+ const results = await svc.findSimilarAnomalyPatterns(makeAnomaly());
+
+ expect(results).toHaveLength(0);
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-ingest-worker.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-ingest-worker.test.ts
new file mode 100644
index 0000000000..34f78afac2
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-ingest-worker.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { TelemetryIngestWorker } from '../../src/workers/telemetry-ingest-worker.js';
+import type { IoTCoordinator } from '../../src/application/iot-coordinator.js';
+
+function createMockCoordinator(
+ devices: Array<{ deviceId: string }> = [],
+ storeStatus = { totalVectors: 42, deletedVectors: 0, dimension: 128, fileSizeBytes: 1024, liveRatio: 1, epoch: 1 },
+) {
+ return {
+ listDevices: vi.fn().mockReturnValue(devices),
+ getDeviceStoreStatus: vi.fn().mockResolvedValue(storeStatus),
+ } as unknown as IoTCoordinator;
+}
+
+describe('TelemetryIngestWorker', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('starts and stops the timer', () => {
+ const worker = new TelemetryIngestWorker(createMockCoordinator());
+ expect(worker.isRunning()).toBe(false);
+
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+
+ worker.stop();
+ expect(worker.isRunning()).toBe(false);
+ });
+
+ it('does not double-start', () => {
+ const worker = new TelemetryIngestWorker(createMockCoordinator());
+ worker.start();
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ });
+
+ it('calls onIngestionComplete for each device', async () => {
+ const onIngestionComplete = vi.fn();
+ const coordinator = createMockCoordinator([
+ { deviceId: 'd1' },
+ { deviceId: 'd2' },
+ ]);
+
+ const worker = new TelemetryIngestWorker(coordinator, {
+ intervalMs: 1000,
+ onIngestionComplete,
+ });
+
+ await worker.ingest();
+
+ expect(coordinator.getDeviceStoreStatus).toHaveBeenCalledTimes(2);
+ expect(onIngestionComplete).toHaveBeenCalledTimes(2);
+ });
+
+ it('calls onIngestionError when getDeviceStoreStatus throws', async () => {
+ const onIngestionError = vi.fn();
+ const coordinator = createMockCoordinator([{ deviceId: 'd1' }]);
+ vi.mocked(coordinator.getDeviceStoreStatus).mockRejectedValueOnce(new Error('offline'));
+
+ const worker = new TelemetryIngestWorker(coordinator, {
+ intervalMs: 1000,
+ onIngestionError,
+ });
+
+ await worker.ingest();
+
+ expect(onIngestionError).toHaveBeenCalledWith('d1', expect.any(Error));
+ });
+
+ it('handles empty device list', async () => {
+ const onIngestionComplete = vi.fn();
+ const coordinator = createMockCoordinator([]);
+
+ const worker = new TelemetryIngestWorker(coordinator, { onIngestionComplete });
+ await worker.ingest();
+
+ expect(onIngestionComplete).not.toHaveBeenCalled();
+ });
+
+ it('defaults to 60-second interval', () => {
+ const worker = new TelemetryIngestWorker(createMockCoordinator());
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-ingestion-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-ingestion-service.test.ts
new file mode 100644
index 0000000000..db7e017f69
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-ingestion-service.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi } from 'vitest';
+import { AnomalyDetectionService } from '../../src/domain/services/anomaly-detection-service.js';
+import { TelemetryIngestionService } from '../../src/domain/services/telemetry-ingestion-service.js';
+import type { TelemetryReading } from '../../src/domain/entities/index.js';
+
+function makeReading(
+ deviceId: string,
+ vector: number[],
+ overrides: Partial<TelemetryReading> = {},
+): TelemetryReading {
+ return {
+ readingId: overrides.readingId ?? `r-${Math.random().toString(36).slice(2, 8)}`,
+ deviceId,
+ fleetId: 'fleet-1',
+ timestamp: new Date(),
+ vector,
+ rawMetrics: {},
+ anomalyScore: 0,
+ metadata: {},
+ ...overrides,
+ };
+}
+
+function createService(anomalyConfig?: Parameters<typeof AnomalyDetectionService.prototype.constructor>[0]) {
+ const deps = {
+ queryDeviceStore: vi.fn().mockResolvedValue([]),
+ getStoreStatus: vi.fn().mockResolvedValue({ total_vectors: 100, dimension: 3 }),
+ };
+ const detector = new AnomalyDetectionService(anomalyConfig);
+ const svc = new TelemetryIngestionService(deps, detector);
+ return { svc, detector, deps };
+}
+
+describe('TelemetryIngestionService', () => {
+ describe('processBatch', () => {
+ it('returns zero anomalies when no baseline exists', () => {
+ const { svc } = createService();
+ const readings = [makeReading('d1', [1, 2, 3])];
+ const result = svc.processBatch('d1', readings);
+
+ expect(result.deviceId).toBe('d1');
+ expect(result.readingsProcessed).toBe(1);
+ expect(result.anomaliesDetected).toBe(0);
+ expect(result.anomalies).toHaveLength(0);
+ });
+
+ it('detects anomalies after baseline is set', () => {
+ const { svc, detector } = createService({ anomalyThreshold: 0.3 });
+ const baselineReadings = Array.from({ length: 20 }, () => makeReading('d1', [10, 20, 30]));
+ baselineReadings[0] = makeReading('d1', [11, 21, 31]);
+ baselineReadings[1] = makeReading('d1', [9, 19, 29]);
+ detector.computeBaseline('d1', baselineReadings);
+
+ const anomalousReadings = [
+ makeReading('d1', [10, 20, 30]),
+ makeReading('d1', [100, 200, 300]),
+ ];
+ const result = svc.processBatch('d1', anomalousReadings);
+
+ expect(result.readingsProcessed).toBe(2);
+ expect(result.anomaliesDetected).toBeGreaterThan(0);
+ expect(result.anomalies.length).toBeGreaterThan(0);
+ expect(result.baseline).toBeDefined();
+ });
+
+ it('processes empty batch without error', () => {
+ const { svc } = createService();
+ const result = svc.processBatch('d1', []);
+
+ expect(result.readingsProcessed).toBe(0);
+ expect(result.anomaliesDetected).toBe(0);
+ });
+ });
+
+ describe('refreshBaseline', () => {
+ it('delegates to anomaly detector', () => {
+ const { svc } = createService();
+ const readings = [
+ makeReading('d1', [1, 2]),
+ makeReading('d1', [3, 4]),
+ ];
+ const baseline = svc.refreshBaseline('d1', readings);
+
+ expect(baseline.deviceId).toBe('d1');
+ expect(baseline.sampleCount).toBe(2);
+ expect(baseline.meanVector).toHaveLength(2);
+ });
+ });
+
+ describe('getBaseline', () => {
+ it('returns undefined before computation', () => {
+ const { svc } = createService();
+ expect(svc.getBaseline('d1')).toBeUndefined();
+ });
+
+ it('returns baseline after refresh', () => {
+ const { svc } = createService();
+ svc.refreshBaseline('d1', [makeReading('d1', [5, 10])]);
+ const baseline = svc.getBaseline('d1');
+
+ expect(baseline).toBeDefined();
+ expect(baseline!.deviceId).toBe('d1');
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-service.test.ts
new file mode 100644
index 0000000000..dec6dc948b
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/telemetry-service.test.ts
@@ -0,0 +1,264 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { TelemetryService } from '../../src/domain/services/telemetry-service.js';
+import type { TelemetryServiceDeps } from '../../src/domain/services/telemetry-service.js';
+import type { TelemetryReading } from '../../src/domain/entities/index.js';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function makeDeps(
+ overrides: Partial<TelemetryServiceDeps> = {},
+): TelemetryServiceDeps {
+ return {
+ queryVectors: vi.fn().mockResolvedValue({
+ results: [
+ { id: 1, distance: 0.12, metadata: { label: 'temp' } },
+ { id: 2, distance: 0.34 },
+ ],
+ query_ms: 5,
+ }),
+ ingestVectors: vi.fn().mockResolvedValue({
+ ingested: 3,
+ epoch: 42,
+ }),
+ getStoreStatus: vi.fn().mockResolvedValue({
+ total_vectors: 1000,
+ deleted_vectors: 50,
+ dimension: 384,
+ file_size_bytes: 2_048_000,
+ epoch: 42,
+ }),
+ ...overrides,
+ };
+}
+
+function makeReading(
+ overrides: Partial<TelemetryReading> = {},
+): TelemetryReading {
+ return {
+ readingId: 'r-001',
+ deviceId: 'dev-001',
+ fleetId: 'fleet-1',
+ timestamp: new Date('2026-01-15T12:00:00Z'),
+ vector: [0.1, 0.2, 0.3],
+ rawMetrics: { temperature: 22.5 },
+ anomalyScore: 0.05,
+ metadata: { source: 'sensor-a' },
+ ...overrides,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('TelemetryService', () => {
+ let deps: TelemetryServiceDeps;
+ let service: TelemetryService;
+
+ beforeEach(() => {
+ deps = makeDeps();
+ service = new TelemetryService(deps);
+ });
+
+ // -----------------------------------------------------------------------
+ // queryDevice
+ // -----------------------------------------------------------------------
+
+ describe('queryDevice', () => {
+ it('should return matches with deviceId and queryMs', async () => {
+ const result = await service.queryDevice('dev-001', [0.1, 0.2], 5);
+
+ expect(result.deviceId).toBe('dev-001');
+ expect(result.queryMs).toBe(5);
+ expect(result.matches).toEqual([
+ { id: 1, distance: 0.12, metadata: { label: 'temp' } },
+ { id: 2, distance: 0.34 },
+ ]);
+ });
+
+ it('should pass deviceId, vector, and k to deps.queryVectors', async () => {
+ const vector = [1.0, 2.0, 3.0];
+ await service.queryDevice('dev-xyz', vector, 10);
+
+ expect(deps.queryVectors).toHaveBeenCalledWith('dev-xyz', vector, 10);
+ });
+
+ it('should default queryMs to 0 when query_ms is undefined', async () => {
+ deps = makeDeps({
+ queryVectors: vi.fn().mockResolvedValue({
+ results: [],
+ query_ms: undefined,
+ }),
+ });
+ service = new TelemetryService(deps);
+
+ const result = await service.queryDevice('dev-001', [0.1], 1);
+
+ expect(result.queryMs).toBe(0);
+ });
+
+ it('should return empty matches when no results', async () => {
+ deps = makeDeps({
+ queryVectors: vi.fn().mockResolvedValue({
+ results: [],
+ query_ms: 1,
+ }),
+ });
+ service = new TelemetryService(deps);
+
+ const result = await service.queryDevice('dev-001', [0.1], 1);
+
+ expect(result.matches).toEqual([]);
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // ingestTelemetry
+ // -----------------------------------------------------------------------
+
+ describe('ingestTelemetry', () => {
+ it('should convert TelemetryReading[] to vectors and return IngestResult', async () => {
+ const readings = [
+ makeReading({ readingId: 'r-001', vector: [0.1, 0.2, 0.3] }),
+ makeReading({ readingId: 'r-002', vector: [0.4, 0.5, 0.6] }),
+ ];
+
+ const result = await service.ingestTelemetry('dev-001', readings);
+
+ expect(result.deviceId).toBe('dev-001');
+ expect(result.ingested).toBe(3);
+ expect(result.epoch).toBe(42);
+ });
+
+ it('should pass correctly structured vectors to deps.ingestVectors', async () => {
+ const timestamp = new Date('2026-03-01T10:00:00Z');
+ const readings = [
+ makeReading({
+ readingId: 'r-100',
+ vector: [1.0, 2.0],
+ timestamp,
+ anomalyScore: 0.9,
+ metadata: { zone: 'A' },
+ }),
+ ];
+
+ await service.ingestTelemetry('dev-001', readings);
+
+ expect(deps.ingestVectors).toHaveBeenCalledWith('dev-001', [
+ {
+ values: [1.0, 2.0],
+ metadata: {
+ readingId: 'r-100',
+ timestamp: '2026-03-01T10:00:00.000Z',
+ anomalyScore: 0.9,
+ zone: 'A',
+ },
+ },
+ ]);
+ });
+
+ it('should merge reading metadata into vector metadata', async () => {
+ const readings = [
+ makeReading({
+ metadata: { custom: 'value', source: 'test' },
+ }),
+ ];
+
+ await service.ingestTelemetry('dev-001', readings);
+
+ const calledVectors = (deps.ingestVectors as ReturnType<typeof vi.fn>)
+ .mock.calls[0][1];
+ expect(calledVectors[0].metadata).toHaveProperty('custom', 'value');
+ expect(calledVectors[0].metadata).toHaveProperty('source', 'test');
+ expect(calledVectors[0].metadata).toHaveProperty('readingId');
+ expect(calledVectors[0].metadata).toHaveProperty('timestamp');
+ expect(calledVectors[0].metadata).toHaveProperty('anomalyScore');
+ });
+
+ it('should handle empty readings array', async () => {
+ deps = makeDeps({
+ ingestVectors: vi.fn().mockResolvedValue({ ingested: 0 }),
+ });
+ service = new TelemetryService(deps);
+
+ const result = await service.ingestTelemetry('dev-001', []);
+
+ expect(deps.ingestVectors).toHaveBeenCalledWith('dev-001', []);
+ expect(result.ingested).toBe(0);
+ });
+ });
+
+ // -----------------------------------------------------------------------
+ // getStoreHealth
+ // -----------------------------------------------------------------------
+
+ describe('getStoreHealth', () => {
+ it('should compute liveRatio correctly', async () => {
+ const result = await service.getStoreHealth('dev-001');
+
+ // (1000 - 50) / 1000 = 0.95
+ expect(result.liveRatio).toBeCloseTo(0.95, 10);
+ expect(result.deviceId).toBe('dev-001');
+ expect(result.totalVectors).toBe(1000);
+ expect(result.deletedVectors).toBe(50);
+ expect(result.dimension).toBe(384);
+ expect(result.fileSizeBytes).toBe(2_048_000);
+ expect(result.epoch).toBe(42);
+ });
+
+ it('should return liveRatio 1.0 when total_vectors is 0', async () => {
+ deps = makeDeps({
+ getStoreStatus: vi.fn().mockResolvedValue({
+ total_vectors: 0,
+ deleted_vectors: 0,
+ dimension: 128,
+ file_size_bytes: 0,
+ epoch: 1,
+ }),
+ });
+ service = new TelemetryService(deps);
+
+ const result = await service.getStoreHealth('dev-001');
+
+ expect(result.liveRatio).toBe(1.0);
+ });
+
+ it('should return liveRatio 0.0 when all vectors are deleted', async () => {
+ deps = makeDeps({
+ getStoreStatus: vi.fn().mockResolvedValue({
+ total_vectors: 100,
+ deleted_vectors: 100,
+ dimension: 256,
+ }),
+ });
+ service = new TelemetryService(deps);
+
+ const result = await service.getStoreHealth('dev-001');
+
+ expect(result.liveRatio).toBeCloseTo(0.0, 10);
+ });
+
+ it('should default fileSizeBytes to 0 when file_size_bytes is undefined', async () => {
+ deps = makeDeps({
+ getStoreStatus: vi.fn().mockResolvedValue({
+ total_vectors: 10,
+ deleted_vectors: 0,
+ dimension: 64,
+ }),
+ });
+ service = new TelemetryService(deps);
+
+ const result = await service.getStoreHealth('dev-001');
+
+ expect(result.fileSizeBytes).toBe(0);
+ });
+
+ it('should pass deviceId to deps.getStoreStatus', async () => {
+ await service.getStoreHealth('dev-xyz');
+
+ expect(deps.getStoreStatus).toHaveBeenCalledWith('dev-xyz');
+ });
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/witness-audit-worker.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/witness-audit-worker.test.ts
new file mode 100644
index 0000000000..ed77fcca84
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/witness-audit-worker.test.ts
@@ -0,0 +1,163 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { WitnessAuditWorker } from '../../src/workers/witness-audit-worker.js';
+import type { IoTCoordinator } from '../../src/application/iot-coordinator.js';
+
+function makeCoordinator(overrides: Partial<IoTCoordinator> = {}): IoTCoordinator {
+ return {
+ listDevices: vi.fn().mockReturnValue([
+ { deviceId: 'dev-001' },
+ ]),
+ getDeviceWitnessChain: vi.fn().mockResolvedValue({
+ length: 3,
+ entries: [
+ { epoch: 1 },
+ { epoch: 2 },
+ { epoch: 3 },
+ ],
+ }),
+ ...overrides,
+ } as unknown as IoTCoordinator;
+}
+
+describe('WitnessAuditWorker', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('starts and stops cleanly', () => {
+ const worker = new WitnessAuditWorker(makeCoordinator());
+ expect(worker.isRunning()).toBe(false);
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ expect(worker.isRunning()).toBe(false);
+ });
+
+ it('does not start twice', () => {
+ const worker = new WitnessAuditWorker(makeCoordinator());
+ worker.start();
+ worker.start();
+ expect(worker.isRunning()).toBe(true);
+ worker.stop();
+ });
+
+ it('calls onAuditComplete for contiguous chain', async () => {
+ const onAuditComplete = vi.fn();
+ const onGapDetected = vi.fn();
+ const coord = makeCoordinator();
+ const worker = new WitnessAuditWorker(coord, {
+ intervalMs: 1000,
+ onAuditComplete,
+ onGapDetected,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onAuditComplete).toHaveBeenCalledWith('dev-001', 3);
+ expect(onGapDetected).not.toHaveBeenCalled();
+ worker.stop();
+ });
+
+ it('detects epoch gaps in witness chain', async () => {
+ const onGapDetected = vi.fn();
+ const coord = makeCoordinator({
+ getDeviceWitnessChain: vi.fn().mockResolvedValue({
+ length: 5,
+ entries: [
+ { epoch: 1 },
+ { epoch: 2 },
+ { epoch: 5 },
+ ],
+ }),
+ });
+
+ const worker = new WitnessAuditWorker(coord, {
+ intervalMs: 1000,
+ onGapDetected,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onGapDetected).toHaveBeenCalledWith('dev-001', 2, 5);
+ worker.stop();
+ });
+
+ it('calls onAuditError when chain fetch fails', async () => {
+ const onAuditError = vi.fn();
+ const coord = makeCoordinator({
+ getDeviceWitnessChain: vi.fn().mockRejectedValue(new Error('chain error')),
+ });
+ const worker = new WitnessAuditWorker(coord, {
+ intervalMs: 1000,
+ onAuditError,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onAuditError).toHaveBeenCalledWith('dev-001', expect.any(Error));
+ worker.stop();
+ });
+
+ it('handles empty chain entries', async () => {
+ const onAuditComplete = vi.fn();
+ const coord = makeCoordinator({
+ getDeviceWitnessChain: vi.fn().mockResolvedValue({
+ length: 0,
+ entries: [],
+ }),
+ });
+ const worker = new WitnessAuditWorker(coord, {
+ intervalMs: 1000,
+ onAuditComplete,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onAuditComplete).toHaveBeenCalledWith('dev-001', 0);
+ worker.stop();
+ });
+
+ it('audits multiple devices', async () => {
+ const onAuditComplete = vi.fn();
+ const coord = makeCoordinator({
+ listDevices: vi.fn().mockReturnValue([
+ { deviceId: 'dev-001' },
+ { deviceId: 'dev-002' },
+ { deviceId: 'dev-003' },
+ ]),
+ });
+
+ const worker = new WitnessAuditWorker(coord, {
+ intervalMs: 1000,
+ onAuditComplete,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onAuditComplete).toHaveBeenCalledTimes(3);
+ worker.stop();
+ });
+
+ it('uses chain.length when available, falls back to entries.length', async () => {
+ const onAuditComplete = vi.fn();
+ const coord = makeCoordinator({
+ getDeviceWitnessChain: vi.fn().mockResolvedValue({
+ entries: [{ epoch: 1 }, { epoch: 2 }],
+ }),
+ });
+ const worker = new WitnessAuditWorker(coord, {
+ intervalMs: 1000,
+ onAuditComplete,
+ });
+ worker.start();
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(onAuditComplete).toHaveBeenCalledWith('dev-001', 2);
+ worker.stop();
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/witness-verification-service.test.ts b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/witness-verification-service.test.ts
new file mode 100644
index 0000000000..99c7ccb907
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/unit/witness-verification-service.test.ts
@@ -0,0 +1,221 @@
+import { describe, it, expect, vi } from 'vitest';
+import {
+ WitnessVerificationService,
+ type WitnessVerificationDeps,
+} from '../../src/domain/services/witness-verification-service.js';
+
+function makeDeps(overrides: Partial<WitnessVerificationDeps> = {}): WitnessVerificationDeps {
+ return {
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 5,
+ head: 'abc123',
+ entries: [
+ { epoch: 1, hash: 'h1' },
+ { epoch: 2, hash: 'h2', previous_hash: 'h1' },
+ { epoch: 3, hash: 'h3', previous_hash: 'h2' },
+ { epoch: 4, hash: 'h4', previous_hash: 'h3' },
+ { epoch: 5, hash: 'h5', previous_hash: 'h4' },
+ ],
+ }),
+ ...overrides,
+ };
+}
+
+describe('WitnessVerificationService', () => {
+ it('verifies a contiguous chain with valid hashes', async () => {
+ const svc = new WitnessVerificationService(makeDeps());
+ const result = await svc.verifyChain('dev-001');
+
+ expect(result.deviceId).toBe('dev-001');
+ expect(result.chainLength).toBe(5);
+ expect(result.verified).toBe(true);
+ expect(result.gaps).toHaveLength(0);
+ expect(result.headEpoch).toBe(5);
+ expect(result.headHash).toBe('abc123');
+ expect(result.integrityScore).toBe(1);
+ });
+
+ it('detects epoch gaps', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 5,
+ head: 'h5',
+ entries: [
+ { epoch: 1, hash: 'h1' },
+ { epoch: 2, hash: 'h2', previous_hash: 'h1' },
+ { epoch: 5, hash: 'h5', previous_hash: 'h4' },
+ ],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-002');
+
+ expect(result.verified).toBe(false);
+ expect(result.gaps).toHaveLength(1);
+ expect(result.gaps[0]).toEqual({
+ deviceId: 'dev-002',
+ fromEpoch: 2,
+ toEpoch: 5,
+ missingCount: 2,
+ });
+ expect(result.integrityScore).toBeLessThan(1);
+ });
+
+ it('detects broken hash chain', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 3,
+ entries: [
+ { epoch: 1, hash: 'h1' },
+ { epoch: 2, hash: 'h2', previous_hash: 'WRONG' },
+ { epoch: 3, hash: 'h3', previous_hash: 'h2' },
+ ],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-003');
+
+ expect(result.verified).toBe(false);
+ expect(result.gaps).toHaveLength(0);
+ expect(result.integrityScore).toBe(0.5);
+ });
+
+ it('handles empty entries with length > 0', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 10,
+ head: 'abc',
+ entries: [],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-004');
+
+ expect(result.verified).toBe(true);
+ expect(result.chainLength).toBe(10);
+ expect(result.integrityScore).toBe(0.5);
+ expect(result.headHash).toBe('abc');
+ });
+
+ it('handles empty chain with length 0', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 0,
+ entries: [],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-005');
+
+ expect(result.verified).toBe(true);
+ expect(result.integrityScore).toBe(1.0);
+ });
+
+ it('handles entries without hash fields (SDK minimal entries)', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 3,
+ entries: [
+ { epoch: 1 },
+ { epoch: 2 },
+ { epoch: 3 },
+ ],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-006');
+
+ expect(result.verified).toBe(true);
+ expect(result.gaps).toHaveLength(0);
+ expect(result.integrityScore).toBe(1);
+ });
+
+ it('sorts entries by epoch regardless of input order', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 4,
+ entries: [
+ { epoch: 4, hash: 'h4' },
+ { epoch: 1, hash: 'h1' },
+ { epoch: 3, hash: 'h3' },
+ { epoch: 2, hash: 'h2' },
+ ],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-007');
+
+ expect(result.headEpoch).toBe(4);
+ expect(result.verified).toBe(true);
+ });
+
+ it('detects multiple gaps', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 10,
+ entries: [
+ { epoch: 1 },
+ { epoch: 3 },
+ { epoch: 7 },
+ { epoch: 10 },
+ ],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-008');
+
+ expect(result.gaps).toHaveLength(3);
+ expect(result.gaps[0].missingCount).toBe(1);
+ expect(result.gaps[1].missingCount).toBe(3);
+ expect(result.gaps[2].missingCount).toBe(2);
+ expect(result.verified).toBe(false);
+ });
+
+ it('uses chain.head as headHash when available', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ head: 'chain-head-hash',
+ entries: [
+ { epoch: 1, hash: 'entry-hash' },
+ ],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-009');
+
+ expect(result.headHash).toBe('chain-head-hash');
+ });
+
+ it('falls back to last entry hash when chain.head is missing', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ entries: [
+ { epoch: 1, hash: 'h1' },
+ { epoch: 2, hash: 'h2' },
+ ],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-010');
+
+ expect(result.headHash).toBe('h2');
+ });
+
+ it('calculates integrity score with gaps and broken hashes', async () => {
+ const deps = makeDeps({
+ getWitnessChain: vi.fn().mockResolvedValue({
+ length: 10,
+ entries: [
+ { epoch: 1, hash: 'h1' },
+ { epoch: 5, hash: 'h5', previous_hash: 'BROKEN' },
+ ],
+ }),
+ });
+ const svc = new WitnessVerificationService(deps);
+ const result = await svc.verifyChain('dev-011');
+
+ expect(result.verified).toBe(false);
+ expect(result.gaps).toHaveLength(1);
+ expect(result.integrityScore).toBeLessThan(0.5);
+ });
+});
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/application/iot-coordinator.ts b/v3/@claude-flow/plugin-iot-cognitum/src/application/iot-coordinator.ts
index eacdafbfda..b5ace47ede 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/application/iot-coordinator.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/application/iot-coordinator.ts
@@ -9,7 +9,26 @@ import type {
} from '../domain/services/telemetry-service.js';
import { MeshService } from '../domain/services/mesh-service.js';
import type { MeshTopology } from '../domain/services/mesh-service.js';
-import type { DeviceAgent, DeviceTrustLevel } from '../domain/entities/index.js';
+import { AnomalyDetectionService } from '../domain/services/anomaly-detection-service.js';
+import type { TelemetryBaseline, AnomalyDetectionConfig } from '../domain/services/anomaly-detection-service.js';
+import { TelemetryIngestionService } from '../domain/services/telemetry-ingestion-service.js';
+import type { IngestionResult } from '../domain/services/telemetry-ingestion-service.js';
+import { FleetTopologyService } from '../domain/services/fleet-topology-service.js';
+import type { CreateFleetOptions, FleetSummary } from '../domain/services/fleet-topology-service.js';
+import { InMemoryFleetRepository } from '../infrastructure/in-memory-fleet-repository.js';
+import { FirmwareOrchestrationService } from '../domain/services/firmware-orchestration-service.js';
+import type { FirmwareRollout } from '../domain/services/firmware-orchestration-service.js';
+import { WitnessVerificationService } from '../domain/services/witness-verification-service.js';
+import type { WitnessVerificationResult } from '../domain/services/witness-verification-service.js';
+import { SONAIntegrationService } from '../domain/services/sona-integration-service.js';
+import type { SONAClient } from '../domain/services/sona-integration-service.js';
+import type { TelemetryRepository } from '../domain/repositories/telemetry-repository.js';
+import type { DeviceAgent, DeviceTrustLevel, TelemetryReading, AnomalyDetection, DeviceFleet, FleetTopology, FirmwarePolicy } from '../domain/entities/index.js';
+import type {
+ DeviceRepository,
+ TrustHistoryRepository,
+ FleetRepository,
+} from '../domain/repositories/index.js';
// ---------------------------------------------------------------------------
// Configuration
@@ -24,6 +43,18 @@ export interface IoTCoordinatorConfig {
defaultTls?: { insecure?: boolean; ca?: string };
/** Active health-probe interval (ms) for each SeedClient. */
healthInterval?: number;
+ /** Optional device persistence repository. */
+ deviceRepository?: DeviceRepository;
+ /** Optional trust history repository. */
+ trustHistoryRepository?: TrustHistoryRepository;
+ /** Anomaly detection configuration. */
+ anomalyDetection?: Partial<AnomalyDetectionConfig>;
+ /** Optional fleet persistence repository. */
+ fleetRepository?: FleetRepository;
+ /** Optional SONA neural learning client. */
+ sonaClient?: SONAClient;
+ /** Optional HNSW-indexed telemetry repository. */
+ telemetryRepository?: TelemetryRepository;
}
export interface IoTCoordinatorCallbacks {
@@ -54,13 +85,24 @@ export class IoTCoordinator {
private readonly lifecycle: DeviceLifecycleService;
private readonly telemetry: TelemetryService;
private readonly mesh: MeshService;
+ private readonly anomalyDetection: AnomalyDetectionService;
+ private readonly ingestion: TelemetryIngestionService;
+ private readonly fleet: FleetTopologyService;
+ private readonly firmware: FirmwareOrchestrationService;
+ private readonly witnessVerification: WitnessVerificationService;
+ private readonly sona: SONAIntegrationService;
+ private readonly telemetryRepo?: TelemetryRepository;
private readonly config: IoTCoordinatorConfig;
+ private readonly deviceRepo?: DeviceRepository;
+ private readonly trustRepo?: TrustHistoryRepository;
constructor(
config: IoTCoordinatorConfig,
callbacks?: IoTCoordinatorCallbacks,
) {
this.config = config;
+ this.deviceRepo = config.deviceRepository;
+ this.trustRepo = config.trustHistoryRepository;
this.factory = new SeedClientFactory({
defaultTls: config.defaultTls,
healthInterval: config.healthInterval,
@@ -96,6 +138,15 @@ export class IoTCoordinator {
const client = this.resolveClient(deviceId);
return client.custody.epoch();
},
+ pairDevice: async (deviceId: string, clientName: string) => {
+ const client = this.resolveClient(deviceId);
+ const resp = await client.pair.create({ clientName });
+ return { paired: true, token: resp.token.reveal() };
+ },
+ unpairDevice: async (deviceId: string, clientName?: string) => {
+ const client = this.resolveClient(deviceId);
+ await client.pair.delete(clientName ?? 'claude-flow');
+ },
onDeviceRegistered: callbacks?.onDeviceRegistered,
onTrustChange: callbacks?.onTrustChange,
});
@@ -133,6 +184,52 @@ export class IoTCoordinator {
return client.mesh.clusterHealth();
},
});
+
+ this.anomalyDetection = new AnomalyDetectionService(config.anomalyDetection);
+ this.ingestion = new TelemetryIngestionService(
+ {
+ queryDeviceStore: async (deviceId, vector, k) => {
+ const client = this.resolveClient(deviceId);
+ const result = await client.store.query({ vector, k });
+ return result.results;
+ },
+ getStoreStatus: async (deviceId) => {
+ const client = this.resolveClient(deviceId);
+ return client.store.status();
+ },
+ },
+ this.anomalyDetection,
+ );
+
+ this.fleet = new FleetTopologyService(
+ config.fleetRepository ?? new InMemoryFleetRepository(),
+ );
+
+ this.firmware = new FirmwareOrchestrationService({
+ getDeviceFirmwareVersion: async (deviceId: string) => {
+ const entry = this.requireEntry(deviceId);
+ return entry.agent.firmwareVersion;
+ },
+ deployFirmware: async (_deviceId: string, _version: string) => {
+ // OTA deployment requires Cognitum Cloud API (not available via local Seed SDK).
+ // Stub returns success; real implementation will use cloud control plane.
+ return { success: true };
+ },
+ getDeviceAnomalyScore: async (deviceId: string) => {
+ const entry = this.requireEntry(deviceId);
+ return 1 - entry.agent.trustScore.overall;
+ },
+ });
+
+ this.witnessVerification = new WitnessVerificationService({
+ getWitnessChain: async (deviceId: string) => {
+ const client = this.resolveClient(deviceId);
+ return client.witness.chain();
+ },
+ });
+
+ this.sona = new SONAIntegrationService(config.sonaClient ?? null);
+ this.telemetryRepo = config.telemetryRepository;
}
// -------------------------------------------------------------------------
@@ -176,6 +273,7 @@ export class IoTCoordinator {
this.devices.delete(endpoint);
this.devices.set(agent.deviceId, { agent, client });
+ await this.deviceRepo?.save(agent);
return agent;
}
@@ -185,11 +283,57 @@ export class IoTCoordinator {
*/
async getDeviceStatus(deviceId: string): Promise<DeviceAgent> {
const entry = this.requireEntry(deviceId);
+ const oldLevel = entry.agent.trustLevel;
const refreshed = await this.lifecycle.refreshDeviceState(entry.agent);
entry.agent = refreshed;
+ await this.deviceRepo?.save(refreshed);
+ if (oldLevel !== refreshed.trustLevel) {
+ await this.trustRepo?.append({
+ deviceId, timestamp: new Date(),
+ oldLevel, newLevel: refreshed.trustLevel,
+ score: refreshed.trustScore, trigger: 'refresh',
+ });
+ }
return refreshed;
}
+ /** Pair a registered device, promoting its trust level. */
+ async pairDevice(
+ deviceId: string,
+ clientName: string,
+ ): Promise<DeviceAgent> {
+ const entry = this.requireEntry(deviceId);
+ const oldLevel = entry.agent.trustLevel;
+ const updated = await this.lifecycle.pairDevice(entry.agent, clientName);
+ entry.agent = updated;
+ await this.deviceRepo?.save(updated);
+ if (oldLevel !== updated.trustLevel) {
+ await this.trustRepo?.append({
+ deviceId, timestamp: new Date(),
+ oldLevel, newLevel: updated.trustLevel,
+ score: updated.trustScore, trigger: 'pair',
+ });
+ }
+ return updated;
+ }
+
+ /** Unpair a registered device, demoting its trust level. */
+ async unpairDevice(deviceId: string): Promise<DeviceAgent> {
+ const entry = this.requireEntry(deviceId);
+ const oldLevel = entry.agent.trustLevel;
+ const updated = await this.lifecycle.unpairDevice(entry.agent);
+ entry.agent = updated;
+ await this.deviceRepo?.save(updated);
+ if (oldLevel !== updated.trustLevel) {
+ await this.trustRepo?.append({
+ deviceId, timestamp: new Date(),
+ oldLevel, newLevel: updated.trustLevel,
+ score: updated.trustScore, trigger: 'unpair',
+ });
+ }
+ return updated;
+ }
+
// -------------------------------------------------------------------------
// Telemetry / vector store
// -------------------------------------------------------------------------
@@ -247,6 +391,131 @@ export class IoTCoordinator {
return client.custody.epoch();
}
+ /** Verify witness chain integrity for a device. */
+ async verifyWitnessChain(deviceId: string): Promise<WitnessVerificationResult> {
+ this.requireEntry(deviceId);
+ return this.witnessVerification.verifyChain(deviceId);
+ }
+
+ // -------------------------------------------------------------------------
+ // Anomaly detection
+ // -------------------------------------------------------------------------
+
+ /** Detect anomalies in a batch of telemetry readings for a device. */
+ detectAnomalies(
+ deviceId: string,
+ readings: TelemetryReading[],
+ ): { anomalies: AnomalyDetection[]; total: number; anomalous: number } {
+ const result = this.ingestion.processBatch(deviceId, readings);
+
+ if (result.anomalies.length > 0) {
+ const baseline = this.ingestion.getBaseline(deviceId);
+ for (const anomaly of result.anomalies) {
+ void this.sona.learnAnomalyPattern(anomaly, baseline);
+ }
+ void this.sona.recordTelemetryTrajectory(deviceId, readings, result.anomalies);
+ }
+
+ if (this.telemetryRepo) {
+ void this.telemetryRepo.storeBatch(readings);
+ for (const anomaly of result.anomalies) {
+ void this.telemetryRepo.storeAnomaly(anomaly);
+ }
+ }
+
+ return {
+ anomalies: result.anomalies,
+ total: result.readingsProcessed,
+ anomalous: result.anomaliesDetected,
+ };
+ }
+
+ /** Compute a telemetry baseline for a device from readings. */
+ computeBaseline(
+ deviceId: string,
+ readings: TelemetryReading[],
+ ): TelemetryBaseline {
+ const oldBaseline = this.ingestion.getBaseline(deviceId);
+ const newBaseline = this.ingestion.refreshBaseline(deviceId, readings);
+ void this.sona.learnBaselineShift(deviceId, oldBaseline, newBaseline);
+ return newBaseline;
+ }
+
+ /** Get the current baseline for a device, if computed. */
+ getBaseline(deviceId: string): TelemetryBaseline | undefined {
+ return this.ingestion.getBaseline(deviceId);
+ }
+
+ // -------------------------------------------------------------------------
+ // Firmware orchestration
+ // -------------------------------------------------------------------------
+
+ async createFirmwareRollout(
+ fleetId: string,
+ firmwareVersion: string,
+ ): Promise<FirmwareRollout> {
+ const fleet = await this.fleet.getFleet(fleetId);
+ return this.firmware.createRollout(
+ fleetId,
+ firmwareVersion,
+ fleet.deviceIds,
+ fleet.firmwarePolicy,
+ );
+ }
+
+ async advanceFirmwareRollout(rolloutId: string): Promise<FirmwareRollout> {
+ return this.firmware.advanceRollout(rolloutId);
+ }
+
+ rollbackFirmwareRollout(rolloutId: string): FirmwareRollout {
+ return this.firmware.rollbackRollout(rolloutId);
+ }
+
+ getFirmwareRollout(rolloutId: string): FirmwareRollout {
+ return this.firmware.getRollout(rolloutId);
+ }
+
+ listFirmwareRollouts(fleetId?: string): FirmwareRollout[] {
+ return this.firmware.listRollouts(fleetId);
+ }
+
+ // -------------------------------------------------------------------------
+ // Fleet management
+ // -------------------------------------------------------------------------
+
+ async createFleet(options: CreateFleetOptions): Promise<DeviceFleet> {
+ return this.fleet.createFleet(options);
+ }
+
+ async getFleet(fleetId: string): Promise<DeviceFleet> {
+ return this.fleet.getFleet(fleetId);
+ }
+
+ async listFleets(): Promise<FleetSummary[]> {
+ return this.fleet.listFleets();
+ }
+
+ async addDeviceToFleet(fleetId: string, deviceId: string): Promise<DeviceFleet> {
+ this.requireEntry(deviceId);
+ return this.fleet.addDeviceToFleet(fleetId, deviceId);
+ }
+
+ async removeDeviceFromFleet(fleetId: string, deviceId: string): Promise<DeviceFleet> {
+ return this.fleet.removeDeviceFromFleet(fleetId, deviceId);
+ }
+
+ async updateFleetTopology(fleetId: string, topology: FleetTopology): Promise<DeviceFleet> {
+ return this.fleet.updateTopology(fleetId, topology);
+ }
+
+ async updateFleetFirmwarePolicy(fleetId: string, policy: Partial<FirmwarePolicy>): Promise<DeviceFleet> {
+ return this.fleet.updateFirmwarePolicy(fleetId, policy);
+ }
+
+ async deleteFleet(fleetId: string): Promise<void> {
+ return this.fleet.deleteFleet(fleetId);
+ }
+
// -------------------------------------------------------------------------
// Inventory
// -------------------------------------------------------------------------
@@ -263,6 +532,8 @@ export class IoTCoordinator {
await entry.client.close();
this.devices.delete(deviceId);
+ await this.deviceRepo?.delete(deviceId);
+ await this.trustRepo?.deleteByDevice(deviceId);
}
/** Shut down all SDK clients and clear internal state. */
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/cli-commands.ts b/v3/@claude-flow/plugin-iot-cognitum/src/cli-commands.ts
index 844497b943..03f0b7904a 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/cli-commands.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/cli-commands.ts
@@ -16,6 +16,27 @@ export function createCliCommands(
_getContext: ContextGetter,
): CLICommandDefinition[] {
return [
+ {
+ name: 'iot init',
+ description: 'Initialize IoT Cognitum plugin configuration',
+ options: [
+ { name: 'fleet-id', description: 'Default fleet identifier', type: 'string', default: 'default' },
+ { name: 'zone-id', description: 'Default IEC 62443 security zone', type: 'string', default: 'zone-0' },
+ { name: 'insecure', description: 'Allow TLS-insecure connections', type: 'boolean', default: true },
+ ],
+ handler: async (args) => {
+ const fleetId = (args['fleet-id'] as string) ?? 'default';
+ const zoneId = (args['zone-id'] as string) ?? 'zone-0';
+ const insecure = args['insecure'] !== false;
+ console.log('IoT Cognitum Plugin Configuration');
+ console.log('-'.repeat(40));
+ console.log(` Fleet ID: ${fleetId}`);
+ console.log(` Zone ID: ${zoneId}`);
+ console.log(` TLS Insecure: ${insecure}`);
+ console.log('');
+ console.log('Plugin ready. Use "iot register -e <endpoint>" to add a device.');
+ },
+ },
{
name: 'iot register',
description: 'Register a Cognitum Seed device by endpoint',
@@ -95,6 +116,35 @@ export function createCliCommands(
console.log(`Device ${args._[0]} removed.`);
},
},
+ {
+ name: 'iot pair',
+ description: 'Pair with a registered device to establish mutual trust',
+ options: [
+ { name: 'device-id', short: 'd', description: 'Device identifier', type: 'string', required: true },
+ { name: 'name', short: 'n', description: 'Client name for pairing', type: 'string', default: 'claude-flow' },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const device = await coordinator.pairDevice(
+ args['device-id'] as string,
+ (args['name'] as string) ?? 'claude-flow',
+ );
+ console.log(`Paired with device: ${device.deviceId}`);
+ console.log(` Trust: ${getDeviceTrustLabel(device.trustLevel)}`);
+ console.log(` Score: ${device.trustScore.overall.toFixed(3)}`);
+ },
+ },
+ {
+ name: 'iot unpair',
+ description: 'Unpair from a registered device',
+ arguments: [{ name: 'device-id', description: 'Device identifier', required: true }],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const device = await coordinator.unpairDevice(args._[0]!);
+ console.log(`Unpaired device: ${device.deviceId}`);
+ console.log(` Trust: ${getDeviceTrustLabel(device.trustLevel)}`);
+ },
+ },
{
name: 'iot query',
description: 'Query device vector store with a k-NN search',
@@ -179,5 +229,278 @@ export function createCliCommands(
}
},
},
+
+ // -- Firmware orchestration (Phase 3) ---------------------------------------
+ {
+ name: 'iot firmware deploy',
+ description: 'Create and start a firmware rollout for a fleet',
+ options: [
+ { name: 'fleet-id', short: 'i', description: 'Fleet identifier', type: 'string', required: true },
+ { name: 'version', short: 'v', description: 'Target firmware version', type: 'string', required: true },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const rollout = await coordinator.createFirmwareRollout(
+ args['fleet-id'] as string,
+ args['version'] as string,
+ );
+ console.log(`Rollout created: ${rollout.rolloutId}`);
+ console.log(` Fleet: ${rollout.fleetId}`);
+ console.log(` Version: ${rollout.firmwareVersion}`);
+ console.log(` Stage: ${rollout.stage}`);
+ console.log(` Targets: ${rollout.targetDeviceIds.length} device(s)`);
+ console.log(` Canaries: ${rollout.canaryDeviceIds.length} device(s)`);
+ },
+ },
+ {
+ name: 'iot firmware advance',
+ description: 'Advance a firmware rollout to the next stage',
+ arguments: [{ name: 'rollout-id', description: 'Rollout identifier', required: true }],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const rollout = await coordinator.advanceFirmwareRollout(args._[0]!);
+ console.log(`Rollout ${rollout.rolloutId}: ${rollout.stage}`);
+ console.log(` Completed: ${rollout.completedDeviceIds.length}/${rollout.targetDeviceIds.length}`);
+ console.log(` Failed: ${rollout.failedDeviceIds.length}`);
+ },
+ },
+ {
+ name: 'iot firmware rollback',
+ description: 'Force rollback a firmware rollout',
+ arguments: [{ name: 'rollout-id', description: 'Rollout identifier', required: true }],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const rollout = coordinator.rollbackFirmwareRollout(args._[0]!);
+ console.log(`Rollout ${rollout.rolloutId} rolled back.`);
+ },
+ },
+ {
+ name: 'iot firmware status',
+ description: 'Show firmware rollout status',
+ arguments: [{ name: 'rollout-id', description: 'Rollout identifier', required: true }],
+ options: [
+ { name: 'format', short: 'f', description: 'Output format (table, json)', type: 'string', default: 'table' },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const rollout = coordinator.getFirmwareRollout(args._[0]!);
+ const format = args['format'] as string;
+
+ if (format === 'json') {
+ console.log(JSON.stringify(rollout, null, 2));
+ } else {
+ console.log(`Rollout: ${rollout.rolloutId}`);
+ console.log(`Fleet: ${rollout.fleetId}`);
+ console.log(`Version: ${rollout.firmwareVersion}`);
+ console.log(`Stage: ${rollout.stage}`);
+ console.log(`Completed: ${rollout.completedDeviceIds.length}/${rollout.targetDeviceIds.length}`);
+ console.log(`Failed: ${rollout.failedDeviceIds.length}`);
+ console.log(`Threshold: ${rollout.anomalyThreshold}`);
+ }
+ },
+ },
+ {
+ name: 'iot firmware list',
+ description: 'List firmware rollouts',
+ options: [
+ { name: 'fleet-id', short: 'i', description: 'Filter by fleet', type: 'string' },
+ { name: 'format', short: 'f', description: 'Output format (table, json)', type: 'string', default: 'table' },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const rollouts = coordinator.listFirmwareRollouts(args['fleet-id'] as string | undefined);
+ const format = args['format'] as string;
+
+ if (format === 'json') {
+ console.log(JSON.stringify(rollouts, null, 2));
+ } else {
+ console.log('Rollout ID | Fleet | Version | Stage');
+ console.log('-'.repeat(80));
+ for (const r of rollouts) {
+ console.log(
+ `${r.rolloutId.padEnd(37)}| ${r.fleetId.padEnd(13)}| ${r.firmwareVersion.padEnd(9)}| ${r.stage}`,
+ );
+ }
+ console.log(`\nTotal: ${rollouts.length} rollout(s)`);
+ }
+ },
+ },
+
+ // -- Fleet management (Phase 3) --------------------------------------------
+ {
+ name: 'iot fleet create',
+ description: 'Create a new device fleet',
+ options: [
+ { name: 'fleet-id', short: 'i', description: 'Fleet identifier', type: 'string', required: true },
+ { name: 'name', short: 'n', description: 'Fleet display name', type: 'string', required: true },
+ { name: 'zone-id', short: 'z', description: 'IEC 62443 security zone', type: 'string', default: 'zone-0' },
+ { name: 'topology', short: 't', description: 'Fleet topology (star, mesh, hierarchical, ring)', type: 'string', default: 'star' },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const fleet = await coordinator.createFleet({
+ fleetId: args['fleet-id'] as string,
+ name: args['name'] as string,
+ zoneId: (args['zone-id'] as string) ?? 'zone-0',
+ topology: args['topology'] as any,
+ });
+ console.log(`Fleet created: ${fleet.fleetId}`);
+ console.log(` Name: ${fleet.name}`);
+ console.log(` Zone: ${fleet.zoneId}`);
+ console.log(` Topology: ${fleet.topology}`);
+ console.log(` Devices: ${fleet.deviceIds.length}`);
+ },
+ },
+ {
+ name: 'iot fleet list',
+ description: 'List all device fleets',
+ options: [
+ { name: 'format', short: 'f', description: 'Output format (table, json)', type: 'string', default: 'table' },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const fleets = await coordinator.listFleets();
+ const format = args['format'] as string;
+
+ if (format === 'json') {
+ console.log(JSON.stringify(fleets, null, 2));
+ } else {
+ console.log('Fleet ID | Name | Devices | Topology');
+ console.log('-'.repeat(75));
+ for (const f of fleets) {
+ console.log(
+ `${f.fleetId.padEnd(25)}| ${f.name.padEnd(21)}| ${String(f.deviceCount).padEnd(8)}| ${f.topology}`,
+ );
+ }
+ console.log(`\nTotal: ${fleets.length} fleet(s)`);
+ }
+ },
+ },
+ {
+ name: 'iot fleet add',
+ description: 'Add a device to a fleet',
+ options: [
+ { name: 'fleet-id', short: 'i', description: 'Fleet identifier', type: 'string', required: true },
+ { name: 'device-id', short: 'd', description: 'Device identifier', type: 'string', required: true },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const fleet = await coordinator.addDeviceToFleet(
+ args['fleet-id'] as string,
+ args['device-id'] as string,
+ );
+ console.log(`Device ${args['device-id']} added to fleet ${fleet.fleetId} (${fleet.deviceIds.length} device(s))`);
+ },
+ },
+ {
+ name: 'iot fleet remove',
+ description: 'Remove a device from a fleet',
+ options: [
+ { name: 'fleet-id', short: 'i', description: 'Fleet identifier', type: 'string', required: true },
+ { name: 'device-id', short: 'd', description: 'Device identifier', type: 'string', required: true },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const fleet = await coordinator.removeDeviceFromFleet(
+ args['fleet-id'] as string,
+ args['device-id'] as string,
+ );
+ console.log(`Device ${args['device-id']} removed from fleet ${fleet.fleetId} (${fleet.deviceIds.length} device(s))`);
+ },
+ },
+ {
+ name: 'iot fleet delete',
+ description: 'Delete a fleet',
+ arguments: [{ name: 'fleet-id', description: 'Fleet identifier to delete', required: true }],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ await coordinator.deleteFleet(args._[0]!);
+ console.log(`Fleet ${args._[0]} deleted.`);
+ },
+ },
+
+ // -- Telemetry anomaly detection (Phase 2) --------------------------------
+ {
+ name: 'iot anomalies',
+ description: 'Show detected anomalies for a device',
+ arguments: [{ name: 'device-id', description: 'Device identifier', required: true }],
+ options: [
+ { name: 'format', short: 'f', description: 'Output format (table, json)', type: 'string', default: 'table' },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const deviceId = args._[0]!;
+ const format = args['format'] as string;
+ const baseline = coordinator.getBaseline(deviceId);
+ if (!baseline) {
+ console.log(`No baseline computed for device ${deviceId}. Run "iot baseline ${deviceId} --compute" first.`);
+ return;
+ }
+ console.log(`Baseline for device ${deviceId}:`);
+ if (format === 'json') {
+ console.log(JSON.stringify(baseline, null, 2));
+ } else {
+ console.log(` Dimensions: ${baseline.meanVector.length}`);
+ console.log(` Samples: ${baseline.sampleCount}`);
+ console.log(` Computed: ${baseline.computedAt.toISOString()}`);
+ }
+ },
+ },
+ {
+ name: 'iot baseline',
+ description: 'Compute or show telemetry baseline for a device',
+ arguments: [{ name: 'device-id', description: 'Device identifier', required: true }],
+ options: [
+ { name: 'compute', short: 'c', description: 'Recompute baseline from recent readings', type: 'boolean' },
+ ],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const deviceId = args._[0]!;
+ const compute = args['compute'] as boolean;
+
+ if (compute) {
+ console.log(`Computing baseline for device ${deviceId}...`);
+ console.log('Note: requires telemetry readings to be ingested first.');
+ console.log('Use "iot ingest -d <device-id>" to provide readings, then rerun with --compute.');
+ return;
+ }
+
+ const baseline = coordinator.getBaseline(deviceId);
+ if (!baseline) {
+ console.log(`No baseline for device ${deviceId}. Use --compute to build from telemetry.`);
+ return;
+ }
+
+ console.log(`Baseline for device ${deviceId}:`);
+ console.log(` Dimensions: ${baseline.meanVector.length}`);
+ console.log(` Samples: ${baseline.sampleCount}`);
+ console.log(` Computed: ${baseline.computedAt.toISOString()}`);
+ },
+ },
+ {
+ name: 'iot witness verify',
+ description: 'Verify witness chain integrity for a device',
+ arguments: [{ name: 'device-id', description: 'Device identifier', required: true }],
+ options: [],
+ handler: async (args) => {
+ const coordinator = requireCoordinator(getCoordinator);
+ const deviceId = args._[0]!;
+ const result = await coordinator.verifyWitnessChain(deviceId);
+
+ console.log(`Witness chain verification for ${deviceId}:`);
+ console.log(` Chain length: ${result.chainLength}`);
+ console.log(` Verified: ${result.verified ? 'YES' : 'NO'}`);
+ console.log(` Head epoch: ${result.headEpoch}`);
+ console.log(` Head hash: ${result.headHash || '(none)'}`);
+ console.log(` Integrity score: ${result.integrityScore.toFixed(3)}`);
+
+ if (result.gaps.length > 0) {
+ console.log(` Gaps (${result.gaps.length}):`);
+ for (const gap of result.gaps) {
+ console.log(` epoch ${gap.fromEpoch} → ${gap.toEpoch} (${gap.missingCount} missing)`);
+ }
+ }
+ },
+ },
];
}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/device-repository.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/device-repository.ts
new file mode 100644
index 0000000000..8c34cc85af
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/device-repository.ts
@@ -0,0 +1,11 @@
+import type { DeviceAgent } from '../entities/index.js';
+
+export interface DeviceRepository {
+ save(device: DeviceAgent): Promise<void>;
+ findById(deviceId: string): Promise<DeviceAgent | null>;
+ findByFleet(fleetId: string): Promise<DeviceAgent[]>;
+ findByZone(zoneId: string): Promise<DeviceAgent[]>;
+ findAll(): Promise<DeviceAgent[]>;
+ delete(deviceId: string): Promise<boolean>;
+ count(): Promise<number>;
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/fleet-repository.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/fleet-repository.ts
new file mode 100644
index 0000000000..d7b28e41ae
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/fleet-repository.ts
@@ -0,0 +1,9 @@
+import type { DeviceFleet } from '../entities/index.js';
+
+export interface FleetRepository {
+ save(fleet: DeviceFleet): Promise<void>;
+ findById(fleetId: string): Promise<DeviceFleet | undefined>;
+ findAll(): Promise<DeviceFleet[]>;
+ delete(fleetId: string): Promise<boolean>;
+ count(): Promise<number>;
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/index.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/index.ts
new file mode 100644
index 0000000000..1d0577fc88
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/index.ts
@@ -0,0 +1,10 @@
+export type { DeviceRepository } from './device-repository.js';
+
+export type {
+ TrustHistoryEntry,
+ TrustHistoryRepository,
+} from './trust-history-repository.js';
+
+export type { FleetRepository } from './fleet-repository.js';
+
+export type { TelemetryRepository } from './telemetry-repository.js';
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/telemetry-repository.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/telemetry-repository.ts
new file mode 100644
index 0000000000..38781d3308
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/telemetry-repository.ts
@@ -0,0 +1,12 @@
+import type { TelemetryReading, AnomalyDetection } from '../entities/telemetry.js';
+
+export interface TelemetryRepository {
+ store(reading: TelemetryReading): Promise<void>;
+ storeBatch(readings: TelemetryReading[]): Promise<number>;
+ findByDevice(deviceId: string, limit?: number): Promise<TelemetryReading[]>;
+ searchSimilar(vector: number[], k: number, deviceId?: string): Promise<TelemetryReading[]>;
+ storeAnomaly(anomaly: AnomalyDetection): Promise<void>;
+ findAnomalies(deviceId: string, limit?: number): Promise<AnomalyDetection[]>;
+ count(deviceId?: string): Promise<number>;
+ deleteByDevice(deviceId: string): Promise<number>;
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/trust-history-repository.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/trust-history-repository.ts
new file mode 100644
index 0000000000..fd6f70c0eb
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/repositories/trust-history-repository.ts
@@ -0,0 +1,20 @@
+import type { DeviceTrustLevel } from '../entities/index.js';
+import type { DeviceTrustScore } from '../entities/index.js';
+
+export interface TrustHistoryEntry {
+ deviceId: string;
+ timestamp: Date;
+ oldLevel: DeviceTrustLevel;
+ newLevel: DeviceTrustLevel;
+ score: DeviceTrustScore;
+ /** What caused the change: 'registration', 'pair', 'unpair', 'refresh', 'probe'. */
+ trigger: string;
+}
+
+export interface TrustHistoryRepository {
+ append(entry: TrustHistoryEntry): Promise<void>;
+ findByDevice(deviceId: string, limit?: number): Promise<TrustHistoryEntry[]>;
+ findByLevel(level: DeviceTrustLevel): Promise<TrustHistoryEntry[]>;
+ deleteByDevice(deviceId: string): Promise<number>;
+ count(): Promise<number>;
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/anomaly-detection-service.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/anomaly-detection-service.ts
new file mode 100644
index 0000000000..dda96171f3
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/anomaly-detection-service.ts
@@ -0,0 +1,159 @@
+import type {
+ TelemetryReading,
+ AnomalyDetection,
+ AnomalyType,
+ AnomalyAction,
+} from '../entities/index.js';
+
+export interface AnomalyDetectionConfig {
+ /** Score threshold above which a reading is anomalous. Default 0.7. */
+ anomalyThreshold: number;
+ /** Score threshold for quarantine action. Default 0.9. */
+ quarantineThreshold: number;
+ /** Window size for baseline computation. */
+ baselineWindowSize: number;
+}
+
+export interface TelemetryBaseline {
+ deviceId: string;
+ /** Mean vector across the baseline window. */
+ meanVector: number[];
+ /** Standard deviation per dimension. */
+ stdVector: number[];
+ /** Number of readings in the baseline. */
+ sampleCount: number;
+ /** When the baseline was last computed. */
+ computedAt: Date;
+}
+
+export class AnomalyDetectionService {
+ private readonly config: AnomalyDetectionConfig;
+ private readonly baselines = new Map<string, TelemetryBaseline>();
+
+ constructor(config?: Partial<AnomalyDetectionConfig>) {
+ this.config = {
+ anomalyThreshold: config?.anomalyThreshold ?? 0.7,
+ quarantineThreshold: config?.quarantineThreshold ?? 0.9,
+ baselineWindowSize: config?.baselineWindowSize ?? 100,
+ };
+ }
+
+ /**
+ * Compute a baseline from a window of readings for a device.
+ * Calculates mean and standard deviation per vector dimension.
+ */
+ computeBaseline(deviceId: string, readings: TelemetryReading[]): TelemetryBaseline {
+ if (readings.length === 0) throw new Error('Cannot compute baseline from empty readings');
+
+ const dim = readings[0].vector.length;
+ const n = readings.length;
+
+ // Compute mean
+ const mean = new Array<number>(dim).fill(0);
+ for (const r of readings) {
+ for (let i = 0; i < dim; i++) mean[i] += r.vector[i] / n;
+ }
+
+ // Compute standard deviation
+ const std = new Array<number>(dim).fill(0);
+ for (const r of readings) {
+ for (let i = 0; i < dim; i++) {
+ const diff = r.vector[i] - mean[i];
+ std[i] += (diff * diff) / n;
+ }
+ }
+ for (let i = 0; i < dim; i++) std[i] = Math.sqrt(std[i]);
+
+ const baseline: TelemetryBaseline = {
+ deviceId,
+ meanVector: mean,
+ stdVector: std,
+ sampleCount: n,
+ computedAt: new Date(),
+ };
+
+ this.baselines.set(deviceId, baseline);
+ return baseline;
+ }
+
+ /** Get the current baseline for a device, if one has been computed. */
+ getBaseline(deviceId: string): TelemetryBaseline | undefined {
+ return this.baselines.get(deviceId);
+ }
+
+ /**
+ * Detect anomalies in a reading by comparing against the device's baseline.
+ * Uses z-score based detection: how many standard deviations each dimension
+ * deviates from the baseline mean.
+ */
+ detect(reading: TelemetryReading): AnomalyDetection {
+ const baseline = this.baselines.get(reading.deviceId);
+
+ if (!baseline) {
+ return {
+ readingId: reading.readingId,
+ deviceId: reading.deviceId,
+ score: 0,
+ type: 'drift',
+ confidence: 0,
+ suggestedAction: 'log',
+ metadata: { reason: 'no-baseline' },
+ };
+ }
+
+ // Z-score per dimension
+ const zScores = reading.vector.map((v, i) => {
+ const s = baseline.stdVector[i];
+ return s > 0 ? Math.abs(v - baseline.meanVector[i]) / s : 0;
+ });
+
+ const maxZ = Math.max(...zScores);
+ const meanZ = zScores.reduce((a, b) => a + b, 0) / zScores.length;
+
+ // Composite anomaly score (0-1): 3 std devs maps to score 1.0
+ const score = Math.min(1, meanZ / 3);
+
+ const type = this.classifyAnomaly(reading, zScores, maxZ);
+ const suggestedAction = this.suggestAction(score);
+ const confidence = Math.min(1, baseline.sampleCount / this.config.baselineWindowSize);
+
+ return {
+ readingId: reading.readingId,
+ deviceId: reading.deviceId,
+ score,
+ type,
+ confidence,
+ baselinePattern: `baseline-${reading.deviceId}`,
+ suggestedAction,
+ metadata: { maxZ, meanZ, baselineSamples: baseline.sampleCount },
+ };
+ }
+
+ /** Classify an anomaly type based on the z-score pattern. */
+ private classifyAnomaly(
+ reading: TelemetryReading,
+ zScores: number[],
+ maxZ: number,
+ ): AnomalyType {
+ const highZCount = zScores.filter((z) => z > 2).length;
+ const allLow = zScores.every((z) => z < 0.5);
+
+ if (maxZ > 5) return 'spike';
+ if (allLow && reading.rawMetrics && Object.values(reading.rawMetrics).every((v) => v === 0))
+ return 'flatline';
+ if (highZCount > zScores.length * 0.5) return 'cluster-outlier';
+ if (highZCount > 0 && highZCount <= 2) return 'drift';
+ return 'pattern-break';
+ }
+
+ private suggestAction(score: number): AnomalyAction {
+ if (score >= this.config.quarantineThreshold) return 'quarantine';
+ if (score >= this.config.anomalyThreshold) return 'alert';
+ return 'log';
+ }
+
+ /** Check whether a detection result exceeds the anomaly threshold. */
+ isAnomalous(detection: AnomalyDetection): boolean {
+ return detection.score >= this.config.anomalyThreshold;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/device-lifecycle-service.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/device-lifecycle-service.ts
index 989fcef816..8bc70180e2 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/device-lifecycle-service.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/device-lifecycle-service.ts
@@ -37,6 +37,11 @@ export interface DeviceLifecycleDeps {
getCustodyEpoch: (deviceId: string) => Promise<{
epoch: number;
}>;
+ pairDevice: (deviceId: string, clientName: string) => Promise<{
+ paired: boolean;
+ token?: string;
+ }>;
+ unpairDevice: (deviceId: string, clientName?: string) => Promise<void>;
onDeviceRegistered?: (device: DeviceAgent) => void;
onTrustChange?: (
deviceId: string,
@@ -98,6 +103,74 @@ export class DeviceLifecycleService {
return device;
}
+ /**
+ * Pair a device using the SDK's pair.create() and promote its trust level.
+ */
+ async pairDevice(
+ device: DeviceAgent,
+ clientName: string,
+ ): Promise<DeviceAgent> {
+ const result = await this.deps.pairDevice(device.deviceId, clientName);
+
+ if (!result.paired) {
+ throw new Error(`Pairing failed for device ${device.deviceId}`);
+ }
+
+ const oldLevel = device.trustLevel;
+ const newLevel =
+ device.trustLevel < DeviceTrustLevel.PROVISIONED
+ ? DeviceTrustLevel.PROVISIONED
+ : device.trustLevel;
+
+ const updated: DeviceAgent = {
+ ...device,
+ trustLevel: newLevel,
+ trustScore: {
+ ...device.trustScore,
+ overall: this.computeTrustScore(device, 0, 0, true).overall,
+ components: {
+ ...device.trustScore.components,
+ pairingIntegrity: 1.0,
+ },
+ },
+ };
+
+ if (oldLevel !== newLevel) {
+ this.deps.onTrustChange?.(device.deviceId, oldLevel, newLevel);
+ }
+
+ return updated;
+ }
+
+ /**
+ * Unpair a device and demote its trust level.
+ */
+ async unpairDevice(device: DeviceAgent): Promise<DeviceAgent> {
+ await this.deps.unpairDevice(device.deviceId);
+
+ const oldLevel = device.trustLevel;
+ const newLevel = DeviceTrustLevel.REGISTERED;
+
+ const updated: DeviceAgent = {
+ ...device,
+ trustLevel: newLevel,
+ trustScore: {
+ ...device.trustScore,
+ overall: this.computeTrustScore(device, 0, 0, false).overall,
+ components: {
+ ...device.trustScore.components,
+ pairingIntegrity: 0.0,
+ },
+ },
+ };
+
+ if (oldLevel !== newLevel) {
+ this.deps.onTrustChange?.(device.deviceId, oldLevel, newLevel);
+ }
+
+ return updated;
+ }
+
/**
* Re-fetch all device state and recalculate trust.
*/
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/firmware-orchestration-service.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/firmware-orchestration-service.ts
new file mode 100644
index 0000000000..8eb967d4d4
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/firmware-orchestration-service.ts
@@ -0,0 +1,221 @@
+import type { DeploymentStrategy, FirmwarePolicy } from '../entities/index.js';
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export type RolloutStage =
+ | 'pending'
+ | 'canary'
+ | 'rolling'
+ | 'complete'
+ | 'rolled-back'
+ | 'failed';
+
+export interface FirmwareRollout {
+ rolloutId: string;
+ fleetId: string;
+ firmwareVersion: string;
+ strategy: DeploymentStrategy;
+ stage: RolloutStage;
+ targetDeviceIds: string[];
+ canaryDeviceIds: string[];
+ completedDeviceIds: string[];
+ failedDeviceIds: string[];
+ anomalyThreshold: number;
+ startedAt: Date;
+ updatedAt: Date;
+ completedAt?: Date;
+}
+
+export interface FirmwareOrchestrationDeps {
+ getDeviceFirmwareVersion: (deviceId: string) => Promise<string>;
+ deployFirmware: (
+ deviceId: string,
+ version: string,
+ ) => Promise<{ success: boolean; error?: string }>;
+ getDeviceAnomalyScore: (deviceId: string) => Promise<number>;
+}
+
+// ---------------------------------------------------------------------------
+// Service
+// ---------------------------------------------------------------------------
+
+/**
+ * State-machine-based firmware rollout engine.
+ *
+ * Lifecycle: pending -> canary -> rolling -> complete
+ * | |
+ * rolled-back failed
+ */
+export class FirmwareOrchestrationService {
+ private readonly rollouts = new Map<string, FirmwareRollout>();
+ private rolloutCounter = 0;
+
+ constructor(private readonly deps: FirmwareOrchestrationDeps) {}
+
+ /**
+ * Create a new rollout. Canary devices are selected as the first N%
+ * of `targetDeviceIds` based on `policy.canaryPercentage`.
+ */
+ createRollout(
+ fleetId: string,
+ firmwareVersion: string,
+ targetDeviceIds: string[],
+ policy: FirmwarePolicy,
+ ): FirmwareRollout {
+ const rolloutId = `rollout-${fleetId}-${Date.now()}-${this.rolloutCounter++}`;
+
+ const canaryCount = Math.max(
+ 1,
+ Math.ceil(targetDeviceIds.length * (policy.canaryPercentage / 100)),
+ );
+ const canaryDeviceIds = targetDeviceIds.slice(0, canaryCount);
+
+ const rollout: FirmwareRollout = {
+ rolloutId,
+ fleetId,
+ firmwareVersion,
+ strategy: 'canary',
+ stage: 'pending',
+ targetDeviceIds,
+ canaryDeviceIds,
+ completedDeviceIds: [],
+ failedDeviceIds: [],
+ anomalyThreshold: policy.rollbackOnAnomalyThreshold,
+ startedAt: new Date(),
+ updatedAt: new Date(),
+ };
+
+ this.rollouts.set(rolloutId, rollout);
+ return rollout;
+ }
+
+ /**
+ * Advance the rollout through its state machine:
+ * pending -> canary (deploy to canary devices)
+ * canary -> rolling (anomaly check passes)
+ * canary -> rolled-back (anomaly check fails)
+ * rolling -> complete (deploy to remaining devices)
+ */
+ async advanceRollout(rolloutId: string): Promise<FirmwareRollout> {
+ const rollout = this.getExistingRollout(rolloutId);
+
+ switch (rollout.stage) {
+ case 'pending':
+ return this.transitionPendingToCanary(rollout);
+ case 'canary':
+ return this.transitionCanaryToNextStage(rollout);
+ case 'rolling':
+ return this.transitionRollingToComplete(rollout);
+ default:
+ return rollout;
+ }
+ }
+
+ /**
+ * Force-rollback a rollout regardless of current stage.
+ */
+ rollbackRollout(rolloutId: string): FirmwareRollout {
+ const rollout = this.getExistingRollout(rolloutId);
+ rollout.stage = 'rolled-back';
+ rollout.updatedAt = new Date();
+ return rollout;
+ }
+
+ /**
+ * Retrieve a rollout by ID. Throws if not found.
+ */
+ getRollout(rolloutId: string): FirmwareRollout {
+ return this.getExistingRollout(rolloutId);
+ }
+
+ /**
+ * List rollouts, optionally filtered by fleet ID.
+ */
+ listRollouts(fleetId?: string): FirmwareRollout[] {
+ const all = Array.from(this.rollouts.values());
+ if (fleetId === undefined) return all;
+ return all.filter((r) => r.fleetId === fleetId);
+ }
+
+ // ---------------------------------------------------------------------------
+ // State-machine transitions
+ // ---------------------------------------------------------------------------
+
+ private async transitionPendingToCanary(
+ rollout: FirmwareRollout,
+ ): Promise<FirmwareRollout> {
+ await this.deployToDevices(
+ rollout,
+ rollout.canaryDeviceIds,
+ rollout.firmwareVersion,
+ );
+ rollout.stage = 'canary';
+ rollout.updatedAt = new Date();
+ return rollout;
+ }
+
+ private async transitionCanaryToNextStage(
+ rollout: FirmwareRollout,
+ ): Promise<FirmwareRollout> {
+ for (const deviceId of rollout.canaryDeviceIds) {
+ const score = await this.deps.getDeviceAnomalyScore(deviceId);
+ if (score > rollout.anomalyThreshold) {
+ rollout.stage = 'rolled-back';
+ rollout.updatedAt = new Date();
+ return rollout;
+ }
+ }
+
+ rollout.stage = 'rolling';
+ rollout.updatedAt = new Date();
+ return rollout;
+ }
+
+ private async transitionRollingToComplete(
+ rollout: FirmwareRollout,
+ ): Promise<FirmwareRollout> {
+ const remainingDeviceIds = rollout.targetDeviceIds.filter(
+ (id) => !rollout.canaryDeviceIds.includes(id),
+ );
+
+ await this.deployToDevices(
+ rollout,
+ remainingDeviceIds,
+ rollout.firmwareVersion,
+ );
+
+ rollout.stage = 'complete';
+ rollout.updatedAt = new Date();
+ rollout.completedAt = new Date();
+ return rollout;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ private async deployToDevices(
+ rollout: FirmwareRollout,
+ deviceIds: string[],
+ version: string,
+ ): Promise<void> {
+ for (const deviceId of deviceIds) {
+ const result = await this.deps.deployFirmware(deviceId, version);
+ if (result.success) {
+ rollout.completedDeviceIds.push(deviceId);
+ } else {
+ rollout.failedDeviceIds.push(deviceId);
+ }
+ }
+ }
+
+ private getExistingRollout(rolloutId: string): FirmwareRollout {
+ const rollout = this.rollouts.get(rolloutId);
+ if (!rollout) {
+ throw new Error(`Rollout ${rolloutId} not found`);
+ }
+ return rollout;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/fleet-topology-service.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/fleet-topology-service.ts
new file mode 100644
index 0000000000..85410527ee
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/fleet-topology-service.ts
@@ -0,0 +1,140 @@
+import type {
+ DeviceFleet,
+ FleetTopology,
+ FirmwarePolicy,
+ TelemetryPolicy,
+ HealthThresholds,
+} from '../entities/index.js';
+import type { FleetRepository } from '../repositories/index.js';
+
+export interface CreateFleetOptions {
+ fleetId: string;
+ name: string;
+ description?: string;
+ zoneId: string;
+ topology?: FleetTopology;
+ firmwarePolicy?: Partial<FirmwarePolicy>;
+ telemetryPolicy?: Partial<TelemetryPolicy>;
+ healthThresholds?: Partial<HealthThresholds>;
+}
+
+export interface FleetSummary {
+ fleetId: string;
+ name: string;
+ zoneId: string;
+ deviceCount: number;
+ topology: FleetTopology;
+ createdAt: Date;
+}
+
+const DEFAULT_FIRMWARE_POLICY: FirmwarePolicy = {
+ channel: 'stable',
+ autoUpdate: false,
+ approvalRequired: true,
+ canaryPercentage: 10,
+ canaryDurationMinutes: 30,
+ rollbackOnAnomalyThreshold: 0.8,
+};
+
+const DEFAULT_TELEMETRY_POLICY: TelemetryPolicy = {
+ ingestionIntervalSeconds: 60,
+ retentionDays: 30,
+ anomalyDetectionEnabled: true,
+ anomalyThreshold: 0.7,
+ vectorDimension: 128,
+};
+
+const DEFAULT_HEALTH_THRESHOLDS: HealthThresholds = {
+ maxOfflineMinutes: 10,
+ minUptimeRatio: 0.95,
+ maxConsecutiveAnomalies: 3,
+ minFirmwareCurrency: 0.8,
+};
+
+export class FleetTopologyService {
+ constructor(private readonly repo: FleetRepository) {}
+
+ async createFleet(options: CreateFleetOptions): Promise<DeviceFleet> {
+ const existing = await this.repo.findById(options.fleetId);
+ if (existing) throw new Error(`Fleet ${options.fleetId} already exists`);
+
+ const fleet: DeviceFleet = {
+ fleetId: options.fleetId,
+ name: options.name,
+ description: options.description ?? '',
+ zoneId: options.zoneId,
+ deviceIds: [],
+ topology: options.topology ?? 'star',
+ firmwarePolicy: { ...DEFAULT_FIRMWARE_POLICY, ...options.firmwarePolicy },
+ telemetryPolicy: { ...DEFAULT_TELEMETRY_POLICY, ...options.telemetryPolicy },
+ healthThresholds: { ...DEFAULT_HEALTH_THRESHOLDS, ...options.healthThresholds },
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ };
+
+ await this.repo.save(fleet);
+ return fleet;
+ }
+
+ async getFleet(fleetId: string): Promise<DeviceFleet> {
+ const fleet = await this.repo.findById(fleetId);
+ if (!fleet) throw new Error(`Fleet ${fleetId} not found`);
+ return fleet;
+ }
+
+ async listFleets(): Promise<FleetSummary[]> {
+ const fleets = await this.repo.findAll();
+ return fleets.map((f) => ({
+ fleetId: f.fleetId,
+ name: f.name,
+ zoneId: f.zoneId,
+ deviceCount: f.deviceIds.length,
+ topology: f.topology,
+ createdAt: f.createdAt,
+ }));
+ }
+
+ async addDeviceToFleet(fleetId: string, deviceId: string): Promise<DeviceFleet> {
+ const fleet = await this.getFleet(fleetId);
+ if (fleet.deviceIds.includes(deviceId)) {
+ return fleet;
+ }
+ fleet.deviceIds.push(deviceId);
+ await this.repo.save(fleet);
+ return fleet;
+ }
+
+ async removeDeviceFromFleet(fleetId: string, deviceId: string): Promise<DeviceFleet> {
+ const fleet = await this.getFleet(fleetId);
+ fleet.deviceIds = fleet.deviceIds.filter((id) => id !== deviceId);
+ await this.repo.save(fleet);
+ return fleet;
+ }
+
+ async updateTopology(fleetId: string, topology: FleetTopology): Promise<DeviceFleet> {
+ const fleet = await this.getFleet(fleetId);
+ fleet.topology = topology;
+ await this.repo.save(fleet);
+ return fleet;
+ }
+
+ async updateFirmwarePolicy(
+ fleetId: string,
+ policy: Partial<FirmwarePolicy>,
+ ): Promise<DeviceFleet> {
+ const fleet = await this.getFleet(fleetId);
+ fleet.firmwarePolicy = { ...fleet.firmwarePolicy, ...policy };
+ await this.repo.save(fleet);
+ return fleet;
+ }
+
+ async deleteFleet(fleetId: string): Promise<void> {
+ const deleted = await this.repo.delete(fleetId);
+ if (!deleted) throw new Error(`Fleet ${fleetId} not found`);
+ }
+
+ async getFleetDeviceCount(fleetId: string): Promise<number> {
+ const fleet = await this.getFleet(fleetId);
+ return fleet.deviceIds.length;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/index.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/index.ts
index e4f37f102d..6019571fdd 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/index.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/index.ts
@@ -17,3 +17,42 @@ export {
type MeshPeer,
type MeshTopology,
} from './mesh-service.js';
+
+export {
+ AnomalyDetectionService,
+ type AnomalyDetectionConfig,
+ type TelemetryBaseline,
+} from './anomaly-detection-service.js';
+
+export {
+ TelemetryIngestionService,
+ type TelemetryIngestionDeps,
+ type IngestionResult,
+} from './telemetry-ingestion-service.js';
+
+export {
+ FleetTopologyService,
+ type CreateFleetOptions,
+ type FleetSummary,
+} from './fleet-topology-service.js';
+
+export {
+ FirmwareOrchestrationService,
+ type FirmwareOrchestrationDeps,
+ type FirmwareRollout,
+ type RolloutStage,
+} from './firmware-orchestration-service.js';
+
+export {
+ WitnessVerificationService,
+ type WitnessVerificationDeps,
+ type WitnessVerificationResult,
+ type WitnessEntry,
+ type WitnessGap,
+} from './witness-verification-service.js';
+
+export {
+ SONAIntegrationService,
+ type SONAClient,
+ type SONAIntegrationConfig,
+} from './sona-integration-service.js';
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/sona-integration-service.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/sona-integration-service.ts
new file mode 100644
index 0000000000..f2a8ad1e73
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/sona-integration-service.ts
@@ -0,0 +1,113 @@
+import type { AnomalyDetection, TelemetryReading } from '../entities/telemetry.js';
+import type { TelemetryBaseline } from './anomaly-detection-service.js';
+
+export interface SONAClient {
+ storePattern(key: string, pattern: Record<string, unknown>): Promise<void>;
+ searchPatterns(query: string, limit?: number): Promise<Array<{ key: string; pattern: Record<string, unknown>; score: number }>>;
+ trainTrajectory(trajectoryId: string, steps: Array<{ action: string; reward: number; state: Record<string, unknown> }>): Promise<void>;
+ predict(input: Record<string, unknown>): Promise<{ prediction: string; confidence: number }>;
+}
+
+export interface SONAIntegrationConfig {
+ enabled: boolean;
+ trajectoryNamespace: string;
+ patternNamespace: string;
+ minConfidence: number;
+}
+
+export class SONAIntegrationService {
+ private readonly config: SONAIntegrationConfig;
+ private readonly client: SONAClient | null;
+
+ constructor(client: SONAClient | null, config?: Partial<SONAIntegrationConfig>) {
+ this.client = client;
+ this.config = {
+ enabled: config?.enabled ?? (client !== null),
+ trajectoryNamespace: config?.trajectoryNamespace ?? 'iot-trajectories',
+ patternNamespace: config?.patternNamespace ?? 'iot-patterns',
+ minConfidence: config?.minConfidence ?? 0.6,
+ };
+ }
+
+ get isEnabled(): boolean {
+ return this.config.enabled && this.client !== null;
+ }
+
+ async learnAnomalyPattern(anomaly: AnomalyDetection, baseline: TelemetryBaseline | undefined): Promise<void> {
+ if (!this.isEnabled || !this.client) return;
+
+ await this.client.storePattern(`anomaly:${anomaly.type}:${anomaly.deviceId}`, {
+ type: anomaly.type,
+ score: anomaly.score,
+ action: anomaly.suggestedAction,
+ deviceId: anomaly.deviceId,
+ baselineSamples: baseline?.sampleCount ?? 0,
+ timestamp: new Date().toISOString(),
+ });
+ }
+
+ async learnBaselineShift(
+ deviceId: string,
+ oldBaseline: TelemetryBaseline | undefined,
+ newBaseline: TelemetryBaseline,
+ ): Promise<void> {
+ if (!this.isEnabled || !this.client) return;
+
+ const drift = oldBaseline
+ ? newBaseline.meanVector.map((v, i) => Math.abs(v - oldBaseline.meanVector[i]))
+ : newBaseline.meanVector.map(() => 0);
+
+ await this.client.storePattern(`baseline-shift:${deviceId}`, {
+ deviceId,
+ driftVector: drift,
+ maxDrift: Math.max(...drift),
+ oldSamples: oldBaseline?.sampleCount ?? 0,
+ newSamples: newBaseline.sampleCount,
+ timestamp: new Date().toISOString(),
+ });
+ }
+
+ async recordTelemetryTrajectory(
+ deviceId: string,
+ readings: TelemetryReading[],
+ anomalies: AnomalyDetection[],
+ ): Promise<void> {
+ if (!this.isEnabled || !this.client) return;
+
+ const steps = readings.map((r) => {
+ const anomaly = anomalies.find((a) => a.readingId === r.readingId);
+ return {
+ action: anomaly ? `anomaly:${anomaly.type}` : 'normal',
+ reward: anomaly ? -anomaly.score : 1.0,
+ state: {
+ vector: r.vector,
+ anomalyScore: r.anomalyScore,
+ deviceId: r.deviceId,
+ },
+ };
+ });
+
+ const trajectoryId = `${this.config.trajectoryNamespace}:${deviceId}:${Date.now()}`;
+ await this.client.trainTrajectory(trajectoryId, steps);
+ }
+
+ async predictAnomalyRisk(reading: TelemetryReading): Promise<{ risk: string; confidence: number } | null> {
+ if (!this.isEnabled || !this.client) return null;
+
+ const result = await this.client.predict({
+ vector: reading.vector,
+ deviceId: reading.deviceId,
+ anomalyScore: reading.anomalyScore,
+ });
+
+ if (result.confidence < this.config.minConfidence) return null;
+
+ return { risk: result.prediction, confidence: result.confidence };
+ }
+
+ async findSimilarAnomalyPatterns(anomaly: AnomalyDetection, limit = 5): Promise<Array<{ key: string; pattern: Record<string, unknown>; score: number }>> {
+ if (!this.isEnabled || !this.client) return [];
+
+ return this.client.searchPatterns(`anomaly:${anomaly.type} score:${anomaly.score.toFixed(2)}`, limit);
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/telemetry-ingestion-service.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/telemetry-ingestion-service.ts
new file mode 100644
index 0000000000..df161249bd
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/telemetry-ingestion-service.ts
@@ -0,0 +1,61 @@
+import type { TelemetryReading, AnomalyDetection } from '../entities/index.js';
+import type { AnomalyDetectionService, TelemetryBaseline } from './anomaly-detection-service.js';
+
+export interface TelemetryIngestionDeps {
+ queryDeviceStore: (
+ deviceId: string,
+ vector: number[],
+ k: number,
+ ) => Promise<Array<{ id: number | string; distance: number; metadata?: Record<string, unknown> }>>;
+ getStoreStatus: (deviceId: string) => Promise<{ total_vectors: number; dimension: number }>;
+}
+
+export interface IngestionResult {
+ deviceId: string;
+ readingsProcessed: number;
+ anomaliesDetected: number;
+ anomalies: AnomalyDetection[];
+ baseline?: TelemetryBaseline;
+}
+
+export class TelemetryIngestionService {
+ constructor(
+ private readonly deps: TelemetryIngestionDeps,
+ private readonly anomalyDetector: AnomalyDetectionService,
+ ) {}
+
+ /**
+ * Process a batch of telemetry readings: run anomaly detection on each,
+ * and return the results.
+ */
+ processBatch(deviceId: string, readings: TelemetryReading[]): IngestionResult {
+ const anomalies: AnomalyDetection[] = [];
+
+ for (const reading of readings) {
+ const detection = this.anomalyDetector.detect(reading);
+ if (this.anomalyDetector.isAnomalous(detection)) {
+ anomalies.push(detection);
+ }
+ }
+
+ return {
+ deviceId,
+ readingsProcessed: readings.length,
+ anomaliesDetected: anomalies.length,
+ anomalies,
+ baseline: this.anomalyDetector.getBaseline(deviceId),
+ };
+ }
+
+ /**
+ * Compute or refresh the baseline for a device from its recent readings.
+ */
+ refreshBaseline(deviceId: string, readings: TelemetryReading[]): TelemetryBaseline {
+ return this.anomalyDetector.computeBaseline(deviceId, readings);
+ }
+
+ /** Get the current baseline for a device. */
+ getBaseline(deviceId: string): TelemetryBaseline | undefined {
+ return this.anomalyDetector.getBaseline(deviceId);
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/witness-verification-service.ts b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/witness-verification-service.ts
new file mode 100644
index 0000000000..8d856bd76b
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/domain/services/witness-verification-service.ts
@@ -0,0 +1,108 @@
+export interface WitnessEntry {
+ epoch: number;
+ action?: string;
+ signature?: string;
+ timestamp?: string;
+ hash?: string;
+ previous_hash?: string;
+}
+
+export interface WitnessGap {
+ deviceId: string;
+ fromEpoch: number;
+ toEpoch: number;
+ missingCount: number;
+}
+
+export interface WitnessVerificationResult {
+ deviceId: string;
+ chainLength: number;
+ verified: boolean;
+ gaps: WitnessGap[];
+ headEpoch: number;
+ headHash: string;
+ integrityScore: number;
+}
+
+export interface WitnessVerificationDeps {
+ getWitnessChain: (deviceId: string) => Promise<{
+ length?: number;
+ head?: string;
+ entries?: Array<{ epoch: number; action?: string; signature?: string; timestamp?: string; hash?: string; previous_hash?: string }>;
+ }>;
+}
+
+export class WitnessVerificationService {
+ constructor(private readonly deps: WitnessVerificationDeps) {}
+
+ async verifyChain(deviceId: string): Promise<WitnessVerificationResult> {
+ const chain = await this.deps.getWitnessChain(deviceId);
+ const entries = chain.entries ?? [];
+ const chainLength = chain.length ?? entries.length ?? 0;
+
+ if (entries.length === 0) {
+ return {
+ deviceId,
+ chainLength,
+ verified: true,
+ gaps: [],
+ headEpoch: 0,
+ headHash: chain.head ?? '',
+ integrityScore: chainLength > 0 ? 0.5 : 1.0,
+ };
+ }
+
+ const sorted = [...entries].sort((a, b) => a.epoch - b.epoch);
+ const gaps = this.detectGaps(deviceId, sorted);
+ const hashValid = this.verifyHashChain(sorted);
+
+ const gapRatio = gaps.length > 0
+ ? gaps.reduce((sum, g) => sum + g.missingCount, 0) / chainLength
+ : 0;
+
+ const integrityScore = Math.max(0, 1 - gapRatio) * (hashValid ? 1 : 0.5);
+
+ return {
+ deviceId,
+ chainLength,
+ verified: gaps.length === 0 && hashValid,
+ gaps,
+ headEpoch: sorted[sorted.length - 1].epoch,
+ headHash: chain.head ?? sorted[sorted.length - 1].hash ?? '',
+ integrityScore,
+ };
+ }
+
+ private detectGaps(
+ deviceId: string,
+ sorted: Array<{ epoch: number }>,
+ ): WitnessGap[] {
+ const gaps: WitnessGap[] = [];
+
+ for (let i = 1; i < sorted.length; i++) {
+ const expected = sorted[i - 1].epoch + 1;
+ const actual = sorted[i].epoch;
+ if (actual > expected) {
+ gaps.push({
+ deviceId,
+ fromEpoch: sorted[i - 1].epoch,
+ toEpoch: actual,
+ missingCount: actual - expected,
+ });
+ }
+ }
+
+ return gaps;
+ }
+
+ private verifyHashChain(
+ sorted: Array<{ hash?: string; previous_hash?: string }>,
+ ): boolean {
+ for (let i = 1; i < sorted.length; i++) {
+ if (sorted[i].previous_hash && sorted[i - 1].hash && sorted[i].previous_hash !== sorted[i - 1].hash) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/index.ts b/v3/@claude-flow/plugin-iot-cognitum/src/index.ts
index 7fe769037d..c4b55d1b5f 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/index.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/index.ts
@@ -3,5 +3,23 @@ export { IoTCoordinator } from './application/iot-coordinator.js';
export type { IoTCoordinatorConfig, IoTCoordinatorCallbacks } from './application/iot-coordinator.js';
export { SeedClientFactory } from './infrastructure/seed-client-factory.js';
export type { SeedClientFactoryConfig } from './infrastructure/seed-client-factory.js';
+export { HealthProbeWorker } from './workers/health-probe-worker.js';
+export type { HealthProbeConfig } from './workers/health-probe-worker.js';
+export { TelemetryIngestWorker } from './workers/telemetry-ingest-worker.js';
+export type { TelemetryIngestConfig } from './workers/telemetry-ingest-worker.js';
+export { AnomalyScanWorker } from './workers/anomaly-scan-worker.js';
+export type { AnomalyScanConfig } from './workers/anomaly-scan-worker.js';
+export { MeshSyncWorker } from './workers/mesh-sync-worker.js';
+export type { MeshSyncConfig } from './workers/mesh-sync-worker.js';
+export { FirmwareWatchWorker } from './workers/firmware-watch-worker.js';
+export type { FirmwareWatchConfig } from './workers/firmware-watch-worker.js';
+export { WitnessAuditWorker } from './workers/witness-audit-worker.js';
+export type { WitnessAuditConfig } from './workers/witness-audit-worker.js';
export * from './domain/entities/index.js';
export * from './domain/services/index.js';
+export * from './domain/repositories/index.js';
+export { InMemoryDeviceRepository } from './infrastructure/in-memory-device-repository.js';
+export { InMemoryTrustHistoryRepository } from './infrastructure/in-memory-trust-history-repository.js';
+export { InMemoryFleetRepository } from './infrastructure/in-memory-fleet-repository.js';
+export { AgentDBTelemetryRepository } from './infrastructure/agentdb-telemetry-repository.js';
+export type { AgentDBTelemetryConfig, AgentDBClient } from './infrastructure/agentdb-telemetry-repository.js';
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/agentdb-telemetry-repository.ts b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/agentdb-telemetry-repository.ts
new file mode 100644
index 0000000000..5b3537370f
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/agentdb-telemetry-repository.ts
@@ -0,0 +1,131 @@
+import type { TelemetryReading, AnomalyDetection } from '../domain/entities/telemetry.js';
+import type { TelemetryRepository } from '../domain/repositories/telemetry-repository.js';
+
+export interface AgentDBTelemetryConfig {
+ namespace: string;
+ hnswM?: number;
+ hnswEfConstruction?: number;
+ hnswEfSearch?: number;
+}
+
+export interface AgentDBClient {
+ store(key: string, value: string, options?: { namespace?: string; tags?: string[] }): Promise<void>;
+ search(query: string, options?: { namespace?: string; limit?: number }): Promise<Array<{ key: string; value: string; score: number }>>;
+ list(options?: { namespace?: string; limit?: number }): Promise<Array<{ key: string; value: string }>>;
+ retrieve(key: string, options?: { namespace?: string }): Promise<string | null>;
+ delete(key: string, options?: { namespace?: string }): Promise<boolean>;
+}
+
+export class AgentDBTelemetryRepository implements TelemetryRepository {
+ private readonly config: Required<AgentDBTelemetryConfig>;
+ private readonly client: AgentDBClient;
+
+ constructor(client: AgentDBClient, config?: Partial<AgentDBTelemetryConfig>) {
+ this.client = client;
+ this.config = {
+ namespace: config?.namespace ?? 'iot-telemetry',
+ hnswM: config?.hnswM ?? 16,
+ hnswEfConstruction: config?.hnswEfConstruction ?? 200,
+ hnswEfSearch: config?.hnswEfSearch ?? 50,
+ };
+ }
+
+ async store(reading: TelemetryReading): Promise<void> {
+ const key = `reading:${reading.deviceId}:${reading.readingId}`;
+ await this.client.store(key, JSON.stringify(this.serializeReading(reading)), {
+ namespace: this.config.namespace,
+ tags: [`device:${reading.deviceId}`, `fleet:${reading.fleetId}`],
+ });
+ }
+
+ async storeBatch(readings: TelemetryReading[]): Promise<number> {
+ let stored = 0;
+ for (const reading of readings) {
+ await this.store(reading);
+ stored++;
+ }
+ return stored;
+ }
+
+ async findByDevice(deviceId: string, limit = 100): Promise<TelemetryReading[]> {
+ const results = await this.client.search(`device:${deviceId}`, {
+ namespace: this.config.namespace,
+ limit,
+ });
+ return results
+ .map((r) => this.deserializeReading(r.value))
+ .filter((r): r is TelemetryReading => r !== null);
+ }
+
+ async searchSimilar(vector: number[], k: number, deviceId?: string): Promise<TelemetryReading[]> {
+ const query = deviceId
+ ? `vector:${vector.slice(0, 4).join(',')} device:${deviceId}`
+ : `vector:${vector.slice(0, 4).join(',')}`;
+ const results = await this.client.search(query, {
+ namespace: this.config.namespace,
+ limit: k,
+ });
+ return results
+ .map((r) => this.deserializeReading(r.value))
+ .filter((r): r is TelemetryReading => r !== null);
+ }
+
+ async storeAnomaly(anomaly: AnomalyDetection): Promise<void> {
+ const key = `anomaly:${anomaly.deviceId}:${anomaly.readingId}`;
+ await this.client.store(key, JSON.stringify(anomaly), {
+ namespace: `${this.config.namespace}-anomalies`,
+ tags: [`device:${anomaly.deviceId}`, `type:${anomaly.type}`, `action:${anomaly.suggestedAction}`],
+ });
+ }
+
+ async findAnomalies(deviceId: string, limit = 50): Promise<AnomalyDetection[]> {
+ const results = await this.client.search(`device:${deviceId}`, {
+ namespace: `${this.config.namespace}-anomalies`,
+ limit,
+ });
+ return results
+ .map((r) => {
+ try { return JSON.parse(r.value) as AnomalyDetection; } catch { return null; }
+ })
+ .filter((a): a is AnomalyDetection => a !== null);
+ }
+
+ async count(deviceId?: string): Promise<number> {
+ const query = deviceId ? `device:${deviceId}` : '*';
+ const results = await this.client.search(query, {
+ namespace: this.config.namespace,
+ limit: 10000,
+ });
+ return results.length;
+ }
+
+ async deleteByDevice(deviceId: string): Promise<number> {
+ const readings = await this.findByDevice(deviceId, 10000);
+ let deleted = 0;
+ for (const reading of readings) {
+ const key = `reading:${reading.deviceId}:${reading.readingId}`;
+ const ok = await this.client.delete(key, { namespace: this.config.namespace });
+ if (ok) deleted++;
+ }
+ return deleted;
+ }
+
+ private serializeReading(reading: TelemetryReading): Record<string, unknown> {
+ return {
+ ...reading,
+ timestamp: reading.timestamp.toISOString(),
+ };
+ }
+
+ private deserializeReading(raw: string): TelemetryReading | null {
+ try {
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
+ return {
+ ...parsed,
+ timestamp: new Date(parsed['timestamp'] as string),
+ } as TelemetryReading;
+ } catch {
+ return null;
+ }
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-device-repository.ts b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-device-repository.ts
new file mode 100644
index 0000000000..f00170168b
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-device-repository.ts
@@ -0,0 +1,38 @@
+import type { DeviceAgent } from '../domain/entities/index.js';
+import type { DeviceRepository } from '../domain/repositories/index.js';
+
+export class InMemoryDeviceRepository implements DeviceRepository {
+ private readonly devices = new Map<string, DeviceAgent>();
+
+ async save(device: DeviceAgent): Promise<void> {
+ this.devices.set(device.deviceId, device);
+ }
+
+ async findById(deviceId: string): Promise<DeviceAgent | null> {
+ return this.devices.get(deviceId) ?? null;
+ }
+
+ async findByFleet(fleetId: string): Promise<DeviceAgent[]> {
+ return [...this.devices.values()].filter(
+ (d) => d.fleetId === fleetId,
+ );
+ }
+
+ async findByZone(zoneId: string): Promise<DeviceAgent[]> {
+ return [...this.devices.values()].filter(
+ (d) => d.zoneId === zoneId,
+ );
+ }
+
+ async findAll(): Promise<DeviceAgent[]> {
+ return [...this.devices.values()];
+ }
+
+ async delete(deviceId: string): Promise<boolean> {
+ return this.devices.delete(deviceId);
+ }
+
+ async count(): Promise<number> {
+ return this.devices.size;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-fleet-repository.ts b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-fleet-repository.ts
new file mode 100644
index 0000000000..aea4bb286c
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-fleet-repository.ts
@@ -0,0 +1,26 @@
+import type { DeviceFleet } from '../domain/entities/index.js';
+import type { FleetRepository } from '../domain/repositories/index.js';
+
+export class InMemoryFleetRepository implements FleetRepository {
+ private readonly fleets = new Map<string, DeviceFleet>();
+
+ async save(fleet: DeviceFleet): Promise<void> {
+ this.fleets.set(fleet.fleetId, { ...fleet, updatedAt: new Date() });
+ }
+
+ async findById(fleetId: string): Promise<DeviceFleet | undefined> {
+ return this.fleets.get(fleetId);
+ }
+
+ async findAll(): Promise<DeviceFleet[]> {
+ return Array.from(this.fleets.values());
+ }
+
+ async delete(fleetId: string): Promise<boolean> {
+ return this.fleets.delete(fleetId);
+ }
+
+ async count(): Promise<number> {
+ return this.fleets.size;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-trust-history-repository.ts b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-trust-history-repository.ts
new file mode 100644
index 0000000000..24b2bf946d
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/in-memory-trust-history-repository.ts
@@ -0,0 +1,44 @@
+import type { DeviceTrustLevel } from '../domain/entities/index.js';
+import type {
+ TrustHistoryEntry,
+ TrustHistoryRepository,
+} from '../domain/repositories/index.js';
+
+export class InMemoryTrustHistoryRepository
+ implements TrustHistoryRepository
+{
+ private readonly entries: TrustHistoryEntry[] = [];
+
+ async append(entry: TrustHistoryEntry): Promise<void> {
+ this.entries.push(entry);
+ }
+
+ async findByDevice(
+ deviceId: string,
+ limit?: number,
+ ): Promise<TrustHistoryEntry[]> {
+ const matches = this.entries.filter((e) => e.deviceId === deviceId);
+ return limit !== undefined ? matches.slice(-limit) : matches;
+ }
+
+ async findByLevel(
+ level: DeviceTrustLevel,
+ ): Promise<TrustHistoryEntry[]> {
+ return this.entries.filter((e) => e.newLevel === level);
+ }
+
+ async deleteByDevice(deviceId: string): Promise<number> {
+ let removed = 0;
+ for (let i = this.entries.length - 1; i >= 0; i--) {
+ if (this.entries[i].deviceId === deviceId) {
+ this.entries.splice(i, 1);
+ removed++;
+ }
+ }
+ return removed;
+ }
+
+ async count(): Promise<number> {
+ return this.entries.length;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/index.ts b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/index.ts
index 6affd33378..c059fe7651 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/index.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/infrastructure/index.ts
@@ -2,3 +2,12 @@ export {
SeedClientFactory,
type SeedClientFactoryConfig,
} from './seed-client-factory.js';
+
+export { InMemoryDeviceRepository } from './in-memory-device-repository.js';
+export { InMemoryTrustHistoryRepository } from './in-memory-trust-history-repository.js';
+export { InMemoryFleetRepository } from './in-memory-fleet-repository.js';
+export {
+ AgentDBTelemetryRepository,
+ type AgentDBTelemetryConfig,
+ type AgentDBClient,
+} from './agentdb-telemetry-repository.js';
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/mcp-tools.ts b/v3/@claude-flow/plugin-iot-cognitum/src/mcp-tools.ts
index 82002c5272..27032d35cc 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/mcp-tools.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/mcp-tools.ts
@@ -111,6 +111,55 @@ export function createMcpTools(
},
},
+ {
+ name: 'iot_device_pair',
+ description: 'Pair with a registered device to establish mutual trust',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ deviceId: { type: 'string', description: 'Device identifier' },
+ clientName: { type: 'string', description: 'Client name for the pairing session' },
+ },
+ required: ['deviceId', 'clientName'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const device = await coordinator.pairDevice(
+ params['deviceId'] as string,
+ params['clientName'] as string,
+ );
+ return textResult(JSON.stringify(device, null, 2));
+ } catch (err) {
+ return textResult(`Pairing failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_device_unpair',
+ description: 'Unpair from a registered device',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ deviceId: { type: 'string', description: 'Device identifier' },
+ },
+ required: ['deviceId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const device = await coordinator.unpairDevice(params['deviceId'] as string);
+ return textResult(JSON.stringify(device, null, 2));
+ } catch (err) {
+ return textResult(`Unpair failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+
// -- Vector store --------------------------------------------------------
{
name: 'iot_store_query',
@@ -288,5 +337,385 @@ export function createMcpTools(
}
},
},
+
+ // -- Firmware orchestration (Phase 3) ---------------------------------------
+ {
+ name: 'iot_firmware_rollout_create',
+ description: 'Create a firmware rollout for a fleet',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ fleetId: { type: 'string', description: 'Fleet identifier' },
+ firmwareVersion: { type: 'string', description: 'Target firmware version' },
+ },
+ required: ['fleetId', 'firmwareVersion'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const rollout = await coordinator.createFirmwareRollout(
+ params['fleetId'] as string,
+ params['firmwareVersion'] as string,
+ );
+ return textResult(JSON.stringify(rollout, null, 2));
+ } catch (err) {
+ return textResult(`Rollout create failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_firmware_rollout_advance',
+ description: 'Advance a firmware rollout to next stage',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ rolloutId: { type: 'string', description: 'Rollout identifier' },
+ },
+ required: ['rolloutId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const rollout = await coordinator.advanceFirmwareRollout(params['rolloutId'] as string);
+ return textResult(JSON.stringify(rollout, null, 2));
+ } catch (err) {
+ return textResult(`Rollout advance failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_firmware_rollout_rollback',
+ description: 'Force rollback a firmware rollout',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ rolloutId: { type: 'string', description: 'Rollout identifier' },
+ },
+ required: ['rolloutId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const rollout = coordinator.rollbackFirmwareRollout(params['rolloutId'] as string);
+ return textResult(JSON.stringify(rollout, null, 2));
+ } catch (err) {
+ return textResult(`Rollout rollback failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_firmware_rollout_status',
+ description: 'Get firmware rollout status',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ rolloutId: { type: 'string', description: 'Rollout identifier' },
+ },
+ required: ['rolloutId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const rollout = coordinator.getFirmwareRollout(params['rolloutId'] as string);
+ return textResult(JSON.stringify(rollout, null, 2));
+ } catch (err) {
+ return textResult(`Rollout status failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_firmware_rollout_list',
+ description: 'List firmware rollouts',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ fleetId: { type: 'string', description: 'Optional fleet filter' },
+ },
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const rollouts = coordinator.listFirmwareRollouts(params['fleetId'] as string | undefined);
+ return textResult(JSON.stringify(rollouts, null, 2));
+ } catch (err) {
+ return textResult(`Rollout list failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+
+ // -- Fleet management (Phase 3) --------------------------------------------
+ {
+ name: 'iot_fleet_create',
+ description: 'Create a new device fleet',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ fleetId: { type: 'string', description: 'Fleet identifier' },
+ name: { type: 'string', description: 'Fleet display name' },
+ zoneId: { type: 'string', description: 'IEC 62443 security zone' },
+ topology: { type: 'string', enum: ['star', 'mesh', 'hierarchical', 'ring'], description: 'Fleet topology' },
+ description: { type: 'string', description: 'Fleet description' },
+ },
+ required: ['fleetId', 'name', 'zoneId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const fleet = await coordinator.createFleet({
+ fleetId: params['fleetId'] as string,
+ name: params['name'] as string,
+ zoneId: params['zoneId'] as string,
+ topology: params['topology'] as any,
+ description: params['description'] as string | undefined,
+ });
+ return textResult(JSON.stringify(fleet, null, 2));
+ } catch (err) {
+ return textResult(`Fleet create failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_fleet_get',
+ description: 'Get fleet details',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ fleetId: { type: 'string', description: 'Fleet identifier' },
+ },
+ required: ['fleetId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const fleet = await coordinator.getFleet(params['fleetId'] as string);
+ return textResult(JSON.stringify(fleet, null, 2));
+ } catch (err) {
+ return textResult(`Fleet get failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_fleet_list',
+ description: 'List all fleets',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {},
+ },
+ handler: async () => {
+ try {
+ const coordinator = requireCoordinator();
+ const fleets = await coordinator.listFleets();
+ return textResult(JSON.stringify(fleets, null, 2));
+ } catch (err) {
+ return textResult(`Fleet list failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_fleet_add_device',
+ description: 'Add a registered device to a fleet',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ fleetId: { type: 'string', description: 'Fleet identifier' },
+ deviceId: { type: 'string', description: 'Device identifier' },
+ },
+ required: ['fleetId', 'deviceId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const fleet = await coordinator.addDeviceToFleet(
+ params['fleetId'] as string,
+ params['deviceId'] as string,
+ );
+ return textResult(JSON.stringify(fleet, null, 2));
+ } catch (err) {
+ return textResult(`Fleet add device failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_fleet_remove_device',
+ description: 'Remove a device from a fleet',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ fleetId: { type: 'string', description: 'Fleet identifier' },
+ deviceId: { type: 'string', description: 'Device identifier' },
+ },
+ required: ['fleetId', 'deviceId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const fleet = await coordinator.removeDeviceFromFleet(
+ params['fleetId'] as string,
+ params['deviceId'] as string,
+ );
+ return textResult(JSON.stringify(fleet, null, 2));
+ } catch (err) {
+ return textResult(`Fleet remove device failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_fleet_delete',
+ description: 'Delete a fleet',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ fleetId: { type: 'string', description: 'Fleet identifier' },
+ },
+ required: ['fleetId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ await coordinator.deleteFleet(params['fleetId'] as string);
+ return textResult(`Fleet ${params['fleetId']} deleted`);
+ } catch (err) {
+ return textResult(`Fleet delete failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+
+ // -- Telemetry anomaly detection (Phase 2) --------------------------------
+ {
+ name: 'iot_telemetry_anomalies',
+ description: 'Detect anomalies in device telemetry readings',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ deviceId: { type: 'string', description: 'Device identifier' },
+ readings: {
+ type: 'array',
+ description: 'Telemetry readings to analyze',
+ items: {
+ type: 'object',
+ properties: {
+ readingId: { type: 'string' },
+ vector: { type: 'array', items: { type: 'number' } },
+ rawMetrics: { type: 'object' },
+ },
+ required: ['readingId', 'vector'],
+ },
+ },
+ },
+ required: ['deviceId', 'readings'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const deviceId = params['deviceId'] as string;
+ const rawReadings = params['readings'] as Array<{
+ readingId: string;
+ vector: number[];
+ rawMetrics?: Record<string, number>;
+ }>;
+ const readings = rawReadings.map((r) => ({
+ readingId: r.readingId,
+ deviceId,
+ fleetId: '',
+ timestamp: new Date(),
+ vector: r.vector,
+ rawMetrics: r.rawMetrics ?? {},
+ anomalyScore: 0,
+ metadata: {},
+ }));
+ const result = coordinator.detectAnomalies(deviceId, readings);
+ return textResult(JSON.stringify(result, null, 2));
+ } catch (err) {
+ return textResult(`Anomaly detection failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_telemetry_baseline',
+ description: 'Compute or retrieve telemetry baseline for a device',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ deviceId: { type: 'string', description: 'Device identifier' },
+ action: {
+ type: 'string',
+ enum: ['compute', 'get'],
+ description: 'Compute new baseline or get existing',
+ },
+ },
+ required: ['deviceId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const deviceId = params['deviceId'] as string;
+ const action = (params['action'] as string) ?? 'get';
+
+ if (action === 'get') {
+ const baseline = coordinator.getBaseline(deviceId);
+ if (!baseline) {
+ return textResult(JSON.stringify({ deviceId, status: 'no-baseline' }));
+ }
+ return textResult(JSON.stringify(baseline, null, 2));
+ }
+
+ return textResult(JSON.stringify({
+ deviceId,
+ status: 'compute-requires-readings',
+ hint: 'Use iot_telemetry_anomalies with readings to build baseline first',
+ }));
+ } catch (err) {
+ return textResult(`Baseline failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
+ {
+ name: 'iot_witness_verify',
+ description: 'Verify witness chain integrity for a device — detects epoch gaps and hash chain breaks',
+ pluginName: '@claude-flow/plugin-iot-cognitum',
+ version: '1.0.0-alpha.1',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ deviceId: { type: 'string', description: 'Device identifier' },
+ },
+ required: ['deviceId'],
+ },
+ handler: async (params) => {
+ try {
+ const coordinator = requireCoordinator();
+ const result = await coordinator.verifyWitnessChain(params['deviceId'] as string);
+ return textResult(JSON.stringify(result, null, 2));
+ } catch (err) {
+ return textResult(`Witness verification failed: ${(err as Error).message}`, true);
+ }
+ },
+ },
];
}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/plugin.ts b/v3/@claude-flow/plugin-iot-cognitum/src/plugin.ts
index f81c3e2cd1..7cf6d8a1df 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/plugin.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/plugin.ts
@@ -7,6 +7,15 @@ import type {
} from '@claude-flow/shared/src/plugin-interface.js';
import { IoTCoordinator } from './application/iot-coordinator.js';
+import { HealthProbeWorker } from './workers/health-probe-worker.js';
+import { TelemetryIngestWorker } from './workers/telemetry-ingest-worker.js';
+import { AnomalyScanWorker } from './workers/anomaly-scan-worker.js';
+import { MeshSyncWorker } from './workers/mesh-sync-worker.js';
+import { FirmwareWatchWorker } from './workers/firmware-watch-worker.js';
+import { WitnessAuditWorker } from './workers/witness-audit-worker.js';
+import { InMemoryDeviceRepository } from './infrastructure/in-memory-device-repository.js';
+import { InMemoryTrustHistoryRepository } from './infrastructure/in-memory-trust-history-repository.js';
+import { InMemoryFleetRepository } from './infrastructure/in-memory-fleet-repository.js';
import { createMcpTools } from './mcp-tools.js';
import { createCliCommands } from './cli-commands.js';
@@ -18,6 +27,12 @@ export class IoTCognitumPlugin implements ClaudeFlowPlugin {
readonly dependencies = ['@claude-flow/shared'];
private coordinator: IoTCoordinator | null = null;
+ private healthProbe: HealthProbeWorker | null = null;
+ private telemetryIngest: TelemetryIngestWorker | null = null;
+ private anomalyScan: AnomalyScanWorker | null = null;
+ private meshSync: MeshSyncWorker | null = null;
+ private firmwareWatch: FirmwareWatchWorker | null = null;
+ private witnessAudit: WitnessAuditWorker | null = null;
private context: PluginContext | null = null;
async initialize(context: PluginContext): Promise<void> {
@@ -31,6 +46,9 @@ export class IoTCognitumPlugin implements ClaudeFlowPlugin {
defaultFleetId,
defaultZoneId,
defaultTls: { insecure },
+ deviceRepository: new InMemoryDeviceRepository(),
+ trustHistoryRepository: new InMemoryTrustHistoryRepository(),
+ fleetRepository: new InMemoryFleetRepository(),
}, {
onDeviceRegistered: (device) => {
context.logger.info(`Device registered: ${device.deviceId} at ${device.endpoint}`);
@@ -43,10 +61,113 @@ export class IoTCognitumPlugin implements ClaudeFlowPlugin {
});
context.services.register('iot:coordinator', this.coordinator);
+
+ const healthIntervalMs = (config['healthIntervalMs'] as number) ?? 30_000;
+ this.healthProbe = new HealthProbeWorker(this.coordinator, {
+ intervalMs: healthIntervalMs,
+ onDeviceOffline: (deviceId) => {
+ context.logger.warn(`Device offline: ${deviceId}`);
+ context.eventBus.emit('iot:device-offline', { deviceId });
+ },
+ onDeviceOnline: (deviceId) => {
+ context.logger.info(`Device back online: ${deviceId}`);
+ context.eventBus.emit('iot:device-online', { deviceId });
+ },
+ });
+ this.healthProbe.start();
+
+ const telemetryIntervalMs = (config['telemetryIntervalMs'] as number) ?? 60_000;
+ this.telemetryIngest = new TelemetryIngestWorker(this.coordinator, {
+ intervalMs: telemetryIntervalMs,
+ onIngestionComplete: (deviceId, vectorCount) => {
+ context.logger.debug(`Telemetry ingest for ${deviceId}: ${vectorCount} vectors`);
+ },
+ onIngestionError: (deviceId, error) => {
+ context.logger.warn(`Telemetry ingest error for ${deviceId}: ${error.message}`);
+ },
+ });
+ this.telemetryIngest.start();
+
+ const anomalyScanIntervalMs = (config['anomalyScanIntervalMs'] as number) ?? 300_000;
+ this.anomalyScan = new AnomalyScanWorker(this.coordinator, {
+ intervalMs: anomalyScanIntervalMs,
+ onAnomalyDetected: (deviceId, score) => {
+ context.logger.warn(`Anomaly detected on ${deviceId}: trust score ${score.toFixed(3)}`);
+ context.eventBus.emit('iot:anomaly-detected', { deviceId, score });
+ },
+ onScanError: (deviceId, error) => {
+ context.logger.warn(`Anomaly scan error for ${deviceId}: ${error.message}`);
+ },
+ });
+ this.anomalyScan.start();
+
+ const meshSyncIntervalMs = (config['meshSyncIntervalMs'] as number) ?? 120_000;
+ this.meshSync = new MeshSyncWorker(this.coordinator, {
+ intervalMs: meshSyncIntervalMs,
+ onMeshPartition: (deviceId, peerCount) => {
+ context.logger.warn(`Mesh partition detected for ${deviceId}: ${peerCount} peers`);
+ context.eventBus.emit('iot:mesh-partition', { deviceId, peerCount });
+ },
+ onSyncError: (deviceId, error) => {
+ context.logger.warn(`Mesh sync error for ${deviceId}: ${error.message}`);
+ },
+ });
+ this.meshSync.start();
+
+ const firmwareWatchIntervalMs = (config['firmwareWatchIntervalMs'] as number) ?? 300_000;
+ this.firmwareWatch = new FirmwareWatchWorker(this.coordinator, {
+ intervalMs: firmwareWatchIntervalMs,
+ onVersionMismatch: (deviceId, expected, actual) => {
+ context.logger.warn(`Firmware mismatch on ${deviceId}: expected ${expected}, got ${actual}`);
+ context.eventBus.emit('iot:firmware-mismatch', { deviceId, expected, actual });
+ },
+ onWatchError: (deviceId, error) => {
+ context.logger.warn(`Firmware watch error for ${deviceId}: ${error.message}`);
+ },
+ });
+ this.firmwareWatch.start();
+
+ const witnessAuditIntervalMs = (config['witnessAuditIntervalMs'] as number) ?? 600_000;
+ this.witnessAudit = new WitnessAuditWorker(this.coordinator, {
+ intervalMs: witnessAuditIntervalMs,
+ onGapDetected: (deviceId, fromEpoch, toEpoch) => {
+ context.logger.warn(`Witness chain gap on ${deviceId}: epoch ${fromEpoch} → ${toEpoch}`);
+ context.eventBus.emit('iot:witness-gap', { deviceId, fromEpoch, toEpoch });
+ },
+ onAuditError: (deviceId, error) => {
+ context.logger.warn(`Witness audit error for ${deviceId}: ${error.message}`);
+ },
+ });
+ this.witnessAudit.start();
+
context.logger.info('IoT Cognitum plugin initialized');
}
async shutdown(): Promise<void> {
+ if (this.witnessAudit) {
+ this.witnessAudit.stop();
+ this.witnessAudit = null;
+ }
+ if (this.firmwareWatch) {
+ this.firmwareWatch.stop();
+ this.firmwareWatch = null;
+ }
+ if (this.meshSync) {
+ this.meshSync.stop();
+ this.meshSync = null;
+ }
+ if (this.anomalyScan) {
+ this.anomalyScan.stop();
+ this.anomalyScan = null;
+ }
+ if (this.telemetryIngest) {
+ this.telemetryIngest.stop();
+ this.telemetryIngest = null;
+ }
+ if (this.healthProbe) {
+ this.healthProbe.stop();
+ this.healthProbe = null;
+ }
if (this.coordinator) {
await this.coordinator.shutdown();
this.coordinator = null;
@@ -82,6 +203,57 @@ export class IoTCognitumPlugin implements ClaudeFlowPlugin {
requiredCapabilities: ['iot:discover', 'iot:register'],
metadata: { trustAware: true, meshAware: true },
},
+ {
+ type: 'telemetry-analyzer',
+ name: 'Telemetry Analyzer',
+ description: 'Analyzes Cognitum Seed device telemetry for anomalies and drift patterns',
+ defaultConfig: {
+ id: '',
+ name: 'telemetry-analyzer',
+ type: 'analyzer',
+ capabilities: ['iot:telemetry', 'iot:anomaly-detect', 'iot:baseline'],
+ maxConcurrentTasks: 5,
+ priority: 75,
+ timeout: 120_000,
+ metadata: { pluginSource: '@claude-flow/plugin-iot-cognitum' },
+ },
+ requiredCapabilities: ['iot:telemetry'],
+ metadata: { anomalyAware: true, baselineAware: true },
+ },
+ {
+ type: 'fleet-manager',
+ name: 'Fleet Manager',
+ description: 'Manages device fleets, firmware rollouts, and fleet-wide policies',
+ defaultConfig: {
+ id: '',
+ name: 'fleet-manager',
+ type: 'coordinator',
+ capabilities: ['iot:fleet-create', 'iot:fleet-manage', 'iot:firmware-deploy', 'iot:firmware-rollback'],
+ maxConcurrentTasks: 8,
+ priority: 90,
+ timeout: 600_000,
+ metadata: { pluginSource: '@claude-flow/plugin-iot-cognitum' },
+ },
+ requiredCapabilities: ['iot:fleet-create', 'iot:fleet-manage'],
+ metadata: { firmwareAware: true, rolloutAware: true },
+ },
+ {
+ type: 'witness-auditor',
+ name: 'Witness Chain Auditor',
+ description: 'Verifies Ed25519 witness chain integrity and detects provenance gaps',
+ defaultConfig: {
+ id: '',
+ name: 'witness-auditor',
+ type: 'auditor',
+ capabilities: ['iot:witness-verify', 'iot:witness-audit', 'iot:custody-check'],
+ maxConcurrentTasks: 3,
+ priority: 70,
+ timeout: 180_000,
+ metadata: { pluginSource: '@claude-flow/plugin-iot-cognitum' },
+ },
+ requiredCapabilities: ['iot:witness-verify'],
+ metadata: { cryptoAware: true, auditAware: true },
+ },
];
}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/workers/anomaly-scan-worker.ts b/v3/@claude-flow/plugin-iot-cognitum/src/workers/anomaly-scan-worker.ts
new file mode 100644
index 0000000000..7280f4739f
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/workers/anomaly-scan-worker.ts
@@ -0,0 +1,52 @@
+import type { IoTCoordinator } from '../application/iot-coordinator.js';
+
+export interface AnomalyScanConfig {
+ intervalMs: number;
+ onAnomalyDetected?: (deviceId: string, score: number) => void;
+ onScanError?: (deviceId: string, error: Error) => void;
+}
+
+export class AnomalyScanWorker {
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private readonly coordinator: IoTCoordinator;
+ private readonly config: AnomalyScanConfig;
+
+ constructor(coordinator: IoTCoordinator, config: Partial<AnomalyScanConfig> = {}) {
+ this.coordinator = coordinator;
+ this.config = {
+ intervalMs: config.intervalMs ?? 300_000,
+ onAnomalyDetected: config.onAnomalyDetected,
+ onScanError: config.onScanError,
+ };
+ }
+
+ start(): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => void this.scan(), this.config.intervalMs);
+ }
+
+ stop(): void {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ }
+
+ async scan(): Promise<void> {
+ const devices = this.coordinator.listDevices();
+ for (const device of devices) {
+ try {
+ const refreshed = await this.coordinator.getDeviceStatus(device.deviceId);
+ if (refreshed.trustScore.overall < 0.5) {
+ this.config.onAnomalyDetected?.(device.deviceId, refreshed.trustScore.overall);
+ }
+ } catch (err) {
+ this.config.onScanError?.(device.deviceId, err as Error);
+ }
+ }
+ }
+
+ isRunning(): boolean {
+ return this.timer !== null;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/workers/firmware-watch-worker.ts b/v3/@claude-flow/plugin-iot-cognitum/src/workers/firmware-watch-worker.ts
new file mode 100644
index 0000000000..1f5c6a5ae2
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/workers/firmware-watch-worker.ts
@@ -0,0 +1,57 @@
+import type { IoTCoordinator } from '../application/iot-coordinator.js';
+
+export interface FirmwareWatchConfig {
+ intervalMs: number;
+ onVersionMismatch?: (deviceId: string, expected: string, actual: string) => void;
+ onWatchError?: (deviceId: string, error: Error) => void;
+}
+
+export class FirmwareWatchWorker {
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private readonly coordinator: IoTCoordinator;
+ private readonly config: FirmwareWatchConfig;
+ private readonly knownVersions = new Map<string, string>();
+
+ constructor(coordinator: IoTCoordinator, config: Partial<FirmwareWatchConfig> = {}) {
+ this.coordinator = coordinator;
+ this.config = {
+ intervalMs: config.intervalMs ?? 300_000,
+ onVersionMismatch: config.onVersionMismatch,
+ onWatchError: config.onWatchError,
+ };
+ }
+
+ start(): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => void this.watch(), this.config.intervalMs);
+ }
+
+ stop(): void {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ }
+
+ async watch(): Promise<void> {
+ const devices = this.coordinator.listDevices();
+ for (const device of devices) {
+ try {
+ const refreshed = await this.coordinator.getDeviceStatus(device.deviceId);
+ const knownVersion = this.knownVersions.get(device.deviceId);
+
+ if (knownVersion && knownVersion !== refreshed.firmwareVersion) {
+ this.config.onVersionMismatch?.(device.deviceId, knownVersion, refreshed.firmwareVersion);
+ }
+
+ this.knownVersions.set(device.deviceId, refreshed.firmwareVersion);
+ } catch (err) {
+ this.config.onWatchError?.(device.deviceId, err as Error);
+ }
+ }
+ }
+
+ isRunning(): boolean {
+ return this.timer !== null;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/workers/health-probe-worker.ts b/v3/@claude-flow/plugin-iot-cognitum/src/workers/health-probe-worker.ts
new file mode 100644
index 0000000000..dafd8a2f8c
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/workers/health-probe-worker.ts
@@ -0,0 +1,62 @@
+import type { IoTCoordinator } from '../application/iot-coordinator.js';
+
+export interface HealthProbeConfig {
+ intervalMs: number;
+ onDeviceOffline?: (deviceId: string) => void;
+ onDeviceOnline?: (deviceId: string) => void;
+ onProbeError?: (deviceId: string, error: Error) => void;
+}
+
+export class HealthProbeWorker {
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private readonly coordinator: IoTCoordinator;
+ private readonly config: HealthProbeConfig;
+ private readonly lastKnownStatus: Map<string, 'online' | 'offline'> =
+ new Map();
+
+ constructor(coordinator: IoTCoordinator, config: Partial<HealthProbeConfig> = {}) {
+ this.coordinator = coordinator;
+ this.config = {
+ intervalMs: config.intervalMs ?? 30_000,
+ onDeviceOffline: config.onDeviceOffline,
+ onDeviceOnline: config.onDeviceOnline,
+ onProbeError: config.onProbeError,
+ };
+ }
+
+ start(): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => void this.probe(), this.config.intervalMs);
+ }
+
+ stop(): void {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ }
+
+ async probe(): Promise<void> {
+ const devices = this.coordinator.listDevices();
+ for (const device of devices) {
+ const prevStatus = this.lastKnownStatus.get(device.deviceId);
+ try {
+ await this.coordinator.getDeviceStatus(device.deviceId);
+ this.lastKnownStatus.set(device.deviceId, 'online');
+ if (prevStatus === 'offline') {
+ this.config.onDeviceOnline?.(device.deviceId);
+ }
+ } catch (err) {
+ this.lastKnownStatus.set(device.deviceId, 'offline');
+ if (prevStatus !== 'offline') {
+ this.config.onDeviceOffline?.(device.deviceId);
+ }
+ this.config.onProbeError?.(device.deviceId, err as Error);
+ }
+ }
+ }
+
+ isRunning(): boolean {
+ return this.timer !== null;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/workers/mesh-sync-worker.ts b/v3/@claude-flow/plugin-iot-cognitum/src/workers/mesh-sync-worker.ts
new file mode 100644
index 0000000000..4fa8570e2f
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/workers/mesh-sync-worker.ts
@@ -0,0 +1,60 @@
+import type { IoTCoordinator } from '../application/iot-coordinator.js';
+
+export interface MeshSyncConfig {
+ intervalMs: number;
+ onMeshPartition?: (deviceId: string, peerCount: number) => void;
+ onSyncComplete?: (deviceId: string, peerCount: number) => void;
+ onSyncError?: (deviceId: string, error: Error) => void;
+}
+
+export class MeshSyncWorker {
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private readonly coordinator: IoTCoordinator;
+ private readonly config: MeshSyncConfig;
+ private readonly lastPeerCounts = new Map<string, number>();
+
+ constructor(coordinator: IoTCoordinator, config: Partial<MeshSyncConfig> = {}) {
+ this.coordinator = coordinator;
+ this.config = {
+ intervalMs: config.intervalMs ?? 120_000,
+ onMeshPartition: config.onMeshPartition,
+ onSyncComplete: config.onSyncComplete,
+ onSyncError: config.onSyncError,
+ };
+ }
+
+ start(): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => void this.sync(), this.config.intervalMs);
+ }
+
+ stop(): void {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ }
+
+ async sync(): Promise<void> {
+ const devices = this.coordinator.listDevices();
+ for (const device of devices) {
+ try {
+ const topology = await this.coordinator.getDeviceMeshTopology(device.deviceId);
+ const prevCount = this.lastPeerCounts.get(device.deviceId) ?? topology.peerCount;
+
+ if (topology.peerCount === 0 && prevCount > 0) {
+ this.config.onMeshPartition?.(device.deviceId, topology.peerCount);
+ }
+
+ this.lastPeerCounts.set(device.deviceId, topology.peerCount);
+ this.config.onSyncComplete?.(device.deviceId, topology.peerCount);
+ } catch (err) {
+ this.config.onSyncError?.(device.deviceId, err as Error);
+ }
+ }
+ }
+
+ isRunning(): boolean {
+ return this.timer !== null;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/workers/telemetry-ingest-worker.ts b/v3/@claude-flow/plugin-iot-cognitum/src/workers/telemetry-ingest-worker.ts
new file mode 100644
index 0000000000..fb0d3031d3
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/workers/telemetry-ingest-worker.ts
@@ -0,0 +1,50 @@
+import type { IoTCoordinator } from '../application/iot-coordinator.js';
+
+export interface TelemetryIngestConfig {
+ intervalMs: number;
+ onIngestionComplete?: (deviceId: string, vectorCount: number) => void;
+ onIngestionError?: (deviceId: string, error: Error) => void;
+}
+
+export class TelemetryIngestWorker {
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private readonly coordinator: IoTCoordinator;
+ private readonly config: TelemetryIngestConfig;
+
+ constructor(coordinator: IoTCoordinator, config: Partial<TelemetryIngestConfig> = {}) {
+ this.coordinator = coordinator;
+ this.config = {
+ intervalMs: config.intervalMs ?? 60_000,
+ onIngestionComplete: config.onIngestionComplete,
+ onIngestionError: config.onIngestionError,
+ };
+ }
+
+ start(): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => void this.ingest(), this.config.intervalMs);
+ }
+
+ stop(): void {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ }
+
+ async ingest(): Promise<void> {
+ const devices = this.coordinator.listDevices();
+ for (const device of devices) {
+ try {
+ const storeStatus = await this.coordinator.getDeviceStoreStatus(device.deviceId);
+ this.config.onIngestionComplete?.(device.deviceId, storeStatus.totalVectors);
+ } catch (err) {
+ this.config.onIngestionError?.(device.deviceId, err as Error);
+ }
+ }
+ }
+
+ isRunning(): boolean {
+ return this.timer !== null;
+ }
+}
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/workers/witness-audit-worker.ts b/v3/@claude-flow/plugin-iot-cognitum/src/workers/witness-audit-worker.ts
new file mode 100644
index 0000000000..d46c11378b
--- /dev/null
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/workers/witness-audit-worker.ts
@@ -0,0 +1,64 @@
+import type { IoTCoordinator } from '../application/iot-coordinator.js';
+
+export interface WitnessAuditConfig {
+ intervalMs: number;
+ onGapDetected?: (deviceId: string, fromEpoch: number, toEpoch: number) => void;
+ onAuditComplete?: (deviceId: string, chainLength: number) => void;
+ onAuditError?: (deviceId: string, error: Error) => void;
+}
+
+export class WitnessAuditWorker {
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private readonly coordinator: IoTCoordinator;
+ private readonly config: WitnessAuditConfig;
+
+ constructor(coordinator: IoTCoordinator, config: Partial<WitnessAuditConfig> = {}) {
+ this.coordinator = coordinator;
+ this.config = {
+ intervalMs: config.intervalMs ?? 600_000,
+ onGapDetected: config.onGapDetected,
+ onAuditComplete: config.onAuditComplete,
+ onAuditError: config.onAuditError,
+ };
+ }
+
+ start(): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => void this.audit(), this.config.intervalMs);
+ }
+
+ stop(): void {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ }
+
+ async audit(): Promise<void> {
+ const devices = this.coordinator.listDevices();
+ for (const device of devices) {
+ try {
+ const chain = await this.coordinator.getDeviceWitnessChain(device.deviceId);
+ const entries = chain.entries ?? [];
+ const sorted = [...entries].sort((a: any, b: any) => a.epoch - b.epoch);
+
+ for (let i = 1; i < sorted.length; i++) {
+ const expected = (sorted[i - 1] as any).epoch + 1;
+ const actual = (sorted[i] as any).epoch;
+ if (actual > expected) {
+ this.config.onGapDetected?.(device.deviceId, (sorted[i - 1] as any).epoch, actual);
+ }
+ }
+
+ const chainLength = chain.length ?? entries.length ?? 0;
+ this.config.onAuditComplete?.(device.deviceId, chainLength);
+ } catch (err) {
+ this.config.onAuditError?.(device.deviceId, err as Error);
+ }
+ }
+ }
+
+ isRunning(): boolean {
+ return this.timer !== null;
+ }
+}