# https://github.com/monoes/monomind 项目说明书

生成时间：2026-05-17 00:56:32 UTC

## 目录

- [Getting Started with Monomind](#getting-started)
- [Project Structure](#project-structure)
- [Architecture Overview](#architecture-overview)
- [Core Packages](#packages-core)
- [Agent Catalog](#agent-catalog)
- [Agent Routing System](#agent-routing)
- [Swarm Topologies](#swarm-topologies)
- [Consensus Protocols](#consensus-protocols)
- [Memory System](#memory-system)
- [Knowledge Graph (Monograph)](#knowledge-graph)

<a id='getting-started'></a>

## Getting Started with Monomind

### 相关页面

相关主题：[Architecture Overview](#architecture-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/cli/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/README.md)
- [README.md](https://github.com/monoes/monomind/blob/main/README.md)
- [packages/@monomind/cli/src/commands/session.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/session.ts)
- [packages/@monomind/cli/src/commands/mcp.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/mcp.ts)
- [packages/@monomind/cli/src/commands/agent.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/agent.ts)
- [packages/@monomind/cli/src/commands/task.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/task.ts)
- [packages/@monomind/memory/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/README.md)
- [packages/helpers/README.md](https://github.com/monoes/monomind/blob/main/packages/helpers/README.md)
</details>

# Getting Started with Monomind

Monomind is an AI coordination system that orchestrates multiple AI agents to work together on complex software development tasks. It provides a unified CLI interface, memory management, knowledge graphs, and neural learning capabilities that enable agents to share context, learn from patterns, and collaborate effectively.

## Overview

Monomind serves as the central intelligence layer for AI-assisted development workflows. It coordinates agents, manages sessions, stores learned patterns in vector memory, and provides a knowledge graph for understanding codebase relationships. 资料来源：[packages/@monomind/cli/README.md]()

### Key Capabilities

| Capability | Description |
|------------|-------------|
| **Agent Orchestration** | Manage and coordinate multiple specialized AI agents |
| **Session Management** | Save, restore, and export conversation sessions |
| **Memory & Intelligence** | Vector-based memory with HNSW indexing and neural learning |
| **Knowledge Graph (Monograph)** | Build dependency graphs of codebases automatically |
| **MCP Server** | Model Context Protocol server for tool integration |
| **Workflow Automation** | Create and execute multi-step development workflows |

## Installation

### Prerequisites

- Node.js 18+ and npm/pnpm
- Git

### Install via npm

```bash
npm install -g @monomind/cli
```

Or use directly with npx:

```bash
npx @monomind/cli@latest --help
```

资料来源：[packages/implementation/adrs/README.md]()

### Verify Installation

```bash
monomind doctor --fix
```

This command checks the installation and attempts to fix common issues automatically.

资料来源：[README.md]()

## Core Concepts

### Architecture Overview

```mermaid
graph TD
    subgraph Monomind
        CLI[CLI Interface]
        MCP[MCP Server]
        Memory[Vector Memory]
        Graph[Knowledge Graph]
        SONA[Neural Learning]
    end
    
    subgraph Agents
        Coder[Coder Agent]
        Reviewer[Reviewer Agent]
        Architect[Architect Agent]
        Coordinator[Coordinator Agent]
    end
    
    CLI --> MCP
    CLI --> Memory
    CLI --> Graph
    Memory --> SONA
    Graph --> SONA
    
    MCP --> Coder
    MCP --> Reviewer
    MCP --> Architect
    MCP --> Coordinator
```

### Agent Types

Monomind supports multiple specialized agent types, each with distinct capabilities:

| Agent Type | Capabilities | Use Case |
|------------|--------------|----------|
| `coder` | Code generation, refactoring, debugging, testing | Primary development work |
| `researcher` | Web search, data analysis, summarization, citation | Information gathering |
| `tester` | Unit testing, integration testing, coverage analysis | Quality assurance |
| `reviewer` | Code review, security audit, quality check | Code inspection |
| `architect` | System design, pattern analysis, scalability | Design decisions |
| `coordinator` | Task orchestration, agent management, workflow control | Multi-agent coordination |
| `security-architect` | Threat modeling, security patterns, compliance | Security-focused work |
| `memory-specialist` | Vector search, agentdb, caching, optimization | Memory optimization |

资料来源：[packages/@monomind/cli/src/commands/agent.ts]()

## CLI Commands Reference

### Session Management

Manage conversation sessions with persistence and export capabilities.

```bash
# List all sessions
monomind session list

# Save current session state
monomind session save

# Restore a saved session
monomind session restore <session-id>

# Delete a saved session
monomind session delete <session-id>

# Export session to file
monomind session export <session-id> --output ./session.json

# Import session from file
monomind session import ./session.json

# Show current active session
monomind session current
```

资料来源：[packages/@monomind/cli/src/commands/session.ts]()

### MCP Server Management

Control the Model Context Protocol server that provides tools to connected agents.

```bash
# Start MCP server
monomind mcp start

# Stop MCP server
monomind mcp stop

# Show server status
monomind mcp status

# Check server health
monomind mcp health

# Restart MCP server
monomind mcp restart

# List available tools
monomind mcp tools

# Enable/disable specific tools
monomind mcp toggle <tool-name> --enable
monomind mcp toggle <tool-name> --disable

# Execute a specific tool
monomind mcp exec <tool-name> --args <json>

# Show server logs
monomind mcp logs
```

资料来源：[packages/@monomind/cli/src/commands/mcp.ts]()

### Task Management

Create and manage development tasks for agents to work on.

```bash
# Create a new task
monomind task create "Implement user authentication" --priority high

# List all tasks
monomind task list

# Get task details
monomind task status <task-id>

# Cancel a running task
monomind task cancel <task-id>

# Assign task to agent(s)
monomind task assign <task-id> --agents coder,reviewer

# Retry a failed task
monomind task retry <task-id>
```

资料来源：[packages/@monomind/cli/src/commands/task.ts]()

### Agent Commands

```bash
# List available agents
monomind agent list

# Show agent metrics
monomind agent metrics

# Manage agent pool
monomind agent pool status

# Show agent health
monomind agent health

# Show agent logs
monomind agent logs --agent coder

# Check WASM runtime availability
monomind agent wasm-status

# Create a WASM-sandboxed agent
monomind agent wasm-create <template>

# List WASM agent gallery templates
monomind agent wasm-gallery
```

资料来源：[packages/@monomind/cli/src/commands/agent.ts]()

## Memory & Intelligence System

### Vector Memory (AgentDB + HNSW)

Monomind stores insights, patterns, and decisions in searchable vector memory with HNSW indexing.

```mermaid
graph LR
    A[User Input] --> B[Embedding Generator]
    B --> C[HNSW Index]
    C --> D[Vector Search]
    D --> E[Relevant Results]
    
    F[(SQLite)] --> G[Structured Data]
    G --> E
```

### Key Features

| Feature | Description |
|---------|-------------|
| **HNSW Indexing** | 150x-12,500x faster than brute-force search |
| **Hybrid Backend** | SQLite for structured data, AgentDB for semantic search |
| **Cross-Session Persistence** | Context survives restarts |
| **A-MEM Auto-Linking** | Automatic bidirectional references between stored entries |

资料来源：[packages/@monomind/memory/README.md]()

### Memory Scopes

Memory is organized into three scopes:

| Scope | Path | Purpose |
|-------|------|---------|
| `project` | `<gitRoot>/.claude/agent-memory/<agent>/` | Project-specific learnings |
| `local` | `<gitRoot>/.claude/agent-memory-local/<agent>/` | Machine-local data |
| `user` | `~/.claude/agent-memory/<agent>/` | Cross-project user knowledge |

### Utility Functions

```typescript
import {
  resolveAgentMemoryDir,  // Get scope directory path
  createAgentBridge,       // Create scoped AutoMemoryBridge
  transferKnowledge,       // Cross-agent knowledge sharing
  listAgentScopes,         // Discover existing agent scopes
} from '@monomind/memory';

// Resolve path for an agent scope
const dir = resolveAgentMemoryDir('my-agent', 'project');
// → /workspaces/my-project/.claude/agent-memory/my-agent/

// List all agent scopes in a directory
const scopes = await listAgentScopes('/workspaces/my-project');
```

资料来源：[packages/@monomind/memory/README.md]()

### Knowledge Graph (Monograph)

Monograph builds a full dependency graph of your codebase that is automatically queried before every task.

```bash
# What files are relevant to my task?
monograph_suggest "add webhook retry logic"
# → returns ranked list of files with relevance scores

# What depends on UserService?
monograph_query "UserService dependencies"
# → returns file paths + line numbers

# Find the most connected files in the codebase
monograph_god_nodes
# → returns high-centrality internal files
```

### Node Types in Monograph

| Type | Meaning | Example |
|------|---------|---------|
| `File` | Source code file | `.ts`, `.py`, `.md` |
| `Class` | Code class or interface | `UserService`, `AuthMiddleware` |
| `Concept` | Extracted semantic concept | `authentication`, `caching` |
| `PDF` | PDF document chunk | Technical documentation |

### Edge Types

| Relation | Meaning |
|----------|---------|
| `IMPORTS` | Code import dependency |
| `DEFINES` | File defines symbol |
| `TAGGED_AS` | Section tagged with concept |
| `CO_OCCURS` | Concepts appear together |
| `INFERRED` | Claude-extracted semantic relationship |
| `DESCRIBES` / `CAUSES` / `PART_OF` | LLM-enriched semantic edges |

### CLI vs MCP Usage

| Method | Use Case |
|--------|----------|
| **CLI** (`monomind monograph ...`) | One-time builds, manual searches, terminal usage |
| **MCP tools** (`mcp__monomind__monograph_*`) | Claude Code integration, programmatic queries during tasks |

资料来源：[plugin/commands/monograph/README.md]()

### Neural Learning (SONA)

Self-Optimizing Neural Adaptation learns from every task:

- **Pattern recognition** improves agent routing over time
- **Trajectory tracking** identifies what works and what doesn't
- **Automatic model adaptation** with <0.05ms overhead

## Quick Start Guide

### Step 1: Initialize Monomind

```bash
# Run the setup wizard
monomind init

# Or initialize with specific template
monomind init --template minimal
```

Available templates:
- `minimal` - Quick start with behavioral rules
- `standard` - Full setup with all features
- `full` - Complete configuration with hooks and learning
- `security` - Security-focused configuration
- `performance` - Performance-optimized setup
- `solo` - Single developer workflow

### Step 2: Configure Your Environment

```bash
# Set configuration
monomind config set providers.openai.api_key <your-key>
monomind config set providers.anthropic.api_key <your-key>

# List current configuration
monomind config list

# Export configuration
monomind config export ./config.json

# Import configuration
monomind config import ./config.json
```

### Step 3: Start Working

```mermaid
graph TD
    A[Start Session] --> B[Create Task]
    B --> C[Agent Selection]
    C --> D{Parallel or Sequential?}
    D -->|Parallel| E[Swarm Orchestration]
    D -->|Sequential| F[Single Agent]
    E --> G[Memory Storage]
    F --> G
    G --> H[Pattern Learning]
    H --> I[Future Task Optimization]
```

### Step 4: Session Workflow

```bash
# Start a new session
monomind session save

# Work on tasks
monomind task create "Build user dashboard"
monomind task assign <task-id> --agents coder

# Monitor progress
monomind task status <task-id>

# Review session details
monomind session current
```

## Cross-Platform Helper Scripts

Monomind includes helper scripts for cross-platform development automation.

### Installation

The helpers are automatically installed when you run `monomind init` and placed in `.claude/helpers/`.

资料来源：[packages/helpers/README.md]()

### Available Helpers

| Script | Purpose |
|--------|---------|
| `monomind-v1.sh status` | Check V1 feature status |
| `monomind-v1.sh doctor` | Diagnose installation issues |
| `monomind-v1.sh help` | Show help information |

### Permission Issues (Linux/Mac)

```bash
find .claude/helpers -name "*.sh" -exec chmod +x {} \;
```

### Windows PowerShell Execution Policy

```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```

资料来源：[packages/helpers/README.md]()

## Configuration Reference

### Configuration File Location

Configuration is stored in:
- Project: `.claude/monomind.config.json`
- User: `~/.config/monomind/config.json`

### Runtime Options

| Option | Default | Description |
|--------|---------|-------------|
| `runtime.claudeMdTemplate` | `'standard'` | CLAUDE.md template to use |
| `runtime.autoSave` | `true` | Automatically save sessions |
| `runtime.maxConcurrentAgents` | `4` | Maximum parallel agents |

### Provider Configuration

```bash
# Configure AI providers
monomind providers configure openai
monomind providers configure anthropic
monomind providers configure local

# Test provider connection
monomind providers test openai

# View usage statistics
monomind providers usage
```

## Troubleshooting

### Common Issues

#### Installation Fails

```bash
# Clear cache and retry
npm cache clean --force
npm install -g @monomind/cli
```

#### MCP Server Won't Start

```bash
# Check server health
monomind mcp health

# View logs for errors
monomind mcp logs

# Restart the server
monomind mcp restart
```

#### Memory Search Returns No Results

```bash
# Check memory backend status
monomind memory status

# Rebuild vector index
monomind memory rebuild
```

### Diagnostic Commands

```bash
# Run full diagnostics
monomind doctor

# Fix common issues automatically
monomind doctor --fix

# Check specific component
monomind agent health
monomind mcp status
```

## Contributing

```bash
# Clone the repository
git clone https://github.com/monoes/monomind.git
cd monomind

# Install dependencies
pnpm install

# Run diagnostic and fix
monomind doctor --fix
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.

## License

MIT License — See [LICENSE](LICENSE) for details.

---

<a id='project-structure'></a>

## Project Structure

### 相关页面

相关主题：[Architecture Overview](#architecture-overview), [Core Packages](#packages-core)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/cli](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli)
- [packages/@monomind/memory](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory)
- [packages/@monomind/hooks](https://github.com/monoes/monomind/blob/main/packages/@monomind/hooks)
- [packages/@monomind/swarm](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm)
- [packages/@monomind/shared](https://github.com/monoes/monomind/blob/main/packages/@monomind/shared)
- [.claude/agents](https://github.com/monoes/monomind/blob/main/.claude/agents)
- [.claude/commands](https://github.com/monoes/monomind/blob/main/.claude/commands)
- [packages/@monomind/plugins](https://github.com/monoes/monomind/blob/main/packages/@monomind/plugins)
</details>

# Project Structure

Monomind is organized as a **monorepo** using pnpm workspaces, with the primary packages located in the `packages/` directory and Claude Code integration files in the `.claude/` directory.

## Repository Layout

```
monomind/
├── packages/
│   ├── @monomind/           # Core packages
│   │   ├── cli/             # Command-line interface
│   │   ├── memory/          # Vector memory & AgentDB
│   │   ├── hooks/           # Hook system for automation
│   │   ├── swarm/           # Multi-agent coordination
│   │   ├── shared/          # Shared utilities & types
│   │   ├── plugins/         # Plugin system
│   │   └── aidefence/       # Security & audit tools
│   └── plugins/             # External plugins
│       ├── gastown-bridge/  # Thread-based work tracking
│       └── teammate-plugin/ # Claude Code integration
├── .claude/
│   ├── agents/              # Claude Code agent definitions
│   └── commands/             # Custom slash commands
└── README.md
```

## Core Packages

### @monomind/cli

The CLI package is the primary user-facing interface for Monomind. It provides commands for:

- **Session Management** — Save, restore, list, delete, export sessions
- **Memory Operations** — Store, retrieve, search, list, delete entries
- **Agent Control** — Metrics, pool management, health checks, WASM agents
- **MCP Server** — Start, stop, health checks, tool execution
- **Configuration** — Get, set, list, reset config values
- **Plugins** — Install, uninstall, toggle, list plugins

资料来源：[packages/@monomind/cli/src/commands/session.ts](packages/@monomind/cli/src/commands/session.ts)
资料来源：[packages/@monomind/cli/src/commands/memory.ts](packages/@monomind/cli/src/commands/memory.ts)
资料来源：[packages/@monomind/cli/src/commands/mcp.ts](packages/@monomind/cli/src/commands/mcp.ts)

### @monomind/memory

The memory package implements a hybrid storage backend combining:

| Component | Purpose |
|-----------|---------|
| **AgentDB** | HNSW-based vector database for semantic search |
| **SQLite** | Structured data storage |
| **A-MEM Auto-Linking** | Zettelkasten-style bidirectional references (arXiv:2409.11987) |

Memory scopes follow a hierarchical structure:

| Scope | Path | Use Case |
|-------|------|----------|
| `project` | `<gitRoot>/.claude/agent-memory/<agent>/` | Project-specific learnings |
| `local` | `<gitRoot>/.claude/agent-memory-local/<agent>/` | Machine-local data |
| `user` | `~/.claude/agent-memory/<agent>/` | Cross-project user knowledge |

资料来源：[packages/@monomind/memory/README.md](packages/@monomind/memory/README.md)

### @monomind/hooks

The hooks system provides event-driven automation with support for:

- **Pre/Post Hooks** — Execute before/after operations
- **Slash Commands** — Custom CLI extensions
- **Status Line** — Real-time status updates

Hooks are configured via JSON:

```json
{
  "onAgentStart": { "command": "log-agent-start" },
  "onTaskComplete": { "type": "command", "command": "notify" },
  "statusLine": { "type": "command", "command": "statusline" }
}
```

资料来源：[packages/@monomind/hooks/README.md](packages/@monomind/hooks/README.md)

### @monomind/swarm

Multi-agent coordination system enabling:

- **Swarm Orchestration** — Task distribution across agents
- **Agent Communication** — Inter-agent messaging protocols
- **Load Balancing** — Work distribution optimization
- **Failure Recovery** — Automatic retry and fallback mechanisms

### @monomind/shared

Shared utilities and TypeScript types used across all Monomind packages:

- Common interfaces and type definitions
- Utility functions
- Constants and configuration schemas

### @monomind/plugins

The plugin system provides extensibility through:

- **Plugin Discovery** — Automatic plugin detection
- **Lifecycle Management** — Install, enable, disable, uninstall
- **Sandboxing** — Isolated plugin execution environments

## Claude Code Integration

### .claude/agents

Agent definitions for Claude Code integration. Each agent can have:

- **System Prompts** — Custom instructions and behavior
- **Tool Sets** — Specific capabilities and permissions
- **Memory Scopes** — Dedicated knowledge bases

### .claude/commands

Custom slash commands extend Claude Code's CLI:

```bash
# Available commands
monograph_suggest  # Get relevant file suggestions
monograph_query    # Query knowledge graph dependencies
monograph_god_nodes # Find highly-connected internal files
```

## CLAUDE.md Generation

The CLI includes a CLAUDE.md generator with multiple templates:

```typescript
export const CLAUDE_MD_TEMPLATES: Array<{ name: ClaudeMdTemplate; description: string }> = [
  { name: 'minimal', description: 'Quick start — behavioral rules, anti-drift' },
  { name: 'standard', description: 'Full features — swarm, hooks, intelligence' },
  { name: 'full', description: 'Complete — all sections including auto-start' },
  { name: 'security', description: 'Security-focused — audit, compliance' },
  { name: 'performance', description: 'Performance-focused — profiling, optimization' },
  { name: 'solo', description: 'Single agent — no swarm' },
];
```

资料来源：[packages/@monomind/cli/src/init/claudemd-generator.ts](packages/@monomind/cli/src/init/claudemd-generator.ts)

## External Plugins

### gastown-bridge

Thread-based work tracking system with concepts:

| Concept | Description |
|---------|-------------|
| **Bead** | Individual work unit |
| **Formula** | Multi-leg work order (convoy, workflow, expansion, aspect) |
| **Thread** | Collection of related beads |

### teammate-plugin

Claude Code integration plugin providing:

- Claude Code version compatibility checking
- Teammate bridge creation
- Claude Code plugin system integration

资料来源：[packages/plugins/gastown-bridge/README.md](packages/plugins/gastown-bridge/README.md)
资料来源：[packages/plugins/teammate-plugin/README.md](packages/plugins/teammate-plugin/README.md)

## Architecture Diagram

```mermaid
graph TD
    subgraph "User Interface"
        CLI[CLI Commands]
        MCP[MCP Tools]
        SL[Slash Commands]
    end

    subgraph "packages/@monomind"
        CLI_PKG[@monomind/cli]
        MEM[@monomind/memory]
        HOOKS[@monomind/hooks]
        SWARM[@monomind/swarm]
        SHARED[@monomind/shared]
    end

    subgraph "Data Layer"
        AGENTDB[AgentDB<br/>HNSW Vector DB]
        SQLITE[SQLite]
        GRAPH[Knowledge Graph<br/>Monograph]
    end

    CLI --> CLI_PKG
    MCP --> CLI_PKG
    SL --> HOOKS

    CLI_PKG --> MEM
    CLI_PKG --> HOOKS
    CLI_PKG --> SWARM
    HOOKS --> SHARED
    SWARM --> SHARED

    MEM --> AGENTDB
    MEM --> SQLITE
    MEM --> GRAPH
```

## Memory & Intelligence System

The Monomind intelligence layer consists of three interconnected systems:

```mermaid
graph LR
    subgraph "Intelligence"
        KG[Knowledge Graph<br/>Monograph]
        VM[Vector Memory<br/>AgentDB + HNSW]
        NL[Neural Learning<br/>SONA]
    end

    KG -.->|Dependency Graph| VM
    VM -.->|Semantic Search| NL
    NL -.->|Pattern Learning| KG
```

### Knowledge Graph (Monograph)

Automatically builds dependency graphs of codebases:

- `IMPORTS` — Code import dependencies
- `DEFINES` — File defines symbol
- `TAGGED_AS` — Section tagged with concept
- `CO_OCCURS` — Concepts appear together
- `INFERRED` — Claude-extracted semantic relationship

资料来源：[plugin/commands/monograph/README.md](plugin/commands/monograph/README.md)

## Build & Installation

```bash
# Clone repository
git clone https://github.com/nokhodian/monomind.git
cd monomind

# Install dependencies
pnpm install

# Run diagnostics
monomind doctor --fix

# Install CLI globally
npx @monomind/cli@latest --help
```

## Contributing Guidelines

1. Fork the repository and create a feature branch
2. Run `pnpm install` to install dependencies
3. Use `monomind doctor --fix` to verify setup
4. Follow the CLAUDE.md guidelines for code contributions

资料来源：[README.md](README.md)

---

<a id='architecture-overview'></a>

## Architecture Overview

### 相关页面

相关主题：[Core Packages](#packages-core), [Swarm Topologies](#swarm-topologies)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/cli/src/commands/agent.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/agent.ts)
- [packages/@monomind/cli/src/commands/agent-wasm.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/agent-wasm.ts)
- [packages/@monomind/cli/src/commands/mcp.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/mcp.ts)
- [packages/@monomind/cli/src/commands/session.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/session.ts)
- [packages/@monomind/cli/src/commands/task.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/task.ts)
- [packages/@monomind/monograph/src/config/types.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/monograph/src/config/types.ts)
- [packages/@monomind/memory/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/README.md)
</details>

# Architecture Overview

Monomind is a comprehensive AI coordination system designed to orchestrate multiple AI agents, manage persistent memory, and provide intelligent workflow automation for complex software development tasks.

## System Architecture

### High-Level Architecture Diagram

```mermaid
graph TB
    subgraph "CLI Layer"
        CLI[CLI Interface<br/>@monomind/cli]
    end

    subgraph "Core Layer"
        MCP[MCP Server<br/>@monomind/mcp]
        Shared[Shared Core<br/>@monomind/shared]
    end

    subgraph "Capability Layer"
        Memory[Memory System<br/>@monomind/memory]
        Monograph[Knowledge Graph<br/>@monomind/monograph]
        AiDefence[Security<br/>@monomind/aidefence]
    end

    subgraph "Agent Layer"
        Agents[Agent Pool]
        WASM[WASM Runtime]
    end

    CLI --> MCP
    CLI --> Shared
    MCP --> Shared
    Shared --> Memory
    Shared --> Monograph
    Shared --> AiDefence
    MCP --> Agents
    Agents --> WASM
```

## Package Structure

### Core Packages

| Package | Purpose | Entry Point |
|---------|---------|-------------|
| `@monomind/cli` | Command-line interface and user interaction | `packages/@monomind/cli/src/index.ts` |
| `@monomind/mcp` | Model Context Protocol server implementation | `packages/@monomind/mcp/src/server.ts` |
| `@monomind/shared` | Shared utilities and core orchestration logic | `packages/@monomind/shared/src/index.ts` |
| `@monomind/shared/src/core/orchestrator` | Agent orchestration engine | `packages/@monomind/shared/src/core/orchestrator/index.ts` |

### Capability Packages

| Package | Description |
|---------|-------------|
| `@monomind/memory` | Vector memory storage with HNSW indexing and SQLite backend |
| `@monomind/monograph` | Knowledge graph builder and dependency analysis |
| `@monomind/aidefence` | Security scanning, CVE detection, and threat modeling |
| `@monomind/teammate-plugin` | Claude Code plugin integration |

## Command Architecture

The CLI provides hierarchical command organization through subcommands. Each command follows a consistent pattern with `help`, `list`, and action subcommands.

```mermaid
graph LR
    subgraph "Top-Level Commands"
        session[session]
        task[task]
        agent[agent]
        mcp[mcp]
        config[config]
    end

    subgraph "Agent Subcommands"
        agent_list[agent list]
        agent_metrics[agent metrics]
        agent_pool[agent pool]
        agent_wasm[agent wasm-*]
    end

    subgraph "MCP Subcommands"
        mcp_start[start]
        mcp_stop[stop]
        mcp_status[status]
        mcp_tools[tools]
    end

    agent --> agent_list
    agent --> agent_metrics
    agent --> agent_pool
    agent --> agent_wasm
    mcp --> mcp_start
    mcp --> mcp_stop
    mcp --> mcp_status
    mcp --> mcp_tools
```

### Session Management

Session commands provide conversation persistence and replay capabilities:

| Subcommand | Purpose | Implementation |
|------------|---------|----------------|
| `list` | List all saved sessions | `packages/@monomind/cli/src/commands/session.ts:1-50` |
| `save` | Save current session state | Session persistence layer |
| `restore` | Restore a saved session | State restoration mechanism |
| `delete` | Delete a saved session | Session cleanup |
| `export` | Export session to file | File serialization |
| `import` | Import session from file | File deserialization |
| `current` | Show current active session | Active session tracking |

### Task Orchestration

Tasks are the primary unit of work in Monomind, managed through the orchestrator:

```typescript
// Task subcommands from packages/@monomind/cli/src/commands/task.ts
const TASK_SUBCOMMANDS = ['create', 'list', 'status', 'cancel', 'assign', 'retry'];
```

| Subcommand | Description |
|------------|-------------|
| `create` | Create a new task |
| `list` | List all tasks |
| `status` | Get task details and progress |
| `cancel` | Cancel a running task |
| `assign` | Assign task to agent(s) |
| `retry` | Retry a failed task |

## Agent System Architecture

### Agent Types and Capabilities

```mermaid
graph TD
    subgraph "Agent Types"
        coder[Coder Agent]
        researcher[Researcher Agent]
        tester[Tester Agent]
        reviewer[Reviewer Agent]
        architect[Architect Agent]
        coordinator[Coordinator Agent]
        security[Security Architect]
        memory[Memory Specialist]
        performance[Performance Engineer]
    end

    subgraph "Capabilities"
        code-gen[code-generation<br/>refactoring<br/>debugging]
        research[web-search<br/>data-analysis]
        test[unit-testing<br/>integration-testing]
        review[code-review<br/>security-audit]
        design[system-design<br/>pattern-analysis]
        orchestrate[task-orchestration<br/>workflow-control]
        security-caps[threat-modeling<br/>compliance]
        memory-caps[vector-search<br/>caching]
        perf[caching<br/>optimization<br/>profiling]
    end

    coder --> code-gen
    researcher --> research
    tester --> test
    reviewer --> review
    architect --> design
    coordinator --> orchestrate
    security --> security-caps
    memory --> memory-caps
    performance --> perf
```

### Agent Capability Matrix

| Agent Type | Primary Capabilities |
|------------|---------------------|
| `coder` | code-generation, refactoring, debugging, testing |
| `researcher` | web-search, data-analysis, summarization, citation |
| `tester` | unit-testing, integration-testing, coverage-analysis, automation |
| `reviewer` | code-review, security-audit, quality-check, documentation |
| `architect` | system-design, pattern-analysis, scalability, documentation |
| `coordinator` | task-orchestration, agent-management, workflow-control |
| `security-architect` | threat-modeling, security-patterns, compliance, audit |
| `memory-specialist` | vector-search, agentdb, caching, optimization |
| `performance-engineer` | caching, optimization, profiling, benchmarking |

*资料来源：[packages/@monomind/cli/src/commands/agent.ts:60-90](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/agent.ts)*

### WASM Agent Runtime

Monomind supports sandboxed agent execution via WebAssembly:

```mermaid
graph LR
    subgraph "WASM Commands"
        wasm-create[wasm-create]
        wasm-prompt[wasm-prompt]
        wasm-gallery[wasm-gallery]
        wasm-status[wasm-status]
    end

    subgraph "Gallery Templates"
        gallery1[Template 1]
        gallery2[Template 2]
        gallery3[Template N]
    end

    wasm-gallery --> gallery1
    wasm-gallery --> gallery2
    wasm-gallery --> gallery3
    wasm-create --> gallery1
```

| Command | Purpose |
|---------|---------|
| `wasm-status` | Check WASM runtime availability |
| `wasm-create` | Create a WASM-sandboxed agent |
| `wasm-prompt` | Send a prompt to a WASM agent |
| `wasm-gallery` | List WASM agent gallery templates |

*资料来源：[packages/@monomind/cli/src/commands/agent-wasm.ts:1-150](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/agent-wasm.ts)*

## Memory System Architecture

### Memory Scopes

Monomind implements a hierarchical memory architecture with multiple scopes:

```mermaid
graph TD
    subgraph "Memory Scopes"
        global[Global<br/>~/.claude/agent-memory/]
        project[Project<br/>/.claude/agent-memory/]
        local[Local<br/>/.claude/agent-memory-local/]
        user[User<br/>~/.claude/agent-memory/]
    end

    subgraph "Per-Agent Isolation"
        coder[Coder Agent]
        tester[Tester Agent]
        reviewer[Reviewer Agent]
    end

    global --> coder
    global --> tester
    global --> reviewer
    project --> coder
    project --> tester
    project --> reviewer
    local --> coder
    local --> tester
    local --> reviewer
```

### Memory Scope Configuration

| Scope | Path Pattern | Purpose |
|-------|--------------|---------|
| `global` | `<gitRoot>/.claude/agent-memory/<agent>/` | Global agent learnings |
| `project` | `<gitRoot>/.claude/agent-memory/<agent>/` | Project-specific learnings |
| `local` | `<gitRoot>/.claude/agent-memory-local/<agent>/` | Machine-local data |
| `user` | `~/.claude/agent-memory/<agent>/` | Cross-project user knowledge |

*资料来源：[packages/@monomind/memory/README.md:50-100](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/README.md)*

### Hybrid Backend

The memory system uses a hybrid approach combining structured and vector storage:

```mermaid
graph LR
    subgraph "Hybrid Backend"
        SQLite[(SQLite<br/>Structured Data)]
        AgentDB[(AgentDB<br/>Vector Search)]
        HNSW[HNSW Index]
    end

    SQLite --> AgentDB
    AgentDB --> HNSW
```

| Component | Function | Performance |
|-----------|----------|-------------|
| SQLite | Structured data persistence | ACID compliance |
| AgentDB | Semantic vector search | HNSW indexing |
| HNSW | Approximate nearest neighbor | 150x-12,500x faster than brute-force |

### A-MEM Auto-Linking

The system implements automatic semantic linking (arXiv:2409.11987):

```typescript
// From packages/@monomind/memory/README.md
const backend = new HybridBackend({
  embeddingGenerator: async (text) => myEmbeddingModel.embed(text),
  // A-MEM auto-linking is automatically active when embeddingGenerator is set
});
```

Each stored entry automatically discovers its top-3 semantic neighbors and creates bidirectional `references` edges.

## Knowledge Graph (Monograph)

### Graph Node Types

| Node Type | Description |
|-----------|-------------|
| `File` | Source code file |
| `Directory` | Project directory |
| `Function` | Function definition |
| `Class` | Code class or interface |
| `Concept` | Extracted semantic concept |
| `PDF` | PDF document chunk |

### Graph Edge Types

| Relation | Meaning |
|----------|---------|
| `IMPORTS` | Code import dependency |
| `DEFINES` | File defines symbol |
| `TAGGED_AS` | Section tagged with concept |
| `CO_OCCURS` | Concepts appear together |
| `INFERRED` | Claude-extracted semantic relationship |
| `DESCRIBES` | LLM-enriched semantic edge |
| `CAUSES` | LLM-enriched semantic edge |
| `PART_OF` | LLM-enriched semantic edge |

*资料来源：[plugin/commands/monograph/README.md:50-80](https://github.com/monoes/monomind/blob/main/plugin/commands/monograph/README.md)*

### Monograph Configuration

```typescript
// From packages/@monomind/monograph/src/config/types.ts
interface MonographConfig {
  root: string;
  entry: string[];
  production: boolean;
  detection: 'default' | 'extended';
  project?: string;
  ignore: string[];
  overrides: OverrideConfig[];
  regression: RegressionConfig;
  audit: AuditConfig;
  normalization: NormalizationConfig;
  boundaries: BoundaryConfig;
  resolve: ResolveConfig;
  health: HealthConfig;
  ownership: OwnershipConfig;
  plugins: string[];
}
```

### Default Configuration

```typescript
// From packages/@monomind/monograph/src/config/types.ts:40-60
export const DEFAULT_MONOGRAPH_CONFIG: ResolvedMonographConfig = {
  root: '.',
  entry: [],
  production: true,
  detection: 'default',
  project: undefined,
  ignore: [],
  overrides: [],
  regression: { tolerance: 0, baselinePath: '.monograph/regression-baseline.json' },
  audit: { gate: 'error', includeHealthGate: false },
  normalization: { 
    stripComments: true, 
    normalizeWhitespace: true, 
    normalizeIdentifiers: false 
  },
  boundaries: {},
  resolve: { 
    paths: {}, 
    alias: {}, 
    conditions: [], 
    extensions: ['.ts', '.tsx', '.mts', '.cts'] 
  },
  health: { 
    cyclomaticThreshold: 10, 
    cognitiveThreshold: 15, 
    crapThreshold: 30, 
    minLines: 5 
  },
  ownership: { emailMode: 'fullEmail' },
  plugins: [],
};
```

## MCP Server Architecture

### Server Capabilities

```mermaid
graph TB
    subgraph "MCP Server"
        server[MCP Server<br/>packages/@monomind/mcp/src/server.ts]
        tools[Tool Handlers]
        resources[Resource Handlers]
    end

    subgraph "Tools"
        monograph_tools[Monograph Tools<br/>mcp__monomind__monograph_*]
        memory_tools[Memory Tools<br/>mcp__monomind__memory_*]
        agent_tools[Agent Tools<br/>mcp__monomind__agent_*]
    end

    server --> tools
    server --> resources
    tools --> monograph_tools
    tools --> memory_tools
    tools --> agent_tools
```

### MCP Subcommands

| Subcommand | Purpose |
|------------|---------|
| `start` | Start MCP server |
| `stop` | Stop MCP server |
| `status` | Show server status |
| `health` | Check server health |
| `restart` | Restart MCP server |
| `tools` | List available tools |
| `toggle` | Enable/disable tools |
| `exec` | Execute a tool |
| `logs` | Show server logs |

*资料来源：[packages/@monomind/cli/src/commands/mcp.ts:20-45](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/mcp.ts)*

## Neural Learning (SONA)

Self-Optimizing Neural Adaptation provides:

- **Pattern Recognition**: Improves agent routing over time
- **Trajectory Tracking**: Identifies what works and what doesn't
- **Automatic Model Adaptation**: <0.05ms overhead per decision

```mermaid
graph LR
    subgraph "SONA System"
        input[Task Input]
        pattern[Pattern Recognition]
        route[Agent Routing]
        track[Trajectory Tracking]
        adapt[Model Adaptation]
        output[Optimized Output]
    end

    input --> pattern
    pattern --> route
    route --> output
    output --> track
    track --> adapt
    adapt --> pattern
```

## Command Suggestion System

The CLI includes a fuzzy matching system for typo correction:

```mermaid
graph TD
    input[User Input]
    input --> levenshtein[Levenshtein Distance]
    input --> similarity[Similarity Score]
    levenshtein --> threshold[Threshold Check]
    similarity --> threshold
    threshold --> suggestions[Suggestions]
```

| Component | Function |
|-----------|----------|
| `levenshteinDistance` | Calculate edit distance between strings |
| `similarityScore` | Compute similarity ratio |
| `findSimilar` | Find commands within similarity threshold |
| `suggestCommand` | Generate command suggestions |
| `COMMON_TYPOS` | Predefined typo mappings |

*资料来源：[packages/@monomind/cli/src/suggest.ts:1-80](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/suggest.ts)*

## Data Flow Architecture

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant MCP
    participant Shared
    participant Memory
    participant Monograph

    User->>CLI: Execute command
    CLI->>MCP: Route to MCP server
    MCP->>Shared: Core orchestration
    Shared->>Memory: Store/retrieve
    Shared->>Monograph: Query graph
    Memory-->>Shared: Results
    Monograph-->>Shared: Dependencies
    Shared-->>MCP: Processed data
    MCP-->>CLI: Response
    CLI-->>User: Output
```

## Extended Configuration

The Monograph system supports extended configuration for enterprise use:

```typescript
// From packages/@monomind/monograph/src/config/types.ts:70-90
export interface ExtendedMonographConfig extends MonographConfig {
  extends?: string[];
  sealed?: boolean;
  includeEntryExports?: boolean;
  publicPackages?: string[];
  dynamicallyLoaded?: string[];
  codeowners?: string;
  ignoreDependencies?: string[];
  ignoreExportsUsedInFile?: boolean | { 
    interface?: boolean; 
    typeAlias?: boolean 
  };
  usedClassMembers?: Array<string | { 
    extends?: string[]; 
    implements?: string[]; 
    members: string[] 
  }>;
  duplicates?: DuplicatesConfig;
}
```

## Summary

Monomind's architecture is built on a modular, layered approach:

1. **CLI Layer**: User-facing command interface with subcommands for all major features
2. **Core Layer**: Shared orchestration logic and MCP protocol implementation
3. **Capability Layer**: Specialized systems for memory, knowledge graphs, and security
4. **Agent Layer**: Pluggable agent pool with WASM sandboxing support

The architecture supports horizontal scaling through agent pooling and vertical optimization through dedicated WASM runtime execution for sensitive operations.

---

<a id='packages-core'></a>

## Core Packages

### 相关页面

相关主题：[Architecture Overview](#architecture-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/cli/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/README.md)
- [packages/@monomind/memory/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/README.md)
- [packages/@monomind/hooks/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/hooks/README.md)
- [packages/@monomind/embeddings/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/embeddings/README.md)
- [packages/implementation/adrs/README.md](https://github.com/monoes/monomind/blob/main/packages/implementation/adrs/README.md)
- [packages/@monomind/cli/src/init/claudemd-generator.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/init/claudemd-generator.ts)
- [packages/@monomind/aidefence/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/aidefence/README.md)
</details>

# Core Packages

Monomind is organized as a monorepo with specialized packages that work together to provide AI coordination, memory management, neural learning, and multi-agent orchestration. The core packages form the foundation of this ecosystem, enabling Claude Code and other AI systems to maintain context, learn patterns, and coordinate complex tasks across sessions.

## Architecture Overview

```mermaid
graph TD
    subgraph "Core Packages"
        CLI[@monomind/cli]
        MEM[@monomind/memory]
        HOOKS[@monomind/hooks]
        EMBED[@monomind/embeddings]
        NEURAL[@monomind/neural]
        SHARED[@monomind/shared]
    end
    
    CLI --> SHARED
    MEM --> EMBED
    HOOKS --> SHARED
    EMBED --> NEURAL
    NEURAL --> SHARED
    
    CLI --> MEM
    CLI --> HOOKS
```

The core packages follow a layered architecture where the `shared` package provides common utilities and types that all other packages depend on, while specialized packages handle specific concerns like memory storage, embedding generation, neural learning, and command execution.

## @monomind/cli

The CLI package is the primary command-line interface for Monomind, providing a unified entry point for all operations. It serves as the orchestration layer that coordinates memory, hooks, neural learning, and multi-agent capabilities.

### Command Structure

The CLI exposes commands organized by functional domain:

| Command | Description | Status |
|---------|-------------|--------|
| `agent` | Agent management, metrics, pool, WASM runtime | ✅ Complete |
| `task` | Task creation, status, list, completion | ✅ Complete |
| `session` | Session save, restore, list, export/import | ✅ Complete |
| `config` | Configuration get, set, list, reset | ✅ Complete |
| `memory` | Store, retrieve, list, delete, search | ✅ Complete |
| `workflow` | Create, execute, list, status, delete | ✅ Complete |
| `mcp` | MCP server start, stop, status, tools | ✅ Complete |
| `neural` | Neural pattern training, MoE, Flash Attention | Advanced |
| `security` | Security scanning, CVE detection, threat modeling | Advanced |
| `performance` | Performance profiling, benchmarking | Advanced |
| `providers` | AI provider management, models, configurations | Advanced |
| `plugins` | Plugin management, installation, lifecycle | Advanced |
| `deployment` | Deployment management, environments, rollbacks | Advanced |
| `claims` | Claims-based authorization, access control | Advanced |
| `embeddings` | Embedding management, models, cache | Advanced |

资料来源：[packages/@monomind/cli/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/README.md)

### CLAUDE.md Generation

The CLI includes a sophisticated CLAUDE.md generator that creates project-specific configuration files for Claude Code. The generator supports multiple templates with varying levels of detail:

```typescript
export const CLAUDE_MD_TEMPLATES: Array<{ name: ClaudeMdTemplate; description: string }> = [
  { name: 'minimal', description: 'Quick start — behavioral rules, anti-drift' },
  { name: 'standard', description: 'Full documentation with all sections' },
  { name: 'full', description: 'Complete including hooks and learning' },
  { name: 'security', description: 'Security-focused template' },
  { name: 'performance', description: 'Performance-optimized template' },
  { name: 'solo', description: 'Single-agent workflow template' }
];
```

Each template includes different combinations of sections such as behavioral rules, coding principles, file organization, project architecture, build and test instructions, security rules, concurrency rules, swarm orchestration, and intelligence system configuration.

资料来源：[packages/@monomind/cli/src/init/claudemd-generator.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/init/claudemd-generator.ts)

### Session Management

The session command provides comprehensive session state management:

```bash
monomind session list      # List all saved sessions
monomind session save      # Save current session state
monomind session restore   # Restore a saved session
monomind session delete    # Delete a saved session
monomind session export    # Export session to file
monomind session import    # Import session from file
monomind session current   # Show current active session
```

资料来源：[packages/@monomind/cli/src/commands/session.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/session.ts)

### Agent Capabilities

The CLI supports multiple agent types, each with specialized capabilities:

| Agent Type | Capabilities |
|------------|--------------|
| `coder` | code-generation, refactoring, debugging, testing |
| `researcher` | web-search, data-analysis, summarization, citation |
| `tester` | unit-testing, integration-testing, coverage-analysis |
| `reviewer` | code-review, security-audit, quality-check |
| `architect` | system-design, pattern-analysis, scalability |
| `coordinator` | task-orchestration, agent-management, workflow-control |
| `security-architect` | threat-modeling, security-patterns, compliance |
| `memory-specialist` | vector-search, agentdb, caching, optimization |
| `performance-engineer` | profiling, benchmarking, optimization |

资料来源：[packages/@monomind/cli/src/commands/agent.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/agent.ts)

### MCP Server Management

```bash
monomind mcp start     # Start MCP server
monomind mcp stop      # Stop MCP server
monomind mcp status    # Show server status
monomind mcp health    # Check server health
monomind mcp restart   # Restart MCP server
monomind mcp tools     # List available tools
monomind mcp toggle    # Enable/disable tools
monomind mcp exec      # Execute a tool
monomind mcp logs      # Show server logs
```

资料来源：[packages/@monomind/cli/src/commands/mcp.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/mcp.ts)

## @monomind/memory

The memory package provides a sophisticated memory system for AI agents, combining structured storage with semantic vector search capabilities.

### HybridBackend Architecture

The memory system uses a HybridBackend that combines SQLite for structured data with AgentDB for semantic search:

```typescript
const backend = new HybridBackend({
  embeddingGenerator: async (text) => myEmbeddingModel.embed(text),
  // A-MEM auto-linking is automatically active when embeddingGenerator is set
});
```

资料来源：[packages/@monomind/memory/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/README.md)

### A-MEM Auto-Linking

When configured with an embedding generator, the HybridBackend implements A-MEM (arxiv:2409.11987) auto-linking. Every stored entry automatically discovers its top-3 semantic neighbors and creates bidirectional references edges, implementing the Zettelkasten note-linking structure.

### Agent Memory Scopes

The memory system supports multiple scope levels for different use cases:

| Scope | Path | Use Case |
|-------|------|----------|
| `system` | `<gitRoot>/.claude/agent-memory-system/<agent>/` | System-wide learnings |
| `project` | `<gitRoot>/.claude/agent-memory/<agent>/` | Project-specific learnings |
| `local` | `<gitRoot>/.claude/agent-memory-local/<agent>/` | Machine-local data |
| `user` | `~/.claude/agent-memory/<agent>/` | Cross-project user knowledge |

### Memory Utilities

```typescript
import {
  resolveAgentMemoryDir,  // Get scope directory path
  createAgentBridge,       // Create scoped AutoMemoryBridge
  transferKnowledge,       // Cross-agent knowledge sharing
  listAgentScopes,         // Discover existing agent scopes
} from '@monomind/memory';

// Resolve path for an agent scope
const dir = resolveAgentMemoryDir('my-agent', 'project');
// → /workspaces/my-project/.claude/agent-memory/my-agent/

// List all agent scopes in a directory
const scopes = await listAgentScopes('/workspaces/my-project');
```

资料来源：[packages/@monomind/memory/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/README.md)

### Memory Commands

```bash
monomind memory init         # Initialize memory database (sql.js)
monomind memory store        # Store data in memory
monomind memory edit         # Edit an entry
monomind memory retrieve     # Retrieve data from memory
monomind memory search       # Semantic/vector search
monomind memory list         # List memory entries
monomind memory delete       # Delete an entry
monomind memory templates    # Show best-practice entry templates
monomind memory stats        # Show statistics
monomind memory configure    # Configure backend
monomind memory cleanup      # Clean expired entries
monomind memory compress     # Compress database
monomind memory export       # Export memory to file
monomind memory import       # Import from file
```

资料来源：[packages/@monomind/cli/src/commands/memory.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/memory.ts)

## @monomind/hooks

The hooks package provides an event-driven system for extending and customizing Monomind behavior.

### Hook Configuration

Hooks are configured in `monomind.config.json` with support for both external scripts and built-in commands:

```json
{
  "hooks": {
    "preCommand": "/path/to/pre-command-hook.sh",
    "postCommand": "/path/to/post-command-hook.sh"
  },
  "statusLine": {
    "type": "command",
    "command": "statusline"
  }
}
```

资料来源：[packages/@monomind/hooks/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/hooks/README.md)

### Hook Types

| Hook Type | Purpose | Trigger Point |
|-----------|---------|---------------|
| `preCommand` | Run before command execution | Before any CLI command |
| `postCommand` | Run after command execution | After any CLI command |
| `statusLine` | Custom status display | During active sessions |
| `preAgent` | Pre-processing for agent tasks | Before agent dispatch |
| `postAgent` | Post-processing for agent results | After agent completion |

### Package Dependencies

The hooks system depends on and integrates with:

- `@monomind/shared` - Shared utilities and types
- `@monomind/neural` - Neural network and SONA learning
- `@monomind/swarm` - Multi-agent coordination
- `@monomind/memory` - AgentDB memory system

资料来源：[packages/@monomind/hooks/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/hooks/README.md)

## @monomind/embeddings

The embeddings package provides embedding generation, caching, and transformation capabilities.

### Features

| Feature | Description |
|---------|-------------|
| Persistent Cache | SQLite-based cache with configurable TTL (default: 30 days) |
| Normalization | L2 normalization for consistent vector comparisons |
| Hyperbolic Conversion | Transform embeddings to Poincaré ball model |
| Neural Operations | Drift detection, storage, and recall |

### Cache Configuration

```typescript
const service = createEmbeddingService({
  provider: "openai",
  apiKey: process.env.OPENAI_API_KEY!,
  persistentCache: {
    enabled: true,
    dbPath: "./cache/embeddings.db",
    maxSize: 50000,
    ttlMs: 30 * 24 * 60 * 60 * 1000, // 30 days
  },
  normalization: "l2",
});
```

### Embeddings CLI Commands

```bash
# Document chunking
monomind embeddings chunk document.txt --strategy sentence --max-size 512

# Normalize embedding file
monomind embeddings normalize embeddings.json --type l2 -o normalized.json

# Convert to hyperbolic
monomind embeddings hyperbolic embeddings.json -o poincare.json

# Neural operations
monomind embeddings neural drift --baseline "context" --input "check this"
monomind embeddings neural store --id mem-1 --content "data"
monomind embeddings neural recall "query" --top-k 5

# List/download models
monomind embeddings models list
monomind embeddings models download all-MiniLM-L6-v2

# Cache management
monomind embeddings cache stats
monomind embeddings cache clear --older-than 7d
```

资料来源：[packages/@monomind/embeddings/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/embeddings/README.md)

### Related Packages

- `@monomind/memory` - HNSW indexing and vector storage
- `@monomind/providers` - Multi-LLM provider system
- `@monomind/neural` - SONA learning system

## @monomind/aidefence

The aidefence package provides security and AI safety features for the Monomind ecosystem.

### Capabilities

The package includes patterns for detecting and preventing various security issues and inappropriate AI behaviors. It integrates with the CLI for security scanning operations.

### Related Packages

- `@monomind/cli` - CLI with security commands
- `agentdb` - HNSW vector database
- `monomind` - Full AI coordination system

资料来源：[packages/@monomind/aidefence/README.md](https://github.com/monoes/monomind/blob/main/packages/@monomind/aidefence/README.md)

## @monomind/shared

The shared package contains common utilities, types, and interfaces used across all Monomind packages.

### Responsibilities

- Type definitions shared across packages
- Common utility functions
- Interface contracts for package integration
- Configuration schemas and validation

### Dependencies

Other core packages depend on `@monomind/shared` for common functionality, ensuring consistent types and utilities across the ecosystem.

## Package Relationships

```mermaid
graph TD
    CLI -->|depends on| SHARED
    MEM -->|depends on| SHARED
    HOOKS -->|depends on| SHARED
    EMBED -->|depends on| NEURAL
    NEURAL -->|depends on| SHARED
    
    CLI -->|coordinates| MEM
    CLI -->|coordinates| HOOKS
    CLI -->|uses| EMBED
    
    MEM -->|uses| EMBED
    
    subgraph "Core Packages"
        CLI[@monomind/cli]
        MEM[@monomind/memory]
        HOOKS[@monomind/hooks]
        EMBED[@monomind/embeddings]
        NEURAL[@monomind/neural]
        SHARED[@monomind/shared]
    end
```

## Installation and Setup

```bash
# Clone the repository
git clone https://github.com/monoes/monomind.git
cd monomind

# Install dependencies
pnpm install

# Run health check and auto-fix
monomind doctor --fix
```

## Development Workflow

The monorepo uses pnpm workspaces with the following structure:

```
monomind/
├── packages/
│   ├── @monomind/
│   │   ├── cli/
│   │   ├── memory/
│   │   ├── hooks/
│   │   ├── embeddings/
│   │   ├── neural/
│   │   ├── shared/
│   │   ├── aidefence/
│   │   └── ...
│   ├── plugins/
│   └── implementation/
```

## Version Compatibility

The Monomind packages follow semantic versioning with alpha releases for new features. The current CLI version is `@monomind/cli@3.0.0-alpha.11` (2026-01-07) with complete support for all core commands including session, task, config, memory, and workflow management.

资料来源：[packages/implementation/adrs/README.md](https://github.com/monoes/monomind/blob/main/packages/implementation/adrs/README.md)

---

<a id='agent-catalog'></a>

## Agent Catalog

### 相关页面

相关主题：[Agent Routing System](#agent-routing), [Swarm Topologies](#swarm-topologies)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/cli/src/commands/agent.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/agent.ts)
- [packages/@monomind/cli/src/commands/agent-wasm.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/agent-wasm.ts)
- [packages/@monomind/cli/src/agents/registry-builder.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/agents/registry-builder.ts)
- [packages/@monomind/cli/src/agents/managed-agent.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/agents/managed-agent.ts)
- [packages/@monomind/swarm/src/workers/worker-dispatch.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/workers/worker-dispatch.ts)
</details>

# Agent Catalog

## Overview

The Agent Catalog is a comprehensive system within Monomind that manages, organizes, and provides access to a diverse collection of specialized AI agents. It serves as the central registry and management hub for all agent types, capabilities, and configurations within the platform.

The catalog provides:
- A unified registry of agent types with their specific capabilities
- Dynamic agent management including creation, monitoring, and lifecycle control
- WASM-based sandboxed agent execution
- Worker dispatch and trigger configurations for autonomous task handling

资料来源：[packages/@monomind/cli/src/commands/agent.ts:1-50]()

## Agent Types and Capabilities

Monomind's Agent Catalog defines multiple specialized agent types, each with distinct capabilities optimized for specific tasks.

### Core Agent Types

| Agent Type | Capabilities | Primary Use Case |
|------------|--------------|------------------|
| `coder` | code-generation, refactoring, debugging, testing | Software development tasks |
| `researcher` | web-search, data-analysis, summarization, citation | Information gathering and analysis |
| `tester` | unit-testing, integration-testing, coverage-analysis, automation | Quality assurance |
| `reviewer` | code-review, security-audit, quality-check, documentation | Code inspection and review |
| `architect` | system-design, pattern-analysis, scalability, documentation | System architecture planning |
| `coordinator` | task-orchestration, agent-management, workflow-control | Multi-agent coordination |
| `security-architect` | threat-modeling, security-patterns, compliance, audit | Security-focused design |
| `memory-specialist` | vector-search, agentdb, caching, optimization | Memory and knowledge management |
| `performance-engineer` | performance-analysis, optimization, benchmarking, profiling | Performance tuning |

资料来源：[packages/@monomind/cli/src/commands/agent.ts:45-80]()

### Agent Commands

The CLI provides several commands for agent management:

```bash
monomind agent <subcommand>

Subcommands:
  metrics      - Show agent metrics
  pool         - Manage agent pool
  health       - Show agent health
  logs         - Show agent logs
  wasm-status  - Check WASM runtime availability
  wasm-create  - Create a WASM-sandboxed agent
  wasm-prompt  - Send a prompt to a WASM agent
  wasm-gallery - List WASM agent gallery templates
```

资料来源：[packages/@monomind/cli/src/commands/agent.ts:20-30]()

## Agent Registry System

The Agent Registry is the core component that maintains agent definitions, configurations, and metadata.

### Registry Architecture

```mermaid
graph TD
    A[Agent Request] --> B[Registry Builder]
    B --> C[Agent Registry]
    C --> D[Agent Type Resolution]
    D --> E[Managed Agent Instance]
    E --> F[Execution Context]
    F --> G[Response/Metrics]
```

### Registry Builder

The `RegistryBuilder` class constructs and manages the agent registry, providing methods to register, retrieve, and manage agent configurations.

**Key Responsibilities:**
- Build agent registry from configuration sources
- Validate agent type definitions
- Provide lookup and discovery mechanisms
- Support dynamic agent registration

资料来源：[packages/@monomind/cli/src/agents/registry-builder.ts:1-50]()

## Managed Agents

Managed Agents provide a structured runtime environment for agent execution with integrated lifecycle management, monitoring, and resource allocation.

### Managed Agent Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Initializing
    Initializing --> Ready: Initialization Complete
    Ready --> Running: Task Assigned
    Running --> Ready: Task Complete
    Running --> Paused: Suspend Request
    Paused --> Running: Resume Request
    Ready --> Terminated: Shutdown
    Running --> Terminated: Force Shutdown
    Terminated --> [*]
```

### Agent Management Features

| Feature | Description |
|---------|-------------|
| Lifecycle Control | Start, pause, resume, and terminate agents |
| Health Monitoring | Track agent health status and metrics |
| Pool Management | Manage agent pools for scaling |
| Log Aggregation | Collect and store agent execution logs |
| Resource Allocation | Assign CPU, memory, and execution quotas |

资料来源：[packages/@monomind/cli/src/agents/managed-agent.ts:1-60]()

## WASM Agent Gallery

The WASM Agent system provides sandboxed agent execution using WebAssembly, offering enhanced security and portability.

### WASM Agent Commands

```bash
# Check WASM runtime status
monomind agent wasm-status

# List available templates
monomind agent wasm-gallery

# Create a new WASM agent
monomind agent wasm-create -t <template-id>

# Send prompt to WASM agent
monomind agent wasm-prompt <agent-id> <prompt>
```

### Gallery Template Structure

Templates in the gallery include:
- **id**: Unique template identifier
- **name**: Human-readable name
- **category**: Template category (coding, research, security, etc.)
- **description**: Brief description of capabilities
- **version**: Template version

```typescript
interface WASMTemplate {
  id: string;
  name: string;
  category: string;
  description: string;
  version: string;
}
```

资料来源：[packages/@monomind/cli/src/commands/agent-wasm.ts:1-80]()

## Worker Dispatch System

The Agent Catalog integrates with a worker dispatch system for autonomous task handling based on trigger patterns.

### Trigger Categories

| Category | Trigger Patterns | Priority |
|----------|------------------|----------|
| `codebase` | explore codebase, project structure, dependency graph | high |
| `preload` | preload, cache ahead, prefetch, warm cache | normal |
| `deepdive` | deep dive, analyze thoroughly, in-depth analysis | normal |
| `document` | document, generate docs, add documentation, write readme | low |
| `refactor` | refactor, clean up code, improve code quality | normal |
| `benchmark` | benchmark, performance test, measure speed | normal |
| `testgaps` | test coverage, missing tests, untested code | normal |

### Trigger Configuration

```typescript
const TRIGGER_CONFIGS = {
  ultralearn: {
    description: 'Deep knowledge acquisition and learning',
    priority: 'normal',
  },
  preload: {
    description: 'Resource preloading for faster access',
    priority: 'normal',
  },
  deepdive: {
    description: 'Thorough code analysis',
    priority: 'normal',
  },
  document: {
    description: 'Documentation generation',
    priority: 'low',
  },
  refactor: {
    description: 'Code refactoring suggestions',
    priority: 'normal',
  },
  benchmark: {
    description: 'Performance benchmarking',
    priority: 'normal',
  },
  testgaps: {
    description: 'Test coverage analysis',
    priority: 'normal',
  },
};
```

资料来源：[packages/@monomind/swarm/src/workers/worker-dispatch.ts:1-100]()

## Agent Pool Management

The Agent Catalog supports managing pools of agents for scalable task processing.

### Pool Operations

```bash
# View pool status
monomind agent pool status

# Scale pool
monomind agent pool scale <agent-type> <count>

# Release idle agents
monomind agent pool cleanup
```

### Pool Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `minSize` | number | 1 | Minimum pool size |
| `maxSize` | number | 10 | Maximum pool size |
| `idleTimeout` | number | 300000 | Idle timeout in milliseconds |
| `scaleUpThreshold` | number | 0.8 | Scale up utilization threshold |
| `scaleDownThreshold` | number | 0.2 | Scale down utilization threshold |

## Health Monitoring

Agents in the catalog are continuously monitored for health status.

### Health Check Response

```typescript
interface HealthCheckResponse {
  status: 'healthy' | 'degraded' | 'unhealthy';
  agentId: string;
  uptime: number;
  lastTask: string;
  metrics: {
    cpu: number;
    memory: number;
    tasksCompleted: number;
    errors: number;
  };
}
```

### CLI Health Command

```bash
monomind agent health <agent-id>
```

## CLI Integration

The Agent Catalog is accessible through the Monomind CLI with the following command structure:

```bash
monomind agent <command> [options]
```

### Available Commands Summary

| Command | Description |
|---------|-------------|
| `metrics` | Display agent performance metrics |
| `pool` | Manage agent pool operations |
| `health` | Show agent health status |
| `logs` | Display agent execution logs |
| `wasm-status` | Check WASM runtime availability |
| `wasm-create` | Create new WASM-sandboxed agent |
| `wasm-prompt` | Send prompt to WASM agent |
| `wasm-gallery` | List available WASM templates |

资料来源：[packages/@monomind/cli/src/commands/agent.ts:15-35]()

## See Also

- [Memory System](../memory/) - Vector memory and knowledge storage
- [Hooks System](../hooks/) - Intelligent automation hooks
- [Monograph](../monograph/) - Knowledge graph analysis
- [Swarm Orchestration](../swarm/) - Multi-agent coordination

---

<a id='agent-routing'></a>

## Agent Routing System

### 相关页面

相关主题：[Agent Catalog](#agent-catalog), [Swarm Topologies](#swarm-topologies)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/routing/src/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/routing/src/index.ts)
- [packages/@monomind/routing/src/route-layer.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/routing/src/route-layer.ts)
- [packages/@monomind/routing/src/capability-index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/routing/src/capability-index.ts)
- [packages/@monomind/routing/src/llm-fallback.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/routing/src/llm-fallback.ts)
- [packages/@monomind/routing/src/routes/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/routing/src/routes/index.ts)
- [packages/@monomind/cli/src/commands/guidance.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/guidance.ts)
- [packages/@monomind/cli/src/mcp-tools/guidance-tools.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/mcp-tools/guidance-tools.ts)
</details>

# Agent Routing System

## Overview

The Agent Routing System is a core subsystem within Monomind that intelligently directs tasks to the most appropriate specialized agent based on task characteristics, agent capabilities, historical performance, and contextual information. It serves as the orchestration brain that enables multi-agent coordination across the entire platform.

The routing system operates with dual-mode intelligence:

- **LLM-powered routing** for complex task understanding: <2s response time
- **Keyword-based fallback** for rapid classification: <5ms response time

资料来源：[README.md](https://github.com/monoes/monomind/blob/main/README.md)

## Architecture

The routing system follows a layered architecture that separates concerns between capability matching, route resolution, and intelligence fallback mechanisms.

```mermaid
graph TD
    A[Task Input] --> B[Route Layer]
    B --> C{Capability Index Match?}
    C -->|High Confidence| D[Direct Route]
    C -->|Low Confidence| E[LLM Fallback]
    C -->|Exact Match| F[Keyword Fallback]
    E --> G[Seraphine Routing Patterns]
    G --> H[Agent Spawn]
    D --> H
    F --> H
```

### Core Components

| Component | Location | Responsibility |
|-----------|----------|----------------|
| Route Layer | `packages/@monomind/routing/src/route-layer.ts` | Central orchestration, request dispatch |
| Capability Index | `packages/@monomind/routing/src/capability-index.ts` | Agent capability registry and matching |
| LLM Fallback | `packages/@monomind/routing/src/llm-fallback.ts` | Semantic routing via LLM inference |
| Routing Patterns | `packages/@monomind/cli/src/transfer/models/seraphine.ts` | Predefined task-to-agent mappings |
| Guidance Commands | `packages/@monomind/cli/src/commands/guidance.ts` | CLI integration layer |
| MCP Tools | `packages/@monomind/cli/src/mcp-tools/guidance-tools.ts` | Model Context Protocol integration |

资料来源：[packages/@monomind/routing/src/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/routing/src/index.ts)

## Routing Pattern System

### Seraphine Routing Patterns

The system defines comprehensive routing patterns through the `SERAPHINE_ROUTING_PATTERNS` array. Each pattern contains:

| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Unique pattern identifier |
| `trigger` | string | Regex or keyword pattern for task matching |
| `action` | string | Command to execute (e.g., "spawn coder agent") |
| `confidence` | number | Base confidence score (0-1) |
| `usageCount` | number | Historical execution count |
| `successRate` | number | Historical success rate (0-1) |
| `context` | object | Additional metadata (category, priority) |

资料来源：[packages/@monomind/cli/src/transfer/models/seraphine.ts:15-80](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/transfer/models/seraphine.ts)

### Default Routing Patterns

| Pattern ID | Trigger Keywords | Action | Confidence | Success Rate |
|------------|------------------|--------|------------|--------------|
| `route-code-to-coder` | implement, code, write, create function, build feature | Spawn coder agent | 0.95 | 0.92 |
| `route-test-to-tester` | test, validate, verify, check, ensure quality | Spawn tester agent | 0.93 | 0.89 |
| `route-review-to-reviewer` | review, audit, analyze code, check security | Spawn reviewer agent | 0.91 | 0.87 |
| `route-research-to-researcher` | research, investigate, explore, find, search codebase | Spawn researcher agent | 0.94 | 0.88 |

资料来源：[packages/@monomind/cli/src/transfer/models/seraphine.ts:25-70](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/transfer/models/seraphine.ts)

## Capability Index

The Capability Index maintains a registry of all available agents and their documented capabilities, enabling efficient matching between incoming tasks and suitable agents.

### Data Model

```typescript
interface CapabilityEntry {
  agentType: string;
  capabilities: string[];
  specializations: string[];
  supportedLanguages: string[];
  framework: string;
  lastUpdated: Date;
}
```

### Matching Algorithm

1. **Exact Match**: Task keywords directly match capability keywords
2. **Fuzzy Match**: LLM-based semantic similarity scoring
3. **Fallback Match**: Keyword-based pattern matching with reduced confidence

资料来源：[packages/@monomind/routing/src/capability-index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/routing/src/capability-index.ts)

## LLM Fallback System

When the capability index cannot confidently match a task, the system escalates to LLM-powered routing. This module handles the fallback mechanism.

### Configuration Parameters

| Parameter | Default | Description |
|-----------|---------|-------------|
| `timeout` | 2000ms | Maximum time for LLM inference |
| `maxRetries` | 3 | Retry attempts on failure |
| `confidenceThreshold` | 0.7 | Minimum confidence to accept LLM decision |
| `fallbackToKeyword` | true | Enable keyword fallback on LLM failure |

### Workflow

```mermaid
graph LR
    A[Task] --> B{Confidence >= Threshold?}
    B -->|Yes| C[Return Route]
    B -->|No| D[LLM Inference]
    D --> E{Result Valid?}
    E -->|Yes| F[Update Patterns]
    E -->|No| G[Keyword Fallback]
    F --> C
    G --> H[Default Agent]
```

资料来源：[packages/@monomind/routing/src/llm-fallback.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/routing/src/llm-fallback.ts)

## CLI Integration

### Route Command

```bash
# Basic routing
monomind hooks route --task "fix bug"

# Q-Learning enhanced routing (requires ruvector)
monomind route "task" --q-learning

# Coverage-aware routing
monomind route "task" --coverage-aware
```

### Guidance Commands

The guidance subsystem provides additional routing intelligence through CLI commands:

```bash
# Display guidance help
monomind guidance --help

# Show routing status
monomind guidance status

# Analyze task complexity
monomind guidance analyze --task "implement webhook retry logic"
```

资料来源：[packages/@monomind/cli/src/commands/guidance.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/guidance.ts)

## MCP Tools Integration

The routing system exposes functionality through the Model Context Protocol (MCP), enabling programmatic access for external integrations.

### Available Tools

| Tool | Handler | Description |
|------|---------|-------------|
| `hooks/route` | `routeTool.handler` | Execute task routing with explanation |
| `hooks/routeWithContext` | `routeWithContextTool.handler` | Route with additional context |
| `guidance/analyze` | `analyzeTool.handler` | Analyze task complexity |

### Usage Example

```typescript
import { hooksMCPTools, getHooksTool } from '@monomind/hooks';

const routeTool = getHooksTool('hooks/route');
const result = await routeTool.handler({
  task: 'Implement user authentication',
  includeExplanation: true,
});

console.log(`Recommended agent: ${result.recommendedAgent}`);
console.log(`Confidence: ${result.confidence}%`);
```

资料来源：[packages/@monomind/cli/src/mcp-tools/guidance-tools.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/mcp-tools/guidance-tools.ts)

## Advanced Routing Features

### Q-Learning Router (ruvector Integration)

For production environments requiring advanced routing decisions, the system integrates with ruvector for Q-learning-based agent selection:

- Learns from historical routing decisions
- Optimizes for task completion rate
- Adapts to team-specific patterns

资料来源：[packages/implementation/adrs/README.md](https://github.com/monoes/monomind/blob/main/packages/implementation/adrs/README.md)

### Coverage-Aware Routing

Routes tasks based on code coverage analysis, directing work to agents with relevant file expertise:

```bash
monomind route "task" --coverage-aware
```

### AST Analysis Routing

For code modification tasks, the routing system can leverage AST (Abstract Syntax Tree) analysis to match agents with expertise in the relevant code structure:

```bash
monomind analyze ast src/
```

资料来源：[packages/implementation/adrs/README.md](https://github.com/monoes/monomind/blob/main/packages/implementation/adrs/README.md)

## Performance Characteristics

| Metric | Value | Mode |
|--------|-------|------|
| Agent routing (LLM) | <2s | Full semantic understanding |
| Agent routing (keyword) | <5ms | Pattern matching fallback |
| Pattern lookup | <1ms | In-memory index |
| Capability matching | <2ms | Optimized trie search |

资料来源：[README.md](https://github.com/monoes/monomind/blob/main/README.md)

## Extending the Routing System

### Adding Custom Patterns

To extend routing capabilities, add new patterns to the Seraphine configuration:

```typescript
import { SERAPHINE_ROUTING_PATTERNS } from './models/seraphine';

const customPattern: RoutingPattern = {
  id: 'route-custom-task',
  trigger: 'your-trigger-keywords',
  action: 'spawn your-agent',
  confidence: 0.85,
  usageCount: 0,
  successRate: 0.0,
  context: {
    category: 'custom',
    priority: 'medium',
  },
};

SERAPHINE_ROUTING_PATTERNS.push(customPattern);
```

### Custom Capability Index

For specialized agent registries:

```typescript
import { CapabilityIndex } from '@monomind/routing';

const customIndex = new CapabilityIndex({
  includeBuiltIn: true,
  customAgents: [...],
  scoringWeights: {
    keyword: 0.4,
    semantic: 0.4,
    historical: 0.2,
  },
});
```

## Summary

The Agent Routing System provides intelligent, adaptive task-to-agent matching through a multi-tier architecture:

1. **Capability Index** for fast, accurate matching of known patterns
2. **LLM Fallback** for semantic understanding of novel tasks
3. **Keyword Fallback** for guaranteed routing with minimal latency
4. **Seraphine Patterns** for configurable, business-specific routing rules
5. **MCP Integration** for programmatic and external system access

This design ensures the routing system scales from simple keyword matching to complex semantic analysis while maintaining predictable performance characteristics.

---

<a id='swarm-topologies'></a>

## Swarm Topologies

### 相关页面

相关主题：[Consensus Protocols](#consensus-protocols), [Agent Catalog](#agent-catalog)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/swarm/src/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/index.ts)
- [packages/@monomind/swarm/src/unified-coordinator.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/unified-coordinator.ts)
- [packages/@monomind/swarm/src/attention-coordinator.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/attention-coordinator.ts)
- [packages/@monomind/swarm/src/coordination/swarm-hub.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/coordination/swarm-hub.ts)
- [packages/@monomind/swarm/src/coordination/task-orchestrator.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/coordination/task-orchestrator.ts)
- [packages/@monomind/swarm/src/topology-manager.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/topology-manager.ts)
- [packages/@monomind/cli/src/commands/swarm.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/commands/swarm.ts)
- [packages/@monomind/cli/src/swarm/communication-graph.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/swarm/communication-graph.ts)
- [packages/@monomind/cli/src/swarm/flow-enforcer.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/swarm/flow-enforcer.ts)
</details>

# Swarm Topologies

## Overview

Swarm Topologies define the structural organization and communication patterns between agents in the Monomind multi-agent orchestration system. These topologies determine how agents connect, collaborate, share information, and coordinate tasks within a swarm.

The topology system provides flexible, pluggable architectures that can adapt to different task requirements—from simple linear workflows to complex hierarchical structures with consensus-based decision making.

资料来源：[packages/@monomind/swarm/src/topology-manager.ts]()

## Architecture Overview

### Core Topology Components

The swarm topology system consists of several interconnected components:

```mermaid
graph TD
    TM[Topology Manager] --> SH[Swarm Hub]
    TM --> TO[Task Orchestrator]
    TM --> AC[Attention Coordinator]
    TM --> UC[Unified Coordinator]
    
    SH --> CG[Communication Graph]
    SH --> FE[Flow Enforcer]
    
    TO --> Agents[Agent Pool]
    AC --> Memory[Memory System]
    UC --> Hooks[Hooks System]
```

### Component Responsibilities

| Component | Purpose |
|-----------|---------|
| **Topology Manager** | Central registry and factory for managing different topology types |
| **Swarm Hub** | Central coordination point for inter-agent communication |
| **Task Orchestrator** | Manages task distribution and workflow execution |
| **Attention Coordinator** | Manages agent focus and priority-based task routing |
| **Unified Coordinator** | Provides unified interface for all coordination operations |
| **Communication Graph** | Tracks and enforces communication patterns between agents |
| **Flow Enforcer** | Validates and enforces workflow constraints |

资料来源：[packages/@monomind/swarm/src/coordination/swarm-hub.ts]()
资料来源：[packages/@monomind/swarm/src/coordination/task-orchestrator.ts]()

## Topology Types

### Linear Topology (Pipeline)

Agents are arranged in a sequential chain where output from one agent becomes input for the next. Best suited for tasks requiring strict sequential processing.

```mermaid
graph LR
    A[Agent 1] --> B[Agent 2]
    B --> C[Agent 3]
    C --> D[Agent 4]
```

### Hierarchical Topology

Agents are organized in parent-child relationships with clear authority chains. Specialized sub-agents report to coordinator agents.

```mermaid
graph TD
    Root[Root Coordinator]
    Root --> C1[Coordinator 1]
    Root --> C2[Coordinator 2]
    C1 --> S1[Specialist 1.1]
    C1 --> S2[Specialist 1.2]
    C2 --> S3[Specialist 2.1]
    C2 --> S4[Specialist 2.2]
```

### Mesh Topology

Agents can communicate directly with any other agent. Provides maximum flexibility but requires careful flow enforcement.

```mermaid
graph TD
    A[Agent A] <--> B[Agent B]
    A <--> C[Agent C]
    A <--> D[Agent D]
    B <--> C
    B <--> D
    C <--> D
```

### Star Topology

A central coordinator agent mediates all communication. All other agents communicate exclusively through the hub.

```mermaid
graph TD
    Hub[Central Hub]
    Hub --> A[Agent A]
    Hub --> B[Agent B]
    Hub --> C[Agent C]
    Hub --> D[Agent D]
```

### Hive-Mind Topology

Distributed consensus-based topology where agents share a collective decision-making mechanism. All agents contribute to decisions through weighted voting or consensus algorithms.

资料来源：[packages/implementation/adrs/README.md]()
资料来源：[packages/@monomind/cli/src/commands/swarm.ts]()

## Swarm Hub

The Swarm Hub serves as the central orchestration point for the swarm topology. It manages:

### Communication Management

- Agent registration and deregistration
- Message routing between agents
- Broadcasting messages to agent groups
- Direct agent-to-agent communication channels

```typescript
interface HubConfig {
  topology: TopologyType;
  maxAgents: number;
  communicationGraph: CommunicationGraph;
  flowEnforcer: FlowEnforcer;
}
```

### Flow Enforcement

The Flow Enforcer component validates that communications follow the defined topology constraints:

```typescript
interface FlowEnforcer {
  validateConnection(source: AgentId, target: AgentId): boolean;
  enforceDirection(agent: AgentId, direction: 'upstream' | 'downstream'): boolean;
  validateMessageFlow(message: Message): ValidationResult;
}
```

资料来源：[packages/@monomind/swarm/src/coordination/swarm-hub.ts]()
资料来源：[packages/@monomind/cli/src/swarm/flow-enforcer.ts]()

## Communication Graph

The Communication Graph tracks the relationships and communication patterns between agents within the topology.

### Graph Structure

```typescript
interface CommunicationNode {
  agentId: AgentId;
  role: AgentRole;
  connections: Connection[];
  metrics: AgentMetrics;
}

interface Connection {
  target: AgentId;
  type: ConnectionType; // 'direct' | 'mediated' | 'broadcast'
  weight: number;
  lastActivity: Timestamp;
}
```

### Graph Operations

| Operation | Description |
|-----------|-------------|
| `addNode(agent)` | Register new agent in the graph |
| `removeNode(agentId)` | Unregister agent and update connections |
| `addEdge(source, target, type)` | Create communication link |
| `removeEdge(source, target)` | Remove communication link |
| `getPath(source, target)` | Find shortest communication path |
| `getNeighbors(agentId)` | Get all connected agents |

资料来源：[packages/@monomind/cli/src/swarm/communication-graph.ts]()

## Task Orchestration

The Task Orchestrator distributes and manages tasks across the topology based on the current topology structure.

### Task Distribution Strategies

| Strategy | Topology Suitability | Description |
|----------|---------------------|-------------|
| **Sequential** | Linear, Pipeline | Tasks flow through agents in order |
| **Parallel** | Mesh, Star | Tasks distributed to multiple agents simultaneously |
| **Hierarchical** | Hierarchical | Tasks delegated down the authority chain |
| **Broadcast** | Star, Mesh | Tasks sent to all relevant agents |
| **Consensus** | Hive-Mind | Tasks require collective approval |

### Task Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Pending: Task Created
    Pending --> Assigned: Orchestrator Routes
    Assigned --> InProgress: Agent Accepts
    InProgress --> Completed: Execution Done
    InProgress --> Blocked: Awaiting Dependencies
    Blocked --> InProgress: Dependencies Met
    Completed --> [*]
```

资料来源：[packages/@monomind/swarm/src/coordination/task-orchestrator.ts]()

## Attention Coordinator

The Attention Coordinator manages agent focus and priority-based routing, ensuring efficient resource utilization across the topology.

### Priority Management

Agents receive attention scores based on:

- Current task priority
- Agent specialization match
- Availability and load
- Historical performance metrics

```typescript
interface AttentionMetrics {
  focusScore: number;
  priority: number;
  specializationMatch: number;
  availabilityScore: number;
  performanceHistory: number;
}
```

资料来源：[packages/@monomind/swarm/src/attention-coordinator.ts]()

## Unified Coordinator

The Unified Coordinator provides a single interface for interacting with all topology components, simplifying complex swarm operations.

### API Surface

```typescript
interface UnifiedSwarmCoordinator {
  // Topology Management
  setTopology(type: TopologyType, config?: TopologyConfig): void;
  getTopology(): TopologyInfo;
  
  // Agent Management
  spawnAgent(type: AgentType, role?: AgentRole): AgentId;
  terminateAgent(agentId: AgentId): void;
  getActiveAgents(): AgentInfo[];
  
  // Communication
  sendMessage(from: AgentId, to: AgentId, message: Message): void;
  broadcast(from: AgentId, message: Message): void;
  
  // Task Management
  submitTask(task: Task): TaskId;
  getTaskStatus(taskId: TaskId): TaskStatus;
  cancelTask(taskId: TaskId): void;
  
  // Coordination
  achieveConsensus(agents: AgentId[], proposal: Proposal): ConsensusResult;
  delegateTask(task: Task, agent: AgentId): void;
}
```

资料来源：[packages/@monomind/swarm/src/unified-coordinator.ts]()

## CLI Integration

The Monomind CLI provides commands for managing and visualizing swarm topologies:

### Available Commands

```bash
# Initialize a swarm with specified topology
monomind swarm init --topology hierarchical

# Set topology type
monomind swarm topology set --type mesh

# Show current topology
monomind swarm topology show

# List agents in swarm
monomind swarm agents list

# View swarm status
monomind swarm status

# Initialize mesh topology
monomind swarm init mesh

# Spawn agent in swarm
monomind swarm agent spawn --type coder
```

### Swarm Subcommands

| Command | Description |
|---------|-------------|
| `swarm init` | Initialize a new swarm |
| `swarm init mesh` | Initialize mesh topology swarm |
| `swarm status` | Display swarm health and metrics |
| `swarm topology` | Manage topology settings |
| `swarm agents` | List and manage swarm agents |
| `swarm connect` | Connect to existing swarm |

资料来源：[packages/@monomind/cli/src/commands/swarm.ts]()

## Configuration

### Topology Configuration Options

```typescript
interface TopologyConfig {
  type: TopologyType;
  
  // General settings
  maxAgents: number;
  agentTimeout: number;
  
  // Topology-specific settings
  mesh?: {
    maxConnectionsPerAgent: number;
    connectionStrategy: 'random' | 'specialized' | 'full';
  };
  
  hierarchical?: {
    maxChildrenPerCoordinator: number;
    delegationDepth: number;
  };
  
  hiveMind?: {
    consensusThreshold: number;
    votingPeriod: number;
    minParticipants: number;
  };
}
```

### Initialization Options

```typescript
interface SwarmInitOptions {
  topology: TopologyType;
  maxAgents?: number;
  defaultAgentType?: AgentType;
  enableConsensus?: boolean;
  communicationGraph?: {
    trackMetrics: boolean;
    retentionPeriod: number;
  };
  flowEnforcer?: {
    strictMode: boolean;
    allowedPatterns: CommunicationPattern[];
  };
}
```

资料来源：[packages/@monomind/swarm/src/topology-manager.ts]()

## Best Practices

### Topology Selection Guidelines

| Use Case | Recommended Topology |
|----------|---------------------|
| Simple sequential processing | Linear/Pipeline |
| Complex multi-domain tasks | Hierarchical |
| Highly collaborative workflows | Mesh |
| Centralized control scenarios | Star |
| Collective decision-making | Hive-Mind |

### Performance Considerations

1. **Mesh topologies** offer maximum parallelism but increase coordination overhead
2. **Hierarchical topologies** reduce communication complexity but may create bottlenecks
3. **Hive-Mind topologies** ensure consistent decisions but require more round-trips
4. **Star topologies** provide clear authority but concentrate load on the hub

### Flow Enforcement

Always enable the Flow Enforcer when using restricted topologies to prevent:

- Unauthorized agent-to-agent communication
- Circular dependencies
- Task routing violations
- Priority inversion attacks

资料来源：[packages/@monomind/cli/src/swarm/flow-enforcer.ts]()

## Related Documentation

- [Agent Management](../cli/agent.md) - Agent spawning and lifecycle
- [Task Orchestration](./task-orchestration.md) - Advanced task routing
- [Memory System](../memory/README.md) - Cross-agent memory sharing
- [Hooks System](../hooks/README.md) - Event-driven coordination

---

<a id='consensus-protocols'></a>

## Consensus Protocols

### 相关页面

相关主题：[Swarm Topologies](#swarm-topologies)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/swarm/src/consensus/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/consensus/index.ts)
- [packages/@monomind/swarm/src/consensus/raft.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/consensus/raft.ts)
- [packages/@monomind/swarm/src/consensus/byzantine.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/consensus/byzantine.ts)
- [packages/@monomind/swarm/src/consensus/gossip.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/swarm/src/consensus/gossip.ts)
- [packages/@monomind/cli/src/consensus/audit-writer.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/consensus/audit-writer.ts)
- [packages/@monomind/cli/src/consensus/vote-signer.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/consensus/vote-signer.ts)
</details>

# Consensus Protocols

## Overview

The Consensus Protocols module in Monomind provides a robust, multi-strategy approach to achieving agreement among distributed agents in a swarm coordination system. This module is critical for maintaining consistency, reliability, and fault tolerance when multiple autonomous agents must reach agreement on decisions, state changes, or leadership elections.

The consensus subsystem is architected to support three primary consensus paradigms, each optimized for different operational requirements and threat models:

| Protocol | Use Case | Fault Tolerance | Performance |
|----------|----------|-----------------|-------------|
| **Raft** | Leader election, state replication | Crash fault tolerance | High throughput |
| **Byzantine** | Adversarial environments, security-critical decisions | Byzantine fault tolerance | Medium throughput |
| **Gossip** | Event propagation, eventual consistency | Partial network partitions | Highest throughput |

资料来源：[packages/@monomind/swarm/src/consensus/index.ts]()

## Architecture

The consensus module follows a layered architecture that separates protocol implementation from coordination logic. The `UnifiedSwarmCoordinator` acts as the primary consumer of consensus services, while individual protocol implementations handle the algorithmic specifics.

```mermaid
graph TD
    A[UnifiedSwarmCoordinator] --> B[ConsensusService]
    B --> C[RaftConsensus]
    B --> D[ByzantineConsensus]
    B --> E[GossipProtocol]
    
    F[CLI Audit Commands] --> G[AuditWriter]
    H[Vote Signing] --> I[VoteSigner]
    
    G --> B
    I --> C
    I --> D
    
    J[Network Transport] --> C
    J --> D
    J --> E
```

### Core Interfaces

The consensus module exposes a unified interface through the main entry point:

```typescript
// packages/@monomind/swarm/src/consensus/index.ts
export interface ConsensusProtocol {
  propose(value: ConsensusValue): Promise<ConsensusResult>;
  join(nodeId: string): Promise<void>;
  leave(nodeId: string): Promise<void>;
  getState(): ConsensusState;
  getMetrics(): ConsensusMetrics;
}
```

资料来源：[packages/@monomind/swarm/src/consensus/index.ts:1-50]()

## Raft Consensus Implementation

The Raft implementation provides crash fault tolerance for leader election and log replication within the swarm. This protocol is selected by default when strong consistency is required without the overhead of Byzantine fault tolerance.

### Leader Election

Raft in Monomind uses a three-state machine model: **Follower**, **Candidate**, and **Leader**. The election process is triggered when a follower node does not receive a heartbeat from the current leader within the election timeout.

```mermaid
stateDiagram-v2
    [*] --> Follower
    Follower --> Candidate : Election timeout
    Candidate --> Leader : Votes received (majority)
    Candidate --> Follower : Higher term discovered
    Leader --> Follower : Higher term discovered
    Follower --> Follower : Heartbeat received
    Candidate --> Candidate : Election timeout (re-election)
```

### Log Replication

Once a leader is elected, it replicates log entries to followers using the `proposeConsensus` method exposed through the coordinator interface. Entries are committed only after receiving acknowledgment from a majority of nodes.

资料来源：[packages/@monomind/swarm/src/consensus/raft.ts]()

## Byzantine Fault Tolerance

The Byzantine consensus implementation is designed for scenarios where agents may exhibit arbitrary or malicious behavior. This is particularly relevant in open multi-agent systems where not all participants can be trusted.

### Byzantine Generals Problem

Byzantine consensus tolerates up to *f* faulty nodes in a system of *3f + 1* total nodes, making it suitable for security-critical swarm operations such as:

- Vote signing and verification
- Access control decisions
- Resource allocation agreements
- Cross-agent transaction validation

```mermaid
graph LR
    A[Propose] --> B[Pre-Prepare]
    B --> C[Prepare]
    C --> D[Commit]
    D --> E[Reply]
    
    F[F+1 Distinct Signatures] --> E
```

资料来源：[packages/@monomind/swarm/src/consensus/byzantine.ts]()

## Gossip Protocol

The Gossip protocol provides eventual consistency with minimal coordination overhead. Unlike Raft and Byzantine consensus, gossip is designed for high-throughput scenarios where strict consistency is not required.

### Message Propagation

Nodes periodically select random peers to exchange state information. Over time, the entire swarm converges to a consistent state through epidemic propagation.

| Property | Value |
|----------|-------|
| Convergence Time | O(log n) rounds |
| Message Complexity | O(n log n) total messages |
| Network Efficiency | High fan-out, low latency |

### Fan-Out Strategy

The gossip implementation uses an adaptive fan-out factor based on network conditions and swarm size, optimizing message delivery while minimizing redundant transmissions.

资料来源：[packages/@monomind/swarm/src/consensus/gossip.ts]()

## CLI Integration

The Monomind CLI provides commands for managing and auditing consensus operations across the swarm.

### Audit Writer

The `audit-writer` module enables operators to record and verify consensus decisions for compliance and debugging purposes.

```bash
# Record consensus decision
monomind consensus audit record --tx-id <transaction> --decision <choice>

# Export audit trail
monomind consensus audit export --format json --since 2024-01-01
```

资料来源：[packages/@monomind/cli/src/consensus/audit-writer.ts]()

### Vote Signing

Vote signing provides cryptographic verification of consensus participation, ensuring that only authorized agents can influence swarm decisions.

```bash
# Sign a vote
monomind consensus vote sign --proposal <id> --node <node-id>

# Verify vote signatures
monomind consensus vote verify --proposal <id> --signatures <path>
```

资料来源：[packages/@monomind/cli/src/consensus/vote-signer.ts]()

## Usage Patterns

### Choosing the Right Protocol

| Scenario | Recommended Protocol | Justification |
|----------|---------------------|---------------|
| Single datacenter, trusted agents | Raft | Highest performance, sufficient fault tolerance |
| Multi-region deployment | Gossip | Partition tolerant, eventual consistency |
| Open network, untrusted agents | Byzantine | Security-first, tolerates malicious behavior |
| Mixed trust environment | Hybrid (Raft + Byzantine) | Use Byzantine for security-critical, Raft for operational |

### Configuration Example

```typescript
import { createConsensusService } from '@monomind/swarm';

const consensus = createConsensusService({
  protocol: 'raft',
  peers: ['agent-1:9001', 'agent-2:9001', 'agent-3:9001'],
  electionTimeout: 500,
  heartbeatInterval: 150,
});

// Propose a value
const result = await consensus.propose({
  type: 'leader_decision',
  value: { action: 'spawn_agent', config: agentConfig },
  timeout: 5000,
});
```

## API Reference

### ConsensusService

| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `propose` | `value: ConsensusValue` | `Promise<ConsensusResult>` | Submit a value for consensus |
| `join` | `nodeId: string` | `Promise<void>` | Join the consensus group |
| `leave` | `nodeId: string` | `Promise<void>` | Leave the consensus group |
| `getState` | — | `ConsensusState` | Get current consensus state |
| `getMetrics` | — | `ConsensusMetrics` | Get performance metrics |

### ConsensusResult

```typescript
interface ConsensusResult {
  success: boolean;
  value?: unknown;
  quorum?: string[];
  term?: number;
  signature?: string;
  timestamp: number;
  latency: number;
}
```

## Performance Targets

The consensus module is designed to meet the following performance benchmarks:

| Metric | Target |
|--------|--------|
| Coordination Latency | < 100ms |
| Throughput | > 10,000 ops/sec |
| Recovery Time | < 5 seconds |
| Memory Overhead | < 50MB per agent |

资料来源：[packages/@monomind/swarm/README.md]()
资料来源：[packages/@monomind/swarm/src/consensus/index.ts]()

## Related Documentation

- [Swarm Coordination](../swarm/README.md) - Higher-level swarm management
- [UnifiedSwarmCoordinator](../swarm/src/coordinator.ts) - Primary coordinator implementation
- [CLI Commands](../cli/src/consensus/) - Command-line consensus tools

---

<a id='memory-system'></a>

## Memory System

### 相关页面

相关主题：[Knowledge Graph (Monograph)](#knowledge-graph)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/memory/src/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/src/index.ts)
- [packages/@monomind/memory/src/agentdb-backend.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/src/agentdb-backend.ts)
- [packages/@monomind/memory/src/hnsw-index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/src/hnsw-index.ts)
- [packages/@monomind/memory/src/hybrid-backend.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/src/hybrid-backend.ts)
- [packages/@monomind/memory/src/sqlite-backend.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/src/sqlite-backend.ts)
- [packages/@monomind/memory/src/sqljs-backend.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/src/sqljs-backend.ts)
- [packages/@monomind/neural/src/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/neural/src/index.ts)
- [packages/@monomind/neural/src/sona-integration.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/neural/src/sona-integration.ts)
- [packages/@monomind/neural/src/pattern-learner.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/neural/src/pattern-learner.ts)
- [packages/@monomind/memory/src/learning-bridge.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/memory/src/learning-bridge.ts)
</details>

# Memory System

The Memory System is a core component of Monomind that provides persistent, searchable storage for agent insights, patterns, and learned knowledge. It implements a hybrid architecture combining SQLite for structured data persistence with HNSW-based vector indexing for high-performance semantic search.

## Overview

The Memory System serves as the long-term knowledge repository for the Monomind AI coordination platform. It enables agents to:

- **Persist insights** across sessions with confidence-weighted storage
- **Search semantically** using vector embeddings and HNSW indexing
- **Link knowledge** automatically using A-MEM auto-linking mechanisms
- **Learn patterns** through SONA neural integration
- **Sync with files** via AutoMemoryBridge for CLAUDE.md integration

资料来源：[packages/@monomind/memory/README.md](packages/@monomind/memory/README.md)

## Architecture

```mermaid
graph TB
    subgraph "Memory System Architecture"
        AMB["AutoMemoryBridge"]
        
        subgraph "Backends"
            HB["HybridBackend"]
            AB["AgentDB Backend"]
            SB["SQLite Backend"]
            HNSW["HNSW Index"]
        end
        
        subgraph "Neural Integration"
            NL["Neural Learning"]
            PL["Pattern Learner"]
            SONA["SONA Integration"]
        end
        
        LB["LearningBridge"]
    end
    
    AMB --> HB
    HB --> AB
    HB --> SB
    HB --> HNSW
    LB --> NL
    LB --> PL
    NL --> SONA
    AMB --> LB
```

### Component Overview

| Component | Purpose | Data Type |
|-----------|---------|-----------|
| `HybridBackend` | Unified interface combining multiple backends | All memory entries |
| `AgentDB Backend` | Vector semantic search with HNSW | Embeddings, insights |
| `SQLite Backend` | Structured relational storage | Metadata, configurations |
| `HNSW Index` | High-performance approximate nearest neighbor search | Vector embeddings |
| `AutoMemoryBridge` | File sync and session management | Markdown files |
| `LearningBridge` | Neural pattern learning integration | Learned patterns |

资料来源：[packages/@monomind/memory/src/hybrid-backend.ts](packages/@monomind/memory/src/hybrid-backend.ts)

## Backends

### HybridBackend

The `HybridBackend` serves as the primary interface, combining structured storage with semantic search capabilities. It coordinates between AgentDB and SQLite backends while maintaining data consistency.

```typescript
interface HybridBackendConfig {
  embeddingGenerator?: EmbeddingGenerator;
  storageDir?: string;
  enableAutoLinking?: boolean;
  maxAutoLinkReferences?: number;
}
```

**Key Features:**
- Automatic embedding generation for stored entries
- A-MEM auto-linking with configurable neighbor count
- Bidirectional reference management
- Cross-session persistence

资料来源：[packages/@monomind/memory/src/hybrid-backend.ts](packages/@monomind/memory/src/hybrid-backend.ts)

### AgentDB Backend

The AgentDB backend provides vector storage and semantic search capabilities using HNSW (Hierarchical Navigable Small World) indexing.

```typescript
interface AgentDBConfig {
  dimension: number;
  storagePath?: string;
  m?: number;        // HNSW M parameter
  efConstruction?: number;
  efSearch?: number;
}
```

**Performance Characteristics:**
- **150x-12,500x faster** than brute-force search
- Supports up to millions of vectors
- Configurable HNSW parameters for accuracy/speed tradeoffs

资料来源：[packages/@monomind/memory/src/agentdb-backend.ts](packages/@monomind/memory/src/agentdb-backend.ts)

### SQLite Backend

Provides structured data storage for metadata, configurations, and entries requiring relational queries.

```typescript
interface SQLiteConfig {
  storagePath?: string;
  enableWAL?: boolean;
  cacheSize?: number;
}
```

资料来源：[packages/@monomind/memory/src/sqlite-backend.ts](packages/@monomind/memory/src/sqlite-backend.ts)

### SQL.js Backend

An in-browser compatible SQLite implementation using WebAssembly, useful for environments without native SQLite support.

```typescript
interface SqlJsConfig {
  locateFile?: (file: string) => string;
  memoryGrowth?: boolean;
}
```

资料来源：[packages/@monomind/memory/src/sqljs-backend.ts](packages/@monomind/memory/src/sqljs-backend.ts)

## HNSW Index

The HNSW (Hierarchical Navigable Small World) index provides the core vector search functionality.

```mermaid
graph LR
    A["Query Vector"] --> B["Search Layer L"]
    B --> C["Search Layer L-1"]
    C --> D["Search Layer L-2"]
    D --> E["Bottom Layer"]
    E --> F["Results"]
```

### Configuration Parameters

| Parameter | Default | Description |
|-----------|---------|-------------|
| `m` | 16 | Max connections per node |
| `efConstruction` | 200 | Construction time search breadth |
| `efSearch` | 100 | Search time search breadth |
| `dimension` | 1536 | Embedding vector dimension |

资料来源：[packages/@monomind/memory/src/hnsw-index.ts](packages/@monomind/memory/src/hnsw-index.ts)

## AutoMemoryBridge

The `AutoMemoryBridge` synchronizes between the in-memory vector database and persistent markdown files for CLAUDE.md integration.

```typescript
import { AutoMemoryBridge } from '@monomind/memory';

const bridge = new AutoMemoryBridge(memoryBackend, {
  workingDir: '/workspaces/my-project',
  syncMode: 'on-session-end',
  pruneStrategy: 'confidence-weighted',
});
```

### Sync Modes

| Mode | Behavior | Use Case |
|------|----------|----------|
| `on-write` | Immediate file writes | Critical data persistence |
| `on-session-end` | Buffer and flush on session close | Efficient batch operations |
| `periodic` | Configurable interval sync | Long-running sessions |

资料来源：[packages/@monomind/memory/README.md](packages/@monomind/memory/README.md)

### Scope Directories

```mermaid
graph TD
    A["Agent Request"] --> B["Scope Selection"]
    B --> C1["project"]
    B --> C2["local"]
    B --> C3["user"]
    
    C1 --> D1["<gitRoot>/.claude/agent-memory/<agent>/"]
    C2 --> D2["<gitRoot>/.claude/agent-memory-local/<agent>/"]
    C3 --> D3["~/.claude/agent-memory/<agent>/"]
```

| Scope | Path Pattern | Description |
|-------|--------------|-------------|
| `project` | `<gitRoot>/.claude/agent-memory/<agent>/` | Project-specific learnings |
| `local` | `<gitRoot>/.claude/agent-memory-local/<agent>/` | Machine-local data |
| `user` | `~/.claude/agent-memory/<agent>/` | Cross-project user knowledge |

资料来源：[packages/@monomind/memory/README.md](packages/@monomind/memory/README.md)

## Insight Categories

| Category | Topic File | Description |
|----------|-----------|-------------|
| `project-patterns` | `patterns.md` | Reusable code patterns |
| `architecture` | `architecture.md` | System design decisions |
| `debugging` | `debugging.md` | Bug fixes and workarounds |
| `decisions` | `decisions.md` | ADR and rationale |
| `api-contracts` | `api-contracts.md` | Interface definitions |

资料来源：[packages/@monomind/memory/README.md](packages/@monomind/memory/README.md)

## Neural Learning Integration

### Pattern Learning

The Pattern Learning system extracts and stores reusable patterns from agent interactions.

```typescript
import { PatternLearner } from '@monomind/neural';

const learner = new PatternLearner({
  extractionThreshold: 0.7,
  consolidationWindow: 100,
});
```

资料来源：[packages/@monomind/neural/src/pattern-learner.ts](packages/@monomind/neural/src/pattern-learner.ts)

### SONA Integration

SONA (Self-Optimizing Neural Adaptation) enables the memory system to learn from patterns and improve agent routing over time.

```mermaid
graph TD
    A["Memory Entry"] --> B["Pattern Extraction"]
    B --> C["SONA Weight Update"]
    C --> D["Agent Routing Optimization"]
    D --> E["Performance Metrics"]
    E --> B
```

**Features:**
- Pattern recognition improves agent routing
- Trajectory tracking identifies effective strategies
- Automatic model adaptation with <0.05ms overhead

资料来源：[packages/@monomind/neural/src/sona-integration.ts](packages/@monomind/neural/src/sona-integration.ts)

### LearningBridge

The `LearningBridge` connects the memory system with neural learning capabilities, enabling bidirectional flow of insights and learned patterns.

```typescript
const bridge = new LearningBridge({
  memoryBackend: hybridBackend,
  neuralBackend: sonaBackend,
  syncInterval: 60000,
});
```

资料来源：[packages/@monomind/memory/src/learning-bridge.ts](packages/@monomind/memory/src/learning-bridge.ts)

## Memory Operations

### Store and Retrieve

```typescript
// Store an insight
await bridge.recordInsight({
  category: 'debugging',
  summary: 'HNSW index requires initialization before search',
  source: 'agent:tester',
  confidence: 0.95,
});

// Semantic search
const results = await backend.search('HNSW initialization', { topK: 5 });

// Sync to files
await bridge.syncToAutoMemory();
```

### Memory CLI Commands

| Command | Description |
|---------|-------------|
| `memory init` | Initialize memory database |
| `memory store` | Store data in memory |
| `memory retrieve` | Retrieve data from memory |
| `memory search` | Semantic/vector search |
| `memory list` | List memory entries |
| `memory delete` | Delete an entry |
| `memory stats` | Show statistics |

资料来源：[packages/@monomind/cli/src/commands/memory.ts](packages/@monomind/cli/src/commands/memory.ts)

## A-MEM Auto-Linking

When `HybridBackend` is configured with an `embeddingGenerator`, every stored entry automatically discovers its top-3 semantic neighbors and creates bidirectional `references` edges—implementing the Zettelkasten note-linking structure.

```typescript
const backend = new HybridBackend({
  embeddingGenerator: async (text) => myEmbeddingModel.embed(text),
  maxAutoLinkReferences: 3,
  enableAutoLinking: true,
});
```

资料来源：[packages/@monomind/memory/README.md](packages/@monomind/memory/README.md)

## Quick Start

```typescript
import { 
  AutoMemoryBridge,
  HybridBackend,
  createAgentBridge,
  resolveAgentMemoryDir,
} from '@monomind/memory';

// Create backend with embedding support
const backend = new HybridBackend({
  embeddingGenerator: async (text) => embeddings.embed(text),
});

// Create bridge for file sync
const bridge = new AutoMemoryBridge(backend, {
  workingDir: '/workspaces/my-project',
  syncMode: 'on-session-end',
});

// Record insights
await bridge.recordInsight({
  category: 'architecture',
  summary: 'Use HybridBackend for production workloads',
  confidence: 0.92,
});

// Sync to CLAUDE.md files
await bridge.syncToAutoMemory();
```

资料来源：[packages/@monomind/memory/src/index.ts](packages/@monomind/memory/src/index.ts)

## Related Packages

| Package | Purpose |
|---------|---------|
| `agentdb` | HNSW vector database |
| `@monomind/neural` | Neural network and SONA learning |
| `@monomind/cli` | CLI with memory commands |

## License

MIT License - see [LICENSE](LICENSE) for details.

---

<a id='knowledge-graph'></a>

## Knowledge Graph (Monograph)

### 相关页面

相关主题：[Memory System](#memory-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/@monomind/monograph/src/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/monograph/src/index.ts)
- [packages/@monomind/monograph/src/pipeline/runner.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/monograph/src/pipeline/runner.ts)
- [packages/@monomind/monograph/src/graph/explain.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/monograph/src/graph/explain.ts)
- [packages/@monomind/monograph/src/graph/hotspots.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/monograph/src/graph/hotspots.ts)
- [packages/@monomind/monograph/src/graph/reachability.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/monograph/src/graph/reachability.ts)
- [packages/@monomind/graph/src/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/graph/src/index.ts)
- [packages/@monomind/graph/src/build.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/graph/src/build.ts)
- [packages/@monomind/graph/src/extract/index.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/graph/src/extract/index.ts)
- [packages/@monomind/cli/src/mcp-tools/monograph-tools.ts](https://github.com/monoes/monomind/blob/main/packages/@monomind/cli/src/mcp-tools/monograph-tools.ts)
</details>

# Knowledge Graph (Monograph)

Monograph is the knowledge graph subsystem of Monomind, designed to build, maintain, and query a semantic dependency graph of your codebase, documentation, and PDFs. It serves as the foundational intelligence layer that automatically maps relationships between code symbols, documents, and concepts before every task execution.

## Overview

Monograph creates a unified graph representation that captures both structural dependencies (imports, definitions) and semantic relationships (concepts, co-occurrences). This graph is automatically queried by hooks and slash commands, enabling agents to understand the codebase topology before making decisions.

```mermaid
graph TD
    A[Codebase + Docs + PDFs] --> B[Graph Builder]
    B --> C[Monograph Graph DB]
    C --> D[Query Engine]
    D --> E[monograph_suggest]
    D --> F[monograph_query]
    D --> G[monograph_god_nodes]
    E --> H[Claude Code Agent]
    F --> H
    G --> H
```

**资料来源：** [packages/@monomind/monograph/src/index.ts]()

## Core Concepts

### Graph Structure

The Monograph graph consists of two primary elements: **nodes** and **edges**.

#### Node Types

| Node Type | Description | Example |
|-----------|-------------|---------|
| `File` | Source file or document | `src/auth/login.ts` |
| `Function` | Function or method definition | `authenticateUser()` |
| `Class` | Class or interface definition | `UserService` |
| `Concept` | Extracted semantic concept | `authentication-flow` |
| `PDF` | PDF document chunk | `architecture.pdf:42-58` |
| `Section` | Documentation section | API Reference, README |
| `Interface` | TypeScript interface | `AuthProvider` |
| `TypeAlias` | Type alias or union type | `UserId` |

**资料来源：** [plugin/commands/monograph/README.md]()

#### Edge Types

| Relation | Meaning | Direction |
|----------|---------|-----------|
| `IMPORTS` | Code import dependency | File → File |
| `DEFINES` | Symbol defined in file | File → Symbol |
| `TAGGED_AS` | Section tagged with concept | Section → Concept |
| `CO_OCCURS` | Concepts appear together | Concept → Concept |
| `INFERRED` | Claude-extracted semantic relationship | Any → Any |
| `DESCRIBES` | LLM-enriched relationship | Concept → Concept |
| `CAUSES` | LLM-enriched relationship | Concept → Concept |
| `PART_OF` | LLM-enriched relationship | Concept → Concept |

**资料来源：** [plugin/commands/monograph/README.md]()

### Graph Analysis Capabilities

Monograph provides several analysis modes for examining the codebase:

```mermaid
graph TD
    subgraph Analysis Modes
        A[reachability] --> A1[Upstream dependencies]
        A --> A2[Downstream dependents]
        B[hotspots] --> B1[High change frequency]
        B --> B2[Cyclomatic complexity]
        C[explain] --> C1[Dependency paths]
        C --> C2[Impact analysis]
    end
```

#### Reachability Analysis

Determines which files and symbols can reach or be reached from a given node. This is useful for understanding the blast radius of changes.

**资料来源：** [packages/@monomind/monograph/src/graph/reachability.ts]()

#### Hotspots Detection

Identifies high-complexity or frequently-changing areas of the codebase that may need attention.

**资料来源：** [packages/@monomind/monograph/src/graph/hotspots.ts]()

#### Explanation Engine

Provides natural language explanations of dependency paths and relationships between code elements.

**资料来源：** [packages/@monomind/monograph/src/graph/explain.ts]()

## CLI Commands

The `monomind monograph` command provides the primary interface for building and querying the knowledge graph.

### Command Reference

| Subcommand | Description |
|------------|-------------|
| `monograph build` | Build knowledge graph from code + docs + PDFs |
| `monograph wiki` | Scan all docs and PDFs into a searchable knowledge graph |
| `monograph search` | Search the graph (BM25 / semantic / hybrid) |
| `monograph stats` | Show node/edge counts and top concepts |
| `monograph watch` | Watch for file changes and rebuild incrementally |

**资料来源：** [packages/@monomind/cli/src/commands/monograph.ts]()

### Quick Start

```bash
# First-time build (code + all docs)
npx monomind monograph build

# Doc/wiki-focused build with Claude semantic extraction
npx monomind monograph wiki --llm

# Search
npx monomind monograph search -q "authentication flow"
npx monomind monograph search -q "pipeline" --mode semantic --label Section

# Stats
npx monomind monograph stats --top 20

# Auto-rebuild on changes
npx monomind monograph watch
```

**资料来源：** [plugin/commands/monograph/README.md]()

### Search Modes

| Mode | Description | Use Case |
|------|-------------|----------|
| `bm25` | Traditional keyword-based search | Exact matches |
| `semantic` | Vector-based similarity search | Conceptual matches |
| `hybrid` | Combined BM25 + semantic | Balanced results |

**资料来源：** [packages/@monomind/cli/src/commands/monograph.ts]()

## MCP Tools

Monograph exposes tools via the Model Context Protocol for programmatic integration with Claude Code and other MCP-compatible clients.

### Available Tools

| Tool Name | Description |
|-----------|-------------|
| `monograph_graphify` | Convert workspace files to graph representation |
| `monograph_stats` | Get node/edge statistics and graph health |
| `monograph_boundary_check` | Check for cross-zone import violations |
| `monograph_suggest` | Find relevant files for a task |
| `monograph_query` | Query specific dependency relationships |

**资料来源：** [packages/@monomind/cli/src/mcp-tools/monograph-tools.ts]()

### Usage Example

```typescript
// Using MCP tool in Claude Code
{
  tool: 'monograph_suggest',
  arguments: {
    query: "add webhook retry logic",
    role: "code"  // Optional: filter by role (code, test, docs)
  }
}
```

### Graphify Tool

The `monograph_graphify` tool provides detailed graph analysis:

```mermaid
graph TD
    A[graphify request] --> B{role filter}
    B -->|unreachable| C[Dead code candidates]
    B -->|test| D[Test utilities]
    B -->|code| E[Source files]
    B -->|all| F[Complete graph]
    C --> G[Dependency stats]
    D --> G
    E --> G
    F --> G
```

**资料来源：** [packages/@monomind/cli/src/mcp-tools/monograph-tools.ts]()

## Configuration

Monograph is configured via `.monographrc.json` in the project root.

### Configuration Schema

```typescript
interface MonographConfig {
  root: string;              // Project root directory
  entry: string[];           // Entry points for analysis
  ignore: string[];          // Patterns to exclude
  production: boolean;      // Enable production checks
  detection: string;        // Detection mode
  regression: {
    tolerance: number;
    baselinePath: string;
  };
  health: {
    cyclomaticThreshold: number;
    cognitiveThreshold: number;
    crapThreshold: number;
    minLines: number;
  };
  boundaries?: BoundaryConfig;  // Zone-based boundary rules
  plugins: string[];
}
```

**资料来源：** [packages/@monomind/monograph/src/config/types.ts]()

### Boundary Configuration

Boundaries define architectural zones with allowed import rules:

```json
{
  "zones": [
    {
      "name": "core",
      "patterns": ["src/core/**"],
      "allowedImports": ["src/utils/**"]
    }
  ]
}
```

**资料来源：** [packages/@monomind/cli/src/mcp-tools/monograph-tools.ts]()

### Default Configuration

```typescript
const DEFAULT_MONOGRAPH_CONFIG = {
  root: '.',
  entry: [],
  production: true,
  detection: 'default',
  project: undefined,
  ignore: [],
  overrides: [],
  regression: { tolerance: 0, baselinePath: '.monograph/regression-baseline.json' },
  audit: { gate: 'error', includeHealthGate: false },
  normalization: {
    stripComments: true,
    normalizeWhitespace: true,
    normalizeIdentifiers: false
  },
  boundaries: {},
  resolve: {
    paths: {},
    alias: {},
    conditions: [],
    extensions: ['.ts', '.tsx', '.mts', '.cts']
  },
  health: {
    cyclomaticThreshold: 10,
    cognitiveThreshold: 15,
    crapThreshold: 30,
    minLines: 5
  },
  ownership: { emailMode: 'fullEmail' },
  plugins: [],
};
```

**资料来源：** [packages/@monomind/monograph/src/config/types.ts]()

## Pipeline Architecture

The Monograph pipeline processes code and documents through multiple stages:

```mermaid
graph LR
    A[Source Files] --> B[Parser]
    B --> C[AST Analysis]
    C --> D[Symbol Extractor]
    D --> E[Graph Builder]
    E --> F[Edge Resolver]
    F --> G[Graph Database]
    G --> H[Query Interface]
    
    I[Documents] --> J[Chunker]
    J --> K[Embedding Generator]
    K --> L[Vector Index]
    L --> G
```

### Pipeline Runner

The pipeline runner orchestrates the graph construction process:

```typescript
interface PipelineResult {
  nodes: number;      // Total nodes created
  edges: number;      // Total edges created
  duration: number;   // Processing time in ms
  errors: string[];   // Any processing errors
}
```

**资料来源：** [packages/@monomind/monograph/src/pipeline/runner.ts]()

### Extraction Pipeline

The extraction pipeline handles both code symbols and documentation:

```typescript
interface ExtractOptions {
  includeTypes: boolean;      // Include type definitions
  includeDocs: boolean;       // Include JSDoc comments
  includeConcepts: boolean;   // Extract semantic concepts
  useLLM: boolean;           // Use LLM for semantic extraction
}
```

**资料来源：** [packages/@monomind/graph/src/extract/index.ts]()

## Graph Query Operations

### monograph_query

Query specific relationships in the graph:

```bash
# Find what depends on UserService
monograph_query "UserService dependencies"

# Find files that define authentication
monograph_query "authentication" --label DEFINES
```

### monograph_suggest

Get ranked file suggestions for a task:

```bash
# Find relevant files for a feature
monograph_suggest "add webhook retry logic"
# → returns ranked list with relevance scores
```

### monograph_god_nodes

Identify high-centrality files (most connected in the graph):

```bash
# Find the most connected internal files
monograph_god_nodes
# → excludes external dependencies and test files
```

**资料来源：** [README.md]()

## Integration with Intelligence System

Monograph integrates with Monomind's intelligence system to provide context-aware assistance:

```mermaid
graph TD
    A[User Task] --> B[Monograph Query]
    B --> C[Relevant Files]
    C --> D[SONA Learning]
    D --> E[Pattern Recognition]
    E --> F[Agent Routing]
    F --> G[Task Execution]
    G --> H[Trajectory Tracking]
    H --> D
```

### Hooks Integration

Monograph tools are called automatically by hooks before task execution, ensuring agents always have relevant context.

**资料来源：** [README.md]()

## Extended Configuration

Monograph supports extended configuration for advanced use cases:

```typescript
interface ExtendedMonographConfig extends MonographConfig {
  extends?: string[];                    // Extend other configs
  sealed?: boolean;                       // Prevent further extension
  includeEntryExports?: boolean;         // Include entry point exports
  publicPackages?: string[];             // Public package boundaries
  dynamicallyLoaded?: string[];          // Dynamic import patterns
  codeowners?: string;                   // CODEOWNERS file path
  ignoreDependencies?: string[];         // Ignore certain imports
  ignoreExportsUsedInFile?: boolean | {
    interface?: boolean;
    typeAlias?: boolean;
  };
  usedClassMembers?: Array<string | {
    extends?: string[];
    implements?: string[];
    members: string[];
  }>;
}
```

**资料来源：** [packages/@monomind/monograph/src/config/types.ts]()

## Health Checks

Monograph includes code health analysis capabilities:

| Metric | Threshold | Description |
|--------|-----------|-------------|
| Cyclomatic Complexity | 10 | Maximum allowed branching |
| Cognitive Complexity | 15 | Maximum cognitive load |
| CRAP Index | 30 | Change Risk Anti-Patterns |
| Minimum Lines | 5 | Minimum function/file size |

**资料来源：** [packages/@monomind/monograph/src/config/types.ts]()

## CLI vs MCP Usage

| Aspect | CLI | MCP Tools |
|--------|-----|-----------|
| **Use Case** | One-time builds, manual searches | Claude Code integration |
| **Invocation** | Terminal commands | Programmatic queries |
| **Real-time** | With `watch` command | During task execution |
| **Output** | Formatted text | JSON structured data |

**资料来源：** [plugin/commands/monograph/README.md]()

## See Also

- `memory` — Vector memory storage (separate from graph)
- `hooks intelligence` — Pattern learning
- CLAUDE.md Knowledge Graph section — workflow guidance for multi-file tasks

---

---

## Doramagic 踩坑日志

项目：monoes/monomind

摘要：发现 15 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：v1.10.0 — Full Paperclip Port: 55 New Mastermind Skills。

## 1. 安装坑 · 来源证据：v1.10.0 — Full Paperclip Port: 55 New Mastermind Skills

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.10.0 — Full Paperclip Port: 55 New Mastermind Skills
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ba46bd2053364ab7b216b1ab09b3714a | https://github.com/monoes/monomind/releases/tag/v1.10.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：v1.6.8

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.6.8
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8e00eb27c790432ba99d18d7125b0cee | https://github.com/monoes/monomind/releases/tag/v1.6.8 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：v1.9.12 — mastermind:idea pipeline hardening

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.9.12 — mastermind:idea pipeline hardening
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6a79f40d2c5e44c4ac6b5e2e855d2a55 | https://github.com/monoes/monomind/releases/tag/v1.9.12 | 来源类型 github_release 暴露的待验证使用条件。

## 4. 安装坑 · 来源证据：v1.9.13 — fix: monograph never installed (workspace:* dep)

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.9.13 — fix: monograph never installed (workspace:* dep)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2ffa187842b347428cc973816067e095 | https://github.com/monoes/monomind/releases/tag/v1.9.13 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 5. 安装坑 · 来源证据：v1.9.2 — mastermind:master hardening

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.9.2 — mastermind:master hardening
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_d4070dac80cb428ba72244762274a6bf | https://github.com/monoes/monomind/releases/tag/v1.9.2 | 来源类型 github_release 暴露的待验证使用条件。

## 6. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。
- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- 证据：capability.host_targets | github_repo:1221944165 | https://github.com/monoes/monomind | host_targets=mcp_host, claude, claude_code

## 7. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1221944165 | https://github.com/monoes/monomind | README/documentation is current enough for a first validation pass.

## 8. 维护坑 · 来源证据：v1.9.1 — Init wipe-and-replace for managed Claude assets

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v1.9.1 — Init wipe-and-replace for managed Claude assets
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e1832d706e974245bfbf1fb183aeafb8 | https://github.com/monoes/monomind/releases/tag/v1.9.1 | 来源类型 github_release 暴露的待验证使用条件。

## 9. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1221944165 | https://github.com/monoes/monomind | last_activity_observed missing

## 10. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1221944165 | https://github.com/monoes/monomind | no_demo; severity=medium

## 11. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1221944165 | https://github.com/monoes/monomind | no_demo; severity=medium

## 12. 安全/权限坑 · 来源证据：Monomind v1.8.0 — Monograph, Mastermind & Security Hardening

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Monomind v1.8.0 — Monograph, Mastermind & Security Hardening
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_57b3501be7e943c5a3329118314c1794 | https://github.com/monoes/monomind/releases/tag/v1.8.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 13. 安全/权限坑 · 来源证据：Monomind v1.9.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Monomind v1.9.0
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_77db71f60ceb4346b348922fc31f9cb7 | https://github.com/monoes/monomind/releases/tag/v1.9.0 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 14. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1221944165 | https://github.com/monoes/monomind | issue_or_pr_quality=unknown

## 15. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1221944165 | https://github.com/monoes/monomind | release_recency=unknown

<!-- canonical_name: monoes/monomind; human_manual_source: deepwiki_human_wiki -->
