# https://github.com/engincankaya/blueprint 项目说明书

生成时间：2026-05-16 00:06:34 UTC

## 目录

- [Blueprint Introduction](#page-blueprint-introduction)
- [CLI and Command Usage](#page-cli-usage)
- [System Architecture](#page-system-architecture)
- [MCP Server Implementation](#page-mcp-server)
- [Scan Tool](#page-scan-tool)
- [Group Tool](#page-group-tool)
- [Compose Tool](#page-compose-tool)
- [Refresh Tool](#page-refresh-tool)
- [Task Context Tool](#page-task-context-tool)
- [Viewer Frontend](#page-viewer-frontend)

<a id='page-blueprint-introduction'></a>

## Blueprint Introduction

### 相关页面

相关主题：[CLI and Command Usage](#page-cli-usage), [System Architecture](#page-system-architecture)

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

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

- [README.md](https://github.com/engincankaya/blueprint/blob/main/README.md)
- [AGENTS.md](https://github.com/engincankaya/blueprint/blob/main/AGENTS.md)
- [src/lib/agent-instructions.ts](https://github.com/engincankaya/blueprint/blob/main/src/lib/agent-instructions.ts)
- [src/tools/scan/scan-file-inventory-builder.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-file-inventory-builder.ts)
- [src/tools/scan/scan-code-analysis-engine.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-code-analysis-engine.ts)
</details>

# Blueprint Introduction

Blueprint is a local architecture memory system designed to help developers and AI agents understand, navigate, and work effectively with software projects. It generates structured project graphs from source code, enabling faster orientation and more accurate context when making changes.

## Overview

Blueprint solves the common problem of diving into unfamiliar or complex codebases by creating a persistent, queryable layer of architectural knowledge. Rather than reading through thousands of files to understand a system, developers can leverage Blueprint's structured output to quickly identify relevant components, dependencies, and architectural patterns.

### Core Purpose

The primary goals of Blueprint are:

1. **Structured Project Graph Generation** - Automatically analyze codebase structure and generate organized representations of files, symbols, imports, and dependencies
2. **Architectural Memory Persistence** - Store architecture knowledge in a local `.blueprint/` directory that can be version-controlled or kept as local developer memory
3. **Agent-Friendly Orientation** - Provide AI agents with reliable starting points for understanding projects before diving into source code
4. **Deterministic Maintenance** - Keep architecture documentation synchronized with actual code through automated refresh workflows

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

## Architecture

### System Components

Blueprint consists of several integrated components that work together to analyze and document projects:

| Component | Purpose |
|-----------|---------|
| **Scan Engine** | Builds file inventory and performs code analysis |
| **Group Module** | Organizes files into semantic architectural groups |
| **Compose Module** | Generates final Blueprint output and Markdown documentation |
| **Viewer** | React-based UI for visualizing project architecture |
| **MCP Server** | Model Context Protocol integration for AI agent workflows |

资料来源：[README.md:40-60]()

### File Inventory System

The scan engine analyzes the codebase using a categorization system that classifies files into meaningful types:

```mermaid
graph TD
    A[File System] --> B[Scan Engine]
    B --> C{File Type Detection}
    C -->|Source Code| D[parseable]
    C -->|Config| E[config]
    C -->|Documentation| F[documentation]
    C -->|Test| G[test]
    C -->|Asset| H[asset]
    C -->|Lockfile| I[lockfile]
    C -->|Script| J[script]
```

The categorization logic uses path segment analysis and file extension matching:

```typescript
// From src/tools/scan/scan-file-inventory-builder.ts
if (segments.includes("test") || segments.includes("tests")) {
  return "test";
}
if (base.endsWith(".md") || language === "markdown") {
  return "documentation";
}
if (segments.includes("assets") || ["html", "css", "svg"].includes(language)) {
  return "asset";
}
```

资料来源：[src/tools/scan/scan-file-inventory-builder.ts:1-50]()

### Code Analysis Engine

The analysis engine performs deep parsing on supported languages to extract symbols, imports, and exports:

```typescript
// From src/tools/scan/scan-code-analysis-engine.ts
interface AnalysisFacts {
  inventoryArtifactId: string;
  rootPath: string;
  files: Record<string, FileFacts>;
  symbols: Record<string, SymbolFacts>;
  imports: Import[];
  exports: Export[];
  dependencies: Dependency[];
  parseErrors: ParseError[];
}
```

The engine tracks validation state to ensure complete analysis:

```typescript
interface Validation {
  isComplete: boolean;
  inventoryFiles: number;
  parseableFiles: number;
  parsedFiles: number;
  parseErrors: number;
  unaccountedFiles: string[];
}
```

资料来源：[src/tools/scan/scan-code-analysis-engine.ts:1-80]()

## Project Memory Structure

Blueprint stores architecture memory in a `.blueprint/` directory with the following structure:

### Generated Artifacts

| File | Purpose |
|------|---------|
| `brief.md` | Project overview, architectural groups, and routing hints |
| `groups/*.md` | Detailed documentation for each architectural group |
| `blueprint-output.json` | Structured project graph in JSON format |
| `refresh-scan.json` | Filesystem hash snapshot for deterministic refreshes |

资料来源：[README.md:25-35]()

### Group Documentation Template

Each group document follows a consistent structure:

- **Snapshot** - Quick orientation and high-level description
- **Responsibilities** - Ownership boundaries and out-of-scope areas
- **Core Flow** - Runtime behavior and data flow explanation
- **Contracts & Invariants** - Behavior that must not be broken
- **Key Files** - Main source files for the group
- **Change Guide** - Files or contracts that should change together
- **Pitfalls** - Known risks and common mistakes
- **Tests** - Most relevant verification points
- **Debugging** - Failure-mode hints
- **Extension / Open Questions** - Uncertainty and known gaps

资料来源：[AGENTS.md:40-65]()

## Workflows

### Initial Setup Workflow

```mermaid
graph LR
    A[blueprint scan] --> B[blueprint group mode: prepare]
    B --> C[Create grouping plan]
    C --> D[blueprint group mode: apply]
    D --> E[blueprint compose]
    E --> F[.blueprint/ memory created]
    F --> G[AGENTS.md patched]
```

To initialize Blueprint for a project:

1. Run `blueprint.scan` to build file inventory and code analysis
2. Run `blueprint.group` with `mode: "prepare"` to analyze grouping options
3. Create a compact grouping plan from the prepare output
4. Run `blueprint.group` with `mode: "apply"` to apply the grouping
5. Run `blueprint.compose` to write the final Blueprint output

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

### Maintenance Workflow

When project changes add, move, delete, or substantially change files:

```mermaid
graph TD
    A[Code Changes] --> B[Run blueprint.refresh]
    B --> C{New files unassigned?}
    C -->|Yes| D[Run blueprint.group.update]
    C -->|No| E[Update affected group docs]
    D --> E
    E --> F[Architecture docs synchronized]
```

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

## Blueprint Viewer

Blueprint includes a lightweight React/Vite viewer for visualizing project architecture.

### Viewing Generated Blueprint

To view a generated Blueprint:

```bash
blueprint open
```

This command:
1. Reads `.blueprint/blueprint-output.json` and `.blueprint/groups/*.md`
2. Writes a self-contained `.blueprint/index.html`
3. Opens it in the default browser

### Static Viewer Features

The viewer generates self-contained HTML with:
- Inline JavaScript
- Inline CSS
- Securely embedded JSON data

```mermaid
graph TD
    A[Blueprint Data] --> B[XSS/Content Escape]
    B --> C[<script type="application/json">]
    C --> D[Inline CSS/JS]
    D --> E[Self-contained HTML]
```

Data is embedded using `<script id="blueprint-data" type="application/json">` rather than `window.__BLUEPRINT_DATA__` for better security isolation.

资料来源：[README.md:90-105]()

## MCP Integration

Blueprint provides Model Context Protocol integration for AI agent workflows:

### Agent Instructions Snippet

The system automatically patches `AGENTS.md` with Blueprint-specific instructions:

```typescript
// From src/lib/agent-instructions.ts
export function renderBlueprintAgentsSnippet(): string {
  return [
    beginMarker,
    "## Blueprint MCP",
    "",
    "This project uses Blueprint MCP for local architecture memory.",
    "",
    "Before broad codebase exploration, read:",
    "",
    "`node_modules/blueprint-mcp-server/docs/agents.md`",
    "",
    "If Blueprint memory exists, start with:",
    "",
    "`.blueprint/brief.md`",
    "",
    endMarker,
  ].join("\n");
}
```

资料来源：[src/lib/agent-instructions.ts:1-30]()

### Agent Workflow Guidelines

When working with Blueprint-enabled projects, agents should:

1. Read `.blueprint/brief.md` for the project map
2. Identify the group or groups that may be relevant
3. Search Blueprint Markdown docs with task-specific keywords
4. Read only the smallest useful set of group documents
5. Inspect source code only where docs are insufficient

资料来源：[AGENTS.md:1-25]()

## Language Support

Blueprint uses Tree-sitter analysis for deep symbol/import extraction:

| Language | Support Level |
|----------|---------------|
| TypeScript / JavaScript | Full symbol analysis |
| Python | Full symbol analysis |
| Go | Full symbol analysis |
| Rust | Full symbol analysis |
| Java | Full symbol analysis |
| Other languages | Included in inventory, limited analysis |

资料来源：[README.md:125-135]()

## Source of Truth Principles

Blueprint memory is an orientation layer, not the authority:

> **Source code is the ground truth.**

If Blueprint docs conflict with source code, trust the source code. After changing source behavior, update the relevant Blueprint group doc if the memory became stale.

资料来源：[AGENTS.md:75-85]()

## Development

### Building and Testing

```bash
npm install
npm run build
npm run lint
npm test
```

### Working Rules

When making changes to Blueprint-enabled projects:

- Keep changes scoped to the user's task
- Prefer existing project patterns over new abstractions
- Add or update tests when behavior changes
- Run the smallest relevant verification first
- Do not edit generated files unless explicitly required
- Do not modify secrets, local environment files, or unrelated configuration

资料来源：[AGENTS.md:90-100]()

## Key Tools Reference

| Tool | Purpose |
|------|---------|
| `blueprint.scan` | Builds file inventory and code analysis artifacts |
| `blueprint.group` | Prepares or applies semantic file grouping |
| `blueprint.compose` | Writes the final Blueprint output and Markdown notes |
| `blueprint.refresh` | Refreshes Blueprint state from current filesystem |
| `blueprint.group.update` | Assigns unassigned files or manages empty groups |
| `blueprint open` | Opens the viewer in the default browser |

资料来源：[README.md:85-95]()

---

<a id='page-cli-usage'></a>

## CLI and Command Usage

### 相关页面

相关主题：[Blueprint Introduction](#page-blueprint-introduction), [MCP Server Implementation](#page-mcp-server)

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

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

- [README.md](https://github.com/engincankaya/blueprint/blob/main/README.md)
- [AGENTS.md](https://github.com/engincankaya/blueprint/blob/main/AGENTS.md)
- [todos_120526.md](https://github.com/engincankaya/blueprint/blob/main/todos_120526.md)
- [frontend/src/components/BlueprintApp.tsx](https://github.com/engincankaya/blueprint/blob/main/frontend/src/components/BlueprintApp.tsx)
- [src/tools/scan/scan-file-inventory-builder.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-file-inventory-builder.ts)
</details>

# CLI and Command Usage

Blueprint provides a command-line interface (CLI) for scanning code repositories, organizing files into semantic groups, and generating project documentation. The CLI is designed to work with MCP (Model Context Protocol) clients and supports a self-contained static viewer without requiring an HTTP server.

## Overview

The Blueprint CLI operates as a terminal-based tool that generates a structured project graph from source code. It focuses on code comprehension rather than modification, providing developers with an orientation layer that points to relevant source files without altering the project itself.

Blueprint's command suite handles the complete lifecycle from initial repository analysis to documentation generation:

| Tool | Purpose |
| --- | --- |
| `blueprint.scan` | Builds file inventory and code analysis artifacts |
| `blueprint.group` | Prepares or applies semantic file grouping |
| `blueprint.compose` | Writes the final Blueprint output and Markdown notes |
| `blueprint.refresh` | Refreshes Blueprint state from the current filesystem snapshot |
| `blueprint.group.update` | Assigns unassigned files or manages empty groups after refresh |

资料来源：[README.md:30-36]()

## Core Commands

### blueprint scan

The `scan` command performs initial repository analysis by building a file inventory and extracting code analysis artifacts. This command identifies all files in the project and categorizes them based on type, language, and path patterns.

```bash
blueprint scan
```

The scan process determines file categories using pattern matching:

| Category | Detection Criteria |
| --- | --- |
| `test` | Files ending with `.test.ts`, `.spec.ts`, or in `test/` directories |
| `lockfile` | `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `cargo.lock`, `poetry.lock` |
| `config` | `.gitignore`, `package.json`, `tsconfig.json`, config files |
| `documentation` | Files in `docs/` directory or ending with `.md` |
| `script` | Files in `scripts/` directory or `.sh` shell scripts |
| `asset` | Files in `assets/` or `public/` directories, SVG/CSS/HTML files |

资料来源：[src/tools/scan/scan-file-inventory-builder.ts:20-65]()

The scan command produces several artifacts stored in the `.blueprint/` directory:

| Artifact | Description |
| --- | --- |
| `file-inventory.json` | Complete list of all project files with metadata |
| `code-analysis.json` | Symbol definitions, imports, exports, and dependencies |
| `refresh-scan.json` | Filesystem hash snapshot for deterministic refreshes |

资料来源：[README.md:49-53]()

### blueprint group

The `group` command manages semantic file organization. It operates in two modes:

```bash
# Prepare mode: generates grouping suggestions
blueprint group --mode prepare

# Apply mode: commits the grouping plan
blueprint group --mode apply --plan <grouping-configuration>
```

#### Prepare Mode

In prepare mode, the tool analyzes the file inventory and generates a suggested grouping plan based on code relationships, shared dependencies, and functional areas. The output helps developers understand how files could be semantically organized without automatically applying changes.

#### Apply Mode

In apply mode, the tool takes a user-defined or tool-generated grouping plan and reorganizes the Blueprint's understanding of the codebase. The plan specifies which files belong to which groups and assigns roles (e.g., `core`, `support`, `test`) to files within each group.

资料来源：[README.md:30-36]()

### blueprint compose

The `compose` command generates the final Blueprint documentation by combining scan results, grouping information, and any custom documentation:

```bash
blueprint compose
```

This command writes output to the `.blueprint/` directory and patches `AGENTS.md` with a marker-delimited Blueprint snippet. The snippet provides project-specific guidance for AI agents without overwriting existing project instructions.

资料来源：[README.md:38-43]()

### blueprint refresh

The `refresh` command updates Blueprint state when the filesystem changes:

```bash
blueprint refresh
```

This command compares the current filesystem against the stored snapshot and updates the project graph accordingly. It handles:

- New files added to the project
- Deleted files removed from the project
- Modified files with updated analysis
- Renamed or moved files

资料来源：[README.md:30-36]()

### blueprint group update

After a refresh operation, unassigned files may exist. This command manages those files:

```bash
blueprint group update
```

The update operation can:
- Assign new files to existing groups based on patterns
- Create new groups for files that don't match existing patterns
- Remove empty groups that no longer have assigned files

资料来源：[README.md:30-36]()

### blueprint open

The `open` command launches the Blueprint viewer:

```bash
# Single open
blueprint open

# Watch mode - auto-regenerate on changes
blueprint open --watch
```

The viewer reads from `.blueprint/blueprint-output.json` and `.blueprint/groups/*.md`, then generates a self-contained `.blueprint/index.html` file that opens in the default browser.

**Important characteristics:**
- Does not start an HTTP server
- Does not include chat, LLM execution, or HTTP APIs
- Watch mode regenerates HTML when source files change but does not inject live reload code

资料来源：[README.md:56-68]()

## Initial Workflow

For first-time setup, run the following MCP tool sequence:

```mcp
1. blueprint.scan           # Inventory all files and analyze code
2. blueprint.group          # With mode: "prepare"
3. [Create grouping plan]   # Developer creates compact grouping
4. blueprint.group          # With mode: "apply"
5. blueprint.compose        # Generate final documentation
```

资料来源：[README.md:58-65]()

```mermaid
graph TD
    A[Start] --> B[blueprint scan]
    B --> C[blueprint group prepare]
    C --> D[Developer Reviews Suggestions]
    D --> E[Developer Creates Plan]
    E --> F[blueprint group apply]
    F --> G[blueprint compose]
    G --> H[Blueprint Memory Ready]
    
    H --> I[blueprint open]
    I --> J[.blueprint/index.html Generated]
```

## Maintenance Workflow

When project changes occur (new files, deletions, or architectural changes):

```mcp
1. blueprint.refresh           # Update Blueprint state
2. blueprint.group.update      # Handle unassigned files
3. [Update affected group docs] # Modify .blueprint/groups/*.md
```

资料来源：[README.md:67-73]()

## Viewer Command Architecture

The viewer generation follows a specific architecture that produces self-contained HTML:

```mermaid
graph LR
    A[blueprint open] --> B[Read blueprint-output.json]
    A --> C[Read .blueprint/groups/*.md]
    B --> D[Generate index.html]
    C --> D
    D --> E[Inline CSS]
    D --> F[Inline JS]
    D --> G[Embed JSON Data]
    E --> H[Self-contained HTML]
    F --> H
    G --> H
    H --> I[Browser Render]
```

The embedded data uses `<script id="blueprint-data" type="application/json">` for secure JSON embedding, protecting against XSS and `</script>` closing tag injection risks.

资料来源：[todos_120526.md:12-15]()

## Agent Integration

Blueprint CLI integrates with AI agents through `AGENTS.md` files that contain marker-based patches. The system uses stable section headings for navigation:

- `Core Flow`
- `Contracts & Invariants`
- `Change Guide`
- `Pitfalls`
- `Tests`

资料来源：[AGENTS.md:4-10]()

### Agent Budget Guidelines

When working with Blueprint in agentic contexts:

| Resource | Budget Policy |
| --- | --- |
| `.blueprint/brief.md` | Always read |
| Blueprint Markdown search | Always prefer early |
| Group docs | Read targeted excerpts first |
| Full group docs | Exception, not default |

资料来源：[AGENTS.md:1-7]()

## Development Commands

For developers working on Blueprint itself:

```bash
npm install      # Install dependencies
npm run build    # Build the project
npm run lint     # Run linter
npm test         # Run tests
```

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

## Command Output Structure

Blueprint generates structured output files in the `.blueprint/` directory:

| File | Purpose |
| --- | --- |
| `brief.md` | Project overview and key architectural decisions |
| `blueprint-output.json` | Structured project graph |
| `groups/*.md` | Individual group documentation |
| `file-inventory.json` | Complete file listing |
| `refresh-scan.json` | Filesystem state snapshot |

资料来源：[README.md:49-53]()

## Language Support

The CLI uses Tree-sitter for deep code analysis of supported languages:

| Language | Support Level |
| --- | --- |
| TypeScript / JavaScript | Full symbol and import analysis |
| Python | Full symbol and import analysis |
| Go | Full symbol and import analysis |
| Rust | Full symbol and import analysis |
| Java | Full symbol and import analysis |
| Other languages | Metadata only (no deep analysis) |

资料来源：[README.md:81-88]()

## Configuration Notes

- `.blueprint/` is local generated memory by default
- Teams decide whether to commit to version control or add to `.gitignore`
- Source code remains the single source of truth
- Do not edit `blueprint-output.json` manually

资料来源：[README.md:53-56]()

## Error Handling

When commands encounter issues:

| Scenario | Behavior |
| --- | --- |
| Missing inventory artifact | Returns error with artifact ID and expected type |
| Unparseable files | Marked as `metadata-only` and skipped |
| Pattern matching failure | Reports unmatched files with suggested paths |
| Missing group documentation | Displays placeholder message in viewer |

资料来源：[src/tools/scan/scan-code-analysis-engine.ts:15-22]()

## Summary

The Blueprint CLI provides a comprehensive toolkit for code comprehension and documentation:

1. **Scan** creates a complete inventory of project files
2. **Group** organizes files into semantic clusters
3. **Compose** generates documentation and updates agent guidance
4. **Refresh** keeps the documentation synchronized with filesystem changes
5. **Open** provides a self-contained HTML viewer

All operations are designed to enhance developer understanding without modifying source code or requiring a persistent HTTP server.

---

<a id='page-system-architecture'></a>

## System Architecture

### 相关页面

相关主题：[Scan Tool](#page-scan-tool), [Group Tool](#page-group-tool), [Compose Tool](#page-compose-tool), [Refresh Tool](#page-refresh-tool)

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

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

- [README.md](https://github.com/engincankaya/blueprint/blob/main/README.md)
- [AGENTS.md](https://github.com/engincankaya/blueprint/blob/main/AGENTS.md)
- [src/tools/scan/scan-file-inventory-builder.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-file-inventory-builder.ts)
- [src/tools/scan/scan-code-analysis-engine.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-code-analysis-engine.ts)
- [src/tools/group/grouping-assignment-engine.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/group/grouping-assignment-engine.ts)
- [src/viewer/render-html.ts](https://github.com/engincankaya/blueprint/blob/main/src/viewer/render-html.ts)
- [frontend/src/components/blueprint/GroupDetailPanel.tsx](https://github.com/engincankaya/blueprint/blob/main/frontend/src/components/blueprint/GroupDetailPanel.tsx)
- [frontend/src/components/BlueprintApp.tsx](https://github.com/engincankaya/blueprint/blob/main/frontend/src/components/BlueprintApp.tsx)
</details>

# System Architecture

## Overview

Blueprint is a documentation and code organization system that generates a structured "memory" layer for software projects. Rather than modifying source code, it creates an orientation layer stored in the `.blueprint/` directory, enabling AI agents and developers to understand project structure without reading every file.

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

The system operates as a **transport-agnostic architecture** that can function in two modes:

1. **Static mode**: Embeds data directly into `index.html` for self-contained viewing
2. **HTTP mode**: Serves data via API for interactive development environments

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

## Core Components

Blueprint's architecture consists of four primary tool layers, each responsible for a distinct phase of the documentation lifecycle.

### Tool Layer Architecture

```mermaid
graph TD
    A[blueprint scan] --> B[blueprint group]
    B --> C[blueprint compose]
    C --> D[blueprint refresh]
    
    A1[File Inventory] --> B1[Grouping Assignment]
    B1 --> C1[Memory Output]
    C1 --> D1[State Refresh]
    
    A2[Code Analysis] --> B2[Pattern Validation]
    B2 --> C2[Markdown Notes]
    C2 --> D2[Incremental Updates]
```

### Component Responsibilities

| Component | Purpose | Key Files |
|-----------|---------|-----------|
| **Scanner** | Builds file inventory and parses code for symbols, imports, exports | `src/tools/scan/*.ts` |
| **Grouper** | Assigns files to semantic groups using glob patterns | `src/tools/group/*.ts` |
| **Composer** | Writes `.blueprint/` memory and patches `AGENTS.md` | `src/tools/compose/*.ts` |
| **Refresher** | Refreshes Blueprint state from current filesystem | `src/tools/refresh/*.ts` |

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

## File Inventory System

The scanning engine builds a comprehensive file inventory by categorizing each file in the project.

### File Categorization Logic

Files are classified into categories based on path segments, file extensions, and naming patterns:

```mermaid
graph LR
    A[File Path] --> B{Extension Check}
    B -->|spec.ts / test.ts| C[test]
    B -->|package-lock.json| D[lockfile]
    B -->|package.json / .config.ts| E[config]
    B -->|readme.md / *.md| F[documentation]
    B -->|.sh / scripts/| G[script]
    B -->|.svg / css / assets/| H[asset]
```

资料来源：[src/tools/scan/scan-file-inventory-builder.ts]()

### Category Detection Rules

| Category | Detection Criteria |
|----------|---------------------|
| `test` | File ends with `.spec.ts`, `.test.ts`, or path contains `test`, `tests`, `__tests__` |
| `lockfile` | `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `cargo.lock`, `poetry.lock` |
| `config` | `.gitignore`, `package.json`, `tsconfig.json`, `*.config.js/ts/mjs/cjs`, or language in `json/yaml/toml/xml` |
| `documentation` | Path contains `docs`, `readme.md`, or any `.md` file |
| `script` | Path contains `scripts`, shell language, or `.sh` extension |
| `asset` | Path contains `assets` or `public`, or language in `html/css/scss/svg` |

资料来源：[src/tools/scan/scan-file-inventory-builder.ts]()

## Code Analysis Engine

The analysis engine parses all "parseable" files to extract structural information.

### Analysis Facts Model

```typescript
interface AnalysisFacts {
  inventoryArtifactId: string;
  rootPath: string;
  files: Record<string, FileFacts>;
  symbols: Record<string, SymbolFacts>;
  imports: ImportStatement[];
  exports: ExportStatement[];
  dependencies: Dependency[];
  unresolvedImports: UnresolvedImport[];
  parseErrors: ParseError[];
  summary: AnalysisSummary;
  validation: ValidationStatus;
}
```

资料来源：[src/tools/scan/scan-code-analysis-engine.ts]()

### Summary Tracking

The engine maintains aggregate statistics during parsing:

| Metric | Description |
|--------|-------------|
| `totalFiles` | Total files in inventory |
| `parseableFiles` | Files eligible for parsing |
| `parsedFiles` | Successfully parsed files |
| `metadataOnlyFiles` | Files with only metadata (binary, etc.) |
| `symbols` | Extracted function/class/variable declarations |
| `imports` | Import statements analyzed |
| `exports` | Export statements analyzed |
| `parseErrors` | Files that failed to parse |

资料来源：[src/tools/scan/scan-code-analysis-engine.ts]()

## Group Assignment System

Files are assigned to semantic groups using glob-based pattern matching.

### Pattern Matching Engine

The grouper supports wildcard patterns for matching file paths:

```mermaid
graph TD
    A[Pattern] --> B{Character}
    B -->|glob `*`| C[Match any chars except /]
    B -->|glob `?`| D[Match single char except /]
    B -->|literal| E[Exact match required]
    C --> F[Build Regex]
    D --> F
    E --> F
    F --> G[^pattern$]
```

资料来源：[src/tools/group/grouping-assignment-engine.ts]()

### Grouped File Structure

```typescript
interface GroupedFile {
  fileId: string;
  path: string;
  category: string;
  language: string;
  importance: "critical" | "important" | "standard" | "unknown";
  role: string;
}
```

资料来源：[src/tools/group/grouping-assignment-engine.ts]()

### Validation and Suggestions

When patterns fail to match any files, the system provides diagnostic information:

```typescript
interface UnknownPattern {
  pattern: string;
  reason: string;
  suggestions: string[];
}
```

The suggester extracts suffixes from patterns and finds similar paths in the inventory.

资料来源：[src/tools/group/grouping-assignment-engine.ts]()

## Group Documentation Template

Each group follows a canonical documentation structure that agents can navigate using stable headings.

### Section Structure

```mermaid
graph LR
    A[Snapshot] --> B[Responsibilities]
    B --> C[Core Flow]
    C --> D[Contracts & Invariants]
    D --> E[Key Files]
    E --> F[Change Guide]
    F --> G[Pitfalls]
    G --> H[Tests]
```

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

| Section | Purpose |
|---------|---------|
| `Snapshot` | Quick orientation for the group |
| `Responsibilities` | Ownership and out-of-scope areas |
| `Core Flow` | Runtime behavior and data flow |
| `Contracts & Invariants` | Behavior that must not be broken |
| `Key Files` | Main source files for the group |
| `Change Guide` | Files or contracts that should change together |
| `Pitfalls` | Known risks and common mistakes |
| `Tests` | Testing guidance |

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

## Frontend Component Architecture

The Blueprint frontend is a React-based application with a tabbed interface.

### Application Structure

```mermaid
graph TD
    A[BlueprintApp] --> B[Tab Bar]
    A --> C[Main Content Area]
    
    B --> D[Canvas Tab]
    B --> E[Group Detail Tabs]
    
    C --> D
    C --> E
    
    E --> F[GroupDetailPanel]
    F --> G[Overview]
    F --> H[Files]
    F --> I[Connections]
    F --> J[Architecture]
    F --> K[Guide]
```

资料来源：[frontend/src/components/BlueprintApp.tsx]()
资料来源：[frontend/src/components/blueprint/GroupDetailPanel.tsx]()

### Sub-Tab Content Mapping

| Sub-Tab | Content Components |
|---------|--------------------|
| `overview` | Snapshot, Responsibilities, Key Files, Open Questions |
| `files` | Role breakdown tags, File tree with icons |
| `connections` | ConnectionDiagram visualization |
| `architecture` | CoreFlow, ContractsAndInvariants, KeyFiles cards |
| `guide` | ChangeGuide, Pitfalls, Tests, Debugging, OpenQuestions |

资料来源：[frontend/src/components/blueprint/GroupDetailPanel.tsx]()

### SectionCard Component

The `SectionCard` component provides collapsible content sections with accent colors:

```typescript
interface SectionCardProps {
  title: string;
  content: string;
  accent?: 'amber' | 'red' | 'green' | 'blue' | 'zinc';
  defaultOpen?: boolean;
  index?: number;
}
```

| Accent Color | Use Case |
|--------------|----------|
| `blue` | Default sections |
| `amber` | Pitfalls and warnings |
| `red` | Invariants (critical constraints) |
| `green` | Extension open questions |
| `zinc` | Standard content |

资料来源：[frontend/src/components/blueprint/GroupDetailPanel.tsx]()

## Static Viewer Rendering

The HTML renderer creates self-contained viewer files by inlining assets.

### Inlining Process

```mermaid
graph LR
    A[Template HTML] --> B[Inline CSS]
    B --> C[Inline JS]
    C --> D[Embed JSON Data]
    D --> E[Escape & Validate]
    E --> F[index.html]
```

资料来源：[src/viewer/render-html.ts]()

### Asset Inlining Strategy

The renderer processes three asset types:

| Asset Type | Regex Pattern | Replacement |
|------------|---------------|-------------|
| CSS | `<link rel="stylesheet" href="...">` | `<style>{inline content}</style>` |
| Module JS (crossorigin) | `<script type="module" crossorigin src="...">` | `<script type="module">{inline content}</script>` |
| Module JS | `<script type="module" src="...">` | `<script type="module">{inline content}</script>` |

资料来源：[src/viewer/render-html.ts]()

### Data Embedding Security

JSON data is embedded using `<script type="application/json">` to avoid XSS risks:

```html
<script id="blueprint-data" type="application/json">
  <!-- Safely escaped JSON here -->
</script>
```

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

## Workflow State Machine

### Initial Workflow

```mermaid
graph TD
    A[Start] --> B[blueprint scan]
    B --> C[blueprint group prepare]
    C --> D{Create grouping plan}
    D --> E[blueprint group apply]
    E --> F[blueprint compose]
    F --> G[Complete]
    
    H[hydrate group docs] -.-> G
```

### Maintenance Workflow

```mermaid
graph TD
    A[Project Change] --> B[blueprint refresh]
    B --> C{New unassigned files?}
    C -->|Yes| D[blueprint group update]
    C -->|No| E[Update affected group docs]
    D --> E
    E --> F[Complete]
```

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

## Artifact Storage

The system uses typed artifact storage for persisting scan results, groupings, and composed output.

### Artifact Types

| Artifact | Purpose |
|----------|---------|
| `fileInventory` | Complete file listing with categories |
| `codeAnalysis` | Symbols, imports, exports from parsing |
| `groupingAssignment` | File-to-group mappings |
| `groupDocAnalysis` | Canonical section validation |

资料来源：[src/lib/artifact-store.ts]()

### Validation Status

Each analysis maintains a validation record:

```typescript
interface ValidationStatus {
  isComplete: boolean;
  inventoryFiles: number;
  parseableFiles: number;
  parsedFiles: number;
  metadataOnlyFiles: number;
  skippedMetadataOnlyFiles: number;
  parseErrors: number;
  unaccountedFiles: string[];
}
```

资料来源：[src/tools/scan/scan-code-analysis-engine.ts]()

## Key Design Principles

1. **Source of Truth**: Source code remains the source of truth; `.blueprint/` is generated memory only
2. **Local by Default**: Blueprint memory is stored in `.blueprint/` (not in `node_modules`)
3. **Transport Agnostic**: Supports both static HTML and HTTP API modes
4. **Safe Embedding**: JSON data is safely escaped before HTML embedding
5. **Canonical Structure**: Group docs follow a stable template for consistent navigation

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

---

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

## MCP Server Implementation

### 相关页面

相关主题：[System Architecture](#page-system-architecture), [Task Context Tool](#page-task-context-tool)

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

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

- [src/tools/scan/scan-code-analysis-engine.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-code-analysis-engine.ts)
- [src/tools/scan/scan-file-inventory-builder.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-file-inventory-builder.ts)
- [src/lib/agent-instructions.ts](https://github.com/engincankaya/blueprint/blob/main/src/lib/agent-instructions.ts)
- [AGENTS.md](https://github.com/engincankaya/blueprint/blob/main/AGENTS.md)
- [README.md](https://github.com/engincankaya/blueprint/blob/main/README.md)
</details>

# MCP Server Implementation

The Blueprint MCP Server provides a Model Context Protocol interface for AI agents to interact with codebase architecture memory. It exposes tools for scanning codebases, grouping files semantically, composing documentation, and maintaining architectural state across project changes.

## Overview

Blueprint operates as a local architecture memory layer that sits above source code. The MCP Server acts as the bridge between AI agents and the Blueprint tooling, enabling deterministic project understanding without manual documentation overhead.

```mermaid
graph TD
    A[AI Agent] -->|MCP Protocol| B[Blueprint MCP Server]
    B -->|blueprint.scan| C[File Inventory Builder]
    B -->|blueprint.group| D[Semantic Grouper]
    B -->|blueprint.compose| E[Documentation Writer]
    B -->|blueprint.refresh| F[State Refresher]
    C -->|Artifacts| G[blueprint-output.json]
    D -->|Groupings| H[groups/*.md]
    E -->|Memory| G & H
    F -->|Sync| G & H
```

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

## MCP Tools Architecture

### Available Tools

| Tool | Purpose | Output |
|------|---------|--------|
| `blueprint.scan` | Builds file inventory and code analysis artifacts | File metadata, symbols, imports |
| `blueprint.group` | Prepares or applies semantic file grouping | Group definitions |
| `blueprint.compose` | Writes Blueprint output and Markdown notes | `.blueprint/` memory files |
| `blueprint.refresh` | Refreshes state from current filesystem | Updated JSON state |
| `blueprint.group.update` | Assigns unassigned files or manages empty groups | Updated groupings |

资料来源：[README.md:30-36]()

### Tool Workflow

```mermaid
graph LR
    A[Initial Setup] --> B[scan]
    B --> C[group prepare]
    C --> D[Review Plan]
    D --> E[group apply]
    E --> F[compose]
    F --> G[Memory Written]
    
    H[Maintenance] --> I[refresh]
    I --> J{Unassigned Files?}
    J -->|Yes| K[group.update]
    J -->|No| L[Update Docs Only]
    K --> M[Update group/*.md]
```

#### Initial Workflow

1. `blueprint.scan` - Builds file inventory and code analysis artifacts
2. `blueprint.group` with `mode: "prepare"` - Prepares grouping plan
3. Review the compact grouping plan output
4. `blueprint.group` with `mode: "apply"` - Applies the grouping
5. `blueprint.compose` - Writes `.blueprint/` memory and patches `AGENTS.md`

资料来源：[README.md:18-27]()

#### Maintenance Workflow

1. Run `blueprint.refresh` when project changes occur
2. If new files are unassigned, run `blueprint.group.update`
3. Update only affected `.blueprint/groups/*.md` notes when architecture changes

资料来源：[README.md:29-33]()

## Scan Tool Implementation

### File Inventory Builder

The `scan-file-inventory-builder.ts` handles filesystem traversal and file classification. It categorizes files into types based on naming conventions and path segments.

#### File Type Classification

| Type | Detection Criteria |
|------|---------------------|
| `test` | `test.spec.ts`, `test.spec.tsx`, `test.spec.js`, `test.spec.jsx`, `/test/`, `/tests/`, `__tests__/` |
| `lockfile` | `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `cargo.lock`, `poetry.lock` |
| `config` | `.gitignore`, `package.json`, `tsconfig.json`, `*.config.js`, `*.config.ts`, language in `[json, yaml, toml, xml]` |
| `documentation` | `/docs/`, `readme.md`, `*.md`, language `markdown` |
| `script` | `/scripts/`, language `shell`, `*.sh` |
| `asset` | `/assets/`, `/public/`, language in `[html, css, scss, svg]` |
| `generated` | `/generated/`, `/__generated__/` |

资料来源：[src/tools/scan/scan-file-inventory-builder.ts:1-80]()

### Code Analysis Engine

The `scan-code-analysis-engine.ts` performs deep analysis on parseable files, extracting symbols, imports, exports, and dependencies.

#### Analysis Facts Model

```typescript
interface AnalysisFacts {
  inventoryArtifactId: string;
  rootPath: string;
  files: Record<string, FileAnalysis>;
  symbols: Record<string, Symbol[]>;
  imports: ImportStatement[];
  exports: ExportStatement[];
  dependencies: Dependency[];
  unresolvedImports: UnresolvedImport[];
  parseErrors: ParseError[];
  summary: {
    totalFiles: number;
    parseableFiles: number;
    metadataOnlyFiles: number;
    plannedFiles: number;
    parsedFiles: number;
    symbols: number;
    imports: number;
    exports: number;
    dependencies: number;
    parseErrors: number;
  };
  validation: AnalysisValidation;
}
```

资料来源：[src/tools/scan/scan-code-analysis-engine.ts:20-40]()

#### Language Support

Blueprint uses Tree-sitter analysis for:

| Language | Symbol Analysis | Import/Export Analysis |
|----------|-----------------|------------------------|
| TypeScript/JavaScript | ✅ Full | ✅ Full |
| Python | ✅ Full | ✅ Full |
| Go | ✅ Full | ✅ Full |
| Rust | ✅ Full | ✅ Full |
| Java | ✅ Full | ✅ Full |
| Other | Metadata only | Metadata only |

资料来源：[README.md:60-65]()

### Validation Model

```typescript
interface AnalysisValidation {
  isComplete: boolean;
  inventoryFiles: number;
  parseableFiles: number;
  parsedFiles: number;
  metadataOnlyFiles: number;
  skippedMetadataOnlyFiles: number;
  parseErrors: number;
  unaccountedFiles: string[];
}
```

资料来源：[src/tools/scan/scan-code-analysis-engine.ts:42-50]()

## Agent Integration

### AGENTS.md Integration

The MCP Server integrates with project `AGENTS.md` files using marker-delimited snippets. When `blueprint.compose` runs, it patches the `AGENTS.md` without overwriting existing project instructions.

#### Snippet Format

```markdown
<!-- BEGIN:blueprint-mcp-agent-rules -->

## Blueprint MCP

This project uses Blueprint MCP for local architecture memory.

Before broad codebase exploration, read:

`node_modules/blueprint-mcp-server/docs/agents.md`

If Blueprint memory exists, start with:

`.blueprint/brief.md`

<!-- END:blueprint-mcp-agent-rules -->
```

资料来源：[src/lib/agent-instructions.ts:15-30]()

### Agent Instruction Rendering

```typescript
export function renderBlueprintAgentsSnippet(): string {
  return [
    beginMarker,
    "",
    "## Blueprint MCP",
    "",
    "This project uses Blueprint MCP for local architecture memory.",
    "",
    "Before broad codebase exploration, read:",
    "",
    "`node_modules/blueprint-mcp-server/docs/agents.md`",
    "",
    "If Blueprint memory exists, start with:",
    "",
    "`.blueprint/brief.md`",
    "",
    endMarker,
  ].join("\n");
}
```

资料来源：[src/lib/agent-instructions.ts:40-58]()

## Blueprint Memory Structure

```mermaid
graph TD
    subgraph ".blueprint/"
        A[blueprint-output.json] -->|Deterministic| B[Group definitions]
        A -->|Deterministic| C[File inventory]
        A -->|Deterministic| D[Analysis facts]
        E[brief.md] -->|Overview| F[Architectural groups]
        G[groups/*.md] -->|Detailed| H[Responsibilities]
        G -->|Detailed| I[Core Flow]
        G -->|Detailed| J[Contracts & Invariants]
        G -->|Detailed| K[Change Guide]
        G -->|Detailed| L[Pitfalls]
    end
    
    M[refresh-scan.json] -->|Hash snapshot| N[Deterministic refresh]
```

### Generated Artifacts

| File | Purpose |
|------|---------|
| `blueprint-output.json` | Structured project graph generated by tools |
| `refresh-scan.json` | Filesystem hash snapshot for deterministic refreshes |

资料来源：[README.md:9-12]()

### Group Documentation Template

Files under `.blueprint/groups/*.md` follow a stable template:

| Section | Purpose |
|---------|---------|
| `Snapshot` | Quick orientation |
| `Responsibilities` | Ownership and out-of-scope areas |
| `Core Flow` | Runtime behavior and data flow |
| `Contracts & Invariants` | Behavior that must not be broken |
| `Key Files` | Main source files for the group |
| `Change Guide` | Files or contracts that should change together |
| `Pitfalls` | Known risks and common mistakes |
| `Tests` | Most relevant verification |
| `Debugging` | Failure-mode hints |
| `Extension / Open Questions` | Uncertainty and known gaps |

资料来源：[AGENTS.md:1-35]()

## Viewer Integration

Blueprint ships a lightweight React/Vite viewer that reads generated Blueprint data.

### Static HTML Generation

```mermaid
graph LR
    A[blueprint open] --> B[Read JSON & MD]
    B --> C[Generate index.html]
    C --> D[Open in browser]
    
    E[--watch mode] --> F[Regenerate on changes]
```

#### Viewer Features

- Self-contained HTML with inline JS and CSS
- Secure embedded JSON data
- No HTTP server required
- No chat or LLM execution

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

## Import Resolution System

### Candidate Import Path Resolution

The code analysis engine resolves relative imports by checking multiple candidate paths:

```typescript
private candidateImportPaths(basePath: string): string[] {
  const candidates = [basePath];
  
  if (ext) {
    return candidates;
  }
  
  return [
    basePath,
    `${basePath}.ts`,
    `${basePath}.tsx`,
    `${basePath}.js`,
    `${basePath}.jsx`,
    `${basePath}/index.ts`,
    `${basePath}/index.tsx`,
    `${basePath}/index.js`,
    `${basePath}/index.jsx`,
  ];
}
```

资料来源：[src/tools/scan/scan-code-analysis-engine.ts:80-95]()

## Key Design Principles

### Source of Truth

| Principle | Implication |
|-----------|-------------|
| Source code is ground truth | Blueprint docs are orientation, not authority |
| Documentation follows changes | Update relevant group docs after source changes |
| Deterministic JSON | Do not edit `blueprint-output.json` manually |

资料来源：[AGENTS.md:55-60]()

### Working Rules

1. Keep changes scoped to the user's task
2. Prefer existing project patterns over new abstractions
3. Add or update tests when behavior changes
4. Run the smallest relevant verification first
5. Do not edit generated files unless explicitly required

资料来源：[AGENTS.md:65-70]()

---

<a id='page-scan-tool'></a>

## Scan Tool

### 相关页面

相关主题：[System Architecture](#page-system-architecture), [Group Tool](#page-group-tool)

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

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

- [src/tools/scan/scan-code-analysis-engine.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-code-analysis-engine.ts)
- [src/tools/scan/scan-file-inventory-builder.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-file-inventory-builder.ts)
</details>

# Scan Tool

The Scan Tool (`blueprint.scan`) is the first stage in the Blueprint workflow. It performs filesystem traversal and static code analysis to build a comprehensive **File Inventory** and **Analysis Facts** artifact. These artifacts serve as the foundational data layer for subsequent grouping, composition, and visualization operations.

## Overview

The Scan Tool operates in two distinct phases:

1. **File Inventory Phase** - Traverses the project filesystem, categorizes files by role (source, test, config, etc.), and detects the technology stack
2. **Code Analysis Phase** - Parses source files using Tree-sitter to extract symbols, imports, exports, and dependency relationships

```
┌─────────────────┐    ┌──────────────────────────┐    ┌─────────────────┐
│  Filesystem     │───▶│  FileInventoryBuilder    │───▶│  FileInventory  │
│  Traversal      │    │  (scan-file-inventory)   │    │  Artifact       │
└─────────────────┘    └──────────────────────────┘    └────────┬────────┘
                                                                  │
                                                                  ▼
┌─────────────────┐    ┌──────────────────────────┐    ┌─────────────────┐
│  AnalysisFacts  │◀───│  CodeAnalysisEngine      │◀───│  Parseable      │
│  Artifact       │    │  (scan-code-analysis)    │    │  Files          │
└─────────────────┘    └──────────────────────────┘    └─────────────────┘
```

## Architecture

### Core Components

| Component | File | Responsibility |
|-----------|------|----------------|
| `ScanFileInventoryBuilder` | `scan-file-inventory-builder.ts` | Filesystem traversal, file categorization, stack detection |
| `CodeAnalysisEngine` | `scan-code-analysis-engine.ts` | Tree-sitter parsing, symbol extraction, dependency analysis |
| `FileInventory` | Data model | Container for all inventoried files and summary statistics |
| `AnalysisFacts` | Data model | Container for parsed code facts (symbols, imports, exports) |

### Class: ScanFileInventoryBuilder

The `ScanFileInventoryBuilder` class is responsible for walking the project directory and building a structured file inventory.

```typescript
class ScanFileInventoryBuilder {
  // Builds the complete file inventory from a root path
  async build(rootPath: string): Promise<FileInventory>
  
  // Validates inventory completeness against scanned paths
  private validateInventory(scannedPaths: string[], files: InventoryFile[]): FileInventoryValidation
}
```

**资料来源**：[scan-file-inventory-builder.ts:1-50]()

### Class: CodeAnalysisEngine

The `CodeAnalysisEngine` class consumes the file inventory and performs deep static analysis on parseable files.

```typescript
class CodeAnalysisEngine {
  async handle(args: CodeAnalysisEngineArgs, store: ArtifactStore): Promise<ToolResult>
  
  // Builds a mapping from file paths to file IDs for efficient lookup
  private buildPathToFileId(inventory: FileInventory): Map<string, string>
  
  // Computes validation metrics for the analysis results
  private computeValidation(parsedFileIds, parseErrorFileIds, inventory): AnalysisValidation
}
```

**资料来源**：[scan-code-analysis-engine.ts:1-60]()

## File Inventory Phase

### File Role Detection

The scanner categorizes each file into one of the following roles based on its path and extension:

| Role | Detection Criteria |
|------|-------------------|
| `source` | Primary language files (`.ts`, `.tsx`, `.js`, `.jsx`, `.py`, `.go`, `.rs`, `.java`) |
| `test` | Files ending in `.spec.ts`, `.test.ts`, or containing `test`/`tests`/`__tests__` in path |
| `lockfile` | `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `Cargo.lock`, `poetry.lock` |
| `config` | `.gitignore`, `package.json`, `tsconfig.json`, `.config.js/ts`, config files |
| `documentation` | Files in `docs/`, `readme.md`, or other `.md` files |
| `script` | Files in `scripts/`, shell scripts (`.sh`), or `language === "shell"` |
| `asset` | Files in `assets/`, `public/`, or with extensions: `.html`, `.css`, `.scss`, `.svg` |

**资料来源**：[scan-file-inventory-builder.ts:50-130]()

### Analysis Level Classification

Each file receives an `analysisLevel` designation:

| Level | Description |
|-------|-------------|
| `parseable` | Files with known parsers that support symbol/import extraction |
| `metadata-only` | Files that are inventoried but cannot be deeply parsed |

**资料来源**：[scan-code-analysis-engine.ts:20-30]()

### Stack Detection

The builder detects the technology stack from two sources:

1. **Language counts** - Extracted from file extensions
2. **Path patterns** - Special directories indicate additional technologies

| Pattern | Stack Addition |
|---------|---------------|
| `*.ts`, `*.js`, etc. | Respective language name |
| `package.json` in paths | `"node"` |
| `mcp-server/` in paths | `"mcp"` |

**资料来源**：[scan-file-inventory-builder.ts:180-200]()

### Package Manager Detection

Detects which package managers are in use:

| File | Manager |
|------|---------|
| `package.json` | `npm`, `yarn`, `pnpm` |
| `Cargo.toml` | `cargo` |
| `go.mod` | `go` |
| `pyproject.toml`, `requirements.txt` | `python` |
| `pom.xml` | `maven` |
| `build.gradle`, `build.gradle.kts` | `gradle` |

**资料来源**：[scan-file-inventory-builder.ts:150-175]()

## Code Analysis Phase

### Tree-sitter Integration

The analysis engine uses Tree-sitter for parsing supported languages:

| Supported Languages | Extensions |
|---------------------|------------|
| TypeScript/JavaScript | `.ts`, `.tsx`, `.js`, `.jsx` |
| Python | `.py` |
| Go | `.go` |
| Rust | `.rs` |
| Java | `.java` |

> **Note**: Files in other languages are still included in the inventory but receive `metadata-only` analysis.

**资料来源**：[README.md - Language Support section]()

### Extracted Facts

For each parseable file, the engine extracts:

```typescript
interface AnalysisFacts {
  inventoryArtifactId: string;
  rootPath: string;
  files: Record<string, ParsedFile>;      // fileId -> parsed content
  symbols: Record<string, Symbol[]>;       // fileId -> extracted symbols
  imports: ImportStatement[];              // all import statements
  exports: ExportStatement[];              // all export statements
  dependencies: DependencyEdge[];         // inter-file dependencies
  unresolvedImports: UnresolvedImport[];   // imports without matching exports
  parseErrors: ParseError[];               // parsing failures
  summary: AnalysisSummary;
  validation: AnalysisValidation;
}
```

**资料来源**：[scan-code-analysis-engine.ts:30-60]()

### Validation Model

The analysis produces a validation object tracking completeness:

```typescript
interface AnalysisValidation {
  isComplete: boolean;                    // true if all files processed
  inventoryFiles: number;                 // total files in inventory
  parseableFiles: number;                // files marked as parseable
  parsedFiles: number;                   // successfully parsed count
  metadataOnlyFiles: number;             // metadata-only file count
  skippedMetadataOnlyFiles: number;      // metadata-only files skipped
  parseErrors: number;                   // parse failure count
  unaccountedFiles: string[];            // files not in parsed or error sets
}
```

**资料来源**：[scan-code-analysis-engine.ts:60-75]()

## Data Flow

```mermaid
graph TD
    A[Root Path] --> B[ScanFileInventoryBuilder.build]
    B --> C[Filesystem Walk]
    C --> D[File Categorization]
    D --> E[Stack Detection]
    E --> F[FileInventory Artifact]
    
    F --> G[CodeAnalysisEngine.handle]
    G --> H[Filter Parseable Files]
    H --> I[For Each Parseable File]
    I --> J[Read File Content]
    J --> K[Create Tree-sitter Parser]
    K --> L[Extract Symbols]
    K --> M[Extract Imports]
    K --> N[Extract Exports]
    L --> O[Build Dependency Graph]
    M --> O
    N --> O
    O --> P[AnalysisFacts Artifact]
    
    I --> Q[Handle Parse Errors]
    Q --> P
```

## Output Artifacts

### FileInventory Artifact

| Field | Type | Description |
|-------|------|-------------|
| `rootPath` | `string` | Absolute path to scanned root |
| `files` | `InventoryFile[]` | All discovered files with metadata |
| `summary` | `InventorySummary` | Aggregated statistics |

### AnalysisFacts Artifact

| Field | Type | Description |
|-------|------|-------------|
| `symbols` | `Record<string, Symbol[]>` | Symbols indexed by file ID |
| `imports` | `ImportStatement[]` | All import declarations |
| `exports` | `ExportStatement[]` | All export declarations |
| `dependencies` | `DependencyEdge[]` | File-to-file dependency edges |
| `unresolvedImports` | `UnresolvedImport[]` | Imports without matching targets |

## Configuration & Behavior

### Summary Statistics

The `FileInventory` summary provides project metrics:

```typescript
interface InventorySummary {
  totalFiles: number;
  parseableFiles: number;
  metadataOnlyFiles: number;
  byLanguage: Record<string, number>;
  byRole: Record<string, number>;
}
```

**资料来源**：[scan-file-inventory-builder.ts:200-220]()

### Validation Completeness Check

The engine computes `isComplete` as:

```
isComplete = (parsedFiles + parseErrorFiles + skippedMetadataOnlyFiles) === totalInventoryFiles
```

If `isComplete` is `false`, there are files in the inventory that were neither successfully parsed nor accounted for in error/skipped sets.

**资料来源**：[scan-code-analysis-engine.ts:100-115]()

## Integration with Blueprint Workflow

The Scan Tool is the entry point for the Blueprint system:

```
blueprint.scan → blueprint.group → blueprint.compose
```

1. **`blueprint.scan`** - Produces `fileInventory` and `analysisFacts` artifacts
2. **`blueprint.group`** - Consumes these artifacts to create semantic groupings
3. **`blueprint.compose`** - Generates the final `blueprint-output.json`

**资料来源**：[README.md - Initial Workflow section]()

## Error Handling

The Scan Tool handles several error conditions:

| Error Condition | Handling |
|-----------------|----------|
| File not found | Included in `parseErrors` array |
| Parser unavailable | File marked as `metadata-only` |
| Syntax error in source | Recorded with location in `parseErrors` |
| Missing inventory artifact | Returns error result from `handle()` |
| Unaccounted files | Listed in `validation.unaccountedFiles` |

**资料来源**：[scan-code-analysis-engine.ts:80-95]()

## Refresh Maintenance

When the filesystem changes:

```bash
blueprint.refresh
```

This re-runs the scan to update the file inventory and analysis facts, ensuring the Blueprint state reflects the current project structure.

**资料来源**：[README.md - Maintenance Workflow section]()

---

<a id='page-group-tool'></a>

## Group Tool

### 相关页面

相关主题：[System Architecture](#page-system-architecture), [Scan Tool](#page-scan-tool), [Compose Tool](#page-compose-tool)

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

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

- [src/tools/group/index.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/group/index.ts)
- [src/tools/group/grouping-assignment-engine.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/group/grouping-assignment-engine.ts)
- [src/tools/group/grouping-plan-validator.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/group/grouping-plan-validator.ts)
- [src/tools/group/grouping.types.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/group/grouping.types.ts)
</details>

# Group Tool

## Overview

The Group Tool is a core component of the Blueprint system responsible for organizing source files into semantic architectural groups. It bridges the gap between raw file inventory (produced by the Scan Tool) and the structured architectural documentation (produced by the Compose Tool).

**Purpose**: The Group Tool transforms a flat list of files into a meaningful hierarchical structure where files are assigned to architectural groups based on semantic patterns, role assignments, and cross-group relationships.

**Scope**:
- Processes file inventory data from the Scan Tool
- Assigns files to groups based on glob patterns and semantic rules
- Validates grouping plans for completeness and conflicts
- Aggregates cross-group edges and relationships
- Handles fallback grouping for unassigned files
- Supports both `prepare` and `apply` modes for iterative group planning

资料来源：[src/tools/group/grouping-assignment-engine.ts:1-50]()

## Architecture

### Component Flow

```mermaid
graph TD
    A[FileInventory] --> B[GroupingAssignmentEngine]
    B --> C[GroupingPlanValidator]
    C --> D[GroupingResult]
    D --> E[ComposeOutputBuilder]
    E --> F[BlueprintOutput]
    
    G[GroupingPlan] --> B
    H[FileFacts] --> B
```

### Core Components

| Component | File | Responsibility |
|-----------|------|----------------|
| `GroupingAssignmentEngine` | `grouping-assignment-engine.ts` | Core logic for file-to-group assignment and pattern matching |
| `GroupingPlanValidator` | `grouping-plan-validator.ts` | Validates grouping plans for completeness and conflicts |
| Grouping Types | `grouping.types.ts` | TypeScript interfaces for grouping data models |
| Tool Entry Point | `index.ts` | CLI/MCP tool interface handling prepare/apply modes |

资料来源：[src/tools/group/grouping-assignment-engine.ts:1-30]()

## Data Models

### Key Types

```typescript
// GroupedFile represents a file assigned to a group
interface GroupedFile {
  fileId: string;
  path: string;
  category: string;
  language: string;
  importance: "unknown";
  role: "unknown";
}

// BlueprintGroup represents a semantic architectural group
interface BlueprintGroup {
  id: string;
  name: string;
  description: string;
  kind: string;
  confidence: number;
  files: GroupedFile[];
}

// GroupingResult contains the complete grouping output
interface GroupingResult {
  groups: BlueprintGroup[];
  crossGroupEdges: CrossGroupEdge[];
}
```

资料来源：[src/tools/group/grouping.types.ts]()

### Group Assignment Strategy

The assignment engine uses a multi-stage process:

1. **Pattern Matching**: Files are matched against glob-like patterns specified in the grouping plan
2. **Role Assignment**: Each file receives a role based on pattern matching and heuristics
3. **Fallback Grouping**: Unmatched files are placed in a fallback group
4. **Edge Aggregation**: Cross-group relationships are aggregated from file-level dependencies

资料来源：[src/tools/group/grouping-assignment-engine.ts:50-150]()

## Pattern Matching Engine

### Regex-Based Pattern System

The assignment engine converts user-friendly glob patterns into regular expressions for flexible file matching:

```mermaid
graph LR
    A[Glob Pattern] --> B[buildRegex]
    B --> C[Regular Expression]
    C --> D[File Path Matching]
    D --> E{Match?}
    E -->|Yes| F[Assign to Group]
    E -->|No| G[Next Pattern]
```

### Supported Pattern Syntax

| Pattern | Regex Equivalent | Description |
|---------|------------------|-------------|
| `*` | `[^/]*` | Match any characters except path separator |
| `?` | `[^/]` | Match single character except path separator |
| `**` | `.*` | Match any characters including path separators |
| Literal chars | Escaped | Match exact characters |

资料来源：[src/tools/group/grouping-assignment-engine.ts:100-130]()

### Pattern Processing Method

```typescript
private buildRegex(pattern: string): RegExp {
  let source = "";
  for (const char of pattern) {
    if (char === "*") {
      source += "[^/]*";
      continue;
    }
    if (char === "?") {
      source += "[^/]";
      continue;
    }
    source += this.escapeRegex(char);
  }
  return new RegExp(`^${source}$`);
}
```

资料来源：[src/tools/group/grouping-assignment-engine.ts:115-127]()

## Grouping Workflow

### Prepare Mode

In `prepare` mode, the tool analyzes the file inventory and suggests:

- Suggested group structures based on directory structure and file patterns
- Suggested role assignments for files
- Cross-group relationship candidates
- Confidence scores for each suggestion

```mermaid
sequenceDiagram
    participant User
    participant GroupTool
    participant ScanTool
    participant ComposeTool
    
    User->>ScanTool: blueprint.scan
    ScanTool->>GroupTool: FileInventory
    GroupTool->>GroupTool: Analyze patterns
    GroupTool-->>User: Suggested grouping plan
    User->>GroupTool: Refine grouping plan
    User->>GroupTool: blueprint.group(mode: apply)
    GroupTool->>ComposeTool: GroupingResult
    ComposeTool-->>User: Blueprint output
```

### Apply Mode

In `apply` mode, the tool:

1. Validates the provided grouping plan
2. Assigns files to groups based on patterns
3. Aggregates cross-group edges
4. Returns the structured `GroupingResult`

资料来源：[src/tools/group/index.ts]()

## Validation System

### Plan Validation Checks

The `GroupingPlanValidator` performs comprehensive validation:

| Validation Check | Purpose |
|------------------|---------|
| `unassignedFiles` | Ensures no files are left unassigned |
| `duplicateAssignments` | Detects files assigned to multiple groups |
| `unknownPatterns` | Flags patterns that matched no files |
| `emptyGroups` | Identifies groups with no files |
| `blockingIssues` | Prevents composition if critical issues exist |

资料来源：[src/tools/group/grouping-plan-validator.ts]()

### Validation Result Structure

```typescript
interface ValidationResult {
  isValid: boolean;
  blockingIssues: string[];
  warningIssues: string[];
  unassignedFiles: FileInventory["files"][number][];
  duplicateAssignments: Array<{ fileId: string; groups: string[] }>;
  unknownPatterns: UnknownPattern[];
  emptyGroups: string[];
}
```

资料来源：[src/tools/group/grouping-plan-validator.ts:1-50]()

## Edge Aggregation

### Cross-Group Relationship Detection

The assignment engine aggregates edges between groups based on:

1. **Import Dependencies**: Files importing from other groups
2. **Reference Patterns**: Cross-module references
3. **Test Relationships**: Test files referencing implementation files

```typescript
private aggregateEdges(
  facts: FileFacts,
  fileToGroup: Map<string, string>
): CrossGroupEdge[] {
  // Aggregates file-level edges into group-level edges
  // Groups edges by fromGroupId, toGroupId, and type
  // Returns sorted, deduplicated edge list
}
```

资料来源：[src/tools/group/grouping-assignment-engine.ts:200-250]()

### Edge Composition

The `compose-output-builder.ts` transforms grouping results into the final output format:

```typescript
edges: [...grouping.crossGroupEdges]
  .sort((a, b) =>
    a.fromGroupId.localeCompare(b.fromGroupId)
    || a.toGroupId.localeCompare(b.toGroupId)
    || a.type.localeCompare(b.type),
  ),
```

资料来源：[src/tools/compose/compose-output-builder.ts:1-50]()

## Group Update Workflow

### Refresh Integration

When files change in the repository, the Group Tool integrates with the refresh workflow:

```mermaid
graph LR
    A[File Changes] --> B[Refresh Tool]
    B --> C{New unassigned files?}
    C -->|Yes| D[Group Update Tool]
    C -->|No| E[Skip Update]
    D --> F[User Decisions]
    F --> G[Updated Grouping]
```

### Empty Group Detection

The refresh process identifies:

- **Unassigned Files**: Files not belonging to any group
- **Empty Group Candidates**: Groups that have lost all their files

```typescript
const emptyGroupCandidates = output.groups
  .filter((group) => group.fileIds.length === 0)
  .map((group) => ({
    groupId: group.id,
    name: group.name,
    docsPath: group.docsPath,
    deletedFileIds: [],
  }));
```

资料来源：[src/tools/group-update/index.ts:1-50]()

## File Categorization

The Group Tool inherits file categorization from the Scan Tool:

| Category | Detection Criteria |
|----------|-------------------|
| `source` | TypeScript, JavaScript, Python source files |
| `test` | Files ending in `.spec.ts`, `.test.ts`, in `test/` directories |
| `config` | `package.json`, `tsconfig.json`, config files |
| `documentation` | `.md` files, `docs/` directories |
| `script` | Shell scripts, `scripts/` directories |
| `asset` | CSS, SVG, image files |
| `lockfile` | `package-lock.json`, `yarn.lock`, etc. |

资料来源：[src/tools/scan/scan-file-inventory-builder.ts:1-100]()

## Integration Points

### With Scan Tool

The Group Tool receives file inventory data:
- File paths and IDs
- Language detection
- Category classification
- Basic file facts

### With Compose Tool

The Group Tool produces `GroupingResult` containing:
- Structured groups with assigned files
- Cross-group edges for relationship visualization
- Role assignments for documentation

### With Refresh Tool

The Group Tool participates in the refresh workflow by:
- Receiving updated file inventory
- Identifying unassigned files
- Detecting empty group candidates

资料来源：[src/tools/refresh/index.ts:1-100]()

## Error Handling

### Unknown Pattern Handling

When a pattern matches no files, the tool provides suggestions:

```typescript
private unknownPattern(
  inventory: FileInventory,
  pattern: string
): UnknownPattern {
  return {
    pattern,
    reason: "matched no inventory files; the path may be ignored or not inventoried",
    suggestions: this.suggestPaths(inventory, pattern),
  };
}
```

### Suggestion Generation

The tool suggests similar paths when patterns fail to match:

```typescript
private suggestPaths(
  inventory: FileInventory,
  pattern: string
): string[] {
  const suffix = pattern
    .replaceAll("*", "")
    .replaceAll("?", "")
    .split("/")
    .filter(Boolean)
    .at(-1);
  if (!suffix) return [];
  return inventory.files
    .map((file) => file.path)
    .filter((path) => path.includes(suffix))
    .slice(0, 5);
}
```

资料来源：[src/tools/group/grouping-assignment-engine.ts:150-180]()

## Usage in Workflows

### Initial Setup Workflow

1. Run `blueprint.scan` to build file inventory
2. Run `blueprint.group` with `mode: "prepare"` to get suggested groupings
3. Review and refine the grouping plan
4. Run `blueprint.group` with `mode: "apply"` to apply the plan
5. Run `blueprint.compose` to generate documentation

### Maintenance Workflow

1. Run `blueprint.refresh` when project structure changes
2. If new files are unassigned, run `blueprint.group.update`
3. Update affected group documentation as needed

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

## Summary

The Group Tool is a critical component in the Blueprint system that transforms raw file inventories into semantic architectural groupings. It provides:

- **Pattern-based assignment** with flexible glob-like syntax
- **Validation** ensuring complete and conflict-free groupings
- **Edge aggregation** for cross-group relationship tracking
- **Fallback handling** for unassigned files
- **Integration** with the broader Blueprint workflow (scan → group → compose → refresh)

The tool operates in two modes (`prepare` and `apply`) enabling iterative group planning and reliable maintenance workflows.

---

<a id='page-compose-tool'></a>

## Compose Tool

### 相关页面

相关主题：[System Architecture](#page-system-architecture), [Group Tool](#page-group-tool)

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

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

- [src/tools/compose/index.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/compose/index.ts)
- [src/tools/compose/compose-output-builder.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/compose/compose-output-builder.ts)
- [src/tools/compose/compose-artifact-writer.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/compose/compose-artifact-writer.ts)
- [src/tools/compose/compose.types.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/compose/compose.types.ts)
- [src/lib/group-note-template.ts](https://github.com/engincankaya/blueprint/blob/main/src/lib/group-note-template.ts)
</details>

# Compose Tool

## Overview

The Compose Tool is the final stage in the Blueprint pipeline. It transforms the semantic grouping artifact into a frontend-ready JSON output and generates Markdown documentation for each group. The tool acts as the bridge between the analysis/grouping phases and the viewer UI.

**Key Responsibilities:**

- Builds the final `blueprint.v1` output JSON from stored grouping artifacts
- Determin joining of groups, files, edges, docs paths, and validation data
- Generates group documentation Markdown files from templates
- Writes output artifacts to `.blueprint/` directory
- Detects entrypoint files for each group
- Validates the composed output against expected schema

资料来源：[src/tools/compose/index.ts:1-18]()

## Architecture

The Compose Tool is composed of several interconnected components that work together to produce the final Blueprint output.

### Component Overview

```mermaid
graph TD
    subgraph "Compose Tool Components"
        CT[ComposeTool]
        COB[ComposeOutputBuilder]
        CAW[ComposeArtifactWriter]
        CED[ComposeEntrypointDetector]
    end
    
    subgraph "Input Dependencies"
        GR[GroupingResult]
        FI[FileInventory]
        AF[AnalysisFacts]
    end
    
    subgraph "Output Artifacts"
        JSON[blueprint-output.json]
        MD[groups/*.md]
    end
    
    CT --> COB
    CT --> CAW
    CT --> CED
    GR --> CT
    FI --> COB
    AF --> COB
    COB --> JSON
    CAW --> MD
```

### Core Classes

| Component | Purpose | Key Methods |
|-----------|---------|-------------|
| `ComposeTool` | Main orchestrator and entry point | `handle()` |
| `ComposeOutputBuilder` | Constructs the final JSON output structure | `build()`, `joinGroups()`, `joinEdges()` |
| `ComposeArtifactWriter` | Persists output to filesystem | `write()`, `writeGroupDocs()` |
| `ComposeEntrypointDetector` | Identifies entrypoint files per group | `detect()` |

资料来源：[src/tools/compose/index.ts:19-27]()

## Data Flow

### Pipeline Integration

The Compose Tool represents stage 3 of the Blueprint pipeline:

```mermaid
graph LR
    subgraph "Stage 1: Scan"
        SI[scan.tool]
        FI[FileInventory]
        AF[AnalysisFacts]
    end
    
    subgraph "Stage 2: Group"
        GI[group.tool]
        GR[GroupingResult]
    end
    
    subgraph "Stage 3: Compose"
        CI[compose.tool]
        JSON[blueprint.v1 JSON]
        MD[Group Docs]
    end
    
    SI --> FI
    SI --> AF
    GI --> GR
    FI --> CI
    GR --> CI
    AF --> CI
    CI --> JSON
    CI --> MD
```

### Input Dependencies

The Compose Tool requires the following artifacts from previous pipeline stages:

1. **GroupingResult** - Semantic file groupings with assignments
2. **FileInventory** - Complete file listing with metadata
3. **AnalysisFacts** - Code analysis data including imports/exports

资料来源：[src/tools/compose/index.ts:28-35]()

## ComposeTool Class

The `ComposeTool` class serves as the main orchestrator, delegating work to specialized components.

```typescript
export class ComposeTool {
  constructor(
    private readonly outputBuilder: ComposeOutputBuilder,
    private readonly artifactWriter: ComposeArtifactWriter,
  ) {}
```

### The `handle()` Method

The primary entry point that processes compose requests:

```typescript
async handle(args: ComposeArgs, store: ArtifactStore): Promise<ToolResult>
```

**Flow:**

1. Retrieves the grouping artifact from the store
2. Validates grouping artifact existence
3. Delegates JSON building to `ComposeOutputBuilder`
4. Delegates artifact writing to `ComposeArtifactWriter`
5. Returns structured tool result

资料来源：[src/tools/compose/index.ts:28-48]()

### Error Handling

The tool provides descriptive error messages when artifacts are missing:

```typescript
if (!grouping) {
  const entry = store.get(args.groupingArtifactId);
  return errorResult(
    entry
      ? `Grouping artifact ${args.groupingArtifactId} not found or has the wrong type`
      : `Grouping artifact ${args.groupingArtifactId} not found`,
  );
}
```

## ComposeOutputBuilder

The `ComposeOutputBuilder` is responsible for constructing the final `blueprint.v1` output structure.

### Output Structure

The builder produces a stable JSON schema containing:

| Field | Type | Description |
|-------|------|-------------|
| `groups` | `Group[]` | All semantic groups with assigned files |
| `files` | `File[]` | Complete file inventory |
| `edges` | `Edge[]` | Connections between groups/files |
| `metadata` | `Metadata` | Output generation timestamp and version |
| `validation` | `ValidationResult` | Schema validation results |

### Building Process

The output builder deterministically joins:

- Groups with their assigned files
- File metadata from inventory
- Edge connections between groups
- Documentation paths
- Validation data

资料来源：[src/tools/compose/compose-output-builder.ts]()

## ComposeArtifactWriter

The `ComposeArtifactWriter` handles persistence of composed output to the filesystem.

### Write Operations

| Method | Target | Description |
|--------|--------|-------------|
| `writeJson()` | `.blueprint/blueprint-output.json` | Writes the main Blueprint JSON |
| `writeGroupDocs()` | `.blueprint/groups/*.md` | Generates Markdown documentation per group |
| `writeBrief()` | `.blueprint/brief.md` | Writes project overview documentation |

### Group Documentation

The artifact writer generates Markdown files for each group using a standardized template that includes:

- **Snapshot** - Quick orientation summary
- **Responsibilities** - Ownership and scope definition
- **Core Flow** - Runtime behavior and data flow
- **Contracts & Invariants** - Behavior constraints
- **Key Files** - Main source file references
- **Change Guide** - Files that should change together
- **Pitfalls** - Known risks and common mistakes

资料来源：[src/lib/group-note-template.ts]()

## ComposeEntrypointDetector

The `ComposeEntrypointDetector` identifies entrypoint files for each group by analyzing:

- Export patterns
- Module initialization files
- Main/index file conventions
- Dependency injection configurations

## API Reference

### ComposeArgs

```typescript
interface ComposeArgs {
  groupingArtifactId: string;  // ID of the grouping artifact to compose
  outputPath?: string;          // Optional custom output path
}
```

### ComposeResponseValidation

```typescript
interface ComposeResponseValidation {
  valid: boolean;
  errors: ValidationError[];
}
```

### ToolResult

The compose tool returns a `ToolResult` with either:

- **Success**: JSON result containing the composed output path
- **Error**: Descriptive error message explaining the failure

## Usage

### CLI Usage

```bash
blueprint compose <groupingArtifactId>
```

### MCP Tool Usage

```json
{
  "tool": "blueprint.compose",
  "arguments": {
    "groupingArtifactId": "grouping-20240115-143022"
  }
}
```

## Integration with Other Tools

### Tool Chain

```mermaid
graph TD
    subgraph "blueprint CLI"
        SCAN[blueprint.scan]
        GROUP[blueprint.group]
        COMPOSE[blueprint.compose]
        REFRESH[blueprint.refresh]
    end
    
    SCAN --> GROUP
    GROUP --> COMPOSE
    COMPOSE --> REFRESH
    REFRESH --> GROUP
```

### Related Tools

| Tool | Input to Compose | Output from Compose |
|------|------------------|---------------------|
| `scan` | - | `FileInventory`, `AnalysisFacts` |
| `group` | `FileInventory`, `AnalysisFacts` | `GroupingResult` |
| `compose` | `GroupingResult` | `blueprint.v1 JSON`, `group/*.md` |
| `refresh` | - | Refreshes from current filesystem |

## Output Schema (blueprint.v1)

```typescript
interface BlueprintOutput {
  version: "blueprint.v1";
  generated: string;           // ISO timestamp
  groups: Group[];
  files: FileEntry[];
  edges: Edge[];
  metadata: {
    sourceRoot: string;
    artifactCount: number;
  };
  validation: ComposeResponseValidation;
}
```

## Best Practices

1. **Always run scan before compose** - Ensure fresh analysis data
2. **Use stable artifact IDs** - Grouping artifacts should be referenced by ID, not path
3. **Validate output** - Check the validation results before consuming the output
4. **Preserve group documentation** - The generated Markdown files should be version-controlled

## File Structure

```
.blueprint/
├── blueprint-output.json    # Main Blueprint JSON (blueprint.v1)
├── brief.md                 # Project overview
└── groups/
    ├── group-1.md           # Group-specific documentation
    ├── group-2.md
    └── ...

---

<a id='page-refresh-tool'></a>

## Refresh Tool

### 相关页面

相关主题：[System Architecture](#page-system-architecture), [Compose Tool](#page-compose-tool)

I cannot generate an accurate technical wiki page about the Refresh Tool based on the provided context. The requested source files are not present in the retrieved repository content:

**Missing Source Files:**
- `src/tools/refresh/index.ts`
- `src/tools/refresh/refresh.types.ts`
- `src/tools/group-update/index.ts`
- `src/tools/group-update/group-update-applier.ts`

**Available Context:**
The README.md does reference `blueprint.refresh` as a tool that "Refreshes Blueprint state from the current filesystem snapshot" and `blueprint.group.update` for "Assigning unassigned files or managing empty groups after refresh," but the actual implementation source code for these components is not included in the provided context.

To generate an accurate wiki page, I would need access to the actual source files for the refresh and group-update tools.

---

<a id='page-task-context-tool'></a>

## Task Context Tool

### 相关页面

相关主题：[System Architecture](#page-system-architecture), [MCP Server Implementation](#page-mcp-server)

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

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

- [src/tools/task-context.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/task-context.ts) - **File not found in provided context**

</details>

# Task Context Tool

The requested source file `src/tools/task-context.ts` was not found in the provided repository context. This wiki page cannot be generated with the specified source file.

---

## Available Context Files

The following files were retrieved from the repository and may provide related context:

| File Path | Purpose |
|-----------|---------|
| `frontend/src/components/blueprint/GroupDetailPanel.tsx` | React component for displaying group details with tabs |
| `frontend/src/components/BlueprintApp.tsx` | Main application component with tab management |
| `src/tools/scan/scan-file-inventory-builder.ts` | File inventory classification system |
| `src/viewer/render-html.ts` | HTML rendering utilities for the viewer |
| `src/lib/group-docs.ts` | Group documentation structure validation |
| `AGENTS.md` | Agent instructions for code analysis workflow |

---

## Next Steps

To generate an accurate wiki page for the Task Context Tool:

1. Request the file `src/tools/task-context.ts` be included in the context
2. Alternatively, search the repository for "task-context" or "TaskContext" references to identify alternative relevant files

---

## Related Components (From Available Context)

### Group Detail Panel Architecture

The `GroupDetailPanel.tsx` component demonstrates the application's approach to displaying structured information:

```typescript
// Tab structure for group details
const SUB_TABS = [
  { id: 'overview', label: 'Overview' },
  { id: 'files', label: 'Files' },
  { id: 'connections', label: 'Connections' },
  { id: 'architecture', label: 'Architecture' },
  { id: 'guide', label: 'Guide' },
]
```

### File Inventory Classification

The `scan-file-inventory-builder.ts` classifies files into categories:

| Category | Criteria |
|----------|----------|
| `test` | `.spec.ts`, `.spec.tsx`, `test/` directories |
| `config` | `package.json`, `.config.js`, `tsconfig.json` |
| `documentation` | `.md` files, `docs/` directory |
| `script` | `.sh` files, `scripts/` directory |
| `asset` | `assets/`, `public/`, `.css`, `.svg` |

资料来源：[src/tools/scan/scan-file-inventory-builder.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/scan/scan-file-inventory-builder.ts)

---

## Recommendation

Provide the `src/tools/task-context.ts` source file to enable accurate documentation generation for the Task Context Tool feature.

---

<a id='page-viewer-frontend'></a>

## Viewer Frontend

### 相关页面

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

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

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

- [frontend/src/components/BlueprintApp.tsx](https://github.com/engincankaya/blueprint/blob/main/frontend/src/components/BlueprintApp.tsx)
- [frontend/src/components/blueprint/GroupDetailPanel.tsx](https://github.com/engincankaya/blueprint/blob/main/frontend/src/components/blueprint/GroupDetailPanel.tsx)
- [frontend/src/components/blueprint/BlueprintCanvas.tsx](https://github.com/engincankaya/blueprint/blob/main/frontend/src/components/blueprint/BlueprintCanvas.tsx)
- [frontend/src/components/blueprint/BlueprintExplorer.tsx](https://github.com/engincankaya/blueprint/blob/main/frontend/src/components/blueprint/BlueprintExplorer.tsx)
- [src/lib/agent-instructions.ts](https://github.com/engincankaya/blueprint/blob/main/src/lib/agent-instructions.ts)
- [README.md](https://github.com/engincankaya/blueprint/blob/main/README.md)
- [todos_120526.md](https://github.com/engincankaya/blueprint/blob/main/todos_120526.md)
- [src/tools/compose/index.ts](https://github.com/engincankaya/blueprint/blob/main/src/tools/compose/index.ts)
</details>

# Viewer Frontend

## Overview

The Viewer Frontend is a lightweight React-based interface for exploring and navigating Blueprint project documentation. It provides an interactive visualization layer that renders the output generated by Blueprint's compose stage, enabling developers to browse groups, files, connections, and architectural documentation through a visual canvas or detailed panel views.

The viewer is designed as a static, self-contained HTML artifact that can be opened in any browser without requiring a dedicated HTTP server. This approach prioritizes portability and simplicity, allowing teams to commit the generated viewer HTML alongside their project documentation.

## Architecture

### High-Level Design

```mermaid
graph TD
    subgraph "Data Sources"
        A[blueprint-output.json] --> D[BlueprintViewerService]
        B[groups/*.md] --> D
    end
    
    subgraph "Application Layer"
        D --> E[BlueprintApp]
        E --> F[BlueprintCanvas]
        E --> G[GroupDetailPanel]
    end
    
    subgraph "Rendering"
        F --> H[BlueprintExplorer]
        G --> I[SectionCard]
        G --> J[ConnectionDiagram]
        G --> K[OpenQuestionsCards]
    end
    
    E --> L[index.html]
```

The viewer follows a service-based architecture that abstracts data access through `BlueprintViewerService`. This design supports multiple data source modes: embedded JSON data for static viewing or HTTP fetching for development workflows.

### Component Hierarchy

| Component | File Path | Responsibility |
|-----------|-----------|----------------|
| `BlueprintApp` | `frontend/src/components/BlueprintApp.tsx` | Root application container managing tab state and routing between canvas and detail views |
| `BlueprintCanvas` | `frontend/src/components/blueprint/BlueprintCanvas.tsx` | Visual graph representation of groups and their connections |
| `BlueprintExplorer` | `frontend/src/components/blueprint/BlueprintExplorer.tsx` | Hierarchical file browser within groups |
| `GroupDetailPanel` | `frontend/src/components/blueprint/GroupDetailPanel.tsx` | Tabbed detail view for individual groups showing documentation sections |
| `SectionCard` | Inline in `GroupDetailPanel.tsx` | Collapsible card component for rendering markdown content sections |
| `ConnectionDiagram` | Referenced in `GroupDetailPanel.tsx` | Visualizes relationships between groups |
| `OpenQuestionsCards` | Referenced in `GroupDetailPanel.tsx` | Displays open questions and extension points |

## Core Components

### BlueprintApp

The main application shell that orchestrates the viewer experience. It maintains the active tab state and determines which view to render based on user interaction.

**State Management:**
- `activeTab`: Tracks whether the user is viewing the canvas or a specific group's details
- `activeGroupId`: Identifies the currently selected group for detail view
- `overview`: Contains the complete Blueprint data including all groups, files, and connections

**Tab Types:**
- `canvas`: The full project visualization showing all groups and their relationships
- `group`: Detailed view of a specific group with its documentation

```typescript
// Tab structure from BlueprintApp.tsx
activeTab.type === "canvas" 
  ? <BlueprintCanvas overview={overview} activeGroupId={activeGroupId} onGroupClick={openGroup} />
  : <GroupDetailPanel detail={details[activeTab.group.id]} />
```

### GroupDetailPanel

The primary content display component that renders detailed documentation for a selected group. It organizes content into logical sub-tabs.

```mermaid
graph LR
    A[GroupDetailPanel] --> B[overview]
    A --> C[files]
    A --> D[connections]
    A --> E[architecture]
    A --> F[guide]
    
    B --> B1[Snapshot]
    B --> B2[Responsibilities]
    B --> B3[Key Files]
    B --> B4[Open Questions]
    
    E --> E1[Core Flow]
    E --> E2[Contracts & Invariants]
    E --> E3[Key Files]
    
    F --> F1[Change Guide]
    F --> F2[Contracts & Invariants]
    F --> F3[Pitfalls]
    F --> F4[Tests]
    F --> F5[Debugging]
    F --> F6[Extension / Open Questions]
```

**Sub-Tabs and Content:**

| Sub-Tab | Content Sections | Accent Color |
|---------|------------------|---------------|
| `overview` | Snapshot, Responsibilities, Key Files, Open Questions | Blue (for Open Questions) |
| `files` | Role breakdown, File tree | Default |
| `connections` | ConnectionDiagram | Default |
| `architecture` | Core Flow, Contracts & Invariants, Key Files | Default |
| `guide` | Change Guide, Invariants, Pitfalls, Tests, Debugging, Extension/Open Questions | Red (Invariants), Amber (Pitfalls), Green (Extension) |

### SectionCard Component

A reusable collapsible component for rendering markdown content sections within the detail panel.

**Features:**
- Expandable/collapsible with smooth animation
- Preview text when collapsed (line-clamp-1)
- Configurable title styling with accent colors
- Markdown content rendering via `SectionContent`

**Animation Behavior:**
```typescript
// Entrance/exit animations
<motion.div
  initial={{ height: 0, opacity: 0 }}
  animate={{ height: 'auto', opacity: 1 }}
  exit={{ height: 0, opacity: 0 }}
  transition={{ duration: 0.2 }}
>
```

## Data Flow

### Static Viewer Data Model

The viewer expects a structured JSON input that is either embedded in the HTML or fetched from the filesystem. The data model follows the `blueprint.v1` schema.

```mermaid
sequenceDiagram
    participant User as User Browser
    participant HTML as index.html
    participant Service as BlueprintViewerService
    participant Store as Artifact Store
    
    User->>HTML: Open .blueprint/index.html
    HTML->>Service: Initialize with embedded data
    Service->>Store: Parse blueprint-output.json
    Store->>HTML: Render overview
    User->>HTML: Click group
    HTML->>Service: Request group details
    Service->>Store: Load groups/*.md files
    Store->>HTML: Render GroupDetailPanel
```

### Data Source Abstraction

The viewer uses a `BlueprintDataSource` abstraction layer that supports two modes:

| Mode | Data Location | Use Case |
|------|---------------|----------|
| Static | Embedded in `index.html` as `<script id="blueprint-data" type="application/json">` | Production viewing, committed artifacts |
| HTTP | Fetched from `.blueprint/` directory | Development with live refresh |

## Static Viewer Generation

### Build Process

The viewer is generated by the `blueprint compose` command, which produces a self-contained HTML file. According to the project roadmap, the generation process follows these principles:

1. **Inline all assets**: JavaScript and CSS are bundled directly into the HTML
2. **Safe JSON embedding**: Data is embedded using `<script id="blueprint-data" type="application/json">` with proper escaping
3. **Security considerations**: XSS and `</script>` closing tag risks are mitigated through escaping

### CLI Commands

| Command | Description | Output |
|---------|-------------|--------|
| `blueprint open` | Generates and opens viewer in browser | Writes `.blueprint/index.html`, opens in default browser |
| `blueprint open --watch` | Watches for file changes and regenerates | Maintains `.blueprint/index.html` updated |
| `blueprint render` | Generates viewer HTML | Writes `.blueprint/index.html` without opening browser |

### Output Artifacts

| Artifact | Path | Description |
|----------|------|-------------|
| `blueprint-output.json` | `.blueprint/blueprint-output.json` | Structured project graph with groups, files, and edges |
| Group docs | `.blueprint/groups/*.md` | Individual group documentation files |
| Brief | `.blueprint/brief.md` | Project overview and quick reference |
| Viewer HTML | `.blueprint/index.html` | Self-contained viewer (generated) |

## UI/UX Design

### Visual Design System

The viewer uses a zinc-based color palette with specific accent colors for semantic meaning:

| Element | Color | Usage |
|---------|-------|-------|
| Primary text | `zinc-100` | Main headings and titles |
| Secondary text | `zinc-400` | Body content and descriptions |
| Muted text | `zinc-500` | Metadata, counts |
| Background | `zinc-950` | Application background |
| Accent Blue | `blue-400` | Open Questions in overview |
| Accent Red | `red-500` | Invariants in guide |
| Accent Amber | `amber-500` | Pitfalls in guide |
| Accent Green | `green-500` | Extension/Open Questions in guide |

### Typography

| Element | Size | Weight | Transform |
|---------|------|--------|-----------|
| Group title | `text-base` | semibold | none |
| Section heading | `text-[11px]` | semibold | uppercase, tracking-wider |
| Body text | `text-sm` | normal | none |
| Code | inline code | monospace | - |

### Animation Guidelines

The viewer uses Framer Motion for animations with consistent timing:

| Animation | Duration | Easing |
|-----------|----------|--------|
| Tab transition | 0.12s | default |
| Content fade | 0.15s | default |
| Section expand | 0.2s | default |
| Section collapse | 0.15s | default |
| Chevron rotation | 0.15s | default |

## Group Documentation Template

Groups follow a standardized documentation template that the viewer renders:

| Section | Content | Panel Location |
|---------|---------|----------------|
| Snapshot | Quick orientation quote | overview |
| Responsibilities | Ownership and out-of-scope areas | overview |
| Core Flow | Runtime behavior and data flow | architecture |
| Contracts & Invariants | Behavior that must not be broken | architecture, guide |
| Key Files | Main source files for the group | overview, architecture |
| Change Guide | Files or contracts that should change together | guide |
| Pitfalls | Known risks and common mistakes | guide |
| Tests | Test coverage and test locations | guide |
| Debugging | Common issues and debugging approaches | guide |
| Extension / Open Questions | Future considerations and unresolved items | overview, guide |

## AGENTS.md Integration

The viewer supports integration with the agent instruction system. The `renderBlueprintAgentsSnippet()` function generates a standardized marker-delimited section that can be injected into project documentation:

```markdown
<!-- BLUEPRINT-AGENTS-BEGIN -->

## Blueprint MCP

This project uses Blueprint MCP for local architecture memory.

Before broad codebase exploration, read:

`node_modules/blueprint-mcp-server/docs/agents.md`

If Blueprint memory exists, start with:

`.blueprint/brief.md`

<!-- BLUEPRINT-AGENTS-END -->
```

This enables tools and agents to discover and use Blueprint documentation automatically.

## Development Workflow

### Running the Viewer During Development

1. **Initial scan and compose:**
   ```bash
   blueprint.scan
   blueprint.group --mode prepare
   blueprint.group --mode apply
   blueprint.compose
   ```

2. **Open the viewer:**
   ```bash
   blueprint open
   ```

3. **Watch for changes:**
   ```bash
   blueprint open --watch
   ```

### Maintenance Workflow

When project files change significantly:

1. Run `blueprint.refresh` to update the file inventory
2. Run `blueprint.group.update` if new files are unassigned
3. Update affected `.blueprint/groups/*.md` notes
4. Regenerate the viewer with `blueprint open`

## Browser Compatibility

The viewer is built with React 18 and Vite, targeting modern browsers with ESM support. No additional polyfills are included in the static bundle.

## Security Model

The static viewer follows security best practices:

- All data is embedded directly in the HTML, eliminating network-based attacks
- JSON data is escaped before embedding to prevent XSS via `</script>` injection
- Special characters (`<`, `-->`, `\u2028`, `\u2029`) are properly escaped
- No eval() or dynamic code execution from embedded data

---

---

## Doramagic 踩坑日志

项目：engincankaya/blueprint

摘要：发现 6 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。

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

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

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

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

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

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

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

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

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

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

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

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

<!-- canonical_name: engincankaya/blueprint; human_manual_source: deepwiki_human_wiki -->
