# https://github.com/cristian1991/AIDOCS 项目说明书

生成时间：2026-05-16 05:31:31 UTC

## 目录

- [Introduction to AIDOCS](#introduction)
- [Installation Guide](#installation)
- [System Architecture Overview](#architecture-overview)
- [MCP Server Architecture](#mcp-server)
- [Dashboard Architecture](#dashboard)
- [Memory System](#memory-system)
- [Conductor & Orchestration](#conductor-orchestration)
- [Security & Access Control](#security-gates)
- [Indexing & Retrieval System](#indexing-retrieval)
- [Configuration Management](#configuration)

<a id='introduction'></a>

## Introduction to AIDOCS

### 相关页面

相关主题：[Installation Guide](#installation), [System Architecture Overview](#architecture-overview)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/cristian1991/AIDOCS/blob/main/README.md)
- [mcp/README.md](https://github.com/cristian1991/AIDOCS/blob/main/mcp/README.md)
- [apps/aidocs-dashboard/src/SetupWizardPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)
- [apps/aidocs-dashboard/src/CastleShell.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/CastleShell.tsx)
- [apps/aidocs-dashboard/src/OverviewPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/OverviewPage.tsx)
- [mcp/server/aidocs_mcp/output_guard.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/output_guard.py)
- [mcp/server/aidocs_mcp/data/opencode_plugin.js](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/data/opencode_plugin.js)
</details>

# Introduction to AIDOCS

## Overview

AIDOCS is an intelligent development system that provides AI coding agents with **persistent memory**, **indexed retrieval**, and **orchestration capabilities**. The platform enables AI agents to resume work efficiently instead of rediscovering repository context on every session. 资料来源：[apps/aidocs-dashboard/src/SetupWizardPage.tsx]()

## Purpose and Scope

AIDOCS addresses a fundamental challenge in AI-assisted development: **context loss between sessions**. When an AI coding agent completes a task or reconnects after a break, it traditionally must re-analyze the entire codebase to understand the project structure, recent changes, and development context. AIDOCS eliminates this inefficiency by maintaining persistent context that survives across sessions.

The system provides:

- **Persistent Memory**: Store and retrieve development context across agent sessions
- **Indexed Retrieval**: Fast lookup of relevant code, documentation, and project artifacts
- **Orchestration**: Coordinate multiple AI agents and their activities
- **Security Guards**: Built-in prompt injection detection and content filtering
- **RBAC**: Role-Based Access Control for multi-tenant environments

## Architecture Overview

```mermaid
graph TD
    subgraph "AIDOCS Core"
        A[AI Coding Agent] --> B[MCP Server]
        B --> C[Memory System]
        B --> D[Index Engine]
        B --> E[Session Manager]
    end
    
    subgraph "Dashboard Layer"
        C --> F[CastleShell Dashboard]
        D --> F
        E --> F
        F --> G[OverviewPage]
        F --> H[ExecutionPage]
        F --> I[ConductorPage]
        F --> J[RBACPage]
    end
    
    subgraph "Security Layer"
        B --> K[output_guard.py]
        K --> L[Prompt Injection Detection]
        K --> M[Sensitive Content Filtering]
    end
    
    subgraph "External Integrations"
        N[MCP Registry] --> B
        B --> O[Claude.ai]
        B --> P[OpenAI API]
    end
```

## Core Components

### MCP Server (Model Context Protocol)

The AIDOCS MCP server acts as the central communication hub between AI agents and the AIDOCS backend. It handles tool routing, session management, and context retrieval.

**Key Tools Provided:**

| Tool Category | Tools | Purpose |
|---------------|-------|---------|
| Classification | `classify_prompt`, `route_prompt` | Advisory routing for prompts |
| Investigation | `ai_investigate`, `ai_bundle` | Broad context exploration |
| Search | `ai_find`, `ai_trace` | Symbol and reference search |
| Database | `schema_query` | Database schema operations |
| Sessions | `ai_session` | List, create, connect, update, resume sessions |
| Tasks | `ai_task` | Begin, update, complete, status tasks |
| Memory | `memory_read`, `memory_capture`, `memory_search` | Memory operations |
| Project | `project_init`, `project_sync_indexes` | Project initialization |
| Code Operations | `ai_get_lines`, `ai_text_search`, `ai_search` | Read operations |
| Edit Operations | `ai_replace`, `ai_edit_lines`, `ai_batch_edit` | Write operations |

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

### Memory System

The memory system provides persistent storage for agent context:

```mermaid
graph LR
    A[Capture Event] --> B[memory_capture]
    B --> C[Memory Index]
    C --> D[memory_search]
    D --> E[Relevant Context]
    E --> F[Agent Context]
```

**Memory Operations:**

- `memory_read`: Retrieve stored memory entries
- `memory_capture`: Store new context from agent activities
- `memory_search`: Search across stored memories using natural language

### Session Management

Sessions enable agents to resume work without context loss:

```mermaid
stateDiagram-v2
    [*] --> List: ai_session list
    List --> Create: ai_session create
    Create --> Connect: ai_session connect
    Connect --> Update: ai_session update
    Connect --> Resume: ai_session resume
    Update --> Release: ai_session release
    Resume --> Release
    Release --> [*]
```

Sessions maintain:
- Current status and goal
- Owner information
- Context budget (token estimates, journal entries)
- Recent execution history

资料来源：[apps/aidocs-dashboard/src/OverviewPage.tsx]()

### Execution Tracking (Conductor)

The Conductor system tracks all tool calls and agent actions:

| Field | Description |
|-------|-------------|
| `session_id` | Associated session identifier |
| `capability_name` | Tool or capability invoked |
| `action_kind` | Type of action performed |
| `observed_at` | Timestamp of observation |
| `lane` | Execution lane (execution context) |
| `logicalMode` | Logical routing mode |
| `nativeMode` | Native routing mode |
| `fallbackUsed` | Whether fallback routing was used |

资料来源：[apps/aidocs-dashboard/src/ConductorPage.tsx](), [apps/aidocs-dashboard/src/ExecutionPage.tsx]()

### Security Layer (output_guard.py)

AIDOCS includes robust security features to protect against prompt injection attacks:

**Prompt Injection Patterns Detected:**

| Pattern ID | Regex Pattern | Description |
|------------|---------------|-------------|
| `system_override` | `(?:ignore\|forget\|disregard) all (?:previous\|prior\|above)` | System override attempts |
| `role_hijack` | `you are now (?:a )?(?:different\|new\|my) (?:ai\|assistant\|agent\|bot)` | Role hijacking attempts |
| `instruction_inject` | `<\s*(?:system\|instructions?\|prompt)\s*>` | XML tag injection |
| `delimiter_escape` | `\`\`\`\s*(?:system\|instructions?)\n` | Code block injection |
| `hidden_instruction` | `(?:IMPORTANT\|CRITICAL\|URGENT)\s*:\s*(?:ignore\|override\|forget\|disregard)` | Hidden instruction attempts |

**Sensitive Content Patterns:**

| Pattern ID | Regex Pattern | Description |
|------------|---------------|-------------|
| `env_file_content` | `^[A-Z_]{3,}=\S{8,}$` | Potential .env file leaks |
| `ssh_config` | `(?:Host\s+\S+\|IdentityFile\s+~/)` | SSH configuration content |

资料来源：[mcp/server/aidocs_mcp/output_guard.py]()

### RBAC (Role-Based Access Control)

AIDOCS implements comprehensive role-based access control:

**Key Features:**
- Permission management with descriptions
- Escalation paths for elevated privileges
- Sticky escalations for persistent elevated access
- Session/task-scoped permission grants

**Escalation Fields:**

| Field | Description |
|-------|-------------|
| `requester` | User or agent requesting escalation |
| `permission` | Permission being escalated |
| `phrase` | Trigger phrase for escalation |
| `session / task` | Associated session or task |
| `sticky` | Whether escalation persists |
| `created · expires` | Temporal bounds |

资料来源：[apps/aidocs-dashboard/src/RBACPage.tsx]()

### Dashboard Interface (CastleShell)

The AIDOCS Dashboard provides a web-based interface for monitoring and managing the system:

```mermaid
graph TD
    subgraph "CastleShell Components"
        A[CastleShell] --> B[Navigation]
        A --> C[StatusBar]
        A --> D[ContextRail]
        A --> E[TopStrip]
    end
    
    subgraph "Dashboard Pages"
        B --> O[OverviewPage]
        B --> P[ExecutionPage]
        B --> Q[ConductorPage]
        B --> R[RBACPage]
        B --> S[SkillsPage]
        B --> T[MonitoringPage]
        B --> U[RegistryPage]
        B --> V[TomlConfigsPage]
    end
    
    subgraph "Navigation Counts"
        C --> W[CastleNavCounts]
        W --> X[executions]
        W --> Y[sessions]
        W --> Z[escalations]
    end
```

**CastleShell Props:**

| Prop | Type | Description |
|------|------|-------------|
| `active` | `NavKey` | Currently active navigation item |
| `onSelect` | `(key: NavKey) => void` | Navigation callback |
| `counts` | `CastleNavCounts` | Badge counts for navigation |
| `managedMode` | `boolean` | Whether managed mode is active |
| `version` | `string` | AIDOCS version |
| `mcpConnected` | `boolean` | MCP server connection status |
| `activeLayer` | `string` | Current execution layer |
| `saveState` | `string` | Current save state indicator |

资料来源：[apps/aidocs-dashboard/src/CastleShell.tsx]()

## Setup and Installation

### Initial Setup Wizard

The setup wizard guides users through project configuration:

```mermaid
graph LR
    A[Welcome] --> B[Project Selection]
    B --> C[Environment Check]
    C --> D[Host Configuration]
    D --> E[Configure]
    E --> F[Done]
```

**Setup Steps:**

1. **Welcome**: Introduction and feature overview
2. **Project Selection**: Choose project folder path
3. **Environment Check**: Verify Node.js and other dependencies
4. **Host Configuration**: Configure Claude.ai, OpenAI API access
5. **Configure**: Set up MCP, hooks, and project structure
6. **Done**: Confirmation of successful setup

**Setup Wizard Features:**

- Progress indicator showing current step
- Environment detection with status checks
- Host authentication status display
- Automatic installation option for missing tools
- Sign-in buttons for external services

资料来源：[apps/aidocs-dashboard/src/SetupWizardPage.tsx]()

### Environment Detection

The setup wizard detects:

| Component | Detection | Installable |
|-----------|-----------|-------------|
| Node.js | Checks for CLI agent support | No |
| Claude | Checks `claude.ai` authentication | Yes |
| OpenAI | Checks API key configuration | Yes |
| Custom Hosts | Configurable external services | Yes |

### MCP Registry Integration

AIDOCS supports discovering and installing MCP servers from a registry:

- Search functionality for MCP servers
- Install commands extraction
- Transport and command information display
- Website URL tracking

资料来源：[apps/aidocs-dashboard/src/RegistryPage.tsx]()

## Workflow Patterns

### Agent Workflow with AIDOCS

```mermaid
graph TD
    A[Start Task] --> B[ai_session create]
    B --> C[Define Goal]
    C --> D[ai_investigate]
    D --> E[ai_find / ai_trace]
    E --> F[ai_get_symbol_info]
    F --> G[Edit Code]
    G --> H[memory_capture]
    H --> I[ai_session update]
    I --> J{More Work?}
    J -->|Yes| E
    J -->|No| K[ai_task complete]
    K --> L[ai_session release]
    L --> M[End]
```

### Code Editing Workflow

Recommended sequence for code modifications:

1. `ai_get_lines` — Read file content
2. `ai_get_symbol_info(kind="signature"|"constructor")` — Confirm target signatures
3. `ai_edit_lines` or `ai_batch_edit` — Apply changes
4. `ai_task_complete` — Mark task complete

**Important:** Do not mix different edit methods within the same task.

### Investigation Workflow

For understanding unfamiliar code:

1. `session_resume_bundle` — Get project/session/skills/plan overview
2. `action_surface_current_session_bundle` — Identify likely next tools
3. `ai_find(query, mode="symbols")` — Locate relevant symbols
4. `ai_get_symbol_snippet` — Retrieve code snippets
5. `ai_bundle(concept, mode="subsystem")` — Get subsystem context

资料来源：[mcp/server/aidocs_mcp/data/opencode_plugin.js]()

## Context Budget Management

Sessions track context budget usage:

| Metric | Description |
|--------|-------------|
| `status` | Budget status (available, exhausted, etc.) |
| `reason` | Reason for budget state |
| `estimated_tokens` | Current token count estimate |
| `journal_entries` | Number of journal entries |
| `available` | Whether compaction is possible |

**Compaction:** When context budget is running low, use the compact function to reduce token usage while preserving critical context.

资料来源：[apps/aidocs-dashboard/src/OverviewPage.tsx]()

## Monitoring and Analytics

### Execution Monitoring

Track agent activities across dimensions:

- **By Event Kind**: Categorize by tool type or action
- **By Source**: Track which agent or integration triggered events
- **Recent Execution**: View recent events with timestamps

### Lane Management

Lanes provide execution isolation and context grouping:

- Events can be tagged with `lane_id`
- Related events are grouped together
- Status tracking (applied, refused, blocked)

资料来源：[apps/aidocs-dashboard/src/MonitoringPage.tsx](), [apps/aidocs-dashboard/src/LaneDetailPanel.tsx]()

## Skills System

AIDOCS supports dynamic skill registration:

| Property | Description |
|----------|-------------|
| `name` | Skill identifier |
| `description` | Human-readable description |
| `skill_kind` | Type of skill |
| `provider` | Skill provider name |
| `source` | Skill source location |
| `selected` | Whether skill is selected for use |
| `active` | Whether skill is currently active |
| `activation_tags` | Tags triggering skill activation |
| `provider_status` | Current provider state |

资料来源：[apps/aidocs-dashboard/src/SkillsPage.tsx]()

## TOML Configuration

AIDOCS uses TOML for project and system configuration:

- Configuration document browsing by category
- Syntax-highlighted editor with save functionality
- Support for multiple TOML files per category

资料来源：[apps/aidocs-dashboard/src/TomlConfigsPage.tsx]()

## Command Line Interface

### Basic Commands

```bash
pip install aidocs-mcp
aidocs --version
aidocs-mcp   # start MCP server
```

## Summary

AIDOCS provides a comprehensive platform for enhancing AI coding agents with persistent memory and intelligent context management. Its modular architecture includes:

- **MCP Server**: Central communication hub with 20+ specialized tools
- **Memory System**: Persistent storage and retrieval of development context
- **Session Management**: Seamless task resumption across agent sessions
- **Security Layer**: Prompt injection detection and sensitive content filtering
- **RBAC**: Fine-grained access control for enterprise environments
- **Dashboard**: Web-based monitoring and management interface

By integrating AIDOCS into AI-assisted development workflows, teams can significantly reduce the time agents spend re-establishing context, leading to faster development cycles and more consistent code quality.

---

<a id='installation'></a>

## Installation Guide

### 相关页面

相关主题：[Introduction to AIDOCS](#introduction), [MCP Server Architecture](#mcp-server)

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

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

- [README_INSTALL.md](https://github.com/cristian1991/AIDOCS/blob/main/README_INSTALL.md)
- [core/scripts/install.sh](https://github.com/cristian1991/AIDOCS/blob/main/core/scripts/install.sh)
- [core/scripts/install.ps1](https://github.com/cristian1991/AIDOCS/blob/main/core/scripts/install.ps1)
- [mcp/server/aidocs_mcp/cli.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/cli.py)
- [apps/aidocs-dashboard/src/SetupWizardPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)
- [apps/aidocs-dashboard/src/RegistryPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RegistryPage.tsx)
</details>

# Installation Guide

AIDOCS is an AI-powered documentation and coding assistant platform that provides persistent memory, indexed retrieval, and orchestration for AI coding agents. This guide covers all installation methods, prerequisites, and configuration steps required to deploy AIDOCS in your development environment.

## Prerequisites

Before installing AIDOCS, ensure your system meets the following requirements.

### System Requirements

| Requirement | Minimum | Recommended |
|-------------|---------|-------------|
| Node.js | 18.x | 20.x LTS |
| Python | 3.10+ | 3.11+ |
| Disk Space | 500 MB | 2 GB |
| RAM | 4 GB | 8 GB |
| OS | macOS, Linux, Windows (WSL2) | macOS, Linux |

### Supported AI Host Platforms

AIDOCS integrates with multiple AI coding assistants. The installation process detects available platforms.

| Platform | Status Detection | Authentication |
|----------|-----------------|----------------|
| Claude (claude.ai) | Auto-detected | Requires sign-in |
| OpenAI (ChatGPT) | Auto-detected | Requires API key |
| Cursor | Supported | Via MCP |
| Windsurf | Supported | Via MCP |

资料来源：[SetupWizardPage.tsx:42-56](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)

## Installation Methods

AIDOCS supports multiple installation methods across different platforms.

### Automated Installation

#### macOS and Linux

Use the shell installer script for POSIX-compliant systems:

```bash
curl -fsSL https://raw.githubusercontent.com/cristian1991/AIDOCS/main/core/scripts/install.sh | bash
```

The script performs the following operations:
1. Checks for required dependencies (Node.js, Python)
2. Creates necessary directory structure
3. Installs the AIDOCS CLI globally
4. Sets up MCP server configurations
5. Initializes the project workspace

资料来源：[core/scripts/install.sh](https://github.com/cristian1991/AIDOCS/blob/main/core/scripts/install.sh)

#### Windows

For Windows systems, use PowerShell:

```powershell
irm https://raw.githubusercontent.com/cristian1991/AIDOCS/main/core/scripts/install.ps1 | iex
```

The PowerShell installer:
1. Validates PowerShell version (5.1+ required)
2. Installs dependencies via winget or chocolatey
3. Configures Windows-specific paths
4. Registers AIDOCS in the system PATH

资料来源：[core/scripts/install.ps1](https://github.com/cristian1991/AIDOCS/blob/main/core/scripts/install.ps1)

### Manual Installation

For custom deployments, install the CLI directly:

```bash
# Clone the repository
git clone https://github.com/cristian1991/AIDOCS.git
cd AIDOCS

# Install Python dependencies
pip install -e .

# Install Node.js dependencies
cd apps/aidocs-dashboard
npm install
npm run build
```

## Setup Wizard

The first time you launch AIDOCS, a setup wizard guides you through the configuration process.

### Workflow Overview

```mermaid
graph TD
    A[Welcome] --> B[Project Selection]
    B --> C[Prerequisites Check]
    C --> D[AI Host Configuration]
    D --> E[Configuring]
    E --> F[Done]
    
    C -->|Missing dependencies| G[Install Required Tools]
    G --> C
    
    D -->|Not authenticated| H[Sign In Required]
    H --> D
```

### Step 1: Welcome

The welcome screen introduces AIDOCS capabilities:

> AIDOCS gives your AI coding agents persistent memory, indexed retrieval, and orchestration — so they resume work instead of rediscovering your repo every time.

资料来源：[SetupWizardPage.tsx:25-31](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)

### Step 2: Project Selection

Specify the project folder where AIDOCS will operate:

| Field | Description |
|-------|-------------|
| Project Path | Absolute path to your project folder (leave empty for current directory) |
| Auto-detect | Attempts to find an existing AIDOCS configuration |

```typescript
<input
  type="text"
  value={projectPath}
  onChange={(e) => setProjectPath(e.target.value)}
  placeholder="Project folder path (or leave empty for current directory)"
/>
```

资料来源：[SetupWizardPage.tsx:50-55](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)

### Step 3: Prerequisites Check

The installer validates the presence of required tools:

| Tool | Required | Optional |
|------|----------|----------|
| Node.js | Yes | For CLI agents |
| Claude | If using Claude | — |
| OpenAI | If using GPT | — |

Detection results display with status indicators:

| Status | Icon | Meaning |
|--------|------|---------|
| Pass | `+` | Installed and authenticated |
| Warning | `!` | Installed but not signed in |
| Missing | `-` | Not installed (can be auto-installed) |

For hosts requiring authentication:

```typescript
<button onClick={() => {
  const url = h.name.includes("Claude") 
    ? "https://claude.ai" 
    : "https://platform.openai.com/api-keys";
  invoke("open_url", { url });
}}>Sign in</button>
```

资料来源：[SetupWizardPage.tsx:58-72](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)

### Step 4: Configuration

The installer configures MCP servers, hooks, and project structure:

| Configuration Item | Output Path | Description |
|-------------------|-------------|-------------|
| MCP Configuration | `{project}/.aidocs/mcp.json` | MCP server endpoints |
| Hooks Registration | `{project}/.aidocs/hooks.json` | Pre/post execution hooks |
| Project Initialization | `{project}/.aidocs/` | Working directory for AIDOCS |

```typescript
{step === "configure" && (
  <div className="setup-content">
    <h2>Configuring</h2>
    <p>Setting up MCP, hooks, and project structure...</p>
    <div className="setup-spinner" />
  </div>
)}
```

资料来源：[SetupWizardPage.tsx:95-102](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)

### Step 5: Completion

Upon successful installation, the wizard displays:

| Checklist Item | Status |
|----------------|--------|
| MCP configured | ✅ With path shown |
| Hooks registered | ✅ With path shown |
| Project initialized | ✅ |
| MCP servers installed | ✅ (if any selected) |

资料来源：[SetupWizardPage.tsx:104-130](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)

## MCP Server Installation

AIDOCS supports Model Context Protocol (MCP) servers for extended functionality.

### Server Registry

The dashboard includes a searchable registry of MCP servers:

```typescript
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: "12px" }}>
  {results.map((server: RegistrySearchResult) => (
    // Server card rendering
  ))}
</div>
```

资料来源：[RegistryPage.tsx:25-28](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RegistryPage.tsx)

### Installing MCP Servers

Each server in the registry provides installation commands:

| Field | Type | Description |
|-------|------|-------------|
| `install_commands` | Array | Available installation methods |
| `transport` | String | Protocol (stdio, sse, http) |
| `command` | String | Execution command |
| `website_url` | String | Official documentation |

```typescript
const installText = typeof firstCmd === "string" 
  ? firstCmd 
  : String((firstCmd as Record<string, string>).command ?? "");
```

资料来源：[RegistryPage.tsx:30-36](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RegistryPage.tsx)

## CLI Commands

The AIDOCS CLI provides command-line access to installation and management functions.

### Primary Commands

| Command | Description |
|---------|-------------|
| `aidocs init` | Initialize AIDOCS in the current project |
| `aidocs start` | Launch the dashboard |
| `aidocs status` | Check MCP and service status |
| `aidocs config` | Manage configuration |

资料来源：[mcp/server/aidocs_mcp/cli.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/cli.py)

### Post-Installation Steps

After successful installation:

1. **Open your project** in your preferred IDE
2. **Start a new agent session**
3. **Type `/aidocs`** to begin

```html
<div className="setup-next-steps">
  <h3>Next Steps</h3>
  <ol>
    <li>Open <strong>{projectPath || "your project"}</strong> in your IDE</li>
    <li>Start a new agent session</li>
    <li>Type <code>/aidocs</code> to begin</li>
  </ol>
</div>
```

资料来源：[SetupWizardPage.tsx:131-139](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)

## Dashboard Access

After installation, access the AIDOCS dashboard:

```bash
# Start the dashboard server
aidocs start

# Or open the dashboard directly
open http://localhost:3000
```

The dashboard is served from `apps/aidocs-dashboard/` and provides:

- **Overview**: Session status, context budget, recent execution
- **Registry**: Browse and install MCP servers
- **RBAC**: Manage roles and permissions
- **Execution**: View tool call history
- **Settings**: Configure project options

资料来源：[apps/aidocs-dashboard/index.html](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/index.html)

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| Node.js not found | Install via `nvm install 20` or download from nodejs.org |
| Authentication failed | Sign in via the setup wizard "Sign in" button |
| MCP connection failed | Check firewall settings and MCP endpoint configuration |
| Dashboard won't load | Ensure port 3000 is available, or configure alternative port |

### Verification

Confirm successful installation:

```bash
# Check AIDOCS version
aidocs --version

# Verify MCP connection
aidocs status

# Test configuration
aidocs config --validate
```

## Upgrade Instructions

To upgrade AIDOCS to the latest version:

```bash
# Update via npm (if installed globally)
npm update -g aidocs

# Or use the built-in update command
aidocs update
```

After upgrading, run the setup wizard again to apply configuration changes:

```bash
aidocs setup --wizard
```

## Uninstallation

To remove AIDOCS from a project:

```bash
# Remove AIDOCS files (keeps data)
aidocs uninstall

# Complete removal including data
aidocs uninstall --clean
```

This removes:
- `.aidocs/` directory
- MCP configurations
- Hook registrations

Global CLI tools remain installed unless explicitly removed with `npm uninstall -g aidocs`.

---

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

## System Architecture Overview

### 相关页面

相关主题：[MCP Server Architecture](#mcp-server), [Dashboard Architecture](#dashboard), [Memory System](#memory-system)

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

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

- [apps/aidocs-dashboard/src/SetupWizardPage.tsx](https://github.com/cistian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)
- [apps/aidocs-dashboard/src/CastleShell.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/CastleShell.tsx)
- [apps/aidocs-dashboard/src/RegistryPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RegistryPage.tsx)
- [mcp/server/aidocs_mcp/data/opencode_plugin.js](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/data/opencode_plugin.js)
- [apps/aidocs-dashboard/src/OverviewPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/OverviewPage.tsx)
- [apps/aidocs-dashboard/src/LivePage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/LivePage.tsx)
- [apps/aidocs-dashboard/src/ConductorPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/ConductorPage.tsx)
- [apps/aidocs-dashboard/src/BashPolicyPanel.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/BashPolicyPanel.tsx)
</details>

# System Architecture Overview

AIDOCS is a persistent memory and orchestration framework designed for AI coding agents. It provides indexed retrieval, session persistence, and policy-based control to enable AI agents to resume work efficiently without repeatedly rediscovering repository context. The system consists of a frontend dashboard application and a backend MCP (Model Context Protocol) server that communicates with AI coding agents.

## Core Architecture Layers

AIDOCS operates through three primary architectural layers that work together to provide persistent context and control for AI agents.

### Layer 1: MCP Server (`mcp/server/`)

The MCP server acts as the bridge between AI coding agents and the AIDOCS persistent storage system. It exposes tools and resources that agents can invoke during their sessions. The server handles context retrieval, session management, and policy enforcement through a standardized MCP interface.

The server provides several categories of tools including context management tools (`ai_find`, `ai_get_symbol_snippet`, `ai_bundle`), session tools (`session_resume_bundle`, `action_surface_current_session_bundle`), and investigation tools (`ai_investigate`). These tools enable agents to query indexed project knowledge, retrieve symbol information, and understand codebase structure.

资料来源：[apps/aidocs-dashboard/src/SetupWizardPage.tsx]()
资料来源：[mcp/server/aidocs_mcp/data/opencode_plugin.js]()

### Layer 2: Dashboard Application (`apps/aidocs-dashboard/`)

The dashboard is a React-based web application that provides a visual interface for managing AIDOCS configuration, monitoring agent sessions, and administering security policies. The dashboard communicates with the MCP server through IPC (Inter-Process Communication) to retrieve and display session data.

The dashboard uses a modular component architecture built around the `CastleShell` wrapper, which provides consistent navigation, status indicators, and layout structure across all pages.

资料来源：[apps/aidocs-dashboard/src/CastleShell.tsx]()

### Layer 3: Persistent Storage and Indexing

AIDOCS maintains indexed knowledge of the project codebase, session state, and configuration policies. This indexing enables fast retrieval of relevant context when agents resume sessions or need to understand unfamiliar parts of the codebase.

## Dashboard Component Architecture

The AIDOCS dashboard is structured as a single-page application with multiple views accessible through a navigation sidebar. Each view addresses a specific aspect of agent management and monitoring.

```mermaid
graph TD
    A[CastleShell] --> B[OverviewPage]
    A --> C[LivePage]
    A --> D[ConductorPage]
    A --> E[ExecutionPage]
    A --> F[RBACPage]
    A --> G[SettingsPage]
    A --> H[RegistryPage]
    A --> I[CommandPalette]
    
    B --> J[Snapshot Data]
    C --> K[Real-time Events]
    D --> L[Tool Routing]
    E --> M[Event Details]
    
    N[MCP Server] --> J
    N --> K
    N --> L
    N --> M
```

### CastleShell — Main Application Wrapper

The `CastleShell` component serves as the root layout container for the entire dashboard. It manages navigation state, renders the sidebar, and displays the status bar showing connection status and project information.

**Key Properties:**

| Property | Type | Description |
|----------|------|-------------|
| `active` | `NavKey` | Currently selected navigation item |
| `onSelect` | `(key: NavKey) => void` | Callback when navigation changes |
| `counts` | `CastleNavCounts` | Badge counts for navigation items |
| `managedMode` | `boolean` | Whether restricted mode is enabled |
| `mcpConnected` | `boolean` | MCP server connection status |
| `version` | `string` | AIDOCS version display |

The status bar component within CastleShell indicates MCP connection state with a color-coded indicator (green for connected, red for disconnected) and displays the current session ID and active layer.

资料来源：[apps/aidocs-dashboard/src/CastleShell.tsx]()

### SetupWizardPage — Initial Configuration

The `SetupWizardPage` guides users through initial AIDOCS setup with a multi-step wizard interface. It handles project selection, dependency detection, MCP configuration, and hook registration.

**Setup Steps Flow:**

```mermaid
graph LR
    A[welcome] --> B[project]
    B --> C[detection]
    C --> D[configure]
    D --> E[done]
    
    A -->|Get Started| B
    B -->|Select Folder| C
    C -->|Dependencies OK| D
    D -->|Configuration Complete| E
```

The wizard validates system requirements including Node.js presence and AI platform authentication status (Claude, OpenAI). It can detect missing components and offer installation options directly within the interface.

资料来源：[apps/aidocs-dashboard/src/SetupWizardPage.tsx]()

## Session and Execution Monitoring

### OverviewPage — Session Snapshot

The `OverviewPage` displays a consolidated snapshot of the current session including session metadata, capability usage statistics, and recent execution events. It provides at-a-glance monitoring of agent activity through a dashboard-style layout with panels for different data categories.

The page renders execution data in a tabular format showing capability names, action kinds, and timestamps for recent events. This allows operators to quickly assess agent behavior without drilling into detailed logs.

资料来源：[apps/aidocs-dashboard/src/OverviewPage.tsx]()

### LivePage — Real-time Event Stream

The `LivePage` provides a real-time view of agent execution events with support for lane-based isolation and policy enforcement. It displays a scrollable event feed with status indicators and allows operators to approve or reject escalated permission requests.

**LivePage Features:**

| Feature | Description |
|---------|-------------|
| Event Feed | Real-time scrolling list of agent actions |
| Lane Indicators | Visual identification of execution lanes |
| Approval Queue | Pending permission escalation requests |
| Quick Actions | Controls for stopping lanes or pausing execution |

The control panel on the right side of the page contains pending approvals with approve/reject buttons, quick action buttons for lane management, and lane detail expanders showing related events.

资料来源：[apps/aidocs-dashboard/src/LivePage.tsx]()

### ExecutionPage — Detailed Event Analysis

The `ExecutionPage` provides deep-dive analysis of individual execution events. It displays full payload data, result summaries, and audit information for each recorded event. The page supports filtering and searching through execution history to locate specific agent actions.

### LaneDetailPanel — Lane Event Context

The `LaneDetailPanel` component renders detailed information about specific execution lanes including related events, lane status, and execution history. Events are displayed with timestamps and status indicators that reflect whether actions were allowed, refused, or blocked.

Lane events show a color-coded status pill: green for `applied` or `allowed`, red for `refused` or `blocked`, and muted gray for other states.

资料来源：[apps/aidocs-dashboard/src/LaneDetailPanel.tsx]()

## Policy Management

### BashPolicyPanel — Shell Command Control

The `BashPolicyPanel` provides a visual interface for managing shell command execution policies. It displays a summary of allow/deny/bubble counts and allows filtering by policy type.

**Policy Controls:**

| Control | Description |
|---------|-------------|
| Search Filter | Filter commands by name match |
| Type Chips | Filter by all/allow/deny/bubble/modified |
| Collapse Toggle | Show/hide policy details |

Each policy entry shows the effective counts for allow, deny, and bubble policies, along with the active layer where modifications were made and the default fallback policy.

资料来源：[apps/aidocs-dashboard/src/BashPolicyPanel.tsx]()

### RBACPage — Role-Based Access Control

The `RBACPage` manages permissions, escalations, and custom policy configurations. It provides three tabbed views:

1. **Policies Tab** — Lists configured policies with their states (system/custom)
2. **Permissions Tab** — Shows available permission definitions
3. **Escalations Tab** — Displays pending or active permission escalations

The escalations table tracks requesters, requested permissions, session/task context, sticky status, and expiration timestamps.

资料来源：[apps/aidocs-dashboard/src/RBACPage.tsx]()

## MCP Server Integration

### RegistryPage — MCP Server Discovery

The `RegistryPage` enables browsing and installing MCP servers from a remote registry. It supports searching for servers by name and displays installation commands, transport types, and website URLs for each available server.

**Server Card Information:**

| Field | Description |
|-------|-------------|
| Name | Server identifier |
| Transport | Communication protocol |
| Command | Installation command |
| Website | Documentation URL |

资料来源：[apps/aidocs-dashboard/src/RegistryPage.tsx]()

### ConductorPage — Tool Routing Configuration

The `ConductorPage` manages the conductor tool routing system, which controls how different AI backends (Claude, Codex, OpenCode) are used for various tasks. It displays recent tool calls with routing audit information and allows configuration of routing rules.

**Conductor Configuration Options:**

| Setting | Options | Default |
|---------|---------|---------|
| Backend | claude, codex, opencode | claude |
| Claude Model | Model identifier | — |
| Codex Model | Model identifier | — |
| OpenCode Model | Model identifier | — |

The page shows a diff viewer for edit operations, displaying old and new content side-by-side for easy comparison of changes made by the agent.

资料来源：[apps/aidocs-dashboard/src/ConductorPage.tsx]()

## User Interface Components

### CommandPalette — Quick Action Interface

The `CommandPalette` provides keyboard-driven access to common actions. It supports fuzzy search, keyboard navigation (arrow keys), execution (Enter), and quick filtering (Tab).

**Keyboard Shortcuts:**

| Key | Action |
|-----|--------|
| ↑/↓ | Navigate commands |
| Enter | Execute selected command |
| Tab | Switch to filter mode |
| Esc | Close palette |

The palette displays commands with status indicators showing whether they are allowed, denied, or require escalation.

资料来源：[apps/aidocs-dashboard/src/CommandPalette.tsx]()

### SettingDetailPanel — Configuration Editor

The `SettingDetailPanel` displays detailed information about individual configuration entries including current values, origins, and layer assignments. It supports editing configuration values directly within the panel.

The panel includes a per-leaf origin view that shows which layers contributed to each configuration value, useful for understanding inheritance and override behavior in multi-layered configurations.

资料来源：[apps/aidocs-dashboard/src/SettingDetailPanel.tsx]()

## Data Flow Architecture

```mermaid
graph TD
    subgraph Agents["AI Coding Agents"]
        Claude[Claude AI]
        Codex[Codex]
        OpenCode[OpenCode]
    end
    
    subgraph MCP["MCP Protocol Layer"]
        Tools[MCP Tools]
        Resources[MCP Resources]
        Notifications[Notifications]
    end
    
    subgraph Server["AIDOCS Backend"]
        Context[Context Engine]
        Index[Indexing Service]
        Policy[Policy Engine]
        Session[Session Manager]
    end
    
    subgraph Dashboard["Dashboard Frontend"]
        UI[React Components]
        IPC[IPC Bridge]
    end
    
    Claude -->|MCP| Tools
    Codex -->|MCP| Tools
    OpenCode -->|MCP| Tools
    
    Tools --> Context
    Context --> Index
    Index --> Policy
    Policy --> Session
    
    Session -->|Events| Dashboard
    UI -->|Config| Session
    IPC -->|Status| UI
```

## Security Architecture

AIDOCS implements a multi-layered security model through the following mechanisms:

**Permission Escalation:** Agents can request elevated permissions for specific operations. These requests appear in the LivePage approval queue for operator review before execution proceeds.

**Policy Layers:** Configuration policies are organized into layers with inheritance. The SettingDetailPanel shows which layer contributed each configuration value, enabling audit and rollback.

**Bash Command Policies:** Shell execution is controlled through allow/deny/bubble policies. The BashPolicyPanel provides visibility into these rules and supports runtime modification.

**Connection Verification:** The status bar in CastleShell continuously monitors MCP connection status. Loss of connection triggers visual indicators and can be configured to halt agent execution.

## Summary

The AIDOCS architecture provides a complete framework for persistent AI agent context management. The MCP server layer exposes tools for agents to query indexed knowledge and manage sessions. The dashboard provides comprehensive monitoring, configuration, and policy management capabilities. Together, these components enable AI coding agents to maintain context across sessions, operate within defined security boundaries, and provide operators with full visibility into agent activities.

---

<a id='mcp-server'></a>

## MCP Server Architecture

### 相关页面

相关主题：[System Architecture Overview](#architecture-overview), [Conductor & Orchestration](#conductor-orchestration), [Security & Access Control](#security-gates)

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

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

- [mcp/server/aidocs_mcp/mcp_server.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/mcp_server.py)
- [mcp/server/aidocs_mcp/service_hub.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/service_hub.py)
- [mcp/server/aidocs_mcp/tool_discovery.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/tool_discovery.py)
- [mcp/server/aidocs_mcp/mcp_registry.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/mcp_registry.py)
- [mcp/server/aidocs_mcp/runtime_service.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)
</details>

# MCP Server Architecture

The AIDOCS MCP Server is a Python-based Model Context Protocol implementation that provides persistent memory, indexed retrieval, and orchestration capabilities for AI coding agents. It acts as an intermediary layer between AI coding assistants (like Claude Code or OpenCode) and project-specific context, enabling agents to maintain memory across sessions and resume work without re-discovering repository structures.

## Core Architecture Overview

The MCP Server follows a modular architecture with distinct layers for tool management, security enforcement, and runtime orchestration.

```mermaid
graph TD
    subgraph "MCP Server Core"
        MS[mcp_server.py<br/>FastMCP Entry Point]
        SH[service_hub.py<br/>Service Hub]
    end
    
    subgraph "Tool Layer"
        TD[tool_discovery.py<br/>Tool Discovery]
        CE[server_code_edit_tools.py<br/>Edit Tools]
        CT[server_code_tools.py<br/>Code Tools]
    end
    
    subgraph "Security Layer"
        GATE[Gate Architecture<br/>6-Level Cascade]
    end
    
    subgraph "Runtime Services"
        RS[runtime_service.py<br/>Runtime Service]
        REG[mcp_registry.py<br/>Registry]
    end
    
    subgraph "External Integrations"
        CC[Claude Hook]
        OC[OpenCode Plugin]
    end
    
    MS --> SH
    SH --> TD
    SH --> CE
    SH --> CT
    SH --> RS
    MS --> REG
    CC --> MS
    OC --> MS
```

资料来源：[mcp/README.md](https://github.com/cristian1991/AIDOCS/blob/main/mcp/README.md)

## Server Entry Point

The `mcp_server.py` file serves as the primary entry point for the MCP server, initializing FastMCP and registering all available tools and resources.

### Server Initialization

The server follows this initialization sequence:

1. **Configuration Loading** - Loads `aidocs.toml` from the project root
2. **Service Hub Initialization** - Establishes the central service coordinator
3. **Tool Registration** - Discovers and registers all available MCP tools
4. **Registry Setup** - Configures the MCP server registry for host integrations
5. **Security Gate Bootstrap** - Initializes the gate architecture

资料来源：[mcp/server/aidocs_mcp/mcp_server.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/mcp_server.py)

## Service Hub

The `service_hub.py` module acts as the central coordinator for all MCP services, providing a unified interface for tool execution, state management, and service discovery.

### Hub Components

| Component | Purpose | File |
|-----------|---------|------|
| `hub.code` | Code analysis and symbol operations | server_code_tools.py |
| `hub.edit` | File editing operations | server_code_edit_tools.py |
| `hub.runtime` | Session and task management | runtime_service.py |
| `hub.managed_mode` | Managed/unmanaged mode state | service_hub.py |
| `hub.session` | Session state management | service_hub.py |

### Managed Mode System

The Service Hub maintains a managed mode state that controls whether the MCP server operates in supervised or unsupervised mode.

```python
managed = hub.managed_mode.get_mode(project_root)
if managed.get("active"):
    # Enforce gate architecture
    # Block raw file tools
    # Route through workflow system
```

资料来源：[mcp/server/aidocs_mcp/service_hub.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/service_hub.py)
资料来源：[mcp/server/aidocs_mcp/server_code_edit_tools.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/server_code_edit_tools.py)

## Tool Discovery

The `tool_discovery.py` module implements dynamic tool discovery, enabling the MCP server to expose capabilities based on runtime context and project configuration.

### Discovery Process

```mermaid
graph LR
    A[Project Root] --> B[Scan aidocs.toml]
    B --> C[Check .MEMORY/ Structure]
    C --> D[Validate Configuration]
    D --> E[Register Available Tools]
    E --> F[Expose via MCP Protocol]
```

### Available Tool Categories

| Category | Tools | Purpose |
|----------|-------|---------|
| **Code Analysis** | `ai_find`, `ai_get_symbol_snippet`, `ai_get_symbol_info`, `ai_bundle`, `ai_schema_query` | Symbol search and code understanding |
| **Code Editing** | `ai_create_file`, `ai_edit_lines`, `ai_batch_edit`, `ai_str_replace`, `ai_delete_lines` | File modification operations |
| **Session Management** | `session_resume_bundle`, `task_begin`, `task_update`, `task_complete` | Workflow orchestration |
| **Project Operations** | `project_init`, `project_bootstrap_or_resume`, `project_status` | Project lifecycle management |

资料来源：[mcp/server/aidocs_mcp/tool_discovery.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/tool_discovery.py)

## Code Analysis Tools

The code analysis tools provide AI agents with capabilities to navigate, understand, and investigate codebases.

### Symbol Information Modes

The `ai_get_symbol_info` tool supports multiple query modes for different levels of symbol detail:

| Mode | Description | Use Case |
|------|-------------|----------|
| `signature` | Single method signature | Verify function parameters |
| `signatures` | Multiple method signatures | Compare overloaded methods |
| `constructor` | Constructor parameters for a type | Understand object instantiation |
| `constructors` | Batch constructor queries | Analyze multiple types |
| `enum` | Enum values and members | List state options |
| `properties` | Entity properties | Understand data structures |
| `api` | Service API surface | Map service endpoints |

资料来源：[mcp/server/aidocs_mcp/server_code_tools.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/server_code_tools.py)

### Investigation Patterns

The `ai_investigate` tool provides guided navigation with depth and focus parameters:

```python
ai_investigate(concept, depth=..., focus=...)
# depth: exploration depth
# focus: symbol-ranked, favors types/classes/structs
```

Investigation alternatives:
- Known symbol name → `ai_find(name, mode="symbols")`
- Concept/type search → `ai_investigate(concept, depth=..., focus=...)`
- Architecture mapping → `ai_bundle(path, mode="file"|"subsystem")`

## Gate Architecture

The security layer implements a 6-level cascade gate system that controls tool execution based on context and permissions.

### Gate Levels

| Level | Gate | Action | Condition |
|-------|------|--------|-----------|
| 1 | Managed Mode | Block raw file tools when managed | `managed.active == true` |
| 2 | Infrastructure | Block writes to aidocs.toml, aidocs_mcp/* | Project config files |
| 3 | Sensitive Files | Block .env, credentials, keys | File extension/name match |
| 4 | Memory Path | .MEMORY/ reads free, workflow writes intent-gated | Path-based rules |
| 5 | Read Gate | Per-file discovery, `known_exact_path` bypass | File visibility rules |
| 6 | Edit Gate | Requires prior read/discovery | Edit sequence validation |

资料来源：[mcp/README.md](https://github.com/cristian1991/AIDOCS/blob/main/mcp/README.md)

### Gate Flow

```mermaid
graph TD
    A[Tool Request] --> B{Level 1: Managed Mode?}
    B -->|Unmanaged| C[Execute Tool]
    B -->|Managed| D{Level 2: Infrastructure?}
    D -->|No| E{Level 3: Sensitive Files?}
    D -->|Yes| X[Block + Log]
    E -->|No| F{Level 4: Memory Path?}
    E -->|Yes| X
    F -->|Check| G{Level 5: Read Gate?}
    G -->|No| H{Level 6: Edit Gate?}
    G -->|Yes| C
    H -->|Valid| C
    H -->|Invalid| X
```

### Configuration Settings

Security gates can be configured via the dashboard:

| Setting | Purpose | Risk |
|---------|---------|------|
| `dev.dev_mode` | Enables editing AIDOCS MCP server source files | Development only |
| `security.allow_config_edit` | Allows agents to modify AIDOCS config via tool calls | High - can change gate settings |
| `security.enforce` | Enables/disables all tool gates | Critical - removes bash allowlist, raw tool blocking |

资料来源：[apps/aidocs-dashboard/src/dashboardModals.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/dashboardModals.tsx)

## Runtime Service

The `runtime_service.py` module manages session lifecycle, task orchestration, and state persistence.

### Session Management

```python
result = self.task_begin(
    project_root=project_root,
    session_id=session_id,
    goal=None,
    state=state,
    upcoming=upcoming,
    partial_goals=partial_goals,
    end_goal=end_goal,
    blockers=blockers,
    relevant_files=effective_relevant_files,
    relevant_commands=relevant_commands,
    relevant_snippets=relevant_snippets,
    session_facts=session_facts,
    constraints=constraints,
    include_code_bundle=include_code_bundle,
    include_tests=include_tests,
)
```

资料来源：[mcp/server/aidocs_mcp/runtime_service.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)

### State Tracking

The runtime service maintains:

- **Session State** - Current session identifier and metadata
- **Task State** - Active tasks, goals, and blockers
- **Relevant Files** - Files relevant to current task
- **Relevant Commands** - Commands needed for task completion
- **Relevant Snippets** - Code snippets for reference
- **Session Facts** - Accumulated knowledge about the session

### Summary-Only Updates

When `summary_only=True`, the runtime service tracks which fields were updated:

```python
updated_fields: list[str] = []
if state is not None:
    updated_fields.append("state")
if upcoming is not None:
    updated_fields.append("upcoming")
# ... additional field tracking
```

## MCP Registry

The `mcp_registry.py` module provides registry functionality for MCP server discovery and management.

### Registry Capabilities

- **Server Discovery** - Find available MCP servers in the system
- **Transport Detection** - Identify server transport protocols (stdio, SSE, etc.)
- **Command Extraction** - Parse install commands for server setup
- **Server Management** - Track installed and available servers

### Registry UI Components

The dashboard displays registered servers with:

```tsx
{srv.name} · {srv.transport} · {srv.command}
```

Search results show installation commands and website URLs for discovered servers.

资料来源：[mcp/server/aidocs_mcp/mcp_registry.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/mcp_registry.py)
资料来源：[apps/aidocs-dashboard/src/RegistryPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RegistryPage.tsx)

## Host Integrations

The MCP server supports multiple AI coding assistant hosts through platform-specific integrations.

### Claude Code Integration

The Claude hook (`claude_hook.py`) provides:
- Prompt injection with action directives
- Interaction text rendering
- Workflow summary compilation
- Tool preamble generation

```python
_ACTION_DIRECTIVES = {
    "write_code": '`ai_create_file` → `ai_get_lines` (read) → `ai_edit_lines` or `ai_batch_edit` (write) → `task_complete`',
    "trace": '`ai_find(query, mode="references")` → `ai_trace(query, mode="field_flow"|"css_class"|"api_to_ui")`',
    "understand": '`session_resume_bundle` → `action_surface_current_session_bundle` → `ai_find(query, mode="symbols")` → `ai_get_symbol_snippet`',
}
```

### OpenCode Integration

The OpenCode plugin (`opencode_plugin.js`) provides:
- Startup state detection
- Project initialization checks
- Execution prompt building
- Interaction text handling

资料来源：[mcp/server/aidocs_mcp/claude_hook.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/claude_hook.py)
资料来源：[mcp/server/aidocs_mcp/data/opencode_plugin.js](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/data/opencode_plugin.js)

## Memory Model

The MCP server maintains a hierarchical memory structure within project directories:

```
/.MEMORY/
  .aidocs/index.aidocs     # Session-start router
  sessions/                # Session-specific state
  skills/                  # Skill definitions
  plans/                   # Task plans
```

### Memory Path Gate Rules

| Path Type | Read Access | Write Access |
|-----------|-------------|--------------|
| `.MEMORY/` | Free (Level 4) | Intent-gated |
| `aidocs.toml` | Free | Blocked (Level 2) |
| `aidocs_mcp/*` | Free | Blocked (Level 2) |
| Project Files | Discovery required | Prior read required |

## Edit Tool Sequencing

Sequential line-based edits to the same file can corrupt line numbers. The MCP server enforces:

1. **Single-file line edits** trigger a rejection if the file was already edited this turn
2. **Batch alternatives** (`ai_batch_edit`, `ai_str_replace`, `ai_batch_str_replace`) handle ordering internally
3. **Line-independent matching** bypasses the sequential edit check

```python
def _check_turn_edited(project_root, path, tool_name):
    """Return rejection if file already edited this turn"""
    managed = hub.managed_mode.get_mode(project_root)
    if not managed.get("active"):
        return None
    # Check session_id and file edit history
```

资料来源：[mcp/server/aidocs_mcp/server_code_edit_tools.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/server_code_edit_tools.py)

## Installation and Setup

### Package Installation

```bash
pip install aidocs-mcp              # from PyPI
pip install aidocs-mcp[dev]         # with pytest
pip install aidocs-mcp[ast]         # with tree-sitter for JS/TS AST parsing
```

### Setup Command

```bash
aidocs setup                  # Configures MCP, hooks, project init
aidocs doctor                 # Verify the install
```

### Setup Wizard

The dashboard includes a setup wizard (`SetupWizardPage.tsx`) that guides users through:

1. **Welcome** - Introduction to AIDOCS capabilities
2. **Project Selection** - Choose project folder
3. **Configuring** - MCP, hooks, and project structure setup
4. **Done** - Confirmation with checklist

资料来源：[apps/aidocs-dashboard/src/SetupWizardPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)
资料来源：[README.md](https://github.com/cristian1991/AIDOCS/blob/main/README.md)

## Dashboard Status Indicators

The CastleShell UI component displays MCP connection status:

```tsx
<span className={mcpConnected ? "text-castle-allow" : "text-castle-deny"}>
    <span className={mcpConnected ? "bg-castle-allow" : "bg-castle-deny"} />
    {mcpConnected ? "MCP connected" : "MCP disconnected"}
</span>
```

### Status Bar Components

| Component | Purpose |
|-----------|---------|
| `mcpConnected` | Boolean indicating MCP server connection |
| `projectName` | Current project identifier |
| `sessionId` | Active session identifier |
| `activeLayer` | Current execution layer |
| `saveState` | Persistence state indicator |

资料来源：[apps/aidocs-dashboard/src/CastleShell.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/CastleShell.tsx)

---

<a id='dashboard'></a>

## Dashboard Architecture

### 相关页面

相关主题：[System Architecture Overview](#architecture-overview), [Conductor & Orchestration](#conductor-orchestration)

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

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

- [apps/aidocs-dashboard/src/SetupWizardPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)
- [apps/aidocs-dashboard/src/CastleShell.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/CastleShell.tsx)
- [apps/aidocs-dashboard/index.html](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/index.html)
- [apps/aidocs-dashboard/src/RegistryPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RegistryPage.tsx)
- [apps/aidocs-dashboard/src/OverviewPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/OverviewPage.tsx)
- [apps/aidocs-dashboard/src/dashboardModals.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/dashboardModals.tsx)
- [apps/aidocs-dashboard/src/TomlConfigsPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/TomlConfigsPage.tsx)
- [apps/aidocs-dashboard/src/dashboardCharts.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/dashboardCharts.tsx)
- [apps/aidocs-dashboard/src/ConductorPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/ConductorPage.tsx)
- [apps/aidocs-dashboard/src/RBACPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RBACPage.tsx)
- [mcp/README.md](https://github.com/cristian1991/AIDOCS/blob/main/mcp/README.md)
- [README.md](https://github.com/cristian1991/AIDOCS/blob/main/README.md)
- [README_INSTALL.md](https://github.com/cristian1991/AIDOCS/blob/main/README_INSTALL.md)
- [mcp/server/aidocs_mcp/config_schema.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/config_schema.py)
</details>

# Dashboard Architecture

The AIDOCS Dashboard is a Tauri-based desktop application that provides a comprehensive user interface for monitoring, managing, and configuring the AIDOCS AI coding assistant infrastructure. It serves as the central control plane for all AIDOCS operations, from initial project setup to ongoing session monitoring and security configuration.

## Overview

The dashboard functions as a bridge between the user and the underlying MCP (Model Context Protocol) server infrastructure. It enables users to visualize project state, manage AI backends, configure security policies, and monitor token usage across sessions. The architecture follows a clean separation between the Rust-based Tauri backend and the React/TypeScript frontend, providing native desktop performance while maintaining rapid development iteration cycles.

The dashboard is designed to work in conjunction with the `aidocs-mcp` Python package, which runs as a separate MCP server process. The dashboard communicates with this server via IPC commands to retrieve runtime state and push configuration changes. This decoupled design allows the MCP server to operate independently of the dashboard GUI, enabling headless operation in CI/CD environments or remote servers.

## Technology Stack

### Frontend Layer

The frontend is built with React 18 and TypeScript, providing type-safe component development and modern hooks-based state management. Vite serves as the build tool and development server, offering fast hot module replacement during development and optimized production builds.

| Component | Technology | Purpose |
|-----------|------------|---------|
| UI Framework | React 18 | Component rendering and state management |
| Language | TypeScript | Type safety and IDE support |
| Build Tool | Vite | Fast builds and HMR |
| Styling | CSS Variables + Tailwind | Custom theming with Castle design system |
| Charts | Custom implementation | Token usage visualization |

资料来源：[apps/aidocs-dashboard/index.html:1-10]()

### Backend Layer

The Tauri backend is implemented in Rust, providing native system integration capabilities including window management, file system access, and process spawning. The backend exposes a command API that the React frontend invokes via Tauri's invoke mechanism.

| Component | Technology | Purpose |
|-----------|------------|---------|
| Runtime | Tauri 2.x | Desktop app framework |
| Language | Rust | Backend command implementation |
| IPC | Tauri Commands | Frontend-backend communication |
| Window | WebView2/WebKit | Render React frontend |

资料来源：[README_INSTALL.md](https://github.com/cristian1991/AIDOCS/blob/main/README_INSTALL.md)

## Architecture Components

### Component Hierarchy

```mermaid
graph TD
    A[Tauri Backend<br/>main.rs] --> B[React App<br/>App.tsx]
    B --> C[CastleShell<br/>Navigation Framework]
    C --> D[OverviewPage<br/>Project Overview]
    C --> E[RegistryPage<br/>MCP Server Registry]
    C --> F[ConductorPage<br/>Backend Routing]
    C --> G[RBACPage<br/>Access Control]
    C --> H[TomlConfigsPage<br/>TOML Editor]
    C --> I[UsagePage<br/>Token Analytics]
    C --> J[SetupWizardPage<br/>Initial Setup]
    C --> K[dashboardModals<br/>Confirmation Dialogs]
    
    L[StatusBar<br/>MCP Status] -.-> C
    M[ContextRail<br/>Sidebar Info] -.-> C
    N[CommandPalette] -.-> C
```

### CastleShell Navigation Framework

The `CastleShell` component serves as the primary layout container, providing consistent navigation, status indication, and context management across all dashboard pages. It implements a tab-based navigation system with optional managed mode indicators.

资料来源：[apps/aidocs-dashboard/src/CastleShell.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/CastleShell.tsx)

#### Navigation Types

```typescript
type NavKey = "overview" | "registry" | "conductor" | "rbac" | 
              "configs" | "usage" | "wizard";
```

#### Shell Props Interface

| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `active` | `NavKey` | Yes | Currently selected navigation tab |
| `onSelect` | `(key: NavKey) => void` | Yes | Callback when navigation changes |
| `counts` | `CastleNavCounts` | No | Badge counts for each section |
| `managedMode` | `boolean` | No | Visual indicator for managed mode state |
| `version` | `string` | No | AIDOCS version display |
| `mcpConnected` | `boolean` | Yes | MCP server connection status |
| `activeLayer` | `string` | No | Current active layer indicator |
| `saveState` | `string` | No | Auto-save state indicator |
| `contextRail` | `ReactNode` | No | Optional sidebar content |

### Status Bar

The status bar component provides real-time connection status and contextual information at the bottom of the application window. It displays MCP connection state with visual indicators and supports tooltip-based detailed status views.

资料来源：[apps/aidocs-dashboard/src/CastleShell.tsx:32-54]()

```typescript
type CastleStatusBarProps = {
  mcpConnected: boolean;
  projectName?: string;
  sessionId?: string;
  activeLayer?: string;
  saveState?: string;
};
```

## Dashboard Pages

### Overview Page

The Overview page provides a snapshot of the current project state, including recent execution events, active sessions, and capability utilization. It renders a runtime snapshot retrieved from the MCP server via the dashboard API.

资料来源：[apps/aidocs-dashboard/src/OverviewPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/OverviewPage.tsx)

```mermaid
graph LR
    A[MCP Server] -->|Runtime Snapshot| B[OverviewPage]
    B --> C[Project Info Panel]
    B --> D[Recent Execution Table]
    B --> E[Capability Stats]
```

### Registry Page

The Registry page enables browsing and searching the MCP server registry. Users can view installed servers, search for available servers by name, and initiate installations directly from the interface.

资料来源：[apps/aidocs-dashboard/src/RegistryPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RegistryPage.tsx)

#### Registry Search Result Structure

```typescript
interface RegistrySearchResult {
  name: string;
  install_commands?: Array<{
    command?: string;
    type?: string;
  }>;
  website_url?: string;
}
```

### Conductor Page

The Conductor page manages backend routing configuration, allowing users to select between different AI backends (Claude, Codex, OpenCode) and configure per-backend model settings. It provides a visual representation of the routing lanes and their blocked/run states.

资料来源：[apps/aidocs-dashboard/src/ConductorPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/ConductorPage.tsx)

#### Conductor Configuration Model

```typescript
interface ConductorConfig {
  backend: "claude" | "codex" | "opencode";
  models: {
    claude: string;
    codex: string;
    opencode: string;
  };
  lanes: ConductorLane[];
}
```

### RBAC Page

The Role-Based Access Control page displays and manages permission grants, showing which sessions and tasks have been granted specific capabilities. It supports both sticky (persistent) and once (single-use) grant types with expiration tracking.

资料来源：[apps/aidocs-dashboard/src/RBACPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RBACPage.tsx)

#### RBAC Entry Display

| Field | Description |
|-------|-------------|
| `session_id` | Session identifier with optional task ID |
| `sticky` | Sticky grants persist across sessions |
| `created_at` | Grant creation timestamp |
| `expires_at` | Optional expiration timestamp |

### TOML Configuration Page

The TOML Configuration page provides a visual editor for AIDOCS TOML documents, organized by category. Users can view and manage configuration entries for Action Tokens, Action Hooks, and Language Descriptors.

资料来源：[apps/aidocs-dashboard/src/TomlConfigsPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/TomlConfigsPage.tsx)

#### Configuration Categories

| Category | Purpose |
|----------|---------|
| `intent_tokens` | Action token definitions for prompt classification |
| `gate_messages` | Action hook message templates |
| `language_descriptors` | Language-specific behavior descriptors |

### Usage Page

The Usage page visualizes token consumption across sessions, providing charts for input/output token ratios, session breakdowns, and tool-specific usage. It supports both bar and pie chart modes for different visualization preferences.

资料来源：[apps/aidocs-dashboard/src/dashboardCharts.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/dashboardCharts.tsx)

#### Usage Data Model

```typescript
interface TokenEstimates {
  tokens_in: number;
  tokens_out: number;
  tokens_in_calls?: number;
  tokens_out_calls?: number;
}

interface SessionBreakdown {
  session_id: string;
  total: number;
  events: number;
}
```

### Setup Wizard

The Setup Wizard guides users through initial AIDOCS configuration with a multi-step flow. It handles project path selection, environment detection, and host authentication verification.

资料来源：[apps/aidocs-dashboard/src/SetupWizardPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)

#### Wizard Steps

```mermaid
graph LR
    A[welcome] --> B[project]
    B --> C[environment]
    C --> D[configure]
    D --> E[done]
    
    A -->|Get Started| B
    B -->|Configure| D
    E -->|Open Dashboard| F[Dashboard]
```

#### Setup Step Configuration

| Step | Purpose |
|------|---------|
| `welcome` | Introduction and value proposition |
| `project` | Project folder selection |
| `environment` | Runtime detection (Node.js, CLI agents) |
| `configure` | MCP, hooks, and project structure setup |
| `done` | Confirmation and next steps |

#### Environment Detection

The wizard detects available AI hosts and their authentication status:

```typescript
interface HostDetection {
  name: string;
  found: boolean;
  authenticated: boolean;
  path?: string;
  installable?: boolean;
}
```

Supported hosts include Claude and OpenAI platforms, with sign-in buttons linking to respective authentication pages.

### Modal Components

Security-sensitive operations require explicit user confirmation through modal dialogs. The dashboard provides dedicated confirmation modals for dangerous configuration changes.

资料来源：[apps/aidocs-dashboard/src/dashboardModals.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/dashboardModals.tsx)

#### Protected Settings

| Setting | Risk Description |
|---------|------------------|
| `dev.dev_mode` | Enables editing AIDOCS MCP server source files |
| `security.allow_config_edit` | Allows agents to modify AIDOCS config via tool calls |
| `security.enforce` | Disabling removes tool gates and destructive command protection |

#### Loading Overlay

The `LoadingOverlay` component displays during snapshot refresh operations:

```typescript
export function LoadingOverlay() {
  return (
    <div className="app-overlay" role="status" aria-live="polite">
      <div className="app-overlay-panel">
        <div className="overlay-spinner" />
        <strong>Loading runtime snapshot</strong>
        <span>Refreshing project, session, and settings state.</span>
      </div>
    </div>
  );
}
```

## MCP Integration

The dashboard communicates with the AIDOCS MCP server through Tauri's IPC mechanism. The MCP server exposes tools for project management, session control, memory operations, and code analysis.

### Core MCP Tools

| Category | Tools |
|----------|-------|
| **Session** | `ai_session` (list, create, connect, update, release, resume) |
| **Memory** | `memory_read`, `memory_capture`, `memory_search` |
| **Project** | `project_init`, `project_bootstrap_or_resume`, `project_sync_indexes` |
| **Code** | `ai_find`, `ai_get_lines`, `ai_edit_lines`, `ai_batch_edit` |
| **Analysis** | `ai_trace`, `ai_bundle`, `schema_query` |

资料来源：[mcp/README.md](https://github.com/cristian1991/AIDOCS/blob/main/mcp/README.md)

### Configuration Schema

The MCP server maintains configuration entries with support for various scopes and security classifications:

资料来源：[mcp/server/aidocs_mcp/config_schema.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/config_schema.py)

#### Security-Sensitive Settings

```python
"dev.dev_mode": _setting(
    type="boolean",
    default=False,
    description="[T0 DASHBOARD-ONLY] Unlocks AIDOCS infrastructure source editing.",
    security_sensitive=True,
    dashboard_only=True,
    scope=["project"],
)
```

#### Tool Output Configuration

| Setting | Default | Purpose |
|---------|---------|---------|
| `tool_output.pretty` | `false` | Dual-channel pretty rendering |
| `tool_output.show_tool_name` | `false` | Inline debug markers |
| `tool_output.show_duration` | `false` | Per-call duration display |
| `tool_output.show_tokens` | `false` | Token count estimation |

## Build and Deployment

### Development Mode

```bash
cd apps/aidocs-dashboard
npm install
npm run tauri dev
```

### Production Build

```bash
npm run tauri build
```

The build process compiles the Rust backend and bundles the React frontend into a native executable.

### Launch Scripts

| Platform | Script |
|----------|--------|
| Windows | `core\scripts\launch-dashboard.cmd` |
| Linux/macOS | `bash core/scripts/launch-dashboard.sh` |

资料来源：[README_INSTALL.md](https://github.com/cristian1991/AIDOCS/blob/main/README_INSTALL.md)

## Data Flow

```mermaid
sequenceDiagram
    participant User
    participant Dashboard as React UI
    participant Tauri as Tauri Backend
    participant MCP as MCP Server
    participant Project as Project Files
    
    User->>Dashboard: Navigate to page
    Dashboard->>Tauri: invoke("command", args)
    Tauri->>MCP: IPC / Tool Calls
    MCP->>Project: File System Operations
    Project-->>MCP: State / Config
    MCP-->>Tauri: Response
    Tauri-->>Dashboard: Serialized Data
    Dashboard-->>User: Rendered UI
```

## Security Architecture

The dashboard implements several security measures:

1. **T0 Dashboard-Only Settings**: Certain configuration changes are restricted to the dashboard and cannot be modified by agents through NLP or tool calls.

2. **Confirmation Modals**: Security-sensitive operations require explicit user confirmation before execution.

3. **Output Guard**: The MCP server includes output filtering to detect and redact sensitive content patterns.

资料来源：[mcp/server/aidocs_mcp/output_guard.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/output_guard.py)

#### Sensitive Content Patterns

| Pattern | Detection |
|---------|-----------|
| `env_file_content` | Environment variables with 8+ character values |
| `ssh_config` | SSH host configurations and identity files |

## Design System

The dashboard uses the "Castle" design system with a dark theme and muted accent colors:

| Token | Value | Usage |
|-------|-------|-------|
| `--castle-line` | Border color | Panel separators |
| `--castle-mute` | Muted text | Secondary labels |
| `--castle-allow` | Green | Success states |
| `--castle-deny` | Red | Error states |

The design system is implemented via CSS custom properties, enabling consistent theming across all components.

---

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

## Memory System

### 相关页面

相关主题：[System Architecture Overview](#architecture-overview), [Indexing & Retrieval System](#indexing-retrieval)

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

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

- [core/.MEMORY/.aidocs/memory-system.aidocs](https://github.com/cristian1991/AIDOCS/blob/main/core/.MEMORY/.aidocs/memory-system.aidocs)
- [mcp/server/aidocs_mcp/memory_store.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/memory_store.py)
- [mcp/server/aidocs_mcp/session_store.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/session_store.py)
- [mcp/server/aidocs_mcp/memory_discovery.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/memory_discovery.py)
- [mcp/server/aidocs_mcp/aidocs_nlp/consumers/memory_surfacer.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/aidocs_nlp/consumers/memory_surfacer.py)
- [mcp/server/aidocs_mcp/runtime_service.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)
</details>

# Memory System

## Overview

The AIDOCS Memory System provides persistent memory infrastructure for AI coding agents, enabling them to resume work across sessions without rediscovering repositories from scratch. The system organizes agent-generated knowledge into structured directories, validates memory file placement, detects stale content, and surfaces relevant memories during task execution.

Memory is stored in a `.MEMORY` directory at the project root, containing structured subdirectories for sessions, archived work, rules, standards, lessons, and roadmaps.

## Architecture

```mermaid
graph TD
    subgraph "Memory Storage Layer"
        MEM[.MEMORY/]
        SESS[.MEMORY/sessions/]
        ARCH[.MEMORY/archive/]
        RULES[.MEMORY/rules/]
        STD[.MEMORY/standards/]
        LESS[.MEMORY/lessons/]
        ROAD[.MEMORY/roadmaps/]
    end
    
    subgraph "MCP Tools"
        MS[memory_store.py]
        SS[session_store.py]
        MD[memory_discovery.py]
        MF[memory_surfacer.py]
    end
    
    subgraph "Validation & Scanning"
        RS[runtime_service.py<br>memory_validator]
        SF[stale_finder]
        GP[pattern_scanner]
    end
    
    MEM --> SESS
    MEM --> ARCH
    MEM --> RULES
    MEM --> STD
    MEM --> LESS
    MEM --> ROAD
    
    SESS --> MS
    ARCH --> SS
    MS --> MD
    MD --> MF
    RS --> GP
```

## Directory Structure

The Memory System enforces a specific directory structure to maintain organized, retrievable knowledge:

| Directory | Purpose |
|-----------|---------|
| `.MEMORY/sessions/<session_id>/` | Active session files |
| `.MEMORY/archive/sessions/<session_id>/` | Archived session data |
| `.MEMORY/rules/` | Coding rules and guidelines |
| `.MEMORY/standards/` | Project standards documentation |
| `.MEMORY/lessons/` | Learned lessons and post-mortems |
| `.MEMORY/roadmaps/` | Future plans and milestones |

资料来源：[runtime_service.py:24-28](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)

## Memory File Naming Rules

The system enforces strict placement rules for memory files. These rules ensure consistent organization and enable reliable retrieval.

### File Location Rules

| File Name | Valid Location | Path Segments |
|-----------|---------------|---------------|
| `SESSION.md` | `.MEMORY/sessions/<id>/` | 3 segments |
| `CONTEXT.md` | `.MEMORY/sessions/<id>/` | 3 segments |
| `TODO.md` | `.MEMORY/sessions/<id>/` | 3 segments |
| `NOTES.md` | `.MEMORY/sessions/<id>/` | 3 segments |
| `PLAN.md` | `.MEMORY/sessions/<id>/plans/` | 4 segments |

资料来源：[runtime_service.py:47-67](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)

### Validation Logic

```python
# For session files (SESSION.md, CONTEXT.md, TODO.md, NOTES.md)
ok = (
    (len(parts) == 3 and parts[0] == "sessions")
    or (len(parts) == 4 and parts[:2] == ("archive", "sessions"))
)

# For PLAN.md
ok = (
    (len(parts) == 4 and parts[0] == "sessions" and parts[2] == "plans")
    or (len(parts) == 5 and parts[:2] == ("archive", "sessions") and parts[3] == "plans")
)
```

资料来源：[runtime_service.py:58-67](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)

## Header Pattern Detection

The system scans memory files for header patterns that indicate the type of content and its organization. These patterns help categorize and prioritize memory retrieval.

### G2 Patterns (Work-in-Progress Headers)

Files with these header patterns indicate ongoing investigation or active work:

| Pattern | Keywords |
|---------|----------|
| `re.IGNORECASE` | `investigating`, `reading`, `trying`, `exploring`, `debugging`, `checking`, `figuring`, `attempting`, `wip`, `todo:`, `notes:` |

```python
g2_pattern = re.compile(
    r"^#+\s+(investigating|reading|trying|exploring|debugging|"
    r"checking|figuring|attempting|wip|todo:|notes?:)\b",
    re.IGNORECASE,
)
```

### G3 Patterns (Planning Headers)

Files with these headers indicate structured planning or backlog items:

| Pattern | Keywords |
|---------|----------|
| `re.IGNORECASE` | `plan`, `phase`, `step`, `tasks`, `backlog`, `roadmap`, `milestone` |

```python
g3_pattern = re.compile(
    r"^#+\s+(plan|phase\s*\d|step\s*\d|steps|tasks|backlog|"
    r"roadmap|milestone)\b",
    re.IGNORECASE,
)
```

### Skipped Directories

Certain directories are excluded from pattern validation as they are expected to contain these patterns:

| Pattern Type | Skipped Directories |
|--------------|---------------------|
| G2 | `sessions`, `archive`, `.aidocs`, `.index` |
| G3 | `sessions`, `archive`, `.aidocs`, `.index`, `roadmaps` |

资料来源：[runtime_service.py:29-35](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)

## Memory Validation API

### `memory_structure_checker`

Validates the entire memory directory structure for compliance with naming and placement rules.

**Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `project_root` | `Path` | — | Project root path |
| `memory_root` | `str` | `".MEMORY"` | Memory directory name |

**Returns:**

```python
{
    "ok": bool,
    "memory_root": str,
    "violations": [
        {
            "path": str,
            "name": str,
            "expected_location": str
        }
    ],
    "count": int,
    "error": Optional[str]
}
```

**Error States:**

| Error Code | Description |
|------------|-------------|
| `memory_root_not_found` | The `.MEMORY` directory does not exist in the project |

资料来源：[runtime_service.py:12-21](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)

## Stale Memory Detection

### `memory_stale_finder`

Identifies memory files that have not been modified in a configurable time period. This helps maintain memory freshness and prevents outdated information from being surfaced.

**Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `project_root` | `Path` | — | Project root path |
| `stale_after_days` | `int` | `90` | Days after which memory is considered stale |
| `memory_root` | `str` | `".MEMORY"` | Memory directory name |

**Rationale:**

> "Memory drifts: rules written months ago for a now-dead workflow are worse than no rules at all."

资料来源：[runtime_service.py:106-108](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_service.py)

## Memory Surfacing

The `memory_surfacer` module provides retrieval capabilities for surfacing relevant memories based on context. It consumes NLP-processed data to match current task context with stored memories.

### Key Responsibilities

- Match query context against stored memory content
- Rank memories by relevance
- Filter memories by type, age, and source
- Handle deduplication across sessions

```python
# Conceptual flow
user_query → context_extraction → memory_search → relevance_ranking → filtered_results
```

资料来源：[memory_surfacer.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/aidocs_nlp/consumers/memory_surfacer.py)

## Memory Discovery

The discovery module (`memory_discovery.py`) provides mechanisms to locate and index memory files across the project.

### Discovery Capabilities

- Recursive traversal of `.MEMORY` directory tree
- Filtering by memory type (sessions, rules, standards, lessons)
- Metadata extraction from memory file headers
- Cross-reference identification between memories

## Session Store

Session storage maintains the state of agent sessions across the memory hierarchy.

### Session File Types

| File | Purpose | Location |
|------|---------|----------|
| `SESSION.md` | Session metadata and context | `.MEMORY/sessions/<id>/` |
| `CONTEXT.md` | Current working context | `.MEMORY/sessions/<id>/` |
| `TODO.md` | Task backlog | `.MEMORY/sessions/<id>/` |
| `NOTES.md` | Session observations | `.MEMORY/sessions/<id>/` |
| `PLAN.md` | Session plan | `.MEMORY/sessions/<id>/plans/` |

资料来源：[session_store.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/session_store.py)

## Security Considerations

The Memory System integrates with the security guard infrastructure to protect against prompt injection and sensitive data leakage.

### Pattern Scanning Integration

Memory files are scanned for:

- **Prompt injection patterns** (role hijack, instruction injection, delimiter escape)
- **Sensitive content** (env file patterns, SSH config)
- **Capability declarations** (file operations, command execution, database access)

See [Security Gates](Security-Gates) for detailed pattern definitions.

## Workflow

```mermaid
graph LR
    A[Agent Session Start] --> B[Create/Load Session]
    B --> C[Memory Discovery]
    C --> D[Relevant Memories Surfaced]
    D --> E[Agent Work]
    E --> F[Update Memory Files]
    F --> G[Structure Validation]
    G --> H[Archive or Keep Active]
    H --> I[Session End]
```

## Configuration

### Memory Root Location

Default: `.MEMORY` (relative to project root)

### Validation Strictness

The system performs validation on:
- File naming conventions
- Directory placement
- Path segment counts
- Header pattern compliance

### Staleness Threshold

Default: 90 days
Configurable via `stale_after_days` parameter

## Related Components

| Component | Relationship |
|-----------|--------------|
| [MCP Runtime](MCP-Runtime) | Provides tools for memory operations |
| [Security Gates](Security-Gates) | Scans memory content for risks |
| [Conductor](Conductor) | Uses memory for task orchestration |
| [Dashboard](Dashboard) | Visualizes memory state and health |

---

<a id='conductor-orchestration'></a>

## Conductor & Orchestration

### 相关页面

相关主题：[MCP Server Architecture](#mcp-server), [Security & Access Control](#security-gates), [Dashboard Architecture](#dashboard)

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

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

- [mcp/server/aidocs_mcp/conductor_comms.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/conductor_comms.py)
- [mcp/server/aidocs_mcp/runtime_orchestration_service.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_orchestration_service.py)
- [mcp/server/aidocs_mcp/runtime_conductor_dispatch_service.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_conductor_dispatch_service.py)
- [mcp/server/aidocs_mcp/plan_conductor.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/plan_conductor.py)
- [mcp/server/aidocs_mcp/co_conductor.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/co_conductor.py)
- [mcp/server/aidocs_mcp/agent_orchestrator.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/agent_orchestrator.py)
- [apps/aidocs-dashboard/src/ConductorPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/ConductorPage.tsx)
- [apps/aidocs-dashboard/src-tauri/src/main.rs](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src-tauri/src/main.rs)
</details>

# Conductor & Orchestration

The Conductor & Orchestration system is the central coordination layer in AIDOCS, providing persistent, long-lived agent orchestration across coding sessions. Rather than spawning isolated one-off agent calls, the Conductor acts as a supervisory intelligence that plans, delegates, monitors, and resolves conflicts among multiple lane-based worker agents.

## Overview

The Conductor orchestrates AI coding work by:

- Maintaining persistent memory across sessions
- Creating and managing execution **lanes** (isolated task pipelines)
- Routing tasks to appropriate backend models (Claude, Codex, OpenCode)
- Resolving inter-lane conflicts and blocking conditions
- Providing a real-time chat interface for human-in-the-loop oversight

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

## Architecture

The orchestration system is composed of multiple layers:

```mermaid
graph TD
    subgraph "Frontend (Dashboard)"
        CP[ConductorPage]
        CH[ConductorChat]
        LP[Lanes Panel]
        TCP[ToolCallsPanel]
    end
    
    subgraph "Backend (Rust/Tauri)"
        MS[Main State]
        CS[ConductorState]
    end
    
    subgraph "MCP Server (Python)"
        ROS[RuntimeOrchestrationService]
        RCDS[RuntimeConductorDispatchService]
        PC[PlanConductor]
        CC[CoConductor]
        AC[AgentOrchestrator]
        CCM[ConductorComms]
    end
    
    CP -->|Tauri Commands| MS
    CH -->|conductor_start/send| CS
    CS -->|MCP Tools| ROS
    ROS --> RCDS
    RCDS --> PC
    RCDS --> CC
    PC --> AC
    CC --> AC
    AC --> CCM
```

## Core Components

### PlanConductor

The `PlanConductor` is responsible for high-level task planning. It receives goals and breaks them into discrete execution lanes, establishing dependencies and ordering constraints.

**Key Responsibilities:**

- Parse incoming task descriptions
- Generate execution plans with lane definitions
- Set lane blocking conditions
- Track plan progress through completion

资料来源：[mcp/server/aidocs_mcp/plan_conductor.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/plan_conductor.py)

### CoConductor

The `CoConductor` operates as a parallel supervisory agent that assists the primary conductor. It handles secondary routing decisions and provides fallback reasoning when the main conductor encounters ambiguous situations.

**Key Responsibilities:**

- Parallel task assessment
- Fallback routing decisions
- Conflict resolution between lanes
- Escalation handling

资料来源：[mcp/server/aidocs_mcp/co_conductor.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/co_conductor.py)

### RuntimeOrchestrationService

The `RuntimeOrchestrationService` serves as the central service entry point for all orchestration operations. It manages session state and dispatches requests to appropriate conductor components.

**Key Responsibilities:**

- Session lifecycle management
- Service initialization and teardown
- Request routing to PlanConductor/CoConductor
- State synchronization with dashboard

资料来源：[mcp/server/aidocs_mcp/runtime_orchestration_service.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_orchestration_service.py)

### RuntimeConductorDispatchService

The `RuntimeConductorDispatchService` handles the low-level dispatch of tasks to specific backends. It manages connection pooling, request queuing, and response aggregation.

**Key Responsibilities:**

- Backend selection (claude/codex/opencode)
- Request dispatch and retry logic
- Response aggregation
- Connection state management

资料来源：[mcp/server/aidocs_mcp/runtime_conductor_dispatch_service.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/runtime_conductor_dispatch_service.py)

### AgentOrchestrator

The `AgentOrchestrator` coordinates the actual execution of tasks within each lane. It manages tool calls, maintains execution context, and handles error recovery.

**Key Responsibilities:**

- Lane-level task execution
- Tool call management and policy enforcement
- Execution state persistence
- Error recovery and retry

资料来源：[mcp/server/aidocs_mcp/agent_orchestrator.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/agent_orchestrator.py)

### ConductorComms

The `ConductorComms` module handles inter-process and inter-service communication. It provides the messaging substrate for conductor components and the dashboard.

**Key Responsibilities:**

- Message formatting and serialization
- Transport abstraction
- Session message routing
- Event broadcasting

资料来源：[mcp/server/aidocs_mcp/conductor_comms.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/conductor_comms.py)

## State Management (Rust Backend)

The Tauri backend maintains conductor state across sessions using a global state map.

```mermaid
graph TD
    subgraph "ConductorState"
        PID[process: Option Child]
        OUT[output: Vec f64, String, String]
        BE[backend: Option String]
        MD[model: Option String]
        PORT[opencode_port: Option u16]
        CSID[claude_session_id: Option String]
        COXSID[codex_session_id: Option String]
        SIF[codex_send_in_flight: bool]
    end
    
    subgraph "Global State"
        CONDUCTORS[HashMap ConductorKey ConductorState]
    end
    
    CONDUCTORS -->|key: (root, session_id)| PID
    CONDUCTORS -->|key: (root, session_id)| BE
```

### ConductorKey Structure

| Field | Type | Description |
|-------|------|-------------|
| `root` | `PathBuf` | Project root directory |
| `session_id` | `String` | Unique session identifier |

### ConductorState Fields

| Field | Type | Description |
|-------|------|-------------|
| `process` | `Option<Child>` | Active child process handle |
| `output` | `Vec<(f64, String, String)>` | Execution output with timing |
| `backend` | `Option<String>` | Current backend (claude/codex/opencode) |
| `model` | `Option<String>` | Selected model identifier |
| `opencode_port` | `Option<u16>` | OpenCode server port |
| `claude_session_id` | `Option<String>` | Claude session identifier |
| `codex_session_id` | `Option<String>` | Codex session identifier |
| `codex_send_in_flight` | `bool` | Request in-flight flag |

资料来源：[apps/aidocs-dashboard/src-tauri/src/main.rs:1-50](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src-tauri/src/main.rs)

## Lanes System

Lanes are the fundamental execution unit in the orchestration system. Each lane represents an isolated task pipeline that can run independently or with dependencies on other lanes.

### Lane States

| State | Description |
|-------|-------------|
| `runnable` | Lane can execute immediately |
| `blocked` | Lane waiting on dependencies or conditions |
| `running` | Lane actively executing |
| `completed` | Lane finished successfully |
| `failed` | Lane encountered an error |

### Blocking Reasons

Lanes can be blocked by:

- Unmet dependency lanes
- Resource constraints
- Security policy gates
- External input waiting

资料来源：[apps/aidocs-dashboard/src/ConductorPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/ConductorPage.tsx)

## Dashboard Integration

### ConductorPage

The `ConductorPage` component provides the main dashboard interface for conductor operations.

```typescript
interface ConductorPageProps {
  progressPercent: number;
  conductorLanes: Lane[];
  runnableLaneIds: string[];
  blockedReasons: Record<string, string[]>;
  recentExecution: ExecutionEvent[];
  configEntries: ConfigEntry[];
  selectedSessionId: string;
  projectRoot: string;
  sessionId: string;
}
```

**Components:**

| Component | Purpose |
|-----------|---------|
| `Lanes Panel` | Visual display of lane states and progress |
| `ConductorChat` | Real-time chat interface with conductor |
| `ToolCallsPanel` | View recent tool execution events |
| `ConductorSummary` | Progress statistics |

### ConductorChat

The chat interface supports multiple message recipients:

| Recipient | Description |
|-----------|-------------|
| `conductor` | Direct to primary conductor |
| `co-conductor` | Direct to co-conductor assistant |
| `both` | Broadcast to both conductors |

Message roles displayed:

| Role | Color | Usage |
|------|-------|-------|
| `king` | `#f5c518` | High-priority directive |
| `conductor` | `var(--accent-bright)` | Standard conductor messages |
| `co-conductor` | `#78aaff` | Co-conductor responses |

资料来源：[apps/aidocs-dashboard/src/ConductorPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/ConductorPage.tsx)

## Multi-Backend Routing

The orchestration system supports routing to different AI backends:

### Supported Backends

| Backend | Configuration Key | Model Key |
|---------|-------------------|-----------|
| Claude | `conductor.backend` | `conductor.claude_model` |
| Codex | `conductor.backend` | `conductor.codex_model` |
| OpenCode | `conductor.backend` | N/A (uses port) |

### Routing Configuration

```typescript
interface RouteConfig {
  backend: "claude" | "codex" | "opencode";
  models: {
    claude: string;
    codex: string;
    opencode: string;
  };
}
```

### Backend Selection Logic

1. Check `conductor.backend` config for default
2. Evaluate task requirements
3. Consider model capabilities
4. Apply routing policies

## Execution Events

Execution events track all conductor activity:

### Event Structure

```typescript
interface ExecutionEvent {
  event_id: string;
  event_kind: string;
  capability_name?: string;
  action_kind?: string;
  session_id: string;
  observed_at: string;
  lane?: string;
  audit?: {
    logicalMode?: string;
    nativeMode?: string;
    fallbackUsed?: boolean;
  };
  payload?: {
    args_preview?: string;
    result_preview?: string;
    result_summary?: string;
  };
}
```

### Audit Trail

| Mode | Description |
|------|-------------|
| `logicalMode` | Logical routing layer used |
| `nativeMode` | Native tool selection |
| `fallbackUsed` | Whether fallback was triggered |

资料来源：[apps/aidocs-dashboard/src/ExecutionPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/ExecutionPage.tsx)

## Workflow

```mermaid
sequenceDiagram
    participant User
    participant Dashboard
    participant Conductor
    participant PlanConductor
    participant CoConductor
    participant AgentOrchestrator
    participant Backend

    User->>Dashboard: Send message/goal
    Dashboard->>Conductor: route_prompt(goal)
    Conductor->>PlanConductor: create_plan(goal)
    PlanConductor-->>Conductor: lanes[], dependencies[]
    Conductor->>CoConductor: validate_plan(lanes)
    CoConductor-->>Conductor: validation_result
    
    loop For each runnable lane
        Conductor->>AgentOrchestrator: execute_lane(lane)
        AgentOrchestrator->>Backend: dispatch(task)
        Backend-->>AgentOrchestrator: result
        AgentOrchestrator-->>Conductor: lane_status
    end
    
    Conductor-->>Dashboard: progress_update
    Dashboard->>User: Display results
```

## Message Flow

Messages flow through the system with role-based routing:

```mermaid
graph LR
    subgraph "Dashboard"
        CH[ConductorChat]
    end
    
    subgraph "Backend"
        CCM[ConductorComms]
        PC[PlanConductor]
        CC[CoConductor]
    end
    
    CH-->|Message| CCM
    CCM-->|Route| PC
    CCM-->|Route| CC
    
    PC-->|Plan| CCM
    CC-->|Response| CCM
    CCM-->|Aggregated| CH
```

## Configuration

### Conductor Settings

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `conductor.backend` | string | `claude` | Default execution backend |
| `conductor.claude_model` | string | - | Claude model identifier |
| `conductor.codex_model` | string | - | Codex model identifier |

### Lane Configuration

Lanes are configured via the plan conductor with:

- **Dependencies**: Ordered constraint list
- **Blocking conditions**: Runtime predicates
- **Resource requirements**: CPU, memory, tool access
- **Timeout settings**: Per-lane execution limits

## Best Practices

### Session Management

1. **Use persistent sessions** - Resume work instead of restarting
2. **Monitor lane states** - Watch for blocking conditions
3. **Review execution events** - Track capability usage

### Error Handling

1. **Check blocked reasons** - First step in debugging stuck lanes
2. **Review fallback usage** - Indicates routing issues
3. **Examine audit trails** - Understand routing decisions

### Security

- Security gates apply to all conductor operations
- Lane isolation prevents cross-task contamination
- RBAC controls conductor access

资料来源：[apps/aidocs-dashboard/src/RBACPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RBACPage.tsx)

---

<a id='security-gates'></a>

## Security & Access Control

### 相关页面

相关主题：[MCP Server Architecture](#mcp-server), [Conductor & Orchestration](#conductor-orchestration), [Configuration Management](#configuration)

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

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

- [mcp/server/aidocs_mcp/access_gate.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/access_gate.py)
- [mcp/server/aidocs_mcp/heuristic_judge.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/heuristic_judge.py)
- [mcp/server/aidocs_mcp/output_guard.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/output_guard.py)
- [mcp/server/aidocs_mcp/rbac.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/rbac.py)
- [mcp/server/aidocs_mcp/enforcement_pkg/controller.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/enforcement_pkg/controller.py)
- [mcp/server/aidocs_mcp/tool_policy.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/tool_policy.py)
- [mcp/server/aidocs_mcp/permission_catalog.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/permission_catalog.py)
</details>

# Security & Access Control

AIDOCS implements a layered security architecture designed to govern AI agent behavior within development environments. The system provides fine-grained control over tool usage, bash command execution, prompt integrity, and permission escalation through multiple enforcement mechanisms working in concert.

## Overview

The Security & Access Control subsystem in AIDOCS operates as a multi-stage guard system that intercepts and evaluates agent requests before they reach system resources. It combines heuristic analysis, role-based access control (RBAC), tool policy enforcement, and output sanitization to create a defense-in-depth approach for AI-assisted development.

### Core Security Components

| Component | File | Primary Responsibility |
|-----------|------|------------------------|
| Access Gate | `access_gate.py` | Central entry point for permission checks |
| Heuristic Judge | `heuristic_judge.py` | Risk scoring based on request patterns |
| Output Guard | `output_guard.py` | Content filtering and redaction |
| RBAC Engine | `rbac.py` | Role and permission management |
| Enforcement Controller | `controller.py` | Orchestrates policy enforcement |
| Tool Policy | `tool_policy.py` | Bash command allowlist/denylist |
| Permission Catalog | `permission_catalog.py` | Defines available permissions |

## Architecture

```mermaid
graph TD
    A[Agent Request] --> B[Access Gate]
    B --> C{Security Enabled?}
    C -->|No| Z[Allow]
    C -->|Yes| D[Heuristic Judge]
    D --> E{Risk Score}
    E -->|Low| F[RBAC Check]
    E -->|Medium| G[Gate Permission Required]
    E -->|High| H[Block]
    F --> I{Has Permission?}
    I -->|Yes| J[Tool Policy Check]
    I -->|No| H
    J --> K{Command Allowed?}
    K -->|Yes| L[Execute]
    K -->|No| H
    G --> M[Request Approval]
    M -->|Approved| L
    M -->|Denied| H
    L --> N[Output Guard]
    N --> O[Filtered Response]
```

## Access Gate

The Access Gate serves as the central authorization checkpoint for all agent requests. It evaluates incoming requests against the current security posture and determines whether additional verification is needed.

### Configuration Paths

The system exposes security settings through configurable paths that control different aspects of enforcement:

| Setting Path | Purpose | Risk Level |
|--------------|---------|------------|
| `dev.dev_mode` | Enables editing of AIDOCS MCP server source files | High |
| `security.allow_config_edit` | Allows agents to modify AIDOCS config via tool calls | High |
| `security.enforce` | Master toggle for tool gates and policy enforcement | Critical |

资料来源：[apps/aidocs-dashboard/src/dashboardModals.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/dashboardModals.tsx)

### Security Toggle Behavior

When `security.enforce` is disabled, the following protections are removed:
- Bash allowlist enforcement
- Raw tool blocking
- Destructive command protection

Agents gain the ability to use any tool freely when enforcement is disabled. This setting should only be modified with explicit user confirmation through the security change confirmation modal.

资料来源：[apps/aidocs-dashboard/src/dashboardModals.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/dashboardModals.tsx)

## Heuristic Judge

The Heuristic Judge performs real-time risk assessment on agent requests by analyzing patterns and content characteristics. It assigns risk scores that determine the level of scrutiny a request receives.

### Risk Categories

The system categorizes risks into several domains:

| Category | Description | Examples |
|----------|-------------|----------|
| `supply_chain` | Package installation and remote code execution | `npm install`, `npx`, `uvx` |
| `capability` | Declared capabilities indicating system access | File operations, command execution |
| `vulnerability` | Code patterns that may indicate security issues | `eval()`, `__import__`, `os.system` |

资料来源：[mcp/server/aidocs_mcp/skill_scanner.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/skill_scanner.py)

### Risk Severity Levels

| Severity | Interpretation | Action |
|----------|----------------|--------|
| `critical` | Highly dangerous operation | Immediate blocking or strict gate |
| `high` | Significant risk requiring scrutiny | Gate permission or enhanced monitoring |
| `medium` | Moderate risk | Standard RBAC check |
| `low` | Minor concern | Allow with logging |

## Output Guard

The Output Guard monitors and sanitizes content flowing from agent responses. It detects potential security issues including prompt injection attempts and sensitive data leakage.

### Prompt Injection Detection

The system recognizes multiple categories of prompt injection patterns:

```python
_PROMPT_INJECTION_PATTERNS = [
    ("system_override", "ignore/forget previous instructions"),
    ("role_hijack", "you are now a different AI"),
    ("instruction_inject", "XML tag instruction injection"),
    ("delimiter_escape", "code block instruction injection"),
    ("hidden_instruction", "URGENT: ignore/override"),
]
```

资料来源：[mcp/server/aidocs_mcp/output_guard.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/output_guard.py)

### Sensitive Content Detection

| Pattern | Description |
|---------|-------------|
| `env_file_content` | Environment variables with values 8+ characters |
| `ssh_config` | SSH configuration content |

The Output Guard applies redaction markers in the format `[REDACTED:{category}]` when sensitive content is detected and redaction is enabled.

资料来源：[mcp/server/aidocs_mcp/output_guard.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/output_guard.py)

## Role-Based Access Control (RBAC)

The RBAC system provides granular permission management for agent capabilities. It defines roles, permissions, and escalation paths that govern what actions agents can perform.

### Permission States

Permissions can exist in three states:

| State | Description |
|-------|-------------|
| `system` | Built-in permissions that cannot be modified |
| `custom` | User-defined permissions for specific use cases |

资料来源：[apps/aidocs-dashboard/src/RBACPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RBACPage.tsx)

### RBAC Table Structure

The RBAC page displays permissions in a structured table format:

| Column | Description |
|--------|-------------|
| permission name | Unique identifier for the permission |
| description | Human-readable explanation of the permission |
| state | Whether the permission is system or custom |

资料来源：[apps/aidocs-dashboard/src/RBACPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/RBACPage.tsx)

### Escalation Management

The RBAC system supports permission escalation with the following attributes:

| Attribute | Description |
|-----------|-------------|
| requester | Entity requesting escalation |
| permission | Target permission being escalated |
| phrase | Trigger phrase for automatic escalation |
| session/task | Associated session or task context |
| sticky | Whether escalation persists beyond current session |
| created/expires | Temporal bounds for the escalation |

## Tool Policy

Tool Policy manages bash command execution through an allowlist/denylist mechanism. It provides fine-grained control over shell commands that agents can execute.

### Policy Structure

```mermaid
graph LR
    A[Command] --> B{Policy Check}
    B -->|allow| C[Execute]
    B -->|deny| D[Block]
    B -->|bubble| E[Request Approval]
    B -->|modified| F[Execute with Modification]
```

### Bash Policy Panel

The Dashboard provides a visual interface for managing shell policies:

| Count Type | Description |
|------------|-------------|
| `allowEff` | Effective allow count |
| `denyEff` | Effective deny count |
| `bubbleEff` | Effective bubble (approval required) count |
| `modifiedAtActive` | Number of rules modified at active layer |

资料来源：[apps/aidocs-dashboard/src/BashPolicyPanel.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/BashPolicyPanel.tsx)

### Policy Layer System

Bash policies support layered configuration with the following characteristics:
- Policies can be defined at different layers
- Active layer determines which policy configuration is currently in effect
- Changes made at the active layer are tracked separately
- Fallback default behavior is configurable

## Enforcement Controller

The Enforcement Controller orchestrates all security mechanisms and ensures consistent policy application across the system.

### Enforcement Actions

| Action | Trigger | Result |
|--------|---------|--------|
| Allow | All checks pass | Execute requested operation |
| Block | Any check fails | Deny operation, log reason |
| Bubble | Medium risk detected | Request user approval |
| Redact | Sensitive content in output | Replace with redaction marker |

### Live Monitoring

The Live Page in the Dashboard provides real-time visibility into enforcement events:

```mermaid
graph TD
    A[Agent Request] --> B[Gate Permission Check]
    B --> C{Permission Status}
    C -->|Required| D[Display in UI]
    C -->|Approved| E[Continue Execution]
    C -->|Rejected| F[Block and Log]
    D --> G{User Action}
    G -->|Approve| E
    G -->|Reject| F
```

The gate permission requests appear in the Live Page with:
- Permission name being requested
- Requester label
- Approve/Reject buttons for user response

资料来源：[apps/aidocs-dashboard/src/LivePage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/LivePage.tsx)

## Quick Actions

The Dashboard provides administrative quick actions for security management:

| Action | Description |
|--------|-------------|
| Stop All Lanes | Terminates all active agent sessions |
| Deactivate AIDOCS | Toggles security posture (not a runtime stop) |

资料来源：[apps/aidocs-dashboard/src/LivePage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/LivePage.tsx)

## Statistics Dashboard

The Live Page includes a stat tile strip showing real-time security metrics:

| Metric | Description |
|--------|-------------|
| Events (last 1h) | Total security events in the past hour |
| Tool Calls | Number of tool invocation attempts |
| Blocked | Count of blocked operations |
| Failed | Count of failed operations |
| Tokens (in/out) | Token consumption for audit purposes |

Blocked and Failed counts display with danger tone styling when greater than zero, providing immediate visual feedback for security administrators.

## Configuration Management

### Setting Origin Tracking

Individual settings can be traced to their origin layer through the Setting Detail Panel:

```mermaid
graph TD
    A[Setting Path] --> B{Origin Count}
    B -->|Single| C[Display Source Layer]
    B -->|Multiple| D[Per-Leaf Origin Table]
    D --> E[List of Leaf Paths]
    D --> F[Layer per Leaf]
```

Settings with multiple origins display a collapsible table showing which layer each configuration leaf originated from.

资料来源：[apps/aidocs-dashboard/src/SettingDetailPanel.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SettingDetailPanel.tsx)

### Layer Tone Indicators

| Layer Type | Visual Tone |
|------------|-------------|
| Default | Standard styling |
| Active | Highlighted indicator |
| Modified | Distinct color for changed values |

## Connection Status

The Castle Shell status bar displays MCP connection state:

| State | Indicator | Meaning |
|-------|-----------|---------|
| Connected | Green dot + "MCP connected" | Security enforcement active |
| Disconnected | Red dot + "MCP disconnected" | Fallback mode or misconfiguration |

资料来源：[apps/aidocs-dashboard/src/CastleShell.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/CastleShell.tsx)

## Security Workflow Summary

```mermaid
graph LR
    A[Request] --> B{Dev Mode?}
    B -->|Yes| C[Additional Access]
    B -->|No| D{Normal Checks}
    D --> E{Security Enforce?}
    E -->|No| F[Minimal Security]
    E -->|Yes| G[Full Enforcement]
    G --> H[Heuristic Analysis]
    H --> I{Risk Level}
    I -->|Low| J[RBAC]
    I -->|Medium| K[Gate Permission]
    I -->|High| L[Block]
    J --> M{Has Permission?}
    M -->|Yes| N[Tool Policy]
    M -->|No| L
    N --> O{Allowed?}
    O -->|Yes| P[Execute + Output Guard]
    O -->|No| L
    K --> Q{Approved?}
    Q -->|Yes| P
    Q -->|No| L
```

## Summary

AIDOCS Security & Access Control provides comprehensive protection for AI-assisted development through:

1. **Centralized Access Gate** - Single entry point for all authorization decisions
2. **Heuristic Analysis** - Automated risk scoring based on request patterns
3. **RBAC Engine** - Fine-grained permission management with escalation support
4. **Tool Policy** - Command allowlisting with layered configuration
5. **Output Guard** - Prompt injection detection and sensitive data redaction
6. **Real-time Monitoring** - Dashboard visibility into security events and statistics

The system is designed with defense-in-depth principles, ensuring that multiple independent checks must pass before potentially risky operations are executed.

---

<a id='indexing-retrieval'></a>

## Indexing & Retrieval System

### 相关页面

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

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

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

- [mcp/server/aidocs_mcp/code_index_store.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/code_index_store.py)
- [mcp/server/aidocs_mcp/code_index_symbol_search_service.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/code_index_symbol_search_service.py)
- [mcp/server/aidocs_mcp/semantic_search.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/semantic_search.py)
- [mcp/server/aidocs_mcp/index_store.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/index_store.py)
- [mcp/server/aidocs_mcp/outline_extractors/__init__.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/outline_extractors/__init__.py)
</details>

# Indexing & Retrieval System

## Overview

The Indexing & Retrieval System is the core backbone of AIDOCS, enabling AI coding agents to efficiently locate, analyze, and retrieve code symbols, semantic concepts, and structural information across a codebase. It transforms a raw repository into a queryable, memory-augmented context that allows agents to resume work without re-discovering the codebase on every session.

The system operates as a layered pipeline that:

1. **Discovers** code files based on language descriptors
2. **Parses** files to extract symbols, outlines, and semantic metadata
3. **Indexes** extracted data into structured storage
4. **Serves** retrieval queries through MCP tools (`ai_find`, `ai_bundle`, `ai_investigate`, `ai_trace`)

This architecture is designed for persistent memory across sessions, fast targeted lookups, and multi-language support with configurable heuristics.

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

## Architecture Overview

```mermaid
graph TD
    A[Codebase Files] --> B[Language Descriptors]
    B --> C[File Discovery]
    C --> D[Outline Extractors]
    D --> E[Symbol Parsers]
    E --> F[Index Storage Layer]
    F --> G[index_store.py]
    F --> H[code_index_store.py]
    G --> I[Retrieval Query Pipeline]
    H --> I
    I --> J[semantic_search.py]
    J --> K[code_index_symbol_search_service.py]
    K --> L[MCP Tools: ai_find, ai_bundle, ai_investigate]
```

## Language Descriptor System

### Purpose

Language descriptors inform the indexer which files belong to a project, what support tier applies, and what heuristic semantics influence indexing behavior. They act as the discovery and classification layer for the entire indexing pipeline.

资料来源：[mcp/INDEX_LANGUAGE_DESCRIPTORS.md]()

### Descriptor Locations

| Location | Path | Purpose |
|----------|------|---------|
| Built-in | `mcp/server/aidocs_mcp/index_languages/` | Ships with AIDOCS |
| Project-local | `<project-root>/index_languages/*.toml` | Extends or overrides built-in |

Project-local descriptors can extend or override built-in behavior, allowing teams to define custom language support or refine heuristics for their specific codebase.

资料来源：[mcp/INDEX_LANGUAGE_DESCRIPTORS.md]()

### Supported Keys

**Discovery Keys** (at least one required):

- `extensions` — file extensions (e.g., `.py`, `.ts`)
- `suffixes` — alternative naming patterns
- `include_globs` — glob patterns for discovery

**Core Keys**:

| Key | Type | Description |
|-----|------|-------------|
| `name` | string | Language identifier |
| `tier` | string | Support tier: `full`, `heuristic`, `minimal` |
| `extensions` | list | File extensions |
| `suffixes` | list | Alternative file suffixes |
| `include_globs` | list | Glob patterns |

**Semantics Keys** (influence indexing behavior):

| Key | Description |
|-----|-------------|
| `semantic_tags` | Tags for semantic classification |
| `outline_family` | Family name for outline patterns |
| `outline_patterns` | Patterns for structural extraction |
| `role_hint` | Default role hint (e.g., `analysis-script`) |
| `role_patterns` | Patterns to detect role classifications |
| `module_hints` | Directory names that hint at modules |

资料来源：[mcp/INDEX_LANGUAGE_DESCRIPTORS.md]()
资料来源：[mcp/server/aidocs_mcp/language_descriptors.py]()

### Loading Descriptors

Descriptors are loaded through `load_language_descriptors()` which implements a caching strategy:

```mermaid
graph TD
    A[load_language_descriptors] --> B{Cache Hit?}
    B -->|Yes, schema version match| C[Return cached]
    B -->|No| D[Compute fingerprint]
    D --> E{Fingerprint match?}
    E -->|Yes| F[Return cached]
    E -->|No| G[Scan descriptor directories]
    G --> H[Load TOML files]
    H --> I[Filter by enabled languages]
    I --> J[Return descriptors]
```

The function checks the schema version first, then compares file fingerprints to avoid unnecessary I/O. Only descriptors matching the enabled language set are loaded.

资料来源：[mcp/server/aidocs_mcp/language_descriptors.py]()

## Outline Extraction

### Role of Outline Extractors

Outline extractors parse source files to identify structural elements—classes, functions, methods, interfaces, and other symbols—and produce a lightweight outline representation. This is the primary mechanism for symbol discovery during indexing.

资料来源：[mcp/server/aidocs_mcp/outline_extractors/__init__.py]()

### Architecture

The outline extractor system uses a modular design with language-specific implementations. Each extractor conforms to a common interface that:

1. Accepts a file path and content
2. Returns structured symbol data with line numbers, kinds, and containers
3. Handles language-specific parsing nuances

The `__init__.py` module exports the extractor registry and common data structures used across all language extractors.

资料来源：[mcp/server/aidocs_mcp/outline_extractors/__init__.py]()

## Index Storage Layer

### Two-Store Architecture

The indexing system maintains two complementary storage mechanisms:

```mermaid
graph LR
    A[index_store.py] --> B[General Index]
    A --> C[File-level metadata]
    A --> D[Language classification]
    E[code_index_store.py] --> F[Symbol Index]
    E --> G[Symbol definitions]
    E --> H[Reference mappings]
    E --> I[Container relationships]
```

**index_store.py** handles:

- File-level metadata and indexing state
- Language classification per file
- Index-wide configuration and statistics

**code_index_store.py** handles:

- Symbol definitions extracted from source
- Reference relationships between symbols
- Container hierarchies (e.g., class → method relationships)

资料来源：[mcp/server/aidocs_mcp/index_store.py]()
资料来源：[mcp/server/aidocs_mcp/code_index_store.py]()

### Symbol Index Structure

The symbol index maintains structured records for each extracted symbol:

| Field | Description |
|-------|-------------|
| `symbol` | Symbol name |
| `kind` | Type (function, class, method, interface, etc.) |
| `path` | File path |
| `line_number` | Definition line |
| `container` | Parent symbol (class containing method, etc.) |
| `language` | Source language |
| `is_partial` | Partial definition flag (for C#, etc.) |

This structure enables efficient filtering by kind, container, and location during retrieval queries.

资料来源：[mcp/server/METHODS.md]()

## Retrieval Services

### Semantic Search

`semantic_search.py` implements concept-level search capabilities that go beyond exact symbol matching. It enables:

- **Concept queries** — searching by semantic meaning rather than exact names
- **Fuzzy matching** — handling typos and partial matches
- **Ranking** — scoring results by relevance

The semantic search layer bridges the gap between natural language queries and structured symbol data, enabling agents to find code using descriptive terms.

资料来源：[mcp/server/aidocs_mcp/semantic_search.py]()

### Symbol Search Service

`code_index_symbol_search_service.py` provides the core symbol-level search functionality:

- **Symbol lookup** — find symbols by exact or partial name match
- **Reference tracing** — locate all usages of a symbol
- **Kind filtering** — search within specific symbol types
- **Scope resolution** — navigate symbol containers

This service is the primary engine behind the `ai_find` MCP tool, which supports multiple search modes:

| Mode | Purpose |
|------|---------|
| `symbols` | Find symbol definitions |
| `references` | Find symbol usages |
| `mutations` | Find code modifying a concept |
| `validation` | Find validation logic |
| `policy` | Find policy enforcement points |

资料来源：[mcp/server/aidocs_mcp/code_index_symbol_search_service.py]()
资料来源：[mcp/server/aidocs_mcp/claude_hook.py]()

## MCP Tool Interface

### Core Retrieval Tools

The indexing system exposes retrieval capabilities through these MCP tools:

**ai_find** — Unified symbol and reference search across indexed code.

**ai_investigate** — Broad concept investigation with ranked results across layers.

**ai_bundle** — Retrieve comprehensive context for a file, path, or concept.

**ai_trace** — Cross-layer relationship tracing for fields, settings, or services.

**ai_get_symbol_snippet** — Retrieve exact symbol body with container context.

**ai_get_symbol_info** — Retrieve symbol metadata (signature, constructor, enum, API).

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

### Read Pipeline

Line-based reading flows through a shared read pipeline with strict mode enforcement:

```mermaid
graph TD
    A[ai_get_lines] --> B[gate: strict mode]
    B --> C{Path valid?}
    C -->|No| D[Refusal]
    C -->|Yes| E[Check managed mode]
    E --> F[indexed_read_block]
    F --> G[Return lines]
```

Strict mode enforces:
- No absolute path inputs
- No `..` traversal
- Zone restrictions (PROJECT_INTERNAL, MEMORY_INTERNAL only)

资料来源：[mcp/server/aidocs_mcp/server_code_edit_tools.py]()

## Configuration Options

### Index Settings

Configuration options in `config_schema.py` control indexing behavior:

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `index.max_file_size` | integer | 100_000 | Max file size in bytes |
| `index.max_json_size` | integer | 100_000 | Max JSON file size |
| `index.enabled_languages` | string | "all" | Language set for filtering |
| `index.include_tests` | boolean | false | Include test directories |
| `index.extra_module_hints` | string_list | [] | Extra module directory names |
| `languages.enabled` | string | "all" | Loaded language descriptors |

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `tools.sync_functions_timeout` | integer | 60 | Timeout for sync/indexer operations |
| `tools.tool_call_timeout` | integer | 10 | Default tool call timeout |

资料来源：[mcp/server/aidocs_mcp/config_schema.py]()

## Layer Inference

The retrieval system infers architectural layers for search results, enabling context-aware queries:

| Layer | Description |
|-------|-------------|
| `data` | Data access, models, DTOs |
| `logic` | Business logic, services |
| `api` | API endpoints, controllers |
| `ui` | User interface components |
| `code` | General code files |

Layer inference helps agents understand where discovered code fits in the system architecture and find code at appropriate abstraction levels.

资料来源：[mcp/server/METHODS.md]()

## Session Persistence

The indexing system supports persistent sessions that maintain index state across agent invocations:

- **Session-based indexing** — indexes can be tied to session IDs
- **Project sync** — `project_sync_indexes` keeps indexes current with codebase
- **Managed mode** — enforces controlled editing with session tracking

This persistence enables the "resume work instead of rediscovering" core value proposition of AIDOCS.

资料来源：[mcp/README.md]()
资料来源：[mcp/server/aidocs_mcp/claude_hook.py]()

## Workflow Summary

```mermaid
graph LR
    A[Initialize Project] --> B[Load Language Descriptors]
    B --> C[Discover Files]
    C --> D[Extract Outlines]
    D --> E[Parse Symbols]
    E --> F[Store in Index]
    F --> G[Ready for Retrieval]
    G --> H[ai_find / ai_investigate]
    G --> I[ai_bundle / ai_trace]
    H --> J[Symbol Search Service]
    I --> K[Semantic Search]
    J --> L[Agent Context]
    K --> L
```

## Related Documentation

- [METHODS.md](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/METHODS.md) — Complete MCP tool reference
- [INDEX_LANGUAGE_DESCRIPTORS.md](https://github.com/cristian1991/AIDOCS/blob/main/mcp/INDEX_LANGUAGE_DESCRIPTORS.md) — Language descriptor specification
- [config_schema.py](https://github.com/cristian1991/AIDOCS/blob/main/mcp/server/aidocs_mcp/config_schema.py) — Configuration reference

---

<a id='configuration'></a>

## Configuration Management

### 相关页面

相关主题：[System Architecture Overview](#architecture-overview), [Security & Access Control](#security-gates)

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

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

- [README.md](https://github.com/cristian1991/AIDOCS/blob/main/README.md)
- [apps/aidocs-dashboard/src/SetupWizardPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/SetupWizardPage.tsx)
- [apps/aidocs-dashboard/src/TomlConfigsPage.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/TomlConfigsPage.tsx)
- [apps/aidocs-dashboard/src/BashPolicyPanel.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/BashPolicyPanel.tsx)
- [apps/aidocs-dashboard/src/dashboardModals.tsx](https://github.com/cristian1991/AIDOCS/blob/main/apps/aidocs-dashboard/src/dashboardModals.tsx)
</details>

# Configuration Management

## Overview

AIDOCS provides a layered, hierarchical configuration system that enables persistent memory, indexed retrieval, and orchestration for AI coding agents. The configuration architecture supports multiple levels of override, from system defaults down to per-project and per-session settings.

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

## Configuration Architecture

AIDOCS uses a **layered configuration model** where settings cascade from base defaults through environment-specific overrides to project-specific customizations.

```mermaid
graph TD
    A[System Defaults] --> B[Environment Variables]
    B --> C[aidocs.toml Base]
    C --> D[Project .aidocs/]
    D --> E[Session Overrides]
    E --> F[Runtime Resolution]
    
    A -->|Low Priority| F
    E -->|High Priority| F
```

### Configuration Files

| File | Location | Purpose | Format |
|------|----------|---------|--------|
| `aidocs.toml` | Project root | Runtime configuration with static definitions | TOML |
| `hooks.json` | `core/hooks/` | Hook definitions for event-driven behavior | JSON |
| Action Tokens | `action_tokens/` | Prompt-classification language files | YAML |
| Language Descriptors | `index_languages/` | Per-language configuration | TOML |
| Gate Messages | `gate_messages/` | Action hooks and permission definitions | TOML |

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

## Core Configuration: aidocs.toml

The primary runtime configuration file defines system-wide and per-project settings.

### Configuration Sections

```toml
# aidocs.toml structure (conceptual)
[dev]
dev_mode = false  # Enable editing MCP server source files

[security]
allow_config_edit = false  # Allow agents to modify config via tool calls
enforce = true  # Enable tool gates and bash allowlist

[memory]
# Memory and indexing settings
retention_days = 30
index_on_startup = true

[mcp]
# MCP server connection settings
transport = "stdio"
command = "aidocs-mcp"
```

### Security Configuration

The security section controls agent capabilities and tool access:

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `security.allow_config_edit` | boolean | `false` | Allows agents to modify AIDOCS config via tool calls |
| `security.enforce` | boolean | `true` | Enables tool gates, bash allowlist, and destructive command protection |
| `dev.dev_mode` | boolean | `false` | Enables editing of MCP server source files |

资料来源：[apps/aidocs-dashboard/src/dashboardModals.tsx](), [apps/aidocs-dashboard/src/TomlConfigsPage.tsx]()

**Warning Messages for Security Changes:**

```typescript
// From dashboardModals.tsx
{settingPath === "dev.dev_mode" && "Enables editing AIDOCS MCP server source files. Only use when actively developing AIDOCS."}
{settingPath === "security.allow_config_edit" && "Allows agents to modify AIDOCS config via tool calls. The agent can change gate settings, conductor config, and other project settings."}
{settingPath === "security.enforce" && "Disabling tool gates removes bash allowlist, raw tool blocking, and destructive command protection. Agents can use any tool freely."}
```

## Shell Policy Configuration

The bash policy system provides fine-grained control over shell command execution with a three-tier decision model.

### Policy Actions

| Action | Description |
|--------|-------------|
| `allow` | Command is permitted to execute |
| `deny` | Command is blocked regardless of context |
| `bubble` | Command requires explicit user approval |

### Policy Display

The dashboard visualizes policy counts per layer:

```typescript
<span className="bash-policy-count bash-policy-count-allow">{counts.allowEff} allow</span>
<span className="bash-policy-count bash-policy-count-deny">{counts.denyEff} deny</span>
<span className="bash-policy-count bash-policy-count-bubble">{counts.bubbleEff} bubble</span>
<span className="bash-policy-count bash-policy-count-mod">{counts.modifiedAtActive} set at {activeLayer}</span>
```

资料来源：[apps/aidocs-dashboard/src/BashPolicyPanel.tsx]()

### Filter Controls

Policy entries can be filtered using the search and category chips:

```typescript
const filters = ["all", "allow", "deny", "bubble", "modified"] as const;
```

| Filter | Function |
|--------|----------|
| `all` | Show all policy entries |
| `allow` | Show only allowed commands |
| `deny` | Show only denied commands |
| `bubble` | Show only commands requiring approval |
| `modified` | Show only modified entries |

## Action Tokens (Prompt Classification)

Action Tokens are YAML-based language files that define how user prompts are classified and routed.

### Structure

```yaml
# action_tokens/en.yaml (conceptual structure)
intent_tokens:
  - name: "implement"
    pattern: "implement|create|build|add"
    action: "code_generation"
    
  - name: "investigate"
    pattern: "investigate|analyze|trace"
    action: "code_analysis"
```

### Configuration Categories

The TOML configuration page in the dashboard provides tabs for different configuration domains:

| Tab | Purpose |
|-----|---------|
| Action Tokens | Prompt-classification language files (en, it, ...) |
| Action Hooks | Gate messages and hook definitions |
| Language Descriptors | Per-language configuration specifications |

资料来源：[apps/aidocs-dashboard/src/TomlConfigsPage.tsx](), [mcp/README.md]()

## Setup Wizard Configuration Flow

The setup wizard guides users through initial project configuration:

```mermaid
graph TD
    A[Welcome] --> B[Project Selection]
    B --> C[Environment Detection]
    C --> D[Configuration]
    D --> E[Done]
    
    B -->|Select folder| B
    C -->|Missing deps| F[Install Dependencies]
    F --> C
```

### Setup Steps

| Step | Description |
|------|-------------|
| `welcome` | Introduction and feature overview |
| `project` | Project folder selection |
| `detect` | Environment and tool detection |
| `configure` | MCP, hooks, and project structure setup |
| `done` | Configuration summary and next steps |

### Configuration Results

After setup, the wizard displays:

```typescript
<div className="setup-checklist">
  <div className="setup-check pass">
    <span>MCP configured</span>
    <span>{configResult.mcp_path}</span>
  </div>
  <div className="setup-check pass">
    <span>Hooks registered</span>
    <span>{configResult.hooks_path}</span>
  </div>
  <div className="setup-check pass">
    <span>Project initialized</span>
  </div>
</div>
```

资料来源：[apps/aidocs-dashboard/src/SetupWizardPage.tsx]()

### Environment Detection

The wizard detects installed tools and authentication status:

| Component | Detection |
|-----------|-----------|
| Node.js | Check for CLI agent support |
| Claude | Check for `claude.ai` authentication |
| OpenAI | Check for API key configuration |

```typescript
{/* Sign-in button for detected but unauthenticated hosts */}
{h.authenticated === false && (
  <button onClick={() => {
    const url = h.name.includes("Claude") ? "https://claude.ai" : "https://platform.openai.com/api-keys";
    invoke("open_url", { url });
  }}>Sign in</button>
)}
```

## Configuration Resolution

Settings follow a precedence hierarchy where higher layers override lower ones:

```mermaid
graph LR
    A[Base Defaults] --> B[Project Config]
    B --> C[Session State]
    C --> D[Runtime Values]
    
    style A fill:#e1e1e1
    style D fill:#90EE90
```

### Layer Model

| Layer | Scope | Override Priority |
|-------|-------|-------------------|
| System Defaults | Global | 1 (lowest) |
| Environment Variables | Process-level | 2 |
| `aidocs.toml` | Project root | 3 |
| `.aidocs/` directory | Project-specific | 4 |
| Session State | Per-session runtime | 5 (highest) |

## TOML Document Management

The dashboard provides a unified interface for managing TOML configuration documents:

```typescript
// Document filtering by category
const categoryPrefix = "mcp/server/aidocs_mcp/index_languages/";
const filteredDocuments = tomlDocuments.filter((d) => d.path.startsWith(categoryPrefix));
```

### Document Table Columns

| Column | Description |
|--------|-------------|
| Target | Configuration target identifier |
| Active | Whether the config is currently active |
| Context | Brief description of the configuration scope |

## Command-Line Configuration

AIDOCS provides CLI commands for configuration management:

```bash
aidocs setup                  # Configures MCP, hooks, and project init
aidocs doctor                 # Verifies installation and configuration
```

| Command | Function |
|---------|----------|
| `aidocs setup` | Run the setup wizard to configure everything |
| `aidocs doctor` | Validate the installation and configuration |

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

## Summary

The AIDOCS configuration management system provides:

1. **Hierarchical Override**: Settings cascade from system defaults through project-specific configurations
2. **Security Controls**: Fine-grained control over agent capabilities and tool access
3. **Shell Policy**: Three-tier command execution model (allow/deny/bubble)
4. **Language Support**: Extensible action token system for prompt classification
5. **Dashboard Integration**: Visual configuration management through the Tauri-based dashboard
6. **CLI Tools**: Command-line utilities for setup and validation

All configuration is designed to support the core goal of giving AI coding agents **persistent memory, indexed retrieval, and orchestration** while maintaining security and operational safety.

---

---

## Doramagic Pitfall Log

Project: cristian1991/AIDOCS

Summary: Found 9 potential pitfall items; 0 are high/blocking. Highest priority: configuration - 可能修改宿主 AI 配置.

## 1. configuration · 可能修改宿主 AI 配置

- Severity: medium
- Evidence strength: source_linked
- Finding: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- User impact: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- Suggested check: 列出会写入的配置文件、目录和卸载/回滚步骤。
- Guardrail action: 涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- Evidence: capability.host_targets | github_repo:1153124183 | https://github.com/cristian1991/AIDOCS | host_targets=mcp_host, claude, claude_code, cursor

## 2. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | github_repo:1153124183 | https://github.com/cristian1991/AIDOCS | README/documentation is current enough for a first validation pass.

## 3. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | github_repo:1153124183 | https://github.com/cristian1991/AIDOCS | last_activity_observed missing

## 4. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | github_repo:1153124183 | https://github.com/cristian1991/AIDOCS | no_demo; severity=medium

## 5. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | github_repo:1153124183 | https://github.com/cristian1991/AIDOCS | no_demo; severity=medium

## 6. security_permissions · 来源证据：v2.0.0 — Unified AccessGate & Agent Enforcement

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v2.0.0 — Unified AccessGate & Agent Enforcement
- User impact: 可能阻塞安装或首次运行。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_2ef38d1286d44ae9b266a98267a2d782 | https://github.com/cristian1991/AIDOCS/releases/tag/v2.0.0 | 来源类型 github_release 暴露的待验证使用条件。

## 7. security_permissions · 来源证据：v2.0.3 — Token Tracking & Dashboard Fixes

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v2.0.3 — Token Tracking & Dashboard Fixes
- User impact: 可能影响授权、密钥配置或安全边界。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_5428bd20316b4bfa987b009350fc138b | https://github.com/cristian1991/AIDOCS/releases/tag/v2.0.3 | 来源类型 github_release 暴露的待验证使用条件。

## 8. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | github_repo:1153124183 | https://github.com/cristian1991/AIDOCS | issue_or_pr_quality=unknown

## 9. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | github_repo:1153124183 | https://github.com/cristian1991/AIDOCS | release_recency=unknown

<!-- canonical_name: cristian1991/AIDOCS; human_manual_source: deepwiki_human_wiki -->
