# https://github.com/Pimzino/spec-workflow-mcp 项目说明书

生成时间：2026-05-16 13:11:01 UTC

## 目录

- [Getting Started](#getting-started)
- [Project Structure](#project-structure)
- [System Architecture](#architecture)
- [MCP Server Implementation](#mcp-server)
- [Spec Management](#spec-management)
- [Approval Workflow System](#approval-workflow)
- [Steering Documents](#steering-documents)
- [Web Dashboard](#web-dashboard)
- [VSCode Extension](#vscode-extension)
- [Docker Deployment](#docker-deployment)

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

## Getting Started

### 相关页面

相关主题：[System Architecture](#architecture)

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

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

- [README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)
- [src/index.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/index.ts)
- [package.json](https://github.com/Pimzino/spec-workflow-mcp/blob/main/package.json)
- [README.ko.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.ko.md)
- [README.fr.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.fr.md)
- [containers/README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/containers/README.md)
</details>

# Getting Started

A comprehensive guide to setting up and running the Spec-Workflow MCP server for AI-assisted specification-based development workflows.

## Overview

Spec-Workflow MCP is a Model Context Protocol (MCP) server that enables AI coding assistants to work with structured specifications. It provides a systematic approach to development by maintaining specs, tracking tasks, managing approvals, and logging implementation details.

**Key Capabilities:**
- Specification management with version control and approval workflows
- Task tracking and progress monitoring
- Implementation logging for code artifacts
- Integration with multiple AI coding tools (Claude Desktop, Cursor, VSCode, etc.)
- Web dashboard and VSCode extension for visualization

## Prerequisites

Before installation, ensure your environment meets the following requirements:

| Requirement | Version | Notes |
|-------------|---------|-------|
| Node.js | ≥ 18.0.0 | Required for npm execution |
| npm | ≥ 9.0.0 | For package management |
| Git | Any recent version | For version control integration |
| Docker | ≥ 20.10.0 | Optional, for containerized deployment |
| Docker Compose | ≥ 2.0.0 | Optional, for multi-container setups |

资料来源：[README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

## Installation Methods

### Method 1: Quick Setup via npx

The simplest way to get started is using npx, which downloads and executes the package without global installation:

```bash
npx -y @pimzino/spec-workflow-mcp@latest /path/to/your/project
```

**Command Arguments:**
| Argument | Description | Required |
|----------|-------------|----------|
| `/path/to/your/project` | Absolute path to your project directory | Yes |

资料来源：[README.md:1-20](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

### Method 2: Global Installation

For persistent installation across sessions:

```bash
npm install -g @pimzino/spec-workflow-mcp
```

Then execute:
```bash
spec-workflow-mcp /path/to/your/project
```

### Method 3: Docker Deployment

For isolated, containerized deployment:

```bash
# Using Docker Compose (recommended)
cd containers
docker-compose up --build

# Or using Docker CLI
docker build -f containers/Dockerfile -t spec-workflow-mcp .
docker run -p 5000:5000 -v "./workspace/.spec-workflow:/workspace/.spec-workflow:rw" spec-workflow-mcp
```

The dashboard becomes available at: `http://localhost:5000`

资料来源：[README.md:85-95](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

## MCP Server Configuration

After installation, configure the MCP server for your preferred AI coding tool.

### Claude Desktop

Add to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "spec-workflow": {
      "command": "npx",
      "args": ["-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/your/project"]
    }
  }
}
```

> **Important:** Run the dashboard separately with `--dashboard` before starting the MCP server.

资料来源：[README.md:55-70](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

### Claude Code CLI

```bash
claude mcp add spec-workflow npx @pimzino/spec-workflow-mcp@latest -- /path/to/your/project
```

**Windows Alternative:**
```bash
claude mcp add spec-workflow cmd.exe /c "npx @pimzino/spec-workflow-mcp@latest /path/to/your/project"
```

资料来源：[README.md:35-50](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

### Cursor IDE

Add to your Cursor settings (`settings.json`):

```json
{
  "mcpServers": {
    "spec-workflow": {
      "command": "npx",
      "args": ["-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/your/project"]
    }
  }
}
```

### VSCode (Cline/Claude Dev)

```json
{
  "mcpServers": {
    "spec-workflow": {
      "command": "npx",
      "args": ["-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/your/project"]
    }
  }
}
```

### Continue IDE Extension

```json
{
  "mcpServers": {
    "spec-workflow": {
      "command": "npx",
      "args": ["-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/your/project"]
    }
  }
}
```

### Windsurf

Add to `~/.codeium/windsurf/mcp_config.json`:

```json
{
  "mcpServers": {
    "spec-workflow": {
      "command": "npx",
      "args": ["-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/your/project"]
    }
  }
}
```

### Codex

Add to `~/.codex/config.toml`:

```toml
[mcp_servers.spec-workflow]
command = "npx"
args = ["-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/your/project"]
```

### OpenCode

Add to `opencode.json`:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "spec-workflow": {
      "type": "local",
      "command": ["npx", "-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/your/project"],
      "enabled": true
    }
  }
}
```

资料来源：[README.md:100-145](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

## Choosing Your Interface

Spec-Workflow MCP offers two interfaces for interacting with specifications. Choose based on your workflow.

### Option A: Web Dashboard

**Recommended for:** CLI users, team collaboration, remote access

```bash
npx -y @pimzino/spec-workflow-mcp@latest --dashboard
```

Access the dashboard at: `http://localhost:5000`

**Key Features:**
- Real-time task progress visualization
- Specification document management
- Approval workflow interface
- Implementation artifact tracking
- Project statistics dashboard

> **Note:** Only one dashboard instance is needed. All projects connect to the same dashboard.

资料来源：[README.ko.md:20-35](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.ko.md)

### Option B: VSCode Extension

**Recommended for:** VSCode users, integrated workflow, inline annotations

The VSCode extension provides:
- Inline spec annotations in code
- Task status indicators
- Quick actions for spec management
- Integrated approval interface

资料来源：[README.ko.md:30-35](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.ko.md)

## Project Structure

After initialization, Spec-Workflow creates a `.spec-workflow` directory with the following structure:

```
your-project/
├── .spec-workflow/
│   ├── approvals/          # Pending approval documents
│   ├── archive/           # Archived specifications
│   ├── specs/             # Active specifications
│   ├── steering/          # Steering/prompt documents
│   ├── templates/         # Built-in templates
│   ├── user-templates/    # Custom user templates
│   └── config.example.toml # Configuration template
```

| Directory | Purpose |
|-----------|---------|
| `approvals/` | Stores documents pending review and approval |
| `archive/` | Contains superseded/archived specifications |
| `specs/` | Active specification documents |
| `steering/` | AI steering prompts and guidelines |
| `templates/` | Reusable specification templates |
| `user-templates/` | Custom templates created by users |

资料来源：[README.md:20-35](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

## Development Setup

For contributing to the project or running from source:

```bash
# Install dependencies
npm install

# Build the project
npm run build

# Run in development mode
npm run dev
```

### Available npm Scripts

| Command | Description |
|---------|-------------|
| `npm run build` | Compiles TypeScript to JavaScript |
| `npm run dev` | Runs in development mode with hot reload |
| `npm test` | Runs the test suite |
| `npm run lint` | Lints code for style and errors |

资料来源：[README.fr.md:25-40](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.fr.md)

## Architecture Overview

```mermaid
graph TD
    A[AI Coding Assistant] -->|MCP Protocol| B[Spec-Workflow MCP Server]
    B --> C[.spec-workflow Directory]
    C --> D[Specs]
    C --> E[Tasks]
    C --> F[Approvals]
    C --> G[Implementation Logs]
    
    H[Web Dashboard] <-->|HTTP API| B
    I[VSCode Extension] <-->|VSCode API| B
    
    J[Project Files] -->|Read/Write| B
    
    style B fill:#e1f5fe
    style H fill:#fff3e0
    style I fill:#e8f5e9
```

## Security Features

Spec-Workflow MCP includes enterprise-grade security controls:

| Feature | Description |
|---------|-------------|
| **Localhost Binding** | Binds to `127.0.0.1` by default, preventing network exposure |
| **Rate Limiting** | 120 requests/minute per client with automatic cleanup |
| **Audit Logging** | Structured JSON logs with timestamp, actor, action, and result |
| **Security Headers** | X-Content-Type-Options, X-Frame-Options, X-XSS-Protection, CSP, Referrer-Policy |
| **CORS Protection** | Configurable cross-origin request policies |

资料来源：[README.md:100-115](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

## Quick Start Workflow

```mermaid
graph LR
    A[Install MCP Server] --> B[Configure AI Tool]
    B --> C[Initialize Project]
    C --> D[Create Specification]
    D --> E[AI Generates Code]
    E --> F[Review & Approve]
    F --> G[Implementation Logged]
    
    style A fill:#ffcdd2
    style D fill:#fff9c4
    style F fill:#c8e6c9
```

## Troubleshooting

### Common Issues

**Issue: Dashboard not accessible**
- Ensure port 5000 is available
- Check if another instance is running
- Verify firewall settings

**Issue: MCP server connection failed**
- Verify the project path is absolute, not relative
- Check that Node.js version meets requirements
- Ensure the npx cache is up to date: `npx -y`

**Issue: Permissions error with .spec-workflow directory**
- Ensure the directory has appropriate read/write permissions
- On Linux/Mac: `chmod -R 755 .spec-workflow`

资料来源：[docs/TROUBLESHOOTING.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/docs/TROUBLESHOOTING.md)

## Next Steps

After completing the getting started guide:

1. **Create your first specification** using the spec template
2. **Explore the dashboard** at `http://localhost:5000`
3. **Review documentation:**
   - [Development Guide](docs/DEVELOPMENT.md) - Contributing and development setup
   - [Tools Reference](docs/TOOLS-REFERENCE.md) - Complete tools documentation
   - [Prompting Guide](docs/PROMPTING-GUIDE.md) - Advanced prompting examples
   - [Interfaces Guide](docs/INTERFACES.md) - Dashboard and VSCode extension details

## License

Spec-Workflow MCP is released under the **GPL-3.0** license.

资料来源：[README.md:45-50](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)

---

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

## Project Structure

### 相关页面

相关主题：[Getting Started](#getting-started), [System Architecture](#architecture)

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

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

- [README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)
- [src/markdown/templates/structure-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/structure-template.md)
- [src/dashboard_frontend/src/modules/api/api.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/api/api.tsx)
- [vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx)
- [vscode-extension/src/webview/components/LogEntryCard.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/components/LogEntryCard.tsx)
</details>

# Project Structure

## Overview

The spec-workflow-mcp project is a Model Context Protocol (MCP) server that provides AI-powered specification-driven development workflow management. The project is organized into multiple subsystems that work together to enable seamless specification management, task tracking, and approval workflows for development projects.

## High-Level Architecture

The project follows a modular architecture with three main interface options:

```mermaid
graph TD
    A[AI Tools / LLM Clients] -->|MCP Protocol| B[MCP Server]
    B --> C[Core Engine]
    B --> D[Dashboard Backend]
    B --> E[Dashboard Frontend]
    B --> F[VSCode Extension]
    
    C -->|File System| G[.spec-workflow/]
    D --> G
    G --> H[specs/]
    G --> I[approvals/]
    G --> J[archive/]
    G --> K[steering/]
    G --> L[templates/]
```

## Directory Structure

The `.spec-workflow` directory is created within your project and contains all specification-related data:

```plaintext
your-project/
  .spec-workflow/
    approvals/          # Pending approval items
    archive/            # Archived specifications
    specs/              # Active specification documents
    steering/           # Steering/prompting files
    templates/          # Default templates
    user-templates/     # User-defined templates
    config.example.toml # Configuration file template
```

## Core Components

### MCP Server (`src/`)

The MCP server is the central component that exposes tools and resources to AI clients. It handles:

- Specification document parsing and management
- Task status tracking
- Approval workflow execution
- Implementation logging

### Dashboard Backend

The backend provides REST API endpoints for the web dashboard:

| Endpoint Pattern | Purpose |
|------------------|---------|
| `/api/specs/{name}` | Get spec document details |
| `/api/specs/{name}/tasks/progress` | Get task progress for a spec |
| `/api/specs/{name}/tasks/{taskId}/status` | Update task status |
| `/api/approvals/{id}/{action}` | Perform approval actions |
| `/api/approvals/batch/{action}` | Batch approval operations |

资料来源：[src/dashboard_frontend/src/modules/api/api.tsx:1-20](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/api/api.tsx)

### Dashboard Frontend

The web dashboard is a React-based interface located at `src/dashboard_frontend/`. It provides pages for:

- **TasksPage** - View and manage tasks within specifications
- **SettingsPage** - Configure automated cleanup jobs
- **JobExecutionHistory** - View historical job executions

#### Frontend API Integration

The frontend uses typed API calls to communicate with the backend:

```typescript
const api = {
  getSpecTasksProgress: (name: string) => getJson(`${prefix}/specs/${encodeURIComponent(name)}/tasks/progress`),
  updateTaskStatus: (specName: string, taskId: string, status: 'pending' | 'in-progress' | 'completed' | 'blocked', reason?: string) =>
    putJson(`${prefix}/specs/${encodeURIComponent(specName)}/tasks/${encodeURIComponent(taskId)}/status`, { status, ...(reason && { reason }) }),
  approvalsAction: (id, action, body) => postJson(`${prefix}/approvals/${encodeURIComponent(id)}/${action}`, body),
};
```

资料来源：[src/dashboard_frontend/src/modules/api/api.tsx:5-8](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/api/api.tsx)

### VSCode Extension

The VSCode extension (`vscode-extension/`) provides an integrated experience within the VSCode editor. It includes:

- **Webview-based UI** - React components rendered in VSCode
- **App Component** - Main application entry point
- **LogEntryCard Component** - Displays implementation log entries

#### Webview Structure

```mermaid
graph LR
    A[index.html] --> B[main.tsx]
    B --> C[App.tsx]
    C --> D[TasksPage]
    C --> E[SettingsPage]
    C --> F[LogEntryCard]
```

The extension uses a webview to render the dashboard UI, with localization support through i18n modules.

资料来源：[vscode-extension/src/webview/index.html:1-15](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/index.html)

## Implementation Log System

The implementation log tracks code artifacts and changes made during development:

```mermaid
graph TD
    A[Implementation Entry] --> B[Statistics]
    A --> C[Files Modified]
    A --> D[Files Created]
    A --> E[Artifacts]
    
    E --> E1[API Endpoints]
    E --> E2[Components]
    E --> E3[Functions]
    E --> E4[Classes]
    E --> E5[Integrations]
```

### Artifact Types

| Type | Properties | Description |
|------|------------|-------------|
| apiEndpoints | method, path, purpose, location, requestFormat, responseFormat | HTTP API endpoints |
| components | name, type, purpose, location, props, exports | UI/components |
| functions | name, purpose, location, signature, isExported | Code functions |
| classes | name, purpose, location, methods, isExported | Code classes |
| integrations | description, frontendComponent, backendEndpoint, dataFlow | Integration points |

资料来源：[vscode-extension/src/webview/components/LogEntryCard.tsx:30-50](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/components/LogEntryCard.tsx)

## Development Workflow Structure

```mermaid
graph LR
    A[Create Spec] --> B[Generate Tasks]
    B --> C[Implement Code]
    C --> D[Log Artifacts]
    D --> E[Request Approval]
    E --> F[Approve/Request Changes]
    F -->|Approve| G[Archive Spec]
    F -->|Changes| C
```

### Template System

Templates define the structure of specification documents. The project includes:

- **structure-template.md** - Defines code organization patterns
- **user-templates/** - Custom user-defined templates

#### Template Sections

The structure template includes guidelines for:

1. **File Organization** - How to structure code files
2. **Function/Method Organization** - Patterns for function design
3. **Code Organization Principles** - Single responsibility, modularity, testability
4. **Module Boundaries** - Defining inter-module interactions
5. **Code Size Guidelines** - Limits for file and function sizes

资料来源：[src/markdown/templates/structure-template.md:1-60](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/structure-template.md)

## Configuration

The project uses TOML configuration files. The example configuration template is located at:

```
.spec-workflow/config.example.toml
```

Configuration options include:
- Dashboard connection settings
- Cleanup job schedules
- Template preferences
- Approval workflow settings

## Project Statistics Display

The dashboard displays project statistics including:

| Metric | Description |
|--------|-------------|
| activeSpecs | Total active specification documents |
| completedSpecs | Successfully completed specifications |
| archivedSpecs | Archived/old specifications |
| totalSpecs | All specifications count |
| totalTasks | Total tasks across all specs |
| completedTasks | Completed tasks count |

These statistics are aggregated from the `.spec-workflow` directory and displayed in both the web dashboard and VSCode extension.

资料来源：[vscode-extension/src/webview/App.tsx:10-40](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx)

## Summary

The spec-workflow-mcp project is organized into distinct layers:

1. **Core Layer** - MCP server handles AI tool interactions
2. **Backend Layer** - REST API for dashboard operations
3. **Frontend Layer** - Web dashboard and VSCode extension
4. **Data Layer** - File-based storage in `.spec-workflow/`

This separation of concerns allows the project to serve multiple interfaces while maintaining a single source of truth for specification data.

---

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

## System Architecture

### 相关页面

相关主题：[MCP Server Implementation](#mcp-server), [Web Dashboard](#web-dashboard), [Spec Management](#spec-management)

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

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

- [src/server.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/server.ts) - **未在当前上下文提供**
- [src/core/project-registry.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/project-registry.ts) - **未在当前上下文提供**
- [src/dashboard/multi-server.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/multi-server.ts) - **未在当前上下文提供**
- [src/dashboard/project-manager.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/project-manager.ts) - **未在当前上下文提供**
- [src/core/global-dir.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/global-dir.ts) - **未在当前上下文提供**

> ⚠️ **注意**: 指定的核心架构源文件（server.ts, project-registry.ts, multi-server.ts, project-manager.ts, global-dir.ts）在当前上下文中不可用。以下内容基于 README 文档、API 客户端代码和前端组件的有限片段综合得出。如需完整准确的架构文档，请确保提供上述源文件。

</details>

# System Architecture

## Overview

The Spec-Workflow MCP (Model Context Protocol) system is designed as a bridge between AI coding assistants and structured software development workflows. It provides a specification-driven approach to managing software development tasks, approvals, and implementation tracking.

The architecture follows a multi-tier design with distinct components for MCP protocol handling, project management, dashboard services, and frontend interfaces.

## High-Level Architecture

```mermaid
graph TD
    subgraph "Client Layer"
        VSCode[VSCode Extension]
        CLI[Claude CLI]
        Desktop[Claude Desktop]
    end

    subgraph "MCP Server Layer"
        MCPServer[MCP Server]
        Tools[Tool Handlers]
    end

    subgraph "Dashboard Layer"
        Dashboard[Web Dashboard]
        MultiServer[Multi-Server Manager]
        ProjectManager[Project Manager]
    end

    subgraph "Core Services"
        Registry[Project Registry]
        GlobalDir[Global Directory]
        ApprovalEngine[Approval Engine]
    end

    subgraph "Storage Layer"
        SpecWorkflowDir[.spec-workflow/]
        Config[Config Files]
        Specs[Specs Data]
        Approvals[Approvals]
    end

    VSCode <--> MCPServer
    CLI <--> MCPServer
    Desktop <--> MCPServer
    
    MCPServer <--> Dashboard
    Dashboard <--> Registry
    Dashboard <--> ProjectManager
    ProjectManager <--> GlobalDir
    Registry <--> SpecWorkflowDir
    ApprovalEngine <--> SpecWorkflowDir
```

## Core Components

### MCP Server (`src/server.ts`)

The MCP server acts as the central protocol handler that bridges AI tools with the spec workflow system.

| Component | Purpose |
|-----------|---------|
| Protocol Handler | Processes MCP requests and responses |
| Tool Registry | Manages available MCP tools |
| Request Router | Routes requests to appropriate handlers |
| Response Formatter | Formats tool outputs for AI consumption |

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

### Project Registry (`src/core/project-registry.ts`)

The project registry maintains a centralized record of all projects connected to the spec workflow system.

| Property | Type | Description |
|----------|------|-------------|
| projectId | string | Unique project identifier |
| path | string | Absolute path to project root |
| config | Config | Project-specific configuration |
| lastAccess | timestamp | Last activity timestamp |

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

### Dashboard Multi-Server Manager (`src/dashboard/multi-server.ts`)

Manages multiple MCP server instances and provides centralized coordination.

```mermaid
graph LR
    A[Dashboard UI] --> B[Multi-Server Manager]
    B --> C[Server 1]
    B --> D[Server 2]
    B --> N[Server N]
    
    C --> E[Project 1]
    D --> F[Project 2]
    N --> G[Project N]
```

### Project Manager (`src/dashboard/project-manager.ts`)

Handles project lifecycle operations including initialization, status tracking, and data synchronization.

| Method | Description |
|--------|-------------|
| initializeProject() | Sets up .spec-workflow directory |
| getProjectStats() | Retrieves project metrics |
| syncProject() | Synchronizes project state |
| archiveProject() | Archives completed projects |

### Global Directory (`src/core/global-dir.ts`)

Provides cross-project data management and shared resources.

The global directory stores shared configuration and data at:
```
~/.spec-workflow/
```

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

## Directory Structure

Each project managed by spec-workflow follows a standardized directory layout:

```
your-project/
  .spec-workflow/
    approvals/          # Approval requests and responses
    archive/            # Archived specifications
    specs/              # Active specifications
    steering/           # Steering configurations
    templates/          # Specification templates
    user-templates/      # Custom user templates
    config.example.toml # Example configuration
```

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

## Dashboard Architecture

The dashboard provides a web-based interface for managing specs and tasks across connected projects.

### Frontend Stack

| Layer | Technology | Purpose |
|-------|------------|---------|
| UI Framework | React | Component rendering |
| API Client | TypeScript | Backend communication |
| Styling | Tailwind CSS | Responsive design |
| Internationalization | i18n | Multi-language support |

资料来源：[vscode-extension/src/webview/App.tsx](), [src/dashboard_frontend/src/modules/api/api.tsx]()

### Backend Services

| Service | Port | Description |
|---------|------|-------------|
| Dashboard Server | 5000 | Main dashboard web server |
| API Endpoints | /api/* | REST API for spec management |

The dashboard binds to `127.0.0.1` by default to prevent network exposure.

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

## API Architecture

```mermaid
graph TD
    subgraph "API Client (Frontend)"
        TasksPage[TasksPage]
        SettingsPage[SettingsPage]
    end

    subgraph "API Endpoints"
        GET_SPECS[GET /specs/:name/all]
        UPDATE_TASK[PUT /specs/:name/tasks/:id/status]
        APPROVALS[POST /approvals/:id/:action]
    end

    TasksPage --> GET_SPECS
    SettingsPage --> UPDATE_TASK
    TasksPage --> APPROVALS
```

### Key API Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/specs/:name/all` | GET | Fetch all spec documents |
| `/specs/:name/archived` | GET | Fetch archived specs |
| `/specs/:name/tasks/progress` | GET | Get task progress statistics |
| `/specs/:name/tasks/:id/status` | PUT | Update task status |
| `/approvals/:id/:action` | POST | Process approval action |
| `/approvals/batch/:action` | POST | Batch approval operations |

资料来源：[src/dashboard_frontend/src/modules/api/api.tsx]()

## Security Architecture

The system implements enterprise-grade security controls suitable for corporate environments.

| Security Feature | Implementation | Purpose |
|-----------------|----------------|---------|
| Localhost Binding | `127.0.0.1` default | Prevent network exposure |
| Rate Limiting | 120 req/min per client | Prevent abuse |
| Audit Logging | JSON structured logs | Track all operations |
| Security Headers | CSP, X-Frame-Options | Browser protection |
| CORS Protection | Configurable origins | Cross-origin control |

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

## Deployment Options

### Docker Deployment

```mermaid
graph LR
    A[Docker Compose] --> B[Dashboard Container]
    B --> C[spec-workflow data]
    D[Projects] --> C
```

```bash
# Using Docker Compose
cd containers
docker-compose up --build

# Dashboard available at http://localhost:5000
```

### MCP Client Integration

| Client | Configuration Method |
|--------|---------------------|
| VSCode (Augment) | `settings.json` MCP servers |
| Claude Code CLI | `claude mcp add` command |
| Claude Desktop | `claude_desktop_config.json` |
| Codex | `~/.codex/config.toml` |

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

## Implementation Log System

The implementation log tracks all changes made during development.

```mermaid
graph TD
    A[Implementation Entry] --> B[Files Modified]
    A --> C[Files Created]
    A --> D[Artifacts]
    D --> E[API Endpoints]
    D --> F[Components]
    D --> G[Functions]
    D --> H[Classes]
    D --> I[Integrations]
```

### Log Entry Structure

| Field | Type | Description |
|-------|------|-------------|
| id | string | Unique entry identifier |
| timestamp | Date | Entry creation time |
| description | string | Summary of changes |
| filesModified | string[] | List of modified files |
| filesCreated | string[] | List of created files |
| artifacts | Artifacts | Structured artifact data |

资料来源：[src/dashboard/implementation-log-manager.ts](), [src/core/implementation-log-migrator.ts]()

## Task Management Flow

```mermaid
graph TD
    A[Create Task] --> B[pending]
    B --> C{inProgress?}
    C -->|Yes| D[in-progress]
    C -->|No| E[blocked]
    D --> F{Completed?}
    F -->|Yes| G[completed]
    F -->|No| D
    E --> H{Blocked Reason Required}
    H --> I[Save Blocked Reason]
    I --> B
```

### Task States

| State | Description |
|-------|-------------|
| `pending` | Task created but not started |
| `in-progress` | Task actively being worked on |
| `completed` | Task finished successfully |
| `blocked` | Task paused due to dependency |

资料来源：[src/dashboard_frontend/src/modules/pages/TasksPage.tsx]()

## Configuration Schema

### MCP Server Configuration

```json
{
  "mcpServers": {
    "spec-workflow": {
      "command": "npx",
      "args": ["-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/project"]
    }
  }
}
```

### Project Configuration (`config.toml`)

| Section | Key | Type | Description |
|---------|-----|------|-------------|
| general | workspace | string | Project root path |
| general | language | string | Primary language |
| dashboard | port | number | Dashboard server port |
| dashboard | host | string | Bind address |
| cleanup | enabled | boolean | Auto cleanup toggle |
| cleanup | schedule | string | Cron schedule |

## Summary

The spec-workflow-mcp architecture provides:

1. **Protocol Bridge**: Seamless MCP integration with AI coding tools
2. **Specification-Driven Workflow**: Structured approach to software development
3. **Multi-Project Management**: Centralized dashboard for all projects
4. **Enterprise Security**: Production-ready security controls
5. **Flexible Deployment**: Docker and native deployment options

This architecture enables teams to maintain consistent development practices while leveraging AI assistance throughout the development lifecycle.

---

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

## MCP Server Implementation

### 相关页面

相关主题：[Approval Workflow System](#approval-workflow), [Spec Management](#spec-management), [Steering Documents](#steering-documents)

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

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

- [src/index.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/index.ts)
- [src/tools/approvals.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/approvals.ts)
- [src/tools/spec-status.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/spec-status.ts)
- [src/tools/log-implementation.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/log-implementation.ts)
- [src/tools/steering-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/steering-guide.ts)
- [src/tools/spec-workflow-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/spec-workflow-guide.ts)
- [src/prompts/index.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/prompts/index.ts)
</details>

# MCP Server Implementation

## Overview

The MCP Server Implementation provides a Model Context Protocol (MCP) server that integrates the spec-workflow system into AI coding assistants. It exposes structured tools that AI agents can invoke to manage specification-driven development workflows, including approvals, spec tracking, and implementation logging.

**Purpose:**
- Bridge AI coding assistants with the spec-workflow specification management system
- Enable AI agents to create, review, and update specification documents
- Provide human-in-the-loop approval workflows for AI-generated code
- Track implementation progress across multiple specification phases

**Scope:**
The server operates as a local MCP server that connects to a project directory, providing tools for steering documentation, spec creation, approval management, and implementation logging. It works alongside a dashboard server for human review and approval.

## Architecture

### System Components

The MCP server architecture consists of three interconnected layers:

```mermaid
graph TD
    A["AI Coding Assistant<br/>(Cline, Cursor, VS Code)"] --> B["MCP Server<br/>(spec-workflow-mcp)"]
    B --> C["Dashboard Server<br/>(Port 5000)"]
    B --> D["Project Directory<br/>(.spec-workflow)"]
    C --> D
    
    B --> E["Tools"]
    E --> E1["approvals"]
    E --> E2["spec-status"]
    E --> E3["spec-workflow-guide"]
    E --> E4["steering-guide"]
    E --> E5["log-implementation"]
    E --> E6["prompt-generation"]
```

### MCP Server Entry Point

The server is initialized in `src/index.ts` and configured via command-line arguments. The primary execution path:

1. Parse command-line arguments for project path and mode
2. Initialize the MCP server with stdio transport
3. Register all available tools and resources
4. Begin message processing loop

**Configuration Example:**
```json
{
  "mcpServers": {
    "spec-workflow": {
      "command": "npx",
      "args": ["-y", "@pimzino/spec-workflow-mcp@latest", "/path/to/your/project"]
    }
  }
}
```

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

> **Important:** Run the dashboard separately with `--dashboard` before starting the MCP server.

## Available Tools

### Tool Overview

| Tool Name | Purpose | Key Actions |
|-----------|---------|-------------|
| `approvals` | Manage approval workflows | request, status, delete |
| `spec-status` | Track specification states | get, update |
| `spec-workflow-guide` | Load spec workflow instructions | N/A (resource loader) |
| `steering-guide` | Load steering workflow instructions | N/A (resource loader) |
| `log-implementation` | Record implementation artifacts | create, list, update |
| `prompt-generation` | Generate workflow prompts | N/A (resource loader) |

### Approvals Tool

The approvals tool manages the human-in-the-loop approval workflow. All AI-generated specs require explicit human approval before proceeding.

**Actions:**

| Action | Parameters | Description |
|--------|------------|-------------|
| `request` | `filePath` | Request approval for a specific file |
| `status` | `approvalId` | Check current status of an approval request |
| `delete` | `approvalId` | Remove approval after acceptance/rejection |

**Workflow Integration:**

```mermaid
graph LR
    A[AI Creates Spec] --> B[Request Approval]
    B --> C{Human Reviews}
    C -->|Approved| D[Delete Approval]
    C -->|Needs Revision| E[AI Updates Spec]
    E --> B
    D --> F[Proceed to Implementation]
```

**Approval Status States:**

| Status | Meaning |
|--------|---------|
| `pending` | Awaiting human review |
| `approved` | Human accepted the specification |
| `needs-revision` | Human requested changes |
| `rejected` | Human rejected the specification |

资料来源：[src/tools/approvals.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/approvals.ts)

### Spec Status Tool

The spec-status tool tracks the lifecycle state of individual specifications.

**Supported States:**

| State | Description |
|-------|-------------|
| `draft` | Initial creation phase |
| `in-progress` | Actively being implemented |
| `review` | Under human review |
| `approved` | Approved and ready for next phase |
| `completed` | Fully implemented |
| `archived` | Moved to archive |

**Operations:**
- Query current status of any spec
- Update status after phase transitions
- Retrieve history of status changes

资料来源：[src/tools/spec-status.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/spec-status.ts)

### Spec Workflow Guide

Provides structured guidance for the specification creation workflow. The guide defines a 4-phase process:

```mermaid
graph TD
    P1[Phase 1: Design] --> P2[Phase 2: Spec]
    P2 --> P3[Phase 3: Tasks]
    P3 --> P4[Phase 4: Implementation]
    
    P1 --> P1A[product.md]
    P2 --> P2A[design.md]
    P3 --> P3A[tasks.md]
    P4 --> P4A[Code Files]
```

**Phase Details:**

| Phase | Document | Template | Output Location |
|-------|----------|----------|-----------------|
| 1 | Product | product-template.md | .spec-workflow/steering/ |
| 2 | Design | design-template.md | .spec-workflow/specs/{name}/ |
| 3 | Tasks | tasks-template.md | .spec-workflow/specs/{name}/ |
| 4 | Implementation | N/A | Project root |

资料来源：[src/tools/spec-workflow-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/spec-workflow-guide.ts)

### Steering Guide

Defines the steering documentation workflow for project-wide guidance:

**Steering Phases:**

| Phase | Purpose | Document | Template |
|-------|---------|----------|----------|
| 1 | Product Vision | product.md | product-template.md |
| 2 | Technology | tech.md | tech-template.md |
| 3 | Structure | structure.md | structure-template.md |

**Template Resolution:**

```mermaid
graph TD
    A[Need Template] --> B{user-templates exist?}
    B -->|Yes| C[Use user-templates]
    B -->|No| D[Use templates]
    C --> E[Load Template]
    D --> E
```

Templates are resolved first from `.spec-workflow/user-templates/` directory, falling back to `.spec-workflow/templates/` if no custom templates exist.

资料来源：[src/tools/steering-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/steering-guide.ts)

### Log Implementation Tool

Records and tracks implementation artifacts generated during the coding phase. Enables the AI to maintain a structured record of what was built.

**Artifact Types:**

| Type | Fields | Description |
|------|--------|-------------|
| `apiEndpoints` | method, path, purpose, location | REST API definitions |
| `components` | name, type, purpose, location, props | UI/functional components |
| `functions` | name, purpose, location, signature, isExported | Code functions |
| `classes` | name, purpose, location, methods, isExported | Class definitions |
| `integrations` | description, frontendComponent, backendEndpoint, dataFlow | Integration points |

**Implementation Log Entry Structure:**

```typescript
interface ImplementationLogEntry {
  timestamp: string;
  specName: string;
  filesCreated: string[];
  filesModified: string[];
  artifacts: {
    apiEndpoints?: ApiEndpoint[];
    components?: Component[];
    functions?: Function[];
    classes?: Class[];
    integrations?: Integration[];
  };
  statistics: {
    linesAdded: number;
    linesRemoved: number;
  };
}
```

资料来源：[src/dashboard/implementation-log-manager.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/implementation-log-manager.ts)

## Workflow Integration

### Initialization Sequence

```mermaid
sequenceDiagram
    participant User
    participant Dashboard
    participant MCP
    participant AI
    
    User->>Dashboard: Start dashboard (port 5000)
    User->>MCP: Start MCP server with project path
    User->>AI: Configure AI client with MCP
    AI->>MCP: List available tools
    MCP-->>AI: Return tool definitions
    AI->>MCP: Call steering-guide
    MCP-->>AI: Return workflow instructions
    AI->>MCP: Create spec via prompts
    AI->>MCP: Request approval
    MCP->>Dashboard: Store approval request
    User->>Dashboard: Review and approve
    Dashboard->>MCP: Update approval status
    MCP-->>AI: Approval granted
```

### Client Configuration

The MCP server supports multiple AI coding assistant clients:

| Client | Configuration Location | Notes |
|--------|----------------------|-------|
| Claude Desktop | claude_desktop_config.json | Run dashboard first |
| Cline | mcp_settings.json | Direct npx execution |
| Claude Dev | mcp_settings.json | Direct npx execution |
| Continue | config.json | MCP server array |
| Cursor | settings.json | User settings |

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

## Dashboard Server Integration

The dashboard server runs independently on port 5000 and provides:

- **Approval Management UI**: Review pending approvals with file diffs
- **Spec Overview**: View all specs and their current states
- **Statistics Dashboard**: Track progress across specs and tasks
- **Implementation Logs**: Browse logged implementation artifacts

**Single Instance Model:**

> **Note:** Only one dashboard instance is required. All projects connect to the same dashboard server.

```bash
# Start dashboard
npx -y @pimzino/spec-workflow-mcp@latest --dashboard

# Dashboard accessible at http://localhost:5000
```

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

## Project Directory Structure

The MCP server expects and manages the following directory structure within each project:

```
your-project/
  .spec-workflow/
    approvals/          # Active approval requests
    archive/            # Completed/archived specs
    specs/              # Individual spec directories
      {spec-name}/
        design.md
        tasks.md
    steering/           # Project-level steering docs
      product.md
      tech.md
      structure.md
    templates/          # Default templates
    user-templates/     # Project-specific custom templates
    config.example.toml
```

## Prompt Generation

The prompt-generation resource provides AI-usable prompts for each workflow phase, enabling consistent spec creation behavior.

**Prompt Categories:**

| Category | Purpose |
|----------|---------|
| spec-creation | Guide spec document creation |
| task-breakdown | Convert specs to implementable tasks |
| implementation | Guide code implementation |
| review | Facilitate human review |

资料来源：[src/prompts/index.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/prompts/index.ts)

## Error Handling

The MCP server implements several error handling strategies:

| Scenario | Handling |
|----------|----------|
| Dashboard unavailable | Continue without real-time sync |
| Approval delete fails | Stop workflow, return to polling |
| Template not found | Fall back to default templates |
| Invalid spec state | Return error, require correction |
| File system errors | Return detailed error message |

**Critical Workflow Constraint:**

If approval deletion fails after acceptance, the workflow **must stop** and return to polling status. The implementation cannot proceed until the approval cleanup succeeds.

资料来源：[src/tools/steering-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/steering-guide.ts)

## Development

### Building the Server

```bash
# Install dependencies
npm install

# Build the project
npm run build

# Run in development mode
npm run dev
```

### Source Organization

| Path | Purpose |
|------|---------|
| src/index.ts | Main entry point, MCP server initialization |
| src/tools/*.ts | Tool implementations |
| src/prompts/*.ts | Prompt generation utilities |
| src/dashboard/*.ts | Dashboard server components |
| src/dashboard_frontend/*.tsx | Dashboard React components |

## Summary

The MCP Server Implementation provides a comprehensive bridge between AI coding assistants and the spec-workflow specification management system. By exposing structured tools for approvals, spec tracking, implementation logging, and workflow guidance, it enables AI agents to participate in human-controlled development workflows while maintaining full transparency and auditability of all generated artifacts.

---

<a id='spec-management'></a>

## Spec Management

### 相关页面

相关主题：[Approval Workflow System](#approval-workflow), [Steering Documents](#steering-documents), [MCP Server Implementation](#mcp-server)

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

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

- [src/prompts/create-spec.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/prompts/create-spec.ts)
- [src/core/parser.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/parser.ts)
- [src/core/task-parser.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/task-parser.ts)
- [src/core/task-validator.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/task-validator.ts)
- [src/markdown/templates/requirements-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/requirements-template.md)
- [src/markdown/templates/design-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/design-template.md)
- [src/markdown/templates/tasks-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/tasks-template.md)
- [src/prompts/implement-task.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/prompts/implement-task.ts)
</details>

# Spec Management

## Overview

Spec Management is the core system within spec-workflow-mcp that enables structured project specification, task planning, and implementation tracking. This system provides a standardized approach to converting project ideas into actionable, trackable implementation tasks through a Markdown-based specification document format.

The spec management system serves as the foundation for the entire workflow, bridging the gap between high-level project requirements and concrete implementation tasks. It ensures that every feature or change is properly documented, validated, and tracked throughout its lifecycle.

## Architecture Overview

```mermaid
graph TD
    A[User] --> B[Spec Creation]
    B --> C[Spec Templates]
    C --> D[Requirements Template]
    C --> E[Design Template]
    C --> F[Tasks Template]
    D --> G[Core Parser]
    E --> G
    F --> H[Task Parser]
    G --> I[Spec Document]
    H --> J[Task Validation]
    J --> K[Task Status Tracking]
    I --> L[Dashboard / VSCode Extension]
    K --> L
```

## Spec Document Structure

### Directory Layout

Specs are stored within each project's `.spec-workflow` directory following a standardized structure:

```
your-project/
  .spec-workflow/
    approvals/
    archive/
    specs/
    steering/
    templates/
    user-templates/
    config.example.toml
```

资料来源：[README.fr.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.fr.md)

### Specification Components

Each specification document is composed of multiple template sections that capture different aspects of the project requirements.

| Component | Purpose | File Pattern |
|-----------|---------|--------------|
| Requirements | Define what needs to be built | `requirements-template.md` |
| Design | Document architectural decisions | `design-template.md` |
| Tasks | Break down implementation steps | `tasks-template.md` |

## Requirements Template

The requirements template establishes the foundation of a specification by capturing the essential "what" of the feature or change.

### Key Sections

The requirements template includes structured fields for:

- **Title and Description**: Clear identification of the feature
- **Purpose**: The motivation behind the feature
- **Leverage**: Existing code, patterns, or systems to build upon
- **Requirements**: Specific constraints and conditions that must be met
- **Acceptance Criteria**: Measurable outcomes that define success

资料来源：[src/markdown/templates/requirements-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/requirements-template.md)

### Purpose Field

The `purposes` array captures multiple reasons for a given feature:

```typescript
// Task structure showing purposes field
interface Task {
  purposes: string[];
  requirements: string[];
  leverage?: string;
  prompt?: string;
}
```

资料来源：[src/dashboard_frontend/src/modules/pages/TasksPage.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/TasksPage.tsx)

## Design Template

The design template documents the "how" of implementation, capturing architectural decisions and technical approach.

### Structure

The design template typically includes:

- **Code Organization**: Guidelines for file and module structure
- **Module Boundaries**: Defining how different parts interact
- **Function/Method Organization**: Patterns for organizing code logic
- **Code Size Guidelines**: Limits on file and function complexity

资料来源：[src/markdown/templates/design-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/design-template.md)

### Design Principles

The template enforces several key principles:

| Principle | Description |
|-----------|-------------|
| Single Responsibility | Each file should have one clear purpose |
| Modularity | Code organized into reusable modules |
| Testability | Structure code to be easily testable |
| Consistency | Follow patterns established in the codebase |

## Tasks Template

The tasks template breaks down the implementation into granular, actionable items that can be tracked and completed independently.

### Task Properties

Each task within the tasks template supports the following properties:

| Property | Type | Description |
|----------|------|-------------|
| `id` | string | Unique identifier for the task |
| `status` | enum | Current state: `pending`, `in-progress`, `completed`, `blocked` |
| `completed` | boolean | Whether task is finished |
| `inProgress` | boolean | Whether task is currently being worked on |
| `purposes` | string[] | Array of purpose descriptions |
| `requirements` | string[] | Specific requirements for this task |
| `leverage` | string | Existing code/patterns to leverage |
| `prompt` | string | AI prompt associated with task |
| `isHeader` | boolean | Whether task is a section header |

资料来源：[src/dashboard_frontend/src/modules/pages/TasksPage.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/TasksPage.tsx)

## Spec Parsing System

### Core Parser

The core parser (`src/core/parser.ts`) is responsible for reading and interpreting spec documents, extracting structured data from Markdown content.

```mermaid
graph LR
    A[Markdown Spec File] --> B[Core Parser]
    B --> C[Extracted Metadata]
    B --> D[Tasks Array]
    B --> E[Requirements]
    B --> F[Design Decisions]
```

资料来源：[src/core/parser.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/parser.ts)

### Task Parser

The task parser (`src/core/task-parser.ts`) specializes in extracting and organizing task information from the tasks section of spec documents.

**Capabilities:**
- Extract task ID and status
- Parse purpose and requirements arrays
- Handle nested task hierarchies
- Support both ordered and unordered task formats

资料来源：[src/core/task-parser.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/task-parser.ts)

### Task Validator

The task validator (`src/core/task-validator.ts`) ensures that parsed tasks meet the required structural and content requirements.

**Validation Checks:**
- Required fields presence
- Status value validity
- Purpose array non-empty
- Requirement completeness

资料来源：[src/core/task-validator.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/task-validator.ts)

## Task Status Workflow

### State Machine

```mermaid
stateDiagram-v2
    [*] --> Pending
    Pending --> InProgress : Start Work
    InProgress --> Completed : Finish Task
    InProgress --> Blocked : Encounter Blocker
    Blocked --> InProgress : Resolve Blocker
    Completed --> [*]
    Blocked --> [*] : Cancel Task
```

### Status Transitions API

```typescript
updateTaskStatus: (
  specName: string, 
  taskId: string, 
  status: 'pending' | 'in-progress' | 'completed' | 'blocked', 
  reason?: string
) => void
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `specName` | string | Yes | Name of the specification |
| `taskId` | string | Yes | Unique task identifier |
| `status` | enum | Yes | New status value |
| `reason` | string | No | Reason for status change (especially for blocked) |

资料来源：[src/dashboard_frontend/src/modules/api/api.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/api/api.tsx)

## Implementation Tracking

### Implementation Log Entry Structure

As tasks are completed, the system tracks implementation artifacts through the ImplementationLogManager:

```typescript
interface ImplementationLogEntry {
  id: string;
  timestamp: Date;
  filesModified: string[];
  filesCreated: string[];
  statistics: {
    linesAdded: number;
    linesRemoved: number;
  };
  artifacts?: {
    apiEndpoints?: ApiEndpoint[];
    components?: Component[];
    functions?: Function[];
    classes?: Class[];
    integrations?: Integration[];
  };
}
```

资料来源：[src/dashboard/implementation-log-manager.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/implementation-log-manager.ts)

### Artifact Types

| Artifact Type | Properties | Description |
|--------------|------------|-------------|
| `apiEndpoints` | method, path, purpose, location, requestFormat, responseFormat | REST API endpoints created |
| `components` | name, type, purpose, location, props, exports | UI/components created |
| `functions` | name, purpose, location, signature, isExported | Functions implemented |
| `classes` | name, purpose, location, methods, isExported | Classes implemented |
| `integrations` | description, frontendComponent, backendEndpoint, dataFlow | Integration points |

资料来源：[src/core/implementation-log-migrator.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/core/implementation-log-migrator.ts)

## Dashboard Integration

### Project Statistics

The dashboard provides an overview of spec and task progress:

| Metric | Description |
|--------|-------------|
| `activeSpecs` | Total number of active specifications |
| `completedSpecs` | Specifications with all tasks completed |
| `archivedSpecs` | Specifications moved to archive |
| `totalSpecs` | Total specs (active + archived) |
| `totalTasks` | Total tasks across all specs |
| `completedTasks` | Tasks marked as completed |

资料来源：[vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx)

### Spec Operations

The dashboard supports the following operations:

| Operation | Endpoint | Description |
|-----------|----------|-------------|
| View Spec | `/specs/{name}` | Retrieve spec document |
| View All Documents | `/specs/{name}/all` | Get all spec-related documents |
| Archive Spec | `/specs/{name}/archive` | Move spec to archive |
| Unarchive Spec | `/specs/{name}/unarchive` | Restore from archive |
| Get Tasks Progress | `/specs/{name}/tasks/progress` | Calculate task completion percentage |

资料来源：[src/dashboard_frontend/src/modules/api/api.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/api/api.tsx)

### Task Progress Calculation

```typescript
const progress = spec.taskProgress?.total
  ? Math.round((spec.taskProgress.completed / spec.taskProgress.total) * 100)
  : 0;
```

资料来源：[src/dashboard_frontend/src/modules/pages/SpecsPage.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/SpecsPage.tsx)

## Steering Documents

Steering documents provide project-level guidance and are managed separately from individual specs:

| Document Type | Purpose |
|--------------|---------|
| Steering Docs | Project-level architectural decisions and direction |
| User Templates | Customizable templates for organization-specific needs |
| Standard Templates | Built-in templates for common spec patterns |

资料来源：[src/dashboard_frontend/src/modules/pages/SteeringPage.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/SteeringPage.tsx)

## AI Integration

### Spec Creation Prompts

The system uses structured prompts for AI-assisted spec creation:

```typescript
interface CreateSpecInput {
  featureName: string;
  description: string;
  leverage?: string;
  requirements?: string[];
}
```

资料来源：[src/prompts/create-spec.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/prompts/create-spec.ts)

### Task Implementation Prompts

When implementing tasks, the AI receives contextual information including:

- Task purposes and requirements
- Leverage information (existing code to build upon)
- Design guidelines from the spec
- Implementation log context

```typescript
interface ImplementTaskInput {
  task: Task;
  spec: Spec;
  leverage: string;
  context: ImplementationLogEntry[];
}
```

资料来源：[src/prompts/implement-task.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/prompts/implement-task.ts)

## Execution History

The system tracks job executions for auditing and debugging purposes:

| Field | Description |
|-------|-------------|
| `itemsDeleted` | Number of items removed during execution |
| `duration` | Execution time in milliseconds |
| `error` | Error message if execution failed |

```typescript
// Duration formatting
{(execution.duration / 1000).toFixed(2)}s
```

资料来源：[src/dashboard_frontend/src/modules/pages/JobExecutionHistory.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/JobExecutionHistory.tsx)

### Execution Statistics

| Metric | Description |
|--------|-------------|
| `totalExecutions` | Total number of execution runs |
| `successRate` | Percentage of successful executions |

## Best Practices

### Writing Effective Specs

1. **Clear Purpose Statements**: Each task should have at least one well-defined purpose
2. **Leverage Existing Code**: Always reference existing patterns or utilities to build upon
3. **Measurable Requirements**: Requirements should be verifiable and testable
4. **Appropriate Granularity**: Tasks should be small enough to complete in one session

### Task Naming Conventions

- Use descriptive task IDs
- Group related tasks under section headers
- Mark section headers with `isHeader: true`
- Keep task titles concise but informative

### Progress Tracking

- Update task status promptly when work begins
- Use the blocked status with reasons when encountering obstacles
- Review implementation logs regularly to ensure accuracy

---

<a id='approval-workflow'></a>

## Approval Workflow System

### 相关页面

相关主题：[Spec Management](#spec-management), [Web Dashboard](#web-dashboard), [VSCode Extension](#vscode-extension)

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

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

- [src/tools/approvals.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/approvals.ts)
- [src/dashboard/approval-storage.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/approval-storage.ts)
- [src/dashboard/watcher.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/watcher.ts)
- [src/tools/steering-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/steering-guide.ts)
- [vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx)
- [src/dashboard/implementation-log-manager.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/implementation-log-manager.ts)
- [src/dashboard_frontend/src/modules/pages/DashboardStatistics.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/DashboardStatistics.tsx)
- [src/dashboard_frontend/src/modules/pages/TasksPage.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/TasksPage.tsx)
</details>

# Approval Workflow System

## Overview

The Approval Workflow System is a core component of the spec-workflow-mcp project that enforces structured document review and revision processes. It ensures that all specifications, designs, and implementation tasks undergo explicit human approval before proceeding to subsequent phases.

**Key Responsibilities:**
- Managing approval requests with associated metadata (title, description, file path)
- Tracking approval status through polling mechanisms
- Enforcing sequential workflow progression (no phase skipping)
- Blocking operations when approvals fail or cleanup is unsuccessful
- Providing cross-platform interfaces (web dashboard and VS Code extension)

**资料来源：**
[src/tools/steering-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/steering-guide.ts)
[src/dashboard/approval-storage.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/approval-storage.ts)

---

## Architecture

### System Components

```mermaid
graph TD
    subgraph "Client Interfaces"
        VSCODE[VS Code Extension]
        DASHBOARD[Web Dashboard]
    end

    subgraph "Core Services"
        APPROVALS[approvals Tool]
        WATCHER[File Watcher]
        STORAGE[Approval Storage]
    end

    subgraph "Data Layer"
        APPROVALS_DIR[.spec-workflow/approvals/]
    end

    VSCODE --> |API calls| APPROVALS
    DASHBOARD --> |API calls| APPROVALS
    APPROVALS --> STORAGE
    STORAGE --> APPROVALS_DIR
    WATCHER --> |File monitoring| APPROVALS_DIR
    WATCHER --> |Events| STORAGE
```

### Technology Stack

| Layer | Technology | Purpose |
|-------|------------|---------|
| Client UI | React + TypeScript | Dashboard and VS Code webview |
| State Management | React Hooks | Local UI state |
| Communication | VS Code API / WebSocket | Real-time updates |
| Persistence | JSON Files | Approval records storage |
| Monitoring | Node.js fs.watch | Directory change detection |

**资料来源：**
[vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx:1-100)
[src/dashboard/watcher.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/watcher.ts)

---

## Approval Lifecycle

### State Machine

```mermaid
stateDiagram-v2
    [*] --> Pending: request action
    Pending --> Approved: User approves
    Pending --> NeedsRevision: User requests changes
    Approved --> Deleted: delete action (success)
    NeedsRevision --> Pending: User re-submits
    Deleted --> [*]
    Deleted --> Pending: delete action fails
```

### Workflow Phases

Each workflow phase follows an identical approval pattern:

| Phase | Document Type | File Path |
|-------|--------------|-----------|
| Phase 1 | Product Document | `.spec-workflow/steering/product.md` |
| Phase 2 | Tech Document | `.spec-workflow/steering/tech.md` |
| Phase 3 | Structure Document | `.spec-workflow/steering/structure.md` |

**Steering Workflow Phase Pattern:**

```mermaid
graph TD
    START[Phase Start] --> TEMPLATE[Check user-templates first,<br/>then read template]
    TEMPLATE --> ANALYZE[Analyze content]
    ANALYZE --> CREATE[Create document file]
    CREATE --> APPROVE[Request approval<br/>approvals action: request]
    APPROVE --> STATUS[Poll status<br/>approvals action: status]
    STATUS --> CHECK{Status?}
    CHECK -->|needs-revision| UPDATE[Update document<br/>using user comments]
    UPDATE --> CREATE
    CHECK -->|approved| CLEAN[Delete approval<br/>approvals action: delete]
    CLEAN -->|success| NEXT[Next Phase]
    CLEAN -->|failed| STATUS
    
    style START fill:#e6f3ff
    style CHECK fill:#ffe6e6
    style NEXT fill:#e6f3ff
```

**资料来源：**
[src/tools/steering-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/steering-guide.ts)

---

## Approvals Tool API

### Tool Actions

The `approvals` tool supports three primary actions:

| Action | Parameters | Description |
|--------|------------|-------------|
| `request` | `title`, `description?`, `filePath` | Create new approval request |
| `status` | `approvalId?` | Check approval status (polling) |
| `delete` | `approvalId` | Remove approval after completion |

### Request Action Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `action` | `"request"` | Yes | Operation to perform |
| `title` | `string` | Yes | Approval request title |
| `description` | `string` | No | Detailed description |
| `filePath` | `string` | Yes | Path to the document under review |

### Usage Example

```typescript
// Request approval for a document
const approvalRequest = await tool.call({
    action: "request",
    title: "Product Vision Document",
    description: "Initial product document for review",
    filePath: ".spec-workflow/steering/product.md"
});

// Poll for status until resolved
let status = await tool.call({ action: "status", approvalId: approvalRequest.id });
while (status === "pending" || status === "in_progress") {
    await sleep(2000);
    status = await tool.call({ action: "status", approvalId: approvalRequest.id });
}

// Delete after successful approval
await tool.call({ action: "delete", approvalId: approvalRequest.id });
```

**资料来源：**
[src/tools/approvals.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/approvals.ts)

---

## Data Models

### Approval Record Schema

```typescript
interface Approval {
    id: string;              // Unique identifier (UUID)
    title: string;           // Display title
    description?: string;    // Optional description
    filePath: string;        // Path to document under review
    status: ApprovalStatus;  // Current state
    createdAt: Date;         // Creation timestamp
    updatedAt: Date;         // Last modification timestamp
    response?: string;        // Approval response message
    requestedBy?: string;     // User who requested approval
}

type ApprovalStatus = "pending" | "approved" | "needs-revision" | "rejected";
```

### Storage Location

Approvals are persisted as JSON files in the `.spec-workflow/approvals/` directory:

```
.spec-workflow/
└── approvals/
    ├── {uuid}.json          # Individual approval records
    └── archive/             # Archived approvals (completed)
```

**资料来源：**
[src/dashboard/approval-storage.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/approval-storage.ts)

---

## UI Components

### VS Code Extension Dashboard

The VS Code extension provides an integrated sidebar for managing approvals:

**Features:**
- Real-time approval list with pending count badge
- Individual action buttons (Approve, Request Changes, View in Editor)
- Batch selection mode for bulk operations
- Selection counter and clear selection functionality
- Translation support (i18n)

**UI Layout:**

```tsx
// Approval card structure
<Card>
    <CardHeader>
        <div className="flex items-center">
            <h3>{approval.title}</h3>
            <Badge>{t('approvals.status.pending')}</Badge>
        </div>
    </CardHeader>
    <CardContent>
        {approval.description && <p>{approval.description}</p>}
        {approval.filePath && <p className="font-mono">{approval.filePath}</p>}
        <Button onClick={() => approveRequest(approval.id)}>
            {t('approvals.approve')}
        </Button>
    </CardContent>
</Card>
```

**资料来源：**
[vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx:1-80)

### Web Dashboard Statistics

The web dashboard displays approval statistics:

```tsx
<div className="stats-card">
    <div className="text-2xl font-semibold tabular-nums">
        {approvals.length}
    </div>
    <div className="text-sm text-muted">
        {approvals.length > 0 
            ? t('stats.approvals.awaiting') 
            : t('stats.approvals.allClear')}
    </div>
</div>
```

**资料来源：**
[src/dashboard_frontend/src/modules/pages/DashboardStatistics.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/DashboardStatistics.tsx)

---

## Critical Workflow Rules

The approval system enforces strict rules that must be followed:

| Rule | Description | Consequence if Violated |
|------|-------------|-------------------------|
| **Sequential Phases** | Complete phases in order | Workflow blocked |
| **Blocking Cleanup** | Approval delete must succeed | Next phase blocked |
| **No Verbal Approval** | Dashboard/VS Code only | Not accepted |
| **No Proceed on "approved"** | Check system status only | Invalid workflow |
| **Two-phase completion** | Approved status + successful cleanup | Incomplete transition |

### Blocking Conditions

```typescript
// CRITICAL: Must have approved status AND successful cleanup before next phase
if (status !== "approved") {
    return { success: false, error: "Approval not granted" };
}

const deleteResult = await approvals({ action: "delete", approvalId });
if (!deleteResult.success) {
    return { success: false, error: "Cleanup failed - blocking next phase" };
}

// Proceed to next phase...
```

**资料来源：**
[src/tools/steering-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/steering-guide.ts)

---

## File Watcher Integration

The approval system integrates with the file watcher for real-time updates:

```mermaid
graph LR
    A[File System Event] --> B[watcher.ts]
    B --> C{Event Type}
    C -->|approval_created| D[Update UI]
    C -->|approval_deleted| E[Refresh List]
    C -->|approval_updated| F[Sync Status]
```

**Watched Events:**
- File creation in `.spec-workflow/approvals/`
- File modification
- File deletion

**资料来源：**
[src/dashboard/watcher.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/watcher.ts)

---

## Internationalization

The approval system supports 11 languages with i18n keys:

| Key | English | Japanese | Chinese |
|-----|---------|----------|---------|
| `approvals.status.pending` | Pending | 保留中 | 待处理 |
| `approvals.approve` | Approve | 承認 | 批准 |
| `approvals.reject` | Request Changes | 変更依頼 | 请求更改 |
| `approvals.noPending` | No pending approvals | 承認待ちなし | 无待批准项 |
| `approvals.selectedCount` | {count} selected | {count}件選択 | 已选择 {count} 项 |

**资料来源：**
[vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx)

---

## Implementation Log Integration

When tasks are implemented following approval, the system tracks artifacts:

```typescript
// Artifacts tracked in implementation logs
interface Artifacts {
    apiEndpoints: APIEndpoint[];
    components: Component[];
    filesCreated: string[];
    filesModified: string[];
}

// Example artifact recording
markdown += `### API Endpoints\n\n`;
artifacts.apiEndpoints.forEach(api => {
    markdown += `#### ${api.method} ${api.path}\n`;
    markdown += `- **Purpose:** ${api.purpose}\n`;
    markdown += `- **Location:** ${api.location}\n`;
});
```

**资料来源：**
[src/dashboard/implementation-log-manager.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/implementation-log-manager.ts)

---

## Best Practices

1. **Always poll for status** - Never assume immediate approval
2. **Handle cleanup failures** - Block workflow on delete failures
3. **Use file paths only** - Approval requests should contain paths, not content
4. **Wait for full resolution** - Both approval AND cleanup must complete
5. **Provide clear titles** - Help reviewers quickly identify documents

---

## Related Documentation

- [Workflow Process](docs/WORKFLOW.md) - Complete workflow guidelines
- [Interfaces Guide](docs/INTERFACES.md) - Dashboard and VSCode extension details
- [Tools Reference](docs/TOOLS-REFERENCE.md) - Complete tools documentation
- [Development Guide](docs/DEVELOPMENT.md) - Contributing and setup

---

<a id='steering-documents'></a>

## Steering Documents

### 相关页面

相关主题：[Spec Management](#spec-management), [Approval Workflow System](#approval-workflow)

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

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

- [src/prompts/create-steering-doc.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/prompts/create-steering-doc.ts)
- [src/tools/steering-guide.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/tools/steering-guide.ts)
- [src/markdown/templates/product-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/product-template.md)
- [src/markdown/templates/tech-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/tech-template.md)
- [src/markdown/templates/structure-template.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/markdown/templates/structure-template.md)
</details>

# Steering Documents

## Overview

Steering Documents are foundational markdown files that guide the development process by defining the product vision, technical architecture, and codebase organization. They serve as the single source of truth for maintaining alignment between development decisions and project goals.

The Steering Documents system consists of three core documents that work together to provide comprehensive guidance for the project.

## Document Types

### 1. Product Vision Document (`product.md`)

The product document defines the **what** and **why** of the project.

| Section | Purpose |
|---------|---------|
| Product Vision | High-level description of the product's purpose and value proposition |
| Target Users | Identification of primary and secondary user groups |
| Key Features | Core functionality that delivers value to users |
| Business Objectives | Goals and metrics that measure project success |

**Template Location:** `src/markdown/templates/product-template.md`

### 2. Technical Architecture Document (`tech.md`)

The tech document defines the **how** of the technical implementation.

| Section | Purpose |
|---------|---------|
| Technology Stack | Programming languages, frameworks, and tools used |
| Architecture Decisions | Key technical choices and their rationale |
| Development Principles | Standards and practices for code quality |
| Dependencies | External libraries and services integrated |

**Template Location:** `src/markdown/templates/tech-template.md`

### 3. Codebase Structure Document (`structure.md`)

The structure document defines the **where** of code organization.

| Section | Purpose |
|---------|---------|
| Directory Structure | High-level organization of project folders |
| Module Architecture | How code is partitioned into logical units |
| Key Files | Important files and their responsibilities |
| Module Relationships | Dependencies between different parts of the codebase |

**Template Location:** `src/markdown/templates/structure-template.md`

## Workflow

```mermaid
graph TD
    A[Create/Update Steering Documents] --> B{Document Type}
    B -->|product.md| C[Define Vision & Features]
    B -->|tech.md| D[Document Architecture]
    B -->|structure.md| E[Map Codebase Organization]
    
    C --> F[Review with AI Assistant]
    D --> F
    E --> F
    
    F --> G[Store in Project Root]
    G --> H[Reference During Development]
```

## Steering Guide Tool

The `steering-guide.ts` module provides the core functionality for managing steering documents.

**Location:** `src/tools/steering-guide.ts`

### Key Functions

| Function | Purpose |
|----------|---------|
| `createSteeringDocument()` | Generate new steering documents from templates |
| `updateSteeringDocument()` | Modify existing documents with new information |
| `validateSteeringDocument()` | Ensure document structure matches template |
| `getSteeringDocument()` | Retrieve document content for reference |

### Configuration Options

```typescript
interface SteeringConfig {
  outputDir: string;        // Directory for steering documents
  templateDir: string;      // Location of markdown templates
  autoSync: boolean;        // Auto-sync with project changes
  validationLevel: 'strict' | 'loose' | 'none';
}
```

## Document Templates

### Product Template Structure

```markdown
# Product Vision
[High-level product description]

# Target Users
[User personas and use cases]

# Key Features
- Feature 1
- Feature 2

# Business Objectives
[Success metrics and goals]
```

### Tech Template Structure

```markdown
# Technology Stack
[Languages, frameworks, tools]

# Architecture Decisions
[Key technical decisions]

# Development Principles
[Code standards and practices]
```

### Structure Template Structure

```markdown
# Directory Structure
[Folder organization]

# Module Architecture
[Code partitioning]

# Key Files
[Important file responsibilities]
```

## Integration with VSCode Extension

The VSCode extension provides a user interface for managing steering documents.

**Location:** `vscode-extension/src/webview/App.tsx`

### Steering Tab Features

```typescript
interface SteeringDocument {
  name: 'product' | 'tech' | 'structure';
  exists: boolean;
  lastModified?: Date;
  path: string;
}
```

| Feature | Description |
|---------|-------------|
| Document List | Display all three steering documents with status |
| Last Modified | Show when each document was last updated |
| Open Document | Quick access to view/edit documents |
| Copy Instructions | Copy AI assistant prompt for document creation |

### User Interface Flow

```mermaid
sequenceDiagram
    participant User
    participant VSCode as VSCode Extension
    participant FS as File System
    
    User->>VSCode: Open Steering Tab
    VSCode->>FS: Check document existence
    FS-->>VSCode: Return file metadata
    VSCode-->>User: Display document list
    
    User->>VSCode: Copy creation instructions
    VSCode->>User: Copy prompt to clipboard
    
    User->>VSCode: Click "Open" on document
    VSCode->>FS: Open file in editor
```

## Implementation Log Integration

Steering documents are referenced in the implementation log system.

**Location:** `src/dashboard/implementation-log-manager.ts`

The implementation log can include references to steering documents as part of task completion records, linking development work back to the guiding documents.

## Best Practices

1. **Keep Documents Updated**: Review and update steering documents when significant changes occur
2. **Consistent Location**: Always store in project root for easy access
3. **Version Control**: Track changes to steering documents in version history
4. **AI Reference**: Use documents as context for AI-assisted development

## File Reference Summary

| Document | Template Path | Output Location |
|----------|---------------|-----------------|
| product.md | src/markdown/templates/product-template.md | Project root |
| tech.md | src/markdown/templates/tech-template.md | Project root |
| structure.md | src/markdown/templates/structure-template.md | Project root |

## Related Components

- **Prompt Generator:** `src/prompts/create-steering-doc.ts` - Generates prompts for AI document creation
- **Steering Guide:** `src/tools/steering-guide.ts` - Core tool for document management
- **VSCode Extension:** `vscode-extension/src/webview/App.tsx` - UI for document interaction
- **Dashboard Frontend:** `src/dashboard_frontend/src/modules/pages/SteeringPage.tsx` - Web dashboard integration

---

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

## Web Dashboard

### 相关页面

相关主题：[VSCode Extension](#vscode-extension), [Docker Deployment](#docker-deployment), [System Architecture](#architecture)

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

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

- [src/server.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/server.ts)
- [src/dashboard/watcher.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/watcher.ts)
- [src/dashboard_frontend/src/modules/app/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/app/App.tsx)
- [src/dashboard_frontend/src/modules/ws/WebSocketProvider.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/ws/WebSocketProvider.tsx)
- [src/dashboard_frontend/src/modules/mdx-editor/MDXEditorWrapper.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/mdx-editor/MDXEditorWrapper.tsx)
- [src/dashboard_frontend/src/i18n.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/i18n.ts)
- [containers/docker-compose.yml](https://github.com/Pimzino/spec-workflow-mcp/blob/main/containers/docker-compose.yml)
</details>

# Web Dashboard

The Web Dashboard is the primary user interface for the spec-workflow-mcp system. It provides a real-time, visual interface for monitoring project specifications, tracking task progress, reviewing implementation logs, and managing automated workflows across all connected projects.

## Overview

The dashboard serves as a centralized monitoring and management hub that complements the MCP (Model Context Protocol) server functionality. While the MCP server handles code execution and specification enforcement, the dashboard offers:

- **Real-time monitoring** of spec files and implementation progress
- **Visual task tracking** with filtering and completion indicators
- **Implementation log visualization** with file change statistics
- **Automated cleanup job management** with execution history
- **Multi-project support** via WebSocket connections

The dashboard runs as a separate service (default port 5000) and communicates with connected projects through a file-watching system and WebSocket connections 资料来源：[README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md).

## Architecture

### System Components

```mermaid
graph TD
    A[Browser Client] <-->|HTTP/WebSocket| B[Dashboard Server :5000]
    B <-->|File System Events| C[.spec-workflow Directory]
    B <-->|WebSocket| D[VSCode Extension Webview]
    C <-->|File Watching| E[Project Specs]
    C <-->|File Watching| F[Steering Documents]
    C <-->|File Watching| G[Implementation Logs]
```

### Frontend Architecture

The dashboard frontend is a React-based single-page application located in `src/dashboard_frontend/`. It uses a modular structure:

```
src/dashboard_frontend/
├── src/
│   ├── modules/
│   │   ├── app/App.tsx           # Main application shell
│   │   ├── pages/               # Page components
│   │   │   ├── SettingsPage.tsx
│   │   │   ├── TasksPage.tsx
│   │   │   ├── LogsPage.tsx
│   │   │   └── JobExecutionHistory.tsx
│   │   ├── ws/                   # WebSocket integration
│   │   │   └── WebSocketProvider.tsx
│   │   └── mdx-editor/           # MDX editing capabilities
│   │       └── MDXEditorWrapper.tsx
│   └── i18n.ts                   # Internationalization
```

The `WebSocketProvider` establishes and maintains a persistent connection to the dashboard server, enabling real-time updates without page refreshes 资料来源：[src/dashboard_frontend/src/modules/ws/WebSocketProvider.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/ws/WebSocketProvider.tsx).

### Backend Server

The server is implemented in `src/server.ts` and provides:

- Express.js HTTP server for static file serving
- WebSocket server for real-time client communication
- File system watcher integration
- REST API endpoints for project data retrieval

## Pages and Features

### Overview Page

The landing page displays project statistics aggregated from all connected projects:

| Metric | Description |
|--------|-------------|
| Active Specs | Number of currently active specification files |
| Archived Specs | Count of completed/archived specifications |
| Total Specs | Overall count of specification documents |
| Tasks | Completed vs total tasks with progress percentage |

The overview uses progress bars to visualize completion status and shows recent activity feed 资料来源：[vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx).

### Tasks Page

The tasks page provides comprehensive task management capabilities:

- **Filtering controls** for narrowing down task lists
- **View mode switcher** between list and other display formats
- **Progress visualization** with percentage indicators
- **Task status indicators** (in-progress, blocked, completed)

Tasks display metadata including leverage scores and AI prompts when available, with expandable sections for detailed information 资料来源：[src/dashboard_frontend/src/modules/pages/TasksPage.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/TasksPage.tsx).

### Logs Page

Implementation logs are displayed with comprehensive statistics:

```mermaid
graph LR
    A[File Change Event] --> B[Log Entry Created]
    B --> C[Statistics Calculated]
    C --> D[Markdown Rendered]
    D --> E[Client Displayed]
```

Log entries include:

- **Statistics**: Lines added/removed, files changed, net change
- **Files Modified**: List with syntax-highlighted file paths
- **Files Created**: Newly created files in the project
- **Artifacts**: API endpoints, components, functions, and classes documented during implementation

资料来源：[src/dashboard_frontend/src/modules/pages/LogsPage.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/LogsPage.tsx).

### Settings Page

The settings page manages automated cleanup jobs:

- Section-based layout with expandable/collapsible panels
- Job configuration controls
- Loading states with spinner indicators
- Error handling with styled alert boxes

The automated cleanup section allows management of jobs that run across all connected projects 资料来源：[src/dashboard_frontend/src/modules/pages/SettingsPage.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/SettingsPage.tsx).

### Job Execution History

A dedicated panel displays execution statistics:

| Metric | Description |
|--------|-------------|
| Total Runs | Number of job executions |
| Success Rate | Percentage of successful runs with color coding |

Success rates are color-coded: green for 100%, yellow for 50-99%, and red for below 50% 资料来源：[src/dashboard_frontend/src/modules/pages/JobExecutionHistory.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/pages/JobExecutionHistory.tsx).

## Real-time Updates

### WebSocket Communication

The dashboard uses WebSocket for bidirectional real-time communication:

1. **Connection establishment**: Client connects to `/ws` endpoint
2. **Project updates**: Server pushes spec and task changes immediately
3. **Language preferences**: Users can change language with instant UI update

The WebSocket provider handles message routing and maintains connection state:

```typescript
// Message types supported
type MessageType = 
  | 'specs-updated'    // Spec files changed
  | 'tasks-updated'    // Task status changed
  | 'language-changed' // UI language update
```

资料来源：[src/dashboard_frontend/src/modules/ws/WebSocketProvider.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard_frontend/src/modules/ws/WebSocketProvider.tsx).

### File Watching

The watcher system monitors the `.spec-workflow` directory:

```mermaid
sequenceDiagram
    participant FS as File System
    participant Watcher as Watcher Service
    participant Server as Dashboard Server
    participant WS as WebSocket Clients
    
    FS->>Watcher: File change detected
    Watcher->>Server: Process change
    Server->>WS: Broadcast update
    WS->>Client: Trigger re-render
```

When spec files, steering documents, or implementation logs change, the watcher triggers updates to all connected clients 资料来源：[src/dashboard/watcher.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/src/dashboard/watcher.ts).

## Internationalization

The dashboard supports multiple languages through `src/dashboard_frontend/src/i18n.ts`. All user-facing strings are externalized and can be translated. Language changes are propagated to all connected clients via WebSocket.

Supported translations in the repository include:

- English (default)
- Korean (README.ko.md)
- French (README.fr.md)
- German
- Portuguese
- Russian
- Italian
- Arabic

## MDX Editor Integration

The `MDXEditorWrapper` component provides in-browser editing capabilities for specification documents. This allows users to:

- Edit spec files directly in the browser
- Preview rendered markdown
- Auto-save changes to the file system

## Deployment Options

### Standalone Server

Start the dashboard with the `--dashboard` flag:

```bash
npx -y @pimzino/spec-workflow-mcp@latest --dashboard
```

The server binds to `127.0.0.1:5000` by default, preventing network exposure 资料来源：[README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md).

### Docker Deployment

Docker deployment provides isolated execution:

```yaml
# containers/docker-compose.yml
services:
  dashboard:
    build: 
      context: .
      dockerfile: containers/Dockerfile
    ports:
      - "5000:5000"
    volumes:
      - ./workspace/.spec-workflow:/workspace/.spec-workflow:rw
```

资料来源：[containers/docker-compose.yml](https://github.com/Pimzino/spec-workflow-mcp/blob/main/containers/docker-compose.yml).

## Security Features

The dashboard implements enterprise-grade security:

| Feature | Implementation |
|---------|----------------|
| Localhost Binding | Binds to `127.0.0.1` by default |
| Rate Limiting | 120 requests/minute per client |
| Security Headers | X-Content-Type-Options, X-Frame-Options, CSP |
| CORS Protection | Restricted cross-origin access |

资料来源：[README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md).

## VSCode Extension Integration

The VSCode extension embeds the dashboard as a webview, providing:

- In-editor dashboard access
- Seamless integration with the development environment
- Real-time updates within VSCode

The webview uses the same React components as the standalone dashboard but is packaged for VSCode's webview API 资料来源：[vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx).

## Configuration

The dashboard behavior is configured through the project's `.spec-workflow/config.toml`:

```toml
[dashboard]
port = 5000
host = "127.0.0.1"
```

Multiple projects can connect to a single dashboard instance, allowing centralized monitoring across a development environment.

---

<a id='vscode-extension'></a>

## VSCode Extension

### 相关页面

相关主题：[Web Dashboard](#web-dashboard), [Approval Workflow System](#approval-workflow)

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

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

- [vscode-extension/package.json](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/package.json)
- [vscode-extension/src/extension.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/extension.ts)
- [vscode-extension/src/extension/providers/SidebarProvider.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/extension/providers/SidebarProvider.ts)
- [vscode-extension/src/extension/services/ApprovalCommandService.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/extension/services/ApprovalCommandService.ts)
- [vscode-extension/src/extension/services/ApprovalEditorService.ts](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/extension/services/ApprovalEditorService.ts)
- [vscode-extension/src/webview/App.tsx](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/src/webview/App.tsx)
- [vscode-extension/README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/vscode-extension/README.md)
</details>

# VSCode Extension

## Overview

The spec-workflow-mcp VSCode Extension provides an integrated development experience for managing specification-based workflows directly within Visual Studio Code. It serves as the recommended interface option for VSCode users, offering a native sidebar panel, approval management tools, and real-time project monitoring capabilities.

资料来源：[vscode-extension/README.md]()

### Purpose and Scope

The extension complements the CLI-based web dashboard by providing:

- **Inline project management** - View and manage specs without leaving the editor
- **Approval workflow integration** - Review, approve, or reject specification changes
- **Task tracking** - Monitor implementation progress across specs and tasks
- **Implementation logging** - Track code artifacts generated during development
- **Multi-project support** - Connect to multiple specification projects simultaneously

资料来源：[vscode-extension/src/extension.ts]()

## Architecture

### Component Overview

The extension follows a modular architecture with clear separation between VSCode integration layers and UI components.

```mermaid
graph TD
    subgraph "VSCode Host Layer"
        EXT[extension.ts]
        SIDEBAR[SidebarProvider]
        CMDS[ApprovalCommandService]
        EDITOR[ApprovalEditorService]
    end
    
    subgraph "Webview Layer"
        APP[App.tsx]
        LOGS[LogsPage]
        TASKS[TasksPage]
        CARDS[LogEntryCard]
        MODAL[comment-modal]
    end
    
    subgraph "Communication"
        MSG[vscode.postMessage]
        EVENTS[Event System]
    end
    
    EXT --> SIDEBAR
    SIDEBAR --> MSG
    MSG --> APP
    APP --> LOGS
    APP --> TASKS
    APP --> CARDS
    LOGS --> MODAL
    CARDS --> MODAL
    
    CMDS --> EVENTS
    EDITOR --> EVENTS
    EVENTS --> MSG
```

### Directory Structure

```
vscode-extension/
├── package.json                    # Extension manifest and configuration
├── src/
│   ├── extension.ts                # Entry point, registers commands and providers
│   ├── extension/
│   │   ├── providers/
│   │   │   └── SidebarProvider.ts  # Sidebar webview container management
│   │   └── services/
│   │       ├── ApprovalCommandService.ts   # Command execution logic
│   │       └── ApprovalEditorService.ts    # Editor-related operations
│   └── webview/
│       ├── App.tsx                 # Main webview application
│       ├── components/
│       │   └── LogEntryCard.tsx    # Implementation log entry display
│       ├── pages/
│       │   ├── LogsPage.tsx        # Implementation logs view
│       │   └── TasksPage.tsx       # Task management view
│       ├── comment-modal.tsx       # Comment input modal
│       ├── comment-modal.html      # Modal HTML template
│       └── globals.css             # Global styles
└── webview-dist/                   # Compiled webview assets
    ├── comment-modal.js
    ├── i18n.js
    └── globals.css
```

资料来源：[vscode-extension/package.json]()

## Core Components

### Extension Entry Point

The `extension.ts` file serves as the main entry point for the VSCode extension. It performs the following initialization tasks:

1. **Command Registration** - Registers VSCode commands for approval actions
2. **Sidebar Provider Registration** - Establishes the sidebar webview container
3. **Event Listeners** - Sets up communication between VSCode and webviews

资料来源：[vscode-extension/src/extension.ts]()

### SidebarProvider

The `SidebarProvider` class manages the lifecycle of the sidebar webview panel.

| Method | Purpose |
|--------|---------|
| `resolveWebviewView()` | Initializes and configures the webview |
| `dispose()` | Cleans up resources when sidebar closes |
| `postMessage()` | Sends messages to the webview |
| `handleMessage()` | Processes messages from webview |

The provider implements the `WebviewViewProvider` interface and creates a webview with:

- **Local resource roots** - Access to extension's local file resources
- **Scripts enabled** - JavaScript execution for interactivity
- **State persistence** - Maintains view state across sessions

资料来源：[vscode-extension/src/extension/providers/SidebarProvider.ts]()

### ApprovalCommandService

This service handles command execution related to the approval workflow system.

| Method | Description |
|--------|-------------|
| `executeCommand()` | Executes registered VSCode commands |
| `getApprovalList()` | Retrieves pending approvals |
| `submitApproval()` | Submits approval decision |
| `submitRejection()` | Submits rejection with reason |
| `undoDecision()` | Reverts previous approval/rejection |

资料来源：[vscode-extension/src/extension/services/ApprovalCommandService.ts]()

### ApprovalEditorService

The `ApprovalEditorService` manages editor-related operations for reviewing specification changes.

| Method | Purpose |
|--------|---------|
| `openDiffViewer()` | Opens built-in diff editor for spec comparisons |
| `getCurrentDocument()` | Retrieves active document content |
| `highlightChanges()` | Applies decorations to changed regions |
| `createSnapshot()` | Creates versioned snapshots of spec state |

资料来源：[vscode-extension/src/extension/services/ApprovalEditorService.ts]()

## Webview UI

### App Component

The `App.tsx` serves as the main container for the sidebar webview, organizing content into logical sections.

```typescript
interface ProjectStats {
  activeSpecs: number;      // Total specs in active development
  completedSpecs: number;   // Fully approved specs
  archivedSpecs: number;    // Archived specifications
  totalSpecs: number;       // Combined total
  totalTasks: number;       // All tasks across specs
  completedTasks: number;   // Completed implementation tasks
}
```

资料来源：[vscode-extension/src/webview/App.tsx]()

### Project Overview Card

Displays aggregate statistics about the connected project:

- **Active Specs** - Shows `completedSpecs / activeSpecs` ratio
- **Archived Specs** - Count of archived specifications
- **Total Specs** - Combined specification count
- **Tasks** - Shows `completedTasks / totalTasks` progress

资料来源：[vscode-extension/src/webview/App.tsx]()

### TasksPage

The tasks view renders individual specification tasks with the following metadata:

| Field | Description | UI Indicator |
|-------|-------------|--------------|
| `purposes` | List of task objectives | Bullet list |
| `requirements` | Technical requirements | Orange label |
| `leverage` | Code patterns to reuse | Cyan badge |
| `prompt` | AI instruction text | Collapsible section |

资料来源：[src/dashboard_frontend/src/modules/pages/TasksPage.tsx]()

### LogEntryCard

Displays implementation log entries with artifact tracking:

```typescript
interface ImplementationLogEntry {
  id: string;
  timestamp: string;
  message: string;
  filesModified: string[];
  filesCreated: string[];
  artifacts: {
    apiEndpoints: ApiEndpoint[];
    components: Component[];
    functions: Function[];
    classes: Class[];
    integrations: Integration[];
  };
  statistics?: {
    linesAdded: number;
    linesRemoved: number;
  };
}
```

资料来源：[vscode-extension/src/webview/components/LogEntryCard.tsx]()

### Artifact Sections

Each artifact type has a dedicated display section:

| Artifact Type | Icon | Color | Properties Displayed |
|--------------|------|-------|----------------------|
| API Endpoints | GlobeAltIcon | Blue | Method, Path, Purpose, Location, Formats |
| Components | CubeIcon | Purple | Name, Type, Purpose, Props, Exports |
| Functions | CodeBracketSquareIcon | Green | Name, Purpose, Location, Signature, Exported |
| Classes | CircleStackIcon | Orange | Name, Purpose, Location, Methods, Exported |
| Integrations | LinkIcon | - | Description, Frontend, Backend, Data Flow |

资料来源：[src/dashboard_frontend/src/modules/pages/LogsPage.tsx]()

### Comment Modal

The comment modal provides a dialog for adding notes to approvals:

**HTML Template Structure:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Add Comment</title>
</head>
<body>
  <div id="root"></div>
  <script type="module" src="./comment-modal.tsx"></script>
</body>
</html>
```

**Compiled Version:**
```html
<script type="module" crossorigin src="/comment-modal.js"></script>
<link rel="modulepreload" crossorigin href="/i18n.js">
<link rel="stylesheet" crossorigin href="/globals.css">
```

资料来源：[vscode-extension/src/webview/comment-modal.html]()
资料来源：[vscode-extension/webview-dist/comment-modal.html]()

## Communication Protocol

### Message Flow

The extension uses VSCode's `postMessage` API for bidirectional communication between the host and webview.

```mermaid
sequenceDiagram
    participant User
    participant Webview
    participant VSCode
    participant Backend
    
    User->>Webview: Click action
    Webview->>VSCode: postMessage({ type, payload })
    VSCode->>Backend: HTTP API call
    Backend-->>VSCode: JSON response
    VSCode-->>Webview: WebviewPanel.webview.postMessage()
    Webview-->>User: Updated UI
```

### Message Types

| Direction | Message Type | Purpose |
|-----------|--------------|---------|
| Webview → VSCode | `OPEN_APPROVAL` | Open approval detail view |
| Webview → VSCode | `SUBMIT_DECISION` | Submit approval/rejection |
| Webview → VSCode | `ADD_COMMENT` | Add comment to approval |
| VSCode → Webview | `UPDATE_STATS` | Refresh project statistics |
| VSCode → Webview | `APPROVAL_UPDATED` | Approval state change notification |

## Configuration

### Extension Settings

The extension supports project-specific configuration through TOML files:

```toml
# .spec-workflow/config.example.toml
[project]
name = "my-project"
dashboard_url = "http://localhost:5000"
auto_refresh = true
refresh_interval = 30
```

### VSCode Configuration

```json
{
  "spec-workflow.projectPath": "/path/to/project",
  "spec-workflow.dashboardUrl": "http://localhost:5000",
  "spec-workflow.autoRefresh": true
}
```

## Integration with Dashboard

The VSCode extension operates independently from the web dashboard while sharing the same backend API:

```mermaid
graph LR
    subgraph "Development Environment"
        VSCODE[VSCode Extension]
        WEBVIEW[Sidebar Webview]
    end
    
    subgraph "Backend Services"
        API[REST API]
        FILES[File System]
    end
    
    VSCODE --> API
    WEBVIEW --> API
    API --> FILES
    
    subgraph "Optional Services"
        DASHBOARD[Web Dashboard]
    end
    
    API <--> DASHBOARD
```

**Key Points:**
- Only one dashboard instance is needed per machine
- All projects connect to the same dashboard
- VSCode extension can work standalone with direct file access
- Approval actions sync across both interfaces

资料来源：[vscode-extension/README.md]()

## Installation

### From VSCode Marketplace

1. Open VSCode
2. Navigate to Extensions (`Ctrl+Shift+X` / `Cmd+Shift+X`)
3. Search for "spec-workflow"
4. Click Install

### From Command Line

```bash
code --install-extension pimzino.spec-workflow
```

### Configuration Required

After installation, configure the project path in VSCode settings:

```json
{
  "spec-workflow.projectPath": "/absolute/path/to/your/project"
}
```

资料来源：[vscode-extension/README.md]()

## Feature Comparison

| Feature | Web Dashboard | VSCode Extension |
|---------|--------------|------------------|
| Interface | Browser-based | Native sidebar |
| Launch command | `npx @pimzino/spec-workflow-mcp@latest --dashboard` | VSCode Extension button |
| Approval management | Full support | Full support |
| Task viewing | Yes | Yes |
| Implementation logs | Yes | Yes |
| Inline editing | Limited | Yes |
| Editor integration | No | Yes (diff viewer) |
| Project switching | URL-based | Dropdown menu |

## Extension Commands

The extension registers the following VSCode commands:

| Command ID | Description | Shortcut |
|------------|-------------|----------|
| `spec-workflow.refresh` | Refresh project data | `Ctrl+Shift+R` |
| `spec-workflow.openDashboard` | Open web dashboard | `Ctrl+Shift+D` |
| `spec-workflow.approveAll` | Approve all pending specs | - |
| `spec-workflow.showApproval` | Show approval detail | - |
| `spec-workflow.addComment` | Add comment to selection | - |

资料来源：[vscode-extension/src/extension.ts]()

## Dependencies

The extension depends on the following packages:

| Package | Version | Purpose |
|---------|---------|---------|
| `@vscode/webview-ui-toolkit` | ^1.2.0 | Webview UI components |
| `@spec-workflow/core` | workspace:* | Core shared logic |
| `react` | ^18.2.0 | UI framework |
| `tailwindcss` | ^3.4.0 | Styling |

资料来源：[vscode-extension/package.json]()

## Troubleshooting

### Sidebar Not Loading

1. Verify project path is correctly configured
2. Check that `.spec-workflow/` directory exists in project root
3. Run "Developer: Reload Window" command

### API Connection Errors

1. Ensure web dashboard is running (if using shared backend)
2. Check `spec-workflow.dashboardUrl` setting
3. Verify network connectivity

### Webview Scripts Blocked

The webview requires script execution. If scripts are blocked:

1. Check `webview.csp` setting in VSCode
2. Ensure no security policies are preventing execution

资料来源：[vscode-extension/README.md]()
</details>

---

<a id='docker-deployment'></a>

## Docker Deployment

### 相关页面

相关主题：[Web Dashboard](#web-dashboard)

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

The following source files were used to generate this documentation page:

- [containers/Dockerfile](https://github.com/Pimzino/spec-workflow-mcp/blob/main/containers/Dockerfile)
- [containers/docker-compose.yml](https://github.com/Pimzino/spec-workflow-mcp/blob/main/containers/docker-compose.yml)
- [containers/README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/containers/README.md)
- [containers/DOCKER_USAGE.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/containers/DOCKER_USAGE.md)
- [README.md](https://github.com/Pimzino/spec-workflow-mcp/blob/main/README.md)
</details>

# Docker Deployment

## Overview

The spec-workflow-mcp project provides a containerized dashboard deployment option for isolated and secure execution in Docker environments. This deployment method is designed for users who prefer not to install Node.js locally or require a self-contained, portable solution for running the specification workflow management system.

The Docker deployment bundles the Node.js runtime (version 24-alpine), the dashboard application, and all required dependencies into a single image that can be run consistently across different host systems.

## Architecture

```mermaid
graph TD
    A[User Host Machine] -->|HTTP Requests| B[Docker Container]
    B -->|Port Mapping| C[Dashboard Application]
    C -->|Volume Mount| D[.spec-workflow Directory]
    
    E[Docker Networking] -->|Security Control| F[127.0.0.1:5000:5000]
    E -->|Optional External| G[0.0.0.0:5000:5000]
    
    style C fill:#f9f,stroke:#333,stroke-width:2px
    style D fill:#ff9,stroke:#333,stroke-width:2px
```

### Container Components

| Component | Description |
|-----------|-------------|
| **Base Image** | `node:24-alpine` - Minimal Node.js runtime |
| **Application User** | `node` (UID 1000) - Non-root execution |
| **Dashboard Port** | 5000 (default) - Internal container port |
| **State Directory** | `/workspace/.spec-workflow` - Project state location |
| **Audit Log** | `<project>/.spec-workflow/audit.log` - JSON logging |

## Quick Start

### Building the Image

```bash
# Build using Docker CLI
docker build -f containers/Dockerfile -t spec-workflow-mcp .

# Verify the image was created
docker images spec-workflow-mcp
```

### Running the Container

```bash
# Basic run with default settings
docker run -p 5000:5000 \
  -v "./workspace/.spec-workflow:/workspace/.spec-workflow:rw" \
  spec-workflow-mcp
```

The dashboard becomes accessible at: `http://localhost:5000` 资料来源：[README.md:1-10]()

## Docker Compose Deployment

Docker Compose is the recommended deployment method as it provides additional security hardening and simplified management.

### Default Configuration

Create a `.env` file for environment configuration:

```bash
# .env file
DASHBOARD_PORT=5000
SPEC_WORKFLOW_PATH=./workspace
```

Start the dashboard:

```bash
cd containers
docker-compose up --build
```

### Management Commands

```bash
# Start in detached mode
docker-compose up -d

# View logs
docker-compose logs -f

# Stop the dashboard
docker-compose down

# Rebuild and restart
docker-compose up --build
```

## Configuration Options

### Environment Variables

| Variable | Default (Docker) | Description |
|----------|------------------|-------------|
| `DASHBOARD_PORT` | `5000` | Port on which the dashboard runs |
| `DASHBOARD_HOST` | `127.0.0.1` | Host IP for port binding |
| `SPEC_WORKFLOW_PATH` | `/workspace` | Path to project directory (inside container) |
| `SPEC_WORKFLOW_BIND_ADDRESS` | `0.0.0.0` | IP address to bind inside container |
| `SPEC_WORKFLOW_ALLOW_EXTERNAL_ACCESS` | `true` | External access control |
| `SPEC_WORKFLOW_RATE_LIMIT_ENABLED` | `true` | Enable/disable rate limiting |
| `SPEC_WORKFLOW_CORS_ENABLED` | `true` | Enable/disable CORS |
| `SPEC_WORKFLOW_HOME` | - | Global state directory for sandboxed environments |

资料来源：[containers/README.md:80-100]()

### Custom Port Configuration

```bash
# Using Docker CLI
docker run -p 8080:8080 \
  -e DASHBOARD_PORT=8080 \
  -v "./workspace/.spec-workflow:/workspace/.spec-workflow:rw" \
  spec-workflow-mcp
```

### Volume Mounts

The dashboard requires read-write access to the `.spec-workflow` directory:

```bash
-v "/path/to/project/.spec-workflow:/workspace/.spec-workflow:rw"
```

**Important Notes:**
- The volume mount must be read-write (`:rw`) for the dashboard to function properly
- Only the `.spec-workflow` directory needs to be mounted
- The directory will be created automatically if it doesn't exist 资料来源：[containers/README.md:60-70]()

## Security Features

### Implemented Security Controls

The Docker image includes enterprise-grade security features suitable for corporate environments:

| Feature | Status | Description |
|---------|--------|-------------|
| **Non-root User** | ✅ Enabled | Runs as `node` user (UID 1000) |
| **Rate Limiting** | ✅ Enabled | 120 requests/minute per client |
| **Audit Logging** | ✅ Enabled | JSON logs with 30-day retention |
| **Security Headers** | ✅ Enabled | XSS, clickjacking, MIME sniffing protection |
| **CORS Protection** | ✅ Enabled | Localhost origins only by default |
| **Localhost Binding** | ✅ Default | `127.0.0.1:5000:5000` in docker-compose |
| **Read-only Filesystem** | ✅ Available | `read_only: true` in compose |
| **Capability Dropping** | ✅ Enabled | All Linux capabilities dropped |

### Network Security Models

```mermaid
graph LR
    A[Localhost Only] -->|127.0.0.1:5000:5000| B[Recommended - Secure]
    C[Network Access] -->|0.0.0.0:5000:5000| D[Available - Requires Firewall]
```

**Option 1: Localhost Only (Secure Default)**

The default `docker-compose.yml` uses localhost-only port mapping:

```yaml
ports:
  - "127.0.0.1:5000:5000"  # Only accessible from host machine
```

Or with Docker CLI:

```bash
docker run -p 127.0.0.1:5000:5000 \
  -v "./workspace/.spec-workflow:/workspace/.spec-workflow:rw" \
  spec-workflow-mcp
```

**Option 2: Network Access (Exposes to Network)**

```bash
docker run -p 5000:5000 \
  -v "./workspace/.spec-workflow:/workspace/.spec-workflow:rw" \
  spec-workflow-mcp
```

⚠️ **Security Warning:** This configuration exposes the dashboard to your network. The application displays a security warning in the logs. Only use when necessary and ensure proper network security measures (firewall, VPN) are in place. 资料来源：[containers/README.md:110-140]()

### Docker Compose Security Hardening

The provided `docker-compose.yml` includes additional security settings:

```yaml
# Read-only root filesystem
read_only: true

# Drop all Linux capabilities
cap_drop:
  - ALL

# Prevent privilege escalation
security_opt:
  - no-new-privileges:true

# Resource limits (prevent DoS)
deploy:
  resources:
    limits:
      cpus: '1.0'
      memory: 512M
```

### Best Practices

1. **Use localhost port mapping** when possible (`127.0.0.1:5000:5000`)
2. **Never expose to public internet** without proper authentication/firewall
3. **Keep rate limiting enabled** in production
4. **Use the provided docker-compose.yml** for security hardening
5. **Run as non-root user** (default in the image)
6. **Mount volumes read-write only when necessary** 资料来源：[containers/README.md:150-165]()

## Audit Logging

All API requests are logged to a structured JSON audit log for compliance and debugging.

### Log Location

```
<project>/.spec-workflow/audit.log
```

### Log Format

```json
{
  "timestamp": "2025-12-06T10:30:45.123Z",
  "actor": "127.0.0.1",
  "action": "GET /api/projects/list",
  "resource": "/api/projects/list",
  "result": "success",
  "details": {
    "statusCode": 200,
    "duration": 45,
    "userAgent": "Mozilla/5.0..."
  }
}
```

### Viewing Logs

```bash
# View recent logs
tail -f .spec-workflow/audit.log

# Parse as JSON (requires jq)
cat .spec-workflow/audit.log | jq '.'

# Filter by result
cat .spec-workflow/audit.log | jq 'select(.result == "denied")'
```

## Advanced Configuration

### Auto-Restart on Failure

```bash
docker run -d \
  --name spec-workflow-dashboard \
  --restart unless-stopped \
  -p 5000:5000 \
  -v "./workspace/.spec-workflow:/workspace/.spec-workflow:rw" \
  spec-workflow-mcp
```

### Health Checks

The dashboard does not currently include built-in health checks. You can verify connectivity manually:

```bash
curl http://localhost:5000
```

### Testing the Docker Image

A comprehensive test script validates Docker image configurations:

```bash
# From the containers directory
./test-docker.sh
```

| Test | Description |
|------|-------------|
| **Image Build** | Verifies the Docker image builds successfully |
| **Docker Default Config** | Tests app binding to 0.0.0.0, Docker exposing to localhost |
| **Security Check** | Verifies app-level security block |
| **Network Exposure** | Tests full network port mapping |
| **Rate Limiting** | Verifies rate limiting configuration |
| **Non-Root User** | Confirms container runs as non-privileged user |
| **Custom Port** | Tests custom port configuration |

资料来源：[README.md:50-75]()

## Troubleshooting

### Container Does Not Start

**Error:** Container exits immediately after starting

**Solutions:**
- Check logs: `docker logs <container-id>`
- Verify volume mount path exists and is correct
- Ensure port 5000 (or your configured port) is not already in use

### Cannot Connect to Dashboard

**Error:** Unable to access `http://localhost:5000`

**Solutions:**
- Verify container is running: `docker ps`
- Check port is properly mapped: `docker port <container-id>`
- Ensure firewall allows connections on the port

### Build Fails

**Error:** Build fails with COPY or dependency errors

**Solutions:**
- Build from repository root: `docker build -f containers/Dockerfile -t spec-workflow-mcp .`
- Verify all source files are present
- Confirm `package.json` and `package-lock.json` exist 资料来源：[containers/README.md:40-60]()

### Inspecting the Container

```bash
# View container details
docker inspect <container-id>

# Access container shell
docker exec -it <container-id> /bin/sh
```

## External Access with Authentication

The dashboard does not include built-in authentication. For external access scenarios, use a reverse proxy:

### nginx with Basic Auth

```nginx
server {
    listen 443 ssl;
    server_name dashboard.example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    auth_basic "Dashboard Access";
    auth_basic_user_file /etc/nginx/.htpasswd;
    
    location / {
        proxy_pass http://127.0.0.1:5000;
    }
}
```

## Sandbox Environments

For sandboxed environments (e.g., Codex CLI with `sandbox_mode=workspace-write`) where `$HOME` is read-only, use the `SPEC_WORKFLOW_HOME` environment variable to redirect global state files to a writable location:

```bash
SPEC_WORKFLOW_HOME=/workspace/.spec-workflow-mcp npx -y @pimzino/spec-workflow-mcp@latest /workspace
```

This approach works similarly in Docker:

```bash
docker run -p 5000:5000 \
  -e SPEC_WORKFLOW_HOME=/workspace/.spec-workflow-mcp \
  -v "/path/to/project:/workspace" \
  spec-workflow-mcp
```

资料来源：[README.md:100-110]()

## Security Comparison Table

| Security Feature | Docker CLI Default | Docker Compose | Notes |
|-----------------|-------------------|----------------|-------|
| Port Binding | `5000:5000` (exposed) | `127.0.0.1:5000:5000` (localhost) | Compose is more secure |
| Root Filesystem | Read-write | Read-only (`read_only: true`) | Prevents container escape |
| Capabilities | Default | Dropped (`cap_drop: ALL`) | Reduces attack surface |
| Privilege Escalation | Allowed | Blocked (`no-new-privileges`) | Hardens against exploits |
| Resource Limits | None | CPU/Memory limits | Prevents DoS |

## See Also

- [Configuration Guide](../docs/CONFIGURATION.md) - Additional configuration options
- [Interfaces Guide](../docs/INTERFACES.md) - Dashboard and VSCode extension details
- [Development Guide](../docs/DEVELOPMENT.md) - Local development setup
- [Troubleshooting](../docs/TROUBLESHOOTING.md) - Common issues and solutions

---

---

## Doramagic 踩坑日志

项目：Pimzino/spec-workflow-mcp

摘要：发现 11 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：[Bug]: approval categoryName path traversal writes outside approvals directory。

## 1. 安装坑 · 来源证据：[Bug]: approval categoryName path traversal writes outside approvals directory

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

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

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

## 3. 配置坑 · 来源证据：[Bug]: Bug Report for spec-workflow-mcp

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Bug]: Bug Report for spec-workflow-mcp
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2224eccf9467459da3e19254a796753a | https://github.com/Pimzino/spec-workflow-mcp/issues/218 | 来源类型 github_issue 暴露的待验证使用条件。

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

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

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

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

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

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

## 7. 安全/权限坑 · 存在安全注意事项

- 严重度：medium
- 证据强度：source_linked
- 发现：No sandbox install has been executed yet; downstream must verify before user use.
- 对用户的影响：用户安装前需要知道权限边界和敏感操作。
- 建议检查：转成明确权限清单和安全审查提示。
- 防护动作：安全注意事项必须面向用户前置展示。
- 证据：risks.safety_notes | github_repo:1033865617 | https://github.com/Pimzino/spec-workflow-mcp | No sandbox install has been executed yet; downstream must verify before user use.

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

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

## 9. 安全/权限坑 · 来源证据：[Bug]: Improper Validation of FilePaths Enabling Arbitrary File Reads

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug]: Improper Validation of FilePaths Enabling Arbitrary File Reads
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_763384ba6d384832ada894b2c653b77b | https://github.com/Pimzino/spec-workflow-mcp/issues/201 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

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

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

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

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

<!-- canonical_name: Pimzino/spec-workflow-mcp; human_manual_source: deepwiki_human_wiki -->
